diff --git a/.gitignore b/.gitignore index e48ca087..da76bd66 100755 --- a/.gitignore +++ b/.gitignore @@ -49,3 +49,6 @@ moc_*.cpp_parameters DSView-prj build* share +.vscode +qtpro +test diff --git a/DSView.icns b/DSView.icns new file mode 100644 index 00000000..d98f5351 Binary files /dev/null and b/DSView.icns differ diff --git a/DSView/DSView.desktop b/DSView/DSView.desktop deleted file mode 100755 index e1143240..00000000 --- a/DSView/DSView.desktop +++ /dev/null @@ -1,10 +0,0 @@ -[Desktop Entry] -Type=Application -Encoding=UTF-8 -Name=DSView -Comment=GUI Program for DreamSourceLab USB-based Instruments -TryExec=DSView -Exec=DSView -Icon=dsview -Terminal=false -Categories=Development;Electronics;Qt; diff --git a/DSView/config.h b/DSView/config.h new file mode 100755 index 00000000..067e528a --- /dev/null +++ b/DSView/config.h @@ -0,0 +1,36 @@ +/* + * This file is part of the PulseView project. + * + * Copyright (C) 2012 Alexandru Gagniuc + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef _DSVIEW_CONFIG_H +#define _DSVIEW_CONFIG_H + +/* Application details */ +#define DS_TITLE "DSView" +#define DS_DESCRIPTION "A GUI for instruments of DreamSourceLab" +#define DS_BIN_NAME "DSView" + +/* DSView version information */ +#define DS_VERSION_MAJOR 1 +#define DS_VERSION_MINOR 2 +#define DS_VERSION_MICRO 0 +#define DS_VERSION_STRING "1.2.0" + +#define DS_DEBUG_TRACE + +#endif diff --git a/DSView/main.cpp b/DSView/main.cpp index cb3d83ae..e038ae68 100755 --- a/DSView/main.cpp +++ b/DSView/main.cpp @@ -19,12 +19,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#include -#ifdef ENABLE_DECODE -#include -#endif - + #include #include @@ -33,22 +28,25 @@ #include #include #include -#include #include #include #include "dsapplication.h" -#include "mystyle.h" -#include "pv/devicemanager.h" +#include "mystyle.h" #include "pv/mainframe.h" - +#include "pv/config/appconfig.h" #include "config.h" +#include "pv/appcontrol.h" -char DS_RES_PATH[256]; +#ifdef _WIN32 +#include +#endif + +//#include void usage() { - fprintf(stdout, + printf( "Usage:\n" " %s [OPTION…] [FILE] — %s\n" "\n" @@ -57,15 +55,18 @@ void usage() " -V, --version Show release version\n" " -h, -?, --help Show help option\n" "\n", DS_BIN_NAME, DS_DESCRIPTION); -} +} + int main(int argc, char *argv[]) -{ - int ret = 0; - struct sr_context *sr_ctx = NULL; +{ + // sr_test_usb_api();return 0; + + int ret = 0; const char *open_file = NULL; - + #if QT_VERSION >= QT_VERSION_CHECK(5,6,0) + //On Windows, need to compile with the QT5 version of the library, which makes the interface slightly larger. QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); #endif // QT_VERSION @@ -110,6 +111,13 @@ int main(int argc, char *argv[]) QApplication::setOrganizationName("DreamSourceLab"); QApplication::setOrganizationDomain("www.DreamSourceLab.com"); +#ifdef Q_OS_LINUX + QCoreApplication::addLibraryPath("/usr/lib/x86_64-linux-gnu/qt5/plugins"); + printf("qt plugins root:/usr/lib/x86_64-linux-gnu/qt5/plugins\n"); +#endif + + AppControl *control = AppControl::Instance(); + // Parse arguments while (1) { static const struct option long_options[] = { @@ -128,18 +136,13 @@ int main(int argc, char *argv[]) case 'l': { const int loglevel = atoi(optarg); - sr_log_loglevel_set(loglevel); - -#ifdef ENABLE_DECODE - srd_log_loglevel_set(loglevel); -#endif - + control->SetLogLevel(loglevel); break; } case 'V': // Print version info - fprintf(stdout, "%s %s\n", DS_TITLE, DS_VERSION_STRING); + printf("%s %s\n", DS_TITLE, DS_VERSION_STRING); return 0; case 'h': @@ -150,69 +153,55 @@ int main(int argc, char *argv[]) } if (argcFinal - optind > 1) { - fprintf(stderr, "Only one file can be openened.\n"); + printf("Only one file can be openened.\n"); return 1; - } else if (argcFinal - optind == 1) + } else if (argcFinal - optind == 1){ open_file = argvFinal[argcFinal - 1]; + control->_open_file_name = open_file; + } - // Initialise DS_RES_PATH - QDir dir(QCoreApplication::applicationDirPath()); - if (dir.cd("..") && - dir.cd("share") && - dir.cd(QApplication::applicationName()) && - dir.cd("res")) { - QString res_dir = dir.absolutePath() + "/"; - strcpy(DS_RES_PATH, res_dir.toUtf8().data()); - } else { - qDebug() << "ERROR: config files don't exist."; - return 1; - } + +//#ifdef Q_OS_DARWIN +//#endif - // Initialise libsigrok - if (sr_init(&sr_ctx) != SR_OK) { - qDebug() << "ERROR: libsigrok init failed."; + //load app config + AppConfig::Instance().LoadAll(); + + //init core + if (!control->Init()){ + printf("init error!"); + qDebug() << control->GetLastError(); return 1; } - do { -#ifdef ENABLE_DECODE - // Initialise libsigrokdecode - if (srd_init(NULL) != SRD_OK) { - qDebug() << "ERROR: libsigrokdecode init failed."; - break; - } + try + { + control->Start(); + + // Initialise the main frame + pv::MainFrame w; + w.show(); + + w.readSettings(); + + //to show the dailog for open help document + w.show_doc(); - // Load the protocol decoders - srd_decoder_load_all(); -#endif + //Run the application + ret = a.exec(); - try { - // Create the device manager, initialise the drivers - pv::DeviceManager device_manager(sr_ctx); + control->Stop(); + } + catch (const std::exception &e) + { + printf("main() catch a except!"); + const char *exstr = e.what(); + qDebug() << exstr; + } - // Initialise the main frame - pv::MainFrame w(device_manager, open_file); - w.show(); - w.readSettings(); - w.show_doc(); - - // Run the application - ret = a.exec(); - - } catch(const std::exception &e) { - qDebug() << e.what(); - } - -#ifdef ENABLE_DECODE - // Destroy libsigrokdecode - srd_exit(); -#endif - - } while (0); - - // Destroy libsigrok - if (sr_ctx) - sr_exit(sr_ctx); + //uninit + control->UnInit(); + control->Destroy(); return ret; } diff --git a/DSView/mystyle.h b/DSView/mystyle.h index c53bda52..e2cc768f 100644 --- a/DSView/mystyle.h +++ b/DSView/mystyle.h @@ -7,7 +7,7 @@ class MyStyle : public QProxyStyle { Q_OBJECT public: - int pixelMetric(PixelMetric metric, const QStyleOption * option = 0, const QWidget * widget = 0 ) const { + int pixelMetric(PixelMetric metric, const QStyleOption * option = 0, const QWidget * widget = 0 ) { int s = QProxyStyle::pixelMetric(metric, option, widget); if (metric == QStyle::PM_SmallIconSize) { s = 24; diff --git a/DSView/pv/ZipMaker.cpp b/DSView/pv/ZipMaker.cpp new file mode 100644 index 00000000..18e48fc6 --- /dev/null +++ b/DSView/pv/ZipMaker.cpp @@ -0,0 +1,273 @@ + +/* + * This file is part of the DSView project. + * DSView is based on PulseView. + * + * Copyright (C) 2012 Joel Holdsworth + * Copyright (C) 2013 DreamSourceLab + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "ZipMaker.h" +#include +#include +#include +#include +#include + +#include "minizip/zip.h" +#include "minizip/unzip.h" + + +ZipMaker::ZipMaker() : + m_zDoc(NULL) +{ + m_error[0] = 0; + m_opt_compress_level = Z_BEST_SPEED; + m_zi = NULL; +} + +ZipMaker::~ZipMaker() +{ + Release(); +} + +bool ZipMaker::CreateNew(const char *fileName, bool bAppend) +{ + assert(fileName); + + Release(); + + m_zDoc = zipOpen64(fileName, bAppend); + if (m_zDoc == NULL) { + strcpy(m_error, "zipOpen64 error"); + } + +//make zip inner file time + m_zi = new zip_fileinfo(); + + time_t rawtime; + time (&rawtime); + struct tm *tinf= localtime(&rawtime); + + struct tm &ti = *tinf; + zip_fileinfo &zi= *(zip_fileinfo*)m_zi; + + zi.tmz_date.tm_year = ti.tm_year; + zi.tmz_date.tm_mon = ti.tm_mon; + zi.tmz_date.tm_mday = ti.tm_mday; + zi.tmz_date.tm_hour = ti.tm_hour; + zi.tmz_date.tm_min = ti.tm_min; + zi.tmz_date.tm_sec = ti.tm_sec; + zi.dosDate = 0; + + return m_zDoc != NULL; +} + +void ZipMaker::Release() +{ + if (m_zDoc){ + zipClose((zipFile)m_zDoc, NULL); + m_zDoc = NULL; + } + if (m_zi){ + delete ((zip_fileinfo*)m_zi); + m_zi = NULL; + } +} + +bool ZipMaker::Close(){ + if (m_zDoc){ + zipClose((zipFile)m_zDoc, NULL); + m_zDoc = NULL; + return true; + } + return false; +} + +bool ZipMaker::AddFromBuffer(const char *innerFile, const char *buffer, unsigned int buferSize) +{ + assert(buffer); + assert(innerFile); + assert(m_zDoc); + int level = m_opt_compress_level; + + if (level < Z_DEFAULT_COMPRESSION || level > Z_BEST_COMPRESSION){ + level = Z_DEFAULT_COMPRESSION; + } + + zipOpenNewFileInZip((zipFile)m_zDoc,innerFile,(zip_fileinfo*)m_zi, + NULL,0,NULL,0,NULL , + Z_DEFLATED, + level); + + zipWriteInFileInZip((zipFile)m_zDoc, buffer, (unsigned int)buferSize); + + zipCloseFileInZip((zipFile)m_zDoc); + + return true; +} + +bool ZipMaker::AddFromFile(const char *localFile, const char *innerFile) +{ + assert(localFile); + + struct stat st; + FILE *fp; + char *data = NULL; + long long size = 0; + + if ((fp = fopen(localFile, "rb")) == NULL) { + strcpy(m_error, "fopen error"); + return false; + } + + if (fstat(fileno(fp), &st) < 0) { + strcpy(m_error, "fstat error"); + fclose(fp); + return -1; + } + + if ((data = (char*)malloc((size_t)st.st_size)) == NULL) { + strcpy(m_error, "can't malloc buffer"); + fclose(fp); + return false; + } + + if (fread(data, 1, (size_t)st.st_size, fp) < (size_t)st.st_size) { + strcpy(m_error, "fread error"); + free(data); + fclose(fp); + return false; + } + + fclose(fp); + size = (size_t)st.st_size; + + bool ret = AddFromBuffer(innerFile, data, size); + return ret; +} + +const char *ZipMaker::GetError() +{ + if (m_error[0]) + return m_error; + return NULL; +} + + +//------------------------ZipDecompress + ZipDecompress::ZipDecompress() + { + m_uzDoc = NULL; + m_curIndex = 0; + m_fileCount = 0; + m_bufferSize = 0; + m_buffer = NULL; + } + + ZipDecompress::~ZipDecompress() + { + Close(); + } + + bool ZipDecompress::Open(const char *fileName) + { + assert(fileName); + m_uzDoc = unzOpen64(fileName); + + if (m_uzDoc){ + m_uzi = new unz_file_info64(); + unz_global_info64 inf; + unzGetGlobalInfo64((unzFile)m_uzDoc, &inf); + m_fileCount = (int)inf.number_entry; + } + return m_uzDoc != NULL; + } + + void ZipDecompress::Close() + { + if (m_uzDoc) + { + unzClose((unzFile)m_uzDoc); + m_uzDoc = NULL; + } + if (m_uzi){ + delete ((unz_file_info64*)m_uzi); + m_uzi = NULL; + } + if (m_buffer){ + free(m_buffer); + m_buffer = NULL; + } + } + + bool ZipDecompress::ReadNextFileData(UnZipFileInfo &inf) +{ + assert(m_uzDoc); + + if (m_curIndex >= m_fileCount){ + strcpy(m_error, "read index is last"); + return false; + } + m_curIndex++; + + int ret = unzGetCurrentFileInfo64((unzFile)m_uzDoc, (unz_file_info64*)m_uzi, inf.inFileName, 256, NULL, 0, NULL, 0); + if (ret != UNZ_OK){ + strcpy(m_error, "unzGetCurrentFileInfo64 error"); + return false; + } + unz_file_info64 &uzinf = *(unz_file_info64*)m_uzi; + inf.dataLen = uzinf.uncompressed_size; + inf.inFileNameLen = uzinf.size_filename; + + // need malloc memory buffer + if (m_buffer == NULL || inf.dataLen > m_bufferSize){ + if (m_buffer) free(m_buffer); + m_buffer = NULL; + + m_buffer = malloc(inf.dataLen + 10); + if (m_buffer == NULL){ + strcpy(m_error, "malloc get null"); + return false; + } + } + + inf.pData = m_buffer; + + unzOpenCurrentFile((unzFile)m_uzDoc); + + //read file data to buffer + char *buf = (char*)inf.pData; + long long buflen = inf.dataLen; + long long rdlen = 0; + + while (rdlen < inf.dataLen) + { + int dlen = unzReadCurrentFile((unzFile)m_uzDoc, buf, buflen); + if (dlen == 0){ + break; + } + rdlen += dlen; + buf += dlen; //move pointer + buflen = inf.dataLen - rdlen; + } + + unzCloseCurrentFile((unzFile)m_uzDoc); + unzGoToNextFile((unzFile)m_uzDoc); + + return true; +} diff --git a/DSView/pv/ZipMaker.h b/DSView/pv/ZipMaker.h new file mode 100644 index 00000000..703c440d --- /dev/null +++ b/DSView/pv/ZipMaker.h @@ -0,0 +1,91 @@ +/* + * This file is part of the DSView project. + * DSView is based on PulseView. + * + * Copyright (C) 2012 Joel Holdsworth + * Copyright (C) 2013 DreamSourceLab + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +//test git 2 + +#pragma once + +typedef struct +{ + char inFileName[256]; + int inFileNameLen; + void *pData; + long long dataLen; +} UnZipFileInfo; + + +class ZipMaker +{ +public: + ZipMaker(); + + ~ZipMaker(); + + //create new zip archive in the memory + bool CreateNew(const char *fileName, bool bAppend); + + //free the source + void Release(); + + //save data to file + bool Close(); + + //add a inner file from buffer + bool AddFromBuffer(const char *innerFile, const char *buffer, unsigned int buferSize); + + //add a inner file from local file + bool AddFromFile(const char *localFile, const char *innerFile); + + //get the last error + const char *GetError(); + +public: + int m_opt_compress_level; + +private: + void *m_zDoc; //zip file handle + void *m_zi; //life must as m_zDoc; + char m_error[500]; +}; + +class ZipDecompress +{ +public: + ZipDecompress(); + + ~ZipDecompress(); + + bool Open(const char *fileName); + + void Close(); + + bool ReadNextFileData(UnZipFileInfo &inf); + +private: + void *m_uzDoc; + void *m_uzi; + int m_fileCount; + int m_curIndex; + char m_error[500]; + void *m_buffer; // file read buffer + long long m_bufferSize; +}; diff --git a/DSView/pv/appcontrol.cpp b/DSView/pv/appcontrol.cpp new file mode 100644 index 00000000..286e8019 --- /dev/null +++ b/DSView/pv/appcontrol.cpp @@ -0,0 +1,149 @@ + +/* + * This file is part of the DSView project. + * DSView is based on PulseView. + * + * Copyright (C) 2012 Joel Holdsworth + * Copyright (C) 2013 DreamSourceLab + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "appcontrol.h" + +#include +#include +#include +#include +#include + +#include "devicemanager.h" +#include "sigsession.h" +#include "dsvdef.h" +#include "config/appconfig.h" + +AppControl::AppControl() +{ + sr_ctx = NULL; + + _device_manager = new pv::DeviceManager(); + _session = new pv::SigSession(_device_manager); +} + +AppControl::AppControl(AppControl &o) +{ + (void)o; +} + +AppControl::~AppControl() +{ + DESTROY_OBJECT(_device_manager); + DESTROY_OBJECT(_session); +} + +AppControl* AppControl::Instance() +{ + static AppControl *ins = NULL; + if (ins == NULL){ + ins = new AppControl(); + } + return ins; +} + +void AppControl::Destroy(){ + delete this; +} + +bool AppControl::Init() +{ + // Initialise libsigrok + if (sr_init(&sr_ctx) != SR_OK) + { + m_error = "DSView run ERROR: libsigrok init failed."; + return false; + } + + QString resdir = GetResourceDir(); + sr_set_firmware_resource_dir(resdir.toUtf8().data()); + + + +#ifdef _WIN32 + //able run debug with qtcreator + QString pythonHome = "c:/python"; + QDir pydir; + if (pydir.exists(pythonHome)){ + const wchar_t *pyhome = reinterpret_cast(pythonHome.utf16()); + srd_set_python_home(pyhome); + } + +#endif + + char path[256] = {0}; + QString dir = GetAppDataDir() + "/decoders"; + strcpy(path, dir.toUtf8().data()); + + // Initialise libsigrokdecode + if (srd_init(path) != SRD_OK) + { + m_error = "ERROR: libsigrokdecode init failed."; + return false; + } + + // Load the protocol decoders + if (srd_decoder_load_all() != SRD_OK) + { + m_error = "ERROR: load the protocol decoders failed."; + return false; + } + + return true; +} + +bool AppControl::Start() +{ + _session->Open(); + _device_manager->initAll(sr_ctx); + return true; +} + + void AppControl::Stop() + { + _session->Close(); + _device_manager->UnInitAll(); + } + +void AppControl::UnInit() +{ + // Destroy libsigrokdecode + srd_exit(); + + if (sr_ctx) + { + sr_exit(sr_ctx); + sr_ctx = NULL; + } +} + +const char *AppControl::GetLastError() +{ + return m_error.c_str(); +} + + void AppControl::SetLogLevel(int level) + { + sr_log_loglevel_set(level); + srd_log_loglevel_set(level); + } diff --git a/DSView/pv/appcontrol.h b/DSView/pv/appcontrol.h new file mode 100644 index 00000000..2766cbae --- /dev/null +++ b/DSView/pv/appcontrol.h @@ -0,0 +1,73 @@ + +/* + * This file is part of the DSView project. + * DSView is based on PulseView. + * + * Copyright (C) 2012 Joel Holdsworth + * Copyright (C) 2013 DreamSourceLab + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#pragma once + +#include + +struct sr_context; + +namespace pv{ + class DeviceManager; + class SigSession; +} + +class AppControl +{ +private: + explicit AppControl(); + ~AppControl(); + AppControl(AppControl &o); + +public: + static AppControl* Instance(); + + void Destroy(); + + bool Init(); + + bool Start(); + + void Stop(); + + void UnInit(); + + const char* GetLastError(); + + void SetLogLevel(int level); + + inline pv::SigSession* GetSession() + { return _session;} + + inline pv::DeviceManager& GetDeviceManager() + { return *_device_manager;} + +public: + std::string _open_file_name; + +private: + std::string m_error; + struct sr_context *sr_ctx; + pv::DeviceManager *_device_manager; + pv::SigSession *_session; +}; diff --git a/DSView/pv/config/appconfig.cpp b/DSView/pv/config/appconfig.cpp new file mode 100644 index 00000000..f94c7304 --- /dev/null +++ b/DSView/pv/config/appconfig.cpp @@ -0,0 +1,354 @@ +/* + * This file is part of the DSView project. + * DSView is based on PulseView. + * + * Copyright (C) 2012 Joel Holdsworth + * Copyright (C) 2013 DreamSourceLab + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "appconfig.h" +#include +#include +#include +#include +#include +#include +#include + +#define MAX_PROTOCOL_FORMAT_LIST 15 + +StringPair::StringPair(const std::string &key, const std::string &value) +{ + m_key = key; + m_value = value; +} + +//------------function +QString FormatArrayToString(std::vector &protocolFormats){ + QString str; + + for (StringPair &o : protocolFormats){ + if (!str.isEmpty()){ + str += ";"; + } + str += o.m_key.c_str(); + str += "="; + str += o.m_value.c_str(); + } + + return str; +} + +void StringToFormatArray(const QString &str, std::vector &protocolFormats){ + QStringList arr = str.split(";"); + for (int i=0; i MAX_PROTOCOL_FORMAT_LIST) + { + while (_appOptions.m_protocolFormats.size() < MAX_PROTOCOL_FORMAT_LIST) + { + _appOptions.m_protocolFormats.erase(_appOptions.m_protocolFormats.begin()); + } + } + _appOptions.m_protocolFormats.push_back(StringPair(protocolName, value)); + bChange = true; + } + + if (bChange){ + SaveApp(); + } +} + +std::string AppConfig::GetProtocolFormat(const std::string &protocolName) +{ + for (StringPair &o : _appOptions.m_protocolFormats){ + if (o.m_key == protocolName){ + return o.m_value; + } + } + return ""; +} + +//-------------api +QString GetDirectoryName(QString path) +{ + int lstdex = path.lastIndexOf('/'); + if (lstdex != -1) + { + return path.left(lstdex); + } + return path; +} + +QString GetIconPath() +{ + QString style = AppConfig::Instance()._frameOptions.style; + if (style == ""){ + style = "dark"; + } + return ":/icons/" + style; +} + +QString GetAppDataDir() +{ +//applicationDirPath not end with '/' +#ifdef Q_OS_LINUX + QDir dir(QCoreApplication::applicationDirPath()); + if (dir.cd("..") && dir.cd("share") &&dir.cd("DSView")) + { + return dir.absolutePath(); + } + qDebug() << "dir is not exists:" << QCoreApplication::applicationDirPath() + "/../share/DSView"; + assert(false); +#else + return QCoreApplication::applicationDirPath(); +#endif +} + +QString GetResourceDir(){ + QDir dir = GetAppDataDir() + "/res"; + if (dir.exists()){ + return dir.absolutePath(); + } + qDebug() << "dir is not exists:" << dir.absolutePath(); + assert(false); +} + +QString GetUserDataDir() +{ + #if QT_VERSION >= 0x050400 + return QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); + #else + return QStandardPaths::writableLocation(QStandardPaths::DataLocation); + #endif +} diff --git a/DSView/pv/config/appconfig.h b/DSView/pv/config/appconfig.h new file mode 100644 index 00000000..176180fd --- /dev/null +++ b/DSView/pv/config/appconfig.h @@ -0,0 +1,118 @@ +/* + * This file is part of the DSView project. + * DSView is based on PulseView. + * + * Copyright (C) 2012 Joel Holdsworth + * Copyright (C) 2013 DreamSourceLab + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#pragma once + +#include +#include +#include +#include + +#define LAN_CN 25 +#define LAN_EN 31 + +//--------------------api--- + +QString GetDirectoryName(QString path); +QString GetIconPath(); +QString GetAppDataDir(); +QString GetResourceDir(); +QString GetUserDataDir(); + +//------------------class + +class StringPair +{ +public: + StringPair(const std::string &key, const std::string &value); + std::string m_key; + std::string m_value; +}; + + +struct AppOptions +{ + bool quickScroll; + bool warnofMultiTrig; + bool originalData; + + std::vector m_protocolFormats; +}; + + struct DockOptions{ + bool decodeDoc; + bool triggerDoc; + bool measureDoc; + bool searchDoc; +}; + +struct FrameOptions +{ + QString style; + int language; + int left; //frame region + int top; + int right; + int bottom; + bool isMax; + QByteArray windowState; + + DockOptions _logicDock; + DockOptions _analogDock; + DockOptions _dsoDock; +}; + +struct UserHistory +{ + QString exportDir; + QString saveDir; + bool showDocuments; + QString screenShotPath; + QString sessionDir; + QString openDir; + QString protocolExportPath; + QString exportFormat; +}; + +class AppConfig +{ +private: + AppConfig(); + ~AppConfig(); + AppConfig(AppConfig &o); + +public: + static AppConfig &Instance(); + + void LoadAll(); + void SaveApp(); + void SaveHistory(); + void SaveFrame(); + + void SetProtocolFormat(const std::string &protocolName, const std::string &value); + std::string GetProtocolFormat(const std::string &protocolName); + +public: + AppOptions _appOptions; + UserHistory _userHistory; + FrameOptions _frameOptions; +}; diff --git a/DSView/pv/data/analog.cpp b/DSView/pv/data/analog.cpp index 6685e453..16339621 100755 --- a/DSView/pv/data/analog.cpp +++ b/DSView/pv/data/analog.cpp @@ -22,26 +22,27 @@ #include "analog.h" #include "analogsnapshot.h" +#include + -#include - -using namespace boost; using namespace std; namespace pv { namespace data { -Analog::Analog() : +Analog::Analog(AnalogSnapshot *snapshot) : SignalData() { + assert(snapshot); + _snapshots.push_front(snapshot); } -void Analog::push_snapshot(boost::shared_ptr &snapshot) +void Analog::push_snapshot(AnalogSnapshot *snapshot) { _snapshots.push_front(snapshot); } -deque< boost::shared_ptr >& Analog::get_snapshots() +std::deque& Analog::get_snapshots() { return _snapshots; } @@ -49,15 +50,20 @@ deque< boost::shared_ptr >& Analog::get_snapshots() void Analog::clear() { //_snapshots.clear(); - BOOST_FOREACH(const boost::shared_ptr s, _snapshots) + for(auto &s : _snapshots) s->clear(); } void Analog::init() { //_snapshots.clear(); - BOOST_FOREACH(const boost::shared_ptr s, _snapshots) + for(auto &s : _snapshots) s->init(); } +AnalogSnapshot* Analog::snapshot() +{ + return _snapshots[0]; +} + } // namespace data } // namespace pv diff --git a/DSView/pv/data/analog.h b/DSView/pv/data/analog.h index c28b649f..d3541f8e 100755 --- a/DSView/pv/data/analog.h +++ b/DSView/pv/data/analog.h @@ -26,7 +26,7 @@ #include "signaldata.h" -#include + #include namespace pv { @@ -37,19 +37,17 @@ class AnalogSnapshot; class Analog : public SignalData { public: - Analog(); - - void push_snapshot( - boost::shared_ptr &snapshot); - - std::deque< boost::shared_ptr >& - get_snapshots(); + Analog(AnalogSnapshot *snapshot); + void push_snapshot(AnalogSnapshot *snapshot); + std::deque& get_snapshots(); void clear(); void init(); + AnalogSnapshot* snapshot(); + private: - std::deque< boost::shared_ptr > _snapshots; + std::deque _snapshots; }; } // namespace data diff --git a/DSView/pv/data/analogsnapshot.cpp b/DSView/pv/data/analogsnapshot.cpp index 77b2e4bf..329bafdf 100755 --- a/DSView/pv/data/analogsnapshot.cpp +++ b/DSView/pv/data/analogsnapshot.cpp @@ -20,20 +20,15 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#include - #include #include #include #include - #include - -#include - + #include "analogsnapshot.h" +#include "../extdef.h" -using namespace boost; using namespace std; namespace pv { @@ -60,7 +55,7 @@ AnalogSnapshot::~AnalogSnapshot() void AnalogSnapshot::free_envelop() { for (unsigned int i = 0; i < _channel_num; i++) { - BOOST_FOREACH(Envelope &e, _envelope_levels[i]) { + for(auto &e : _envelope_levels[i]) { if (e.samples) free(e.samples); } @@ -70,7 +65,12 @@ void AnalogSnapshot::free_envelop() void AnalogSnapshot::init() { - boost::lock_guard lock(_mutex); + std::lock_guard lock(_mutex); + init_all(); +} + +void AnalogSnapshot::init_all() +{ _sample_count = 0; _ring_sample_count = 0; _memory_failed = false; @@ -88,10 +88,10 @@ void AnalogSnapshot::init() void AnalogSnapshot::clear() { - boost::lock_guard lock(_mutex); + std::lock_guard lock(_mutex); free_data(); free_envelop(); - init(); + init_all(); } void AnalogSnapshot::first_payload(const sr_datafeed_analog &analog, uint64_t total_sample_count, GSList *channels) @@ -167,7 +167,7 @@ void AnalogSnapshot::first_payload(const sr_datafeed_analog &analog, uint64_t to void AnalogSnapshot::append_payload( const sr_datafeed_analog &analog) { - boost::lock_guard lock(_mutex); + std::lock_guard lock(_mutex); append_data(analog.data, analog.num_samples, analog.unit_pitch); // Generate the first mip-map from the data @@ -212,7 +212,7 @@ void AnalogSnapshot::append_data(void *data, uint64_t samples, uint16_t pitch) } } -const uint8_t* AnalogSnapshot::get_samples(int64_t start_sample) const +const uint8_t* AnalogSnapshot::get_samples(int64_t start_sample) { assert(start_sample >= 0); assert(start_sample < (int64_t)get_sample_count()); @@ -225,7 +225,7 @@ const uint8_t* AnalogSnapshot::get_samples(int64_t start_sample) const } void AnalogSnapshot::get_envelope_section(EnvelopeSection &s, - uint64_t start, int64_t count, float min_length, int probe_index) const + uint64_t start, int64_t count, float min_length, int probe_index) { assert(count >= 0); assert(min_length > 0); @@ -369,7 +369,7 @@ int AnalogSnapshot::get_ch_order(int sig_index) return order; } -int AnalogSnapshot::get_scale_factor() const +int AnalogSnapshot::get_scale_factor() { return EnvelopeScaleFactor; } diff --git a/DSView/pv/data/analogsnapshot.h b/DSView/pv/data/analogsnapshot.h index 644dbfaa..e9716a45 100755 --- a/DSView/pv/data/analogsnapshot.h +++ b/DSView/pv/data/analogsnapshot.h @@ -79,6 +79,9 @@ private: static const uint64_t LeafBlockSamples = 1 << LeafBlockPower; static const uint64_t LeafMask = ~(~0ULL << LeafBlockPower); +private: + void init_all(); + public: AnalogSnapshot(); @@ -92,14 +95,14 @@ public: void append_payload(const sr_datafeed_analog &analog); - const uint8_t *get_samples(int64_t start_sample) const; + const uint8_t *get_samples(int64_t start_sample); void get_envelope_section(EnvelopeSection &s, - uint64_t start, int64_t count, float min_length, int probe_index) const; + uint64_t start, int64_t count, float min_length, int probe_index); int get_ch_order(int sig_index); - int get_scale_factor() const; + int get_scale_factor(); bool has_data(int index); int get_block_num(); diff --git a/DSView/pv/data/decode/AnnotationResTable.cpp b/DSView/pv/data/decode/AnnotationResTable.cpp new file mode 100644 index 00000000..223a3409 --- /dev/null +++ b/DSView/pv/data/decode/AnnotationResTable.cpp @@ -0,0 +1,206 @@ +/* + * This file is part of the PulseView project. + * + * Copyright (C) 2013 Joel Holdsworth + * Copyright (C) 2014 DreamSourceLab + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "AnnotationResTable.h" +#include +#include "../../dsvdef.h" + +#define DECODER_MAX_DATA_BLOCK_LEN 25 + +const char g_bin_cvt_table[] = "0000000100100011010001010110011110001001101010111100110111101111"; +char g_bin_format_tmp_buffer[DECODER_MAX_DATA_BLOCK_LEN * 4 + 2]; +char g_oct_format_tmp_buffer[DECODER_MAX_DATA_BLOCK_LEN * 3 + 2]; +char g_number_tmp_64[30]; + + char* bin2oct_string(char *buf, int size, const char *bin, int len){ + char *wr = buf + size - 1; + *wr = 0; //end flag + + char *rd = (char*)bin + len - 1; //move to last byte + char tmp[3]; + + while (rd >= bin && wr > buf) + { + wr--; + int num = 0; + + while (rd >= bin && num < 3) + { + tmp[2-num] = *rd; + rd--; + num++; + } + + //fill + while (num < 3) + { + tmp[2-num] = '0'; + ++num; + } + + if (strncmp(tmp, "000", 3) == 0) + *wr = '0'; + else if (strncmp(tmp, "001", 3) == 0) + *wr = '1'; + else if (strncmp(tmp, "010", 3) == 0) + *wr = '2'; + else if (strncmp(tmp, "011", 3) == 0) + *wr = '3'; + else if (strncmp(tmp, "100", 3) == 0) + *wr = '4'; + else if (strncmp(tmp, "101", 3) == 0) + *wr = '5'; + else if (strncmp(tmp, "110", 3) == 0) + *wr = '6'; + else if (strncmp(tmp, "111", 3) == 0) + *wr = '7'; + } + + return wr; +} + +long long bin2long_string(const char *bin, int len) +{ + char *rd = (char *)bin + len - 1; //move to last byte + int dex = 0; + long long value = 0; + long long bv = 0; + + while (rd >= bin) + { + if (*rd == '1') + { + bv = 1 << dex; + value += bv; + } + rd--; + ++dex; + } + + return value; +} + + +int AnnotationResTable::MakeIndex(const std::string &key, AnnotationSourceItem* &newItem) +{ + auto fd = m_indexs.find(key); + if (fd != m_indexs.end()){ + return (*fd).second; + } + + AnnotationSourceItem *item = new AnnotationSourceItem(); + m_resourceTable.push_back(item); + + item->cur_display_format = -1; + item->is_numeric = false; + newItem = item; + + int dex = m_indexs.size(); + m_indexs[key] = dex; + return dex; +} + +AnnotationSourceItem* AnnotationResTable::GetItem(int index){ + assert(index >= 0 && index < m_resourceTable.size()); + return m_resourceTable[index]; +} + +const char* AnnotationResTable::format_numberic(const char *hex_str, int fmt) +{ + assert(hex_str); + + //flow, convert to oct\dec\bin format + const char *data = hex_str; + if (data[0] == 0 || fmt == DecoderDataFormat::hex){ + return data; + } + + //convert to bin format + char *buf = g_bin_format_tmp_buffer + sizeof(g_bin_format_tmp_buffer) - 2; + buf[1] = 0; //set the end flag + buf[0] = 0; + + int len = strlen(data); + //buffer is not enough + if (len > DECODER_MAX_DATA_BLOCK_LEN){ + return data; + } + + char *rd = (char*)data + len - 1; //move to last byte + char c = 0; + int dex = 0; + + while (rd >= data) + { + c = *rd; + dex = (int)(c <= '9' ? (c - '0') : (c - 'A' + 10)); + char *ptable = (char*)g_bin_cvt_table + dex * 4; + + buf -= 4; //move to left for 4 bytes + buf[0] = ptable[0]; + buf[1] = ptable[1]; + buf[2] = ptable[2]; + buf[3] = ptable[3]; + + rd--; + } + + //get bin format + if (fmt == DecoderDataFormat::bin){ + return buf; + } + + //get oct format + if (fmt == DecoderDataFormat::oct){ + char *oct_buf = bin2oct_string(g_oct_format_tmp_buffer, + sizeof(g_oct_format_tmp_buffer), buf, len * 4); + return oct_buf; + } + + //64 bit integer + if (fmt == DecoderDataFormat::dec && len * 4 <= 64){ + long long lv = bin2long_string(buf, len * 4); + g_number_tmp_64[0] = 0; + sprintf(g_number_tmp_64, "%lld", lv); + return g_number_tmp_64; + } + + //ascii + if (fmt == DecoderDataFormat::ascii && len < 30 - 3){ + if (len == 2){ + int lv = (int)bin2long_string(buf, len * 4); + //can display chars + if (lv >= 33 && lv <= 126){ + sprintf(g_number_tmp_64, "%c", (char)lv); + return g_number_tmp_64; + } + } + char * const wr_buf = g_number_tmp_64; + g_number_tmp_64[0] = '['; + strcpy(g_number_tmp_64 + 1, data); + g_number_tmp_64[len+1] = ']'; + g_number_tmp_64[len+2] = 0; + return g_number_tmp_64; + } + + return data; +} + diff --git a/DSView/pv/data/decode/AnnotationResTable.h b/DSView/pv/data/decode/AnnotationResTable.h new file mode 100644 index 00000000..1cf98f73 --- /dev/null +++ b/DSView/pv/data/decode/AnnotationResTable.h @@ -0,0 +1,53 @@ +/* + * This file is part of the PulseView project. + * + * Copyright (C) 2013 Joel Holdsworth + * Copyright (C) 2014 DreamSourceLab + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#pragma once + +#include +#include +#include +#include + +struct AnnotationSourceItem +{ + bool is_numeric; + char str_number_hex[18]; //numerical value hex format string + long long numberic_value; + std::vector src_lines; //the origin source string lines + std::vector cvt_lines; //the converted to bin/hex/oct format string lines + int cur_display_format; //current format as bin/ex/oct..., init with -1 +}; + +class AnnotationResTable +{ + public: + int MakeIndex(const std::string &key, AnnotationSourceItem* &newItem); + AnnotationSourceItem* GetItem(int index); + + inline int GetCount(){ + return m_resourceTable.size();} + + static const char* format_numberic(const char *hex_str, int fmt); + + private: + std::map m_indexs; + std::vector m_resourceTable; +}; \ No newline at end of file diff --git a/DSView/pv/data/decode/annotation.cpp b/DSView/pv/data/decode/annotation.cpp index 7f23e36e..6bd60bee 100755 --- a/DSView/pv/data/decode/annotation.cpp +++ b/DSView/pv/data/decode/annotation.cpp @@ -25,27 +25,91 @@ #include #include "annotation.h" +#include "AnnotationResTable.h" +#include +#include +#include +#include "../../config/appconfig.h" +#include "decoderstatus.h" +#include "../../dsvdef.h" + + //a find talbe instance +AnnotationResTable annTable; +char sz_format_tmp_buf[50]; + +bool is_hex_number_str(const char *str) +{ + char c = *str; + int len = 0; + + while (c) + { + ++len; + if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')){ + c = *str; + str++; + continue; + } + return false; + } + return len % 2 == 0 && len > 0; +} namespace pv { namespace data { namespace decode { - -Annotation::Annotation(const srd_proto_data *const pdata) : - _start_sample(pdata->start_sample), - _end_sample(pdata->end_sample) + +Annotation::Annotation(const srd_proto_data *const pdata, DecoderStatus *status) { assert(pdata); const srd_proto_data_annotation *const pda = (const srd_proto_data_annotation*)pdata->data; assert(pda); - _format = pda->ann_class; - _type = pda->ann_type; + _start_sample = pdata->start_sample; + _end_sample = pdata->end_sample; + _format = pda->ann_class; + _type = pda->ann_type; + _resIndex = 0; + _status = status; + + //make resource find key + std::string key; - const char *const *annotations = (char**)pda->ann_text; - while(*annotations) { - _annotations.push_back(QString::fromUtf8(*annotations)); - annotations++; + char **annotations = pda->ann_text; + while(annotations && *annotations) { + key.append(*annotations, strlen(*annotations)); + annotations++; + } + + if (pda->str_number_hex[0]){ + //append numeric string + key.append(pda->str_number_hex, strlen(pda->str_number_hex)); + } + + AnnotationSourceItem *resItem = NULL; + _resIndex = annTable.MakeIndex(key, resItem); + + //is a new item + if (resItem != NULL){ + char **annotations = pda->ann_text; + while(annotations && *annotations) { + resItem->src_lines.push_back(QString::fromUtf8(*annotations)); + annotations++; + } + + //get numeric data + if (pda->str_number_hex[0]){ + strcpy(resItem->str_number_hex, pda->str_number_hex); + resItem->is_numeric = true; + } + else if (resItem->src_lines.size() == 1 && _type >= 100 && _type < 200){ + if (is_hex_number_str(resItem->src_lines[0].toLatin1().data())){ + resItem->is_numeric = true; + } + } + + _status->m_bNumeric |= resItem->is_numeric; } } @@ -57,33 +121,60 @@ Annotation::Annotation() Annotation::~Annotation() { - _annotations.clear(); + } - -uint64_t Annotation::start_sample() const -{ - return _start_sample; -} - -uint64_t Annotation::end_sample() const -{ - return _end_sample; -} - -int Annotation::format() const -{ - return _format; -} - -int Annotation::type() const -{ - return _type; -} - + const std::vector& Annotation::annotations() const { - return _annotations; -} + assert(_status); + + AnnotationSourceItem &resItem = *annTable.GetItem(_resIndex); + + //get origin data, is not a numberic value + if (!resItem.is_numeric){ + return resItem.src_lines; + } + + if (resItem.cur_display_format != _status->m_format){ + resItem.cur_display_format = _status->m_format; + resItem.cvt_lines.clear(); + + if (resItem.src_lines.size() > 0) + { + for (QString &rd_src : resItem.src_lines) + { + if (resItem.str_number_hex[0] != 0) + { + QString src = rd_src.replace("{$}", "%s"); + const char *num_str = AnnotationResTable::format_numberic(resItem.str_number_hex, resItem.cur_display_format); + sprintf(sz_format_tmp_buf, src.toLatin1().data(), num_str); + resItem.cvt_lines.push_back(QString(sz_format_tmp_buf)); + } + else + { + const char *src_str = rd_src.toLatin1().data(); + const char *num_str = AnnotationResTable::format_numberic(src_str, resItem.cur_display_format); + if (src_str != num_str) + resItem.cvt_lines.push_back(QString(num_str)); + else + resItem.cvt_lines.push_back(QString(rd_src)); + } + } + } + else{ + const char *num_str = AnnotationResTable::format_numberic(resItem.str_number_hex, resItem.cur_display_format); + resItem.cvt_lines.push_back(QString(num_str)); + } + } + + return resItem.cvt_lines; +} + +bool Annotation::is_numberic() +{ + AnnotationSourceItem *resItem = annTable.GetItem(_resIndex); + return resItem->is_numeric; +} } // namespace decode } // namespace data diff --git a/DSView/pv/data/decode/annotation.h b/DSView/pv/data/decode/annotation.h index 03e208ef..629ea6fa 100755 --- a/DSView/pv/data/decode/annotation.h +++ b/DSView/pv/data/decode/annotation.h @@ -25,6 +25,10 @@ #include #include +#include + +class AnnotationResTable; +class DecoderStatus; struct srd_proto_data; @@ -32,25 +36,44 @@ namespace pv { namespace data { namespace decode { +//create at DecoderStack.annotation_callback class Annotation { public: - Annotation(const srd_proto_data *const pdata); + Annotation(const srd_proto_data *const pdata, DecoderStatus *status); Annotation(); +public: + ~Annotation(); - uint64_t start_sample() const; - uint64_t end_sample() const; - int format() const; - int type() const; + inline uint64_t start_sample() const{ + return _start_sample; + } + + inline uint64_t end_sample() const{ + return _end_sample; + } + + inline int format() const{ + return _format; + } + + inline int type() const{ + return _type; + } + + bool is_numberic(); + +public: const std::vector& annotations() const; private: - uint64_t _start_sample; - uint64_t _end_sample; - int _format; - int _type; - std::vector _annotations; + uint64_t _start_sample; + uint64_t _end_sample; + short _format; + short _type; + short _resIndex; + DecoderStatus *_status; /*a global variable*/ }; } // namespace decode diff --git a/DSView/pv/data/decode/decoder.cpp b/DSView/pv/data/decode/decoder.cpp index 486340cc..81e4f1c7 100755 --- a/DSView/pv/data/decode/decoder.cpp +++ b/DSView/pv/data/decode/decoder.cpp @@ -22,63 +22,38 @@ #include #include "decoder.h" +#include -using boost::shared_ptr; -using std::set; -using std::map; -using std::string; - + namespace pv { namespace data { namespace decode { -Decoder::Decoder(const srd_decoder *const dec) : - _decoder(dec), - _shown(true), - _setted(true) +Decoder::Decoder(const srd_decoder *const dec): + _decoder(dec) { + _shown = true; + _setted = true; + _decode_start = 0; + _decode_end = 0; + _decode_start_back = 0; + _decode_end_back = 0; } Decoder::~Decoder() { - for (map::const_iterator i = _options_back.begin(); + for (auto i = _options_back.begin(); i != _options_back.end(); i++) if ((*i).second) g_variant_unref((*i).second); } - -const srd_decoder* Decoder::decoder() const -{ - return _decoder; -} - -bool Decoder::shown() const -{ - return _shown; -} - -void Decoder::show(bool show) -{ - _shown = show; -} - -const map& -Decoder::channels() const -{ - return _probes; -} - -void Decoder::set_probes(std::map probes) + +void Decoder::set_probes(std::map probes) { _probes_back = probes; _setted = true; } - -const std::map& Decoder::options() const -{ - return _options; -} - + void Decoder::set_option(const char *id, GVariant *value) { assert(value); @@ -94,21 +69,13 @@ void Decoder::set_decode_region(uint64_t start, uint64_t end) { _decode_start_back = start; _decode_end_back = end; - if (_decode_start != start || - _decode_end != end) - _setted = true; + + if (_decode_start != start || _decode_end != end){ + _setted = true; + } } - -uint64_t Decoder::decode_start() const -{ - return _decode_start; -} - -uint64_t Decoder::decode_end() const -{ - return _decode_end; -} - + +//apply setting bool Decoder::commit() { if (_setted) { @@ -123,7 +90,7 @@ bool Decoder::commit() } } -bool Decoder::have_required_probes() const +bool Decoder::have_required_probes() { for (GSList *l = _decoder->channels; l; l = l->next) { const srd_channel *const pdch = (const srd_channel*)l->data; @@ -135,12 +102,12 @@ bool Decoder::have_required_probes() const return true; } -srd_decoder_inst* Decoder::create_decoder_inst(srd_session *session) const +srd_decoder_inst* Decoder::create_decoder_inst(srd_session *session) { GHashTable *const opt_hash = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, (GDestroyNotify)g_variant_unref); - for (map::const_iterator i = _options.begin(); + for (auto i = _options.begin(); i != _options.end(); i++) { GVariant *const value = (*i).second; @@ -160,9 +127,7 @@ srd_decoder_inst* Decoder::create_decoder_inst(srd_session *session) const GHashTable *const probes = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, (GDestroyNotify)g_variant_unref); - for(map:: - const_iterator i = _probes.begin(); - i != _probes.end(); i++) + for(auto i = _probes.begin(); i != _probes.end(); i++) { GVariant *const gvar = g_variant_new_int32((*i).second); g_variant_ref_sink(gvar); @@ -173,11 +138,7 @@ srd_decoder_inst* Decoder::create_decoder_inst(srd_session *session) const return decoder_inst; } - -int Decoder::get_channel_type(const srd_channel *ch) -{ - return ch->type; -} + } // decode } // data diff --git a/DSView/pv/data/decode/decoder.h b/DSView/pv/data/decode/decoder.h index 0309ae47..1f737f90 100755 --- a/DSView/pv/data/decode/decoder.h +++ b/DSView/pv/data/decode/decoder.h @@ -27,9 +27,7 @@ #include #include #include - -#include - + #include struct srd_decoder; @@ -46,47 +44,69 @@ class Decoder public: Decoder(const srd_decoder *const decoder); +public: + virtual ~Decoder(); - const srd_decoder* decoder() const; + inline const srd_decoder* decoder(){ + return _decoder; + } - bool shown() const; - void show(bool show = true); + inline bool shown(){ + return _shown; + } + + inline void show(bool show = true){ + _shown = show; + } + + inline std::map& channels(){ + return _probes; + } - const std::map& channels() const; void set_probes(std::map probes); - const std::map& options() const; + inline std::map& options(){ + return _options; + } void set_option(const char *id, GVariant *value); - bool have_required_probes() const; + bool have_required_probes(); - srd_decoder_inst* create_decoder_inst(srd_session *session) const; + srd_decoder_inst* create_decoder_inst(srd_session *session); void set_decode_region(uint64_t start, uint64_t end); - uint64_t decode_start() const; - uint64_t decode_end() const; + + inline uint64_t decode_start(){ + return _decode_start; + } + + inline uint64_t decode_end(){ + return _decode_end; + } bool commit(); - int get_channel_type(const srd_channel* ch); + inline int get_channel_type(const srd_channel* ch){ + return ch->type; + } private: const srd_decoder *const _decoder; + + std::map _probes; + std::map _options; + std::map _probes_back; + std::map _options_back; - bool _shown; + uint64_t _decode_start; + uint64_t _decode_end; + uint64_t _decode_start_back; + uint64_t _decode_end_back; - std::map _probes; - std::map _options; - - std::map _probes_back; - std::map _options_back; - - uint64_t _decode_start, _decode_end; - uint64_t _decode_start_back, _decode_end_back; - - bool _setted; + bool _setted; + bool _shown; }; } // namespace decode diff --git a/DSView/pv/data/decode/decoderstatus.h b/DSView/pv/data/decode/decoderstatus.h new file mode 100644 index 00000000..8761bcc2 --- /dev/null +++ b/DSView/pv/data/decode/decoderstatus.h @@ -0,0 +1,38 @@ +/* + * This file is part of the PulseView project. + * + * Copyright (C) 2013 Joel Holdsworth + * Copyright (C) 2014 DreamSourceLab + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#pragma once + +class DecoderStatus +{ +public: + DecoderStatus() + { + m_bNumeric = false; + m_format = 0; + sdr_decoder_handle = NULL; + } + +public: + bool m_bNumeric; //when decoder get any numerical data,it will be set + int m_format; //protocol format code + void *sdr_decoder_handle; +}; diff --git a/DSView/pv/data/decode/row.cpp b/DSView/pv/data/decode/row.cpp index 99958900..abe1633b 100755 --- a/DSView/pv/data/decode/row.cpp +++ b/DSView/pv/data/decode/row.cpp @@ -38,24 +38,16 @@ Row::Row(const srd_decoder *decoder, const srd_decoder_annotation_row *row, cons _row(row), _order(order) { -} +} -Row::~Row() +Row::Row(const Row &o) { - + _decoder = o._decoder; + _row = o._row; + _order = o._order; } -const srd_decoder* Row::decoder() const -{ - return _decoder; -} - -const srd_decoder_annotation_row* Row::row() const -{ - return _row; -} - -const QString Row::title() const +QString Row::title() const { if (_decoder && _decoder->name && _row && _row->desc) return QString("%1: %2") diff --git a/DSView/pv/data/decode/row.h b/DSView/pv/data/decode/row.h index 9466a68d..b5c6cdd9 100755 --- a/DSView/pv/data/decode/row.h +++ b/DSView/pv/data/decode/row.h @@ -32,27 +32,36 @@ namespace pv { namespace data { namespace decode { +//map find key data class Row { public: Row(); - ~Row(); Row(const srd_decoder *decoder, const srd_decoder_annotation_row *row = NULL, const int order = -1); - const srd_decoder* decoder() const; - const srd_decoder_annotation_row* row() const; + Row(const Row &o); - const QString title() const; +public: - bool operator<(const Row &other) const; + inline const srd_decoder* decoder() const{ + return _decoder; + } + + inline const srd_decoder_annotation_row* row() const{ + return _row; + } + + QString title() const; + + bool operator<(const Row &other)const; private: const srd_decoder *_decoder; const srd_decoder_annotation_row *_row; - int _order; + int _order; }; } // decode diff --git a/DSView/pv/data/decode/rowdata.cpp b/DSView/pv/data/decode/rowdata.cpp index c80cbfbd..7dbe30a3 100755 --- a/DSView/pv/data/decode/rowdata.cpp +++ b/DSView/pv/data/decode/rowdata.cpp @@ -31,35 +31,47 @@ namespace pv { namespace data { namespace decode { +std::mutex RowData::_global_visitor_mutex; + RowData::RowData() : _max_annotation(0), _min_annotation(UINT64_MAX) { + _item_count = 0; } RowData::~RowData() { - clear(); + //stack object can not destory the sources } void RowData::clear() { + std::lock_guard lock(_global_visitor_mutex); + + //destroy objercts + for (Annotation *p : _annotations){ + delete p; + } _annotations.clear(); + _item_count = 0; } -uint64_t RowData::get_max_sample() const +uint64_t RowData::get_max_sample() { + std::lock_guard lock(_global_visitor_mutex); + if (_annotations.empty()) return 0; - return _annotations.back().end_sample(); + return _annotations.back()->end_sample(); } -uint64_t RowData::get_max_annotation() const +uint64_t RowData::get_max_annotation() { return _max_annotation; } -uint64_t RowData::get_min_annotation() const +uint64_t RowData::get_min_annotation() { if (_min_annotation == UINT64_MAX) return 10; @@ -67,52 +79,62 @@ uint64_t RowData::get_min_annotation() const return _min_annotation; } -void RowData::get_annotation_subset( - vector &dest, - uint64_t start_sample, uint64_t end_sample) const -{ - for (vector::const_iterator i = _annotations.begin(); - i != _annotations.end(); i++) - if ((*i).end_sample() > start_sample && - (*i).start_sample() <= end_sample) - dest.push_back(*i); +void RowData::get_annotation_subset(std::vector &dest, + uint64_t start_sample, uint64_t end_sample) +{ + std::lock_guard lock(_global_visitor_mutex); + + for (Annotation *p : _annotations){ + if (p->end_sample() > start_sample && + p->start_sample() <= end_sample){ + Annotation a = *p; + dest.push_back(a); + } + } } -uint64_t RowData::get_annotation_index(uint64_t start_sample) const +uint64_t RowData::get_annotation_index(uint64_t start_sample) { + std::lock_guard lock(_global_visitor_mutex); uint64_t index = 0; - for (vector::const_iterator i = _annotations.begin(); - i != _annotations.end(); i++) { - if ((*i).start_sample() > start_sample) - break; - index++; - } + + for (Annotation *p : _annotations){ + if (p->start_sample() > start_sample) + break; + index++; + } + return index; } -bool RowData::push_annotation(const Annotation &a) -{ +bool RowData::push_annotation(Annotation *a) +{ + assert(a); + + std::lock_guard lock(_global_visitor_mutex); + try { _annotations.push_back(a); - _max_annotation = max(_max_annotation, a.end_sample() - a.start_sample()); - if (a.end_sample() != a.start_sample()) - _min_annotation = min(_min_annotation, a.end_sample() - a.start_sample()); + _item_count = _annotations.size(); + _max_annotation = max(_max_annotation, a->end_sample() - a->start_sample()); + + if (a->end_sample() != a->start_sample()) + _min_annotation = min(_min_annotation, a->end_sample() - a->start_sample()); + return true; + } catch (const std::bad_alloc&) { return false; } } + -uint64_t RowData::get_annotation_size() const +bool RowData::get_annotation(Annotation &ann, uint64_t index) { - return _annotations.size(); -} + std::lock_guard lock(_global_visitor_mutex); -bool RowData::get_annotation(Annotation &ann, - uint64_t index) const -{ if (index < _annotations.size()) { - ann = _annotations[index]; + ann = *_annotations[index]; return true; } else { return false; diff --git a/DSView/pv/data/decode/rowdata.h b/DSView/pv/data/decode/rowdata.h index 72d33456..e04af7a6 100755 --- a/DSView/pv/data/decode/rowdata.h +++ b/DSView/pv/data/decode/rowdata.h @@ -22,7 +22,8 @@ #ifndef DSVIEW_PV_DATA_DECODE_ROWDATA_H #define DSVIEW_PV_DATA_DECODE_ROWDATA_H -#include +#include +#include #include "annotation.h" @@ -35,33 +36,37 @@ class RowData public: RowData(); ~RowData(); -public: - uint64_t get_max_sample() const; - uint64_t get_max_annotation() const; - uint64_t get_min_annotation() const; - /** +public: + uint64_t get_max_sample(); + + uint64_t get_max_annotation(); + uint64_t get_min_annotation(); + + uint64_t get_annotation_index(uint64_t start_sample); + + bool push_annotation(Annotation *a); + + inline uint64_t get_annotation_size(){ + return _item_count; + } + + bool get_annotation(pv::data::decode::Annotation &ann, uint64_t index); + + /** * Extracts sorted annotations between two period into a vector. */ - void get_annotation_subset( - std::vector &dest, - uint64_t start_sample, uint64_t end_sample) const; - - uint64_t get_annotation_index(uint64_t start_sample) const; - - bool push_annotation(const Annotation &a); - - uint64_t get_annotation_size() const; - - bool get_annotation(pv::data::decode::Annotation &ann, - uint64_t index) const; + void get_annotation_subset(std::vector &dest, + uint64_t start_sample, uint64_t end_sample); void clear(); private: - uint64_t _max_annotation; - uint64_t _min_annotation; - std::vector _annotations; + uint64_t _max_annotation; + uint64_t _min_annotation; + uint64_t _item_count; + std::vector _annotations; + static std::mutex _global_visitor_mutex; }; } diff --git a/DSView/pv/data/decodermodel.cpp b/DSView/pv/data/decodermodel.cpp index 614f67ff..dbf7f121 100755 --- a/DSView/pv/data/decodermodel.cpp +++ b/DSView/pv/data/decodermodel.cpp @@ -19,13 +19,9 @@ */ #include - -#include -#include - -#include -#include - + +#include "decode/annotation.h" +#include "decode/rowdata.h" #include "decoderstack.h" #include "decodermodel.h" @@ -41,18 +37,13 @@ DecoderModel::DecoderModel(QObject *parent) { } -void DecoderModel::setDecoderStack(boost::shared_ptr decoder_stack) +void DecoderModel::setDecoderStack(DecoderStack *decoder_stack) { beginResetModel(); _decoder_stack = decoder_stack; endResetModel(); } - -const boost::shared_ptr& DecoderModel::getDecoderStack() const -{ - return _decoder_stack; -} - + int DecoderModel::rowCount(const QModelIndex & /* parent */) const { if (_decoder_stack) diff --git a/DSView/pv/data/decodermodel.h b/DSView/pv/data/decodermodel.h index 09032729..a08fe1bf 100755 --- a/DSView/pv/data/decodermodel.h +++ b/DSView/pv/data/decodermodel.h @@ -22,10 +22,8 @@ #define DSVIEW_PV_DATA_DECODERMODEL_H #include - -#include - -#include + +#include "decode/rowdata.h" namespace pv { namespace data { @@ -46,14 +44,16 @@ public: int rowCount(const QModelIndex & /*parent*/) const; int columnCount(const QModelIndex & /*parent*/) const; QVariant data(const QModelIndex &index, int role) const; - QVariant headerData(int section, Qt::Orientation orientation, - int role) const; + QVariant headerData(int section, Qt::Orientation orientation,int role) const; - void setDecoderStack(boost::shared_ptr decoder_stack); - const boost::shared_ptr& getDecoderStack() const; + void setDecoderStack(DecoderStack *decoder_stack); + + inline DecoderStack* getDecoderStack(){ + return _decoder_stack; + } private: - boost::shared_ptr _decoder_stack; + DecoderStack *_decoder_stack; }; } // namespace data diff --git a/DSView/pv/data/decoderstack.cpp b/DSView/pv/data/decoderstack.cpp index 60bb699e..7b7f3930 100755 --- a/DSView/pv/data/decoderstack.cpp +++ b/DSView/pv/data/decoderstack.cpp @@ -18,9 +18,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#include -#include + #include #include @@ -29,74 +27,72 @@ #include "decoderstack.h" -#include -#include -#include -#include -#include -#include - -using namespace boost; -using namespace std; +#include "logic.h" +#include "logicsnapshot.h" +#include "decode/decoder.h" +#include "decode/annotation.h" +#include "decode/rowdata.h" +#include "../sigsession.h" +#include "../view/logicsignal.h" +#include "../dsvdef.h" +#include using namespace pv::data::decode; +using namespace std; +using namespace boost; namespace pv { namespace data { const double DecoderStack::DecodeMargin = 1.0; const double DecoderStack::DecodeThreshold = 0.2; -const int64_t DecoderStack::DecodeChunkLength = 4 * 1024; -//const int64_t DecoderStack::DecodeChunkLength = 1024 * 1024; +const int64_t DecoderStack::DecodeChunkLength = 4 * 1024; const unsigned int DecoderStack::DecodeNotifyPeriod = 1024; - -boost::mutex DecoderStack::_global_decode_mutex; - -DecoderStack::DecoderStack(pv::SigSession &session, - const srd_decoder *const dec) : - _session(session), - _sample_count(0), - _frame_complete(false), - _samples_decoded(0), - _decode_state(Stopped), - _options_changed(false), - _no_memory(false), - _mark_index(-1) + +DecoderStack::DecoderStack(pv::SigSession *session, + const srd_decoder *const dec, DecoderStatus *decoder_status) : + _session(session) { - connect(&_session, SIGNAL(frame_began()), - this, SLOT(on_new_frame())); - connect(&_session, SIGNAL(data_received()), - this, SLOT(on_data_received())); - connect(&_session, SIGNAL(frame_ended()), - this, SLOT(on_frame_ended())); - - _stack.push_back(boost::shared_ptr( - new decode::Decoder(dec))); - + assert(session); + assert(dec); + assert(decoder_status); + + _samples_decoded = 0; + _sample_count = 0; + _decode_state = Stopped; + _options_changed = false; + _no_memory = false; + _mark_index = -1; + _decoder_status = decoder_status; + _stask_stauts = NULL; + + _stack.push_back(new decode::Decoder(dec)); + build_row(); } DecoderStack::~DecoderStack() -{ -// if (_decode_thread.joinable()) { -// _decode_thread.interrupt(); -// _decode_thread.join(); -// } - stop_decode(); - _stack.clear(); +{ + //release source + for (auto &kv : _rows) + { + kv.second->clear(); + delete kv.second; + } _rows.clear(); + + //Decoder + for (auto *p : _stack){ + delete p; + } + _stack.clear(); + _rows_gshow.clear(); _rows_lshow.clear(); _class_rows.clear(); } - -const std::list< boost::shared_ptr >& -DecoderStack::stack() const -{ - return _stack; -} - -void DecoderStack::push(boost::shared_ptr decoder) + +void DecoderStack::push(decode::Decoder *decoder) { assert(decoder); _stack.push_back(decoder); @@ -104,17 +100,20 @@ void DecoderStack::push(boost::shared_ptr decoder) _options_changed = true; } -void DecoderStack::remove(boost::shared_ptr &decoder) +void DecoderStack::remove(Decoder *decoder) { // Find the decoder in the stack - list< boost::shared_ptr >::iterator iter = _stack.begin(); + auto iter = _stack.begin(); for(unsigned int i = 0; i < _stack.size(); i++, iter++) if ((*iter) == decoder) break; // Delete the element if (iter != _stack.end()) + { _stack.erase(iter); + delete decoder; + } build_row(); _options_changed = true; @@ -122,9 +121,15 @@ void DecoderStack::remove(boost::shared_ptr &decoder) void DecoderStack::build_row() { + //release source + for (auto &kv : _rows) + { + delete kv.second; + } _rows.clear(); + // Add classes - BOOST_FOREACH (const boost::shared_ptr &dec, _stack) + for (auto &dec : _stack) { assert(dec); const srd_decoder *const decc = dec->decoder(); @@ -133,7 +138,7 @@ void DecoderStack::build_row() // Add a row for the decoder if it doesn't have a row list if (!decc->annotation_rows) { const Row row(decc); - _rows[row] = decode::RowData(); + _rows[row] = new decode::RowData(); std::map::const_iterator iter = _rows_gshow.find(row); if (iter == _rows_gshow.end()) { _rows_gshow[row] = true; @@ -157,7 +162,7 @@ void DecoderStack::build_row() const Row row(decc, ann_row, order); // Add a new empty row data object - _rows[row] = decode::RowData(); + _rows[row] = new decode::RowData(); std::map::const_iterator iter = _rows_gshow.find(row); if (iter == _rows_gshow.end()) { _rows_gshow[row] = true; @@ -180,61 +185,49 @@ void DecoderStack::build_row() } } -int64_t DecoderStack::samples_decoded() const +int64_t DecoderStack::samples_decoded() { - boost::lock_guard decode_lock(_output_mutex); + std::lock_guard decode_lock(_output_mutex); return _samples_decoded; } void DecoderStack::get_annotation_subset( std::vector &dest, const Row &row, uint64_t start_sample, - uint64_t end_sample) const -{ - //lock_guard lock(_output_mutex); - - std::map::const_iterator iter = - _rows.find(row); + uint64_t end_sample) +{ + auto iter = _rows.find(row); if (iter != _rows.end()) - (*iter).second.get_annotation_subset(dest, + (*iter).second->get_annotation_subset(dest, start_sample, end_sample); } uint64_t DecoderStack::get_annotation_index( - const Row &row, uint64_t start_sample) const -{ - //lock_guard lock(_output_mutex); - + const Row &row, uint64_t start_sample) +{ uint64_t index = 0; - std::map::const_iterator iter = - _rows.find(row); + auto iter = _rows.find(row); if (iter != _rows.end()) - index = (*iter).second.get_annotation_index(start_sample); + index = (*iter).second->get_annotation_index(start_sample); return index; } uint64_t DecoderStack::get_max_annotation(const Row &row) -{ - //lock_guard lock(_output_mutex); - - std::map::const_iterator iter = - _rows.find(row); +{ + auto iter = _rows.find(row); if (iter != _rows.end()) - return (*iter).second.get_max_annotation(); + return (*iter).second->get_max_annotation(); return 0; } uint64_t DecoderStack::get_min_annotation(const Row &row) -{ - //lock_guard lock(_output_mutex); - - std::map::const_iterator iter = - _rows.find(row); +{ + auto iter = _rows.find(row); if (iter != _rows.end()) - return (*iter).second.get_min_annotation(); + return (*iter).second->get_min_annotation(); return 0; } @@ -275,14 +268,12 @@ void DecoderStack::set_rows_lshow(const decode::Row row, bool show) } } -bool DecoderStack::has_annotations(const Row &row) const -{ - //lock_guard lock(_output_mutex); - - std::map::const_iterator iter = +bool DecoderStack::has_annotations(const Row &row) +{ + auto iter = _rows.find(row); if (iter != _rows.end()) - if(0 == (*iter).second.get_max_sample()) + if(0 == (*iter).second->get_max_sample()) return false; else return true; @@ -290,46 +281,43 @@ bool DecoderStack::has_annotations(const Row &row) const return false; } -uint64_t DecoderStack::list_annotation_size() const +uint64_t DecoderStack::list_annotation_size() { - boost::lock_guard lock(_output_mutex); + std::lock_guard lock(_output_mutex); uint64_t max_annotation_size = 0; - for (map::const_iterator i = _rows.begin(); + for (auto i = _rows.begin(); i != _rows.end(); i++) { - map::const_iterator iter = _rows_lshow.find((*i).first); + auto iter = _rows_lshow.find((*i).first); if (iter != _rows_lshow.end() && (*iter).second) max_annotation_size = max(max_annotation_size, - (*i).second.get_annotation_size()); + (*i).second->get_annotation_size()); } return max_annotation_size; } -uint64_t DecoderStack::list_annotation_size(uint16_t row_index) const -{ - //lock_guard lock(_output_mutex); - //int row = 0; - for (map::const_iterator i = _rows.begin(); +uint64_t DecoderStack::list_annotation_size(uint16_t row_index) +{ + for (auto i = _rows.begin(); i != _rows.end(); i++) { - map::const_iterator iter = _rows_lshow.find((*i).first); + auto iter = _rows_lshow.find((*i).first); if (iter != _rows_lshow.end() && (*iter).second) if (row_index-- == 0) { - return (*i).second.get_annotation_size(); + return (*i).second->get_annotation_size(); } } return 0; } bool DecoderStack::list_annotation(pv::data::decode::Annotation &ann, - uint16_t row_index, uint64_t col_index) const -{ - //lock_guard lock(_output_mutex); - for (map::const_iterator i = _rows.begin(); + uint16_t row_index, uint64_t col_index) +{ + for (auto i = _rows.begin(); i != _rows.end(); i++) { - map::const_iterator iter = _rows_lshow.find((*i).first); + auto iter = _rows_lshow.find((*i).first); if (iter != _rows_lshow.end() && (*iter).second) { if (row_index-- == 0) { - return (*i).second.get_annotation(ann, col_index); + return (*i).second->get_annotation(ann, col_index); } } } @@ -338,12 +326,11 @@ bool DecoderStack::list_annotation(pv::data::decode::Annotation &ann, } -bool DecoderStack::list_row_title(int row, QString &title) const -{ - //lock_guard lock(_output_mutex); - for (map::const_iterator i = _rows.begin(); +bool DecoderStack::list_row_title(int row, QString &title) +{ + for (auto i = _rows.begin(); i != _rows.end(); i++) { - map::const_iterator iter = _rows_lshow.find((*i).first); + auto iter = _rows_lshow.find((*i).first); if (iter != _rows_lshow.end() && (*iter).second) { if (row-- == 0) { title = (*i).first.title(); @@ -355,8 +342,7 @@ bool DecoderStack::list_row_title(int row, QString &title) const } QString DecoderStack::error_message() -{ - //lock_guard lock(_output_mutex); +{ return _error_message; } @@ -367,45 +353,59 @@ void DecoderStack::clear() void DecoderStack::init() { - _sample_count = 0; - _frame_complete = false; + _sample_count = 0; _samples_decoded = 0; _error_message = QString(); _no_memory = false; - for (map::iterator i = _rows.begin(); - i != _rows.end(); i++) { - //_rows[(*i).first] = decode::RowData(); - (*i).second.clear(); + + for (auto i = _rows.begin(); + i != _rows.end(); i++) { + (*i).second->clear(); } + set_mark_index(-1); } - -void DecoderStack::stop_decode() -{ - //_snapshot.reset(); - if(_decode_state != Stopped) { - if (_decode_thread.get()) { - _decode_thread->interrupt(); - _decode_thread->join(); - _decode_state = Stopped; - } - _decode_thread.reset(); - } + +void DecoderStack::stop_decode_work() +{ + //set the flag to exit from task thread + if (_stask_stauts){ + _stask_stauts->m_bStop = true; + } + _decode_state = Stopped; } -void DecoderStack::begin_decode() +void DecoderStack::begin_decode_work() { - boost::shared_ptr logic_signal; - boost::shared_ptr data; + assert(_decode_state == Stopped); + + _decode_state = Running; + do_decode_work(); + _decode_state = Stopped; +} + +void DecoderStack::do_decode_work() +{ + //set the flag to exit from task thread + if (_stask_stauts){ + _stask_stauts->m_bStop = true; + } + _stask_stauts = new decode_task_status(); + _stask_stauts->m_bStop = false; + + pv::view::LogicSignal *logic_signal = NULL; + pv::data::Logic *data = NULL; if (!_options_changed) + { return; + } _options_changed = false; - stop_decode(); + init(); // Check that all decoders have the required channels - BOOST_FOREACH(const boost::shared_ptr &dec, _stack) + for(auto &dec : _stack) if (!dec->have_required_probes()) { _error_message = tr("One or more required channels " "have not been specified"); @@ -415,11 +415,11 @@ void DecoderStack::begin_decode() // We get the logic data of the first channel in the list. // This works because we are currently assuming all // LogicSignals have the same data/snapshot - BOOST_FOREACH (const boost::shared_ptr &dec, _stack) { + for (auto &dec : _stack) { if (dec && !dec->channels().empty()) { - BOOST_FOREACH(boost::shared_ptr sig, _session.get_signals()) { + for(auto &sig : _session->get_signals()) { if((sig->get_index() == (*dec->channels().begin()).second) && - (logic_signal = dynamic_pointer_cast(sig)) && + (logic_signal = dynamic_cast(sig)) && (data = logic_signal->logic_data())) break; } @@ -432,10 +432,10 @@ void DecoderStack::begin_decode() return; // Check we have a snapshot of data - const deque< boost::shared_ptr > &snapshots = - data->get_snapshots(); + const auto &snapshots = data->get_snapshots(); if (snapshots.empty()) return; + _snapshot = snapshots.front(); if (_snapshot->empty()) return; @@ -444,27 +444,27 @@ void DecoderStack::begin_decode() _samplerate = data->samplerate(); if (_samplerate == 0.0) return; - - //_decode_thread = boost::thread(&DecoderStack::decode_proc, this); - _decode_thread.reset(new boost::thread(&DecoderStack::decode_proc, this)); + + decode_proc(); } -uint64_t DecoderStack::get_max_sample_count() const +uint64_t DecoderStack::get_max_sample_count() { uint64_t max_sample_count = 0; - for (map::const_iterator i = _rows.begin(); - i != _rows.end(); i++) - max_sample_count = max(max_sample_count, - (*i).second.get_max_sample()); + for (auto i = _rows.begin(); i != _rows.end(); i++){ + max_sample_count = max(max_sample_count, (*i).second->get_max_sample()); + } return max_sample_count; } -void DecoderStack::decode_data( - const uint64_t decode_start, const uint64_t decode_end, - srd_session *const session) +void DecoderStack::decode_data(const uint64_t decode_start, const uint64_t decode_end, srd_session *const session) { + decode_task_status *status = _stask_stauts; + + // qDebug()<<"decode start:"< decode_lock(_global_decode_mutex); + char *error = NULL; + + if( i >= decode_end){ + qDebug()<<"decode data index have been end:"<m_bStop){ + break; + } + std::vector chunk; std::vector chunk_const; uint64_t chunk_end = decode_end; + for (int j =0 ; j < logic_di->dec_num_channels; j++) { int sig_index = logic_di->dec_channelmap[j]; if (sig_index == -1) { @@ -510,15 +518,23 @@ void DecoderStack::decode_data( if (chunk_end - i > MaxChunkSize) chunk_end = i + MaxChunkSize; - if (srd_session_send(session, i, chunk_end, - chunk.data(), chunk_const.data(), chunk_end - i, &error) != SRD_OK) { + if (srd_session_send( + session, + i, + chunk_end, + chunk.data(), + chunk_const.data(), + chunk_end - i, + &error) != SRD_OK){ _error_message = QString::fromLocal8Bit(error); break; } + i = chunk_end; + //use mutex { - boost::lock_guard lock(_output_mutex); + std::lock_guard lock(_output_mutex); _samples_decoded = i - decode_start + 1; } @@ -527,17 +543,19 @@ void DecoderStack::decode_data( new_decode_data(); } entry_cnt++; - } + } + + qDebug()<<"send to decoder times:"<is_closed()) + decode_done(); } void DecoderStack::decode_proc() -{ - boost::lock_guard decode_lock(_global_decode_mutex); - - optional sample_count; +{ srd_session *session; srd_decoder_inst *prev_di = NULL; uint64_t decode_start = 0; @@ -547,18 +565,15 @@ void DecoderStack::decode_proc() // Create the session srd_session_new(&session); + assert(session); - - _decode_state = Running; - + // Get the intial sample count - { - //unique_lock input_lock(_input_mutex); - sample_count = _sample_count = _snapshot->get_sample_count(); - } + _sample_count = _snapshot->get_sample_count(); + // Create the decoders - BOOST_FOREACH(const boost::shared_ptr &dec, _stack) + for(auto &dec : _stack) { srd_decoder_inst *const di = dec->create_decoder_inst(session); @@ -586,6 +601,7 @@ void DecoderStack::decode_proc() char *error = NULL; if (srd_session_start(session, &error) == SRD_OK) + //need a lot time decode_data(decode_start, decode_end, session); else _error_message = QString::fromLocal8Bit(error); @@ -594,12 +610,10 @@ void DecoderStack::decode_proc() if (error) { g_free(error); } - srd_session_destroy(session); - - _decode_state = Stopped; + srd_session_destroy(session); } -uint64_t DecoderStack::sample_count() const +uint64_t DecoderStack::sample_count() { if (_snapshot) return _snapshot->get_sample_count(); @@ -607,11 +621,12 @@ uint64_t DecoderStack::sample_count() const return 0; } -uint64_t DecoderStack::sample_rate() const +uint64_t DecoderStack::sample_rate() { return _samplerate; } +//the decode callback, annotation object will be create void DecoderStack::annotation_callback(srd_proto_data *pdata, void *decoder) { assert(pdata); @@ -619,14 +634,16 @@ void DecoderStack::annotation_callback(srd_proto_data *pdata, void *decoder) DecoderStack *const d = (DecoderStack*)decoder; assert(d); - - //lock_guard lock(d->_output_mutex); - + if (d->_no_memory) { return; } - const Annotation a(pdata); + Annotation *a = new Annotation(pdata, d->_decoder_status); + if (a == NULL){ + d->_no_memory = true; + return; + } // Find the row assert(pdata->pdo); @@ -634,11 +651,11 @@ void DecoderStack::annotation_callback(srd_proto_data *pdata, void *decoder) const srd_decoder *const decc = pdata->pdo->di->decoder; assert(decc); - map::iterator row_iter = d->_rows.end(); + auto row_iter = d->_rows.end(); // Try looking up the sub-row of this class const map, Row>::const_iterator r = - d->_class_rows.find(make_pair(decc, a.format())); + d->_class_rows.find(make_pair(decc, a->format())); if (r != d->_class_rows.end()) row_iter = d->_rows.find((*r).second); else @@ -650,58 +667,33 @@ void DecoderStack::annotation_callback(srd_proto_data *pdata, void *decoder) assert(row_iter != d->_rows.end()); if (row_iter == d->_rows.end()) { qDebug() << "Unexpected annotation: decoder = " << decc << - ", format = " << a.format(); + ", format = " << a->format(); assert(0); return; } - // Add the annotation - boost::lock_guard lock(d->_output_mutex); - if (!(*row_iter).second.push_annotation(a)) - d->_no_memory = true; + // Add the annotation + if (!(*row_iter).second->push_annotation(a)) + d->_no_memory = true; } - -void DecoderStack::on_new_frame() -{ - //begin_decode(); -} - -void DecoderStack::on_data_received() -{ -// { -// unique_lock lock(_input_mutex); -// if (_snapshot) -// _sample_count = _snapshot->get_sample_count(); -// } -// _input_cond.notify_one(); -} - -void DecoderStack::on_frame_ended() -{ -// { -// unique_lock lock(_input_mutex); -// if (_snapshot) -// _frame_complete = true; -// } -// _input_cond.notify_one(); - _options_changed = true; - begin_decode(); + +void DecoderStack::frame_ended() +{ + _options_changed = true; } int DecoderStack::list_rows_size() -{ - //lock_guard lock(_output_mutex); +{ int rows_size = 0; - for (map::const_iterator i = _rows.begin(); - i != _rows.end(); i++) { - map::const_iterator iter = _rows_lshow.find((*i).first); + for (auto i = _rows.begin(); i != _rows.end(); i++) { + auto iter = _rows_lshow.find((*i).first); if (iter != _rows_lshow.end() && (*iter).second) rows_size++; } return rows_size; } -bool DecoderStack::options_changed() const +bool DecoderStack::options_changed() { return _options_changed; } @@ -711,7 +703,7 @@ void DecoderStack::set_options_changed(bool changed) _options_changed = changed; } -bool DecoderStack::out_of_memory() const +bool DecoderStack::out_of_memory() { return _no_memory; } @@ -721,7 +713,7 @@ void DecoderStack::set_mark_index(int64_t index) _mark_index = index; } -int64_t DecoderStack::get_mark_index() const +int64_t DecoderStack::get_mark_index() { return _mark_index; } diff --git a/DSView/pv/data/decoderstack.h b/DSView/pv/data/decoderstack.h index c7baf7cc..7685e272 100755 --- a/DSView/pv/data/decoderstack.h +++ b/DSView/pv/data/decoderstack.h @@ -21,25 +21,28 @@ #ifndef DSVIEW_PV_DATA_DECODERSTACK_H #define DSVIEW_PV_DATA_DECODERSTACK_H + #include - #include - #include -#include -#include - #include #include +#include -#include "../data/decode/row.h" -#include "../data/decode/rowdata.h" +#include "decode/row.h" #include "../data/signaldata.h" +class DecoderStatus; + +struct decode_task_status +{ + volatile bool m_bStop; +}; + namespace DecoderStackTest { class TwoDecoderStack; } - + namespace pv { class SigSession; @@ -55,10 +58,12 @@ class LogicSnapshot; namespace decode { class Annotation; class Decoder; +class RowData; } class Logic; + //a torotocol have a DecoderStack, destroy by DecodeTrace class DecoderStack : public QObject, public SignalData { Q_OBJECT @@ -77,17 +82,22 @@ public: }; public: - DecoderStack(pv::SigSession &_session, - const srd_decoder *const decoder); + DecoderStack(pv::SigSession *_session, + const srd_decoder *const decoder, DecoderStatus *decoder_status); + +public: virtual ~DecoderStack(); - const std::list< boost::shared_ptr >& stack() const; - void push(boost::shared_ptr decoder); - void remove(boost::shared_ptr& decoder); + inline std::list& stack(){ + return _stack; + } + + void push(decode::Decoder *decoder); + void remove(decode::Decoder *decoder); void build_row(); - int64_t samples_decoded() const; + int64_t samples_decoded(); /** * Extracts sorted annotations between two period into a vector. @@ -95,11 +105,10 @@ public: void get_annotation_subset( std::vector &dest, const decode::Row &row, uint64_t start_sample, - uint64_t end_sample) const; + uint64_t end_sample); uint64_t get_annotation_index( - const decode::Row &row, uint64_t start_sample) const; - + const decode::Row &row, uint64_t start_sample); uint64_t get_max_annotation(const decode::Row &row); uint64_t get_min_annotation(const decode::Row &row); // except instant(end=start) annotation @@ -107,100 +116,71 @@ public: std::map get_rows_lshow(); void set_rows_gshow(const decode::Row row, bool show); void set_rows_lshow(const decode::Row row, bool show); - - bool has_annotations(const decode::Row &row) const; - - uint64_t list_annotation_size() const; - uint64_t list_annotation_size(uint16_t row_index) const; + bool has_annotations(const decode::Row &row); + uint64_t list_annotation_size(); + uint64_t list_annotation_size(uint16_t row_index); bool list_annotation(decode::Annotation &ann, - uint16_t row_index, uint64_t col_index) const; + uint16_t row_index, uint64_t col_index); - bool list_row_title(int row, QString &title) const; - + bool list_row_title(int row, QString &title); QString error_message(); - void clear(); void init(); + uint64_t get_max_sample_count(); - uint64_t get_max_sample_count() const; - - void begin_decode(); - - void stop_decode(); - + inline bool IsRunning(){ + return _decode_state == Running; + } + + void begin_decode_work(); + void do_decode_work(); + void stop_decode_work(); int list_rows_size(); - - bool options_changed() const; + bool options_changed(); void set_options_changed(bool changed); - uint64_t sample_count() const; - uint64_t sample_rate() const; - - bool out_of_memory() const; - + uint64_t sample_count(); + uint64_t sample_rate(); + bool out_of_memory(); void set_mark_index(int64_t index); - int64_t get_mark_index() const; + int64_t get_mark_index(); + void frame_ended(); private: void decode_data(const uint64_t decode_start, const uint64_t decode_end, srd_session *const session); - void decode_proc(); + static void annotation_callback(srd_proto_data *pdata, void *decoder); - static void annotation_callback(srd_proto_data *pdata, - void *decoder); - -private slots: - void on_new_frame(); - - void on_data_received(); - - void on_frame_ended(); - + signals: void new_decode_data(); void decode_done(); - -private: - pv::SigSession &_session; - - /** - * This mutex prevents more than one decode operation occuring - * concurrently. - * @todo A proper solution should be implemented to allow multiple - * decode operations. - */ - static boost::mutex _global_decode_mutex; - - std::list< boost::shared_ptr > _stack; - - boost::shared_ptr _snapshot; - - //mutable boost::mutex _input_mutex; - //mutable boost::condition_variable _input_cond; - uint64_t _sample_count; - bool _frame_complete; - - mutable boost::recursive_mutex _output_mutex; - //mutable boost::mutex _output_mutex; - int64_t _samples_decoded; - - std::map _rows; - std::map _rows_gshow; - std::map _rows_lshow; + +private: + std::list _stack; + pv::data::LogicSnapshot *_snapshot; + + std::map _rows; + std::map _rows_gshow; + std::map _rows_lshow; std::map, decode::Row> _class_rows; + + SigSession *_session; + decode_state _decode_state; + volatile bool _options_changed; + volatile bool _no_memory; + int64_t _mark_index; - QString _error_message; - - std::unique_ptr _decode_thread; - decode_state _decode_state; - - bool _options_changed; - bool _no_memory; - - int64_t _mark_index; + DecoderStatus *_decoder_status; + QString _error_message; + int64_t _samples_decoded; + uint64_t _sample_count; + + decode_task_status *_stask_stauts; + mutable std::mutex _output_mutex; friend class DecoderStackTest::TwoDecoderStack; }; diff --git a/DSView/pv/data/dso.cpp b/DSView/pv/data/dso.cpp index 7362010f..ea05f5b7 100755 --- a/DSView/pv/data/dso.cpp +++ b/DSView/pv/data/dso.cpp @@ -21,26 +21,27 @@ #include "dso.h" #include "dsosnapshot.h" +#include + -#include - -using namespace boost; using namespace std; namespace pv { namespace data { -Dso::Dso() : +Dso::Dso(DsoSnapshot *snapshot) : SignalData() { + assert(snapshot); + _snapshots.push_front(snapshot); } -void Dso::push_snapshot(boost::shared_ptr &snapshot) +void Dso::push_snapshot(DsoSnapshot *snapshot) { _snapshots.push_front(snapshot); } -deque< boost::shared_ptr >& Dso::get_snapshots() +std::deque& Dso::get_snapshots() { return _snapshots; } @@ -48,16 +49,21 @@ deque< boost::shared_ptr >& Dso::get_snapshots() void Dso::clear() { //_snapshots.clear(); - BOOST_FOREACH(const boost::shared_ptr s, _snapshots) + for(auto &s : _snapshots) s->clear(); } void Dso::init() { //_snapshots.clear(); - BOOST_FOREACH(const boost::shared_ptr s, _snapshots) + for(auto &s : _snapshots) s->init(); } + DsoSnapshot* Dso::snapshot() + { + return _snapshots[0]; + } + } // namespace data } // namespace pv diff --git a/DSView/pv/data/dso.h b/DSView/pv/data/dso.h index 0902972a..cd03988d 100755 --- a/DSView/pv/data/dso.h +++ b/DSView/pv/data/dso.h @@ -24,8 +24,7 @@ #define DSVIEW_PV_DATA_DSO_H #include "signaldata.h" - -#include + #include namespace pv { @@ -36,19 +35,19 @@ class DsoSnapshot; class Dso : public SignalData { public: - Dso(); + Dso(DsoSnapshot *snapshot); - void push_snapshot( - boost::shared_ptr &snapshot); + void push_snapshot(DsoSnapshot *snapshot); - std::deque< boost::shared_ptr >& - get_snapshots(); + std::deque& get_snapshots(); void clear(); void init(); + DsoSnapshot* snapshot(); + private: - std::deque< boost::shared_ptr > _snapshots; + std::deque _snapshots; }; } // namespace data diff --git a/DSView/pv/data/dsosnapshot.cpp b/DSView/pv/data/dsosnapshot.cpp index 89da7800..62642a94 100755 --- a/DSView/pv/data/dsosnapshot.cpp +++ b/DSView/pv/data/dsosnapshot.cpp @@ -19,20 +19,15 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#include - #include #include #include #include - #include - -#include - + #include "dsosnapshot.h" +#include "../extdef.h" -using namespace boost; using namespace std; namespace pv { @@ -63,7 +58,7 @@ DsoSnapshot::~DsoSnapshot() void DsoSnapshot::free_envelop() { for (unsigned int i = 0; i < _channel_num; i++) { - BOOST_FOREACH(Envelope &e, _envelope_levels[i]) { + for(auto &e : _envelope_levels[i]) { if (e.samples) free(e.samples); } @@ -73,13 +68,19 @@ void DsoSnapshot::free_envelop() void DsoSnapshot::init() { - boost::lock_guard lock(_mutex); + std::lock_guard lock(_mutex); + init_all(); +} + +void DsoSnapshot::init_all() +{ _sample_count = 0; _ring_sample_count = 0; _memory_failed = false; _last_ended = true; _envelope_done = false; _ch_enable.clear(); + for (unsigned int i = 0; i < _channel_num; i++) { for (unsigned int level = 0; level < ScaleStepCount; level++) { _envelope_levels[i][level].length = 0; @@ -90,10 +91,10 @@ void DsoSnapshot::init() void DsoSnapshot::clear() { - boost::lock_guard lock(_mutex); + std::lock_guard lock(_mutex); free_data(); free_envelop(); - init(); + init_all(); } void DsoSnapshot::first_payload(const sr_datafeed_dso &dso, uint64_t total_sample_count, @@ -157,7 +158,7 @@ void DsoSnapshot::first_payload(const sr_datafeed_dso &dso, uint64_t total_sampl void DsoSnapshot::append_payload(const sr_datafeed_dso &dso) { - boost::lock_guard lock(_mutex); + std::lock_guard lock(_mutex); if (_channel_num > 0 && dso.num_samples != 0) { append_data(dso.data, dso.num_samples, _instant); @@ -184,33 +185,30 @@ void DsoSnapshot::append_data(void *data, uint64_t samples, bool instant) void DsoSnapshot::enable_envelope(bool enable) { - boost::lock_guard lock(_mutex); + std::lock_guard lock(_mutex); if (!_envelope_done && enable) append_payload_to_envelope_levels(true); _envelope_en = enable; } const uint8_t *DsoSnapshot::get_samples( - int64_t start_sample, int64_t end_sample, uint16_t index) const + int64_t start_sample, int64_t end_sample, uint16_t index) { - boost::lock_guard lock(_mutex); + std::lock_guard lock(_mutex); (void)end_sample; assert(start_sample >= 0); - assert(start_sample < (int64_t)get_sample_count()); + assert(start_sample < (int64_t)sample_count()); assert(end_sample >= 0); - assert(end_sample < (int64_t)get_sample_count()); + assert(end_sample < (int64_t)sample_count()); assert(start_sample <= end_sample); -// uint16_t *const data = new uint16_t[end_sample - start_sample]; -// memcpy(data, (uint16_t*)_data + start_sample, sizeof(uint16_t) * -// (end_sample - start_sample)); -// return data; + return (uint8_t*)_data + start_sample * _channel_num + index * (_channel_num != 1); } void DsoSnapshot::get_envelope_section(EnvelopeSection &s, - uint64_t start, uint64_t end, float min_length, int probe_index) const + uint64_t start, uint64_t end, float min_length, int probe_index) { assert(end <= get_sample_count()); assert(start <= end); @@ -348,7 +346,7 @@ void DsoSnapshot::append_payload_to_envelope_levels(bool header) _envelope_done = true; } -double DsoSnapshot::cal_vrms(double zero_off, int index) const +double DsoSnapshot::cal_vrms(double zero_off, int index) { assert(index >= 0); //assert(index < _channel_num); @@ -378,12 +376,12 @@ double DsoSnapshot::cal_vrms(double zero_off, int index) const vrms = vrms_pre + vrms / get_sample_count(); vrms_pre = vrms; } - vrms = std::pow(vrms, 0.5); + vrms = pow(vrms, 0.5); return vrms; } -double DsoSnapshot::cal_vmean(int index) const +double DsoSnapshot::cal_vmean(int index) { assert(index >= 0); //assert(index < _channel_num); diff --git a/DSView/pv/data/dsosnapshot.h b/DSView/pv/data/dsosnapshot.h index aa19cca5..b32eb78f 100755 --- a/DSView/pv/data/dsosnapshot.h +++ b/DSView/pv/data/dsosnapshot.h @@ -25,6 +25,7 @@ #include #include +#include #include #include "snapshot.h" @@ -74,6 +75,9 @@ private: static const int VrmsScaleFactor; +private: + void init_all(); + public: DsoSnapshot(); @@ -88,15 +92,15 @@ public: void append_payload(const sr_datafeed_dso &dso); const uint8_t* get_samples(int64_t start_sample, - int64_t end_sample, uint16_t index) const; + int64_t end_sample, uint16_t index); void get_envelope_section(EnvelopeSection &s, - uint64_t start, uint64_t end, float min_length, int probe_index) const; + uint64_t start, uint64_t end, float min_length, int probe_index); void enable_envelope(bool enable); - double cal_vrms(double zero_off, int index) const; - double cal_vmean(int index) const; + double cal_vrms(double zero_off, int index); + double cal_vmean(int index); bool has_data(int index); int get_block_num(); diff --git a/DSView/pv/data/group.cpp b/DSView/pv/data/group.cpp index a9ee2cbe..04f699a1 100755 --- a/DSView/pv/data/group.cpp +++ b/DSView/pv/data/group.cpp @@ -21,10 +21,8 @@ #include "group.h" #include "groupsnapshot.h" + -#include - -using namespace boost; using namespace std; namespace pv { @@ -35,25 +33,25 @@ Group::Group() : { } -void Group::push_snapshot(boost::shared_ptr &snapshot) +void Group::push_snapshot(GroupSnapshot *snapshot) { _snapshots.push_back(snapshot); } -deque< boost::shared_ptr >& Group::get_snapshots() +std::deque& Group::get_snapshots() { return _snapshots; } void Group::clear() { - BOOST_FOREACH(const boost::shared_ptr s, _snapshots) + for(auto &s : _snapshots) s->clear(); } void Group::init() { - BOOST_FOREACH(const boost::shared_ptr s, _snapshots) + for(auto &s : _snapshots) s->init(); } diff --git a/DSView/pv/data/group.h b/DSView/pv/data/group.h index 1312c6ee..bc6e4e53 100755 --- a/DSView/pv/data/group.h +++ b/DSView/pv/data/group.h @@ -24,8 +24,7 @@ #define DSVIEW_PV_DATA_GROUP_H #include "signaldata.h" - -#include + #include namespace pv { @@ -38,17 +37,15 @@ class Group : public SignalData public: Group(); - void push_snapshot( - boost::shared_ptr &snapshot); + void push_snapshot(GroupSnapshot *snapshot); - std::deque< boost::shared_ptr >& - get_snapshots(); + std::deque& get_snapshots(); void clear(); void init(); private: - std::deque< boost::shared_ptr > _snapshots; + std::deque _snapshots; }; } // namespace data diff --git a/DSView/pv/data/groupsnapshot.cpp b/DSView/pv/data/groupsnapshot.cpp index ae6b6cb3..1e8430a4 100755 --- a/DSView/pv/data/groupsnapshot.cpp +++ b/DSView/pv/data/groupsnapshot.cpp @@ -18,9 +18,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#include - + #include #include #include @@ -28,12 +26,10 @@ #include -#include - #include "logicsnapshot.h" #include "groupsnapshot.h" +#include "../extdef.h" -using namespace boost; using namespace std; namespace pv { @@ -49,15 +45,17 @@ const uint16_t GroupSnapshot::value_mask[16] = {0x1, 0x2, 0x4, 0x8, 0x100, 0x200, 0x400, 0x800, 0x1000, 0x2000, 0x4000, 0x8000}; -GroupSnapshot::GroupSnapshot(const boost::shared_ptr &_logic_snapshot, std::list index_list) +GroupSnapshot::GroupSnapshot(const LogicSnapshot *_logic_snapshot, std::list index_list) { assert(_logic_snapshot); - //boost::lock_guard lock(_mutex); + LogicSnapshot *logic_snapshot = const_cast(_logic_snapshot); + + memset(_envelope_levels, 0, sizeof(_envelope_levels)); - _data = _logic_snapshot->get_data(); - _sample_count = _logic_snapshot->get_sample_count(); - _unit_size = _logic_snapshot->unit_size(); + _data = logic_snapshot->get_data(); + _sample_count = logic_snapshot->get_sample_count(); + _unit_size = logic_snapshot->unit_size(); _index_list = index_list; _mask = 0; @@ -94,9 +92,8 @@ GroupSnapshot::GroupSnapshot(const boost::shared_ptr &_logic_snap } GroupSnapshot::~GroupSnapshot() -{ - //boost::lock_guard lock(_mutex); - BOOST_FOREACH(Envelope &e, _envelope_levels) +{ + for(auto &e : _envelope_levels) free(e.samples); } @@ -110,17 +107,14 @@ void GroupSnapshot::clear() } -uint64_t GroupSnapshot::get_sample_count() const -{ - //boost::lock_guard lock(_mutex); +uint64_t GroupSnapshot::get_sample_count() +{ return _sample_count; } void GroupSnapshot::append_payload() { - //boost::lock_guard lock(_mutex); - - // Generate the first mip-map from the data + append_payload_to_envelope_levels(); } @@ -134,13 +128,10 @@ const uint16_t* GroupSnapshot::get_samples( assert(start_sample <= end_sample); int64_t i; - uint16_t tmpl, tmpr; - //boost::lock_guard lock(_mutex); + uint16_t tmpl, tmpr; uint16_t *const data = new uint16_t[end_sample - start_sample]; -// memcpy(data, (uint16_t*)_data + start_sample, sizeof(uint16_t) * -// (end_sample - start_sample)); -// memset(data, 0, sizeof(uint16_t) * (end_sample - start_sample)); + for(i = start_sample; i < end_sample; i++) { if (_unit_size == 2) tmpl = *((uint16_t*)_data + i) & _mask; @@ -158,13 +149,12 @@ const uint16_t* GroupSnapshot::get_samples( } void GroupSnapshot::get_envelope_section(EnvelopeSection &s, - uint64_t start, uint64_t end, float min_length) const + uint64_t start, uint64_t end, float min_length) { assert(end <= _sample_count); assert(start <= end); assert(min_length > 0); - - //boost::lock_guard lock(_mutex); + const unsigned int min_level = max((int)floorf(logf(min_length) / LogEnvelopeScaleFactor) - 1, 0); diff --git a/DSView/pv/data/groupsnapshot.h b/DSView/pv/data/groupsnapshot.h index 4d87b001..683e4f96 100755 --- a/DSView/pv/data/groupsnapshot.h +++ b/DSView/pv/data/groupsnapshot.h @@ -22,10 +22,7 @@ #ifndef DSVIEW_PV_DATA_GROUPSNAPSHOT_H #define DSVIEW_PV_DATA_GROUPSNAPSHOT_H - -#include -#include - + #include "../view/signal.h" #include @@ -75,7 +72,7 @@ private: static const uint16_t value_mask[16]; public: - GroupSnapshot(const boost::shared_ptr &_logic_snapshot, std::list index_list); + GroupSnapshot(const LogicSnapshot *_logic_snapshot, std::list index_list); virtual ~GroupSnapshot(); @@ -84,13 +81,13 @@ public: void append_payload(); - uint64_t get_sample_count() const; + uint64_t get_sample_count(); const uint16_t* get_samples(int64_t start_sample, int64_t end_sample); void get_envelope_section(EnvelopeSection &s, - uint64_t start, uint64_t end, float min_length) const; + uint64_t start, uint64_t end, float min_length); private: void reallocate_envelope(Envelope &l); @@ -99,11 +96,11 @@ private: private: struct Envelope _envelope_levels[ScaleStepCount]; - //mutable boost::recursive_mutex _mutex; + const void *_data; uint64_t _sample_count; int _unit_size; - boost::shared_ptr _signal; + view::Signal *_signal; std::list _index_list; uint16_t _mask; int _bubble_start[32]; diff --git a/DSView/pv/data/logic.cpp b/DSView/pv/data/logic.cpp index 9797b214..ccc7ec54 100755 --- a/DSView/pv/data/logic.cpp +++ b/DSView/pv/data/logic.cpp @@ -22,27 +22,26 @@ #include "logic.h" #include "logicsnapshot.h" +#include -#include - -using namespace boost; using namespace std; namespace pv { namespace data { -Logic::Logic() : +Logic::Logic(LogicSnapshot *snapshot) : SignalData() { + assert(snapshot); + _snapshots.push_front(snapshot); } -void Logic::push_snapshot( - boost::shared_ptr &snapshot) +void Logic::push_snapshot(LogicSnapshot *snapshot) { _snapshots.push_front(snapshot); } -deque< boost::shared_ptr >& Logic::get_snapshots() +std::deque& Logic::get_snapshots() { return _snapshots; } @@ -50,16 +49,21 @@ deque< boost::shared_ptr >& Logic::get_snapshots() void Logic::clear() { //_snapshots.clear(); - BOOST_FOREACH(const boost::shared_ptr s, _snapshots) + for(auto &s : _snapshots) s->clear(); } void Logic::init() { //_snapshots.clear(); - BOOST_FOREACH(const boost::shared_ptr s, _snapshots) + for(auto &s : _snapshots) s->init(); } + LogicSnapshot* Logic::snapshot() + { + return _snapshots[0]; + } + } // namespace data } // namespace pv diff --git a/DSView/pv/data/logic.h b/DSView/pv/data/logic.h index f163b35c..5f925a1c 100755 --- a/DSView/pv/data/logic.h +++ b/DSView/pv/data/logic.h @@ -25,8 +25,7 @@ #define DSVIEW_PV_DATA_LOGIC_H #include "signaldata.h" - -#include + #include namespace pv { @@ -37,20 +36,20 @@ class LogicSnapshot; class Logic : public SignalData { public: - Logic(); + Logic(LogicSnapshot *snapshot); - void push_snapshot( - boost::shared_ptr &snapshot); + void push_snapshot(LogicSnapshot *snapshot); - std::deque< boost::shared_ptr >& - get_snapshots(); + std::deque& get_snapshots(); void clear(); void init(); + LogicSnapshot* snapshot(); + private: - std::deque< boost::shared_ptr > _snapshots; + std::deque _snapshots; }; } // namespace data diff --git a/DSView/pv/data/logicsnapshot.cpp b/DSView/pv/data/logicsnapshot.cpp index 05426722..f4e42584 100755 --- a/DSView/pv/data/logicsnapshot.cpp +++ b/DSView/pv/data/logicsnapshot.cpp @@ -19,21 +19,17 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#include - + #include #include #include #include #include - -#include - + #include "logicsnapshot.h" +#include "../extdef.h" -using namespace boost; using namespace std; namespace pv { @@ -80,8 +76,13 @@ void LogicSnapshot::free_data() void LogicSnapshot::init() { - boost::lock_guard lock(_mutex); - _sample_count = 0; + std::lock_guard lock(_mutex); + init_all(); +} + +void LogicSnapshot::init_all() +{ + _sample_count = 0; _ring_sample_count = 0; _block_num = 0; _byte_fraction = 0; @@ -95,9 +96,9 @@ void LogicSnapshot::init() void LogicSnapshot::clear() { - boost::lock_guard lock(_mutex); + std::lock_guard lock(_mutex); free_data(); - init(); + init_all(); } void LogicSnapshot::capture_ended() @@ -203,7 +204,7 @@ void LogicSnapshot::first_payload(const sr_datafeed_logic &logic, uint64_t total void LogicSnapshot::append_payload( const sr_datafeed_logic &logic) { - boost::lock_guard lock(_mutex); + std::lock_guard lock(_mutex); if (logic.format == LA_CROSS_DATA) append_cross_payload(logic); @@ -473,8 +474,9 @@ const uint8_t *LogicSnapshot::get_samples(uint64_t start_sample, uint64_t &end_s int sig_index) { //assert(data); - assert(start_sample < get_sample_count()); - assert(end_sample <= get_sample_count()); + uint64_t sample_count = get_sample_count(); + assert(start_sample < sample_count); + assert(end_sample <= sample_count); assert(start_sample <= end_sample); int order = get_ch_order(sig_index); diff --git a/DSView/pv/data/logicsnapshot.h b/DSView/pv/data/logicsnapshot.h index bfbf0b78..34bcc13c 100755 --- a/DSView/pv/data/logicsnapshot.h +++ b/DSView/pv/data/logicsnapshot.h @@ -32,6 +32,7 @@ #include #include +#include namespace LogicSnapshotTest { class Pow2; @@ -76,13 +77,19 @@ private: public: typedef std::pair EdgePair; +private: + void init_all(); + public: LogicSnapshot(); virtual ~LogicSnapshot(); + void free_data(); + void clear(); - void init(); + + void init(); void first_payload(const sr_datafeed_logic &logic, uint64_t total_sample_count, GSList *channels); diff --git a/DSView/pv/data/mathstack.cpp b/DSView/pv/data/mathstack.cpp index 759b53b3..9b2d9686 100755 --- a/DSView/pv/data/mathstack.cpp +++ b/DSView/pv/data/mathstack.cpp @@ -19,14 +19,12 @@ */ #include "mathstack.h" - -#include -#include - -#include -#include -#include -#include + +#include "dso.h" +#include "dsosnapshot.h" +#include "../sigsession.h" +#include "../view/dsosignal.h" +#include #define PI 3.1415 @@ -75,9 +73,9 @@ const QString MathStack::vDialDivUnit[MathStack::vDialUnitCount] = { "V/V", }; -MathStack::MathStack(pv::SigSession &session, - boost::shared_ptr dsoSig1, - boost::shared_ptr dsoSig2, +MathStack::MathStack(pv::SigSession *session, + view::DsoSignal* dsoSig1, + view::DsoSignal* dsoSig2, MathType type) : _session(session), _dsoSig1(dsoSig1), @@ -100,7 +98,7 @@ MathStack::~MathStack() void MathStack::free_envelop() { - BOOST_FOREACH(Envelope &e, _envelope_level) { + for(auto &e : _envelope_level) { if (e.samples) free(e.samples); } @@ -109,23 +107,23 @@ void MathStack::free_envelop() void MathStack::clear() { - boost::lock_guard lock(_mutex); + std::lock_guard lock(_mutex); } void MathStack::init() { - boost::lock_guard lock(_mutex); + std::lock_guard lock(_mutex); _sample_num = 0; _envelope_done = false; } -MathStack::MathType MathStack::get_type() const +MathStack::MathType MathStack::get_type() { return _type; } -uint64_t MathStack::get_sample_num() const +uint64_t MathStack::get_sample_num() { return _sample_num; } @@ -279,13 +277,13 @@ double MathStack::get_math_scale() return scale; } -const double* MathStack::get_math(uint64_t start) const +const double* MathStack::get_math(uint64_t start) { return _math.data() + start; } void MathStack::get_math_envelope_section(EnvelopeSection &s, - uint64_t start, uint64_t end, float min_length) const + uint64_t start, uint64_t end, float min_length) { assert(end <= get_sample_num()); assert(start <= end); @@ -315,18 +313,16 @@ void MathStack::get_math_envelope_section(EnvelopeSection &s, void MathStack::calc_math() { - boost::lock_guard lock(_mutex); + std::lock_guard lock(_mutex); _math_state = Running; - const boost::shared_ptr data = _dsoSig1->dso_data(); - const deque< boost::shared_ptr > &snapshots = - data->get_snapshots(); + const auto data = _dsoSig1->dso_data(); + const auto &snapshots = data->get_snapshots(); if (snapshots.empty()) return; - const boost::shared_ptr &snapshot = - snapshots.front(); + const auto snapshot = snapshots.front(); if (snapshot->empty()) return; diff --git a/DSView/pv/data/mathstack.h b/DSView/pv/data/mathstack.h index ffb80db4..2fb72fbc 100755 --- a/DSView/pv/data/mathstack.h +++ b/DSView/pv/data/mathstack.h @@ -25,9 +25,8 @@ #include -#include -#include -#include +#include + #include #include @@ -102,17 +101,17 @@ private: static const QString vDialDivUnit[vDialUnitCount]; public: - MathStack(pv::SigSession &_session, - boost::shared_ptr dsoSig1, - boost::shared_ptr dsoSig2, MathType type); + MathStack(pv::SigSession *_session, + view::DsoSignal *dsoSig1, + view::DsoSignal *dsoSig2, MathType type); virtual ~MathStack(); void clear(); void init(); void free_envelop(); void realloc(uint64_t num); - MathType get_type() const; - uint64_t get_sample_num() const; + MathType get_type(); + uint64_t get_sample_num(); void enable_envelope(bool enable); @@ -121,9 +120,9 @@ public: QString get_unit(int level); double get_math_scale(); - const double *get_math(uint64_t start) const; + const double *get_math(uint64_t start); void get_math_envelope_section(EnvelopeSection &s, - uint64_t start, uint64_t end, float min_length) const; + uint64_t start, uint64_t end, float min_length); void calc_math(); void reallocate_envelope(Envelope &e); @@ -132,9 +131,9 @@ public: signals: private: - pv::SigSession &_session; - boost::shared_ptr _dsoSig1; - boost::shared_ptr _dsoSig2; + pv::SigSession *_session; + view::DsoSignal *_dsoSig1; + view::DsoSignal *_dsoSig2; MathType _type; uint64_t _sample_num; diff --git a/DSView/pv/data/signaldata.cpp b/DSView/pv/data/signaldata.cpp index 19005905..31c60937 100755 --- a/DSView/pv/data/signaldata.cpp +++ b/DSView/pv/data/signaldata.cpp @@ -33,11 +33,7 @@ SignalData::SignalData() : } SignalData::~SignalData() {} - -double SignalData::samplerate() const -{ - return _samplerate; -} + void SignalData::set_samplerate(double samplerate) { diff --git a/DSView/pv/data/signaldata.h b/DSView/pv/data/signaldata.h index 7ade4ddd..f3269421 100755 --- a/DSView/pv/data/signaldata.h +++ b/DSView/pv/data/signaldata.h @@ -25,7 +25,7 @@ #define DSVIEW_PV_DATA_SIGNALDATA_H #include -#include +#include namespace pv { namespace data { @@ -35,17 +35,17 @@ class SignalData public: SignalData(); virtual ~SignalData() = 0; + public: - double samplerate() const; + inline double samplerate()const + {return _samplerate; } + void set_samplerate(double samplerate); - virtual void clear() = 0; - virtual void init() = 0; protected: - mutable boost::recursive_mutex _mutex; - + mutable std::mutex _mutex; double _samplerate; }; diff --git a/DSView/pv/data/snapshot.cpp b/DSView/pv/data/snapshot.cpp index 50a094d0..c359addb 100755 --- a/DSView/pv/data/snapshot.cpp +++ b/DSView/pv/data/snapshot.cpp @@ -28,9 +28,7 @@ #include #include #include - -using namespace boost; - + namespace pv { namespace data { @@ -66,12 +64,7 @@ void Snapshot::free_data() _ch_index.clear(); } -bool Snapshot::memory_failed() const -{ - return _memory_failed; -} - -bool Snapshot::empty() const +bool Snapshot::empty() { if (get_sample_count() == 0) return true; @@ -79,34 +72,34 @@ bool Snapshot::empty() const return false; } -bool Snapshot::last_ended() const +uint64_t Snapshot::get_sample_count() { - return _last_ended; -} - -void Snapshot::set_last_ended(bool ended) -{ - _last_ended = ended; -} - -uint64_t Snapshot::get_sample_count() const -{ - boost::lock_guard lock(_mutex); + std::lock_guard lock(_mutex); return _sample_count; } - -uint64_t Snapshot::get_ring_start() const + +uint64_t Snapshot::get_ring_start() { - boost::lock_guard lock(_mutex); + std::lock_guard lock(_mutex); + return ring_start(); +} + +uint64_t Snapshot::get_ring_end() +{ + std::lock_guard lock(_mutex); + return ring_end(); +} + +uint64_t Snapshot::ring_start() +{ if (_sample_count < _total_sample_count) return 0; else return _ring_sample_count; } - -uint64_t Snapshot::get_ring_end() const -{ - boost::lock_guard lock(_mutex); + +uint64_t Snapshot::ring_end() +{ if (_sample_count == 0) return 0; else if (_ring_sample_count == 0) @@ -115,26 +108,6 @@ uint64_t Snapshot::get_ring_end() const return _ring_sample_count - 1; } -const void* Snapshot::get_data() const -{ - return _data; -} - -int Snapshot::unit_size() const -{ - return _unit_size; -} - -uint8_t Snapshot::get_unit_bytes() const -{ - return _unit_bytes; -} - -unsigned int Snapshot::get_channel_num() const -{ - return _channel_num; -} - void Snapshot::capture_ended() { set_last_ended(true); diff --git a/DSView/pv/data/snapshot.h b/DSView/pv/data/snapshot.h index 5ea70a9a..5113aef0 100755 --- a/DSView/pv/data/snapshot.h +++ b/DSView/pv/data/snapshot.h @@ -23,7 +23,8 @@ #ifndef DSVIEW_PV_DATA_SNAPSHOT_H #define DSVIEW_PV_DATA_SNAPSHOT_H -#include +#include +#include namespace pv { namespace data { @@ -38,22 +39,39 @@ public: virtual void clear() = 0; virtual void init() = 0; - uint64_t get_sample_count() const; - uint64_t get_ring_start() const; - uint64_t get_ring_end() const; + uint64_t get_sample_count(); + uint64_t get_ring_start(); + uint64_t get_ring_end(); - const void * get_data() const; + inline const void* get_data(){ + return _data; + } - int unit_size() const; - uint8_t get_unit_bytes() const; + inline int unit_size(){ + return _unit_size; + } - bool memory_failed() const; - bool empty() const; + inline uint8_t get_unit_bytes(){ + return _unit_bytes; + } - bool last_ended() const; - void set_last_ended(bool ended); + inline bool memory_failed(){ + return _memory_failed; + } - unsigned int get_channel_num() const; + bool empty(); + + inline bool last_ended(){ + return _last_ended; + } + + inline void set_last_ended(bool ended){ + _last_ended = ended; + } + + inline unsigned int get_channel_num(){ + return _channel_num; + } virtual void capture_ended(); virtual bool has_data(int index) = 0; @@ -63,12 +81,19 @@ public: protected: virtual void free_data(); -protected: - mutable boost::recursive_mutex _mutex; + inline uint64_t sample_count(){ + return _sample_count; + } - //std::vector _data; + uint64_t ring_start(); + uint64_t ring_end(); + +protected: + mutable std::mutex _mutex; + + void* _data; - std::vector _ch_index; + mutable std::vector _ch_index; uint64_t _capacity; unsigned int _channel_num; diff --git a/DSView/pv/data/spectrumstack.cpp b/DSView/pv/data/spectrumstack.cpp index d040eb9b..99c34e9b 100755 --- a/DSView/pv/data/spectrumstack.cpp +++ b/DSView/pv/data/spectrumstack.cpp @@ -19,14 +19,12 @@ */ #include "spectrumstack.h" - -#include -#include - -#include -#include -#include -#include + +#include "dso.h" +#include "dsosnapshot.h" +#include "../sigsession.h" +#include "../view/dsosignal.h" +#include #define PI 3.1415 @@ -52,7 +50,7 @@ const uint64_t SpectrumStack::length_support[5] = { 16384, }; -SpectrumStack::SpectrumStack(pv::SigSession &session, int index) : +SpectrumStack::SpectrumStack(pv::SigSession *session, int index) : _session(session), _index(index), _dc_ignore(true), @@ -79,12 +77,12 @@ void SpectrumStack::init() { } -int SpectrumStack::get_index() const +int SpectrumStack::get_index() { return _index; } -uint64_t SpectrumStack::get_sample_num() const +uint64_t SpectrumStack::get_sample_num() { return _sample_num; } @@ -99,7 +97,7 @@ void SpectrumStack::set_sample_num(uint64_t num) FFTW_R2HC, FFTW_ESTIMATE); } -int SpectrumStack::get_windows_index() const +int SpectrumStack::get_windows_index() { return _windows_index; } @@ -109,7 +107,7 @@ void SpectrumStack::set_windows_index(int index) _windows_index = index; } -bool SpectrumStack::dc_ignored() const +bool SpectrumStack::dc_ignored() { return _dc_ignore; } @@ -119,7 +117,7 @@ void SpectrumStack::set_dc_ignore(bool ignore) _dc_ignore = ignore; } -int SpectrumStack::get_sample_interval() const +int SpectrumStack::get_sample_interval() { return _sample_interval; } @@ -129,7 +127,7 @@ void SpectrumStack::set_sample_interval(int interval) _sample_interval = interval; } -const std::vector SpectrumStack::get_windows_support() const +const std::vector SpectrumStack::get_windows_support() { std::vector windows; for (size_t i = 0; i < sizeof(windows_support)/sizeof(windows_support[0]); i++) @@ -139,7 +137,7 @@ const std::vector SpectrumStack::get_windows_support() const return windows; } -const std::vector SpectrumStack::get_length_support() const +const std::vector SpectrumStack::get_length_support() { std::vector length; for (size_t i = 0; i < sizeof(length_support)/sizeof(length_support[0]); i++) @@ -149,7 +147,7 @@ const std::vector SpectrumStack::get_length_support() const return length; } -const std::vector SpectrumStack::get_fft_spectrum() const +const std::vector SpectrumStack::get_fft_spectrum() { std::vector empty; if (_spectrum_state == Stopped) @@ -171,10 +169,11 @@ void SpectrumStack::calc_fft() { _spectrum_state = Running; // Get the dso data - boost::shared_ptr data; - boost::shared_ptr dsoSig; - BOOST_FOREACH(const boost::shared_ptr s, _session.get_signals()) { - if ((dsoSig = dynamic_pointer_cast(s))) { + pv::data::Dso *data = NULL; + pv::view::DsoSignal *dsoSig = NULL; + + for(auto &s : _session->get_signals()) { + if ((dsoSig = dynamic_cast(s))) { if (dsoSig->get_index() == _index && dsoSig->enabled()) { data = dsoSig->dso_data(); break; @@ -186,10 +185,10 @@ void SpectrumStack::calc_fft() return; // Check we have a snapshot of data - const deque< boost::shared_ptr > &snapshots = - data->get_snapshots(); + const auto &snapshots = data->get_snapshots(); if (snapshots.empty()) return; + _snapshot = snapshots.front(); if (_snapshot->get_sample_count() < _sample_num*_sample_interval) diff --git a/DSView/pv/data/spectrumstack.h b/DSView/pv/data/spectrumstack.h index caa4d268..146742ed 100755 --- a/DSView/pv/data/spectrumstack.h +++ b/DSView/pv/data/spectrumstack.h @@ -25,10 +25,8 @@ #include -#include -#include -#include - +#include + #include #include @@ -63,29 +61,29 @@ public: }; public: - SpectrumStack(pv::SigSession &_session, int index); + SpectrumStack(pv::SigSession *_session, int index); virtual ~SpectrumStack(); void clear(); void init(); - int get_index() const; + int get_index(); - uint64_t get_sample_num() const; + uint64_t get_sample_num(); void set_sample_num(uint64_t num); - int get_windows_index() const; + int get_windows_index(); void set_windows_index(int index); - const std::vector get_windows_support() const; - const std::vector get_length_support() const; + const std::vector get_windows_support(); + const std::vector get_length_support(); - bool dc_ignored() const; + bool dc_ignored(); void set_dc_ignore(bool ignore); - int get_sample_interval() const; + int get_sample_interval(); void set_sample_interval(int interval); - const std::vector get_fft_spectrum() const; + const std::vector get_fft_spectrum(); double get_fft_spectrum(uint64_t index); void calc_fft(); @@ -95,7 +93,7 @@ public: signals: private: - pv::SigSession &_session; + pv::SigSession *_session; int _index; uint64_t _sample_num; @@ -103,7 +101,7 @@ private: bool _dc_ignore; int _sample_interval; - boost::shared_ptr _snapshot; + pv::data::DsoSnapshot *_snapshot; spectrum_state _spectrum_state; fftw_plan _fft_plan; diff --git a/DSView/pv/device/device.cpp b/DSView/pv/device/device.cpp index 4eb77b33..4e056b45 100755 --- a/DSView/pv/device/device.cpp +++ b/DSView/pv/device/device.cpp @@ -35,7 +35,12 @@ Device::Device(sr_dev_inst *sdi) : assert(_sdi); } -sr_dev_inst* Device::dev_inst() const +Device::~Device() +{ + +} + +sr_dev_inst* Device::dev_inst() { return _sdi; } @@ -45,9 +50,8 @@ void Device::use(SigSession *owner) DevInst::use(owner); sr_session_new(); - - assert(_sdi); sr_dev_open(_sdi); + _usable = (_sdi->status == SR_ST_ACTIVE); if (sr_session_dev_add(_sdi) != SR_OK) throw QString(tr("Failed to use device.")); @@ -63,19 +67,10 @@ void Device::release() sr_dev_close(_sdi); } -QString Device::format_device_title() const +QString Device::format_device_title() { ostringstream s; - assert(_sdi); - -// if (_sdi->vendor && _sdi->vendor[0]) { -// s << _sdi->vendor; -// if ((_sdi->model && _sdi->model[0]) || -// (_sdi->version && _sdi->version[0])) -// s << ' '; -// } - if (_sdi->model && _sdi->model[0]) { s << _sdi->model; if (_sdi->version && _sdi->version[0]) @@ -88,9 +83,8 @@ QString Device::format_device_title() const return QString::fromStdString(s.str()); } -bool Device::is_trigger_enabled() const +bool Device::is_trigger_enabled() { - assert(_sdi); for (const GSList *l = _sdi->channels; l; l = l->next) { const sr_channel *const p = (const sr_channel *)l->data; assert(p); diff --git a/DSView/pv/device/device.h b/DSView/pv/device/device.h index f1ec24f1..0290f5a2 100755 --- a/DSView/pv/device/device.h +++ b/DSView/pv/device/device.h @@ -28,19 +28,21 @@ namespace pv { namespace device { class Device : public DevInst -{ +{ public: Device(sr_dev_inst *dev_inst); - sr_dev_inst* dev_inst() const; + ~Device(); + + sr_dev_inst* dev_inst(); void use(SigSession *owner); void release(); - QString format_device_title() const; + QString format_device_title(); - bool is_trigger_enabled() const; + bool is_trigger_enabled(); private: sr_dev_inst *const _sdi; diff --git a/DSView/pv/device/devinst.cpp b/DSView/pv/device/devinst.cpp index 6aeeeb87..92c4894f 100755 --- a/DSView/pv/device/devinst.cpp +++ b/DSView/pv/device/devinst.cpp @@ -25,7 +25,7 @@ #include "devinst.h" -#include +#include "../sigsession.h" namespace pv { namespace device { @@ -43,7 +43,7 @@ DevInst::~DevInst() free(_id); } -void* DevInst::get_id() const +void* DevInst::get_id() { assert(_id); @@ -53,7 +53,6 @@ void* DevInst::get_id() const void DevInst::use(SigSession *owner) { assert(owner); - assert(!_owner); _owner = owner; } @@ -61,11 +60,10 @@ void DevInst::release() { if (_owner) { _owner->release_device(this); - _owner = NULL; } } -SigSession* DevInst::owner() const +SigSession* DevInst::owner() { return _owner; } @@ -189,7 +187,7 @@ QString DevInst::name() return QString::fromLocal8Bit(sdi->driver->name); } -bool DevInst::is_trigger_enabled() const +bool DevInst::is_trigger_enabled() { return false; } @@ -197,18 +195,34 @@ bool DevInst::is_trigger_enabled() const void DevInst::start() { if (sr_session_start() != SR_OK) - throw tr("Failed to start session."); + throw tr("Failed to start session."); + //assert(false); } void DevInst::run() { - sr_session_run(); + qDebug()<<"session run loop start"; + int ret = sr_session_run(); + if (ret != SR_OK){ + qDebug()<<"start session error!"; + } + qDebug()<<"session run loop end"; } -bool DevInst::is_usable() const +void DevInst::stop() +{ + sr_session_stop(); +} + +bool DevInst::is_usable() { return _usable; } +void DevInst::destroy(){ + release(); + //delete this; //do not to destroy +} + } // device } // pv diff --git a/DSView/pv/device/devinst.h b/DSView/pv/device/devinst.h index b7c7f8c3..83b1a884 100755 --- a/DSView/pv/device/devinst.h +++ b/DSView/pv/device/devinst.h @@ -22,8 +22,6 @@ #ifndef DSVIEW_PV_DEVICE_DEVINST_H #define DSVIEW_PV_DEVICE_DEVINST_H -#include - #include #include @@ -48,19 +46,12 @@ class DevInst : public QObject protected: DevInst(); - ~DevInst(); -public: - virtual sr_dev_inst* dev_inst() const = 0; - - virtual void use(SigSession *owner); - - virtual void release(); - - SigSession* owner() const; - - virtual QString format_device_title() const = 0; + virtual ~DevInst(); +public: + SigSession* owner(); + GVariant* get_config(const sr_channel *ch, const sr_channel_group *group, int key); bool set_config(sr_channel *ch, sr_channel_group *group, int key, GVariant *data); @@ -115,17 +106,30 @@ public: * @return device name */ QString name(); + - virtual bool is_trigger_enabled() const; + bool is_usable(); - bool is_usable() const; + void destroy(); public: virtual void start(); virtual void run(); - virtual void* get_id() const; + virtual void stop(); + + virtual void* get_id(); + + virtual sr_dev_inst* dev_inst() = 0; + + virtual void use(SigSession *owner); + + virtual void release(); + + virtual bool is_trigger_enabled(); + + virtual QString format_device_title() = 0; signals: void device_updated(); diff --git a/DSView/pv/device/file.cpp b/DSView/pv/device/file.cpp index 7efee676..c24233e2 100755 --- a/DSView/pv/device/file.cpp +++ b/DSView/pv/device/file.cpp @@ -39,7 +39,11 @@ File::File(QString path) : { } -QString File::format_device_title() const +File::~File(){ + +} + +QString File::format_device_title() { QFileInfo fi(_path); return fi.fileName(); @@ -92,7 +96,7 @@ QJsonArray File::get_decoders() } } - zip_close(archive); + zip_close(archive); } return dec_array; diff --git a/DSView/pv/device/file.h b/DSView/pv/device/file.h index d4299e7b..569d2ef9 100755 --- a/DSView/pv/device/file.h +++ b/DSView/pv/device/file.h @@ -35,10 +35,13 @@ namespace device { class File : public DevInst { + protected: File(QString path); public: + ~File(); + static File* create(QString name); QJsonArray get_decoders(); @@ -46,7 +49,7 @@ public: QJsonDocument get_session(); public: - QString format_device_title() const; + QString format_device_title(); protected: const QString _path; diff --git a/DSView/pv/device/inputfile.cpp b/DSView/pv/device/inputfile.cpp index bd2feef7..83ed6995 100755 --- a/DSView/pv/device/inputfile.cpp +++ b/DSView/pv/device/inputfile.cpp @@ -37,7 +37,7 @@ InputFile::InputFile(QString path) : { } -sr_dev_inst* InputFile::dev_inst() const +sr_dev_inst* InputFile::dev_inst() { assert(_input); return _input->sdi; @@ -51,15 +51,7 @@ void InputFile::use(SigSession *owner) // only *.dsl file is valid // don't allow other types of file input throw tr("Not a valid DSView data file."); - return; - -// _input = load_input_file_format(_path, NULL); -// File::use(owner); - -// sr_session_new(); - -// if (sr_session_dev_add(_input->sdi) != SR_OK) -// throw tr("Failed to add session device."); + return; } void InputFile::release() diff --git a/DSView/pv/device/inputfile.h b/DSView/pv/device/inputfile.h index e1c1e179..c7e6a50d 100755 --- a/DSView/pv/device/inputfile.h +++ b/DSView/pv/device/inputfile.h @@ -37,7 +37,7 @@ class InputFile : public File public: InputFile(QString path); - sr_dev_inst* dev_inst() const; + sr_dev_inst* dev_inst(); virtual void use(SigSession *owner); diff --git a/DSView/pv/device/sessionfile.cpp b/DSView/pv/device/sessionfile.cpp index 2ce80e7e..3873fa22 100755 --- a/DSView/pv/device/sessionfile.cpp +++ b/DSView/pv/device/sessionfile.cpp @@ -25,12 +25,12 @@ namespace pv { namespace device { SessionFile::SessionFile(QString path) : - File(path), - _sdi(NULL) + File(path) { + _sdi = NULL; } -sr_dev_inst* SessionFile::dev_inst() const +sr_dev_inst* SessionFile::dev_inst() { return _sdi; } @@ -38,6 +38,9 @@ sr_dev_inst* SessionFile::dev_inst() const void SessionFile::use(SigSession *owner) { assert(!_sdi); + if (_sdi){ + //return; + } if (sr_session_load(_path.toUtf8().data()) != SR_OK) throw tr("Failed to open file.\n"); @@ -58,16 +61,15 @@ void SessionFile::use(SigSession *owner) } void SessionFile::release() -{ - if (!_owner) - return; - - assert(_sdi); - File::release(); - sr_dev_close(_sdi); - sr_dev_clear(_sdi->driver); - sr_session_destroy(); - _sdi = NULL; +{ + if (_owner != NULL && _sdi != NULL) + { + File::release(); + sr_dev_close(_sdi); + sr_dev_clear(_sdi->driver); + sr_session_destroy(); + _sdi = NULL; + } } } // device diff --git a/DSView/pv/device/sessionfile.h b/DSView/pv/device/sessionfile.h index 08783bdd..cf50ddaa 100755 --- a/DSView/pv/device/sessionfile.h +++ b/DSView/pv/device/sessionfile.h @@ -32,7 +32,7 @@ class SessionFile : public File public: SessionFile(QString path); - sr_dev_inst* dev_inst() const; + sr_dev_inst* dev_inst(); virtual void use(SigSession *owner); diff --git a/DSView/pv/devicemanager.cpp b/DSView/pv/devicemanager.cpp index d7778be5..f148ee11 100755 --- a/DSView/pv/devicemanager.cpp +++ b/DSView/pv/devicemanager.cpp @@ -29,15 +29,12 @@ #include #include #include - -#include + #include #include #include +#include "config/appconfig.h" -#include - -using boost::shared_ptr; using std::list; using std::map; using std::ostringstream; @@ -46,66 +43,72 @@ using std::string; namespace pv { -DeviceManager::DeviceManager(struct sr_context *sr_ctx) : - _sr_ctx(sr_ctx) +DeviceManager::DeviceManager() { - init_drivers(); - scan_all_drivers(); + _sr_ctx = NULL; +} + +DeviceManager::DeviceManager(DeviceManager &o) +{ + (void)o; } DeviceManager::~DeviceManager() { - release_devices(); + } -const std::list > &DeviceManager::devices() const +void DeviceManager::initAll(struct sr_context *sr_ctx) +{ + _sr_ctx = sr_ctx; + init_drivers(); + scan_all_drivers(); +} + + void DeviceManager::UnInitAll() + { + release_devices(); + } + +void DeviceManager::add_device(DevInst *device) { - return _devices; + assert(device); + + auto it = std::find(_devices.begin(), _devices.end(), device); + if (it ==_devices.end()){ + _devices.push_front(device); + } } -void DeviceManager::add_device(boost::shared_ptr device) +void DeviceManager::del_device(DevInst *device) { assert(device); - if (std::find(_devices.begin(), _devices.end(), device) == - _devices.end()) - _devices.push_front(device); -} - -void DeviceManager::del_device(boost::shared_ptr device) -{ - assert(device); - BOOST_FOREACH(shared_ptr dev, _devices) { - assert(dev); - if(dev == device) { - dev->release(); - break; - } + auto it = std::find(_devices.begin(), _devices.end(), device); + if (it !=_devices.end()){ + _devices.erase(it); //remove from list + device->destroy(); } - if (std::find(_devices.begin(), _devices.end(), device) != - _devices.end()) - _devices.remove(device); } -std::list > DeviceManager::driver_scan( - struct sr_dev_driver *const driver, GSList *const drvopts) -{ - list< shared_ptr > driver_devices; - +void DeviceManager::driver_scan( + std::list &driver_devices, + struct sr_dev_driver *const driver, + GSList *const drvopts) +{ assert(driver); // Remove any device instances from this driver from the device // list. They will not be valid after the scan. - list< shared_ptr >::iterator i = _devices.begin(); + auto i = _devices.begin(); while (i != _devices.end()) { - if ((*i)->dev_inst() && - (*i)->dev_inst()->driver == driver) { + if ((*i)->dev_inst() && (*i)->dev_inst()->driver == driver) { (*i)->release(); i = _devices.erase(i); } else { i++; } - } + } // Clear all the old device instances from this driver sr_dev_clear(driver); @@ -113,25 +116,23 @@ std::list > DeviceManager::driver_scan( // Check If DSL hardware driver if (strncmp(driver->name, "virtual", 7)) { - QDir dir(DS_RES_PATH); + QDir dir(GetResourceDir()); if (!dir.exists()) - return driver_devices; + return; } // Do the scan GSList *const devices = sr_driver_scan(driver, drvopts); - for (GSList *l = devices; l; l = l->next) - driver_devices.push_front(shared_ptr( - new device::Device((sr_dev_inst*)l->data))); + + for (GSList *l = devices; l; l = l->next){ + Device *dev = new device::Device((sr_dev_inst*)l->data); //create new device + driver_devices.push_front(dev); + } + g_slist_free(devices); - //driver_devices.sort(compare_devices); - // Add the scanned devices to the main list - _devices.insert(_devices.end(), driver_devices.begin(), - driver_devices.end()); - //_devices.sort(compare_devices); - - return driver_devices; + // append the scanned devices to the main list + _devices.insert(_devices.end(), driver_devices.begin(), driver_devices.end()); } void DeviceManager::init_drivers() @@ -150,8 +151,7 @@ void DeviceManager::init_drivers() void DeviceManager::release_devices() { // Release all the used devices - BOOST_FOREACH(shared_ptr dev, _devices) { - assert(dev); + for (DevInst *dev : _devices) { dev->release(); } @@ -165,14 +165,15 @@ void DeviceManager::scan_all_drivers() { // Scan all drivers for all devices. struct sr_dev_driver **const drivers = sr_driver_list(); - for (struct sr_dev_driver **driver = drivers; *driver; driver++) - driver_scan(*driver); + for (struct sr_dev_driver **driver = drivers; *driver; driver++){ + std::list driver_devices; + driver_scan(driver_devices, *driver); + } } void DeviceManager::release_driver(struct sr_dev_driver *const driver) { - BOOST_FOREACH(shared_ptr dev, _devices) { - assert(dev); + for (DevInst *dev : _devices) { if(dev->dev_inst()->driver == driver) dev->release(); } @@ -181,8 +182,7 @@ void DeviceManager::release_driver(struct sr_dev_driver *const driver) sr_dev_clear(driver); } -bool DeviceManager::compare_devices(boost::shared_ptr a, - boost::shared_ptr b) +bool DeviceManager::compare_devices(DevInst *a, DevInst *b) { assert(a); assert(b); diff --git a/DSView/pv/devicemanager.h b/DSView/pv/devicemanager.h index 426b9aa8..c8b85b63 100755 --- a/DSView/pv/devicemanager.h +++ b/DSView/pv/devicemanager.h @@ -29,20 +29,13 @@ #include #include #include - -#include -#include -#include - #include #include struct sr_context; struct sr_dev_driver; struct sr_dev_inst; -struct libusbhp_t; -struct libusbhp_device_t; - + namespace pv { class SigSession; @@ -51,21 +44,33 @@ namespace device { class DevInst; } +using namespace pv::device; + class DeviceManager { +private: + DeviceManager(DeviceManager &o); + public: - DeviceManager(struct sr_context *sr_ctx); + DeviceManager(); ~DeviceManager(); - const std::list< boost::shared_ptr >& devices() const; + inline const std::list& devices(){ + return _devices; + } - void add_device(boost::shared_ptr device); - void del_device(boost::shared_ptr device); + void add_device(DevInst *device); + void del_device(DevInst *device); - std::list< boost::shared_ptr > driver_scan( - struct sr_dev_driver *const driver, - GSList *const drvopts = NULL); + void driver_scan( + std::list &driver_devices, + struct sr_dev_driver *const driver=NULL, + GSList *const drvopts=NULL); + + void initAll(struct sr_context *sr_ctx); + + void UnInitAll(); private: void init_drivers(); @@ -76,12 +81,11 @@ private: void release_driver(struct sr_dev_driver *const driver); - static bool compare_devices(boost::shared_ptr a, - boost::shared_ptr b); + static bool compare_devices(DevInst *a, DevInst *b); private: - struct sr_context *const _sr_ctx; - std::list< boost::shared_ptr > _devices; + struct sr_context* _sr_ctx; + std::list _devices; }; } // namespace pv diff --git a/DSView/pv/dialogs/about.cpp b/DSView/pv/dialogs/about.cpp index ef9079b5..920dfeaa 100755 --- a/DSView/pv/dialogs/about.cpp +++ b/DSView/pv/dialogs/about.cpp @@ -21,6 +21,8 @@ */ +#include "about.h" + #include #include #include @@ -28,9 +30,9 @@ #include #include #include -#include - -#include "about.h" + +#include "../config/appconfig.h" +#include "../dsvdef.h" namespace pv { namespace dialogs { @@ -74,18 +76,18 @@ About::About(QWidget *parent) : .arg("http://sigrok.org/"); QString changlogs = tr("Changelogs
"); - #ifndef Q_OS_LINUX - QDir dir(QCoreApplication::applicationDirPath()); - #else - QDir dir(DS_RES_PATH); - dir.cdUp(); - #endif - QString filename = dir.absolutePath() + "/NEWS" + QString::number(qApp->property("Language").toInt()); + + QDir dir(GetAppDataDir()); + AppConfig &app = AppConfig::Instance(); + int lan = app._frameOptions.language; + + QString filename = dir.absolutePath() + "/NEWS" + QString::number(lan); QFile news(filename); if (news.open(QIODevice::ReadOnly)) { - QTextCodec *code=QTextCodec::codecForName("UTF-8"); + QTextStream stream(&news); - stream.setCodec(code); + app::set_utf8(stream); + QString line; while (!stream.atEnd()){ line = stream.readLine(); diff --git a/DSView/pv/dialogs/about.h b/DSView/pv/dialogs/about.h index a82377e7..a86ca127 100755 --- a/DSView/pv/dialogs/about.h +++ b/DSView/pv/dialogs/about.h @@ -27,8 +27,7 @@ #include #include "dsdialog.h" -#include - + namespace pv { namespace dialogs { diff --git a/DSView/pv/dialogs/applicationpardlg.cpp b/DSView/pv/dialogs/applicationpardlg.cpp new file mode 100644 index 00000000..ed4e99fc --- /dev/null +++ b/DSView/pv/dialogs/applicationpardlg.cpp @@ -0,0 +1,75 @@ +/* + * This file is part of the DSView project. + * DSView is based on PulseView. + * + * Copyright (C) 2015 DreamSourceLab + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "applicationpardlg.h" +#include "dsdialog.h" +#include +#include +#include +#include "../config/appconfig.h" + +namespace pv +{ +namespace dialogs +{ + +ApplicationParamDlg::ApplicationParamDlg() +{ + +} + +ApplicationParamDlg::~ApplicationParamDlg() +{ +} + +bool ApplicationParamDlg::ShowDlg(QWidget *parent) +{ + DSDialog dlg(parent, true, true); + dlg.setTitle("Application options"); + dlg.setMinimumSize(300, 200); + QFormLayout &lay = *(new QFormLayout()); + lay.setContentsMargins(0,20,0,30); + + //show config + AppConfig &app = AppConfig::Instance(); + + QCheckBox *ck_quickScroll = new QCheckBox(); + ck_quickScroll->setChecked(app._appOptions.quickScroll); + lay.addRow("Quick scroll", ck_quickScroll); + dlg.layout()->addLayout(&lay); + + dlg.exec(); + + bool ret = dlg.IsClickYes(); + + //save config + if (ret){ + app._appOptions.quickScroll = ck_quickScroll->isChecked(); + app.SaveApp(); + } + + return ret; +} + + +} // +}// + diff --git a/DSView/pv/dialogs/applicationpardlg.h b/DSView/pv/dialogs/applicationpardlg.h new file mode 100644 index 00000000..e890c985 --- /dev/null +++ b/DSView/pv/dialogs/applicationpardlg.h @@ -0,0 +1,50 @@ +/* + * This file is part of the DSView project. + * DSView is based on PulseView. + * + * Copyright (C) 2015 DreamSourceLab + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#pragma once + +#include +#include + +namespace pv +{ + namespace dialogs +{ + + class ApplicationParamDlg + { + // Q_OBJECT + + public: + ApplicationParamDlg(); + ~ApplicationParamDlg(); + + bool ShowDlg(QWidget *parent); + + //IDlgCallback + private: + void OnDlgResult(bool bYes); + + + }; + +}// +}// diff --git a/DSView/pv/dialogs/calibration.cpp b/DSView/pv/dialogs/calibration.cpp index 36298622..76648789 100755 --- a/DSView/pv/dialogs/calibration.cpp +++ b/DSView/pv/dialogs/calibration.cpp @@ -20,9 +20,7 @@ */ #include "calibration.h" - -#include - + #include #include #include @@ -31,8 +29,9 @@ #include "../view/trace.h" #include "../dialogs/dsmessagebox.h" +#include "../dsvdef.h" + -using namespace boost; using namespace std; namespace pv { @@ -44,7 +43,13 @@ const QString Calibration::VCOMB = QT_TR_NOOP(" VCOMB"); Calibration::Calibration(QWidget *parent) : DSDialog(parent) -{ +{ + _save_btn = NULL; + _abort_btn = NULL; + _reset_btn = NULL; + _exit_btn = NULL; + _flayout = NULL; + #ifdef Q_OS_DARWIN Qt::WindowFlags flags = windowFlags(); this->setWindowFlags(flags | Qt::Tool); @@ -89,6 +94,14 @@ Calibration::Calibration(QWidget *parent) : retranslateUi(); } +Calibration::~Calibration(){ + DESTROY_QT_OBJECT(_save_btn); + DESTROY_QT_OBJECT(_abort_btn); + DESTROY_QT_OBJECT(_reset_btn); + DESTROY_QT_OBJECT(_exit_btn); + DESTROY_QT_OBJECT(_flayout); +} + void Calibration::changeEvent(QEvent *event) { if (event->type() == QEvent::LanguageChange) @@ -106,7 +119,7 @@ void Calibration::retranslateUi() setTitle(tr("Manual Calibration")); } -void Calibration::set_device(boost::shared_ptr dev_inst) +void Calibration::set_device(DevInst *dev_inst) { assert(dev_inst); _dev_inst = dev_inst; diff --git a/DSView/pv/dialogs/calibration.h b/DSView/pv/dialogs/calibration.h index 97bf7ce2..6253de04 100755 --- a/DSView/pv/dialogs/calibration.h +++ b/DSView/pv/dialogs/calibration.h @@ -29,13 +29,14 @@ #include #include -#include -#include +#include -#include +#include "../device/devinst.h" #include "../toolbars/titlebar.h" #include "dsdialog.h" +using namespace pv::device; + namespace pv { namespace dialogs { @@ -50,8 +51,9 @@ private: public: Calibration(QWidget *parent); + ~Calibration(); - void set_device(boost::shared_ptr dev_inst); + void set_device(DevInst *dev_inst); protected: void accept(); void reject(); @@ -68,9 +70,8 @@ private slots: void reload_value(); private: - boost::shared_ptr _dev_inst; - - toolbars::TitleBar *_titlebar; + DevInst *_dev_inst; + QPushButton *_save_btn; QPushButton *_abort_btn; QPushButton *_reset_btn; diff --git a/DSView/pv/dialogs/deviceoptions.cpp b/DSView/pv/dialogs/deviceoptions.cpp index 8d5800dd..b0b6119e 100755 --- a/DSView/pv/dialogs/deviceoptions.cpp +++ b/DSView/pv/dialogs/deviceoptions.cpp @@ -21,29 +21,32 @@ */ #include "deviceoptions.h" - -#include - + #include #include #include #include "dsmessagebox.h" -#include +#include "../prop/property.h" +#include "../dsvdef.h" using namespace boost; using namespace std; - + namespace pv { namespace dialogs { -DeviceOptions::DeviceOptions(QWidget *parent, boost::shared_ptr dev_inst) : +DeviceOptions::DeviceOptions(QWidget *parent, DevInst *dev_inst) : DSDialog(parent), _dev_inst(dev_inst), - _button_box(QDialogButtonBox::Ok, - Qt::Horizontal, this), + _button_box(QDialogButtonBox::Ok, Qt::Horizontal, this), _device_options_binding(_dev_inst->dev_inst()) { + _dynamic_box = NULL; + _props_box = NULL; + _config_button = NULL; + _cali_button = NULL; + _props_box = new QGroupBox(tr("Mode"), this); _props_box->setLayout(get_property_form(_props_box)); _layout.addWidget(_props_box); @@ -52,7 +55,7 @@ DeviceOptions::DeviceOptions(QWidget *parent, boost::shared_ptrsetLayout(&_dynamic_layout); _layout.addWidget(_dynamic_box); - _dynamic_box->setVisible(_dynamic_box->title() != NULL); + _dynamic_box->setVisible(_dynamic_box->title() != ""); _layout.addStretch(1); _layout.addWidget(&_button_box); @@ -62,7 +65,7 @@ DeviceOptions::DeviceOptions(QWidget *parent, boost::shared_ptrget_config(NULL, NULL, SR_CONF_OPERATION_MODE); if (gvar != NULL) { @@ -74,15 +77,21 @@ DeviceOptions::DeviceOptions(QWidget *parent, boost::shared_ptr > &dev_props = - _device_options_binding.properties(); - BOOST_FOREACH(boost::shared_ptr p, dev_props) { + const auto &dev_props = _device_options_binding.properties(); + for(auto &p : dev_props) { assert(p); p->commit(); } @@ -106,9 +115,9 @@ void DeviceOptions::accept() if (hasEnabled) { QVector::iterator i = _probe_options_binding_list.begin(); while(i != _probe_options_binding_list.end()) { - const vector< boost::shared_ptr > &probe_props = - (*i)->properties(); - BOOST_FOREACH(boost::shared_ptr p, probe_props) { + const auto &probe_props = (*i)->properties(); + + for(auto &p :probe_props) { assert(p); p->commit(); } @@ -138,10 +147,10 @@ QGridLayout * DeviceOptions::get_property_form(QWidget * parent) QGridLayout *const layout = new QGridLayout(parent); layout->setVerticalSpacing(5); - const vector< boost::shared_ptr > &properties = - _device_options_binding.properties(); + const auto &properties =_device_options_binding.properties(); + int i = 0; - BOOST_FOREACH(boost::shared_ptr p, properties) + for(auto &p : properties) { assert(p); const QString label = p->labeled_widget() ? QString() : p->label(); @@ -337,7 +346,7 @@ void DeviceOptions::mode_check() if (mode != _mode) { dynamic_widget(_dynamic_layout); - _dynamic_box->setVisible(_dynamic_box->title() != NULL); + _dynamic_box->setVisible(_dynamic_box->title() != ""); _mode = mode; } } @@ -366,7 +375,7 @@ void DeviceOptions::channel_check() if(sc != NULL) _dev_inst->set_config(NULL, NULL, SR_CONF_CHANNEL_MODE, g_variant_new_string(text.toUtf8().data())); dynamic_widget(_dynamic_layout); - _dynamic_box->setVisible(_dynamic_box->title() != NULL); + _dynamic_box->setVisible(_dynamic_box->title() != ""); } void DeviceOptions::analog_channel_check() @@ -382,7 +391,7 @@ void DeviceOptions::analog_channel_check() } } dynamic_widget(_dynamic_layout); - _dynamic_box->setVisible(_dynamic_box->title() != NULL); + _dynamic_box->setVisible(_dynamic_box->title() != ""); } void DeviceOptions::channel_enable() @@ -512,10 +521,10 @@ void DeviceOptions::analog_probes(QGridLayout &layout) pv::prop::binding::ProbeOptions *probe_options_binding = new pv::prop::binding::ProbeOptions(_dev_inst->dev_inst(), probe); - const vector< boost::shared_ptr > &properties = - probe_options_binding->properties(); + const auto &properties = probe_options_binding->properties(); int i = 1; - BOOST_FOREACH(boost::shared_ptr p, properties) + + for(auto &p : properties) { assert(p); const QString label = p->labeled_widget() ? QString() : p->label(); diff --git a/DSView/pv/dialogs/deviceoptions.h b/DSView/pv/dialogs/deviceoptions.h index 0b9591f7..7c4d1cdd 100755 --- a/DSView/pv/dialogs/deviceoptions.h +++ b/DSView/pv/dialogs/deviceoptions.h @@ -34,11 +34,8 @@ #include #include #include -#include #include -#include - -#include +#include #include #include "../device/devinst.h" @@ -46,6 +43,9 @@ #include "../prop/binding/probeoptions.h" #include "../toolbars/titlebar.h" #include "../dialogs/dsdialog.h" +#include "../ui/dscombobox.h" + +using namespace pv::device; namespace pv { namespace dialogs { @@ -55,7 +55,9 @@ class DeviceOptions : public DSDialog Q_OBJECT public: - DeviceOptions(QWidget *parent, boost::shared_ptr dev_inst); + DeviceOptions(QWidget *parent, DevInst *dev_inst); + + ~DeviceOptions(); protected: void accept(); @@ -83,9 +85,8 @@ private slots: void channel_enable(); private: - boost::shared_ptr _dev_inst; - QVBoxLayout _layout; - toolbars::TitleBar *_titlebar; + DevInst *_dev_inst; + QVBoxLayout _layout; QGroupBox *_dynamic_box; QGridLayout _dynamic_layout; diff --git a/DSView/pv/dialogs/dsdialog.cpp b/DSView/pv/dialogs/dsdialog.cpp index 359a4971..37a0e7cd 100755 --- a/DSView/pv/dialogs/dsdialog.cpp +++ b/DSView/pv/dialogs/dsdialog.cpp @@ -28,118 +28,131 @@ #include #include #include +#include "../dsvdef.h" namespace pv { namespace dialogs { -DSDialog::DSDialog(QWidget *parent, bool hasClose) : - QDialog(parent), - _moving(false) +DSDialog::DSDialog() : DSDialog(NULL, false, false) { +} + +DSDialog::DSDialog(QWidget *parent): DSDialog(parent, false, false) +{ +} + +DSDialog::DSDialog(QWidget *parent, bool hasClose): DSDialog(parent, hasClose, false) +{ +} + +DSDialog::DSDialog(QWidget *parent, bool hasClose, bool bBaseButton) : + QDialog(NULL), //must be null, otherwise window can not able to move + m_bBaseButton(bBaseButton) +{ + (void)parent; + + _base_layout = NULL; + _main_layout = NULL; + _main_widget = NULL; + _titlebar = NULL; + _shadow = NULL; + _base_button = NULL; + + m_callback = NULL; + _clickYes = false; + setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint | Qt::WindowSystemMenuHint); setAttribute(Qt::WA_TranslucentBackground); - build_main(hasClose); + build_base(hasClose); +} - _layout = new QVBoxLayout(this); - _layout->addWidget(_main); - setLayout(_layout); +DSDialog::~DSDialog() +{ + DESTROY_QT_OBJECT(_base_layout); + DESTROY_QT_OBJECT(_main_layout); + DESTROY_QT_OBJECT(_main_widget); + DESTROY_QT_OBJECT(_titlebar); + DESTROY_QT_OBJECT(_shadow); + DESTROY_QT_OBJECT(_base_button); } void DSDialog::accept() -{ - using namespace Qt; +{ + _clickYes = true; + if (m_callback){ + m_callback->OnDlgResult(true); + } + QDialog::accept(); } void DSDialog::reject() -{ - using namespace Qt; +{ + _clickYes = false; + + if (m_callback){ + m_callback->OnDlgResult(false); + } QDialog::reject(); } - -bool DSDialog::eventFilter(QObject *object, QEvent *event) -{ - (void)object; - const QEvent::Type type = event->type(); - const QMouseEvent *const mouse_event = (QMouseEvent*)event; - if (type == QEvent::MouseMove) { - if (_moving && mouse_event->buttons().testFlag(Qt::LeftButton)) { - move(mouse_event->globalPos() - _startPos); - } - return true; - } else if (type == QEvent::MouseButtonPress) { - if (mouse_event->buttons().testFlag(Qt::LeftButton)) { - _moving = true; -#ifndef _WIN32 - _startPos = mouse_event->pos() + - QPoint(_layout->margin(), _layout->margin()) + - QPoint(_layout->spacing(), _layout->spacing()) + - QPoint(_mlayout->margin(), _mlayout->margin()) + - QPoint(_mlayout->spacing(), _mlayout->spacing()); -#else - _startPos = mouse_event->pos() + - QPoint(_layout->margin(), _layout->margin()) + - QPoint(_layout->spacing(), _layout->spacing()); -#endif - } - } else if (type == QEvent::MouseButtonRelease) { - if (mouse_event->buttons().testFlag(Qt::LeftButton)) { - _moving = false; - } - } - return false; -} - -QVBoxLayout* DSDialog::layout() -{ - return _mlayout; -} - -QWidget* DSDialog::mainWidget() -{ - return _main; -} - + void DSDialog::setTitle(QString title) { - _titlebar->setTitle(title); + if (_titlebar){ + _titlebar->setTitle(title); + } } -void DSDialog::reload(bool hasClose) +void DSDialog::reload() { - QString title; - if (_titlebar) - title = _titlebar->title(); - if (_main) - delete _main; - - build_main(hasClose); - _titlebar->setTitle(title); - _layout->addWidget(_main); + show(); } -void DSDialog::build_main(bool hasClose) -{ - _main = new QWidget(this); - _mlayout = new QVBoxLayout(_main); - _main->setLayout(_mlayout); - //_mlayout->setMargin(5); - //_mlayout->setSpacing(5); +int DSDialog::exec() +{ + //ok,cancel + if (m_bBaseButton){ + _base_button = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,Qt::Horizontal, this); + _main_layout->addWidget(_base_button);//, 5, 1, 1, 1, Qt::AlignHCenter | Qt::AlignBottom); + //_main_layout->addWidget(_base_button,0, Qt::AlignHCenter | Qt::AlignBottom); + connect(_base_button, SIGNAL(rejected()), this, SLOT(reject())); + connect(_base_button, SIGNAL(accepted()), this, SLOT(accept())); + } + + return QDialog::exec(); +} - Shadow *bodyShadow = new Shadow(_main); - bodyShadow->setBlurRadius(10.0); - bodyShadow->setDistance(3.0); - bodyShadow->setColor(QColor(0, 0, 0, 80)); - _main->setAutoFillBackground(true); - _main->setGraphicsEffect(bodyShadow); + +void DSDialog::build_base(bool hasClose) +{ + _main_widget = new QWidget(this); + _main_layout = new QVBoxLayout(_main_widget); + _main_widget->setLayout(_main_layout); + + _shadow = new Shadow(this); + _shadow->setBlurRadius(10.0); + _shadow->setDistance(3.0); + _shadow->setColor(QColor(0, 0, 0, 80)); + _main_widget->setAutoFillBackground(true); + this->setGraphicsEffect(_shadow); _titlebar = new toolbars::TitleBar(false, this, hasClose); - _titlebar->installEventFilter(this); - _mlayout->addWidget(_titlebar); -} + _main_layout->addWidget(_titlebar); + + QWidget *space = new QWidget(this); + space->setFixedHeight(15); + _main_layout->addWidget(space); + + _base_layout = new QVBoxLayout(this); + _base_layout->addWidget(_main_widget); + setLayout(_base_layout); + + _main_layout->setAlignment(Qt::AlignCenter | Qt::AlignTop); + _main_layout->setContentsMargins(10,5,10,10); +} } // namespace dialogs } // namespace pv diff --git a/DSView/pv/dialogs/dsdialog.h b/DSView/pv/dialogs/dsdialog.h index cefc614d..00f83ef7 100755 --- a/DSView/pv/dialogs/dsdialog.h +++ b/DSView/pv/dialogs/dsdialog.h @@ -26,40 +26,58 @@ #include #include #include +#include #include "../toolbars/titlebar.h" +#include "../interface/uicallback.h" +class QDialogButtonBox; + + namespace pv { namespace dialogs { + class Shadow; + +//DSView any dialog base class class DSDialog : public QDialog { Q_OBJECT public: - DSDialog(QWidget *parent = 0, bool hasClose = false); - QVBoxLayout *layout(); - QWidget *mainWidget(); + DSDialog(); + DSDialog(QWidget *parent); + DSDialog(QWidget *parent, bool hasClose); + DSDialog(QWidget *parent, bool hasClose, bool bBaseButton); + ~DSDialog(); + inline void SetCallback(IDlgCallback *callback){m_callback = callback;} + inline QVBoxLayout *layout(){return _main_layout;} void setTitle(QString title); - void reload(bool hasClose); + void reload(); + int exec(); + inline bool IsClickYes(){return _clickYes;} protected: void accept(); void reject(); - //void mousePressEvent(QMouseEvent *event); - //void mouseReleaseEvent(QMouseEvent *event); - bool eventFilter(QObject *object, QEvent *event); -private: - void build_main(bool hasClose); private: - QVBoxLayout *_layout; - QVBoxLayout *_mlayout; - QWidget *_main; - toolbars::TitleBar *_titlebar; - bool _moving; - QPoint _startPos; + void build_base(bool hasClose); + +private: + QVBoxLayout *_base_layout; + QWidget *_main_widget; + QVBoxLayout *_main_layout; + toolbars::TitleBar *_titlebar; + Shadow *_shadow; + QDialogButtonBox *_base_button; + + QPoint _startPos; + bool m_bBaseButton; + bool _clickYes; + + IDlgCallback *m_callback; }; } // namespace dialogs diff --git a/DSView/pv/dialogs/dsmessagebox.cpp b/DSView/pv/dialogs/dsmessagebox.cpp index 70445d7e..1d6fb9ef 100755 --- a/DSView/pv/dialogs/dsmessagebox.cpp +++ b/DSView/pv/dialogs/dsmessagebox.cpp @@ -28,45 +28,72 @@ #include #include #include +#include "../dsvdef.h" namespace pv { namespace dialogs { -DSMessageBox::DSMessageBox(QWidget *parent) : - QDialog(parent), - _moving(false) +DSMessageBox::DSMessageBox(QWidget *parent,const char *title) : + QDialog(NULL) //must be null, otherwise window can not able to move { + (void)parent; + _layout = NULL; + _main_widget = NULL; + _msg = NULL; + _titlebar = NULL; + _shadow = NULL; + _main_layout = NULL; + + _bClickYes = false; + setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint | Qt::WindowSystemMenuHint); setAttribute(Qt::WA_TranslucentBackground); - _main = new QWidget(this); - QVBoxLayout *mlayout = new QVBoxLayout(_main); - _main->setLayout(mlayout); - Shadow *bodyShadow = new Shadow(); - bodyShadow->setBlurRadius(10.0); - bodyShadow->setDistance(3.0); - bodyShadow->setColor(QColor(0, 0, 0, 80)); - _main->setAutoFillBackground(true); - _main->setGraphicsEffect(bodyShadow); + _main_widget = new QWidget(this); + _main_layout = new QVBoxLayout(_main_widget); + _main_widget->setLayout(_main_layout); + _shadow = new Shadow(this); _msg = new QMessageBox(this); - _msg->setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint | Qt::WindowSystemMenuHint); - _titlebar = new toolbars::TitleBar(false, this); - _titlebar->setTitle(tr("Message")); - _titlebar->installEventFilter(this); - - mlayout->addWidget(_titlebar); - mlayout->addWidget(_msg); - _layout = new QVBoxLayout(this); - _layout->addWidget(_main); - setLayout(_layout); + + _shadow->setBlurRadius(10.0); + _shadow->setDistance(3.0); + _shadow->setColor(QColor(0, 0, 0, 80)); + + _main_widget->setAutoFillBackground(true); + this->setGraphicsEffect(_shadow); + + _msg->setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint | Qt::WindowSystemMenuHint); + + if (title){ + _titlebar->setTitle(QString(title)); + } + else{ + _titlebar->setTitle(tr("Message")); + } + + _main_layout->addWidget(_titlebar); + _main_layout->addWidget(_msg); + _layout->addWidget(_main_widget); + + setLayout(_layout); - //connect(_msg, SIGNAL(finished(int)), this, SLOT(accept())); connect(_msg, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(on_button(QAbstractButton*))); } + +DSMessageBox::~DSMessageBox() +{ + DESTROY_QT_OBJECT(_layout); + DESTROY_QT_OBJECT(_main_widget); + DESTROY_QT_OBJECT(_msg); + DESTROY_QT_OBJECT(_titlebar); + DESTROY_QT_OBJECT(_shadow); + DESTROY_QT_OBJECT(_main_layout); +} + void DSMessageBox::accept() { using namespace Qt; @@ -80,48 +107,20 @@ void DSMessageBox::reject() QDialog::reject(); } - -bool DSMessageBox::eventFilter(QObject *object, QEvent *event) -{ - (void)object; - const QEvent::Type type = event->type(); - const QMouseEvent *const mouse_event = (QMouseEvent*)event; - if (type == QEvent::MouseMove) { - if (_moving && mouse_event->buttons().testFlag(Qt::LeftButton)) { - move(mouse_event->globalPos() - _startPos); - } - return true; - } else if (type == QEvent::MouseButtonPress) { - if (mouse_event->buttons().testFlag(Qt::LeftButton)) { - _moving = true; - _startPos = mouse_event->pos() + - QPoint(_layout->margin(), _layout->margin()) + - QPoint(_layout->spacing(), _layout->spacing()); - } - } else if (type == QEvent::MouseButtonRelease) { - if (mouse_event->buttons().testFlag(Qt::LeftButton)) { - _moving = false; - } - } - return false; -} - + QMessageBox* DSMessageBox::mBox() { return _msg; } - -int DSMessageBox::exec() -{ - //_msg->show(); - return QDialog::exec(); -} - + void DSMessageBox::on_button(QAbstractButton *btn) { QMessageBox::ButtonRole role = _msg->buttonRole(btn); - if (role == QMessageBox::AcceptRole) - accept(); + + if (role == QMessageBox::AcceptRole || role == QMessageBox::YesRole){ + _bClickYes = true; + accept(); + } else reject(); } diff --git a/DSView/pv/dialogs/dsmessagebox.h b/DSView/pv/dialogs/dsmessagebox.h index 5fc2ea30..7b2a1038 100755 --- a/DSView/pv/dialogs/dsmessagebox.h +++ b/DSView/pv/dialogs/dsmessagebox.h @@ -33,33 +33,38 @@ namespace pv { namespace dialogs { + class Shadow; + class DSMessageBox : public QDialog { Q_OBJECT public: - DSMessageBox(QWidget *parent); - QMessageBox *mBox(); + DSMessageBox(QWidget *parent, const char *title=0); - int exec(); + ~DSMessageBox(); + + QMessageBox *mBox(); + + inline int IsYes(){return _bClickYes;} protected: void accept(); - void reject(); - //void mousePressEvent(QMouseEvent *event); - //void mouseReleaseEvent(QMouseEvent *event); - bool eventFilter(QObject *object, QEvent *event); + void reject(); private slots: void on_button(QAbstractButton* btn); private: - QVBoxLayout *_layout; - QWidget *_main; - QMessageBox *_msg; - toolbars::TitleBar *_titlebar; - bool _moving; - QPoint _startPos; + QVBoxLayout *_layout; + QVBoxLayout *_main_layout; + QWidget *_main_widget; + QMessageBox *_msg; + toolbars::TitleBar *_titlebar; + Shadow *_shadow; + + QPoint _startPos; + bool _bClickYes; }; } // namespace dialogs diff --git a/DSView/pv/dialogs/dsomeasure.cpp b/DSView/pv/dialogs/dsomeasure.cpp index d1acaa19..7e9825ef 100755 --- a/DSView/pv/dialogs/dsomeasure.cpp +++ b/DSView/pv/dialogs/dsomeasure.cpp @@ -29,8 +29,8 @@ #include #include #include - -#include + +#include "../dsvdef.h" using namespace boost; using namespace std; @@ -39,7 +39,7 @@ using namespace pv::view; namespace pv { namespace dialogs { -DsoMeasure::DsoMeasure(SigSession &session, View &parent, +DsoMeasure::DsoMeasure(SigSession *session, View &parent, unsigned int position, int last_sig_index) : DSDialog((QWidget *)&parent), _session(session), @@ -48,15 +48,17 @@ DsoMeasure::DsoMeasure(SigSession &session, View &parent, _button_box(QDialogButtonBox::Reset | QDialogButtonBox::Cancel, Qt::Horizontal, this) { + _measure_tab = NULL; + setMinimumSize(500, 400); _measure_tab = new QTabWidget(this); _measure_tab->setTabPosition(QTabWidget::West); _measure_tab->setUsesScrollButtons(false); - BOOST_FOREACH(const boost::shared_ptr s, _session.get_signals()) { - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s)) && dsoSig->enabled()) { + for(auto &s : _session->get_signals()) { + view::DsoSignal *dsoSig; + if ((dsoSig = dynamic_cast(s)) && dsoSig->enabled()) { QWidget *measure_widget = new QWidget(this); this->add_measure(measure_widget, dsoSig); _measure_tab->addTab(measure_widget, QString::number(dsoSig->get_index())); @@ -76,23 +78,29 @@ DsoMeasure::DsoMeasure(SigSession &session, View &parent, connect(_button_box.button(QDialogButtonBox::Cancel), SIGNAL(clicked()), this, SLOT(reject())); connect(_button_box.button(QDialogButtonBox::Reset), SIGNAL(clicked()), this, SLOT(reset())); - connect(_session.get_device().get(), SIGNAL(device_updated()), this, SLOT(reject())); + connect(_session->get_device(), SIGNAL(device_updated()), this, SLOT(reject())); } -void DsoMeasure::add_measure(QWidget *widget, const boost::shared_ptr dsoSig) +DsoMeasure::~DsoMeasure(){ + DESTROY_QT_OBJECT(_measure_tab); +} + +void DsoMeasure::add_measure(QWidget *widget, const view::DsoSignal *dsoSig) { const int Column = 5; const int IconSizeForText = 5; QGridLayout *layout = new QGridLayout(widget); - layout->setMargin(0); layout->setSpacing(0); + + pv::view::DsoSignal *psig = const_cast(dsoSig); + for (int i=DSO_MS_BEGIN+1; isetProperty("id", QVariant(i)); button->setIconSize(QSize(48, 48)); QPixmap msPix(get_ms_icon(i)); QBitmap msMask = msPix.createMaskFromColor(QColor("black"), Qt::MaskOutColor); - msPix.fill(dsoSig->get_colour()); + msPix.fill(psig->get_colour()); msPix.setMask(msMask); button->setIcon(QIcon(msPix)); layout->addWidget(button, @@ -150,9 +158,10 @@ void DsoMeasure::accept() if(sc != NULL) { QVariant id = sc->property("id"); enum DSO_MEASURE_TYPE ms_type = DSO_MEASURE_TYPE(id.toInt()); - BOOST_FOREACH(const boost::shared_ptr s, _session.get_signals()) { - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s))) { + + for(auto &s : _session->get_signals()) { + view::DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(s))) { if (_measure_tab->currentWidget()->property("index").toInt() == dsoSig->get_index()) { _view.get_viewstatus()->set_measure(_position, false, dsoSig->get_index(), ms_type); break; diff --git a/DSView/pv/dialogs/dsomeasure.h b/DSView/pv/dialogs/dsomeasure.h index ab9c25ea..ca541ef1 100755 --- a/DSView/pv/dialogs/dsomeasure.h +++ b/DSView/pv/dialogs/dsomeasure.h @@ -27,8 +27,7 @@ #include #include #include - -#include + #include "../view/dsosignal.h" #include "../toolbars/titlebar.h" @@ -49,14 +48,15 @@ class DsoMeasure : public DSDialog Q_OBJECT public: - DsoMeasure(SigSession &session, view::View &parent, - unsigned int position, int last_sig_index); + DsoMeasure(SigSession *session, view::View &parent, unsigned int position, int last_sig_index); + + ~DsoMeasure(); static QString get_ms_icon(int ms_type); static QString get_ms_text(int ms_type); private: - void add_measure(QWidget *widget, const boost::shared_ptr dsoSig); + void add_measure(QWidget *widget, const view::DsoSignal *dsoSig); private slots: void set_measure(bool en); @@ -67,15 +67,13 @@ protected: void reject(); private: - SigSession &_session; + SigSession *_session; view::View &_view; unsigned int _position; - - toolbars::TitleBar *_titlebar; + QDialogButtonBox _button_box; QTabWidget *_measure_tab; - QVBoxLayout _layout; - std::vector _mbtn_vec; + QVBoxLayout _layout; }; } // namespace dialogs diff --git a/DSView/pv/dialogs/fftoptions.cpp b/DSView/pv/dialogs/fftoptions.cpp index 3436ff7f..10855971 100755 --- a/DSView/pv/dialogs/fftoptions.cpp +++ b/DSView/pv/dialogs/fftoptions.cpp @@ -21,50 +21,64 @@ #include "fftoptions.h" -#include - + #include #include +#include #include "../sigsession.h" #include "../data/spectrumstack.h" #include "../view/trace.h" #include "../view/dsosignal.h" #include "../view/spectrumtrace.h" +#include "../dsvdef.h" + using namespace boost; using namespace std; - + namespace pv { namespace dialogs { -FftOptions::FftOptions(QWidget *parent, SigSession &session) : +FftOptions::FftOptions(QWidget *parent, SigSession *session) : DSDialog(parent), _session(session), _button_box(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this) { + _len_combobox = NULL; + _interval_combobox = NULL; + _en_checkbox = NULL; + _ch_combobox = NULL; + _window_combobox = NULL; + _dc_checkbox = NULL; + _view_combobox = NULL; + _dbv_combobox = NULL; + _hint_label = NULL; + _glayout = NULL; + _layout = NULL; + _en_checkbox = new QCheckBox(this); - _len_combobox = new QComboBox(this); - _interval_combobox = new QComboBox(this); - _ch_combobox = new QComboBox(this); - _window_combobox = new QComboBox(this); + _len_combobox = new DsComboBox(this); + _interval_combobox = new DsComboBox(this); + _ch_combobox = new DsComboBox(this); + _window_combobox = new DsComboBox(this); _dc_checkbox = new QCheckBox(this); _dc_checkbox->setChecked(true); - _view_combobox = new QComboBox(this); - _dbv_combobox = new QComboBox(this); - + _view_combobox = new DsComboBox(this); + _dbv_combobox = new DsComboBox(this); + // setup _ch_combobox - BOOST_FOREACH(const boost::shared_ptr s, _session.get_signals()) { - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s))) { + for(auto &s : _session->get_signals()) { + view::DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(s))) { _ch_combobox->addItem(dsoSig->get_name(), QVariant::fromValue(dsoSig->get_index())); } } // setup _window_combobox _len_combobox _sample_limit = 0; - GVariant* gvar = _session.get_device()->get_config(NULL, NULL, SR_CONF_MAX_DSO_SAMPLELIMITS); + GVariant* gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_MAX_DSO_SAMPLELIMITS); if (gvar != NULL) { _sample_limit = g_variant_get_uint64(gvar) * 0.5; g_variant_unref(gvar); @@ -75,9 +89,10 @@ FftOptions::FftOptions(QWidget *parent, SigSession &session) : std::vector length; std::vector view_modes; std::vector dbv_ranges; - BOOST_FOREACH(const boost::shared_ptr t, _session.get_spectrum_traces()) { - boost::shared_ptr spectrumTraces; - if ((spectrumTraces = dynamic_pointer_cast(t))) { + + for(auto &t : _session->get_spectrum_traces()) { + view::SpectrumTrace *spectrumTraces = NULL; + if ((spectrumTraces = dynamic_cast(t))) { windows = spectrumTraces->get_spectrum_stack()->get_windows_support(); length = spectrumTraces->get_spectrum_stack()->get_length_support(); view_modes = spectrumTraces->get_view_modes_support(); @@ -125,9 +140,9 @@ FftOptions::FftOptions(QWidget *parent, SigSession &session) : } // load current settings - BOOST_FOREACH(const boost::shared_ptr t, _session.get_spectrum_traces()) { - boost::shared_ptr spectrumTraces; - if ((spectrumTraces = dynamic_pointer_cast(t))) { + for(auto &t : _session->get_spectrum_traces()) { + view::SpectrumTrace *spectrumTraces = NULL; + if ((spectrumTraces = dynamic_cast(t))) { if (spectrumTraces->enabled()) { _en_checkbox->setChecked(true); for (int i = 0; i < _ch_combobox->count(); i++) { @@ -173,7 +188,7 @@ FftOptions::FftOptions(QWidget *parent, SigSession &session) : QPixmap pixmap(hint_pic); _hint_label->setPixmap(pixmap); - _glayout = new QGridLayout(); + _glayout = new QGridLayout(); //QGridLayout _glayout->setVerticalSpacing(5); _glayout->addWidget(new QLabel(tr("FFT Enable: "), this), 0, 0); _glayout->addWidget(_en_checkbox, 0, 1); @@ -203,9 +218,13 @@ FftOptions::FftOptions(QWidget *parent, SigSession &session) : connect(&_button_box, SIGNAL(accepted()), this, SLOT(accept())); connect(&_button_box, SIGNAL(rejected()), this, SLOT(reject())); - connect(_window_combobox, SIGNAL(currentIndexChanged(QString)), this, SLOT(window_changed(QString))); + connect(_window_combobox, SIGNAL(currentIndexChanged(int)), this, SLOT(window_changed(int))); connect(_len_combobox, SIGNAL(currentIndexChanged(int)), this, SLOT(len_changed(int))); - connect(_session.get_device().get(), SIGNAL(device_updated()), this, SLOT(reject())); + connect(_session->get_device(), SIGNAL(device_updated()), this, SLOT(reject())); +} + +FftOptions::~FftOptions(){ + } void FftOptions::accept() @@ -214,9 +233,9 @@ void FftOptions::accept() QDialog::accept(); - BOOST_FOREACH(const boost::shared_ptr t, _session.get_spectrum_traces()) { - boost::shared_ptr spectrumTraces; - if ((spectrumTraces = dynamic_pointer_cast(t))) { + for(auto &t : _session->get_spectrum_traces()) { + view::SpectrumTrace *spectrumTraces = NULL; + if ((spectrumTraces = dynamic_cast(t))) { spectrumTraces->set_enable(false); if (spectrumTraces->get_index() == _ch_combobox->currentData().toInt()) { spectrumTraces->get_spectrum_stack()->set_dc_ignore(_dc_checkbox->isChecked()); @@ -227,13 +246,13 @@ void FftOptions::accept() //spectrumTraces->init_zoom(); spectrumTraces->set_dbv_range(_dbv_combobox->currentData().toInt()); spectrumTraces->set_enable(_en_checkbox->isChecked()); - if (_session.get_capture_state() == SigSession::Stopped && + if (_session->get_capture_state() == SigSession::Stopped && spectrumTraces->enabled()) spectrumTraces->get_spectrum_stack()->calc_fft(); } } } - _session.spectrum_rebuild(); + _session->spectrum_rebuild(); } void FftOptions::reject() @@ -243,8 +262,9 @@ void FftOptions::reject() QDialog::reject(); } -void FftOptions::window_changed(QString str) +void FftOptions::window_changed(int index) { + QString str = _window_combobox->itemText(index); QString hint_pic= ":/icons/" + str +".png"; QPixmap pixmap(hint_pic); _hint_label->setPixmap(pixmap); diff --git a/DSView/pv/dialogs/fftoptions.h b/DSView/pv/dialogs/fftoptions.h index b16dfe60..631713bf 100755 --- a/DSView/pv/dialogs/fftoptions.h +++ b/DSView/pv/dialogs/fftoptions.h @@ -27,14 +27,13 @@ #include #include #include -#include -#include - -#include +#include + #include "../device/devinst.h" #include "../toolbars/titlebar.h" #include "dsdialog.h" +#include "../ui/dscombobox.h" namespace pv { @@ -50,29 +49,30 @@ private: public: - FftOptions(QWidget *parent, SigSession &session); + FftOptions(QWidget *parent, SigSession *session); + + ~FftOptions(); protected: void accept(); void reject(); private slots: - void window_changed(QString str); + void window_changed(int index); void len_changed(int index); private: - SigSession &_session; + SigSession *_session; uint64_t _sample_limit; - - toolbars::TitleBar *_titlebar; - QComboBox *_len_combobox; - QComboBox *_interval_combobox; + + DsComboBox *_len_combobox; + DsComboBox *_interval_combobox; QCheckBox *_en_checkbox; - QComboBox *_ch_combobox; - QComboBox *_window_combobox; + DsComboBox *_ch_combobox; + DsComboBox *_window_combobox; QCheckBox *_dc_checkbox; - QComboBox *_view_combobox; - QComboBox *_dbv_combobox; + DsComboBox *_view_combobox; + DsComboBox *_dbv_combobox; QLabel *_hint_label; QGridLayout *_glayout; diff --git a/DSView/pv/dialogs/interval.cpp b/DSView/pv/dialogs/interval.cpp index e2ff752b..dcb13ca5 100755 --- a/DSView/pv/dialogs/interval.cpp +++ b/DSView/pv/dialogs/interval.cpp @@ -26,12 +26,17 @@ namespace pv { namespace dialogs { -Interval::Interval(SigSession &session, QWidget *parent) : +Interval::Interval(SigSession *session, QWidget *parent) : DSDialog(parent), _session(session), _button_box(QDialogButtonBox::Ok, Qt::Horizontal, this) { + _interval_label = NULL; + _interval_spinBox = NULL; + _interval_slider = NULL; + + setMinimumWidth(300); _interval_label = new QLabel(tr("Interval(s): "), this); _interval_spinBox = new QSpinBox(this); @@ -42,7 +47,7 @@ Interval::Interval(SigSession &session, QWidget *parent) : connect(_interval_slider, SIGNAL(valueChanged(int)), _interval_spinBox, SLOT(setValue(int))); connect(_interval_spinBox, SIGNAL(valueChanged(int)), _interval_slider, SLOT(setValue(int))); - _interval_slider->setValue(_session.get_repeat_intvl()); + _interval_slider->setValue(_session->get_repeat_intvl()); QGridLayout *glayout = new QGridLayout(this); glayout->addWidget(_interval_label, 0, 0); @@ -59,7 +64,7 @@ Interval::Interval(SigSession &session, QWidget *parent) : void Interval::accept() { using namespace Qt; - _session.set_repeat_intvl(_interval_slider->value()); + _session->set_repeat_intvl(_interval_slider->value()); QDialog::accept(); } diff --git a/DSView/pv/dialogs/interval.h b/DSView/pv/dialogs/interval.h index 86e42ade..9e3c0c40 100755 --- a/DSView/pv/dialogs/interval.h +++ b/DSView/pv/dialogs/interval.h @@ -40,14 +40,14 @@ class Interval : public DSDialog Q_OBJECT public: - Interval(SigSession &session, QWidget *parent); + Interval(SigSession *session, QWidget *parent); protected: void accept(); void reject(); private: - SigSession &_session; + SigSession *_session; QLabel *_interval_label; QSpinBox *_interval_spinBox; diff --git a/DSView/pv/dialogs/lissajousoptions.cpp b/DSView/pv/dialogs/lissajousoptions.cpp index 5f502f81..2ae27886 100755 --- a/DSView/pv/dialogs/lissajousoptions.cpp +++ b/DSView/pv/dialogs/lissajousoptions.cpp @@ -30,9 +30,9 @@ #include #include #include +#include -#include - + using namespace boost; using namespace std; using namespace pv::view; @@ -40,12 +40,18 @@ using namespace pv::view; namespace pv { namespace dialogs { -LissajousOptions::LissajousOptions(SigSession &session, QWidget *parent) : +LissajousOptions::LissajousOptions(SigSession *session, QWidget *parent) : DSDialog(parent), _session(session), _button_box(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this) { + _enable = NULL; + _x_group = NULL; + _y_group = NULL; + _percent = NULL; + _layout = NULL; + setMinimumSize(300, 300); _enable = new QCheckBox(this); @@ -56,8 +62,8 @@ LissajousOptions::LissajousOptions(SigSession &session, QWidget *parent) : _percent = new QSlider(Qt::Horizontal, this); _percent->setRange(100, 100); _percent->setEnabled(false); - if (_session.cur_samplelimits() > WellLen) { - int min = ceil(WellLen*100.0/_session.cur_samplelimits()); + if (_session->cur_samplelimits() > WellLen) { + int min = ceil(WellLen*100.0/_session->cur_samplelimits()); _percent->setEnabled(true); _percent->setRange(min, 100); _percent->setValue(min); @@ -67,9 +73,10 @@ LissajousOptions::LissajousOptions(SigSession &session, QWidget *parent) : _y_group = new QGroupBox(this); QHBoxLayout *xlayout = new QHBoxLayout(); QHBoxLayout *ylayout = new QHBoxLayout(); - BOOST_FOREACH(const boost::shared_ptr s, _session.get_signals()) { - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s))) { + + for(auto &s : _session->get_signals()) { + view::DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(s))) { QString index_str = QString::number(dsoSig->get_index()); QRadioButton *xradio = new QRadioButton(index_str, _x_group); xradio->setProperty("index", dsoSig->get_index()); @@ -85,7 +92,7 @@ LissajousOptions::LissajousOptions(SigSession &session, QWidget *parent) : _y_group->setLayout(ylayout); - boost::shared_ptr lissajous = _session.get_lissajous_trace(); + auto lissajous = _session->get_lissajous_trace(); if (lissajous) { _enable->setChecked(lissajous->enabled()); _percent->setValue(lissajous->percent()); @@ -118,7 +125,6 @@ LissajousOptions::LissajousOptions(SigSession &session, QWidget *parent) : } _layout = new QGridLayout(); - _layout->setMargin(0); _layout->setSpacing(0); _layout->addWidget(lisa_label, 0, 0, 1, 2, Qt::AlignCenter); _layout->addWidget(_enable, 1, 0, 1, 1); @@ -173,15 +179,15 @@ void LissajousOptions::accept() } } bool enable = (xindex != -1 && yindex != -1 && _enable->isChecked()); - _session.lissajous_rebuild(enable, xindex, yindex, _percent->value()); + _session->lissajous_rebuild(enable, xindex, yindex, _percent->value()); - BOOST_FOREACH(const boost::shared_ptr s, _session.get_signals()) { - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s))) { + for(auto &s : _session->get_signals()) { + view::DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(s))) { dsoSig->set_show(!enable); } } - boost::shared_ptr mathTrace = _session.get_math_trace(); + auto mathTrace = _session->get_math_trace(); if (mathTrace && mathTrace->enabled()) { mathTrace->set_show(!enable); } diff --git a/DSView/pv/dialogs/lissajousoptions.h b/DSView/pv/dialogs/lissajousoptions.h index b3fd13f1..edb6ce68 100755 --- a/DSView/pv/dialogs/lissajousoptions.h +++ b/DSView/pv/dialogs/lissajousoptions.h @@ -31,8 +31,7 @@ #include #include #include - -#include + #include "../view/dsosignal.h" #include "../toolbars/titlebar.h" @@ -56,7 +55,7 @@ private: static const int WellLen = SR_Kn(16); public: - LissajousOptions(SigSession &session, QWidget *parent); + LissajousOptions(SigSession *session, QWidget *parent); private: void changeEvent(QEvent *event); @@ -67,16 +66,17 @@ protected: void reject(); private: - SigSession &_session; + SigSession *_session; QCheckBox *_enable; QGroupBox *_x_group; QGroupBox *_y_group; QSlider *_percent; + QGridLayout *_layout; + QVector _x_radio; QVector _y_radio; - QDialogButtonBox _button_box; - QGridLayout *_layout; + QDialogButtonBox _button_box; }; } // namespace dialogs diff --git a/DSView/pv/dialogs/mathoptions.cpp b/DSView/pv/dialogs/mathoptions.cpp index 99169c7a..afc2e9f9 100755 --- a/DSView/pv/dialogs/mathoptions.cpp +++ b/DSView/pv/dialogs/mathoptions.cpp @@ -31,8 +31,7 @@ #include #include #include - -#include + using namespace boost; using namespace std; @@ -41,7 +40,7 @@ using namespace pv::view; namespace pv { namespace dialogs { -MathOptions::MathOptions(SigSession &session, QWidget *parent) : +MathOptions::MathOptions(SigSession *session, QWidget *parent) : DSDialog(parent), _session(session), _button_box(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, @@ -78,9 +77,10 @@ MathOptions::MathOptions(SigSession &session, QWidget *parent) : _src2_group = new QGroupBox(this); QHBoxLayout *src1_layout = new QHBoxLayout(); QHBoxLayout *src2_layout = new QHBoxLayout(); - BOOST_FOREACH(const boost::shared_ptr s, _session.get_signals()) { - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s))) { + + for(auto &s : _session->get_signals()) { + view::DsoSignal *dsoSig = NULL;; + if ((dsoSig = dynamic_cast(s))) { QString index_str = QString::number(dsoSig->get_index()); QRadioButton *xradio = new QRadioButton(index_str, _src1_group); xradio->setProperty("index", dsoSig->get_index()); @@ -96,7 +96,7 @@ MathOptions::MathOptions(SigSession &session, QWidget *parent) : _src2_group->setLayout(src2_layout); - boost::shared_ptr math = _session.get_math_trace(); + auto math = _session->get_math_trace(); if (math) { _enable->setChecked(math->enabled()); for (QVector::const_iterator i = _src1_radio.begin(); @@ -139,8 +139,7 @@ MathOptions::MathOptions(SigSession &session, QWidget *parent) : } } - _layout = new QGridLayout(); - _layout->setMargin(0); + _layout = new QGridLayout(); _layout->setSpacing(0); _layout->addWidget(lisa_label, 0, 0, 1, 2, Qt::AlignCenter); _layout->addWidget(_enable, 1, 0, 1, 1); @@ -204,18 +203,19 @@ void MathOptions::accept() } } bool enable = (src1 != -1 && src2 != -1 && _enable->isChecked()); - boost::shared_ptr dsoSig1; - boost::shared_ptr dsoSig2; - BOOST_FOREACH(const boost::shared_ptr s, _session.get_signals()) { - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s))) { + view::DsoSignal *dsoSig1 = NULL; + view::DsoSignal *dsoSig2 = NULL; + + for(auto &s : _session->get_signals()) { + view::DsoSignal *dsoSig = NULL;; + if ((dsoSig = dynamic_cast(s))) { if (dsoSig->get_index() == src1) dsoSig1 = dsoSig; if (dsoSig->get_index() == src2) dsoSig2 = dsoSig; } } - _session.math_rebuild(enable, dsoSig1, dsoSig2, type); + _session->math_rebuild(enable, dsoSig1, dsoSig2, type); } void MathOptions::reject() diff --git a/DSView/pv/dialogs/mathoptions.h b/DSView/pv/dialogs/mathoptions.h index d11afa36..ed6aa2fb 100755 --- a/DSView/pv/dialogs/mathoptions.h +++ b/DSView/pv/dialogs/mathoptions.h @@ -31,8 +31,7 @@ #include #include #include - -#include + #include "../view/dsosignal.h" #include "../toolbars/titlebar.h" @@ -56,7 +55,7 @@ private: static const int WellLen = SR_Kn(16); public: - MathOptions(SigSession &session, QWidget *parent); + MathOptions(SigSession *session, QWidget *parent); private: void changeEvent(QEvent *event); @@ -67,7 +66,7 @@ protected: void reject(); private: - SigSession &_session; + SigSession *_session; QCheckBox *_enable; QGroupBox *_src1_group; diff --git a/DSView/pv/dialogs/protocolexp.cpp b/DSView/pv/dialogs/protocolexp.cpp index 4d93b9f8..728410e5 100755 --- a/DSView/pv/dialogs/protocolexp.cpp +++ b/DSView/pv/dialogs/protocolexp.cpp @@ -20,10 +20,7 @@ */ #include "protocolexp.h" - -#include - -#include + #include #include #include @@ -39,6 +36,8 @@ #include "../data/decode/annotation.h" #include "../view/decodetrace.h" #include "../data/decodermodel.h" +#include "../config/appconfig.h" +#include "../dsvdef.h" using namespace boost; using namespace std; @@ -46,14 +45,14 @@ using namespace std; namespace pv { namespace dialogs { -ProtocolExp::ProtocolExp(QWidget *parent, SigSession &session) : +ProtocolExp::ProtocolExp(QWidget *parent, SigSession *session) : DSDialog(parent), _session(session), _button_box(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this), _export_cancel(false) { - _format_combobox = new QComboBox(this); + _format_combobox = new DsComboBox(this); _format_combobox->addItem(tr("Comma-Separated Values (*.csv)")); _format_combobox->addItem(tr("Text files (*.txt)")); @@ -64,13 +63,14 @@ ProtocolExp::ProtocolExp(QWidget *parent, SigSession &session) : _flayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); _flayout->addRow(new QLabel(tr("Export Format: "), this), _format_combobox); - pv::data::DecoderModel* decoder_model = _session.get_decoder_model(); - const boost::shared_ptr& decoder_stack = decoder_model->getDecoderStack(); + pv::data::DecoderModel* decoder_model = _session->get_decoder_model(); + + const auto decoder_stack = decoder_model->getDecoderStack(); if (decoder_stack) { int row_index = 0; - const std::map rows = decoder_stack->get_rows_lshow(); - for (std::map::const_iterator i = rows.begin(); - i != rows.end(); i++) { + auto rows = decoder_stack->get_rows_lshow(); + + for (auto i = rows.begin();i != rows.end(); i++) { if ((*i).second) { QLabel *row_label = new QLabel((*i).first.title(), this); QRadioButton *row_sel = new QRadioButton(this); @@ -96,7 +96,7 @@ ProtocolExp::ProtocolExp(QWidget *parent, SigSession &session) : connect(&_button_box, SIGNAL(accepted()), this, SLOT(accept())); connect(&_button_box, SIGNAL(rejected()), this, SLOT(reject())); - connect(_session.get_device().get(), SIGNAL(device_updated()), this, SLOT(reject())); + connect(_session->get_device(), SIGNAL(device_updated()), this, SLOT(reject())); } @@ -118,15 +118,20 @@ void ProtocolExp::accept() if(i < supportedFormats.count() - 1) filter.append(";;"); } - const QString DIR_KEY("ProtocolExportPath"); - QSettings settings(QApplication::organizationName(), QApplication::applicationName()); + + AppConfig &app = AppConfig::Instance(); + QString default_filter = _format_combobox->currentText(); - QString default_name = settings.value(DIR_KEY).toString() + "/" + "decoder-"; - default_name += _session.get_session_time().toString("-yyMMdd-hhmmss"); + QString default_name = app._userHistory.protocolExportPath + "/" + "decoder-"; + default_name += _session->get_session_time().toString("-yyMMdd-hhmmss"); QString file_name = QFileDialog::getSaveFileName( - this, tr("Export Data"), default_name,filter,&default_filter); + this, + tr("Export Data"), + default_name,filter, + &default_filter); + if (!file_name.isEmpty()) { QFileInfo f(file_name); QStringList list = default_filter.split('.').last().split(')'); @@ -134,13 +139,17 @@ void ProtocolExp::accept() if(f.suffix().compare(ext)) file_name+=tr(".")+ext; - QDir CurrentDir; - settings.setValue(DIR_KEY, CurrentDir.filePath(file_name)); + QString fname = GetDirectoryName(file_name); + if (fname != app._userHistory.openDir) + { + app._userHistory.protocolExportPath = fname; + app.SaveHistory(); + } QFile file(file_name); file.open(QIODevice::WriteOnly | QIODevice::Text); QTextStream out(&file); - out.setCodec("UTF-8"); + app::set_utf8(out); //out.setGenerateByteOrderMark(true); // UTF-8 without BOM QFuture future; @@ -161,8 +170,8 @@ void ProtocolExp::accept() .arg("Time[ns]") .arg(title); - pv::data::DecoderModel* decoder_model = _session.get_decoder_model(); - const boost::shared_ptr& decoder_stack = decoder_model->getDecoderStack(); + pv::data::DecoderModel* decoder_model = _session->get_decoder_model(); + const auto decoder_stack = decoder_model->getDecoderStack(); int row_index = 0; Row row; const std::map rows_lshow = decoder_stack->get_rows_lshow(); @@ -179,11 +188,11 @@ void ProtocolExp::accept() uint64_t exported = 0; double ns_per_sample = SR_SEC(1) * 1.0 / decoder_stack->samplerate(); - vector annotations; + std::vector annotations; decoder_stack->get_annotation_subset(annotations, row, 0, decoder_stack->sample_count()-1); if (!annotations.empty()) { - BOOST_FOREACH(const Annotation &a, annotations) { + for(auto &a : annotations) { out << QString("%1,%2,%3\n") .arg(QString::number(exported)) .arg(QString::number(a.start_sample()*ns_per_sample, 'f', 20)) diff --git a/DSView/pv/dialogs/protocolexp.h b/DSView/pv/dialogs/protocolexp.h index b978c604..a4894459 100755 --- a/DSView/pv/dialogs/protocolexp.h +++ b/DSView/pv/dialogs/protocolexp.h @@ -28,14 +28,12 @@ #include #include #include -#include - -#include - + #include "../device/devinst.h" #include "../prop/binding/deviceoptions.h" #include "../toolbars/titlebar.h" #include "dsdialog.h" +#include "../ui/dscombobox.h" namespace pv { @@ -54,7 +52,7 @@ class ProtocolExp : public DSDialog Q_OBJECT public: - ProtocolExp(QWidget *parent, SigSession &session); + ProtocolExp(QWidget *parent, SigSession *session); protected: void accept(); @@ -67,10 +65,10 @@ private slots: void cancel_export(); private: - SigSession &_session; + SigSession *_session; toolbars::TitleBar *_titlebar; - QComboBox *_format_combobox; + DsComboBox *_format_combobox; std::list _row_sel_list; std::list _row_label_list; QFormLayout *_flayout; diff --git a/DSView/pv/dialogs/protocollist.cpp b/DSView/pv/dialogs/protocollist.cpp index 170f8eda..4144cc58 100755 --- a/DSView/pv/dialogs/protocollist.cpp +++ b/DSView/pv/dialogs/protocollist.cpp @@ -20,8 +20,7 @@ */ #include "protocollist.h" - -#include + #include #include @@ -38,29 +37,31 @@ using namespace std; namespace pv { namespace dialogs { -ProtocolList::ProtocolList(QWidget *parent, SigSession &session) : +ProtocolList::ProtocolList(QWidget *parent, SigSession *session) : DSDialog(parent), _session(session), _button_box(QDialogButtonBox::Ok, Qt::Horizontal, this) { - pv::data::DecoderModel* decoder_model = _session.get_decoder_model(); + pv::data::DecoderModel* decoder_model = _session->get_decoder_model(); - _map_zoom_combobox = new QComboBox(this); + _map_zoom_combobox = new DsComboBox(this); _map_zoom_combobox->addItem(tr("Fit to Window")); _map_zoom_combobox->addItem(tr("Fixed")); - int cur_map_zoom = _session.get_map_zoom(); + int cur_map_zoom = _session->get_map_zoom(); + if (cur_map_zoom >= _map_zoom_combobox->count()) _map_zoom_combobox->setCurrentIndex(0); else _map_zoom_combobox->setCurrentIndex(cur_map_zoom); - connect(_map_zoom_combobox, SIGNAL(currentIndexChanged(int)), &_session, SLOT(set_map_zoom(int))); - _protocol_combobox = new QComboBox(this); - const std::vector< boost::shared_ptr > decode_sigs( - _session.get_decode_signals()); + connect(_map_zoom_combobox, SIGNAL(currentIndexChanged(int)), this, SLOT(on_set_map_zoom(int))); + + _protocol_combobox = new DsComboBox(this); + auto &decode_sigs = _session->get_decode_signals(); int index = 0; - BOOST_FOREACH(boost::shared_ptr d, decode_sigs) { + + for(auto &d : decode_sigs) { _protocol_combobox->addItem(d->get_name()); if (decoder_model->getDecoderStack() == d->decoder()) _protocol_combobox->setCurrentIndex(index); @@ -89,7 +90,7 @@ ProtocolList::ProtocolList(QWidget *parent, SigSession &session) : connect(&_button_box, SIGNAL(accepted()), this, SLOT(accept())); connect(_protocol_combobox, SIGNAL(currentIndexChanged(int)), this, SLOT(set_protocol(int))); set_protocol(_protocol_combobox->currentIndex()); - connect(_session.get_device().get(), SIGNAL(device_updated()), this, SLOT(reject())); + connect(_session->get_device(), SIGNAL(device_updated()), this, SLOT(reject())); } @@ -126,11 +127,11 @@ void ProtocolList::set_protocol(int index) } _show_label_list.clear(); - boost::shared_ptr decoder_stack; - const std::vector< boost::shared_ptr > decode_sigs( - _session.get_decode_signals()); + pv::data::DecoderStack *decoder_stack = NULL; + const auto &decode_sigs = _session->get_decode_signals(); int cur_index = 0; - BOOST_FOREACH(boost::shared_ptr d, decode_sigs) { + + for(auto &d : decode_sigs) { if (index == cur_index) { decoder_stack = d->decoder(); break; @@ -139,15 +140,15 @@ void ProtocolList::set_protocol(int index) } if (!decoder_stack){ - _session.get_decoder_model()->setDecoderStack(NULL); + _session->get_decoder_model()->setDecoderStack(NULL); return; } - _session.get_decoder_model()->setDecoderStack(decoder_stack); + _session->get_decoder_model()->setDecoderStack(decoder_stack); int row_index = 0; - const std::map rows = decoder_stack->get_rows_lshow(); - for (std::map::const_iterator i = rows.begin(); - i != rows.end(); i++) { + const auto rows = decoder_stack->get_rows_lshow(); + + for (auto i = rows.begin();i != rows.end(); i++) { QLabel *row_label = new QLabel((*i).first.title(), this); QCheckBox *row_checkbox = new QCheckBox(this); //row_checkbox->setChecked(false); @@ -168,11 +169,11 @@ void ProtocolList::on_row_check(bool show) QVariant id = sc->property("index"); int index = id.toInt(); - boost::shared_ptr decoder_stack; - const std::vector< boost::shared_ptr > decode_sigs( - _session.get_decode_signals()); + pv::data::DecoderStack *decoder_stack = NULL; + const auto &decode_sigs = _session->get_decode_signals(); int cur_index = 0; - BOOST_FOREACH(boost::shared_ptr d, decode_sigs) { + + for(auto &d : decode_sigs) { if (cur_index == _protocol_combobox->currentIndex()) { decoder_stack = d->decoder(); break; @@ -192,7 +193,13 @@ void ProtocolList::on_row_check(bool show) } } - _session.get_decoder_model()->setDecoderStack(decoder_stack); + _session->get_decoder_model()->setDecoderStack(decoder_stack); } + + void ProtocolList::on_set_map_zoom(int index) + { + _session->set_map_zoom(index); + } + } // namespace dialogs } // namespace pv diff --git a/DSView/pv/dialogs/protocollist.h b/DSView/pv/dialogs/protocollist.h index bc6a9891..879787c0 100755 --- a/DSView/pv/dialogs/protocollist.h +++ b/DSView/pv/dialogs/protocollist.h @@ -27,15 +27,13 @@ #include #include #include -#include -#include - -#include +#include #include "../device/devinst.h" #include "../prop/binding/deviceoptions.h" #include "../toolbars/titlebar.h" #include "dsdialog.h" +#include "../ui/dscombobox.h" namespace pv { @@ -48,7 +46,7 @@ class ProtocolList : public DSDialog Q_OBJECT public: - ProtocolList(QWidget *parent, SigSession &session); + ProtocolList(QWidget *parent, SigSession *session); protected: void accept(); @@ -57,13 +55,14 @@ protected: private slots: void set_protocol(int index); void on_row_check(bool show); + void on_set_map_zoom(int index); private: - SigSession &_session; + SigSession *_session; toolbars::TitleBar *_titlebar; - QComboBox *_map_zoom_combobox; - QComboBox *_protocol_combobox; + DsComboBox *_map_zoom_combobox; + DsComboBox *_protocol_combobox; std::list _show_checkbox_list; std::list _show_label_list; QFormLayout *_flayout; diff --git a/DSView/pv/dialogs/regionoptions.cpp b/DSView/pv/dialogs/regionoptions.cpp index 0a113133..8c455d26 100755 --- a/DSView/pv/dialogs/regionoptions.cpp +++ b/DSView/pv/dialogs/regionoptions.cpp @@ -20,9 +20,7 @@ */ #include "regionoptions.h" - -#include - + #include "../sigsession.h" #include "../view/cursor.h" #include "../view/view.h" @@ -37,7 +35,7 @@ namespace dialogs { const QString RegionOptions::RegionStart = QT_TR_NOOP("Start"); const QString RegionOptions::RegionEnd = QT_TR_NOOP("End"); -RegionOptions::RegionOptions(view::View *view, SigSession &session, QWidget *parent) : +RegionOptions::RegionOptions(view::View *view, SigSession *session, QWidget *parent) : DSDialog(parent), _session(session), _view(view), @@ -45,10 +43,10 @@ RegionOptions::RegionOptions(view::View *view, SigSession &session, QWidget *par Qt::Horizontal, this) { QHBoxLayout *hlayout = new QHBoxLayout(); - hlayout->setMargin(0); + hlayout->setContentsMargins(0,0,0,0); hlayout->setSpacing(0); - _start_comboBox = new QComboBox(this); - _end_comboBox = new QComboBox(this); + _start_comboBox = new DsComboBox(this); + _end_comboBox = new DsComboBox(this); _start_comboBox->addItem(RegionStart); _end_comboBox->addItem(RegionEnd); if (_view) { @@ -75,19 +73,19 @@ RegionOptions::RegionOptions(view::View *view, SigSession &session, QWidget *par setTitle(tr("Region")); connect(&_button_box, SIGNAL(accepted()), this, SLOT(set_region())); - connect(_session.get_device().get(), SIGNAL(device_updated()), this, SLOT(reject())); + connect(_session->get_device(), SIGNAL(device_updated()), this, SLOT(reject())); } void RegionOptions::set_region() { - const uint64_t last_samples = _session.cur_samplelimits() - 1; + const uint64_t last_samples = _session->cur_samplelimits() - 1; const int index1 = _start_comboBox->currentIndex(); const int index2 = _end_comboBox->currentIndex(); uint64_t start, end; - _session.set_save_start(0); - _session.set_save_end(last_samples); + _session->set_save_start(0); + _session->set_save_end(last_samples); if (index1 == 0) { start = 0; @@ -105,8 +103,8 @@ void RegionOptions::set_region() if (end > last_samples) end = last_samples; - _session.set_save_start(min(start, end)); - _session.set_save_end(max(start, end)); + _session->set_save_start(min(start, end)); + _session->set_save_end(max(start, end)); QDialog::accept(); } diff --git a/DSView/pv/dialogs/regionoptions.h b/DSView/pv/dialogs/regionoptions.h index 097baff7..a66b2811 100755 --- a/DSView/pv/dialogs/regionoptions.h +++ b/DSView/pv/dialogs/regionoptions.h @@ -27,12 +27,10 @@ #include #include #include -#include - -#include - + #include "../toolbars/titlebar.h" #include "dsdialog.h" +#include "../ui/dscombobox.h" namespace pv { @@ -52,17 +50,17 @@ private: static const QString RegionEnd; public: - RegionOptions(view::View *view, SigSession &session, QWidget *parent = 0); + RegionOptions(view::View *view, SigSession *session, QWidget *parent = 0); private slots: void set_region(); private: - SigSession &_session; + SigSession *_session; view::View *_view; - QComboBox *_start_comboBox; - QComboBox *_end_comboBox; + DsComboBox *_start_comboBox; + DsComboBox *_end_comboBox; QDialogButtonBox _button_box; diff --git a/DSView/pv/dialogs/search.cpp b/DSView/pv/dialogs/search.cpp index 86e69dda..406f1be8 100755 --- a/DSView/pv/dialogs/search.cpp +++ b/DSView/pv/dialogs/search.cpp @@ -23,14 +23,13 @@ #include "../view/logicsignal.h" #include -#include - -#include +#include + namespace pv { namespace dialogs { -Search::Search(QWidget *parent, SigSession &session, std::map pattern) : +Search::Search(QWidget *parent, SigSession *session, std::map pattern) : DSDialog(parent), _session(session) { @@ -40,8 +39,8 @@ Search::Search(QWidget *parent, SigSession &session, std::map font.setFixedPitch(true); //this->setMinimumWidth(350); - QRegExp value_rx("[10XRFCxrfc]+"); - QValidator *value_validator = new QRegExpValidator(value_rx, this); + QRegularExpression value_rx("[10XRFCxrfc]+"); + QValidator *value_validator = new QRegularExpressionValidator(value_rx, this); search_buttonBox.addButton(QDialogButtonBox::Ok); search_buttonBox.addButton(QDialogButtonBox::Cancel); @@ -50,11 +49,11 @@ Search::Search(QWidget *parent, SigSession &session, std::map search_layout->setVerticalSpacing(0); int index = 0; - BOOST_FOREACH(const boost::shared_ptr sig, - _session.get_signals()) { + + for(auto &sig : _session->get_signals()) { assert(sig); - boost::shared_ptr logic_sig; - if ((logic_sig = boost::dynamic_pointer_cast(sig))) { + view::LogicSignal *logic_sig = NULL; + if ((logic_sig = dynamic_cast(sig))) { QLineEdit *search_lineEdit = new QLineEdit(this); if (pattern.find(logic_sig->get_index()) != pattern.end()) search_lineEdit->setText(pattern[logic_sig->get_index()]); @@ -86,7 +85,7 @@ Search::Search(QWidget *parent, SigSession &session, std::map connect(&search_buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(&search_buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - connect(_session.get_device().get(), SIGNAL(device_updated()), this, SLOT(reject())); + connect(_session->get_device(), SIGNAL(device_updated()), this, SLOT(reject())); } Search::~Search() @@ -111,11 +110,10 @@ std::map Search::get_pattern() std::map pattern; int index = 0; - BOOST_FOREACH(const boost::shared_ptr sig, - _session.get_signals()) { + for(auto &sig :_session->get_signals()) { assert(sig); - boost::shared_ptr logic_sig; - if ((logic_sig = boost::dynamic_pointer_cast(sig))) { + view::LogicSignal *logic_sig = NULL; + if ((logic_sig = dynamic_cast(sig))) { pattern[logic_sig->get_index()] = _search_lineEdit_vec[index]->text(); index++; } diff --git a/DSView/pv/dialogs/search.h b/DSView/pv/dialogs/search.h index d1f7950a..013c4723 100755 --- a/DSView/pv/dialogs/search.h +++ b/DSView/pv/dialogs/search.h @@ -33,9 +33,7 @@ #include "../toolbars/titlebar.h" #include "dsdialog.h" #include "../device/devinst.h" - -#include - + namespace pv { namespace dialogs { @@ -45,7 +43,7 @@ class Search : public DSDialog public: - Search(QWidget *parent, SigSession &session, std::map pattern); + Search(QWidget *parent, SigSession *session, std::map pattern); ~Search(); std::map get_pattern(); @@ -59,7 +57,7 @@ private slots: void format(); private: - SigSession &_session; + SigSession *_session; toolbars::TitleBar *_titlebar; QVector _search_lineEdit_vec; diff --git a/DSView/pv/dialogs/storeprogress.cpp b/DSView/pv/dialogs/storeprogress.cpp index 2bb91a18..ad6d4596 100755 --- a/DSView/pv/dialogs/storeprogress.cpp +++ b/DSView/pv/dialogs/storeprogress.cpp @@ -19,36 +19,71 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#include "storeprogress.h" -#include "dsmessagebox.h" -#include "pv/sigsession.h" +#include "storeprogress.h" +#include "../sigsession.h" +#include +#include +#include +#include +#include +#include -#include "QVBoxLayout" +#include "../ui/msgbox.h" +#include "../config/appconfig.h" namespace pv { namespace dialogs { -StoreProgress::StoreProgress(SigSession &session, QWidget *parent) : +StoreProgress::StoreProgress(SigSession *session, QWidget *parent) : DSDialog(parent), - _store_session(session), - _button_box(QDialogButtonBox::Cancel, Qt::Horizontal, this), - _done(false) + _store_session(session) { - this->setModal(true); + _fileLab = NULL; + _ckOrigin = NULL; - _info.setText("..."); + this->setMinimumSize(550, 220); + this->setModal(true); + _progress.setValue(0); _progress.setMaximum(100); - QVBoxLayout* add_layout = new QVBoxLayout(); - add_layout->addWidget(&_info, 0, Qt::AlignCenter); - add_layout->addWidget(&_progress); - add_layout->addWidget(&_button_box); - layout()->addLayout(add_layout); + _isExport = false; + _done = false; + + QGridLayout *grid = new QGridLayout(); + _grid = grid; + grid->setContentsMargins(10, 20, 10, 10); + grid->setVerticalSpacing(25); + + grid->setColumnStretch(0, 2); + grid->setColumnStretch(1, 2); + grid->setColumnStretch(2, 1); + grid->setColumnStretch(3, 1); + + _fileLab = new QLineEdit(); + _fileLab->setEnabled(false); + _fileLab->setObjectName("PathLine"); + + QPushButton *openButton = new QPushButton(this); + openButton->setText(tr("change")); + + grid->addWidget(&_progress, 0, 0, 1, 4); + grid->addWidget(_fileLab, 1, 0, 1, 3); + grid->addWidget(openButton, 1, 3, 1, 1); + + QDialogButtonBox *_button_box = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, + Qt::Horizontal, this); + grid->addWidget(_button_box, 2, 2, 1, 2, Qt::AlignRight | Qt::AlignBottom); + + layout()->addLayout(grid); + + connect(_button_box, SIGNAL(rejected()), this, SLOT(reject())); + connect(_button_box, SIGNAL(accepted()), this, SLOT(accept())); - connect(&_button_box, SIGNAL(rejected()), this, SLOT(reject())); connect(&_store_session, SIGNAL(progress_updated()), this, SLOT(on_progress_updated()), Qt::QueuedConnection); + + connect(openButton, SIGNAL(clicked()),this, SLOT(on_change_file())); } StoreProgress::~StoreProgress() @@ -56,57 +91,117 @@ StoreProgress::~StoreProgress() _store_session.wait(); } + void StoreProgress::on_change_file() + { + if (_isExport){ + QString file = _store_session.MakeExportFile(true); + if (file != "") + _fileLab->setText(file); + } + else{ + QString file = _store_session.MakeSaveFile(true); + if (file != "") + _fileLab->setText(file); + } + } + void StoreProgress::reject() { using namespace Qt; _store_session.cancel(); save_done(); - QDialog::reject(); + DSDialog::reject(); +} + +void StoreProgress::accept() +{ + if (_store_session.GetFileName() == ""){ + MsgBox::Show(NULL, "you need to select a file name."); + return; + } + + if (_isExport && _store_session.IsLogicDataType()){ + bool ck = _ckOrigin->isChecked(); + AppConfig &app = AppConfig::Instance(); + if (app._appOptions.originalData != ck){ + app._appOptions.originalData = ck; + app.SaveApp(); + } + } + + //start done + if (_isExport){ + if (_store_session.export_start()){ + QTimer::singleShot(100, this, SLOT(timeout())); + } + else{ + save_done(); + close(); + show_error(); + } + } + else{ + if (_store_session.save_start()){ + QTimer::singleShot(100, this, SLOT(timeout())); + } + else{ + save_done(); + close(); + show_error(); + } + } + //do not to call base class method, otherwise the window will be closed; } void StoreProgress::timeout() { if (_done) { - _store_session.session().set_saving(false); + _store_session.session()->set_saving(false); save_done(); - close(); + close(); + delete this; + } else { QTimer::singleShot(100, this, SLOT(timeout())); } } -void StoreProgress::save_run(QString session_file) +void StoreProgress::save_run(ISessionDataGetter *getter) { - _info.setText(tr("Saving...")); - if (_store_session.save_start(session_file)) - show(); - else - show_error(); - - QTimer::singleShot(100, this, SLOT(timeout())); + _isExport = false; + setTitle(tr("Saving...")); + QString file = _store_session.MakeSaveFile(false); + _fileLab->setText(file); + _store_session._sessionDataGetter = getter; + show(); } void StoreProgress::export_run() { - _info.setText(tr("Exporting...")); - if (_store_session.export_start()) - show(); - else - show_error(); + if (_store_session.IsLogicDataType()) + { + QGridLayout *lay = new QGridLayout(); + lay->setContentsMargins(15, 0, 0, 0); + AppConfig &app = AppConfig::Instance(); + _ckOrigin = new QCheckBox(); + _ckOrigin->setChecked(app._appOptions.originalData); + _ckOrigin->setText(tr("all original data")); + lay->addWidget(_ckOrigin); + _grid->addLayout(lay, 2, 0, 1, 2); + } - QTimer::singleShot(100, this, SLOT(timeout())); + _isExport = true; + setTitle(tr("Exporting...")); + QString file = _store_session.MakeExportFile(false); + _fileLab->setText(file); + show(); } void StoreProgress::show_error() { _done = true; - if (!_store_session.error().isEmpty()) { - dialogs::DSMessageBox msg(parentWidget()); - msg.mBox()->setText(tr("Failed to save data.")); - msg.mBox()->setInformativeText(_store_session.error()); - msg.mBox()->setStandardButtons(QMessageBox::Ok); - msg.mBox()->setIcon(QMessageBox::Warning); - msg.exec(); + if (!_store_session.error().isEmpty()) { + MsgBox::Show(NULL, _store_session.error().toStdString().c_str(), NULL); } } diff --git a/DSView/pv/dialogs/storeprogress.h b/DSView/pv/dialogs/storeprogress.h index 93c61ef4..54a5b548 100755 --- a/DSView/pv/dialogs/storeprogress.h +++ b/DSView/pv/dialogs/storeprogress.h @@ -21,19 +21,15 @@ #ifndef DSVIEW_PV_DIALOGS_SAVEPROGRESS_H #define DSVIEW_PV_DIALOGS_SAVEPROGRESS_H - -#include - -#include - -#include + #include -#include -#include - #include "../storesession.h" -#include "../dialogs/dsdialog.h" -#include "../toolbars/titlebar.h" +#include "../dialogs/dsdialog.h" +#include "../interface/icallbacks.h" + +class QLineEdit; +class QCheckBox; +class QGridLayout; namespace pv { @@ -46,15 +42,15 @@ class StoreProgress : public DSDialog Q_OBJECT public: - StoreProgress(SigSession &session, + StoreProgress(SigSession *session, QWidget *parent = 0); virtual ~StoreProgress(); - - + protected: void reject(); + void accept(); private: void show_error(); @@ -64,23 +60,22 @@ signals: void save_done(); public slots: - void save_run(QString session_file); + void save_run(ISessionDataGetter *getter); void export_run(); private slots: void on_progress_updated(); void timeout(); + void on_change_file(); private: - pv::StoreSession _store_session; - - QLabel _info; - QProgressBar _progress; - QDialogButtonBox _button_box; - - toolbars::TitleBar *_titlebar; - - bool _done; + pv::StoreSession _store_session; + QProgressBar _progress; + bool _done; + bool _isExport; + QLineEdit *_fileLab; + QCheckBox *_ckOrigin; + QGridLayout *_grid; }; } // dialogs diff --git a/DSView/pv/dialogs/waitingdialog.cpp b/DSView/pv/dialogs/waitingdialog.cpp index f4144ec5..1817c34b 100755 --- a/DSView/pv/dialogs/waitingdialog.cpp +++ b/DSView/pv/dialogs/waitingdialog.cpp @@ -20,8 +20,7 @@ */ #include "waitingdialog.h" - -#include + #include #include @@ -32,6 +31,7 @@ #include "../view/trace.h" #include "../view/dsosignal.h" +#include "../config/appconfig.h" using namespace boost; using namespace std; @@ -42,14 +42,14 @@ namespace dialogs { const QString WaitingDialog::TIPS_WAIT = "Waiting"; const QString WaitingDialog::TIPS_FINISHED = "Finished!"; -WaitingDialog::WaitingDialog(QWidget *parent, SigSession &session, int key) : +WaitingDialog::WaitingDialog(QWidget *parent, SigSession *session, int key) : DSDialog(parent), _key(key), _session(session), _button_box(QDialogButtonBox::Abort, Qt::Horizontal, this) { - _dev_inst = _session.get_device(); + _dev_inst = _session->get_device(); this->setFixedSize((GIF_WIDTH+2*TIP_WIDTH)*1.2, (GIF_HEIGHT+2*TIP_HEIGHT)*4); this->setWindowOpacity(0.7); @@ -62,7 +62,7 @@ WaitingDialog::WaitingDialog(QWidget *parent, SigSession &session, int key) : warning_tips->setFont(font); warning_tips->setAlignment(Qt::AlignCenter); - QString iconPath = ":/icons/" + qApp->property("Style").toString(); + QString iconPath = GetIconPath(); label = new QLabel(this); movie = new QMovie(iconPath+"/wait.gif"); label->setMovie(movie); @@ -78,7 +78,7 @@ WaitingDialog::WaitingDialog(QWidget *parent, SigSession &session, int key) : connect(timer, SIGNAL(timeout()), this, SLOT(changeText())); connect(&_button_box, SIGNAL(accepted()), this, SLOT(accept())); connect(&_button_box, SIGNAL(rejected()), this, SLOT(reject())); - connect(_dev_inst.get(), SIGNAL(device_updated()), this, SLOT(stop())); + connect(_dev_inst, SIGNAL(device_updated()), this, SLOT(stop())); QVBoxLayout *mlayout = new QVBoxLayout(); @@ -184,13 +184,14 @@ void WaitingDialog::changeText() zero_fgain = g_variant_get_boolean(gvar); g_variant_unref(gvar); if (zero_fgain) { - boost::shared_ptr dsoSig; - BOOST_FOREACH(const boost::shared_ptr s, _session.get_signals()) + view::DsoSignal *dsoSig = NULL; + + for(auto &s : _session->get_signals()) { - if ((dsoSig = dynamic_pointer_cast(s))) + if ((dsoSig = dynamic_cast(s))) dsoSig->set_enable(dsoSig->get_index() == 0); } - boost::this_thread::sleep(boost::posix_time::millisec(100)); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); _dev_inst->set_config(NULL, NULL, SR_CONF_ZERO_COMB, g_variant_new_boolean(true)); } } diff --git a/DSView/pv/dialogs/waitingdialog.h b/DSView/pv/dialogs/waitingdialog.h index fd14615a..dd1071d0 100755 --- a/DSView/pv/dialogs/waitingdialog.h +++ b/DSView/pv/dialogs/waitingdialog.h @@ -27,14 +27,14 @@ #include #include #include - -#include - + #include "../sigsession.h" #include "../device/devinst.h" #include "../toolbars/titlebar.h" #include "dsdialog.h" +using namespace pv::device; + namespace pv { namespace dialogs { @@ -53,7 +53,7 @@ private: static const QString TIPS_FINISHED; public: - WaitingDialog(QWidget *parent, SigSession &session, int key); + WaitingDialog(QWidget *parent, SigSession *session, int key); int start(); protected: @@ -66,8 +66,8 @@ private slots: private: int _key; - SigSession &_session; - boost::shared_ptr _dev_inst; + SigSession *_session; + DevInst* _dev_inst; toolbars::TitleBar *_titlebar; QDialogButtonBox _button_box; diff --git a/DSView/pv/dock/dsotriggerdock.cpp b/DSView/pv/dock/dsotriggerdock.cpp index 5e54dce7..7fce3f47 100755 --- a/DSView/pv/dock/dsotriggerdock.cpp +++ b/DSView/pv/dock/dsotriggerdock.cpp @@ -24,9 +24,7 @@ #include "../device/devinst.h" #include "../dialogs/dsmessagebox.h" #include "../view/dsosignal.h" - -#include -#include + #include #include @@ -37,6 +35,7 @@ #include #include #include +#include using namespace boost; using namespace std; @@ -44,7 +43,7 @@ using namespace std; namespace pv { namespace dock { -DsoTriggerDock::DsoTriggerDock(QWidget *parent, SigSession &session) : +DsoTriggerDock::DsoTriggerDock(QWidget *parent, SigSession *session) : QScrollArea(parent), _session(session) { @@ -62,7 +61,7 @@ DsoTriggerDock::DsoTriggerDock(QWidget *parent, SigSession &session) : connect(_position_slider, SIGNAL(valueChanged(int)), this, SLOT(pos_changed(int))); _holdoff_label = new QLabel(_widget); - _holdoff_comboBox = new QComboBox(_widget); + _holdoff_comboBox = new DsComboBox(_widget); _holdoff_comboBox->addItem(tr("uS"), QVariant::fromValue(1000)); _holdoff_comboBox->addItem(tr("mS"), QVariant::fromValue(1000000)); _holdoff_comboBox->addItem(tr("S"), QVariant::fromValue(1000000000)); @@ -104,7 +103,7 @@ DsoTriggerDock::DsoTriggerDock(QWidget *parent, SigSession &session) : connect(_falling_radioButton, SIGNAL(clicked()), this, SLOT(type_changed())); _source_group=new QButtonGroup(_widget); - _channel_comboBox = new QComboBox(_widget); + _channel_comboBox = new DsComboBox(_widget); _type_group=new QButtonGroup(_widget); _source_group->addButton(_auto_radioButton); @@ -200,7 +199,7 @@ void DsoTriggerDock::retranslateUi() void DsoTriggerDock::reStyle() { - //QString iconPath = ":/icons/" + qApp->property("Style").toString(); + } void DsoTriggerDock::paintEvent(QPaintEvent *) @@ -222,7 +221,7 @@ void DsoTriggerDock::auto_trig(int index) void DsoTriggerDock::pos_changed(int pos) { int ret; - ret = _session.get_device()->set_config(NULL, NULL, + ret = _session->get_device()->set_config(NULL, NULL, SR_CONF_HORIZ_TRIGGERPOS, g_variant_new_byte((uint8_t)pos)); if (!ret) { @@ -247,7 +246,7 @@ void DsoTriggerDock::hold_changed(int hold) _holdoff_slider->setRange(0, 999); } holdoff = _holdoff_slider->value() * _holdoff_comboBox->currentData().toDouble() / 10; - ret = _session.get_device()->set_config(NULL, NULL, + ret = _session->get_device()->set_config(NULL, NULL, SR_CONF_TRIGGER_HOLDOFF, g_variant_new_uint64(holdoff)); @@ -264,7 +263,7 @@ void DsoTriggerDock::hold_changed(int hold) void DsoTriggerDock::margin_changed(int margin) { int ret; - ret = _session.get_device()->set_config(NULL, NULL, + ret = _session->get_device()->set_config(NULL, NULL, SR_CONF_TRIGGER_MARGIN, g_variant_new_byte(margin)); if (!ret) { @@ -282,7 +281,7 @@ void DsoTriggerDock::source_changed() int id = _source_group->checkedId(); int ret; - ret = _session.get_device()->set_config(NULL, NULL, + ret = _session->get_device()->set_config(NULL, NULL, SR_CONF_TRIGGER_SOURCE, g_variant_new_byte(id)); if (!ret) { @@ -300,7 +299,7 @@ void DsoTriggerDock::channel_changed(int ch) (void)ch; int ret; - ret = _session.get_device()->set_config(NULL, NULL, + ret = _session->get_device()->set_config(NULL, NULL, SR_CONF_TRIGGER_CHANNEL, g_variant_new_byte(_channel_comboBox->currentData().toInt())); if (!ret) { @@ -318,7 +317,7 @@ void DsoTriggerDock::type_changed() int id = _type_group->checkedId(); int ret; - ret = _session.get_device()->set_config(NULL, NULL, + ret = _session->get_device()->set_config(NULL, NULL, SR_CONF_TRIGGER_SLOPE, g_variant_new_byte(id)); if (!ret) { @@ -333,7 +332,7 @@ void DsoTriggerDock::type_changed() void DsoTriggerDock::device_change() { - if (_session.get_device()->name() != "DSLogic") { + if (_session->get_device()->name() != "DSLogic") { _position_spinBox->setDisabled(true); _position_slider->setDisabled(true); } else { @@ -344,11 +343,13 @@ void DsoTriggerDock::device_change() void DsoTriggerDock::init() { - if (_session.get_device()->name().contains("virtual")) { - foreach(QAbstractButton * btn, _source_group->buttons()) + if (_session->get_device()->name().contains("virtual")) { + for(QAbstractButton * btn : _source_group->buttons()) btn->setDisabled(true); - foreach(QAbstractButton * btn, _type_group->buttons()) + + for(QAbstractButton * btn : _type_group->buttons()) btn->setDisabled(true); + _holdoff_slider->setDisabled(true); _holdoff_spinBox->setDisabled(true); _holdoff_comboBox->setDisabled(true); @@ -356,10 +357,12 @@ void DsoTriggerDock::init() _channel_comboBox->setDisabled(true); return; } else { - foreach(QAbstractButton * btn, _source_group->buttons()) + for(QAbstractButton * btn : _source_group->buttons()) btn->setDisabled(false); - foreach(QAbstractButton * btn, _type_group->buttons()) + + for(QAbstractButton * btn : _type_group->buttons()) btn->setDisabled(false); + _holdoff_slider->setDisabled(false); _holdoff_spinBox->setDisabled(false); _holdoff_comboBox->setDisabled(false); @@ -368,7 +371,7 @@ void DsoTriggerDock::init() } // TRIGGERPOS - GVariant* gvar = _session.get_device()->get_config(NULL, NULL, + GVariant* gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_HORIZ_TRIGGERPOS); if (gvar != NULL) { uint16_t pos = g_variant_get_byte(gvar); @@ -376,7 +379,7 @@ void DsoTriggerDock::init() _position_slider->setValue(pos); } - gvar = _session.get_device()->get_config(NULL, NULL, + gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_TRIGGER_SOURCE); if (gvar != NULL) { uint8_t src = g_variant_get_byte(gvar); @@ -387,13 +390,14 @@ void DsoTriggerDock::init() // setup _channel_comboBox disconnect(_channel_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(channel_changed(int))); _channel_comboBox->clear(); - BOOST_FOREACH(const boost::shared_ptr s, _session.get_signals()) { - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s))) { + + for(auto &s : _session->get_signals()) { + view::DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(s))) { _channel_comboBox->addItem(dsoSig->get_name(), QVariant::fromValue(dsoSig->get_index())); } } - gvar = _session.get_device()->get_config(NULL, NULL, + gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_TRIGGER_CHANNEL); if (gvar != NULL) { uint8_t src = g_variant_get_byte(gvar); @@ -407,7 +411,7 @@ void DsoTriggerDock::init() } connect(_channel_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(channel_changed(int))); - gvar = _session.get_device()->get_config(NULL, NULL, + gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_TRIGGER_SLOPE); if (gvar != NULL) { uint8_t slope = g_variant_get_byte(gvar); @@ -417,7 +421,7 @@ void DsoTriggerDock::init() disconnect(_holdoff_slider, SIGNAL(valueChanged(int)), this, SLOT(hold_changed(int))); disconnect(_holdoff_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(hold_changed(int))); - gvar = _session.get_device()->get_config(NULL, NULL, + gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_TRIGGER_HOLDOFF); if (gvar != NULL) { uint64_t holdoff = g_variant_get_uint64(gvar); @@ -439,7 +443,7 @@ void DsoTriggerDock::init() connect(_holdoff_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(hold_changed(int))); disconnect(_margin_slider, SIGNAL(valueChanged(int)), this, SLOT(margin_changed(int))); - gvar = _session.get_device()->get_config(NULL, NULL, + gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_TRIGGER_MARGIN); if (gvar != NULL) { uint8_t margin = g_variant_get_byte(gvar); diff --git a/DSView/pv/dock/dsotriggerdock.h b/DSView/pv/dock/dsotriggerdock.h index b0971b72..847194e5 100755 --- a/DSView/pv/dock/dsotriggerdock.h +++ b/DSView/pv/dock/dsotriggerdock.h @@ -27,12 +27,13 @@ #include #include #include -#include #include #include #include +#include "../ui/dscombobox.h" + namespace pv { class SigSession; @@ -44,7 +45,7 @@ class DsoTriggerDock : public QScrollArea Q_OBJECT public: - DsoTriggerDock(QWidget *parent, SigSession &session); + DsoTriggerDock(QWidget *parent, SigSession *session); ~DsoTriggerDock(); void paintEvent(QPaintEvent *); @@ -75,11 +76,11 @@ private slots: private: private: - SigSession &_session; + SigSession *_session; QWidget *_widget; - QComboBox *_holdoff_comboBox; + DsComboBox *_holdoff_comboBox; QSpinBox *_holdoff_spinBox; QSlider *_holdoff_slider; @@ -89,7 +90,7 @@ private: QSlider *_position_slider; QButtonGroup *_source_group; - QComboBox *_channel_comboBox; + DsComboBox *_channel_comboBox; QButtonGroup *_type_group; QLabel *_position_label; diff --git a/DSView/pv/dock/measuredock.cpp b/DSView/pv/dock/measuredock.cpp index 0892d229..cd98281f 100755 --- a/DSView/pv/dock/measuredock.cpp +++ b/DSView/pv/dock/measuredock.cpp @@ -38,9 +38,9 @@ #include "../dialogs/dsmessagebox.h" #include -#include -#include +#include #include +#include "../config/appconfig.h" using namespace boost; @@ -49,7 +49,7 @@ namespace dock { using namespace pv::view; -MeasureDock::MeasureDock(QWidget *parent, View &view, SigSession &session) : +MeasureDock::MeasureDock(QWidget *parent, View &view, SigSession *session) : QScrollArea(parent), _session(session), _view(view) @@ -183,7 +183,7 @@ void MeasureDock::retranslateUi() void MeasureDock::reStyle() { - QString iconPath = ":/icons/" + qApp->property("Style").toString(); + QString iconPath = GetIconPath(); _dist_add_btn->setIcon(QIcon(iconPath+"/add.svg")); _edge_add_btn->setIcon(QIcon(iconPath+"/add.svg")); @@ -211,12 +211,12 @@ void MeasureDock::refresh() void MeasureDock::reload() { - if (_session.get_device()->dev_inst()->mode == LOGIC) + if (_session->get_device()->dev_inst()->mode == LOGIC) _edge_groupBox->setDisabled(false); else _edge_groupBox->setDisabled(true); - for (QVector ::const_iterator i = _edge_ch_cmb_vec.begin(); + for (QVector ::const_iterator i = _edge_ch_cmb_vec.begin(); i != _edge_ch_cmb_vec.end(); i++) { update_probe_selector(*i); } @@ -247,7 +247,7 @@ void MeasureDock::cursor_update() update_edge(); int index = 1; - QString iconPath = ":/icons/" + qApp->property("Style").toString(); + QString iconPath = GetIconPath(); for(std::list::iterator i = _view.get_cursorList().begin(); i != _view.get_cursorList().end(); i++) { QString curCursor = QString::number(index); @@ -307,6 +307,7 @@ void MeasureDock::reCalc() update_dist(); update_edge(); } + void MeasureDock::goto_cursor() { @@ -336,7 +337,7 @@ void MeasureDock::add_dist_measure() row_widget->setLayout(row_layout); _dist_row_widget_vec.push_back(row_widget); - QString iconPath = ":/icons/" + qApp->property("Style").toString(); + QString iconPath = GetIconPath(); QToolButton *del_btn = new QToolButton(row_widget); del_btn->setIcon(QIcon(iconPath+"/del.svg")); del_btn->setCheckable(true); @@ -402,7 +403,7 @@ void MeasureDock::add_edge_measure() row_widget->setLayout(row_layout); _edge_row_widget_vec.push_back(row_widget); - QString iconPath = ":/icons/" + qApp->property("Style").toString(); + QString iconPath = GetIconPath(); QToolButton *del_btn = new QToolButton(row_widget); del_btn->setIcon(QIcon(iconPath+"/del.svg")); del_btn->setCheckable(true); @@ -415,7 +416,7 @@ void MeasureDock::add_edge_measure() g_label->setContentsMargins(0,0,0,0); QLabel *a_label = new QLabel(tr("@"), row_widget); a_label->setContentsMargins(0,0,0,0); - QComboBox *ch_cmb = create_probe_selector(row_widget); + DsComboBox *ch_cmb = create_probe_selector(row_widget); _edge_del_btn_vec.push_back(del_btn); _edge_s_btn_vec.push_back(s_btn); _edge_e_btn_vec.push_back(e_btn); @@ -597,12 +598,15 @@ void MeasureDock::update_edge() if (start_ret && end_ret) { uint64_t rising_edges; uint64_t falling_edges; - const std::vector< boost::shared_ptr > sigs(_session.get_signals()); + + const auto &sigs = _session->get_signals(); + for(size_t i = 0; i < sigs.size(); i++) { - const boost::shared_ptr s(sigs[i]); - boost::shared_ptr logicSig; + view::Signal *s = sigs[i]; + view::LogicSignal *logicSig = NULL; assert(s); - if ((logicSig = dynamic_pointer_cast(s)) && + + if ((logicSig = dynamic_cast(s)) && (logicSig->enabled()) && (logicSig->get_index() == _edge_ch_cmb_vec[edge_index]->currentText().toInt())){ if (logicSig->edges(_view.get_cursor_samples(end), _view.get_cursor_samples(start), rising_edges, falling_edges)) { @@ -639,22 +643,23 @@ void MeasureDock::set_cursor_btn_color(QPushButton *btn) btn->setStyleSheet(style); } -QComboBox* MeasureDock::create_probe_selector(QWidget *parent) +DsComboBox* MeasureDock::create_probe_selector(QWidget *parent) { - QComboBox *selector = new QComboBox(parent); + DsComboBox *selector = new DsComboBox(parent); update_probe_selector(selector); return selector; } -void MeasureDock::update_probe_selector(QComboBox *selector) +void MeasureDock::update_probe_selector(DsComboBox *selector) { selector->clear(); - const std::vector< boost::shared_ptr > sigs(_session.get_signals()); + const auto &sigs = _session->get_signals(); + for(size_t i = 0; i < sigs.size(); i++) { - const boost::shared_ptr s(sigs[i]); + const auto s = sigs[i]; assert(s); - if (dynamic_pointer_cast(s) && s->enabled()) + if (dynamic_cast(s) && s->enabled()) { selector->addItem(QString::number(s->get_index())); } diff --git a/DSView/pv/dock/measuredock.h b/DSView/pv/dock/measuredock.h index c9f9beeb..63b77b52 100755 --- a/DSView/pv/dock/measuredock.h +++ b/DSView/pv/dock/measuredock.h @@ -24,7 +24,6 @@ #include #include -#include #include #include #include @@ -42,6 +41,8 @@ #include +#include "../ui/dscombobox.h" + namespace pv { class SigSession; @@ -61,7 +62,7 @@ private: static const int Max_Measure_Limits = 16; public: - MeasureDock(QWidget *parent, pv::view::View &view, SigSession &session); + MeasureDock(QWidget *parent, pv::view::View &view, SigSession *session); ~MeasureDock(); void paintEvent(QPaintEvent *); @@ -73,8 +74,8 @@ private: void reStyle(); private: - QComboBox* create_probe_selector(QWidget *parent); - void update_probe_selector(QComboBox *selector); + DsComboBox* create_probe_selector(QWidget *parent); + void update_probe_selector(DsComboBox *selector); signals: @@ -101,7 +102,7 @@ public slots: void refresh(); private: - SigSession &_session; + SigSession *_session; view::View &_view; QWidget *_widget; @@ -129,7 +130,7 @@ private: QVector _edge_del_btn_vec; QVector _edge_s_btn_vec; QVector _edge_e_btn_vec; - QVector _edge_ch_cmb_vec; + QVector _edge_ch_cmb_vec; QVector _edge_r_label_vec; QPushButton *_sel_btn; diff --git a/DSView/pv/dock/protocoldock.cpp b/DSView/pv/dock/protocoldock.cpp index 2039c9da..6081c64f 100755 --- a/DSView/pv/dock/protocoldock.cpp +++ b/DSView/pv/dock/protocoldock.cpp @@ -26,8 +26,7 @@ #include "../data/decodermodel.h" #include "../data/decoderstack.h" #include "../dialogs/protocollist.h" -#include "../dialogs/protocolexp.h" -#include "../dialogs/dsmessagebox.h" +#include "../dialogs/protocolexp.h" #include "../view/view.h" #include @@ -39,20 +38,26 @@ #include #include #include -#include +#include #include #include #include #include +#include -#include -#include + #include +#include "../ui/msgbox.h" +#include "../dsvdef.h" +#include "../config/appconfig.h" +#include "../data/decode/decoderstatus.h" + +using namespace std; namespace pv { namespace dock { - -ProtocolDock::ProtocolDock(QWidget *parent, view::View &view, SigSession &session) : + +ProtocolDock::ProtocolDock(QWidget *parent, view::View &view, SigSession *session) : QScrollArea(parent), _session(session), _view(view), @@ -70,7 +75,7 @@ ProtocolDock::ProtocolDock(QWidget *parent, view::View &view, SigSession &sessio _del_all_button = new QPushButton(_up_widget); _del_all_button->setFlat(true); _del_all_button->setCheckable(true); - _protocol_combobox = new QComboBox(_up_widget); + _protocol_combobox = new DsComboBox(_up_widget); GSList *l = g_slist_sort(g_slist_copy( (GSList*)srd_decoder_list()), decoder_name_cmp); @@ -90,12 +95,7 @@ ProtocolDock::ProtocolDock(QWidget *parent, view::View &view, SigSession &sessio hori_layout->addWidget(_del_all_button); hori_layout->addWidget(_protocol_combobox); hori_layout->addStretch(1); - - connect(_add_button, SIGNAL(clicked()), - this, SLOT(add_protocol())); - connect(_del_all_button, SIGNAL(clicked()), - this, SLOT(del_protocol())); - + _up_layout = new QVBoxLayout(); _up_layout->addLayout(hori_layout); _up_layout->addStretch(1); @@ -111,18 +111,12 @@ ProtocolDock::ProtocolDock(QWidget *parent, view::View &view, SigSession &sessio _dn_set_button = new QPushButton(_dn_widget); _dn_set_button->setFlat(true); - connect(_dn_set_button, SIGNAL(clicked()), - this, SLOT(set_model())); _dn_save_button = new QPushButton(_dn_widget); - _dn_save_button->setFlat(true); - connect(_dn_save_button, SIGNAL(clicked()), - this, SLOT(export_table_view())); + _dn_save_button->setFlat(true); _dn_nav_button = new QPushButton(_dn_widget); - _dn_nav_button->setFlat(true); - connect(_dn_nav_button, SIGNAL(clicked()), - this, SLOT(nav_table_view())); + _dn_nav_button->setFlat(true); QHBoxLayout *dn_title_layout = new QHBoxLayout(); _dn_title_label = new QLabel(_dn_widget); @@ -133,7 +127,7 @@ ProtocolDock::ProtocolDock(QWidget *parent, view::View &view, SigSession &sessio //dn_title_layout->addStretch(1); _table_view = new QTableView(_dn_widget); - _table_view->setModel(_session.get_decoder_model()); + _table_view->setModel(_session->get_decoder_model()); _table_view->setAlternatingRowColors(true); _table_view->setShowGrid(false); _table_view->horizontalHeader()->setStretchLastSection(true); @@ -142,10 +136,6 @@ ProtocolDock::ProtocolDock(QWidget *parent, view::View &view, SigSession &sessio _pre_button = new QPushButton(_dn_widget); _nxt_button = new QPushButton(_dn_widget); - connect(_pre_button, SIGNAL(clicked()), - this, SLOT(search_pre())); - connect(_nxt_button, SIGNAL(clicked()), - this, SLOT(search_nxt())); _search_button = new QPushButton(this); _search_button->setFixedWidth(_search_button->height()); @@ -186,26 +176,35 @@ ProtocolDock::ProtocolDock(QWidget *parent, view::View &view, SigSession &sessio _split_widget->setOrientation(Qt::Vertical); _split_widget->setCollapsible(0, false); _split_widget->setCollapsible(1, false); - //_split_widget->setStretchFactor(1, 1); - //_split_widget this->setWidgetResizable(true); this->setWidget(_split_widget); - //_split_widget->setGeometry(0, 0, sizeHint().width(), 500); + _split_widget->setObjectName("protocolWidget"); - connect(&_session, SIGNAL(decode_done()), this, SLOT(update_model())); + connect(_dn_nav_button, SIGNAL(clicked()),this, SLOT(nav_table_view())); + connect(_dn_save_button, SIGNAL(clicked()),this, SLOT(export_table_view())); + connect(_dn_set_button, SIGNAL(clicked()),this, SLOT(set_model())); + connect(_pre_button, SIGNAL(clicked()),this, SLOT(search_pre())); + connect(_nxt_button, SIGNAL(clicked()),this, SLOT(search_nxt())); + connect(_add_button, SIGNAL(clicked()),this, SLOT(on_add_protocol())); + connect(_del_all_button, SIGNAL(clicked()),this, SLOT(on_del_all_protocol())); + connect(this, SIGNAL(protocol_updated()), this, SLOT(update_model())); connect(_table_view, SIGNAL(clicked(QModelIndex)), this, SLOT(item_clicked(QModelIndex))); connect(_table_view->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(column_resize(int, int, int))); - //connect(_table_view->verticalScrollBar(), SIGNAL(sliderMoved()), this, SLOT(sliderMoved())); connect(_search_edit, SIGNAL(editingFinished()), this, SLOT(search_changed())); - retranslateUi(); + retranslateUi(); } ProtocolDock::~ProtocolDock() { + //destroy protocol item layers + for (auto it = _protocol_items.begin(); it != _protocol_items.end(); it++){ + DESTROY_QT_LATER(*it); + } + _protocol_items.clear(); } void ProtocolDock::changeEvent(QEvent *event) @@ -226,7 +225,7 @@ void ProtocolDock::retranslateUi() void ProtocolDock::reStyle() { - QString iconPath = ":/icons/" + qApp->property("Style").toString(); + QString iconPath = GetIconPath(); _add_button->setIcon(QIcon(iconPath+"/add.svg")); _del_all_button->setIcon(QIcon(iconPath+"/del.svg")); @@ -237,28 +236,24 @@ void ProtocolDock::reStyle() _nxt_button->setIcon(QIcon(iconPath+"/next.svg")); _search_button->setIcon(QIcon(iconPath+"/search.svg")); - for (QVector ::const_iterator i = _del_button_list.begin(); - i != _del_button_list.end(); i++) - (*i)->setIcon(QIcon(iconPath+"/del.svg")); - - for (QVector ::const_iterator i = _set_button_list.begin(); - i != _set_button_list.end(); i++) - (*i)->setIcon(QIcon(iconPath+"/gear.svg")); + for (auto it = _protocol_items.begin(); it != _protocol_items.end(); it++){ + (*it)->ResetStyle(); + } } void ProtocolDock::paintEvent(QPaintEvent *) -{ -// QStyleOption opt; -// opt.init(this); -// QPainter p(this); -// style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); +{ } void ProtocolDock::resizeEvent(QResizeEvent *event) { int width = this->visibleRegion().boundingRect().width(); - width = width - _dn_layout->margin() * 2 - - _dn_search_layout->margin() * 2 - + + int mg1 = 10; + int mg2 = 10; + + width = width - mg1 * 2 - + mg2 * 2 - _dn_search_layout->spacing() * 2 - _pre_button->width()-_nxt_button->width(); width = std::max(width, 0); @@ -298,179 +293,81 @@ bool ProtocolDock::sel_protocol(QString id) return false; } -void ProtocolDock::add_protocol() +void ProtocolDock::on_add_protocol() { add_protocol(false); } void ProtocolDock::add_protocol(bool silent) -{ - if (_session.get_device()->dev_inst()->mode != LOGIC) { - dialogs::DSMessageBox msg(this); - msg.mBox()->setText(tr("Protocol Analyzer")); - msg.mBox()->setInformativeText(tr("Protocol Analyzer is only valid in Digital Mode!")); - msg.mBox()->setStandardButtons(QMessageBox::Ok); - msg.mBox()->setIcon(QMessageBox::Warning); - msg.exec(); - } else { - srd_decoder *const decoder = - (srd_decoder*)(_protocol_combobox->itemData(_protocol_combobox->currentIndex())).value(); - if (_session.add_decoder(decoder, silent)) { - //std::list _sel_probes = dlg.get_sel_probes(); - //QMap & _options = dlg.get_options(); - //QMap _options_index = dlg.get_options_index(); +{ + if (_session->get_device()->dev_inst()->mode != LOGIC) { + MsgBox::Show(NULL, "Protocol Analyzer\nProtocol Analyzer is only valid in Digital Mode!", this); + return; + } - QString iconPath = ":/icons/" + qApp->property("Style").toString(); - QPushButton *_del_button = new QPushButton(_up_widget); - QPushButton *_set_button = new QPushButton(_up_widget); - _del_button->setFlat(true); - _del_button->setIcon(QIcon(iconPath+"/del.svg")); - _set_button->setFlat(true); - _set_button->setIcon(QIcon(iconPath+"/gear.svg")); - QLabel *_protocol_label = new QLabel(_up_widget); - QLabel *_progress_label = new QLabel(_up_widget); - - _del_button->setCheckable(true); - _protocol_label->setText(_protocol_combobox->currentText()); - - connect(_del_button, SIGNAL(clicked()), - this, SLOT(del_protocol())); - connect(_set_button, SIGNAL(clicked()), - this, SLOT(rst_protocol())); - - _del_button_list.push_back(_del_button); - _set_button_list.push_back(_set_button); - _protocol_label_list.push_back(_protocol_label); - _progress_label_list.push_back(_progress_label); - _protocol_index_list.push_back(_protocol_combobox->currentIndex()); - - QHBoxLayout *hori_layout = new QHBoxLayout(); - hori_layout->addWidget(_set_button); - hori_layout->addWidget(_del_button); - hori_layout->addWidget(_protocol_label); - hori_layout->addWidget(_progress_label); - hori_layout->addStretch(1); - _hori_layout_list.push_back(hori_layout); - _up_layout->insertLayout(_del_button_list.size(), hori_layout); - - // progress connection - const std::vector< boost::shared_ptr > decode_sigs( - _session.get_decode_signals()); - connect(decode_sigs.back().get(), SIGNAL(decoded_progress(int)), this, SLOT(decoded_progress(int))); - - protocol_updated(); + //have no protocol + if (_protocol_combobox->count() == 0){ + if (!silent){ + MsgBox::Show(NULL, "Protocol list is empty!"); } + return; + } + + srd_decoder *const decoder = + (srd_decoder *)(_protocol_combobox->itemData(_protocol_combobox->currentIndex())).value(); + + DecoderStatus *dstatus = new DecoderStatus(); + dstatus->m_format = (int)DecoderDataFormat::hex; + + if (_session->add_decoder(decoder, silent, dstatus)) + { + //crate item layer + QString protocolName = _protocol_combobox->currentText(); + ProtocolItemLayer *layer = new ProtocolItemLayer(_up_widget, protocolName, this); + _protocol_items.push_back(layer); + _up_layout->insertLayout(_protocol_items.size(), layer); + layer->m_decoderStatus = dstatus; + + //set current protocol format + string fmt = AppConfig::Instance().GetProtocolFormat(protocolName.toStdString()); + if (fmt != ""){ + layer->SetProtocolFormat(fmt.c_str()); + dstatus->m_format = DecoderDataFormat::Parse(fmt.c_str()); + } + + //progress connection + const auto &decode_sigs = _session->get_decode_signals(); + + connect(decode_sigs.back(), SIGNAL(decoded_progress(int)), this, SLOT(decoded_progress(int))); + + protocol_updated(); } } + + void ProtocolDock::on_del_all_protocol(){ + if (_protocol_items.size() == 0){ + MsgBox::Show(NULL, "No Protocol Analyzer to delete!", this); + return; + } -void ProtocolDock::rst_protocol() -{ - int rst_index = 0; - for (QVector ::const_iterator i = _set_button_list.begin(); - i != _set_button_list.end(); i++) { - QPushButton *button = qobject_cast(sender()); - if ((*i) == button) { - //pv::decoder::DemoConfig dlg(this, _session.get_device(), _protocol_index_list.at(rst_index)); - //dlg.set_config(_session.get_decode_probes(rst_index), _session.get_decode_options_index(rst_index)); - //if (dlg.exec()) { - //std::list _sel_probes = dlg.get_sel_probes(); - //QMap & _options = dlg.get_options(); - //QMap _options_index = dlg.get_options_index(); - - //_session.rst_protocol_analyzer(rst_index, _sel_probes, _options, _options_index); - //} - _session.rst_decoder(rst_index); - break; - } - rst_index++; + if (MsgBox::Confirm("Are you sure to remove all protocol analyzer?", this)){ + del_all_protocol(); } - protocol_updated(); -} - -void ProtocolDock::del_protocol() -{ - if (_del_all_button->isChecked()) { - _del_all_button->setChecked(false); - if (_hori_layout_list.size() > 0) { - int del_index = 0; - for (QVector ::const_iterator i = _hori_layout_list.begin(); - i != _hori_layout_list.end(); i++) { - _up_layout->removeItem((*i)); - delete (*i); - delete _del_button_list.at(del_index); - delete _set_button_list.at(del_index); - delete _protocol_label_list.at(del_index); - delete _progress_label_list.at(del_index); - - _session.remove_decode_signal(0); - del_index++; - } - _hori_layout_list.clear(); - _del_button_list.clear(); - _set_button_list.clear(); - _protocol_label_list.clear(); - _progress_label_list.clear(); - _protocol_index_list.clear(); - } else { - dialogs::DSMessageBox msg(NULL); - msg.mBox()->setText(tr("Protocol Analyzer")); - msg.mBox()->setInformativeText(tr("No Protocol Analyzer to delete!")); - msg.mBox()->setStandardButtons(QMessageBox::Ok); - msg.mBox()->setIcon(QMessageBox::Warning); - msg.exec(); - } - } else { - int del_index = 0; - for (QVector ::const_iterator i = _del_button_list.begin(); - i != _del_button_list.end(); i++) { - if ((*i)->isChecked()) { - _up_layout->removeItem(_hori_layout_list.at(del_index)); - - delete _hori_layout_list.at(del_index); - delete _del_button_list.at(del_index); - delete _set_button_list.at(del_index); - delete _protocol_label_list.at(del_index); - delete _progress_label_list.at(del_index); - - _hori_layout_list.remove(del_index); - _del_button_list.remove(del_index); - _set_button_list.remove(del_index); - _protocol_label_list.remove(del_index); - _progress_label_list.remove(del_index); - _protocol_index_list.remove(del_index); - - _session.remove_decode_signal(del_index); - break; - } - del_index++; - } - } - protocol_updated(); -} + } + void ProtocolDock::del_all_protocol() -{ - if (_hori_layout_list.size() > 0) { - int del_index = 0; - for (QVector ::const_iterator i = _hori_layout_list.begin(); - i != _hori_layout_list.end(); i++) { - _up_layout->removeItem((*i)); - delete (*i); - delete _del_button_list.at(del_index); - delete _set_button_list.at(del_index); - delete _protocol_label_list.at(del_index); - delete _progress_label_list.at(del_index); +{ + if (_protocol_items.size() > 0) + { + _session->clear_all_decoder(); - _session.remove_decode_signal(0); - del_index++; + for (auto it = _protocol_items.begin(); it != _protocol_items.end(); it++) + { + DESTROY_QT_LATER((*it)); //destory control } - _hori_layout_list.clear(); - _del_button_list.clear(); - _set_button_list.clear(); - _protocol_label_list.clear(); - _progress_label_list.clear(); - _protocol_index_list.clear(); + _protocol_items.clear(); protocol_updated(); } } @@ -481,53 +378,65 @@ void ProtocolDock::decoded_progress(int progress) int pg = 0; QString err=""; - const std::vector< boost::shared_ptr > decode_sigs( - _session.get_decode_signals()); + const auto &decode_sigs = _session->get_decode_signals(); int index = 0; - BOOST_FOREACH(boost::shared_ptr d, decode_sigs) { + + for(auto &d : decode_sigs) { pg = d->get_progress(); if (d->decoder()->out_of_memory()) err = tr("(Out of Memory)"); - QString progress_str = QString::number(pg) + "%" + err; - if (pg == 100) - _progress_label_list.at(index)->setStyleSheet("color:green;"); - else - _progress_label_list.at(index)->setStyleSheet("color:red;"); - _progress_label_list.at(index)->setText(progress_str); + + if (index < _protocol_items.size()) + { + ProtocolItemLayer &lay = *(_protocol_items.at(index)); + lay.SetProgress(pg, err); + + //when decode complete, check data format + if (pg == 100) + { + // bool flag = ((DecoderStatus*)lay.m_decoderStatus)->m_bNumerical; + // lay.LoadFormatSelect(!flag); + // QString &protocolName = lay.GetProtocolName(); + // lay.SetProtocolFormat(protocolName.toStdString().c_str()); + } + } + index++; } - if (pg == 0 || pg % 10 == 1) - update_model(); + + if (pg == 0 || pg % 10 == 1){ + update_model(); + } } void ProtocolDock::set_model() { pv::dialogs::ProtocolList *protocollist_dlg = new pv::dialogs::ProtocolList(this, _session); protocollist_dlg->exec(); - resize_table_view(_session.get_decoder_model()); - _model_proxy.setSourceModel(_session.get_decoder_model()); + resize_table_view(_session->get_decoder_model()); + _model_proxy.setSourceModel(_session->get_decoder_model()); search_done(); // clear mark_index of all DecoderStacks - const std::vector< boost::shared_ptr > decode_sigs( - _session.get_decode_signals()); - BOOST_FOREACH(boost::shared_ptr d, decode_sigs) { + const auto &decode_sigs = _session->get_decode_signals(); + + for(auto &d : decode_sigs) { d->decoder()->set_mark_index(-1); } } void ProtocolDock::update_model() { - pv::data::DecoderModel *decoder_model = _session.get_decoder_model(); - const std::vector< boost::shared_ptr > decode_sigs( - _session.get_decode_signals()); + pv::data::DecoderModel *decoder_model = _session->get_decoder_model(); + const auto &decode_sigs = _session->get_decode_signals(); + if (decode_sigs.size() == 0) decoder_model->setDecoderStack(NULL); else if (!decoder_model->getDecoderStack()) decoder_model->setDecoderStack(decode_sigs.at(0)->decoder()); else { unsigned int index = 0; - BOOST_FOREACH(const boost::shared_ptr d, decode_sigs) { + for(auto &d : decode_sigs) { if (d->decoder() == decoder_model->getDecoderStack()) { decoder_model->setDecoderStack(d->decoder()); break; @@ -561,18 +470,22 @@ void ProtocolDock::resize_table_view(data::DecoderModel* decoder_model) void ProtocolDock::item_clicked(const QModelIndex &index) { - pv::data::DecoderModel *decoder_model = _session.get_decoder_model(); - boost::shared_ptr decoder_stack = decoder_model->getDecoderStack(); + pv::data::DecoderModel *decoder_model = _session->get_decoder_model(); + + auto decoder_stack = decoder_model->getDecoderStack(); if (decoder_stack) { pv::data::decode::Annotation ann; if (decoder_stack->list_annotation(ann, index.column(), index.row())) { - const std::vector< boost::shared_ptr > decode_sigs( - _session.get_decode_signals()); - BOOST_FOREACH(boost::shared_ptr d, decode_sigs) { + const auto &decode_sigs = _session->get_decode_signals(); + + for(auto &d : decode_sigs) { d->decoder()->set_mark_index(-1); } + decoder_stack->set_mark_index((ann.start_sample()+ann.end_sample())/2); - _session.show_region(ann.start_sample(), ann.end_sample(), false); + _session->show_region(ann.start_sample(), ann.end_sample(), false); + + // qDebug()<resizeRowToContents(index.row()); @@ -619,7 +532,7 @@ void ProtocolDock::column_resize(int index, int old_size, int new_size) (void)index; (void)old_size; (void)new_size; - pv::data::DecoderModel *decoder_model = _session.get_decoder_model(); + pv::data::DecoderModel *decoder_model = _session->get_decoder_model(); if (decoder_model->getDecoderStack()) { int top_row = _table_view->rowAt(0); int bom_row = _table_view->rowAt(_table_view->height()); @@ -639,8 +552,9 @@ void ProtocolDock::export_table_view() void ProtocolDock::nav_table_view() { uint64_t row_index = 0; - pv::data::DecoderModel *decoder_model = _session.get_decoder_model(); - boost::shared_ptr decoder_stack = decoder_model->getDecoderStack(); + pv::data::DecoderModel *decoder_model = _session->get_decoder_model(); + + auto decoder_stack = decoder_model->getDecoderStack(); if (decoder_stack) { uint64_t offset = _view.offset() * (decoder_stack->samplerate() * _view.scale()); std::map rows = decoder_stack->get_rows_lshow(); @@ -659,9 +573,9 @@ void ProtocolDock::nav_table_view() pv::data::decode::Annotation ann; decoder_stack->list_annotation(ann, index.column(), index.row()); - const std::vector< boost::shared_ptr > decode_sigs( - _session.get_decode_signals()); - BOOST_FOREACH(boost::shared_ptr d, decode_sigs) { + const auto &decode_sigs = _session->get_decode_signals(); + + for(auto &d : decode_sigs) { d->decoder()->set_mark_index(-1); } decoder_stack->set_mark_index((ann.start_sample()+ann.end_sample())/2); @@ -686,8 +600,9 @@ void ProtocolDock::search_pre() int i = 0; uint64_t rowCount = _model_proxy.rowCount(); QModelIndex matchingIndex; - pv::data::DecoderModel *decoder_model = _session.get_decoder_model(); - boost::shared_ptr decoder_stack = decoder_model->getDecoderStack(); + pv::data::DecoderModel *decoder_model = _session->get_decoder_model(); + + auto decoder_stack = decoder_model->getDecoderStack(); do { _cur_search_index--; if (_cur_search_index <= -1 || _cur_search_index >= _model_proxy.rowCount()) @@ -703,10 +618,12 @@ void ProtocolDock::search_pre() bool ann_valid; while(i < _str_list.size()) { QString nxt = _str_list.at(i); + do { ann_valid = decoder_stack->list_annotation(ann, col, row); row++; - }while(ann_valid && (ann.type() < 100 || ann.type() > 999)); + }while(ann_valid && !ann.is_numberic()); + QString source = ann.annotations().at(0); if (ann_valid && source.contains(nxt)) i++; @@ -739,30 +656,45 @@ void ProtocolDock::search_nxt() _cur_search_index = -1; return; } + int i = 0; uint64_t rowCount = _model_proxy.rowCount(); QModelIndex matchingIndex; - pv::data::DecoderModel *decoder_model = _session.get_decoder_model(); - boost::shared_ptr decoder_stack = decoder_model->getDecoderStack(); + pv::data::DecoderModel *decoder_model = _session->get_decoder_model(); + auto decoder_stack = decoder_model->getDecoderStack(); + + if (decoder_stack == NULL){ + qDebug()<<"decoder_stack is null"; + return; + } + do { _cur_search_index++; if (_cur_search_index < 0 || _cur_search_index >= _model_proxy.rowCount()) _cur_search_index = 0; matchingIndex = _model_proxy.mapToSource(_model_proxy.index(floor(_cur_search_index),_model_proxy.filterKeyColumn())); - if (!decoder_stack || !matchingIndex.isValid()) + + if (!matchingIndex.isValid()) break; + + // qDebug()<<"row:"<list_annotation(ann, col, row); row++; - }while(ann_valid && (ann.type() < 100 || ann.type() > 999)); + }while(ann_valid && !ann.is_numberic()); + + auto strlist = ann.annotations(); QString source = ann.annotations().at(0); if (ann_valid && source.contains(nxt)) i++; @@ -786,7 +718,7 @@ void ProtocolDock::search_nxt() void ProtocolDock::search_done() { QString str = _search_edit->text().trimmed(); - QRegExp rx("(-)"); + QRegularExpression rx("(-)"); _str_list = str.split(rx); _model_proxy.setFilterFixedString(_str_list.first()); if (_str_list.size() > 1) @@ -806,8 +738,9 @@ void ProtocolDock::search_update() if (!_search_edited) return; - pv::data::DecoderModel *decoder_model = _session.get_decoder_model(); - boost::shared_ptr decoder_stack = decoder_model->getDecoderStack(); + pv::data::DecoderModel *decoder_model = _session->get_decoder_model(); + + auto decoder_stack = decoder_model->getDecoderStack(); if (!decoder_stack) return; @@ -833,9 +766,52 @@ void ProtocolDock::search_update() search_done(); } _search_edited = false; - //search_done(); } + //-------------------IProtocolItemLayerCallback +void ProtocolDock::OnProtocolSetting(void *handle){ + int dex = 0; + for (auto it = _protocol_items.begin(); it != _protocol_items.end(); it++){ + if ((*it) == handle){ + _session->rst_decoder(dex); + protocol_updated(); + break; + } + dex++; + } +} + +void ProtocolDock::OnProtocolDelete(void *handle){ + if (!MsgBox::Confirm("Are you sure to remove this protocol analyzer?", this)){ + return; + } + + int dex = 0; + for (auto it = _protocol_items.begin(); it != _protocol_items.end(); it++){ + if ((*it) == handle){ + DESTROY_QT_LATER(*it); + _protocol_items.remove(dex); + _session->remove_decoder(dex); + protocol_updated(); + break; + } + dex++; + } +} + +void ProtocolDock::OnProtocolFormatChanged(QString format, void *handle){ + for (auto it = _protocol_items.begin(); it != _protocol_items.end(); it++){ + if ((*it) == handle){ + QString &name = (*it)->GetProtocolName(); + AppConfig::Instance().SetProtocolFormat(name.toStdString(), format.toStdString()); + (*it)->m_decoderStatus->m_format = DecoderDataFormat::Parse(format.toStdString().c_str()); + protocol_updated(); + break; + } + } +} +//------------------------- + } // namespace dock } // namespace pv diff --git a/DSView/pv/dock/protocoldock.h b/DSView/pv/dock/protocoldock.h index f5bc4534..c01245f0 100755 --- a/DSView/pv/dock/protocoldock.h +++ b/DSView/pv/dock/protocoldock.h @@ -27,7 +27,6 @@ #include #include -#include #include #include #include @@ -38,14 +37,17 @@ #include #include -#include +#include #include "../data/decodermodel.h" +#include "protocolitemlayer.h" +#include "../ui/dscombobox.h" + namespace pv { class SigSession; - + namespace data { class DecoderModel; } @@ -55,8 +57,8 @@ class View; } namespace dock { - -class ProtocolDock : public QScrollArea + +class ProtocolDock : public QScrollArea,public IProtocolItemLayerCallback { Q_OBJECT @@ -64,12 +66,13 @@ public: static const uint64_t ProgressRows = 100000; public: - ProtocolDock(QWidget *parent, view::View &view, SigSession &session); + ProtocolDock(QWidget *parent, view::View &view, SigSession *session); ~ProtocolDock(); void del_all_protocol(); bool sel_protocol(QString name); void add_protocol(bool silent); + private: void changeEvent(QEvent *event); void retranslateUi(); @@ -79,16 +82,23 @@ protected: void paintEvent(QPaintEvent *); void resizeEvent(QResizeEvent *); +private: + //IProtocolItemLayerCallback + void OnProtocolSetting(void *handle); + void OnProtocolDelete(void *handle); + void OnProtocolFormatChanged(QString format, void *handle); + signals: void protocol_updated(); -private slots: - void add_protocol(); - void rst_protocol(); - void del_protocol(); - void decoded_progress(int progress); - void set_model(); +public slots: void update_model(); + +private slots: + void on_add_protocol(); + void on_del_all_protocol(); + void decoded_progress(int progress); + void set_model(); void export_table_view(); void nav_table_view(); void item_clicked(const QModelIndex &index); @@ -104,10 +114,10 @@ private: void resize_table_view(data::DecoderModel *decoder_model); private: - SigSession &_session; + SigSession *_session; view::View &_view; QSortFilterProxyModel _model_proxy; - double _cur_search_index; + int _cur_search_index; QStringList _str_list; QSplitter *_split_widget; @@ -125,22 +135,17 @@ private: QPushButton *_add_button; QPushButton *_del_all_button; - QComboBox *_protocol_combobox; - QVector _del_button_list; - QVector _set_button_list; - QVector _protocol_label_list; - QVector _progress_label_list; - QVector _protocol_index_list; - QVector _hori_layout_list; + DsComboBox *_protocol_combobox; + QVector _protocol_index_list; QVBoxLayout *_up_layout; + QVector _protocol_items; //protocol item layers QPushButton *_dn_set_button; QPushButton *_dn_save_button; QPushButton *_dn_nav_button; - QPushButton *_search_button; - mutable boost::mutex _search_mutex; + mutable std::mutex _search_mutex; bool _search_edited; bool _searching; diff --git a/DSView/pv/dock/protocolitemlayer.cpp b/DSView/pv/dock/protocolitemlayer.cpp new file mode 100644 index 00000000..863bbaa9 --- /dev/null +++ b/DSView/pv/dock/protocolitemlayer.cpp @@ -0,0 +1,150 @@ +/* + * This file is part of the DSView project. + * DSView is based on PulseView. + * + * Copyright (C) 2013 DreamSourceLab + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "protocolitemlayer.h" +#include "../dsvdef.h" +#include +#include "../config/appconfig.h" + +namespace pv { +namespace dock { + +ProtocolItemLayer::ProtocolItemLayer(QWidget *parent, QString protocolName, IProtocolItemLayerCallback *callback){ + assert(parent); + assert(callback); + + m_callback = callback; + _protocolName = protocolName; + m_bSetting = false; + + _protocol_label = new QLabel(parent); + _progress_label = new QLabel(parent); + _set_button = new QPushButton(parent); + _del_button = new QPushButton(parent); + _format_combox = new DsComboBox(parent); + + QString iconPath = GetIconPath(); + _del_button->setFlat(true); + _del_button->setIcon(QIcon(iconPath + "/del.svg")); + _set_button->setFlat(true); + _set_button->setIcon(QIcon(iconPath + "/gear.svg")); + _protocol_label->setText(protocolName); + + m_singleFlag = true; + m_decoderStatus = NULL; + + LoadFormatSelect(false); + + QHBoxLayout *hori_layout = this; + hori_layout->addWidget(_set_button); + hori_layout->addWidget(_del_button); + hori_layout->addWidget(_format_combox); + hori_layout->addWidget(_protocol_label); + hori_layout->addWidget(_progress_label); + + hori_layout->addStretch(1); + + connect(_del_button, SIGNAL(clicked()),this, SLOT(on_del_protocol())); + + connect(_set_button, SIGNAL(clicked()),this, SLOT(on_set_protocol())); + + connect(_format_combox, SIGNAL(currentIndexChanged(int)),this, SLOT(on_format_select_changed(int))); +} + +ProtocolItemLayer::~ProtocolItemLayer(){ + DESTROY_QT_OBJECT(_progress_label); + DESTROY_QT_OBJECT(_protocol_label); + DESTROY_QT_OBJECT(_set_button); + DESTROY_QT_OBJECT(_del_button); + DESTROY_QT_OBJECT(_format_combox); +} + + +//-------------control event +void ProtocolItemLayer::on_set_protocol() +{ + m_callback->OnProtocolSetting(this); +} + +void ProtocolItemLayer::on_del_protocol(){ + m_callback->OnProtocolDelete(this); +} + +void ProtocolItemLayer::on_format_select_changed(int index){ + if (index >= 0 && !m_bSetting){ + QString text = _format_combox->currentText(); + m_callback->OnProtocolFormatChanged(text, this); + } +} +//----------------- + + void ProtocolItemLayer::SetProgress(int progress, QString text){ + QString str = QString::number(progress) + "%" + text; + + if (progress == 100) + _progress_label->setStyleSheet("color:green;"); + else + _progress_label->setStyleSheet("color:red;"); + _progress_label->setText(str); + } + +void ProtocolItemLayer::ResetStyle(){ + QString iconPath = GetIconPath(); + _del_button->setIcon(QIcon(iconPath + "/del.svg")); + _set_button->setIcon(QIcon(iconPath + "/gear.svg")); +} + +void ProtocolItemLayer::LoadFormatSelect(bool bSingle) +{ + if (bSingle == m_singleFlag){ + return; + } + m_singleFlag = bSingle; + + m_bSetting = true; + _format_combox->clear(); + + if (!bSingle){ + _format_combox->addItem("hex"); + _format_combox->addItem("dec"); + _format_combox->addItem("oct"); + _format_combox->addItem("bin"); + } + _format_combox->addItem("ascii"); + + _format_combox->setCurrentIndex(0); + m_bSetting = false; +} + + void ProtocolItemLayer::SetProtocolFormat(const char *format) + { + assert(format); + + m_bSetting = true; + int dex = DecoderDataFormat::Parse(format); + if (dex < (int)_format_combox->count()){ + _format_combox->setCurrentIndex(dex); + } + m_bSetting = false; + } + +} //dock +} //pv diff --git a/DSView/pv/dock/protocolitemlayer.h b/DSView/pv/dock/protocolitemlayer.h new file mode 100644 index 00000000..3591cb9e --- /dev/null +++ b/DSView/pv/dock/protocolitemlayer.h @@ -0,0 +1,78 @@ +/* + * This file is part of the DSView project. + * DSView is based on PulseView. + * + * Copyright (C) 2013 DreamSourceLab + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#pragma once + +#include +#include +#include +#include +#include "../ui/dscombobox.h" + +class DecoderStatus; + +namespace pv{ +namespace dock{ + +class IProtocolItemLayerCallback + { + public: + virtual void OnProtocolSetting(void *handle)=0; + virtual void OnProtocolDelete(void *handle)=0; + virtual void OnProtocolFormatChanged(QString format, void *handle)=0; +}; + +class ProtocolItemLayer: public QHBoxLayout +{ + Q_OBJECT + +public: + ProtocolItemLayer(QWidget *parent, QString protocolName, IProtocolItemLayerCallback *callback); + ~ProtocolItemLayer(); + + void SetProgress(int progress, QString text); + void ResetStyle(); + void LoadFormatSelect(bool bSingle); + inline QString &GetProtocolName(){return _protocolName;} + void SetProtocolFormat(const char *format); + +private slots: + void on_set_protocol(); + void on_del_protocol(); + void on_format_select_changed(int index); + +public: + DecoderStatus *m_decoderStatus; //DecoderStatus + +private: + QLabel *_protocol_label; + QLabel *_progress_label; + QPushButton *_set_button; + QPushButton *_del_button; + DsComboBox *_format_combox; + IProtocolItemLayerCallback *m_callback; + QString _protocolName; + bool m_bSetting; + bool m_singleFlag; +}; + + } //dock +} //pv diff --git a/DSView/pv/dock/searchdock.cpp b/DSView/pv/dock/searchdock.cpp index 162b58a0..1d7cd1c3 100755 --- a/DSView/pv/dock/searchdock.cpp +++ b/DSView/pv/dock/searchdock.cpp @@ -32,16 +32,15 @@ #include "../dialogs/dsmessagebox.h" #include -#include -#include +#include #include #include #include #include #include -#include -#include +#include +#include "../config/appconfig.h" namespace pv { namespace dock { @@ -49,7 +48,7 @@ namespace dock { using namespace pv::view; using namespace pv::widgets; -SearchDock::SearchDock(QWidget *parent, View &view, SigSession &session) : +SearchDock::SearchDock(QWidget *parent, View &view, SigSession *session) : QWidget(parent), _session(session), _view(view) @@ -109,7 +108,7 @@ void SearchDock::retranslateUi() void SearchDock::reStyle() { - QString iconPath = ":/icons/" + qApp->property("Style").toString(); + QString iconPath = GetIconPath(); _pre_button.setIcon(QIcon(iconPath+"/pre.svg")); _nxt_button.setIcon(QIcon(iconPath+"/next.svg")); @@ -129,9 +128,9 @@ void SearchDock::on_previous() bool ret; int64_t last_pos; bool last_hit; - const boost::shared_ptr snapshot(_session.get_snapshot(SR_CHANNEL_LOGIC)); + const auto snapshot = _session->get_snapshot(SR_CHANNEL_LOGIC); assert(snapshot); - const boost::shared_ptr logic_snapshot = boost::dynamic_pointer_cast(snapshot); + const auto logic_snapshot = dynamic_cast(snapshot); if (!logic_snapshot || logic_snapshot->empty()) { dialogs::DSMessageBox msg(this); @@ -191,9 +190,9 @@ void SearchDock::on_next() { bool ret; int64_t last_pos; - const boost::shared_ptr snapshot(_session.get_snapshot(SR_CHANNEL_LOGIC)); + const auto snapshot = _session->get_snapshot(SR_CHANNEL_LOGIC); assert(snapshot); - const boost::shared_ptr logic_snapshot = boost::dynamic_pointer_cast(snapshot); + const auto logic_snapshot = dynamic_cast(snapshot); if (!logic_snapshot || logic_snapshot->empty()) { dialogs::DSMessageBox msg(this); @@ -262,7 +261,9 @@ void SearchDock::on_set() _search_value->setText(search_label); QFontMetrics fm = this->fontMetrics(); - _search_value->setFixedWidth(fm.width(search_label)+_search_button->width()+20); + //fm.width(search_label) + int tw = fm.boundingRect(search_label).width(); + _search_value->setFixedWidth(tw + _search_button->width()+20); if (new_pattern != _pattern) { _view.set_search_pos(_view.get_search_pos(), false); diff --git a/DSView/pv/dock/searchdock.h b/DSView/pv/dock/searchdock.h index 0f68daad..d53c261e 100755 --- a/DSView/pv/dock/searchdock.h +++ b/DSView/pv/dock/searchdock.h @@ -25,7 +25,6 @@ #include #include -#include #include #include #include @@ -43,6 +42,7 @@ #include #include "../widgets/fakelineedit.h" +#include "../ui/dscombobox.h" namespace pv { @@ -63,7 +63,7 @@ class SearchDock : public QWidget Q_OBJECT public: - SearchDock(QWidget *parent, pv::view::View &view, SigSession &session); + SearchDock(QWidget *parent, pv::view::View &view, SigSession *session); ~SearchDock(); void paintEvent(QPaintEvent *); @@ -78,7 +78,7 @@ public slots: void on_set(); private: - SigSession &_session; + SigSession *_session; view::View &_view; std::map _pattern; diff --git a/DSView/pv/dock/triggerdock.cpp b/DSView/pv/dock/triggerdock.cpp index 6c727e85..962f6a9f 100755 --- a/DSView/pv/dock/triggerdock.cpp +++ b/DSView/pv/dock/triggerdock.cpp @@ -29,24 +29,26 @@ #include #include #include -#include +#include #include #include +#include +#include -#include "libsigrok4DSL/libsigrok.h" +#include namespace pv { namespace dock { const int TriggerDock::MinTrigPosition = 1; -TriggerDock::TriggerDock(QWidget *parent, SigSession &session) : +TriggerDock::TriggerDock(QWidget *parent, SigSession *session) : QScrollArea(parent), _session(session) { _cur_ch_num = 16; - if (_session.get_device()) { - GVariant *gvar = _session.get_device()->get_config(NULL, NULL, SR_CONF_TOTAL_CH_NUM); + if (_session->get_device()) { + GVariant *gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_TOTAL_CH_NUM); if (gvar != NULL) { _cur_ch_num = g_variant_get_int16(gvar); g_variant_unref(gvar); @@ -69,7 +71,7 @@ TriggerDock::TriggerDock(QWidget *parent, SigSession &session) : _stages_label = new QLabel(_widget); _stages_label->setDisabled(true); - stages_comboBox = new QComboBox(_widget); + stages_comboBox = new DsComboBox(_widget); for (int i = 1; i <= TriggerStages; i++) stages_comboBox->addItem(QString::number(i)); //stages_comboBox->setCurrentIndex(stages_comboBox->count() - 1); @@ -160,7 +162,7 @@ void TriggerDock::retranslateUi() void TriggerDock::reStyle() { - //QString iconPath = ":/icons/" + qApp->property("Style").toString(); + } void TriggerDock::paintEvent(QPaintEvent *) @@ -180,9 +182,9 @@ void TriggerDock::simple_trigger() void TriggerDock::adv_trigger() { - if (_session.get_device()->name() == "DSLogic") { + if (_session->get_device()->name() == "DSLogic") { bool stream = false; - GVariant *gvar = _session.get_device()->get_config(NULL, NULL, SR_CONF_STREAM); + GVariant *gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_STREAM); if (gvar != NULL) { stream = g_variant_get_boolean(gvar); g_variant_unref(gvar); @@ -248,20 +250,20 @@ void TriggerDock::device_updated() bool stream = false; uint8_t maxRange; uint64_t sample_limits; - GVariant *gvar = _session.get_device()->get_config(NULL, NULL, SR_CONF_HW_DEPTH); + GVariant *gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_HW_DEPTH); if (gvar != NULL) { hw_depth = g_variant_get_uint64(gvar); g_variant_unref(gvar); - if (_session.get_device()->dev_inst()->mode == LOGIC) { + if (_session->get_device()->dev_inst()->mode == LOGIC) { - gvar = _session.get_device()->get_config(NULL, NULL, SR_CONF_STREAM); + gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_STREAM); if (gvar != NULL) { stream = g_variant_get_boolean(gvar); g_variant_unref(gvar); } - sample_limits = _session.get_device()->get_sample_limit(); + sample_limits = _session->get_device()->get_sample_limit(); if (stream) maxRange = 1; else if (hw_depth >= sample_limits) @@ -271,7 +273,7 @@ void TriggerDock::device_updated() _position_spinBox->setRange(MinTrigPosition, maxRange); _position_slider->setRange(MinTrigPosition, maxRange); - if (_session.get_device()->name().contains("virtual") || + if (_session->get_device()->name().contains("virtual") || stream) { _simple_radioButton->setChecked(true); simple_trigger(); @@ -279,7 +281,7 @@ void TriggerDock::device_updated() } } - gvar = _session.get_device()->get_config(NULL, NULL, SR_CONF_TOTAL_CH_NUM); + gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_TOTAL_CH_NUM); if (gvar != NULL) { int ch_num = g_variant_get_int16(gvar); g_variant_unref(gvar); @@ -564,10 +566,10 @@ void TriggerDock::setup_adv_tab() _stage_tabWidget->setUsesScrollButtons(false); const QString mask = "N N N N N N N N N N N N N N N N"; - QRegExp value_rx("[10XRFCxrfc ]+"); - QValidator *value_validator = new QRegExpValidator(value_rx, _stage_tabWidget); + QRegularExpression value_rx("[10XRFCxrfc ]+"); + QValidator *value_validator = new QRegularExpressionValidator(value_rx, _stage_tabWidget); for (int i = 0; i < TriggerStages; i++) { - QComboBox *_logic_comboBox = new QComboBox(_stage_tabWidget); + DsComboBox *_logic_comboBox = new DsComboBox(_stage_tabWidget); _logic_comboBox->addItem(tr("Or")); _logic_comboBox->addItem(tr("And")); _logic_comboBox->setCurrentIndex(1); @@ -584,7 +586,7 @@ void TriggerDock::setup_adv_tab() _count_spinBox->setRange(1, INT32_MAX); _count_spinBox->setButtonSymbols(QAbstractSpinBox::NoButtons); _count_spinBox_list.push_back(_count_spinBox); - QComboBox *_inv0_comboBox = new QComboBox(_stage_tabWidget); + DsComboBox *_inv0_comboBox = new DsComboBox(_stage_tabWidget); _inv0_comboBox->addItem(tr("==")); _inv0_comboBox->addItem(tr("!=")); _inv0_comboBox_list.push_back(_inv0_comboBox); @@ -596,7 +598,7 @@ void TriggerDock::setup_adv_tab() _value1_lineEdit->setInputMask(mask); _value1_lineEdit->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); _value1_lineEdit_list.push_back(_value1_lineEdit); - QComboBox *_inv1_comboBox = new QComboBox(_stage_tabWidget); + DsComboBox *_inv1_comboBox = new DsComboBox(_stage_tabWidget); _inv1_comboBox->addItem(tr("==")); _inv1_comboBox->addItem(tr("!=")); _inv1_comboBox_list.push_back(_inv1_comboBox); @@ -732,7 +734,7 @@ void TriggerDock::setup_adv_tab() _serial_edge_lineEdit->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); _serial_data_label = new QLabel(_serial_groupBox); - _serial_data_comboBox = new QComboBox(_serial_groupBox); + _serial_data_comboBox = new DsComboBox(_serial_groupBox); for(int i = 0; i < _cur_ch_num; i++) _serial_data_comboBox->addItem(QString::number(i)); @@ -744,7 +746,7 @@ void TriggerDock::setup_adv_tab() _serial_value_lineEdit->setInputMask(mask); _serial_value_lineEdit->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - _serial_bits_comboBox = new QComboBox(_serial_groupBox); + _serial_bits_comboBox = new DsComboBox(_serial_groupBox); for(int i = 1; i <= 16; i++) _serial_bits_comboBox->addItem(QString::number(i)); diff --git a/DSView/pv/dock/triggerdock.h b/DSView/pv/dock/triggerdock.h index 3dd19e68..eef9cab3 100755 --- a/DSView/pv/dock/triggerdock.h +++ b/DSView/pv/dock/triggerdock.h @@ -25,7 +25,6 @@ #include #include -#include #include #include #include @@ -43,6 +42,8 @@ #include +#include "../ui/dscombobox.h" + namespace pv { class SigSession; @@ -57,7 +58,7 @@ private: static const int MinTrigPosition; public: - TriggerDock(QWidget *parent, SigSession &session); + TriggerDock(QWidget *parent, SigSession *session); ~TriggerDock(); void paintEvent(QPaintEvent *); @@ -95,7 +96,7 @@ public slots: private: private: - SigSession &_session; + SigSession *_session; int _cur_ch_num; QWidget *_widget; @@ -108,20 +109,20 @@ private: QSlider *_position_slider; QLabel *_stages_label; - QComboBox *stages_comboBox; + DsComboBox *stages_comboBox; QTabWidget *_stage_tabWidget; QVector _stage_groupBox_list; QVector _mu_label_list; - QVector _logic_comboBox_list; + QVector _logic_comboBox_list; QVector _value0_lineEdit_list; QVector _value0_ext32_lineEdit_list; QVector _count_spinBox_list; - QVector _inv0_comboBox_list; + QVector _inv0_comboBox_list; QVector _value1_lineEdit_list; QVector _value1_ext32_lineEdit_list; - QVector _inv1_comboBox_list; + QVector _inv1_comboBox_list; QVector _contiguous_checkbox_list; QTabWidget *_adv_tabWidget; @@ -136,10 +137,10 @@ private: QLineEdit *_serial_edge_lineEdit; QLineEdit *_serial_edge_ext32_lineEdit; QLabel *_serial_data_label; - QComboBox *_serial_data_comboBox; + DsComboBox *_serial_data_comboBox; QLabel *_serial_value_label; QLineEdit *_serial_value_lineEdit; - QComboBox *_serial_bits_comboBox; + DsComboBox *_serial_bits_comboBox; QLabel *_serial_note_label; QLabel *_data_bits_label; diff --git a/DSView/pv/dstimer.cpp b/DSView/pv/dstimer.cpp new file mode 100644 index 00000000..e3bbaad2 --- /dev/null +++ b/DSView/pv/dstimer.cpp @@ -0,0 +1,49 @@ + +#include "dstimer.h" +#include + +DsTimer::DsTimer(){ + _binded = false; +} + + void DsTimer::on_timeout() + { + _call(); //call back + } + +void DsTimer::TimeOut(int millsec, CALLBACL_FUNC f) +{ + _call = f; + QTimer::singleShot(millsec, this, SLOT(on_timeout())); +} + +void DsTimer::SetCallback(CALLBACL_FUNC f) + { + assert(!_binded); + _binded = true; + + _call = f; + connect(&_timer, SIGNAL(timeout()), this, SLOT(on_timeout())); + } + + void DsTimer::Start(int millsec, CALLBACL_FUNC f) + { + assert(!_binded); + _binded = true; + + _call = f; + connect(&_timer, SIGNAL(timeout()), this, SLOT(on_timeout())); + _timer.start(millsec); + } + + void DsTimer::Start(int millsec) + { + //check if connectb + assert(_binded); + _timer.start(millsec); + } + + void DsTimer::Stop() + { + _timer.stop(); + } diff --git a/DSView/pv/dstimer.h b/DSView/pv/dstimer.h new file mode 100644 index 00000000..87c35f41 --- /dev/null +++ b/DSView/pv/dstimer.h @@ -0,0 +1,37 @@ + +#ifndef _DS_TIMER_H +#define _DS_TIMER_H + +#include +#include +#include + +typedef std::function CALLBACL_FUNC; + +class DsTimer : public QObject +{ + Q_OBJECT + +public: + DsTimer(); + + void TimeOut(int millsec, CALLBACL_FUNC f); + + void SetCallback(CALLBACL_FUNC f); + + void Start(int millsec, CALLBACL_FUNC f); + + void Start(int millsec); + + void Stop(); + +private slots: + void on_timeout(); + +private: + CALLBACL_FUNC _call; + QTimer _timer; + bool _binded; +}; + +#endif diff --git a/DSView/pv/dsvdef.cpp b/DSView/pv/dsvdef.cpp new file mode 100644 index 00000000..113cac13 --- /dev/null +++ b/DSView/pv/dsvdef.cpp @@ -0,0 +1,91 @@ +/* + * This file is part of the DSView project. + * DSView is based on PulseView. + * + * Copyright (C) 2012 Joel Holdsworth + * Copyright (C) 2013 DreamSourceLab + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "dsvdef.h" +#include + +#ifdef DS_DEBUG_TRACE +#include + void ds_print(const char *s){ + printf(s); + } +#endif + +#include + +#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) +#include +#else +#include +#endif + +namespace DecoderDataFormat +{ + int Parse(const char *name){ + if (strcmp(name, "dec") == 0){ + return (int)dec; + } + if (strcmp(name, "hex") == 0){ + return (int)hex; + } + if (strcmp(name, "oct") == 0){ + return (int)oct; + } + if (strcmp(name, "bin") == 0){ + return (int)bin; + } + if (strcmp(name, "ascii") == 0){ + return (int)ascii; + } + return (int)hex; + } +} + + +namespace app +{ + QWidget* get_app_window_instance(QWidget *ins, bool bSet){ + + static QWidget *g_ins = NULL; + if (bSet){ + g_ins = ins; + } + return g_ins; + } + + bool is_app_top_window(QWidget* w){ + QWidget *top =get_app_window_instance(NULL, NULL); + if (top && top == w){ + return true; + } + return false; + } + + void set_utf8(QTextStream &stream){ + #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) + stream.setEncoding(QStringConverter::Utf8); + #else + QTextCodec *code=QTextCodec::codecForName("UTF-8"); + stream.setCodec(code); + #endif + } +} diff --git a/DSView/pv/dsvdef.h b/DSView/pv/dsvdef.h new file mode 100644 index 00000000..13c61d51 --- /dev/null +++ b/DSView/pv/dsvdef.h @@ -0,0 +1,70 @@ +/* + * This file is part of the DSView project. + * DSView is based on PulseView. + * + * Copyright (C) 2012 Joel Holdsworth + * Copyright (C) 2013 DreamSourceLab + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#pragma once + +#include "../config.h" +#include + + +#ifdef DS_DEBUG_TRACE + void ds_print(const char *s); + + #define ds_debug(x) ds_print((x)) +#else + #define ds_debug(x) +#endif + +class QWidget; +class QTextStream; + +#define DESTROY_OBJECT(p) if((p)){delete (p); p = NULL;} +#define DESTROY_QT_OBJECT(p) if((p)){((p))->deleteLater(); p = NULL;} +#define DESTROY_QT_LATER(p) ((p))->deleteLater(); + +#define RELEASE_ARRAY(a) for (auto ptr : (a)){delete ptr;} (a).clear(); + +#define ABS_VAL(x) (x>0?x:-x) + +namespace DecoderDataFormat +{ + enum _data_format + { + hex=0, + dec=1, + oct=2, + bin=3, + ascii=4 + }; + + int Parse(const char *name); +} + +namespace app +{ + QWidget* get_app_window_instance(QWidget *ins, bool bSet); + + bool is_app_top_window(QWidget* w); + + void set_utf8(QTextStream &stream); +} + diff --git a/DSView/pv/eventobject.cpp b/DSView/pv/eventobject.cpp new file mode 100644 index 00000000..d8671fa3 --- /dev/null +++ b/DSView/pv/eventobject.cpp @@ -0,0 +1,6 @@ + +#include "eventobject.h" + +EventObject::EventObject(){ + +} \ No newline at end of file diff --git a/DSView/pv/eventobject.h b/DSView/pv/eventobject.h new file mode 100644 index 00000000..770b884d --- /dev/null +++ b/DSView/pv/eventobject.h @@ -0,0 +1,55 @@ + +/* + * This file is part of the DSView project. + * DSView is based on PulseView. + * + * Copyright (C) 2012 Joel Holdsworth + * Copyright (C) 2013 DreamSourceLab + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef _EVENT_OBJECT_H +#define _EVENT_OBJECT_H + +#include + +class EventObject : public QObject +{ + Q_OBJECT + +public: + EventObject(); + + +signals: + void show_error(QString error); + void capture_state_changed(int state); + void data_updated(); + void device_attach(); + void device_detach(); + + void session_error(); + void signals_changed(); + void receive_trigger(quint64 trigger_pos); + void frame_ended(); + void frame_began(); + + void decode_done(); + void receive_data_len(quint64 len); + void cur_snap_samplerate_changed(); +}; + +#endif \ No newline at end of file diff --git a/DSView/extdef.h b/DSView/pv/extdef.h similarity index 100% rename from DSView/extdef.h rename to DSView/pv/extdef.h diff --git a/DSView/pv/interface/icallbacks.h b/DSView/pv/interface/icallbacks.h new file mode 100644 index 00000000..0fca6f66 --- /dev/null +++ b/DSView/pv/interface/icallbacks.h @@ -0,0 +1,43 @@ + +#ifndef _I_CALLBACKS_ +#define _I_CALLBACKS_ + +class ISessionCallback +{ +public: + virtual void show_error(QString error)=0; + virtual void session_error()=0; + virtual void capture_state_changed(int state)=0; + virtual void device_attach()=0; + virtual void device_detach()=0; + + virtual void session_save()=0; + virtual void data_updated()=0; + virtual void repeat_resume()=0; + virtual void update_capture()=0; + virtual void cur_snap_samplerate_changed()=0; + + virtual void device_setted()=0; + virtual void signals_changed()=0; + virtual void receive_trigger(quint64 trigger_pos)=0; + virtual void frame_ended()=0; + virtual void frame_began()=0; + + virtual void show_region(uint64_t start, uint64_t end, bool keep)=0; + virtual void show_wait_trigger()=0; + virtual void repeat_hold(int percent)=0; + virtual void decode_done()=0; + virtual void receive_data_len(quint64 len)=0; + + virtual void receive_header()=0; + virtual void data_received()=0; + +}; + +class ISessionDataGetter +{ +public: + virtual bool genSessionData(std::string &str) = 0; +}; + +#endif diff --git a/libsigrokdecode4DSL/tests/lib.h b/DSView/pv/interface/uicallback.h old mode 100755 new mode 100644 similarity index 56% rename from libsigrokdecode4DSL/tests/lib.h rename to DSView/pv/interface/uicallback.h index a4c1dd6b..58c2394c --- a/libsigrokdecode4DSL/tests/lib.h +++ b/DSView/pv/interface/uicallback.h @@ -1,7 +1,9 @@ + /* - * This file is part of the libsigrokdecode project. + * This file is part of the DSView project. + * DSView is based on PulseView. * - * Copyright (C) 2013 Uwe Hermann + * Copyright (C) 2014 Joel Holdsworth * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -14,18 +16,19 @@ * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License - * along with this program; if not, see . + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#ifndef LIBSIGROKDECODE_TESTS_LIB_H -#define LIBSIGROKDECODE_TESTS_LIB_H +#pragma once -void srdtest_setup(void); -void srdtest_teardown(void); +class IDlgCallback +{ +public: + virtual void OnDlgResult(bool bYes)=0; +}; -Suite *suite_core(void); -Suite *suite_decoder(void); -Suite *suite_inst(void); -Suite *suite_session(void); - -#endif +class IMainForm{ +public: + virtual void switchLanguage(int language)=0; +}; diff --git a/DSView/pv/mainframe.cpp b/DSView/pv/mainframe.cpp old mode 100755 new mode 100644 index 4ed79087..adab48f6 --- a/DSView/pv/mainframe.cpp +++ b/DSView/pv/mainframe.cpp @@ -36,20 +36,31 @@ #include #include #include -#include #include #include -#include -#include +#include #include +#include +#include +#include + +#include "dsvdef.h" +#include "config/appconfig.h" +#include "ui/msgbox.h" #include namespace pv { -MainFrame::MainFrame(DeviceManager &device_manager, - const char *open_file_name) +MainFrame::MainFrame() { + _layout = NULL; + _bDraging = false; + _hit_border = None; + _freezing = false; + _titleBar = NULL; + _mainWindow = NULL; + setAttribute(Qt::WA_TranslucentBackground); // Make this a borderless window which can't // be resized or moved via the window system @@ -58,34 +69,27 @@ MainFrame::MainFrame(DeviceManager &device_manager, #else setWindowFlags(Qt::Window | Qt::FramelessWindowHint | Qt::WindowSystemMenuHint); #endif + setMinimumHeight(minHeight); setMinimumWidth(minWidth); - //resize(1024, 768); - + // Set the window icon QIcon icon; - icon.addFile(QString::fromUtf8(":/icons/logo.svg"), - QSize(), QIcon::Normal, QIcon::Off); + icon.addFile(QString::fromUtf8(":/icons/logo.svg"), QSize(), QIcon::Normal, QIcon::Off); setWindowIcon(icon); - _moving = false; - _draging = false; - _startPos = None; - _freezing = false; - _minimized = false; - + app::get_app_window_instance(this, true); + // Title _titleBar = new toolbars::TitleBar(true, this); - _titleBar->installEventFilter(this); - + // MainWindow - _mainWindow = new MainWindow(device_manager, open_file_name, this); + _mainWindow = new MainWindow(this); _mainWindow->setWindowFlags(Qt::Widget); - _titleBar->setTitle(_mainWindow->windowTitle()); QVBoxLayout *vbox = new QVBoxLayout(); - vbox->setMargin(0); + vbox->setContentsMargins(0,0,0,0); vbox->setSpacing(0); vbox->addWidget(_titleBar); vbox->addWidget(_mainWindow); @@ -118,8 +122,8 @@ MainFrame::MainFrame(DeviceManager &device_manager, _bottom_right->installEventFilter(this); _layout = new QGridLayout(this); - _layout->setMargin(0); _layout->setSpacing(0); + _layout->setContentsMargins(0,0,0,0); _layout->addWidget(_top_left, 0, 0); _layout->addWidget(_top, 0, 1); _layout->addWidget(_top_right, 0, 2); @@ -130,27 +134,17 @@ MainFrame::MainFrame(DeviceManager &device_manager, _layout->addWidget(_bottom, 2, 1); _layout->addWidget(_bottom_right, 2, 2); - connect(&_timer, SIGNAL(timeout()), this, SLOT(unfreezing())); - //readSettings(); + connect(&_timer, SIGNAL(timeout()), this, SLOT(unfreezing())); } - -void MainFrame::changeEvent(QEvent* event) -{ - QFrame::changeEvent(event); - QWindowStateChangeEvent* win_event = static_cast< QWindowStateChangeEvent* >(event); - if(win_event->type() == QEvent::WindowStateChange) { - if (win_event->oldState() & Qt::WindowMinimized) { - if (_minimized) { - readSettings(); - _minimized = false; - } - } - } -} - + void MainFrame::resizeEvent(QResizeEvent *event) { QFrame::resizeEvent(event); + + if (_layout == NULL){ + return; + } + if (isMaximized()) { hide_border(); } else { @@ -185,7 +179,7 @@ void MainFrame::hide_border() } void MainFrame::show_border() -{ +{ _top_left->setVisible(true); _top_right->setVisible(true); _top->setVisible(true); @@ -198,19 +192,18 @@ void MainFrame::show_border() void MainFrame::showNormal() { - show_border(); + show_border(); QFrame::showNormal(); } void MainFrame::showMaximized() -{ +{ hide_border(); QFrame::showMaximized(); } void MainFrame::showMinimized() -{ - _minimized = true; +{ writeSettings(); QFrame::showMinimized(); } @@ -224,101 +217,136 @@ bool MainFrame::eventFilter(QObject *object, QEvent *event) int newLeft; int newTop; - if (type == QEvent::MouseMove && !isMaximized()) { - if (!(mouse_event->buttons() || Qt::NoButton)) { - if (object == _top_left) { - _startPos = TopLeft; + if (type != QEvent::MouseMove + && type != QEvent::MouseButtonPress + && type != QEvent::MouseButtonRelease + && type != QEvent::Leave){ + return QFrame::eventFilter(object, event); + } + + //when window is maximized, or is moving, call return + if (isMaximized() || _titleBar->IsMoving()){ + return QFrame::eventFilter(object, event); + } + + if (!_bDraging && type == QEvent::MouseMove && (!(mouse_event->buttons() | Qt::NoButton))){ + if (object == _top_left) { + _hit_border = TopLeft; setCursor(Qt::SizeFDiagCursor); } else if (object == _bottom_right) { - _startPos = BottomRight; + _hit_border = BottomRight; setCursor(Qt::SizeFDiagCursor); } else if (object == _top_right) { - _startPos = TopRight; + _hit_border = TopRight; setCursor(Qt::SizeBDiagCursor); } else if (object == _bottom_left) { - _startPos = BottomLeft; + _hit_border = BottomLeft; setCursor(Qt::SizeBDiagCursor); } else if (object == _left) { - _startPos = Left; + _hit_border = Left; setCursor(Qt::SizeHorCursor); } else if (object == _right) { - _startPos = Right; + _hit_border = Right; setCursor(Qt::SizeHorCursor); } else if (object == _bottom) { - _startPos = Bottom; + _hit_border = Bottom; setCursor(Qt::SizeVerCursor); } else if (object == _top) { - _startPos = Top; + _hit_border = Top; setCursor(Qt::SizeVerCursor); } else { - _startPos = None; + _hit_border = None; setCursor(Qt::ArrowCursor); } - } else if(mouse_event->buttons().testFlag(Qt::LeftButton)) { - if (_moving) { - this->move(mouse_event->globalPos() - _lastMousePosition); - } else if (!_freezing) { - switch (_startPos) { + + return QFrame::eventFilter(object, event); + } + + if (type == QEvent::MouseMove) { + +#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) + int x0 = (int)mouse_event->globalPosition().x(); + int y0 = (int)mouse_event->globalPosition().y(); +#else + int x0 = mouse_event->globalX(); + int y0 = mouse_event->globalY(); +#endif + + if(mouse_event->buttons().testFlag(Qt::LeftButton)) { + if (!_freezing) { + switch (_hit_border) { case TopLeft: - newWidth = std::max(_dragStartGeometry.right() - mouse_event->globalX(), minimumWidth()); - newHeight = std::max(_dragStartGeometry.bottom() - mouse_event->globalY(), minimumHeight()); + newWidth = std::max(_dragStartGeometry.right() - x0, minimumWidth()); + newHeight = std::max(_dragStartGeometry.bottom() - y0, minimumHeight()); newLeft = geometry().left(); newTop = geometry().top(); if (newWidth > minimumWidth()) - newLeft = mouse_event->globalX(); + newLeft = x0; if (newHeight > minimumHeight()) - newTop = mouse_event->globalY(); - setGeometry(newLeft, newTop, - newWidth, newHeight); + newTop = y0; + setGeometry(newLeft, newTop, newWidth, newHeight); + saveWindowRegion(); break; + case BottomLeft: - newWidth = std::max(_dragStartGeometry.right() - mouse_event->globalX(), minimumWidth()); - newHeight = std::max(mouse_event->globalY() - _dragStartGeometry.top(), minimumHeight()); + newWidth = std::max(_dragStartGeometry.right() - x0, minimumWidth()); + newHeight = std::max(y0 - _dragStartGeometry.top(), minimumHeight()); newLeft = geometry().left(); if (newWidth > minimumWidth()) - newLeft = mouse_event->globalX(); - setGeometry(newLeft, _dragStartGeometry.top(), - newWidth, newHeight); + newLeft = x0; + setGeometry(newLeft, _dragStartGeometry.top(), newWidth, newHeight); + saveWindowRegion(); break; + case TopRight: - newWidth = std::max(mouse_event->globalX() - _dragStartGeometry.left(), minimumWidth()); - newHeight = std::max(_dragStartGeometry.bottom() - mouse_event->globalY(), minimumHeight()); + newWidth = std::max(x0 - _dragStartGeometry.left(), minimumWidth()); + newHeight = std::max(_dragStartGeometry.bottom() - y0, minimumHeight()); newTop = geometry().top(); if (newHeight > minimumHeight()) - newTop = mouse_event->globalY(); - setGeometry(_dragStartGeometry.left(), newTop, - newWidth, newHeight); + newTop = y0; + setGeometry(_dragStartGeometry.left(), newTop, newWidth, newHeight); + saveWindowRegion(); break; + case BottomRight: - newWidth = std::max(mouse_event->globalX() - _dragStartGeometry.left(), minimumWidth()); - newHeight = std::max(mouse_event->globalY() - _dragStartGeometry.top(), minimumHeight()); - setGeometry(_dragStartGeometry.left(), _dragStartGeometry.top(), - newWidth, newHeight); + newWidth = std::max(x0 - _dragStartGeometry.left(), minimumWidth()); + newHeight = std::max(y0 - _dragStartGeometry.top(), minimumHeight()); + setGeometry(_dragStartGeometry.left(), _dragStartGeometry.top(), newWidth, newHeight); + saveWindowRegion(); break; + case Left: - newWidth = _dragStartGeometry.right() - mouse_event->globalX(); - if (newWidth > minimumWidth()) - setGeometry(mouse_event->globalX(), _dragStartGeometry.top(), - newWidth, height()); + newWidth = _dragStartGeometry.right() - x0; + if (newWidth > minimumWidth()){ + setGeometry(x0, _dragStartGeometry.top(), newWidth, height()); + saveWindowRegion(); + } break; + case Right: - newWidth = mouse_event->globalX() - _dragStartGeometry.left(); - if (newWidth > minimumWidth()) - setGeometry(_dragStartGeometry.left(), _dragStartGeometry.top(), - newWidth, height()); + newWidth = x0 - _dragStartGeometry.left(); + if (newWidth > minimumWidth()){ + setGeometry(_dragStartGeometry.left(), _dragStartGeometry.top(), newWidth, height()); + saveWindowRegion(); + } break; + case Top: - newHeight = _dragStartGeometry.bottom() - mouse_event->globalY(); - if (newHeight > minimumHeight()) - setGeometry(_dragStartGeometry.left(), mouse_event->globalY(), - width(), newHeight); + newHeight = _dragStartGeometry.bottom() - y0; + if (newHeight > minimumHeight()){ + setGeometry(_dragStartGeometry.left(), y0,width(), newHeight); + saveWindowRegion(); + } break; + case Bottom: - newHeight = mouse_event->globalY() - _dragStartGeometry.top(); - if (newHeight > minimumHeight()) - setGeometry(_dragStartGeometry.left(), _dragStartGeometry.top(), - width(), newHeight); + newHeight = y0 - _dragStartGeometry.top(); + if (newHeight > minimumHeight()){ + setGeometry(_dragStartGeometry.left(), _dragStartGeometry.top(), width(), newHeight); + saveWindowRegion(); + } break; + default: break; } @@ -326,75 +354,86 @@ bool MainFrame::eventFilter(QObject *object, QEvent *event) } return true; } - } else if (type == QEvent::MouseButtonPress) { - if (mouse_event->button() == Qt::LeftButton) - if (_titleBar->rect().contains(mouse_event->pos()) && - _startPos == None) { - _moving = true; - _lastMousePosition = mouse_event->pos() + - //QPoint(Margin, Margin) + - QPoint(geometry().left() - frameGeometry().left(), frameGeometry().right() - geometry().right()); - } - if (_startPos != None) - _draging = true; + } + else if (type == QEvent::MouseButtonPress) { + if (mouse_event->button() == Qt::LeftButton) + if (_hit_border != None) + _bDraging = true; _timer.start(50); _dragStartGeometry = geometry(); - } else if (type == QEvent::MouseButtonRelease) { - if (mouse_event->button() == Qt::LeftButton) { - _moving = false; - _draging = false; + } + else if (type == QEvent::MouseButtonRelease) { + if (mouse_event->button() == Qt::LeftButton) { + _bDraging = false; _timer.stop(); } - } else if (!_draging && type == QEvent::Leave) { - _startPos = None; + } else if (!_bDraging && type == QEvent::Leave) { + _hit_border = None; setCursor(Qt::ArrowCursor); - } - - return QObject::eventFilter(object, event); + } + + + return QFrame::eventFilter(object, event); } -void MainFrame::writeSettings() -{ - QSettings settings(QApplication::organizationName(), QApplication::applicationName()); + void MainFrame::saveWindowRegion() + { + AppConfig &app = AppConfig::Instance(); + QRect rc = geometry(); + app._frameOptions.left = rc.left(); + app._frameOptions.top = rc.top(); + app._frameOptions.right = rc.right(); + app._frameOptions.bottom = rc.bottom(); + } - settings.beginGroup("MainFrame"); - settings.setValue("style", qApp->property("Style").toString()); - settings.setValue("language", qApp->property("Language").toInt()); - settings.setValue("geometry", saveGeometry()); - settings.setValue("isMax", isMaximized()); - settings.endGroup(); +void MainFrame::writeSettings() +{ + AppConfig &app = AppConfig::Instance(); + app._frameOptions.isMax = isMaximized(); + + if (!isMaximized()){ + saveWindowRegion(); + } + + app.SaveFrame(); } void MainFrame::readSettings() { - QSettings settings(QApplication::organizationName(), QApplication::applicationName()); + if (_layout == NULL) + return; - settings.beginGroup("MainFrame"); - bool isMax = settings.value("isMax", false).toBool(); - const QByteArray geometry = settings.value("geometry", QByteArray()).toByteArray(); - // defaut language - if (settings.contains("language")) { - _mainWindow->switchLanguage(settings.value("language").toInt()); - } else { - QLocale locale; - _mainWindow->switchLanguage(locale.language()); - } - settings.endGroup(); + AppConfig &app = AppConfig::Instance(); + + if (app._frameOptions.language > 0){ + _mainWindow->switchLanguage(app._frameOptions.language); + } - if (geometry.isEmpty()) { + if (app._frameOptions.right == 0) { QScreen *screen=QGuiApplication::primaryScreen (); const QRect availableGeometry = screen->availableGeometry(); resize(availableGeometry.width() / 2, availableGeometry.height() / 1.5); const int origX = std::max(0, (availableGeometry.width() - width()) / 2); const int origY = std::max(0, (availableGeometry.height() - height()) / 2); move(origX, origY); + } else { - restoreGeometry(geometry); + if (app._frameOptions.isMax){ + showMaximized(); //show max by system api + } + else{ + int left = app._frameOptions.left; + int top = app._frameOptions.top; + int right = app._frameOptions.right; + int bottom = app._frameOptions.bottom; + resize(right-left, bottom-top); + move(left, top); + } } // restore dockwidgets _mainWindow->restore_dock(); - _titleBar->setRestoreButton(isMax); + _titleBar->setRestoreButton(app._frameOptions.isMax); } void MainFrame::setTaskbarProgress(int progress) @@ -404,18 +443,25 @@ void MainFrame::setTaskbarProgress(int progress) void MainFrame::show_doc() { - const QString DOC_KEY("ShowDocuments"); - QSettings settings(QApplication::organizationName(), QApplication::applicationName()); - if (!settings.contains(DOC_KEY)) { - dialogs::DSDialog dlg(this); + AppConfig &app = AppConfig::Instance(); + int lan = app._frameOptions.language; + + if (app._userHistory.showDocuments) { + dialogs::DSDialog dlg(this, true); dlg.setTitle(tr("Document")); + QString path = GetAppDataDir() + "/showDoc" + QString::number(lan)+ ".png"; + if (!QFile::exists(path)){ + path = ":/icons/showDoc"+QString::number(lan)+".png"; + } + QLabel tipsLabel; - tipsLabel.setPixmap(QPixmap(":/icons/showDoc"+QString::number(_mainWindow->language())+".png")); + tipsLabel.setPixmap(path); + QMessageBox msg; msg.setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint | Qt::WindowSystemMenuHint); msg.setContentsMargins(0, 0, 0, 0); - connect(&msg, SIGNAL(buttonClicked(QAbstractButton*)), &dlg, SLOT(accept())); + QPushButton *noMoreButton = msg.addButton(tr("Not Show Again"), QMessageBox::ActionRole); msg.addButton(tr("Ignore"), QMessageBox::ActionRole); QPushButton *openButton = msg.addButton(tr("Open"), QMessageBox::ActionRole); @@ -426,13 +472,17 @@ void MainFrame::show_doc() layout.setContentsMargins(0, 0, 0, 0); dlg.layout()->addLayout(&layout); + connect(&msg, SIGNAL(buttonClicked(QAbstractButton*)), &dlg, SLOT(accept())); + dlg.exec(); if (msg.clickedButton() == openButton) { _mainWindow->openDoc(); } - if (msg.clickedButton() == noMoreButton) - settings.setValue(DOC_KEY, false); + if (msg.clickedButton() == noMoreButton){ + app._userHistory.showDocuments = false; + app.SaveHistory(); + } } } diff --git a/DSView/pv/mainframe.h b/DSView/pv/mainframe.h index 615dd3f1..25b8df4b 100755 --- a/DSView/pv/mainframe.h +++ b/DSView/pv/mainframe.h @@ -30,8 +30,7 @@ #include namespace pv { - -class DeviceManager; + class MainWindow; namespace toolbars { @@ -66,13 +65,11 @@ public: }borderTypes; public: - MainFrame(DeviceManager &device_manager, - const char *open_file_name = NULL); + MainFrame(); void readSettings(); -protected: - void changeEvent(QEvent* event); +protected: void resizeEvent(QResizeEvent *event); void closeEvent(QCloseEvent *event); bool eventFilter(QObject *object, QEvent *event); @@ -88,8 +85,8 @@ public slots: private: void hide_border(); void show_border(); - void writeSettings(); + void saveWindowRegion(); private: toolbars::TitleBar *_titleBar; @@ -104,15 +101,12 @@ private: widgets::Border *_top_right; widgets::Border *_bottom_left; widgets::Border *_bottom_right; - - bool _moving; - bool _draging; - QPoint _lastMousePosition; - QRect _dragStartGeometry; - int _startPos; - QTimer _timer; - bool _freezing; - bool _minimized; + + bool _bDraging; + QRect _dragStartGeometry; + int _hit_border; + QTimer _timer; + bool _freezing; }; } // namespace pv diff --git a/DSView/pv/mainwindow.cpp b/DSView/pv/mainwindow.cpp old mode 100755 new mode 100644 index 2fea92dd..c6522eab --- a/DSView/pv/mainwindow.cpp +++ b/DSView/pv/mainwindow.cpp @@ -21,17 +21,8 @@ */ -#ifdef ENABLE_DECODE -#include -#include "dock/protocoldock.h" -#endif - -#include -#include -#include - + #include -#include #include #include #include @@ -39,15 +30,21 @@ #include #include #include -#include -#include -#include -#include +#include +#include #include #include #include #include #include +#include +#include +#include +#include + +#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) +#include +#endif #include "mainwindow.h" @@ -75,6 +72,7 @@ #include "dock/dsotriggerdock.h" #include "dock/measuredock.h" #include "dock/searchdock.h" +#include "dock/protocoldock.h" #include "view/view.h" #include "view/trace.h" @@ -89,39 +87,35 @@ #include #include #include -#include - -using boost::shared_ptr; -using boost::dynamic_pointer_cast; -using std::list; -using std::vector; +#include "ui/msgbox.h" +#include "config/appconfig.h" +#include "appcontrol.h" +#include "dsvdef.h" +#include "appcontrol.h" + namespace pv { -MainWindow::MainWindow(DeviceManager &device_manager, - const char *open_file_name, - QWidget *parent) : +MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), - _device_manager(device_manager), - _session(device_manager), _hot_detach(false), _msg(NULL) { + _control = AppControl::Instance(); + _control->GetSession()->set_callback(this); + _bFirstLoad = true; + setup_ui(); - if (open_file_name) { - qDebug("Open file: %s", open_file_name); - const QString s(QString::fromUtf8(open_file_name)); - QMetaObject::invokeMethod(this, "load_file", - Qt::QueuedConnection, - Q_ARG(QString, s)); - } + + setContextMenuPolicy(Qt::NoContextMenu); } void MainWindow::setup_ui() -{ +{ + SigSession *_session = _control->GetSession(); + setObjectName(QString::fromUtf8("MainWindow")); setContentsMargins(0,0,0,0); - layout()->setMargin(0); layout()->setSpacing(0); // Setup the central widget @@ -140,34 +134,7 @@ void MainWindow::setup_ui() _file_bar->setObjectName("file_bar"); _logo_bar = new toolbars::LogoBar(_session, this); _logo_bar->setObjectName("logo_bar"); - - connect(_trig_bar, SIGNAL(on_protocol(bool)), this, - SLOT(on_protocol(bool))); - connect(_trig_bar, SIGNAL(on_trigger(bool)), this, - SLOT(on_trigger(bool))); - connect(_trig_bar, SIGNAL(on_measure(bool)), this, - SLOT(on_measure(bool))); - connect(_trig_bar, SIGNAL(on_search(bool)), this, - SLOT(on_search(bool))); - connect(_trig_bar, SIGNAL(setTheme(QString)), this, - SLOT(switchTheme(QString))); - connect(_file_bar, SIGNAL(load_file(QString)), this, - SLOT(load_file(QString))); - connect(_file_bar, SIGNAL(on_save()), this, - SLOT(on_save())); - connect(_file_bar, SIGNAL(on_export()), this, - SLOT(on_export())); - connect(_file_bar, SIGNAL(on_screenShot()), this, - SLOT(on_screenShot()), Qt::QueuedConnection); - connect(_file_bar, SIGNAL(load_session(QString)), this, - SLOT(load_session(QString))); - connect(_file_bar, SIGNAL(store_session(QString)), this, - SLOT(store_session(QString))); - connect(_logo_bar, SIGNAL(setLanguage(int)), this, - SLOT(switchLanguage(int))); - connect(_logo_bar, SIGNAL(openDoc()), this, - SLOT(openDoc())); - + // trigger dock _trigger_dock=new QDockWidget(tr("Trigger Setting..."),this); _trigger_dock->setObjectName("trigger_dock"); @@ -189,49 +156,24 @@ void MainWindow::setup_ui() // Setup _view widget _view = new pv::view::View(_session, _sampling_bar, this); _vertical_layout->addWidget(_view); - - connect(_sampling_bar, SIGNAL(device_selected()), this, - SLOT(update_device_list())); - connect(_sampling_bar, SIGNAL(device_updated()), this, - SLOT(reload())); - connect(_sampling_bar, SIGNAL(run_stop()), this, - SLOT(run_stop())); - connect(_sampling_bar, SIGNAL(instant_stop()), this, - SLOT(instant_stop())); - connect(_sampling_bar, SIGNAL(duration_changed()), _trigger_widget, - SLOT(device_updated())); - connect(_sampling_bar, SIGNAL(duration_changed()), _view, - SLOT(timebase_changed())); - connect(_sampling_bar, SIGNAL(show_calibration()), _view, - SLOT(show_calibration())); - connect(_trig_bar, SIGNAL(show_lissajous(bool)), _view, - SLOT(show_lissajous(bool))); - connect(_dso_trigger_widget, SIGNAL(set_trig_pos(int)), _view, - SLOT(set_trig_pos(int))); - connect(_view, SIGNAL(auto_trig(int)), _dso_trigger_widget, - SLOT(auto_trig(int))); - + setIconSize(QSize(40,40)); addToolBar(_sampling_bar); addToolBar(_trig_bar); addToolBar(_file_bar); addToolBar(_logo_bar); - - // Setup the dockWidget -#ifdef ENABLE_DECODE - // protocol dock + + //Setup the dockWidget _protocol_dock=new QDockWidget(tr("Protocol"),this); _protocol_dock->setObjectName("protocol_dock"); _protocol_dock->setFeatures(QDockWidget::DockWidgetMovable); _protocol_dock->setAllowedAreas(Qt::RightDockWidgetArea); - _protocol_dock->setVisible(false); - //dock::ProtocolDock *_protocol_widget = new dock::ProtocolDock(_protocol_dock, _session); + _protocol_dock->setVisible(false); _protocol_widget = new dock::ProtocolDock(_protocol_dock, *_view, _session); _protocol_dock->setWidget(_protocol_widget); - qDebug() << "Protocol decoder enabled!\n"; + //qDebug() << "Protocol decoder enabled!\n"; + - connect(_protocol_widget, SIGNAL(protocol_updated()), _view, SLOT(signals_changed())); -#endif // measure dock _measure_dock=new QDockWidget(tr("Measurement"),this); _measure_dock->setObjectName("measure_dock"); @@ -251,9 +193,9 @@ void MainWindow::setup_ui() _search_widget = new dock::SearchDock(_search_dock, *_view, _session); _search_dock->setWidget(_search_widget); -#ifdef ENABLE_DECODE + addDockWidget(Qt::RightDockWidgetArea,_protocol_dock); -#endif + addDockWidget(Qt::RightDockWidgetArea,_trigger_dock); addDockWidget(Qt::RightDockWidgetArea,_dso_trigger_dock); addDockWidget(Qt::RightDockWidgetArea, _measure_dock); @@ -264,35 +206,6 @@ void MainWindow::setup_ui() std::string std_title = title.toStdString(); setWindowTitle(QApplication::translate("MainWindow", std_title.c_str(), 0)); - // Setup _session events - connect(&_session, SIGNAL(capture_state_changed(int)), this, - SLOT(capture_state_changed(int))); - connect(&_session, SIGNAL(device_attach()), this, - SLOT(device_attach()), Qt::QueuedConnection); - connect(&_session, SIGNAL(device_detach()), this, - SLOT(device_detach()), Qt::QueuedConnection); - connect(&_session, SIGNAL(session_error()), this, - SLOT(show_error()), Qt::QueuedConnection); - connect(&_session, SIGNAL(session_save()), this, - SLOT(session_save())); - connect(&_session, SIGNAL(data_updated()), _measure_widget, - SLOT(reCalc())); - connect(&_session, SIGNAL(repeat_resume()), this, - SLOT(repeat_resume())); - connect(&_session, SIGNAL(update_capture()), _view, - SLOT(update_hori_res()), Qt::DirectConnection); - - connect(&_session, SIGNAL(cur_snap_samplerate_changed()), _measure_widget, - SLOT(cursor_update())); - connect(_view, SIGNAL(cursor_update()), _measure_widget, - SLOT(cursor_update())); - connect(_view, SIGNAL(cursor_moving()), _measure_widget, - SLOT(cursor_moving())); - connect(_view, SIGNAL(cursor_moved()), _measure_widget, - SLOT(reCalc())); - connect(_view, SIGNAL(prgRate(int)), this, SIGNAL(prgRate(int))); - connect(_view, SIGNAL(device_changed(bool)), - this, SLOT(device_changed(bool)), Qt::DirectConnection); // event filter _view->installEventFilter(this); @@ -302,33 +215,87 @@ void MainWindow::setup_ui() _logo_bar->installEventFilter(this); _dso_trigger_dock->installEventFilter(this); _trigger_dock->installEventFilter(this); -#ifdef ENABLE_DECODE _protocol_dock->installEventFilter(this); -#endif _measure_dock->installEventFilter(this); _search_dock->installEventFilter(this); // Populate the device list and select the initially selected device - _session.set_default_device(boost::bind(&MainWindow::session_error, this, - QString(tr("Set Default Device failed")), _1)); + _session->set_default_device(); // defaut language - QSettings settings(QApplication::organizationName(), QApplication::applicationName()); - QLocale locale; - settings.beginGroup("MainFrame"); - switchLanguage(settings.value("language", locale.language()).toInt()); - switchTheme(settings.value("style", "dark").toString()); - settings.endGroup(); - + AppConfig &app = AppConfig::Instance(); + switchLanguage(app._frameOptions.language); + switchTheme(app._frameOptions.style); + // UI initial _measure_widget->add_dist_measure(); - - // update device - update_device_list(); - _session.start_hotplug_proc(boost::bind(&MainWindow::session_error, this, - QString(tr("Hotplug failed")), _1)); + + _session->start_hotplug_work(); retranslateUi(); + + //event + connect(&_event, SIGNAL(capture_state_changed(int)), this, SLOT(on_capture_state_changed(int))); + connect(&_event, SIGNAL(device_attach()), this, SLOT(on_device_attach())); + connect(&_event, SIGNAL(device_detach()), this, SLOT(on_device_detach())); + connect(&_event, SIGNAL(session_error()), this, SLOT(on_session_error())); + connect(&_event, SIGNAL(show_error(QString)), this, SLOT(on_show_error(QString))); + connect(&_event, SIGNAL(signals_changed()), this, SLOT(on_signals_changed())); + connect(&_event, SIGNAL(receive_trigger(quint64)), this, SLOT(on_receive_trigger(quint64))); + connect(&_event, SIGNAL(frame_ended()), this, SLOT(on_frame_ended())); + connect(&_event, SIGNAL(frame_began()), this, SLOT(on_frame_began())); + connect(&_event, SIGNAL(decode_done()), this, SLOT(on_decode_done())); + connect(&_event, SIGNAL(data_updated()), this, SLOT(on_data_updated())); + connect(&_event, SIGNAL(cur_snap_samplerate_changed()), this, SLOT(on_cur_snap_samplerate_changed())); + connect(&_event, SIGNAL(receive_data_len(quint64)), this, SLOT(on_receive_data_len(quint64))); + + + //view + connect(_view, SIGNAL(cursor_update()), _measure_widget, SLOT(cursor_update())); + connect(_view, SIGNAL(cursor_moving()), _measure_widget, SLOT(cursor_moving())); + connect(_view, SIGNAL(cursor_moved()), _measure_widget, SLOT(reCalc())); + connect(_view, SIGNAL(prgRate(int)), this, SIGNAL(prgRate(int))); + connect(_view, SIGNAL(device_changed(bool)), this, SLOT(device_changed(bool)), Qt::DirectConnection); + connect(_view, SIGNAL(auto_trig(int)), _dso_trigger_widget, SLOT(auto_trig(int))); + + //trig_bar + connect(_trig_bar, SIGNAL(sig_protocol(bool)), this, SLOT(on_protocol(bool))); + connect(_trig_bar, SIGNAL(sig_trigger(bool)), this, SLOT(on_trigger(bool))); + connect(_trig_bar, SIGNAL(sig_measure(bool)), this, SLOT(on_measure(bool))); + connect(_trig_bar, SIGNAL(sig_search(bool)), this, SLOT(on_search(bool))); + connect(_trig_bar, SIGNAL(sig_setTheme(QString)), this, SLOT(switchTheme(QString))); + connect(_trig_bar, SIGNAL(sig_show_lissajous(bool)), _view, SLOT(show_lissajous(bool))); + + //file toolbar + connect(_file_bar, SIGNAL(sig_load_file(QString)), this, SLOT(on_load_file(QString))); + connect(_file_bar, SIGNAL(sig_save()), this, SLOT(on_save())); + connect(_file_bar, SIGNAL(sig_export()), this, SLOT(on_export())); + connect(_file_bar, SIGNAL(sig_screenShot()), this, SLOT(on_screenShot()), Qt::QueuedConnection); + connect(_file_bar, SIGNAL(sig_load_session(QString)), this, SLOT(on_load_session(QString))); + connect(_file_bar, SIGNAL(sig_store_session(QString)), this, SLOT(on_store_session(QString))); + + //logobar + connect(_logo_bar, SIGNAL(sig_open_doc()), this, SLOT(on_open_doc())); + + + connect(_protocol_widget, SIGNAL(protocol_updated()), this, SLOT(on_signals_changed())); + + //SamplingBar + connect(_sampling_bar, SIGNAL(sig_device_selected()), this, SLOT(on_device_selected())); + connect(_sampling_bar, SIGNAL(sig_device_updated()), this, SLOT(on_device_updated_reload())); + connect(_sampling_bar, SIGNAL(sig_run_stop()), this, SLOT(on_run_stop())); + connect(_sampling_bar, SIGNAL(sig_instant_stop()), this, SLOT(on_instant_stop())); + connect(_sampling_bar, SIGNAL(sig_duration_changed()), _trigger_widget, SLOT(device_updated())); + connect(_sampling_bar, SIGNAL(sig_duration_changed()), _view, SLOT(timebase_changed())); + connect(_sampling_bar, SIGNAL(sig_show_calibration()), _view, SLOT(show_calibration())); + + connect(_dso_trigger_widget, SIGNAL(set_trig_pos(int)), _view, SLOT(set_trig_pos(int))); + + _logo_bar->set_mainform_callback(this); + + //delay to update device list + QTimer::singleShot(200, this, SLOT(update_device_list())); + } @@ -341,12 +308,10 @@ void MainWindow::retranslateUi() _search_dock->setWindowTitle(tr("Search...")); } -void MainWindow::session_error( - const QString text, const QString info_text) + +void MainWindow::on_device_selected() { - QMetaObject::invokeMethod(this, "show_session_error", - Qt::QueuedConnection, Q_ARG(QString, text), - Q_ARG(QString, info_text)); + update_device_list(); } void MainWindow::update_device_list() @@ -356,22 +321,28 @@ void MainWindow::update_device_list() if (_msg) _msg->close(); - switchLanguage(_language); - _session.stop_capture(); + AppConfig &app = AppConfig::Instance(); + + SigSession *_session = _control->GetSession(); + + switchLanguage(app._frameOptions.language); + _session->stop_capture(); _view->reload(); _trigger_widget->device_updated(); -#ifdef ENABLE_DECODE + _protocol_widget->del_all_protocol(); -#endif + _trig_bar->reload(); - shared_ptr selected_device = _session.get_device(); + DeviceManager &_device_manager = _control->GetDeviceManager(); + + DevInst *selected_device = _session->get_device(); _device_manager.add_device(selected_device); - _session.init_signals(); + _session->init_signals(); _sampling_bar->set_device_list(_device_manager.devices(), selected_device); - shared_ptr file_dev; - if((file_dev = dynamic_pointer_cast(selected_device))) { + File *file_dev = NULL; + if((file_dev = dynamic_cast(selected_device))) { // check version if (selected_device->dev_inst()->mode == LOGIC) { GVariant* gvar = selected_device->get_config(NULL, NULL, SR_CONF_FILE_VERSION); @@ -379,28 +350,25 @@ void MainWindow::update_device_list() int16_t version = g_variant_get_int16(gvar); g_variant_unref(gvar); if (version == 1) { - show_session_error(tr("Attension"), - tr("Current loading file has an old format. " + show_error(tr("Current loading file has an old format. " "This will lead to a slow loading speed. " "Please resave it after loaded.")); } } } - #ifdef ENABLE_DECODE - // load decoders + + // load decoders StoreSession ss(_session); - ss.load_decoders(_protocol_widget, file_dev->get_decoders()); - #endif + bool bFlag = ss.load_decoders(_protocol_widget, file_dev->get_decoders()); // load session - load_session_json(file_dev->get_session(), true); + load_session_json(file_dev->get_session(), true, !bFlag); // load data const QString errorMessage( QString(tr("Failed to capture file data!"))); - _session.start_capture(true, boost::bind(&MainWindow::session_error, this, - errorMessage, _1)); + _session->start_capture(true); } if (!selected_device->name().contains("virtual")) { @@ -413,22 +381,18 @@ void MainWindow::update_device_list() #endif if (dir.exists()) { QString str = dir.absolutePath() + "/"; - QString lang_name = ".ses" + QString::number(_language); + QString lang_name = ".ses" + QString::number(app._frameOptions.language); QString ses_name = str + selected_device->name() + QString::number(selected_device->dev_inst()->mode) + lang_name + ".dsc"; - load_session(ses_name); + on_load_session(ses_name); } } else { _file_bar->set_settings_en(false); _logo_bar->dsl_connected(false); - #ifdef Q_OS_LINUX - QDir dir(DS_RES_PATH); - #else - QDir dir(QCoreApplication::applicationDirPath()); - assert(dir.cd("res")); - #endif + + QDir dir(GetResourceDir()); if (dir.exists()) { QString str = dir.absolutePath() + "/"; QString ses_name = str + @@ -436,7 +400,7 @@ void MainWindow::update_device_list() QString::number(selected_device->dev_inst()->mode) + ".dsc"; if (QFileInfo(ses_name).exists()) - load_session(ses_name); + on_load_session(ses_name); } } _sampling_bar->reload(); @@ -461,90 +425,124 @@ void MainWindow::update_device_list() g_variant_unref(gvar); if (usb30_support && usb_speed == LIBUSB_SPEED_HIGH) - show_session_error(tr("Speed limited"), tr("This is a super-speed usb device(USB 3.0). " - "Plug it into a USB 2.0 port will seriously affect its performance." - "Please replug it into a USB 3.0 port.")); + show_error("Plug it into a USB 2.0 port will seriously affect its performance." + "Please replug it into a USB 3.0 port."); } } + + _trig_bar->restore_status(); + + //load specified file name from application startup param + if (_bFirstLoad){ + _bFirstLoad = false; + + if (AppControl::Instance()->_open_file_name != ""){ + QString opf(QString::fromUtf8(AppControl::Instance()->_open_file_name.c_str())); + QFile fpath; + + if (fpath.exists(opf)){ + qDebug()<<"auto load file:"<GetSession(); _trigger_widget->device_updated(); - _session.reload(); + _session->reload(); _measure_widget->reload(); } -void MainWindow::load_file(QString file_name) +void MainWindow::on_load_file(QString file_name) { + SigSession *_session = _control->GetSession(); + try { - if (strncmp(_session.get_device()->name().toUtf8(), "virtual", 7)) + if (strncmp(_session->get_device()->name().toUtf8(), "virtual", 7)) session_save(); - _session.set_file(file_name); + _session->set_file(file_name); } catch(QString e) { - show_session_error(tr("Failed to load ") + file_name, e); - _session.set_default_device(boost::bind(&MainWindow::session_error, this, - QString(tr("Set Default Device failed")), _1)); - update_device_list(); - return; + show_error(tr("Failed to load ") + file_name); + _session->set_default_device(); } update_device_list(); } -void MainWindow::show_session_error( - const QString text, const QString info_text) +void MainWindow::show_error(QString error) { - dialogs::DSMessageBox msg(this); - _msg = &msg; - msg.mBox()->setText(text); - msg.mBox()->setInformativeText(info_text); - msg.mBox()->setStandardButtons(QMessageBox::Ok); - msg.mBox()->setIcon(QMessageBox::Warning); - msg.exec(); - _msg = NULL; + _event.show_error(error); //safe call +} + +void MainWindow::on_show_error(QString error) +{ + MsgBox::Show(NULL, error.toStdString().c_str(), this); } void MainWindow::device_attach() { - _session.get_device()->device_updated(); - //_session.stop_hot_plug_proc(); + _event.device_attach(); //safe call +} - _session.set_repeating(false); - _session.stop_capture(); +void MainWindow::on_device_attach() +{ + SigSession *_session = _control->GetSession(); + + _session->get_device()->device_updated(); + + _session->set_repeating(false); + _session->stop_capture(); _sampling_bar->set_sampling(false); - _session.capture_state_changed(SigSession::Stopped); + _session->capture_state_changed(SigSession::Stopped); struct sr_dev_driver **const drivers = sr_driver_list(); struct sr_dev_driver **driver; + + DeviceManager &_device_manager = _control->GetDeviceManager(); + for (driver = drivers; *driver; driver++) - if (*driver) - _device_manager.driver_scan(*driver); + { + if (*driver){ + std::list driver_devices; + _device_manager.driver_scan(driver_devices, *driver); + } + } - _session.set_default_device(boost::bind(&MainWindow::session_error, this, - QString(tr("Set Default Device failed")), _1)); + _session->set_default_device(); update_device_list(); - } -void MainWindow::device_detach() -{ - _session.get_device()->device_updated(); - //_session.stop_hot_plug_proc(); +void MainWindow::device_detach(){ + _event.device_detach(); //safe call +} - _session.set_repeating(false); - _session.stop_capture(); +void MainWindow::on_device_detach() +{ + SigSession *_session = _control->GetSession(); + + _session->get_device()->device_updated(); + //_session->stop_hot_plug_proc(); + + _session->set_repeating(false); + _session->stop_capture(); _sampling_bar->set_sampling(false); - _session.capture_state_changed(SigSession::Stopped); + _session->capture_state_changed(SigSession::Stopped); session_save(); _view->hide_calibration(); - if (_session.get_device()->dev_inst()->mode != DSO && - strncmp(_session.get_device()->name().toUtf8(), "virtual", 7)) { - const boost::shared_ptr logic_snapshot(_session.get_snapshot(SR_CHANNEL_LOGIC)); + if (_session->get_device()->dev_inst()->mode != DSO && + strncmp(_session->get_device()->name().toUtf8(), "virtual", 7)) { + const auto logic_snapshot = _session->get_snapshot(SR_CHANNEL_LOGIC); assert(logic_snapshot); - const boost::shared_ptr analog_snapshot(_session.get_snapshot(SR_CHANNEL_ANALOG)); + const auto analog_snapshot = _session->get_snapshot(SR_CHANNEL_ANALOG); assert(analog_snapshot); if (!logic_snapshot->empty() || !analog_snapshot->empty()) { @@ -562,69 +560,76 @@ void MainWindow::device_detach() } _hot_detach = true; - if (!_session.get_saving()) + if (!_session->get_saving()) device_detach_post(); } void MainWindow::device_detach_post() { + SigSession *_session = _control->GetSession(); + if (!_hot_detach) return; + DeviceManager &_device_manager = _control->GetDeviceManager(); _hot_detach = false; struct sr_dev_driver **const drivers = sr_driver_list(); struct sr_dev_driver **driver; - for (driver = drivers; *driver; driver++) - if (*driver) - _device_manager.driver_scan(*driver); + for (driver = drivers; *driver; driver++){ + if (*driver){ + std::list driver_devices; + _device_manager.driver_scan(driver_devices, *driver); + } + } - _session.set_default_device(boost::bind(&MainWindow::session_error, this, - QString(tr("Set Default Device failed")), _1)); + _session->set_default_device(); update_device_list(); } void MainWindow::device_changed(bool close) { + SigSession *_session = _control->GetSession(); + if (close) { _sampling_bar->set_sampling(false); - _session.set_default_device(boost::bind(&MainWindow::session_error, this, - QString(tr("Set Default Device failed")), _1)); - } - update_device_list(); + _session->set_default_device(); + } + + update_device_list(); } -void MainWindow::run_stop() -{ - switch(_session.get_capture_state()) { +void MainWindow::on_run_stop() +{ + SigSession *_session = _control->GetSession(); + + switch(_session->get_capture_state()) { case SigSession::Init: case SigSession::Stopped: commit_trigger(false); - _session.start_capture(false, - boost::bind(&MainWindow::session_error, this, - QString(tr("Capture failed")), _1)); + _session->start_capture(false); _view->capture_init(); break; case SigSession::Running: - _session.stop_capture(); + _session->stop_capture(); break; } } -void MainWindow::instant_stop() +void MainWindow::on_instant_stop() { - switch(_session.get_capture_state()) { + SigSession *_session = _control->GetSession(); + + switch(_session->get_capture_state()) { case SigSession::Init: case SigSession::Stopped: commit_trigger(true); - _session.start_capture(true, - boost::bind(&MainWindow::session_error, this, - QString(tr("Capture failed")), _1)); + _session->start_capture(true); _view->capture_init(); break; case SigSession::Running: - _session.stop_capture(); + _session->stop_capture(); break; } } @@ -633,36 +638,43 @@ void MainWindow::repeat_resume() { while(_view->session().get_capture_state() == SigSession::Running) QCoreApplication::processEvents(); - run_stop(); + on_run_stop(); } -void MainWindow::show_error() +void MainWindow::session_error() +{ + _event.session_error(); +} + +void MainWindow::on_session_error() { QString title; QString details; QString ch_status = ""; uint64_t error_pattern; - switch(_session.get_error()) { + SigSession *_session = _control->GetSession(); + + switch(_session->get_error()) { case SigSession::Hw_err: - _session.set_repeating(false); - _session.stop_capture(); + _session->set_repeating(false); + _session->stop_capture(); title = tr("Hardware Operation Failed"); details = tr("Please replug device to refresh hardware configuration!"); break; case SigSession::Malloc_err: - _session.set_repeating(false); - _session.stop_capture(); + _session->set_repeating(false); + _session->stop_capture(); title = tr("Malloc Error"); details = tr("Memory is not enough for this sample!\nPlease reduce the sample depth!"); break; case SigSession::Test_data_err: - _session.set_repeating(false); - _session.stop_capture(); + _session->set_repeating(false); + _session->stop_capture(); _sampling_bar->set_sampling(false); - _session.capture_state_changed(SigSession::Stopped); + _session->capture_state_changed(SigSession::Stopped); title = tr("Data Error"); - error_pattern = _session.get_error_pattern(); + error_pattern = _session->get_error_pattern(); for(int i = 0; i < 16; i++) { if (error_pattern & 0x01) ch_status += "X "; @@ -677,11 +689,11 @@ void MainWindow::show_error() case SigSession::Pkt_data_err: title = tr("Packet Error"); details = tr("the content of received packet are not expected!"); - _session.refresh(0); + _session->refresh(0); break; case SigSession::Data_overflow: - _session.set_repeating(false); - _session.stop_capture(); + _session->set_repeating(false); + _session->stop_capture(); title = tr("Data Overflow"); details = tr("USB bandwidth can not support current sample rate! \nPlease reduce the sample rate!"); break; @@ -692,7 +704,7 @@ void MainWindow::show_error() } dialogs::DSMessageBox msg(this); - connect(_session.get_device().get(), SIGNAL(device_updated()), &msg, SLOT(accept())); + connect(_session->get_device(), SIGNAL(device_updated()), &msg, SLOT(accept())); QFont font("Monaco"); font.setStyleHint(QFont::Monospace); font.setFixedPitch(true); @@ -704,18 +716,25 @@ void MainWindow::show_error() msg.mBox()->setIcon(QMessageBox::Warning); msg.exec(); - _session.clear_error(); + _session->clear_error(); } void MainWindow::capture_state_changed(int state) { - if (!_session.repeat_check()) { + _event.capture_state_changed(state);//safe call +} + +void MainWindow::on_capture_state_changed(int state) +{ + SigSession *_session = _control->GetSession(); + + if (!_session->repeat_check()) { _file_bar->enable_toggle(state != SigSession::Running); _sampling_bar->set_sampling(state == SigSession::Running); _view->on_state_changed(state != SigSession::Running); - if (_session.get_device()->dev_inst()->mode != DSO || - _session.get_instant()) { + if (_session->get_device()->dev_inst()->mode != DSO || + _session->get_instant()) { _sampling_bar->enable_toggle(state != SigSession::Running); _trig_bar->enable_toggle(state != SigSession::Running); //_measure_dock->widget()->setEnabled(state != SigSession::Running); @@ -737,22 +756,26 @@ void MainWindow::session_save() #else QString path = QStandardPaths::writableLocation(QStandardPaths::DataLocation); #endif + + AppConfig &app = AppConfig::Instance(); + SigSession *_session = _control->GetSession(); + if(dir.mkpath(path)) { dir.cd(path); - QString driver_name = _session.get_device()->name(); - QString mode_name = QString::number(_session.get_device()->dev_inst()->mode); - QString lang_name = ".ses" + QString::number(_language); + QString driver_name = _session->get_device()->name(); + QString mode_name = QString::number(_session->get_device()->dev_inst()->mode); + QString lang_name = ".ses" + QString::number(app._frameOptions.language); QString file_name = dir.absolutePath() + "/" + driver_name + mode_name + lang_name + ".dsc"; if (strncmp(driver_name.toUtf8(), "virtual", 7) && !file_name.isEmpty()) { - store_session(file_name); + on_store_session(file_name); } } - - QSettings settings(QApplication::organizationName(), QApplication::applicationName()); - settings.setValue("windowState", saveState()); + + app._frameOptions.windowState = saveState(); + app.SaveFrame(); } void MainWindow::closeEvent(QCloseEvent *event) @@ -764,14 +787,16 @@ void MainWindow::closeEvent(QCloseEvent *event) void MainWindow::on_protocol(bool visible) { -#ifdef ENABLE_DECODE + _protocol_dock->setVisible(visible); -#endif + } void MainWindow::on_trigger(bool visible) { - if (_session.get_device()->dev_inst()->mode != DSO) { + SigSession *_session = _control->GetSession(); + + if (_session->get_device()->dev_inst()->mode != DSO) { _trigger_widget->init(); _trigger_dock->setVisible(visible); _dso_trigger_dock->setVisible(false); @@ -786,28 +811,28 @@ void MainWindow::on_trigger(bool visible) void MainWindow::commit_trigger(bool instant) { int i = 0; - const QString TRIG_KEY("WarnofMultiTrig"); - QSettings settings(QApplication::organizationName(), QApplication::applicationName()); + + AppConfig &app = AppConfig::Instance(); + SigSession *_session = _control->GetSession(); ds_trigger_init(); - if (_session.get_device()->dev_inst()->mode != LOGIC || + if (_session->get_device()->dev_inst()->mode != LOGIC || instant) return; if (!_trigger_widget->commit_trigger()) { /* simple trigger check trigger_enable */ - BOOST_FOREACH(const boost::shared_ptr s, _session.get_signals()) + for(auto &s : _session->get_signals()) { assert(s); - boost::shared_ptr logicSig; - if ((logicSig = dynamic_pointer_cast(s))) { + view::LogicSignal *logicSig = NULL; + if ((logicSig = dynamic_cast(s))) { if (logicSig->commit_trig()) i++; } } - if (!settings.contains(TRIG_KEY) && - i > 1) { + if (app._appOptions.warnofMultiTrig && i > 1) { dialogs::DSMessageBox msg(this); msg.mBox()->setText(tr("Trigger")); msg.mBox()->setInformativeText(tr("Trigger setted on multiple channels! " @@ -819,19 +844,24 @@ void MainWindow::commit_trigger(bool instant) msg.mBox()->addButton(tr("Continue"), QMessageBox::ActionRole); msg.exec(); + if (msg.mBox()->clickedButton() == cancelButton) { - BOOST_FOREACH(const boost::shared_ptr s, _session.get_signals()) + for(auto &s : _session->get_signals()) { assert(s); - boost::shared_ptr logicSig; - if ((logicSig = dynamic_pointer_cast(s))) { + view::LogicSignal *logicSig = NULL; + if ((logicSig = dynamic_cast(s))) { logicSig->set_trig(view::LogicSignal::NONTRIG); logicSig->commit_trig(); } } } + if (msg.mBox()->clickedButton() == noMoreButton) - settings.setValue(TRIG_KEY, false); + { + app._appOptions.warnofMultiTrig = false; + app.SaveApp(); + } } } } @@ -849,66 +879,71 @@ void MainWindow::on_search(bool visible) void MainWindow::on_screenShot() { - const QString DIR_KEY("ScreenShotPath"); - QSettings settings(QApplication::organizationName(), QApplication::applicationName()); - QString default_name = settings.value(DIR_KEY).toString() + "/DSView" + QDateTime::currentDateTime().toString("-yyMMdd-hhmmss"); - QPixmap pixmap; - QScreen *screen = QGuiApplication::primaryScreen(); - QDesktopWidget *desktop = QApplication::desktop(); - pixmap = screen->grabWindow(desktop->winId(), parentWidget()->pos().x(), parentWidget()->pos().y(), - parentWidget()->frameGeometry().width(), parentWidget()->frameGeometry().height()); + AppConfig &app = AppConfig::Instance(); + QString default_name = app._userHistory.screenShotPath + "/DSView" + QDateTime::currentDateTime().toString("-yyMMdd-hhmmss"); + +#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) + QScreen *scr = QGuiApplication::primaryScreen(); + QPixmap pixmap = scr->grabWindow(winId()); +#else + QPixmap pixmap = QPixmap::grabWindow(winId()); +#endif + QString format = "png"; - QString fileName = QFileDialog::getSaveFileName(this, - tr("Save As"), default_name, - tr("%1 Files (*.%2);;All Files (*)") - .arg(format.toUpper()).arg(format)); + QString fileName = QFileDialog::getSaveFileName( + this, + tr("Save As"), + default_name, + // tr("%1 Files (*.%2);;All Files (*)") + "png file(*.png);;jpeg file(*.jpeg)", + &format); + if (!fileName.isEmpty()) { - QDir CurrentDir; - settings.setValue(DIR_KEY, CurrentDir.filePath(fileName)); - pixmap.save(fileName, format.toLatin1()); + + QStringList list = format.split('.').last().split(')'); + QString suffix = list.first(); + + QFileInfo f(fileName); + if (f.suffix().compare(suffix)) + { + fileName += tr(".") + suffix; + } + + pixmap.save(fileName, suffix.toLatin1()); + + fileName = GetDirectoryName(fileName); + + if (app._userHistory.screenShotPath != fileName){ + app._userHistory.screenShotPath = fileName; + app.SaveHistory(); + } } } +//save file void MainWindow::on_save() { - using pv::dialogs::StoreProgress; + using pv::dialogs::StoreProgress; -// dialogs::RegionOptions *regionDlg = new dialogs::RegionOptions(_view, _session, this); -// regionDlg->exec(); - - _session.set_saving(true); - QString session_file; - QDir dir; - #if QT_VERSION >= 0x050400 - QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); - #else - QString path = QStandardPaths::writableLocation(QStandardPaths::DataLocation); - #endif - if(dir.mkpath(path)) { - dir.cd(path); - - session_file = dir.absolutePath() + "/DSView-session-XXXXXX"; - store_session(session_file); - } + SigSession *_session = _control->GetSession(); + _session->set_saving(true); StoreProgress *dlg = new StoreProgress(_session, this); connect(dlg, SIGNAL(save_done()), this, SLOT(device_detach_post())); - dlg->save_run(session_file); + dlg->save_run(this); } void MainWindow::on_export() { using pv::dialogs::StoreProgress; - -// dialogs::RegionOptions *regionDlg = new dialogs::RegionOptions(_view, _session, this); -// regionDlg->exec(); + SigSession *_session = _control->GetSession(); StoreProgress *dlg = new StoreProgress(_session, this); dlg->export_run(); } -bool MainWindow::load_session(QString name) +bool MainWindow::on_load_session(QString name) { QFile sessionFile(name); if (!sessionFile.open(QIODevice::ReadOnly)) { @@ -922,7 +957,7 @@ bool MainWindow::load_session(QString name) return load_session_json(sessionDoc, false); } -bool MainWindow::load_session_json(QJsonDocument json, bool file_dev) +bool MainWindow::load_session_json(QJsonDocument json, bool file_dev, bool bDecoder) { QJsonObject sessionObj = json.object(); @@ -931,39 +966,21 @@ bool MainWindow::load_session_json(QJsonDocument json, bool file_dev) sessionObj["Version"].toInt() != Session_Version) return false; + SigSession *_session = _control->GetSession(); + // check device and mode - const sr_dev_inst *const sdi = _session.get_device()->dev_inst(); + const sr_dev_inst *const sdi = _session->get_device()->dev_inst(); if ((!file_dev && strcmp(sdi->driver->name, sessionObj["Device"].toString().toUtf8()) != 0) || sdi->mode != sessionObj["DeviceMode"].toDouble()) { - dialogs::DSMessageBox msg(this); - msg.mBox()->setText(tr("Session Error")); - msg.mBox()->setInformativeText(tr("Session File is not compatible with current device or mode!")); - msg.mBox()->setStandardButtons(QMessageBox::Ok); - msg.mBox()->setIcon(QMessageBox::Warning); - msg.exec(); + MsgBox::Show(NULL, "Session File is not compatible with current device or mode!", this); return false; } - - // check language - if (sessionObj.contains("Language")) { - switchLanguage(sessionObj["Language"].toInt()); - } else if (sessionObj.contains("Operation Mode")) { - bool language_matched = _session.get_device()->set_config(NULL, NULL, SR_CONF_OPERATION_MODE, - g_variant_new_string(sessionObj["Operation Mode"].toString().toUtf8())); - if (!language_matched) { - if (_language != QLocale::Chinese) - switchLanguage(QLocale::Chinese); - else - switchLanguage(QLocale::English); - } - } - - // clear decoders - #ifdef ENABLE_DECODE - if (sdi->mode == LOGIC) { + + // clear decoders + if (sdi->mode == LOGIC && !file_dev) + { _protocol_widget->del_all_protocol(); - } - #endif + } // load device settings GVariant *gvar_opts; @@ -977,24 +994,25 @@ bool MainWindow::load_session_json(QJsonDocument json, bool file_dev) if (!sessionObj.contains(info->name)) continue; if (info->datatype == SR_T_BOOL) - _session.get_device()->set_config(NULL, NULL, info->key, g_variant_new_boolean(sessionObj[info->name].toDouble())); + _session->get_device()->set_config(NULL, NULL, info->key, g_variant_new_boolean(sessionObj[info->name].toDouble())); else if (info->datatype == SR_T_UINT64) - _session.get_device()->set_config(NULL, NULL, info->key, g_variant_new_uint64(sessionObj[info->name].toString().toULongLong())); + _session->get_device()->set_config(NULL, NULL, info->key, g_variant_new_uint64(sessionObj[info->name].toString().toULongLong())); else if (info->datatype == SR_T_UINT8) - _session.get_device()->set_config(NULL, NULL, info->key, g_variant_new_byte(sessionObj[info->name].toString().toUInt())); + _session->get_device()->set_config(NULL, NULL, info->key, g_variant_new_byte(sessionObj[info->name].toString().toUInt())); else if (info->datatype == SR_T_FLOAT) - _session.get_device()->set_config(NULL, NULL, info->key, g_variant_new_double(sessionObj[info->name].toDouble())); + _session->get_device()->set_config(NULL, NULL, info->key, g_variant_new_double(sessionObj[info->name].toDouble())); else if (info->datatype == SR_T_CHAR) - _session.get_device()->set_config(NULL, NULL, info->key, g_variant_new_string(sessionObj[info->name].toString().toUtf8())); + _session->get_device()->set_config(NULL, NULL, info->key, g_variant_new_string(sessionObj[info->name].toString().toUtf8())); } } // load channel settings if (file_dev && (sdi->mode == DSO)) { - for (const GSList *l = _session.get_device()->dev_inst()->channels; l; l = l->next) { + for (const GSList *l = _session->get_device()->dev_inst()->channels; l; l = l->next) { sr_channel *const probe = (sr_channel*)l->data; assert(probe); - foreach (const QJsonValue &value, sessionObj["channel"].toArray()) { + + for (const QJsonValue &value : sessionObj["channel"].toArray()) { QJsonObject obj = value.toObject(); if ((strcmp(probe->name, g_strdup(obj["name"].toString().toStdString().c_str())) == 0) && (probe->type == obj["type"].toDouble())) { @@ -1010,11 +1028,12 @@ bool MainWindow::load_session_json(QJsonDocument json, bool file_dev) } } } else { - for (const GSList *l = _session.get_device()->dev_inst()->channels; l; l = l->next) { + for (const GSList *l = _session->get_device()->dev_inst()->channels; l; l = l->next) { sr_channel *const probe = (sr_channel*)l->data; assert(probe); bool isEnabled = false; - foreach (const QJsonValue &value, sessionObj["channel"].toArray()) { + + for (const QJsonValue &value : sessionObj["channel"].toArray()) { QJsonObject obj = value.toObject(); if ((probe->index == obj["index"].toDouble()) && (probe->type == obj["type"].toDouble())) { @@ -1036,20 +1055,21 @@ bool MainWindow::load_session_json(QJsonDocument json, bool file_dev) } } - //_session.init_signals(); - _session.reload(); + //_session->init_signals(); + _session->reload(); // load signal setting if (file_dev && (sdi->mode == DSO)) { - BOOST_FOREACH(const boost::shared_ptr s, _session.get_signals()) { - foreach (const QJsonValue &value, sessionObj["channel"].toArray()) { + + for(auto &s : _session->get_signals()) { + for (const QJsonValue &value : sessionObj["channel"].toArray()) { QJsonObject obj = value.toObject(); if ((strcmp(s->get_name().toStdString().c_str(), g_strdup(obj["name"].toString().toStdString().c_str())) == 0) && (s->get_type() == obj["type"].toDouble())) { s->set_colour(QColor(obj["colour"].toString())); - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s))) { + view::DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(s))) { dsoSig->load_settings(); dsoSig->set_zero_ratio(obj["zeroPos"].toDouble()); dsoSig->set_trig_ratio(obj["trigValue"].toDouble()); @@ -1060,29 +1080,29 @@ bool MainWindow::load_session_json(QJsonDocument json, bool file_dev) } } } else { - BOOST_FOREACH(const boost::shared_ptr s, _session.get_signals()) { - foreach (const QJsonValue &value, sessionObj["channel"].toArray()) { + for(auto &s : _session->get_signals()) { + for (const QJsonValue &value : sessionObj["channel"].toArray()) { QJsonObject obj = value.toObject(); if ((s->get_index() == obj["index"].toDouble()) && (s->get_type() == obj["type"].toDouble())) { s->set_colour(QColor(obj["colour"].toString())); s->set_name(g_strdup(obj["name"].toString().toUtf8().data())); - boost::shared_ptr logicSig; - if ((logicSig = dynamic_pointer_cast(s))) { + view::LogicSignal *logicSig = NULL; + if ((logicSig = dynamic_cast(s))) { logicSig->set_trig(obj["strigger"].toDouble()); } - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s))) { + view::DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(s))) { dsoSig->load_settings(); dsoSig->set_zero_ratio(obj["zeroPos"].toDouble()); dsoSig->set_trig_ratio(obj["trigValue"].toDouble()); dsoSig->commit_settings(); } - boost::shared_ptr analogSig; - if ((analogSig = dynamic_pointer_cast(s))) { + view::AnalogSignal *analogSig = NULL; + if ((analogSig = dynamic_cast(s))) { analogSig->set_zero_ratio(obj["zeroPos"].toDouble()); analogSig->commit_settings(); } @@ -1104,13 +1124,12 @@ bool MainWindow::load_session_json(QJsonDocument json, bool file_dev) } on_trigger(false); - #ifdef ENABLE_DECODE + // load decoders - if (sessionObj.contains("decoder")) { + if (bDecoder && sessionObj.contains("decoder")) { StoreSession ss(_session); ss.load_decoders(_protocol_widget, sessionObj["decoder"].toArray()); } - #endif // load measure if (sessionObj.contains("measure")) { @@ -1120,43 +1139,30 @@ bool MainWindow::load_session_json(QJsonDocument json, bool file_dev) return true; } - -bool MainWindow::store_session(QString name) -{ - QFile sessionFile(name); - if (!sessionFile.open(QIODevice::WriteOnly | QIODevice::Text)) { -// dialogs::DSMessageBox msg(this); -// msg.mBox()->setText(tr("File Error")); -// msg.mBox()->setInformativeText(tr("Couldn't open session file to write!")); -// msg.mBox()->setStandardButtons(QMessageBox::Ok); -// msg.mBox()->setIcon(QMessageBox::Warning); -// msg.exec(); - qDebug("Warning: Couldn't open session file to write!"); - return false; - } - QTextStream outStream(&sessionFile); - outStream.setCodec("UTF-8"); - //outStream.setGenerateByteOrderMark(true); // UTF-8 without BOM +bool MainWindow::gen_session_json(QJsonArray &array){ + SigSession *_session = _control->GetSession(); + AppConfig &app = AppConfig::Instance(); GVariant *gvar_opts; GVariant *gvar; gsize num_opts; - const sr_dev_inst *const sdi = _session.get_device()->dev_inst(); + const sr_dev_inst *const sdi = _session->get_device()->dev_inst(); QJsonObject sessionVar; QJsonArray channelVar; sessionVar["Version"]= QJsonValue::fromVariant(Session_Version); sessionVar["Device"] = QJsonValue::fromVariant(sdi->driver->name); sessionVar["DeviceMode"] = QJsonValue::fromVariant(sdi->mode); - sessionVar["Language"] = QJsonValue::fromVariant(_language); + sessionVar["Language"] = QJsonValue::fromVariant(app._frameOptions.language); if ((sr_config_list(sdi->driver, sdi, NULL, SR_CONF_DEVICE_SESSIONS, &gvar_opts) != SR_OK)) return false; /* Driver supports no device instance sessions. */ + const int *const options = (const int32_t *)g_variant_get_fixed_array( gvar_opts, &num_opts, sizeof(int32_t)); for (unsigned int i = 0; i < num_opts; i++) { const struct sr_config_info *const info = sr_config_info_get(options[i]); - gvar = _session.get_device()->get_config(NULL, NULL, info->key); + gvar = _session->get_device()->get_config(NULL, NULL, info->key); if (gvar != NULL) { if (info->datatype == SR_T_BOOL) sessionVar[info->name] = QJsonValue::fromVariant(g_variant_get_boolean(gvar)); @@ -1172,7 +1178,7 @@ bool MainWindow::store_session(QString name) } } - BOOST_FOREACH(const boost::shared_ptr s, _session.get_signals()) { + for(auto &s : _session->get_signals()) { QJsonObject s_obj; s_obj["index"] = s->get_index(); s_obj["type"] = s->get_type(); @@ -1183,13 +1189,13 @@ bool MainWindow::store_session(QString name) else s_obj["colour"] = QJsonValue::fromVariant("default"); - boost::shared_ptr logicSig; - if ((logicSig = dynamic_pointer_cast(s))) { + view::LogicSignal *logicSig = NULL; + if ((logicSig = dynamic_cast(s))) { s_obj["strigger"] = logicSig->get_trig(); } - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s))) { + view::DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(s))) { s_obj["vdiv"] = QJsonValue::fromVariant(static_cast(dsoSig->get_vDialValue())); s_obj["vfactor"] = QJsonValue::fromVariant(static_cast(dsoSig->get_factor())); s_obj["coupling"] = dsoSig->get_acCoupling(); @@ -1197,8 +1203,8 @@ bool MainWindow::store_session(QString name) s_obj["zeroPos"] = dsoSig->get_zero_ratio(); } - boost::shared_ptr analogSig; - if ((analogSig = dynamic_pointer_cast(s))) { + view::AnalogSignal *analogSig = NULL; + if ((analogSig = dynamic_cast(s))) { s_obj["vdiv"] = QJsonValue::fromVariant(static_cast(analogSig->get_vdiv())); s_obj["vfactor"] = QJsonValue::fromVariant(static_cast(analogSig->get_factor())); s_obj["coupling"] = analogSig->get_acCoupling(); @@ -1211,42 +1217,84 @@ bool MainWindow::store_session(QString name) } sessionVar["channel"] = channelVar; - if (_session.get_device()->dev_inst()->mode == LOGIC) { + if (_session->get_device()->dev_inst()->mode == LOGIC) { sessionVar["trigger"] = _trigger_widget->get_session(); } - - #ifdef ENABLE_DECODE + StoreSession ss(_session); - sessionVar["decoder"] = ss.json_decoders(); - #endif + QJsonArray decodeJson; + ss.json_decoders(decodeJson); + sessionVar["decoder"] = decodeJson; - if (_session.get_device()->dev_inst()->mode == DSO) { + if (_session->get_device()->dev_inst()->mode == DSO) { sessionVar["measure"] = _view->get_viewstatus()->get_session(); + } + + array.push_back(sessionVar); + return true; +} + +bool MainWindow::on_store_session(QString name) +{ + QFile sessionFile(name); + if (!sessionFile.open(QIODevice::WriteOnly | QIODevice::Text)) { + qDebug("Warning: Couldn't open session file to write!"); + return false; } - QJsonDocument sessionDoc(sessionVar); + QTextStream outStream(&sessionFile); + app::set_utf8(outStream); + + QJsonArray jsonArray; + if (!gen_session_json(jsonArray)) + return false; + QJsonDocument sessionDoc(jsonArray); //sessionFile.write(QString::fromUtf8(sessionDoc.toJson())); outStream << QString::fromUtf8(sessionDoc.toJson()); - sessionFile.close(); + sessionFile.close(); + return true; +} + +bool MainWindow::genSessionData(std::string &str) +{ + QJsonArray jsonArray; + if (!gen_session_json(jsonArray)) + return false; + QJsonDocument sessionDoc(jsonArray); + QString data = QString::fromUtf8(sessionDoc.toJson()); + str.append(data.toLatin1().data()); return true; } void MainWindow::restore_dock() { - // default dockwidget size - QSettings settings(QApplication::organizationName(), QApplication::applicationName()); - restoreState(settings.value("windowState").toByteArray()); - if (_session.get_device()->dev_inst()->mode != DSO) { + // default dockwidget size + AppConfig &app = AppConfig::Instance(); + QByteArray st = app._frameOptions.windowState; + if (!st.isEmpty()){ + try + { + restoreState(st); + } + catch(...) + { + MsgBox::Show(NULL, "restore window status error!"); + } + } + + SigSession *_session = _control->GetSession(); + + if (_session->get_device()->dev_inst()->mode != DSO) { _dso_trigger_dock->setVisible(false); _trig_bar->update_trig_btn(_trigger_dock->isVisible()); } else { _trigger_dock->setVisible(false); _trig_bar->update_trig_btn(_dso_trigger_dock->isVisible()); } - if (_session.get_device()->dev_inst()->mode != LOGIC) { -#ifdef ENABLE_DECODE + if (_session->get_device()->dev_inst()->mode != LOGIC) { + on_protocol(false); -#endif + } _trig_bar->update_protocol_btn(_protocol_dock->isVisible()); _trig_bar->update_measure_btn(_measure_dock->isVisible()); @@ -1258,26 +1306,27 @@ bool MainWindow::eventFilter(QObject *object, QEvent *event) (void) object; if ( event->type() == QEvent::KeyPress ) { - const vector< shared_ptr > sigs(_session.get_signals()); + SigSession *_session = _control->GetSession(); + const auto &sigs = _session->get_signals(); QKeyEvent *ke = (QKeyEvent *) event; switch(ke->key()) { case Qt::Key_S: - run_stop(); + on_run_stop(); break; case Qt::Key_I: - instant_stop(); + on_instant_stop(); break; case Qt::Key_T: - if (_session.get_device()->dev_inst()->mode == DSO) + if (_session->get_device()->dev_inst()->mode == DSO) on_trigger(!_dso_trigger_dock->isVisible()); else on_trigger(!_trigger_dock->isVisible()); break; -#ifdef ENABLE_DECODE + case Qt::Key_D: on_protocol(!_protocol_dock->isVisible()); break; -#endif + case Qt::Key_M: on_measure(!_measure_dock->isVisible()); break; @@ -1303,9 +1352,9 @@ bool MainWindow::eventFilter(QObject *object, QEvent *event) _view->zoom(-1); break; case Qt::Key_0: - BOOST_FOREACH(const shared_ptr s, sigs) { - shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s))) { + for(auto & s : sigs) { + view::DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(s))) { if (dsoSig->get_index() == 0) dsoSig->set_vDialActive(!dsoSig->get_vDialActive()); else @@ -1316,9 +1365,9 @@ bool MainWindow::eventFilter(QObject *object, QEvent *event) update(); break; case Qt::Key_1: - BOOST_FOREACH(const shared_ptr s, sigs) { - shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s))) { + for(auto & s : sigs) { + view::DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(s))) { if (dsoSig->get_index() == 1) dsoSig->set_vDialActive(!dsoSig->get_vDialActive()); else @@ -1329,9 +1378,9 @@ bool MainWindow::eventFilter(QObject *object, QEvent *event) update(); break; case Qt::Key_Up: - BOOST_FOREACH(const shared_ptr s, sigs) { - shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s))) { + for(auto &s : sigs) { + view::DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(s))) { if (dsoSig->get_vDialActive()) { dsoSig->go_vDialNext(true); update(); @@ -1341,9 +1390,9 @@ bool MainWindow::eventFilter(QObject *object, QEvent *event) } break; case Qt::Key_Down: - BOOST_FOREACH(const shared_ptr s, sigs) { - shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s))) { + for(auto &s : sigs) { + view::DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(s))) { if (dsoSig->get_vDialActive()) { dsoSig->go_vDialPre(true); update(); @@ -1359,58 +1408,171 @@ bool MainWindow::eventFilter(QObject *object, QEvent *event) } return false; } - -int MainWindow::language() const -{ - return _language; -} - + + void MainWindow::switchLanguage(int language) { - shared_ptr dev = _session.get_device(); + SigSession *_session = _control->GetSession(); + DevInst *dev = _session->get_device(); dev->set_config(NULL, NULL, SR_CONF_LANGUAGE, g_variant_new_int16(language)); + AppConfig &app = AppConfig::Instance(); - if (_language != language) { - _language = language; - if (_language != QLocale::English) { - _qtTrans.load(":/qt_"+QString::number(_language)); - qApp->installTranslator(&_qtTrans); - _myTrans.load(":/my_"+QString::number(_language)); - qApp->installTranslator(&_myTrans); - retranslateUi(); - } else { - qApp->removeTranslator(&_qtTrans); - qApp->removeTranslator(&_myTrans); - retranslateUi(); - } - qApp->setProperty("Language", _language); + if (app._frameOptions.language != language && language > 0) + { + app._frameOptions.language = language; + app.SaveFrame(); + } + + if (language == LAN_CN) + { + _qtTrans.load(":/qt_" + QString::number(language)); + qApp->installTranslator(&_qtTrans); + _myTrans.load(":/my_" + QString::number(language)); + qApp->installTranslator(&_myTrans); + retranslateUi(); + } + else + { + qApp->removeTranslator(&_qtTrans); + qApp->removeTranslator(&_myTrans); + retranslateUi(); } } void MainWindow::switchTheme(QString style) { - if (_style != style) { - _style = style; - qApp->setProperty("Style", _style); - QString qssRes = ":/"+_style+".qss"; - QFile qss(qssRes); - qss.open(QFile::ReadOnly | QFile::Text); - qApp->setStyleSheet(qss.readAll()); - qss.close(); - _session.data_updated(); - } + AppConfig &app = AppConfig::Instance(); + + if (app._frameOptions.style != style) + { + app._frameOptions.style = style; + app.SaveFrame(); + } + + QString qssRes = ":/" + style + ".qss"; + QFile qss(qssRes); + qss.open(QFile::ReadOnly | QFile::Text); + qApp->setStyleSheet(qss.readAll()); + qss.close(); + + data_updated(); +} + +void MainWindow::data_updated() +{ + _event.data_updated(); //safe call +} + +void MainWindow::on_data_updated(){ + _measure_widget->reCalc(); + _view->data_updated(); +} + +void MainWindow::on_open_doc(){ + openDoc(); } void MainWindow::openDoc() -{ - #ifndef Q_OS_LINUX - QDir dir(QCoreApplication::applicationDirPath()); - #else - QDir dir(DS_RES_PATH); - dir.cdUp(); - #endif +{ + QDir dir(GetAppDataDir()); + AppConfig &app = AppConfig::Instance(); + int lan = app._frameOptions.language; QDesktopServices::openUrl( - QUrl("file:///"+dir.absolutePath() + "/ug"+QString::number(_language)+".pdf")); + QUrl("file:///"+dir.absolutePath() + "/ug"+QString::number(lan)+".pdf")); +} + +void MainWindow::update_capture(){ + _view->update_hori_res(); +} + +void MainWindow::cur_snap_samplerate_changed(){ + _event.cur_snap_samplerate_changed(); //safe call +} + +void MainWindow::on_cur_snap_samplerate_changed() +{ + _measure_widget->cursor_update(); +} + +void MainWindow::device_setted(){ + _view->set_device(); +} + + void MainWindow::signals_changed() + { + _event.signals_changed(); //safe call + } + + void MainWindow::on_signals_changed() + { + _view->signals_changed(); + } + + void MainWindow::receive_trigger(quint64 trigger_pos) + { + _event.receive_trigger(trigger_pos); //save call + } + + void MainWindow::on_receive_trigger(quint64 trigger_pos) + { + _view->receive_trigger(trigger_pos); + } + + void MainWindow::frame_ended() + { + _event.frame_ended(); //save call + } + + void MainWindow::on_frame_ended() + { + _view->receive_end(); + } + + void MainWindow::frame_began() + { + _event.frame_began(); //save call + } + + void MainWindow::on_frame_began() + { + _view->frame_began(); + } + + void MainWindow::show_region(uint64_t start, uint64_t end, bool keep){ + _view->show_region(start, end, keep); + } + + void MainWindow::show_wait_trigger(){ + _view->show_wait_trigger(); + } + + void MainWindow::repeat_hold(int percent){ + (void)percent; + _view->repeat_show(); + } + + void MainWindow::decode_done(){ + _event.decode_done(); //safe call + } + + void MainWindow::on_decode_done(){ + _protocol_widget->update_model(); + } + + void MainWindow::receive_data_len(quint64 len){ + _event.receive_data_len(len);//safe call + } + +void MainWindow::on_receive_data_len(quint64 len){ + _view->set_receive_len(len); +} + +void MainWindow::receive_header(){ + +} + +void MainWindow::data_received(){ + } } // namespace pv diff --git a/DSView/pv/mainwindow.h b/DSView/pv/mainwindow.h index 0af21189..553a58be 100755 --- a/DSView/pv/mainwindow.h +++ b/DSView/pv/mainwindow.h @@ -25,11 +25,12 @@ #define DSVIEW_PV_MAINWINDOW_H #include - #include - -#include "sigsession.h" +#include #include "dialogs/dsmessagebox.h" +#include "interface/icallbacks.h" +#include "eventobject.h" +#include "interface/uicallback.h" class QAction; class QMenuBar; @@ -40,9 +41,10 @@ class QToolBar; class QWidget; class QDockWidget; -namespace pv { +class AppControl; -class DeviceManager; +namespace pv { + namespace toolbars { class SamplingBar; @@ -63,149 +65,166 @@ namespace view { class View; } -class MainWindow : public QMainWindow +namespace device{ + class DevInst; +} + +using namespace pv::device; + +//The mainwindow,referenced by MainFrame +//TODO: create graph view,toolbar,and show device list +class MainWindow : public QMainWindow, public ISessionCallback, public IMainForm, ISessionDataGetter { Q_OBJECT private: static constexpr int Session_Version = 2; - + public: - explicit MainWindow(DeviceManager &device_manager, - const char *open_file_name = NULL, - QWidget *parent = 0); + explicit MainWindow(QWidget *parent = 0); -protected: + void openDoc(); + +private: void closeEvent(QCloseEvent *event); -private: void setup_ui(); - void retranslateUi(); - void session_error(const QString text, const QString info_text); + void retranslateUi(); bool eventFilter(QObject *object, QEvent *event); + bool load_session_json(QJsonDocument json, bool file_dev,bool bDecoder=true); -public slots: - void session_save(); - int language() const; - void openDoc(); - - void switchLanguage(int language); +public slots: void switchTheme(QString style); - void restore_dock(); private slots: - void load_file(QString file_name); - - /** - * Updates the device list in the sampling bar, and updates the - * selection. - * @param selected_device The device to select, or NULL if the - * first device in the device list should be selected. - */ + void on_load_file(QString file_name); + void on_open_doc(); + void on_device_updated_reload(); void update_device_list(); - - void reload(); - - void show_session_error( - const QString text, const QString info_text); - - void run_stop(); - - void instant_stop(); - - void capture_state_changed(int state); - + + void on_run_stop(); + void on_instant_stop(); void on_protocol(bool visible); - void on_trigger(bool visible); - void commit_trigger(bool instant); void on_measure(bool visible); - void on_search(bool visible); - void on_screenShot(); - void on_save(); void on_export(); - - bool load_session(QString name); - bool load_session_json(QJsonDocument json, bool file_dev); - bool store_session(QString name); - - /* - * repeat - */ - void repeat_resume(); - - /* - * hotplug slot function - */ - void device_attach(); - void device_detach(); + bool on_load_session(QString name); + bool on_store_session(QString name); void device_detach_post(); void device_changed(bool close); + void on_device_selected(); - /* - * errors - */ - void show_error(); - + void on_capture_state_changed(int state); + void on_data_updated(); + void on_device_attach(); + void on_device_detach(); + void on_show_error(QString str); + void on_session_error(); + void on_signals_changed(); + void on_receive_trigger(quint64 trigger_pos); + void on_frame_ended(); + void on_frame_began(); + void on_decode_done(); + void on_receive_data_len(quint64 len); + void on_cur_snap_samplerate_changed(); + signals: void prgRate(int progress); +//IMainForm +public: + void switchLanguage(int language); + +//ISessionCallback +public: + void session_save(); + + //ISessionDataGetter private: - DeviceManager &_device_manager; + bool genSessionData(std::string &str); - SigSession _session; - bool _hot_detach; +//ISessionCallback +private: + void show_error(QString error); + void session_error(); + void capture_state_changed(int state); + void device_attach(); + void device_detach(); - pv::view::View *_view; - dialogs::DSMessageBox *_msg; + void data_updated(); + void repeat_resume(); + void update_capture(); + void cur_snap_samplerate_changed(); + void device_setted(); - QMenuBar *_menu_bar; - QMenu *_menu_file; - QAction *_action_open; - QAction *_action_connect; - QAction *_action_quit; + void signals_changed(); + void receive_trigger(quint64 trigger_pos); + void frame_ended(); + void frame_began(); + void show_region(uint64_t start, uint64_t end, bool keep); - QMenu *_menu_view; - QAction *_action_view_zoom_in; - QAction *_action_view_zoom_out; - QAction *_action_view_show_cursors; + void show_wait_trigger(); + void repeat_hold(int percent); + void decode_done(); + void receive_data_len(quint64 len); + void receive_header(); + void data_received(); - QMenu *_menu_help; - QAction *_action_about; + //------private + bool gen_session_json(QJsonArray &array); - QWidget *_central_widget; - QVBoxLayout *_vertical_layout; +private: + AppControl *_control; + bool _hot_detach; - toolbars::SamplingBar *_sampling_bar; - toolbars::TrigBar *_trig_bar; - toolbars::FileBar *_file_bar; - toolbars::LogoBar *_logo_bar; + pv::view::View *_view; + dialogs::DSMessageBox *_msg; -#ifdef ENABLE_DECODE - QDockWidget *_protocol_dock; - dock::ProtocolDock *_protocol_widget; -#endif + QMenuBar *_menu_bar; + QMenu *_menu_file; + QAction *_action_open; + QAction *_action_connect; + QAction *_action_quit; - QDockWidget *_trigger_dock; - QDockWidget *_dso_trigger_dock; - dock::TriggerDock *_trigger_widget; - dock::DsoTriggerDock *_dso_trigger_widget; - QDockWidget *_measure_dock; - dock::MeasureDock *_measure_widget; - QDockWidget *_search_dock; - dock::SearchDock * _search_widget; + QMenu *_menu_view; + QAction *_action_view_zoom_in; + QAction *_action_view_zoom_out; + QAction *_action_view_show_cursors; - int _language; - QString _style; - QTranslator _qtTrans; - QTranslator _myTrans; + QMenu *_menu_help; + QAction *_action_about; + + QWidget *_central_widget; + QVBoxLayout *_vertical_layout; + + toolbars::SamplingBar *_sampling_bar; + toolbars::TrigBar *_trig_bar; + toolbars::FileBar *_file_bar; + toolbars::LogoBar *_logo_bar; //help button, on top right + + + QDockWidget *_protocol_dock; + dock::ProtocolDock *_protocol_widget; + QDockWidget *_trigger_dock; + QDockWidget *_dso_trigger_dock; + dock::TriggerDock *_trigger_widget; + dock::DsoTriggerDock *_dso_trigger_widget; + QDockWidget *_measure_dock; + dock::MeasureDock *_measure_widget; + QDockWidget *_search_dock; + dock::SearchDock *_search_widget; + + QTranslator _qtTrans; + QTranslator _myTrans; + EventObject _event; + bool _bFirstLoad; }; } // namespace pv diff --git a/DSView/pv/minizip/crypt.h b/DSView/pv/minizip/crypt.h new file mode 100644 index 00000000..1e9e8200 --- /dev/null +++ b/DSView/pv/minizip/crypt.h @@ -0,0 +1,131 @@ +/* crypt.h -- base code for crypt/uncrypt ZIPfile + + + Version 1.01e, February 12th, 2005 + + Copyright (C) 1998-2005 Gilles Vollant + + This code is a modified version of crypting code in Infozip distribution + + The encryption/decryption parts of this source code (as opposed to the + non-echoing password parts) were originally written in Europe. The + whole source package can be freely distributed, including from the USA. + (Prior to January 2000, re-export from the US was a violation of US law.) + + This encryption code is a direct transcription of the algorithm from + Roger Schlafly, described by Phil Katz in the file appnote.txt. This + file (appnote.txt) is distributed with the PKZIP program (even in the + version without encryption capabilities). + + If you don't need crypting in your application, just define symbols + NOCRYPT and NOUNCRYPT. + + This code support the "Traditional PKWARE Encryption". + + The new AES encryption added on Zip format by Winzip (see the page + http://www.winzip.com/aes_info.htm ) and PKWare PKZip 5.x Strong + Encryption is not supported. +*/ + +#define CRC32(c, b) ((*(pcrc_32_tab+(((int)(c) ^ (b)) & 0xff))) ^ ((c) >> 8)) + +/*********************************************************************** + * Return the next byte in the pseudo-random sequence + */ +static int decrypt_byte(unsigned long* pkeys, const z_crc_t* pcrc_32_tab) +{ + unsigned temp; /* POTENTIAL BUG: temp*(temp^1) may overflow in an + * unpredictable manner on 16-bit systems; not a problem + * with any known compiler so far, though */ + + temp = ((unsigned)(*(pkeys+2)) & 0xffff) | 2; + return (int)(((temp * (temp ^ 1)) >> 8) & 0xff); +} + +/*********************************************************************** + * Update the encryption keys with the next byte of plain text + */ +static int update_keys(unsigned long* pkeys,const z_crc_t* pcrc_32_tab,int c) +{ + (*(pkeys+0)) = CRC32((*(pkeys+0)), c); + (*(pkeys+1)) += (*(pkeys+0)) & 0xff; + (*(pkeys+1)) = (*(pkeys+1)) * 134775813L + 1; + { + register int keyshift = (int)((*(pkeys+1)) >> 24); + (*(pkeys+2)) = CRC32((*(pkeys+2)), keyshift); + } + return c; +} + + +/*********************************************************************** + * Initialize the encryption keys and the random header according to + * the given password. + */ +static void init_keys(const char* passwd,unsigned long* pkeys,const z_crc_t* pcrc_32_tab) +{ + *(pkeys+0) = 305419896L; + *(pkeys+1) = 591751049L; + *(pkeys+2) = 878082192L; + while (*passwd != '\0') { + update_keys(pkeys,pcrc_32_tab,(int)*passwd); + passwd++; + } +} + +#define zdecode(pkeys,pcrc_32_tab,c) \ + (update_keys(pkeys,pcrc_32_tab,c ^= decrypt_byte(pkeys,pcrc_32_tab))) + +#define zencode(pkeys,pcrc_32_tab,c,t) \ + (t=decrypt_byte(pkeys,pcrc_32_tab), update_keys(pkeys,pcrc_32_tab,c), t^(c)) + +#ifdef INCLUDECRYPTINGCODE_IFCRYPTALLOWED + +#define RAND_HEAD_LEN 12 + /* "last resort" source for second part of crypt seed pattern */ +# ifndef ZCR_SEED2 +# define ZCR_SEED2 3141592654UL /* use PI as default pattern */ +# endif + +static int crypthead(const char* passwd, /* password string */ + unsigned char* buf, /* where to write header */ + int bufSize, + unsigned long* pkeys, + const z_crc_t* pcrc_32_tab, + unsigned long crcForCrypting) +{ + int n; /* index in random header */ + int t; /* temporary */ + int c; /* random byte */ + unsigned char header[RAND_HEAD_LEN-2]; /* random header */ + static unsigned calls = 0; /* ensure different random header each time */ + + if (bufSize> 7) & 0xff; + header[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, c, t); + } + /* Encrypt random header (last two bytes is high word of crc) */ + init_keys(passwd, pkeys, pcrc_32_tab); + for (n = 0; n < RAND_HEAD_LEN-2; n++) + { + buf[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, header[n], t); + } + buf[n++] = (unsigned char)zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 16) & 0xff, t); + buf[n++] = (unsigned char)zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 24) & 0xff, t); + return n; +} + +#endif diff --git a/DSView/pv/minizip/ioapi.c b/DSView/pv/minizip/ioapi.c new file mode 100644 index 00000000..7f5c191b --- /dev/null +++ b/DSView/pv/minizip/ioapi.c @@ -0,0 +1,247 @@ +/* ioapi.h -- IO base function header for compress/uncompress .zip + part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications for Zip64 support + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) + + For more info read MiniZip_info.txt + +*/ + +#if defined(_WIN32) && (!(defined(_CRT_SECURE_NO_WARNINGS))) + #define _CRT_SECURE_NO_WARNINGS +#endif + +#if defined(__APPLE__) || defined(IOAPI_NO_64) +// In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions +#define FOPEN_FUNC(filename, mode) fopen(filename, mode) +#define FTELLO_FUNC(stream) ftello(stream) +#define FSEEKO_FUNC(stream, offset, origin) fseeko(stream, offset, origin) +#else +#define FOPEN_FUNC(filename, mode) fopen64(filename, mode) +#define FTELLO_FUNC(stream) ftello64(stream) +#define FSEEKO_FUNC(stream, offset, origin) fseeko64(stream, offset, origin) +#endif + + +#include "ioapi.h" + +voidpf call_zopen64 (const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode) +{ + if (pfilefunc->zfile_func64.zopen64_file != NULL) + return (*(pfilefunc->zfile_func64.zopen64_file)) (pfilefunc->zfile_func64.opaque,filename,mode); + else + { + return (*(pfilefunc->zopen32_file))(pfilefunc->zfile_func64.opaque,(const char*)filename,mode); + } +} + +long call_zseek64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin) +{ + if (pfilefunc->zfile_func64.zseek64_file != NULL) + return (*(pfilefunc->zfile_func64.zseek64_file)) (pfilefunc->zfile_func64.opaque,filestream,offset,origin); + else + { + uLong offsetTruncated = (uLong)offset; + if (offsetTruncated != offset) + return -1; + else + return (*(pfilefunc->zseek32_file))(pfilefunc->zfile_func64.opaque,filestream,offsetTruncated,origin); + } +} + +ZPOS64_T call_ztell64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream) +{ + if (pfilefunc->zfile_func64.zseek64_file != NULL) + return (*(pfilefunc->zfile_func64.ztell64_file)) (pfilefunc->zfile_func64.opaque,filestream); + else + { + uLong tell_uLong = (*(pfilefunc->ztell32_file))(pfilefunc->zfile_func64.opaque,filestream); + if ((tell_uLong) == MAXU32) + return (ZPOS64_T)-1; + else + return tell_uLong; + } +} + +void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32) +{ + p_filefunc64_32->zfile_func64.zopen64_file = NULL; + p_filefunc64_32->zopen32_file = p_filefunc32->zopen_file; + p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file; + p_filefunc64_32->zfile_func64.zread_file = p_filefunc32->zread_file; + p_filefunc64_32->zfile_func64.zwrite_file = p_filefunc32->zwrite_file; + p_filefunc64_32->zfile_func64.ztell64_file = NULL; + p_filefunc64_32->zfile_func64.zseek64_file = NULL; + p_filefunc64_32->zfile_func64.zclose_file = p_filefunc32->zclose_file; + p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file; + p_filefunc64_32->zfile_func64.opaque = p_filefunc32->opaque; + p_filefunc64_32->zseek32_file = p_filefunc32->zseek_file; + p_filefunc64_32->ztell32_file = p_filefunc32->ztell_file; +} + + + +static voidpf ZCALLBACK fopen_file_func OF((voidpf opaque, const char* filename, int mode)); +static uLong ZCALLBACK fread_file_func OF((voidpf opaque, voidpf stream, void* buf, uLong size)); +static uLong ZCALLBACK fwrite_file_func OF((voidpf opaque, voidpf stream, const void* buf,uLong size)); +static ZPOS64_T ZCALLBACK ftell64_file_func OF((voidpf opaque, voidpf stream)); +static long ZCALLBACK fseek64_file_func OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin)); +static int ZCALLBACK fclose_file_func OF((voidpf opaque, voidpf stream)); +static int ZCALLBACK ferror_file_func OF((voidpf opaque, voidpf stream)); + +static voidpf ZCALLBACK fopen_file_func (voidpf opaque, const char* filename, int mode) +{ + FILE* file = NULL; + const char* mode_fopen = NULL; + if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) + mode_fopen = "rb"; + else + if (mode & ZLIB_FILEFUNC_MODE_EXISTING) + mode_fopen = "r+b"; + else + if (mode & ZLIB_FILEFUNC_MODE_CREATE) + mode_fopen = "wb"; + + if ((filename!=NULL) && (mode_fopen != NULL)) + file = fopen(filename, mode_fopen); + return file; +} + +static voidpf ZCALLBACK fopen64_file_func (voidpf opaque, const void* filename, int mode) +{ + FILE* file = NULL; + const char* mode_fopen = NULL; + if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) + mode_fopen = "rb"; + else + if (mode & ZLIB_FILEFUNC_MODE_EXISTING) + mode_fopen = "r+b"; + else + if (mode & ZLIB_FILEFUNC_MODE_CREATE) + mode_fopen = "wb"; + + if ((filename!=NULL) && (mode_fopen != NULL)) + file = FOPEN_FUNC((const char*)filename, mode_fopen); + return file; +} + + +static uLong ZCALLBACK fread_file_func (voidpf opaque, voidpf stream, void* buf, uLong size) +{ + uLong ret; + ret = (uLong)fread(buf, 1, (size_t)size, (FILE *)stream); + return ret; +} + +static uLong ZCALLBACK fwrite_file_func (voidpf opaque, voidpf stream, const void* buf, uLong size) +{ + uLong ret; + ret = (uLong)fwrite(buf, 1, (size_t)size, (FILE *)stream); + return ret; +} + +static long ZCALLBACK ftell_file_func (voidpf opaque, voidpf stream) +{ + long ret; + ret = ftell((FILE *)stream); + return ret; +} + + +static ZPOS64_T ZCALLBACK ftell64_file_func (voidpf opaque, voidpf stream) +{ + ZPOS64_T ret; + ret = FTELLO_FUNC((FILE *)stream); + return ret; +} + +static long ZCALLBACK fseek_file_func (voidpf opaque, voidpf stream, uLong offset, int origin) +{ + int fseek_origin=0; + long ret; + switch (origin) + { + case ZLIB_FILEFUNC_SEEK_CUR : + fseek_origin = SEEK_CUR; + break; + case ZLIB_FILEFUNC_SEEK_END : + fseek_origin = SEEK_END; + break; + case ZLIB_FILEFUNC_SEEK_SET : + fseek_origin = SEEK_SET; + break; + default: return -1; + } + ret = 0; + if (fseek((FILE *)stream, offset, fseek_origin) != 0) + ret = -1; + return ret; +} + +static long ZCALLBACK fseek64_file_func (voidpf opaque, voidpf stream, ZPOS64_T offset, int origin) +{ + int fseek_origin=0; + long ret; + switch (origin) + { + case ZLIB_FILEFUNC_SEEK_CUR : + fseek_origin = SEEK_CUR; + break; + case ZLIB_FILEFUNC_SEEK_END : + fseek_origin = SEEK_END; + break; + case ZLIB_FILEFUNC_SEEK_SET : + fseek_origin = SEEK_SET; + break; + default: return -1; + } + ret = 0; + + if(FSEEKO_FUNC((FILE *)stream, offset, fseek_origin) != 0) + ret = -1; + + return ret; +} + + +static int ZCALLBACK fclose_file_func (voidpf opaque, voidpf stream) +{ + int ret; + ret = fclose((FILE *)stream); + return ret; +} + +static int ZCALLBACK ferror_file_func (voidpf opaque, voidpf stream) +{ + int ret; + ret = ferror((FILE *)stream); + return ret; +} + +void fill_fopen_filefunc (pzlib_filefunc_def) + zlib_filefunc_def* pzlib_filefunc_def; +{ + pzlib_filefunc_def->zopen_file = fopen_file_func; + pzlib_filefunc_def->zread_file = fread_file_func; + pzlib_filefunc_def->zwrite_file = fwrite_file_func; + pzlib_filefunc_def->ztell_file = ftell_file_func; + pzlib_filefunc_def->zseek_file = fseek_file_func; + pzlib_filefunc_def->zclose_file = fclose_file_func; + pzlib_filefunc_def->zerror_file = ferror_file_func; + pzlib_filefunc_def->opaque = NULL; +} + +void fill_fopen64_filefunc (zlib_filefunc64_def* pzlib_filefunc_def) +{ + pzlib_filefunc_def->zopen64_file = fopen64_file_func; + pzlib_filefunc_def->zread_file = fread_file_func; + pzlib_filefunc_def->zwrite_file = fwrite_file_func; + pzlib_filefunc_def->ztell64_file = ftell64_file_func; + pzlib_filefunc_def->zseek64_file = fseek64_file_func; + pzlib_filefunc_def->zclose_file = fclose_file_func; + pzlib_filefunc_def->zerror_file = ferror_file_func; + pzlib_filefunc_def->opaque = NULL; +} diff --git a/DSView/pv/minizip/ioapi.h b/DSView/pv/minizip/ioapi.h new file mode 100644 index 00000000..8dcbdb06 --- /dev/null +++ b/DSView/pv/minizip/ioapi.h @@ -0,0 +1,208 @@ +/* ioapi.h -- IO base function header for compress/uncompress .zip + part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications for Zip64 support + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) + + For more info read MiniZip_info.txt + + Changes + + Oct-2009 - Defined ZPOS64_T to fpos_t on windows and u_int64_t on linux. (might need to find a better why for this) + Oct-2009 - Change to fseeko64, ftello64 and fopen64 so large files would work on linux. + More if/def section may be needed to support other platforms + Oct-2009 - Defined fxxxx64 calls to normal fopen/ftell/fseek so they would compile on windows. + (but you should use iowin32.c for windows instead) + +*/ + +#ifndef _ZLIBIOAPI64_H +#define _ZLIBIOAPI64_H + +#if (!defined(_WIN32)) && (!defined(WIN32)) && (!defined(__APPLE__)) + + // Linux needs this to support file operation on files larger then 4+GB + // But might need better if/def to select just the platforms that needs them. + + #ifndef __USE_FILE_OFFSET64 + #define __USE_FILE_OFFSET64 + #endif + #ifndef __USE_LARGEFILE64 + #define __USE_LARGEFILE64 + #endif + #ifndef _LARGEFILE64_SOURCE + #define _LARGEFILE64_SOURCE + #endif + #ifndef _FILE_OFFSET_BIT + #define _FILE_OFFSET_BIT 64 + #endif + +#endif + +#include +#include +#include "zlib.h" + +#if defined(USE_FILE32API) +#define fopen64 fopen +#define ftello64 ftell +#define fseeko64 fseek +#else +#ifdef __FreeBSD__ +#define fopen64 fopen +#define ftello64 ftello +#define fseeko64 fseeko +#endif +#ifdef _MSC_VER + #define fopen64 fopen + #if (_MSC_VER >= 1400) && (!(defined(NO_MSCVER_FILE64_FUNC))) + #define ftello64 _ftelli64 + #define fseeko64 _fseeki64 + #else // old MSC + #define ftello64 ftell + #define fseeko64 fseek + #endif +#endif +#endif + +/* +#ifndef ZPOS64_T + #ifdef _WIN32 + #define ZPOS64_T fpos_t + #else + #include + #define ZPOS64_T uint64_t + #endif +#endif +*/ + +#ifdef HAVE_MINIZIP64_CONF_H +#include "mz64conf.h" +#endif + +/* a type choosen by DEFINE */ +#ifdef HAVE_64BIT_INT_CUSTOM +typedef 64BIT_INT_CUSTOM_TYPE ZPOS64_T; +#else +#ifdef HAS_STDINT_H +#include "stdint.h" +typedef uint64_t ZPOS64_T; +#else + +/* Maximum unsigned 32-bit value used as placeholder for zip64 */ +#define MAXU32 0xffffffff + +#if defined(_MSC_VER) || defined(__BORLANDC__) +typedef unsigned __int64 ZPOS64_T; +#else +typedef unsigned long long int ZPOS64_T; +#endif +#endif +#endif + + + +#ifdef __cplusplus +extern "C" { +#endif + + +#define ZLIB_FILEFUNC_SEEK_CUR (1) +#define ZLIB_FILEFUNC_SEEK_END (2) +#define ZLIB_FILEFUNC_SEEK_SET (0) + +#define ZLIB_FILEFUNC_MODE_READ (1) +#define ZLIB_FILEFUNC_MODE_WRITE (2) +#define ZLIB_FILEFUNC_MODE_READWRITEFILTER (3) + +#define ZLIB_FILEFUNC_MODE_EXISTING (4) +#define ZLIB_FILEFUNC_MODE_CREATE (8) + + +#ifndef ZCALLBACK + #if (defined(WIN32) || defined(_WIN32) || defined (WINDOWS) || defined (_WINDOWS)) && defined(CALLBACK) && defined (USEWINDOWS_CALLBACK) + #define ZCALLBACK CALLBACK + #else + #define ZCALLBACK + #endif +#endif + + + + +typedef voidpf (ZCALLBACK *open_file_func) OF((voidpf opaque, const char* filename, int mode)); +typedef uLong (ZCALLBACK *read_file_func) OF((voidpf opaque, voidpf stream, void* buf, uLong size)); +typedef uLong (ZCALLBACK *write_file_func) OF((voidpf opaque, voidpf stream, const void* buf, uLong size)); +typedef int (ZCALLBACK *close_file_func) OF((voidpf opaque, voidpf stream)); +typedef int (ZCALLBACK *testerror_file_func) OF((voidpf opaque, voidpf stream)); + +typedef long (ZCALLBACK *tell_file_func) OF((voidpf opaque, voidpf stream)); +typedef long (ZCALLBACK *seek_file_func) OF((voidpf opaque, voidpf stream, uLong offset, int origin)); + + +/* here is the "old" 32 bits structure structure */ +typedef struct zlib_filefunc_def_s +{ + open_file_func zopen_file; + read_file_func zread_file; + write_file_func zwrite_file; + tell_file_func ztell_file; + seek_file_func zseek_file; + close_file_func zclose_file; + testerror_file_func zerror_file; + voidpf opaque; +} zlib_filefunc_def; + +typedef ZPOS64_T (ZCALLBACK *tell64_file_func) OF((voidpf opaque, voidpf stream)); +typedef long (ZCALLBACK *seek64_file_func) OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin)); +typedef voidpf (ZCALLBACK *open64_file_func) OF((voidpf opaque, const void* filename, int mode)); + +typedef struct zlib_filefunc64_def_s +{ + open64_file_func zopen64_file; + read_file_func zread_file; + write_file_func zwrite_file; + tell64_file_func ztell64_file; + seek64_file_func zseek64_file; + close_file_func zclose_file; + testerror_file_func zerror_file; + voidpf opaque; +} zlib_filefunc64_def; + +void fill_fopen64_filefunc OF((zlib_filefunc64_def* pzlib_filefunc_def)); +void fill_fopen_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def)); + +/* now internal definition, only for zip.c and unzip.h */ +typedef struct zlib_filefunc64_32_def_s +{ + zlib_filefunc64_def zfile_func64; + open_file_func zopen32_file; + tell_file_func ztell32_file; + seek_file_func zseek32_file; +} zlib_filefunc64_32_def; + + +#define ZREAD64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zread_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size)) +#define ZWRITE64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zwrite_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size)) +//#define ZTELL64(filefunc,filestream) ((*((filefunc).ztell64_file)) ((filefunc).opaque,filestream)) +//#define ZSEEK64(filefunc,filestream,pos,mode) ((*((filefunc).zseek64_file)) ((filefunc).opaque,filestream,pos,mode)) +#define ZCLOSE64(filefunc,filestream) ((*((filefunc).zfile_func64.zclose_file)) ((filefunc).zfile_func64.opaque,filestream)) +#define ZERROR64(filefunc,filestream) ((*((filefunc).zfile_func64.zerror_file)) ((filefunc).zfile_func64.opaque,filestream)) + +voidpf call_zopen64 OF((const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode)); +long call_zseek64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin)); +ZPOS64_T call_ztell64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream)); + +void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32); + +#define ZOPEN64(filefunc,filename,mode) (call_zopen64((&(filefunc)),(filename),(mode))) +#define ZTELL64(filefunc,filestream) (call_ztell64((&(filefunc)),(filestream))) +#define ZSEEK64(filefunc,filestream,pos,mode) (call_zseek64((&(filefunc)),(filestream),(pos),(mode))) + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/DSView/pv/minizip/iowin32.c b/DSView/pv/minizip/iowin32.c new file mode 100644 index 00000000..274f39eb --- /dev/null +++ b/DSView/pv/minizip/iowin32.c @@ -0,0 +1,462 @@ +/* iowin32.c -- IO base function header for compress/uncompress .zip + Version 1.1, February 14h, 2010 + part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications for Zip64 support + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) + + For more info read MiniZip_info.txt + +*/ + +#include + +#include "zlib.h" +#include "ioapi.h" +#include "iowin32.h" + +#ifndef INVALID_HANDLE_VALUE +#define INVALID_HANDLE_VALUE (0xFFFFFFFF) +#endif + +#ifndef INVALID_SET_FILE_POINTER +#define INVALID_SET_FILE_POINTER ((DWORD)-1) +#endif + + +// see Include/shared/winapifamily.h in the Windows Kit +#if defined(WINAPI_FAMILY_PARTITION) && (!(defined(IOWIN32_USING_WINRT_API))) +#if WINAPI_FAMILY_ONE_PARTITION(WINAPI_FAMILY, WINAPI_PARTITION_APP) +#define IOWIN32_USING_WINRT_API 1 +#endif +#endif + +voidpf ZCALLBACK win32_open_file_func OF((voidpf opaque, const char* filename, int mode)); +uLong ZCALLBACK win32_read_file_func OF((voidpf opaque, voidpf stream, void* buf, uLong size)); +uLong ZCALLBACK win32_write_file_func OF((voidpf opaque, voidpf stream, const void* buf, uLong size)); +ZPOS64_T ZCALLBACK win32_tell64_file_func OF((voidpf opaque, voidpf stream)); +long ZCALLBACK win32_seek64_file_func OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin)); +int ZCALLBACK win32_close_file_func OF((voidpf opaque, voidpf stream)); +int ZCALLBACK win32_error_file_func OF((voidpf opaque, voidpf stream)); + +typedef struct +{ + HANDLE hf; + int error; +} WIN32FILE_IOWIN; + + +static void win32_translate_open_mode(int mode, + DWORD* lpdwDesiredAccess, + DWORD* lpdwCreationDisposition, + DWORD* lpdwShareMode, + DWORD* lpdwFlagsAndAttributes) +{ + *lpdwDesiredAccess = *lpdwShareMode = *lpdwFlagsAndAttributes = *lpdwCreationDisposition = 0; + + if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) + { + *lpdwDesiredAccess = GENERIC_READ; + *lpdwCreationDisposition = OPEN_EXISTING; + *lpdwShareMode = FILE_SHARE_READ; + } + else if (mode & ZLIB_FILEFUNC_MODE_EXISTING) + { + *lpdwDesiredAccess = GENERIC_WRITE | GENERIC_READ; + *lpdwCreationDisposition = OPEN_EXISTING; + } + else if (mode & ZLIB_FILEFUNC_MODE_CREATE) + { + *lpdwDesiredAccess = GENERIC_WRITE | GENERIC_READ; + *lpdwCreationDisposition = CREATE_ALWAYS; + } +} + +static voidpf win32_build_iowin(HANDLE hFile) +{ + voidpf ret=NULL; + + if ((hFile != NULL) && (hFile != INVALID_HANDLE_VALUE)) + { + WIN32FILE_IOWIN w32fiow; + w32fiow.hf = hFile; + w32fiow.error = 0; + ret = malloc(sizeof(WIN32FILE_IOWIN)); + + if (ret==NULL) + CloseHandle(hFile); + else + *((WIN32FILE_IOWIN*)ret) = w32fiow; + } + return ret; +} + +voidpf ZCALLBACK win32_open64_file_func (voidpf opaque,const void* filename,int mode) +{ + const char* mode_fopen = NULL; + DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ; + HANDLE hFile = NULL; + + win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes); + +#ifdef IOWIN32_USING_WINRT_API +#ifdef UNICODE + if ((filename!=NULL) && (dwDesiredAccess != 0)) + hFile = CreateFile2((LPCTSTR)filename, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL); +#else + if ((filename!=NULL) && (dwDesiredAccess != 0)) + { + WCHAR filenameW[FILENAME_MAX + 0x200 + 1]; + MultiByteToWideChar(CP_ACP,0,(const char*)filename,-1,filenameW,FILENAME_MAX + 0x200); + hFile = CreateFile2(filenameW, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL); + } +#endif +#else + if ((filename!=NULL) && (dwDesiredAccess != 0)) + hFile = CreateFile((LPCTSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL); +#endif + + return win32_build_iowin(hFile); +} + + +voidpf ZCALLBACK win32_open64_file_funcA (voidpf opaque,const void* filename,int mode) +{ + const char* mode_fopen = NULL; + DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ; + HANDLE hFile = NULL; + + win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes); + +#ifdef IOWIN32_USING_WINRT_API + if ((filename!=NULL) && (dwDesiredAccess != 0)) + { + WCHAR filenameW[FILENAME_MAX + 0x200 + 1]; + MultiByteToWideChar(CP_ACP,0,(const char*)filename,-1,filenameW,FILENAME_MAX + 0x200); + hFile = CreateFile2(filenameW, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL); + } +#else + if ((filename!=NULL) && (dwDesiredAccess != 0)) + hFile = CreateFileA((LPCSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL); +#endif + + return win32_build_iowin(hFile); +} + + +voidpf ZCALLBACK win32_open64_file_funcW (voidpf opaque,const void* filename,int mode) +{ + const char* mode_fopen = NULL; + DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ; + HANDLE hFile = NULL; + + win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes); + +#ifdef IOWIN32_USING_WINRT_API + if ((filename!=NULL) && (dwDesiredAccess != 0)) + hFile = CreateFile2((LPCWSTR)filename, dwDesiredAccess, dwShareMode, dwCreationDisposition,NULL); +#else + if ((filename!=NULL) && (dwDesiredAccess != 0)) + hFile = CreateFileW((LPCWSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL); +#endif + + return win32_build_iowin(hFile); +} + + +voidpf ZCALLBACK win32_open_file_func (voidpf opaque,const char* filename,int mode) +{ + const char* mode_fopen = NULL; + DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ; + HANDLE hFile = NULL; + + win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes); + +#ifdef IOWIN32_USING_WINRT_API +#ifdef UNICODE + if ((filename!=NULL) && (dwDesiredAccess != 0)) + hFile = CreateFile2((LPCTSTR)filename, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL); +#else + if ((filename!=NULL) && (dwDesiredAccess != 0)) + { + WCHAR filenameW[FILENAME_MAX + 0x200 + 1]; + MultiByteToWideChar(CP_ACP,0,(const char*)filename,-1,filenameW,FILENAME_MAX + 0x200); + hFile = CreateFile2(filenameW, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL); + } +#endif +#else + if ((filename!=NULL) && (dwDesiredAccess != 0)) + hFile = CreateFile((LPCTSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL); +#endif + + return win32_build_iowin(hFile); +} + + +uLong ZCALLBACK win32_read_file_func (voidpf opaque, voidpf stream, void* buf,uLong size) +{ + uLong ret=0; + HANDLE hFile = NULL; + if (stream!=NULL) + hFile = ((WIN32FILE_IOWIN*)stream) -> hf; + + if (hFile != NULL) + { + if (!ReadFile(hFile, buf, size, &ret, NULL)) + { + DWORD dwErr = GetLastError(); + if (dwErr == ERROR_HANDLE_EOF) + dwErr = 0; + ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr; + } + } + + return ret; +} + + +uLong ZCALLBACK win32_write_file_func (voidpf opaque,voidpf stream,const void* buf,uLong size) +{ + uLong ret=0; + HANDLE hFile = NULL; + if (stream!=NULL) + hFile = ((WIN32FILE_IOWIN*)stream) -> hf; + + if (hFile != NULL) + { + if (!WriteFile(hFile, buf, size, &ret, NULL)) + { + DWORD dwErr = GetLastError(); + if (dwErr == ERROR_HANDLE_EOF) + dwErr = 0; + ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr; + } + } + + return ret; +} + +static BOOL MySetFilePointerEx(HANDLE hFile, LARGE_INTEGER pos, LARGE_INTEGER *newPos, DWORD dwMoveMethod) +{ +#ifdef IOWIN32_USING_WINRT_API + return SetFilePointerEx(hFile, pos, newPos, dwMoveMethod); +#else + LONG lHigh = pos.HighPart; + DWORD dwNewPos = SetFilePointer(hFile, pos.LowPart, &lHigh, dwMoveMethod); + BOOL fOk = TRUE; + if (dwNewPos == 0xFFFFFFFF) + if (GetLastError() != NO_ERROR) + fOk = FALSE; + if ((newPos != NULL) && (fOk)) + { + newPos->LowPart = dwNewPos; + newPos->HighPart = lHigh; + } + return fOk; +#endif +} + +long ZCALLBACK win32_tell_file_func (voidpf opaque,voidpf stream) +{ + long ret=-1; + HANDLE hFile = NULL; + if (stream!=NULL) + hFile = ((WIN32FILE_IOWIN*)stream) -> hf; + if (hFile != NULL) + { + LARGE_INTEGER pos; + pos.QuadPart = 0; + + if (!MySetFilePointerEx(hFile, pos, &pos, FILE_CURRENT)) + { + DWORD dwErr = GetLastError(); + ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr; + ret = -1; + } + else + ret=(long)pos.LowPart; + } + return ret; +} + +ZPOS64_T ZCALLBACK win32_tell64_file_func (voidpf opaque, voidpf stream) +{ + ZPOS64_T ret= (ZPOS64_T)-1; + HANDLE hFile = NULL; + if (stream!=NULL) + hFile = ((WIN32FILE_IOWIN*)stream)->hf; + + if (hFile) + { + LARGE_INTEGER pos; + pos.QuadPart = 0; + + if (!MySetFilePointerEx(hFile, pos, &pos, FILE_CURRENT)) + { + DWORD dwErr = GetLastError(); + ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr; + ret = (ZPOS64_T)-1; + } + else + ret=pos.QuadPart; + } + return ret; +} + + +long ZCALLBACK win32_seek_file_func (voidpf opaque,voidpf stream,uLong offset,int origin) +{ + DWORD dwMoveMethod=0xFFFFFFFF; + HANDLE hFile = NULL; + + long ret=-1; + if (stream!=NULL) + hFile = ((WIN32FILE_IOWIN*)stream) -> hf; + switch (origin) + { + case ZLIB_FILEFUNC_SEEK_CUR : + dwMoveMethod = FILE_CURRENT; + break; + case ZLIB_FILEFUNC_SEEK_END : + dwMoveMethod = FILE_END; + break; + case ZLIB_FILEFUNC_SEEK_SET : + dwMoveMethod = FILE_BEGIN; + break; + default: return -1; + } + + if (hFile != NULL) + { + LARGE_INTEGER pos; + pos.QuadPart = offset; + if (!MySetFilePointerEx(hFile, pos, NULL, dwMoveMethod)) + { + DWORD dwErr = GetLastError(); + ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr; + ret = -1; + } + else + ret=0; + } + return ret; +} + +long ZCALLBACK win32_seek64_file_func (voidpf opaque, voidpf stream,ZPOS64_T offset,int origin) +{ + DWORD dwMoveMethod=0xFFFFFFFF; + HANDLE hFile = NULL; + long ret=-1; + + if (stream!=NULL) + hFile = ((WIN32FILE_IOWIN*)stream)->hf; + + switch (origin) + { + case ZLIB_FILEFUNC_SEEK_CUR : + dwMoveMethod = FILE_CURRENT; + break; + case ZLIB_FILEFUNC_SEEK_END : + dwMoveMethod = FILE_END; + break; + case ZLIB_FILEFUNC_SEEK_SET : + dwMoveMethod = FILE_BEGIN; + break; + default: return -1; + } + + if (hFile) + { + LARGE_INTEGER pos; + pos.QuadPart = offset; + if (!MySetFilePointerEx(hFile, pos, NULL, dwMoveMethod)) + { + DWORD dwErr = GetLastError(); + ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr; + ret = -1; + } + else + ret=0; + } + return ret; +} + +int ZCALLBACK win32_close_file_func (voidpf opaque, voidpf stream) +{ + int ret=-1; + + if (stream!=NULL) + { + HANDLE hFile; + hFile = ((WIN32FILE_IOWIN*)stream) -> hf; + if (hFile != NULL) + { + CloseHandle(hFile); + ret=0; + } + free(stream); + } + return ret; +} + +int ZCALLBACK win32_error_file_func (voidpf opaque,voidpf stream) +{ + int ret=-1; + if (stream!=NULL) + { + ret = ((WIN32FILE_IOWIN*)stream) -> error; + } + return ret; +} + +void fill_win32_filefunc (zlib_filefunc_def* pzlib_filefunc_def) +{ + pzlib_filefunc_def->zopen_file = win32_open_file_func; + pzlib_filefunc_def->zread_file = win32_read_file_func; + pzlib_filefunc_def->zwrite_file = win32_write_file_func; + pzlib_filefunc_def->ztell_file = win32_tell_file_func; + pzlib_filefunc_def->zseek_file = win32_seek_file_func; + pzlib_filefunc_def->zclose_file = win32_close_file_func; + pzlib_filefunc_def->zerror_file = win32_error_file_func; + pzlib_filefunc_def->opaque = NULL; +} + +void fill_win32_filefunc64(zlib_filefunc64_def* pzlib_filefunc_def) +{ + pzlib_filefunc_def->zopen64_file = win32_open64_file_func; + pzlib_filefunc_def->zread_file = win32_read_file_func; + pzlib_filefunc_def->zwrite_file = win32_write_file_func; + pzlib_filefunc_def->ztell64_file = win32_tell64_file_func; + pzlib_filefunc_def->zseek64_file = win32_seek64_file_func; + pzlib_filefunc_def->zclose_file = win32_close_file_func; + pzlib_filefunc_def->zerror_file = win32_error_file_func; + pzlib_filefunc_def->opaque = NULL; +} + + +void fill_win32_filefunc64A(zlib_filefunc64_def* pzlib_filefunc_def) +{ + pzlib_filefunc_def->zopen64_file = win32_open64_file_funcA; + pzlib_filefunc_def->zread_file = win32_read_file_func; + pzlib_filefunc_def->zwrite_file = win32_write_file_func; + pzlib_filefunc_def->ztell64_file = win32_tell64_file_func; + pzlib_filefunc_def->zseek64_file = win32_seek64_file_func; + pzlib_filefunc_def->zclose_file = win32_close_file_func; + pzlib_filefunc_def->zerror_file = win32_error_file_func; + pzlib_filefunc_def->opaque = NULL; +} + + +void fill_win32_filefunc64W(zlib_filefunc64_def* pzlib_filefunc_def) +{ + pzlib_filefunc_def->zopen64_file = win32_open64_file_funcW; + pzlib_filefunc_def->zread_file = win32_read_file_func; + pzlib_filefunc_def->zwrite_file = win32_write_file_func; + pzlib_filefunc_def->ztell64_file = win32_tell64_file_func; + pzlib_filefunc_def->zseek64_file = win32_seek64_file_func; + pzlib_filefunc_def->zclose_file = win32_close_file_func; + pzlib_filefunc_def->zerror_file = win32_error_file_func; + pzlib_filefunc_def->opaque = NULL; +} diff --git a/DSView/pv/minizip/iowin32.h b/DSView/pv/minizip/iowin32.h new file mode 100644 index 00000000..0ca0969a --- /dev/null +++ b/DSView/pv/minizip/iowin32.h @@ -0,0 +1,28 @@ +/* iowin32.h -- IO base function header for compress/uncompress .zip + Version 1.1, February 14h, 2010 + part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications for Zip64 support + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) + + For more info read MiniZip_info.txt + +*/ + +#include + + +#ifdef __cplusplus +extern "C" { +#endif + +void fill_win32_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def)); +void fill_win32_filefunc64 OF((zlib_filefunc64_def* pzlib_filefunc_def)); +void fill_win32_filefunc64A OF((zlib_filefunc64_def* pzlib_filefunc_def)); +void fill_win32_filefunc64W OF((zlib_filefunc64_def* pzlib_filefunc_def)); + +#ifdef __cplusplus +} +#endif diff --git a/DSView/pv/minizip/miniunz.c b/DSView/pv/minizip/miniunz.c new file mode 100644 index 00000000..3d65401b --- /dev/null +++ b/DSView/pv/minizip/miniunz.c @@ -0,0 +1,660 @@ +/* + miniunz.c + Version 1.1, February 14h, 2010 + sample part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications of Unzip for Zip64 + Copyright (C) 2007-2008 Even Rouault + + Modifications for Zip64 support on both zip and unzip + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) +*/ + +#if (!defined(_WIN32)) && (!defined(WIN32)) && (!defined(__APPLE__)) + #ifndef __USE_FILE_OFFSET64 + #define __USE_FILE_OFFSET64 + #endif + #ifndef __USE_LARGEFILE64 + #define __USE_LARGEFILE64 + #endif + #ifndef _LARGEFILE64_SOURCE + #define _LARGEFILE64_SOURCE + #endif + #ifndef _FILE_OFFSET_BIT + #define _FILE_OFFSET_BIT 64 + #endif +#endif + +#ifdef __APPLE__ +// In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions +#define FOPEN_FUNC(filename, mode) fopen(filename, mode) +#define FTELLO_FUNC(stream) ftello(stream) +#define FSEEKO_FUNC(stream, offset, origin) fseeko(stream, offset, origin) +#else +#define FOPEN_FUNC(filename, mode) fopen64(filename, mode) +#define FTELLO_FUNC(stream) ftello64(stream) +#define FSEEKO_FUNC(stream, offset, origin) fseeko64(stream, offset, origin) +#endif + + +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +# include +# include +#else +# include +# include +#endif + + +#include "unzip.h" + +#define CASESENSITIVITY (0) +#define WRITEBUFFERSIZE (8192) +#define MAXFILENAME (256) + +#ifdef _WIN32 +#define USEWIN32IOAPI +#include "iowin32.h" +#endif +/* + mini unzip, demo of unzip package + + usage : + Usage : miniunz [-exvlo] file.zip [file_to_extract] [-d extractdir] + + list the file in the zipfile, and print the content of FILE_ID.ZIP or README.TXT + if it exists +*/ + + +/* change_file_date : change the date/time of a file + filename : the filename of the file where date/time must be modified + dosdate : the new date at the MSDos format (4 bytes) + tmu_date : the SAME new date at the tm_unz format */ +void change_file_date(filename,dosdate,tmu_date) + const char *filename; + uLong dosdate; + tm_unz tmu_date; +{ +#ifdef _WIN32 + HANDLE hFile; + FILETIME ftm,ftLocal,ftCreate,ftLastAcc,ftLastWrite; + + hFile = CreateFileA(filename,GENERIC_READ | GENERIC_WRITE, + 0,NULL,OPEN_EXISTING,0,NULL); + GetFileTime(hFile,&ftCreate,&ftLastAcc,&ftLastWrite); + DosDateTimeToFileTime((WORD)(dosdate>>16),(WORD)dosdate,&ftLocal); + LocalFileTimeToFileTime(&ftLocal,&ftm); + SetFileTime(hFile,&ftm,&ftLastAcc,&ftm); + CloseHandle(hFile); +#else +#ifdef unix || __APPLE__ + struct utimbuf ut; + struct tm newdate; + newdate.tm_sec = tmu_date.tm_sec; + newdate.tm_min=tmu_date.tm_min; + newdate.tm_hour=tmu_date.tm_hour; + newdate.tm_mday=tmu_date.tm_mday; + newdate.tm_mon=tmu_date.tm_mon; + if (tmu_date.tm_year > 1900) + newdate.tm_year=tmu_date.tm_year - 1900; + else + newdate.tm_year=tmu_date.tm_year ; + newdate.tm_isdst=-1; + + ut.actime=ut.modtime=mktime(&newdate); + utime(filename,&ut); +#endif +#endif +} + + +/* mymkdir and change_file_date are not 100 % portable + As I don't know well Unix, I wait feedback for the unix portion */ + +int mymkdir(dirname) + const char* dirname; +{ + int ret=0; +#ifdef _WIN32 + ret = _mkdir(dirname); +#elif unix + ret = mkdir (dirname,0775); +#elif __APPLE__ + ret = mkdir (dirname,0775); +#endif + return ret; +} + +int makedir (newdir) + char *newdir; +{ + char *buffer ; + char *p; + int len = (int)strlen(newdir); + + if (len <= 0) + return 0; + + buffer = (char*)malloc(len+1); + if (buffer==NULL) + { + printf("Error allocating memory\n"); + return UNZ_INTERNALERROR; + } + strcpy(buffer,newdir); + + if (buffer[len-1] == '/') { + buffer[len-1] = '\0'; + } + if (mymkdir(buffer) == 0) + { + free(buffer); + return 1; + } + + p = buffer+1; + while (1) + { + char hold; + + while(*p && *p != '\\' && *p != '/') + p++; + hold = *p; + *p = 0; + if ((mymkdir(buffer) == -1) && (errno == ENOENT)) + { + printf("couldn't create directory %s\n",buffer); + free(buffer); + return 0; + } + if (hold == 0) + break; + *p++ = hold; + } + free(buffer); + return 1; +} + +void do_banner() +{ + printf("MiniUnz 1.01b, demo of zLib + Unz package written by Gilles Vollant\n"); + printf("more info at http://www.winimage.com/zLibDll/unzip.html\n\n"); +} + +void do_help() +{ + printf("Usage : miniunz [-e] [-x] [-v] [-l] [-o] [-p password] file.zip [file_to_extr.] [-d extractdir]\n\n" \ + " -e Extract without pathname (junk paths)\n" \ + " -x Extract with pathname\n" \ + " -v list files\n" \ + " -l list files\n" \ + " -d directory to extract into\n" \ + " -o overwrite files without prompting\n" \ + " -p extract crypted file using password\n\n"); +} + +void Display64BitsSize(ZPOS64_T n, int size_char) +{ + /* to avoid compatibility problem , we do here the conversion */ + char number[21]; + int offset=19; + int pos_string = 19; + number[20]=0; + for (;;) { + number[offset]=(char)((n%10)+'0'); + if (number[offset] != '0') + pos_string=offset; + n/=10; + if (offset==0) + break; + offset--; + } + { + int size_display_string = 19-pos_string; + while (size_char > size_display_string) + { + size_char--; + printf(" "); + } + } + + printf("%s",&number[pos_string]); +} + +int do_list(uf) + unzFile uf; +{ + uLong i; + unz_global_info64 gi; + int err; + + err = unzGetGlobalInfo64(uf,&gi); + if (err!=UNZ_OK) + printf("error %d with zipfile in unzGetGlobalInfo \n",err); + printf(" Length Method Size Ratio Date Time CRC-32 Name\n"); + printf(" ------ ------ ---- ----- ---- ---- ------ ----\n"); + for (i=0;i0) + ratio = (uLong)((file_info.compressed_size*100)/file_info.uncompressed_size); + + /* display a '*' if the file is crypted */ + if ((file_info.flag & 1) != 0) + charCrypt='*'; + + if (file_info.compression_method==0) + string_method="Stored"; + else + if (file_info.compression_method==Z_DEFLATED) + { + uInt iLevel=(uInt)((file_info.flag & 0x6)/2); + if (iLevel==0) + string_method="Defl:N"; + else if (iLevel==1) + string_method="Defl:X"; + else if ((iLevel==2) || (iLevel==3)) + string_method="Defl:F"; /* 2:fast , 3 : extra fast*/ + } + else + if (file_info.compression_method==Z_BZIP2ED) + { + string_method="BZip2 "; + } + else + string_method="Unkn. "; + + Display64BitsSize(file_info.uncompressed_size,7); + printf(" %6s%c",string_method,charCrypt); + Display64BitsSize(file_info.compressed_size,7); + printf(" %3lu%% %2.2lu-%2.2lu-%2.2lu %2.2lu:%2.2lu %8.8lx %s\n", + ratio, + (uLong)file_info.tmu_date.tm_mon + 1, + (uLong)file_info.tmu_date.tm_mday, + (uLong)file_info.tmu_date.tm_year % 100, + (uLong)file_info.tmu_date.tm_hour,(uLong)file_info.tmu_date.tm_min, + (uLong)file_info.crc,filename_inzip); + if ((i+1)='a') && (rep<='z')) + rep -= 0x20; + } + while ((rep!='Y') && (rep!='N') && (rep!='A')); + } + + if (rep == 'N') + skip = 1; + + if (rep == 'A') + *popt_overwrite=1; + } + + if ((skip==0) && (err==UNZ_OK)) + { + fout=FOPEN_FUNC(write_filename,"wb"); + /* some zipfile don't contain directory alone before file */ + if ((fout==NULL) && ((*popt_extract_without_path)==0) && + (filename_withoutpath!=(char*)filename_inzip)) + { + char c=*(filename_withoutpath-1); + *(filename_withoutpath-1)='\0'; + makedir(write_filename); + *(filename_withoutpath-1)=c; + fout=FOPEN_FUNC(write_filename,"wb"); + } + + if (fout==NULL) + { + printf("error opening %s\n",write_filename); + } + } + + if (fout!=NULL) + { + printf(" extracting: %s\n",write_filename); + + do + { + err = unzReadCurrentFile(uf,buf,size_buf); + if (err<0) + { + printf("error %d with zipfile in unzReadCurrentFile\n",err); + break; + } + if (err>0) + if (fwrite(buf,err,1,fout)!=1) + { + printf("error in writing extracted file\n"); + err=UNZ_ERRNO; + break; + } + } + while (err>0); + if (fout) + fclose(fout); + + if (err==0) + change_file_date(write_filename,file_info.dosDate, + file_info.tmu_date); + } + + if (err==UNZ_OK) + { + err = unzCloseCurrentFile (uf); + if (err!=UNZ_OK) + { + printf("error %d with zipfile in unzCloseCurrentFile\n",err); + } + } + else + unzCloseCurrentFile(uf); /* don't lose the error */ + } + + free(buf); + return err; +} + + +int do_extract(uf,opt_extract_without_path,opt_overwrite,password) + unzFile uf; + int opt_extract_without_path; + int opt_overwrite; + const char* password; +{ + uLong i; + unz_global_info64 gi; + int err; + FILE* fout=NULL; + + err = unzGetGlobalInfo64(uf,&gi); + if (err!=UNZ_OK) + printf("error %d with zipfile in unzGetGlobalInfo \n",err); + + for (i=0;i +#include +#include +#include +#include +#include + +#ifdef _WIN32 +# include +# include +#else +# include +# include +# include +# include +#endif + +#include "zip.h" + +#ifdef _WIN32 + #define USEWIN32IOAPI + #include "iowin32.h" +#endif + + + +#define WRITEBUFFERSIZE (16384) +#define MAXFILENAME (256) + +#ifdef _WIN32 +uLong filetime(f, tmzip, dt) + char *f; /* name of file to get info on */ + tm_zip *tmzip; /* return value: access, modific. and creation times */ + uLong *dt; /* dostime */ +{ + int ret = 0; + { + FILETIME ftLocal; + HANDLE hFind; + WIN32_FIND_DATAA ff32; + + hFind = FindFirstFileA(f,&ff32); + if (hFind != INVALID_HANDLE_VALUE) + { + FileTimeToLocalFileTime(&(ff32.ftLastWriteTime),&ftLocal); + FileTimeToDosDateTime(&ftLocal,((LPWORD)dt)+1,((LPWORD)dt)+0); + FindClose(hFind); + ret = 1; + } + } + return ret; +} +#else +#ifdef unix || __APPLE__ +uLong filetime(f, tmzip, dt) + char *f; /* name of file to get info on */ + tm_zip *tmzip; /* return value: access, modific. and creation times */ + uLong *dt; /* dostime */ +{ + int ret=0; + struct stat s; /* results of stat() */ + struct tm* filedate; + time_t tm_t=0; + + if (strcmp(f,"-")!=0) + { + char name[MAXFILENAME+1]; + int len = strlen(f); + if (len > MAXFILENAME) + len = MAXFILENAME; + + strncpy(name, f,MAXFILENAME-1); + /* strncpy doesnt append the trailing NULL, of the string is too long. */ + name[ MAXFILENAME ] = '\0'; + + if (name[len - 1] == '/') + name[len - 1] = '\0'; + /* not all systems allow stat'ing a file with / appended */ + if (stat(name,&s)==0) + { + tm_t = s.st_mtime; + ret = 1; + } + } + filedate = localtime(&tm_t); + + tmzip->tm_sec = filedate->tm_sec; + tmzip->tm_min = filedate->tm_min; + tmzip->tm_hour = filedate->tm_hour; + tmzip->tm_mday = filedate->tm_mday; + tmzip->tm_mon = filedate->tm_mon ; + tmzip->tm_year = filedate->tm_year; + + return ret; +} +#else +uLong filetime(f, tmzip, dt) + char *f; /* name of file to get info on */ + tm_zip *tmzip; /* return value: access, modific. and creation times */ + uLong *dt; /* dostime */ +{ + return 0; +} +#endif +#endif + + + + +int check_exist_file(filename) + const char* filename; +{ + FILE* ftestexist; + int ret = 1; + ftestexist = FOPEN_FUNC(filename,"rb"); + if (ftestexist==NULL) + ret = 0; + else + fclose(ftestexist); + return ret; +} + +void do_banner() +{ + printf("MiniZip 1.1, demo of zLib + MiniZip64 package, written by Gilles Vollant\n"); + printf("more info on MiniZip at http://www.winimage.com/zLibDll/minizip.html\n\n"); +} + +void do_help() +{ + printf("Usage : minizip [-o] [-a] [-0 to -9] [-p password] [-j] file.zip [files_to_add]\n\n" \ + " -o Overwrite existing file.zip\n" \ + " -a Append to existing file.zip\n" \ + " -0 Store only\n" \ + " -1 Compress faster\n" \ + " -9 Compress better\n\n" \ + " -j exclude path. store only the file name.\n\n"); +} + +/* calculate the CRC32 of a file, + because to encrypt a file, we need known the CRC32 of the file before */ +int getFileCrc(const char* filenameinzip,void*buf,unsigned long size_buf,unsigned long* result_crc) +{ + unsigned long calculate_crc=0; + int err=ZIP_OK; + FILE * fin = FOPEN_FUNC(filenameinzip,"rb"); + + unsigned long size_read = 0; + unsigned long total_read = 0; + if (fin==NULL) + { + err = ZIP_ERRNO; + } + + if (err == ZIP_OK) + do + { + err = ZIP_OK; + size_read = (int)fread(buf,1,size_buf,fin); + if (size_read < size_buf) + if (feof(fin)==0) + { + printf("error in reading %s\n",filenameinzip); + err = ZIP_ERRNO; + } + + if (size_read>0) + calculate_crc = crc32(calculate_crc,buf,size_read); + total_read += size_read; + + } while ((err == ZIP_OK) && (size_read>0)); + + if (fin) + fclose(fin); + + *result_crc=calculate_crc; + printf("file %s crc %lx\n", filenameinzip, calculate_crc); + return err; +} + +int isLargeFile(const char* filename) +{ + int largeFile = 0; + ZPOS64_T pos = 0; + FILE* pFile = FOPEN_FUNC(filename, "rb"); + + if(pFile != NULL) + { + int n = FSEEKO_FUNC(pFile, 0, SEEK_END); + pos = FTELLO_FUNC(pFile); + + printf("File : %s is %lld bytes\n", filename, pos); + + if(pos >= 0xffffffff) + largeFile = 1; + + fclose(pFile); + } + + return largeFile; +} + +int main(argc,argv) + int argc; + char *argv[]; +{ + int i; + int opt_overwrite=0; + int opt_compress_level=Z_DEFAULT_COMPRESSION; + int opt_exclude_path=0; + int zipfilenamearg = 0; + char filename_try[MAXFILENAME+16]; + int zipok; + int err=0; + int size_buf=0; + void* buf=NULL; + const char* password=NULL; + + + do_banner(); + if (argc==1) + { + do_help(); + return 0; + } + else + { + for (i=1;i='0') && (c<='9')) + opt_compress_level = c-'0'; + if ((c=='j') || (c=='J')) + opt_exclude_path = 1; + + if (((c=='p') || (c=='P')) && (i+1='a') && (rep<='z')) + rep -= 0x20; + } + while ((rep!='Y') && (rep!='N') && (rep!='A')); + if (rep=='N') + zipok = 0; + if (rep=='A') + opt_overwrite = 2; + } + } + + if (zipok==1) + { + zipFile zf; + int errclose; +# ifdef USEWIN32IOAPI + zlib_filefunc64_def ffunc; + fill_win32_filefunc64A(&ffunc); + zf = zipOpen2_64(filename_try,(opt_overwrite==2) ? 2 : 0,NULL,&ffunc); +# else + zf = zipOpen64(filename_try,(opt_overwrite==2) ? 2 : 0); +# endif + + if (zf == NULL) + { + printf("error opening %s\n",filename_try); + err= ZIP_ERRNO; + } + else + printf("creating %s\n",filename_try); + + for (i=zipfilenamearg+1;(i='0') || (argv[i][1]<='9'))) && + (strlen(argv[i]) == 2))) + { + FILE * fin; + int size_read; + const char* filenameinzip = argv[i]; + const char *savefilenameinzip; + zip_fileinfo zi; + unsigned long crcFile=0; + int zip64 = 0; + + zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour = + zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0; + zi.dosDate = 0; + zi.internal_fa = 0; + zi.external_fa = 0; + filetime(filenameinzip,&zi.tmz_date,&zi.dosDate); + +/* + err = zipOpenNewFileInZip(zf,filenameinzip,&zi, + NULL,0,NULL,0,NULL / * comment * /, + (opt_compress_level != 0) ? Z_DEFLATED : 0, + opt_compress_level); +*/ + if ((password != NULL) && (err==ZIP_OK)) + err = getFileCrc(filenameinzip,buf,size_buf,&crcFile); + + zip64 = isLargeFile(filenameinzip); + + /* The path name saved, should not include a leading slash. */ + /*if it did, windows/xp and dynazip couldn't read the zip file. */ + savefilenameinzip = filenameinzip; + while( savefilenameinzip[0] == '\\' || savefilenameinzip[0] == '/' ) + { + savefilenameinzip++; + } + + /*should the zip file contain any path at all?*/ + if( opt_exclude_path ) + { + const char *tmpptr; + const char *lastslash = 0; + for( tmpptr = savefilenameinzip; *tmpptr; tmpptr++) + { + if( *tmpptr == '\\' || *tmpptr == '/') + { + lastslash = tmpptr; + } + } + if( lastslash != NULL ) + { + savefilenameinzip = lastslash+1; // base filename follows last slash. + } + } + + /**/ + err = zipOpenNewFileInZip3_64(zf,savefilenameinzip,&zi, + NULL,0,NULL,0,NULL /* comment*/, + (opt_compress_level != 0) ? Z_DEFLATED : 0, + opt_compress_level,0, + /* -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, */ + -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, + password,crcFile, zip64); + + if (err != ZIP_OK) + printf("error in opening %s in zipfile\n",filenameinzip); + else + { + fin = FOPEN_FUNC(filenameinzip,"rb"); + if (fin==NULL) + { + err=ZIP_ERRNO; + printf("error in opening %s for reading\n",filenameinzip); + } + } + + if (err == ZIP_OK) + do + { + err = ZIP_OK; + size_read = (int)fread(buf,1,size_buf,fin); + if (size_read < size_buf) + if (feof(fin)==0) + { + printf("error in reading %s\n",filenameinzip); + err = ZIP_ERRNO; + } + + if (size_read>0) + { + err = zipWriteInFileInZip (zf,buf,size_read); + if (err<0) + { + printf("error in writing %s in the zipfile\n", + filenameinzip); + } + + } + } while ((err == ZIP_OK) && (size_read>0)); + + if (fin) + fclose(fin); + + if (err<0) + err=ZIP_ERRNO; + else + { + err = zipCloseFileInZip(zf); + if (err!=ZIP_OK) + printf("error in closing %s in the zipfile\n", + filenameinzip); + } + } + } + errclose = zipClose(zf,NULL); + if (errclose != ZIP_OK) + printf("error in closing %s\n",filename_try); + } + else + { + do_help(); + } + + free(buf); + return 0; +} diff --git a/DSView/pv/minizip/mztools.c b/DSView/pv/minizip/mztools.c new file mode 100644 index 00000000..6047d70c --- /dev/null +++ b/DSView/pv/minizip/mztools.c @@ -0,0 +1,291 @@ +/* + Additional tools for Minizip + Code: Xavier Roche '2004 + License: Same as ZLIB (www.gzip.org) +*/ + +/* Code */ +#include +#include +#include +#include "zlib.h" +#include "unzip.h" + +#define READ_8(adr) ((unsigned char)*(adr)) +#define READ_16(adr) ( READ_8(adr) | (READ_8(adr+1) << 8) +#define READ_32(adr) ( READ_16(adr) | (READ_16((adr)+2) << 16) + +#define WRITE_8(buff, n) do { \ + *((unsigned char*)(buff)) = (unsigned char) ((n) & 0xff); \ +} while(0) +#define WRITE_16(buff, n) do { \ + WRITE_8((unsigned char*)(buff), n); \ + WRITE_8(((unsigned char*)(buff)) + 1, (n) >> 8); \ +} while(0) +#define WRITE_32(buff, n) do { \ + WRITE_16((unsigned char*)(buff), (n) & 0xffff); \ + WRITE_16((unsigned char*)(buff) + 2, (n) >> 16); \ +} while(0) + +extern int ZEXPORT unzRepair(file, fileOut, fileOutTmp, nRecovered, bytesRecovered) +const char* file; +const char* fileOut; +const char* fileOutTmp; +uLong* nRecovered; +uLong* bytesRecovered; +{ + int err = Z_OK; + FILE* fpZip = fopen(file, "rb"); + FILE* fpOut = fopen(fileOut, "wb"); + FILE* fpOutCD = fopen(fileOutTmp, "wb"); + if (fpZip != NULL && fpOut != NULL) { + int entries = 0; + uLong totalBytes = 0; + char header[30]; + char filename[1024]; + char extra[1024]; + int offset = 0; + int offsetCD = 0; + while ( fread(header, 1, 30, fpZip) == 30 ) { + int currentOffset = offset; + + /* File entry */ + if (READ_32(header) == 0x04034b50) { + unsigned int version = READ_16(header + 4); + unsigned int gpflag = READ_16(header + 6); + unsigned int method = READ_16(header + 8); + unsigned int filetime = READ_16(header + 10); + unsigned int filedate = READ_16(header + 12); + unsigned int crc = READ_32(header + 14); /* crc */ + unsigned int cpsize = READ_32(header + 18); /* compressed size */ + unsigned int uncpsize = READ_32(header + 22); /* uncompressed sz */ + unsigned int fnsize = READ_16(header + 26); /* file name length */ + unsigned int extsize = READ_16(header + 28); /* extra field length */ + filename[0] = extra[0] = '\0'; + + /* Header */ + if (fwrite(header, 1, 30, fpOut) == 30) { + offset += 30; + } else { + err = Z_ERRNO; + break; + } + + /* Filename */ + if (fnsize > 0) { + if (fnsize < sizeof(filename)) { + if (fread(filename, 1, fnsize, fpZip) == fnsize) { + if (fwrite(filename, 1, fnsize, fpOut) == fnsize) { + offset += fnsize; + } else { + err = Z_ERRNO; + break; + } + } else { + err = Z_ERRNO; + break; + } + } else { + err = Z_ERRNO; + break; + } + } else { + err = Z_STREAM_ERROR; + break; + } + + /* Extra field */ + if (extsize > 0) { + if (extsize < sizeof(extra)) { + if (fread(extra, 1, extsize, fpZip) == extsize) { + if (fwrite(extra, 1, extsize, fpOut) == extsize) { + offset += extsize; + } else { + err = Z_ERRNO; + break; + } + } else { + err = Z_ERRNO; + break; + } + } else { + err = Z_ERRNO; + break; + } + } + + /* Data */ + { + int dataSize = cpsize; + if (dataSize == 0) { + dataSize = uncpsize; + } + if (dataSize > 0) { + char* data = malloc(dataSize); + if (data != NULL) { + if ((int)fread(data, 1, dataSize, fpZip) == dataSize) { + if ((int)fwrite(data, 1, dataSize, fpOut) == dataSize) { + offset += dataSize; + totalBytes += dataSize; + } else { + err = Z_ERRNO; + } + } else { + err = Z_ERRNO; + } + free(data); + if (err != Z_OK) { + break; + } + } else { + err = Z_MEM_ERROR; + break; + } + } + } + + /* Central directory entry */ + { + char header[46]; + char* comment = ""; + int comsize = (int) strlen(comment); + WRITE_32(header, 0x02014b50); + WRITE_16(header + 4, version); + WRITE_16(header + 6, version); + WRITE_16(header + 8, gpflag); + WRITE_16(header + 10, method); + WRITE_16(header + 12, filetime); + WRITE_16(header + 14, filedate); + WRITE_32(header + 16, crc); + WRITE_32(header + 20, cpsize); + WRITE_32(header + 24, uncpsize); + WRITE_16(header + 28, fnsize); + WRITE_16(header + 30, extsize); + WRITE_16(header + 32, comsize); + WRITE_16(header + 34, 0); /* disk # */ + WRITE_16(header + 36, 0); /* int attrb */ + WRITE_32(header + 38, 0); /* ext attrb */ + WRITE_32(header + 42, currentOffset); + /* Header */ + if (fwrite(header, 1, 46, fpOutCD) == 46) { + offsetCD += 46; + + /* Filename */ + if (fnsize > 0) { + if (fwrite(filename, 1, fnsize, fpOutCD) == fnsize) { + offsetCD += fnsize; + } else { + err = Z_ERRNO; + break; + } + } else { + err = Z_STREAM_ERROR; + break; + } + + /* Extra field */ + if (extsize > 0) { + if (fwrite(extra, 1, extsize, fpOutCD) == extsize) { + offsetCD += extsize; + } else { + err = Z_ERRNO; + break; + } + } + + /* Comment field */ + if (comsize > 0) { + if ((int)fwrite(comment, 1, comsize, fpOutCD) == comsize) { + offsetCD += comsize; + } else { + err = Z_ERRNO; + break; + } + } + + + } else { + err = Z_ERRNO; + break; + } + } + + /* Success */ + entries++; + + } else { + break; + } + } + + /* Final central directory */ + { + int entriesZip = entries; + char header[22]; + char* comment = ""; // "ZIP File recovered by zlib/minizip/mztools"; + int comsize = (int) strlen(comment); + if (entriesZip > 0xffff) { + entriesZip = 0xffff; + } + WRITE_32(header, 0x06054b50); + WRITE_16(header + 4, 0); /* disk # */ + WRITE_16(header + 6, 0); /* disk # */ + WRITE_16(header + 8, entriesZip); /* hack */ + WRITE_16(header + 10, entriesZip); /* hack */ + WRITE_32(header + 12, offsetCD); /* size of CD */ + WRITE_32(header + 16, offset); /* offset to CD */ + WRITE_16(header + 20, comsize); /* comment */ + + /* Header */ + if (fwrite(header, 1, 22, fpOutCD) == 22) { + + /* Comment field */ + if (comsize > 0) { + if ((int)fwrite(comment, 1, comsize, fpOutCD) != comsize) { + err = Z_ERRNO; + } + } + + } else { + err = Z_ERRNO; + } + } + + /* Final merge (file + central directory) */ + fclose(fpOutCD); + if (err == Z_OK) { + fpOutCD = fopen(fileOutTmp, "rb"); + if (fpOutCD != NULL) { + int nRead; + char buffer[8192]; + while ( (nRead = (int)fread(buffer, 1, sizeof(buffer), fpOutCD)) > 0) { + if ((int)fwrite(buffer, 1, nRead, fpOut) != nRead) { + err = Z_ERRNO; + break; + } + } + fclose(fpOutCD); + } + } + + /* Close */ + fclose(fpZip); + fclose(fpOut); + + /* Wipe temporary file */ + (void)remove(fileOutTmp); + + /* Number of recovered entries */ + if (err == Z_OK) { + if (nRecovered != NULL) { + *nRecovered = entries; + } + if (bytesRecovered != NULL) { + *bytesRecovered = totalBytes; + } + } + } else { + err = Z_STREAM_ERROR; + } + return err; +} diff --git a/DSView/pv/minizip/mztools.h b/DSView/pv/minizip/mztools.h new file mode 100644 index 00000000..a49a426e --- /dev/null +++ b/DSView/pv/minizip/mztools.h @@ -0,0 +1,37 @@ +/* + Additional tools for Minizip + Code: Xavier Roche '2004 + License: Same as ZLIB (www.gzip.org) +*/ + +#ifndef _zip_tools_H +#define _zip_tools_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef _ZLIB_H +#include "zlib.h" +#endif + +#include "unzip.h" + +/* Repair a ZIP file (missing central directory) + file: file to recover + fileOut: output file after recovery + fileOutTmp: temporary file name used for recovery +*/ +extern int ZEXPORT unzRepair(const char* file, + const char* fileOut, + const char* fileOutTmp, + uLong* nRecovered, + uLong* bytesRecovered); + + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/DSView/pv/minizip/unzip.c b/DSView/pv/minizip/unzip.c new file mode 100644 index 00000000..bcfb9416 --- /dev/null +++ b/DSView/pv/minizip/unzip.c @@ -0,0 +1,2125 @@ +/* unzip.c -- IO for uncompress .zip files using zlib + Version 1.1, February 14h, 2010 + part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications of Unzip for Zip64 + Copyright (C) 2007-2008 Even Rouault + + Modifications for Zip64 support on both zip and unzip + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) + + For more info read MiniZip_info.txt + + + ------------------------------------------------------------------------------------ + Decryption code comes from crypt.c by Info-ZIP but has been greatly reduced in terms of + compatibility with older software. The following is from the original crypt.c. + Code woven in by Terry Thorsen 1/2003. + + Copyright (c) 1990-2000 Info-ZIP. All rights reserved. + + See the accompanying file LICENSE, version 2000-Apr-09 or later + (the contents of which are also included in zip.h) for terms of use. + If, for some reason, all these files are missing, the Info-ZIP license + also may be found at: ftp://ftp.info-zip.org/pub/infozip/license.html + + crypt.c (full version) by Info-ZIP. Last revised: [see crypt.h] + + The encryption/decryption parts of this source code (as opposed to the + non-echoing password parts) were originally written in Europe. The + whole source package can be freely distributed, including from the USA. + (Prior to January 2000, re-export from the US was a violation of US law.) + + This encryption code is a direct transcription of the algorithm from + Roger Schlafly, described by Phil Katz in the file appnote.txt. This + file (appnote.txt) is distributed with the PKZIP program (even in the + version without encryption capabilities). + + ------------------------------------------------------------------------------------ + + Changes in unzip.c + + 2007-2008 - Even Rouault - Addition of cpl_unzGetCurrentFileZStreamPos + 2007-2008 - Even Rouault - Decoration of symbol names unz* -> cpl_unz* + 2007-2008 - Even Rouault - Remove old C style function prototypes + 2007-2008 - Even Rouault - Add unzip support for ZIP64 + + Copyright (C) 2007-2008 Even Rouault + + + Oct-2009 - Mathias Svensson - Removed cpl_* from symbol names (Even Rouault added them but since this is now moved to a new project (minizip64) I renamed them again). + Oct-2009 - Mathias Svensson - Fixed problem if uncompressed size was > 4G and compressed size was <4G + should only read the compressed/uncompressed size from the Zip64 format if + the size from normal header was 0xFFFFFFFF + Oct-2009 - Mathias Svensson - Applied some bug fixes from paches recived from Gilles Vollant + Oct-2009 - Mathias Svensson - Applied support to unzip files with compression mathod BZIP2 (bzip2 lib is required) + Patch created by Daniel Borca + + Jan-2010 - back to unzip and minizip 1.0 name scheme, with compatibility layer + + Copyright (C) 1998 - 2010 Gilles Vollant, Even Rouault, Mathias Svensson + +*/ + + +#include +#include +#include + +#ifndef NOUNCRYPT + #define NOUNCRYPT +#endif + +#include "zlib.h" +#include "unzip.h" + +#ifdef STDC +# include +# include +# include +#endif +#ifdef NO_ERRNO_H + extern int errno; +#else +# include +#endif + + +#ifndef local +# define local static +#endif +/* compile with -Dlocal if your debugger can't find static symbols */ + + +#ifndef CASESENSITIVITYDEFAULT_NO +# if !defined(unix) && !defined(CASESENSITIVITYDEFAULT_YES) +# define CASESENSITIVITYDEFAULT_NO +# endif +#endif + + +#ifndef UNZ_BUFSIZE +#define UNZ_BUFSIZE (16384) +#endif + +#ifndef UNZ_MAXFILENAMEINZIP +#define UNZ_MAXFILENAMEINZIP (256) +#endif + +#ifndef ALLOC +# define ALLOC(size) (malloc(size)) +#endif +#ifndef TRYFREE +# define TRYFREE(p) {if (p) free(p);} +#endif + +#define SIZECENTRALDIRITEM (0x2e) +#define SIZEZIPLOCALHEADER (0x1e) + + +const char unz_copyright[] = + " unzip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll"; + +/* unz_file_info_interntal contain internal info about a file in zipfile*/ +typedef struct unz_file_info64_internal_s +{ + ZPOS64_T offset_curfile;/* relative offset of local header 8 bytes */ +} unz_file_info64_internal; + + +/* file_in_zip_read_info_s contain internal information about a file in zipfile, + when reading and decompress it */ +typedef struct +{ + char *read_buffer; /* internal buffer for compressed data */ + z_stream stream; /* zLib stream structure for inflate */ + +#ifdef HAVE_BZIP2 + bz_stream bstream; /* bzLib stream structure for bziped */ +#endif + + ZPOS64_T pos_in_zipfile; /* position in byte on the zipfile, for fseek*/ + uLong stream_initialised; /* flag set if stream structure is initialised*/ + + ZPOS64_T offset_local_extrafield;/* offset of the local extra field */ + uInt size_local_extrafield;/* size of the local extra field */ + ZPOS64_T pos_local_extrafield; /* position in the local extra field in read*/ + ZPOS64_T total_out_64; + + uLong crc32; /* crc32 of all data uncompressed */ + uLong crc32_wait; /* crc32 we must obtain after decompress all */ + ZPOS64_T rest_read_compressed; /* number of byte to be decompressed */ + ZPOS64_T rest_read_uncompressed;/*number of byte to be obtained after decomp*/ + zlib_filefunc64_32_def z_filefunc; + voidpf filestream; /* io structore of the zipfile */ + uLong compression_method; /* compression method (0==store) */ + ZPOS64_T byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ + int raw; +} file_in_zip64_read_info_s; + + +/* unz64_s contain internal information about the zipfile +*/ +typedef struct +{ + zlib_filefunc64_32_def z_filefunc; + int is64bitOpenFunction; + voidpf filestream; /* io structore of the zipfile */ + unz_global_info64 gi; /* public global information */ + ZPOS64_T byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ + ZPOS64_T num_file; /* number of the current file in the zipfile*/ + ZPOS64_T pos_in_central_dir; /* pos of the current file in the central dir*/ + ZPOS64_T current_file_ok; /* flag about the usability of the current file*/ + ZPOS64_T central_pos; /* position of the beginning of the central dir*/ + + ZPOS64_T size_central_dir; /* size of the central directory */ + ZPOS64_T offset_central_dir; /* offset of start of central directory with + respect to the starting disk number */ + + unz_file_info64 cur_file_info; /* public info about the current file in zip*/ + unz_file_info64_internal cur_file_info_internal; /* private info about it*/ + file_in_zip64_read_info_s* pfile_in_zip_read; /* structure about the current + file if we are decompressing it */ + int encrypted; + + int isZip64; + +# ifndef NOUNCRYPT + unsigned long keys[3]; /* keys defining the pseudo-random sequence */ + const z_crc_t* pcrc_32_tab; +# endif +} unz64_s; + + +#ifndef NOUNCRYPT +#include "crypt.h" +#endif + +/* =========================================================================== + Read a byte from a gz_stream; update next_in and avail_in. Return EOF + for end of file. + IN assertion: the stream s has been successfully opened for reading. +*/ + + +local int unz64local_getByte OF(( + const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream, + int *pi)); + +local int unz64local_getByte(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, int *pi) +{ + unsigned char c; + int err = (int)ZREAD64(*pzlib_filefunc_def,filestream,&c,1); + if (err==1) + { + *pi = (int)c; + return UNZ_OK; + } + else + { + if (ZERROR64(*pzlib_filefunc_def,filestream)) + return UNZ_ERRNO; + else + return UNZ_EOF; + } +} + + +/* =========================================================================== + Reads a long in LSB order from the given gz_stream. Sets +*/ +local int unz64local_getShort OF(( + const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream, + uLong *pX)); + +local int unz64local_getShort (const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream, + uLong *pX) +{ + uLong x ; + int i = 0; + int err; + + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x = (uLong)i; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((uLong)i)<<8; + + if (err==UNZ_OK) + *pX = x; + else + *pX = 0; + return err; +} + +local int unz64local_getLong OF(( + const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream, + uLong *pX)); + +local int unz64local_getLong (const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream, + uLong *pX) +{ + uLong x ; + int i = 0; + int err; + + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x = (uLong)i; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((uLong)i)<<8; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((uLong)i)<<16; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((uLong)i)<<24; + + if (err==UNZ_OK) + *pX = x; + else + *pX = 0; + return err; +} + +local int unz64local_getLong64 OF(( + const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream, + ZPOS64_T *pX)); + + +local int unz64local_getLong64 (const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream, + ZPOS64_T *pX) +{ + ZPOS64_T x ; + int i = 0; + int err; + + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x = (ZPOS64_T)i; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((ZPOS64_T)i)<<8; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((ZPOS64_T)i)<<16; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((ZPOS64_T)i)<<24; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((ZPOS64_T)i)<<32; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((ZPOS64_T)i)<<40; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((ZPOS64_T)i)<<48; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((ZPOS64_T)i)<<56; + + if (err==UNZ_OK) + *pX = x; + else + *pX = 0; + return err; +} + +/* My own strcmpi / strcasecmp */ +local int strcmpcasenosensitive_internal (const char* fileName1, const char* fileName2) +{ + for (;;) + { + char c1=*(fileName1++); + char c2=*(fileName2++); + if ((c1>='a') && (c1<='z')) + c1 -= 0x20; + if ((c2>='a') && (c2<='z')) + c2 -= 0x20; + if (c1=='\0') + return ((c2=='\0') ? 0 : -1); + if (c2=='\0') + return 1; + if (c1c2) + return 1; + } +} + + +#ifdef CASESENSITIVITYDEFAULT_NO +#define CASESENSITIVITYDEFAULTVALUE 2 +#else +#define CASESENSITIVITYDEFAULTVALUE 1 +#endif + +#ifndef STRCMPCASENOSENTIVEFUNCTION +#define STRCMPCASENOSENTIVEFUNCTION strcmpcasenosensitive_internal +#endif + +/* + Compare two filename (fileName1,fileName2). + If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp) + If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi + or strcasecmp) + If iCaseSenisivity = 0, case sensitivity is defaut of your operating system + (like 1 on Unix, 2 on Windows) + +*/ +extern int ZEXPORT unzStringFileNameCompare (const char* fileName1, + const char* fileName2, + int iCaseSensitivity) + +{ + if (iCaseSensitivity==0) + iCaseSensitivity=CASESENSITIVITYDEFAULTVALUE; + + if (iCaseSensitivity==1) + return strcmp(fileName1,fileName2); + + return STRCMPCASENOSENTIVEFUNCTION(fileName1,fileName2); +} + +#ifndef BUFREADCOMMENT +#define BUFREADCOMMENT (0x400) +#endif + +/* + Locate the Central directory of a zipfile (at the end, just before + the global comment) +*/ +local ZPOS64_T unz64local_SearchCentralDir OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream)); +local ZPOS64_T unz64local_SearchCentralDir(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream) +{ + unsigned char* buf; + ZPOS64_T uSizeFile; + ZPOS64_T uBackRead; + ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */ + ZPOS64_T uPosFound=0; + + if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0) + return 0; + + + uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream); + + if (uMaxBack>uSizeFile) + uMaxBack = uSizeFile; + + buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4); + if (buf==NULL) + return 0; + + uBackRead = 4; + while (uBackReaduMaxBack) + uBackRead = uMaxBack; + else + uBackRead+=BUFREADCOMMENT; + uReadPos = uSizeFile-uBackRead ; + + uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? + (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos); + if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0) + break; + + if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize) + break; + + for (i=(int)uReadSize-3; (i--)>0;) + if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && + ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06)) + { + uPosFound = uReadPos+i; + break; + } + + if (uPosFound!=0) + break; + } + TRYFREE(buf); + return uPosFound; +} + + +/* + Locate the Central directory 64 of a zipfile (at the end, just before + the global comment) +*/ +local ZPOS64_T unz64local_SearchCentralDir64 OF(( + const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream)); + +local ZPOS64_T unz64local_SearchCentralDir64(const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream) +{ + unsigned char* buf; + ZPOS64_T uSizeFile; + ZPOS64_T uBackRead; + ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */ + ZPOS64_T uPosFound=0; + uLong uL; + ZPOS64_T relativeOffset; + + if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0) + return 0; + + + uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream); + + if (uMaxBack>uSizeFile) + uMaxBack = uSizeFile; + + buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4); + if (buf==NULL) + return 0; + + uBackRead = 4; + while (uBackReaduMaxBack) + uBackRead = uMaxBack; + else + uBackRead+=BUFREADCOMMENT; + uReadPos = uSizeFile-uBackRead ; + + uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? + (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos); + if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0) + break; + + if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize) + break; + + for (i=(int)uReadSize-3; (i--)>0;) + if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && + ((*(buf+i+2))==0x06) && ((*(buf+i+3))==0x07)) + { + uPosFound = uReadPos+i; + break; + } + + if (uPosFound!=0) + break; + } + TRYFREE(buf); + if (uPosFound == 0) + return 0; + + /* Zip64 end of central directory locator */ + if (ZSEEK64(*pzlib_filefunc_def,filestream, uPosFound,ZLIB_FILEFUNC_SEEK_SET)!=0) + return 0; + + /* the signature, already checked */ + if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK) + return 0; + + /* number of the disk with the start of the zip64 end of central directory */ + if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK) + return 0; + if (uL != 0) + return 0; + + /* relative offset of the zip64 end of central directory record */ + if (unz64local_getLong64(pzlib_filefunc_def,filestream,&relativeOffset)!=UNZ_OK) + return 0; + + /* total number of disks */ + if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK) + return 0; + if (uL != 1) + return 0; + + /* Goto end of central directory record */ + if (ZSEEK64(*pzlib_filefunc_def,filestream, relativeOffset,ZLIB_FILEFUNC_SEEK_SET)!=0) + return 0; + + /* the signature */ + if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK) + return 0; + + if (uL != 0x06064b50) + return 0; + + return relativeOffset; +} + +/* + Open a Zip file. path contain the full pathname (by example, + on a Windows NT computer "c:\\test\\zlib114.zip" or on an Unix computer + "zlib/zlib114.zip". + If the zipfile cannot be opened (file doesn't exist or in not valid), the + return value is NULL. + Else, the return value is a unzFile Handle, usable with other function + of this unzip package. +*/ +local unzFile unzOpenInternal (const void *path, + zlib_filefunc64_32_def* pzlib_filefunc64_32_def, + int is64bitOpenFunction) +{ + unz64_s us; + unz64_s *s; + ZPOS64_T central_pos; + uLong uL; + + uLong number_disk; /* number of the current dist, used for + spaning ZIP, unsupported, always 0*/ + uLong number_disk_with_CD; /* number the the disk with central dir, used + for spaning ZIP, unsupported, always 0*/ + ZPOS64_T number_entry_CD; /* total number of entries in + the central dir + (same than number_entry on nospan) */ + + int err=UNZ_OK; + + if (unz_copyright[0]!=' ') + return NULL; + + us.z_filefunc.zseek32_file = NULL; + us.z_filefunc.ztell32_file = NULL; + if (pzlib_filefunc64_32_def==NULL) + fill_fopen64_filefunc(&us.z_filefunc.zfile_func64); + else + us.z_filefunc = *pzlib_filefunc64_32_def; + us.is64bitOpenFunction = is64bitOpenFunction; + + + + us.filestream = ZOPEN64(us.z_filefunc, + path, + ZLIB_FILEFUNC_MODE_READ | + ZLIB_FILEFUNC_MODE_EXISTING); + if (us.filestream==NULL) + return NULL; + + central_pos = unz64local_SearchCentralDir64(&us.z_filefunc,us.filestream); + if (central_pos) + { + uLong uS; + ZPOS64_T uL64; + + us.isZip64 = 1; + + if (ZSEEK64(us.z_filefunc, us.filestream, + central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0) + err=UNZ_ERRNO; + + /* the signature, already checked */ + if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) + err=UNZ_ERRNO; + + /* size of zip64 end of central directory record */ + if (unz64local_getLong64(&us.z_filefunc, us.filestream,&uL64)!=UNZ_OK) + err=UNZ_ERRNO; + + /* version made by */ + if (unz64local_getShort(&us.z_filefunc, us.filestream,&uS)!=UNZ_OK) + err=UNZ_ERRNO; + + /* version needed to extract */ + if (unz64local_getShort(&us.z_filefunc, us.filestream,&uS)!=UNZ_OK) + err=UNZ_ERRNO; + + /* number of this disk */ + if (unz64local_getLong(&us.z_filefunc, us.filestream,&number_disk)!=UNZ_OK) + err=UNZ_ERRNO; + + /* number of the disk with the start of the central directory */ + if (unz64local_getLong(&us.z_filefunc, us.filestream,&number_disk_with_CD)!=UNZ_OK) + err=UNZ_ERRNO; + + /* total number of entries in the central directory on this disk */ + if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.gi.number_entry)!=UNZ_OK) + err=UNZ_ERRNO; + + /* total number of entries in the central directory */ + if (unz64local_getLong64(&us.z_filefunc, us.filestream,&number_entry_CD)!=UNZ_OK) + err=UNZ_ERRNO; + + if ((number_entry_CD!=us.gi.number_entry) || + (number_disk_with_CD!=0) || + (number_disk!=0)) + err=UNZ_BADZIPFILE; + + /* size of the central directory */ + if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.size_central_dir)!=UNZ_OK) + err=UNZ_ERRNO; + + /* offset of start of central directory with respect to the + starting disk number */ + if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.offset_central_dir)!=UNZ_OK) + err=UNZ_ERRNO; + + us.gi.size_comment = 0; + } + else + { + central_pos = unz64local_SearchCentralDir(&us.z_filefunc,us.filestream); + if (central_pos==0) + err=UNZ_ERRNO; + + us.isZip64 = 0; + + if (ZSEEK64(us.z_filefunc, us.filestream, + central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0) + err=UNZ_ERRNO; + + /* the signature, already checked */ + if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) + err=UNZ_ERRNO; + + /* number of this disk */ + if (unz64local_getShort(&us.z_filefunc, us.filestream,&number_disk)!=UNZ_OK) + err=UNZ_ERRNO; + + /* number of the disk with the start of the central directory */ + if (unz64local_getShort(&us.z_filefunc, us.filestream,&number_disk_with_CD)!=UNZ_OK) + err=UNZ_ERRNO; + + /* total number of entries in the central dir on this disk */ + if (unz64local_getShort(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) + err=UNZ_ERRNO; + us.gi.number_entry = uL; + + /* total number of entries in the central dir */ + if (unz64local_getShort(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) + err=UNZ_ERRNO; + number_entry_CD = uL; + + if ((number_entry_CD!=us.gi.number_entry) || + (number_disk_with_CD!=0) || + (number_disk!=0)) + err=UNZ_BADZIPFILE; + + /* size of the central directory */ + if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) + err=UNZ_ERRNO; + us.size_central_dir = uL; + + /* offset of start of central directory with respect to the + starting disk number */ + if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) + err=UNZ_ERRNO; + us.offset_central_dir = uL; + + /* zipfile comment length */ + if (unz64local_getShort(&us.z_filefunc, us.filestream,&us.gi.size_comment)!=UNZ_OK) + err=UNZ_ERRNO; + } + + if ((central_pospfile_in_zip_read!=NULL) + unzCloseCurrentFile(file); + + ZCLOSE64(s->z_filefunc, s->filestream); + TRYFREE(s); + return UNZ_OK; +} + + +/* + Write info about the ZipFile in the *pglobal_info structure. + No preparation of the structure is needed + return UNZ_OK if there is no problem. */ +extern int ZEXPORT unzGetGlobalInfo64 (unzFile file, unz_global_info64* pglobal_info) +{ + unz64_s* s; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + *pglobal_info=s->gi; + return UNZ_OK; +} + +extern int ZEXPORT unzGetGlobalInfo (unzFile file, unz_global_info* pglobal_info32) +{ + unz64_s* s; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + /* to do : check if number_entry is not truncated */ + pglobal_info32->number_entry = (uLong)s->gi.number_entry; + pglobal_info32->size_comment = s->gi.size_comment; + return UNZ_OK; +} +/* + Translate date/time from Dos format to tm_unz (readable more easilty) +*/ +local void unz64local_DosDateToTmuDate (ZPOS64_T ulDosDate, tm_unz* ptm) +{ + ZPOS64_T uDate; + uDate = (ZPOS64_T)(ulDosDate>>16); + ptm->tm_mday = (uInt)(uDate&0x1f) ; + ptm->tm_mon = (uInt)((((uDate)&0x1E0)/0x20)-1) ; + ptm->tm_year = (uInt)(((uDate&0x0FE00)/0x0200)+1980) ; + + ptm->tm_hour = (uInt) ((ulDosDate &0xF800)/0x800); + ptm->tm_min = (uInt) ((ulDosDate&0x7E0)/0x20) ; + ptm->tm_sec = (uInt) (2*(ulDosDate&0x1f)) ; +} + +/* + Get Info about the current file in the zipfile, with internal only info +*/ +local int unz64local_GetCurrentFileInfoInternal OF((unzFile file, + unz_file_info64 *pfile_info, + unz_file_info64_internal + *pfile_info_internal, + char *szFileName, + uLong fileNameBufferSize, + void *extraField, + uLong extraFieldBufferSize, + char *szComment, + uLong commentBufferSize)); + +local int unz64local_GetCurrentFileInfoInternal (unzFile file, + unz_file_info64 *pfile_info, + unz_file_info64_internal + *pfile_info_internal, + char *szFileName, + uLong fileNameBufferSize, + void *extraField, + uLong extraFieldBufferSize, + char *szComment, + uLong commentBufferSize) +{ + unz64_s* s; + unz_file_info64 file_info; + unz_file_info64_internal file_info_internal; + int err=UNZ_OK; + uLong uMagic; + long lSeek=0; + uLong uL; + + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + if (ZSEEK64(s->z_filefunc, s->filestream, + s->pos_in_central_dir+s->byte_before_the_zipfile, + ZLIB_FILEFUNC_SEEK_SET)!=0) + err=UNZ_ERRNO; + + + /* we check the magic */ + if (err==UNZ_OK) + { + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uMagic) != UNZ_OK) + err=UNZ_ERRNO; + else if (uMagic!=0x02014b50) + err=UNZ_BADZIPFILE; + } + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.version) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.version_needed) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.flag) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.compression_method) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&file_info.dosDate) != UNZ_OK) + err=UNZ_ERRNO; + + unz64local_DosDateToTmuDate(file_info.dosDate,&file_info.tmu_date); + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&file_info.crc) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK) + err=UNZ_ERRNO; + file_info.compressed_size = uL; + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK) + err=UNZ_ERRNO; + file_info.uncompressed_size = uL; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.size_filename) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.size_file_extra) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.size_file_comment) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.disk_num_start) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.internal_fa) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&file_info.external_fa) != UNZ_OK) + err=UNZ_ERRNO; + + // relative offset of local header + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK) + err=UNZ_ERRNO; + file_info_internal.offset_curfile = uL; + + lSeek+=file_info.size_filename; + if ((err==UNZ_OK) && (szFileName!=NULL)) + { + uLong uSizeRead ; + if (file_info.size_filename0) && (fileNameBufferSize>0)) + if (ZREAD64(s->z_filefunc, s->filestream,szFileName,uSizeRead)!=uSizeRead) + err=UNZ_ERRNO; + lSeek -= uSizeRead; + } + + // Read extrafield + if ((err==UNZ_OK) && (extraField!=NULL)) + { + ZPOS64_T uSizeRead ; + if (file_info.size_file_extraz_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0) + lSeek=0; + else + err=UNZ_ERRNO; + } + + if ((file_info.size_file_extra>0) && (extraFieldBufferSize>0)) + if (ZREAD64(s->z_filefunc, s->filestream,extraField,(uLong)uSizeRead)!=uSizeRead) + err=UNZ_ERRNO; + + lSeek += file_info.size_file_extra - (uLong)uSizeRead; + } + else + lSeek += file_info.size_file_extra; + + + if ((err==UNZ_OK) && (file_info.size_file_extra != 0)) + { + uLong acc = 0; + + // since lSeek now points to after the extra field we need to move back + lSeek -= file_info.size_file_extra; + + if (lSeek!=0) + { + if (ZSEEK64(s->z_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0) + lSeek=0; + else + err=UNZ_ERRNO; + } + + while(acc < file_info.size_file_extra) + { + uLong headerId; + uLong dataSize; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&headerId) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&dataSize) != UNZ_OK) + err=UNZ_ERRNO; + + /* ZIP64 extra fields */ + if (headerId == 0x0001) + { + uLong uL; + + if(file_info.uncompressed_size == MAXU32) + { + if (unz64local_getLong64(&s->z_filefunc, s->filestream,&file_info.uncompressed_size) != UNZ_OK) + err=UNZ_ERRNO; + } + + if(file_info.compressed_size == MAXU32) + { + if (unz64local_getLong64(&s->z_filefunc, s->filestream,&file_info.compressed_size) != UNZ_OK) + err=UNZ_ERRNO; + } + + if(file_info_internal.offset_curfile == MAXU32) + { + /* Relative Header offset */ + if (unz64local_getLong64(&s->z_filefunc, s->filestream,&file_info_internal.offset_curfile) != UNZ_OK) + err=UNZ_ERRNO; + } + + if(file_info.disk_num_start == MAXU32) + { + /* Disk Start Number */ + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK) + err=UNZ_ERRNO; + } + + } + else + { + if (ZSEEK64(s->z_filefunc, s->filestream,dataSize,ZLIB_FILEFUNC_SEEK_CUR)!=0) + err=UNZ_ERRNO; + } + + acc += 2 + 2 + dataSize; + } + } + + if ((err==UNZ_OK) && (szComment!=NULL)) + { + uLong uSizeRead ; + if (file_info.size_file_commentz_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0) + lSeek=0; + else + err=UNZ_ERRNO; + } + + if ((file_info.size_file_comment>0) && (commentBufferSize>0)) + if (ZREAD64(s->z_filefunc, s->filestream,szComment,uSizeRead)!=uSizeRead) + err=UNZ_ERRNO; + lSeek+=file_info.size_file_comment - uSizeRead; + } + else + lSeek+=file_info.size_file_comment; + + + if ((err==UNZ_OK) && (pfile_info!=NULL)) + *pfile_info=file_info; + + if ((err==UNZ_OK) && (pfile_info_internal!=NULL)) + *pfile_info_internal=file_info_internal; + + return err; +} + + + +/* + Write info about the ZipFile in the *pglobal_info structure. + No preparation of the structure is needed + return UNZ_OK if there is no problem. +*/ +extern int ZEXPORT unzGetCurrentFileInfo64 (unzFile file, + unz_file_info64 * pfile_info, + char * szFileName, uLong fileNameBufferSize, + void *extraField, uLong extraFieldBufferSize, + char* szComment, uLong commentBufferSize) +{ + return unz64local_GetCurrentFileInfoInternal(file,pfile_info,NULL, + szFileName,fileNameBufferSize, + extraField,extraFieldBufferSize, + szComment,commentBufferSize); +} + +extern int ZEXPORT unzGetCurrentFileInfo (unzFile file, + unz_file_info * pfile_info, + char * szFileName, uLong fileNameBufferSize, + void *extraField, uLong extraFieldBufferSize, + char* szComment, uLong commentBufferSize) +{ + int err; + unz_file_info64 file_info64; + err = unz64local_GetCurrentFileInfoInternal(file,&file_info64,NULL, + szFileName,fileNameBufferSize, + extraField,extraFieldBufferSize, + szComment,commentBufferSize); + if ((err==UNZ_OK) && (pfile_info != NULL)) + { + pfile_info->version = file_info64.version; + pfile_info->version_needed = file_info64.version_needed; + pfile_info->flag = file_info64.flag; + pfile_info->compression_method = file_info64.compression_method; + pfile_info->dosDate = file_info64.dosDate; + pfile_info->crc = file_info64.crc; + + pfile_info->size_filename = file_info64.size_filename; + pfile_info->size_file_extra = file_info64.size_file_extra; + pfile_info->size_file_comment = file_info64.size_file_comment; + + pfile_info->disk_num_start = file_info64.disk_num_start; + pfile_info->internal_fa = file_info64.internal_fa; + pfile_info->external_fa = file_info64.external_fa; + + pfile_info->tmu_date = file_info64.tmu_date, + + + pfile_info->compressed_size = (uLong)file_info64.compressed_size; + pfile_info->uncompressed_size = (uLong)file_info64.uncompressed_size; + + } + return err; +} +/* + Set the current file of the zipfile to the first file. + return UNZ_OK if there is no problem +*/ +extern int ZEXPORT unzGoToFirstFile (unzFile file) +{ + int err=UNZ_OK; + unz64_s* s; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + s->pos_in_central_dir=s->offset_central_dir; + s->num_file=0; + err=unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info, + &s->cur_file_info_internal, + NULL,0,NULL,0,NULL,0); + s->current_file_ok = (err == UNZ_OK); + return err; +} + +/* + Set the current file of the zipfile to the next file. + return UNZ_OK if there is no problem + return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. +*/ +extern int ZEXPORT unzGoToNextFile (unzFile file) +{ + unz64_s* s; + int err; + + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + if (!s->current_file_ok) + return UNZ_END_OF_LIST_OF_FILE; + if (s->gi.number_entry != 0xffff) /* 2^16 files overflow hack */ + if (s->num_file+1==s->gi.number_entry) + return UNZ_END_OF_LIST_OF_FILE; + + s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename + + s->cur_file_info.size_file_extra + s->cur_file_info.size_file_comment ; + s->num_file++; + err = unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info, + &s->cur_file_info_internal, + NULL,0,NULL,0,NULL,0); + s->current_file_ok = (err == UNZ_OK); + return err; +} + + +/* + Try locate the file szFileName in the zipfile. + For the iCaseSensitivity signification, see unzStringFileNameCompare + + return value : + UNZ_OK if the file is found. It becomes the current file. + UNZ_END_OF_LIST_OF_FILE if the file is not found +*/ +extern int ZEXPORT unzLocateFile (unzFile file, const char *szFileName, int iCaseSensitivity) +{ + unz64_s* s; + int err; + + /* We remember the 'current' position in the file so that we can jump + * back there if we fail. + */ + unz_file_info64 cur_file_infoSaved; + unz_file_info64_internal cur_file_info_internalSaved; + ZPOS64_T num_fileSaved; + ZPOS64_T pos_in_central_dirSaved; + + + if (file==NULL) + return UNZ_PARAMERROR; + + if (strlen(szFileName)>=UNZ_MAXFILENAMEINZIP) + return UNZ_PARAMERROR; + + s=(unz64_s*)file; + if (!s->current_file_ok) + return UNZ_END_OF_LIST_OF_FILE; + + /* Save the current state */ + num_fileSaved = s->num_file; + pos_in_central_dirSaved = s->pos_in_central_dir; + cur_file_infoSaved = s->cur_file_info; + cur_file_info_internalSaved = s->cur_file_info_internal; + + err = unzGoToFirstFile(file); + + while (err == UNZ_OK) + { + char szCurrentFileName[UNZ_MAXFILENAMEINZIP+1]; + err = unzGetCurrentFileInfo64(file,NULL, + szCurrentFileName,sizeof(szCurrentFileName)-1, + NULL,0,NULL,0); + if (err == UNZ_OK) + { + if (unzStringFileNameCompare(szCurrentFileName, + szFileName,iCaseSensitivity)==0) + return UNZ_OK; + err = unzGoToNextFile(file); + } + } + + /* We failed, so restore the state of the 'current file' to where we + * were. + */ + s->num_file = num_fileSaved ; + s->pos_in_central_dir = pos_in_central_dirSaved ; + s->cur_file_info = cur_file_infoSaved; + s->cur_file_info_internal = cur_file_info_internalSaved; + return err; +} + + +/* +/////////////////////////////////////////// +// Contributed by Ryan Haksi (mailto://cryogen@infoserve.net) +// I need random access +// +// Further optimization could be realized by adding an ability +// to cache the directory in memory. The goal being a single +// comprehensive file read to put the file I need in a memory. +*/ + +/* +typedef struct unz_file_pos_s +{ + ZPOS64_T pos_in_zip_directory; // offset in file + ZPOS64_T num_of_file; // # of file +} unz_file_pos; +*/ + +extern int ZEXPORT unzGetFilePos64(unzFile file, unz64_file_pos* file_pos) +{ + unz64_s* s; + + if (file==NULL || file_pos==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + if (!s->current_file_ok) + return UNZ_END_OF_LIST_OF_FILE; + + file_pos->pos_in_zip_directory = s->pos_in_central_dir; + file_pos->num_of_file = s->num_file; + + return UNZ_OK; +} + +extern int ZEXPORT unzGetFilePos( + unzFile file, + unz_file_pos* file_pos) +{ + unz64_file_pos file_pos64; + int err = unzGetFilePos64(file,&file_pos64); + if (err==UNZ_OK) + { + file_pos->pos_in_zip_directory = (uLong)file_pos64.pos_in_zip_directory; + file_pos->num_of_file = (uLong)file_pos64.num_of_file; + } + return err; +} + +extern int ZEXPORT unzGoToFilePos64(unzFile file, const unz64_file_pos* file_pos) +{ + unz64_s* s; + int err; + + if (file==NULL || file_pos==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + + /* jump to the right spot */ + s->pos_in_central_dir = file_pos->pos_in_zip_directory; + s->num_file = file_pos->num_of_file; + + /* set the current file */ + err = unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info, + &s->cur_file_info_internal, + NULL,0,NULL,0,NULL,0); + /* return results */ + s->current_file_ok = (err == UNZ_OK); + return err; +} + +extern int ZEXPORT unzGoToFilePos( + unzFile file, + unz_file_pos* file_pos) +{ + unz64_file_pos file_pos64; + if (file_pos == NULL) + return UNZ_PARAMERROR; + + file_pos64.pos_in_zip_directory = file_pos->pos_in_zip_directory; + file_pos64.num_of_file = file_pos->num_of_file; + return unzGoToFilePos64(file,&file_pos64); +} + +/* +// Unzip Helper Functions - should be here? +/////////////////////////////////////////// +*/ + +/* + Read the local header of the current zipfile + Check the coherency of the local header and info in the end of central + directory about this file + store in *piSizeVar the size of extra info in local header + (filename and size of extra field data) +*/ +local int unz64local_CheckCurrentFileCoherencyHeader (unz64_s* s, uInt* piSizeVar, + ZPOS64_T * poffset_local_extrafield, + uInt * psize_local_extrafield) +{ + uLong uMagic,uData,uFlags; + uLong size_filename; + uLong size_extra_field; + int err=UNZ_OK; + + *piSizeVar = 0; + *poffset_local_extrafield = 0; + *psize_local_extrafield = 0; + + if (ZSEEK64(s->z_filefunc, s->filestream,s->cur_file_info_internal.offset_curfile + + s->byte_before_the_zipfile,ZLIB_FILEFUNC_SEEK_SET)!=0) + return UNZ_ERRNO; + + + if (err==UNZ_OK) + { + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uMagic) != UNZ_OK) + err=UNZ_ERRNO; + else if (uMagic!=0x04034b50) + err=UNZ_BADZIPFILE; + } + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) + err=UNZ_ERRNO; +/* + else if ((err==UNZ_OK) && (uData!=s->cur_file_info.wVersion)) + err=UNZ_BADZIPFILE; +*/ + if (unz64local_getShort(&s->z_filefunc, s->filestream,&uFlags) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) + err=UNZ_ERRNO; + else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compression_method)) + err=UNZ_BADZIPFILE; + + if ((err==UNZ_OK) && (s->cur_file_info.compression_method!=0) && +/* #ifdef HAVE_BZIP2 */ + (s->cur_file_info.compression_method!=Z_BZIP2ED) && +/* #endif */ + (s->cur_file_info.compression_method!=Z_DEFLATED)) + err=UNZ_BADZIPFILE; + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* date/time */ + err=UNZ_ERRNO; + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* crc */ + err=UNZ_ERRNO; + else if ((err==UNZ_OK) && (uData!=s->cur_file_info.crc) && ((uFlags & 8)==0)) + err=UNZ_BADZIPFILE; + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* size compr */ + err=UNZ_ERRNO; + else if (uData != 0xFFFFFFFF && (err==UNZ_OK) && (uData!=s->cur_file_info.compressed_size) && ((uFlags & 8)==0)) + err=UNZ_BADZIPFILE; + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* size uncompr */ + err=UNZ_ERRNO; + else if (uData != 0xFFFFFFFF && (err==UNZ_OK) && (uData!=s->cur_file_info.uncompressed_size) && ((uFlags & 8)==0)) + err=UNZ_BADZIPFILE; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&size_filename) != UNZ_OK) + err=UNZ_ERRNO; + else if ((err==UNZ_OK) && (size_filename!=s->cur_file_info.size_filename)) + err=UNZ_BADZIPFILE; + + *piSizeVar += (uInt)size_filename; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&size_extra_field) != UNZ_OK) + err=UNZ_ERRNO; + *poffset_local_extrafield= s->cur_file_info_internal.offset_curfile + + SIZEZIPLOCALHEADER + size_filename; + *psize_local_extrafield = (uInt)size_extra_field; + + *piSizeVar += (uInt)size_extra_field; + + return err; +} + +/* + Open for reading data the current file in the zipfile. + If there is no error and the file is opened, the return value is UNZ_OK. +*/ +extern int ZEXPORT unzOpenCurrentFile3 (unzFile file, int* method, + int* level, int raw, const char* password) +{ + int err=UNZ_OK; + uInt iSizeVar; + unz64_s* s; + file_in_zip64_read_info_s* pfile_in_zip_read_info; + ZPOS64_T offset_local_extrafield; /* offset of the local extra field */ + uInt size_local_extrafield; /* size of the local extra field */ +# ifndef NOUNCRYPT + char source[12]; +# else + if (password != NULL) + return UNZ_PARAMERROR; +# endif + + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + if (!s->current_file_ok) + return UNZ_PARAMERROR; + + if (s->pfile_in_zip_read != NULL) + unzCloseCurrentFile(file); + + if (unz64local_CheckCurrentFileCoherencyHeader(s,&iSizeVar, &offset_local_extrafield,&size_local_extrafield)!=UNZ_OK) + return UNZ_BADZIPFILE; + + pfile_in_zip_read_info = (file_in_zip64_read_info_s*)ALLOC(sizeof(file_in_zip64_read_info_s)); + if (pfile_in_zip_read_info==NULL) + return UNZ_INTERNALERROR; + + pfile_in_zip_read_info->read_buffer=(char*)ALLOC(UNZ_BUFSIZE); + pfile_in_zip_read_info->offset_local_extrafield = offset_local_extrafield; + pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield; + pfile_in_zip_read_info->pos_local_extrafield=0; + pfile_in_zip_read_info->raw=raw; + + if (pfile_in_zip_read_info->read_buffer==NULL) + { + TRYFREE(pfile_in_zip_read_info); + return UNZ_INTERNALERROR; + } + + pfile_in_zip_read_info->stream_initialised=0; + + if (method!=NULL) + *method = (int)s->cur_file_info.compression_method; + + if (level!=NULL) + { + *level = 6; + switch (s->cur_file_info.flag & 0x06) + { + case 6 : *level = 1; break; + case 4 : *level = 2; break; + case 2 : *level = 9; break; + } + } + + if ((s->cur_file_info.compression_method!=0) && +/* #ifdef HAVE_BZIP2 */ + (s->cur_file_info.compression_method!=Z_BZIP2ED) && +/* #endif */ + (s->cur_file_info.compression_method!=Z_DEFLATED)) + + err=UNZ_BADZIPFILE; + + pfile_in_zip_read_info->crc32_wait=s->cur_file_info.crc; + pfile_in_zip_read_info->crc32=0; + pfile_in_zip_read_info->total_out_64=0; + pfile_in_zip_read_info->compression_method = s->cur_file_info.compression_method; + pfile_in_zip_read_info->filestream=s->filestream; + pfile_in_zip_read_info->z_filefunc=s->z_filefunc; + pfile_in_zip_read_info->byte_before_the_zipfile=s->byte_before_the_zipfile; + + pfile_in_zip_read_info->stream.total_out = 0; + + if ((s->cur_file_info.compression_method==Z_BZIP2ED) && (!raw)) + { +#ifdef HAVE_BZIP2 + pfile_in_zip_read_info->bstream.bzalloc = (void *(*) (void *, int, int))0; + pfile_in_zip_read_info->bstream.bzfree = (free_func)0; + pfile_in_zip_read_info->bstream.opaque = (voidpf)0; + pfile_in_zip_read_info->bstream.state = (voidpf)0; + + pfile_in_zip_read_info->stream.zalloc = (alloc_func)0; + pfile_in_zip_read_info->stream.zfree = (free_func)0; + pfile_in_zip_read_info->stream.opaque = (voidpf)0; + pfile_in_zip_read_info->stream.next_in = (voidpf)0; + pfile_in_zip_read_info->stream.avail_in = 0; + + err=BZ2_bzDecompressInit(&pfile_in_zip_read_info->bstream, 0, 0); + if (err == Z_OK) + pfile_in_zip_read_info->stream_initialised=Z_BZIP2ED; + else + { + TRYFREE(pfile_in_zip_read_info); + return err; + } +#else + pfile_in_zip_read_info->raw=1; +#endif + } + else if ((s->cur_file_info.compression_method==Z_DEFLATED) && (!raw)) + { + pfile_in_zip_read_info->stream.zalloc = (alloc_func)0; + pfile_in_zip_read_info->stream.zfree = (free_func)0; + pfile_in_zip_read_info->stream.opaque = (voidpf)0; + pfile_in_zip_read_info->stream.next_in = 0; + pfile_in_zip_read_info->stream.avail_in = 0; + + err=inflateInit2(&pfile_in_zip_read_info->stream, -MAX_WBITS); + if (err == Z_OK) + pfile_in_zip_read_info->stream_initialised=Z_DEFLATED; + else + { + TRYFREE(pfile_in_zip_read_info); + return err; + } + /* windowBits is passed < 0 to tell that there is no zlib header. + * Note that in this case inflate *requires* an extra "dummy" byte + * after the compressed stream in order to complete decompression and + * return Z_STREAM_END. + * In unzip, i don't wait absolutely Z_STREAM_END because I known the + * size of both compressed and uncompressed data + */ + } + pfile_in_zip_read_info->rest_read_compressed = + s->cur_file_info.compressed_size ; + pfile_in_zip_read_info->rest_read_uncompressed = + s->cur_file_info.uncompressed_size ; + + + pfile_in_zip_read_info->pos_in_zipfile = + s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER + + iSizeVar; + + pfile_in_zip_read_info->stream.avail_in = (uInt)0; + + s->pfile_in_zip_read = pfile_in_zip_read_info; + s->encrypted = 0; + +# ifndef NOUNCRYPT + if (password != NULL) + { + int i; + s->pcrc_32_tab = get_crc_table(); + init_keys(password,s->keys,s->pcrc_32_tab); + if (ZSEEK64(s->z_filefunc, s->filestream, + s->pfile_in_zip_read->pos_in_zipfile + + s->pfile_in_zip_read->byte_before_the_zipfile, + SEEK_SET)!=0) + return UNZ_INTERNALERROR; + if(ZREAD64(s->z_filefunc, s->filestream,source, 12)<12) + return UNZ_INTERNALERROR; + + for (i = 0; i<12; i++) + zdecode(s->keys,s->pcrc_32_tab,source[i]); + + s->pfile_in_zip_read->pos_in_zipfile+=12; + s->encrypted=1; + } +# endif + + + return UNZ_OK; +} + +extern int ZEXPORT unzOpenCurrentFile (unzFile file) +{ + return unzOpenCurrentFile3(file, NULL, NULL, 0, NULL); +} + +extern int ZEXPORT unzOpenCurrentFilePassword (unzFile file, const char* password) +{ + return unzOpenCurrentFile3(file, NULL, NULL, 0, password); +} + +extern int ZEXPORT unzOpenCurrentFile2 (unzFile file, int* method, int* level, int raw) +{ + return unzOpenCurrentFile3(file, method, level, raw, NULL); +} + +/** Addition for GDAL : START */ + +extern ZPOS64_T ZEXPORT unzGetCurrentFileZStreamPos64( unzFile file) +{ + unz64_s* s; + file_in_zip64_read_info_s* pfile_in_zip_read_info; + s=(unz64_s*)file; + if (file==NULL) + return 0; //UNZ_PARAMERROR; + pfile_in_zip_read_info=s->pfile_in_zip_read; + if (pfile_in_zip_read_info==NULL) + return 0; //UNZ_PARAMERROR; + return pfile_in_zip_read_info->pos_in_zipfile + + pfile_in_zip_read_info->byte_before_the_zipfile; +} + +/** Addition for GDAL : END */ + +/* + Read bytes from the current file. + buf contain buffer where data must be copied + len the size of buf. + + return the number of byte copied if somes bytes are copied + return 0 if the end of file was reached + return <0 with error code if there is an error + (UNZ_ERRNO for IO error, or zLib error for uncompress error) +*/ +extern int ZEXPORT unzReadCurrentFile (unzFile file, voidp buf, unsigned len) +{ + int err=UNZ_OK; + uInt iRead = 0; + unz64_s* s; + file_in_zip64_read_info_s* pfile_in_zip_read_info; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + pfile_in_zip_read_info=s->pfile_in_zip_read; + + if (pfile_in_zip_read_info==NULL) + return UNZ_PARAMERROR; + + + if (pfile_in_zip_read_info->read_buffer == NULL) + return UNZ_END_OF_LIST_OF_FILE; + if (len==0) + return 0; + + pfile_in_zip_read_info->stream.next_out = (Bytef*)buf; + + pfile_in_zip_read_info->stream.avail_out = (uInt)len; + + if ((len>pfile_in_zip_read_info->rest_read_uncompressed) && + (!(pfile_in_zip_read_info->raw))) + pfile_in_zip_read_info->stream.avail_out = + (uInt)pfile_in_zip_read_info->rest_read_uncompressed; + + if ((len>pfile_in_zip_read_info->rest_read_compressed+ + pfile_in_zip_read_info->stream.avail_in) && + (pfile_in_zip_read_info->raw)) + pfile_in_zip_read_info->stream.avail_out = + (uInt)pfile_in_zip_read_info->rest_read_compressed+ + pfile_in_zip_read_info->stream.avail_in; + + while (pfile_in_zip_read_info->stream.avail_out>0) + { + if ((pfile_in_zip_read_info->stream.avail_in==0) && + (pfile_in_zip_read_info->rest_read_compressed>0)) + { + uInt uReadThis = UNZ_BUFSIZE; + if (pfile_in_zip_read_info->rest_read_compressedrest_read_compressed; + if (uReadThis == 0) + return UNZ_EOF; + if (ZSEEK64(pfile_in_zip_read_info->z_filefunc, + pfile_in_zip_read_info->filestream, + pfile_in_zip_read_info->pos_in_zipfile + + pfile_in_zip_read_info->byte_before_the_zipfile, + ZLIB_FILEFUNC_SEEK_SET)!=0) + return UNZ_ERRNO; + if (ZREAD64(pfile_in_zip_read_info->z_filefunc, + pfile_in_zip_read_info->filestream, + pfile_in_zip_read_info->read_buffer, + uReadThis)!=uReadThis) + return UNZ_ERRNO; + + +# ifndef NOUNCRYPT + if(s->encrypted) + { + uInt i; + for(i=0;iread_buffer[i] = + zdecode(s->keys,s->pcrc_32_tab, + pfile_in_zip_read_info->read_buffer[i]); + } +# endif + + + pfile_in_zip_read_info->pos_in_zipfile += uReadThis; + + pfile_in_zip_read_info->rest_read_compressed-=uReadThis; + + pfile_in_zip_read_info->stream.next_in = + (Bytef*)pfile_in_zip_read_info->read_buffer; + pfile_in_zip_read_info->stream.avail_in = (uInt)uReadThis; + } + + if ((pfile_in_zip_read_info->compression_method==0) || (pfile_in_zip_read_info->raw)) + { + uInt uDoCopy,i ; + + if ((pfile_in_zip_read_info->stream.avail_in == 0) && + (pfile_in_zip_read_info->rest_read_compressed == 0)) + return (iRead==0) ? UNZ_EOF : iRead; + + if (pfile_in_zip_read_info->stream.avail_out < + pfile_in_zip_read_info->stream.avail_in) + uDoCopy = pfile_in_zip_read_info->stream.avail_out ; + else + uDoCopy = pfile_in_zip_read_info->stream.avail_in ; + + for (i=0;istream.next_out+i) = + *(pfile_in_zip_read_info->stream.next_in+i); + + pfile_in_zip_read_info->total_out_64 = pfile_in_zip_read_info->total_out_64 + uDoCopy; + + pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32, + pfile_in_zip_read_info->stream.next_out, + uDoCopy); + pfile_in_zip_read_info->rest_read_uncompressed-=uDoCopy; + pfile_in_zip_read_info->stream.avail_in -= uDoCopy; + pfile_in_zip_read_info->stream.avail_out -= uDoCopy; + pfile_in_zip_read_info->stream.next_out += uDoCopy; + pfile_in_zip_read_info->stream.next_in += uDoCopy; + pfile_in_zip_read_info->stream.total_out += uDoCopy; + iRead += uDoCopy; + } + else if (pfile_in_zip_read_info->compression_method==Z_BZIP2ED) + { +#ifdef HAVE_BZIP2 + uLong uTotalOutBefore,uTotalOutAfter; + const Bytef *bufBefore; + uLong uOutThis; + + pfile_in_zip_read_info->bstream.next_in = (char*)pfile_in_zip_read_info->stream.next_in; + pfile_in_zip_read_info->bstream.avail_in = pfile_in_zip_read_info->stream.avail_in; + pfile_in_zip_read_info->bstream.total_in_lo32 = pfile_in_zip_read_info->stream.total_in; + pfile_in_zip_read_info->bstream.total_in_hi32 = 0; + pfile_in_zip_read_info->bstream.next_out = (char*)pfile_in_zip_read_info->stream.next_out; + pfile_in_zip_read_info->bstream.avail_out = pfile_in_zip_read_info->stream.avail_out; + pfile_in_zip_read_info->bstream.total_out_lo32 = pfile_in_zip_read_info->stream.total_out; + pfile_in_zip_read_info->bstream.total_out_hi32 = 0; + + uTotalOutBefore = pfile_in_zip_read_info->bstream.total_out_lo32; + bufBefore = (const Bytef *)pfile_in_zip_read_info->bstream.next_out; + + err=BZ2_bzDecompress(&pfile_in_zip_read_info->bstream); + + uTotalOutAfter = pfile_in_zip_read_info->bstream.total_out_lo32; + uOutThis = uTotalOutAfter-uTotalOutBefore; + + pfile_in_zip_read_info->total_out_64 = pfile_in_zip_read_info->total_out_64 + uOutThis; + + pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32,bufBefore, (uInt)(uOutThis)); + pfile_in_zip_read_info->rest_read_uncompressed -= uOutThis; + iRead += (uInt)(uTotalOutAfter - uTotalOutBefore); + + pfile_in_zip_read_info->stream.next_in = (Bytef*)pfile_in_zip_read_info->bstream.next_in; + pfile_in_zip_read_info->stream.avail_in = pfile_in_zip_read_info->bstream.avail_in; + pfile_in_zip_read_info->stream.total_in = pfile_in_zip_read_info->bstream.total_in_lo32; + pfile_in_zip_read_info->stream.next_out = (Bytef*)pfile_in_zip_read_info->bstream.next_out; + pfile_in_zip_read_info->stream.avail_out = pfile_in_zip_read_info->bstream.avail_out; + pfile_in_zip_read_info->stream.total_out = pfile_in_zip_read_info->bstream.total_out_lo32; + + if (err==BZ_STREAM_END) + return (iRead==0) ? UNZ_EOF : iRead; + if (err!=BZ_OK) + break; +#endif + } // end Z_BZIP2ED + else + { + ZPOS64_T uTotalOutBefore,uTotalOutAfter; + const Bytef *bufBefore; + ZPOS64_T uOutThis; + int flush=Z_SYNC_FLUSH; + + uTotalOutBefore = pfile_in_zip_read_info->stream.total_out; + bufBefore = pfile_in_zip_read_info->stream.next_out; + + /* + if ((pfile_in_zip_read_info->rest_read_uncompressed == + pfile_in_zip_read_info->stream.avail_out) && + (pfile_in_zip_read_info->rest_read_compressed == 0)) + flush = Z_FINISH; + */ + err=inflate(&pfile_in_zip_read_info->stream,flush); + + if ((err>=0) && (pfile_in_zip_read_info->stream.msg!=NULL)) + err = Z_DATA_ERROR; + + uTotalOutAfter = pfile_in_zip_read_info->stream.total_out; + uOutThis = uTotalOutAfter-uTotalOutBefore; + + pfile_in_zip_read_info->total_out_64 = pfile_in_zip_read_info->total_out_64 + uOutThis; + + pfile_in_zip_read_info->crc32 = + crc32(pfile_in_zip_read_info->crc32,bufBefore, + (uInt)(uOutThis)); + + pfile_in_zip_read_info->rest_read_uncompressed -= + uOutThis; + + iRead += (uInt)(uTotalOutAfter - uTotalOutBefore); + + if (err==Z_STREAM_END) + return (iRead==0) ? UNZ_EOF : iRead; + if (err!=Z_OK) + break; + } + } + + if (err==Z_OK) + return iRead; + return err; +} + + +/* + Give the current position in uncompressed data +*/ +extern z_off_t ZEXPORT unztell (unzFile file) +{ + unz64_s* s; + file_in_zip64_read_info_s* pfile_in_zip_read_info; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + pfile_in_zip_read_info=s->pfile_in_zip_read; + + if (pfile_in_zip_read_info==NULL) + return UNZ_PARAMERROR; + + return (z_off_t)pfile_in_zip_read_info->stream.total_out; +} + +extern ZPOS64_T ZEXPORT unztell64 (unzFile file) +{ + + unz64_s* s; + file_in_zip64_read_info_s* pfile_in_zip_read_info; + if (file==NULL) + return (ZPOS64_T)-1; + s=(unz64_s*)file; + pfile_in_zip_read_info=s->pfile_in_zip_read; + + if (pfile_in_zip_read_info==NULL) + return (ZPOS64_T)-1; + + return pfile_in_zip_read_info->total_out_64; +} + + +/* + return 1 if the end of file was reached, 0 elsewhere +*/ +extern int ZEXPORT unzeof (unzFile file) +{ + unz64_s* s; + file_in_zip64_read_info_s* pfile_in_zip_read_info; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + pfile_in_zip_read_info=s->pfile_in_zip_read; + + if (pfile_in_zip_read_info==NULL) + return UNZ_PARAMERROR; + + if (pfile_in_zip_read_info->rest_read_uncompressed == 0) + return 1; + else + return 0; +} + + + +/* +Read extra field from the current file (opened by unzOpenCurrentFile) +This is the local-header version of the extra field (sometimes, there is +more info in the local-header version than in the central-header) + + if buf==NULL, it return the size of the local extra field that can be read + + if buf!=NULL, len is the size of the buffer, the extra header is copied in + buf. + the return value is the number of bytes copied in buf, or (if <0) + the error code +*/ +extern int ZEXPORT unzGetLocalExtrafield (unzFile file, voidp buf, unsigned len) +{ + unz64_s* s; + file_in_zip64_read_info_s* pfile_in_zip_read_info; + uInt read_now; + ZPOS64_T size_to_read; + + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + pfile_in_zip_read_info=s->pfile_in_zip_read; + + if (pfile_in_zip_read_info==NULL) + return UNZ_PARAMERROR; + + size_to_read = (pfile_in_zip_read_info->size_local_extrafield - + pfile_in_zip_read_info->pos_local_extrafield); + + if (buf==NULL) + return (int)size_to_read; + + if (len>size_to_read) + read_now = (uInt)size_to_read; + else + read_now = (uInt)len ; + + if (read_now==0) + return 0; + + if (ZSEEK64(pfile_in_zip_read_info->z_filefunc, + pfile_in_zip_read_info->filestream, + pfile_in_zip_read_info->offset_local_extrafield + + pfile_in_zip_read_info->pos_local_extrafield, + ZLIB_FILEFUNC_SEEK_SET)!=0) + return UNZ_ERRNO; + + if (ZREAD64(pfile_in_zip_read_info->z_filefunc, + pfile_in_zip_read_info->filestream, + buf,read_now)!=read_now) + return UNZ_ERRNO; + + return (int)read_now; +} + +/* + Close the file in zip opened with unzOpenCurrentFile + Return UNZ_CRCERROR if all the file was read but the CRC is not good +*/ +extern int ZEXPORT unzCloseCurrentFile (unzFile file) +{ + int err=UNZ_OK; + + unz64_s* s; + file_in_zip64_read_info_s* pfile_in_zip_read_info; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + pfile_in_zip_read_info=s->pfile_in_zip_read; + + if (pfile_in_zip_read_info==NULL) + return UNZ_PARAMERROR; + + + if ((pfile_in_zip_read_info->rest_read_uncompressed == 0) && + (!pfile_in_zip_read_info->raw)) + { + if (pfile_in_zip_read_info->crc32 != pfile_in_zip_read_info->crc32_wait) + err=UNZ_CRCERROR; + } + + + TRYFREE(pfile_in_zip_read_info->read_buffer); + pfile_in_zip_read_info->read_buffer = NULL; + if (pfile_in_zip_read_info->stream_initialised == Z_DEFLATED) + inflateEnd(&pfile_in_zip_read_info->stream); +#ifdef HAVE_BZIP2 + else if (pfile_in_zip_read_info->stream_initialised == Z_BZIP2ED) + BZ2_bzDecompressEnd(&pfile_in_zip_read_info->bstream); +#endif + + + pfile_in_zip_read_info->stream_initialised = 0; + TRYFREE(pfile_in_zip_read_info); + + s->pfile_in_zip_read=NULL; + + return err; +} + + +/* + Get the global comment string of the ZipFile, in the szComment buffer. + uSizeBuf is the size of the szComment buffer. + return the number of byte copied or an error code <0 +*/ +extern int ZEXPORT unzGetGlobalComment (unzFile file, char * szComment, uLong uSizeBuf) +{ + unz64_s* s; + uLong uReadThis ; + if (file==NULL) + return (int)UNZ_PARAMERROR; + s=(unz64_s*)file; + + uReadThis = uSizeBuf; + if (uReadThis>s->gi.size_comment) + uReadThis = s->gi.size_comment; + + if (ZSEEK64(s->z_filefunc,s->filestream,s->central_pos+22,ZLIB_FILEFUNC_SEEK_SET)!=0) + return UNZ_ERRNO; + + if (uReadThis>0) + { + *szComment='\0'; + if (ZREAD64(s->z_filefunc,s->filestream,szComment,uReadThis)!=uReadThis) + return UNZ_ERRNO; + } + + if ((szComment != NULL) && (uSizeBuf > s->gi.size_comment)) + *(szComment+s->gi.size_comment)='\0'; + return (int)uReadThis; +} + +/* Additions by RX '2004 */ +extern ZPOS64_T ZEXPORT unzGetOffset64(unzFile file) +{ + unz64_s* s; + + if (file==NULL) + return 0; //UNZ_PARAMERROR; + s=(unz64_s*)file; + if (!s->current_file_ok) + return 0; + if (s->gi.number_entry != 0 && s->gi.number_entry != 0xffff) + if (s->num_file==s->gi.number_entry) + return 0; + return s->pos_in_central_dir; +} + +extern uLong ZEXPORT unzGetOffset (unzFile file) +{ + ZPOS64_T offset64; + + if (file==NULL) + return 0; //UNZ_PARAMERROR; + offset64 = unzGetOffset64(file); + return (uLong)offset64; +} + +extern int ZEXPORT unzSetOffset64(unzFile file, ZPOS64_T pos) +{ + unz64_s* s; + int err; + + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + + s->pos_in_central_dir = pos; + s->num_file = s->gi.number_entry; /* hack */ + err = unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info, + &s->cur_file_info_internal, + NULL,0,NULL,0,NULL,0); + s->current_file_ok = (err == UNZ_OK); + return err; +} + +extern int ZEXPORT unzSetOffset (unzFile file, uLong pos) +{ + return unzSetOffset64(file,pos); +} diff --git a/DSView/pv/minizip/unzip.h b/DSView/pv/minizip/unzip.h new file mode 100644 index 00000000..2104e391 --- /dev/null +++ b/DSView/pv/minizip/unzip.h @@ -0,0 +1,437 @@ +/* unzip.h -- IO for uncompress .zip files using zlib + Version 1.1, February 14h, 2010 + part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications of Unzip for Zip64 + Copyright (C) 2007-2008 Even Rouault + + Modifications for Zip64 support on both zip and unzip + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) + + For more info read MiniZip_info.txt + + --------------------------------------------------------------------------------- + + Condition of use and distribution are the same than zlib : + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + --------------------------------------------------------------------------------- + + Changes + + See header of unzip64.c + +*/ + +#ifndef _unz64_H +#define _unz64_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef _ZLIB_H +#include "zlib.h" +#endif + +#ifndef _ZLIBIOAPI_H +#include "ioapi.h" +#endif + +#ifdef HAVE_BZIP2 +#include "bzlib.h" +#endif + +#define Z_BZIP2ED 12 + +#if defined(STRICTUNZIP) || defined(STRICTZIPUNZIP) +/* like the STRICT of WIN32, we define a pointer that cannot be converted + from (void*) without cast */ +typedef struct TagunzFile__ { int unused; } unzFile__; +typedef unzFile__ *unzFile; +#else +typedef voidp unzFile; +#endif + + +#define UNZ_OK (0) +#define UNZ_END_OF_LIST_OF_FILE (-100) +#define UNZ_ERRNO (Z_ERRNO) +#define UNZ_EOF (0) +#define UNZ_PARAMERROR (-102) +#define UNZ_BADZIPFILE (-103) +#define UNZ_INTERNALERROR (-104) +#define UNZ_CRCERROR (-105) + +/* tm_unz contain date/time info */ +typedef struct tm_unz_s +{ + uInt tm_sec; /* seconds after the minute - [0,59] */ + uInt tm_min; /* minutes after the hour - [0,59] */ + uInt tm_hour; /* hours since midnight - [0,23] */ + uInt tm_mday; /* day of the month - [1,31] */ + uInt tm_mon; /* months since January - [0,11] */ + uInt tm_year; /* years - [1980..2044] */ +} tm_unz; + +/* unz_global_info structure contain global data about the ZIPfile + These data comes from the end of central dir */ +typedef struct unz_global_info64_s +{ + ZPOS64_T number_entry; /* total number of entries in + the central dir on this disk */ + uLong size_comment; /* size of the global comment of the zipfile */ +} unz_global_info64; + +typedef struct unz_global_info_s +{ + uLong number_entry; /* total number of entries in + the central dir on this disk */ + uLong size_comment; /* size of the global comment of the zipfile */ +} unz_global_info; + +/* unz_file_info contain information about a file in the zipfile */ +typedef struct unz_file_info64_s +{ + uLong version; /* version made by 2 bytes */ + uLong version_needed; /* version needed to extract 2 bytes */ + uLong flag; /* general purpose bit flag 2 bytes */ + uLong compression_method; /* compression method 2 bytes */ + uLong dosDate; /* last mod file date in Dos fmt 4 bytes */ + uLong crc; /* crc-32 4 bytes */ + ZPOS64_T compressed_size; /* compressed size 8 bytes */ + ZPOS64_T uncompressed_size; /* uncompressed size 8 bytes */ + uLong size_filename; /* filename length 2 bytes */ + uLong size_file_extra; /* extra field length 2 bytes */ + uLong size_file_comment; /* file comment length 2 bytes */ + + uLong disk_num_start; /* disk number start 2 bytes */ + uLong internal_fa; /* internal file attributes 2 bytes */ + uLong external_fa; /* external file attributes 4 bytes */ + + tm_unz tmu_date; +} unz_file_info64; + +typedef struct unz_file_info_s +{ + uLong version; /* version made by 2 bytes */ + uLong version_needed; /* version needed to extract 2 bytes */ + uLong flag; /* general purpose bit flag 2 bytes */ + uLong compression_method; /* compression method 2 bytes */ + uLong dosDate; /* last mod file date in Dos fmt 4 bytes */ + uLong crc; /* crc-32 4 bytes */ + uLong compressed_size; /* compressed size 4 bytes */ + uLong uncompressed_size; /* uncompressed size 4 bytes */ + uLong size_filename; /* filename length 2 bytes */ + uLong size_file_extra; /* extra field length 2 bytes */ + uLong size_file_comment; /* file comment length 2 bytes */ + + uLong disk_num_start; /* disk number start 2 bytes */ + uLong internal_fa; /* internal file attributes 2 bytes */ + uLong external_fa; /* external file attributes 4 bytes */ + + tm_unz tmu_date; +} unz_file_info; + +extern int ZEXPORT unzStringFileNameCompare OF ((const char* fileName1, + const char* fileName2, + int iCaseSensitivity)); +/* + Compare two filename (fileName1,fileName2). + If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp) + If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi + or strcasecmp) + If iCaseSenisivity = 0, case sensitivity is defaut of your operating system + (like 1 on Unix, 2 on Windows) +*/ + + +extern unzFile ZEXPORT unzOpen OF((const char *path)); +extern unzFile ZEXPORT unzOpen64 OF((const void *path)); +/* + Open a Zip file. path contain the full pathname (by example, + on a Windows XP computer "c:\\zlib\\zlib113.zip" or on an Unix computer + "zlib/zlib113.zip". + If the zipfile cannot be opened (file don't exist or in not valid), the + return value is NULL. + Else, the return value is a unzFile Handle, usable with other function + of this unzip package. + the "64" function take a const void* pointer, because the path is just the + value passed to the open64_file_func callback. + Under Windows, if UNICODE is defined, using fill_fopen64_filefunc, the path + is a pointer to a wide unicode string (LPCTSTR is LPCWSTR), so const char* + does not describe the reality +*/ + + +extern unzFile ZEXPORT unzOpen2 OF((const char *path, + zlib_filefunc_def* pzlib_filefunc_def)); +/* + Open a Zip file, like unzOpen, but provide a set of file low level API + for read/write the zip file (see ioapi.h) +*/ + +extern unzFile ZEXPORT unzOpen2_64 OF((const void *path, + zlib_filefunc64_def* pzlib_filefunc_def)); +/* + Open a Zip file, like unz64Open, but provide a set of file low level API + for read/write the zip file (see ioapi.h) +*/ + +extern int ZEXPORT unzClose OF((unzFile file)); +/* + Close a ZipFile opened with unzOpen. + If there is files inside the .Zip opened with unzOpenCurrentFile (see later), + these files MUST be closed with unzCloseCurrentFile before call unzClose. + return UNZ_OK if there is no problem. */ + +extern int ZEXPORT unzGetGlobalInfo OF((unzFile file, + unz_global_info *pglobal_info)); + +extern int ZEXPORT unzGetGlobalInfo64 OF((unzFile file, + unz_global_info64 *pglobal_info)); +/* + Write info about the ZipFile in the *pglobal_info structure. + No preparation of the structure is needed + return UNZ_OK if there is no problem. */ + + +extern int ZEXPORT unzGetGlobalComment OF((unzFile file, + char *szComment, + uLong uSizeBuf)); +/* + Get the global comment string of the ZipFile, in the szComment buffer. + uSizeBuf is the size of the szComment buffer. + return the number of byte copied or an error code <0 +*/ + + +/***************************************************************************/ +/* Unzip package allow you browse the directory of the zipfile */ + +extern int ZEXPORT unzGoToFirstFile OF((unzFile file)); +/* + Set the current file of the zipfile to the first file. + return UNZ_OK if there is no problem +*/ + +extern int ZEXPORT unzGoToNextFile OF((unzFile file)); +/* + Set the current file of the zipfile to the next file. + return UNZ_OK if there is no problem + return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. +*/ + +extern int ZEXPORT unzLocateFile OF((unzFile file, + const char *szFileName, + int iCaseSensitivity)); +/* + Try locate the file szFileName in the zipfile. + For the iCaseSensitivity signification, see unzStringFileNameCompare + + return value : + UNZ_OK if the file is found. It becomes the current file. + UNZ_END_OF_LIST_OF_FILE if the file is not found +*/ + + +/* ****************************************** */ +/* Ryan supplied functions */ +/* unz_file_info contain information about a file in the zipfile */ +typedef struct unz_file_pos_s +{ + uLong pos_in_zip_directory; /* offset in zip file directory */ + uLong num_of_file; /* # of file */ +} unz_file_pos; + +extern int ZEXPORT unzGetFilePos( + unzFile file, + unz_file_pos* file_pos); + +extern int ZEXPORT unzGoToFilePos( + unzFile file, + unz_file_pos* file_pos); + +typedef struct unz64_file_pos_s +{ + ZPOS64_T pos_in_zip_directory; /* offset in zip file directory */ + ZPOS64_T num_of_file; /* # of file */ +} unz64_file_pos; + +extern int ZEXPORT unzGetFilePos64( + unzFile file, + unz64_file_pos* file_pos); + +extern int ZEXPORT unzGoToFilePos64( + unzFile file, + const unz64_file_pos* file_pos); + +/* ****************************************** */ + +extern int ZEXPORT unzGetCurrentFileInfo64 OF((unzFile file, + unz_file_info64 *pfile_info, + char *szFileName, + uLong fileNameBufferSize, + void *extraField, + uLong extraFieldBufferSize, + char *szComment, + uLong commentBufferSize)); + +extern int ZEXPORT unzGetCurrentFileInfo OF((unzFile file, + unz_file_info *pfile_info, + char *szFileName, + uLong fileNameBufferSize, + void *extraField, + uLong extraFieldBufferSize, + char *szComment, + uLong commentBufferSize)); +/* + Get Info about the current file + if pfile_info!=NULL, the *pfile_info structure will contain somes info about + the current file + if szFileName!=NULL, the filemane string will be copied in szFileName + (fileNameBufferSize is the size of the buffer) + if extraField!=NULL, the extra field information will be copied in extraField + (extraFieldBufferSize is the size of the buffer). + This is the Central-header version of the extra field + if szComment!=NULL, the comment string of the file will be copied in szComment + (commentBufferSize is the size of the buffer) +*/ + + +/** Addition for GDAL : START */ + +extern ZPOS64_T ZEXPORT unzGetCurrentFileZStreamPos64 OF((unzFile file)); + +/** Addition for GDAL : END */ + + +/***************************************************************************/ +/* for reading the content of the current zipfile, you can open it, read data + from it, and close it (you can close it before reading all the file) + */ + +extern int ZEXPORT unzOpenCurrentFile OF((unzFile file)); +/* + Open for reading data the current file in the zipfile. + If there is no error, the return value is UNZ_OK. +*/ + +extern int ZEXPORT unzOpenCurrentFilePassword OF((unzFile file, + const char* password)); +/* + Open for reading data the current file in the zipfile. + password is a crypting password + If there is no error, the return value is UNZ_OK. +*/ + +extern int ZEXPORT unzOpenCurrentFile2 OF((unzFile file, + int* method, + int* level, + int raw)); +/* + Same than unzOpenCurrentFile, but open for read raw the file (not uncompress) + if raw==1 + *method will receive method of compression, *level will receive level of + compression + note : you can set level parameter as NULL (if you did not want known level, + but you CANNOT set method parameter as NULL +*/ + +extern int ZEXPORT unzOpenCurrentFile3 OF((unzFile file, + int* method, + int* level, + int raw, + const char* password)); +/* + Same than unzOpenCurrentFile, but open for read raw the file (not uncompress) + if raw==1 + *method will receive method of compression, *level will receive level of + compression + note : you can set level parameter as NULL (if you did not want known level, + but you CANNOT set method parameter as NULL +*/ + + +extern int ZEXPORT unzCloseCurrentFile OF((unzFile file)); +/* + Close the file in zip opened with unzOpenCurrentFile + Return UNZ_CRCERROR if all the file was read but the CRC is not good +*/ + +extern int ZEXPORT unzReadCurrentFile OF((unzFile file, + voidp buf, + unsigned len)); +/* + Read bytes from the current file (opened by unzOpenCurrentFile) + buf contain buffer where data must be copied + len the size of buf. + + return the number of byte copied if somes bytes are copied + return 0 if the end of file was reached + return <0 with error code if there is an error + (UNZ_ERRNO for IO error, or zLib error for uncompress error) +*/ + +extern z_off_t ZEXPORT unztell OF((unzFile file)); + +extern ZPOS64_T ZEXPORT unztell64 OF((unzFile file)); +/* + Give the current position in uncompressed data +*/ + +extern int ZEXPORT unzeof OF((unzFile file)); +/* + return 1 if the end of file was reached, 0 elsewhere +*/ + +extern int ZEXPORT unzGetLocalExtrafield OF((unzFile file, + voidp buf, + unsigned len)); +/* + Read extra field from the current file (opened by unzOpenCurrentFile) + This is the local-header version of the extra field (sometimes, there is + more info in the local-header version than in the central-header) + + if buf==NULL, it return the size of the local extra field + + if buf!=NULL, len is the size of the buffer, the extra header is copied in + buf. + the return value is the number of bytes copied in buf, or (if <0) + the error code +*/ + +/***************************************************************************/ + +/* Get the current file offset */ +extern ZPOS64_T ZEXPORT unzGetOffset64 (unzFile file); +extern uLong ZEXPORT unzGetOffset (unzFile file); + +/* Set the current file offset */ +extern int ZEXPORT unzSetOffset64 (unzFile file, ZPOS64_T pos); +extern int ZEXPORT unzSetOffset (unzFile file, uLong pos); + + + +#ifdef __cplusplus +} +#endif + +#endif /* _unz64_H */ diff --git a/DSView/pv/minizip/zip.c b/DSView/pv/minizip/zip.c new file mode 100644 index 00000000..44e88a9c --- /dev/null +++ b/DSView/pv/minizip/zip.c @@ -0,0 +1,2007 @@ +/* zip.c -- IO on .zip files using zlib + Version 1.1, February 14h, 2010 + part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications for Zip64 support + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) + + For more info read MiniZip_info.txt + + Changes + Oct-2009 - Mathias Svensson - Remove old C style function prototypes + Oct-2009 - Mathias Svensson - Added Zip64 Support when creating new file archives + Oct-2009 - Mathias Svensson - Did some code cleanup and refactoring to get better overview of some functions. + Oct-2009 - Mathias Svensson - Added zipRemoveExtraInfoBlock to strip extra field data from its ZIP64 data + It is used when recreting zip archive with RAW when deleting items from a zip. + ZIP64 data is automatically added to items that needs it, and existing ZIP64 data need to be removed. + Oct-2009 - Mathias Svensson - Added support for BZIP2 as compression mode (bzip2 lib is required) + Jan-2010 - back to unzip and minizip 1.0 name scheme, with compatibility layer + +*/ + + +#include +#include +#include +#include +#include "zlib.h" +#include "zip.h" + +#ifdef STDC +# include +# include +# include +#endif +#ifdef NO_ERRNO_H + extern int errno; +#else +# include +#endif + + +#ifndef local +# define local static +#endif +/* compile with -Dlocal if your debugger can't find static symbols */ + +#ifndef VERSIONMADEBY +# define VERSIONMADEBY (0x0) /* platform depedent */ +#endif + +#ifndef Z_BUFSIZE +#define Z_BUFSIZE (64*1024) //(16384) +#endif + +#ifndef Z_MAXFILENAMEINZIP +#define Z_MAXFILENAMEINZIP (256) +#endif + +#ifndef ALLOC +# define ALLOC(size) (malloc(size)) +#endif +#ifndef TRYFREE +# define TRYFREE(p) {if (p) free(p);} +#endif + +/* +#define SIZECENTRALDIRITEM (0x2e) +#define SIZEZIPLOCALHEADER (0x1e) +*/ + +/* I've found an old Unix (a SunOS 4.1.3_U1) without all SEEK_* defined.... */ + + +// NOT sure that this work on ALL platform +#define MAKEULONG64(a, b) ((ZPOS64_T)(((unsigned long)(a)) | ((ZPOS64_T)((unsigned long)(b))) << 32)) + +#ifndef SEEK_CUR +#define SEEK_CUR 1 +#endif + +#ifndef SEEK_END +#define SEEK_END 2 +#endif + +#ifndef SEEK_SET +#define SEEK_SET 0 +#endif + +#ifndef DEF_MEM_LEVEL +#if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +#else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#endif +#endif +const char zip_copyright[] =" zip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll"; + + +#define SIZEDATA_INDATABLOCK (4096-(4*4)) + +#define LOCALHEADERMAGIC (0x04034b50) +#define CENTRALHEADERMAGIC (0x02014b50) +#define ENDHEADERMAGIC (0x06054b50) +#define ZIP64ENDHEADERMAGIC (0x6064b50) +#define ZIP64ENDLOCHEADERMAGIC (0x7064b50) + +#define FLAG_LOCALHEADER_OFFSET (0x06) +#define CRC_LOCALHEADER_OFFSET (0x0e) + +#define SIZECENTRALHEADER (0x2e) /* 46 */ + +typedef struct linkedlist_datablock_internal_s +{ + struct linkedlist_datablock_internal_s* next_datablock; + uLong avail_in_this_block; + uLong filled_in_this_block; + uLong unused; /* for future use and alignment */ + unsigned char data[SIZEDATA_INDATABLOCK]; +} linkedlist_datablock_internal; + +typedef struct linkedlist_data_s +{ + linkedlist_datablock_internal* first_block; + linkedlist_datablock_internal* last_block; +} linkedlist_data; + + +typedef struct +{ + z_stream stream; /* zLib stream structure for inflate */ +#ifdef HAVE_BZIP2 + bz_stream bstream; /* bzLib stream structure for bziped */ +#endif + + int stream_initialised; /* 1 is stream is initialised */ + uInt pos_in_buffered_data; /* last written byte in buffered_data */ + + ZPOS64_T pos_local_header; /* offset of the local header of the file + currenty writing */ + char* central_header; /* central header data for the current file */ + uLong size_centralExtra; + uLong size_centralheader; /* size of the central header for cur file */ + uLong size_centralExtraFree; /* Extra bytes allocated to the centralheader but that are not used */ + uLong flag; /* flag of the file currently writing */ + + int method; /* compression method of file currenty wr.*/ + int raw; /* 1 for directly writing raw data */ + Byte buffered_data[Z_BUFSIZE];/* buffer contain compressed data to be writ*/ + uLong dosDate; + uLong crc32; + int encrypt; + int zip64; /* Add ZIP64 extened information in the extra field */ + ZPOS64_T pos_zip64extrainfo; + ZPOS64_T totalCompressedData; + ZPOS64_T totalUncompressedData; +#ifndef NOCRYPT + unsigned long keys[3]; /* keys defining the pseudo-random sequence */ + const z_crc_t* pcrc_32_tab; + int crypt_header_size; +#endif +} curfile64_info; + +typedef struct +{ + zlib_filefunc64_32_def z_filefunc; + voidpf filestream; /* io structore of the zipfile */ + linkedlist_data central_dir;/* datablock with central dir in construction*/ + int in_opened_file_inzip; /* 1 if a file in the zip is currently writ.*/ + curfile64_info ci; /* info on the file curretly writing */ + + ZPOS64_T begin_pos; /* position of the beginning of the zipfile */ + ZPOS64_T add_position_when_writing_offset; + ZPOS64_T number_entry; + +#ifndef NO_ADDFILEINEXISTINGZIP + char *globalcomment; +#endif + +} zip64_internal; + + +#ifndef NOCRYPT +#define INCLUDECRYPTINGCODE_IFCRYPTALLOWED +#include "crypt.h" +#endif + +local linkedlist_datablock_internal* allocate_new_datablock() +{ + linkedlist_datablock_internal* ldi; + ldi = (linkedlist_datablock_internal*) + ALLOC(sizeof(linkedlist_datablock_internal)); + if (ldi!=NULL) + { + ldi->next_datablock = NULL ; + ldi->filled_in_this_block = 0 ; + ldi->avail_in_this_block = SIZEDATA_INDATABLOCK ; + } + return ldi; +} + +local void free_datablock(linkedlist_datablock_internal* ldi) +{ + while (ldi!=NULL) + { + linkedlist_datablock_internal* ldinext = ldi->next_datablock; + TRYFREE(ldi); + ldi = ldinext; + } +} + +local void init_linkedlist(linkedlist_data* ll) +{ + ll->first_block = ll->last_block = NULL; +} + +local void free_linkedlist(linkedlist_data* ll) +{ + free_datablock(ll->first_block); + ll->first_block = ll->last_block = NULL; +} + + +local int add_data_in_datablock(linkedlist_data* ll, const void* buf, uLong len) +{ + linkedlist_datablock_internal* ldi; + const unsigned char* from_copy; + + if (ll==NULL) + return ZIP_INTERNALERROR; + + if (ll->last_block == NULL) + { + ll->first_block = ll->last_block = allocate_new_datablock(); + if (ll->first_block == NULL) + return ZIP_INTERNALERROR; + } + + ldi = ll->last_block; + from_copy = (unsigned char*)buf; + + while (len>0) + { + uInt copy_this; + uInt i; + unsigned char* to_copy; + + if (ldi->avail_in_this_block==0) + { + ldi->next_datablock = allocate_new_datablock(); + if (ldi->next_datablock == NULL) + return ZIP_INTERNALERROR; + ldi = ldi->next_datablock ; + ll->last_block = ldi; + } + + if (ldi->avail_in_this_block < len) + copy_this = (uInt)ldi->avail_in_this_block; + else + copy_this = (uInt)len; + + to_copy = &(ldi->data[ldi->filled_in_this_block]); + + for (i=0;ifilled_in_this_block += copy_this; + ldi->avail_in_this_block -= copy_this; + from_copy += copy_this ; + len -= copy_this; + } + return ZIP_OK; +} + + + +/****************************************************************************/ + +#ifndef NO_ADDFILEINEXISTINGZIP +/* =========================================================================== + Inputs a long in LSB order to the given file + nbByte == 1, 2 ,4 or 8 (byte, short or long, ZPOS64_T) +*/ + +local int zip64local_putValue OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T x, int nbByte)); +local int zip64local_putValue (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T x, int nbByte) +{ + unsigned char buf[8]; + int n; + for (n = 0; n < nbByte; n++) + { + buf[n] = (unsigned char)(x & 0xff); + x >>= 8; + } + if (x != 0) + { /* data overflow - hack for ZIP64 (X Roche) */ + for (n = 0; n < nbByte; n++) + { + buf[n] = 0xff; + } + } + + if (ZWRITE64(*pzlib_filefunc_def,filestream,buf,nbByte)!=(uLong)nbByte) + return ZIP_ERRNO; + else + return ZIP_OK; +} + +local void zip64local_putValue_inmemory OF((void* dest, ZPOS64_T x, int nbByte)); +local void zip64local_putValue_inmemory (void* dest, ZPOS64_T x, int nbByte) +{ + unsigned char* buf=(unsigned char*)dest; + int n; + for (n = 0; n < nbByte; n++) { + buf[n] = (unsigned char)(x & 0xff); + x >>= 8; + } + + if (x != 0) + { /* data overflow - hack for ZIP64 */ + for (n = 0; n < nbByte; n++) + { + buf[n] = 0xff; + } + } +} + +/****************************************************************************/ + + +local uLong zip64local_TmzDateToDosDate(const tm_zip* ptm) +{ + uLong year = (uLong)ptm->tm_year; + if (year>=1980) + year-=1980; + else if (year>=80) + year-=80; + return + (uLong) (((ptm->tm_mday) + (32 * (ptm->tm_mon+1)) + (512 * year)) << 16) | + ((ptm->tm_sec/2) + (32* ptm->tm_min) + (2048 * (uLong)ptm->tm_hour)); +} + + +/****************************************************************************/ + +local int zip64local_getByte OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, int *pi)); + +local int zip64local_getByte(const zlib_filefunc64_32_def* pzlib_filefunc_def,voidpf filestream,int* pi) +{ + unsigned char c; + int err = (int)ZREAD64(*pzlib_filefunc_def,filestream,&c,1); + if (err==1) + { + *pi = (int)c; + return ZIP_OK; + } + else + { + if (ZERROR64(*pzlib_filefunc_def,filestream)) + return ZIP_ERRNO; + else + return ZIP_EOF; + } +} + + +/* =========================================================================== + Reads a long in LSB order from the given gz_stream. Sets +*/ +local int zip64local_getShort OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong *pX)); + +local int zip64local_getShort (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong* pX) +{ + uLong x ; + int i = 0; + int err; + + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x = (uLong)i; + + if (err==ZIP_OK) + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((uLong)i)<<8; + + if (err==ZIP_OK) + *pX = x; + else + *pX = 0; + return err; +} + +local int zip64local_getLong OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong *pX)); + +local int zip64local_getLong (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong* pX) +{ + uLong x ; + int i = 0; + int err; + + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x = (uLong)i; + + if (err==ZIP_OK) + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((uLong)i)<<8; + + if (err==ZIP_OK) + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((uLong)i)<<16; + + if (err==ZIP_OK) + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((uLong)i)<<24; + + if (err==ZIP_OK) + *pX = x; + else + *pX = 0; + return err; +} + +local int zip64local_getLong64 OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T *pX)); + + +local int zip64local_getLong64 (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T *pX) +{ + ZPOS64_T x; + int i = 0; + int err; + + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x = (ZPOS64_T)i; + + if (err==ZIP_OK) + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((ZPOS64_T)i)<<8; + + if (err==ZIP_OK) + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((ZPOS64_T)i)<<16; + + if (err==ZIP_OK) + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((ZPOS64_T)i)<<24; + + if (err==ZIP_OK) + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((ZPOS64_T)i)<<32; + + if (err==ZIP_OK) + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((ZPOS64_T)i)<<40; + + if (err==ZIP_OK) + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((ZPOS64_T)i)<<48; + + if (err==ZIP_OK) + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((ZPOS64_T)i)<<56; + + if (err==ZIP_OK) + *pX = x; + else + *pX = 0; + + return err; +} + +#ifndef BUFREADCOMMENT +#define BUFREADCOMMENT (0x400) +#endif +/* + Locate the Central directory of a zipfile (at the end, just before + the global comment) +*/ +local ZPOS64_T zip64local_SearchCentralDir OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream)); + +local ZPOS64_T zip64local_SearchCentralDir(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream) +{ + unsigned char* buf; + ZPOS64_T uSizeFile; + ZPOS64_T uBackRead; + ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */ + ZPOS64_T uPosFound=0; + + if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0) + return 0; + + + uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream); + + if (uMaxBack>uSizeFile) + uMaxBack = uSizeFile; + + buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4); + if (buf==NULL) + return 0; + + uBackRead = 4; + while (uBackReaduMaxBack) + uBackRead = uMaxBack; + else + uBackRead+=BUFREADCOMMENT; + uReadPos = uSizeFile-uBackRead ; + + uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? + (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos); + if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0) + break; + + if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize) + break; + + for (i=(int)uReadSize-3; (i--)>0;) + if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && + ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06)) + { + uPosFound = uReadPos+i; + break; + } + + if (uPosFound!=0) + break; + } + TRYFREE(buf); + return uPosFound; +} + +/* +Locate the End of Zip64 Central directory locator and from there find the CD of a zipfile (at the end, just before +the global comment) +*/ +local ZPOS64_T zip64local_SearchCentralDir64 OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream)); + +local ZPOS64_T zip64local_SearchCentralDir64(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream) +{ + unsigned char* buf; + ZPOS64_T uSizeFile; + ZPOS64_T uBackRead; + ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */ + ZPOS64_T uPosFound=0; + uLong uL; + ZPOS64_T relativeOffset; + + if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0) + return 0; + + uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream); + + if (uMaxBack>uSizeFile) + uMaxBack = uSizeFile; + + buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4); + if (buf==NULL) + return 0; + + uBackRead = 4; + while (uBackReaduMaxBack) + uBackRead = uMaxBack; + else + uBackRead+=BUFREADCOMMENT; + uReadPos = uSizeFile-uBackRead ; + + uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? + (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos); + if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0) + break; + + if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize) + break; + + for (i=(int)uReadSize-3; (i--)>0;) + { + // Signature "0x07064b50" Zip64 end of central directory locater + if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && ((*(buf+i+2))==0x06) && ((*(buf+i+3))==0x07)) + { + uPosFound = uReadPos+i; + break; + } + } + + if (uPosFound!=0) + break; + } + + TRYFREE(buf); + if (uPosFound == 0) + return 0; + + /* Zip64 end of central directory locator */ + if (ZSEEK64(*pzlib_filefunc_def,filestream, uPosFound,ZLIB_FILEFUNC_SEEK_SET)!=0) + return 0; + + /* the signature, already checked */ + if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK) + return 0; + + /* number of the disk with the start of the zip64 end of central directory */ + if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK) + return 0; + if (uL != 0) + return 0; + + /* relative offset of the zip64 end of central directory record */ + if (zip64local_getLong64(pzlib_filefunc_def,filestream,&relativeOffset)!=ZIP_OK) + return 0; + + /* total number of disks */ + if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK) + return 0; + if (uL != 1) + return 0; + + /* Goto Zip64 end of central directory record */ + if (ZSEEK64(*pzlib_filefunc_def,filestream, relativeOffset,ZLIB_FILEFUNC_SEEK_SET)!=0) + return 0; + + /* the signature */ + if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK) + return 0; + + if (uL != 0x06064b50) // signature of 'Zip64 end of central directory' + return 0; + + return relativeOffset; +} + +int LoadCentralDirectoryRecord(zip64_internal* pziinit) +{ + int err=ZIP_OK; + ZPOS64_T byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ + + ZPOS64_T size_central_dir; /* size of the central directory */ + ZPOS64_T offset_central_dir; /* offset of start of central directory */ + ZPOS64_T central_pos; + uLong uL; + + uLong number_disk; /* number of the current dist, used for + spaning ZIP, unsupported, always 0*/ + uLong number_disk_with_CD; /* number the the disk with central dir, used + for spaning ZIP, unsupported, always 0*/ + ZPOS64_T number_entry; + ZPOS64_T number_entry_CD; /* total number of entries in + the central dir + (same than number_entry on nospan) */ + uLong VersionMadeBy; + uLong VersionNeeded; + uLong size_comment; + + int hasZIP64Record = 0; + + // check first if we find a ZIP64 record + central_pos = zip64local_SearchCentralDir64(&pziinit->z_filefunc,pziinit->filestream); + if(central_pos > 0) + { + hasZIP64Record = 1; + } + else if(central_pos == 0) + { + central_pos = zip64local_SearchCentralDir(&pziinit->z_filefunc,pziinit->filestream); + } + +/* disable to allow appending to empty ZIP archive + if (central_pos==0) + err=ZIP_ERRNO; +*/ + + if(hasZIP64Record) + { + ZPOS64_T sizeEndOfCentralDirectory; + if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, central_pos, ZLIB_FILEFUNC_SEEK_SET) != 0) + err=ZIP_ERRNO; + + /* the signature, already checked */ + if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&uL)!=ZIP_OK) + err=ZIP_ERRNO; + + /* size of zip64 end of central directory record */ + if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream, &sizeEndOfCentralDirectory)!=ZIP_OK) + err=ZIP_ERRNO; + + /* version made by */ + if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &VersionMadeBy)!=ZIP_OK) + err=ZIP_ERRNO; + + /* version needed to extract */ + if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &VersionNeeded)!=ZIP_OK) + err=ZIP_ERRNO; + + /* number of this disk */ + if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&number_disk)!=ZIP_OK) + err=ZIP_ERRNO; + + /* number of the disk with the start of the central directory */ + if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&number_disk_with_CD)!=ZIP_OK) + err=ZIP_ERRNO; + + /* total number of entries in the central directory on this disk */ + if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream, &number_entry)!=ZIP_OK) + err=ZIP_ERRNO; + + /* total number of entries in the central directory */ + if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,&number_entry_CD)!=ZIP_OK) + err=ZIP_ERRNO; + + if ((number_entry_CD!=number_entry) || (number_disk_with_CD!=0) || (number_disk!=0)) + err=ZIP_BADZIPFILE; + + /* size of the central directory */ + if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,&size_central_dir)!=ZIP_OK) + err=ZIP_ERRNO; + + /* offset of start of central directory with respect to the + starting disk number */ + if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,&offset_central_dir)!=ZIP_OK) + err=ZIP_ERRNO; + + // TODO.. + // read the comment from the standard central header. + size_comment = 0; + } + else + { + // Read End of central Directory info + if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0) + err=ZIP_ERRNO; + + /* the signature, already checked */ + if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&uL)!=ZIP_OK) + err=ZIP_ERRNO; + + /* number of this disk */ + if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream,&number_disk)!=ZIP_OK) + err=ZIP_ERRNO; + + /* number of the disk with the start of the central directory */ + if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream,&number_disk_with_CD)!=ZIP_OK) + err=ZIP_ERRNO; + + /* total number of entries in the central dir on this disk */ + number_entry = 0; + if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK) + err=ZIP_ERRNO; + else + number_entry = uL; + + /* total number of entries in the central dir */ + number_entry_CD = 0; + if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK) + err=ZIP_ERRNO; + else + number_entry_CD = uL; + + if ((number_entry_CD!=number_entry) || (number_disk_with_CD!=0) || (number_disk!=0)) + err=ZIP_BADZIPFILE; + + /* size of the central directory */ + size_central_dir = 0; + if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK) + err=ZIP_ERRNO; + else + size_central_dir = uL; + + /* offset of start of central directory with respect to the starting disk number */ + offset_central_dir = 0; + if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK) + err=ZIP_ERRNO; + else + offset_central_dir = uL; + + + /* zipfile global comment length */ + if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &size_comment)!=ZIP_OK) + err=ZIP_ERRNO; + } + + if ((central_posz_filefunc, pziinit->filestream); + return ZIP_ERRNO; + } + + if (size_comment>0) + { + pziinit->globalcomment = (char*)ALLOC(size_comment+1); + if (pziinit->globalcomment) + { + size_comment = ZREAD64(pziinit->z_filefunc, pziinit->filestream, pziinit->globalcomment,size_comment); + pziinit->globalcomment[size_comment]=0; + } + } + + byte_before_the_zipfile = central_pos - (offset_central_dir+size_central_dir); + pziinit->add_position_when_writing_offset = byte_before_the_zipfile; + + { + ZPOS64_T size_central_dir_to_read = size_central_dir; + size_t buf_size = SIZEDATA_INDATABLOCK; + void* buf_read = (void*)ALLOC(buf_size); + if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, offset_central_dir + byte_before_the_zipfile, ZLIB_FILEFUNC_SEEK_SET) != 0) + err=ZIP_ERRNO; + + while ((size_central_dir_to_read>0) && (err==ZIP_OK)) + { + ZPOS64_T read_this = SIZEDATA_INDATABLOCK; + if (read_this > size_central_dir_to_read) + read_this = size_central_dir_to_read; + + if (ZREAD64(pziinit->z_filefunc, pziinit->filestream,buf_read,(uLong)read_this) != read_this) + err=ZIP_ERRNO; + + if (err==ZIP_OK) + err = add_data_in_datablock(&pziinit->central_dir,buf_read, (uLong)read_this); + + size_central_dir_to_read-=read_this; + } + TRYFREE(buf_read); + } + pziinit->begin_pos = byte_before_the_zipfile; + pziinit->number_entry = number_entry_CD; + + if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, offset_central_dir+byte_before_the_zipfile,ZLIB_FILEFUNC_SEEK_SET) != 0) + err=ZIP_ERRNO; + + return err; +} + + +#endif /* !NO_ADDFILEINEXISTINGZIP*/ + + +/************************************************************/ +extern zipFile ZEXPORT zipOpen3 (const void *pathname, int append, zipcharpc* globalcomment, zlib_filefunc64_32_def* pzlib_filefunc64_32_def) +{ + zip64_internal ziinit; + zip64_internal* zi; + int err=ZIP_OK; + + ziinit.z_filefunc.zseek32_file = NULL; + ziinit.z_filefunc.ztell32_file = NULL; + if (pzlib_filefunc64_32_def==NULL) + fill_fopen64_filefunc(&ziinit.z_filefunc.zfile_func64); + else + ziinit.z_filefunc = *pzlib_filefunc64_32_def; + + ziinit.filestream = ZOPEN64(ziinit.z_filefunc, + pathname, + (append == APPEND_STATUS_CREATE) ? + (ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE | ZLIB_FILEFUNC_MODE_CREATE) : + (ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE | ZLIB_FILEFUNC_MODE_EXISTING)); + + if (ziinit.filestream == NULL) + return NULL; + + if (append == APPEND_STATUS_CREATEAFTER) + ZSEEK64(ziinit.z_filefunc,ziinit.filestream,0,SEEK_END); + + ziinit.begin_pos = ZTELL64(ziinit.z_filefunc,ziinit.filestream); + ziinit.in_opened_file_inzip = 0; + ziinit.ci.stream_initialised = 0; + ziinit.number_entry = 0; + ziinit.add_position_when_writing_offset = 0; + init_linkedlist(&(ziinit.central_dir)); + + + + zi = (zip64_internal*)ALLOC(sizeof(zip64_internal)); + if (zi==NULL) + { + ZCLOSE64(ziinit.z_filefunc,ziinit.filestream); + return NULL; + } + + /* now we add file in a zipfile */ +# ifndef NO_ADDFILEINEXISTINGZIP + ziinit.globalcomment = NULL; + if (append == APPEND_STATUS_ADDINZIP) + { + // Read and Cache Central Directory Records + err = LoadCentralDirectoryRecord(&ziinit); + } + + if (globalcomment) + { + *globalcomment = ziinit.globalcomment; + } +# endif /* !NO_ADDFILEINEXISTINGZIP*/ + + if (err != ZIP_OK) + { +# ifndef NO_ADDFILEINEXISTINGZIP + TRYFREE(ziinit.globalcomment); +# endif /* !NO_ADDFILEINEXISTINGZIP*/ + TRYFREE(zi); + return NULL; + } + else + { + *zi = ziinit; + return (zipFile)zi; + } +} + +extern zipFile ZEXPORT zipOpen2 (const char *pathname, int append, zipcharpc* globalcomment, zlib_filefunc_def* pzlib_filefunc32_def) +{ + if (pzlib_filefunc32_def != NULL) + { + zlib_filefunc64_32_def zlib_filefunc64_32_def_fill; + fill_zlib_filefunc64_32_def_from_filefunc32(&zlib_filefunc64_32_def_fill,pzlib_filefunc32_def); + return zipOpen3(pathname, append, globalcomment, &zlib_filefunc64_32_def_fill); + } + else + return zipOpen3(pathname, append, globalcomment, NULL); +} + +extern zipFile ZEXPORT zipOpen2_64 (const void *pathname, int append, zipcharpc* globalcomment, zlib_filefunc64_def* pzlib_filefunc_def) +{ + if (pzlib_filefunc_def != NULL) + { + zlib_filefunc64_32_def zlib_filefunc64_32_def_fill; + zlib_filefunc64_32_def_fill.zfile_func64 = *pzlib_filefunc_def; + zlib_filefunc64_32_def_fill.ztell32_file = NULL; + zlib_filefunc64_32_def_fill.zseek32_file = NULL; + return zipOpen3(pathname, append, globalcomment, &zlib_filefunc64_32_def_fill); + } + else + return zipOpen3(pathname, append, globalcomment, NULL); +} + + + +extern zipFile ZEXPORT zipOpen (const char* pathname, int append) +{ + return zipOpen3((const void*)pathname,append,NULL,NULL); +} + +extern zipFile ZEXPORT zipOpen64 (const void* pathname, int append) +{ + return zipOpen3(pathname,append,NULL,NULL); +} + +int Write_LocalFileHeader(zip64_internal* zi, const char* filename, uInt size_extrafield_local, const void* extrafield_local) +{ + /* write the local header */ + int err; + uInt size_filename = (uInt)strlen(filename); + uInt size_extrafield = size_extrafield_local; + + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)LOCALHEADERMAGIC, 4); + + if (err==ZIP_OK) + { + if(zi->ci.zip64) + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)45,2);/* version needed to extract */ + else + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)20,2);/* version needed to extract */ + } + + if (err==ZIP_OK) + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.flag,2); + + if (err==ZIP_OK) + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.method,2); + + if (err==ZIP_OK) + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.dosDate,4); + + // CRC / Compressed size / Uncompressed size will be filled in later and rewritten later + if (err==ZIP_OK) + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* crc 32, unknown */ + if (err==ZIP_OK) + { + if(zi->ci.zip64) + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xFFFFFFFF,4); /* compressed size, unknown */ + else + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* compressed size, unknown */ + } + if (err==ZIP_OK) + { + if(zi->ci.zip64) + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xFFFFFFFF,4); /* uncompressed size, unknown */ + else + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* uncompressed size, unknown */ + } + + if (err==ZIP_OK) + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_filename,2); + + if(zi->ci.zip64) + { + size_extrafield += 20; + } + + if (err==ZIP_OK) + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_extrafield,2); + + if ((err==ZIP_OK) && (size_filename > 0)) + { + if (ZWRITE64(zi->z_filefunc,zi->filestream,filename,size_filename)!=size_filename) + err = ZIP_ERRNO; + } + + if ((err==ZIP_OK) && (size_extrafield_local > 0)) + { + if (ZWRITE64(zi->z_filefunc, zi->filestream, extrafield_local, size_extrafield_local) != size_extrafield_local) + err = ZIP_ERRNO; + } + + + if ((err==ZIP_OK) && (zi->ci.zip64)) + { + // write the Zip64 extended info + short HeaderID = 1; + short DataSize = 16; + ZPOS64_T CompressedSize = 0; + ZPOS64_T UncompressedSize = 0; + + // Remember position of Zip64 extended info for the local file header. (needed when we update size after done with file) + zi->ci.pos_zip64extrainfo = ZTELL64(zi->z_filefunc,zi->filestream); + + err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (short)HeaderID,2); + err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (short)DataSize,2); + + err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (ZPOS64_T)UncompressedSize,8); + err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (ZPOS64_T)CompressedSize,8); + } + + return err; +} + +/* + NOTE. + When writing RAW the ZIP64 extended information in extrafield_local and extrafield_global needs to be stripped + before calling this function it can be done with zipRemoveExtraInfoBlock + + It is not done here because then we need to realloc a new buffer since parameters are 'const' and I want to minimize + unnecessary allocations. + */ +extern int ZEXPORT zipOpenNewFileInZip4_64 (zipFile file, const char* filename, const zip_fileinfo* zipfi, + const void* extrafield_local, uInt size_extrafield_local, + const void* extrafield_global, uInt size_extrafield_global, + const char* comment, int method, int level, int raw, + int windowBits,int memLevel, int strategy, + const char* password, uLong crcForCrypting, + uLong versionMadeBy, uLong flagBase, int zip64) +{ + zip64_internal* zi; + uInt size_filename; + uInt size_comment; + uInt i; + int err = ZIP_OK; + +# ifdef NOCRYPT + (crcForCrypting); + if (password != NULL) + return ZIP_PARAMERROR; +# endif + + if (file == NULL) + return ZIP_PARAMERROR; + +#ifdef HAVE_BZIP2 + if ((method!=0) && (method!=Z_DEFLATED) && (method!=Z_BZIP2ED)) + return ZIP_PARAMERROR; +#else + if ((method!=0) && (method!=Z_DEFLATED)) + return ZIP_PARAMERROR; +#endif + + zi = (zip64_internal*)file; + + if (zi->in_opened_file_inzip == 1) + { + err = zipCloseFileInZip (file); + if (err != ZIP_OK) + return err; + } + + if (filename==NULL) + filename="-"; + + if (comment==NULL) + size_comment = 0; + else + size_comment = (uInt)strlen(comment); + + size_filename = (uInt)strlen(filename); + + if (zipfi == NULL) + zi->ci.dosDate = 0; + else + { + if (zipfi->dosDate != 0) + zi->ci.dosDate = zipfi->dosDate; + else + zi->ci.dosDate = zip64local_TmzDateToDosDate(&zipfi->tmz_date); + } + + zi->ci.flag = flagBase; + if ((level==8) || (level==9)) + zi->ci.flag |= 2; + if (level==2) + zi->ci.flag |= 4; + if (level==1) + zi->ci.flag |= 6; + if (password != NULL) + zi->ci.flag |= 1; + + zi->ci.crc32 = 0; + zi->ci.method = method; + zi->ci.encrypt = 0; + zi->ci.stream_initialised = 0; + zi->ci.pos_in_buffered_data = 0; + zi->ci.raw = raw; + zi->ci.pos_local_header = ZTELL64(zi->z_filefunc,zi->filestream); + + zi->ci.size_centralheader = SIZECENTRALHEADER + size_filename + size_extrafield_global + size_comment; + zi->ci.size_centralExtraFree = 32; // Extra space we have reserved in case we need to add ZIP64 extra info data + + zi->ci.central_header = (char*)ALLOC((uInt)zi->ci.size_centralheader + zi->ci.size_centralExtraFree); + + zi->ci.size_centralExtra = size_extrafield_global; + zip64local_putValue_inmemory(zi->ci.central_header,(uLong)CENTRALHEADERMAGIC,4); + /* version info */ + zip64local_putValue_inmemory(zi->ci.central_header+4,(uLong)versionMadeBy,2); + zip64local_putValue_inmemory(zi->ci.central_header+6,(uLong)20,2); + zip64local_putValue_inmemory(zi->ci.central_header+8,(uLong)zi->ci.flag,2); + zip64local_putValue_inmemory(zi->ci.central_header+10,(uLong)zi->ci.method,2); + zip64local_putValue_inmemory(zi->ci.central_header+12,(uLong)zi->ci.dosDate,4); + zip64local_putValue_inmemory(zi->ci.central_header+16,(uLong)0,4); /*crc*/ + zip64local_putValue_inmemory(zi->ci.central_header+20,(uLong)0,4); /*compr size*/ + zip64local_putValue_inmemory(zi->ci.central_header+24,(uLong)0,4); /*uncompr size*/ + zip64local_putValue_inmemory(zi->ci.central_header+28,(uLong)size_filename,2); + zip64local_putValue_inmemory(zi->ci.central_header+30,(uLong)size_extrafield_global,2); + zip64local_putValue_inmemory(zi->ci.central_header+32,(uLong)size_comment,2); + zip64local_putValue_inmemory(zi->ci.central_header+34,(uLong)0,2); /*disk nm start*/ + + if (zipfi==NULL) + zip64local_putValue_inmemory(zi->ci.central_header+36,(uLong)0,2); + else + zip64local_putValue_inmemory(zi->ci.central_header+36,(uLong)zipfi->internal_fa,2); + + if (zipfi==NULL) + zip64local_putValue_inmemory(zi->ci.central_header+38,(uLong)0,4); + else + zip64local_putValue_inmemory(zi->ci.central_header+38,(uLong)zipfi->external_fa,4); + + if(zi->ci.pos_local_header >= 0xffffffff) + zip64local_putValue_inmemory(zi->ci.central_header+42,(uLong)0xffffffff,4); + else + zip64local_putValue_inmemory(zi->ci.central_header+42,(uLong)zi->ci.pos_local_header - zi->add_position_when_writing_offset,4); + + for (i=0;ici.central_header+SIZECENTRALHEADER+i) = *(filename+i); + + for (i=0;ici.central_header+SIZECENTRALHEADER+size_filename+i) = + *(((const char*)extrafield_global)+i); + + for (i=0;ici.central_header+SIZECENTRALHEADER+size_filename+ + size_extrafield_global+i) = *(comment+i); + if (zi->ci.central_header == NULL) + return ZIP_INTERNALERROR; + + zi->ci.zip64 = zip64; + zi->ci.totalCompressedData = 0; + zi->ci.totalUncompressedData = 0; + zi->ci.pos_zip64extrainfo = 0; + + err = Write_LocalFileHeader(zi, filename, size_extrafield_local, extrafield_local); + +#ifdef HAVE_BZIP2 + zi->ci.bstream.avail_in = (uInt)0; + zi->ci.bstream.avail_out = (uInt)Z_BUFSIZE; + zi->ci.bstream.next_out = (char*)zi->ci.buffered_data; + zi->ci.bstream.total_in_hi32 = 0; + zi->ci.bstream.total_in_lo32 = 0; + zi->ci.bstream.total_out_hi32 = 0; + zi->ci.bstream.total_out_lo32 = 0; +#endif + + zi->ci.stream.avail_in = (uInt)0; + zi->ci.stream.avail_out = (uInt)Z_BUFSIZE; + zi->ci.stream.next_out = zi->ci.buffered_data; + zi->ci.stream.total_in = 0; + zi->ci.stream.total_out = 0; + zi->ci.stream.data_type = Z_BINARY; + +#ifdef HAVE_BZIP2 + if ((err==ZIP_OK) && (zi->ci.method == Z_DEFLATED || zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw)) +#else + if ((err==ZIP_OK) && (zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) +#endif + { + if(zi->ci.method == Z_DEFLATED) + { + zi->ci.stream.zalloc = (alloc_func)0; + zi->ci.stream.zfree = (free_func)0; + zi->ci.stream.opaque = (voidpf)0; + + if (windowBits>0) + windowBits = -windowBits; + + err = deflateInit2(&zi->ci.stream, level, Z_DEFLATED, windowBits, memLevel, strategy); + + if (err==Z_OK) + zi->ci.stream_initialised = Z_DEFLATED; + } + else if(zi->ci.method == Z_BZIP2ED) + { +#ifdef HAVE_BZIP2 + // Init BZip stuff here + zi->ci.bstream.bzalloc = 0; + zi->ci.bstream.bzfree = 0; + zi->ci.bstream.opaque = (voidpf)0; + + err = BZ2_bzCompressInit(&zi->ci.bstream, level, 0,35); + if(err == BZ_OK) + zi->ci.stream_initialised = Z_BZIP2ED; +#endif + } + + } + +# ifndef NOCRYPT + zi->ci.crypt_header_size = 0; + if ((err==Z_OK) && (password != NULL)) + { + unsigned char bufHead[RAND_HEAD_LEN]; + unsigned int sizeHead; + zi->ci.encrypt = 1; + zi->ci.pcrc_32_tab = get_crc_table(); + /*init_keys(password,zi->ci.keys,zi->ci.pcrc_32_tab);*/ + + sizeHead=crypthead(password,bufHead,RAND_HEAD_LEN,zi->ci.keys,zi->ci.pcrc_32_tab,crcForCrypting); + zi->ci.crypt_header_size = sizeHead; + + if (ZWRITE64(zi->z_filefunc,zi->filestream,bufHead,sizeHead) != sizeHead) + err = ZIP_ERRNO; + } +# endif + + if (err==Z_OK) + zi->in_opened_file_inzip = 1; + return err; +} + +extern int ZEXPORT zipOpenNewFileInZip4 (zipFile file, const char* filename, const zip_fileinfo* zipfi, + const void* extrafield_local, uInt size_extrafield_local, + const void* extrafield_global, uInt size_extrafield_global, + const char* comment, int method, int level, int raw, + int windowBits,int memLevel, int strategy, + const char* password, uLong crcForCrypting, + uLong versionMadeBy, uLong flagBase) +{ + return zipOpenNewFileInZip4_64 (file, filename, zipfi, + extrafield_local, size_extrafield_local, + extrafield_global, size_extrafield_global, + comment, method, level, raw, + windowBits, memLevel, strategy, + password, crcForCrypting, versionMadeBy, flagBase, 0); +} + +extern int ZEXPORT zipOpenNewFileInZip3 (zipFile file, const char* filename, const zip_fileinfo* zipfi, + const void* extrafield_local, uInt size_extrafield_local, + const void* extrafield_global, uInt size_extrafield_global, + const char* comment, int method, int level, int raw, + int windowBits,int memLevel, int strategy, + const char* password, uLong crcForCrypting) +{ + return zipOpenNewFileInZip4_64 (file, filename, zipfi, + extrafield_local, size_extrafield_local, + extrafield_global, size_extrafield_global, + comment, method, level, raw, + windowBits, memLevel, strategy, + password, crcForCrypting, VERSIONMADEBY, 0, 0); +} + +extern int ZEXPORT zipOpenNewFileInZip3_64(zipFile file, const char* filename, const zip_fileinfo* zipfi, + const void* extrafield_local, uInt size_extrafield_local, + const void* extrafield_global, uInt size_extrafield_global, + const char* comment, int method, int level, int raw, + int windowBits,int memLevel, int strategy, + const char* password, uLong crcForCrypting, int zip64) +{ + return zipOpenNewFileInZip4_64 (file, filename, zipfi, + extrafield_local, size_extrafield_local, + extrafield_global, size_extrafield_global, + comment, method, level, raw, + windowBits, memLevel, strategy, + password, crcForCrypting, VERSIONMADEBY, 0, zip64); +} + +extern int ZEXPORT zipOpenNewFileInZip2(zipFile file, const char* filename, const zip_fileinfo* zipfi, + const void* extrafield_local, uInt size_extrafield_local, + const void* extrafield_global, uInt size_extrafield_global, + const char* comment, int method, int level, int raw) +{ + return zipOpenNewFileInZip4_64 (file, filename, zipfi, + extrafield_local, size_extrafield_local, + extrafield_global, size_extrafield_global, + comment, method, level, raw, + -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, + NULL, 0, VERSIONMADEBY, 0, 0); +} + +extern int ZEXPORT zipOpenNewFileInZip2_64(zipFile file, const char* filename, const zip_fileinfo* zipfi, + const void* extrafield_local, uInt size_extrafield_local, + const void* extrafield_global, uInt size_extrafield_global, + const char* comment, int method, int level, int raw, int zip64) +{ + return zipOpenNewFileInZip4_64 (file, filename, zipfi, + extrafield_local, size_extrafield_local, + extrafield_global, size_extrafield_global, + comment, method, level, raw, + -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, + NULL, 0, VERSIONMADEBY, 0, zip64); +} + +extern int ZEXPORT zipOpenNewFileInZip64 (zipFile file, const char* filename, const zip_fileinfo* zipfi, + const void* extrafield_local, uInt size_extrafield_local, + const void*extrafield_global, uInt size_extrafield_global, + const char* comment, int method, int level, int zip64) +{ + return zipOpenNewFileInZip4_64 (file, filename, zipfi, + extrafield_local, size_extrafield_local, + extrafield_global, size_extrafield_global, + comment, method, level, 0, + -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, + NULL, 0, VERSIONMADEBY, 0, zip64); +} + +extern int ZEXPORT zipOpenNewFileInZip (zipFile file, const char* filename, const zip_fileinfo* zipfi, + const void* extrafield_local, uInt size_extrafield_local, + const void*extrafield_global, uInt size_extrafield_global, + const char* comment, int method, int level) +{ + return zipOpenNewFileInZip4_64 (file, filename, zipfi, + extrafield_local, size_extrafield_local, + extrafield_global, size_extrafield_global, + comment, method, level, 0, + -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, + NULL, 0, VERSIONMADEBY, 0, 0); +} + +local int zip64FlushWriteBuffer(zip64_internal* zi) +{ + int err=ZIP_OK; + + if (zi->ci.encrypt != 0) + { +#ifndef NOCRYPT + uInt i; + int t; + for (i=0;ici.pos_in_buffered_data;i++) + zi->ci.buffered_data[i] = zencode(zi->ci.keys, zi->ci.pcrc_32_tab, zi->ci.buffered_data[i],t); +#endif + } + + if (ZWRITE64(zi->z_filefunc,zi->filestream,zi->ci.buffered_data,zi->ci.pos_in_buffered_data) != zi->ci.pos_in_buffered_data) + err = ZIP_ERRNO; + + zi->ci.totalCompressedData += zi->ci.pos_in_buffered_data; + +#ifdef HAVE_BZIP2 + if(zi->ci.method == Z_BZIP2ED) + { + zi->ci.totalUncompressedData += zi->ci.bstream.total_in_lo32; + zi->ci.bstream.total_in_lo32 = 0; + zi->ci.bstream.total_in_hi32 = 0; + } + else +#endif + { + zi->ci.totalUncompressedData += zi->ci.stream.total_in; + zi->ci.stream.total_in = 0; + } + + + zi->ci.pos_in_buffered_data = 0; + + return err; +} + +extern int ZEXPORT zipWriteInFileInZip (zipFile file,const void* buf,unsigned int len) +{ + zip64_internal* zi; + int err=ZIP_OK; + + if (file == NULL) + return ZIP_PARAMERROR; + zi = (zip64_internal*)file; + + if (zi->in_opened_file_inzip == 0) + return ZIP_PARAMERROR; + + zi->ci.crc32 = crc32(zi->ci.crc32,buf,(uInt)len); + +#ifdef HAVE_BZIP2 + if(zi->ci.method == Z_BZIP2ED && (!zi->ci.raw)) + { + zi->ci.bstream.next_in = (void*)buf; + zi->ci.bstream.avail_in = len; + err = BZ_RUN_OK; + + while ((err==BZ_RUN_OK) && (zi->ci.bstream.avail_in>0)) + { + if (zi->ci.bstream.avail_out == 0) + { + if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO) + err = ZIP_ERRNO; + zi->ci.bstream.avail_out = (uInt)Z_BUFSIZE; + zi->ci.bstream.next_out = (char*)zi->ci.buffered_data; + } + + + if(err != BZ_RUN_OK) + break; + + if ((zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw)) + { + uLong uTotalOutBefore_lo = zi->ci.bstream.total_out_lo32; +// uLong uTotalOutBefore_hi = zi->ci.bstream.total_out_hi32; + err=BZ2_bzCompress(&zi->ci.bstream, BZ_RUN); + + zi->ci.pos_in_buffered_data += (uInt)(zi->ci.bstream.total_out_lo32 - uTotalOutBefore_lo) ; + } + } + + if(err == BZ_RUN_OK) + err = ZIP_OK; + } + else +#endif + { + zi->ci.stream.next_in = (Bytef*)buf; + zi->ci.stream.avail_in = len; + + while ((err==ZIP_OK) && (zi->ci.stream.avail_in>0)) + { + if (zi->ci.stream.avail_out == 0) + { + if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO) + err = ZIP_ERRNO; + zi->ci.stream.avail_out = (uInt)Z_BUFSIZE; + zi->ci.stream.next_out = zi->ci.buffered_data; + } + + + if(err != ZIP_OK) + break; + + if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) + { + uLong uTotalOutBefore = zi->ci.stream.total_out; + err=deflate(&zi->ci.stream, Z_NO_FLUSH); + if(uTotalOutBefore > zi->ci.stream.total_out) + { + int bBreak = 0; + bBreak++; + } + + zi->ci.pos_in_buffered_data += (uInt)(zi->ci.stream.total_out - uTotalOutBefore) ; + } + else + { + uInt copy_this,i; + if (zi->ci.stream.avail_in < zi->ci.stream.avail_out) + copy_this = zi->ci.stream.avail_in; + else + copy_this = zi->ci.stream.avail_out; + + for (i = 0; i < copy_this; i++) + *(((char*)zi->ci.stream.next_out)+i) = + *(((const char*)zi->ci.stream.next_in)+i); + { + zi->ci.stream.avail_in -= copy_this; + zi->ci.stream.avail_out-= copy_this; + zi->ci.stream.next_in+= copy_this; + zi->ci.stream.next_out+= copy_this; + zi->ci.stream.total_in+= copy_this; + zi->ci.stream.total_out+= copy_this; + zi->ci.pos_in_buffered_data += copy_this; + } + } + }// while(...) + } + + return err; +} + +extern int ZEXPORT zipCloseFileInZipRaw (zipFile file, uLong uncompressed_size, uLong crc32) +{ + return zipCloseFileInZipRaw64 (file, uncompressed_size, crc32); +} + +extern int ZEXPORT zipCloseFileInZipRaw64 (zipFile file, ZPOS64_T uncompressed_size, uLong crc32) +{ + zip64_internal* zi; + ZPOS64_T compressed_size; + uLong invalidValue = 0xffffffff; + short datasize = 0; + int err=ZIP_OK; + + if (file == NULL) + return ZIP_PARAMERROR; + zi = (zip64_internal*)file; + + if (zi->in_opened_file_inzip == 0) + return ZIP_PARAMERROR; + zi->ci.stream.avail_in = 0; + + if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) + { + while (err==ZIP_OK) + { + uLong uTotalOutBefore; + if (zi->ci.stream.avail_out == 0) + { + if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO) + err = ZIP_ERRNO; + zi->ci.stream.avail_out = (uInt)Z_BUFSIZE; + zi->ci.stream.next_out = zi->ci.buffered_data; + } + uTotalOutBefore = zi->ci.stream.total_out; + err=deflate(&zi->ci.stream, Z_FINISH); + zi->ci.pos_in_buffered_data += (uInt)(zi->ci.stream.total_out - uTotalOutBefore) ; + } + } + else if ((zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw)) + { +#ifdef HAVE_BZIP2 + err = BZ_FINISH_OK; + while (err==BZ_FINISH_OK) + { + uLong uTotalOutBefore; + if (zi->ci.bstream.avail_out == 0) + { + if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO) + err = ZIP_ERRNO; + zi->ci.bstream.avail_out = (uInt)Z_BUFSIZE; + zi->ci.bstream.next_out = (char*)zi->ci.buffered_data; + } + uTotalOutBefore = zi->ci.bstream.total_out_lo32; + err=BZ2_bzCompress(&zi->ci.bstream, BZ_FINISH); + if(err == BZ_STREAM_END) + err = Z_STREAM_END; + + zi->ci.pos_in_buffered_data += (uInt)(zi->ci.bstream.total_out_lo32 - uTotalOutBefore); + } + + if(err == BZ_FINISH_OK) + err = ZIP_OK; +#endif + } + + if (err==Z_STREAM_END) + err=ZIP_OK; /* this is normal */ + + if ((zi->ci.pos_in_buffered_data>0) && (err==ZIP_OK)) + { + if (zip64FlushWriteBuffer(zi)==ZIP_ERRNO) + err = ZIP_ERRNO; + } + + if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) + { + int tmp_err = deflateEnd(&zi->ci.stream); + if (err == ZIP_OK) + err = tmp_err; + zi->ci.stream_initialised = 0; + } +#ifdef HAVE_BZIP2 + else if((zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw)) + { + int tmperr = BZ2_bzCompressEnd(&zi->ci.bstream); + if (err==ZIP_OK) + err = tmperr; + zi->ci.stream_initialised = 0; + } +#endif + + if (!zi->ci.raw) + { + crc32 = (uLong)zi->ci.crc32; + uncompressed_size = zi->ci.totalUncompressedData; + } + compressed_size = zi->ci.totalCompressedData; + +# ifndef NOCRYPT + compressed_size += zi->ci.crypt_header_size; +# endif + + // update Current Item crc and sizes, + if(compressed_size >= 0xffffffff || uncompressed_size >= 0xffffffff || zi->ci.pos_local_header >= 0xffffffff) + { + /*version Made by*/ + zip64local_putValue_inmemory(zi->ci.central_header+4,(uLong)45,2); + /*version needed*/ + zip64local_putValue_inmemory(zi->ci.central_header+6,(uLong)45,2); + + } + + zip64local_putValue_inmemory(zi->ci.central_header+16,crc32,4); /*crc*/ + + + if(compressed_size >= 0xffffffff) + zip64local_putValue_inmemory(zi->ci.central_header+20, invalidValue,4); /*compr size*/ + else + zip64local_putValue_inmemory(zi->ci.central_header+20, compressed_size,4); /*compr size*/ + + /// set internal file attributes field + if (zi->ci.stream.data_type == Z_ASCII) + zip64local_putValue_inmemory(zi->ci.central_header+36,(uLong)Z_ASCII,2); + + if(uncompressed_size >= 0xffffffff) + zip64local_putValue_inmemory(zi->ci.central_header+24, invalidValue,4); /*uncompr size*/ + else + zip64local_putValue_inmemory(zi->ci.central_header+24, uncompressed_size,4); /*uncompr size*/ + + // Add ZIP64 extra info field for uncompressed size + if(uncompressed_size >= 0xffffffff) + datasize += 8; + + // Add ZIP64 extra info field for compressed size + if(compressed_size >= 0xffffffff) + datasize += 8; + + // Add ZIP64 extra info field for relative offset to local file header of current file + if(zi->ci.pos_local_header >= 0xffffffff) + datasize += 8; + + if(datasize > 0) + { + char* p = NULL; + + if((uLong)(datasize + 4) > zi->ci.size_centralExtraFree) + { + // we can not write more data to the buffer that we have room for. + return ZIP_BADZIPFILE; + } + + p = zi->ci.central_header + zi->ci.size_centralheader; + + // Add Extra Information Header for 'ZIP64 information' + zip64local_putValue_inmemory(p, 0x0001, 2); // HeaderID + p += 2; + zip64local_putValue_inmemory(p, datasize, 2); // DataSize + p += 2; + + if(uncompressed_size >= 0xffffffff) + { + zip64local_putValue_inmemory(p, uncompressed_size, 8); + p += 8; + } + + if(compressed_size >= 0xffffffff) + { + zip64local_putValue_inmemory(p, compressed_size, 8); + p += 8; + } + + if(zi->ci.pos_local_header >= 0xffffffff) + { + zip64local_putValue_inmemory(p, zi->ci.pos_local_header, 8); + p += 8; + } + + // Update how much extra free space we got in the memory buffer + // and increase the centralheader size so the new ZIP64 fields are included + // ( 4 below is the size of HeaderID and DataSize field ) + zi->ci.size_centralExtraFree -= datasize + 4; + zi->ci.size_centralheader += datasize + 4; + + // Update the extra info size field + zi->ci.size_centralExtra += datasize + 4; + zip64local_putValue_inmemory(zi->ci.central_header+30,(uLong)zi->ci.size_centralExtra,2); + } + + if (err==ZIP_OK) + err = add_data_in_datablock(&zi->central_dir, zi->ci.central_header, (uLong)zi->ci.size_centralheader); + + free(zi->ci.central_header); + + if (err==ZIP_OK) + { + // Update the LocalFileHeader with the new values. + + ZPOS64_T cur_pos_inzip = ZTELL64(zi->z_filefunc,zi->filestream); + + if (ZSEEK64(zi->z_filefunc,zi->filestream, zi->ci.pos_local_header + 14,ZLIB_FILEFUNC_SEEK_SET)!=0) + err = ZIP_ERRNO; + + if (err==ZIP_OK) + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,crc32,4); /* crc 32, unknown */ + + if(uncompressed_size >= 0xffffffff || compressed_size >= 0xffffffff ) + { + if(zi->ci.pos_zip64extrainfo > 0) + { + // Update the size in the ZIP64 extended field. + if (ZSEEK64(zi->z_filefunc,zi->filestream, zi->ci.pos_zip64extrainfo + 4,ZLIB_FILEFUNC_SEEK_SET)!=0) + err = ZIP_ERRNO; + + if (err==ZIP_OK) /* compressed size, unknown */ + err = zip64local_putValue(&zi->z_filefunc, zi->filestream, uncompressed_size, 8); + + if (err==ZIP_OK) /* uncompressed size, unknown */ + err = zip64local_putValue(&zi->z_filefunc, zi->filestream, compressed_size, 8); + } + else + err = ZIP_BADZIPFILE; // Caller passed zip64 = 0, so no room for zip64 info -> fatal + } + else + { + if (err==ZIP_OK) /* compressed size, unknown */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,compressed_size,4); + + if (err==ZIP_OK) /* uncompressed size, unknown */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,uncompressed_size,4); + } + + if (ZSEEK64(zi->z_filefunc,zi->filestream, cur_pos_inzip,ZLIB_FILEFUNC_SEEK_SET)!=0) + err = ZIP_ERRNO; + } + + zi->number_entry ++; + zi->in_opened_file_inzip = 0; + + return err; +} + +extern int ZEXPORT zipCloseFileInZip (zipFile file) +{ + return zipCloseFileInZipRaw (file,0,0); +} + +int Write_Zip64EndOfCentralDirectoryLocator(zip64_internal* zi, ZPOS64_T zip64eocd_pos_inzip) +{ + int err = ZIP_OK; + ZPOS64_T pos = zip64eocd_pos_inzip - zi->add_position_when_writing_offset; + + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)ZIP64ENDLOCHEADERMAGIC,4); + + /*num disks*/ + if (err==ZIP_OK) /* number of the disk with the start of the central directory */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); + + /*relative offset*/ + if (err==ZIP_OK) /* Relative offset to the Zip64EndOfCentralDirectory */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream, pos,8); + + /*total disks*/ /* Do not support spawning of disk so always say 1 here*/ + if (err==ZIP_OK) /* number of the disk with the start of the central directory */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)1,4); + + return err; +} + +int Write_Zip64EndOfCentralDirectoryRecord(zip64_internal* zi, uLong size_centraldir, ZPOS64_T centraldir_pos_inzip) +{ + int err = ZIP_OK; + + uLong Zip64DataSize = 44; + + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)ZIP64ENDHEADERMAGIC,4); + + if (err==ZIP_OK) /* size of this 'zip64 end of central directory' */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(ZPOS64_T)Zip64DataSize,8); // why ZPOS64_T of this ? + + if (err==ZIP_OK) /* version made by */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)45,2); + + if (err==ZIP_OK) /* version needed */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)45,2); + + if (err==ZIP_OK) /* number of this disk */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); + + if (err==ZIP_OK) /* number of the disk with the start of the central directory */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); + + if (err==ZIP_OK) /* total number of entries in the central dir on this disk */ + err = zip64local_putValue(&zi->z_filefunc, zi->filestream, zi->number_entry, 8); + + if (err==ZIP_OK) /* total number of entries in the central dir */ + err = zip64local_putValue(&zi->z_filefunc, zi->filestream, zi->number_entry, 8); + + if (err==ZIP_OK) /* size of the central directory */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(ZPOS64_T)size_centraldir,8); + + if (err==ZIP_OK) /* offset of start of central directory with respect to the starting disk number */ + { + ZPOS64_T pos = centraldir_pos_inzip - zi->add_position_when_writing_offset; + err = zip64local_putValue(&zi->z_filefunc,zi->filestream, (ZPOS64_T)pos,8); + } + return err; +} +int Write_EndOfCentralDirectoryRecord(zip64_internal* zi, uLong size_centraldir, ZPOS64_T centraldir_pos_inzip) +{ + int err = ZIP_OK; + + /*signature*/ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)ENDHEADERMAGIC,4); + + if (err==ZIP_OK) /* number of this disk */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,2); + + if (err==ZIP_OK) /* number of the disk with the start of the central directory */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,2); + + if (err==ZIP_OK) /* total number of entries in the central dir on this disk */ + { + { + if(zi->number_entry >= 0xFFFF) + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xffff,2); // use value in ZIP64 record + else + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->number_entry,2); + } + } + + if (err==ZIP_OK) /* total number of entries in the central dir */ + { + if(zi->number_entry >= 0xFFFF) + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xffff,2); // use value in ZIP64 record + else + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->number_entry,2); + } + + if (err==ZIP_OK) /* size of the central directory */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_centraldir,4); + + if (err==ZIP_OK) /* offset of start of central directory with respect to the starting disk number */ + { + ZPOS64_T pos = centraldir_pos_inzip - zi->add_position_when_writing_offset; + if(pos >= 0xffffffff) + { + err = zip64local_putValue(&zi->z_filefunc,zi->filestream, (uLong)0xffffffff,4); + } + else + err = zip64local_putValue(&zi->z_filefunc,zi->filestream, (uLong)(centraldir_pos_inzip - zi->add_position_when_writing_offset),4); + } + + return err; +} + +int Write_GlobalComment(zip64_internal* zi, const char* global_comment) +{ + int err = ZIP_OK; + uInt size_global_comment = 0; + + if(global_comment != NULL) + size_global_comment = (uInt)strlen(global_comment); + + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_global_comment,2); + + if (err == ZIP_OK && size_global_comment > 0) + { + if (ZWRITE64(zi->z_filefunc,zi->filestream, global_comment, size_global_comment) != size_global_comment) + err = ZIP_ERRNO; + } + return err; +} + +extern int ZEXPORT zipClose (zipFile file, const char* global_comment) +{ + zip64_internal* zi; + int err = 0; + uLong size_centraldir = 0; + ZPOS64_T centraldir_pos_inzip; + ZPOS64_T pos; + + if (file == NULL) + return ZIP_PARAMERROR; + + zi = (zip64_internal*)file; + + if (zi->in_opened_file_inzip == 1) + { + err = zipCloseFileInZip (file); + } + +#ifndef NO_ADDFILEINEXISTINGZIP + if (global_comment==NULL) + global_comment = zi->globalcomment; +#endif + + centraldir_pos_inzip = ZTELL64(zi->z_filefunc,zi->filestream); + + if (err==ZIP_OK) + { + linkedlist_datablock_internal* ldi = zi->central_dir.first_block; + while (ldi!=NULL) + { + if ((err==ZIP_OK) && (ldi->filled_in_this_block>0)) + { + if (ZWRITE64(zi->z_filefunc,zi->filestream, ldi->data, ldi->filled_in_this_block) != ldi->filled_in_this_block) + err = ZIP_ERRNO; + } + + size_centraldir += ldi->filled_in_this_block; + ldi = ldi->next_datablock; + } + } + free_linkedlist(&(zi->central_dir)); + + pos = centraldir_pos_inzip - zi->add_position_when_writing_offset; + if(pos >= 0xffffffff || zi->number_entry > 0xFFFF) + { + ZPOS64_T Zip64EOCDpos = ZTELL64(zi->z_filefunc,zi->filestream); + Write_Zip64EndOfCentralDirectoryRecord(zi, size_centraldir, centraldir_pos_inzip); + + Write_Zip64EndOfCentralDirectoryLocator(zi, Zip64EOCDpos); + } + + if (err==ZIP_OK) + err = Write_EndOfCentralDirectoryRecord(zi, size_centraldir, centraldir_pos_inzip); + + if(err == ZIP_OK) + err = Write_GlobalComment(zi, global_comment); + + if (ZCLOSE64(zi->z_filefunc,zi->filestream) != 0) + if (err == ZIP_OK) + err = ZIP_ERRNO; + +#ifndef NO_ADDFILEINEXISTINGZIP + TRYFREE(zi->globalcomment); +#endif + TRYFREE(zi); + + return err; +} + +extern int ZEXPORT zipRemoveExtraInfoBlock (char* pData, int* dataLen, short sHeader) +{ + char* p = pData; + int size = 0; + char* pNewHeader; + char* pTmp; + short header; + short dataSize; + + int retVal = ZIP_OK; + + if(pData == NULL || *dataLen < 4) + return ZIP_PARAMERROR; + + pNewHeader = (char*)ALLOC(*dataLen); + pTmp = pNewHeader; + + while(p < (pData + *dataLen)) + { + header = *(short*)p; + dataSize = *(((short*)p)+1); + + if( header == sHeader ) // Header found. + { + p += dataSize + 4; // skip it. do not copy to temp buffer + } + else + { + // Extra Info block should not be removed, So copy it to the temp buffer. + memcpy(pTmp, p, dataSize + 4); + p += dataSize + 4; + size += dataSize + 4; + } + + } + + if(size < *dataLen) + { + // clean old extra info block. + memset(pData,0, *dataLen); + + // copy the new extra info block over the old + if(size > 0) + memcpy(pData, pNewHeader, size); + + // set the new extra info size + *dataLen = size; + + retVal = ZIP_OK; + } + else + retVal = ZIP_ERRNO; + + TRYFREE(pNewHeader); + + return retVal; +} diff --git a/DSView/pv/minizip/zip.h b/DSView/pv/minizip/zip.h new file mode 100644 index 00000000..8aaebb62 --- /dev/null +++ b/DSView/pv/minizip/zip.h @@ -0,0 +1,362 @@ +/* zip.h -- IO on .zip files using zlib + Version 1.1, February 14h, 2010 + part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications for Zip64 support + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) + + For more info read MiniZip_info.txt + + --------------------------------------------------------------------------- + + Condition of use and distribution are the same than zlib : + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + --------------------------------------------------------------------------- + + Changes + + See header of zip.h + +*/ + +#ifndef _zip12_H +#define _zip12_H + +#ifdef __cplusplus +extern "C" { +#endif + +//#define HAVE_BZIP2 + +#ifndef _ZLIB_H +#include "zlib.h" +#endif + +#ifndef _ZLIBIOAPI_H +#include "ioapi.h" +#endif + +#ifdef HAVE_BZIP2 +#include "bzlib.h" +#endif + +#define Z_BZIP2ED 12 + +#if defined(STRICTZIP) || defined(STRICTZIPUNZIP) +/* like the STRICT of WIN32, we define a pointer that cannot be converted + from (void*) without cast */ +typedef struct TagzipFile__ { int unused; } zipFile__; +typedef zipFile__ *zipFile; +#else +typedef voidp zipFile; +#endif + +#define ZIP_OK (0) +#define ZIP_EOF (0) +#define ZIP_ERRNO (Z_ERRNO) +#define ZIP_PARAMERROR (-102) +#define ZIP_BADZIPFILE (-103) +#define ZIP_INTERNALERROR (-104) + +#ifndef DEF_MEM_LEVEL +# if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +# else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +# endif +#endif +/* default memLevel */ + +/* tm_zip contain date/time info */ +typedef struct tm_zip_s +{ + uInt tm_sec; /* seconds after the minute - [0,59] */ + uInt tm_min; /* minutes after the hour - [0,59] */ + uInt tm_hour; /* hours since midnight - [0,23] */ + uInt tm_mday; /* day of the month - [1,31] */ + uInt tm_mon; /* months since January - [0,11] */ + uInt tm_year; /* years - [1980..2044] */ +} tm_zip; + +typedef struct +{ + tm_zip tmz_date; /* date in understandable format */ + uLong dosDate; /* if dos_date == 0, tmu_date is used */ +/* uLong flag; */ /* general purpose bit flag 2 bytes */ + + uLong internal_fa; /* internal file attributes 2 bytes */ + uLong external_fa; /* external file attributes 4 bytes */ +} zip_fileinfo; + +typedef const char* zipcharpc; + + +#define APPEND_STATUS_CREATE (0) +#define APPEND_STATUS_CREATEAFTER (1) +#define APPEND_STATUS_ADDINZIP (2) + +extern zipFile ZEXPORT zipOpen OF((const char *pathname, int append)); +extern zipFile ZEXPORT zipOpen64 OF((const void *pathname, int append)); +/* + Create a zipfile. + pathname contain on Windows XP a filename like "c:\\zlib\\zlib113.zip" or on + an Unix computer "zlib/zlib113.zip". + if the file pathname exist and append==APPEND_STATUS_CREATEAFTER, the zip + will be created at the end of the file. + (useful if the file contain a self extractor code) + if the file pathname exist and append==APPEND_STATUS_ADDINZIP, we will + add files in existing zip (be sure you don't add file that doesn't exist) + If the zipfile cannot be opened, the return value is NULL. + Else, the return value is a zipFile Handle, usable with other function + of this zip package. +*/ + +/* Note : there is no delete function into a zipfile. + If you want delete file into a zipfile, you must open a zipfile, and create another + Of couse, you can use RAW reading and writing to copy the file you did not want delte +*/ + +extern zipFile ZEXPORT zipOpen2 OF((const char *pathname, + int append, + zipcharpc* globalcomment, + zlib_filefunc_def* pzlib_filefunc_def)); + +extern zipFile ZEXPORT zipOpen2_64 OF((const void *pathname, + int append, + zipcharpc* globalcomment, + zlib_filefunc64_def* pzlib_filefunc_def)); + +extern int ZEXPORT zipOpenNewFileInZip OF((zipFile file, + const char* filename, + const zip_fileinfo* zipfi, + const void* extrafield_local, + uInt size_extrafield_local, + const void* extrafield_global, + uInt size_extrafield_global, + const char* comment, + int method, + int level)); + +extern int ZEXPORT zipOpenNewFileInZip64 OF((zipFile file, + const char* filename, + const zip_fileinfo* zipfi, + const void* extrafield_local, + uInt size_extrafield_local, + const void* extrafield_global, + uInt size_extrafield_global, + const char* comment, + int method, + int level, + int zip64)); + +/* + Open a file in the ZIP for writing. + filename : the filename in zip (if NULL, '-' without quote will be used + *zipfi contain supplemental information + if extrafield_local!=NULL and size_extrafield_local>0, extrafield_local + contains the extrafield data the the local header + if extrafield_global!=NULL and size_extrafield_global>0, extrafield_global + contains the extrafield data the the local header + if comment != NULL, comment contain the comment string + method contain the compression method (0 for store, Z_DEFLATED for deflate) + level contain the level of compression (can be Z_DEFAULT_COMPRESSION) + zip64 is set to 1 if a zip64 extended information block should be added to the local file header. + this MUST be '1' if the uncompressed size is >= 0xffffffff. + +*/ + + +extern int ZEXPORT zipOpenNewFileInZip2 OF((zipFile file, + const char* filename, + const zip_fileinfo* zipfi, + const void* extrafield_local, + uInt size_extrafield_local, + const void* extrafield_global, + uInt size_extrafield_global, + const char* comment, + int method, + int level, + int raw)); + + +extern int ZEXPORT zipOpenNewFileInZip2_64 OF((zipFile file, + const char* filename, + const zip_fileinfo* zipfi, + const void* extrafield_local, + uInt size_extrafield_local, + const void* extrafield_global, + uInt size_extrafield_global, + const char* comment, + int method, + int level, + int raw, + int zip64)); +/* + Same than zipOpenNewFileInZip, except if raw=1, we write raw file + */ + +extern int ZEXPORT zipOpenNewFileInZip3 OF((zipFile file, + const char* filename, + const zip_fileinfo* zipfi, + const void* extrafield_local, + uInt size_extrafield_local, + const void* extrafield_global, + uInt size_extrafield_global, + const char* comment, + int method, + int level, + int raw, + int windowBits, + int memLevel, + int strategy, + const char* password, + uLong crcForCrypting)); + +extern int ZEXPORT zipOpenNewFileInZip3_64 OF((zipFile file, + const char* filename, + const zip_fileinfo* zipfi, + const void* extrafield_local, + uInt size_extrafield_local, + const void* extrafield_global, + uInt size_extrafield_global, + const char* comment, + int method, + int level, + int raw, + int windowBits, + int memLevel, + int strategy, + const char* password, + uLong crcForCrypting, + int zip64 + )); + +/* + Same than zipOpenNewFileInZip2, except + windowBits,memLevel,,strategy : see parameter strategy in deflateInit2 + password : crypting password (NULL for no crypting) + crcForCrypting : crc of file to compress (needed for crypting) + */ + +extern int ZEXPORT zipOpenNewFileInZip4 OF((zipFile file, + const char* filename, + const zip_fileinfo* zipfi, + const void* extrafield_local, + uInt size_extrafield_local, + const void* extrafield_global, + uInt size_extrafield_global, + const char* comment, + int method, + int level, + int raw, + int windowBits, + int memLevel, + int strategy, + const char* password, + uLong crcForCrypting, + uLong versionMadeBy, + uLong flagBase + )); + + +extern int ZEXPORT zipOpenNewFileInZip4_64 OF((zipFile file, + const char* filename, + const zip_fileinfo* zipfi, + const void* extrafield_local, + uInt size_extrafield_local, + const void* extrafield_global, + uInt size_extrafield_global, + const char* comment, + int method, + int level, + int raw, + int windowBits, + int memLevel, + int strategy, + const char* password, + uLong crcForCrypting, + uLong versionMadeBy, + uLong flagBase, + int zip64 + )); +/* + Same than zipOpenNewFileInZip4, except + versionMadeBy : value for Version made by field + flag : value for flag field (compression level info will be added) + */ + + +extern int ZEXPORT zipWriteInFileInZip OF((zipFile file, + const void* buf, + unsigned len)); +/* + Write data in the zipfile +*/ + +extern int ZEXPORT zipCloseFileInZip OF((zipFile file)); +/* + Close the current file in the zipfile +*/ + +extern int ZEXPORT zipCloseFileInZipRaw OF((zipFile file, + uLong uncompressed_size, + uLong crc32)); + +extern int ZEXPORT zipCloseFileInZipRaw64 OF((zipFile file, + ZPOS64_T uncompressed_size, + uLong crc32)); + +/* + Close the current file in the zipfile, for file opened with + parameter raw=1 in zipOpenNewFileInZip2 + uncompressed_size and crc32 are value for the uncompressed size +*/ + +extern int ZEXPORT zipClose OF((zipFile file, + const char* global_comment)); +/* + Close the zipfile +*/ + + +extern int ZEXPORT zipRemoveExtraInfoBlock OF((char* pData, int* dataLen, short sHeader)); +/* + zipRemoveExtraInfoBlock - Added by Mathias Svensson + + Remove extra information block from a extra information data for the local file header or central directory header + + It is needed to remove ZIP64 extra information blocks when before data is written if using RAW mode. + + 0x0001 is the signature header for the ZIP64 extra information blocks + + usage. + Remove ZIP64 Extra information from a central director extra field data + zipRemoveExtraInfoBlock(pCenDirExtraFieldData, &nCenDirExtraFieldDataLen, 0x0001); + + Remove ZIP64 Extra information from a Local File Header extra field data + zipRemoveExtraInfoBlock(pLocalHeaderExtraFieldData, &nLocalHeaderExtraFieldDataLen, 0x0001); +*/ + +#ifdef __cplusplus +} +#endif + +#endif /* _zip64_H */ diff --git a/DSView/pv/prop/binding/binding.cpp b/DSView/pv/prop/binding/binding.cpp index c5252716..4d861370 100755 --- a/DSView/pv/prop/binding/binding.cpp +++ b/DSView/pv/prop/binding/binding.cpp @@ -19,54 +19,57 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#include + #include -#include - +#include "../property.h" #include "binding.h" - -using boost::shared_ptr; + namespace pv { namespace prop { namespace binding { -const std::vector< boost::shared_ptr >& Binding::properties() +const std::vector& Binding::properties() { return _properties; } void Binding::commit() { - BOOST_FOREACH(shared_ptr p, _properties) { + for(auto &p : _properties) { assert(p); p->commit(); } } void Binding::add_properties_to_form(QFormLayout *layout, - bool auto_commit) const + bool auto_commit) { assert(layout); - BOOST_FOREACH(shared_ptr p, _properties) + for(auto &p : _properties) { assert(p); - QWidget *const widget = p->get_widget(layout->parentWidget(), - auto_commit); + QWidget *const widget = p->get_widget(layout->parentWidget(), auto_commit); + if (p->labeled_widget()) layout->addRow(widget); - else - layout->addRow(p->label(), widget); + else{ + const QString &lbstr = p->label(); + //remove data format options + if (lbstr == "Data format"){ + continue; + } + layout->addRow(p->label(), widget); + } } } QWidget* Binding::get_property_form(QWidget *parent, - bool auto_commit) const + bool auto_commit) { QWidget *const form = new QWidget(parent); QFormLayout *const layout = new QFormLayout(form); @@ -79,12 +82,11 @@ QWidget* Binding::get_property_form(QWidget *parent, return form; } -std::map< boost::shared_ptr, - GVariant* > Binding::get_property_value() const +std::map Binding::get_property_value() { - std::map < boost::shared_ptr, - GVariant* > pvalue; - BOOST_FOREACH(shared_ptr p, _properties) + std::map pvalue; + + for(auto &p : _properties) { assert(p); pvalue[p] = p->get_value(); diff --git a/DSView/pv/prop/binding/binding.h b/DSView/pv/prop/binding/binding.h index 8b413e05..68bae0d7 100755 --- a/DSView/pv/prop/binding/binding.h +++ b/DSView/pv/prop/binding/binding.h @@ -27,8 +27,7 @@ #include #include -#include -#include +#include #include @@ -45,23 +44,22 @@ namespace binding { class Binding { public: - const std::vector< boost::shared_ptr >& properties(); + const std::vector& properties(); void commit(); void add_properties_to_form(QFormLayout *layout, - bool auto_commit = false) const; + bool auto_commit = false); QWidget* get_property_form(QWidget *parent, - bool auto_commit = false) const; + bool auto_commit = false); - std::map< boost::shared_ptr, - GVariant* > get_property_value() const; + std::map get_property_value(); static QString print_gvariant(GVariant *const gvar); protected: - std::vector< boost::shared_ptr > _properties; + std::vector _properties; QWidget *_form; }; diff --git a/DSView/pv/prop/binding/decoderoptions.cpp b/DSView/pv/prop/binding/decoderoptions.cpp index 644db938..b1ecae3b 100755 --- a/DSView/pv/prop/binding/decoderoptions.cpp +++ b/DSView/pv/prop/binding/decoderoptions.cpp @@ -23,32 +23,26 @@ #include "decoderoptions.h" #include -#include + #include -#include -#include -#include -#include -#include -#include - -using boost::bind; -using boost::none; -using boost::shared_ptr; -using std::make_pair; -using std::map; -using std::pair; -using std::string; -using std::vector; +#include "../../data/decoderstack.h" +#include "../../data/decode/decoder.h" +#include "../double.h" +#include "../enum.h" +#include "../int.h" +#include "../string.h" +using namespace boost; +using namespace std; + namespace pv { namespace prop { namespace binding { DecoderOptions::DecoderOptions( - shared_ptr decoder_stack, - shared_ptr decoder) : + pv::data::DecoderStack* decoder_stack, + data::decode::Decoder *decoder) : _decoder_stack(decoder_stack), _decoder(decoder) { @@ -69,19 +63,16 @@ DecoderOptions::DecoderOptions( const Property::Setter setter = bind( &DecoderOptions::setter, this, opt->id, _1); - shared_ptr prop; + Property *prop = NULL; if (opt->values) prop = bind_enum(name, opt, getter, setter); else if (g_variant_is_of_type(opt->def, G_VARIANT_TYPE("d"))) - prop = shared_ptr(new Double(name, name, 2, "", - none, none, getter, setter)); + prop = new Double(name, name, 2, "",none, none, getter, setter); else if (g_variant_is_of_type(opt->def, G_VARIANT_TYPE("x"))) - prop = shared_ptr( - new Int(name, name, "", none, getter, setter)); + prop = new Int(name, name, "", none, getter, setter); else if (g_variant_is_of_type(opt->def, G_VARIANT_TYPE("s"))) - prop = shared_ptr( - new String(name, name, getter, setter)); + prop = new String(name, name, getter, setter); else continue; @@ -89,18 +80,18 @@ DecoderOptions::DecoderOptions( } } -shared_ptr DecoderOptions::bind_enum( +Property* DecoderOptions::bind_enum( const QString &name, const srd_decoder_option *option, Property::Getter getter, Property::Setter setter) { - vector< pair > values; + std::vector > values; for (GSList *l = option->values; l; l = l->next) { GVariant *const var = (GVariant*)l->data; assert(var); values.push_back(make_pair(var, print_gvariant(var))); } - return shared_ptr(new Enum(name, name, values, getter, setter)); + return new Enum(name, name, values, getter, setter); } GVariant* DecoderOptions::getter(const char *id) @@ -111,7 +102,7 @@ GVariant* DecoderOptions::getter(const char *id) // Get the value from the hash table if it is already present const map& options = _decoder->options(); - map::const_iterator iter = options.find(id); + auto iter = options.find(id); if (iter != options.end()) val = (*iter).second; diff --git a/DSView/pv/prop/binding/decoderoptions.h b/DSView/pv/prop/binding/decoderoptions.h index 62d91ec3..258c3a62 100755 --- a/DSView/pv/prop/binding/decoderoptions.h +++ b/DSView/pv/prop/binding/decoderoptions.h @@ -23,7 +23,7 @@ #include "binding.h" -#include +#include "../property.h" struct srd_decoder_option; @@ -42,23 +42,23 @@ namespace binding { class DecoderOptions : public Binding { public: - DecoderOptions(boost::shared_ptr decoder_stack, - boost::shared_ptr decoder); + DecoderOptions(pv::data::DecoderStack *decoder_stack, + pv::data::decode::Decoder* decoder); GVariant* getter(const char *id); void setter(const char *id, GVariant *value); private: - static boost::shared_ptr bind_enum(const QString &name, + static Property* bind_enum(const QString &name, const srd_decoder_option *option, Property::Getter getter, Property::Setter setter); private: - boost::shared_ptr _decoder_stack; - boost::shared_ptr _decoder; + pv::data::DecoderStack *_decoder_stack; + pv::data::decode::Decoder *_decoder; }; } // binding diff --git a/DSView/pv/prop/binding/deviceoptions.cpp b/DSView/pv/prop/binding/deviceoptions.cpp index deef3fac..66a9900f 100755 --- a/DSView/pv/prop/binding/deviceoptions.cpp +++ b/DSView/pv/prop/binding/deviceoptions.cpp @@ -20,19 +20,18 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#include - -#include -#include - -#include - #include "deviceoptions.h" -#include -#include -#include -#include +#include +#include +#include +#include + +#include "../bool.h" +#include "../double.h" +#include "../enum.h" +#include "../int.h" +#include "../../config/appconfig.h" using namespace boost; using namespace std; @@ -72,7 +71,7 @@ DeviceOptions::DeviceOptions(struct sr_dev_inst *sdi) : if (sr_config_get(_sdi->driver, _sdi, NULL, NULL, SR_CONF_LANGUAGE, &gvar_tmp) == SR_OK) { if (gvar_tmp != NULL) { int language = g_variant_get_int16(gvar_tmp); - if (language == QLocale::Chinese) + if (language == LAN_CN) label_char = info->label_cn; g_variant_unref(gvar_tmp); } @@ -166,9 +165,9 @@ void DeviceOptions::config_setter( void DeviceOptions::bind_bool(const QString &name, const QString label, int key) { - _properties.push_back(boost::shared_ptr( + _properties.push_back( new Bool(name, label, bind(config_getter, _sdi, key), - bind(config_setter, _sdi, key, _1)))); + bind(config_setter, _sdi, key, _1))); } void DeviceOptions::bind_enum(const QString &name, const QString label, int key, @@ -176,7 +175,7 @@ void DeviceOptions::bind_enum(const QString &name, const QString label, int key, { GVariant *gvar; GVariantIter iter; - vector< pair > values; + std::vector< pair > values; assert(gvar_list); @@ -184,29 +183,29 @@ void DeviceOptions::bind_enum(const QString &name, const QString label, int key, while ((gvar = g_variant_iter_next_value (&iter))) values.push_back(make_pair(gvar, printer(gvar))); - _properties.push_back(boost::shared_ptr( + _properties.push_back( new Enum(name, label, values, bind(config_getter, _sdi, key), - bind(config_setter, _sdi, key, _1)))); + bind(config_setter, _sdi, key, _1))); } void DeviceOptions::bind_int(const QString &name, const QString label, int key, QString suffix, - optional< std::pair > range) + boost::optional< std::pair > range) { - _properties.push_back(boost::shared_ptr( + _properties.push_back( new Int(name, label, suffix, range, bind(config_getter, _sdi, key), - bind(config_setter, _sdi, key, _1)))); + bind(config_setter, _sdi, key, _1))); } void DeviceOptions::bind_double(const QString &name, const QString label, int key, QString suffix, - optional< std::pair > range, + boost::optional< std::pair > range, int decimals, boost::optional step) { - _properties.push_back(boost::shared_ptr( + _properties.push_back( new Double(name, label, decimals, suffix, range, step, bind(config_getter, _sdi, key), - bind(config_setter, _sdi, key, _1)))); + bind(config_setter, _sdi, key, _1))); } QString DeviceOptions::print_gvariant(GVariant *const gvar) @@ -242,12 +241,12 @@ void DeviceOptions::bind_samplerate(const QString &name, const QString label, assert(num_elements == 3); - _properties.push_back(boost::shared_ptr( + _properties.push_back( new Double(name, label, 0, QObject::tr("Hz"), make_pair((double)elements[0], (double)elements[1]), (double)elements[2], bind(samplerate_double_getter, _sdi), - bind(samplerate_double_setter, _sdi, _1)))); + bind(samplerate_double_setter, _sdi, _1))); g_variant_unref(gvar_list_samplerates); } @@ -312,7 +311,7 @@ void DeviceOptions::bind_bandwidths(const QString &name, const QString label, in { GVariant *gvar; GVariantIter iter; - vector< pair > values; + std::vector< pair > values; bool bw_limit = FALSE; assert(gvar_list); @@ -332,10 +331,10 @@ void DeviceOptions::bind_bandwidths(const QString &name, const QString label, in while ((gvar = g_variant_iter_next_value (&iter))) values.push_back(make_pair(gvar, printer(gvar))); - _properties.push_back(boost::shared_ptr( + _properties.push_back( new Enum(name, label, values, bind(config_getter, _sdi, key), - bind(config_setter, _sdi, key, _1)))); + bind(config_setter, _sdi, key, _1))); } } // binding diff --git a/DSView/pv/prop/binding/probeoptions.cpp b/DSView/pv/prop/binding/probeoptions.cpp index 3b6a101f..74b18088 100755 --- a/DSView/pv/prop/binding/probeoptions.cpp +++ b/DSView/pv/prop/binding/probeoptions.cpp @@ -19,19 +19,19 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ +#include "probeoptions.h" + #include #include #include - #include +#include "../bool.h" +#include "../double.h" +#include "../enum.h" +#include "../int.h" -#include "probeoptions.h" - -#include -#include -#include -#include +#include "../../config/appconfig.h" using namespace boost; using namespace std; @@ -73,7 +73,7 @@ ProbeOptions::ProbeOptions(struct sr_dev_inst *sdi, if (sr_config_get(_sdi->driver, _sdi, NULL, NULL, SR_CONF_LANGUAGE, &gvar_tmp) == SR_OK) { if (gvar_tmp != NULL) { int language = g_variant_get_int16(gvar_tmp); - if (language == QLocale::Chinese) + if (language == LAN_CN) label_char = info->label_cn; g_variant_unref(gvar_tmp); } @@ -138,9 +138,9 @@ void ProbeOptions::config_setter( void ProbeOptions::bind_bool(const QString &name, const QString label, int key) { - _properties.push_back(boost::shared_ptr( + _properties.push_back( new Bool(name, label, bind(config_getter, _sdi, _probe, key), - bind(config_setter, _sdi, _probe, key, _1)))); + bind(config_setter, _sdi, _probe, key, _1))); } void ProbeOptions::bind_enum(const QString &name, const QString label, int key, @@ -148,7 +148,7 @@ void ProbeOptions::bind_enum(const QString &name, const QString label, int key, { GVariant *gvar; GVariantIter iter; - vector< pair > values; + std::vector< pair > values; assert(gvar_list); @@ -156,29 +156,29 @@ void ProbeOptions::bind_enum(const QString &name, const QString label, int key, while ((gvar = g_variant_iter_next_value (&iter))) values.push_back(make_pair(gvar, printer(gvar))); - _properties.push_back(boost::shared_ptr( + _properties.push_back( new Enum(name, label, values, bind(config_getter, _sdi, _probe, key), - bind(config_setter, _sdi, _probe, key, _1)))); + bind(config_setter, _sdi, _probe, key, _1))); } void ProbeOptions::bind_int(const QString &name, const QString label, int key, QString suffix, - optional< std::pair > range) + boost::optional< std::pair > range) { - _properties.push_back(boost::shared_ptr( + _properties.push_back( new Int(name, label, suffix, range, bind(config_getter, _sdi, _probe, key), - bind(config_setter, _sdi, _probe, key, _1)))); + bind(config_setter, _sdi, _probe, key, _1))); } void ProbeOptions::bind_double(const QString &name, const QString label, int key, QString suffix, - optional< std::pair > range, + boost::optional< std::pair > range, int decimals, boost::optional step) { - _properties.push_back(boost::shared_ptr( + _properties.push_back( new Double(name, label, decimals, suffix, range, step, bind(config_getter, _sdi, _probe, key), - bind(config_setter, _sdi, _probe, key, _1)))); + bind(config_setter, _sdi, _probe, key, _1))); } void ProbeOptions::bind_vdiv(const QString &name, const QString label, diff --git a/DSView/pv/prop/bool.cpp b/DSView/pv/prop/bool.cpp index 75169b86..b31369c2 100755 --- a/DSView/pv/prop/bool.cpp +++ b/DSView/pv/prop/bool.cpp @@ -65,12 +65,12 @@ QWidget* Bool::get_widget(QWidget *parent, bool auto_commit) return _check_box; } -bool Bool::labeled_widget() const +bool Bool::labeled_widget() { return true; } -GVariant* Bool::get_value() const +GVariant* Bool::get_value() { GVariant *const value = _getter ? _getter() : NULL; diff --git a/DSView/pv/prop/bool.h b/DSView/pv/prop/bool.h index c9f9e409..5603914c 100755 --- a/DSView/pv/prop/bool.h +++ b/DSView/pv/prop/bool.h @@ -40,9 +40,9 @@ public: virtual ~Bool(); QWidget* get_widget(QWidget *parent, bool auto_commit); - bool labeled_widget() const; + bool labeled_widget(); - GVariant* get_value() const; + GVariant* get_value(); void commit(); diff --git a/DSView/pv/prop/double.cpp b/DSView/pv/prop/double.cpp index 2c832d9a..b5c7c3d7 100755 --- a/DSView/pv/prop/double.cpp +++ b/DSView/pv/prop/double.cpp @@ -35,8 +35,8 @@ namespace prop { Double::Double(QString name, QString label, int decimals, QString suffix, - optional< pair > range, - optional step, + boost::optional< pair > range, + boost::optional step, Getter getter, Setter setter) : Property(name, label, getter, setter), diff --git a/DSView/pv/prop/enum.cpp b/DSView/pv/prop/enum.cpp index 9f5aadca..e70f1925 100755 --- a/DSView/pv/prop/enum.cpp +++ b/DSView/pv/prop/enum.cpp @@ -22,10 +22,10 @@ #include -#include #include #include "enum.h" +#include "../ui/dscombobox.h" using namespace boost; using namespace std; @@ -34,13 +34,13 @@ namespace pv { namespace prop { Enum::Enum(QString name, QString label, - vector > values, + std::vector > values, Getter getter, Setter setter) : Property(name, label, getter, setter), _values(values), _selector(NULL) { - for (vector< pair >::const_iterator i = + for (std::vector< pair >::const_iterator i = _values.begin(); i != _values.end(); i++) g_variant_ref((*i).first); } @@ -62,7 +62,7 @@ QWidget* Enum::get_widget(QWidget *parent, bool auto_commit) return NULL; } - _selector = new QComboBox(parent); + _selector = new DsComboBox(parent); for (unsigned int i = 0; i < _values.size(); i++) { const pair &v = _values[i]; _selector->addItem(v.second, QVariant::fromValue((void*)v.first)); diff --git a/DSView/pv/prop/enum.h b/DSView/pv/prop/enum.h index 6b1214cd..41606271 100755 --- a/DSView/pv/prop/enum.h +++ b/DSView/pv/prop/enum.h @@ -28,7 +28,7 @@ #include "property.h" -class QComboBox; +class DsComboBox; namespace pv { namespace prop { @@ -53,7 +53,7 @@ private slots: private: const std::vector< std::pair > _values; - QComboBox *_selector; + DsComboBox *_selector; }; } // prop diff --git a/DSView/pv/prop/int.cpp b/DSView/pv/prop/int.cpp index ac7961ee..3648193d 100755 --- a/DSView/pv/prop/int.cpp +++ b/DSView/pv/prop/int.cpp @@ -51,7 +51,7 @@ namespace prop { Int::Int(QString name, QString label, QString suffix, - optional< pair > range, + boost::optional< pair > range, Getter getter, Setter setter) : Property(name, label, getter, setter), diff --git a/DSView/pv/prop/property.cpp b/DSView/pv/prop/property.cpp index de7150b5..7933398f 100755 --- a/DSView/pv/prop/property.cpp +++ b/DSView/pv/prop/property.cpp @@ -33,22 +33,26 @@ Property::Property(QString name, QString label, Getter getter, Setter setter) : { } -const QString& Property::name() const +Property::~Property(){ + +} + +const QString& Property::name() { return _name; } -const QString& Property::label() const +const QString& Property::label() { return _label; } -bool Property::labeled_widget() const +bool Property::labeled_widget() { return false; } -GVariant* Property::get_value() const +GVariant* Property::get_value() { return NULL; } diff --git a/DSView/pv/prop/property.h b/DSView/pv/prop/property.h index 2868eedb..5ba344be 100755 --- a/DSView/pv/prop/property.h +++ b/DSView/pv/prop/property.h @@ -47,14 +47,16 @@ protected: Property(QString name, QString label, Getter getter, Setter setter); public: - const QString& name() const; - const QString& label() const; + const QString& name(); + const QString& label(); + + virtual ~Property(); virtual QWidget* get_widget(QWidget *parent, bool auto_commit = false) = 0; - virtual bool labeled_widget() const; + virtual bool labeled_widget(); - virtual GVariant* get_value() const; + virtual GVariant* get_value(); virtual void commit() = 0; diff --git a/DSView/pv/sigsession.cpp b/DSView/pv/sigsession.cpp index f55f1058..1eff15f9 100755 --- a/DSView/pv/sigsession.cpp +++ b/DSView/pv/sigsession.cpp @@ -20,9 +20,9 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#ifdef ENABLE_DECODE + #include -#endif + #include "sigsession.h" #include "mainwindow.h" @@ -55,113 +55,95 @@ #include #include -#include - +#include #include -#include -#include -#include -#include -#include -#include - -#include - -//using boost::dynamic_pointer_cast; -//using boost::function; -//using boost::lock_guard; -//using boost::mutex; -//using boost::shared_ptr; -//using std::list; -//using std::map; -//using std::set; -//using std::string; -//using std::vector; -//using std::deque; -//using std::min; - -using namespace boost; -using namespace std; - +#include + +#include "data/decode/decoderstatus.h" +#include "dsvdef.h" + namespace pv { // TODO: This should not be necessary SigSession* SigSession::_session = NULL; -SigSession::SigSession(DeviceManager &device_manager) : - _device_manager(device_manager), - _capture_state(Init), - _instant(false), - _error(No_err), - _run_mode(Single), - _repeat_intvl(1), - _repeating(false), - _repeat_hold_prg(0), - _map_zoom(0) +SigSession::SigSession(DeviceManager *device_manager) { - // TODO: This should not be necessary - _session = this; + _hotplug_handle = 0; + _dev_inst = NULL; + _device_manager = device_manager; + // TODO: This should not be necessary + _session = this; _hot_attach = false; _hot_detach = false; _group_cnt = 0; - register_hotplug_callback(); - _feed_timer.stop(); + _bHotplugStop = false; + + _map_zoom = 0; + _repeat_hold_prg = 0; + _repeating = false; + _repeat_intvl = 1; + _run_mode = Single; + _error = No_err; + _instant = false; + _capture_state = Init; + _noData_cnt = 0; _data_lock = false; _data_updated = false; - #ifdef ENABLE_DECODE - _decoder_model = new pv::data::DecoderModel(this); - #endif + + _decoder_model = new pv::data::DecoderModel(NULL); + _lissajous_trace = NULL; _math_trace = NULL; _saving = false; _dso_feed = false; - _stop_scale = 1; + _stop_scale = 1; + _bDecodeRunning = false; + _bClose = false; + _callback = NULL; - // Create snapshots & data containers - _cur_logic_snapshot.reset(new data::LogicSnapshot()); - _logic_data.reset(new data::Logic()); - _logic_data->push_snapshot(_cur_logic_snapshot); - _cur_dso_snapshot.reset(new data::DsoSnapshot()); - _dso_data.reset(new data::Dso()); - _dso_data->push_snapshot(_cur_dso_snapshot); - _cur_analog_snapshot.reset(new data::AnalogSnapshot()); - _analog_data.reset(new data::Analog()); - _analog_data->push_snapshot(_cur_analog_snapshot); - _group_data.reset(new data::Group()); + // Create snapshots & data containers + _logic_data = new data::Logic(new data::LogicSnapshot()); + _dso_data = new data::Dso(new data::DsoSnapshot()); + _analog_data = new data::Analog(new data::AnalogSnapshot()); + _group_data = new data::Group(); _group_cnt = 0; - connect(&_feed_timer, SIGNAL(timeout()), this, SLOT(feed_timeout())); + _feed_timer.Stop(); + _feed_timer.SetCallback(std::bind(&SigSession::feed_timeout, this)); } +SigSession::SigSession(SigSession &o){(void)o;} + SigSession::~SigSession() -{ - stop_capture(); - - ds_trigger_destroy(); - - _dev_inst->release(); - - // TODO: This should not be necessary - _session = NULL; - - if (_hotplug_handle) { - stop_hotplug_proc(); - deregister_hotplug_callback(); - } +{ } -boost::shared_ptr SigSession::get_device() const +DevInst* SigSession::get_device() { return _dev_inst; } -void SigSession::set_device(boost::shared_ptr dev_inst) -{ - using pv::device::Device; +void SigSession::deselect_device() +{ + RELEASE_ARRAY(_decode_traces); + RELEASE_ARRAY(_group_traces); + _dev_inst = NULL; +} +/* + when be called, it will call 4DSL lib sr_session_new, and create a session struct in the lib +*/ +void SigSession::set_device(DevInst *dev_inst) +{ // Ensure we are not capturing before setting the device - //stop_capture(); + + assert(dev_inst); + + if (_dev_inst){ + _dev_inst->dev_inst(); + } if (_dev_inst) { sr_session_datafeed_callback_remove_all(); @@ -169,10 +151,9 @@ void SigSession::set_device(boost::shared_ptr dev_inst) } _dev_inst = dev_inst; -#ifdef ENABLE_DECODE - _decode_traces.clear(); -#endif - _group_traces.clear(); + + RELEASE_ARRAY(_decode_traces); + RELEASE_ARRAY(_group_traces); if (_dev_inst) { try { @@ -189,7 +170,7 @@ void SigSession::set_device(boost::shared_ptr dev_inst) return; } sr_session_datafeed_callback_add(data_feed_in_proc, NULL); - device_setted(); + _callback->device_setted(); } } @@ -198,83 +179,86 @@ void SigSession::set_file(QString name) { // Deslect the old device, because file type detection in File::create // destorys the old session inside libsigrok. + deselect_device(); + try { - set_device(boost::shared_ptr()); - } catch(const QString e) { - throw(e); - return; - } - try { - set_device(boost::shared_ptr(device::File::create(name))); + set_device(device::File::create(name)); } catch(const QString e) { throw(e); return; } } -void SigSession::close_file(boost::shared_ptr dev_inst) +void SigSession::close_file(DevInst *dev_inst) { assert(dev_inst); + assert(_device_manager); + try { dev_inst->device_updated(); set_repeating(false); stop_capture(); capture_state_changed(SigSession::Stopped); - _device_manager.del_device(dev_inst); + _device_manager->del_device(dev_inst); } catch(const QString e) { throw(e); return; } } -void SigSession::set_default_device(boost::function error_handler) +void SigSession::set_default_device() { - boost::shared_ptr default_device; - const list > &devices = - _device_manager.devices(); + assert(_device_manager); + DevInst *default_device = NULL; + + const std::list &devices = _device_manager->devices(); if (!devices.empty()) { // Fall back to the first device in the list. default_device = devices.front(); // Try and find the DreamSourceLab device and select that by default - BOOST_FOREACH (boost::shared_ptr dev, devices) - if (dev->dev_inst() && - !dev->name().contains("virtual")) { + for (DevInst *dev : devices) + if (dev->dev_inst() && !dev->name().contains("virtual")) { default_device = dev; break; } - try { + } + + if (default_device != NULL){ + try { set_device(default_device); } catch(const QString e) { - error_handler(e); + _callback->show_error(e); return; } } } -void SigSession::release_device(device::DevInst *dev_inst) +void SigSession::release_device(DevInst *dev_inst) { - (void)dev_inst; - assert(_dev_inst.get() == dev_inst); + if (_dev_inst == NULL) + return; + assert(dev_inst); + // assert(_dev_inst == dev_inst); assert(get_capture_state() != Running); - _dev_inst = boost::shared_ptr(); - //_dev_inst.reset(); + + _dev_inst = NULL; } -SigSession::capture_state SigSession::get_capture_state() const -{ - boost::lock_guard lock(_sampling_mutex); - return _capture_state; +SigSession::capture_state SigSession::get_capture_state() +{ + std::lock_guard lock(_sampling_mutex); + return _capture_state; } -uint64_t SigSession::cur_samplelimits() const +uint64_t SigSession::cur_samplelimits() { return _cur_samplelimits; } -uint64_t SigSession::cur_samplerate() const +uint64_t SigSession::cur_samplerate() { // samplerate for current viewport if (_dev_inst->dev_inst()->mode == DSO) @@ -283,23 +267,23 @@ uint64_t SigSession::cur_samplerate() const return cur_snap_samplerate(); } -uint64_t SigSession::cur_snap_samplerate() const +uint64_t SigSession::cur_snap_samplerate() { // samplerate for current snapshot return _cur_snap_samplerate; } -double SigSession::cur_sampletime() const +double SigSession::cur_sampletime() { return cur_samplelimits() * 1.0 / cur_samplerate(); } -double SigSession::cur_snap_sampletime() const +double SigSession::cur_snap_sampletime() { return cur_samplelimits() * 1.0 / cur_snap_samplerate(); } -double SigSession::cur_view_time() const +double SigSession::cur_view_time() { return _dev_inst->get_time_base() * DS_CONF_DSO_HDIVS * 1.0 / SR_SEC(1); } @@ -320,19 +304,19 @@ void SigSession::set_cur_snap_samplerate(uint64_t samplerate) if (_group_data) _group_data->set_samplerate(_cur_snap_samplerate); -#ifdef ENABLE_DECODE + // DecoderStack - BOOST_FOREACH(const boost::shared_ptr d, _decode_traces) + for(auto &d : _decode_traces) d->decoder()->set_samplerate(_cur_snap_samplerate); -#endif + // Math if (_math_trace && _math_trace->enabled()) _math_trace->get_math_stack()->set_samplerate(_dev_inst->get_sample_rate()); // SpectrumStack - BOOST_FOREACH(const boost::shared_ptr m, _spectrum_traces) + for(auto & m : _spectrum_traces) m->get_spectrum_stack()->set_samplerate(_cur_snap_samplerate); - cur_snap_samplerate_changed(); + _callback->cur_snap_samplerate_changed(); } void SigSession::set_cur_samplelimits(uint64_t samplelimits) @@ -348,7 +332,7 @@ void SigSession::capture_init() set_repeating(get_run_mode() == Repetitive); // update instant setting _dev_inst->set_config(NULL, NULL, SR_CONF_INSTANT, g_variant_new_boolean(_instant)); - update_capture(); + _callback->update_capture(); set_cur_snap_samplerate(_dev_inst->get_sample_rate()); set_cur_samplelimits(_dev_inst->get_sample_limit()); @@ -357,10 +341,11 @@ void SigSession::capture_init() _trigger_flag = false; _trigger_ch = 0; _hw_replied = false; + if (_dev_inst->dev_inst()->mode != LOGIC) - _feed_timer.start(FeedInterval); + _feed_timer.Start(FeedInterval); else - _feed_timer.stop(); + _feed_timer.Stop(); _noData_cnt = 0; data_unlock(); @@ -369,15 +354,15 @@ void SigSession::capture_init() container_init(); // update current hw offset - BOOST_FOREACH(const boost::shared_ptr s, _signals) + for(auto &s : _signals) { assert(s); - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s))) { + view::DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(s))) { dsoSig->set_zero_ratio(dsoSig->get_zero_ratio()); } - boost::shared_ptr analogSig; - if ((analogSig = dynamic_pointer_cast(s))) { + view::AnalogSignal *analogSig = NULL; + if ((analogSig = dynamic_cast(s))) { analogSig->set_zero_ratio(analogSig->get_zero_ratio()); } } @@ -402,7 +387,7 @@ void SigSession::container_init() _dso_data->init(); // SpectrumStack - BOOST_FOREACH(const boost::shared_ptr m, _spectrum_traces) + for(auto &m : _spectrum_traces) { assert(m); m->get_spectrum_stack()->init(); @@ -411,22 +396,20 @@ void SigSession::container_init() if (_math_trace) _math_trace->get_math_stack()->init(); -#ifdef ENABLE_DECODE + // DecoderModel //pv::data::DecoderModel *decoder_model = get_decoder_model(); //decoder_model->setDecoderStack(NULL); // DecoderStack - BOOST_FOREACH(const boost::shared_ptr d, _decode_traces) - { - assert(d); + for(auto &d : _decode_traces) + { d->decoder()->init(); } -#endif + } -void SigSession::start_capture(bool instant, - boost::function error_handler) -{ +void SigSession::start_capture(bool instant) +{ // Check that a device instance has been selected. if (!_dev_inst) { qDebug() << "No device selected"; @@ -435,72 +418,105 @@ void SigSession::start_capture(bool instant, } assert(_dev_inst->dev_inst()); + qDebug()<<"start capture, device title:"<<_dev_inst->format_device_title(); + if (!_dev_inst->is_usable()) { _error = Hw_err; - session_error(); + _callback->session_error(); capture_state_changed(SigSession::Stopped); return; } // stop previous capture - stop_capture(); + stop_capture(); + // reset measure of dso signal - BOOST_FOREACH(const boost::shared_ptr s, _signals) + for(auto &s : _signals) { - assert(s); - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s))) + view::DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(s))) dsoSig->set_mValid(false); } - // update setting + // update setting + if (_dev_inst->name() != "virtual-session") _instant = instant; else _instant = true; + capture_init(); - // Check that at least one probe is enabled - const GSList *l; + // Check that at least one probe is enabled + const GSList *l; for (l = _dev_inst->dev_inst()->channels; l; l = l->next) { sr_channel *const probe = (sr_channel*)l->data; - assert(probe); - if (probe->enabled) - break; - } - if (!l) { - error_handler(tr("No probes enabled.")); + assert(probe); + if (probe->enabled) + break; + } + if (!l) { + _callback->show_error("No probes enabled."); data_updated(); set_repeating(false); capture_state_changed(SigSession::Stopped); - return; - } + return; + } - // Begin the session - _sampling_thread.reset(new boost::thread( - &SigSession::sample_thread_proc, this, _dev_inst, - error_handler)); + if (_sampling_thread.joinable()){ + _sampling_thread.join(); + } + + if (sr_check_session_start_before() != 0){ + assert(false); + } + _sampling_thread = std::thread(&SigSession::sample_thread_proc, this, _dev_inst); +} + + +void SigSession::sample_thread_proc(DevInst *dev_inst) +{ + assert(dev_inst); + assert(dev_inst->dev_inst()); + + try { + dev_inst->start(); + } catch(const QString e) { + _callback->show_error(e); + return; + } + + receive_data(0); + set_capture_state(Running); + //session loop + dev_inst->run(); + set_capture_state(Stopped); + + // Confirm that SR_DF_END was received + assert(_logic_data->snapshot()->last_ended()); + assert(_dso_data->snapshot()->last_ended()); + assert(_analog_data->snapshot()->last_ended()); } void SigSession::stop_capture() { - data_unlock(); -#ifdef ENABLE_DECODE - for (vector< boost::shared_ptr >::iterator i = - _decode_traces.begin(); - i != _decode_traces.end(); - i++) - (*i)->decoder()->stop_decode(); -#endif - if (get_capture_state() != Running) - return; + do_stop_capture(); + int dex = 0; + clear_all_decode_task(dex); +} - sr_session_stop(); +void SigSession::do_stop_capture() +{ + data_unlock(); - // Check that sampling stopped - if (_sampling_thread.get()) - _sampling_thread->join(); - _sampling_thread.reset(); + if (_dev_inst){ + _dev_inst->stop(); + } + + // Check that sampling stopped + if (_sampling_thread.joinable()){ + _sampling_thread.join(); + } } bool SigSession::get_capture_status(bool &triggered, int &progress) @@ -526,23 +542,21 @@ bool SigSession::get_capture_status(bool &triggered, int &progress) return false; } -vector< boost::shared_ptr > SigSession::get_signals() -{ - //boost::lock_guard lock(_signals_mutex); - return _signals; +std::vector& SigSession::get_signals() +{ + return _signals; } -vector< boost::shared_ptr > SigSession::get_group_signals() -{ - //boost::lock_guard lock(_signals_mutex); +std::vector& SigSession::get_group_signals() +{ return _group_traces; } -set< boost::shared_ptr > SigSession::get_data() const -{ - //lock_guard lock(_signals_mutex); - set< boost::shared_ptr > data; - BOOST_FOREACH(const boost::shared_ptr sig, _signals) { +std::set SigSession::get_data() +{ + std::set data; + + for(auto &sig : _signals) { assert(sig); data.insert(sig->data()); } @@ -556,43 +570,16 @@ bool SigSession::get_instant() } void SigSession::set_capture_state(capture_state state) -{ - boost::lock_guard lock(_sampling_mutex); - _capture_state = state; +{ + std::lock_guard lock(_sampling_mutex); + _capture_state = state; data_updated(); - capture_state_changed(state); + capture_state_changed(state); } - -void SigSession::sample_thread_proc(boost::shared_ptr dev_inst, - boost::function error_handler) -{ - assert(dev_inst); - assert(dev_inst->dev_inst()); - assert(error_handler); - - try { - dev_inst->start(); - } catch(const QString e) { - error_handler(e); - return; - } - - receive_data(0); - set_capture_state(Running); - - dev_inst->run(); - - set_capture_state(Stopped); - - // Confirm that SR_DF_END was received - assert(_cur_logic_snapshot->last_ended()); - assert(_cur_dso_snapshot->last_ended()); - assert(_cur_analog_snapshot->last_ended()); -} - + void SigSession::check_update() { - boost::lock_guard lock(_data_mutex); + ds_lock_guard lock(_data_mutex); if (_capture_state != Running) return; @@ -612,37 +599,25 @@ void SigSession::add_group() { std::list probe_index_list; - std::vector< boost::shared_ptr >::iterator i = _signals.begin(); + auto i = _signals.begin(); while (i != _signals.end()) { if ((*i)->get_type() == SR_CHANNEL_LOGIC && (*i)->selected()) probe_index_list.push_back((*i)->get_index()); i++; } - if (probe_index_list.size() > 1) { - //_group_data.reset(new data::Group(_last_sample_rate)); -// if (_group_data->get_snapshots().empty()) -// _group_data->set_samplerate(_dev_inst->get_sample_rate()); + if (probe_index_list.size() > 1) { _group_data->init(); _group_data->set_samplerate(_cur_snap_samplerate); - const boost::shared_ptr signal( - new view::GroupSignal("New Group", - _group_data, probe_index_list, _group_cnt)); + auto signal = new view::GroupSignal("New Group", _group_data, probe_index_list, _group_cnt); _group_traces.push_back(signal); _group_cnt++; - const deque< boost::shared_ptr > &snapshots = - _logic_data->get_snapshots(); - if (!snapshots.empty()) { - //if (!_cur_group_snapshot) - //{ - // Create a new data snapshot - _cur_group_snapshot = boost::shared_ptr( - new data::GroupSnapshot(snapshots.front(), signal->get_index_list())); - //_cur_group_snapshot->append_payload(); - _group_data->push_snapshot(_cur_group_snapshot); - _cur_group_snapshot.reset(); - //} + const auto &snapshots = _logic_data->get_snapshots(); + if (!snapshots.empty()) + { + auto p = new data::GroupSnapshot(snapshots.front(), signal->get_index_list()); + _group_data->push_snapshot(p); } signals_changed(); @@ -652,25 +627,33 @@ void SigSession::add_group() void SigSession::del_group() { - std::vector< boost::shared_ptr >::iterator i = _group_traces.begin(); - while (i != _group_traces.end()) { - if ((*i)->selected()) { - std::vector< boost::shared_ptr >::iterator j = _group_traces.begin(); + auto i = _group_traces.begin(); + + while (i != _group_traces.end()) { + + pv::view::GroupSignal *psig = *(i); + + if (psig->selected()) { + auto j = _group_traces.begin(); while(j != _group_traces.end()) { - if ((*j)->get_sec_index() > (*i)->get_sec_index()) + if ((*j)->get_sec_index() > psig->get_sec_index()) (*j)->set_sec_index((*j)->get_sec_index() - 1); j++; } - std::deque< boost::shared_ptr > &snapshots = _group_data->get_snapshots(); + auto &snapshots = _group_data->get_snapshots(); if (!snapshots.empty()) { - _group_data->get_snapshots().at((*i)->get_sec_index()).reset(); - std::deque< boost::shared_ptr >::iterator k = snapshots.begin(); + int dex = psig->get_sec_index(); + pv::data::GroupSnapshot *pshot = _group_data->get_snapshots().at(dex); + delete pshot; + + auto k = snapshots.begin(); k += (*i)->get_sec_index(); _group_data->get_snapshots().erase(k); } + + delete psig; - (*i).reset(); i = _group_traces.erase(i); _group_cnt--; @@ -688,8 +671,8 @@ void SigSession::init_signals() assert(_dev_inst); stop_capture(); - vector< boost::shared_ptr > sigs; - boost::shared_ptr signal; + std::vector sigs; + view::Signal *signal = NULL; unsigned int logic_probe_count = 0; unsigned int dso_probe_count = 0; unsigned int analog_probe_count = 0; @@ -703,10 +686,9 @@ void SigSession::init_signals() if (_group_data) _group_data->clear(); -#ifdef ENABLE_DECODE - // Clear the decode traces - _decode_traces.clear(); -#endif + + // Clear the decode traces + RELEASE_ARRAY(_decode_traces); // Detect what data types we will receive if(_dev_inst) { @@ -733,47 +715,45 @@ void SigSession::init_signals() } } - // Make the logic probe list + // Make the logic probe list + RELEASE_ARRAY(_group_traces); + + std::vector().swap(_group_traces); + + for (GSList *l = _dev_inst->dev_inst()->channels; l; l = l->next) { - _group_traces.clear(); - vector< boost::shared_ptr >().swap(_group_traces); + sr_channel *probe = + (sr_channel *)l->data; + assert(probe); + signal = NULL; - for (GSList *l = _dev_inst->dev_inst()->channels; l; l = l->next) { - sr_channel *probe = - ( sr_channel *)l->data; - assert(probe); - signal.reset(); - switch(probe->type) { - case SR_CHANNEL_LOGIC: - if (probe->enabled) - signal = boost::shared_ptr( - new view::LogicSignal(_dev_inst, _logic_data, probe)); - break; + switch (probe->type) + { + case SR_CHANNEL_LOGIC: + if (probe->enabled) + signal = new view::LogicSignal(_dev_inst, _logic_data, probe); + break; - case SR_CHANNEL_DSO: - signal = boost::shared_ptr( - new view::DsoSignal(_dev_inst, _dso_data, probe)); - break; + case SR_CHANNEL_DSO: + signal = new view::DsoSignal(_dev_inst, _dso_data, probe); + break; - case SR_CHANNEL_ANALOG: - if (probe->enabled) - signal = boost::shared_ptr( - new view::AnalogSignal(_dev_inst, _analog_data, probe)); - break; - } - if(signal.get()) - sigs.push_back(signal); + case SR_CHANNEL_ANALOG: + if (probe->enabled) + signal = new view::AnalogSignal(_dev_inst, _analog_data, probe); + break; } - - _signals.clear(); - vector< boost::shared_ptr >().swap(_signals); - _signals = sigs; + if (signal != NULL) + sigs.push_back(signal); } + RELEASE_ARRAY(_signals); + std::vector().swap(_signals); + _signals = sigs; + spectrum_rebuild(); lissajous_disable(); math_disable(); - //data_updated(); } void SigSession::reload() @@ -783,70 +763,72 @@ void SigSession::reload() if (_capture_state == Running) stop_capture(); - //refresh(0); - vector< boost::shared_ptr > sigs; - boost::shared_ptr signal; + std::vector sigs; + view::Signal *signal = NULL; // Make the logic probe list + for (GSList *l = _dev_inst->dev_inst()->channels; l; l = l->next) { - for (GSList *l = _dev_inst->dev_inst()->channels; l; l = l->next) { - sr_channel *probe = - (sr_channel *)l->data; - assert(probe); - signal.reset(); - switch(probe->type) { - case SR_CHANNEL_LOGIC: - if (probe->enabled) { - std::vector< boost::shared_ptr >::iterator i = _signals.begin(); - while (i != _signals.end()) { - if ((*i)->get_index() == probe->index) { - boost::shared_ptr logicSig; - if ((logicSig = dynamic_pointer_cast(*i))) - signal = boost::shared_ptr( - new view::LogicSignal(logicSig, _logic_data, probe)); - break; - } - i++; - } - if (!signal.get()) - signal = boost::shared_ptr( - new view::LogicSignal(_dev_inst, _logic_data, probe)); - } - break; + sr_channel *probe = + (sr_channel *)l->data; + assert(probe); + signal = NULL; -// case SR_CHANNEL_DSO: -// signal = boost::shared_ptr( -// new view::DsoSignal(_dev_inst,_dso_data, probe)); -// break; - - case SR_CHANNEL_ANALOG: - if (probe->enabled) { - std::vector< boost::shared_ptr >::iterator i = _signals.begin(); - while (i != _signals.end()) { - if ((*i)->get_index() == probe->index) { - boost::shared_ptr analogSig; - if ((analogSig = dynamic_pointer_cast(*i))) - signal = boost::shared_ptr( - new view::AnalogSignal(analogSig, _analog_data, probe)); - break; - } - i++; + switch (probe->type) + { + case SR_CHANNEL_LOGIC: + if (probe->enabled) + { + auto i = _signals.begin(); + while (i != _signals.end()) + { + if ((*i)->get_index() == probe->index) + { + view::LogicSignal *logicSig = NULL; + if ((logicSig = dynamic_cast(*i))) + signal = new view::LogicSignal(logicSig, _logic_data, probe); + break; } - if (!signal.get()) - signal = boost::shared_ptr( - new view::AnalogSignal(_dev_inst, _analog_data, probe)); + i++; + } + if (signal == NULL) + { + signal = new view::LogicSignal(_dev_inst, _logic_data, probe); } - break; } - if (signal.get()) - sigs.push_back(signal); - } + break; - if (!sigs.empty()) { - _signals.clear(); - vector< boost::shared_ptr >().swap(_signals); - _signals = sigs; + case SR_CHANNEL_ANALOG: + if (probe->enabled) + { + auto i = _signals.begin(); + while (i != _signals.end()) + { + if ((*i)->get_index() == probe->index) + { + view::AnalogSignal *analogSig = NULL; + if ((analogSig = dynamic_cast(*i))) + signal = new view::AnalogSignal(analogSig, _analog_data, probe); + break; + } + i++; + } + if (signal == NULL) + { + signal = new view::AnalogSignal(_dev_inst, _analog_data, probe); + } + } + break; } + if (signal != NULL) + sigs.push_back(signal); + } + + if (!sigs.empty()) + { + RELEASE_ARRAY(_signals); + std::vector().swap(_signals); + _signals = sigs; } spectrum_rebuild(); @@ -854,39 +836,37 @@ void SigSession::reload() void SigSession::refresh(int holdtime) { - boost::lock_guard lock(_data_mutex); + ds_lock_guard lock(_data_mutex); data_lock(); if (_logic_data) { - _logic_data->init(); - //_cur_logic_snapshot.reset(); -#ifdef ENABLE_DECODE - BOOST_FOREACH(const boost::shared_ptr d, _decode_traces) - { - assert(d); + _logic_data->init(); + + for(auto &d : _decode_traces) + { d->decoder()->init(); } -#endif } + if (_dso_data) { _dso_data->init(); // SpectrumStack - BOOST_FOREACH(const boost::shared_ptr m, _spectrum_traces) + for(auto &m : _spectrum_traces) { assert(m); m->get_spectrum_stack()->init(); } + if (_math_trace) _math_trace->get_math_stack()->init(); } - if (_analog_data) { - _analog_data->init(); - //_cur_analog_snapshot.reset(); - } - QTimer::singleShot(holdtime, this, SLOT(feed_timeout())); - //data_updated(); + if (_analog_data) { + _analog_data->init(); + } + + _out_timer.TimeOut(holdtime, std::bind(&SigSession::feed_timeout, this)); _data_updated = true; } @@ -924,26 +904,26 @@ void SigSession::feed_in_header(const sr_dev_inst *sdi) { (void)sdi; _trigger_pos = 0; - receive_header(); + _callback->receive_header(); } void SigSession::feed_in_meta(const sr_dev_inst *sdi, const sr_datafeed_meta &meta) { - (void)sdi; + (void)sdi; - for (const GSList *l = meta.config; l; l = l->next) { + for (const GSList *l = meta.config; l; l = l->next) { const sr_config *const src = (const sr_config*)l->data; - switch (src->key) { - case SR_CONF_SAMPLERATE: - /// @todo handle samplerate changes - /// samplerate = (uint64_t *)src->value; - break; - default: - // Unknown metadata is not an error. - break; - } - } + switch (src->key) { + case SR_CONF_SAMPLERATE: + /// @todo handle samplerate changes + /// samplerate = (uint64_t *)src->value; + break; + default: + // Unknown metadata is not an error. + break; + } + } } void SigSession::feed_in_trigger(const ds_trigger_pos &trigger_pos) @@ -953,7 +933,7 @@ void SigSession::feed_in_trigger(const ds_trigger_pos &trigger_pos) _trigger_flag = (trigger_pos.status & 0x01); if (_trigger_flag) { _trigger_pos = trigger_pos.real_pos; - receive_trigger(_trigger_pos); + _callback->receive_trigger(_trigger_pos); } } else { int probe_count = 0; @@ -968,106 +948,97 @@ void SigSession::feed_in_trigger(const ds_trigger_pos &trigger_pos) } } _trigger_pos = trigger_pos.real_pos * probe_count / probe_en_count; - receive_trigger(_trigger_pos); + _callback->receive_trigger(_trigger_pos); } } void SigSession::feed_in_logic(const sr_datafeed_logic &logic) -{ - //boost::lock_guard lock(_data_mutex); - if (!_logic_data || _cur_logic_snapshot->memory_failed()) { - qDebug() << "Unexpected logic packet"; - return; - } +{ + if (!_logic_data || _logic_data->snapshot()->memory_failed()) { + qDebug() << "Unexpected logic packet"; + return; + } if (logic.data_error == 1) { _error = Test_data_err; _error_pattern = logic.error_pattern; - session_error(); + _callback->session_error(); } - if (_cur_logic_snapshot->last_ended()) { - _cur_logic_snapshot->first_payload(logic, _dev_inst->get_sample_limit(), _dev_inst->dev_inst()->channels); + if (_logic_data->snapshot()->last_ended()) { + _logic_data->snapshot()->first_payload(logic, _dev_inst->get_sample_limit(), _dev_inst->dev_inst()->channels); // @todo Putting this here means that only listeners querying // for logic will be notified. Currently the only user of // frame_began is DecoderStack, but in future we need to signal // this after both analog and logic sweeps have begun. - frame_began(); + _callback->frame_began(); } else { - // Append to the existing data snapshot - _cur_logic_snapshot->append_payload(logic); + // Append to the existing data snapshot + _logic_data->snapshot()->append_payload(logic); } - if (_cur_logic_snapshot->memory_failed()) { + if (_logic_data->snapshot()->memory_failed()) { _error = Malloc_err; - session_error(); + _callback->session_error(); return; } - emit receive_data(logic.length * 8 / get_ch_num(SR_CHANNEL_LOGIC)); - data_received(); - //data_updated(); + receive_data(logic.length * 8 / get_ch_num(SR_CHANNEL_LOGIC)); + + _callback->data_received(); + _data_updated = true; } void SigSession::feed_in_dso(const sr_datafeed_dso &dso) -{ - //boost::lock_guard lock(_data_mutex); - - if(!_dso_data || _cur_dso_snapshot->memory_failed()) +{ + if(!_dso_data || _dso_data->snapshot()->memory_failed()) { qDebug() << "Unexpected dso packet"; return; // This dso packet was not expected. } - if (_cur_dso_snapshot->last_ended()) + if (_dso_data->snapshot()->last_ended()) { std::map sig_enable; // reset scale of dso signal - BOOST_FOREACH(const boost::shared_ptr s, _signals) + for(auto &s : _signals) { assert(s); - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s))) { + view::DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(s))) { dsoSig->set_scale(dsoSig->get_view_rect().height()); sig_enable[dsoSig->get_index()] = dsoSig->enabled(); } } // first payload - _cur_dso_snapshot->first_payload(dso, _dev_inst->get_sample_limit(), sig_enable, _instant); + _dso_data->snapshot()->first_payload(dso, _dev_inst->get_sample_limit(), sig_enable, _instant); } else { // Append to the existing data snapshot - _cur_dso_snapshot->append_payload(dso); + _dso_data->snapshot()->append_payload(dso); } - BOOST_FOREACH(const boost::shared_ptr s, _signals) { - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s)) && (dsoSig->enabled())) + for(auto &s : _signals) { + view::DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(s)) && (dsoSig->enabled())) dsoSig->paint_prepare(); } if (dso.num_samples != 0) { // update current sample rate set_cur_snap_samplerate(_dev_inst->get_sample_rate()); -// // reset measure of dso signal -// BOOST_FOREACH(const boost::shared_ptr s, _signals) -// { -// assert(s); -// boost::shared_ptr dsoSig; -// if ((dsoSig = dynamic_pointer_cast(s))) -// dsoSig->set_mValid(false); -// } + } - if (_cur_dso_snapshot->memory_failed()) { + if (_dso_data->snapshot()->memory_failed()) { _error = Malloc_err; - session_error(); + _callback->session_error(); return; } // calculate related spectrum results - BOOST_FOREACH(const boost::shared_ptr m, _spectrum_traces) + for(auto &m : _spectrum_traces) { assert(m); if (m->enabled()) @@ -1086,153 +1057,155 @@ void SigSession::feed_in_dso(const sr_datafeed_dso &dso) if (!_instant) data_lock(); + _data_updated = true; } void SigSession::feed_in_analog(const sr_datafeed_analog &analog) -{ - //boost::lock_guard lock(_data_mutex); +{ - if(!_analog_data || _cur_analog_snapshot->memory_failed()) - { - qDebug() << "Unexpected analog packet"; - return; // This analog packet was not expected. - } + if(!_analog_data || _analog_data->snapshot()->memory_failed()) + { + qDebug() << "Unexpected analog packet"; + return; // This analog packet was not expected. + } - if (_cur_analog_snapshot->last_ended()) - { + if (_analog_data->snapshot()->last_ended()) + { // reset scale of analog signal - BOOST_FOREACH(const boost::shared_ptr s, _signals) + for(auto &s : _signals) { assert(s); - boost::shared_ptr analogSig; - if ((analogSig = dynamic_pointer_cast(s))) { + view::AnalogSignal *analogSig = NULL; + if ((analogSig = dynamic_cast(s))) { analogSig->set_scale(analogSig->get_totalHeight()); } } // first payload - _cur_analog_snapshot->first_payload(analog, _dev_inst->get_sample_limit(), _dev_inst->dev_inst()->channels); + _analog_data->snapshot()->first_payload(analog, _dev_inst->get_sample_limit(), _dev_inst->dev_inst()->channels); } else { - // Append to the existing data snapshot - _cur_analog_snapshot->append_payload(analog); + // Append to the existing data snapshot + _analog_data->snapshot()->append_payload(analog); } - if (_cur_analog_snapshot->memory_failed()) { + if (_analog_data->snapshot()->memory_failed()) { _error = Malloc_err; - session_error(); + _callback->session_error(); return; } receive_data(analog.num_samples); - //data_updated(); _data_updated = true; } - + void SigSession::data_feed_in(const struct sr_dev_inst *sdi, const struct sr_datafeed_packet *packet) { - assert(sdi); - assert(packet); - - boost::lock_guard lock(_data_mutex); - + assert(sdi); + assert(packet); + + ds_lock_guard lock(_data_mutex); + if (_data_lock && packet->type != SR_DF_END) return; + if (packet->type != SR_DF_END && packet->status != SR_PKT_OK) { _error = Pkt_data_err; - session_error(); + _callback->session_error(); return; } - switch (packet->type) { - case SR_DF_HEADER: - feed_in_header(sdi); - break; + switch (packet->type) { + case SR_DF_HEADER: + feed_in_header(sdi); + break; - case SR_DF_META: - assert(packet->payload); - feed_in_meta(sdi, + case SR_DF_META: + assert(packet->payload); + feed_in_meta(sdi, *(const sr_datafeed_meta*)packet->payload); - break; + break; case SR_DF_TRIGGER: assert(packet->payload); feed_in_trigger(*(const ds_trigger_pos*)packet->payload); break; - case SR_DF_LOGIC: - assert(packet->payload); + case SR_DF_LOGIC: + assert(packet->payload); feed_in_logic(*(const sr_datafeed_logic*)packet->payload); - break; + break; case SR_DF_DSO: assert(packet->payload); feed_in_dso(*(const sr_datafeed_dso*)packet->payload); break; - case SR_DF_ANALOG: - assert(packet->payload); + case SR_DF_ANALOG: + assert(packet->payload); feed_in_analog(*(const sr_datafeed_analog*)packet->payload); - break; + break; case SR_DF_OVERFLOW: { if (_error == No_err) { _error = Data_overflow; - session_error(); + _callback->session_error(); } break; } - case SR_DF_END: - { - { - //boost::lock_guard lock(_data_mutex); - if (!_cur_logic_snapshot->empty()) { - BOOST_FOREACH(const boost::shared_ptr g, _group_traces) - { - assert(g); + case SR_DF_END: + { + if (!_logic_data->snapshot()->empty()) + { + for (auto &g : _group_traces) + { + assert(g); - _cur_group_snapshot = boost::shared_ptr( - new data::GroupSnapshot(_logic_data->get_snapshots().front(), g->get_index_list())); - _group_data->push_snapshot(_cur_group_snapshot); - _cur_group_snapshot.reset(); - } + auto p = new data::GroupSnapshot(_logic_data->get_snapshots().front(), g->get_index_list()); + _group_data->push_snapshot(p); } - _cur_logic_snapshot->capture_ended(); - _cur_dso_snapshot->capture_ended(); - _cur_analog_snapshot->capture_ended(); -#ifdef ENABLE_DECODE - BOOST_FOREACH(const boost::shared_ptr d, _decode_traces) - d->frame_ended(); -#endif - } + } + _logic_data->snapshot()->capture_ended(); + _dso_data->snapshot()->capture_ended(); + _analog_data->snapshot()->capture_ended(); + + for (auto trace : _decode_traces){ + trace->decoder()->frame_ended(); + trace->frame_ended(); + add_decode_task(trace); + } if (packet->status != SR_PKT_OK) { _error = Pkt_data_err; - session_error(); + _callback->session_error(); } - frame_ended(); - if (get_device()->dev_inst()->mode != LOGIC) - set_session_time(QDateTime::currentDateTime()); - break; - } - } + + _callback->frame_ended(); + + if (get_device()->dev_inst()->mode != LOGIC){ + set_session_time(QDateTime::currentDateTime()); + } + + break; + } + } } void SigSession::data_feed_in_proc(const struct sr_dev_inst *sdi, const struct sr_datafeed_packet *packet, void *cb_data) { - (void) cb_data; - assert(_session); - _session->data_feed_in(sdi, packet); + (void) cb_data; + assert(_session); + _session->data_feed_in(sdi, packet); } /* * hotplug function */ -int SigSession::hotplug_callback(struct libusb_context *ctx, struct libusb_device *dev, +int SigSession::hotplug_callback(struct libusb_context *ctx, struct libusb_device *dev, libusb_hotplug_event event, void *user_data) { (void)ctx; @@ -1252,48 +1225,50 @@ int SigSession::hotplug_callback(struct libusb_context *ctx, struct libusb_devic return 0; } -void SigSession::hotplug_proc(boost::function error_handler) +void SigSession::hotplug_proc() { - struct timeval tv; - - (void)error_handler; + struct timeval tv; if (!_dev_inst) return; tv.tv_sec = tv.tv_usec = 0; try { - while(_session) { + while(_session && !_bHotplugStop) { libusb_handle_events_timeout(NULL, &tv); if (_hot_attach) { qDebug("DreamSourceLab hardware attached!"); - device_attach(); + _callback->device_attach(); _hot_attach = false; } if (_hot_detach) { qDebug("DreamSourceLab hardware detached!"); - device_detach(); + _callback->device_detach(); _hot_detach = false; } - boost::this_thread::sleep(boost::posix_time::millisec(100)); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } catch(...) { qDebug("Interrupt exception for hotplug thread was thrown."); } - qDebug("Hotplug thread exit!"); + // qDebug("Hotplug thread exit!"); } void SigSession::register_hotplug_callback() { int ret; - ret = libusb_hotplug_register_callback(NULL, (libusb_hotplug_event)(LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED | - LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT), - (libusb_hotplug_flag)LIBUSB_HOTPLUG_ENUMERATE, 0x2A0E, LIBUSB_HOTPLUG_MATCH_ANY, - LIBUSB_HOTPLUG_MATCH_ANY, hotplug_callback, NULL, + ret = libusb_hotplug_register_callback(NULL, + (libusb_hotplug_event)(LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED | LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT), + (libusb_hotplug_flag)LIBUSB_HOTPLUG_ENUMERATE, + 0x2A0E, + LIBUSB_HOTPLUG_MATCH_ANY, + LIBUSB_HOTPLUG_MATCH_ANY, + hotplug_callback, + NULL, &_hotplug_handle); if (LIBUSB_SUCCESS != ret){ - qDebug() << "Error creating a hotplug callback\n"; + qDebug() << "Error creating a hotplug callback,code:"< error_handler) -{ - +void SigSession::start_hotplug_work() +{ // Begin the session - qDebug() << "Starting a hotplug thread...\n"; + // qDebug() << "Starting a hotplug thread...\n"; _hot_attach = false; _hot_detach = false; - _hotplug.reset(new boost::thread( - &SigSession::hotplug_proc, this, error_handler)); + if (_hotplug_thread.joinable()){ + return; + } + _hotplug_thread = std::thread(&SigSession::hotplug_proc, this); } -void SigSession::stop_hotplug_proc() -{ - if (_hotplug.get()) { - _hotplug->interrupt(); - _hotplug->join(); - } - _hotplug.reset(); +void SigSession::stop_hotplug_work() +{ + _bHotplugStop = true; + if (_hotplug_thread.joinable()){ + _hotplug_thread.join(); + } } uint16_t SigSession::get_ch_num(int type) @@ -1329,20 +1304,18 @@ uint16_t SigSession::get_ch_num(int type) uint16_t logic_ch_num = 0; uint16_t dso_ch_num = 0; uint16_t analog_ch_num = 0; + if (_dev_inst->dev_inst()) { - BOOST_FOREACH(const boost::shared_ptr s, _signals) + for(auto &s : _signals) { assert(s); - if (dynamic_pointer_cast(s) && s->enabled()) { - //if (dynamic_pointer_cast(s)) { + if (dynamic_cast(s) && s->enabled()) { logic_ch_num++; } - if (dynamic_pointer_cast(s) && s->enabled()) { - //if (dynamic_pointer_cast(s)) { + if (dynamic_cast(s) && s->enabled()) { dso_ch_num++; } - if (dynamic_pointer_cast(s) && s->enabled()) { - //if (dynamic_pointer_cast(s)) { + if (dynamic_cast(s) && s->enabled()) { analog_ch_num++; } } @@ -1362,186 +1335,151 @@ uint16_t SigSession::get_ch_num(int type) return num_channels; } -#ifdef ENABLE_DECODE -bool SigSession::add_decoder(srd_decoder *const dec, bool silent) -{ - bool ret = false; - map probes; - boost::shared_ptr decoder_stack; +bool SigSession::add_decoder(srd_decoder *const dec, bool silent, DecoderStatus *dstatus){ + return do_add_decoder(dec, silent, dstatus); +} - try { - //lock_guard lock(_signals_mutex); +bool SigSession::do_add_decoder(srd_decoder *const dec, bool silent, DecoderStatus *dstatus) +{ + try { + + bool ret = false; // Create the decoder - decoder_stack = boost::shared_ptr( - new data::DecoderStack(*this, dec)); + std::map probes; + data::DecoderStack *decoder_stack = new data::DecoderStack(this, dec, dstatus); + assert(decoder_stack); // Make a list of all the probes std::vector all_probes; for(const GSList *i = dec->channels; i; i = i->next) all_probes.push_back((const srd_channel*)i->data); + for(const GSList *i = dec->opt_channels; i; i = i->next) all_probes.push_back((const srd_channel*)i->data); - - assert(decoder_stack); - assert(!decoder_stack->stack().empty()); - assert(decoder_stack->stack().front()); + decoder_stack->stack().front()->set_probes(probes); // Create the decode signal - boost::shared_ptr d( - new view::DecodeTrace(*this, decoder_stack, - _decode_traces.size())); + view::DecodeTrace *trace = new view::DecodeTrace(this, decoder_stack, _decode_traces.size()); + assert(trace); + // set view early for decode start/end region setting - BOOST_FOREACH(const boost::shared_ptr s, _signals) { + for(auto &s : _signals) { if (s->get_view()) { - d->set_view(s->get_view()); + trace->set_view(s->get_view()); break; } } - if (silent) { - _decode_traces.push_back(d); + if (silent) { ret = true; - } else if (d->create_popup()) { - _decode_traces.push_back(d); + } else if (trace->create_popup()) { ret = true; } - } catch(const std::runtime_error &e) { - return false; - } - if (ret) { - signals_changed(); - // Do an initial decode - decoder_stack->begin_decode(); - data_updated(); - } + if (ret) + { + _decode_traces.push_back(trace); + add_decode_task(trace); + signals_changed(); + data_updated(); + } + else + { + delete trace; + } - return ret; + return ret; + + } catch(...) { + ds_debug("Starting a hotplug thread...\n"); + } + + return false; } - -vector< boost::shared_ptr > SigSession::get_decode_signals() const -{ - //lock_guard lock(_signals_mutex); + +std::vector& SigSession::get_decode_signals() +{ return _decode_traces; } -void SigSession::remove_decode_signal(view::DecodeTrace *signal) +void SigSession::remove_decoder(int index) { - for (vector< boost::shared_ptr >::iterator i = - _decode_traces.begin(); - i != _decode_traces.end(); - i++) - if ((*i).get() == signal) - { - _decode_traces.erase(i); - signals_changed(); - return; - } -} + int size = (int)_decode_traces.size(); + assert(index < size); -void SigSession::remove_decode_signal(int index) -{ - int cur_index = 0; - for (vector< boost::shared_ptr >::iterator i = - _decode_traces.begin(); - i != _decode_traces.end(); - i++) - { - if (cur_index == index) - { - _decode_traces.erase(i); - signals_changed(); - return; - } - cur_index++; + auto it = _decode_traces.begin() + index; + auto trace = (*it); + _decode_traces.erase(it); + + bool isRunning = trace->decoder()->IsRunning(); + + remove_decode_task(trace); + + if (isRunning){ + //destroy it in thread + trace->_delete_flag = true; } + else{ + delete trace; + signals_changed(); + } } void SigSession::rst_decoder(int index) { - int cur_index = 0; - for (vector< boost::shared_ptr >::iterator i = - _decode_traces.begin(); - i != _decode_traces.end(); - i++) - { - if (cur_index == index) - { - if ((*i)->create_popup()) - { - (*i)->decoder()->stop_decode(); - (*i)->decoder()->begin_decode(); - data_updated(); - } - return; - } - cur_index++; + auto trace = get_decoder_trace(index); + + if (trace && trace->create_popup() ){ + remove_decode_task(trace); //remove old task + add_decode_task(trace); + data_updated(); } } - -void SigSession::rst_decoder(view::DecodeTrace *signal) -{ - for (vector< boost::shared_ptr >::iterator i = - _decode_traces.begin(); - i != _decode_traces.end(); - i++) - if ((*i).get() == signal) - { - if ((*i)->create_popup()) - { - (*i)->decoder()->stop_decode(); - (*i)->decoder()->begin_decode(); - data_updated(); - } - return; - } -} - -pv::data::DecoderModel* SigSession::get_decoder_model() const + +pv::data::DecoderModel* SigSession::get_decoder_model() { return _decoder_model; } -#endif + void SigSession::spectrum_rebuild() { bool has_dso_signal = false; - BOOST_FOREACH(const boost::shared_ptr s, _signals) { - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s))) { + for(auto &s : _signals) { + view::DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(s))) { has_dso_signal = true; // check already have - std::vector< boost::shared_ptr >::iterator iter = _spectrum_traces.begin(); + auto iter = _spectrum_traces.begin(); for(unsigned int i = 0; i < _spectrum_traces.size(); i++, iter++) if ((*iter)->get_index() == dsoSig->get_index()) break; // if not, rebuild if (iter == _spectrum_traces.end()) { - boost::shared_ptr spectrum_stack( - new data::SpectrumStack(*this, dsoSig->get_index())); - boost::shared_ptr spectrum_trace( - new view::SpectrumTrace(*this, spectrum_stack, dsoSig->get_index())); + auto spectrum_stack = new data::SpectrumStack(this, dsoSig->get_index()); + auto spectrum_trace = new view::SpectrumTrace(this, spectrum_stack, dsoSig->get_index()); _spectrum_traces.push_back(spectrum_trace); } } } - if (!has_dso_signal) - _spectrum_traces.clear(); + if (!has_dso_signal){ + RELEASE_ARRAY(_spectrum_traces); + } signals_changed(); } -vector< boost::shared_ptr > SigSession::get_spectrum_traces() -{ - //lock_guard lock(_signals_mutex); +std::vector& SigSession::get_spectrum_traces() +{ return _spectrum_traces; } void SigSession::lissajous_rebuild(bool enable, int xindex, int yindex, double percent) { - _lissajous_trace.reset(new view::LissajousTrace(enable, _dso_data, xindex, yindex, percent)); + DESTROY_OBJECT(_lissajous_trace); + _lissajous_trace = new view::LissajousTrace(enable, _dso_data, xindex, yindex, percent); signals_changed(); } @@ -1551,21 +1489,21 @@ void SigSession::lissajous_disable() _lissajous_trace->set_enable(false); } -boost::shared_ptr SigSession::get_lissajous_trace() -{ - //lock_guard lock(_signals_mutex); +view::LissajousTrace* SigSession::get_lissajous_trace() +{ return _lissajous_trace; } -void SigSession::math_rebuild(bool enable, - boost::shared_ptr dsoSig1, - boost::shared_ptr dsoSig2, +void SigSession::math_rebuild(bool enable,view::DsoSignal *dsoSig1, + view::DsoSignal *dsoSig2, data::MathStack::MathType type) { - boost::lock_guard lock(_data_mutex); - boost::shared_ptr math_stack( - new data::MathStack(*this, dsoSig1, dsoSig2, type)); - _math_trace.reset(new view::MathTrace(enable, math_stack, dsoSig1, dsoSig2)); + ds_lock_guard lock(_data_mutex); + + auto math_stack = new data::MathStack(this, dsoSig1, dsoSig2, type); + DESTROY_OBJECT(_math_trace); + _math_trace = new view::MathTrace(enable, math_stack, dsoSig1, dsoSig2); + if (_math_trace && _math_trace->enabled()) { _math_trace->get_math_stack()->set_samplerate(_dev_inst->get_sample_rate()); _math_trace->get_math_stack()->realloc(_dev_inst->get_sample_limit()); @@ -1580,9 +1518,8 @@ void SigSession::math_disable() _math_trace->set_enable(false); } -boost::shared_ptr SigSession::get_math_trace() +view::MathTrace* SigSession::get_math_trace() { - //lock_guard lock(_signals_mutex); return _math_trace; } @@ -1591,22 +1528,22 @@ void SigSession::set_session_time(QDateTime time) _session_time = time; } -QDateTime SigSession::get_session_time() const +QDateTime SigSession::get_session_time() { return _session_time; } -uint64_t SigSession::get_trigger_pos() const +uint64_t SigSession::get_trigger_pos() { return _trigger_pos; } -bool SigSession::trigd() const +bool SigSession::trigd() { return _trigger_flag; } -uint8_t SigSession::trigd_ch() const +uint8_t SigSession::trigd_ch() { return _trigger_ch; } @@ -1617,12 +1554,12 @@ void SigSession::nodata_timeout() if (gvar == NULL) return; if (g_variant_get_byte(gvar) != DSO_TRIGGER_AUTO) { - show_wait_trigger(); + _callback->show_wait_trigger(); } } void SigSession::feed_timeout() -{ +{ data_unlock(); if (!_data_updated) { if (++_noData_cnt >= (WaitShowTime/FeedInterval)) @@ -1630,19 +1567,19 @@ void SigSession::feed_timeout() } } -boost::shared_ptr SigSession::get_snapshot(int type) +data::Snapshot* SigSession::get_snapshot(int type) { if (type == SR_CHANNEL_LOGIC) - return _cur_logic_snapshot; + return _logic_data->snapshot(); else if (type == SR_CHANNEL_ANALOG) - return _cur_analog_snapshot; + return _analog_data->snapshot(); else if (type == SR_CHANNEL_DSO) - return _cur_dso_snapshot; + return _dso_data->snapshot(); else return NULL; } -SigSession::error_state SigSession::get_error() const +SigSession::error_state SigSession::get_error() { return _error; } @@ -1658,12 +1595,12 @@ void SigSession::clear_error() _error = No_err; } -uint64_t SigSession::get_error_pattern() const +uint64_t SigSession::get_error_pattern() { return _error_pattern; } -SigSession::run_mode SigSession::get_run_mode() const +SigSession::run_mode SigSession::get_run_mode() { return _run_mode; } @@ -1673,7 +1610,7 @@ void SigSession::set_run_mode(run_mode mode) _run_mode = mode; } -int SigSession::get_repeat_intvl() const +int SigSession::get_repeat_intvl() { return _repeat_intvl; } @@ -1690,7 +1627,7 @@ void SigSession::set_repeating(bool repeat) _repeat_hold_prg = 0; } -bool SigSession::isRepeating() const +bool SigSession::isRepeating() { return _repeating; } @@ -1705,8 +1642,8 @@ bool SigSession::repeat_check() if (_dev_inst->dev_inst()->mode == LOGIC) { _repeat_hold_prg = 100; - repeat_hold(_repeat_hold_prg); - QTimer::singleShot(_repeat_intvl*1000/RepeatHoldDiv, this, SLOT(repeat_update())); + _callback->repeat_hold(_repeat_hold_prg); + _out_timer.TimeOut(_repeat_intvl*1000/RepeatHoldDiv, std::bind(&SigSession::repeat_update, this)); return true; } else { return false; @@ -1717,15 +1654,16 @@ void SigSession::repeat_update() { if (isRepeating()) { _repeat_hold_prg -= 100/RepeatHoldDiv; - if (_repeat_hold_prg != 0) - QTimer::singleShot(_repeat_intvl*1000/RepeatHoldDiv, this, SLOT(repeat_update())); - repeat_hold(_repeat_hold_prg); + if (_repeat_hold_prg != 0){ + _out_timer.TimeOut(_repeat_intvl*1000/RepeatHoldDiv, std::bind(&SigSession::repeat_update, this)); + } + _callback->repeat_hold(_repeat_hold_prg); if (_repeat_hold_prg == 0) repeat_resume(); } } -int SigSession::get_repeat_hold() const +int SigSession::get_repeat_hold() { if (isRepeating()) return _repeat_hold_prg; @@ -1738,16 +1676,16 @@ void SigSession::set_map_zoom(int index) _map_zoom = index; } -int SigSession::get_map_zoom() const +int SigSession::get_map_zoom() { return _map_zoom; } void SigSession::auto_end() { - BOOST_FOREACH(const boost::shared_ptr s, _signals) { - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s))) { + for(auto &s : _signals) { + view::DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(s))) { dsoSig->auto_end(); } } @@ -1763,17 +1701,17 @@ void SigSession::set_save_end(uint64_t end) _save_end = end; } -uint64_t SigSession::get_save_start() const +uint64_t SigSession::get_save_start() { return _save_start; } -uint64_t SigSession::get_save_end() const +uint64_t SigSession::get_save_end() { return _save_end; } -bool SigSession::get_saving() const +bool SigSession::get_saving() { return _saving; } @@ -1800,7 +1738,7 @@ void SigSession::exit_capture() } } -float SigSession::stop_scale() const +float SigSession::stop_scale() { return _stop_scale; } @@ -1810,4 +1748,192 @@ void SigSession::set_stop_scale(float scale) _stop_scale = scale; } + sr_dev_inst* SigSession::get_dev_inst_c() + { + if (_dev_inst != NULL){ + return _dev_inst->dev_inst(); + } + return NULL; + } + + void SigSession::Open() + { + register_hotplug_callback(); + } + + void SigSession::Close() + { + if (_bClose) + return; + + _bClose = true; + + do_stop_capture(); //stop capture + + clear_all_decoder(); //clear all decode task, and stop decode thread + + ds_trigger_destroy(); + + if (_dev_inst) + { + _dev_inst->release(); + } + + // TODO: This should not be necessary + _session = NULL; + + stop_hotplug_work(); + + if (_hotplug_handle) + { + deregister_hotplug_callback(); + _hotplug_handle = 0; + } + } + +//append a decode task, and try create a thread + void SigSession::add_decode_task(view::DecodeTrace *trace) + { + //qDebug()<<"add a decode task"; + + std::lock_guard lock(_decode_task_mutex); + _decode_tasks.push_back(trace); + + if (!_bDecodeRunning) + { + if (_decode_thread.joinable()) + _decode_thread.join(); + + _decode_thread = std::thread(&SigSession::decode_task_proc, this); + _bDecodeRunning = true; + } + } + + void SigSession::remove_decode_task(view::DecodeTrace *trace) + { + std::lock_guard lock(_decode_task_mutex); + + for (auto it = _decode_tasks.begin(); it != _decode_tasks.end(); it++){ + if ((*it) == trace){ + (*it)->decoder()->stop_decode_work(); + _decode_tasks.erase(it); + qDebug()<<"remove a wait decode task"; + return; + } + } + + //the task maybe is running + // qDebug()<<"remove a running decode task"; + trace->decoder()->stop_decode_work(); + } + + void SigSession::clear_all_decoder() + { + //create the wait task deque + int dex = -1; + clear_all_decode_task(dex); + + view::DecodeTrace *runningTrace = NULL; + if (dex != -1){ + runningTrace = _decode_traces[dex]; + runningTrace->_delete_flag = true; //destroy it in thread + } + + for (auto trace : _decode_traces) + { + if (trace != runningTrace){ + delete trace; + } + } + _decode_traces.clear(); + + //wait thread end + if (_decode_thread.joinable()) + { + // qDebug() << "wait the decode thread end"; + _decode_thread.join(); + } + + if (!is_closed()) + signals_changed(); + } + + void SigSession::clear_all_decode_task(int &runningDex) + { + std::lock_guard lock(_decode_task_mutex); + + //remove wait task + for (auto trace : _decode_tasks){ + trace->decoder()->stop_decode_work(); //set decode proc stop flag + } + _decode_tasks.clear(); + + //make sure the running task can stop + runningDex = -1; + int dex = 0; + for (auto trace : _decode_traces) + { + if (trace->decoder()->IsRunning()) + { + trace->decoder()->stop_decode_work(); + runningDex = dex; + } + dex++; + } + } + + view::DecodeTrace* SigSession::get_decoder_trace(int index) + { + int size = (int)_decode_traces.size(); + assert(index < size); + return _decode_traces[index]; + } + + view::DecodeTrace* SigSession::get_top_decode_task() + { + std::lock_guard lock(_decode_task_mutex); + + auto it = _decode_tasks.begin(); + if (it != _decode_tasks.end()){ + auto p = (*it); + _decode_tasks.erase(it); + return p; + } + + return NULL; + } + + //the decode task thread proc + void SigSession::decode_task_proc(){ + + //qDebug()<<"decode thread start"; + auto task = get_top_decode_task(); + + while (task != NULL) + { + // qDebug()<<"one decode task be actived"; + + if (!task->_delete_flag){ + task->decoder()->begin_decode_work(); + } + + if (task->_delete_flag){ + qDebug()<<"desroy a decoder in task thread"; + + DESTROY_QT_LATER(task); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + if (!_bClose){ + signals_changed(); + } + } + + task = get_top_decode_task(); + } + + // qDebug()<<"decode thread end"; + _bDecodeRunning = false; + } + + + } // namespace pv diff --git a/DSView/pv/sigsession.h b/DSView/pv/sigsession.h index 96fd0649..4de67805 100755 --- a/DSView/pv/sigsession.h +++ b/DSView/pv/sigsession.h @@ -22,38 +22,30 @@ #ifndef DSVIEW_PV_SIGSESSION_H #define DSVIEW_PV_SIGSESSION_H - -#include -#include -#include -#include -#include - -#include -#include -#include + #include #include #include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - +#include +#include #include +#include +#include #include "view/mathtrace.h" #include "data/mathstack.h" +#include "interface/icallbacks.h" +#include "dstimer.h" + +#include struct srd_decoder; struct srd_channel; + + +class DecoderStatus; + +typedef std::lock_guard ds_lock_guard; namespace pv { @@ -92,10 +84,11 @@ class Decoder; class DecoderFactory; } -class SigSession : public QObject -{ - Q_OBJECT +using namespace pv::device; +//created by MainWindow +class SigSession +{ private: static constexpr float Oversampling = 2.0f; static const int RefreshTime = 500; @@ -127,142 +120,178 @@ public: Data_overflow }; +private: + SigSession(SigSession &o); + public: - SigSession(DeviceManager &device_manager); + explicit SigSession(DeviceManager *device_manager); - ~SigSession(); + ~SigSession(); - boost::shared_ptr get_device() const; + DevInst* get_device(); /** * Sets device instance that will be used in the next capture session. */ - void set_device(boost::shared_ptr dev_inst); - + void set_device(DevInst *dev_inst); + void deselect_device(); void set_file(QString name); + void close_file(DevInst *dev_inst); + void set_default_device(); - void close_file(boost::shared_ptr dev_inst); + void release_device(DevInst *dev_inst); + capture_state get_capture_state(); + uint64_t cur_samplerate(); + uint64_t cur_snap_samplerate(); + uint64_t cur_samplelimits(); - void set_default_device(boost::function error_handler); - - void release_device(device::DevInst *dev_inst); - - capture_state get_capture_state() const; - - uint64_t cur_samplerate() const; - uint64_t cur_snap_samplerate() const; - uint64_t cur_samplelimits() const; - double cur_sampletime() const; - double cur_snap_sampletime() const; - double cur_view_time() const; + double cur_sampletime(); + double cur_snap_sampletime(); + double cur_view_time(); void set_cur_snap_samplerate(uint64_t samplerate); void set_cur_samplelimits(uint64_t samplelimits); void set_session_time(QDateTime time); - QDateTime get_session_time() const; - uint64_t get_trigger_pos() const; - void start_capture(bool instant, - boost::function error_handler); - void capture_init(); + QDateTime get_session_time(); + uint64_t get_trigger_pos(); + bool get_capture_status(bool &triggered, int &progress); - void container_init(); - std::set< boost::shared_ptr > get_data() const; + void container_init(); + std::set get_data(); + std::vector& get_signals(); + std::vector& get_group_signals(); - std::vector< boost::shared_ptr > - get_signals(); - - std::vector< boost::shared_ptr > - get_group_signals(); - -#ifdef ENABLE_DECODE - bool add_decoder(srd_decoder *const dec, bool silent); - - std::vector< boost::shared_ptr > - get_decode_signals() const; - - void remove_decode_signal(view::DecodeTrace *signal); - - void remove_decode_signal(int index); - - void rst_decoder(int index); - - void rst_decoder(view::DecodeTrace *signal); - - pv::data::DecoderModel* get_decoder_model() const; -#endif - - std::vector< boost::shared_ptr > - get_spectrum_traces(); - - boost::shared_ptr - get_lissajous_trace(); - - boost::shared_ptr - get_math_trace(); + bool add_decoder(srd_decoder *const dec, bool silent, DecoderStatus *dstatus); + void remove_decoder(int index); + std::vector& get_decode_signals(); + + void rst_decoder(int index); + pv::data::DecoderModel* get_decoder_model(); + std::vector& get_spectrum_traces(); + view::LissajousTrace* get_lissajous_trace(); + view::MathTrace* get_math_trace(); void init_signals(); - void add_group(); - void del_group(); - - void start_hotplug_proc(boost::function error_handler); - void stop_hotplug_proc(); - void register_hotplug_callback(); - void deregister_hotplug_callback(); - + void start_hotplug_work(); + void stop_hotplug_work(); uint16_t get_ch_num(int type); bool get_instant(); - bool get_data_lock(); void data_auto_lock(int lock); void data_auto_unlock(); bool get_data_auto_lock(); + void spectrum_rebuild(); void lissajous_rebuild(bool enable, int xindex, int yindex, double percent); void lissajous_disable(); - void math_rebuild(bool enable, - boost::shared_ptr dsoSig1, - boost::shared_ptr dsoSig2, + + void math_rebuild(bool enable,pv::view::DsoSignal *dsoSig1, + pv::view::DsoSignal *dsoSig2, data::MathStack::MathType type); + void math_disable(); - - bool trigd() const; - uint8_t trigd_ch() const; - - boost::shared_ptr get_snapshot(int type); - - error_state get_error() const; + bool trigd(); + uint8_t trigd_ch(); + data::Snapshot* get_snapshot(int type); + error_state get_error(); void set_error(error_state state); void clear_error(); - uint64_t get_error_pattern() const; - run_mode get_run_mode() const; + uint64_t get_error_pattern(); + run_mode get_run_mode(); void set_run_mode(run_mode mode); - int get_repeat_intvl() const; + int get_repeat_intvl(); void set_repeat_intvl(int interval); - bool isRepeating() const; + + bool isRepeating(); bool repeat_check(); - int get_repeat_hold() const; - - int get_map_zoom() const; - + int get_repeat_hold(); + int get_map_zoom(); void set_save_start(uint64_t start); + void set_save_end(uint64_t end); - uint64_t get_save_start() const; - uint64_t get_save_end() const; - bool get_saving() const; + uint64_t get_save_start(); + uint64_t get_save_end(); + bool get_saving(); + void set_saving(bool saving); void set_stop_scale(float scale); - float stop_scale() const; + float stop_scale(); void exit_capture(); + sr_dev_inst* get_dev_inst_c(); + void Open(); + void Close(); + void clear_all_decoder(); + + inline bool is_closed(){ + return _bClose; + } + + inline void set_callback(ISessionCallback *callback){ + _callback = callback; + } + +public: + inline void capture_state_changed(int state){ + _callback->capture_state_changed(state); + } + + inline void session_save(){ + _callback->session_save(); + } + + inline void repeat_resume(){ + _callback->repeat_resume(); + } + + inline void show_region(uint64_t start, uint64_t end, bool keep){ + _callback->show_region(start, end, keep); + } + + inline void decode_done(){ + _callback->decode_done(); + } +private: + inline void data_updated(){ + _callback->data_updated(); + } + + inline void signals_changed(){ + _callback->signals_changed(); + } + + inline void receive_data(quint64 len){ + _callback->receive_data_len(len); + } + private: void set_capture_state(capture_state state); + void register_hotplug_callback(); + void deregister_hotplug_callback(); + bool do_add_decoder(srd_decoder *const dec, bool silent, DecoderStatus *dstatus); + + void add_decode_task(view::DecodeTrace *trace); + void remove_decode_task(view::DecodeTrace *trace); + void clear_all_decode_task(int &runningDex); + + view::DecodeTrace* get_decoder_trace(int index); + void decode_task_proc(); + view::DecodeTrace* get_top_decode_task(); + + void capture_init(); + void do_stop_capture(); + void data_lock(); + void data_unlock(); + void nodata_timeout(); + void feed_timeout(); + void repeat_update(); private: /** @@ -272,171 +301,117 @@ private: * used, or NULL if no input format was selected or * auto-detected. */ - static sr_input_format* determine_input_file_format( - const std::string &filename); - - static sr_input* load_input_file_format( - const std::string &filename, - boost::function error_handler, - sr_input_format *format = NULL); - - void sample_thread_proc(boost::shared_ptr dev_inst, - boost::function error_handler); + static sr_input_format* determine_input_file_format(const std::string &filename); + void sample_thread_proc(DevInst *dev_inst); // data feed void feed_in_header(const sr_dev_inst *sdi); - void feed_in_meta(const sr_dev_inst *sdi, - const sr_datafeed_meta &meta); + void feed_in_meta(const sr_dev_inst *sdi, const sr_datafeed_meta &meta); void feed_in_trigger(const ds_trigger_pos &trigger_pos); void feed_in_logic(const sr_datafeed_logic &logic); + void feed_in_dso(const sr_datafeed_dso &dso); - void feed_in_analog(const sr_datafeed_analog &analog); + void feed_in_analog(const sr_datafeed_analog &analog); void data_feed_in(const struct sr_dev_inst *sdi, const struct sr_datafeed_packet *packet); + static void data_feed_in_proc(const struct sr_dev_inst *sdi, const struct sr_datafeed_packet *packet, void *cb_data); // thread for hotplug - void hotplug_proc(boost::function error_handler); - static int hotplug_callback(struct libusb_context *ctx, struct libusb_device *dev, + void hotplug_proc(); + + static LIBUSB_CALL int hotplug_callback(struct libusb_context *ctx, struct libusb_device *dev, libusb_hotplug_event event, void *user_data); +public: + void reload(); + void refresh(int holdtime); + void start_capture(bool instant); + void stop_capture(); + void check_update(); + void set_repeating(bool repeat); + void set_map_zoom(int index); + void auto_end(); + private: - DeviceManager &_device_manager; + DeviceManager *_device_manager; /** * The device instance that will be used in the next capture session. */ - boost::shared_ptr _dev_inst; + DevInst *_dev_inst; + mutable std::mutex _sampling_mutex; + mutable std::mutex _data_mutex; + mutable std::mutex _decode_task_mutex; + + std::thread _hotplug_thread; + std::thread _sampling_thread; + std::thread _decode_thread; - mutable boost::mutex _sampling_mutex; - capture_state _capture_state; - bool _instant; - uint64_t _cur_snap_samplerate; - uint64_t _cur_samplelimits; + volatile bool _bHotplugStop; + volatile bool _bDecodeRunning; - //mutable boost::mutex _signals_mutex; - std::vector< boost::shared_ptr > _signals; - std::vector< boost::shared_ptr > _group_traces; -#ifdef ENABLE_DECODE - std::vector< boost::shared_ptr > _decode_traces; - pv::data::DecoderModel *_decoder_model; -#endif - std::vector< boost::shared_ptr > _spectrum_traces; - boost::shared_ptr _lissajous_trace; - boost::shared_ptr _math_trace; + capture_state _capture_state; + bool _instant; + uint64_t _cur_snap_samplerate; + uint64_t _cur_samplelimits; + + std::vector _signals; + std::vector _group_traces; - mutable boost::mutex _data_mutex; - boost::shared_ptr _logic_data; - boost::shared_ptr _cur_logic_snapshot; - boost::shared_ptr _dso_data; - boost::shared_ptr _cur_dso_snapshot; - boost::shared_ptr _analog_data; - boost::shared_ptr _cur_analog_snapshot; - boost::shared_ptr _group_data; - boost::shared_ptr _cur_group_snapshot; - int _group_cnt; - - std::unique_ptr _sampling_thread; + std::vector _decode_traces; + std::vector _decode_tasks; + pv::data::DecoderModel *_decoder_model; + std::vector _spectrum_traces; + view::LissajousTrace *_lissajous_trace; + view::MathTrace *_math_trace; + + data::Logic *_logic_data; + data::Dso *_dso_data; + data::Analog *_analog_data; + data::Group *_group_data; + int _group_cnt; + libusb_hotplug_callback_handle _hotplug_handle; - std::unique_ptr _hotplug; - bool _hot_attach; - bool _hot_detach; + + bool _hot_attach; + bool _hot_detach; - QTimer _feed_timer; - int _noData_cnt; - bool _data_lock; - bool _data_updated; - int _data_auto_lock; + DsTimer _feed_timer; + DsTimer _out_timer; + int _noData_cnt; + bool _data_lock; + bool _data_updated; + int _data_auto_lock; - QDateTime _session_time; - uint64_t _trigger_pos; - bool _trigger_flag; - uint8_t _trigger_ch; - bool _hw_replied; + QDateTime _session_time; + uint64_t _trigger_pos; + bool _trigger_flag; + uint8_t _trigger_ch; + bool _hw_replied; error_state _error; - uint64_t _error_pattern; + uint64_t _error_pattern; - run_mode _run_mode; - int _repeat_intvl; - bool _repeating; - int _repeat_hold_prg; + run_mode _run_mode; + int _repeat_intvl; + bool _repeating; + int _repeat_hold_prg; - int _map_zoom; + int _map_zoom; - uint64_t _save_start; - uint64_t _save_end; - bool _saving; + uint64_t _save_start; + uint64_t _save_end; + bool _saving; - bool _dso_feed; - float _stop_scale; - -signals: - void capture_state_changed(int state); - - void signals_changed(); - - void data_updated(); - - void receive_data(quint64 length); - - void device_attach(); - void device_detach(); - - void receive_trigger(quint64 trigger_pos); - - void receive_header(); - - void dso_ch_changed(uint16_t num); - - void frame_began(); - - void data_received(); - - void frame_ended(); - - void device_setted(); - - void zero_adj(); - void progressSaveFileValueChanged(int percent); - - void decode_done(); - - void show_region(uint64_t start, uint64_t end, bool keep); - - void show_wait_trigger(); - - void session_save(); - - void session_error(); - - void repeat_hold(int percent); - void repeat_resume(); - - void cur_snap_samplerate_changed(); - - void update_capture(); - -public slots: - void reload(); - void refresh(int holdtime); - void stop_capture(); - void check_update(); - // repeat - void set_repeating(bool repeat); - void set_map_zoom(int index); - // OSC auto - void auto_end(); - -private slots: - void data_lock(); - void data_unlock(); - void nodata_timeout(); - void feed_timeout(); - void repeat_update(); + bool _dso_feed; + float _stop_scale; + bool _bClose; + ISessionCallback *_callback; + private: // TODO: This should not be necessary. Multiple concurrent // sessions should should be supported and it should be diff --git a/DSView/pv/storesession.cpp b/DSView/pv/storesession.cpp index d41881ac..44404627 100755 --- a/DSView/pv/storesession.cpp +++ b/DSView/pv/storesession.cpp @@ -23,51 +23,53 @@ #define __STDC_FORMAT_MACROS #include "storesession.h" +#include "sigsession.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include +#include "data/logic.h" +#include "data/logicsnapshot.h" +#include "data/dsosnapshot.h" +#include "data/analogsnapshot.h" +#include "data/decoderstack.h" +#include "data/decode/decoder.h" +#include "data/decode/row.h" +#include "view/trace.h" +#include "view/signal.h" +#include "view/logicsignal.h" +#include "view/dsosignal.h" +#include "view/decodetrace.h" +#include "device/devinst.h" +#include "dock/protocoldock.h" + #include +#include +#include +#include +#include +#include +#include +#include +#include -using boost::dynamic_pointer_cast; -using boost::mutex; -using boost::shared_ptr; -using boost::thread; -using boost::lock_guard; -using std::deque; -using std::make_pair; -using std::min; -using std::pair; -using std::set; -using std::string; -using std::vector; +#ifdef _WIN32 +#include +#endif + +#include +#include "config/appconfig.h" +#include "dsvdef.h" -namespace pv { + +namespace pv { -StoreSession::StoreSession(SigSession &session) : +StoreSession::StoreSession(SigSession *session) : _session(session), _outModule(NULL), _units_stored(0), _unit_count(0), _has_error(false), _canceled(false) -{ +{ + _sessionDataGetter = NULL; } StoreSession::~StoreSession() @@ -75,20 +77,18 @@ StoreSession::~StoreSession() wait(); } -SigSession& StoreSession::session() +SigSession* StoreSession::session() { return _session; } -pair StoreSession::progress() const -{ - //lock_guard lock(_mutex); - return make_pair(_units_stored, _unit_count); +std::pair StoreSession::progress() +{ + return std::make_pair(_units_stored, _unit_count); } -const QString& StoreSession::error() const -{ - //lock_guard lock(_mutex); +const QString& StoreSession::error() +{ return _error; } @@ -99,9 +99,8 @@ void StoreSession::wait() } void StoreSession::cancel() -{ - _canceled = true; - _thread.interrupt(); +{ + _canceled = true; } QList StoreSession::getSuportedExportFormats(){ @@ -110,7 +109,7 @@ QList StoreSession::getSuportedExportFormats(){ while(*supportedModules){ if(*supportedModules == NULL) break; - if (_session.get_device()->dev_inst()->mode != LOGIC && + if (_session->get_device()->dev_inst()->mode != LOGIC && strcmp((*supportedModules)->id, "csv")) break; QString format((*supportedModules)->desc); @@ -123,10 +122,12 @@ QList StoreSession::getSuportedExportFormats(){ return list; } -bool StoreSession::save_start(QString session_file) -{ +bool StoreSession::save_start() +{ + assert(_sessionDataGetter); + std::set type_set; - BOOST_FOREACH(const boost::shared_ptr sig, _session.get_signals()) { + for(auto &sig : _session->get_signals()) { assert(sig); type_set.insert(sig->get_type()); } @@ -135,50 +136,26 @@ bool StoreSession::save_start(QString session_file) _error = tr("DSView does not currently support" "file saving for multiple data types."); return false; + } else if (type_set.size() == 0) { _error = tr("No data to save."); return false; } - const boost::shared_ptr snapshot(_session.get_snapshot(*type_set.begin())); + if (_file_name == ""){ + _error = tr("No set file name."); + return false; + } + + const auto snapshot = _session->get_snapshot(*type_set.begin()); assert(snapshot); // Check we have data if (snapshot->empty()) { _error = tr("No data to save."); return false; - } + } - const QString DIR_KEY("SavePath"); - QSettings settings(QApplication::organizationName(), QApplication::applicationName()); - QString default_name = settings.value(DIR_KEY).toString() + "/" + _session.get_device()->name() + "-"; - for (const GSList *l = _session.get_device()->get_dev_mode_list(); - l; l = l->next) { - const sr_dev_mode *mode = (const sr_dev_mode *)l->data; - if (_session.get_device()->dev_inst()->mode == mode->mode) { - default_name += mode->acronym; - break; - } - } - default_name += _session.get_session_time().toString("-yyMMdd-hhmmss"); - - // Show the dialog - _file_name = QFileDialog::getSaveFileName( - NULL, tr("Save File"), default_name, - tr("DSView Data (*.dsl)")); - - if (!_file_name.isEmpty()) { - QFileInfo f(_file_name); - if(f.suffix().compare("dsl")) - _file_name.append(tr(".dsl")); - QDir CurrentDir; - settings.setValue(DIR_KEY, CurrentDir.filePath(_file_name)); - - QString meta_file = meta_gen(snapshot); - #ifdef ENABLE_DECODE - QString decoders_file = decoders_gen(); - #else - QString decoders_file = NULL; - #endif + /* if (meta_file == NULL) { _error = tr("Generate temp file failed."); } else { @@ -189,30 +166,76 @@ bool StoreSession::save_start(QString session_file) if (ret != SR_OK) { _error = tr("Failed to create zip file. Initialization error."); } else { - _thread = boost::thread(&StoreSession::save_proc, this, snapshot); + _thread = std::thread(&StoreSession::save_proc, this, snapshot); return !_has_error; } } + */ + + std::string meta_data; + std::string decoder_data; + std::string session_data; + + meta_gen(snapshot, meta_data); + decoders_gen(decoder_data); + _sessionDataGetter->genSessionData(session_data); + + if (meta_data.empty()) { + _error = tr("Generate temp file data failed."); + QFile::remove(_file_name); + return false; + } + if (decoder_data.empty()){ + _error = tr("Generate decoder file data failed."); + QFile::remove(_file_name); + return false; + } + if (session_data.empty()){ + _error = tr("Generate session file data failed."); + QFile::remove(_file_name); + return false; + } + + std::string _filename = getFileName(_file_name); + if (m_zipDoc.CreateNew(_filename.c_str(), false)) + { + if ( !m_zipDoc.AddFromBuffer("header", meta_data.c_str(), meta_data.size()) + || !m_zipDoc.AddFromBuffer("decoders", decoder_data.c_str(), decoder_data.size()) + || !m_zipDoc.AddFromBuffer("session", session_data.c_str(), session_data.size()) + ){ + _has_error = true; + _error = m_zipDoc.GetError(); + } + else + { + if (_thread.joinable()) _thread.join(); + _thread = std::thread(&StoreSession::save_proc, this, snapshot); + return !_has_error; + } + } + else{ + _error = tr("Generate zip file failed."); } QFile::remove(_file_name); - //_error.clear(); return false; } -void StoreSession::save_proc(shared_ptr snapshot) +void StoreSession::save_proc(data::Snapshot *snapshot) { assert(snapshot); + char chunk_name[20] = {0}; + int ret = SR_ERR; int num = 0; - shared_ptr logic_snapshot; - shared_ptr analog_snapshot; - shared_ptr dso_snapshot; + data::LogicSnapshot *logic_snapshot = NULL; + //data::AnalogSnapshot *analog_snapshot = NULL; + //data::DsoSnapshot *dso_snapshot = NULL; - if ((logic_snapshot = boost::dynamic_pointer_cast(snapshot))) { + if ((logic_snapshot = dynamic_cast(snapshot))) { uint16_t to_save_probes = 0; - BOOST_FOREACH(const boost::shared_ptr s, _session.get_signals()) { + for(auto &s : _session->get_signals()) { if (s->enabled() && logic_snapshot->has_data(s->get_index())) to_save_probes++; } @@ -220,13 +243,13 @@ void StoreSession::save_proc(shared_ptr snapshot) num = logic_snapshot->get_block_num(); bool sample; - BOOST_FOREACH(const boost::shared_ptr s, _session.get_signals()) { + for(auto &s : _session->get_signals()) { int ch_type = s->get_type(); if (ch_type == SR_CHANNEL_LOGIC) { int ch_index = s->get_index(); if (!s->enabled() || !logic_snapshot->has_data(ch_index)) continue; - for (int i = 0; !boost::this_thread::interruption_requested() && i < num; i++) { + for (int i = 0; !_canceled && i < num; i++) { uint8_t *buf = logic_snapshot->get_block_buf(i, ch_index, sample); uint64_t size = logic_snapshot->get_block_size(i); bool need_malloc = (buf == NULL); @@ -239,8 +262,13 @@ void StoreSession::save_proc(shared_ptr snapshot) memset(buf, sample ? 0xff : 0x0, size); } } - ret = sr_session_append(_file_name.toUtf8().data(), buf, size, - i, ch_index, ch_type, File_Version); + + // ret = sr_session_append(_file_name.toUtf8().data(), buf, size, + // i, ch_index, ch_type, File_Version); + + MakeChunkName(chunk_name, i, ch_index, ch_type, File_Version); + ret = m_zipDoc.AddFromBuffer(chunk_name, (const char*)buf, size) ? SR_OK : -1; + if (ret != SR_OK) { if (!_has_error) { _has_error = true; @@ -260,7 +288,7 @@ void StoreSession::save_proc(shared_ptr snapshot) } } else { int ch_type = -1; - BOOST_FOREACH(const boost::shared_ptr s, _session.get_signals()) { + for(auto &s : _session->get_signals()) { ch_type = s->get_type(); break; } @@ -274,7 +302,7 @@ void StoreSession::save_proc(shared_ptr snapshot) const uint8_t *buf_start = (uint8_t *)snapshot->get_data(); const uint8_t *buf_end = buf_start + _unit_count; - for (int i = 0; !boost::this_thread::interruption_requested() && i < num; i++) { + for (int i = 0; !_canceled && i < num; i++) { const uint64_t size = snapshot->get_block_size(i); if ((buf + size) > buf_end) { uint8_t *tmp = (uint8_t *)malloc(size); @@ -285,14 +313,24 @@ void StoreSession::save_proc(shared_ptr snapshot) memcpy(tmp, buf, buf_end-buf); memcpy(tmp+(buf_end-buf), buf_start, buf+size-buf_end); } - ret = sr_session_append(_file_name.toUtf8().data(), tmp, size, - i, 0, ch_type, File_Version); + + // ret = sr_session_append(_file_name.toUtf8().data(), tmp, size, + // i, 0, ch_type, File_Version); + + MakeChunkName(chunk_name, i, 0, ch_type, File_Version); + ret = m_zipDoc.AddFromBuffer(chunk_name, (const char*)tmp, size) ? SR_OK : -1; + buf += (size - _unit_count); if (tmp) free(tmp); } else { - ret = sr_session_append(_file_name.toUtf8().data(), buf, size, - i, 0, ch_type, File_Version); + + // ret = sr_session_append(_file_name.toUtf8().data(), buf, size, + // i, 0, ch_type, File_Version); + + MakeChunkName(chunk_name, i, 0, ch_type, File_Version); + ret = m_zipDoc.AddFromBuffer(chunk_name, (const char*)buf, size) ? SR_OK : -1; + buf += size; } if (ret != SR_OK) { @@ -314,209 +352,258 @@ void StoreSession::save_proc(shared_ptr snapshot) if (_canceled || num == 0) QFile::remove(_file_name); + else { + bool bret = m_zipDoc.Close(); + m_zipDoc.Release(); + + if (!bret){ + _has_error = true; + _error = m_zipDoc.GetError(); + } + } } -QString StoreSession::meta_gen(boost::shared_ptr snapshot) +bool StoreSession::meta_gen(data::Snapshot *snapshot, std::string &str) { GSList *l; - GVariant *gvar; - FILE *meta = NULL; + GVariant *gvar; struct sr_channel *probe; int probecnt; char *s; struct sr_status status; - QString metafile; + const sr_dev_inst *sdi = NULL; + char meta[300] = {0}; + + sdi = _session->get_device()->dev_inst(); + + sprintf(meta, "%s", "[version]\n"); str += meta; + sprintf(meta, "version = %d\n", File_Version); str += meta; + sprintf(meta, "%s", "[header]\n"); str += meta; - /* init "metadata" */ - QDir dir; - #if QT_VERSION >= 0x050400 - QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); - #else - QString path = QStandardPaths::writableLocation(QStandardPaths::DataLocation); - #endif - if(dir.mkpath(path)) { - dir.cd(path); - metafile = dir.absolutePath() + "/DSView-meta-XXXXXX"; - } else { - return NULL; - } - - const sr_dev_inst *sdi = _session.get_device()->dev_inst(); - meta = fopen(metafile.toUtf8().data(), "wb"); - if (meta == NULL) { - qDebug() << "Failed to create temp meta file."; - return NULL; - } - - fprintf(meta, "[version]\n"); - fprintf(meta, "version = %d\n", File_Version); - - /* metadata */ - fprintf(meta, "[header]\n"); if (sdi->driver) { - fprintf(meta, "driver = %s\n", sdi->driver->name); - fprintf(meta, "device mode = %d\n", sdi->mode); + sprintf(meta, "driver = %s\n", sdi->driver->name); str += meta; + sprintf(meta, "device mode = %d\n", sdi->mode); str += meta; } /* metadata */ - fprintf(meta, "capturefile = data\n"); - fprintf(meta, "total samples = %" PRIu64 "\n", snapshot->get_sample_count()); + sprintf(meta, "capturefile = data\n"); str += meta; + sprintf(meta, "total samples = %" PRIu64 "\n", snapshot->get_sample_count()); str += meta; if (sdi->mode != LOGIC) { - fprintf(meta, "total probes = %d\n", snapshot->get_channel_num()); - fprintf(meta, "total blocks = %d\n", snapshot->get_block_num()); + sprintf(meta, "total probes = %d\n", snapshot->get_channel_num()); str += meta; + sprintf(meta, "total blocks = %d\n", snapshot->get_block_num()); str += meta; } - shared_ptr logic_snapshot; - if ((logic_snapshot = dynamic_pointer_cast(snapshot))) { + data::LogicSnapshot *logic_snapshot = NULL; + if ((logic_snapshot = dynamic_cast(snapshot))) { uint16_t to_save_probes = 0; for (l = sdi->channels; l; l = l->next) { probe = (struct sr_channel *)l->data; if (probe->enabled && logic_snapshot->has_data(probe->index)) to_save_probes++; } - fprintf(meta, "total probes = %d\n", to_save_probes); - fprintf(meta, "total blocks = %d\n", logic_snapshot->get_block_num()); + sprintf(meta, "total probes = %d\n", to_save_probes); str += meta; + sprintf(meta, "total blocks = %d\n", logic_snapshot->get_block_num()); str += meta; } - s = sr_samplerate_string(_session.cur_snap_samplerate()); - fprintf(meta, "samplerate = %s\n", s); + s = sr_samplerate_string(_session->cur_snap_samplerate()); + + sprintf(meta, "samplerate = %s\n", s); str += meta; if (sdi->mode == DSO) { - gvar = _session.get_device()->get_config(NULL, NULL, SR_CONF_TIMEBASE); + gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_TIMEBASE); if (gvar != NULL) { uint64_t tmp_u64 = g_variant_get_uint64(gvar); - fprintf(meta, "hDiv = %" PRIu64 "\n", tmp_u64); + sprintf(meta, "hDiv = %" PRIu64 "\n", tmp_u64); str += meta; g_variant_unref(gvar); } - gvar = _session.get_device()->get_config(NULL, NULL, SR_CONF_MAX_TIMEBASE); + gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_MAX_TIMEBASE); if (gvar != NULL) { uint64_t tmp_u64 = g_variant_get_uint64(gvar); - fprintf(meta, "hDiv max = %" PRIu64 "\n", tmp_u64); + sprintf(meta, "hDiv max = %" PRIu64 "\n", tmp_u64); str += meta; g_variant_unref(gvar); } - gvar = _session.get_device()->get_config(NULL, NULL, SR_CONF_MIN_TIMEBASE); + gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_MIN_TIMEBASE); if (gvar != NULL) { uint64_t tmp_u64 = g_variant_get_uint64(gvar); - fprintf(meta, "hDiv min = %" PRIu64 "\n", tmp_u64); + sprintf(meta, "hDiv min = %" PRIu64 "\n", tmp_u64); str += meta; g_variant_unref(gvar); } - gvar = _session.get_device()->get_config(NULL, NULL, SR_CONF_UNIT_BITS); + gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_UNIT_BITS); if (gvar != NULL) { uint8_t tmp_u8 = g_variant_get_byte(gvar); - fprintf(meta, "bits = %d\n", tmp_u8); + sprintf(meta, "bits = %d\n", tmp_u8); str += meta; g_variant_unref(gvar); } - gvar = _session.get_device()->get_config(NULL, NULL, SR_CONF_REF_MIN); + gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_REF_MIN); if (gvar != NULL) { uint32_t tmp_u32 = g_variant_get_uint32(gvar); - fprintf(meta, "ref min = %d\n", tmp_u32); + sprintf(meta, "ref min = %d\n", tmp_u32); str += meta; g_variant_unref(gvar); } - gvar = _session.get_device()->get_config(NULL, NULL, SR_CONF_REF_MAX); + gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_REF_MAX); if (gvar != NULL) { uint32_t tmp_u32 = g_variant_get_uint32(gvar); - fprintf(meta, "ref max = %d\n", tmp_u32); + sprintf(meta, "ref max = %d\n", tmp_u32); str += meta; g_variant_unref(gvar); } } else if (sdi->mode == LOGIC) { - fprintf(meta, "trigger time = %lld\n", _session.get_session_time().toMSecsSinceEpoch()); + sprintf(meta, "trigger time = %lld\n", _session->get_session_time().toMSecsSinceEpoch()); str += meta; } else if (sdi->mode == ANALOG) { - shared_ptr analog_snapshot; - if ((analog_snapshot = dynamic_pointer_cast(snapshot))) { + data::AnalogSnapshot *analog_snapshot = NULL; + if ((analog_snapshot = dynamic_cast(snapshot))) { uint8_t tmp_u8 = analog_snapshot->get_unit_bytes(); - fprintf(meta, "bits = %d\n", tmp_u8*8); + sprintf(meta, "bits = %d\n", tmp_u8*8); str += meta; } - gvar = _session.get_device()->get_config(NULL, NULL, SR_CONF_REF_MIN); + gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_REF_MIN); if (gvar != NULL) { uint32_t tmp_u32 = g_variant_get_uint32(gvar); - fprintf(meta, "ref min = %d\n", tmp_u32); + sprintf(meta, "ref min = %d\n", tmp_u32); str += meta; g_variant_unref(gvar); } - gvar = _session.get_device()->get_config(NULL, NULL, SR_CONF_REF_MAX); + gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_REF_MAX); if (gvar != NULL) { uint32_t tmp_u32 = g_variant_get_uint32(gvar); - fprintf(meta, "ref max = %d\n", tmp_u32); + sprintf(meta, "ref max = %d\n", tmp_u32); str += meta; g_variant_unref(gvar); } } - fprintf(meta, "trigger pos = %" PRIu64 "\n", _session.get_trigger_pos()); + sprintf(meta, "trigger pos = %" PRIu64 "\n", _session->get_trigger_pos()); str += meta; + + probecnt = 0; - probecnt = 0; for (l = sdi->channels; l; l = l->next) { + probe = (struct sr_channel *)l->data; - if (snapshot->has_data(probe->index)) { - if (sdi->mode == LOGIC && !probe->enabled) - continue; + if (!snapshot->has_data(probe->index)) + continue; + if (sdi->mode == LOGIC && !probe->enabled) + continue; - if (probe->name) - fprintf(meta, "probe%d = %s\n", (sdi->mode == LOGIC) ? probe->index : probecnt, probe->name); - if (probe->trigger) - fprintf(meta, " trigger%d = %s\n", probecnt, probe->trigger); - if (sdi->mode == DSO) { - fprintf(meta, " enable%d = %d\n", probecnt, probe->enabled); - fprintf(meta, " coupling%d = %d\n", probecnt, probe->coupling); - fprintf(meta, " vDiv%d = %" PRIu64 "\n", probecnt, probe->vdiv); - fprintf(meta, " vFactor%d = %" PRIu64 "\n", probecnt, probe->vfactor); - fprintf(meta, " vOffset%d = %d\n", probecnt, probe->hw_offset); - fprintf(meta, " vTrig%d = %d\n", probecnt, probe->trig_value); - if (sr_status_get(sdi, &status, false) == SR_OK) { - if (probe->index == 0) { - fprintf(meta, " period%d = %" PRIu32 "\n", probecnt, status.ch0_cyc_tlen); - fprintf(meta, " pcnt%d = %" PRIu32 "\n", probecnt, status.ch0_cyc_cnt); - fprintf(meta, " max%d = %d\n", probecnt, status.ch0_max); - fprintf(meta, " min%d = %d\n", probecnt, status.ch0_min); - fprintf(meta, " plen%d = %" PRIu32 "\n", probecnt, status.ch0_cyc_plen); - fprintf(meta, " llen%d = %" PRIu32 "\n", probecnt, status.ch0_cyc_llen); - fprintf(meta, " level%d = %d\n", probecnt, status.ch0_level_valid); - fprintf(meta, " plevel%d = %d\n", probecnt, status.ch0_plevel); - fprintf(meta, " low%d = %" PRIu32 "\n", probecnt, status.ch0_low_level); - fprintf(meta, " high%d = %" PRIu32 "\n", probecnt, status.ch0_high_level); - fprintf(meta, " rlen%d = %" PRIu32 "\n", probecnt, status.ch0_cyc_rlen); - fprintf(meta, " flen%d = %" PRIu32 "\n", probecnt, status.ch0_cyc_flen); - fprintf(meta, " rms%d = %" PRIu64 "\n", probecnt, status.ch0_acc_square); - fprintf(meta, " mean%d = %" PRIu32 "\n", probecnt, status.ch0_acc_mean); - } else { - fprintf(meta, " period%d = %" PRIu32 "\n", probecnt, status.ch1_cyc_tlen); - fprintf(meta, " pcnt%d = %" PRIu32 "\n", probecnt, status.ch1_cyc_cnt); - fprintf(meta, " max%d = %d\n", probecnt, status.ch1_max); - fprintf(meta, " min%d = %d\n", probecnt, status.ch1_min); - fprintf(meta, " plen%d = %" PRIu32 "\n", probecnt, status.ch1_cyc_plen); - fprintf(meta, " llen%d = %" PRIu32 "\n", probecnt, status.ch1_cyc_llen); - fprintf(meta, " level%d = %d\n", probecnt, status.ch1_level_valid); - fprintf(meta, " plevel%d = %d\n", probecnt, status.ch1_plevel); - fprintf(meta, " low%d = %" PRIu32 "\n", probecnt, status.ch1_low_level); - fprintf(meta, " high%d = %" PRIu32 "\n", probecnt, status.ch1_high_level); - fprintf(meta, " rlen%d = %" PRIu32 "\n", probecnt, status.ch1_cyc_rlen); - fprintf(meta, " flen%d = %" PRIu32 "\n", probecnt, status.ch1_cyc_flen); - fprintf(meta, " rms%d = %" PRIu64 "\n", probecnt, status.ch1_acc_square); - fprintf(meta, " mean%d = %" PRIu32 "\n", probecnt, status.ch1_acc_mean); - } - } - } else if (sdi->mode == ANALOG) { - fprintf(meta, " enable%d = %d\n", probecnt, probe->enabled); - fprintf(meta, " coupling%d = %d\n", probecnt, probe->coupling); - fprintf(meta, " vDiv%d = %" PRIu64 "\n", probecnt, probe->vdiv); - fprintf(meta, " vOffset%d = %d\n", probecnt, probe->hw_offset); - fprintf(meta, " mapUnit%d = %s\n", probecnt, probe->map_unit); - fprintf(meta, " mapMax%d = %lf\n", probecnt, probe->map_max); - fprintf(meta, " mapMin%d = %lf\n", probecnt, probe->map_min); - } - probecnt++; + if (probe->name) + { + int sigdex = (sdi->mode == LOGIC) ? probe->index : probecnt; + sprintf(meta, "probe%d = %s\n", sigdex, probe->name); + str += meta; } - } - fclose(meta); + if (probe->trigger){ + sprintf(meta, " trigger%d = %s\n", probecnt, probe->trigger); + str += meta; + } - return metafile; + if (sdi->mode == DSO) + { + sprintf(meta, " enable%d = %d\n", probecnt, probe->enabled); + str += meta; + sprintf(meta, " coupling%d = %d\n", probecnt, probe->coupling); + str += meta; + sprintf(meta, " vDiv%d = %" PRIu64 "\n", probecnt, probe->vdiv); + str += meta; + sprintf(meta, " vFactor%d = %" PRIu64 "\n", probecnt, probe->vfactor); + str += meta; + sprintf(meta, " vOffset%d = %d\n", probecnt, probe->hw_offset); + str += meta; + sprintf(meta, " vTrig%d = %d\n", probecnt, probe->trig_value); + str += meta; + + if (sr_status_get(sdi, &status, false) == SR_OK) + { + if (probe->index == 0) + { + sprintf(meta, " period%d = %" PRIu32 "\n", probecnt, status.ch0_cyc_tlen); + str += meta; + sprintf(meta, " pcnt%d = %" PRIu32 "\n", probecnt, status.ch0_cyc_cnt); + str += meta; + sprintf(meta, " max%d = %d\n", probecnt, status.ch0_max); + str += meta; + sprintf(meta, " min%d = %d\n", probecnt, status.ch0_min); + str += meta; + sprintf(meta, " plen%d = %" PRIu32 "\n", probecnt, status.ch0_cyc_plen); + str += meta; + sprintf(meta, " llen%d = %" PRIu32 "\n", probecnt, status.ch0_cyc_llen); + str += meta; + sprintf(meta, " level%d = %d\n", probecnt, status.ch0_level_valid); + str += meta; + sprintf(meta, " plevel%d = %d\n", probecnt, status.ch0_plevel); + str += meta; + sprintf(meta, " low%d = %" PRIu32 "\n", probecnt, status.ch0_low_level); + str += meta; + sprintf(meta, " high%d = %" PRIu32 "\n", probecnt, status.ch0_high_level); + str += meta; + sprintf(meta, " rlen%d = %" PRIu32 "\n", probecnt, status.ch0_cyc_rlen); + str += meta; + sprintf(meta, " flen%d = %" PRIu32 "\n", probecnt, status.ch0_cyc_flen); + str += meta; + sprintf(meta, " rms%d = %" PRIu64 "\n", probecnt, status.ch0_acc_square); + str += meta; + sprintf(meta, " mean%d = %" PRIu32 "\n", probecnt, status.ch0_acc_mean); + str += meta; + } + else + { + sprintf(meta, " period%d = %" PRIu32 "\n", probecnt, status.ch1_cyc_tlen); + str += meta; + sprintf(meta, " pcnt%d = %" PRIu32 "\n", probecnt, status.ch1_cyc_cnt); + str += meta; + sprintf(meta, " max%d = %d\n", probecnt, status.ch1_max); + str += meta; + sprintf(meta, " min%d = %d\n", probecnt, status.ch1_min); + str += meta; + sprintf(meta, " plen%d = %" PRIu32 "\n", probecnt, status.ch1_cyc_plen); + str += meta; + sprintf(meta, " llen%d = %" PRIu32 "\n", probecnt, status.ch1_cyc_llen); + str += meta; + sprintf(meta, " level%d = %d\n", probecnt, status.ch1_level_valid); + str += meta; + sprintf(meta, " plevel%d = %d\n", probecnt, status.ch1_plevel); + str += meta; + sprintf(meta, " low%d = %" PRIu32 "\n", probecnt, status.ch1_low_level); + str += meta; + sprintf(meta, " high%d = %" PRIu32 "\n", probecnt, status.ch1_high_level); + str += meta; + sprintf(meta, " rlen%d = %" PRIu32 "\n", probecnt, status.ch1_cyc_rlen); + str += meta; + sprintf(meta, " flen%d = %" PRIu32 "\n", probecnt, status.ch1_cyc_flen); + str += meta; + sprintf(meta, " rms%d = %" PRIu64 "\n", probecnt, status.ch1_acc_square); + str += meta; + sprintf(meta, " mean%d = %" PRIu32 "\n", probecnt, status.ch1_acc_mean); + str += meta; + } + } + } + else if (sdi->mode == ANALOG) + { + sprintf(meta, " enable%d = %d\n", probecnt, probe->enabled); + str += meta; + sprintf(meta, " coupling%d = %d\n", probecnt, probe->coupling); + str += meta; + sprintf(meta, " vDiv%d = %" PRIu64 "\n", probecnt, probe->vdiv); + str += meta; + sprintf(meta, " vOffset%d = %d\n", probecnt, probe->hw_offset); + str += meta; + sprintf(meta, " mapUnit%d = %s\n", probecnt, probe->map_unit); + str += meta; + sprintf(meta, " mapMax%d = %lf\n", probecnt, probe->map_max); + str += meta; + sprintf(meta, " mapMin%d = %lf\n", probecnt, probe->map_min); + str += meta; + } + probecnt++; + } + + return true; } +//export as csv file bool StoreSession::export_start() { std::set type_set; - BOOST_FOREACH(const boost::shared_ptr sig, _session.get_signals()) { + for(auto &sig : _session->get_signals()) { assert(sig); - type_set.insert(sig->get_type()); + int _tp = sig->get_type(); + type_set.insert(_tp); } if (type_set.size() > 1) { @@ -528,7 +615,7 @@ bool StoreSession::export_start() return false; } - const boost::shared_ptr snapshot(_session.get_snapshot(*type_set.begin())); + const auto snapshot = _session->get_snapshot(*type_set.begin()); assert(snapshot); // Check we have data if (snapshot->empty()) { @@ -536,75 +623,58 @@ bool StoreSession::export_start() return false; } - const QString DIR_KEY("ExportPath"); - QSettings settings(QApplication::organizationName(), QApplication::applicationName()); - QString default_name = settings.value(DIR_KEY).toString() + "/" + _session.get_device()->name() + "-"; - for (const GSList *l = _session.get_device()->get_dev_mode_list(); - l; l = l->next) { - const sr_dev_mode *mode = (const sr_dev_mode *)l->data; - if (_session.get_device()->dev_inst()->mode == mode->mode) { - default_name += mode->acronym; + if (_file_name == ""){ + _error = tr("No set file name."); + return false; + } + + //set export all data flag + AppConfig &app = AppConfig::Instance(); + int flag = app._appOptions.originalData ? 1 : 0; + sr_set_export_original_data(flag); + + const struct sr_output_module **supportedModules = sr_output_list(); + while (*supportedModules) + { + if (*supportedModules == NULL) + break; + if (!strcmp((*supportedModules)->id, _suffix.toUtf8().data())) + { + _outModule = *supportedModules; break; } + supportedModules++; } - default_name += _session.get_session_time().toString("-yyMMdd-hhmmss"); - // Show the dialog - QList supportedFormats = getSuportedExportFormats(); - QString filter; - for(int i = 0; i < supportedFormats.count();i++){ - filter.append(supportedFormats[i]); - if(i < supportedFormats.count() - 1) - filter.append(";;"); + if (_outModule == NULL) + { + _error = tr("Invalid export format."); } - _file_name = QFileDialog::getSaveFileName( - NULL, tr("Export Data"), default_name,filter,&filter); - if (!_file_name.isEmpty()) { - QFileInfo f(_file_name); - QStringList list = filter.split('.').last().split(')'); - _suffix = list.first(); - if(f.suffix().compare(_suffix)) - _file_name += tr(".") + _suffix; - QDir CurrentDir; - settings.setValue(DIR_KEY, CurrentDir.filePath(_file_name)); - - const struct sr_output_module** supportedModules = sr_output_list(); - while(*supportedModules){ - if(*supportedModules == NULL) - break; - if(!strcmp((*supportedModules)->id, _suffix.toUtf8().data())){ - _outModule = *supportedModules; - break; - } - supportedModules++; - } - - if(_outModule == NULL) { - _error = tr("Invalid export format."); - } else { - _thread = boost::thread(&StoreSession::export_proc, this, snapshot); - return !_has_error; - } + else + { + if (_thread.joinable()) _thread.join(); + _thread = std::thread(&StoreSession::export_proc, this, snapshot); + return !_has_error; } _error.clear(); return false; } -void StoreSession::export_proc(shared_ptr snapshot) +void StoreSession::export_proc(data::Snapshot *snapshot) { assert(snapshot); - shared_ptr logic_snapshot; - shared_ptr analog_snapshot; - shared_ptr dso_snapshot; + data::LogicSnapshot *logic_snapshot = NULL; + data::AnalogSnapshot *analog_snapshot = NULL; + data::DsoSnapshot *dso_snapshot = NULL; int channel_type; - if ((logic_snapshot = boost::dynamic_pointer_cast(snapshot))) { + if ((logic_snapshot = dynamic_cast(snapshot))) { channel_type = SR_CHANNEL_LOGIC; - } else if ((dso_snapshot = boost::dynamic_pointer_cast(snapshot))) { + } else if ((dso_snapshot = dynamic_cast(snapshot))) { channel_type = SR_CHANNEL_DSO; - } else if ((analog_snapshot = boost::dynamic_pointer_cast(snapshot))) { + } else if ((analog_snapshot = dynamic_cast(snapshot))) { channel_type = SR_CHANNEL_ANALOG; } else { _has_error = true; @@ -620,14 +690,15 @@ void StoreSession::export_proc(shared_ptr snapshot) struct sr_output output; output.module = (sr_output_module*) _outModule; - output.sdi = _session.get_device()->dev_inst(); + output.sdi = _session->get_device()->dev_inst(); output.param = NULL; if(_outModule->init) _outModule->init(&output, params); + QFile file(_file_name); file.open(QIODevice::WriteOnly | QIODevice::Text); - QTextStream out(&file); - out.setCodec("UTF-8"); + QTextStream out(&file); + app::set_utf8(out); //out.setGenerateByteOrderMark(true); // UTF-8 without BOM // Meta @@ -635,21 +706,23 @@ void StoreSession::export_proc(shared_ptr snapshot) struct sr_datafeed_packet p; struct sr_datafeed_meta meta; struct sr_config *src; + src = sr_config_new(SR_CONF_SAMPLERATE, - g_variant_new_uint64(_session.cur_snap_samplerate())); + g_variant_new_uint64(_session->cur_snap_samplerate())); meta.config = g_slist_append(NULL, src); + src = sr_config_new(SR_CONF_LIMIT_SAMPLES, g_variant_new_uint64(snapshot->get_sample_count())); meta.config = g_slist_append(meta.config, src); GVariant *gvar; uint8_t bits; - gvar = _session.get_device()->get_config(NULL, NULL, SR_CONF_UNIT_BITS); + gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_UNIT_BITS); if (gvar != NULL) { bits = g_variant_get_byte(gvar); g_variant_unref(gvar); } - gvar = _session.get_device()->get_config(NULL, NULL, SR_CONF_REF_MIN); + gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_REF_MIN); if (gvar != NULL) { src = sr_config_new(SR_CONF_REF_MIN, gvar); g_variant_unref(gvar); @@ -657,7 +730,7 @@ void StoreSession::export_proc(shared_ptr snapshot) src = sr_config_new(SR_CONF_REF_MIN, g_variant_new_uint32(1)); } meta.config = g_slist_append(meta.config, src); - gvar = _session.get_device()->get_config(NULL, NULL, SR_CONF_REF_MAX); + gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_REF_MAX); if (gvar != NULL) { src = sr_config_new(SR_CONF_REF_MAX, gvar); g_variant_unref(gvar); @@ -686,12 +759,13 @@ void StoreSession::export_proc(shared_ptr snapshot) bool sample; std::vector buf_vec; std::vector buf_sample; - for (int blk = 0; !boost::this_thread::interruption_requested() && - blk < blk_num; blk++) { + + for (int blk = 0; !_canceled && blk < blk_num; blk++) { uint64_t buf_sample_num = logic_snapshot->get_block_size(blk) * 8; buf_vec.clear(); buf_sample.clear(); - BOOST_FOREACH(const boost::shared_ptr s, _session.get_signals()) { + + for(auto &s : _session->get_signals()) { int ch_type = s->get_type(); if (ch_type == SR_CHANNEL_LOGIC) { int ch_index = s->get_index(); @@ -707,8 +781,8 @@ void StoreSession::export_proc(shared_ptr snapshot) unsigned int usize = 8192; unsigned int size = usize; struct sr_datafeed_logic lp; - for(uint64_t i = 0; !boost::this_thread::interruption_requested() && - i < buf_sample_num; i+=usize){ + + for(uint64_t i = 0; !_canceled && i < buf_sample_num; i+=usize){ if(buf_sample_num - i < usize) size = buf_sample_num - i; uint8_t *xbuf = (uint8_t *)malloc(size * unitsize); @@ -716,8 +790,9 @@ void StoreSession::export_proc(shared_ptr snapshot) _has_error = true; _error = tr("xbuffer malloc failed."); return; - } + } memset(xbuf, 0, size * unitsize); + for (uint64_t j = 0; j < size; j++) { for (unsigned int k = 0; k < buf_vec.size(); k++) { if (buf_vec[k] == NULL && buf_sample[k]) @@ -726,6 +801,7 @@ void StoreSession::export_proc(shared_ptr snapshot) xbuf[j*unitsize+k/8] += 1 << k%8; } } + lp.data = xbuf; lp.length = size * unitsize; lp.unitsize = unitsize; @@ -733,6 +809,7 @@ void StoreSession::export_proc(shared_ptr snapshot) p.status = SR_PKT_OK; p.payload = &lp; _outModule->receive(&output, &p, &data_out); + if(data_out){ out << QString::fromUtf8((char*) data_out->str); g_string_free(data_out,TRUE); @@ -744,21 +821,25 @@ void StoreSession::export_proc(shared_ptr snapshot) progress_updated(); } } + } else if (channel_type == SR_CHANNEL_DSO) { _unit_count = snapshot->get_sample_count(); unsigned char* datat = (unsigned char*)snapshot->get_data(); unsigned int usize = 8192; unsigned int size = usize; - struct sr_datafeed_dso dp; - for(uint64_t i = 0; !boost::this_thread::interruption_requested() && i < _unit_count; i+=usize){ + struct sr_datafeed_dso dp; + + for(uint64_t i = 0; !_canceled && i < _unit_count; i+=usize){ if(_unit_count - i < usize) size = _unit_count - i; + dp.data = &datat[i*snapshot->get_channel_num()]; dp.num_samples = size; p.type = SR_DF_DSO; p.status = SR_PKT_OK; p.payload = &dp; _outModule->receive(&output, &p, &data_out); + if(data_out){ out << (char*) data_out->str; g_string_free(data_out,TRUE); @@ -767,13 +848,15 @@ void StoreSession::export_proc(shared_ptr snapshot) _units_stored += size; progress_updated(); } + } else if (channel_type == SR_CHANNEL_ANALOG) { _unit_count = snapshot->get_sample_count(); unsigned char* datat = (unsigned char*)snapshot->get_data(); unsigned int usize = 8192; unsigned int size = usize; struct sr_datafeed_analog ap; - for(uint64_t i = 0; !boost::this_thread::interruption_requested() && i < _unit_count; i+=usize){ + + for(uint64_t i = 0; !_canceled && i < _unit_count; i+=usize){ if(_unit_count - i < usize) size = _unit_count - i; ap.data = &datat[i*snapshot->get_channel_num()]; @@ -802,55 +885,34 @@ void StoreSession::export_proc(shared_ptr snapshot) progress_updated(); } -#ifdef ENABLE_DECODE -QString StoreSession::decoders_gen() -{ - QDir dir; - #if QT_VERSION >= 0x050400 - QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); - #else - QString path = QStandardPaths::writableLocation(QStandardPaths::DataLocation); - #endif - if(dir.mkpath(path)) { - dir.cd(path); - - QString file_name = dir.absolutePath() + "/DSView-decoders-XXXXXX"; - QFile sessionFile(file_name); - if (!sessionFile.open(QIODevice::WriteOnly | QIODevice::Text)) { - qDebug("Warning: Couldn't open session file to write!"); - return NULL; - } - QTextStream outStream(&sessionFile); - outStream.setCodec("UTF-8"); - //outStream.setGenerateByteOrderMark(true); // UTF-8 without BOM - - QJsonArray dec_array = json_decoders(); - QJsonDocument sessionDoc(dec_array); - outStream << QString::fromUtf8(sessionDoc.toJson()); - sessionFile.close(); - - return file_name; - } else { - return NULL; - } - + +bool StoreSession::decoders_gen(std::string &str) +{ + QJsonArray dec_array; + if (!json_decoders(dec_array)) + return false; + QJsonDocument sessionDoc(dec_array); + QString data = QString::fromUtf8(sessionDoc.toJson()); + str.append(data.toLatin1().data()); + return true; } -QJsonArray StoreSession::json_decoders() -{ - QJsonArray dec_array; - BOOST_FOREACH(boost::shared_ptr t, _session.get_decode_signals()) { +bool StoreSession::json_decoders(QJsonArray &array) +{ + for(auto &t : _session->get_decode_signals()) { QJsonObject dec_obj; QJsonArray stack_array; QJsonObject show_obj; - const boost::shared_ptr& stack = t->decoder(); - const std::list< boost::shared_ptr >& decoder = stack->stack(); - BOOST_FOREACH(boost::shared_ptr dec, decoder) { + const auto &stack = t->decoder(); + const auto &decoder = stack->stack(); + + for(auto &dec : decoder) { QJsonArray ch_array; const srd_decoder *const d = dec->decoder();; const bool have_probes = (d->channels || d->opt_channels) != 0; + if (have_probes) { - for(std::map::const_iterator i = dec->channels().begin(); + for(auto i = dec->channels().begin(); i != dec->channels().end(); i++) { QJsonObject ch_obj; ch_obj[(*i).first->id] = QJsonValue::fromVariant((*i).second); @@ -859,8 +921,8 @@ QJsonArray StoreSession::json_decoders() } QJsonObject options_obj; - boost::shared_ptr dec_binding( - new prop::binding::DecoderOptions(stack, dec)); + auto dec_binding = new prop::binding::DecoderOptions(stack, dec); + for (GSList *l = d->options; l; l = l->next) { const srd_decoder_option *const opt = @@ -889,7 +951,6 @@ QJsonArray StoreSession::json_decoders() } } - if (have_probes) { dec_obj["id"] = QJsonValue::fromVariant(d->id); dec_obj["channel"] = ch_array; @@ -905,40 +966,51 @@ QJsonArray StoreSession::json_decoders() dec_obj["stacked decoders"] = stack_array; - std::map rows = stack->get_rows_gshow(); - for (std::map::const_iterator i = rows.begin(); - i != rows.end(); i++) { - show_obj[(*i).first.title()] = QJsonValue::fromVariant((*i).second); + auto rows = stack->get_rows_gshow(); + for (auto i = rows.begin(); i != rows.end(); i++) { + pv::data::decode::Row _row = (*i).first; + show_obj[_row.title()] = QJsonValue::fromVariant((*i).second); } dec_obj["show"] = show_obj; - dec_array.push_back(dec_obj); + array.push_back(dec_obj); } - return dec_array; + + return true; } -void StoreSession::load_decoders(dock::ProtocolDock *widget, QJsonArray dec_array) +bool StoreSession::load_decoders(dock::ProtocolDock *widget, QJsonArray dec_array) { - if (_session.get_device()->dev_inst()->mode != LOGIC || - dec_array.empty()) - return; + if (_session->get_device()->dev_inst()->mode != LOGIC || dec_array.empty()) + { + return false; + } + - foreach (const QJsonValue &dec_value, dec_array) { - QJsonObject dec_obj = dec_value.toObject(); - const vector< boost::shared_ptr > pre_dsigs( - _session.get_decode_signals()); + for (const QJsonValue &dec_value : dec_array) { + + QJsonObject dec_obj = dec_value.toObject(); + std::vector &pre_dsigs = _session->get_decode_signals(); + + //set current protocol if (widget->sel_protocol(dec_obj["id"].toString())) - widget->add_protocol(true); - const vector< boost::shared_ptr > aft_dsigs( - _session.get_decode_signals()); + { + widget->add_protocol(true); + } + else{ + continue; //protocol is not exists; + } - if (aft_dsigs.size() > pre_dsigs.size()) { + std::vector &aft_dsigs = _session->get_decode_signals(); + + if (aft_dsigs.size() >= pre_dsigs.size()) { const GSList *l; - boost::shared_ptr new_dsig = aft_dsigs.back(); - const boost::shared_ptr& stack = new_dsig->decoder(); + + auto new_dsig = aft_dsigs.back(); + auto stack = new_dsig->decoder(); if (dec_obj.contains("stacked decoders")) { - foreach(const QJsonValue &value, dec_obj["stacked decoders"].toArray()) { + for(const QJsonValue &value : dec_obj["stacked decoders"].toArray()) { QJsonObject stacked_obj = value.toObject(); GSList *dl = g_slist_copy((GSList*)srd_decoder_list()); @@ -947,8 +1019,7 @@ void StoreSession::load_decoders(dock::ProtocolDock *widget, QJsonArray dec_arra assert(d); if (QString::fromUtf8(d->id) == stacked_obj["id"].toString()) { - stack->push(boost::shared_ptr( - new data::decode::Decoder(d))); + stack->push(new data::decode::Decoder(d)); break; } } @@ -956,8 +1027,9 @@ void StoreSession::load_decoders(dock::ProtocolDock *widget, QJsonArray dec_arra } } - const std::list< boost::shared_ptr >& decoder = stack->stack(); - BOOST_FOREACH(boost::shared_ptr dec, decoder) { + auto &decoder = stack->stack(); + + for(auto &dec : decoder) { const srd_decoder *const d = dec->decoder(); QJsonObject options_obj; @@ -965,9 +1037,9 @@ void StoreSession::load_decoders(dock::ProtocolDock *widget, QJsonArray dec_arra std::map probe_map; // Load the mandatory channels for(l = d->channels; l; l = l->next) { - const struct srd_channel *const pdch = - (struct srd_channel *)l->data; - foreach (const QJsonValue &value, dec_obj["channel"].toArray()) { + const struct srd_channel *const pdch = (struct srd_channel *)l->data; + + for (const QJsonValue &value : dec_obj["channel"].toArray()) { QJsonObject ch_obj = value.toObject(); if (ch_obj.contains(pdch->id)) { probe_map[pdch] = ch_obj[pdch->id].toInt(); @@ -978,9 +1050,9 @@ void StoreSession::load_decoders(dock::ProtocolDock *widget, QJsonArray dec_arra // Load the optional channels for(l = d->opt_channels; l; l = l->next) { - const struct srd_channel *const pdch = - (struct srd_channel *)l->data; - foreach (const QJsonValue &value, dec_obj["channel"].toArray()) { + const struct srd_channel *const pdch = (struct srd_channel *)l->data; + + for (const QJsonValue &value : dec_obj["channel"].toArray()) { QJsonObject ch_obj = value.toObject(); if (ch_obj.contains(pdch->id)) { probe_map[pdch] = ch_obj[pdch->id].toInt(); @@ -991,7 +1063,7 @@ void StoreSession::load_decoders(dock::ProtocolDock *widget, QJsonArray dec_arra dec->set_probes(probe_map); options_obj = dec_obj["options"].toObject(); } else { - foreach(const QJsonValue &value, dec_obj["stacked decoders"].toArray()) { + for(const QJsonValue &value : dec_obj["stacked decoders"].toArray()) { QJsonObject stacked_obj = value.toObject(); if (QString::fromUtf8(d->id) == stacked_obj["id"].toString()) { options_obj = stacked_obj["options"].toObject(); @@ -1044,18 +1116,22 @@ void StoreSession::load_decoders(dock::ProtocolDock *widget, QJsonArray dec_arra if (dec_obj.contains("show")) { QJsonObject show_obj = dec_obj["show"].toObject(); std::map rows = stack->get_rows_gshow(); - for (std::map::const_iterator i = rows.begin(); - i != rows.end(); i++) { - if (show_obj.contains((*i).first.title())) { - stack->set_rows_gshow((*i).first, show_obj[(*i).first.title()].toBool()); + + for (auto i = rows.begin();i != rows.end(); i++) { + QString key = (*i).first.title(); + if (show_obj.contains(key)) { + bool bShow = show_obj[key].toBool(); + const pv::data::decode::Row r = (*i).first; + stack->set_rows_gshow(r, bShow); } } } } } + return true; } -#endif + double StoreSession::get_integer(GVariant *var) { @@ -1083,5 +1159,193 @@ double StoreSession::get_integer(GVariant *var) return val; } +QString StoreSession::MakeSaveFile(bool bDlg) +{ + QString default_name; + + AppConfig &app = AppConfig::Instance(); + if (app._userHistory.saveDir != "") + { + default_name = app._userHistory.saveDir + "/" + _session->get_device()->name() + "-"; + } + else{ + QDir _dir; + QString _root = _dir.home().path(); + default_name = _root + "/" + _session->get_device()->name() + "-"; + } + + for (const GSList *l = _session->get_device()->get_dev_mode_list(); + l; l = l->next) { + const sr_dev_mode *mode = (const sr_dev_mode *)l->data; + if (_session->get_device()->dev_inst()->mode == mode->mode) { + default_name += mode->acronym; + break; + } + } + + default_name += _session->get_session_time().toString("-yyMMdd-hhmmss"); + + // Show the dialog + if (bDlg) + { + default_name = QFileDialog::getSaveFileName( + NULL, + tr("Save File"), + default_name, + tr("DSView Data (*.dsl)")); + + if (default_name.isEmpty()) + { + return ""; //no select file + } + + QString _dir_path = GetDirectoryName(default_name); + + if (_dir_path != app._userHistory.saveDir) + { + app._userHistory.saveDir = _dir_path; + app.SaveHistory(); + } + } + + QFileInfo f(default_name); + if (f.suffix().compare("dsl")) + { + default_name.append(tr(".dsl")); + } + _file_name = default_name; + return default_name; +} + +QString StoreSession::MakeExportFile(bool bDlg) +{ + QString default_name; + AppConfig &app = AppConfig::Instance(); + + if (app._userHistory.exportDir != "") + { + default_name = app._userHistory.exportDir + "/" + _session->get_device()->name() + "-"; + } + else{ + QDir _dir; + QString _root = _dir.home().path(); + default_name = _root + "/" + _session->get_device()->name() + "-"; + } + + for (const GSList *l = _session->get_device()->get_dev_mode_list(); + l; l = l->next) { + const sr_dev_mode *mode = (const sr_dev_mode *)l->data; + if (_session->get_device()->dev_inst()->mode == mode->mode) { + default_name += mode->acronym; + break; + } + } + default_name += _session->get_session_time().toString("-yyMMdd-hhmmss"); + + //ext name + QList supportedFormats = getSuportedExportFormats(); + QString filter; + for(int i = 0; i < supportedFormats.count();i++){ + filter.append(supportedFormats[i]); + if(i < supportedFormats.count() - 1) + filter.append(";;"); + } + + QString selfilter; + if (app._userHistory.exportFormat != ""){ + selfilter.append(app._userHistory.exportFormat); + } + + if (bDlg) + { + default_name = QFileDialog::getSaveFileName( + NULL, + tr("Export Data"), + default_name, + filter, + &selfilter); + + if (default_name == "") + { + return ""; + } + + bool bChange = false; + QString _dir_path = GetDirectoryName(default_name); + if (_dir_path != app._userHistory.exportDir) + { + app._userHistory.exportDir = _dir_path; + bChange = true; + } + if (selfilter != app._userHistory.exportFormat){ + app._userHistory.exportFormat = selfilter; + bChange = true; + } + + if (bChange){ + app.SaveHistory(); + } + } + + QString extName = selfilter; + if (extName == ""){ + extName = filter; + } + + QStringList list = extName.split('.').last().split(')'); + _suffix = list.first(); + + QFileInfo f(default_name); + if(f.suffix().compare(_suffix)){ + default_name += tr(".") + _suffix; + } + + _file_name = default_name; + return default_name; +} + +bool StoreSession::IsLogicDataType() +{ + std::set type_set; + for(auto &sig : _session->get_signals()) { + assert(sig); + type_set.insert(sig->get_type()); + } + + if (type_set.size()){ + int type = *(type_set.begin()); + return type == SR_CHANNEL_LOGIC; + } + + return false; +} + +void StoreSession::MakeChunkName(char *chunk_name, int chunk_num, int index, int type, int version) +{ + chunk_name[0] = 0; + + if (version == 2) + { + const char *type_name = NULL; + type_name = (type == SR_CHANNEL_LOGIC) ? "L" : (type == SR_CHANNEL_DSO) ? "O" + : (type == SR_CHANNEL_ANALOG) ? "A" + : "U"; + snprintf(chunk_name, 15, "%s-%d/%d", type_name, index, chunk_num); + } + else + { + snprintf(chunk_name, 15, "data"); + } +} + +std::string StoreSession::getFileName(QString fileName) +{ +#if defined(_WIN32) + QTextCodec *code = QTextCodec::codecForName("GB2312"); + return code->fromUnicode(fileName).data(); +#else + return _file_name.toUtf8().toStdString(); +#endif +} } // pv diff --git a/DSView/pv/storesession.h b/DSView/pv/storesession.h index 2f369385..882653e9 100755 --- a/DSView/pv/storesession.h +++ b/DSView/pv/storesession.h @@ -24,13 +24,13 @@ #include #include - -#include - +#include #include - #include -#include + +#include "interface/icallbacks.h" + +#include "ZipMaker.h" namespace pv { @@ -52,17 +52,17 @@ private: const static int File_Version = 2; public: - StoreSession(SigSession &session); + StoreSession(SigSession *session); ~StoreSession(); - SigSession& session(); + SigSession* session(); - std::pair progress() const; + std::pair progress(); - const QString& error() const; + const QString& error(); - bool save_start(QString session_file); + bool save_start(); bool export_start(); @@ -71,41 +71,51 @@ public: void cancel(); private: - void save_proc(boost::shared_ptr snapshot); - QString meta_gen(boost::shared_ptr snapshot); - void export_proc(boost::shared_ptr snapshot); - #ifdef ENABLE_DECODE - QString decoders_gen(); - #endif + void save_proc(pv::data::Snapshot *snapshot); + bool meta_gen(data::Snapshot *snapshot, std::string &str); + void export_proc(pv::data::Snapshot *snapshot); + bool decoders_gen(std::string &str); + -public: - #ifdef ENABLE_DECODE - QJsonArray json_decoders(); - void load_decoders(dock::ProtocolDock *widget, QJsonArray dec_array); - #endif +public: + bool json_decoders(QJsonArray &array); + bool load_decoders(dock::ProtocolDock *widget, QJsonArray dec_array); + QString MakeSaveFile(bool bDlg); + QString MakeExportFile(bool bDlg); + + inline QString GetFileName() + { return _file_name;} + + bool IsLogicDataType(); + private: QList getSuportedExportFormats(); double get_integer(GVariant * var); + void MakeChunkName(char *chunk_name, int chunk_num, int index, int type, int version); + std:: string getFileName(QString fileName); signals: void progress_updated(); -private: - QString _file_name; - QString _suffix; - SigSession &_session; +public: + ISessionDataGetter *_sessionDataGetter; - boost::thread _thread; +private: + QString _file_name; + QString _suffix; + SigSession *_session; + + std::thread _thread; const struct sr_output_module* _outModule; - - //mutable boost::mutex _mutex; - uint64_t _units_stored; - uint64_t _unit_count; - bool _has_error; - QString _error; - bool _canceled; + + uint64_t _units_stored; + uint64_t _unit_count; + bool _has_error; + QString _error; + volatile bool _canceled; + ZipMaker m_zipDoc; }; } // pv diff --git a/DSView/pv/toolbars/filebar.cpp b/DSView/pv/toolbars/filebar.cpp index a61939e6..81996711 100755 --- a/DSView/pv/toolbars/filebar.cpp +++ b/DSView/pv/toolbars/filebar.cpp @@ -19,24 +19,21 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#include -#include -#include - +#include #include -#include +#include +#include #include #include "filebar.h" -#include "../device/devinst.h" -#include "../dialogs/dsmessagebox.h" - -#include +#include "../device/devinst.h" +#include "../ui/msgbox.h" +#include "../config/appconfig.h" namespace pv { namespace toolbars { -FileBar::FileBar(SigSession &session, QWidget *parent) : +FileBar::FileBar(SigSession *session, QWidget *parent) : QToolBar("File Bar", parent), _enable(true), _session(session), @@ -47,16 +44,14 @@ FileBar::FileBar(SigSession &session, QWidget *parent) : _action_load = new QAction(this); _action_load->setObjectName(QString::fromUtf8("actionLoad")); - connect(_action_load, SIGNAL(triggered()), this, SLOT(on_actionLoad_triggered())); - + _action_store = new QAction(this); _action_store->setObjectName(QString::fromUtf8("actionStore")); - connect(_action_store, SIGNAL(triggered()), this, SLOT(on_actionStore_triggered())); - + _action_default = new QAction(this); _action_default->setObjectName(QString::fromUtf8("actionDefault")); - connect(_action_default, SIGNAL(triggered()), this, SLOT(on_actionDefault_triggered())); - + + //second level menu _menu_session = new QMenu(this); _menu_session->setObjectName(QString::fromUtf8("menuSession")); _menu_session->addAction(_action_load); @@ -65,21 +60,16 @@ FileBar::FileBar(SigSession &session, QWidget *parent) : _action_open = new QAction(this); _action_open->setObjectName(QString::fromUtf8("actionOpen")); - connect(_action_open, SIGNAL(triggered()), this, SLOT(on_actionOpen_triggered())); - + _action_save = new QAction(this); _action_save->setObjectName(QString::fromUtf8("actionSave")); - connect(_action_save, SIGNAL(triggered()), this, SIGNAL(on_save())); - + _action_export = new QAction(this); _action_export->setObjectName(QString::fromUtf8("actionExport")); - connect(_action_export, SIGNAL(triggered()), this, SIGNAL(on_export())); - - + _action_capture = new QAction(this); _action_capture->setObjectName(QString::fromUtf8("actionCapture")); - connect(_action_capture, SIGNAL(triggered()), this, SLOT(on_actionCapture_triggered())); - + _file_button.setToolButtonStyle(Qt::ToolButtonTextUnderIcon); _file_button.setPopupMode(QToolButton::InstantPopup); @@ -93,6 +83,14 @@ FileBar::FileBar(SigSession &session, QWidget *parent) : addWidget(&_file_button); retranslateUi(); + + connect(_action_load, SIGNAL(triggered()), this, SLOT(on_actionLoad_triggered())); + connect(_action_store, SIGNAL(triggered()), this, SLOT(on_actionStore_triggered())); + connect(_action_default, SIGNAL(triggered()), this, SLOT(on_actionDefault_triggered())); + connect(_action_open, SIGNAL(triggered()), this, SLOT(on_actionOpen_triggered())); + connect(_action_save, SIGNAL(triggered()), this, SIGNAL(sig_save())); + connect(_action_export, SIGNAL(triggered()), this, SIGNAL(sig_export())); + connect(_action_capture, SIGNAL(triggered()), this, SLOT(on_actionCapture_triggered())); } void FileBar::changeEvent(QEvent *event) @@ -107,7 +105,7 @@ void FileBar::changeEvent(QEvent *event) void FileBar::retranslateUi() { _file_button.setText(tr("File")); - _menu_session->setTitle(tr("Settings")); + _menu_session->setTitle(tr("Con&fig...")); //load,save session file _action_load->setText(tr("&Load...")); _action_store->setText(tr("S&tore...")); _action_default->setText(tr("&Default...")); @@ -119,7 +117,7 @@ void FileBar::retranslateUi() void FileBar::reStyle() { - QString iconPath = ":/icons/" + qApp->property("Style").toString(); + QString iconPath = GetIconPath(); _action_load->setIcon(QIcon(iconPath+"/open.svg")); _action_store->setIcon(QIcon(iconPath+"/save.svg")); @@ -134,16 +132,24 @@ void FileBar::reStyle() void FileBar::on_actionOpen_triggered() { - const QString DIR_KEY("OpenPath"); - QSettings settings(QApplication::organizationName(), QApplication::applicationName()); + //open data file + AppConfig &app = AppConfig::Instance(); + // Show the dialog const QString file_name = QFileDialog::getOpenFileName( - this, tr("Open File"), settings.value(DIR_KEY).toString(), tr( - "DSView Data (*.dsl)")); - if (!file_name.isEmpty()) { - QDir CurrentDir; - settings.setValue(DIR_KEY, CurrentDir.absoluteFilePath(file_name)); - load_file(file_name); + this, + tr("Open File"), + app._userHistory.openDir, + tr("DSView Data (*.dsl)")); + + if (!file_name.isEmpty()) { + QString fname = GetDirectoryName(file_name); + if (fname != app._userHistory.openDir){ + app._userHistory.openDir = fname; + app.SaveHistory(); + } + + sig_load_file(file_name); } } @@ -157,52 +163,45 @@ void FileBar::session_error( void FileBar::show_session_error( const QString text, const QString info_text) -{ - dialogs::DSMessageBox msg(this); - msg.mBox()->setText(text); - msg.mBox()->setInformativeText(info_text); - msg.mBox()->setStandardButtons(QMessageBox::Ok); - msg.mBox()->setIcon(QMessageBox::Warning); - msg.exec(); +{ + (void)text; + MsgBox::Show(NULL, info_text.toStdString().c_str(), this); } void FileBar::on_actionLoad_triggered() -{ - const QString DIR_KEY("SessionLoadPath"); - QSettings settings(QApplication::organizationName(), QApplication::applicationName()); - // Show the dialog +{ + //load session file + AppConfig &app = AppConfig::Instance(); + const QString file_name = QFileDialog::getOpenFileName( - this, tr("Open Session"), settings.value(DIR_KEY).toString(), tr( - "DSView Session (*.dsc)")); + this, + tr("Open Session"), + app._userHistory.sessionDir, + tr("DSView Session (*.dsc)")); + if (!file_name.isEmpty()) { - QDir CurrentDir; - settings.setValue(DIR_KEY, CurrentDir.absoluteFilePath(file_name)); - load_session(file_name); + QString fname = GetDirectoryName(file_name); + if (fname != app._userHistory.sessionDir){ + app._userHistory.sessionDir = fname; + app.SaveHistory(); + } + + sig_load_session(file_name); } } void FileBar::on_actionDefault_triggered() -{ -#ifdef Q_OS_LINUX - QDir dir(DS_RES_PATH); -#else - QDir dir(QCoreApplication::applicationDirPath()); - assert(dir.cd("res")); -#endif - if (!dir.exists()) { - dialogs::DSMessageBox msg(this); - msg.mBox()->setText(tr("Session Load")); - msg.mBox()->setInformativeText(tr("Cannot find default session file for this device!")); - msg.mBox()->setStandardButtons(QMessageBox::Ok); - msg.mBox()->setIcon(QMessageBox::Warning); - msg.exec(); - return; +{ + QDir dir(GetResourceDir()); + if (!dir.exists()) { + MsgBox::Show(NULL, "Cannot find default session file for this device!", this); + return; } - QString driver_name = _session.get_device()->name(); - QString mode_name = QString::number(_session.get_device()->dev_inst()->mode); - int language = QLocale::English; - GVariant *gvar_tmp = _session.get_device()->get_config(NULL, NULL, SR_CONF_LANGUAGE); + QString driver_name = _session->get_device()->name(); + QString mode_name = QString::number(_session->get_device()->dev_inst()->mode); + int language = LAN_EN; + GVariant *gvar_tmp = _session->get_device()->get_config(NULL, NULL, SR_CONF_LANGUAGE); if (gvar_tmp != NULL) { language = g_variant_get_int16(gvar_tmp); g_variant_unref(gvar_tmp); @@ -210,23 +209,33 @@ void FileBar::on_actionDefault_triggered() QString file_name = dir.absolutePath() + "/" + driver_name + mode_name + ".def"+QString::number(language)+".dsc"; if (!file_name.isEmpty()) - load_session(file_name); + sig_load_session(file_name); } void FileBar::on_actionStore_triggered() { - const QString DIR_KEY("SessionStorePath"); - QSettings settings(QApplication::organizationName(), QApplication::applicationName()); + //store session file + + AppConfig &app = AppConfig::Instance(); + QString file_name = QFileDialog::getSaveFileName( - this, tr("Save Session"), settings.value(DIR_KEY).toString(), + this, + tr("Save Session"), + app._userHistory.sessionDir, tr("DSView Session (*.dsc)")); + if (!file_name.isEmpty()) { QFileInfo f(file_name); if(f.suffix().compare("dsc")) file_name.append(tr(".dsc")); - QDir CurrentDir; - settings.setValue(DIR_KEY, CurrentDir.absoluteFilePath(file_name)); - store_session(file_name); + + QString fname = GetDirectoryName(file_name); + if (fname != app._userHistory.sessionDir){ + app._userHistory.sessionDir = fname; + app.SaveHistory(); + } + + sig_store_session(file_name); } } @@ -234,7 +243,7 @@ void FileBar::on_actionCapture_triggered() { _file_button.close(); QCoreApplication::sendPostedEvents(); - QTimer::singleShot(100, this, SIGNAL(on_screenShot())); + QTimer::singleShot(100, this, SIGNAL(sig_screenShot())); } void FileBar::enable_toggle(bool enable) diff --git a/DSView/pv/toolbars/filebar.h b/DSView/pv/toolbars/filebar.h index 3696fab5..32cbbe81 100755 --- a/DSView/pv/toolbars/filebar.h +++ b/DSView/pv/toolbars/filebar.h @@ -33,12 +33,14 @@ namespace pv { namespace toolbars { +//toolbar button,referenced by MainWindow +//TODO: load session file, sorte session, load log data file, sorte data, export data class FileBar : public QToolBar { Q_OBJECT public: - explicit FileBar(SigSession &session, QWidget *parent = 0); + explicit FileBar(SigSession *session, QWidget *parent = 0); void enable_toggle(bool enable); @@ -55,12 +57,12 @@ private: const QString text, const QString info_text); signals: - void load_file(QString); - void on_save(); - void on_export(); - void on_screenShot(); - void load_session(QString); - void store_session(QString); + void sig_load_file(QString); + void sig_save(); + void sig_export(); + void sig_screenShot(); //post screen capture event message + void sig_load_session(QString); //post load session event message + void sig_store_session(QString); //post store session event message private slots: void on_actionLoad_triggered(); @@ -71,13 +73,13 @@ private slots: private: bool _enable; - SigSession& _session; + SigSession* _session; QToolButton _file_button; QMenu *_menu; - QMenu *_menu_session; + QMenu *_menu_session; //when the hardware device is connected,it will be enable QAction *_action_load; QAction *_action_store; QAction *_action_default; diff --git a/DSView/pv/toolbars/logobar.cpp b/DSView/pv/toolbars/logobar.cpp index 0904c12b..3914d9f0 100755 --- a/DSView/pv/toolbars/logobar.cpp +++ b/DSView/pv/toolbars/logobar.cpp @@ -20,28 +20,32 @@ */ #include -#include + #include -#include -#include +#include #include #include +#include +#include #include "logobar.h" #include "../dialogs/about.h" #include "../dialogs/dsmessagebox.h" +#include "../config/appconfig.h" namespace pv { namespace toolbars { -LogoBar::LogoBar(SigSession &session, QWidget *parent) : +LogoBar::LogoBar(SigSession *session, QWidget *parent) : QToolBar("File Bar", parent), _enable(true), _connected(false), _session(session), _logo_button(this) { + _mainForm = NULL; + setMovable(false); setContentsMargins(0,0,0,0); @@ -69,7 +73,7 @@ LogoBar::LogoBar(SigSession &session, QWidget *parent) : _manual = new QAction(this); _manual->setObjectName(QString::fromUtf8("actionManual")); _logo_button.addAction(_manual); - connect(_manual, SIGNAL(triggered()), this, SIGNAL(openDoc())); + connect(_manual, SIGNAL(triggered()), this, SIGNAL(sig_open_doc())); _issue = new QAction(this); _issue->setObjectName(QString::fromUtf8("actionManual")); @@ -116,7 +120,8 @@ void LogoBar::retranslateUi() _manual->setText(tr("&Manual")); _issue->setText(tr("&Bug Report")); - if (qApp->property("Language") == QLocale::Chinese) + AppConfig &app = AppConfig::Instance(); + if (app._frameOptions.language == LAN_CN) _language->setIcon(QIcon(":/icons/Chinese.svg")); else _language->setIcon(QIcon(":/icons/English.svg")); @@ -124,7 +129,7 @@ void LogoBar::retranslateUi() void LogoBar::reStyle() { - QString iconPath = ":/icons/" + qApp->property("Style").toString(); + QString iconPath = GetIconPath(); _about->setIcon(QIcon(iconPath+"/about.svg")); _manual->setIcon(QIcon(iconPath+"/manual.svg")); @@ -138,7 +143,7 @@ void LogoBar::reStyle() void LogoBar::dsl_connected(bool conn) { _connected = conn; - QString iconPath = ":/icons/" + qApp->property("Style").toString(); + QString iconPath = GetIconPath(); if (_connected) _logo_button.setIcon(QIcon(iconPath+"/logo_color.svg")); else @@ -168,14 +173,17 @@ void LogoBar::on_actionEn_triggered() { _language->setIcon(QIcon::fromTheme("file", QIcon(":/icons/English.svg"))); - setLanguage(QLocale::English); + + assert(_mainForm); + _mainForm->switchLanguage(LAN_EN); } void LogoBar::on_actionCn_triggered() { _language->setIcon(QIcon::fromTheme("file", QIcon(":/icons/Chinese.svg"))); - setLanguage(QLocale::Chinese); + assert(_mainForm); + _mainForm->switchLanguage(LAN_CN); } void LogoBar::on_actionAbout_triggered() @@ -185,22 +193,14 @@ void LogoBar::on_actionAbout_triggered() } void LogoBar::on_actionManual_triggered() -{ - #ifndef Q_OS_LINUX - QDir dir(QCoreApplication::applicationDirPath()); - #else - QDir dir(DS_RES_PATH); - dir.cdUp(); - #endif - QDesktopServices::openUrl( - QUrl("file:///"+dir.absolutePath() + "/ug.pdf")); +{ + QDir dir(GetAppDataDir()); + QDesktopServices::openUrl( QUrl("file:///"+dir.absolutePath() + "/ug.pdf")); } void LogoBar::on_actionIssue_triggered() { - QDir dir(QCoreApplication::applicationDirPath()); - QDesktopServices::openUrl( - QUrl(QLatin1String("https://github.com/DreamSourceLab/DSView/issues"))); + QDesktopServices::openUrl(QUrl(QLatin1String("https://github.com/DreamSourceLab/DSView/issues"))); } void LogoBar::enable_toggle(bool enable) diff --git a/DSView/pv/toolbars/logobar.h b/DSView/pv/toolbars/logobar.h index caf686c5..a3f8982b 100755 --- a/DSView/pv/toolbars/logobar.h +++ b/DSView/pv/toolbars/logobar.h @@ -27,25 +27,33 @@ #include #include #include +#include #include "../sigsession.h" +#include "../interface/uicallback.h" -#include namespace pv { namespace toolbars { +//The tool button for help,is a ui class,referenced by MainWindow +//TODO: switch language,submit bug descript, class LogoBar : public QToolBar { Q_OBJECT public: - explicit LogoBar(SigSession &session, QWidget *parent = 0); + explicit LogoBar(SigSession *session, QWidget *parent = 0); void enable_toggle(bool enable); + //show the hardware device conneted status with logo picture void dsl_connected(bool conn); + inline void set_mainform_callback(IMainForm *callback){ + _mainForm = callback; + } + private: void changeEvent(QEvent *event); void retranslateUi(); @@ -56,9 +64,9 @@ private: void show_session_error( const QString text, const QString info_text); -signals: - void setLanguage(int language); - void openDoc(); +signals: + //post event message to open user help document, MainWindow class receive it + void sig_open_doc(); private slots: void on_actionEn_triggered(); @@ -70,7 +78,7 @@ private slots: private: bool _enable; bool _connected; - SigSession& _session; + SigSession* _session; QToolButton _logo_button; @@ -83,6 +91,7 @@ private: QAction *_about; QAction *_manual; QAction *_issue; + IMainForm *_mainForm; }; } // namespace toolbars diff --git a/DSView/pv/toolbars/samplingbar.cpp b/DSView/pv/toolbars/samplingbar.cpp index 7a06a71d..753eeb92 100755 --- a/DSView/pv/toolbars/samplingbar.cpp +++ b/DSView/pv/toolbars/samplingbar.cpp @@ -20,17 +20,14 @@ */ #include "samplingbar.h" +#include "../extdef.h" -#include -#include -#include -#include - +#include #include #include #include #include -#include +#include #include "../devicemanager.h" #include "../device/devinst.h" @@ -39,21 +36,23 @@ #include "../dialogs/dsmessagebox.h" #include "../view/dsosignal.h" #include "../dialogs/interval.h" +#include "../config/appconfig.h" + -using namespace boost; -using boost::shared_ptr; using std::map; using std::max; using std::min; using std::string; +using namespace pv::device; + namespace pv { namespace toolbars { const QString SamplingBar::RLEString = tr("(RLE)"); const QString SamplingBar::DIVString = tr(" / div"); -SamplingBar::SamplingBar(SigSession &session, QWidget *parent) : +SamplingBar::SamplingBar(SigSession *session, QWidget *parent) : QToolBar("Sampling Bar", parent), _session(session), _enable(true), @@ -73,34 +72,18 @@ SamplingBar::SamplingBar(SigSession &session, QWidget *parent) : { setMovable(false); setContentsMargins(0,0,0,0); - layout()->setMargin(0); layout()->setSpacing(0); - - connect(&_device_selector, SIGNAL(currentIndexChanged (int)), - this, SLOT(on_device_selected())); - connect(&_configure_button, SIGNAL(clicked()), - this, SLOT(on_configure())); - connect(&_run_stop_button, SIGNAL(clicked()), - this, SLOT(on_run_stop()), Qt::DirectConnection); - connect(&_instant_button, SIGNAL(clicked()), - this, SLOT(on_instant_stop())); - + _mode_button.setPopupMode(QToolButton::InstantPopup); - _device_selector.setSizeAdjustPolicy(QComboBox::AdjustToContents); - _sample_rate.setSizeAdjustPolicy(QComboBox::AdjustToContents); - _sample_count.setSizeAdjustPolicy(QComboBox::AdjustToContents); + _device_selector.setSizeAdjustPolicy(DsComboBox::AdjustToContents); + _sample_rate.setSizeAdjustPolicy(DsComboBox::AdjustToContents); + _sample_count.setSizeAdjustPolicy(DsComboBox::AdjustToContents); _device_selector.setMaximumWidth(ComboBoxMaxWidth); - - connect(&_sample_count, SIGNAL(currentIndexChanged(int)), - this, SLOT(on_samplecount_sel(int))); - + //_run_stop_button.setToolButtonStyle(Qt::ToolButtonTextBesideIcon); _run_stop_button.setObjectName(tr("run_stop_button")); - - connect(&_sample_rate, SIGNAL(currentIndexChanged(int)), - this, SLOT(on_samplerate_sel(int))); - + QWidget *leftMargin = new QWidget(this); leftMargin->setFixedWidth(4); addWidget(leftMargin); @@ -116,10 +99,8 @@ SamplingBar::SamplingBar(SigSession &session, QWidget *parent) : addWidget(&_sample_rate); _action_single = new QAction(this); - connect(_action_single, SIGNAL(triggered()), this, SLOT(on_mode())); _action_repeat = new QAction(this); - connect(_action_repeat, SIGNAL(triggered()), this, SLOT(on_mode())); _mode_menu = new QMenu(this); _mode_menu->addAction(_action_single); @@ -136,6 +117,15 @@ SamplingBar::SamplingBar(SigSession &session, QWidget *parent) : set_sampling(false); //retranslateUi(); + + connect(&_device_selector, SIGNAL(currentIndexChanged (int)), this, SLOT(on_device_selected())); + connect(&_configure_button, SIGNAL(clicked()),this, SLOT(on_configure())); + connect(&_run_stop_button, SIGNAL(clicked()),this, SLOT(on_run_stop()), Qt::DirectConnection); + connect(&_instant_button, SIGNAL(clicked()), this, SLOT(on_instant_stop())); + connect(&_sample_count, SIGNAL(currentIndexChanged(int)), this, SLOT(on_samplecount_sel(int))); + connect(_action_single, SIGNAL(triggered()), this, SLOT(on_mode())); + connect(_action_repeat, SIGNAL(triggered()), this, SLOT(on_mode())); + connect(&_sample_rate, SIGNAL(currentIndexChanged(int)), this, SLOT(on_samplerate_sel(int))); } void SamplingBar::changeEvent(QEvent *event) @@ -149,7 +139,7 @@ void SamplingBar::changeEvent(QEvent *event) void SamplingBar::retranslateUi() { - shared_ptr dev_inst = get_selected_device(); + DevInst *dev_inst = get_selected_device(); if (dev_inst && dev_inst->dev_inst()) { if (dev_inst->name().contains("virtual-demo")) _device_type.setText(tr("Demo")); @@ -172,17 +162,18 @@ void SamplingBar::retranslateUi() } _configure_button.setText(tr("Options")); _mode_button.setText(tr("Mode")); + + sr_dev_inst *dev_c = _session->get_dev_inst_c(); + if (_instant) { - if (_session.get_device() && - _session.get_device()->dev_inst()->mode == DSO) + if (dev_c && dev_c->mode == DSO) _instant_button.setText(_sampling ? tr("Stop") : tr("Single")); else _instant_button.setText(_sampling ? tr("Stop") : tr("Instant")); _run_stop_button.setText(tr("Start")); } else { _run_stop_button.setText(_sampling ? tr("Stop") : tr("Start")); - if (_session.get_device() && - _session.get_device()->dev_inst()->mode == DSO) + if (dev_c && dev_c->mode == DSO) _instant_button.setText(tr("Single")); else _instant_button.setText(tr("Instant")); @@ -194,7 +185,7 @@ void SamplingBar::retranslateUi() void SamplingBar::reStyle() { - shared_ptr dev_inst = get_selected_device(); + DevInst *dev_inst = get_selected_device(); if (dev_inst && dev_inst->dev_inst()) { if (dev_inst->name().contains("virtual-demo")) _device_type.setIcon(QIcon(":/icons/demo.svg")); @@ -215,10 +206,10 @@ void SamplingBar::reStyle() } } - if (!qApp->property("Style").isNull()) { - QString iconPath = ":/icons/" + qApp->property("Style").toString(); + if (true) { + QString iconPath = GetIconPath(); _configure_button.setIcon(QIcon(iconPath+"/params.svg")); - _mode_button.setIcon(_session.get_run_mode() == pv::SigSession::Single ? QIcon(iconPath+"/modes.svg") : + _mode_button.setIcon(_session->get_run_mode() == pv::SigSession::Single ? QIcon(iconPath+"/modes.svg") : QIcon(iconPath+"/moder.svg")); _run_stop_button.setIcon(_sampling ? QIcon(iconPath+"/stop.svg") : QIcon(iconPath+"/start.svg")); @@ -228,9 +219,7 @@ void SamplingBar::reStyle() } } -void SamplingBar::set_device_list( - const std::list< shared_ptr > &devices, - shared_ptr selected) +void SamplingBar::set_device_list(const std::list &devices, DevInst *selected) { int selected_index = -1; @@ -241,7 +230,7 @@ void SamplingBar::set_device_list( _device_selector.clear(); _device_selector_map.clear(); - BOOST_FOREACH (shared_ptr dev_inst, devices) { + for (DevInst *dev_inst : devices) { assert(dev_inst); const QString title = dev_inst->format_device_title(); const void *id = dev_inst->get_id(); @@ -267,36 +256,35 @@ void SamplingBar::set_device_list( _updating_device_selector = false; } -shared_ptr SamplingBar::get_selected_device() const +DevInst* SamplingBar::get_selected_device() { const int index = _device_selector.currentIndex(); if (index < 0) - return shared_ptr(); + return NULL; const void *const id = _device_selector.itemData(index).value(); assert(id); - map >:: - const_iterator iter = _device_selector_map.find(id); - if (iter == _device_selector_map.end()) - return shared_ptr(); + auto it = _device_selector_map.find(id); + if (it == _device_selector_map.end()) + return NULL; - return shared_ptr((*iter).second); + return (*it).second; } void SamplingBar::on_configure() { - hide_calibration(); + sig_hide_calibration(); int ret; - shared_ptr dev_inst = get_selected_device(); + DevInst *dev_inst = get_selected_device(); assert(dev_inst); pv::dialogs::DeviceOptions dlg(this, dev_inst); ret = dlg.exec(); if (ret == QDialog::Accepted) { - device_updated(); + sig_device_updated(); update_sample_rate_selector(); GVariant* gvar; @@ -316,7 +304,7 @@ void SamplingBar::on_configure() bool cali = g_variant_get_boolean(gvar); g_variant_unref(gvar); if (cali) { - show_calibration(); + sig_show_calibration(); return; } } @@ -340,51 +328,55 @@ void SamplingBar::on_configure() void SamplingBar::zero_adj() { - boost::shared_ptr dsoSig; - BOOST_FOREACH(const boost::shared_ptr s, _session.get_signals()) + view::DsoSignal *dsoSig = NULL; + + for(auto &s : _session->get_signals()) { - if ((dsoSig = dynamic_pointer_cast(s))) + if ((dsoSig = dynamic_cast(s))) dsoSig->set_enable(true); } + const int index_back = _sample_count.currentIndex(); int i = 0; + for (i = 0; i < _sample_count.count(); i++) if (_sample_count.itemData(i).value() == ZeroTimeBase) break; + _sample_count.setCurrentIndex(i); commit_hori_res(); - run_stop(); + sig_run_stop(); pv::dialogs::WaitingDialog wait(this, _session, SR_CONF_ZERO); if (wait.start() == QDialog::Rejected) { - BOOST_FOREACH(const boost::shared_ptr s, _session.get_signals()) + for(auto &s : _session->get_signals()) { - if ((dsoSig = dynamic_pointer_cast(s))) + if ((dsoSig = dynamic_cast(s))) dsoSig->commit_settings(); } } - if (_session.get_capture_state() == pv::SigSession::Running) + if (_session->get_capture_state() == pv::SigSession::Running) on_run_stop(); _sample_count.setCurrentIndex(index_back); commit_hori_res(); } -bool SamplingBar::get_sampling() const +bool SamplingBar::get_sampling() { return _sampling; } -bool SamplingBar::get_instant() const +bool SamplingBar::get_instant() { return _instant; } void SamplingBar::set_sampling(bool sampling) { - lock_guard lock(_sampling_mutex); + std::lock_guard lock(_sampling_mutex); _sampling = sampling; if (!sampling) { @@ -401,14 +393,14 @@ void SamplingBar::set_sampling(bool sampling) _configure_button.setEnabled(!sampling); _device_selector.setEnabled(!sampling); - if (!qApp->property("Style").isNull()) { - QString iconPath = ":/icons/" + qApp->property("Style").toString(); + if (true) { + QString iconPath = GetIconPath(); if (_instant) { _instant_button.setIcon(sampling ? QIcon(iconPath+"/stop.svg") : QIcon(iconPath+"/single.svg")); } else { _run_stop_button.setIcon(sampling ? QIcon(iconPath+"/stop.svg") : QIcon(iconPath+"/start.svg")); } - _mode_button.setIcon(_session.get_run_mode() == pv::SigSession::Single ? QIcon(iconPath+"/modes.svg") : + _mode_button.setIcon(_session->get_run_mode() == pv::SigSession::Single ? QIcon(iconPath+"/modes.svg") : QIcon(iconPath+"/moder.svg")); } @@ -439,7 +431,7 @@ void SamplingBar::update_sample_rate_selector() disconnect(&_sample_rate, SIGNAL(currentIndexChanged(int)), this, SLOT(on_samplerate_sel(int))); - const shared_ptr dev_inst = get_selected_device(); + DevInst *dev_inst = get_selected_device(); if (!dev_inst) return; @@ -513,7 +505,7 @@ void SamplingBar::update_sample_rate_selector_value() void SamplingBar::on_samplerate_sel(int index) { (void)index; - const shared_ptr dev_inst = get_selected_device(); + DevInst *dev_inst = get_selected_device(); if (dev_inst->dev_inst()->mode != DSO) update_sample_count_selector(); } @@ -539,7 +531,7 @@ void SamplingBar::update_sample_count_selector() assert(!_updating_sample_count); _updating_sample_count = true; - const shared_ptr dev_inst = get_selected_device(); + DevInst *dev_inst = get_selected_device(); GVariant* gvar = dev_inst->get_config(NULL, NULL, SR_CONF_STREAM); if (gvar != NULL) { stream_mode = g_variant_get_boolean(gvar); @@ -555,7 +547,7 @@ void SamplingBar::update_sample_count_selector() #if defined(__x86_64__) || defined(_M_X64) sw_depth = LogicMaxSWDepth64; #elif defined(__i386) || defined(_M_IX86) - int ch_num = _session.get_ch_num(SR_CHANNEL_LOGIC); + int ch_num = _session->get_ch_num(SR_CHANNEL_LOGIC); if (ch_num <= 0) sw_depth = LogicMaxSWDepth32; else @@ -672,7 +664,7 @@ void SamplingBar::update_sample_count_selector_value() GVariant* gvar; double duration; - const shared_ptr dev_inst = get_selected_device(); + DevInst *dev_inst = get_selected_device(); if (dev_inst->dev_inst()->mode == DSO) { gvar = dev_inst->get_config(NULL, NULL, SR_CONF_TIMEBASE); if (gvar != NULL) { @@ -715,10 +707,10 @@ void SamplingBar::on_samplecount_sel(int index) { (void)index; - const shared_ptr dev_inst = get_selected_device(); + DevInst *dev_inst = get_selected_device(); if (dev_inst->dev_inst()->mode == DSO) commit_hori_res(); - duration_changed(); + sig_duration_changed(); } double SamplingBar::get_hori_res() @@ -729,8 +721,6 @@ double SamplingBar::get_hori_res() double SamplingBar::hori_knob(int dir) { double hori_res = -1; - disconnect(&_sample_count, SIGNAL(currentIndexChanged(int)), - this, SLOT(on_samplecount_sel(int))); if (0 == dir) { hori_res = commit_hori_res(); @@ -742,6 +732,9 @@ double SamplingBar::hori_knob(int dir) hori_res = commit_hori_res(); } + disconnect(&_sample_count, SIGNAL(currentIndexChanged(int)), + this, SLOT(on_samplecount_sel(int))); + connect(&_sample_count, SIGNAL(currentIndexChanged(int)), this, SLOT(on_samplecount_sel(int))); @@ -753,7 +746,7 @@ double SamplingBar::commit_hori_res() const double hori_res = _sample_count.itemData( _sample_count.currentIndex()).value(); - const shared_ptr dev_inst = get_selected_device(); + DevInst *dev_inst = get_selected_device(); const uint64_t sample_limit = dev_inst->get_sample_limit(); GVariant* gvar; uint64_t max_sample_rate; @@ -769,7 +762,7 @@ double SamplingBar::commit_hori_res() const uint64_t sample_rate = min((uint64_t)(sample_limit * SR_SEC(1) / (hori_res * DS_CONF_DSO_HDIVS)), (uint64_t)(max_sample_rate / - (_session.get_ch_num(SR_CHANNEL_DSO) ? _session.get_ch_num(SR_CHANNEL_DSO) : 1))); + (_session->get_ch_num(SR_CHANNEL_DSO) ? _session->get_ch_num(SR_CHANNEL_DSO) : 1))); set_sample_rate(sample_rate); dev_inst->set_config(NULL, NULL, SR_CONF_TIMEBASE, @@ -781,7 +774,7 @@ double SamplingBar::commit_hori_res() void SamplingBar::commit_settings() { bool test = false; - const shared_ptr dev_inst = get_selected_device(); + DevInst *dev_inst = get_selected_device(); if (dev_inst && dev_inst->owner()) { GVariant *gvar = dev_inst->get_config(NULL, NULL, SR_CONF_TEST); if (gvar != NULL) { @@ -799,7 +792,7 @@ void SamplingBar::commit_settings() const uint64_t sample_rate = _sample_rate.itemData( _sample_rate.currentIndex()).value(); - const shared_ptr dev_inst = get_selected_device(); + DevInst *dev_inst = get_selected_device(); if (dev_inst) { if (sample_rate != dev_inst->get_sample_rate()) dev_inst->set_config(NULL, NULL, @@ -822,18 +815,21 @@ void SamplingBar::commit_settings() } } +//start or stop capture void SamplingBar::on_run_stop() { - if (get_sampling() || _session.isRepeating()) { - _session.exit_capture(); + if (get_sampling() || _session->isRepeating()) { + _session->exit_capture(); } else { enable_run_stop(false); enable_instant(false); commit_settings(); _instant = false; - const shared_ptr dev_inst = get_selected_device(); + + DevInst *dev_inst = get_selected_device(); if (!dev_inst) return; + if (dev_inst->dev_inst()->mode == DSO) { GVariant* gvar = dev_inst->get_config(NULL, NULL, SR_CONF_ZERO); if (gvar != NULL) { @@ -858,16 +854,17 @@ void SamplingBar::on_run_stop() } } } - run_stop(); + + sig_run_stop(); } } void SamplingBar::on_instant_stop() { if (get_sampling()) { - _session.set_repeating(false); + _session->set_repeating(false); bool wait_upload = false; - if (_session.get_run_mode() != SigSession::Repetitive) { + if (_session->get_run_mode() != SigSession::Repetitive) { GVariant *gvar = get_selected_device()->get_config(NULL, NULL, SR_CONF_WAIT_UPLOAD); if (gvar != NULL) { wait_upload = g_variant_get_boolean(gvar); @@ -875,27 +872,32 @@ void SamplingBar::on_instant_stop() } } if (!wait_upload) { - _session.stop_capture(); - _session.capture_state_changed(SigSession::Stopped); + _session->stop_capture(); + _session->capture_state_changed(SigSession::Stopped); } } else { enable_run_stop(false); enable_instant(false); commit_settings(); _instant = true; - const shared_ptr dev_inst = get_selected_device(); + + DevInst *dev_inst = get_selected_device(); + if (!dev_inst) return; + if (dev_inst->dev_inst()->mode == DSO) { GVariant* gvar = dev_inst->get_config(NULL, NULL, SR_CONF_ZERO); + if (gvar != NULL) { bool zero = g_variant_get_boolean(gvar); g_variant_unref(gvar); + if (zero) { dialogs::DSMessageBox msg(this); msg.mBox()->setText(tr("Auto Calibration")); msg.mBox()->setInformativeText(tr("Auto Calibration program will be started. Don't connect any probes. It can take a while!")); - //msg.mBox()->setStandardButtons(QMessageBox::Ok); + msg.mBox()->addButton(tr("Ok"), QMessageBox::AcceptRole); msg.mBox()->addButton(tr("Skip"), QMessageBox::RejectRole); msg.mBox()->setIcon(QMessageBox::Warning); @@ -910,7 +912,8 @@ void SamplingBar::on_instant_stop() } } } - instant_stop(); + + sig_instant_stop(); } } @@ -919,25 +922,25 @@ void SamplingBar::on_device_selected() if (_updating_device_selector) return; - _session.stop_capture(); - _session.session_save(); + _session->stop_capture(); + _session->session_save(); - const shared_ptr dev_inst = get_selected_device(); + DevInst* dev_inst = get_selected_device(); if (!dev_inst) return; try { - _session.set_device(dev_inst); + _session->set_device(dev_inst); } catch(QString e) { show_session_error(tr("Failed to select ") + dev_inst->dev_inst()->model, e); } - device_selected(); + sig_device_selected(); } void SamplingBar::enable_toggle(bool enable) { bool test = false; - const shared_ptr dev_inst = get_selected_device(); + DevInst *dev_inst = get_selected_device(); if (dev_inst && dev_inst->owner()) { GVariant *gvar = dev_inst->get_config(NULL, NULL, SR_CONF_TEST); if (gvar != NULL) { @@ -956,7 +959,7 @@ void SamplingBar::enable_toggle(bool enable) _sample_rate.setDisabled(true); } - if (_session.get_device()->name() == "virtual-session") { + if (_session->get_device()->name() == "virtual-session") { _sample_count.setDisabled(true); _sample_rate.setDisabled(true); } @@ -985,24 +988,24 @@ void SamplingBar::show_session_error( void SamplingBar::reload() { - QString iconPath = ":/icons/" + qApp->property("Style").toString(); - if (_session.get_device()->dev_inst()->mode == LOGIC) { - if (_session.get_device()->name() == "virtual-session") { + QString iconPath = GetIconPath(); + if (_session->get_device()->dev_inst()->mode == LOGIC) { + if (_session->get_device()->name() == "virtual-session") { _mode_action->setVisible(false); } else { - _mode_button.setIcon(_session.get_run_mode() == pv::SigSession::Single ? QIcon(iconPath+"/modes.svg") : + _mode_button.setIcon(_session->get_run_mode() == pv::SigSession::Single ? QIcon(iconPath+"/modes.svg") : QIcon(iconPath+"/moder.svg")); _mode_action->setVisible(true); } _run_stop_action->setVisible(true); _instant_action->setVisible(true); enable_toggle(true); - } else if (_session.get_device()->dev_inst()->mode == ANALOG) { + } else if (_session->get_device()->dev_inst()->mode == ANALOG) { _mode_action->setVisible(false); _run_stop_action->setVisible(true); _instant_action->setVisible(false); enable_toggle(true); - } else if (_session.get_device()->dev_inst()->mode == DSO) { + } else if (_session->get_device()->dev_inst()->mode == DSO) { _mode_action->setVisible(false); _run_stop_action->setVisible(true); _instant_action->setVisible(true); @@ -1016,16 +1019,16 @@ void SamplingBar::reload() void SamplingBar::on_mode() { - QString iconPath = ":/icons/" + qApp->property("Style").toString(); + QString iconPath = GetIconPath(); QAction *act = qobject_cast(sender()); if (act == _action_single) { _mode_button.setIcon(QIcon(iconPath+"/modes.svg")); - _session.set_run_mode(pv::SigSession::Single); + _session->set_run_mode(pv::SigSession::Single); } else if (act == _action_repeat) { _mode_button.setIcon(QIcon(iconPath+"/moder.svg")); pv::dialogs::Interval interval_dlg(_session, this); interval_dlg.exec(); - _session.set_run_mode(pv::SigSession::Repetitive); + _session->set_run_mode(pv::SigSession::Repetitive); } } diff --git a/DSView/pv/toolbars/samplingbar.h b/DSView/pv/toolbars/samplingbar.h index 567eff1f..81ca3c8c 100755 --- a/DSView/pv/toolbars/samplingbar.h +++ b/DSView/pv/toolbars/samplingbar.h @@ -19,7 +19,6 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - #ifndef DSVIEW_PV_TOOLBARS_SAMPLINGBAR_H #define DSVIEW_PV_TOOLBARS_SAMPLINGBAR_H @@ -28,146 +27,137 @@ #include #include #include - -#include - -#include + #include #include #include #include +#include "../ui/dscombobox.h" struct st_dev_inst; class QAction; -namespace pv { +namespace pv +{ + class SigSession; -class SigSession; + namespace device + { + class DevInst; + } -namespace device { -class DevInst; -} + namespace dialogs + { + class deviceoptions; + class Calibration; + } -namespace dialogs { -class deviceoptions; -class Calibration; -} + namespace toolbars + { -namespace toolbars { + class SamplingBar : public QToolBar + { + Q_OBJECT -class SamplingBar : public QToolBar -{ - Q_OBJECT + private: + static const int ComboBoxMaxWidth = 200; + static const int RefreshShort = 500; + static const uint64_t LogicMaxSWDepth64 = SR_GB(16); + static const uint64_t LogicMaxSWDepth32 = SR_GB(8); + + static const uint64_t AnalogMaxSWDepth = SR_Mn(100); + static const QString RLEString; + static const QString DIVString; + static const uint64_t ZeroTimeBase = SR_US(2); -private: - static const int ComboBoxMaxWidth = 200; - static const int RefreshShort = 500; - static const uint64_t LogicMaxSWDepth64 = SR_GB(16); - static const uint64_t LogicMaxSWDepth32 = SR_GB(8); - static const uint64_t AnalogMaxSWDepth = SR_Mn(100); - static const QString RLEString; - static const QString DIVString; - static const uint64_t ZeroTimeBase = SR_US(2); + public: + SamplingBar(SigSession *session, QWidget *parent); + void set_device_list(const std::list &devices, DevInst* selected); + DevInst *get_selected_device(); + void update_sample_rate_selector(); -public: - SamplingBar(SigSession &session, QWidget *parent); + void set_sampling(bool sampling); + bool get_sampling(); + bool get_instant(); - void set_device_list(const std::list< boost::shared_ptr > &devices, - boost::shared_ptr selected); + void enable_toggle(bool enable); + void enable_run_stop(bool enable); + void enable_instant(bool enable); - boost::shared_ptr get_selected_device() const; + double hori_knob(int dir); + double commit_hori_res(); + double get_hori_res(); - void update_sample_rate_selector(); + public slots: + void set_sample_rate(uint64_t sample_rate); - void set_sampling(bool sampling); - bool get_sampling() const; - bool get_instant() const; + signals: + void sig_run_stop(); + void sig_instant_stop(); + void sig_device_selected(); + void sig_device_updated(); + void sig_duration_changed(); + void sig_show_calibration(); + void sig_hide_calibration(); - void enable_toggle(bool enable); + private: + void changeEvent(QEvent *event); + void retranslateUi(); + void reStyle(); - void enable_run_stop(bool enable); + void update_sample_rate_selector_value(); + void update_sample_count_selector(); + void update_sample_count_selector_value(); + void commit_settings(); + void setting_adj(); - void enable_instant(bool enable); + private slots: + void on_mode(); + void on_run_stop(); + void on_instant_stop(); + void on_device_selected(); + void on_samplerate_sel(int index); + void on_samplecount_sel(int index); - double hori_knob(int dir); - double commit_hori_res(); - double get_hori_res(); + void show_session_error( + const QString text, const QString info_text); -public slots: - void set_sample_rate(uint64_t sample_rate); + public slots: + void on_configure(); + void zero_adj(); + void reload(); -signals: - void run_stop(); - void instant_stop(); - void device_selected(); - void device_updated(); - void duration_changed(); - void show_calibration(); - void hide_calibration(); + private: + SigSession *_session; + mutable std::mutex _sampling_mutex; + bool _enable; + bool _sampling; -private: - void changeEvent(QEvent *event); - void retranslateUi(); - void reStyle(); + QToolButton _device_type; + DsComboBox _device_selector; + std::map _device_selector_map; + bool _updating_device_selector; - void update_sample_rate_selector_value(); - void update_sample_count_selector(); - void update_sample_count_selector_value(); - void commit_settings(); - void setting_adj(); + QToolButton _configure_button; + DsComboBox _sample_count; + DsComboBox _sample_rate; + bool _updating_sample_rate; + bool _updating_sample_count; -private slots: - void on_mode(); - void on_run_stop(); - void on_instant_stop(); - void on_device_selected(); - void on_samplerate_sel(int index); - void on_samplecount_sel(int index); + QToolButton _run_stop_button; + QToolButton _instant_button; + QAction *_run_stop_action; + QAction *_instant_action; + QAction *_mode_action; + QToolButton _mode_button; - void show_session_error( - const QString text, const QString info_text); + QMenu *_mode_menu; + QAction *_action_repeat; + QAction *_action_single; + bool _instant; + }; -public slots: - void on_configure(); - void zero_adj(); - void reload(); - -private: - SigSession &_session; - - mutable boost::recursive_mutex _sampling_mutex; - bool _enable; - bool _sampling; - - QToolButton _device_type; - - QComboBox _device_selector; - std::map > - _device_selector_map; - bool _updating_device_selector; - - QToolButton _configure_button; - - QComboBox _sample_count; - QComboBox _sample_rate; - bool _updating_sample_rate; - bool _updating_sample_count; - - QToolButton _run_stop_button; - QToolButton _instant_button; - QAction* _run_stop_action; - QAction* _instant_action; - - QAction* _mode_action; - QToolButton _mode_button; - QMenu *_mode_menu; - QAction *_action_repeat; - QAction *_action_single; - - bool _instant; -}; - -} // namespace toolbars + } // namespace toolbars } // namespace pv #endif // DSVIEW_PV_TOOLBARS_SAMPLINGBAR_H diff --git a/DSView/pv/toolbars/titlebar.cpp b/DSView/pv/toolbars/titlebar.cpp index ed595925..aae90e15 100755 --- a/DSView/pv/toolbars/titlebar.cpp +++ b/DSView/pv/toolbars/titlebar.cpp @@ -25,29 +25,41 @@ #include #include #include +#include #include -#include -#include +#include #include #include +#include +#include "../config/appconfig.h" +#include "../dsvdef.h" namespace pv { namespace toolbars { TitleBar::TitleBar(bool top, QWidget *parent, bool hasClose) : - QWidget(parent), - _moving(false), - _isTop(top), - _hasClose(hasClose) -{ + QWidget(parent) +{ + _minimizeButton = NULL; + _maximizeButton = NULL; + _closeButton = NULL; + _moving = false; + _parent = parent; + _isTop = top; + _hasClose = hasClose; + _title = NULL; + + assert(parent); + setObjectName("TitleBar"); setContentsMargins(0,0,0,0); - setFixedHeight(32); + setFixedHeight(32); + + QHBoxLayout *lay1 = new QHBoxLayout(this); _title = new QLabel(this); - QHBoxLayout *hbox = new QHBoxLayout(this); - hbox->addWidget(_title); + lay1->addWidget(_title); if (_isTop) { _minimizeButton = new QToolButton(this); @@ -55,29 +67,36 @@ TitleBar::TitleBar(bool top, QWidget *parent, bool hasClose) : _maximizeButton = new QToolButton(this); _maximizeButton->setObjectName("MaximizeButton"); - hbox->addWidget(_minimizeButton); - hbox->addWidget(_maximizeButton); + lay1->addWidget(_minimizeButton); + lay1->addWidget(_maximizeButton); - connect(this, SIGNAL( normalShow() ), parent, SLOT(showNormal() ) ); - connect(this, SIGNAL( maximizedShow() ), parent, SLOT(showMaximized() ) ); - connect(_minimizeButton, SIGNAL( clicked() ), parent, SLOT(showMinimized() ) ); - connect(_maximizeButton, SIGNAL( clicked() ), this, SLOT(showMaxRestore() ) ); + connect(this, SIGNAL(normalShow()), parent, SLOT(showNormal())); + connect(this, SIGNAL( maximizedShow()), parent, SLOT(showMaximized())); + connect(_minimizeButton, SIGNAL( clicked()), parent, SLOT(showMinimized())); + connect(_maximizeButton, SIGNAL( clicked()), this, SLOT(showMaxRestore())); } if (_isTop || _hasClose) { _closeButton= new QToolButton(this); _closeButton->setObjectName("CloseButton"); - hbox->addWidget(_closeButton); - connect(_closeButton, SIGNAL( clicked() ), parent, SLOT(close() ) ); + lay1->addWidget(_closeButton); + connect(_closeButton, SIGNAL( clicked()), parent, SLOT(close())); } - hbox->insertStretch(0, 500); - hbox->insertStretch(2, 500); - hbox->setMargin(0); - hbox->setSpacing(0); + lay1->insertStretch(0, 500); + lay1->insertStretch(2, 500); + lay1->setContentsMargins(0,0,0,0); + lay1->setSpacing(0); + setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); } +TitleBar::~TitleBar(){ + DESTROY_QT_OBJECT(_minimizeButton); + DESTROY_QT_OBJECT(_maximizeButton); + DESTROY_QT_OBJECT(_closeButton); +} + void TitleBar::changeEvent(QEvent *event) { if (event->type() == QEvent::StyleChange) @@ -87,7 +106,7 @@ void TitleBar::changeEvent(QEvent *event) void TitleBar::reStyle() { - QString iconPath = ":/icons/" + qApp->property("Style").toString(); + QString iconPath = GetIconPath(); if (_isTop) { _minimizeButton->setIcon(QIcon(iconPath+"/minimize.svg")); @@ -101,7 +120,8 @@ void TitleBar::reStyle() } void TitleBar::paintEvent(QPaintEvent *event) -{ +{ + //draw logo icon QStyleOption o; o.initFrom(this); QPainter p(this); @@ -138,20 +158,15 @@ void TitleBar::setTitle(QString title) { _title->setText(title); } - -QPoint TitleBar::get_startPos() const -{ - return _startPos; -} - -QString TitleBar::title() const + +QString TitleBar::title() { return _title->text(); } void TitleBar::showMaxRestore() { - QString iconPath = ":/icons/" + qApp->property("Style").toString(); + QString iconPath = GetIconPath(); if (parentWidget()->isMaximized()) { _maximizeButton->setIcon(QIcon(iconPath+"/maximize.svg")); normalShow(); @@ -163,42 +178,57 @@ void TitleBar::showMaxRestore() void TitleBar::setRestoreButton(bool max) { - QString iconPath = ":/icons/" + qApp->property("Style").toString(); + QString iconPath = GetIconPath(); if (!max) { _maximizeButton->setIcon(QIcon(iconPath+"/maximize.svg")); } else { _maximizeButton->setIcon(QIcon(iconPath+"/restore.svg")); } } - + void TitleBar::mousePressEvent(QMouseEvent* event) -{ - if(event->button() == Qt::LeftButton && !parentWidget()->isMaximized()) { - _moving = true; - _startPos = mapToParent(event->pos()); - } +{ + if(event->button() == Qt::LeftButton && !parentWidget()->isMaximized()) + { + int x = event->pos().x(); + int y = event->pos().y(); + bool bTopWidow = app::is_app_top_window(_parent); + bool bClick = (x >= 6 && y >= 5 && x <= width() - 6); //top window need resize hit check + + if (!bTopWidow || bClick ){ + _moving = true; + _startPos = event->globalPos() - _parent->frameGeometry().topLeft(); + event->accept(); + return; + } + } + QWidget::mousePressEvent(event); } void TitleBar::mouseMoveEvent(QMouseEvent *event) -{ - if(_moving && event->buttons().testFlag(Qt::LeftButton)) { - parentWidget()->move(event->globalPos() - _startPos); - } +{ + if(_moving){ + _parent->move(event->globalPos() - _startPos); + event->accept(); + return; + } + QWidget::mouseMoveEvent(event); } void TitleBar::mouseReleaseEvent(QMouseEvent* event) { - if(event->button() == Qt::LeftButton) { - _moving = false; - } + _moving = false; + QWidget::mouseReleaseEvent(event); } void TitleBar::mouseDoubleClickEvent(QMouseEvent *event) { - if (_isTop) - showMaxRestore(); + if (_isTop){ + showMaxRestore(); + } QWidget::mouseDoubleClickEvent(event); } + } // namespace toolbars } // namespace pv diff --git a/DSView/pv/toolbars/titlebar.h b/DSView/pv/toolbars/titlebar.h index d48878b1..47d937fa 100755 --- a/DSView/pv/toolbars/titlebar.h +++ b/DSView/pv/toolbars/titlebar.h @@ -23,8 +23,10 @@ #define DSVIEW_PV_TOOLBARS_TITLEBAR_H #include -class QLabel; + class QToolButton; +class QHBoxLayout; +class QLabel; namespace pv { namespace toolbars { @@ -35,9 +37,10 @@ class TitleBar : public QWidget public: TitleBar(bool top, QWidget *parent, bool hasClose = false); - void setTitle(QString title); - QPoint get_startPos() const; - QString title() const; + ~TitleBar(); + + void setTitle(QString title); + QString title(); private: void changeEvent(QEvent *event); @@ -50,6 +53,7 @@ signals: public slots: void showMaxRestore(); void setRestoreButton(bool max); + inline bool IsMoving(){return _moving;} protected: void paintEvent(QPaintEvent *event); @@ -57,16 +61,18 @@ protected: void mouseMoveEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); void mouseDoubleClickEvent(QMouseEvent *event); - - QLabel *_title; + + QToolButton *_minimizeButton; QToolButton *_maximizeButton; QToolButton *_closeButton; - + QLabel *_title; + bool _moving; bool _isTop; bool _hasClose; QPoint _startPos; + QWidget *_parent; }; } // namespace toolbars diff --git a/DSView/pv/toolbars/trigbar.cpp b/DSView/pv/toolbars/trigbar.cpp index c4344027..202eb572 100755 --- a/DSView/pv/toolbars/trigbar.cpp +++ b/DSView/pv/toolbars/trigbar.cpp @@ -20,16 +20,19 @@ */ #include "trigbar.h" + +#include +#include +#include + #include "../sigsession.h" #include "../device/devinst.h" #include "../dialogs/fftoptions.h" #include "../dialogs/lissajousoptions.h" #include "../dialogs/mathoptions.h" #include "../view/trace.h" - -#include -#include -#include +#include "../dialogs/applicationpardlg.h" +#include "../config/appconfig.h" namespace pv { namespace toolbars { @@ -37,44 +40,35 @@ namespace toolbars { const QString TrigBar::DARK_STYLE = "dark"; const QString TrigBar::LIGHT_STYLE = "light"; -TrigBar::TrigBar(SigSession &session, QWidget *parent) : +TrigBar::TrigBar(SigSession *session, QWidget *parent) : QToolBar("Trig Bar", parent), _session(session), - _enable(true), + _trig_button(this), _protocol_button(this), _measure_button(this), _search_button(this), _function_button(this), - _display_button(this) + _setting_button(this) { + _enable = true; + setMovable(false); setContentsMargins(0,0,0,0); - - connect(&_trig_button, SIGNAL(clicked()), - this, SLOT(trigger_clicked())); - connect(&_protocol_button, SIGNAL(clicked()), - this, SLOT(protocol_clicked())); - connect(&_measure_button, SIGNAL(clicked()), - this, SLOT(measure_clicked())); - connect(&_search_button, SIGNAL(clicked()), - this, SLOT(search_clicked())); - + _trig_button.setCheckable(true); -#ifdef ENABLE_DECODE + _protocol_button.setCheckable(true); -#endif + _measure_button.setCheckable(true); _search_button.setCheckable(true); _action_fft = new QAction(this); _action_fft->setObjectName(QString::fromUtf8("actionFft")); - connect(_action_fft, SIGNAL(triggered()), this, SLOT(on_actionFft_triggered())); - + _action_math = new QAction(this); _action_math->setObjectName(QString::fromUtf8("actionMath")); - connect(_action_math, SIGNAL(triggered()), this, SLOT(on_actionMath_triggered())); - + _function_menu = new QMenu(this); _function_menu->setContentsMargins(0,0,0,0); _function_menu->addAction(_action_fft); @@ -84,34 +78,36 @@ TrigBar::TrigBar(SigSession &session, QWidget *parent) : _action_lissajous = new QAction(this); _action_lissajous->setObjectName(QString::fromUtf8("actionLissajous")); - connect(_action_lissajous, SIGNAL(triggered()), this, SLOT(on_actionLissajous_triggered())); - + _dark_style = new QAction(this); _dark_style->setObjectName(QString::fromUtf8("actionDark")); - connect(_dark_style, SIGNAL(triggered()), this, SLOT(on_actionDark_triggered())); - + _light_style = new QAction(this); _light_style->setObjectName(QString::fromUtf8("actionLight")); - connect(_light_style, SIGNAL(triggered()), this, SLOT(on_actionLight_triggered())); - + _themes = new QMenu(this); _themes->setObjectName(QString::fromUtf8("menuThemes")); _themes->addAction(_light_style); _themes->addAction(_dark_style); + _appParam_action = new QAction(this); + _display_menu = new QMenu(this); _display_menu->setContentsMargins(0,0,0,0); + + _display_menu->addAction(_appParam_action); + _display_menu->addAction(_action_lissajous); _display_menu->addMenu(_themes); - _display_menu->addAction(_action_lissajous); - _display_button.setPopupMode(QToolButton::InstantPopup); - _display_button.setMenu(_display_menu); + + _setting_button.setPopupMode(QToolButton::InstantPopup); + _setting_button.setMenu(_display_menu); _trig_button.setToolButtonStyle(Qt::ToolButtonTextUnderIcon); _protocol_button.setToolButtonStyle(Qt::ToolButtonTextUnderIcon); _measure_button.setToolButtonStyle(Qt::ToolButtonTextUnderIcon); _search_button.setToolButtonStyle(Qt::ToolButtonTextUnderIcon); _function_button.setToolButtonStyle(Qt::ToolButtonTextUnderIcon); - _display_button.setToolButtonStyle(Qt::ToolButtonTextUnderIcon); + _setting_button.setToolButtonStyle(Qt::ToolButtonTextUnderIcon); _protocol_button.setContentsMargins(0,0,0,0); @@ -119,10 +115,22 @@ TrigBar::TrigBar(SigSession &session, QWidget *parent) : _protocol_action = addWidget(&_protocol_button); _measure_action = addWidget(&_measure_button); _search_action = addWidget(&_search_button); - _function_action = addWidget(&_function_button); - _display_action = addWidget(&_display_button); - + _function_action = addWidget(&_function_button); + _display_action = addWidget(&_setting_button); //must be created + retranslateUi(); + + connect(&_trig_button, SIGNAL(clicked()),this, SLOT(trigger_clicked())); + connect(&_protocol_button, SIGNAL(clicked()),this, SLOT(protocol_clicked())); + connect(&_measure_button, SIGNAL(clicked()),this, SLOT(measure_clicked())); + connect(&_search_button, SIGNAL(clicked()), this, SLOT(search_clicked())); + + connect(_action_fft, SIGNAL(triggered()), this, SLOT(on_actionFft_triggered())); + connect(_action_math, SIGNAL(triggered()), this, SLOT(on_actionMath_triggered())); + connect(_action_lissajous, SIGNAL(triggered()), this, SLOT(on_actionLissajous_triggered())); + connect(_dark_style, SIGNAL(triggered()), this, SLOT(on_actionDark_triggered())); + connect(_light_style, SIGNAL(triggered()), this, SLOT(on_actionLight_triggered())); + connect(_appParam_action, SIGNAL(triggered()), this, SLOT(on_application_param())); } void TrigBar::changeEvent(QEvent *event) @@ -141,43 +149,61 @@ void TrigBar::retranslateUi() _measure_button.setText(tr("Measure")); _search_button.setText(tr("Search")); _function_button.setText(tr("Function")); - _display_button.setText(tr("Display")); + _setting_button.setText(tr("Setting")); + + _action_lissajous->setText(tr("&Lissajous")); + _themes->setTitle(tr("Themes")); _dark_style->setText(tr("Dark")); _light_style->setText(tr("Light")); - _action_lissajous->setText(tr("&Lissajous")); _action_fft->setText(tr("FFT")); _action_math->setText(tr("Math")); + + _appParam_action->setText(tr("Application")); } void TrigBar::reStyle() { - QString iconPath = ":/icons/" + qApp->property("Style").toString(); + QString iconPath = GetIconPath(); _trig_button.setIcon(QIcon(iconPath+"/trigger.svg")); _protocol_button.setIcon(QIcon(iconPath+"/protocol.svg")); _measure_button.setIcon(QIcon(iconPath+"/measure.svg")); _search_button.setIcon(QIcon(iconPath+"/search-bar.svg")); _function_button.setIcon(QIcon(iconPath+"/function.svg")); - _display_button.setIcon(QIcon(iconPath+"/display.svg")); + _setting_button.setIcon(QIcon(iconPath+"/display.svg")); _action_fft->setIcon(QIcon(iconPath+"/fft.svg")); _action_math->setIcon(QIcon(iconPath+"/math.svg")); _action_lissajous->setIcon(QIcon(iconPath+"/lissajous.svg")); _dark_style->setIcon(QIcon(iconPath+"/dark.svg")); _light_style->setIcon(QIcon(iconPath+"/light.svg")); - _themes->setIcon(QIcon(iconPath+"/"+qApp->property("Style").toString()+".svg")); + + _appParam_action->setIcon(QIcon(iconPath+"/params.svg")); + + AppConfig &app = AppConfig::Instance(); + + QString icon_fname = iconPath +"/"+ app._frameOptions.style +".svg"; + _themes->setIcon(QIcon(icon_fname)); } void TrigBar::protocol_clicked() -{ - on_protocol(_protocol_button.isChecked()); +{ + sig_protocol(_protocol_button.isChecked()); + + DockOptions *opt = getDockOptions(); + opt->decodeDoc = _protocol_button.isChecked(); + AppConfig::Instance().SaveFrame(); } void TrigBar::trigger_clicked() { - on_trigger(_trig_button.isChecked()); + sig_trigger(_trig_button.isChecked()); + + DockOptions *opt = getDockOptions(); + opt->triggerDoc = _trig_button.isChecked(); + AppConfig::Instance().SaveFrame(); } void TrigBar::update_trig_btn(bool checked) @@ -202,12 +228,20 @@ void TrigBar::update_search_btn(bool checked) void TrigBar::measure_clicked() { - on_measure(_measure_button.isChecked()); + sig_measure(_measure_button.isChecked()); + + DockOptions *opt = getDockOptions(); + opt->measureDoc = _measure_button.isChecked(); + AppConfig::Instance().SaveFrame(); } void TrigBar::search_clicked() { - on_search(_search_button.isChecked()); + sig_search(_search_button.isChecked()); + + DockOptions *opt = getDockOptions(); + opt->searchDoc = _search_button.isChecked(); + AppConfig::Instance().SaveFrame(); } void TrigBar::enable_toggle(bool enable) @@ -217,7 +251,7 @@ void TrigBar::enable_toggle(bool enable) _measure_button.setDisabled(!enable); _search_button.setDisabled(!enable); _function_button.setDisabled(!enable); - _display_button.setDisabled(!enable); + _setting_button.setDisabled(!enable); } void TrigBar::enable_protocol(bool enable) @@ -229,40 +263,43 @@ void TrigBar::close_all() { if (_trig_button.isChecked()) { _trig_button.setChecked(false); - on_trigger(false); + sig_trigger(false); } if (_protocol_button.isChecked()) { _protocol_button.setChecked(false); - on_protocol(false); + sig_protocol(false); } if (_measure_button.isChecked()) { _measure_button.setChecked(false); - on_measure(false); + sig_measure(false); } if(_search_button.isChecked()) { _search_button.setChecked(false); - on_search(false); + sig_search(false); } } void TrigBar::reload() { close_all(); - if (_session.get_device()->dev_inst()->mode == LOGIC) { + + if (_session->get_device()->dev_inst()->mode == LOGIC) { _trig_action->setVisible(true); _protocol_action->setVisible(true); _measure_action->setVisible(true); _search_action->setVisible(true); _function_action->setVisible(false); _action_lissajous->setVisible(false); - } else if (_session.get_device()->dev_inst()->mode == ANALOG) { + + } else if (_session->get_device()->dev_inst()->mode == ANALOG) { _trig_action->setVisible(false); _protocol_action->setVisible(false); _measure_action->setVisible(true); _search_action->setVisible(false); _function_action->setVisible(false); _action_lissajous->setVisible(false); - } else if (_session.get_device()->dev_inst()->mode == DSO) { + + } else if (_session->get_device()->dev_inst()->mode == DSO) { _trig_action->setVisible(true); _protocol_action->setVisible(false); _measure_action->setVisible(true); @@ -270,6 +307,7 @@ void TrigBar::reload() _function_action->setVisible(true); _action_lissajous->setVisible(true); } + enable_toggle(true); update(); } @@ -288,14 +326,16 @@ void TrigBar::on_actionMath_triggered() void TrigBar::on_actionDark_triggered() { - setTheme(DARK_STYLE); - _themes->setIcon(QIcon(":/icons/"+DARK_STYLE+"/"+DARK_STYLE+".svg")); + sig_setTheme(DARK_STYLE); + QString icon = GetIconPath() + "/" + DARK_STYLE + ".svg"; + _themes->setIcon(QIcon(icon)); } void TrigBar::on_actionLight_triggered() { - setTheme(LIGHT_STYLE); - _themes->setIcon(QIcon(":/icons/"+LIGHT_STYLE+"/"+LIGHT_STYLE+".svg")); + sig_setTheme(LIGHT_STYLE); + QString icon = GetIconPath() + "/" + LIGHT_STYLE +".svg"; + _themes->setIcon(QIcon(icon)); } void TrigBar::on_actionLissajous_triggered() @@ -304,5 +344,52 @@ void TrigBar::on_actionLissajous_triggered() lissajous_dlg.exec(); } + void TrigBar::on_application_param(){ + // pv::dialogs::MathOptions math_dlg(_session, this); math_dlg.exec(); return; + + pv::dialogs::ApplicationParamDlg dlg; + dlg.ShowDlg(this); + } + + +void TrigBar::restore_status() +{ + DockOptions *opt = getDockOptions(); + int mode = _session->get_device()->dev_inst()->mode; + + if (opt->decodeDoc){ + _protocol_button.setChecked(true); + sig_protocol(true); + } + + if (opt->triggerDoc){ + _trig_button.setChecked(true); + sig_trigger(true); + } + + if (opt->measureDoc){ + _measure_button.setChecked(true); + sig_measure(true); + } + + if (opt->searchDoc){ + _search_button.setChecked(true); + sig_search(true); + } +} + + DockOptions* TrigBar::getDockOptions() + { + AppConfig &app = AppConfig::Instance(); + int mode = _session->get_device()->dev_inst()->mode; + + if (mode == LOGIC) + return &app._frameOptions._logicDock; + else if (mode == DSO) + return &app._frameOptions._dsoDock; + else + return &app._frameOptions._analogDock; + } + } // namespace toolbars } // namespace pv diff --git a/DSView/pv/toolbars/trigbar.h b/DSView/pv/toolbars/trigbar.h index 6a86218f..68f6c219 100755 --- a/DSView/pv/toolbars/trigbar.h +++ b/DSView/pv/toolbars/trigbar.h @@ -28,12 +28,16 @@ #include #include +class DockOptions; + namespace pv { class SigSession; namespace toolbars { +//boolbar, referenced by MainWindow +//TODO:show the property panel about protocol\trigger class TrigBar : public QToolBar { Q_OBJECT @@ -43,7 +47,7 @@ protected: static const QString LIGHT_STYLE; public: - explicit TrigBar(SigSession &session, QWidget *parent = 0); + explicit TrigBar(SigSession *session, QWidget *parent = 0); void enable_toggle(bool enable); void enable_protocol(bool enable); @@ -54,14 +58,15 @@ private: void changeEvent(QEvent *event); void retranslateUi(); void reStyle(); + DockOptions* getDockOptions(); signals: - void setTheme(QString style); - void on_protocol(bool visible); - void on_trigger(bool visible); - void on_measure(bool visible); - void on_search(bool visible); - void show_lissajous(bool visible); + void sig_setTheme(QString style); + void sig_protocol(bool visible); //post decode button click event,to show or hide protocol property panel + void sig_trigger(bool visible); //post decode button click event,to show or hide trigger property panel + void sig_measure(bool visible);//post decode button click event,to show or hide measure property panel + void sig_search(bool visible); + void sig_show_lissajous(bool visible); private slots: void on_actionDark_triggered(); @@ -81,32 +86,37 @@ public slots: void on_actionFft_triggered(); void on_actionMath_triggered(); + void on_application_param(); + +public: + void restore_status(); private: - SigSession& _session; - bool _enable; + SigSession *_session; + bool _enable; QToolButton _trig_button; QToolButton _protocol_button; QToolButton _measure_button; QToolButton _search_button; QToolButton _function_button; - QToolButton _display_button; - QAction* _trig_action; - QAction* _protocol_action; - QAction* _measure_action; - QAction* _search_action; - QAction* _function_action; - QAction* _display_action; + QToolButton _setting_button; + QAction *_trig_action; + QAction *_protocol_action; + QAction *_measure_action; + QAction *_search_action; + QAction *_function_action; + QAction *_display_action; - QMenu* _function_menu; - QAction* _action_fft; - QAction* _action_math; + QMenu *_function_menu; + QAction *_action_fft; + QAction *_action_math; - QMenu* _display_menu; - QMenu *_themes; - QAction *_dark_style; - QAction *_light_style; - QAction* _action_lissajous; + QMenu *_display_menu; + QMenu *_themes; + QAction *_appParam_action; + QAction *_dark_style; + QAction *_light_style; + QAction *_action_lissajous; }; } // namespace toolbars diff --git a/DSView/pv/ui/dscombobox.cpp b/DSView/pv/ui/dscombobox.cpp new file mode 100644 index 00000000..f405b6b9 --- /dev/null +++ b/DSView/pv/ui/dscombobox.cpp @@ -0,0 +1,72 @@ +/* + * This file is part of the DSView project. + * DSView is based on PulseView. + * + * Copyright (C) 2012 Joel Holdsworth + * Copyright (C) 2013 DreamSourceLab + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + +#include "dscombobox.h" +#include +#include +#include "../config/appconfig.h" + +DsComboBox::DsComboBox(QWidget *parent) : QComboBox(parent) +{ + _contentWidth = 0; + QComboBox::setSizeAdjustPolicy(QComboBox::AdjustToContents); +} + + void DsComboBox::addItem(const QString &atext, const QVariant &auserData) + { + QComboBox::addItem(atext, auserData); + +#ifdef Q_OS_DARWIN + if (!atext.isEmpty()){ + QFontMetrics fm = this->fontMetrics(); + int w = fm.boundingRect(atext).width(); + if (w > _contentWidth){ + _contentWidth = w; + this->setStyleSheet("QAbstractItemView{min-width:" + QString::number(w + 30) + "px;}"); + } + } +#endif + } + + void DsComboBox::showPopup() + { + QComboBox::showPopup(); + +#ifdef Q_OS_DARWIN + + QWidget *popup = this->findChild(); + auto rc = popup->geometry(); + int x = rc.left() + 6; + int y = rc.top(); + int w = rc.right() - rc.left(); + int h = rc.bottom() - rc.top() + 15; + popup->setGeometry(x, y, w, h); + + if (AppConfig::Instance()._frameOptions.style == "dark"){ + popup->setStyleSheet("background-color:#262626;"); + } + else{ + popup->setStyleSheet("background-color:#white;"); + } +#endif + } diff --git a/DSView/pv/ui/dscombobox.h b/DSView/pv/ui/dscombobox.h new file mode 100644 index 00000000..00820d50 --- /dev/null +++ b/DSView/pv/ui/dscombobox.h @@ -0,0 +1,47 @@ + +/* + * This file is part of the DSView project. + * DSView is based on PulseView. + * + * Copyright (C) 2012 Joel Holdsworth + * Copyright (C) 2013 DreamSourceLab + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef DSCOMBOBOX_H +#define DSCOMBOBOX_H + +#include + +class DsComboBox : public QComboBox +{ + Q_OBJECT + +public: + explicit DsComboBox(QWidget *parent = nullptr); + + void addItem(const QString &atext, const QVariant &userData = QVariant()); + +protected: + void showPopup(); + +private: + int _contentWidth; +}; + + + +#endif // DSCOMBOBOX_H diff --git a/DSView/pv/ui/msgbox.cpp b/DSView/pv/ui/msgbox.cpp new file mode 100644 index 00000000..3b10c38e --- /dev/null +++ b/DSView/pv/ui/msgbox.cpp @@ -0,0 +1,63 @@ +/* + * This file is part of the DSView project. + * DSView is based on PulseView. + * + * Copyright (C) 2012 Joel Holdsworth + * Copyright (C) 2013 DreamSourceLab + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ +#include "msgbox.h" +#include "../dialogs/dsmessagebox.h" +#include +#include +#include + +//QMessageBox::information(NULL, "Title", "Content",QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); +//QMessageBox::information(NULL, "Title", "Content",QMessageBox::Yes|QMessageBox::No); +//QMessageBox::information(NULL, "Title", "Content"); +//QMessageBox::information(NULL, "Title", "Content",QMessageBox::Yes|QMessageBox::No|QMessageBox::Abort); + +void MsgBox::Show(const char *title, const char *text, QWidget *parent) +{ + assert(text); + + QString str; + str.append("\n"); + str.append(text); + + pv::dialogs::DSMessageBox msg(parent, title); + msg.mBox()->setText(str); + // msg.mBox()->setInformativeText(QString(text)); + msg.mBox()->setStandardButtons(QMessageBox::Ok); + msg.mBox()->setIcon(QMessageBox::Warning); + msg.exec(); +} + +bool MsgBox::Confirm(const char *text, QWidget *parent) +{ + assert(text); + + QString str; + str.append("\n"); + str.append(text); + + pv::dialogs::DSMessageBox msg(parent, "Question"); + msg.mBox()->setText(str); + msg.mBox()->setStandardButtons(QMessageBox::Yes | QMessageBox::No); + msg.mBox()->setIcon(QMessageBox::Question); + msg.exec(); + return msg.IsYes(); +} diff --git a/DSView/pv/ui/msgbox.h b/DSView/pv/ui/msgbox.h new file mode 100644 index 00000000..7b725158 --- /dev/null +++ b/DSView/pv/ui/msgbox.h @@ -0,0 +1,33 @@ +/* + * This file is part of the DSView project. + * DSView is based on PulseView. + * + * Copyright (C) 2012 Joel Holdsworth + * Copyright (C) 2013 DreamSourceLab + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#pragma once + +class QWidget; + +class MsgBox +{ +public: + static void Show(const char *title, const char *text, QWidget *parent=0); + + static bool Confirm(const char *text, QWidget *parent=0); +}; \ No newline at end of file diff --git a/DSView/pv/view/analogsignal.cpp b/DSView/pv/view/analogsignal.cpp index 2460fe5e..498d46f9 100755 --- a/DSView/pv/view/analogsignal.cpp +++ b/DSView/pv/view/analogsignal.cpp @@ -20,8 +20,8 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#include - + +#include #include #include "../view/analogsignal.h" @@ -29,8 +29,9 @@ #include "../data/analogsnapshot.h" #include "../view/view.h" #include "../device/devinst.h" +#include "../extdef.h" + -using namespace boost; using namespace std; #define byte(x) uint##x##_t @@ -47,8 +48,7 @@ const QColor AnalogSignal::SignalColours[4] = { const float AnalogSignal::EnvelopeThreshold = 16.0f; -AnalogSignal::AnalogSignal(boost::shared_ptr dev_inst, - boost::shared_ptr data, +AnalogSignal::AnalogSignal(DevInst *dev_inst,data::Analog *data, sr_channel *probe) : Signal(dev_inst, probe), _data(data), @@ -96,10 +96,8 @@ AnalogSignal::AnalogSignal(boost::shared_ptr dev_inst, } } -AnalogSignal::AnalogSignal(boost::shared_ptr s, - boost::shared_ptr data, - sr_channel *probe) : - Signal(*s.get(), probe), +AnalogSignal::AnalogSignal(view::AnalogSignal *s, pv::data::Analog *data, sr_channel *probe) : + Signal(*s, probe), _data(data), _rects(NULL), _hover_en(false), @@ -124,7 +122,7 @@ AnalogSignal::~AnalogSignal() } } -boost::shared_ptr AnalogSignal::data() const +pv::data::SignalData* AnalogSignal::data() { return _data; } @@ -134,27 +132,27 @@ void AnalogSignal::set_scale(int height) _scale = height / (_ref_max - _ref_min); } -float AnalogSignal::get_scale() const +float AnalogSignal::get_scale() { return _scale; } -int AnalogSignal::get_bits() const +int AnalogSignal::get_bits() { return _bits; } -double AnalogSignal::get_ref_min() const +double AnalogSignal::get_ref_min() { return _ref_min; } -double AnalogSignal::get_ref_max() const +double AnalogSignal::get_ref_max() { return _ref_max; } -int AnalogSignal::get_hw_offset() const +int AnalogSignal::get_hw_offset() { int hw_offset = 0; GVariant *gvar = _dev_inst->get_config(_probe, NULL, SR_CONF_PROBE_HW_OFFSET); @@ -205,13 +203,11 @@ bool AnalogSignal::measure(const QPointF &p) if (!window.contains(p)) return false; - const deque< boost::shared_ptr > &snapshots = - _data->get_snapshots(); + const auto &snapshots = _data->get_snapshots(); if (snapshots.empty()) return false; - const boost::shared_ptr &snapshot = - snapshots.front(); + const auto snapshot = snapshots.front(); if (snapshot->empty()) return false; @@ -248,13 +244,11 @@ QPointF AnalogSignal::get_point(uint64_t index, float &value) if (!enabled()) return pt; - const deque< boost::shared_ptr > &snapshots = - _data->get_snapshots(); + const auto &snapshots = _data->get_snapshots(); if (snapshots.empty()) return pt; - const boost::shared_ptr &snapshot = - snapshots.front(); + const auto snapshot = snapshots.front(); if (snapshot->empty()) return pt; @@ -288,7 +282,7 @@ QPointF AnalogSignal::get_point(uint64_t index, float &value) /** * Probe options **/ -uint64_t AnalogSignal::get_vdiv() const +uint64_t AnalogSignal::get_vdiv() { uint64_t vdiv = 0; GVariant* gvar = _dev_inst->get_config(_probe, NULL, SR_CONF_PROBE_VDIV); @@ -299,7 +293,7 @@ uint64_t AnalogSignal::get_vdiv() const return vdiv; } -uint8_t AnalogSignal::get_acCoupling() const +uint8_t AnalogSignal::get_acCoupling() { uint64_t coupling = 0; GVariant* gvar = _dev_inst->get_config(_probe, NULL, SR_CONF_PROBE_COUPLING); @@ -310,7 +304,7 @@ uint8_t AnalogSignal::get_acCoupling() const return coupling; } -bool AnalogSignal::get_mapDefault() const +bool AnalogSignal::get_mapDefault() { bool isDefault = true; GVariant* gvar = _dev_inst->get_config(_probe, NULL, SR_CONF_PROBE_MAP_DEFAULT); @@ -321,7 +315,7 @@ bool AnalogSignal::get_mapDefault() const return isDefault; } -QString AnalogSignal::get_mapUnit() const +QString AnalogSignal::get_mapUnit() { QString unit; GVariant* gvar = _dev_inst->get_config(_probe, NULL, SR_CONF_PROBE_MAP_UNIT); @@ -332,7 +326,7 @@ QString AnalogSignal::get_mapUnit() const return unit; } -double AnalogSignal::get_mapMin() const +double AnalogSignal::get_mapMin() { double min = -1; GVariant* gvar = _dev_inst->get_config(_probe, NULL, SR_CONF_PROBE_MAP_MIN); @@ -343,7 +337,7 @@ double AnalogSignal::get_mapMin() const return min; } -double AnalogSignal::get_mapMax() const +double AnalogSignal::get_mapMax() { double max = 1; GVariant* gvar = _dev_inst->get_config(_probe, NULL, SR_CONF_PROBE_MAP_MAX); @@ -354,7 +348,7 @@ double AnalogSignal::get_mapMax() const return max; } -uint64_t AnalogSignal::get_factor() const +uint64_t AnalogSignal::get_factor() { GVariant* gvar; uint64_t factor; @@ -369,24 +363,24 @@ uint64_t AnalogSignal::get_factor() const } } -int AnalogSignal::ratio2value(double ratio) const +int AnalogSignal::ratio2value(double ratio) { return ratio * (_ref_max - _ref_min) + _ref_min; } -int AnalogSignal::ratio2pos(double ratio) const +int AnalogSignal::ratio2pos(double ratio) { const int height = get_totalHeight(); const int top = get_y() - height * 0.5; return ratio * height + top; } -double AnalogSignal::value2ratio(int value) const +double AnalogSignal::value2ratio(int value) { return max(0.0, (value - _ref_min) / (_ref_max - _ref_min)); } -double AnalogSignal::pos2ratio(int pos) const +double AnalogSignal::pos2ratio(int pos) { const int height = get_totalHeight(); const int top = get_y() - height / 2; @@ -403,7 +397,7 @@ void AnalogSignal::set_zero_vpos(int pos) } } -int AnalogSignal::get_zero_vpos() const +int AnalogSignal::get_zero_vpos() { return ratio2pos(get_zero_ratio()); } @@ -418,12 +412,12 @@ void AnalogSignal::set_zero_ratio(double ratio) g_variant_new_uint16(_zero_offset)); } -double AnalogSignal::get_zero_ratio() const +double AnalogSignal::get_zero_ratio() { return value2ratio(_zero_offset); } -int AnalogSignal::get_zero_offset() const +int AnalogSignal::get_zero_offset() { return _zero_offset; } @@ -510,13 +504,11 @@ void AnalogSignal::paint_mid(QPainter &p, int left, int right, QColor fore, QCol assert(scale > 0); const int64_t offset = _view->offset(); - const deque< boost::shared_ptr > &snapshots = - _data->get_snapshots(); + const auto &snapshots = _data->get_snapshots(); if (snapshots.empty()) return; - const boost::shared_ptr &snapshot = - snapshots.front(); + const auto snapshot = snapshots.front(); if (snapshot->empty()) return; @@ -571,7 +563,7 @@ void AnalogSignal::paint_fore(QPainter &p, int left, int right, QColor fore, QCo } void AnalogSignal::paint_trace(QPainter &p, - const boost::shared_ptr &snapshot, + const pv::data::AnalogSnapshot *snapshot, int zeroY, const int start_pixel, const uint64_t start_index, const int64_t sample_count, const double samples_per_pixel, const int order, @@ -579,10 +571,12 @@ void AnalogSignal::paint_trace(QPainter &p, { (void)width; - const int64_t channel_num = snapshot->get_channel_num(); + pv::data::AnalogSnapshot *pshot = const_cast(snapshot); + + int64_t channel_num = (int64_t)pshot->get_channel_num(); if (sample_count > 0) { - const uint8_t unit_bytes = snapshot->get_unit_bytes(); - const uint8_t *const samples = snapshot->get_samples(0); + const uint8_t unit_bytes = pshot->get_unit_bytes(); + const uint8_t *const samples = pshot->get_samples(0); assert(samples); p.setPen(_colour); @@ -603,10 +597,10 @@ void AnalogSignal::paint_trace(QPainter &p, yvalue = zeroY + (yvalue - hw_offset) * _scale; yvalue = min(max(yvalue, top), bottom); *point++ = QPointF(x, yvalue); - if (yindex == snapshot->get_ring_end()) + if (yindex == pshot->get_ring_end()) break; yindex++; - yindex %= snapshot->get_sample_count(); + yindex %= pshot->get_sample_count(); x += pixels_per_sample; } p.drawPolyline(points, point - points); @@ -615,7 +609,7 @@ void AnalogSignal::paint_trace(QPainter &p, } void AnalogSignal::paint_envelope(QPainter &p, - const boost::shared_ptr &snapshot, + const pv::data::AnalogSnapshot *snapshot, int zeroY, const int start_pixel, const uint64_t start_index, const int64_t sample_count, const double samples_per_pixel, const int order, @@ -623,9 +617,10 @@ void AnalogSignal::paint_envelope(QPainter &p, { using namespace Qt; using pv::data::AnalogSnapshot; + pv::data::AnalogSnapshot *pshot = const_cast(snapshot); AnalogSnapshot::EnvelopeSection e; - snapshot->get_envelope_section(e, start_index, sample_count, + pshot->get_envelope_section(e, start_index, sample_count, samples_per_pixel, order); if (e.samples_num == 0) return; @@ -640,7 +635,8 @@ void AnalogSignal::paint_envelope(QPainter &p, float y_min = zeroY, y_max = zeroY, pre_y_min = zeroY, pre_y_max = zeroY; int pcnt = 0; const double scale_pixels_per_samples = e.scale / samples_per_pixel; - const uint64_t ring_end = max((int64_t)0, (int64_t)snapshot->get_ring_end() / e.scale - 1); + int64_t end_v = pshot->get_ring_end(); + const uint64_t ring_end = max((int64_t)0, end_v / e.scale - 1); const int hw_offset = get_hw_offset(); float x = start_pixel; @@ -717,7 +713,7 @@ void AnalogSignal::paint_hover_measure(QPainter &p, QColor fore, QColor back) p.drawText(hover_rect, Qt::AlignCenter | Qt::AlignTop | Qt::TextDontClip, hover_str); } - list::iterator i = _view->get_cursorList().begin(); + auto i = _view->get_cursorList().begin(); while (i != _view->get_cursorList().end()) { float pt_value; const QPointF pt = get_point((*i)->index(), pt_value); diff --git a/DSView/pv/view/analogsignal.h b/DSView/pv/view/analogsignal.h index ac7ff67a..48f3d7f6 100755 --- a/DSView/pv/view/analogsignal.h +++ b/DSView/pv/view/analogsignal.h @@ -24,8 +24,7 @@ #define DSVIEW_PV_ANALOGSIGNAL_H #include "signal.h" - -#include + namespace pv { @@ -37,6 +36,8 @@ class AnalogSnapshot; namespace view { +//when device is data acquisition model, to draw signal trace +//created by SigSession class AnalogSignal : public Signal { Q_OBJECT @@ -51,23 +52,21 @@ private: static const uint8_t DefaultBits = 8; public: - AnalogSignal(boost::shared_ptr dev_inst, - boost::shared_ptr data, - sr_channel *probe); - AnalogSignal(boost::shared_ptr s, - boost::shared_ptr data, + AnalogSignal(DevInst* dev_inst, pv::data::Analog *data, sr_channel *probe); + AnalogSignal(view::AnalogSignal* s, pv::data::Analog *data, sr_channel *probe); + virtual ~AnalogSignal(); - boost::shared_ptr data() const; + pv::data::SignalData* data(); void set_scale(int height); - float get_scale() const; - int get_bits() const; - double get_ref_min() const; - double get_ref_max() const; - int get_hw_offset() const; + float get_scale(); + int get_bits(); + double get_ref_min(); + double get_ref_max(); + int get_hw_offset(); int commit_settings(); /** @@ -81,30 +80,30 @@ public: /** * Probe options **/ - uint64_t get_vdiv() const; - uint8_t get_acCoupling() const; - bool get_mapDefault() const; - QString get_mapUnit() const; - double get_mapMin() const; - double get_mapMax() const; - uint64_t get_factor() const; + uint64_t get_vdiv(); + uint8_t get_acCoupling(); + bool get_mapDefault(); + QString get_mapUnit(); + double get_mapMin(); + double get_mapMax(); + uint64_t get_factor(); /** * **/ void set_zero_vpos(int pos); - int get_zero_vpos() const; + int get_zero_vpos(); void set_zero_ratio(double ratio); - double get_zero_ratio() const; - int get_zero_offset() const; + double get_zero_ratio(); + int get_zero_offset(); /** * */ - int ratio2value(double ratio) const; - int ratio2pos(double ratio) const; - double value2ratio(int value) const; - double pos2ratio(int pos) const; + int ratio2value(double ratio); + int ratio2pos(double ratio); + double value2ratio(int value); + double pos2ratio(int pos); /** * Event @@ -137,14 +136,14 @@ public: private: void paint_trace(QPainter &p, - const boost::shared_ptr &snapshot, + const pv::data::AnalogSnapshot *snapshot, int zeroY, const int start_pixel, const uint64_t start_index, const int64_t sample_count, const double samples_per_pixel, const int order, const float top, const float bottom, const int width); void paint_envelope(QPainter &p, - const boost::shared_ptr &snapshot, + const pv::data::AnalogSnapshot *snapshot, int zeroY, const int start_pixel, const uint64_t start_index, const int64_t sample_count, const double samples_per_pixel, const int order, @@ -153,7 +152,7 @@ private: void paint_hover_measure(QPainter &p, QColor fore, QColor back); private: - boost::shared_ptr _data; + pv::data::Analog *_data; QRectF *_rects; diff --git a/DSView/pv/view/cursor.cpp b/DSView/pv/view/cursor.cpp index 7c136567..a4b667a3 100755 --- a/DSView/pv/view/cursor.cpp +++ b/DSView/pv/view/cursor.cpp @@ -35,7 +35,7 @@ #include #include -#include +#include "../extdef.h" namespace pv { namespace view { @@ -57,7 +57,7 @@ Cursor::Cursor(View &view, QColor color, uint64_t index) : { } -QRect Cursor::get_label_rect(const QRect &rect, bool &visible, bool has_hoff) const +QRect Cursor::get_label_rect(const QRect &rect, bool &visible, bool has_hoff) { const double samples_per_pixel = _view.session().cur_snap_samplerate() * _view.scale(); const double cur_offset = _index / samples_per_pixel; @@ -79,7 +79,7 @@ QRect Cursor::get_label_rect(const QRect &rect, bool &visible, bool has_hoff) co return QRect(x - label_size.width() / 2, top, label_size.width(), height); } -QRect Cursor::get_close_rect(const QRect &rect) const +QRect Cursor::get_close_rect(const QRect &rect) { return QRect(rect.right() - CloseSize, rect.top(), CloseSize, CloseSize); } diff --git a/DSView/pv/view/cursor.h b/DSView/pv/view/cursor.h index 0248c9ce..6e8292fc 100755 --- a/DSView/pv/view/cursor.h +++ b/DSView/pv/view/cursor.h @@ -33,6 +33,7 @@ class QPainter; namespace pv { namespace view { +//created by View class Cursor : public TimeMarker { Q_OBJECT @@ -64,9 +65,9 @@ public: * @param rect The rectangle of the ruler client area. * @return Returns the label rectangle. */ - QRect get_label_rect(const QRect &rect, bool &visible, bool has_hoff = true) const; + QRect get_label_rect(const QRect &rect, bool &visible, bool has_hoff = true); - QRect get_close_rect(const QRect &rect) const; + QRect get_close_rect(const QRect &rect); /** * Paints the cursor's label to the ruler. diff --git a/DSView/pv/view/decodetrace.cpp b/DSView/pv/view/decodetrace.cpp index 733497fb..9c05d62e 100755 --- a/DSView/pv/view/decodetrace.cpp +++ b/DSView/pv/view/decodetrace.cpp @@ -21,14 +21,12 @@ #include -#include +#include "../extdef.h" -#include + #include -#include -#include -#include +#include #include #include #include @@ -36,6 +34,7 @@ #include #include #include +#include #include "decodetrace.h" @@ -52,10 +51,13 @@ #include "../device/devinst.h" #include "../view/cursor.h" #include "../toolbars/titlebar.h" +#include "../dsvdef.h" +#include "../ui/dscombobox.h" +#include using namespace boost; using namespace std; - + namespace pv { namespace view { @@ -114,50 +116,51 @@ const QColor DecodeTrace::OutlineColours[16] = { const QString DecodeTrace::RegionStart = QT_TR_NOOP("Start"); const QString DecodeTrace::RegionEnd = QT_TR_NOOP("End "); -DecodeTrace::DecodeTrace(pv::SigSession &session, - boost::shared_ptr decoder_stack, int index) : - Trace(QString::fromUtf8( - decoder_stack->stack().front()->decoder()->name), index, SR_CHANNEL_DECODER), - _session(session), - _decoder_stack(decoder_stack), - _decode_start(0), - _decode_end(INT64_MAX), - _start_index(0), - _end_index(0), - _start_count(0), - _end_count(0), - _progress(0), - _popup_form(NULL), - _popup() +DecodeTrace::DecodeTrace(pv::SigSession *session, + pv::data::DecoderStack *decoder_stack, int index) : + Trace(QString::fromUtf8(decoder_stack->stack().front()->decoder()->name), index, SR_CHANNEL_DECODER) { - assert(_decoder_stack); + assert(decoder_stack); - _colour = DecodeColours[index % countof(DecodeColours)]; + _colour = DecodeColours[index % countof(DecodeColours)]; + _start_comboBox = NULL; + _end_comboBox = NULL; + _pub_input_layer = NULL; + _progress = 0; - connect(_decoder_stack.get(), SIGNAL(new_decode_data()), - this, SLOT(on_new_decode_data())); - connect(_decoder_stack.get(), SIGNAL(decode_done()), - this, SLOT(on_decode_done())); + _decode_start = 0; + _decode_end = INT64_MAX; + _end_count = 0; + _start_count = 0; + _end_index = 0; + _start_index = 0; + _decoder_container = NULL; + _form_base_height = 0; + + _decoder_stack = decoder_stack; + _session = session; + _delete_flag = false; + + connect(_decoder_stack, SIGNAL(new_decode_data()), this, SLOT(on_new_decode_data())); + + connect(_decoder_stack, SIGNAL(decode_done()), this, SLOT(on_decode_done())); } DecodeTrace::~DecodeTrace() -{ - if (_popup_form) - delete _popup_form; - if (_popup) - delete _popup; - _cur_row_headings.clear(); +{ _cur_row_headings.clear(); _decoder_forms.clear(); _probe_selectors.clear(); _bindings.clear(); + + DESTROY_OBJECT(_decoder_stack); } -bool DecodeTrace::enabled() const +bool DecodeTrace::enabled() { return true; } -const boost::shared_ptr& DecodeTrace::decoder() const +pv::data::DecoderStack* DecodeTrace::decoder() { return _decoder_stack; } @@ -181,7 +184,7 @@ void DecodeTrace::paint_back(QPainter &p, int left, int right, QColor fore, QCol p.drawLine(left, sigY, right, sigY); // --draw decode region control - const double samples_per_pixel = _session.cur_snap_samplerate() * _view->scale(); + const double samples_per_pixel = _session->cur_snap_samplerate() * _view->scale(); const double startX = _decode_start/samples_per_pixel - _view->offset(); const double endX = _decode_end/samples_per_pixel - _view->offset(); const double regionY = get_y() - _totalHeight*0.5 - ControlRectWidth; @@ -268,11 +271,13 @@ void DecodeTrace::paint_mid(QPainter &p, int left, int right, QColor fore, QColo samples_per_pixel, 0.0); uint64_t end_sample = (uint64_t)max((right + pixels_offset) * samples_per_pixel, 0.0); - BOOST_FOREACH(const boost::shared_ptr &dec, _decoder_stack->stack()) { + + for(auto &dec : _decoder_stack->stack()) { start_sample = max(dec->decode_start(), start_sample); end_sample = min(dec->decode_end(), end_sample); break; } + if (end_sample < start_sample) return; @@ -284,8 +289,7 @@ void DecodeTrace::paint_mid(QPainter &p, int left, int right, QColor fore, QColo assert(_decoder_stack); - BOOST_FOREACH(boost::shared_ptr dec, - _decoder_stack->stack()) { + for(auto &dec :_decoder_stack->stack()) { if (dec->shown()) { const std::map rows = _decoder_stack->get_rows_gshow(); for (std::map::const_iterator i = rows.begin(); @@ -302,14 +306,16 @@ void DecodeTrace::paint_mid(QPainter &p, int left, int right, QColor fore, QColo const uint64_t max_annotation = _decoder_stack->get_max_annotation(row); const double max_annWidth = max_annotation / samples_per_pixel; + if ((max_annWidth > 100) || (max_annWidth > 10 && min_annWidth > 1) || (max_annWidth == 0 && samples_per_pixel < 10)) { - vector annotations; + std::vector annotations; _decoder_stack->get_annotation_subset(annotations, row, start_sample, end_sample); + if (!annotations.empty()) { - BOOST_FOREACH(const Annotation &a, annotations) + for(Annotation &a : annotations) draw_annotation(a, p, get_text_colour(), annotation_height, left, right, samples_per_pixel, pixels_offset, y, @@ -342,17 +348,20 @@ void DecodeTrace::paint_fore(QPainter &p, int left, int right, QColor fore, QCol (void)back; } +//to show decoder's property setting dialog bool DecodeTrace::create_popup() -{ - int ret = false; - _popup = new dialogs::DSDialog(); +{ + int ret = false; //setting have changed flag + _form_base_height = 0; + _decoder_container = NULL; + + dialogs::DSDialog dlg; + //dlg.setMinimumSize(500,600); + create_popup_form(&dlg); - create_popup_form(); - - if (QDialog::Accepted == _popup->exec()) + if (QDialog::Accepted == dlg.exec()) { - BOOST_FOREACH(boost::shared_ptr dec, - _decoder_stack->stack()) + for(auto &dec : _decoder_stack->stack()) { if (dec->commit() || _decoder_stack->options_changed()) { _decoder_stack->set_options_changed(true); @@ -363,33 +372,57 @@ bool DecodeTrace::create_popup() } } - delete _popup_form; - delete _popup; - _popup = NULL; - _popup_form = NULL; - + _decoder_container = NULL; return ret; } -void DecodeTrace::create_popup_form() +void DecodeTrace::create_popup_form(dialogs::DSDialog *dlg) { - // Clear the layout - // Transfer the layout and the child widgets to a temporary widget // which then goes out of scope destroying the layout and all the child - // widgets. - if (_popup_form) - _popup->reload(false); + // widgets. + QFormLayout *form = new QFormLayout(); + form->setVerticalSpacing(5); + form->setFormAlignment(Qt::AlignLeft); + form->setLabelAlignment(Qt::AlignLeft); + form->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); - _popup_form = new QFormLayout(); - _popup_form->setVerticalSpacing(5); - _popup_form->setFormAlignment(Qt::AlignLeft); - _popup_form->setLabelAlignment(Qt::AlignLeft); - _popup_form->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); - _popup->layout()->addLayout(_popup_form); - _popup->setTitle(tr("Decoder Options")); + _decoder_container = new QWidget(dlg); + dlg->layout()->addWidget(_decoder_container); + + QVBoxLayout *decoder_lay = new QVBoxLayout(); + decoder_lay->setContentsMargins(0, 0, 0, 0); + decoder_lay->setDirection(QBoxLayout::TopToBottom); + _decoder_container->setLayout(decoder_lay); + + dlg->layout()->addLayout(form); + dlg->setTitle(tr("Decoder Options")); - populate_popup_form(_popup, _popup_form); + populate_popup_form(dlg, form); +} + +void DecodeTrace::load_all_decoder_property(std::list &ls) +{ + assert(_decoder_container); + QVBoxLayout *lay = dynamic_cast(_decoder_container->layout()); + assert(lay); + + for(auto &dec : ls) + { + QWidget *panel = new QWidget(_decoder_container); + QFormLayout *form = new QFormLayout(); + form->setContentsMargins(0,0,0,0); + panel->setLayout(form); + lay->addWidget(panel); + + create_decoder_form(_decoder_stack, dec, panel, form); + + decoder_panel_item inf; + inf.decoder_handle = dec; + inf.panel = panel; + inf.panel_height = 0; + _decoder_panels.push_back(inf); + } } void DecodeTrace::populate_popup_form(QWidget *parent, QFormLayout *form) @@ -405,28 +438,18 @@ void DecodeTrace::populate_popup_form(QWidget *parent, QFormLayout *form) _probe_selectors.clear(); _decoder_forms.clear(); - const list< boost::shared_ptr >& stack = _decoder_stack->stack(); + load_all_decoder_property(_decoder_stack->stack()); - if (stack.empty()) { - QLabel *const l = new QLabel( - tr("

No decoders in the stack

")); - l->setAlignment(Qt::AlignCenter); - form->addRow(l); - } else { - BOOST_FOREACH(boost::shared_ptr dec,stack) { - //boost::shared_ptr dec(*iter); - create_decoder_form(_decoder_stack, dec, parent, form); - } + if (_decoder_stack->stack().size() > 0){ + form->addRow(new QLabel(tr("* Required channels"), parent)); + } - form->addRow(new QLabel( - tr("* Required channels"), parent)); - } - - // Add region combobox - _start_comboBox = new QComboBox(parent); - _end_comboBox = new QComboBox(parent); + //Add region combobox + _start_comboBox = new DsComboBox(parent); + _end_comboBox = new DsComboBox(parent); _start_comboBox->addItem(RegionStart); _end_comboBox->addItem(RegionEnd); + if (_view) { int index = 1; for(std::list::iterator i = _view->get_cursorList().begin(); @@ -437,6 +460,7 @@ void DecodeTrace::populate_popup_form(QWidget *parent, QFormLayout *form) index++; } } + if (_start_count > _start_comboBox->count()) _start_index = 0; if (_end_count > _end_comboBox->count()) @@ -446,10 +470,7 @@ void DecodeTrace::populate_popup_form(QWidget *parent, QFormLayout *form) _start_comboBox->setCurrentIndex(_start_index); _end_comboBox->setCurrentIndex(_end_index); - connect(_start_comboBox, SIGNAL(currentIndexChanged(int)), - this, SLOT(on_region_set(int))); - connect(_end_comboBox, SIGNAL(currentIndexChanged(int)), - this, SLOT(on_region_set(int))); + on_region_set(_start_index); form->addRow(_start_comboBox, new QLabel( tr("Decode Start From"))); @@ -459,11 +480,8 @@ void DecodeTrace::populate_popup_form(QWidget *parent, QFormLayout *form) // Add stacking button pv::widgets::DecoderMenu *const decoder_menu = new pv::widgets::DecoderMenu(parent); - connect(decoder_menu, SIGNAL(decoder_selected(srd_decoder*)), - this, SLOT(on_stack_decoder(srd_decoder*))); - //connect(decoder_menu, SIGNAL(selected()), - // parent, SLOT(accept())); + QPushButton *const stack_button = new QPushButton(tr("Stack Decoder"), parent); stack_button->setMenu(decoder_menu); @@ -475,18 +493,23 @@ void DecodeTrace::populate_popup_form(QWidget *parent, QFormLayout *form) // Add ButtonBox (OK/Cancel) QDialogButtonBox *button_box = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, parent); - connect(button_box, SIGNAL(accepted()), parent, SLOT(accept())); - connect(button_box, SIGNAL(rejected()), parent, SLOT(reject())); + QHBoxLayout *confirm_button_box = new QHBoxLayout; confirm_button_box->addWidget(button_box, 0, Qt::AlignRight); form->addRow(confirm_button_box); + + connect(_start_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(on_region_set(int))); + connect(_end_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(on_region_set(int))); + connect(decoder_menu, SIGNAL(decoder_selected(srd_decoder *)), this, SLOT(on_stack_decoder(srd_decoder *))); + connect(button_box, SIGNAL(accepted()), parent, SLOT(accept())); + connect(button_box, SIGNAL(rejected()), parent, SLOT(reject())); } void DecodeTrace::draw_annotation(const pv::data::decode::Annotation &a, QPainter &p, QColor text_color, int h, int left, int right, double samples_per_pixel, double pixels_offset, int y, - size_t base_colour, double min_annWidth, QColor fore, QColor back) const + size_t base_colour, double min_annWidth, QColor fore, QColor back) { const double start = max(a.start_sample() / samples_per_pixel - pixels_offset, (double)left); @@ -525,17 +548,18 @@ void DecodeTrace::draw_annotation(const pv::data::decode::Annotation &a, draw_range(a, p, fill, outline, text_color, h, start, end, y, fore, back); if ((a.type()/100 == 2) && (end - start > 20)) { - BOOST_FOREACH(boost::shared_ptr dec, - _decoder_stack->stack()) { + for(auto &dec : _decoder_stack->stack()) { for (auto& iter: dec->channels()) { int type = dec->get_channel_type(iter.first); if ((type == SRD_CHANNEL_COMMON) || ((type%100 != a.type()%100) && (type%100 != 0))) continue; - boost::shared_ptr logic_sig; - BOOST_FOREACH(boost::shared_ptr sig, _session.get_signals()) { + + LogicSignal *logic_sig = NULL; + + for(auto &sig : _session->get_signals()) { if((sig->get_index() == iter.second) && - (logic_sig = dynamic_pointer_cast(sig))) { + (logic_sig = dynamic_cast(sig))) { logic_sig->paint_mark(p, start, end, type/100); break; } @@ -548,7 +572,7 @@ void DecodeTrace::draw_annotation(const pv::data::decode::Annotation &a, void DecodeTrace::draw_nodetail(QPainter &p, int h, int left, int right, int y, - size_t base_colour, QColor fore, QColor back) const + size_t base_colour, QColor fore, QColor back) { (void)base_colour; (void)back; @@ -572,7 +596,7 @@ void DecodeTrace::draw_nodetail(QPainter &p, } void DecodeTrace::draw_instant(const pv::data::decode::Annotation &a, QPainter &p, - QColor fill, QColor outline, QColor text_color, int h, double x, int y, double min_annWidth) const + QColor fill, QColor outline, QColor text_color, int h, double x, int y, double min_annWidth) { (void)outline; @@ -597,13 +621,13 @@ void DecodeTrace::draw_instant(const pv::data::decode::Annotation &a, QPainter & void DecodeTrace::draw_range(const pv::data::decode::Annotation &a, QPainter &p, QColor fill, QColor outline, QColor text_color, int h, double start, - double end, int y, QColor fore, QColor back) const + double end, int y, QColor fore, QColor back) { (void)fore; const double top = y + .5 - h / 2; const double bottom = y + .5 + h / 2; - const vector annotations = a.annotations(); + const std::vector annotations = a.annotations(); p.setPen(outline); p.setBrush(fill); @@ -643,7 +667,7 @@ void DecodeTrace::draw_range(const pv::data::decode::Annotation &a, QPainter &p, QString best_annotation; int best_width = 0; - BOOST_FOREACH(const QString &a, annotations) { + for(auto &&a : annotations) { const int w = p.boundingRect(QRectF(), 0, a).width(); if (w <= rect.width() && w > best_width) best_annotation = a, best_width = w; @@ -702,13 +726,15 @@ void DecodeTrace::draw_unshown_row(QPainter &p, int y, int h, int left, } void DecodeTrace::create_decoder_form( - boost::shared_ptr &decoder_stack, - boost::shared_ptr &dec, QWidget *parent, + pv::data::DecoderStack *decoder_stack, + data::decode::Decoder *dec, QWidget *parent, QFormLayout *form) { const GSList *l; assert(dec); + assert(decoder_stack); + const srd_decoder *const decoder = dec->decoder(); assert(decoder); @@ -723,35 +749,36 @@ void DecodeTrace::create_decoder_form( for(l = decoder->channels; l; l = l->next) { const struct srd_channel *const pdch = (struct srd_channel *)l->data; - QComboBox *const combo = create_probe_selector(parent, dec, pdch); - connect(combo, SIGNAL(currentIndexChanged(int)), - this, SLOT(on_probe_selected(int))); + DsComboBox *const combo = create_probe_selector(parent, dec, pdch); + decoder_form->addRow(tr("%1 (%2) *") .arg(QString::fromUtf8(pdch->name)) .arg(QString::fromUtf8(pdch->desc)), combo); const ProbeSelector s = {combo, dec, pdch}; _probe_selectors.push_back(s); + + connect(combo, SIGNAL(currentIndexChanged(int)), this, SLOT(on_probe_selected(int))); } // Add the optional channels for(l = decoder->opt_channels; l; l = l->next) { const struct srd_channel *const pdch = (struct srd_channel *)l->data; - QComboBox *const combo = create_probe_selector(parent, dec, pdch); - connect(combo, SIGNAL(currentIndexChanged(int)), - this, SLOT(on_probe_selected(int))); + DsComboBox *const combo = create_probe_selector(parent, dec, pdch); + decoder_form->addRow(tr("%1 (%2)") .arg(QString::fromUtf8(pdch->name)) .arg(QString::fromUtf8(pdch->desc)), combo); const ProbeSelector s = {combo, dec, pdch}; _probe_selectors.push_back(s); + + connect(combo, SIGNAL(currentIndexChanged(int)), this, SLOT(on_probe_selected(int))); } // Add the options - boost::shared_ptr binding( - new prop::binding::DecoderOptions(decoder_stack, dec)); + auto binding = new prop::binding::DecoderOptions(decoder_stack, dec); binding->add_properties_to_form(decoder_form, true); _bindings.push_back(binding); @@ -759,41 +786,38 @@ void DecodeTrace::create_decoder_form( // pv::widgets::DecoderGroupBox *const group = new pv::widgets::DecoderGroupBox(decoder_stack, dec, decoder_form, parent); - connect(group, SIGNAL(del_stack(boost::shared_ptr&)), - this, SLOT(on_del_stack(boost::shared_ptr&))); - + form->addRow(group); _decoder_forms.push_back(group); + + connect(group, SIGNAL(del_stack(data::decode::Decoder*)), this, SLOT(on_del_stack(data::decode::Decoder*))); } -QComboBox* DecodeTrace::create_probe_selector( - QWidget *parent, const boost::shared_ptr &dec, +DsComboBox* DecodeTrace::create_probe_selector( + QWidget *parent, const data::decode::Decoder *dec, const srd_channel *const pdch) { assert(dec); - - const vector< boost::shared_ptr > sigs(_session.get_signals()); - + const auto &sigs = _session->get_signals(); assert(_decoder_stack); - const map::const_iterator probe_iter = - dec->channels().find(pdch); - - QComboBox *selector = new QComboBox(parent); + data::decode::Decoder *_dec = const_cast(dec); + auto probe_iter = _dec->channels().find(pdch); + DsComboBox *selector = new DsComboBox(parent); selector->addItem("-", QVariant::fromValue(-1)); - if (probe_iter == dec->channels().end()) + if (probe_iter == _dec->channels().end()) selector->setCurrentIndex(0); for(size_t i = 0; i < sigs.size(); i++) { - const boost::shared_ptr s(sigs[i]); + const auto s = sigs[i]; assert(s); - if (dynamic_pointer_cast(s) && s->enabled()) + if (dynamic_cast(s) && s->enabled()) { selector->addItem(s->get_name(), QVariant::fromValue(s->get_index())); - if (probe_iter != dec->channels().end()) { + if (probe_iter != _dec->channels().end()) { if ((*probe_iter).second == s->get_index()) selector->setCurrentIndex(i + 1); } @@ -803,15 +827,15 @@ QComboBox* DecodeTrace::create_probe_selector( return selector; } -void DecodeTrace::commit_decoder_probes(boost::shared_ptr &dec) +void DecodeTrace::commit_decoder_probes(data::decode::Decoder *dec) { assert(dec); - map probe_map; - const vector< boost::shared_ptr > sigs(_session.get_signals()); + std::map probe_map; + const auto &sigs = _session->get_signals(); _index_list.clear(); - BOOST_FOREACH(const ProbeSelector &s, _probe_selectors) + for(auto &s : _probe_selectors) { if(s._decoder != dec) break; @@ -819,7 +843,7 @@ void DecodeTrace::commit_decoder_probes(boost::shared_ptr const int selection = s._combo->itemData( s._combo->currentIndex()).value(); - BOOST_FOREACH(boost::shared_ptr sig, sigs) + for(auto &sig : sigs) if(sig->get_index() == selection) { probe_map[s._pdch] = selection; _index_list.push_back(selection); @@ -833,11 +857,8 @@ void DecodeTrace::commit_decoder_probes(boost::shared_ptr void DecodeTrace::commit_probes() { assert(_decoder_stack); - BOOST_FOREACH(boost::shared_ptr dec, - _decoder_stack->stack()) - commit_decoder_probes(dec); - - //_decoder_stack->begin_decode(); + for(auto &dec : _decoder_stack->stack()) + commit_decoder_probes(dec); } void DecodeTrace::on_new_decode_data() @@ -860,49 +881,119 @@ void DecodeTrace::on_new_decode_data() _view->signals_changed(); } -int DecodeTrace::get_progress() const +int DecodeTrace::get_progress() { return _progress; } void DecodeTrace::on_decode_done() -{ -// if (_view) { -// _view->set_update(_viewport, true); -// _view->signals_changed(); -// } +{ on_new_decode_data(); - _session.decode_done(); -} - -void DecodeTrace::on_delete() -{ - _session.remove_decode_signal(this); + _session->decode_done(); } + void DecodeTrace::on_probe_selected(int) { commit_probes(); -} +} void DecodeTrace::on_stack_decoder(srd_decoder *decoder) { assert(decoder); assert(_decoder_stack); - _decoder_stack->push(boost::shared_ptr( - new data::decode::Decoder(decoder))); - //_decoder_stack->begin_decode(); - create_popup_form(); + auto dec = new data::decode::Decoder(decoder); + + _decoder_stack->push(dec); + std::list items; + items.push_back(dec); + + if (_decoder_panels.size()){ + auto it = _decoder_panels.end(); + --it; + if ((*it).panel_height == 0){ + (*it).panel_height = (*it).panel->geometry().height(); + } + } + + if (_decoder_panels.size() == 1 && _decoder_container && _form_base_height == 0){ + QWidget *dlg = dynamic_cast(_decoder_container->parent()); + assert(dlg); + _form_base_height = dlg->geometry().height(); + } + + load_all_decoder_property(items); } - -void DecodeTrace::on_del_stack(boost::shared_ptr &dec) + +void DecodeTrace::on_del_stack(data::decode::Decoder *dec) { assert(dec); assert(_decoder_stack); + _decoder_stack->remove(dec); - create_popup_form(); + std::list dels; + std::list adds; + + for (auto it = _decoder_panels.begin(); it != _decoder_panels.end(); it++){ + if ((*it).decoder_handle == dec){ + dels.push_back((*it)); + auto del_it = it; + + it++; + while (it != _decoder_panels.end()) + { + dels.push_back((*it)); + adds.push_back((pv::data::decode::Decoder*)(*it).decoder_handle); + it++; + } + _decoder_panels.erase(del_it); + break; + } + } + + while (true) + { + if (dels.empty()) + break; + + auto it = dels.end(); + it--; + auto inf = (*it); + assert(inf.panel); + + inf.panel->deleteLater(); + dels.erase(it); + + for (auto fd = _decoder_panels.begin(); fd != _decoder_panels.end(); ++fd){ + if ((*fd).decoder_handle == inf.decoder_handle){ + _decoder_panels.erase(fd); + break; + } + } + } + + if (adds.size() > 0){ + load_all_decoder_property(adds); + } + +// QTimer::singleShot(200, this, SLOT(on_resize_decoder_panel())); +} + +void DecodeTrace::on_resize_decoder_panel() +{ + /* + int dex = 0; + + for (auto &panel : _decoder_panels){ + assert(panel.panel); + dex++; + if (dex > 1){ + panel.panel->setMaximumHeight(panel.panel_height); + } + } + */ } int DecodeTrace::rows_size() @@ -910,13 +1001,14 @@ int DecodeTrace::rows_size() using pv::data::decode::Decoder; int size = 0; - BOOST_FOREACH(boost::shared_ptr dec, - _decoder_stack->stack()) { + for(auto &dec : _decoder_stack->stack()) { if (dec->shown()) { - const std::map rows = _decoder_stack->get_rows_gshow(); - for (std::map::const_iterator i = rows.begin(); - i != rows.end(); i++) { - if ((*i).first.decoder() == dec->decoder() && + + auto rows = _decoder_stack->get_rows_gshow(); + + for (auto i = rows.begin(); i != rows.end(); i++) { + pv::data::decode::Row _row = (*i).first; + if (_row.decoder() == dec->decoder() && _decoder_stack->has_annotations((*i).first) && (*i).second) size++; @@ -970,7 +1062,7 @@ QRectF DecodeTrace::get_rect(DecodeSetRegions type, int y, int right) void DecodeTrace::on_region_set(int index) { (void)index; - const uint64_t last_samples = _session.cur_samplelimits() - 1; + const uint64_t last_samples = _session->cur_samplelimits() - 1; const int index1 = _start_comboBox->currentIndex(); const int index2 = _end_comboBox->currentIndex(); uint64_t decode_start, decode_end; @@ -999,15 +1091,14 @@ void DecodeTrace::on_region_set(int index) _start_index = index1; _end_index = index2; - BOOST_FOREACH(boost::shared_ptr dec, - _decoder_stack->stack()) { + for(auto &dec : _decoder_stack->stack()) { dec->set_decode_region(decode_start, decode_end); } } void DecodeTrace::frame_ended() { - const uint64_t last_samples = _session.cur_samplelimits() - 1; + const uint64_t last_samples = _session->cur_samplelimits() - 1; if (_decode_start > last_samples) { _decode_start = 0; _start_index = 0; @@ -1017,8 +1108,7 @@ void DecodeTrace::frame_ended() _decode_end = last_samples; _end_index = 0; } - BOOST_FOREACH(boost::shared_ptr dec, - _decoder_stack->stack()) { + for(auto &dec : _decoder_stack->stack()) { dec->set_decode_region(_decode_start, _decode_end); dec->commit(); } diff --git a/DSView/pv/view/decodetrace.h b/DSView/pv/view/decodetrace.h index 1fcb1257..b76c6360 100755 --- a/DSView/pv/view/decodetrace.h +++ b/DSView/pv/view/decodetrace.h @@ -22,23 +22,27 @@ #ifndef DSVIEW_PV_VIEW_DECODETRACE_H #define DSVIEW_PV_VIEW_DECODETRACE_H -#include "trace.h" #include #include - #include #include +#include -#include - -#include +#include "trace.h" +#include "../prop/binding/decoderoptions.h" #include "../dialogs/dsdialog.h" struct srd_channel; struct srd_decoder; -class QComboBox; +struct decoder_panel_item{ + QWidget *panel; + void *decoder_handle; + int panel_height; +}; + +class DsComboBox; namespace pv { @@ -60,6 +64,7 @@ class DecoderGroupBox; namespace view { +//create by SigSession class DecodeTrace : public Trace { Q_OBJECT @@ -67,8 +72,8 @@ class DecodeTrace : public Trace private: struct ProbeSelector { - const QComboBox *_combo; - const boost::shared_ptr _decoder; + const DsComboBox *_combo; + const pv::data::decode::Decoder *_decoder; const srd_channel *_pdch; }; @@ -97,14 +102,16 @@ private: static const QString RegionEnd; public: - DecodeTrace(pv::SigSession &session, - boost::shared_ptr decoder_stack, + DecodeTrace(pv::SigSession *session, + pv::data::DecoderStack *decoder_stack, int index); + +public: ~DecodeTrace(); - bool enabled() const; + bool enabled(); - const boost::shared_ptr& decoder() const; + pv::data::DecoderStack* decoder(); void set_view(pv::view::View *view); @@ -143,31 +150,31 @@ public: **/ void frame_ended(); - int get_progress() const; + int get_progress(); protected: void paint_type_options(QPainter &p, int right, const QPoint pt, QColor fore); private: - void create_popup_form(); + void create_popup_form(dialogs::DSDialog *dlg); void populate_popup_form(QWidget *parent, QFormLayout *form); void draw_annotation(const pv::data::decode::Annotation &a, QPainter &p, QColor text_colour, int text_height, int left, int right, double samples_per_pixel, double pixels_offset, int y, - size_t base_colour, double min_annWidth, QColor fore, QColor back) const; + size_t base_colour, double min_annWidth, QColor fore, QColor back); void draw_nodetail(QPainter &p, int text_height, int left, int right, int y, - size_t base_colour, QColor fore, QColor back) const; + size_t base_colour, QColor fore, QColor back); void draw_instant(const pv::data::decode::Annotation &a, QPainter &p, QColor fill, QColor outline, QColor text_color, int h, double x, - int y, double min_annWidth) const; + int y, double min_annWidth); void draw_range(const pv::data::decode::Annotation &a, QPainter &p, QColor fill, QColor outline, QColor text_color, int h, double start, - double end, int y, QColor fore, QColor back) const; + double end, int y, QColor fore, QColor back); void draw_error(QPainter &p, const QString &message, int left, int right); @@ -175,56 +182,60 @@ private: void draw_unshown_row(QPainter &p, int y, int h, int left, int right, QString info, QColor fore, QColor back); - void create_decoder_form(boost::shared_ptr &decoder_stack, - boost::shared_ptr &dec, + void create_decoder_form(data::DecoderStack *decoder_stack, + pv::data::decode::Decoder *dec, QWidget *parent, QFormLayout *form); - QComboBox* create_probe_selector(QWidget *parent, - const boost::shared_ptr &dec, + DsComboBox* create_probe_selector(QWidget *parent, + const pv::data::decode::Decoder *dec, const srd_channel *const pdch); void commit_decoder_probes( - boost::shared_ptr &dec); + data::decode::Decoder *dec); void commit_probes(); + void load_all_decoder_property(std::list &ls); signals: void decoded_progress(int progress); private slots: - void on_new_decode_data(); - - void on_delete(); - + void on_new_decode_data(); void on_probe_selected(int); - void on_stack_decoder(srd_decoder *decoder); - void on_del_stack(boost::shared_ptr &dec); + void on_del_stack(data::decode::Decoder *dec); void on_decode_done(); - void on_region_set(int index); + void on_resize_decoder_panel(); + +public: + volatile bool _delete_flag; //detroy it when deocde task end private: - pv::SigSession &_session; - boost::shared_ptr _decoder_stack; + pv::SigSession *_session; + pv::data::DecoderStack *_decoder_stack; - uint64_t _decode_start, _decode_end; - int _start_index, _end_index; - int _start_count, _end_count; - QComboBox *_start_comboBox, *_end_comboBox; - int _progress; - - std::list< boost::shared_ptr > - _bindings; + uint64_t _decode_start; + uint64_t _decode_end; + int _start_index; + int _end_index; + int _start_count; + int _end_count; + + DsComboBox *_start_comboBox; + DsComboBox *_end_comboBox; + QFormLayout *_pub_input_layer; + int _progress; + QWidget *_decoder_container; + std::list _decoder_panels; + int _form_base_height; + std::list _bindings; std::list _probe_selectors; std::vector _decoder_forms; - std::vector _cur_row_headings; - - QFormLayout *_popup_form; - dialogs::DSDialog *_popup; + std::vector _cur_row_headings; }; } // namespace view diff --git a/DSView/pv/view/devmode.cpp b/DSView/pv/view/devmode.cpp index f567a7a0..1c3b5a8d 100755 --- a/DSView/pv/view/devmode.cpp +++ b/DSView/pv/view/devmode.cpp @@ -26,57 +26,60 @@ #include "../device/devinst.h" #include "../device/file.h" -#include - -#include - -#include +#include #include #include #include #include #include +#include -using boost::shared_ptr; -using namespace std; - +#include "../config/appconfig.h" +#include "../ui/msgbox.h" + namespace pv { namespace view { -DevMode::DevMode(QWidget *parent, SigSession &session) : +DevMode::DevMode(QWidget *parent, SigSession *session) : QWidget(parent), - _session(session) - + _session(session) { - _layout = new QHBoxLayout(this); - _layout->setMargin(0); - _layout->setSpacing(0); - _layout->setContentsMargins(2, 0, 0, 0); + _bFile = false; - _close_button = new QToolButton(this); + QHBoxLayout *layout = new QHBoxLayout(this); + layout->setSpacing(0); + layout->setContentsMargins(2, 0, 0, 0); + + _close_button = new QToolButton(); _close_button->setObjectName("FileCloseButton"); _close_button->setContentsMargins(0, 0, 0, 0); _close_button->setFixedWidth(10); _close_button->setFixedHeight(height()); _close_button->setIconSize(QSize(10, 10)); - _close_button->setToolButtonStyle(Qt::ToolButtonIconOnly); + _close_button->setToolButtonStyle(Qt::ToolButtonIconOnly); + _close_button->setMinimumWidth(10); - _pop_menu = new QMenu(this); - - _mode_btn = new QToolButton(this); + _mode_btn = new QToolButton(); _mode_btn->setObjectName("ModeButton"); - _mode_btn->setIconSize(QSize(height()*2, height())); + _mode_btn->setIconSize(QSize(height() * 1.5, height())); _mode_btn->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); - _mode_btn->setContentsMargins(0, 0, 1000, 0); - _mode_btn->setMenu(_pop_menu); + _mode_btn->setContentsMargins(0, 0, 0, 0); _mode_btn->setPopupMode(QToolButton::InstantPopup); _mode_btn->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Maximum); - _layout->addWidget(_close_button); - _layout->addWidget(_mode_btn); - //_layout->addWidget(new QWidget(this)); - _layout->setStretch(1, 100); - setLayout(_layout); + // _mode_btn->setArrowType(Qt::NoArrow); + + _pop_menu = new QMenu(this); + _pop_menu->setContentsMargins(15,0,0,0); + _mode_btn->setMenu(_pop_menu); + + layout->addWidget(_close_button); + layout->addWidget(_mode_btn); + + layout->setStretch(1, 100); + setLayout(layout); + + connect(_close_button, SIGNAL(clicked()), this, SLOT(on_close())); } @@ -90,10 +93,13 @@ void DevMode::changeEvent(QEvent *event) } void DevMode::set_device() -{ - const boost::shared_ptr dev_inst = _session.get_device(); +{ + DevInst* dev_inst = _session->get_device(); assert(dev_inst); + + _bFile = false; + //remove all action object for(std::map::const_iterator i = _mode_list.begin(); i != _mode_list.end(); i++) { (*i).first->setParent(NULL); @@ -101,48 +107,54 @@ void DevMode::set_device() delete (*i).first; } _mode_list.clear(); + _close_button->setIcon(QIcon()); - _close_button->setDisabled(true); - disconnect(_close_button, SIGNAL(clicked()), this, SLOT(on_close())); + _close_button->setDisabled(true); - if (!qApp->property("Style").isNull()) { - QString iconPath = ":/icons/" + qApp->property("Style").toString() + "/"; - for (const GSList *l = dev_inst->get_dev_mode_list(); - l; l = l->next) { - const sr_dev_mode *mode = (const sr_dev_mode *)l->data; - QString icon_name = QString::fromLocal8Bit(mode->icon); + AppConfig &app = AppConfig::Instance(); + int lan = app._frameOptions.language; - QAction *action = new QAction(this); - action->setIcon(QIcon(iconPath+"square-"+icon_name)); - if (qApp->property("Language") == QLocale::Chinese) - action->setText(mode->name_cn); + QString iconPath = GetIconPath() + "/"; + + for (const GSList *l = dev_inst->get_dev_mode_list(); l; l = l->next) + { + const sr_dev_mode *mode = (const sr_dev_mode *)l->data; + QString icon_name = QString::fromLocal8Bit(mode->icon); + + QAction *action = new QAction(this); + action->setIcon(QIcon(iconPath + "square-" + icon_name)); + if (lan == LAN_CN) + action->setText(mode->name_cn); + else + action->setText(mode->name); + + connect(action, SIGNAL(triggered()), this, SLOT(on_mode_change())); + + _mode_list[action] = mode; + if (dev_inst->dev_inst()->mode == _mode_list[action]->mode) + { + QString icon_fname = iconPath + icon_name; + _mode_btn->setIcon(QIcon(icon_fname)); + if (lan == LAN_CN) + _mode_btn->setText(mode->name_cn); else - action->setText(mode->name); - connect(action, SIGNAL(triggered()), this, SLOT(on_mode_change())); - - _mode_list[action] = mode; - if (dev_inst->dev_inst()->mode == _mode_list[action]->mode) { - _mode_btn->setIcon(QIcon(iconPath+icon_name)); - if (qApp->property("Language") == QLocale::Chinese) - _mode_btn->setText(mode->name_cn); - else - _mode_btn->setText(mode->name); - } - _pop_menu->addAction(action); - } - - boost::shared_ptr file_dev; - if((file_dev = dynamic_pointer_cast(dev_inst))) { - _close_button->setDisabled(false); - _close_button->setIcon(QIcon(iconPath+"/close.svg")); - connect(_close_button, SIGNAL(clicked()), this, SLOT(on_close())); + _mode_btn->setText(mode->name); } + _pop_menu->addAction(action); } + + if ((dynamic_cast(dev_inst))) + { + _close_button->setDisabled(false); + _close_button->setIcon(QIcon(iconPath + "/close.svg")); + _bFile = true; + } + update(); } void DevMode::paintEvent(QPaintEvent*) -{ +{ using pv::view::Trace; QStyleOption o; @@ -153,45 +165,53 @@ void DevMode::paintEvent(QPaintEvent*) void DevMode::on_mode_change() { - const boost::shared_ptr dev_inst = _session.get_device(); + DevInst* dev_inst = _session->get_device(); assert(dev_inst); QAction *action = qobject_cast(sender()); if (dev_inst->dev_inst()->mode == _mode_list[action]->mode) return; - QString iconPath = ":/icons/" + qApp->property("Style").toString(); - for(std::map::const_iterator i = _mode_list.begin(); - i != _mode_list.end(); i++) { + QString iconPath = GetIconPath(); + AppConfig &app = AppConfig::Instance(); + int lan = app._frameOptions.language; + + for(auto i = _mode_list.begin();i != _mode_list.end(); i++) + { if ((*i).first == action) { if (dev_inst->dev_inst()->mode != (*i).second->mode) { - _session.set_run_mode(SigSession::Single); - _session.set_repeating(false); - _session.stop_capture(); - _session.capture_state_changed(SigSession::Stopped); - _session.session_save(); + _session->set_run_mode(SigSession::Single); + _session->set_repeating(false); + _session->stop_capture(); + _session->capture_state_changed(SigSession::Stopped); + _session->session_save(); dev_inst->set_config(NULL, NULL, SR_CONF_DEVICE_MODE, g_variant_new_int16((*i).second->mode)); - QString icon_name = "/" + QString::fromLocal8Bit((*i).second->icon); - _mode_btn->setIcon(QIcon(iconPath+icon_name)); - if (qApp->property("Language") == QLocale::Chinese) + QString icon_fname = iconPath + "/" + QString::fromLocal8Bit((*i).second->icon); + + _mode_btn->setIcon(QIcon(icon_fname)); + if (lan == LAN_CN) _mode_btn->setText((*i).second->name_cn); else _mode_btn->setText((*i).second->name); dev_changed(false); } + + break; } } } void DevMode::on_close() { - const boost::shared_ptr dev_inst = _session.get_device(); + DevInst *dev_inst = _session->get_device(); assert(dev_inst); - _session.close_file(dev_inst); - dev_changed(true); + if (_bFile && MsgBox::Confirm("are you sure to close the device?")){ + _session->close_file(dev_inst); + dev_changed(true); + } } void DevMode::mousePressEvent(QMouseEvent *event) diff --git a/DSView/pv/view/devmode.h b/DSView/pv/view/devmode.h index 999f1df0..0d148da6 100755 --- a/DSView/pv/view/devmode.h +++ b/DSView/pv/view/devmode.h @@ -22,10 +22,7 @@ #ifndef DSVIEW_PV_VIEW_DEVMODE_H #define DSVIEW_PV_VIEW_DEVMODE_H - -#include -#include - + #include #include #include @@ -33,13 +30,12 @@ #include #include -#include #include #include #include #include - + namespace pv { namespace device{ @@ -50,6 +46,7 @@ class SigSession; namespace view { +//devece work mode select list class DevMode : public QWidget { Q_OBJECT @@ -58,7 +55,7 @@ private: static const int GRID_COLS = 3; public: - DevMode(QWidget *parent, SigSession &session); + DevMode(QWidget *parent, SigSession *ession); private: void paintEvent(QPaintEvent *event); @@ -82,14 +79,13 @@ signals: void dev_changed(bool close); private: - SigSession &_session; - - QHBoxLayout * _layout; + SigSession *_session; std::map _mode_list; - QToolButton *_mode_btn; - QMenu *_pop_menu; - QPoint _mouse_point; - QToolButton *_close_button; + QToolButton *_mode_btn; + QMenu *_pop_menu; + QPoint _mouse_point; + QToolButton *_close_button; + bool _bFile; }; } // namespace view diff --git a/DSView/pv/view/dsldial.cpp b/DSView/pv/view/dsldial.cpp index f20c872c..86fa462e 100755 --- a/DSView/pv/view/dsldial.cpp +++ b/DSView/pv/view/dsldial.cpp @@ -48,7 +48,7 @@ dslDial::~dslDial() } void dslDial::paint(QPainter &p, QRectF dialRect, QColor dialColor, const QPoint pt, QString &pText) -{ +{ p.setPen(dialColor); p.setBrush(dialColor); @@ -108,6 +108,8 @@ void dslDial::paint(QPainter &p, QRectF dialRect, QColor dialColor, const QPoint inc ? 10 : -10, hoverRect.width()/2 + 4); p.restore(); } + + (void*)0; } void dslDial::set_sel(uint64_t sel) @@ -117,12 +119,12 @@ void dslDial::set_sel(uint64_t sel) _sel = sel; } -uint64_t dslDial::get_sel() const +uint64_t dslDial::get_sel() { return _sel; } -uint64_t dslDial::get_count() const +uint64_t dslDial::get_count() { return _div; } @@ -143,22 +145,22 @@ bool dslDial::isMax() return false; } -uint64_t dslDial::get_min() const +uint64_t dslDial::get_min() { return _value[0]; } -uint64_t dslDial::get_max() const +uint64_t dslDial::get_max() { return _value[_div-1]; } -uint64_t dslDial::get_value() const +uint64_t dslDial::get_value() { return _value[_sel]; } -uint64_t dslDial::get_value(uint64_t i) const +uint64_t dslDial::get_value(uint64_t i) { assert(i < _div); return _value[i]; @@ -177,7 +179,7 @@ void dslDial::set_factor(uint64_t factor) } } -uint64_t dslDial::get_factor() const +uint64_t dslDial::get_factor() { return _factor; } diff --git a/DSView/pv/view/dsldial.h b/DSView/pv/view/dsldial.h index 973e0e6e..9c0895c9 100755 --- a/DSView/pv/view/dsldial.h +++ b/DSView/pv/view/dsldial.h @@ -28,6 +28,8 @@ namespace pv { namespace view { +//when device is oscilloscope model, to draw the dail on the left +//created by DsoSignal class dslDial : public QObject { //Q_OBJECT @@ -48,23 +50,23 @@ public: // set/get current select void set_sel(uint64_t sel); - uint64_t get_sel() const; - uint64_t get_count() const; + uint64_t get_sel(); + uint64_t get_count(); // boundary detection bool isMin(); bool isMax(); - uint64_t get_min() const; - uint64_t get_max() const; + uint64_t get_min(); + uint64_t get_max(); // get current value - uint64_t get_value() const; - uint64_t get_value(uint64_t i) const; + uint64_t get_value(); + uint64_t get_value(uint64_t i); void set_value(uint64_t value); // set/get factor void set_factor(uint64_t factor); - uint64_t get_factor() const; + uint64_t get_factor(); private: uint64_t _div; diff --git a/DSView/pv/view/dsosignal.cpp b/DSView/pv/view/dsosignal.cpp index a359acad..65e5fb59 100755 --- a/DSView/pv/view/dsosignal.cpp +++ b/DSView/pv/view/dsosignal.cpp @@ -19,23 +19,19 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#include -#include - -#include "../../extdef.h" +#include "../extdef.h" #include "dsosignal.h" -#include "pv/data/dso.h" -#include "pv/data/dsosnapshot.h" +#include "../data/dso.h" +#include "../data/dsosnapshot.h" #include "view.h" #include "../sigsession.h" -#include "../device/devinst.h" - -#include - +#include "../device/devinst.h" #include #include - -using namespace boost; +#include +#include +#include + using namespace std; namespace pv { @@ -56,8 +52,8 @@ const QColor DsoSignal::SignalColours[4] = { const float DsoSignal::EnvelopeThreshold = 256.0f; -DsoSignal::DsoSignal(boost::shared_ptr dev_inst, - boost::shared_ptr data, +DsoSignal::DsoSignal(DevInst *dev_inst, + data::Dso *data, sr_channel *probe): Signal(dev_inst, probe), _data(data), @@ -108,12 +104,12 @@ DsoSignal::~DsoSignal() { } -boost::shared_ptr DsoSignal::data() const +pv::data::SignalData* DsoSignal::data() { return _data; } -boost::shared_ptr DsoSignal::dso_data() const +pv::data::Dso* DsoSignal::dso_data() { return _data; } @@ -133,17 +129,17 @@ uint8_t DsoSignal::get_bits() return _bits; } -double DsoSignal::get_ref_min() const +double DsoSignal::get_ref_min() { return _ref_min; } -double DsoSignal::get_ref_max() const +double DsoSignal::get_ref_max() { return _ref_max; } -int DsoSignal::get_name_width() const +int DsoSignal::get_name_width() { return 0; } @@ -193,7 +189,7 @@ void DsoSignal::set_enable(bool enable) _en_lock = false; } -bool DsoSignal::get_vDialActive() const +bool DsoSignal::get_vDialActive() { return _vDialActive; } @@ -400,22 +396,22 @@ int DsoSignal::commit_settings() return ret; } -dslDial * DsoSignal::get_vDial() const +dslDial * DsoSignal::get_vDial() { return _vDial; } -uint64_t DsoSignal::get_vDialValue() const +uint64_t DsoSignal::get_vDialValue() { return _vDial->get_value(); } -uint16_t DsoSignal::get_vDialSel() const +uint16_t DsoSignal::get_vDialSel() { return _vDial->get_sel(); } -uint8_t DsoSignal::get_acCoupling() const +uint8_t DsoSignal::get_acCoupling() { return _acCoupling; } @@ -429,27 +425,27 @@ void DsoSignal::set_acCoupling(uint8_t coupling) } } -int DsoSignal::ratio2value(double ratio) const +int DsoSignal::ratio2value(double ratio) { return ratio * (_ref_max - _ref_min) + _ref_min; } -int DsoSignal::ratio2pos(double ratio) const +int DsoSignal::ratio2pos(double ratio) { return ratio * get_view_rect().height() + get_view_rect().top(); } -double DsoSignal::value2ratio(int value) const +double DsoSignal::value2ratio(int value) { return max(0.0, (value - _ref_min) / (_ref_max - _ref_min)); } -double DsoSignal::pos2ratio(int pos) const +double DsoSignal::pos2ratio(int pos) { return min(max(pos - get_view_rect().top(), 0), get_view_rect().height()) * 1.0 / get_view_rect().height(); } -double DsoSignal::get_trig_vrate() const +double DsoSignal::get_trig_vrate() { if (_dev_inst->name() == "DSLogic") return value2ratio(_trig_value - ratio2value(0.5)) + get_zero_ratio(); @@ -485,17 +481,17 @@ void DsoSignal::set_trig_ratio(double ratio, bool delta_change) g_variant_new_byte(_trig_value)); } -int DsoSignal::get_zero_vpos() const +int DsoSignal::get_zero_vpos() { return ratio2pos(get_zero_ratio()); } -double DsoSignal::get_zero_ratio() const +double DsoSignal::get_zero_ratio() { return value2ratio(_zero_offset); } -int DsoSignal::get_hw_offset() const +int DsoSignal::get_hw_offset() { int hw_offset = 0; GVariant *gvar = _dev_inst->get_config(_probe, NULL, SR_CONF_PROBE_HW_OFFSET); @@ -564,7 +560,7 @@ void DsoSignal::set_show(bool show) _show = show; } -bool DsoSignal::show() const +bool DsoSignal::show() { return _show; } @@ -692,7 +688,7 @@ QString DsoSignal::get_measure(enum DSO_MEASURE_TYPE type) return mString; } -QRect DsoSignal::get_view_rect() const +QRect DsoSignal::get_view_rect() { assert(_viewport); return QRect(0, UpMargin, @@ -704,12 +700,11 @@ void DsoSignal::paint_prepare() { assert(_view); - const deque< boost::shared_ptr > &snapshots = - _data->get_snapshots(); + const auto &snapshots = _data->get_snapshots(); if (snapshots.empty()) return; - const boost::shared_ptr &snapshot = - snapshots.front(); + + const auto snapshot = snapshots.front(); if (snapshot->empty()) return; @@ -847,12 +842,11 @@ void DsoSignal::paint_mid(QPainter &p, int left, int right, QColor fore, QColor assert(scale > 0); const int64_t offset = _view->offset(); - const deque< boost::shared_ptr > &snapshots = - _data->get_snapshots(); + const auto &snapshots = _data->get_snapshots(); if (snapshots.empty()) return; - const boost::shared_ptr &snapshot = - snapshots.front(); + + const auto snapshot = snapshots.front(); if (snapshot->empty()) return; @@ -1018,7 +1012,7 @@ void DsoSignal::paint_fore(QPainter &p, int left, int right, QColor fore, QColor } } -QRectF DsoSignal::get_trig_rect(int left, int right) const +QRectF DsoSignal::get_trig_rect(int left, int right) { (void)left; @@ -1028,14 +1022,16 @@ QRectF DsoSignal::get_trig_rect(int left, int right) const } void DsoSignal::paint_trace(QPainter &p, - const boost::shared_ptr &snapshot, + const pv::data::DsoSnapshot *snapshot, int zeroY, int left, const int64_t start, const int64_t end, int hw_offset, const double pixels_offset, const double samples_per_pixel, uint64_t num_channels) { const int64_t sample_count = end - start + 1; if (sample_count > 0) { - const uint8_t *const samples = snapshot->get_samples(start, end, get_index()); + pv::data::DsoSnapshot *pshot = const_cast(snapshot); + auto pdata = pshot->get_samples(start, end, get_index()); + const uint8_t *const samples = pdata; assert(samples); QColor trace_colour = _colour; @@ -1073,16 +1069,18 @@ void DsoSignal::paint_trace(QPainter &p, } void DsoSignal::paint_envelope(QPainter &p, - const boost::shared_ptr &snapshot, + const pv::data::DsoSnapshot *snapshot, int zeroY, int left, const int64_t start, const int64_t end, int hw_offset, const double pixels_offset, const double samples_per_pixel, uint64_t num_channels) { using namespace Qt; using pv::data::DsoSnapshot; + data::DsoSnapshot *pshot = const_cast(snapshot); + DsoSnapshot::EnvelopeSection e; const uint16_t index = get_index() % num_channels; - snapshot->get_envelope_section(e, start, end, samples_per_pixel, index); + pshot->get_envelope_section(e, start, end, samples_per_pixel, index); if (e.length < 2) return; @@ -1332,7 +1330,7 @@ void DsoSignal::paint_hover_measure(QPainter &p, QColor fore, QColor back) p.drawText(hover_rect, Qt::AlignCenter | Qt::AlignTop | Qt::TextDontClip, hover_str); } - list::iterator i = _view->get_cursorList().begin(); + auto i = _view->get_cursorList().begin(); while (i != _view->get_cursorList().end()) { float pt_value; const QPointF pt = get_point((*i)->index(), pt_value); @@ -1459,8 +1457,8 @@ void DsoSignal::auto_start() _view->session().data_auto_lock(AutoLock); _autoV = true; _autoH = true; - _view->auto_trig(get_index()); - QTimer::singleShot(AutoTime, &_view->session(), SLOT(auto_end())); + _view->auto_trig(get_index()); + _end_timer.TimeOut(AutoTime, std::bind(&DsoSignal::call_auto_end, this)); //start a timeout } } @@ -1477,13 +1475,11 @@ bool DsoSignal::measure(const QPointF &p) if (!window.contains(p)) return false; - const deque< boost::shared_ptr > &snapshots = - _data->get_snapshots(); + const auto &snapshots = _data->get_snapshots(); if (snapshots.empty()) return false; - const boost::shared_ptr &snapshot = - snapshots.front(); + auto snapshot = const_cast(snapshots.front()); if (snapshot->empty()) return false; @@ -1514,13 +1510,11 @@ QPointF DsoSignal::get_point(uint64_t index, float &value) if (!enabled()) return pt; - const deque< boost::shared_ptr > &snapshots = - _data->get_snapshots(); + const auto &snapshots = _data->get_snapshots(); if (snapshots.empty()) return pt; - const boost::shared_ptr &snapshot = - snapshots.front(); + const auto snapshot = snapshots.front(); if (snapshot->empty()) return pt; @@ -1543,13 +1537,11 @@ double DsoSignal::get_voltage(uint64_t index) if (!enabled()) return 1; - const deque< boost::shared_ptr > &snapshots = - _data->get_snapshots(); + auto &snapshots = _data->get_snapshots(); if (snapshots.empty()) return 1; - const boost::shared_ptr &snapshot = - snapshots.front(); + auto snapshot = const_cast(snapshots.front()); if (snapshot->empty()) return 1; @@ -1580,5 +1572,9 @@ QString DsoSignal::get_time(double t) return str; } +void DsoSignal::call_auto_end(){ + _view->session().auto_end(); +} + } // namespace view } // namespace pv diff --git a/DSView/pv/view/dsosignal.h b/DSView/pv/view/dsosignal.h index a1b040c4..606cd5ba 100755 --- a/DSView/pv/view/dsosignal.h +++ b/DSView/pv/view/dsosignal.h @@ -24,11 +24,9 @@ #define DSVIEW_PV_DSOSIGNAL_H #include "signal.h" - -#include - +#include "../dstimer.h" + namespace pv { - namespace data { class Logic; class Dso; @@ -38,6 +36,8 @@ class DsoSnapshot; namespace view { +//when device is oscilloscope model,to draw trace +//created by SigSession class DsoSignal : public Signal { Q_OBJECT @@ -85,46 +85,44 @@ private: static const uint16_t MS_RectHeight = 25; public: - DsoSignal(boost::shared_ptr dev_inst, - boost::shared_ptr data, + DsoSignal(DevInst* dev_inst, pv::data::Dso *data, sr_channel *probe); virtual ~DsoSignal(); - boost::shared_ptr data() const; - boost::shared_ptr dso_data() const; + pv::data::SignalData* data(); + pv::data::Dso* dso_data(); void set_scale(int height); float get_scale(); uint8_t get_bits(); - double get_ref_min() const; - double get_ref_max() const; + double get_ref_min(); + double get_ref_max(); - int get_name_width() const; + int get_name_width(); /** * */ void set_enable(bool enable); - bool get_vDialActive() const; + bool get_vDialActive(); void set_vDialActive(bool active); bool go_vDialPre(bool manul); - bool go_vDialNext(bool manul); - bool update_capture(bool instant); - dslDial *get_vDial() const; - uint64_t get_vDialValue() const; - uint16_t get_vDialSel() const; - uint8_t get_acCoupling() const; + bool go_vDialNext(bool manul); + dslDial *get_vDial(); + uint64_t get_vDialValue(); + uint16_t get_vDialSel(); + uint8_t get_acCoupling(); void set_acCoupling(uint8_t coupling); void set_trig_vpos(int pos, bool delta_change = true); void set_trig_ratio(double ratio, bool delta_change = true); - double get_trig_vrate() const; + double get_trig_vrate(); void set_factor(uint64_t factor); uint64_t get_factor(); void set_show(bool show); - bool show() const; + bool show(); void set_mValid(bool valid); bool load_settings(); @@ -148,9 +146,9 @@ public: /** * Gets the mid-Y position of this signal. */ - int get_zero_vpos() const; - double get_zero_ratio() const; - int get_hw_offset() const; + int get_zero_vpos(); + double get_zero_ratio(); + int get_hw_offset(); /** * Sets the mid-Y position of this signal. */ @@ -163,10 +161,10 @@ public: /** * */ - int ratio2value(double ratio) const; - int ratio2pos(double ratio) const; - double value2ratio(int value) const; - double pos2ratio(int pos) const; + int ratio2value(double ratio); + int ratio2pos(double ratio); + double value2ratio(int value); + double pos2ratio(int pos); /** * paint prepare @@ -197,9 +195,9 @@ public: **/ void paint_fore(QPainter &p, int left, int right, QColor fore, QColor back); - QRect get_view_rect() const; + QRect get_view_rect(); - QRectF get_trig_rect(int left, int right) const; + QRectF get_trig_rect(int left, int right); QString get_measure(enum DSO_MEASURE_TYPE type); @@ -215,13 +213,13 @@ protected: private: void paint_trace(QPainter &p, - const boost::shared_ptr &snapshot, + const pv::data::DsoSnapshot* snapshot, int zeroY, int left, const int64_t start, const int64_t end, int hw_offset, const double pixels_offset, const double samples_per_pixel, uint64_t num_channels); void paint_envelope(QPainter &p, - const boost::shared_ptr &snapshot, + const pv::data::DsoSnapshot *snapshot, int zeroY, int left, const int64_t start, const int64_t end, int hw_offset, const double pixels_offset, const double samples_per_pixel, uint64_t num_channels); @@ -229,8 +227,10 @@ private: void paint_hover_measure(QPainter &p, QColor fore, QColor back); void auto_set(); + void call_auto_end(); + private: - boost::shared_ptr _data; + pv::data::Dso *_data; float _scale; bool _en_lock; bool _show; @@ -270,6 +270,7 @@ private: uint64_t _hover_index; QPointF _hover_point; float _hover_value; + DsTimer _end_timer; }; } // namespace view diff --git a/DSView/pv/view/groupsignal.cpp b/DSView/pv/view/groupsignal.cpp index 1e67f654..b33ae478 100755 --- a/DSView/pv/view/groupsignal.cpp +++ b/DSView/pv/view/groupsignal.cpp @@ -19,15 +19,14 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#include -#include - +#include "../extdef.h" #include "groupsignal.h" -#include "pv/data/group.h" -#include "pv/data/groupsnapshot.h" +#include "../data/group.h" +#include "../data/groupsnapshot.h" #include "view.h" -using namespace boost; +#include + using namespace std; namespace pv { @@ -42,7 +41,7 @@ const QColor GroupSignal::SignalColours[4] = { const float GroupSignal::EnvelopeThreshold = 256.0f; -GroupSignal::GroupSignal(QString name, boost::shared_ptr data, +GroupSignal::GroupSignal(QString name, data::Group *data, std::list probe_index_list, int group_index) : Trace(name, probe_index_list, SR_CHANNEL_GROUP, group_index), _data(data) @@ -55,12 +54,12 @@ GroupSignal::~GroupSignal() { } -bool GroupSignal::enabled() const +bool GroupSignal::enabled() { return true; } -boost::shared_ptr GroupSignal::data() const +pv::data::SignalData* GroupSignal::data() { return _data; } @@ -85,13 +84,11 @@ void GroupSignal::paint_mid(QPainter &p, int left, int right, QColor fore, QColo _scale = _totalHeight * 1.0f / std::pow(2.0, static_cast(_index_list.size())); - const deque< boost::shared_ptr > &snapshots = - _data->get_snapshots(); + const auto &snapshots = _data->get_snapshots(); if (snapshots.empty()) return; - const boost::shared_ptr &snapshot = - snapshots.at(_sec_index); + const auto snapshot = snapshots.at(_sec_index); const double pixels_offset = offset; const double samplerate = _data->samplerate(); @@ -116,13 +113,15 @@ void GroupSignal::paint_mid(QPainter &p, int left, int right, QColor fore, QColo } void GroupSignal::paint_trace(QPainter &p, - const boost::shared_ptr &snapshot, + const pv::data::GroupSnapshot *snapshot, int y, int left, const int64_t start, const int64_t end, const double pixels_offset, const double samples_per_pixel) { const int64_t sample_count = end - start; - const uint16_t *samples = snapshot->get_samples(start, end); + pv::data::GroupSnapshot *pshot = const_cast(snapshot); + + const uint16_t *samples = pshot->get_samples(start, end); assert(samples); p.setPen(_colour); @@ -144,7 +143,7 @@ void GroupSignal::paint_trace(QPainter &p, } void GroupSignal::paint_envelope(QPainter &p, - const boost::shared_ptr &snapshot, + const pv::data::GroupSnapshot *snapshot, int y, int left, const int64_t start, const int64_t end, const double pixels_offset, const double samples_per_pixel) { @@ -152,7 +151,9 @@ void GroupSignal::paint_envelope(QPainter &p, using pv::data::GroupSnapshot; GroupSnapshot::EnvelopeSection e; - snapshot->get_envelope_section(e, start, end, samples_per_pixel); + + pv::data::GroupSnapshot *pshot = const_cast(snapshot); + pshot->get_envelope_section(e, start, end, samples_per_pixel); if (e.length < 2) return; diff --git a/DSView/pv/view/groupsignal.h b/DSView/pv/view/groupsignal.h index 358c300f..a86c388e 100755 --- a/DSView/pv/view/groupsignal.h +++ b/DSView/pv/view/groupsignal.h @@ -26,8 +26,7 @@ #include "signal.h" #include "../data/groupsnapshot.h" -#include -#include +#include namespace pv { @@ -40,6 +39,7 @@ class GroupSnapshot; namespace view { +//created by SigSession class GroupSignal : public Trace { private: @@ -54,7 +54,7 @@ private: public: GroupSignal(QString name, - boost::shared_ptr data, + pv::data::Group *data, std::list probe_index_list, int group_index); virtual ~GroupSignal(); @@ -62,9 +62,9 @@ public: /** * Returns true if the trace is visible and enabled. */ - bool enabled() const; + bool enabled(); - boost::shared_ptr data() const; + pv::data::SignalData* data(); void set_scale(float scale); @@ -83,17 +83,17 @@ protected: private: void paint_trace(QPainter &p, - const boost::shared_ptr &snapshot, + const pv::data::GroupSnapshot *snapshot, int y, int left, const int64_t start, const int64_t end, const double pixels_offset, const double samples_per_pixel); void paint_envelope(QPainter &p, - const boost::shared_ptr &snapshot, + const pv::data::GroupSnapshot *snapshot, int y, int left, const int64_t start, const int64_t end, const double pixels_offset, const double samples_per_pixel); private: - boost::shared_ptr _data; + pv::data::Group *_data; float _scale; }; diff --git a/DSView/pv/view/header.cpp b/DSView/pv/view/header.cpp index 40bcaa43..58563dd3 100755 --- a/DSView/pv/view/header.cpp +++ b/DSView/pv/view/header.cpp @@ -20,10 +20,19 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#include "header.h" -#include "view.h" +#include "header.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include -#include "../../extdef.h" +#include "view.h" #include "trace.h" #include "dsosignal.h" #include "logicsignal.h" @@ -32,21 +41,10 @@ #include "decodetrace.h" #include "../sigsession.h" #include "../device/devinst.h" +#include "../extdef.h" +#include "../dsvdef.h" -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace boost; + using namespace std; namespace pv { @@ -61,6 +59,8 @@ Header::Header(View &parent) : _moveFlag = false; _colorFlag = false; _nameFlag = false; + _context_trace = NULL; + nameEdit = new QLineEdit(this); nameEdit->setFixedWidth(100); nameEdit->hide(); @@ -99,15 +99,12 @@ int Header::get_nameEditWidth() return 0; } -boost::shared_ptr Header::get_mTrace( - int &action, - const QPoint &pt) +pv::view::Trace* Header::get_mTrace(int &action, const QPoint &pt) { const int w = width(); - const vector< boost::shared_ptr > traces( - _view.get_traces(ALL_VIEW)); + const auto &traces = _view.get_traces(ALL_VIEW); - BOOST_FOREACH(const boost::shared_ptr t, traces) + for(auto &t : traces) { assert(t); @@ -115,7 +112,7 @@ boost::shared_ptr Header::get_mTrace( return t; } - return boost::shared_ptr(); + return NULL; } void Header::paintEvent(QPaintEvent*) @@ -128,13 +125,13 @@ void Header::paintEvent(QPaintEvent*) style()->drawPrimitive(QStyle::PE_Widget, &o, &painter, this); const int w = width(); - const vector< boost::shared_ptr > traces( - _view.get_traces(ALL_VIEW)); + const auto &traces = _view.get_traces(ALL_VIEW); const bool dragging = !_drag_traces.empty(); QColor fore(QWidget::palette().color(QWidget::foregroundRole())); fore.setAlpha(View::ForeAlpha); - BOOST_FOREACH(const boost::shared_ptr t, traces) + + for(auto &t : traces) { assert(t); t->paint_label(painter, w, dragging ? QPoint(-1, -1) : _mouse_point, fore); @@ -147,20 +144,19 @@ void Header::mouseDoubleClickEvent(QMouseEvent *event) { assert(event); - const vector< boost::shared_ptr > traces( - _view.get_traces(ALL_VIEW)); + const auto &traces = _view.get_traces(ALL_VIEW); if (event->button() & Qt::LeftButton) { _mouse_down_point = event->pos(); // Save the offsets of any Traces which will be dragged - BOOST_FOREACH(const boost::shared_ptr t, traces) + for(auto &t : traces) if (t->selected()) _drag_traces.push_back( make_pair(t, t->get_v_offset())); // Select the Trace if it has been clicked - BOOST_FOREACH(const boost::shared_ptr t, traces) + for(auto &t : traces) if (t->mouse_double_click(width(), event->pos())) break; } @@ -171,8 +167,7 @@ void Header::mousePressEvent(QMouseEvent *event) { assert(event); - const vector< boost::shared_ptr > traces( - _view.get_traces(ALL_VIEW)); + const auto &traces = _view.get_traces(ALL_VIEW); int action; const bool instant = _view.session().get_instant(); if (instant && _view.session().get_capture_state() == SigSession::Running) { @@ -183,14 +178,13 @@ void Header::mousePressEvent(QMouseEvent *event) _mouse_down_point = event->pos(); // Save the offsets of any Traces which will be dragged - BOOST_FOREACH(const boost::shared_ptr t, traces) + for(auto &t : traces) if (t->selected()) _drag_traces.push_back( make_pair(t, t->get_v_offset())); // Select the Trace if it has been clicked - const boost::shared_ptr mTrace = - get_mTrace(action, event->pos()); + const auto mTrace = get_mTrace(action, event->pos()); if (action == Trace::COLOR && mTrace) { _colorFlag = true; } else if (action == Trace::NAME && mTrace) { @@ -204,14 +198,14 @@ void Header::mousePressEvent(QMouseEvent *event) mTrace->set_old_v_offset(mTrace->get_v_offset()); } - BOOST_FOREACH(const boost::shared_ptr t, traces) + for(auto &t : traces) if (t->mouse_press(width(), event->pos())) break; if (~QApplication::keyboardModifiers() & Qt::ControlModifier) { // Unselect all other Traces because the Ctrl is not // pressed - BOOST_FOREACH(const boost::shared_ptr t, traces) + for(auto &t : traces) if (t != mTrace) t->select(false); } @@ -225,8 +219,7 @@ void Header::mouseReleaseEvent(QMouseEvent *event) // judge for color / name / trigger / move int action; - const boost::shared_ptr mTrace = - get_mTrace(action, event->pos()); + const auto mTrace = get_mTrace(action, event->pos()); if (mTrace){ if (action == Trace::COLOR && _colorFlag) { _context_trace = mTrace; @@ -243,10 +236,11 @@ void Header::mouseReleaseEvent(QMouseEvent *event) _view.signals_changed(); _view.set_all_update(true); - const vector< boost::shared_ptr > traces( - _view.get_traces(ALL_VIEW)); - BOOST_FOREACH(const boost::shared_ptr t, traces) + const auto &traces = _view.get_traces(ALL_VIEW); + + for(auto &t : traces){ t->select(false); + } } _colorFlag = false; @@ -260,34 +254,74 @@ void Header::wheelEvent(QWheelEvent *event) { assert(event); - if (event->orientation() == Qt::Vertical) { - const vector< boost::shared_ptr > traces( - _view.get_traces(ALL_VIEW)); + int x = 0; + int y = 0; + int delta = 0; + bool isVertical = true; + QPoint pos; + (void)x; + (void)y; + +#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) + x = (int)event->position().x(); + y = (int)event->position().y(); + int anglex = event->angleDelta().x(); + int angley = event->angleDelta().y(); + + pos.setX(x); + pos.setY(y); + + if (anglex == 0 || ABS_VAL(angley) >= ABS_VAL(anglex)){ + delta = angley; + isVertical = true; + } + else{ + delta = anglex; + isVertical = false; //hori direction + } +#else + x = event->x(); + delta = event->delta(); + isVertical = event->orientation() == Qt::Vertical; + pos = event->pos(); +#endif + + if (isVertical) + { + const auto &traces = _view.get_traces(ALL_VIEW); // Vertical scrolling double shift = 0; - #ifdef Q_OS_DARWIN + +#ifdef Q_OS_DARWIN static bool active = true; static int64_t last_time; - if (event->source() == Qt::MouseEventSynthesizedBySystem) { - if (active) { + if (event->source() == Qt::MouseEventSynthesizedBySystem) + { + if (active) + { last_time = QDateTime::currentMSecsSinceEpoch(); - shift = event->delta() > 1.5 ? -1 : - event->delta() < -1.5 ? 1 : 0; + shift = delta > 1.5 ? -1 : delta < -1.5 ? 1 : 0; } int64_t cur_time = QDateTime::currentMSecsSinceEpoch(); if (cur_time - last_time > 100) active = true; else active = false; - } else { - shift = -event->delta() / 80.0; } - #else - shift = event->delta() / 80.0; - #endif - BOOST_FOREACH(const boost::shared_ptr t, traces) - if (t->mouse_wheel(width(), event->pos(), shift)) + else + { + shift = -delta / 80.0; + } +#else + shift = delta / 80.0; +#endif + + for (auto &t : traces) + { + if (t->mouse_wheel(width(), pos, shift)) break; + } + update(); } } @@ -323,29 +357,27 @@ void Header::mouseMoveEvent(QMouseEvent *event) if (!_drag_traces.empty()) { const int delta = event->pos().y() - _mouse_down_point.y(); - for (std::list, - int> >::iterator i = _drag_traces.begin(); - i != _drag_traces.end(); i++) { - const boost::shared_ptr sig((*i).first); + for (auto i = _drag_traces.begin(); i != _drag_traces.end(); i++) { + const auto sig = (*i).first; if (sig) { int y = (*i).second + delta; if (sig->get_type() == SR_CHANNEL_DSO) { - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(sig))) { + DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(sig))) { dsoSig->set_zero_vpos(y); _moveFlag = true; traces_moved(); } } else if (sig->get_type() == SR_CHANNEL_MATH) { - boost::shared_ptr mathTrace; - if ((mathTrace = dynamic_pointer_cast(sig))) { + MathTrace *mathTrace = NULL; + if ((mathTrace = dynamic_cast(sig))) { mathTrace->set_zero_vpos(y); _moveFlag = true; traces_moved(); } } else if (sig->get_type() == SR_CHANNEL_ANALOG) { - boost::shared_ptr analogSig; - if ((analogSig = dynamic_pointer_cast(sig))) { + AnalogSignal *analogSig = NULL; + if ((analogSig = dynamic_cast(sig))) { analogSig->set_zero_vpos(y); _moveFlag = true; traces_moved(); @@ -380,7 +412,7 @@ void Header::contextMenuEvent(QContextMenuEvent *event) int action; - const boost::shared_ptr t = get_mTrace(action, _mouse_point); + const auto t = get_mTrace(action, _mouse_point); if (!t || !t->selected() || action != Trace::LABEL) return; @@ -396,12 +428,12 @@ void Header::contextMenuEvent(QContextMenuEvent *event) // _context_trace = t; // menu.exec(event->globalPos()); -// _context_trace.reset(); +// _context_trace.r-eset(); } void Header::on_action_set_name_triggered() { - boost::shared_ptr context_Trace = _context_trace; + auto context_Trace = _context_trace; if (!context_Trace) return; diff --git a/DSView/pv/view/header.h b/DSView/pv/view/header.h index 7362973a..cf7741e4 100755 --- a/DSView/pv/view/header.h +++ b/DSView/pv/view/header.h @@ -24,9 +24,6 @@ #ifndef DSVIEW_PV_VIEW_HEADER_H #define DSVIEW_PV_VIEW_HEADER_H -#include -#include - #include #include @@ -39,6 +36,8 @@ namespace view { class Trace; class View; +//the left panel of main graph +//created by View class Header : public QWidget { Q_OBJECT @@ -47,9 +46,7 @@ public: Header(View &parent); private: - boost::shared_ptr get_mTrace( - int &action, - const QPoint &pt); + pv::view::Trace* get_mTrace(int &action, const QPoint &pt); private: void changeEvent(QEvent *event); @@ -98,10 +95,9 @@ private: QLineEdit *nameEdit; - std::list, int> > - _drag_traces; + std::list > _drag_traces; - boost::shared_ptr _context_trace; + Trace *_context_trace; QAction *_action_add_group; QAction *_action_del_group; diff --git a/DSView/pv/view/lissajoustrace.cpp b/DSView/pv/view/lissajoustrace.cpp index f2c5959c..a39a66e7 100755 --- a/DSView/pv/view/lissajoustrace.cpp +++ b/DSView/pv/view/lissajoustrace.cpp @@ -19,30 +19,30 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#include + #include -#include "../../extdef.h" -#include "lissajoustrace.h" -#include "pv/data/dso.h" -#include "pv/data/dsosnapshot.h" #include "view.h" +#include "../extdef.h" +#include "lissajoustrace.h" +#include "../data/dso.h" +#include "../data/dsosnapshot.h" #include "../sigsession.h" #include "../device/devinst.h" -#include + #include #include -using namespace boost; + using namespace std; namespace pv { namespace view { LissajousTrace::LissajousTrace(bool enable, - boost::shared_ptr data, + data::Dso *data, int xIndex, int yIndex, int percent): Trace("Lissajous", xIndex, SR_CHANNEL_LISSAJOUS), _data(data), @@ -58,7 +58,7 @@ LissajousTrace::~LissajousTrace() { } -bool LissajousTrace::enabled() const +bool LissajousTrace::enabled() { return _enable; } @@ -68,27 +68,27 @@ void LissajousTrace::set_enable(bool enable) _enable = enable; } -int LissajousTrace::xIndex() const +int LissajousTrace::xIndex() { return _xIndex; } -int LissajousTrace::yIndex() const +int LissajousTrace::yIndex() { return _yIndex; } -int LissajousTrace::percent() const +int LissajousTrace::percent() { return _percent; } -boost::shared_ptr LissajousTrace::get_data() const +pv::data::Dso* LissajousTrace::get_data() { return _data; } -void LissajousTrace::set_data(boost::shared_ptr data) +void LissajousTrace::set_data(data::Dso *data) { _data = data; } @@ -151,12 +151,11 @@ void LissajousTrace::paint_mid(QPainter &p, int left, int right, QColor fore, QC assert(right >= left); if (enabled()) { - const deque< boost::shared_ptr > &snapshots = - _data->get_snapshots(); + const auto &snapshots = _data->get_snapshots(); if (snapshots.empty()) return; - const boost::shared_ptr &snapshot = - snapshots.front(); + + auto snapshot = snapshots.front(); if (snapshot->empty()) return; diff --git a/DSView/pv/view/lissajoustrace.h b/DSView/pv/view/lissajoustrace.h index 1b5dd2f3..5a038a33 100755 --- a/DSView/pv/view/lissajoustrace.h +++ b/DSView/pv/view/lissajoustrace.h @@ -24,9 +24,7 @@ #define DSVIEW_PV_LISSAJOUSTRACE_H #include "trace.h" - -#include - + namespace pv { namespace data { @@ -38,28 +36,29 @@ class DsoSnapshot; namespace view { +//when device is oscilloscope mode, it can use to draw Lissajous graph +//created by SigSession class LissajousTrace : public Trace { Q_OBJECT private: - static const int DIV_NUM = 10; + static const int DIV_NUM = 10; public: - LissajousTrace(bool enable, - boost::shared_ptr data, + LissajousTrace(bool enable, pv::data::Dso *data, int xIndex, int yIndex, int percent); virtual ~LissajousTrace(); - bool enabled() const; + bool enabled(); void set_enable(bool enable); - int xIndex() const; - int yIndex() const; - int percent() const; + int xIndex(); + int yIndex(); + int percent(); - boost::shared_ptr get_data() const; - void set_data(boost::shared_ptr data); + pv::data::Dso* get_data(); + void set_data(pv::data::Dso* data); int rows_size(); @@ -90,7 +89,7 @@ public: void paint_label(QPainter &p, int right, const QPoint pt, QColor fore); private: - boost::shared_ptr _data; + pv::data::Dso *_data; bool _enable; int _xIndex; diff --git a/DSView/pv/view/logicsignal.cpp b/DSView/pv/view/logicsignal.cpp index 95d57b67..dae072a8 100755 --- a/DSView/pv/view/logicsignal.cpp +++ b/DSView/pv/view/logicsignal.cpp @@ -21,18 +21,15 @@ */ #include - -#include - + #include - #include - #include "logicsignal.h" #include "view.h" -#include "pv/data/logic.h" -#include "pv/data/logicsnapshot.h" +#include "../data/logic.h" +#include "../data/logicsnapshot.h" #include "view.h" +#include "../extdef.h" using namespace boost; using namespace std; @@ -45,8 +42,8 @@ const float LogicSignal::Oversampling = 1.0f; const int LogicSignal::StateHeight = 12; const int LogicSignal::StateRound = 5; -LogicSignal::LogicSignal(boost::shared_ptr dev_inst, - boost::shared_ptr data, +LogicSignal::LogicSignal(DevInst *dev_inst, + data::Logic *data, sr_channel *probe) : Signal(dev_inst, probe), _data(data), @@ -54,10 +51,10 @@ LogicSignal::LogicSignal(boost::shared_ptr dev_inst, { } -LogicSignal::LogicSignal(boost::shared_ptr s, - boost::shared_ptr data, +LogicSignal::LogicSignal(view::LogicSignal *s, + data::Logic *data, sr_channel *probe) : - Signal(*s.get(), probe), + Signal(*s, probe), _data(data), _trig(s->get_trig()) { @@ -69,22 +66,22 @@ LogicSignal::~LogicSignal() _cur_pulses.clear(); } -const sr_channel* LogicSignal::probe() const +const sr_channel* LogicSignal::probe() { return _probe; } -boost::shared_ptr LogicSignal::data() const +pv::data::SignalData* LogicSignal::data() { return _data; } -boost::shared_ptr LogicSignal::logic_data() const +pv::data::Logic* LogicSignal::logic_data() { return _data; } -LogicSignal::LogicSetRegions LogicSignal::get_trig() const +LogicSignal::LogicSetRegions LogicSignal::get_trig() { return _trig; } @@ -137,14 +134,12 @@ void LogicSignal::paint_mid(QPainter &p, int left, int right, QColor fore, QColo const int high_offset = y - _totalHeight + 0.5f; const int low_offset = y + 0.5f; - const deque< boost::shared_ptr > &snapshots = - _data->get_snapshots(); + const auto &snapshots =_data->get_snapshots(); double samplerate = _data->samplerate(); if (snapshots.empty() || samplerate == 0) return; - - const boost::shared_ptr &snapshot = - snapshots.front(); + + auto snapshot = const_cast(snapshots.front()); if (snapshot->empty() || !snapshot->has_data(_probe->index)) return; @@ -202,7 +197,7 @@ void LogicSignal::paint_mid(QPainter &p, int left, int right, QColor fore, QColo } void LogicSignal::paint_caps(QPainter &p, QLineF *const lines, - vector< pair > &edges, bool level, + std::vector< pair > &edges, bool level, double samples_per_pixel, double pixels_offset, float x_offset, float y_offset) { @@ -210,7 +205,7 @@ void LogicSignal::paint_caps(QPainter &p, QLineF *const lines, uint64_t curX = 0; uint64_t nxtX = 0; - for (vector::const_iterator i = + for (std::vector::const_iterator i = edges.begin(); i != (edges.end() - 1); i++) if ((*i).second == level) { curX = ((*i).first / samples_per_pixel - @@ -289,17 +284,15 @@ void LogicSignal::paint_type_options(QPainter &p, int right, const QPoint pt, QC edgeTrig_rect.right() - 5, edgeTrig_rect.bottom() - 5); } -bool LogicSignal::measure(const QPointF &p, uint64_t &index0, uint64_t &index1, uint64_t &index2) const +bool LogicSignal::measure(const QPointF &p, uint64_t &index0, uint64_t &index1, uint64_t &index2) { const float gap = abs(p.y() - get_y()); if (gap < get_totalHeight() * 0.5) { - const deque< boost::shared_ptr > &snapshots = - _data->get_snapshots(); + const auto &snapshots =_data->get_snapshots(); if (snapshots.empty()) return false; - const boost::shared_ptr &snapshot = - snapshots.front(); + const auto snapshot = snapshots.front(); if (snapshot->empty() || !snapshot->has_data(_probe->index)) return false; @@ -343,18 +336,16 @@ bool LogicSignal::measure(const QPointF &p, uint64_t &index0, uint64_t &index1, return false; } -bool LogicSignal::edge(const QPointF &p, uint64_t &index, int radius) const +bool LogicSignal::edge(const QPointF &p, uint64_t &index, int radius) { uint64_t pre_index, nxt_index; const float gap = abs(p.y() - get_y()); if (gap < get_totalHeight() * 0.5) { - const deque< boost::shared_ptr > &snapshots = - _data->get_snapshots(); + const auto &snapshots = _data->get_snapshots(); if (snapshots.empty()) return false; - const boost::shared_ptr &snapshot = - snapshots.front(); + const auto snapshot = snapshots.front(); if (snapshot->empty() || !snapshot->has_data(_probe->index)) return false; @@ -397,7 +388,7 @@ bool LogicSignal::edge(const QPointF &p, uint64_t &index, int radius) const return false; } -bool LogicSignal::edges(const QPointF &p, uint64_t start, uint64_t &rising, uint64_t &falling) const +bool LogicSignal::edges(const QPointF &p, uint64_t start, uint64_t &rising, uint64_t &falling) { uint64_t end; const float gap = abs(p.y() - get_y()); @@ -408,15 +399,13 @@ bool LogicSignal::edges(const QPointF &p, uint64_t start, uint64_t &rising, uint return false; } -bool LogicSignal::edges(uint64_t end, uint64_t start, uint64_t &rising, uint64_t &falling) const +bool LogicSignal::edges(uint64_t end, uint64_t start, uint64_t &rising, uint64_t &falling) { - const deque< boost::shared_ptr > &snapshots = - _data->get_snapshots(); + const auto &snapshots = _data->get_snapshots(); if (snapshots.empty()) return false; - const boost::shared_ptr &snapshot = - snapshots.front(); + const auto snapshot = snapshots.front(); if (snapshot->empty() || !snapshot->has_data(_probe->index)) return false; diff --git a/DSView/pv/view/logicsignal.h b/DSView/pv/view/logicsignal.h index 2cb30d4e..931c0df6 100755 --- a/DSView/pv/view/logicsignal.h +++ b/DSView/pv/view/logicsignal.h @@ -26,9 +26,7 @@ #include "signal.h" -#include - -#include +#include namespace pv { @@ -37,8 +35,12 @@ class Logic; class Analog; } +using namespace pv::device; + namespace view { +//when device is logic analyzer mode, to draw logic signal trace +//created by SigSession class LogicSignal : public Signal { Q_OBJECT @@ -62,26 +64,22 @@ public: }; public: - LogicSignal(boost::shared_ptr dev_inst, - boost::shared_ptr data, - sr_channel *probe); + LogicSignal(DevInst *dev_inst, data::Logic* data, sr_channel *probe); - LogicSignal(boost::shared_ptr s, - boost::shared_ptr data, - sr_channel *probe); + LogicSignal(view::LogicSignal*s, pv::data::Logic *data, sr_channel *probe); virtual ~LogicSignal(); - const sr_channel* probe() const; + const sr_channel* probe(); - boost::shared_ptr data() const; + pv::data::SignalData* data(); - boost::shared_ptr logic_data() const; + pv::data::Logic* logic_data(); /** * */ - LogicSetRegions get_trig() const; + LogicSetRegions get_trig(); void set_trig(int trig); bool commit_trig(); @@ -93,13 +91,13 @@ public: **/ void paint_mid(QPainter &p, int left, int right, QColor fore, QColor back); - bool measure(const QPointF &p, uint64_t &index0, uint64_t &index1, uint64_t &index2) const; + bool measure(const QPointF &p, uint64_t &index0, uint64_t &index1, uint64_t &index2); - bool edge(const QPointF &p, uint64_t &index, int radius) const; + bool edge(const QPointF &p, uint64_t &index, int radius); - bool edges(const QPointF &p, uint64_t start, uint64_t &rising, uint64_t &falling) const; + bool edges(const QPointF &p, uint64_t start, uint64_t &rising, uint64_t &falling); - bool edges(uint64_t end, uint64_t start, uint64_t &rising, uint64_t &falling) const; + bool edges(uint64_t end, uint64_t start, uint64_t &rising, uint64_t &falling); bool mouse_press(int right, const QPoint pt); @@ -118,7 +116,7 @@ private: float x_offset, float y_offset); private: - boost::shared_ptr _data; + pv::data::Logic* _data; std::vector< std::pair > _cur_edges; std::vector> _cur_pulses; LogicSetRegions _trig; diff --git a/DSView/pv/view/mathtrace.cpp b/DSView/pv/view/mathtrace.cpp index fe838d9b..8ea5d8ff 100755 --- a/DSView/pv/view/mathtrace.cpp +++ b/DSView/pv/view/mathtrace.cpp @@ -19,10 +19,9 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#include + #include -#include "../../extdef.h" #include "mathtrace.h" #include "../data/dso.h" #include "../data/dsosnapshot.h" @@ -31,22 +30,20 @@ #include "../sigsession.h" #include "../device/devinst.h" #include "../view/dsosignal.h" - -#include - +#include "../dsvdef.h" +#include "../extdef.h" + #include #include -using namespace boost; using namespace std; namespace pv { namespace view { -MathTrace::MathTrace(bool enable, - boost::shared_ptr math_stack, - boost::shared_ptr dsoSig1, - boost::shared_ptr dsoSig2): +MathTrace::MathTrace(bool enable,data::MathStack *math_stack, + view::DsoSignal *dsoSig1, + view::DsoSignal *dsoSig2): Trace("M", dsoSig1->get_index(), SR_CHANNEL_MATH), _math_stack(math_stack), _dsoSig1(dsoSig1), @@ -70,9 +67,10 @@ MathTrace::MathTrace(bool enable, MathTrace::~MathTrace() { + DESTROY_OBJECT(_math_stack); } -bool MathTrace::enabled() const +bool MathTrace::enabled() { return _enable; } @@ -82,12 +80,12 @@ void MathTrace::set_enable(bool enable) _enable = enable; } -int MathTrace::src1() const +int MathTrace::src1() { return _dsoSig1->get_index(); } -int MathTrace::src2() const +int MathTrace::src2() { return _dsoSig2->get_index(); } @@ -97,7 +95,7 @@ float MathTrace::get_scale() return _scale; } -int MathTrace::get_name_width() const +int MathTrace::get_name_width() { return 0; } @@ -139,12 +137,12 @@ void MathTrace::go_vDialNext() } } -uint64_t MathTrace::get_vDialValue() const +uint64_t MathTrace::get_vDialValue() { return _vDial->get_value(); } -uint16_t MathTrace::get_vDialSel() const +uint16_t MathTrace::get_vDialSel() { return _vDial->get_sel(); } @@ -160,7 +158,7 @@ void MathTrace::set_zero_vrate(double rate) _hw_offset = _zero_vrate * (_ref_max - _ref_min) + _ref_min; } -int MathTrace::get_zero_vpos() const +int MathTrace::get_zero_vpos() { return _zero_vrate * get_view_rect().height() + DsoSignal::UpMargin; } @@ -178,7 +176,7 @@ void MathTrace::set_show(bool show) _show = show; } -QRect MathTrace::get_view_rect() const +QRect MathTrace::get_view_rect() { assert(_viewport); return QRect(0, DsoSignal::UpMargin, @@ -427,7 +425,7 @@ void MathTrace::paint_hover_measure(QPainter &p, QColor fore, QColor back) p.drawText(hover_rect, Qt::AlignCenter | Qt::AlignTop | Qt::TextDontClip, hover_str); } - list::iterator i = _view->get_cursorList().begin(); + auto i = _view->get_cursorList().begin(); while (i != _view->get_cursorList().end()) { float pt_value; const QPointF pt = get_point((*i)->index(), pt_value); @@ -501,7 +499,7 @@ QString MathTrace::get_time(double t) return str; } -const boost::shared_ptr& MathTrace::get_math_stack() const +pv::data::MathStack* MathTrace::get_math_stack() { return _math_stack; } diff --git a/DSView/pv/view/mathtrace.h b/DSView/pv/view/mathtrace.h index 3bcd9428..8eb6413b 100755 --- a/DSView/pv/view/mathtrace.h +++ b/DSView/pv/view/mathtrace.h @@ -23,9 +23,7 @@ #ifndef DSVIEW_PV_MATHTRACE_H #define DSVIEW_PV_MATHTRACE_H -#include "trace.h" - -#include +#include "trace.h" namespace pv { @@ -52,15 +50,15 @@ public: }; public: - MathTrace(bool enable, boost::shared_ptr math_stack, - boost::shared_ptr dsoSig1, - boost::shared_ptr dsoSig2); + MathTrace(bool enable, pv::data::MathStack *math_stack, + view::DsoSignal *dsoSig1, + view::DsoSignal *dsoSig2); virtual ~MathTrace(); float get_scale(); - int get_name_width() const; + int get_name_width(); /** * @@ -68,18 +66,18 @@ public: void update_vDial(); void go_vDialPre(); void go_vDialNext(); - uint64_t get_vDialValue() const; - uint16_t get_vDialSel() const; + uint64_t get_vDialValue(); + uint16_t get_vDialSel(); - bool enabled() const; + bool enabled(); void set_enable(bool enable); void set_show(bool show); - int get_zero_vpos() const; + int get_zero_vpos(); void set_zero_vpos(int pos); - int src1() const; - int src2() const; + int src1(); + int src2(); /** * @@ -125,13 +123,13 @@ public: **/ void paint_fore(QPainter &p, int left, int right, QColor fore, QColor back); - QRect get_view_rect() const; + QRect get_view_rect(); QRectF get_rect(MathSetRegions type, int y, int right); bool mouse_wheel(int right, const QPoint pt, const int shift); - const boost::shared_ptr& get_math_stack() const; + pv::data::MathStack* get_math_stack(); protected: void paint_type_options(QPainter &p, int right, const QPoint pt, QColor fore); @@ -148,9 +146,9 @@ private: void paint_hover_measure(QPainter &p, QColor fore, QColor back); private: - boost::shared_ptr _math_stack; - boost::shared_ptr _dsoSig1; - boost::shared_ptr _dsoSig2; + pv::data::MathStack *_math_stack; + view::DsoSignal *_dsoSig1; + view::DsoSignal *_dsoSig2; bool _enable; bool _show; diff --git a/DSView/pv/view/ruler.cpp b/DSView/pv/view/ruler.cpp index 86448b42..7abc58e7 100755 --- a/DSView/pv/view/ruler.cpp +++ b/DSView/pv/view/ruler.cpp @@ -28,8 +28,7 @@ #include "../sigsession.h" #include "../device/devinst.h" #include "dsosignal.h" - -#include +#include "../extdef.h" #include #include @@ -38,12 +37,11 @@ #include #include #include -#include - -#include - -using namespace boost; +#include + + using namespace std; +using namespace Qt; namespace pv { namespace view { @@ -98,12 +96,21 @@ QString Ruler::format_freq(double period, unsigned precision) const int prefix = ceil((order - FirstSIPrefixPower) / 3.0f); const double multiplier = pow(10.0, max(-prefix * 3.0 - FirstSIPrefixPower, 0.0)); + /* QString s; QTextStream ts(&s); ts.setRealNumberPrecision(precision); ts << fixed << 1 / (period * multiplier) << FreqPrefixes[prefix] << "Hz"; return s; + */ + + char buf[20] = {0}; + char format[10] = {0}; + sprintf(format, "%%.%df%%s", precision); + QString prev = FreqPrefixes[prefix] + "Hz"; + sprintf(buf, format, 1 / (period * multiplier), prev.toLatin1().data()); + return QString(buf); } } @@ -112,12 +119,21 @@ QString Ruler::format_time(double t, int prefix, { const double multiplier = pow(10.0, -prefix * 3 - FirstSIPrefixPower + 6.0); + /* QString s; QTextStream ts(&s); ts.setRealNumberPrecision(precision); ts << fixed << forcesign << (t * multiplier) / 1000000.0 << SIPrefixes[prefix] << "s"; return s; + */ + + char buf[20] = {0}; + char format[10] = {0}; + sprintf(format, "%%.%df%%s", precision); + QString prev = FreqPrefixes[prefix] + "s"; + sprintf(buf, format, (t * multiplier) / 1000000.0, prev.toLatin1().data()); + return QString(buf); } QString Ruler::format_time(double t) @@ -168,7 +184,7 @@ void Ruler::rel_grabbed_cursor() } void Ruler::paintEvent(QPaintEvent*) -{ +{ QStyleOption o; o.initFrom(this); QPainter p(this); @@ -219,7 +235,7 @@ void Ruler::mousePressEvent(QMouseEvent *event) bool visible; if (!_cursor_sel_visible & !_view.get_cursorList().empty()) { _view.show_cursors(true); - list::iterator i = _view.get_cursorList().begin(); + auto i = _view.get_cursorList().begin(); while (i != _view.get_cursorList().end()) { const QRect cursor_rect((*i)->get_label_rect(rect(), visible)); if ((*i)->get_close_rect(cursor_rect).contains(event->pos())) { @@ -262,7 +278,7 @@ void Ruler::mouseReleaseEvent(QMouseEvent *event) _view.show_cursors(true); updatedCursor = true; } else if (overCursor > 0) { - list::iterator i = _view.get_cursorList().begin(); + auto i = _view.get_cursorList().begin(); while (--overCursor != 0) i++; (*i)->set_index(index); @@ -304,7 +320,7 @@ void Ruler::mouseReleaseEvent(QMouseEvent *event) int overCursor; overCursor = in_cursor_sel_rect(event->pos()); if (overCursor > 0) { - list::iterator i = _view.get_cursorList().begin(); + auto i = _view.get_cursorList().begin(); while (--overCursor != 0) i++; _view.del_cursor(*i); @@ -430,7 +446,7 @@ void Ruler::draw_logic_tick_mark(QPainter &p) // Draw the cursors if (!_view.get_cursorList().empty()) { - list::iterator i = _view.get_cursorList().begin(); + auto i = _view.get_cursorList().begin(); int index = 1; while (i != _view.get_cursorList().end()) { (*i)->paint_label(p, rect(), prefix, index, _view.session().get_capture_state() == SigSession::Stopped); @@ -548,7 +564,7 @@ void Ruler::draw_osc_tick_mark(QPainter &p) // Draw the cursors if (!_view.get_cursorList().empty()) { - list::iterator i = _view.get_cursorList().begin(); + auto i = _view.get_cursorList().begin(); int index = 1; while (i != _view.get_cursorList().end()) { (*i)->paint_label(p, rect(), prefix, index, _view.session().get_capture_state() == SigSession::Stopped); @@ -613,7 +629,7 @@ void Ruler::draw_cursor_sel(QPainter &p) if (!_view.get_cursorList().empty()) { int index = 1; - list::iterator i = _view.get_cursorList().begin(); + auto i = _view.get_cursorList().begin(); while (i != _view.get_cursorList().end()) { const QRectF cursorRect = get_cursor_sel_rect(index); p.setPen(QPen(Qt::black, 1, Qt::DotLine)); @@ -662,7 +678,7 @@ void Ruler::hover_point_changed() update(); } -double Ruler::get_min_period() const +double Ruler::get_min_period() { return _min_period / MinPeriodScale; } diff --git a/DSView/pv/view/ruler.h b/DSView/pv/view/ruler.h index f3cf204d..822c7d5f 100755 --- a/DSView/pv/view/ruler.h +++ b/DSView/pv/view/ruler.h @@ -33,6 +33,8 @@ namespace view { class TimeMarker; class View; +//the rule panel on the top +//created by View class Ruler : public QWidget { Q_OBJECT @@ -67,7 +69,7 @@ public: void set_grabbed_cursor(TimeMarker* grabbed_marker); void rel_grabbed_cursor(); - double get_min_period() const; + double get_min_period(); private: void paintEvent(QPaintEvent *event); diff --git a/DSView/pv/view/selectableitem.cpp b/DSView/pv/view/selectableitem.cpp index 1c4d987e..ed23e2ff 100755 --- a/DSView/pv/view/selectableitem.cpp +++ b/DSView/pv/view/selectableitem.cpp @@ -21,10 +21,10 @@ */ #include "selectableitem.h" - -#include + #include #include +#include namespace pv { namespace view { @@ -36,7 +36,7 @@ SelectableItem::SelectableItem() : { } -bool SelectableItem::selected() const +bool SelectableItem::selected() { return _selected; } diff --git a/DSView/pv/view/selectableitem.h b/DSView/pv/view/selectableitem.h index de9998a9..4a23cc97 100755 --- a/DSView/pv/view/selectableitem.h +++ b/DSView/pv/view/selectableitem.h @@ -35,6 +35,7 @@ namespace pv { namespace view { +//Trace's base class class SelectableItem : public QObject { Q_OBJECT @@ -42,14 +43,14 @@ class SelectableItem : public QObject private: static const int HighlightRadius; -public: +protected: SelectableItem(); public: /** * Returns true if the signal has been selected by the user. */ - bool selected() const; + bool selected(); /** * Selects or deselects the signal. diff --git a/DSView/pv/view/signal.cpp b/DSView/pv/view/signal.cpp index d694c033..f8146bef 100755 --- a/DSView/pv/view/signal.cpp +++ b/DSView/pv/view/signal.cpp @@ -20,21 +20,17 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#include - -#include - -#include - + +#include #include "signal.h" #include "view.h" #include "../device/devinst.h" +#include "../extdef.h" namespace pv { namespace view { -Signal::Signal(boost::shared_ptr dev_inst, - sr_channel *probe) : +Signal::Signal(DevInst *dev_inst,sr_channel *probe) : Trace(probe->name, probe->index, probe->type), _dev_inst(dev_inst), _probe(probe) @@ -48,7 +44,7 @@ Signal::Signal(const Signal &s, sr_channel *probe) : { } -bool Signal::enabled() const +bool Signal::enabled() { return _probe->enabled; } @@ -60,7 +56,7 @@ void Signal::set_name(QString name) _probe->name = g_strdup(name.toUtf8().data()); } -boost::shared_ptr Signal::get_device() const +DevInst* Signal::get_device() { return _dev_inst; } diff --git a/DSView/pv/view/signal.h b/DSView/pv/view/signal.h index 0c37ca9d..931d54b6 100755 --- a/DSView/pv/view/signal.h +++ b/DSView/pv/view/signal.h @@ -23,8 +23,7 @@ #ifndef DSVIEW_PV_SIGNAL_H #define DSVIEW_PV_SIGNAL_H - -#include + #include #include @@ -48,8 +47,11 @@ namespace device { class DevInst; } +using namespace pv::device; + namespace view { +//draw signal trace base class class Signal : public Trace { Q_OBJECT @@ -58,8 +60,7 @@ private: protected: - Signal(boost::shared_ptr dev_inst, - sr_channel * const probe); + Signal(DevInst* dev_inst,sr_channel * const probe); /** * Copy constructor @@ -67,12 +68,12 @@ protected: Signal(const Signal &s, sr_channel * const probe); public: - virtual boost::shared_ptr data() const = 0; + virtual pv::data::SignalData* data() = 0; /** * Returns true if the trace is visible and enabled. */ - bool enabled() const; + bool enabled(); /** * Sets the name of the signal. @@ -89,10 +90,10 @@ public: */ //virtual void paint_label(QPainter &p, int right, bool hover, int action); - boost::shared_ptr get_device() const; + DevInst* get_device(); protected: - boost::shared_ptr _dev_inst; + DevInst* _dev_inst; sr_channel *const _probe; }; diff --git a/DSView/pv/view/spectrumtrace.cpp b/DSView/pv/view/spectrumtrace.cpp index 4be12280..b55a1325 100755 --- a/DSView/pv/view/spectrumtrace.cpp +++ b/DSView/pv/view/spectrumtrace.cpp @@ -18,12 +18,12 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#include + #include #include - -#include +#include #include +#include #include "spectrumtrace.h" #include "../sigsession.h" @@ -33,6 +33,8 @@ #include "../view/viewport.h" #include "../device/devinst.h" #include "../data/spectrumstack.h" +#include "../dsvdef.h" +#include "../extdef.h" using namespace boost; using namespace std; @@ -67,8 +69,8 @@ const int SpectrumTrace::DbvRanges[4] = { const int SpectrumTrace::HoverPointSize = 3; const double SpectrumTrace::VerticalRate = 1.0 / 2000.0; -SpectrumTrace::SpectrumTrace(pv::SigSession &session, - boost::shared_ptr spectrum_stack, int index) : +SpectrumTrace::SpectrumTrace(pv::SigSession *session, + pv::data::SpectrumStack *spectrum_stack, int index) : Trace("FFT("+QString::number(index)+")", index, SR_CHANNEL_FFT), _session(session), _spectrum_stack(spectrum_stack), @@ -79,21 +81,21 @@ SpectrumTrace::SpectrumTrace(pv::SigSession &session, _offset(0) { _typeWidth = 0; - const vector< boost::shared_ptr > sigs(_session.get_signals()); + const auto &sigs = _session->get_signals(); for(size_t i = 0; i < sigs.size(); i++) { - const boost::shared_ptr s(sigs[i]); + const auto s = sigs[i]; assert(s); - if (dynamic_pointer_cast(s) && index == s->get_index()) + if (dynamic_cast(s) && index == s->get_index()) _colour = s->get_colour(); } } SpectrumTrace::~SpectrumTrace() { - + DESTROY_OBJECT(_spectrum_stack); } -bool SpectrumTrace::enabled() const +bool SpectrumTrace::enabled() { return _enable; } @@ -103,7 +105,7 @@ void SpectrumTrace::set_enable(bool enable) _enable = enable; } -int SpectrumTrace::view_mode() const +int SpectrumTrace::view_mode() { return _view_mode; } @@ -123,7 +125,7 @@ std::vector SpectrumTrace::get_view_modes_support() return modes; } -const boost::shared_ptr& SpectrumTrace::get_spectrum_stack() const +pv::data::SpectrumStack* SpectrumTrace::get_spectrum_stack() { return _spectrum_stack; } @@ -160,7 +162,7 @@ void SpectrumTrace::set_offset(double delta) _view->update(); } -double SpectrumTrace::get_offset() const +double SpectrumTrace::get_offset() { return _offset; } @@ -173,7 +175,7 @@ void SpectrumTrace::set_scale(double scale) _view->update(); } -double SpectrumTrace::get_scale() const +double SpectrumTrace::get_scale() { return _scale; } @@ -183,7 +185,7 @@ void SpectrumTrace::set_dbv_range(int range) _dbv_range = range; } -int SpectrumTrace::dbv_range() const +int SpectrumTrace::dbv_range() { return _dbv_range; } @@ -208,12 +210,17 @@ QString SpectrumTrace::format_freq(double freq, unsigned precision) const int prefix = floor((order - FirstSIPrefixPower)/ 3.0f); const double divider = pow(10.0, max(prefix * 3.0 + FirstSIPrefixPower, 0.0)); - QString s; - QTextStream ts(&s); - ts.setRealNumberPrecision(precision); - ts << fixed << freq / divider << - FreqPrefixes[prefix] << "Hz"; - return s; + //QString s; + //QTextStream ts(&s); + //ts.setRealNumberPrecision(precision); + //ts << fixed << freq / divider << FreqPrefixes[prefix] << "Hz"; + //return s; + char buf[20] = {0}; + char format[10] = {0}; + sprintf(format, "%%.%df%%s", precision); + QString prev = FreqPrefixes[prefix] + "Hz"; + sprintf(buf, format, freq / divider, prev.toLatin1().data()); + return QString(buf); } } @@ -294,9 +301,10 @@ void SpectrumTrace::paint_mid(QPainter &p, int left, int right, QColor fore, QCo double vdiv = 0; double vfactor = 0; - BOOST_FOREACH(const boost::shared_ptr s, _session.get_signals()) { - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s))) { + + for(auto &s : _session->get_signals()) { + DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(s))) { if(dsoSig->get_index() == _spectrum_stack->get_index()) { vdiv = dsoSig->get_vDialValue(); vfactor = dsoSig->get_factor(); @@ -364,8 +372,8 @@ void SpectrumTrace::paint_fore(QPainter &p, int left, int right, QColor fore, QC double blank_right = width; // horizontal ruler - const double NyFreq = _session.cur_snap_samplerate() / (2.0 * _spectrum_stack->get_sample_interval()); - const double deltaFreq = _session.cur_snap_samplerate() * 1.0 / + const double NyFreq = _session->cur_snap_samplerate() / (2.0 * _spectrum_stack->get_sample_interval()); + const double deltaFreq = _session->cur_snap_samplerate() * 1.0 / (_spectrum_stack->get_sample_num() * _spectrum_stack->get_sample_interval()); const double FreqRange = NyFreq * _scale; const double FreqOffset = NyFreq * _offset; @@ -482,7 +490,7 @@ void SpectrumTrace::paint_type_options(QPainter &p, int right, const QPoint pt, (void)fore; } -QRect SpectrumTrace::get_view_rect() const +QRect SpectrumTrace::get_view_rect() { assert(_viewport); return QRect(0, UpMargin, diff --git a/DSView/pv/view/spectrumtrace.h b/DSView/pv/view/spectrumtrace.h index e8a08796..9c3f368b 100755 --- a/DSView/pv/view/spectrumtrace.h +++ b/DSView/pv/view/spectrumtrace.h @@ -25,8 +25,7 @@ #include #include - -#include + struct srd_channel; @@ -40,6 +39,8 @@ class SpectrumStack; namespace view { +//when device is oscillcopse mode, to draw signal trace +//created by SigSession class SpectrumTrace : public Trace { Q_OBJECT @@ -65,33 +66,32 @@ private: static const double VerticalRate; public: - SpectrumTrace(pv::SigSession &session, - boost::shared_ptr spectrum_stack, int index); + SpectrumTrace(pv::SigSession *session, pv::data::SpectrumStack *spectrum_stack, int index); ~SpectrumTrace(); - bool enabled() const; + bool enabled(); void set_enable(bool enable); void init_zoom(); void zoom(double steps, int offset); - bool zoom_hit() const; + bool zoom_hit(); void set_zoom_hit(bool hit); void set_offset(double delta); - double get_offset() const; + double get_offset(); void set_scale(double scale); - double get_scale() const; + double get_scale(); void set_dbv_range(int range); - int dbv_range() const; + int dbv_range(); std::vector get_dbv_ranges(); - int view_mode() const; + int view_mode(); void set_view_mode(unsigned int mode); std::vector get_view_modes_support(); - const boost::shared_ptr& get_spectrum_stack() const; + pv::data::SpectrumStack* get_spectrum_stack(); static QString format_freq(double freq, unsigned precision = Pricision); @@ -121,7 +121,7 @@ public: **/ void paint_fore(QPainter &p, int left, int right, QColor fore, QColor back); - QRect get_view_rect() const; + QRect get_view_rect(); protected: void paint_type_options(QPainter &p, int right, const QPoint pt, QColor fore); @@ -131,8 +131,8 @@ private: private slots: private: - pv::SigSession &_session; - boost::shared_ptr _spectrum_stack; + pv::SigSession *_session; + pv::data::SpectrumStack *_spectrum_stack; bool _enable; int _view_mode; diff --git a/DSView/pv/view/timemarker.cpp b/DSView/pv/view/timemarker.cpp index f103eb7f..79a43707 100755 --- a/DSView/pv/view/timemarker.cpp +++ b/DSView/pv/view/timemarker.cpp @@ -48,7 +48,7 @@ TimeMarker::TimeMarker(const TimeMarker &s) : { } -QColor TimeMarker::colour() const +QColor TimeMarker::colour() { return _colour; } @@ -58,7 +58,7 @@ void TimeMarker::set_colour(QColor color) _colour = color; } -bool TimeMarker::grabbed() const +bool TimeMarker::grabbed() { return _grabbed; } @@ -67,7 +67,7 @@ void TimeMarker::set_grabbed(bool grabbed) _grabbed = grabbed; } -uint64_t TimeMarker::index() const +uint64_t TimeMarker::index() { return _index; } diff --git a/DSView/pv/view/timemarker.h b/DSView/pv/view/timemarker.h index 7a5425b8..84cc0bcb 100755 --- a/DSView/pv/view/timemarker.h +++ b/DSView/pv/view/timemarker.h @@ -37,6 +37,7 @@ namespace view { class View; +//the Cursor's base class class TimeMarker : public QObject { Q_OBJECT @@ -59,8 +60,8 @@ public: /** * Gets the time of the marker. */ - double time() const; - uint64_t index() const; + double time(); + uint64_t index(); /** * Sets the time of the marker. @@ -70,13 +71,13 @@ public: /** * Gets/Sets colour of the marker */ - QColor colour() const; + QColor colour(); void set_colour(QColor color); /* * */ - bool grabbed() const; + bool grabbed(); void set_grabbed(bool grabbed); /** @@ -92,7 +93,7 @@ public: * @param visible is this marker in visible area * @return Returns the label rectangle. */ - virtual QRect get_label_rect(const QRect &rect, bool &visible, bool has_hoff = true) const = 0; + virtual QRect get_label_rect(const QRect &rect, bool &visible, bool has_hoff = true) = 0; /** * Paints the marker's label to the ruler. diff --git a/DSView/pv/view/trace.cpp b/DSView/pv/view/trace.cpp index def3fdb0..cf6f17e3 100755 --- a/DSView/pv/view/trace.cpp +++ b/DSView/pv/view/trace.cpp @@ -20,18 +20,19 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#include + #include -#include - -#include +#include #include #include +#include #include "trace.h" #include "view.h" #include "../device/devinst.h" #include "../sigsession.h" +#include "../extdef.h" + namespace pv { namespace view { @@ -87,12 +88,12 @@ Trace::Trace(const Trace &t) : { } -QString Trace::get_name() const +QString Trace::get_name() { return _name; } -int Trace::get_name_width() const +int Trace::get_name_width() { QFont font = QApplication::font(); QFontMetrics fm(font); @@ -105,7 +106,7 @@ void Trace::set_name(QString name) _name = name; } -QColor Trace::get_colour() const +QColor Trace::get_colour() { return _colour; } @@ -115,7 +116,7 @@ void Trace::set_colour(QColor colour) _colour = colour; } -int Trace::get_v_offset() const +int Trace::get_v_offset() { return _v_offset; } @@ -126,12 +127,12 @@ void Trace::set_v_offset(int v_offset) } -int Trace::get_type() const +int Trace::get_type() { return _type; } -int Trace::get_index() const +int Trace::get_index() { return _index_list.front(); } @@ -148,7 +149,7 @@ void Trace::set_index_list(std::list index_list) _index_list = index_list; } -int Trace::get_sec_index() const +int Trace::get_sec_index() { return _sec_index; } @@ -158,7 +159,7 @@ void Trace::set_sec_index(int sec_index) _sec_index = sec_index; } -int Trace::get_old_v_offset() const +int Trace::get_old_v_offset() { return _old_v_offset; } @@ -168,12 +169,12 @@ void Trace::set_old_v_offset(int v_offset) _old_v_offset = v_offset; } -int Trace::get_zero_vpos() const +int Trace::get_zero_vpos() { return _v_offset; } -int Trace::get_totalHeight() const +int Trace::get_totalHeight() { return _totalHeight; } @@ -195,7 +196,7 @@ void Trace::set_view(pv::view::View *view) connect(_view, SIGNAL(resize()), this, SLOT(resize())); } -pv::view::View* Trace::get_view() const +pv::view::View* Trace::get_view() { return _view; } @@ -206,7 +207,7 @@ void Trace::set_viewport(pv::view::Viewport *viewport) _viewport = viewport; } -pv::view::Viewport* Trace::get_viewport() const +pv::view::Viewport* Trace::get_viewport() { return _viewport; } @@ -399,18 +400,18 @@ void Trace::compute_text_size(QPainter &p) p.boundingRect(QRectF(), 0, "99").height()); } -QRect Trace::get_view_rect() const +QRect Trace::get_view_rect() { assert(_view); return QRect(0, 0, _view->viewport()->width(), _view->viewport()->height()); } -int Trace::get_y() const +int Trace::get_y() { return _v_offset; } -QColor Trace::get_text_colour() const +QColor Trace::get_text_colour() { return (_colour.lightness() > 64) ? Qt::black : Qt::white; } @@ -432,22 +433,22 @@ int Trace::rows_size() return 1; } -int Trace::get_leftWidth() const +int Trace::get_leftWidth() { return SquareWidth/2 + Margin; } -int Trace::get_rightWidth() const +int Trace::get_rightWidth() { return 2 * Margin + _typeWidth * SquareWidth + 1.5 * SquareWidth; } -int Trace::get_headerHeight() const +int Trace::get_headerHeight() { return SquareWidth; } -QRectF Trace::get_rect(const char *s, int y, int right) const +QRectF Trace::get_rect(const char *s, int y, int right) { const QSizeF color_size(get_leftWidth() - Margin, SquareWidth); const QSizeF name_size(right - get_leftWidth() - get_rightWidth(), SquareWidth); diff --git a/DSView/pv/view/trace.h b/DSView/pv/view/trace.h index 6c0ad638..e1b3ecfb 100755 --- a/DSView/pv/view/trace.h +++ b/DSView/pv/view/trace.h @@ -42,6 +42,7 @@ namespace view { class View; class Viewport; +//base class class Trace : public SelectableItem { Q_OBJECT @@ -72,8 +73,8 @@ public: /** * Gets the name of this signal. */ - QString get_name() const; - virtual int get_name_width() const; + QString get_name(); + virtual int get_name_width(); /** * Sets the name of the signal. @@ -83,7 +84,7 @@ public: /** * Get the colour of the signal. */ - QColor get_colour() const; + QColor get_colour(); /** * Set the colour of the signal. @@ -93,7 +94,7 @@ public: /** * Gets the vertical layout offset of this signal. */ - int get_v_offset() const; + int get_v_offset(); /** * Sets the vertical layout offset of this signal. @@ -103,21 +104,21 @@ public: /** * Gets trace type */ - int get_type() const; + int get_type(); /** * Index process */ - int get_index() const; + int get_index(); std::list &get_index_list(); void set_index_list(std::list index_list); - int get_sec_index() const; + int get_sec_index(); void set_sec_index(int sec_index); /** * Gets the height of this signal. */ - int get_totalHeight() const; + int get_totalHeight(); /** * Sets the height of this signal. @@ -127,31 +128,31 @@ public: /** * Geom */ - int get_leftWidth() const; - int get_rightWidth() const; - int get_headerHeight() const; + int get_leftWidth(); + int get_rightWidth(); + int get_headerHeight(); /** * Gets the old vertical layout offset of this signal. */ - int get_old_v_offset() const; + int get_old_v_offset(); /** * Sets the old vertical layout offset of this signal. */ void set_old_v_offset(int v_offset); - virtual int get_zero_vpos() const; + virtual int get_zero_vpos(); /** * Returns true if the trace is visible and enabled. */ - virtual bool enabled() const = 0; + virtual bool enabled() = 0; virtual void set_view(pv::view::View *view); - pv::view::View* get_view() const; + pv::view::View* get_view(); virtual void set_viewport(pv::view::Viewport *viewport); - pv::view::Viewport* get_viewport() const; + pv::view::Viewport* get_viewport(); /** * Paints prepare @@ -194,7 +195,7 @@ public: /** * Gets the y-offset of the axis. */ - int get_y() const; + int get_y(); /** * Determines if a point is in the header rect. @@ -222,11 +223,11 @@ public: * area. * @return Returns the rectangle of the signal label. */ - QRectF get_rect(const char *s, int y, int right) const; + QRectF get_rect(const char *s, int y, int right); virtual int rows_size(); - virtual QRect get_view_rect() const; + virtual QRect get_view_rect(); virtual bool mouse_double_click(int right, const QPoint pt); @@ -242,7 +243,7 @@ protected: * of the trace colour against a threshold to determine whether * white or black would be more visible. */ - QColor get_text_colour() const; + QColor get_text_colour(); /** * Paints optoins for different trace type. diff --git a/DSView/pv/view/view.cpp b/DSView/pv/view/view.cpp index 4d959f0d..3328fb5d 100755 --- a/DSView/pv/view/view.cpp +++ b/DSView/pv/view/view.cpp @@ -24,9 +24,6 @@ #include #include -#include - -#include #include #include #include @@ -45,13 +42,13 @@ #include "analogsignal.h" #include "../device/devinst.h" -#include "pv/sigsession.h" -#include "pv/data/logic.h" -#include "pv/data/logicsnapshot.h" -#include "pv/dialogs/calibration.h" -#include "pv/dialogs/lissajousoptions.h" +#include "../sigsession.h" +#include "../data/logic.h" +#include "../data/logicsnapshot.h" +#include "../dialogs/calibration.h" +#include "../dialogs/lissajousoptions.h" + -using namespace boost; using namespace std; namespace pv { @@ -80,7 +77,7 @@ const QColor View::LightBlue = QColor(17, 133, 209, 200); const QColor View::LightRed = QColor(213, 15, 37, 200); -View::View(SigSession &session, pv::toolbars::SamplingBar *sampling_bar, QWidget *parent) : +View::View(SigSession *session, pv::toolbars::SamplingBar *sampling_bar, QWidget *parent) : QScrollArea(parent), _session(session), _sampling_bar(sampling_bar), @@ -99,14 +96,11 @@ View::View(SigSession &session, pv::toolbars::SamplingBar *sampling_bar, QWidget _dso_auto(true), _show_lissajous(false), _back_ready(false) -{ +{ + assert(session); + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn); - - connect(horizontalScrollBar(), SIGNAL(valueChanged(int)), - this, SLOT(h_scroll_value_changed(int))); - connect(verticalScrollBar(), SIGNAL(valueChanged(int)), - this, SLOT(v_scroll_value_changed(int))); - + // trace viewport map _trace_view_map[SR_CHANNEL_LOGIC] = TIME_VIEW; _trace_view_map[SR_CHANNEL_GROUP] = TIME_VIEW; @@ -123,22 +117,17 @@ View::View(SigSession &session, pv::toolbars::SamplingBar *sampling_bar, QWidget _devmode = new DevMode(this, session); setViewportMargins(headerWidth(), RulerHeight, 0, 0); - //setViewport(_viewport); // windows splitter _time_viewport = new Viewport(*this, TIME_VIEW); _time_viewport->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); _time_viewport->setMinimumHeight(100); - connect(_time_viewport, SIGNAL(measure_updated()), - this, SLOT(on_measure_updated())); - connect(_time_viewport, SIGNAL(prgRate(int)), this, SIGNAL(prgRate(int))); + _fft_viewport = new Viewport(*this, FFT_VIEW); _fft_viewport->setVisible(false); _fft_viewport->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); _fft_viewport->setMinimumHeight(100); - connect(_fft_viewport, SIGNAL(measure_updated()), - this, SLOT(on_measure_updated())); - + _vsplitter = new QSplitter(this); _vsplitter->setOrientation(Qt::Vertical); _vsplitter->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); @@ -163,35 +152,6 @@ View::View(SigSession &session, pv::toolbars::SamplingBar *sampling_bar, QWidget _viewbottom->setFixedHeight(StatusHeight); layout->addWidget(_viewbottom, 1, 0); setViewport(_viewcenter); - connect(_vsplitter, SIGNAL(splitterMoved(int,int)), - this, SLOT(splitterMoved(int, int))); - - connect(&_session, SIGNAL(device_setted()), - _devmode, SLOT(set_device())); - connect(&_session, SIGNAL(signals_changed()), - this, SLOT(signals_changed()), Qt::DirectConnection); - connect(&_session, SIGNAL(data_updated()), - this, SLOT(data_updated())); - connect(&_session, SIGNAL(receive_trigger(quint64)), - this, SLOT(receive_trigger(quint64))); - connect(&_session, SIGNAL(frame_ended()), - this, SLOT(receive_end())); - connect(&_session, SIGNAL(frame_began()), - this, SLOT(frame_began())); - connect(&_session, SIGNAL(show_region(uint64_t, uint64_t, bool)), - this, SLOT(show_region(uint64_t, uint64_t, bool))); - connect(&_session, SIGNAL(show_wait_trigger()), - _time_viewport, SLOT(show_wait_trigger())); - connect(&_session, SIGNAL(repeat_hold(int)), - this, SLOT(repeat_show())); - - connect(_devmode, SIGNAL(dev_changed(bool)), - this, SLOT(dev_changed(bool)), Qt::DirectConnection); - - connect(_header, SIGNAL(traces_moved()), - this, SLOT(on_traces_moved())); - connect(_header, SIGNAL(header_updated()), - this, SLOT(header_updated())); _time_viewport->installEventFilter(this); _fft_viewport->installEventFilter(this); @@ -214,24 +174,47 @@ View::View(SigSession &session, pv::toolbars::SamplingBar *sampling_bar, QWidget _cali = new pv::dialogs::Calibration(this); _cali->hide(); + + connect(horizontalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(h_scroll_value_changed(int))); + connect(verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(v_scroll_value_changed(int))); + + connect(_time_viewport, SIGNAL(measure_updated()),this, SLOT(on_measure_updated())); + connect(_time_viewport, SIGNAL(prgRate(int)), this, SIGNAL(prgRate(int))); + connect(_fft_viewport, SIGNAL(measure_updated()), this, SLOT(on_measure_updated())); + + connect(_vsplitter, SIGNAL(splitterMoved(int,int)), this, SLOT(splitterMoved(int, int))); + + connect(_devmode, SIGNAL(dev_changed(bool)),this, SLOT(dev_changed(bool)), Qt::DirectConnection); + connect(_header, SIGNAL(traces_moved()),this, SLOT(on_traces_moved())); + connect(_header, SIGNAL(header_updated()),this, SLOT(header_updated())); +} + +void View::show_wait_trigger() +{ + _time_viewport->show_wait_trigger(); +} + +void View::set_device() +{ + _devmode->set_device(); } SigSession& View::session() { - return _session; + return *_session; } -double View::scale() const +double View::scale() { return _scale; } -int64_t View::offset() const +int64_t View::offset() { return _offset; } -double View::trig_hoff() const +double View::trig_hoff() { return _trig_hoff; } @@ -241,25 +224,25 @@ void View::set_trig_hoff(double hoff) _trig_hoff = hoff; } -double View::get_minscale() const +double View::get_minscale() { return _minscale; } -double View::get_maxscale() const +double View::get_maxscale() { return _maxscale; } void View::capture_init() { - if (_session.get_device()->dev_inst()->mode == DSO) + if (_session->get_device()->dev_inst()->mode == DSO) show_trig_cursor(true); - else if (!_session.isRepeating()) + else if (!_session->isRepeating()) show_trig_cursor(false); - _maxscale = _session.cur_sampletime() / (get_view_width() * MaxViewRate); - if (_session.get_device()->dev_inst()->mode == ANALOG) + _maxscale = _session->cur_sampletime() / (get_view_width() * MaxViewRate); + if (_session->get_device()->dev_inst()->mode == ANALOG) set_scale_offset(_maxscale, 0); status_clear(); _trig_time_setted = false; @@ -289,7 +272,7 @@ double View::get_hori_res() void View::update_hori_res() { - if (_session.get_device()->dev_inst()->mode == DSO) { + if (_session->get_device()->dev_inst()->mode == DSO) { _sampling_bar->hori_knob(0); } } @@ -300,12 +283,12 @@ bool View::zoom(double steps, int offset) _preScale = _scale; _preOffset = _offset; - if (_session.get_device()->dev_inst()->mode != DSO) { + if (_session->get_device()->dev_inst()->mode != DSO) { _scale *= std::pow(3.0/2.0, -steps); _scale = max(min(_scale, _maxscale), _minscale); } else { - if (_session.get_capture_state() == SigSession::Running && - _session.get_instant()) + if (_session->get_capture_state() == SigSession::Running && + _session->get_instant()) return ret; double hori_res = -1; @@ -315,7 +298,7 @@ bool View::zoom(double steps, int offset) hori_res = _sampling_bar->hori_knob(1); if (hori_res > 0) { - const double scale = _session.cur_view_time() / get_view_width(); + const double scale = _session->cur_view_time() / get_view_width(); _scale = max(min(scale, _maxscale), _minscale); } else { ret = false; @@ -323,7 +306,7 @@ bool View::zoom(double steps, int offset) } _offset = floor((_offset + offset) * (_preScale / _scale) - offset); - _offset = max(min(_offset, get_max_offset()), get_min_offset()); + _offset = max (min(_offset, get_max_offset()), get_min_offset()); if (_scale != _preScale || _offset != _preOffset) { _header->update(); @@ -337,19 +320,19 @@ bool View::zoom(double steps, int offset) void View::timebase_changed() { - if (_session.get_device()->dev_inst()->mode != DSO) + if (_session->get_device()->dev_inst()->mode != DSO) return; double scale = this->scale(); double hori_res = _sampling_bar->get_hori_res(); if (hori_res > 0) - scale = _session.cur_view_time() / get_view_width(); + scale = _session->cur_view_time() / get_view_width(); set_scale_offset(scale, this->offset()); } void View::set_scale_offset(double scale, int64_t offset) { - //if (_session.get_capture_state() == SigSession::Stopped) { + //if (_session->get_capture_state() == SigSession::Stopped) { _preScale = _scale; _preOffset = _offset; @@ -374,43 +357,44 @@ void View::set_preScale_preOffset() set_scale_offset(_preScale, _preOffset); } -vector< boost::shared_ptr > View::get_traces(int type) +std::vector View::get_traces(int type) { - const vector< boost::shared_ptr > sigs(_session.get_signals()); - const vector< boost::shared_ptr > groups(_session.get_group_signals()); -#ifdef ENABLE_DECODE - const vector< boost::shared_ptr > decode_sigs( - _session.get_decode_signals()); -#endif - const vector< boost::shared_ptr > spectrums(_session.get_spectrum_traces()); + assert(_session); - vector< boost::shared_ptr > traces; - BOOST_FOREACH(boost::shared_ptr t, sigs) { + auto &sigs = _session->get_signals(); + const auto &groups = _session->get_group_signals(); + + const auto &decode_sigs = _session->get_decode_signals(); + + const auto &spectrums = _session->get_spectrum_traces(); + + std::vector traces; + for(auto &t : sigs) { if (type == ALL_VIEW || _trace_view_map[t->get_type()] == type) traces.push_back(t); } -#ifdef ENABLE_DECODE - BOOST_FOREACH(boost::shared_ptr t, decode_sigs) { + + for(auto &t : decode_sigs) { if (type == ALL_VIEW || _trace_view_map[t->get_type()] == type) traces.push_back(t); } -#endif - BOOST_FOREACH(boost::shared_ptr t, groups) { + + for(auto &t : groups) { if (type == ALL_VIEW || _trace_view_map[t->get_type()] == type) traces.push_back(t); } - BOOST_FOREACH(boost::shared_ptr t, spectrums) { + for(auto &t : spectrums) { if (type == ALL_VIEW || _trace_view_map[t->get_type()] == type) traces.push_back(t); } - boost::shared_ptr lissajous = _session.get_lissajous_trace(); + auto lissajous = _session->get_lissajous_trace(); if (lissajous && lissajous->enabled() && (type == ALL_VIEW || _trace_view_map[lissajous->get_type()] == type)) traces.push_back(lissajous); - boost::shared_ptr math = _session.get_math_trace(); + auto math = _session->get_math_trace(); if (math && math->enabled() && (type == ALL_VIEW || _trace_view_map[math->get_type()] == type)) traces.push_back(math); @@ -419,30 +403,34 @@ vector< boost::shared_ptr > View::get_traces(int type) return traces; } -bool View::compare_trace_v_offsets(const boost::shared_ptr &a, - const boost::shared_ptr &b) +bool View::compare_trace_v_offsets(const Trace *a, + const Trace *b) { assert(a); assert(b); - if (a->get_type() != b->get_type()) - return a->get_type() < b->get_type(); - else if (a->get_type() == SR_CHANNEL_DSO || a->get_type() == SR_CHANNEL_ANALOG) - return a->get_index() < b->get_index(); + + Trace *a1 = const_cast(a); + Trace *b1 = const_cast(b); + + if (a1->get_type() != b1->get_type()) + return a1->get_type() < b1->get_type(); + else if (a1->get_type() == SR_CHANNEL_DSO || a1->get_type() == SR_CHANNEL_ANALOG) + return a1->get_index() < b1->get_index(); else - return a->get_v_offset() < b->get_v_offset(); + return a1->get_v_offset() < b1->get_v_offset(); } -bool View::cursors_shown() const +bool View::cursors_shown() { return _show_cursors; } -bool View::trig_cursor_shown() const +bool View::trig_cursor_shown() { return _show_trig_cursor; } -bool View::search_cursor_shown() const +bool View::search_cursor_shown() { return _show_search_cursor; } @@ -482,8 +470,8 @@ void View::repeat_unshow() void View::frame_began() { -// if (_session.get_device()->dev_inst()->mode == LOGIC) -// _viewbottom->set_trig_time(_session.get_session_time()); +// if (_session->get_device()->dev_inst()->mode == LOGIC) +// _viewbottom->set_trig_time(_session->get_session_time()); _search_hit = false; _search_pos = 0; set_search_pos(_search_pos, _search_hit); @@ -491,9 +479,9 @@ void View::frame_began() void View::set_trig_time() { - if (!_trig_time_setted && _session.get_device()->dev_inst()->mode == LOGIC) { - _session.set_session_time(QDateTime::currentDateTime()); - _viewbottom->set_trig_time(_session.get_session_time()); + if (!_trig_time_setted && _session->get_device()->dev_inst()->mode == LOGIC) { + _session->set_session_time(QDateTime::currentDateTime()); + _viewbottom->set_trig_time(_session->get_session_time()); } _trig_time_setted = true; } @@ -505,17 +493,17 @@ bool View::trig_time_setted() void View::receive_end() { - if (_session.get_device()->dev_inst()->mode == LOGIC) { - GVariant *gvar = _session.get_device()->get_config(NULL, NULL, SR_CONF_RLE); + if (_session->get_device()->dev_inst()->mode == LOGIC) { + GVariant *gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_RLE); if (gvar != NULL) { bool rle = g_variant_get_boolean(gvar); g_variant_unref(gvar); if (rle) { - gvar = _session.get_device()->get_config(NULL, NULL, SR_CONF_ACTUAL_SAMPLES); + gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_ACTUAL_SAMPLES); if (gvar != NULL) { uint64_t actual_samples = g_variant_get_uint64(gvar); g_variant_unref(gvar); - if (actual_samples != _session.cur_samplelimits()) { + if (actual_samples != _session->cur_samplelimits()) { _viewbottom->set_rle_depth(actual_samples); } } @@ -527,11 +515,11 @@ void View::receive_end() void View::receive_trigger(quint64 trig_pos) { - const double time = trig_pos * 1.0 / _session.cur_snap_samplerate(); + const double time = trig_pos * 1.0 / _session->cur_snap_samplerate(); _trig_cursor->set_index(trig_pos); if (ds_trigger_get_en() || - _session.get_device()->name() == "virtual-session" || - _session.get_device()->dev_inst()->mode == DSO) { + _session->get_device()->name() == "virtual-session" || + _session->get_device()->dev_inst()->mode == DSO) { _show_trig_cursor = true; set_scale_offset(_scale, (time / _scale) - (get_view_width() / 2)); } @@ -542,7 +530,7 @@ void View::receive_trigger(quint64 trig_pos) void View::set_trig_pos(int percent) { - uint64_t index = _session.cur_samplelimits() * percent / 100; + uint64_t index = _session->cur_samplelimits() * percent / 100; receive_trigger(index); } @@ -552,7 +540,7 @@ void View::set_search_pos(uint64_t search_pos, bool hit) QColor fore(QWidget::palette().color(QWidget::foregroundRole())); fore.setAlpha(View::BackAlpha); - const double time = search_pos * 1.0 / _session.cur_snap_samplerate(); + const double time = search_pos * 1.0 / _session->cur_snap_samplerate(); _search_pos = search_pos; _search_hit = hit; _search_cursor->set_index(search_pos); @@ -575,22 +563,25 @@ bool View::get_search_hit() return _search_hit; } -const QPoint& View::hover_point() const +const QPoint& View::hover_point() { return _hover_point; } void View::normalize_layout() { - const vector< boost::shared_ptr > traces(get_traces(ALL_VIEW)); + auto traces = get_traces(ALL_VIEW); int v_min = INT_MAX; - BOOST_FOREACH(const boost::shared_ptr t, traces) - v_min = min(t->get_v_offset(), v_min); + for(auto &t : traces){ + v_min = min(t->get_v_offset(), v_min); + } const int delta = -min(v_min, 0); - BOOST_FOREACH(boost::shared_ptr t, traces) + + for(auto &t : traces){ t->set_v_offset(t->get_v_offset() + delta); + } verticalScrollBar()->setSliderPosition(delta); v_scroll_value_changed(verticalScrollBar()->sliderPosition()); @@ -607,13 +598,13 @@ int View::get_signalHeight() return _signalHeight; } -void View::get_scroll_layout(int64_t &length, int64_t &offset) const +void View::get_scroll_layout(int64_t &length, int64_t &offset) { - const set< boost::shared_ptr > data_set = _session.get_data(); + const auto data_set = _session->get_data(); if (data_set.empty()) return; - length = ceil(_session.cur_snap_sampletime() / _scale); + length = ceil(_session->cur_snap_sampletime() / _scale); offset = _offset; } @@ -651,11 +642,11 @@ void View::update_scroll() void View::update_scale_offset() { - if (_session.get_device()->dev_inst()->mode != DSO) { - _maxscale = _session.cur_sampletime() / (get_view_width() * MaxViewRate); - _minscale = (1.0 / _session.cur_snap_samplerate()) / MaxPixelsPerSample; + if (_session->get_device()->dev_inst()->mode != DSO) { + _maxscale = _session->cur_sampletime() / (get_view_width() * MaxViewRate); + _minscale = (1.0 / _session->cur_snap_samplerate()) / MaxPixelsPerSample; } else { - _scale = _session.cur_view_time() / get_view_width(); + _scale = _session->cur_view_time() / get_view_width(); _maxscale = 1e9; _minscale = 1e-15; } @@ -666,7 +657,7 @@ void View::update_scale_offset() _preScale = _scale; _preOffset = _offset; - //_trig_cursor->set_index(_session.get_trigger_pos()); + //_trig_cursor->set_index(_session->get_trigger_pos()); _ruler->update(); viewport_update(); @@ -675,8 +666,8 @@ void View::update_scale_offset() void View::dev_changed(bool close) { if (!close) { - if (_session.get_device()->name().contains("virtual")) - _scale = WellSamplesPerPixel * 1.0 / _session.cur_snap_samplerate(); + if (_session->get_device()->name().contains("virtual")) + _scale = WellSamplesPerPixel * 1.0 / _session->cur_snap_samplerate(); _scale = max(min(_scale, _maxscale), _minscale); } @@ -689,10 +680,10 @@ void View::signals_changed() int total_rows = 0; int label_size = 0; uint8_t max_height = MaxHeightUnit; - vector< boost::shared_ptr > time_traces; - vector< boost::shared_ptr > fft_traces; + std::vector time_traces; + std::vector fft_traces; - BOOST_FOREACH(const boost::shared_ptr t, get_traces(ALL_VIEW)) { + for(auto &t : get_traces(ALL_VIEW)) { if (_trace_view_map[t->get_type()] == TIME_VIEW) time_traces.push_back(t); else if (_trace_view_map[t->get_type()] == FFT_VIEW) @@ -707,7 +698,7 @@ void View::signals_changed() _viewport_list.push_back(_fft_viewport); _vsplitter->refresh(); } - BOOST_FOREACH(boost::shared_ptr t, fft_traces) { + for(auto &t : fft_traces) { t->set_view(this); t->set_viewport(_fft_viewport); t->set_totalHeight(_fft_viewport->height()); @@ -728,9 +719,9 @@ void View::signals_changed() } if (!time_traces.empty() && _time_viewport) { - BOOST_FOREACH(const boost::shared_ptr t, time_traces) { + for(auto &t : time_traces) { assert(t); - if (dynamic_pointer_cast(t) || + if (dynamic_cast(t) || t->enabled()) total_rows += t->rows_size(); if (t->rows_size() != 0) @@ -740,8 +731,8 @@ void View::signals_changed() const double height = (_time_viewport->height() - 2 * actualMargin * label_size) * 1.0 / total_rows; - if (_session.get_device()->dev_inst()->mode == LOGIC) { - GVariant* gvar = _session.get_device()->get_config(NULL, NULL, SR_CONF_MAX_HEIGHT_VALUE); + if (_session->get_device()->dev_inst()->mode == LOGIC) { + GVariant* gvar = _session->get_device()->get_config(NULL, NULL, SR_CONF_MAX_HEIGHT_VALUE); if (gvar != NULL) { max_height = (g_variant_get_byte(gvar) + 1) * MaxHeightUnit; g_variant_unref(gvar); @@ -753,7 +744,7 @@ void View::signals_changed() } else { _signalHeight = (height >= max_height) ? max_height : height; } - } else if (_session.get_device()->dev_inst()->mode == DSO) { + } else if (_session->get_device()->dev_inst()->mode == DSO) { _signalHeight = (_header->height() - horizontalScrollBar()->height() - 2 * actualMargin * label_size) * 1.0 / total_rows; @@ -762,7 +753,8 @@ void View::signals_changed() } _spanY = _signalHeight + 2 * actualMargin; int next_v_offset = actualMargin; - BOOST_FOREACH(boost::shared_ptr t, time_traces) { + + for(auto &t : time_traces) { t->set_view(this); t->set_viewport(_time_viewport); if (t->rows_size() == 0) @@ -772,13 +764,13 @@ void View::signals_changed() t->set_v_offset(next_v_offset + 0.5 * traceHeight + actualMargin); next_v_offset += traceHeight + 2 * actualMargin; - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(t))) { + view::DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(t))) { dsoSig->set_scale(dsoSig->get_view_rect().height()); } - boost::shared_ptr analogSig; - if ((analogSig = dynamic_pointer_cast(t))) { + view::AnalogSignal *analogSig = NULL; + if ((analogSig = dynamic_cast(t))) { analogSig->set_scale(analogSig->get_totalHeight()); } } @@ -801,7 +793,7 @@ bool View::eventFilter(QObject *object, QEvent *event) double cur_periods = (mouse_event->pos().x() + _offset) * _scale / _ruler->get_min_period(); int integer_x = round(cur_periods) * _ruler->get_min_period() / _scale - _offset; double cur_deviate_x = qAbs(mouse_event->pos().x() - integer_x); - if (_session.get_device()->dev_inst()->mode == LOGIC && + if (_session->get_device()->dev_inst()->mode == LOGIC && cur_deviate_x < 10) _hover_point = QPoint(integer_x, mouse_event->pos().y()); else @@ -841,9 +833,9 @@ int View::headerWidth() { int headerWidth = _header->get_nameEditWidth(); - const vector< boost::shared_ptr > traces(get_traces(ALL_VIEW)); + const auto &traces = get_traces(ALL_VIEW); if (!traces.empty()) { - BOOST_FOREACH(const boost::shared_ptr t, traces) + for(auto &t : traces) headerWidth = max(t->get_name_width() + t->get_leftWidth() + t->get_rightWidth(), headerWidth); } @@ -860,11 +852,11 @@ void View::resizeEvent(QResizeEvent*) update_margins(); update_scroll(); signals_changed(); - if (_session.get_device()->dev_inst()->mode == DSO) - _scale = _session.cur_view_time() / get_view_width(); + if (_session->get_device()->dev_inst()->mode == DSO) + _scale = _session->cur_view_time() / get_view_width(); - if (_session.get_device()->dev_inst()->mode != DSO) - _maxscale = _session.cur_sampletime() / (get_view_width() * MaxViewRate); + if (_session->get_device()->dev_inst()->mode != DSO) + _maxscale = _session->cur_sampletime() / (get_view_width() * MaxViewRate); else _maxscale = 1e9; @@ -930,12 +922,11 @@ void View::data_updated() void View::update_margins() { - _ruler->setGeometry(_viewcenter->x(), 0, - get_view_width(), _viewcenter->y()); - _header->setGeometry(0, _viewcenter->y(), - _viewcenter->x(), _viewcenter->height()); - _devmode->setGeometry(0, 0, - _viewcenter->x(), _viewcenter->y()); + _ruler->setGeometry(_viewcenter->x(), 0, get_view_width(), _viewcenter->y()); + + _header->setGeometry(0, _viewcenter->y(), _viewcenter->x(), _viewcenter->height()); + + _devmode->setGeometry(0, 0, _viewcenter->x(), _viewcenter->y()); } void View::header_updated() @@ -1006,10 +997,10 @@ void View::set_cursor_middle(int index) { assert(index < (int)_cursorList.size()); - list::iterator i = _cursorList.begin(); + auto i = _cursorList.begin(); while (index-- != 0) i++; - set_scale_offset(_scale, (*i)->index() / (_session.cur_snap_samplerate() * _scale) - (get_view_width() / 2)); + set_scale_offset(_scale, (*i)->index() / (_session->cur_snap_samplerate() * _scale) - (get_view_width() / 2)); } void View::on_measure_updated() @@ -1028,7 +1019,7 @@ QString View::get_measure(QString option) QString View::get_cm_time(int index) { - return _ruler->format_real_time(get_cursor_samples(index), _session.cur_snap_samplerate()); + return _ruler->format_real_time(get_cursor_samples(index), _session->cur_snap_samplerate()); } QString View::get_cm_delta(int index1, int index2) @@ -1039,7 +1030,7 @@ QString View::get_cm_delta(int index1, int index2) uint64_t samples1 = get_cursor_samples(index1); uint64_t samples2 = get_cursor_samples(index2); uint64_t delta_sample = (samples1 > samples2) ? samples1 - samples2 : samples2 - samples1; - return _ruler->format_real_time(delta_sample, _session.cur_snap_samplerate()); + return _ruler->format_real_time(delta_sample, _session->cur_snap_samplerate()); } QString View::get_index_delta(uint64_t start, uint64_t end) @@ -1048,7 +1039,7 @@ QString View::get_index_delta(uint64_t start, uint64_t end) return "0"; uint64_t delta_sample = (start > end) ? start - end : end - start; - return _ruler->format_real_time(delta_sample, _session.cur_snap_samplerate()); + return _ruler->format_real_time(delta_sample, _session->cur_snap_samplerate()); } uint64_t View::get_cursor_samples(int index) @@ -1084,9 +1075,9 @@ void View::on_state_changed(bool stop) QRect View::get_view_rect() { - if (_session.get_device()->dev_inst()->mode == DSO) { - const vector< boost::shared_ptr > sigs(_session.get_signals()); - BOOST_FOREACH(const boost::shared_ptr s, sigs) { + if (_session->get_device()->dev_inst()->mode == DSO) { + const auto &sigs = _session->get_signals(); + for(auto &s : sigs) { return s->get_view_rect(); } } @@ -1097,9 +1088,9 @@ QRect View::get_view_rect() int View::get_view_width() { int view_width = 0; - if (_session.get_device()->dev_inst()->mode == DSO) { - const vector< boost::shared_ptr > sigs(_session.get_signals()); - BOOST_FOREACH(const boost::shared_ptr s, sigs) { + if (_session->get_device()->dev_inst()->mode == DSO) { + const auto &sigs = _session->get_signals(); + for(auto &s : sigs) { view_width = max(view_width, s->get_view_rect().width()); } } else { @@ -1112,9 +1103,9 @@ int View::get_view_width() int View::get_view_height() { int view_height = 0; - if (_session.get_device()->dev_inst()->mode == DSO) { - const vector< boost::shared_ptr > sigs(_session.get_signals()); - BOOST_FOREACH(const boost::shared_ptr s, sigs) { + if (_session->get_device()->dev_inst()->mode == DSO) { + const auto &sigs = _session->get_signals(); + for(auto &s : sigs) { view_height = max(view_height, s->get_view_rect().height()); } } else { @@ -1134,14 +1125,14 @@ int64_t View::get_min_offset() int64_t View::get_max_offset() { - return ceil((_session.cur_snap_sampletime() / _scale) - + return ceil((_session->cur_snap_sampletime() / _scale) - (get_view_width() * MaxViewRate)); } // -- calibration dialog void View::show_calibration() { - _cali->set_device(_session.get_device()); + _cali->set_device(_session->get_device()); _cali->show(); } @@ -1153,9 +1144,9 @@ void View::hide_calibration() void View::vDial_updated() { if (_cali->isVisible()) { - _cali->set_device(_session.get_device()); + _cali->set_device(_session->get_device()); } - boost::shared_ptr math_trace = _session.get_math_trace(); + auto math_trace = _session->get_math_trace(); if (math_trace && math_trace->enabled()) { math_trace->update_vDial(); } @@ -1174,14 +1165,14 @@ void View::show_region(uint64_t start, uint64_t end, bool keep) if (keep) { set_all_update(true); update(); - } else if (_session.get_map_zoom() == 0) { - const double ideal_scale = (end-start) * 2.0 / _session.cur_snap_samplerate() / get_view_width(); - const double new_scale = max(min(ideal_scale, _maxscale), _minscale); - const double new_off = (start + end) * 0.5 / (_session.cur_snap_samplerate() * new_scale) - (get_view_width() / 2); + } else if (_session->get_map_zoom() == 0) { + const double ideal_scale = (end-start) * 2.0 / _session->cur_snap_samplerate() / get_view_width(); + const double new_scale = max (min(ideal_scale, _maxscale), _minscale); + const double new_off = (start + end) * 0.5 / (_session->cur_snap_samplerate() * new_scale) - (get_view_width() / 2); set_scale_offset(new_scale, new_off); } else { const double new_scale = scale(); - const double new_off = (start + end) * 0.5 / (_session.cur_snap_samplerate() * new_scale) - (get_view_width() / 2); + const double new_off = (start + end) * 0.5 / (_session->cur_snap_samplerate() * new_scale) - (get_view_width() / 2); set_scale_offset(new_scale, new_off); } } @@ -1189,7 +1180,7 @@ void View::show_region(uint64_t start, uint64_t end, bool keep) void View::viewport_update() { _viewcenter->update(); - BOOST_FOREACH(QWidget *viewport, _viewport_list) + for(QWidget *viewport : _viewport_list) viewport->update(); } @@ -1215,7 +1206,7 @@ void View::clear() { show_trig_cursor(false); - if (_session.get_device()->dev_inst()->mode != DSO) { + if (_session->get_device()->dev_inst()->mode != DSO) { show_xcursors(false); } else { if (!get_xcursorList().empty()) @@ -1225,7 +1216,7 @@ void View::clear() void View::reconstruct() { - if (_session.get_device()->dev_inst()->mode == DSO) + if (_session->get_device()->dev_inst()->mode == DSO) _viewbottom->setFixedHeight(DsoStatusHeight); else _viewbottom->setFixedHeight(StatusHeight); @@ -1241,13 +1232,13 @@ void View::set_capture_status() { bool triggered; int progress; - if (_session.get_capture_status(triggered, progress)) { + if (_session->get_capture_status(triggered, progress)) { _viewbottom->set_capture_status(triggered, progress); _viewbottom->update(); } } -bool View::get_dso_trig_moved() const +bool View::get_dso_trig_moved() { return _time_viewport->get_dso_trig_moved(); } @@ -1291,7 +1282,7 @@ ViewStatus* View::get_viewstatus() return _viewbottom; } -bool View::back_ready() const +bool View::back_ready() { return _back_ready; } @@ -1321,5 +1312,14 @@ uint64_t View::pixel2index(double pixel) return index; } +void View::set_receive_len(uint64_t len) +{ + if (_time_viewport) + _time_viewport->set_receive_len(len); + + if (_fft_viewport) + _fft_viewport->set_receive_len(len); +} + } // namespace view } // namespace pv diff --git a/DSView/pv/view/view.h b/DSView/pv/view/view.h index 58893ec8..6475cd7d 100755 --- a/DSView/pv/view/view.h +++ b/DSView/pv/view/view.h @@ -27,16 +27,13 @@ #include #include #include - -#include -#include - + #include #include #include #include -#include "../../extdef.h" + #include "../toolbars/samplingbar.h" #include "../data/signaldata.h" #include "../view/viewport.h" @@ -44,6 +41,7 @@ #include "xcursor.h" #include "signal.h" #include "viewstatus.h" +#include "../extdef.h" namespace pv { @@ -67,6 +65,7 @@ class Trace; class Viewport; class LissajousFigure; +//created by MainWindow class View : public QScrollArea { Q_OBJECT @@ -104,25 +103,25 @@ public: static const QColor LightRed; public: - explicit View(SigSession &session, pv::toolbars::SamplingBar *sampling_bar, QWidget *parent = 0); + explicit View(SigSession *session, pv::toolbars::SamplingBar *sampling_bar, QWidget *parent = 0); SigSession& session(); /** * Returns the view time scale in seconds per pixel. */ - double scale() const; + double scale(); /** * Returns the pixels offset of the left edge of the view */ - int64_t offset() const; - int v_offset() const; + int64_t offset(); + int v_offset(); /** * trigger position fix */ - double trig_hoff() const; + double trig_hoff(); void set_trig_hoff(double hoff); int64_t get_min_offset(); @@ -141,14 +140,14 @@ public: void set_scale_offset(double scale, int64_t offset); void set_preScale_preOffset(); - std::vector< boost::shared_ptr > get_traces(int type); + std::vector get_traces(int type); /** * Returns true if cursors are displayed. false otherwise. */ - bool cursors_shown() const; - bool trig_cursor_shown() const; - bool search_cursor_shown() const; + bool cursors_shown(); + bool trig_cursor_shown(); + bool search_cursor_shown(); int get_spanY(); @@ -163,7 +162,7 @@ public: */ void show_cursors(bool show = true); - const QPoint& hover_point() const; + const QPoint& hover_point(); void normalize_layout(); @@ -199,8 +198,8 @@ public: /* * */ - double get_minscale() const; - double get_maxscale() const; + double get_minscale(); + double get_maxscale(); void set_update(Viewport *viewport, bool need_update); void set_all_update(bool need_update); @@ -224,14 +223,14 @@ public: void set_capture_status(); - bool get_dso_trig_moved() const; + bool get_dso_trig_moved(); ViewStatus* get_viewstatus(); /* * back paint status */ - bool back_ready() const; + bool back_ready(); void set_back(bool ready); /* @@ -259,16 +258,16 @@ signals: void auto_trig(int index); -private: - void get_scroll_layout(int64_t &length, int64_t &offset) const; +private: + void get_scroll_layout(int64_t &length, int64_t &offset); void update_scroll(); void update_margins(); static bool compare_trace_v_offsets( - const boost::shared_ptr &a, - const boost::shared_ptr &b); + const pv::view::Trace *a, + const pv::view::Trace *b); void clear(); void reconstruct(); @@ -308,6 +307,12 @@ public slots: // void header_updated(); + void receive_trigger(quint64 trig_pos); + + void receive_end(); + + void frame_began(); + private slots: void h_scroll_value_changed(int value); @@ -317,13 +322,9 @@ private slots: void on_traces_moved(); - void receive_trigger(quint64 trig_pos); + void set_trig_pos(int percent); - - void receive_end(); - - void frame_began(); - + // calibration for oscilloscope void show_calibration(); // lissajous figure @@ -334,59 +335,65 @@ private slots: void dev_changed(bool close); +public: + void show_wait_trigger(); + void set_device(); + void set_receive_len(uint64_t len); + private: - SigSession &_session; - pv::toolbars::SamplingBar *_sampling_bar; + SigSession *_session; + pv::toolbars::SamplingBar *_sampling_bar; - QWidget *_viewcenter; - ViewStatus *_viewbottom; - QSplitter *_vsplitter; - Viewport * _time_viewport; - Viewport * _fft_viewport; - LissajousFigure *_lissajous; - Viewport *_active_viewport; - std::list _viewport_list; - std::map _trace_view_map; - Ruler *_ruler; - Header *_header; - DevMode *_devmode; + QWidget *_viewcenter; + ViewStatus *_viewbottom; + QSplitter *_vsplitter; + Viewport *_time_viewport; + Viewport *_fft_viewport; + Viewport *_active_viewport; + LissajousFigure *_lissajous; + std::list _viewport_list; + std::map _trace_view_map; + Ruler *_ruler; + Header *_header; + DevMode *_devmode; + /// The view time scale in seconds per pixel. - double _scale; - double _preScale; - double _maxscale; - double _minscale; + double _scale; + double _preScale; + double _maxscale; + double _minscale; /// The pixels offset of the left edge of the view - int64_t _offset; - int64_t _preOffset; - int _spanY; - int _signalHeight; - bool _updating_scroll; + int64_t _offset; + int64_t _preOffset; + int _spanY; + int _signalHeight; + bool _updating_scroll; // trigger position fix - double _trig_hoff; + double _trig_hoff; - bool _show_cursors; + bool _show_cursors; std::list _cursorList; - Cursor *_trig_cursor; - bool _show_trig_cursor; - Cursor *_search_cursor; - bool _show_search_cursor; - uint64_t _search_pos; - bool _search_hit; + Cursor *_trig_cursor; + bool _show_trig_cursor; + Cursor *_search_cursor; + bool _show_search_cursor; + uint64_t _search_pos; + bool _search_hit; - bool _show_xcursors; + bool _show_xcursors; std::list _xcursorList; - QPoint _hover_point; + QPoint _hover_point; dialogs::Calibration *_cali; - bool _dso_auto; - bool _show_lissajous; - bool _back_ready; - bool _trig_time_setted; + bool _dso_auto; + bool _show_lissajous; + bool _back_ready; + bool _trig_time_setted; }; } // namespace view diff --git a/DSView/pv/view/viewport.cpp b/DSView/pv/view/viewport.cpp index 16cdce97..6bbaa6da 100755 --- a/DSView/pv/view/viewport.cpp +++ b/DSView/pv/view/viewport.cpp @@ -37,13 +37,14 @@ #include #include -#include - +#include #include - -#include - -using namespace boost; +#include +#include + +#include "../config/appconfig.h" +#include "../dsvdef.h" + using namespace std; namespace pv { @@ -91,32 +92,27 @@ Viewport::Viewport(View &parent, View_type type) : // drag inertial _drag_strength = 0; _drag_timer.setSingleShot(true); - - connect(&trigger_timer, SIGNAL(timeout()), - this, SLOT(on_trigger_timer())); - connect(&_drag_timer, SIGNAL(timeout()), - this, SLOT(on_drag_timer())); - - connect(&_view.session(), &SigSession::receive_data, - this, &Viewport::set_receive_len); - + _cmenu = new QMenu(this); QAction *yAction = _cmenu->addAction(tr("Add Y-cursor")); QAction *xAction = _cmenu->addAction(tr("Add X-cursor")); + + setContextMenuPolicy(Qt::CustomContextMenu); + + connect(&trigger_timer, SIGNAL(timeout()),this, SLOT(on_trigger_timer())); + connect(&_drag_timer, SIGNAL(timeout()),this, SLOT(on_drag_timer())); + connect(yAction, SIGNAL(triggered(bool)), this, SLOT(add_cursor_y())); connect(xAction, SIGNAL(triggered(bool)), this, SLOT(add_cursor_x())); - - setContextMenuPolicy(Qt::CustomContextMenu); - connect(this, SIGNAL(customContextMenuRequested(const QPoint&)), - this, SLOT(show_contextmenu(const QPoint&))); + connect(this, SIGNAL(customContextMenuRequested(const QPoint&)),this, SLOT(show_contextmenu(const QPoint&))); } -int Viewport::get_total_height() const +int Viewport::get_total_height() { int h = 0; - const vector< boost::shared_ptr > traces(_view.get_traces(_type)); - BOOST_FOREACH(const boost::shared_ptr t, traces) { + const auto &traces = _view.get_traces(_type); + for(auto &t : traces) { assert(t); h += (int)(t->get_totalHeight()); } @@ -125,7 +121,7 @@ int Viewport::get_total_height() const return h; } -QPoint Viewport::get_mouse_point() const +QPoint Viewport::get_mouse_point() { return _mouse_point; } @@ -138,7 +134,7 @@ bool Viewport::event(QEvent *event) } void Viewport::paintEvent(QPaintEvent *event) -{ +{ (void)event; using pv::view::Signal; @@ -153,15 +149,20 @@ void Viewport::paintEvent(QPaintEvent *event) QColor back(QWidget::palette().color(QWidget::backgroundRole())); fore.setAlpha(View::ForeAlpha); _view.set_back(false); - const vector< boost::shared_ptr > traces(_view.get_traces(_type)); - BOOST_FOREACH(const boost::shared_ptr t, traces) + + const auto &traces = _view.get_traces(_type); + + for(auto &t : traces) { - assert(t); + assert(t); + t->paint_back(p, 0, _view.get_view_width(), fore, back); if (_view.back_ready()) break; } + //auto st = _view.session().get_capture_state(); + if (_view.session().get_device()->dev_inst()->mode == LOGIC || _view.session().get_instant()) { switch(_view.session().get_capture_state()) { @@ -187,7 +188,7 @@ void Viewport::paintEvent(QPaintEvent *event) paintSignals(p, fore, back); } - BOOST_FOREACH(const boost::shared_ptr t, traces) + for(auto &t : traces) { assert(t); if (t->enabled()) @@ -202,11 +203,14 @@ void Viewport::paintEvent(QPaintEvent *event) void Viewport::paintSignals(QPainter &p, QColor fore, QColor back) { - const vector< boost::shared_ptr > traces(_view.get_traces(_type)); + const auto &traces = _view.get_traces(_type); + if (_view.session().get_device()->dev_inst()->mode == LOGIC) { - BOOST_FOREACH(const boost::shared_ptr t, traces) + + for(auto &t : traces) { - assert(t); + assert(t); + if (t->enabled()) t->paint_mid(p, 0, t->get_view_rect().right(), fore, back); } @@ -224,11 +228,20 @@ void Viewport::paintSignals(QPainter &p, QColor fore, QColor back) QPainter dbp(&pixmap); //dbp.begin(this); - BOOST_FOREACH(const boost::shared_ptr t, traces) + for(auto &t : traces) { assert(t); + + /* + auto ptr = t->get(); + if (ptr->enabled()){ + ptr->paint_mid(dbp, 0, t->get_view_rect().right(), fore, back); + continue; + } + */ + if (t->enabled()) - t->paint_mid(dbp, 0, t->get_view_rect().right(), fore, back); + t->paint_mid(dbp, 0, t->get_view_rect().right(), fore, back); } _need_update = false; } @@ -239,7 +252,7 @@ void Viewport::paintSignals(QPainter &p, QColor fore, QColor back) //const QRect xrect = QRect(rect().left(), rect().top(), _view.get_view_width(), rect().height()); const QRect xrect = _view.get_view_rect(); if (_view.cursors_shown() && _type == TIME_VIEW) { - list::iterator i = _view.get_cursorList().begin(); + auto i = _view.get_cursorList().begin(); int index = 0; while (i != _view.get_cursorList().end()) { const int64_t cursorX = _view.index2pixel((*i)->index()); @@ -254,7 +267,7 @@ void Viewport::paintSignals(QPainter &p, QColor fore, QColor back) } if (_view.xcursors_shown() && _type == TIME_VIEW) { - list::iterator i = _view.get_xcursorList().begin(); + auto i = _view.get_xcursorList().begin(); int index = 0; bool hovered = false; while (i != _view.get_xcursorList().end()) { @@ -485,7 +498,7 @@ void Viewport::paintProgress(QPainter &p, QColor fore, QColor back) void Viewport::mousePressEvent(QMouseEvent *event) { assert(event); - + _mouse_down_point = event->pos(); _mouse_down_offset = _view.offset(); _drag_strength = 0; @@ -507,13 +520,15 @@ void Viewport::mousePressEvent(QMouseEvent *event) if (_action_type == NO_ACTION && event->button() == Qt::LeftButton && _view.session().get_device()->dev_inst()->mode == DSO) { - const vector< boost::shared_ptr > sigs(_view.session().get_signals()); - BOOST_FOREACH(const boost::shared_ptr s, sigs) { + + const auto &sigs = _view.session().get_signals(); + + for(auto &s : sigs) { assert(s); if (!s->enabled()) continue; - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s))) { + DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(s))) { if (dsoSig->get_trig_rect(0, _view.get_view_width()).contains(_mouse_point)) { _drag_sig = s; _action_type = DSO_TRIG_MOVE; @@ -536,7 +551,7 @@ void Viewport::mousePressEvent(QMouseEvent *event) } } if (_action_type == NO_ACTION && _view.cursors_shown()) { - list::iterator i = _view.get_cursorList().begin(); + auto i = _view.get_cursorList().begin(); while (i != _view.get_cursorList().end()) { const int64_t cursorX = _view.index2pixel((*i)->index()); if ((*i)->grabbed()) { @@ -550,7 +565,7 @@ void Viewport::mousePressEvent(QMouseEvent *event) } } if (_action_type == NO_ACTION && _view.xcursors_shown()) { - list::iterator i = _view.get_xcursorList().begin(); + auto i = _view.get_xcursorList().begin(); const QRect xrect = _view.get_view_rect(); while (i != _view.get_xcursorList().end()) { const double cursorX = xrect.left() + (*i)->value(XCursor::XCur_Y)*xrect.width(); @@ -562,13 +577,13 @@ void Viewport::mousePressEvent(QMouseEvent *event) _view.show_xcursors(false); break; } else if ((*i)->get_map_rect(xrect).contains(_view.hover_point())) { - vector< boost::shared_ptr > sigs(_view.session().get_signals()); - vector< boost::shared_ptr >::iterator s = sigs.begin(); + auto &sigs = _view.session().get_signals(); + auto s = sigs.begin(); bool sig_looped = ((*i)->channel() == NULL); bool no_dsoSig = true; while (1) { - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(*s)) && + view::DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(*s)) && dsoSig->enabled()) { no_dsoSig = false; if (sig_looped) { @@ -625,7 +640,7 @@ void Viewport::mouseMoveEvent(QMouseEvent *event) } _drag_strength = (_mouse_down_point - event->pos()).x(); } else if (_type == FFT_VIEW) { - BOOST_FOREACH(const boost::shared_ptr t, _view.session().get_spectrum_traces()) { + for(auto &t: _view.session().get_spectrum_traces()) { assert(t); if(t->enabled()) { double delta = (_mouse_point - event->pos()).x(); @@ -641,8 +656,8 @@ void Viewport::mouseMoveEvent(QMouseEvent *event) !(event->buttons() | Qt::NoButton)) { if (_action_type == DSO_TRIG_MOVE) { if (_drag_sig) { - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(_drag_sig))) { + view::DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(_drag_sig))) { dsoSig->set_trig_vpos(event->pos().y()); _dso_trig_moved = true; } @@ -654,20 +669,21 @@ void Viewport::mouseMoveEvent(QMouseEvent *event) int curX = _view.hover_point().x(); uint64_t index0 = 0, index1 = 0, index2 = 0; bool logic = false; - const vector< boost::shared_ptr > sigs(_view.session().get_signals()); - BOOST_FOREACH(const boost::shared_ptr s, sigs) { + const auto &sigs = _view.session().get_signals(); + + for(auto &s: sigs) { assert(s); - boost::shared_ptr logicSig; - boost::shared_ptr dsoSig; + view::LogicSignal *logicSig = NULL; + view::DsoSignal *dsoSig = NULL; if ((_view.session().get_device()->dev_inst()->mode == LOGIC) && - (logicSig = dynamic_pointer_cast(s))) { + (logicSig = dynamic_cast(s))) { if (logicSig->measure(event->pos(), index0, index1, index2)) { logic = true; break; } } if ((_view.session().get_device()->dev_inst()->mode == DSO) && - (dsoSig = dynamic_pointer_cast(s))) { + (dsoSig = dynamic_cast(s))) { curX = min(dsoSig->get_view_rect().right(), curX); break; } @@ -696,7 +712,7 @@ void Viewport::mouseMoveEvent(QMouseEvent *event) _curs_moved = true; } else { if (_view.xcursors_shown()) { - list::iterator i = _view.get_xcursorList().begin(); + auto i = _view.get_xcursorList().begin(); const QRect xrect = _view.get_view_rect(); while (i != _view.get_xcursorList().end()) { if ((*i)->grabbed() != XCursor::XCur_None) { @@ -718,7 +734,7 @@ void Viewport::mouseMoveEvent(QMouseEvent *event) } if (!(event->buttons() | Qt::NoButton)) { if (_action_type == DSO_XM_STEP1 || _action_type == DSO_XM_STEP2) { - BOOST_FOREACH(const boost::shared_ptr s, _view.session().get_signals()) { + for(auto &s : _view.session().get_signals()) { assert(s); if (!s->get_view_rect().contains(event->pos())) { clear_dso_xm(); @@ -741,14 +757,19 @@ void Viewport::mouseMoveEvent(QMouseEvent *event) void Viewport::mouseReleaseEvent(QMouseEvent *event) { assert(event); - - if (_type == TIME_VIEW) { + + if (_type != TIME_VIEW){ + update(); + return; + } + if ((_action_type == NO_ACTION) && (event->button() == Qt::LeftButton)) { if (_view.session().get_device()->dev_inst()->mode == LOGIC && _view.session().get_capture_state() == SigSession::Stopped) { - // priority 1 - if (_action_type == NO_ACTION) { + //priority 1 + //try to quick scroll view... + if (_action_type == NO_ACTION && AppConfig::Instance()._appOptions.quickScroll) { const double strength = _drag_strength*DragTimerInterval*1.0/_elapsed_time.elapsed(); if (_elapsed_time.elapsed() < 200 && abs(_drag_strength) < MinorDragOffsetUp && @@ -766,11 +787,12 @@ void Viewport::mouseReleaseEvent(QMouseEvent *event) // priority 2 if (_action_type == NO_ACTION) { if (_mouse_down_point.x() == event->pos().x()) { - const vector< boost::shared_ptr > sigs(_view.session().get_signals()); - BOOST_FOREACH(const boost::shared_ptr s, sigs) { + const auto &sigs = _view.session().get_signals(); + + for(auto &s : sigs) { assert(s); - boost::shared_ptr logicSig; - if ((logicSig = dynamic_pointer_cast(s))) { + view::LogicSignal *logicSig = NULL; + if ((logicSig = dynamic_cast(s))) { if (logicSig->edge(event->pos(), _edge_start, 10)) { _action_type = LOGIC_JUMP; _cur_preX = _view.index2pixel(_edge_start); @@ -789,8 +811,9 @@ void Viewport::mouseReleaseEvent(QMouseEvent *event) // priority 3 if (_action_type == NO_ACTION) { if (_mouse_down_point.x() == event->pos().x()) { - const vector< boost::shared_ptr > sigs(_view.session().get_signals()); - BOOST_FOREACH(const boost::shared_ptr s, sigs) { + const auto &sigs = _view.session().get_signals(); + + for(auto &s : sigs) { assert(s); if (abs(event->pos().y() - s->get_y()) < _view.get_signalHeight()) { _action_type = LOGIC_EDGE; @@ -821,15 +844,17 @@ void Viewport::mouseReleaseEvent(QMouseEvent *event) } } else if (_action_type == DSO_TRIG_MOVE) { if (_dso_trig_moved && event->button() == Qt::LeftButton) { - _drag_sig.reset(); + _drag_sig = NULL; _action_type = NO_ACTION; _dso_trig_moved = false; - const vector< boost::shared_ptr > traces( - _view.get_traces(ALL_VIEW)); - BOOST_FOREACH(const boost::shared_ptr t, traces) - t->select(false); + const auto &traces = _view.get_traces(ALL_VIEW); + + for(auto &t : traces){ + t->select(false); + } } + } else if (_action_type == DSO_XM_STEP0) { if (event->button() == Qt::LeftButton) { _action_type = DSO_XM_STEP1; @@ -872,7 +897,7 @@ void Viewport::mouseReleaseEvent(QMouseEvent *event) } if (_xcurs_moved && event->button() == Qt::LeftButton) { _action_type = NO_ACTION; - list::iterator i = _view.get_xcursorList().begin(); + auto i = _view.get_xcursorList().begin(); while (i != _view.get_xcursorList().end()) { (*i)->rel_grabbed(); i++; @@ -920,7 +945,7 @@ void Viewport::mouseReleaseEvent(QMouseEvent *event) } _action_type = NO_ACTION; } - } + update(); } @@ -943,11 +968,11 @@ void Viewport::mouseDoubleClickEvent(QMouseEvent *event) uint64_t index; uint64_t index0 = 0, index1 = 0, index2 = 0; if (_view.session().get_device()->dev_inst()->mode == LOGIC) { - const vector< boost::shared_ptr > sigs(_view.session().get_signals()); - BOOST_FOREACH(const boost::shared_ptr s, sigs) { + const auto &sigs = _view.session().get_signals(); + for(auto &s : sigs) { assert(s); - boost::shared_ptr logicSig; - if ((logicSig = dynamic_pointer_cast(s))) { + view::LogicSignal *logicSig = NULL; + if ((logicSig = dynamic_cast(s))) { if (logicSig->measure(event->pos(), index0, index1, index2)) { logic = true; break; @@ -977,7 +1002,7 @@ void Viewport::mouseDoubleClickEvent(QMouseEvent *event) clear_dso_xm(); measure_updated(); } else if (_action_type == NO_ACTION) { - BOOST_FOREACH(const boost::shared_ptr s, _view.session().get_signals()) { + for(auto &s : _view.session().get_signals()) { assert(s); if (s->get_view_rect().contains(event->pos())) { _dso_xm_index[0] = _view.pixel2index(event->pos().x()); @@ -1000,54 +1025,86 @@ void Viewport::mouseDoubleClickEvent(QMouseEvent *event) void Viewport::wheelEvent(QWheelEvent *event) { - assert(event); + assert(event); - if (_type == FFT_VIEW) { - BOOST_FOREACH(const boost::shared_ptr t, _view.session().get_spectrum_traces()) { - assert(t); - if(t->enabled()) { - t->zoom(event->delta() / 80, event->x()); + int x = 0; //mouse x pos + int delta = 0; + bool isVertical = true; + +#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) + x = (int)event->position().x(); + int anglex = event->angleDelta().x(); + int angley = event->angleDelta().y(); + + if (anglex == 0 || ABS_VAL(angley) >= ABS_VAL(anglex)){ + delta = angley; + isVertical = true; + } + else{ + delta = anglex; + isVertical = false; //hori direction + } +#else + x = event->x(); + delta = event->delta(); + isVertical = event->orientation() == Qt::Vertical; +#endif + + if (_type == FFT_VIEW) + { + for (auto &t : _view.session().get_spectrum_traces()) + { + if (t->enabled()) + { + t->zoom(delta / 80, x); break; } } - } else if (_type == TIME_VIEW){ - if (event->orientation() == Qt::Vertical) { + } + else if (_type == TIME_VIEW) + { + if (isVertical) + { // Vertical scrolling is interpreted as zooming in/out - const int offset = event->x(); - #ifdef Q_OS_DARWIN +#ifdef Q_OS_DARWIN static bool active = true; static int64_t last_time; - if (event->source() == Qt::MouseEventSynthesizedBySystem) { - if (active && (event->modifiers() & Qt::ShiftModifier)) { + if (event->source() == Qt::MouseEventSynthesizedBySystem) + { + if (active && (event->modifiers() & Qt::ShiftModifier)) + { last_time = QDateTime::currentMSecsSinceEpoch(); - const double scale = event->delta() > 1.5 ? 1 : - event->delta() < -1.5 ? -1 : 0; - _view.zoom(scale, offset); + const double scale = delta > 1.5 ? 1 : (delta < -1.5 ? -1 : 0); + _view.zoom(scale, x); } int64_t cur_time = QDateTime::currentMSecsSinceEpoch(); if (cur_time - last_time > 50) active = true; else active = false; - } else { - _view.zoom(-event->delta() / 80, offset); } - #else - _view.zoom(event->delta() / 80, offset); - #endif - } else if (event->orientation() == Qt::Horizontal) { + else + { + _view.zoom(-delta / 80, x); + } +#else + _view.zoom(delta / 80, x); +#endif + } + else + { // Horizontal scrolling is interpreted as moving left/right if (!(event->modifiers() & Qt::ShiftModifier)) - _view.set_scale_offset(_view.scale(), - _view.offset() - event->delta()); + _view.set_scale_offset(_view.scale(), _view.offset() - delta); } } - const vector< boost::shared_ptr > sigs(_view.session().get_signals()); - BOOST_FOREACH(const boost::shared_ptr s, sigs) { - assert(s); - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s))) { + const auto &sigs = _view.session().get_signals(); + for (auto &s : sigs) + { + view::DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(s))) + { dsoSig->auto_end(); } } @@ -1151,13 +1208,15 @@ void Viewport::measure() _measure_type = NO_MEASURE; if (_type == TIME_VIEW) { const uint64_t sample_rate = _view.session().cur_snap_samplerate(); - const vector< boost::shared_ptr > sigs(_view.session().get_signals()); - BOOST_FOREACH(const boost::shared_ptr s, sigs) { + const auto &sigs = _view.session().get_signals(); + + for(auto &s : sigs) { assert(s); - boost::shared_ptr logicSig; - boost::shared_ptr dsoSig; - boost::shared_ptr analogSig; - if ((logicSig = dynamic_pointer_cast(s))) { + view::LogicSignal *logicSig = NULL; + view::DsoSignal *dsoSig = NULL; + view::AnalogSignal *analogSig = NULL; + + if ((logicSig = dynamic_cast(s))) { if (_action_type == NO_ACTION) { if (logicSig->measure(_mouse_point, _cur_sample, _nxt_sample, _thd_sample)) { _measure_type = LOGIC_FREQ; @@ -1207,7 +1266,7 @@ void Viewport::measure() _edge_hit = false; } } - } else if ((dsoSig = dynamic_pointer_cast(s))) { + } else if ((dsoSig = dynamic_cast(s))) { if (dsoSig->enabled()) { if (_measure_en && dsoSig->measure(_view.hover_point())) { _measure_type = DSO_VALUE; @@ -1215,7 +1274,7 @@ void Viewport::measure() _measure_type = NO_MEASURE; } } - } else if ((analogSig = dynamic_pointer_cast(s))) { + } else if ((analogSig = dynamic_cast(s))) { if (analogSig->enabled()) { if (_measure_en && analogSig->measure(_view.hover_point())) { _measure_type = DSO_VALUE; @@ -1225,7 +1284,7 @@ void Viewport::measure() } } } - const boost::shared_ptr mathTrace(_view.session().get_math_trace()); + const auto mathTrace = _view.session().get_math_trace(); if (mathTrace && mathTrace->enabled()) { if (_measure_en && mathTrace->measure(_view.hover_point())) { _measure_type = DSO_VALUE; @@ -1234,7 +1293,7 @@ void Viewport::measure() } } } else if (_type == FFT_VIEW) { - BOOST_FOREACH(const boost::shared_ptr t, _view.session().get_spectrum_traces()) { + for(auto &t : _view.session().get_spectrum_traces()) { assert(t); if(t->enabled()) { t->measure(_mouse_point); @@ -1305,13 +1364,15 @@ void Viewport::paintMeasure(QPainter &p, QColor fore, QColor back) } } - const vector< boost::shared_ptr > sigs(_view.session().get_signals()); + const auto &sigs = _view.session().get_signals(); if (_action_type == NO_ACTION && _measure_type == DSO_VALUE) { - BOOST_FOREACH(const boost::shared_ptr s, sigs) { - boost::shared_ptr dsoSig; - boost::shared_ptr analogSig; - if ((dsoSig = dynamic_pointer_cast(s))) { + + for(auto &s : sigs) { + view::DsoSignal *dsoSig = NULL; + view::AnalogSignal* analogSig = NULL; + + if ((dsoSig = dynamic_cast(s))) { uint64_t index; double value; QPointF hpoint; @@ -1321,7 +1382,7 @@ void Viewport::paintMeasure(QPainter &p, QColor fore, QColor back) p.drawLine(hpoint.x(), dsoSig->get_view_rect().top(), hpoint.x(), dsoSig->get_view_rect().bottom()); } - } else if ((analogSig = dynamic_pointer_cast(s))) { + } else if ((analogSig = dynamic_cast(s))) { uint64_t index; double value; QPointF hpoint; @@ -1336,9 +1397,9 @@ void Viewport::paintMeasure(QPainter &p, QColor fore, QColor back) } if (_dso_ym_valid) { - BOOST_FOREACH(const boost::shared_ptr s, sigs) { - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s))) { + for(auto &s : sigs) { + view::DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(s))) { if (dsoSig->get_index() == _dso_ym_sig_index) { p.setPen(QPen(dsoSig->get_colour(), 1, Qt::DotLine)); const int text_height = p.boundingRect(0, 0, INT_MAX, INT_MAX, @@ -1536,7 +1597,9 @@ void Viewport::paintMeasure(QPainter &p, QColor fore, QColor back) QString delta_text = _view.get_index_delta(_edge_start, _edge_end) + "/" + QString::number(delta); QFontMetrics fm = this->fontMetrics(); - const int rectW = fm.width(delta_text) + 60; + // const int rectW = fm.width(delta_text) + 60; + const int rectW = fm.boundingRect(delta_text).width() + 60; + const int rectH = fm.height() + 10; //const int rectY = (_cur_aftY >= _cur_preY) ? _cur_preY_top : _cur_preY_bottom; //const int rectX = (_cur_aftX >= _cur_preX) ? _cur_preX : _cur_preX - rectW; @@ -1605,7 +1668,7 @@ void Viewport::on_trigger_timer() } void Viewport::on_drag_timer() -{ +{ const int64_t offset = _view.offset(); const double scale = _view.scale(); if (_view.session().get_capture_state() == SigSession::Stopped && @@ -1645,7 +1708,7 @@ void Viewport::unshow_wait_trigger() update(); } -bool Viewport::get_dso_trig_moved() const +bool Viewport::get_dso_trig_moved() { return _dso_trig_moved; } diff --git a/DSView/pv/view/viewport.h b/DSView/pv/view/viewport.h index 9a9689cf..0442645d 100755 --- a/DSView/pv/view/viewport.h +++ b/DSView/pv/view/viewport.h @@ -25,10 +25,7 @@ #define DSVIEW_PV_VIEW_VIEWPORT_H #include - -#include -#include - + #include #include #include @@ -36,7 +33,7 @@ #include #include "../view/view.h" -#include "../../extdef.h" +#include "../extdef.h" class QPainter; class QPaintEvent; @@ -48,6 +45,9 @@ namespace view { class Signal; class View; +//main graph view port, in the middle region +//draw the left and right rule scale +//created by View class Viewport : public QWidget { Q_OBJECT @@ -89,9 +89,9 @@ public: public: explicit Viewport(View &parent, View_type type); - int get_total_height() const; + int get_total_height(); - QPoint get_mouse_point() const; + QPoint get_mouse_point(); QString get_measure(QString option); @@ -106,7 +106,7 @@ public: void set_need_update(bool update); - bool get_dso_trig_moved() const; + bool get_dso_trig_moved(); protected: bool event(QEvent *event) override; @@ -131,8 +131,7 @@ private: private slots: void on_trigger_timer(); void on_drag_timer(); - void set_receive_len(quint64 length); - + void show_contextmenu(const QPoint& pos); void add_cursor_x(); void add_cursor_y(); @@ -140,6 +139,7 @@ private slots: public slots: void show_wait_trigger(); void unshow_wait_trigger(); + void set_receive_len(quint64 length); signals: void measure_updated(); @@ -195,7 +195,7 @@ private: bool transfer_started; int timer_cnt; - boost::shared_ptr _drag_sig; + Signal *_drag_sig; uint64_t _hover_index; bool _hover_hit; diff --git a/DSView/pv/view/viewstatus.cpp b/DSView/pv/view/viewstatus.cpp index 83db6d83..ccd3872a 100755 --- a/DSView/pv/view/viewstatus.cpp +++ b/DSView/pv/view/viewstatus.cpp @@ -26,6 +26,8 @@ #include #include #include +#include +#include #include "../view/trace.h" #include "../sigsession.h" @@ -34,13 +36,13 @@ #include "../view/trace.h" #include "../dialogs/dsomeasure.h" -using namespace boost; + using namespace std; namespace pv { namespace view { -ViewStatus::ViewStatus(SigSession &session, View &parent) : +ViewStatus::ViewStatus(SigSession *session, View &parent) : QWidget(&parent), _session(session), _view(parent), @@ -52,12 +54,17 @@ ViewStatus::ViewStatus(SigSession &session, View &parent) : void ViewStatus::paintEvent(QPaintEvent *) { QStyleOption opt; - opt.init(this); + #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) + opt.initFrom(this); + #else + opt.init(this); + #endif + QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); QColor fore(QWidget::palette().color(QWidget::foregroundRole())); - if (_session.get_device()->dev_inst()->mode == LOGIC) { + if (_session->get_device()->dev_inst()->mode == LOGIC) { fore.setAlpha(View::ForeAlpha); p.setPen(fore); p.drawText(this->rect(), Qt::AlignLeft | Qt::AlignVCenter, _rle_depth); @@ -66,21 +73,22 @@ void ViewStatus::paintEvent(QPaintEvent *) p.setPen(Qt::NoPen); p.setBrush(View::Blue); p.drawRect(this->rect().left(), this->rect().bottom() - 3, - _session.get_repeat_hold() * this->rect().width() / 100, 3); + _session->get_repeat_hold() * this->rect().width() / 100, 3); p.setPen(View::Blue); p.drawText(this->rect(), Qt::AlignCenter | Qt::AlignVCenter, _capture_status); - } else if (_session.get_device()->dev_inst()->mode == DSO) { + } else if (_session->get_device()->dev_inst()->mode == DSO) { fore.setAlpha(View::BackAlpha); for(size_t i = 0; i < _mrects.size(); i++) { int sig_index = std::get<1>(_mrects[i]); - boost::shared_ptr dsoSig = NULL; - const vector< boost::shared_ptr > sigs(_session.get_signals()); - BOOST_FOREACH(const boost::shared_ptr s, sigs) { + view::DsoSignal *dsoSig = NULL; + const auto &sigs = _session->get_signals(); + + for(auto &s : sigs) { assert(s); if (!s->enabled()) continue; - if ((dsoSig = dynamic_pointer_cast(s))) { + if ((dsoSig = dynamic_cast(s))) { if (sig_index == dsoSig->get_index()) break; else @@ -133,7 +141,7 @@ void ViewStatus::reload() const int COLUMN = 5; const int ROW = 2; const int MARGIN = 3; - if (_session.get_device()->dev_inst()->mode == DSO) + if (_session->get_device()->dev_inst()->mode == DSO) { const double width = _view.get_view_width() * 1.0 / COLUMN; const int height = (this->height() - 2*MARGIN) / ROW; @@ -184,11 +192,10 @@ void ViewStatus::mousePressEvent(QMouseEvent *event) { assert(event); - if (_session.get_device()->dev_inst()->mode != DSO) + if (_session->get_device()->dev_inst()->mode != DSO) return; - if (event->button() == Qt::LeftButton) { - //BOOST_FOREACH(QRect rect, std::get<0>(_mrects)) { + if (event->button() == Qt::LeftButton) { for(size_t i = 0; i < _mrects.size(); i++) { const QRect rect = std::get<0>(_mrects[i]); if (rect.contains(event->pos())) { @@ -233,11 +240,11 @@ QJsonArray ViewStatus::get_session() void ViewStatus::load_session(QJsonArray measure_array) { - if (_session.get_device()->dev_inst()->mode != DSO || + if (_session->get_device()->dev_inst()->mode != DSO || measure_array.empty()) return; - foreach (const QJsonValue &measure_value, measure_array) { + for (const QJsonValue &measure_value : measure_array) { QJsonObject m_obj = measure_value.toObject(); int index = m_obj["site"].toInt(); int sig_index = m_obj["index"].toInt(); diff --git a/DSView/pv/view/viewstatus.h b/DSView/pv/view/viewstatus.h index 804dfbfa..c4125ca3 100755 --- a/DSView/pv/view/viewstatus.h +++ b/DSView/pv/view/viewstatus.h @@ -27,10 +27,7 @@ #include #include #include - -#include -#include - + #include namespace pv { @@ -41,12 +38,15 @@ namespace view { class View; class DsoSignal; - +//created by View class ViewStatus : public QWidget { Q_OBJECT + public: - ViewStatus(SigSession &session, View &parent); + ViewStatus(SigSession *session, View &parent); + +public: void paintEvent(QPaintEvent *); void mousePressEvent(QMouseEvent *); @@ -68,7 +68,7 @@ public slots: void set_capture_status(bool triggered, int progess); private: - SigSession &_session; + SigSession *_session; View &_view; int _hit_rect; diff --git a/DSView/pv/view/xcursor.cpp b/DSView/pv/view/xcursor.cpp index 2566505d..1148dfb5 100755 --- a/DSView/pv/view/xcursor.cpp +++ b/DSView/pv/view/xcursor.cpp @@ -28,10 +28,7 @@ #include "dsosignal.h" #include - -#include - -using namespace boost; + using namespace std; namespace pv { @@ -47,10 +44,11 @@ XCursor::XCursor(View &view, QColor &colour, _colour(colour) { _dsoSig = NULL; - const std::vector< boost::shared_ptr > sigs(_view.session().get_signals()); - BOOST_FOREACH(const boost::shared_ptr s, sigs) { - boost::shared_ptr dsoSig; - if ((dsoSig = dynamic_pointer_cast(s))) + const auto &sigs = _view.session().get_signals(); + + for(auto &s : sigs) { + DsoSignal *dsoSig = NULL; + if ((dsoSig = dynamic_cast(s))) if (dsoSig->enabled()) { _dsoSig = dsoSig; break; @@ -70,7 +68,7 @@ XCursor::XCursor(const XCursor &x) : { } -QColor XCursor::colour() const +QColor XCursor::colour() { return _colour; } @@ -83,16 +81,16 @@ void XCursor::set_colour(QColor color) /** * Gets/Sets the mapping channel of the marker */ -boost::shared_ptr XCursor::channel() const +DsoSignal* XCursor::channel() { return _dsoSig; } -void XCursor::set_channel(boost::shared_ptr sig) +void XCursor::set_channel(DsoSignal *sig) { _dsoSig = sig; } -enum XCursor::XCur_type XCursor::grabbed() const +enum XCursor::XCur_type XCursor::grabbed() { return _grabbed; } @@ -108,7 +106,7 @@ void XCursor::rel_grabbed() _grabbed = XCur_None; } -double XCursor::value(XCur_type type) const +double XCursor::value(XCur_type type) { if (type == XCur_Y) return _yvalue; @@ -132,7 +130,7 @@ void XCursor::set_value(XCur_type type, double value) } void XCursor::paint(QPainter &p, const QRect &rect, XCur_type highlight, int order) -{ +{ const int arrow = 3; const int x = rect.left() + _yvalue * rect.width(); const int y0 = rect.top() + _value0 * rect.height(); @@ -182,7 +180,7 @@ void XCursor::paint(QPainter &p, const QRect &rect, XCur_type highlight, int or * @param rect The rectangle of the xcursor area. * @return Returns the map label rectangle. */ -QRect XCursor::get_map_rect(const QRect &rect) const +QRect XCursor::get_map_rect(const QRect &rect) { const int width = 10; const int64_t y = rect.top() + _value0 * rect.height() - width/2; @@ -194,7 +192,7 @@ QRect XCursor::get_map_rect(const QRect &rect) const * @param rect The rectangle of the xcursor area. * @return Returns the close label rectangle. */ -QRect XCursor::get_close_rect(const QRect &rect) const +QRect XCursor::get_close_rect(const QRect &rect) { const int width = 10; const int64_t y = rect.top() + _value1 * rect.height() - width/2; diff --git a/DSView/pv/view/xcursor.h b/DSView/pv/view/xcursor.h index 7f5901ba..7a95bf1c 100755 --- a/DSView/pv/view/xcursor.h +++ b/DSView/pv/view/xcursor.h @@ -26,10 +26,7 @@ #include #include #include - -#include -#include - + #include class QPainter; @@ -41,9 +38,11 @@ namespace view { class View; class DsoSignal; +//created by View class XCursor : public QObject { Q_OBJECT + public: enum XCur_type { XCur_None = -2, @@ -72,25 +71,25 @@ public: /** * Gets/Set the value of the marker. */ - double value(enum XCur_type type) const; + double value(enum XCur_type type); void set_value(enum XCur_type type, double value); /** * Gets/Sets colour of the marker */ - QColor colour() const; + QColor colour(); void set_colour(QColor color); /** * Gets/Sets the mapping channel of the marker */ - boost::shared_ptr channel() const; - void set_channel(boost::shared_ptr sig); + DsoSignal* channel(); + void set_channel(DsoSignal *sig); /** * grab & move */ - enum XCur_type grabbed() const; + enum XCur_type grabbed(); void set_grabbed(enum XCur_type type, bool grabbed); void rel_grabbed(); @@ -106,14 +105,14 @@ public: * @param rect The rectangle of the xcursor area. * @return Returns the map label rectangle. */ - QRect get_map_rect(const QRect &rect) const; + QRect get_map_rect(const QRect &rect); /** * Gets the close label rectangle. * @param rect The rectangle of the xcursor area. * @return Returns the close label rectangle. */ - QRect get_close_rect(const QRect &rect) const; + QRect get_close_rect(const QRect &rect); /** * Paints the labels to the xcursor. @@ -126,8 +125,8 @@ signals: void value_changed(); protected: - View &_view; - boost::shared_ptr _dsoSig; + View &_view; + DsoSignal *_dsoSig; double _yvalue; double _value0; diff --git a/DSView/pv/widgets/border.cpp b/DSView/pv/widgets/border.cpp index 9ff70e20..79737213 100755 --- a/DSView/pv/widgets/border.cpp +++ b/DSView/pv/widgets/border.cpp @@ -21,11 +21,11 @@ #include "border.h" #include "../mainframe.h" - -#include + #include #include #include +#include "../config/appconfig.h" namespace pv { namespace widgets { @@ -56,7 +56,10 @@ void Border::paintEvent(QPaintEvent *) painter.setPen(Qt::NoPen); painter.setRenderHint(QPainter::Antialiasing, true); QLinearGradient linearGrad(QPointF(width(), height()), QPointF(0, 0)); - if (qApp->property("Style").toString() == "dark") { + AppConfig &app = AppConfig::Instance(); + QString style = app._frameOptions.style; + + if (style == "dark") { linearGrad.setColorAt(0, dark_border0); linearGrad.setColorAt(0.25, dark_border1); linearGrad.setColorAt(0.5, dark_border2); @@ -71,7 +74,7 @@ void Border::paintEvent(QPaintEvent *) } QRadialGradient radialGrad(QPointF(0, 0), width()); - if (qApp->property("Style").toString() == "dark") { + if (style == "dark") { radialGrad.setColorAt(0, dark_border0); radialGrad.setColorAt(0.25, dark_border1); radialGrad.setColorAt(0.5, dark_border2); diff --git a/DSView/pv/widgets/decodergroupbox.cpp b/DSView/pv/widgets/decodergroupbox.cpp index 80c4c446..82a809b5 100755 --- a/DSView/pv/widgets/decodergroupbox.cpp +++ b/DSView/pv/widgets/decodergroupbox.cpp @@ -32,16 +32,17 @@ #include #include #include - -#include +#include + +#include "../config/appconfig.h" #include namespace pv { namespace widgets { -DecoderGroupBox::DecoderGroupBox(boost::shared_ptr &decoder_stack, - boost::shared_ptr &dec, +DecoderGroupBox::DecoderGroupBox(data::DecoderStack *decoder_stack, + data::decode::Decoder *dec, QLayout *dec_layout, QWidget *parent) : QScrollArea(parent), @@ -55,7 +56,7 @@ DecoderGroupBox::DecoderGroupBox(boost::shared_ptr &decoder_ setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setWidgetResizable(true); - QString iconPath = ":/icons/" + qApp->property("Style").toString(); + QString iconPath = GetIconPath(); _layout->addWidget(new QLabel(QString("

%1

").arg(_dec->decoder()->name), _widget), 0, 0); _layout->setColumnStretch(0, 1); @@ -70,8 +71,7 @@ DecoderGroupBox::DecoderGroupBox(boost::shared_ptr &decoder_ } _index = 0; - BOOST_FOREACH(boost::shared_ptr dec, - _decoder_stack->stack()) { + for(auto &dec : _decoder_stack->stack()) { if (dec == _dec) break; _index++; @@ -129,14 +129,14 @@ bool DecoderGroupBox::eventFilter(QObject *o, QEvent *e) void DecoderGroupBox::tog_icon() { - QString iconPath = ":/icons/" + qApp->property("Style").toString(); + QString iconPath = GetIconPath(); QPushButton *sc = dynamic_cast(sender()); QVariant id = sc->property("index"); int index = id.toInt(); if (index == -1) { int i = _index; - BOOST_FOREACH(boost::shared_ptr dec, - _decoder_stack->stack()) { + + for(auto &dec : _decoder_stack->stack()) { if (i-- == 0) { dec->show(!dec->shown()); sc->setIcon(QIcon(dec->shown() ? iconPath+"/shown.svg" : @@ -162,8 +162,7 @@ void DecoderGroupBox::tog_icon() void DecoderGroupBox::on_del_stack() { int i = _index; - BOOST_FOREACH(boost::shared_ptr dec, - _decoder_stack->stack()) { + for(auto &dec : _decoder_stack->stack()) { if (i-- == 0) { del_stack(dec); break; diff --git a/DSView/pv/widgets/decodergroupbox.h b/DSView/pv/widgets/decodergroupbox.h index 814e42a6..96812532 100755 --- a/DSView/pv/widgets/decodergroupbox.h +++ b/DSView/pv/widgets/decodergroupbox.h @@ -22,12 +22,11 @@ #ifndef DSVIEW_PV_WIDGETS_DECODERGROUPBOX_H #define DSVIEW_PV_WIDGETS_DECODERGROUPBOX_H -#include + #include #include #include -#include -#include +#include namespace pv { @@ -45,8 +44,8 @@ class DecoderGroupBox : public QScrollArea Q_OBJECT public: - DecoderGroupBox(boost::shared_ptr &decoder_stack, - boost::shared_ptr &dec, QLayout *dec_layout, + DecoderGroupBox(pv::data::DecoderStack *decoder_stack, + data::decode::Decoder *dec, QLayout *dec_layout, QWidget *parent = NULL); ~DecoderGroupBox(); bool eventFilter(QObject *o, QEvent *e); @@ -54,7 +53,7 @@ public: signals: void show_hide_decoder(); void show_hide_row(); - void del_stack(boost::shared_ptr &_dec); + void del_stack(data::decode::Decoder *_dec); private slots: void tog_icon(); @@ -63,8 +62,8 @@ private slots: private: QWidget *_widget; - boost::shared_ptr &_decoder_stack; - boost::shared_ptr &_dec; + pv::data::DecoderStack *_decoder_stack; + data::decode::Decoder *_dec; int _index; QGridLayout *_layout; diff --git a/DSView/pv/widgets/decodermenu.cpp b/DSView/pv/widgets/decodermenu.cpp index 39b1c156..f0a7a201 100755 --- a/DSView/pv/widgets/decodermenu.cpp +++ b/DSView/pv/widgets/decodermenu.cpp @@ -50,8 +50,11 @@ DecoderMenu::DecoderMenu(QWidget *parent, bool first_level_decoder) : } g_slist_free(l); - connect(&_mapper, SIGNAL(mapped(QObject*)), - this, SLOT(on_action(QObject*))); +#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) + connect(&_mapper, SIGNAL(mappedObject(QObject*)), this, SLOT(on_action(QObject*))); +#else + connect(&_mapper, SIGNAL(mapped(QObject*)), this, SLOT(on_action(QObject*))); +#endif } int DecoderMenu::decoder_name_cmp(const void *a, const void *b) diff --git a/DSView/test/data/analogsnapshot.cpp b/DSView/test/data/analogsnapshot.cpp index cd1fd773..7cf4f289 100755 --- a/DSView/test/data/analogsnapshot.cpp +++ b/DSView/test/data/analogsnapshot.cpp @@ -17,15 +17,13 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#include - + #define __STDC_LIMIT_MACROS #include #include - #include "../../pv/data/analogsnapshot.h" +#include "../extdef.h" using namespace std; diff --git a/DSView/test/data/logicsnapshot.cpp b/DSView/test/data/logicsnapshot.cpp index bbc74383..2473580e 100755 --- a/DSView/test/data/logicsnapshot.cpp +++ b/DSView/test/data/logicsnapshot.cpp @@ -18,7 +18,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#include +#include "../extdef.h" #define __STDC_LIMIT_MACROS #include diff --git a/DSView/themes/dark.qss b/DSView/themes/dark.qss index 4ff510ba..d9d62acd 100755 --- a/DSView/themes/dark.qss +++ b/DSView/themes/dark.qss @@ -1279,25 +1279,35 @@ QToolButton::menu-arrow:open QToolButton#ModeButton::menu-arrow { - image: url(:/dark/mode_down_arrow.svg); + /*image: url(:/dark/mode_down_arrow.svg);*/ + image:none; } /* the subcontrol below is used only in the InstantPopup or DelayedPopup mode */ QToolButton::menu-indicator { image: url(:/dark/down_arrow.svg); - top: -7px; - left: -2px; + top: -20px; + left: 0px; + width:8px; + height:10px; } + +QToolButton{ + font-size:14px; +} + QToolButton#ModeButton::menu-indicator { image: url(:/dark/mode_down_arrow.svg); - top: -7px; - left: -3px; + top: 0px; + left: 0px; + width:12px; + height:12px; } QToolButton#ModeButton::menu-indicator:hover { - top: -5px; + top: 0px; } QPushButton::menu-indicator @@ -1612,3 +1622,7 @@ QTextBrowser:hover { border: 1px transparent; } + +QLineEdit#PathLine{ + color:#eff0f1; +} \ No newline at end of file diff --git a/DSView/themes/light.qss b/DSView/themes/light.qss index 06f704e6..06b47f2e 100755 --- a/DSView/themes/light.qss +++ b/DSView/themes/light.qss @@ -1319,26 +1319,35 @@ QToolButton::menu-arrow:open QToolButton#ModeButton::menu-arrow { - image: url(:/light/mode_down_arrow.svg); + /*image: url(:/light/mode_down_arrow.svg);*/ + image:none; } /* the subcontrol below is used only in the InstantPopup or DelayedPopup mode */ QToolButton::menu-indicator { image: url(:/light/down_arrow.svg); - top: -7px; - left: -2px; + top: -20px; + left: 0px; + width:8px; + height:10px; +} + +QToolButton{ + font-size:14px; } QToolButton#ModeButton::menu-indicator { image: url(:/light/mode_down_arrow.svg); - top: -7px; - left: -3px; + top: 0px; + left: 0px; + width:12px; + height:12px; } QToolButton#ModeButton::menu-indicator:hover { - top: -5px; + top: 0px; } QPushButton::menu-indicator @@ -1651,3 +1660,7 @@ QTextBrowser:hover { border: 1px transparent; } + +QLineEdit#PathLine{ + color:#2A2A2A; +} diff --git a/INSTALL b/INSTALL index 94bdb080..abe9eafe 100755 --- a/INSTALL +++ b/INSTALL @@ -26,6 +26,7 @@ Requirements This is part of the standard OpenBSD install (not an extra package), apparently. - check >= 0.9.4 (optional, only needed to run unit tests) - libfftw3 >= 3.3 + - zlib Building and installing ----------------------- diff --git a/applogo.rc b/applogo.rc new file mode 100644 index 00000000..3f4ac618 --- /dev/null +++ b/applogo.rc @@ -0,0 +1 @@ +IDI_ICON1 ICON DISCARDABLE "logo-win.ico" diff --git a/doc/decoder.txt b/doc/decoder.txt new file mode 100644 index 00000000..542a084f --- /dev/null +++ b/doc/decoder.txt @@ -0,0 +1,28 @@ +sigrokdecode module's types + +output types: + 1.OUTPUT_ANN + 2.OUTPUT_PYTHON + 3.OUTPUT_BINARY + 4.OUTPUT_META + +default sample rate name: SRD_CONF_SAMPLERATE,value is 10000 + +sigrokdecode.Decoder methods: + +class Decoder{ + PyObject* put(PyObject *self, PyObject *args); + PyObject* register(PyObject *self, PyObject *args,PyObject *kwargs); + PyObject* wait(PyObject *self, PyObject *args); + PyObject* has_channel(PyObject *self, PyObject *args); +} + + +c can call's method of python: + 1.reset + 2.start + 3.decode + 4.metadata + + + diff --git a/libsigrok4DSL/config.h b/libsigrok4DSL/config.h new file mode 100644 index 00000000..1c40c8d3 --- /dev/null +++ b/libsigrok4DSL/config.h @@ -0,0 +1,192 @@ +/* config.h. Generated from config.h.in by configure. */ +/* config.h.in. Generated from configure.ac by autoheader. */ + +#ifndef SR_CONFIG_H +#define SR_CONFIG_H /* To stop multiple inclusions. */ + +/* Define if building universal (internal helper macro) */ +/* #undef AC_APPLE_UNIVERSAL_BUILD */ + +/* Define to 1 if you have the header file. */ +#define HAVE_DLFCN_H 1 + +/* DreamSourceLab hardware driver support */ +#define HAVE_DSL_DEVICE 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_FCNTL_H 1 + +/* Define to 1 if you have the `gettimeofday' function. */ +#define HAVE_GETTIMEOFDAY 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Demo driver support */ +#define HAVE_LA_DEMO 1 + +/* Specifies whether we have libserialport. */ +/* #undef HAVE_LIBSERIALPORT */ + +/* Specifies whether we have a libusb.h header. */ +#define HAVE_LIBUSB_1_0 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_MEMORY_H 1 + +/* Define to 1 if you have the `memset' function. */ +#define HAVE_MEMSET 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the `strchr' function. */ +#define HAVE_STRCHR 1 + +/* Define to 1 if you have the `strcspn' function. */ +#define HAVE_STRCSPN 1 + +/* Define to 1 if you have the `strdup' function. */ +#define HAVE_STRDUP 1 + +/* Define to 1 if you have the `strerror' function. */ +#define HAVE_STRERROR 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRINGS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have the `strncasecmp' function. */ +#define HAVE_STRNCASECMP 1 + +/* Define to 1 if you have the `strstr' function. */ +#define HAVE_STRSTR 1 + +/* Define to 1 if you have the `strtol' function. */ +#define HAVE_STRTOL 1 + +/* Define to 1 if you have the `strtoul' function. */ +#define HAVE_STRTOUL 1 + +/* Define to 1 if you have the `strtoull' function. */ +#define HAVE_STRTOULL 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TIME_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_TERMIOS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UNISTD_H 1 + +/* Define to the sub-directory where libtool stores uninstalled libraries. */ +#define LT_OBJDIR ".libs/" + +/* Name of package */ +#define PACKAGE "libsigrok4DSL" + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "support@dreamsourcelab.com" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "libsigrok4DSL" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "libsigrok4DSL 0.2.0" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "libsigrok4DSL" + +/* Define to the home page for this package. */ +#define PACKAGE_URL "http://www.dreamsourcelab.com" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "0.2.0" + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Version number of package */ +#define VERSION "0.2.0" + +/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most + significant byte first (like Motorola and SPARC, unlike Intel). */ +#if defined AC_APPLE_UNIVERSAL_BUILD +# if defined __BIG_ENDIAN__ +# define WORDS_BIGENDIAN 1 +# endif +#else +# ifndef WORDS_BIGENDIAN +/* # undef WORDS_BIGENDIAN */ +# endif +#endif + +/* Define for Solaris 2.5.1 so the uint32_t typedef from , + , or is not used. If the typedef were allowed, the + #define below would cause a syntax error. */ +/* #undef _UINT32_T */ + +/* Define for Solaris 2.5.1 so the uint64_t typedef from , + , or is not used. If the typedef were allowed, the + #define below would cause a syntax error. */ +/* #undef _UINT64_T */ + +/* Define for Solaris 2.5.1 so the uint8_t typedef from , + , or is not used. If the typedef were allowed, the + #define below would cause a syntax error. */ +/* #undef _UINT8_T */ + +/* Define to `__inline__' or `__inline' if that's what the C compiler + calls it, or to nothing if 'inline' is not supported under any name. */ +#ifndef __cplusplus +/* #undef inline */ +#endif + +/* Define to the type of a signed integer type of width exactly 16 bits if + such a type exists and the standard includes do not define it. */ +/* #undef int16_t */ + +/* Define to the type of a signed integer type of width exactly 32 bits if + such a type exists and the standard includes do not define it. */ +/* #undef int32_t */ + +/* Define to the type of a signed integer type of width exactly 64 bits if + such a type exists and the standard includes do not define it. */ +/* #undef int64_t */ + +/* Define to the type of a signed integer type of width exactly 8 bits if such + a type exists and the standard includes do not define it. */ +/* #undef int8_t */ + +/* Define to `unsigned int' if does not define. */ +/* #undef size_t */ + +/* Define to the type of an unsigned integer type of width exactly 16 bits if + such a type exists and the standard includes do not define it. */ +/* #undef uint16_t */ + +/* Define to the type of an unsigned integer type of width exactly 32 bits if + such a type exists and the standard includes do not define it. */ +/* #undef uint32_t */ + +/* Define to the type of an unsigned integer type of width exactly 64 bits if + such a type exists and the standard includes do not define it. */ +/* #undef uint64_t */ + +/* Define to the type of an unsigned integer type of width exactly 8 bits if + such a type exists and the standard includes do not define it. */ +/* #undef uint8_t */ + +#endif /* SR_CONFIG_H */ diff --git a/libsigrok4DSL/dsdevice.c b/libsigrok4DSL/dsdevice.c index bf0c6ce9..213a91db 100755 --- a/libsigrok4DSL/dsdevice.c +++ b/libsigrok4DSL/dsdevice.c @@ -360,7 +360,7 @@ SR_API int sr_dev_open(struct sr_dev_inst *sdi) SR_API int sr_dev_close(struct sr_dev_inst *sdi) { int ret; - + if (!sdi || !sdi->driver || !sdi->driver->dev_close) return SR_ERR; diff --git a/libsigrok4DSL/hardware/DSL/command.c b/libsigrok4DSL/hardware/DSL/command.c index 82170f08..b391237d 100755 --- a/libsigrok4DSL/hardware/DSL/command.c +++ b/libsigrok4DSL/hardware/DSL/command.c @@ -17,8 +17,8 @@ * along with this program. If not, see . */ -#include "libsigrok.h" -#include "libsigrok-internal.h" +#include "../../libsigrok.h" +#include "../../libsigrok-internal.h" #include "command.h" #include "dsl.h" diff --git a/libsigrok4DSL/hardware/DSL/command.h b/libsigrok4DSL/hardware/DSL/command.h index 0a541c47..a5647638 100755 --- a/libsigrok4DSL/hardware/DSL/command.h +++ b/libsigrok4DSL/hardware/DSL/command.h @@ -21,8 +21,8 @@ #define LIBDSL_HARDWARE_COMMAND_H #include -#include "libsigrok.h" -#include "libsigrok-internal.h" +#include "../../libsigrok.h" +#include "../../libsigrok-internal.h" /* Protocol commands */ #define CMD_CTL_WR 0xb0 diff --git a/libsigrok4DSL/hardware/DSL/dscope.c b/libsigrok4DSL/hardware/DSL/dscope.c index 12652a55..b9bdb446 100755 --- a/libsigrok4DSL/hardware/DSL/dscope.c +++ b/libsigrok4DSL/hardware/DSL/dscope.c @@ -18,8 +18,8 @@ * along with this program. If not, see . */ -#include "libsigrok.h" -#include "libsigrok-internal.h" +#include "../../libsigrok.h" +#include "../../libsigrok-internal.h" #include "dsl.h" #include "command.h" diff --git a/libsigrok4DSL/hardware/DSL/dsl.c b/libsigrok4DSL/hardware/DSL/dsl.c index a08452b1..70c5da81 100755 --- a/libsigrok4DSL/hardware/DSL/dsl.c +++ b/libsigrok4DSL/hardware/DSL/dsl.c @@ -17,8 +17,8 @@ * along with this program. If not, see . */ -#include "libsigrok.h" -#include "libsigrok-internal.h" +#include "../../libsigrok.h" +#include "../../libsigrok-internal.h" #include "command.h" #include "dsl.h" @@ -1779,6 +1779,7 @@ SR_PRIV int dsl_dev_open(struct sr_dev_driver *di, struct sr_dev_inst *sdi, gboo int ret; uint8_t hw_info; struct ctl_rd_cmd rd_cmd; + int fdError = 0; devc = sdi->priv; usb = sdi->conn; @@ -1799,7 +1800,7 @@ SR_PRIV int dsl_dev_open(struct sr_dev_driver *di, struct sr_dev_inst *sdi, gboo sr_err("%s: Unable to open device.", __func__); return SR_ERR; } - + ret = libusb_claim_interface(usb->devhdl, USB_INTERFACE); if (ret != 0) { switch(ret) { @@ -1810,13 +1811,27 @@ SR_PRIV int dsl_dev_open(struct sr_dev_driver *di, struct sr_dev_inst *sdi, gboo case LIBUSB_ERROR_NO_DEVICE: sr_err("%s: Device has been disconnected.", __func__); break; + case LIBUSB_ERROR_NOT_FOUND: + { + sr_err("%s: Unable to claim interface, try again: LIBUSB_ERROR_NOT_FOUND.", __func__); + ret = libusb_claim_interface(usb->devhdl, USB_INTERFACE); + fdError = 1; + } + break; default: - sr_err("%s: Unable to claim interface: %s.", + sr_err("%s: Unable to claim interface, try again: %s.", __func__, libusb_error_name(ret)); break; } - return SR_ERR; + if (ret != 0 && fdError == 1){ + sr_err("%s: Unable to claim interface, the second time: %s.", + __func__, libusb_error_name(ret)); + } + + if (ret != 0){ + return SR_ERR; + } } rd_cmd.header.dest = DSL_CTL_HW_STATUS; diff --git a/libsigrok4DSL/hardware/DSL/dsl.h b/libsigrok4DSL/hardware/DSL/dsl.h index 4d695380..9f9fe95f 100755 --- a/libsigrok4DSL/hardware/DSL/dsl.h +++ b/libsigrok4DSL/hardware/DSL/dsl.h @@ -22,8 +22,8 @@ #define LIBDSL_HARDWARE_DSL_H #include -#include "libsigrok.h" -#include "libsigrok-internal.h" +#include "../../libsigrok.h" +#include "../../libsigrok-internal.h" #include "command.h" #include diff --git a/libsigrok4DSL/hardware/DSL/dslogic.c b/libsigrok4DSL/hardware/DSL/dslogic.c index 443c8052..345f9db9 100755 --- a/libsigrok4DSL/hardware/DSL/dslogic.c +++ b/libsigrok4DSL/hardware/DSL/dslogic.c @@ -18,8 +18,8 @@ * along with this program. If not, see . */ -#include "libsigrok.h" -#include "libsigrok-internal.h" +#include "../../libsigrok.h" +#include "../../libsigrok-internal.h" #include "dsl.h" #include "command.h" @@ -287,7 +287,9 @@ static GSList *scan(GSList *options) /* Find all DSLogic compatible devices and upload firmware to them. */ devices = NULL; - libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist); + int usbnum = libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist); + int stdnum = 0; + for (i = 0; devlist[i]; i++) { if (conn) { usb = NULL; @@ -314,6 +316,8 @@ static GSList *scan(GSList *options) (usb_speed != LIBUSB_SPEED_SUPER)) continue; + stdnum++; + prof = NULL; for (j = 0; supported_DSLogic[j].vid; j++) { if (des.idVendor == supported_DSLogic[j].vid && diff --git a/libsigrok4DSL/hardware/common/ezusb.c b/libsigrok4DSL/hardware/common/ezusb.c index d05d2a79..dce61729 100755 --- a/libsigrok4DSL/hardware/common/ezusb.c +++ b/libsigrok4DSL/hardware/common/ezusb.c @@ -20,8 +20,8 @@ /* * Helper functions for the Cypress EZ-USB / FX2 series chips. */ -#include "libsigrok.h" -#include "libsigrok-internal.h" +#include "../../libsigrok.h" +#include "../../libsigrok-internal.h" //#include #include #include diff --git a/libsigrok4DSL/hardware/common/usb.c b/libsigrok4DSL/hardware/common/usb.c index 09c287ea..5e11c710 100755 --- a/libsigrok4DSL/hardware/common/usb.c +++ b/libsigrok4DSL/hardware/common/usb.c @@ -17,8 +17,8 @@ * along with this program. If not, see . */ -#include "libsigrok.h" -#include "libsigrok-internal.h" +#include "../../libsigrok.h" +#include "../../libsigrok-internal.h" #include #include //#include diff --git a/libsigrok4DSL/hardware/demo/demo.h b/libsigrok4DSL/hardware/demo/demo.h index 08a6f421..e347401f 100755 --- a/libsigrok4DSL/hardware/demo/demo.h +++ b/libsigrok4DSL/hardware/demo/demo.h @@ -22,8 +22,8 @@ #define LIBDSL_HARDWARE_DEMO_H #include -#include "libsigrok.h" -#include "libsigrok-internal.h" +#include "../../libsigrok.h" +#include "../../libsigrok-internal.h" #include #include @@ -168,8 +168,9 @@ static const struct DEMO_profile supported_Demo[] = { (1 << DEMO_LOGIC100x16) | (1 << DEMO_ANALOG10x2) | (1 << DEMO_DSO200x2), - SR_Mn(100), - SR_Kn(20), + //SR_Mn(100), + SR_Gn(16), + SR_Kn(20), 0, vdivs10to2000, 0, diff --git a/libsigrok4DSL/hwdriver.c b/libsigrok4DSL/hwdriver.c index 6af67d91..5be41d3d 100755 --- a/libsigrok4DSL/hwdriver.c +++ b/libsigrok4DSL/hwdriver.c @@ -27,6 +27,8 @@ #include #include "config.h" /* Needed for HAVE_LIBUSB_1_0 and others. */ +#include "hardware/DSL/dsl.h" + /* Message logging helpers with subsystem-specific prefix string. */ #define LOG_PREFIX "hwdriver: " #define sr_log(l, s, args...) sr_log(l, LOG_PREFIX s, ## args) @@ -475,3 +477,79 @@ SR_PRIV int sr_source_add(int fd, int events, int timeout, } /** @} */ + +/* +test usb device api +*/ +SR_API void sr_test_usb_api() +{ + libusb_context *ctx; + struct libusb_device_descriptor des; + int usb_speed; + int ret; + int i; + int num_devs; + libusb_device **devlist; + int stdnum = 0; + int j; + int bfind = 0; + int dlsnum = 0; + struct libusb_device_handle *devhandle; + + printf("\n"); + + ret = libusb_init(&ctx); + if (ret) { + printf("unable to initialize libusb: %i\n", ret); + return; + } + + num_devs = libusb_get_device_list(ctx, &devlist); + printf("usb dev num:%d\n", num_devs); + + for (i=0; i. */ -#include "libsigrok.h" -#include "libsigrok-internal.h" +#include "../libsigrok.h" +#include "../libsigrok-internal.h" #include #include #include diff --git a/libsigrok4DSL/input/in_vcd.c b/libsigrok4DSL/input/in_vcd.c index 41ff6c0b..a19146a5 100755 --- a/libsigrok4DSL/input/in_vcd.c +++ b/libsigrok4DSL/input/in_vcd.c @@ -57,8 +57,8 @@ /* */ -#include "libsigrok.h" -#include "libsigrok-internal.h" +#include "../libsigrok.h" +#include "../libsigrok-internal.h" #include #include #include diff --git a/libsigrok4DSL/input/in_wav.c b/libsigrok4DSL/input/in_wav.c index 33db01d9..a576aa8a 100755 --- a/libsigrok4DSL/input/in_wav.c +++ b/libsigrok4DSL/input/in_wav.c @@ -17,8 +17,8 @@ * along with this program. If not, see . */ -#include "libsigrok.h" -#include "libsigrok-internal.h" +#include "../libsigrok.h" +#include "../libsigrok-internal.h" #include #include #include diff --git a/libsigrok4DSL/input/input.c b/libsigrok4DSL/input/input.c index 68ae49e4..bcfb6576 100755 --- a/libsigrok4DSL/input/input.c +++ b/libsigrok4DSL/input/input.c @@ -17,8 +17,8 @@ * along with this program. If not, see . */ -#include "libsigrok.h" -#include "libsigrok-internal.h" +#include "../libsigrok.h" +#include "../libsigrok-internal.h" /** * @file diff --git a/libsigrok4DSL/libsigrok-internal.h b/libsigrok4DSL/libsigrok-internal.h index de86db20..c310a370 100755 --- a/libsigrok4DSL/libsigrok-internal.h +++ b/libsigrok4DSL/libsigrok-internal.h @@ -27,6 +27,9 @@ #include #endif +// firmware binary file directory, endswith letter '/' +extern char DS_RES_PATH[500]; + /** * @file * @@ -119,6 +122,9 @@ SR_PRIV int sr_session_send(const struct sr_dev_inst *sdi, const struct sr_datafeed_packet *packet); SR_PRIV int sr_session_stop_sync(void); +SR_PRIV int usb_hotplug_callback(struct libusb_context *ctx, struct libusb_device *dev, + libusb_hotplug_event event, void *user_data); + /*--- std.c -----------------------------------------------------------------*/ typedef int (*dev_close_t)(struct sr_dev_inst *sdi); diff --git a/libsigrok4DSL/libsigrok.h b/libsigrok4DSL/libsigrok.h index 1409514d..9ca4936b 100755 --- a/libsigrok4DSL/libsigrok.h +++ b/libsigrok4DSL/libsigrok.h @@ -134,8 +134,6 @@ enum { #define MAX_TIMEBASE SR_SEC(10) #define MIN_TIMEBASE SR_NS(10) -extern char DS_RES_PATH[256]; - /** libsigrok loglevels. */ enum { SR_LOG_NONE = 0, /**< Output no messages at all. */ @@ -176,6 +174,7 @@ enum { #define SR_PRIV #endif + /** Data types used by sr_config_info(). */ enum { SR_T_UINT64 = 10000, diff --git a/libsigrok4DSL/output/csv.c b/libsigrok4DSL/output/csv.c index 47a85dd6..4aa398a5 100755 --- a/libsigrok4DSL/output/csv.c +++ b/libsigrok4DSL/output/csv.c @@ -18,14 +18,15 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#include "libsigrok.h" -#include "libsigrok-internal.h" +#include "../libsigrok.h" +#include "../libsigrok-internal.h" #include #include #include -#include "config.h" /* Needed for PACKAGE_STRING and others. */ +#include "../config.h" /* Needed for PACKAGE_STRING and others. */ #define LOG_PREFIX "output/csv" + struct context { unsigned int num_enabled_channels; @@ -234,10 +235,16 @@ static int receive(const struct sr_output *o, const struct sr_datafeed_packet *p *out = g_string_sized_new(512); } + int bflag = sr_get_export_original_flag(); + for (i = 0; i <= logic->length - logic->unitsize; i += logic->unitsize) { ctx->index++; - if (ctx->index > 1 && (*(uint64_t *)(logic->data + i) & ctx->mask) == ctx->pre_data) - continue; + + if (bflag == 0){ + if (ctx->index > 1 && (*(uint64_t *)(logic->data + i) & ctx->mask) == ctx->pre_data) + continue; + } + g_string_append_printf(*out, "%0.10g", (ctx->index-1)*1.0/ctx->samplerate); for (j = 0; j < ctx->num_enabled_channels; j++) { //idx = ctx->channel_index[j]; @@ -331,3 +338,4 @@ SR_PRIV struct sr_output_module output_csv = { .receive = receive, .cleanup = cleanup, }; + diff --git a/libsigrok4DSL/output/gnuplot.c b/libsigrok4DSL/output/gnuplot.c index 92b01324..e39c1d4c 100755 --- a/libsigrok4DSL/output/gnuplot.c +++ b/libsigrok4DSL/output/gnuplot.c @@ -18,14 +18,14 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#include "libsigrok.h" -#include "libsigrok-internal.h" +#include "../libsigrok.h" +#include "../libsigrok-internal.h" #include #include #include #include #include -#include "config.h" /* Needed for PACKAGE_STRING and others. */ +#include "../config.h" /* Needed for PACKAGE_STRING and others. */ #define LOG_PREFIX "output/gnuplot" diff --git a/libsigrok4DSL/output/output.c b/libsigrok4DSL/output/output.c index 639bd24b..68292a86 100755 --- a/libsigrok4DSL/output/output.c +++ b/libsigrok4DSL/output/output.c @@ -17,8 +17,8 @@ * along with this program. If not, see . */ -#include "libsigrok.h" -#include "libsigrok-internal.h" +#include "../libsigrok.h" +#include "../libsigrok-internal.h" #include /** @cond PRIVATE */ diff --git a/libsigrok4DSL/output/srzip.c b/libsigrok4DSL/output/srzip.c index 5f19f5ab..f723ce69 100755 --- a/libsigrok4DSL/output/srzip.c +++ b/libsigrok4DSL/output/srzip.c @@ -17,8 +17,8 @@ * along with this program. If not, see . */ -#include "libsigrok.h" -#include "libsigrok-internal.h" +#include "../libsigrok.h" +#include "../libsigrok-internal.h" #include #include #include diff --git a/libsigrok4DSL/output/vcd.c b/libsigrok4DSL/output/vcd.c index ce923350..37a5a9af 100755 --- a/libsigrok4DSL/output/vcd.c +++ b/libsigrok4DSL/output/vcd.c @@ -19,12 +19,12 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#include "libsigrok.h" -#include "libsigrok-internal.h" +#include "../libsigrok.h" +#include "../libsigrok-internal.h" #include #include #include -#include "config.h" /* Needed for PACKAGE and others. */ +#include "../config.h" /* Needed for PACKAGE and others. */ #define LOG_PREFIX "output/vcd" diff --git a/libsigrok4DSL/proto.h b/libsigrok4DSL/proto.h index aeac6b81..31937370 100755 --- a/libsigrok4DSL/proto.h +++ b/libsigrok4DSL/proto.h @@ -82,10 +82,16 @@ SR_API int sr_status_get(const struct sr_dev_inst *sdi, struct sr_status *status SR_API struct sr_config *sr_config_new(int key, GVariant *data); SR_API void sr_config_free(struct sr_config *src); -/*--- session.c -------------------------------------------------------------*/ +SR_API void sr_test_usb_api(); +/*--------------------session.c----------------*/ typedef void (*sr_datafeed_callback_t)(const struct sr_dev_inst *sdi, const struct sr_datafeed_packet *packet, void *cb_data); + +SR_API void sr_set_export_original_data(int flag); +SR_API int sr_get_export_original_flag(); +SR_API void sr_set_firmware_resource_dir(const char *dir); + /* Session setup */ SR_API int sr_session_load(const char *filename); @@ -117,6 +123,9 @@ SR_API int sr_session_source_remove(int fd); SR_API int sr_session_source_remove_pollfd(GPollFD *pollfd); SR_API int sr_session_source_remove_channel(GIOChannel *channel); +//0:ok, 1:error +SR_API int sr_check_session_start_before(); + /*--- input/input.c ---------------------------------------------------------*/ SR_API struct sr_input_format **sr_input_list(void); @@ -179,4 +188,6 @@ SR_PRIV uint16_t ds_trigger_get_edge0(uint16_t stage, uint16_t msc, uint16_t lsc SR_PRIV uint16_t ds_trigger_get_mask1(uint16_t stage, uint16_t msc, uint16_t lsc, gboolean qutr_mode, gboolean half_mode); SR_PRIV uint16_t ds_trigger_get_value1(uint16_t stage, uint16_t msc, uint16_t lsc, gboolean qutr_mode, gboolean half_mode); SR_PRIV uint16_t ds_trigger_get_edge1(uint16_t stage, uint16_t msc, uint16_t lsc, gboolean qutr_mode, gboolean half_mode); + + #endif diff --git a/libsigrok4DSL/session.c b/libsigrok4DSL/session.c index f3f822f1..24786c07 100755 --- a/libsigrok4DSL/session.c +++ b/libsigrok4DSL/session.c @@ -34,6 +34,10 @@ #define sr_warn(s, args...) sr_warn(LOG_PREFIX s, ## args) #define sr_err(s, args...) sr_err(LOG_PREFIX s, ## args) +char DS_RES_PATH[500] = {0}; + +int bExportOriginalData = 0; //able export all data + /** * @file * @@ -379,6 +383,17 @@ SR_API int sr_session_start(void) return ret; } +/* +* check session if be created +*/ +int sr_check_session_start_before(){ + + if (!session || !session->devs) { + return 1; + } + return 0; +} + /** * Run the session. * @@ -416,8 +431,9 @@ SR_API int sr_session_run(void) } } else { /* Real sources, use g_poll() main loop. */ - while (session->num_sources) - sr_session_iteration(TRUE); + while (session->num_sources){ + sr_session_iteration(TRUE); + } } g_mutex_lock(&session->stop_mutex); @@ -484,7 +500,7 @@ SR_API int sr_session_stop(void) g_mutex_lock(&session->stop_mutex); if (session->running) - session->abort_session = TRUE; + session->abort_session = TRUE; g_mutex_unlock(&session->stop_mutex); return SR_OK; @@ -813,4 +829,27 @@ SR_API int sr_session_source_remove_channel(GIOChannel *channel) return _sr_session_source_remove((gintptr)channel); } +SR_API void sr_set_export_original_data(int flag) +{ + bExportOriginalData = flag; +} + +SR_API int sr_get_export_original_flag() +{ + return bExportOriginalData; +} + +void sr_set_firmware_resource_dir(const char *dir) +{ + if (dir){ + strcpy(DS_RES_PATH, dir); + + int len = strlen(DS_RES_PATH); + if (DS_RES_PATH[len-1] != '/'){ + DS_RES_PATH[len] = '/'; + DS_RES_PATH[len + 1] = 0; + } + } +} + /** @} */ diff --git a/libsigrok4DSL/session_file.c b/libsigrok4DSL/session_file.c index 4ae027db..ec76d4a5 100755 --- a/libsigrok4DSL/session_file.c +++ b/libsigrok4DSL/session_file.c @@ -621,6 +621,7 @@ SR_API int sr_session_append(const char *filename, const unsigned char *buf, goto err; } if (zip_file_add(archive, chunk_name, logicsrc, ZIP_FL_OVERWRITE) == -1) { + // if (zip_add(archive, chunk_name, logicsrc) == -1) { goto err; } if ((ret = zip_close(archive)) == -1) { diff --git a/libsigrok4DSL/version.h b/libsigrok4DSL/version.h new file mode 100644 index 00000000..8597d4f8 --- /dev/null +++ b/libsigrok4DSL/version.h @@ -0,0 +1,69 @@ +/* + * This file is part of the libsigrok project. + * + * Copyright (C) 2010-2012 Bert Vermeulen + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef LIBSIGROK_VERSION_H +#define LIBSIGROK_VERSION_H + +/** + * @file + * + * Version number definitions and macros. + */ + +/** + * @ingroup grp_versions + * + * @{ + */ + +/* + * Package version macros (can be used for conditional compilation). + */ + +/** The libsigrok package 'major' version number. */ +#define SR_PACKAGE_VERSION_MAJOR 0 + +/** The libsigrok package 'minor' version number. */ +#define SR_PACKAGE_VERSION_MINOR 2 + +/** The libsigrok package 'micro' version number. */ +#define SR_PACKAGE_VERSION_MICRO 0 + +/** The libsigrok package version ("major.minor.micro") as string. */ +#define SR_PACKAGE_VERSION_STRING "0.2.0" + +/* + * Library/libtool version macros (can be used for conditional compilation). + */ + +/** The libsigrok libtool 'current' version number. */ +#define SR_LIB_VERSION_CURRENT 1 + +/** The libsigrok libtool 'revision' version number. */ +#define SR_LIB_VERSION_REVISION 2 + +/** The libsigrok libtool 'age' version number. */ +#define SR_LIB_VERSION_AGE 0 + +/** The libsigrok libtool version ("current:revision:age") as string. */ +#define SR_LIB_VERSION_STRING "1:2:0" + +/** @} */ + +#endif diff --git a/libsigrokdecode4DSL/config.h b/libsigrokdecode4DSL/config.h new file mode 100644 index 00000000..1d480390 --- /dev/null +++ b/libsigrokdecode4DSL/config.h @@ -0,0 +1,114 @@ +/* config.h. Generated from config.h.in by configure. */ +/* config.h.in. Generated from configure.ac by autoheader. */ + +/* Define if building universal (internal helper macro) */ +/* #undef AC_APPLE_UNIVERSAL_BUILD */ + +/* The canonical host libsigrokdecode will run on. */ +#define CONF_HOST "x86_64-pc-linux-gnu" + +/* Define to 1 if you have the header file. */ +#define HAVE_DLFCN_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_MEMORY_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRINGS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UNISTD_H 1 + +/* Define to the sub-directory where libtool stores uninstalled libraries. */ +#define LT_OBJDIR ".libs/" + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "support@dreamsourcelab.com" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "libsigrokdecode4DSL" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "libsigrokdecode4DSL 0.6.0" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "libsigrokdecode4DSL" + +/* Define to the home page for this package. */ +#define PACKAGE_URL "http://www.dreamsourcelab.com" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "0.6.0" + +/* Binary age of libsigrokdecode4DSL. */ +#define SRD_LIB_VERSION_AGE 0 + +/* Binary version of libsigrokdecode4DSL. */ +#define SRD_LIB_VERSION_CURRENT 4 + +/* Binary revision of libsigrokdecode4DSL. */ +#define SRD_LIB_VERSION_REVISION 0 + +/* Binary version triple of libsigrokdecode4DSL. */ +#define SRD_LIB_VERSION_STRING "4:0:0" + +/* Major version number of libsigrokdecode4DSL. */ +#define SRD_PACKAGE_VERSION_MAJOR 0 + +/* Micro version number of libsigrokdecode4DSL. */ +#define SRD_PACKAGE_VERSION_MICRO 0 + +/* Minor version number of libsigrokdecode4DSL. */ +#define SRD_PACKAGE_VERSION_MINOR 6 + +/* Version of libsigrokdecode4DSL. */ +#define SRD_PACKAGE_VERSION_STRING "0.6.0-git-c708a00" + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most + significant byte first (like Motorola and SPARC, unlike Intel). */ +#if defined AC_APPLE_UNIVERSAL_BUILD +# if defined __BIG_ENDIAN__ +# define WORDS_BIGENDIAN 1 +# endif +#else +# ifndef WORDS_BIGENDIAN +/* # undef WORDS_BIGENDIAN */ +# endif +#endif + +/* Enable large inode numbers on Mac OS X 10.5. */ +#ifndef _DARWIN_USE_64_BIT_INODE +# define _DARWIN_USE_64_BIT_INODE 1 +#endif + +/* Number of bits in a file offset, on hosts where this is settable. */ +/* #undef _FILE_OFFSET_BITS */ + +/* Define for large files, on AIX-style hosts. */ +/* #undef _LARGE_FILES */ + +/* The targeted POSIX standard. */ +#ifndef _POSIX_C_SOURCE +# define _POSIX_C_SOURCE 200112L +#endif diff --git a/libsigrokdecode4DSL/decoder.c b/libsigrokdecode4DSL/decoder.c index 4906b5d9..809cb25b 100755 --- a/libsigrokdecode4DSL/decoder.c +++ b/libsigrokdecode4DSL/decoder.c @@ -40,7 +40,10 @@ /** @cond PRIVATE */ -/* The list of loaded protocol decoders. */ +/* + The list of loaded protocol decoders. + Is srd_decoder* type +*/ static GSList *pd_list = NULL; /* srd.c */ @@ -719,6 +722,7 @@ SRD_API int srd_decoder_load(const char *module_name) d = g_malloc0(sizeof(struct srd_decoder)); fail_txt = NULL; + //Load module from python script file,module_name is a sub directory d->py_mod = py_import_by_name(module_name); if (!d->py_mod) { fail_txt = "import by name failed"; @@ -731,13 +735,19 @@ SRD_API int srd_decoder_load(const char *module_name) goto err_out; } - /* Get the 'Decoder' class as Python object. */ + /* + Get the 'Decoder' class as Python object. + Here, Decoder is python class type + */ d->py_dec = PyObject_GetAttrString(d->py_mod, "Decoder"); if (!d->py_dec) { fail_txt = "no 'Decoder' attribute in imported module"; goto except_out; } + /* + Here, Decoder is c class type + */ py_basedec = PyObject_GetAttrString(mod_sigrokdecode, "Decoder"); if (!py_basedec) { fail_txt = "no 'Decoder' attribute in sigrokdecode(3)"; diff --git a/libsigrokdecode4DSL/decoders/0-i2c/__init__.py b/libsigrokdecode4DSL/decoders/0-i2c/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/0-i2c/pd.py b/libsigrokdecode4DSL/decoders/0-i2c/pd.py old mode 100755 new mode 100644 index 8cb47ee0..dad9922d --- a/libsigrokdecode4DSL/decoders/0-i2c/pd.py +++ b/libsigrokdecode4DSL/decoders/0-i2c/pd.py @@ -188,8 +188,7 @@ class Decoder(srd.Decoder): self.putx([proto[cmd][0], w]) self.ss, self.es = self.ss_byte, self.samplenum - self.putx([proto[cmd][0], ['%s: %02X' % (proto[cmd][1], d), - '%s: %02X' % (proto[cmd][2], d), '%02X' % d]]) + self.putx([proto[cmd][0], ['%s: {$}' % proto[cmd][1], '%s: {$}' % proto[cmd][2], '{$}', d]]) # Done with this packet. self.bitcount = self.databyte = 0 diff --git a/libsigrokdecode4DSL/decoders/0-spi/__init__.py b/libsigrokdecode4DSL/decoders/0-spi/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/0-spi/pd.py b/libsigrokdecode4DSL/decoders/0-spi/pd.py old mode 100755 new mode 100644 index 4708a98d..2d397f02 --- a/libsigrokdecode4DSL/decoders/0-spi/pd.py +++ b/libsigrokdecode4DSL/decoders/0-spi/pd.py @@ -151,9 +151,9 @@ class Decoder(srd.Decoder): # Dataword annotations. if self.have_miso: - self.put(ss, es, self.out_ann, [0, ['%02X' % self.misodata]]) + self.put(ss, es, self.out_ann, [0, [self.misodata]]) if self.have_mosi: - self.put(ss, es, self.out_ann, [1, ['%02X' % self.mosidata]]) + self.put(ss, es, self.out_ann, [1, [self.mosidata]]) def reset_decoder_state(self): self.misodata = 0 if self.have_miso else None diff --git a/libsigrokdecode4DSL/decoders/0-uart/__init__.py b/libsigrokdecode4DSL/decoders/0-uart/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/0-uart/pd.py b/libsigrokdecode4DSL/decoders/0-uart/pd.py old mode 100755 new mode 100644 index fdb7c28b..9edf2254 --- a/libsigrokdecode4DSL/decoders/0-uart/pd.py +++ b/libsigrokdecode4DSL/decoders/0-uart/pd.py @@ -218,11 +218,11 @@ class Decoder(srd.Decoder): if self.options['bit_order'] == 'msb-first': bits.reverse() self.datavalue = bitpack(bits) - - b = self.datavalue - formatted = self.format_value(b) - if formatted is not None: - self.putx([0, [formatted]]) + self.putx([0, [self.datavalue]]) + #b = self.datavalue + #formatted = self.format_value(b) + #if formatted is not None: + # self.putx([0, [formatted]]) self.databits = [] diff --git a/libsigrokdecode4DSL/decoders/1-i2c/__init__.py b/libsigrokdecode4DSL/decoders/1-i2c/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/1-i2c/pd.py b/libsigrokdecode4DSL/decoders/1-i2c/pd.py old mode 100755 new mode 100644 index fb6af6bb..a163eba4 --- a/libsigrokdecode4DSL/decoders/1-i2c/pd.py +++ b/libsigrokdecode4DSL/decoders/1-i2c/pd.py @@ -213,11 +213,10 @@ class Decoder(srd.Decoder): if cmd.startswith('ADDRESS'): self.ss, self.es = self.samplenum, self.samplenum + self.bitwidth w = ['Write', 'Wr', 'W'] if self.wr else ['Read', 'Rd', 'R'] - self.putx([proto[cmd][0], w]) + self.putx([0, w]) self.ss, self.es = self.ss_byte, self.samplenum - self.putx([proto[cmd][0], ['%s: %02X' % (proto[cmd][1], d), - '%s: %02X' % (proto[cmd][2], d), '%02X' % d]]) + self.putx([proto[cmd][0], ['%s: {$}' % proto[cmd][1], '%s: {$}' % proto[cmd][2], '{$}', d]]) # Done with this packet. self.bitcount = self.databyte = 0 diff --git a/libsigrokdecode4DSL/decoders/1-spi/__init__.py b/libsigrokdecode4DSL/decoders/1-spi/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/1-spi/pd.py b/libsigrokdecode4DSL/decoders/1-spi/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/1-uart/__init__.py b/libsigrokdecode4DSL/decoders/1-uart/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/1-uart/pd.py b/libsigrokdecode4DSL/decoders/1-uart/pd.py old mode 100755 new mode 100644 index 1984f4e1..f3d6181c --- a/libsigrokdecode4DSL/decoders/1-uart/pd.py +++ b/libsigrokdecode4DSL/decoders/1-uart/pd.py @@ -253,10 +253,12 @@ class Decoder(srd.Decoder): self.datavalue = bitpack(bits) self.putpx(['DATA', 0, (self.datavalue, self.databits)]) + self.putx([0, [self.datavalue]]) + b = self.datavalue - formatted = self.format_value(b) - if formatted is not None: - self.putx([0, [formatted]]) + #formatted = self.format_value(b) + #if formatted is not None: + # self.putx([0, [formatted]]) bdata = b.to_bytes(self.bw, byteorder='big') self.putbin([0, bdata]) diff --git a/libsigrokdecode4DSL/decoders/ac97/__init__.py b/libsigrokdecode4DSL/decoders/ac97/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ac97/pd.py b/libsigrokdecode4DSL/decoders/ac97/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ade77xx/__init__.py b/libsigrokdecode4DSL/decoders/ade77xx/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ade77xx/lists.py b/libsigrokdecode4DSL/decoders/ade77xx/lists.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ade77xx/pd.py b/libsigrokdecode4DSL/decoders/ade77xx/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/adf435x/__init__.py b/libsigrokdecode4DSL/decoders/adf435x/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/adf435x/pd.py b/libsigrokdecode4DSL/decoders/adf435x/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/adns5020/__init__.py b/libsigrokdecode4DSL/decoders/adns5020/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/adns5020/pd.py b/libsigrokdecode4DSL/decoders/adns5020/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/am230x/__init__.py b/libsigrokdecode4DSL/decoders/am230x/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/am230x/pd.py b/libsigrokdecode4DSL/decoders/am230x/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/arm_etmv3/__init__.py b/libsigrokdecode4DSL/decoders/arm_etmv3/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/arm_etmv3/pd.py b/libsigrokdecode4DSL/decoders/arm_etmv3/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/arm_itm/__init__.py b/libsigrokdecode4DSL/decoders/arm_itm/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/arm_itm/pd.py b/libsigrokdecode4DSL/decoders/arm_itm/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/arm_tpiu/__init__.py b/libsigrokdecode4DSL/decoders/arm_tpiu/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/arm_tpiu/pd.py b/libsigrokdecode4DSL/decoders/arm_tpiu/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/atsha204a/__init__.py b/libsigrokdecode4DSL/decoders/atsha204a/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/atsha204a/pd.py b/libsigrokdecode4DSL/decoders/atsha204a/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/aud/__init__.py b/libsigrokdecode4DSL/decoders/aud/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/aud/pd.py b/libsigrokdecode4DSL/decoders/aud/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/avr_isp/__init__.py b/libsigrokdecode4DSL/decoders/avr_isp/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/avr_isp/parts.py b/libsigrokdecode4DSL/decoders/avr_isp/parts.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/avr_isp/pd.py b/libsigrokdecode4DSL/decoders/avr_isp/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/avr_pdi/__init__.py b/libsigrokdecode4DSL/decoders/avr_pdi/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/avr_pdi/pd.py b/libsigrokdecode4DSL/decoders/avr_pdi/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/can/__init__.py b/libsigrokdecode4DSL/decoders/can/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/can/pd.py b/libsigrokdecode4DSL/decoders/can/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/cec/__init__.py b/libsigrokdecode4DSL/decoders/cec/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/cec/pd.py b/libsigrokdecode4DSL/decoders/cec/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/cec/protocoldata.py b/libsigrokdecode4DSL/decoders/cec/protocoldata.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/cfp/__init__.py b/libsigrokdecode4DSL/decoders/cfp/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/cfp/pd.py b/libsigrokdecode4DSL/decoders/cfp/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/common/__init__.py b/libsigrokdecode4DSL/decoders/common/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/common/plugtrx/__init__.py b/libsigrokdecode4DSL/decoders/common/plugtrx/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/common/plugtrx/mod.py b/libsigrokdecode4DSL/decoders/common/plugtrx/mod.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/common/sdcard/__init__.py b/libsigrokdecode4DSL/decoders/common/sdcard/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/common/sdcard/mod.py b/libsigrokdecode4DSL/decoders/common/sdcard/mod.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/common/srdhelper/__init__.py b/libsigrokdecode4DSL/decoders/common/srdhelper/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/common/srdhelper/mod.py b/libsigrokdecode4DSL/decoders/common/srdhelper/mod.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/counter/__init__.py b/libsigrokdecode4DSL/decoders/counter/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/counter/pd.py b/libsigrokdecode4DSL/decoders/counter/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/dali/__init__.py b/libsigrokdecode4DSL/decoders/dali/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/dali/lists.py b/libsigrokdecode4DSL/decoders/dali/lists.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/dali/pd.py b/libsigrokdecode4DSL/decoders/dali/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/dcf77/__init__.py b/libsigrokdecode4DSL/decoders/dcf77/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/dcf77/pd.py b/libsigrokdecode4DSL/decoders/dcf77/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/dmx512/__init__.py b/libsigrokdecode4DSL/decoders/dmx512/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/dmx512/pd.py b/libsigrokdecode4DSL/decoders/dmx512/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ds1307/__init__.py b/libsigrokdecode4DSL/decoders/ds1307/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ds1307/pd.py b/libsigrokdecode4DSL/decoders/ds1307/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ds243x/__init__.py b/libsigrokdecode4DSL/decoders/ds243x/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ds243x/pd.py b/libsigrokdecode4DSL/decoders/ds243x/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ds28ea00/__init__.py b/libsigrokdecode4DSL/decoders/ds28ea00/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ds28ea00/pd.py b/libsigrokdecode4DSL/decoders/ds28ea00/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/dsi/__init__.py b/libsigrokdecode4DSL/decoders/dsi/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/dsi/pd.py b/libsigrokdecode4DSL/decoders/dsi/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/edid/__init__.py b/libsigrokdecode4DSL/decoders/edid/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/edid/config b/libsigrokdecode4DSL/decoders/edid/config old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/edid/pd.py b/libsigrokdecode4DSL/decoders/edid/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/edid/pnpids.txt b/libsigrokdecode4DSL/decoders/edid/pnpids.txt old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/eeprom24xx/__init__.py b/libsigrokdecode4DSL/decoders/eeprom24xx/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/eeprom24xx/lists.py b/libsigrokdecode4DSL/decoders/eeprom24xx/lists.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/eeprom24xx/pd.py b/libsigrokdecode4DSL/decoders/eeprom24xx/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/eeprom93xx/__init__.py b/libsigrokdecode4DSL/decoders/eeprom93xx/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/eeprom93xx/pd.py b/libsigrokdecode4DSL/decoders/eeprom93xx/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/em4100/__init__.py b/libsigrokdecode4DSL/decoders/em4100/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/em4100/pd.py b/libsigrokdecode4DSL/decoders/em4100/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/em4305/__init__.py b/libsigrokdecode4DSL/decoders/em4305/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/em4305/pd.py b/libsigrokdecode4DSL/decoders/em4305/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/fsi/__init__.py b/libsigrokdecode4DSL/decoders/fsi/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/fsi/pd.py b/libsigrokdecode4DSL/decoders/fsi/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/gpib/__init__.py b/libsigrokdecode4DSL/decoders/gpib/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/gpib/pd.py b/libsigrokdecode4DSL/decoders/gpib/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/graycode/__init__.py b/libsigrokdecode4DSL/decoders/graycode/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/graycode/pd.py b/libsigrokdecode4DSL/decoders/graycode/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/guess_bitrate/__init__.py b/libsigrokdecode4DSL/decoders/guess_bitrate/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/guess_bitrate/pd.py b/libsigrokdecode4DSL/decoders/guess_bitrate/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/i2cdemux/__init__.py b/libsigrokdecode4DSL/decoders/i2cdemux/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/i2cdemux/pd.py b/libsigrokdecode4DSL/decoders/i2cdemux/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/i2cfilter/__init__.py b/libsigrokdecode4DSL/decoders/i2cfilter/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/i2cfilter/pd.py b/libsigrokdecode4DSL/decoders/i2cfilter/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/i2s/__init__.py b/libsigrokdecode4DSL/decoders/i2s/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/i2s/pd.py b/libsigrokdecode4DSL/decoders/i2s/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/iec/__init__.py b/libsigrokdecode4DSL/decoders/iec/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/iec/pd.py b/libsigrokdecode4DSL/decoders/iec/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ir_nec/__init__.py b/libsigrokdecode4DSL/decoders/ir_nec/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ir_nec/lists.py b/libsigrokdecode4DSL/decoders/ir_nec/lists.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ir_nec/pd.py b/libsigrokdecode4DSL/decoders/ir_nec/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ir_rc5/__init__.py b/libsigrokdecode4DSL/decoders/ir_rc5/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ir_rc5/lists.py b/libsigrokdecode4DSL/decoders/ir_rc5/lists.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ir_rc5/pd.py b/libsigrokdecode4DSL/decoders/ir_rc5/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/jitter/__init__.py b/libsigrokdecode4DSL/decoders/jitter/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/jitter/pd.py b/libsigrokdecode4DSL/decoders/jitter/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/jtag/__init__.py b/libsigrokdecode4DSL/decoders/jtag/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/jtag/pd.py b/libsigrokdecode4DSL/decoders/jtag/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/jtag_ejtag/__init__.py b/libsigrokdecode4DSL/decoders/jtag_ejtag/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/jtag_ejtag/pd.py b/libsigrokdecode4DSL/decoders/jtag_ejtag/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/jtag_stm32/__init__.py b/libsigrokdecode4DSL/decoders/jtag_stm32/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/jtag_stm32/pd.py b/libsigrokdecode4DSL/decoders/jtag_stm32/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/lin/__init__.py b/libsigrokdecode4DSL/decoders/lin/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/lin/pd.py b/libsigrokdecode4DSL/decoders/lin/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/lm75/__init__.py b/libsigrokdecode4DSL/decoders/lm75/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/lm75/pd.py b/libsigrokdecode4DSL/decoders/lm75/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/lpc/__init__.py b/libsigrokdecode4DSL/decoders/lpc/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/lpc/pd.py b/libsigrokdecode4DSL/decoders/lpc/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/maple_bus/__init__.py b/libsigrokdecode4DSL/decoders/maple_bus/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/maple_bus/pd.py b/libsigrokdecode4DSL/decoders/maple_bus/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/max7219/__init__.py b/libsigrokdecode4DSL/decoders/max7219/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/max7219/pd.py b/libsigrokdecode4DSL/decoders/max7219/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/mcs48/__init__.py b/libsigrokdecode4DSL/decoders/mcs48/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/mcs48/pd.py b/libsigrokdecode4DSL/decoders/mcs48/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/mdio/__init__.py b/libsigrokdecode4DSL/decoders/mdio/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/mdio/pd.py b/libsigrokdecode4DSL/decoders/mdio/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/microwire/__init__.py b/libsigrokdecode4DSL/decoders/microwire/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/microwire/pd.py b/libsigrokdecode4DSL/decoders/microwire/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/midi/__init__.py b/libsigrokdecode4DSL/decoders/midi/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/midi/lists.py b/libsigrokdecode4DSL/decoders/midi/lists.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/midi/pd.py b/libsigrokdecode4DSL/decoders/midi/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/miller/__init__.py b/libsigrokdecode4DSL/decoders/miller/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/miller/pd.py b/libsigrokdecode4DSL/decoders/miller/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/mlx90614/__init__.py b/libsigrokdecode4DSL/decoders/mlx90614/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/mlx90614/pd.py b/libsigrokdecode4DSL/decoders/mlx90614/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/modbus/__init__.py b/libsigrokdecode4DSL/decoders/modbus/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/modbus/pd.py b/libsigrokdecode4DSL/decoders/modbus/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/morse/__init__.py b/libsigrokdecode4DSL/decoders/morse/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/morse/pd.py b/libsigrokdecode4DSL/decoders/morse/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/mrf24j40/__init__.py b/libsigrokdecode4DSL/decoders/mrf24j40/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/mrf24j40/lists.py b/libsigrokdecode4DSL/decoders/mrf24j40/lists.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/mrf24j40/pd.py b/libsigrokdecode4DSL/decoders/mrf24j40/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/mxc6225xu/__init__.py b/libsigrokdecode4DSL/decoders/mxc6225xu/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/mxc6225xu/pd.py b/libsigrokdecode4DSL/decoders/mxc6225xu/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/nrf24l01/__init__.py b/libsigrokdecode4DSL/decoders/nrf24l01/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/nrf24l01/pd.py b/libsigrokdecode4DSL/decoders/nrf24l01/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/nunchuk/__init__.py b/libsigrokdecode4DSL/decoders/nunchuk/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/nunchuk/pd.py b/libsigrokdecode4DSL/decoders/nunchuk/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/onewire_link/__init__.py b/libsigrokdecode4DSL/decoders/onewire_link/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/onewire_link/pd.py b/libsigrokdecode4DSL/decoders/onewire_link/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/onewire_network/__init__.py b/libsigrokdecode4DSL/decoders/onewire_network/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/onewire_network/pd.py b/libsigrokdecode4DSL/decoders/onewire_network/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ook/__init__.py b/libsigrokdecode4DSL/decoders/ook/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ook/pd.py b/libsigrokdecode4DSL/decoders/ook/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ook_oregon/__init__.py b/libsigrokdecode4DSL/decoders/ook_oregon/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ook_oregon/lists.py b/libsigrokdecode4DSL/decoders/ook_oregon/lists.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ook_oregon/pd.py b/libsigrokdecode4DSL/decoders/ook_oregon/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ook_vis/__init__.py b/libsigrokdecode4DSL/decoders/ook_vis/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ook_vis/pd.py b/libsigrokdecode4DSL/decoders/ook_vis/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/pan1321/__init__.py b/libsigrokdecode4DSL/decoders/pan1321/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/pan1321/pd.py b/libsigrokdecode4DSL/decoders/pan1321/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/parallel/__init__.py b/libsigrokdecode4DSL/decoders/parallel/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/parallel/pd.py b/libsigrokdecode4DSL/decoders/parallel/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ps2/__init__.py b/libsigrokdecode4DSL/decoders/ps2/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ps2/pd.py b/libsigrokdecode4DSL/decoders/ps2/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/pwm/__init__.py b/libsigrokdecode4DSL/decoders/pwm/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/pwm/pd.py b/libsigrokdecode4DSL/decoders/pwm/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/qi/__init__.py b/libsigrokdecode4DSL/decoders/qi/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/qi/pd.py b/libsigrokdecode4DSL/decoders/qi/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/rc_encode/__init__.py b/libsigrokdecode4DSL/decoders/rc_encode/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/rc_encode/pd.py b/libsigrokdecode4DSL/decoders/rc_encode/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/rfm12/__init__.py b/libsigrokdecode4DSL/decoders/rfm12/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/rfm12/pd.py b/libsigrokdecode4DSL/decoders/rfm12/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/rgb_led_spi/__init__.py b/libsigrokdecode4DSL/decoders/rgb_led_spi/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/rgb_led_spi/pd.py b/libsigrokdecode4DSL/decoders/rgb_led_spi/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/rgb_led_ws281x/__init__.py b/libsigrokdecode4DSL/decoders/rgb_led_ws281x/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/rgb_led_ws281x/pd.py b/libsigrokdecode4DSL/decoders/rgb_led_ws281x/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/rtc8564/__init__.py b/libsigrokdecode4DSL/decoders/rtc8564/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/rtc8564/pd.py b/libsigrokdecode4DSL/decoders/rtc8564/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/sda2506/__init__.py b/libsigrokdecode4DSL/decoders/sda2506/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/sda2506/pd.py b/libsigrokdecode4DSL/decoders/sda2506/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/sdcard_sd/__init__.py b/libsigrokdecode4DSL/decoders/sdcard_sd/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/sdcard_sd/pd.py b/libsigrokdecode4DSL/decoders/sdcard_sd/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/sdcard_spi/__init__.py b/libsigrokdecode4DSL/decoders/sdcard_spi/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/sdcard_spi/pd.py b/libsigrokdecode4DSL/decoders/sdcard_spi/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/spdif/__init__.py b/libsigrokdecode4DSL/decoders/spdif/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/spdif/pd.py b/libsigrokdecode4DSL/decoders/spdif/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/spiflash/__init__.py b/libsigrokdecode4DSL/decoders/spiflash/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/spiflash/lists.py b/libsigrokdecode4DSL/decoders/spiflash/lists.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/spiflash/pd.py b/libsigrokdecode4DSL/decoders/spiflash/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ssi32/__init__.py b/libsigrokdecode4DSL/decoders/ssi32/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/ssi32/pd.py b/libsigrokdecode4DSL/decoders/ssi32/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/st7735/__init__.py b/libsigrokdecode4DSL/decoders/st7735/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/st7735/pd.py b/libsigrokdecode4DSL/decoders/st7735/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/stepper_motor/__init__.py b/libsigrokdecode4DSL/decoders/stepper_motor/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/stepper_motor/pd.py b/libsigrokdecode4DSL/decoders/stepper_motor/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/swd/__init__.py b/libsigrokdecode4DSL/decoders/swd/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/swd/pd.py b/libsigrokdecode4DSL/decoders/swd/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/swim/__init__.py b/libsigrokdecode4DSL/decoders/swim/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/swim/pd.py b/libsigrokdecode4DSL/decoders/swim/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/t55xx/__init__.py b/libsigrokdecode4DSL/decoders/t55xx/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/t55xx/pd.py b/libsigrokdecode4DSL/decoders/t55xx/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/tca6408a/__init__.py b/libsigrokdecode4DSL/decoders/tca6408a/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/tca6408a/pd.py b/libsigrokdecode4DSL/decoders/tca6408a/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/timing/__init__.py b/libsigrokdecode4DSL/decoders/timing/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/timing/pd.py b/libsigrokdecode4DSL/decoders/timing/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/tlc5620/__init__.py b/libsigrokdecode4DSL/decoders/tlc5620/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/tlc5620/pd.py b/libsigrokdecode4DSL/decoders/tlc5620/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/usb_packet/__init__.py b/libsigrokdecode4DSL/decoders/usb_packet/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/usb_packet/pd.py b/libsigrokdecode4DSL/decoders/usb_packet/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/usb_power_delivery/__init__.py b/libsigrokdecode4DSL/decoders/usb_power_delivery/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/usb_power_delivery/pd.py b/libsigrokdecode4DSL/decoders/usb_power_delivery/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/usb_request/__init__.py b/libsigrokdecode4DSL/decoders/usb_request/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/usb_request/pd.py b/libsigrokdecode4DSL/decoders/usb_request/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/usb_signalling/__init__.py b/libsigrokdecode4DSL/decoders/usb_signalling/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/usb_signalling/pd.py b/libsigrokdecode4DSL/decoders/usb_signalling/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/wiegand/__init__.py b/libsigrokdecode4DSL/decoders/wiegand/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/wiegand/pd.py b/libsigrokdecode4DSL/decoders/wiegand/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/xfp/__init__.py b/libsigrokdecode4DSL/decoders/xfp/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/xfp/pd.py b/libsigrokdecode4DSL/decoders/xfp/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/z80/__init__.py b/libsigrokdecode4DSL/decoders/z80/__init__.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/z80/pd.py b/libsigrokdecode4DSL/decoders/z80/pd.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/decoders/z80/tables.py b/libsigrokdecode4DSL/decoders/z80/tables.py old mode 100755 new mode 100644 diff --git a/libsigrokdecode4DSL/instance.c b/libsigrokdecode4DSL/instance.c index 5d96701f..1b3d5df7 100755 --- a/libsigrokdecode4DSL/instance.c +++ b/libsigrokdecode4DSL/instance.c @@ -379,9 +379,10 @@ SRD_API struct srd_decoder_inst *srd_inst_new(struct srd_session *sess, di->py_pinvalues = NULL; di->dec_num_channels = g_slist_length(di->decoder->channels) + g_slist_length(di->decoder->opt_channels); + if (di->dec_num_channels) { - di->dec_channelmap = - g_malloc(sizeof(int) * di->dec_num_channels); + di->dec_channelmap = g_malloc(sizeof(int) * di->dec_num_channels); + for (i = 0; i < di->dec_num_channels; i++) di->dec_channelmap[i] = i; @@ -913,7 +914,8 @@ static gboolean all_terms_match(struct srd_decoder_inst *di, return TRUE; } -static gboolean find_match(struct srd_decoder_inst *di) +static gboolean +find_match(struct srd_decoder_inst *di) { uint64_t j; GSList *l, *cond; @@ -1059,9 +1061,11 @@ static gpointer di_thread(gpointer data) * "Regular" termination of the decode() method is not expected. */ //Py_IncRef(di->py_inst); + //srd_err("start call decode()"); srd_dbg("%s: Calling decode().", di->inst_id); py_res = PyObject_CallMethod(di->py_inst, "decode", NULL); srd_dbg("%s: decode() terminated.", di->inst_id); + //srd_err("end call decode()"); if (!py_res) di->decoder_state = SRD_ERR; @@ -1210,7 +1214,10 @@ SRD_PRIV int srd_inst_decode(struct srd_decoder_inst *di, abs_start_samplenum, abs_end_samplenum, abs_end_samplenum - abs_start_samplenum, inbuflen, di->inst_id); - /* If this is the first call, start the worker thread. */ + /* + If this is the first call, start the worker thread. + One session may be have more decoder,so more thread will be created + */ if (!di->thread_handle) { srd_dbg("No worker thread for this decoder stack " "exists yet, creating one: %s.", di->inst_id); diff --git a/libsigrokdecode4DSL/libsigrokdecode.h b/libsigrokdecode4DSL/libsigrokdecode.h index 491c3371..a399de18 100755 --- a/libsigrokdecode4DSL/libsigrokdecode.h +++ b/libsigrokdecode4DSL/libsigrokdecode.h @@ -32,7 +32,10 @@ extern "C" { struct srd_session { int session_id; - /* List of decoder instances. */ + /* + List of decoder instances. + srd_decoder_inst* type + */ GSList *di_list; /* List of frontend callbacks to receive decoder output. */ @@ -257,14 +260,16 @@ struct srd_decoder_inst { struct srd_decoder *decoder; struct srd_session *sess; void *py_inst; - void *py_pinvalues; + void *py_pinvalues; /* is a python duple type, like (1,0,255,255)*/ char *inst_id; - GSList *pd_output; + GSList *pd_output; /* srd_pd_output* type */ int dec_num_channels; int *dec_channelmap; GSList *next_di; - /** List of conditions a PD wants to wait for. */ + /** List of conditions a PD wants to wait for. + * Type is srd_term* of GSList* + */ GSList *condition_list; /** Array of booleans denoting which conditions matched. */ @@ -291,7 +296,9 @@ struct srd_decoder_inst { /** Absolute current sample matched conditions. */ gboolean abs_cur_matched; - /** Array of "old" (previous sample) pin values. */ + /** Array of "old" (previous sample) pin values. + * Type of uint8_t + */ GArray *old_pins_array; /** Handle for this PD stack's worker thread. */ @@ -339,8 +346,10 @@ struct srd_proto_data { }; struct srd_proto_data_annotation { int ann_class; - int ann_type; - char **ann_text; + int ann_type; + char str_number_hex[18]; //numerical value hex format string + long long numberic_value; + char **ann_text; //text string lines }; struct srd_proto_data_binary { int bin_class; @@ -361,6 +370,7 @@ struct srd_pd_callback { SRD_API int srd_init(const char *path); SRD_API int srd_exit(void); SRD_API GSList *srd_searchpaths_get(void); +SRD_API void srd_set_python_home(const wchar_t *path); /* session.c */ SRD_API int srd_session_new(struct srd_session **sess); diff --git a/libsigrokdecode4DSL/session.c b/libsigrokdecode4DSL/session.c index e60a9da1..32597486 100755 --- a/libsigrokdecode4DSL/session.c +++ b/libsigrokdecode4DSL/session.c @@ -269,6 +269,7 @@ SRD_API int srd_session_send(struct srd_session *sess, if (!sess) return SRD_ERR_ARG; + //foreach srd_decoder_inst* stack for (d = sess->di_list; d; d = d->next) { if ((ret = srd_inst_decode(d->data, abs_start_samplenum, abs_end_samplenum, inbuf, inbuf_const, inbuflen, error)) != SRD_OK) diff --git a/libsigrokdecode4DSL/srd.c b/libsigrokdecode4DSL/srd.c index 6b2569d2..5a43b98e 100755 --- a/libsigrokdecode4DSL/srd.c +++ b/libsigrokdecode4DSL/srd.c @@ -190,7 +190,7 @@ SRD_API int srd_init(const char *path) size_t i; int ret; const char *env_path; - + if (max_session_id != -1) { srd_err("libsigrokdecode is already initialized."); return SRD_ERR; @@ -202,30 +202,15 @@ SRD_API int srd_init(const char *path) PyImport_AppendInittab("sigrokdecode", PyInit_sigrokdecode); /* Initialize the Python interpreter. */ - Py_InitializeEx(0); + Py_InitializeEx(0); - /* Locations relative to the XDG system data directories. */ - sys_datadirs = g_get_system_data_dirs(); - for (i = g_strv_length((char **)sys_datadirs); i > 0; i--) { - ret = searchpath_add_xdg_dir(sys_datadirs[i-1]); - if (ret != SRD_OK) { - Py_Finalize(); - return ret; - } - } #ifdef DECODERS_DIR /* Hardcoded decoders install location, if defined. */ if ((ret = srd_decoder_searchpath_add(DECODERS_DIR)) != SRD_OK) { Py_Finalize(); return ret; } -#endif - /* Location relative to the XDG user data directory. */ - ret = searchpath_add_xdg_dir(g_get_user_data_dir()); - if (ret != SRD_OK) { - Py_Finalize(); - return ret; - } +#endif /* Path specified by the user. */ if (path) { @@ -234,20 +219,43 @@ SRD_API int srd_init(const char *path) return ret; } } + else{ + /* Locations relative to the XDG system data directories. */ + sys_datadirs = g_get_system_data_dirs(); + for (i = g_strv_length((char **)sys_datadirs); i > 0; i--) + { + ret = searchpath_add_xdg_dir(sys_datadirs[i - 1]); + if (ret != SRD_OK) + { + Py_Finalize(); + return ret; + } + } - /* Environment variable overrides everything, for debugging. */ - if ((env_path = g_getenv("SIGROKDECODE_DIR"))) { - if ((ret = srd_decoder_searchpath_add(env_path)) != SRD_OK) { + /* Location relative to the XDG user data directory. */ + ret = searchpath_add_xdg_dir(g_get_user_data_dir()); + if (ret != SRD_OK) + { Py_Finalize(); return ret; } + + /* Environment variable overrides everything, for debugging. */ + if ((env_path = g_getenv("SIGROKDECODE_DIR"))) + { + if ((ret = srd_decoder_searchpath_add(env_path)) != SRD_OK) + { + Py_Finalize(); + return ret; + } + } } /* Initialize the Python GIL (this also happens to acquire it). */ PyEval_InitThreads(); /* Release the GIL (ignore return value, we don't need it here). */ - (void)PyEval_SaveThread(); + PyEval_SaveThread(); max_session_id = 0; @@ -351,6 +359,7 @@ SRD_PRIV int srd_decoder_searchpath_add(const char *path) PyGILState_Release(gstate); + //append the directory to search list searchpaths = g_slist_prepend(searchpaths, g_strdup(path)); return SRD_OK; @@ -378,4 +387,10 @@ SRD_API GSList *srd_searchpaths_get(void) return paths; } +//set python home directory +SRD_API void srd_set_python_home(const wchar_t *path) +{ + Py_SetPythonHome((wchar_t*)path); +} + /** @} */ diff --git a/libsigrokdecode4DSL/tests/core.c b/libsigrokdecode4DSL/tests/core.c deleted file mode 100755 index f09a6e87..00000000 --- a/libsigrokdecode4DSL/tests/core.c +++ /dev/null @@ -1,104 +0,0 @@ -/* - * This file is part of the libsigrokdecode project. - * - * Copyright (C) 2013 Uwe Hermann - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, see . - */ - -#include -#include /* First, to avoid compiler warning. */ -#include -#include -#include "lib.h" - -/* - * Check various basic init related things. - * - * - Check whether an srd_init() call with path == NULL works. - * If it returns != SRD_OK (or segfaults) this test will fail. - * - * - Check whether a subsequent srd_exit() works. - * If it returns != SRD_OK (or segfaults) this test will fail. - */ -START_TEST(test_init_exit) -{ - int ret; - - ret = srd_init(NULL); - fail_unless(ret == SRD_OK, "srd_init() failed: %d.", ret); - ret = srd_exit(); - fail_unless(ret == SRD_OK, "srd_exit() failed: %d.", ret); -} -END_TEST - -/* - * Check whether nested srd_init()/srd_exit() calls work/fail correctly. - * Two consecutive srd_init() calls without any srd_exit() inbetween are - * not allowed and should fail. However, two consecutive srd_exit() calls - * are currently allowed, the second one will just be a NOP basically. - */ -START_TEST(test_init_exit_2) -{ - int ret; - - ret = srd_init(NULL); - fail_unless(ret == SRD_OK, "srd_init() 1 failed: %d.", ret); - ret = srd_init(NULL); - fail_unless(ret != SRD_OK, "srd_init() 2 didn't fail: %d.", ret); - ret = srd_exit(); - fail_unless(ret == SRD_OK, "srd_exit() 2 failed: %d.", ret); - ret = srd_exit(); - fail_unless(ret == SRD_OK, "srd_exit() 1 failed: %d.", ret); -} -END_TEST - -/* - * Check whether three nested srd_init()/srd_exit() calls work/fail correctly. - */ -START_TEST(test_init_exit_3) -{ - int ret; - - ret = srd_init(NULL); - fail_unless(ret == SRD_OK, "srd_init() 1 failed: %d.", ret); - ret = srd_init(NULL); - fail_unless(ret != SRD_OK, "srd_init() 2 didn't fail: %d.", ret); - ret = srd_init(NULL); - fail_unless(ret != SRD_OK, "srd_init() 3 didn't fail: %d.", ret); - ret = srd_exit(); - fail_unless(ret == SRD_OK, "srd_exit() 3 failed: %d.", ret); - ret = srd_exit(); - fail_unless(ret == SRD_OK, "srd_exit() 2 failed: %d.", ret); - ret = srd_exit(); - fail_unless(ret == SRD_OK, "srd_exit() 1 failed: %d.", ret); -} -END_TEST - -Suite *suite_core(void) -{ - Suite *s; - TCase *tc; - - s = suite_create("core"); - - tc = tcase_create("init_exit"); - tcase_add_checked_fixture(tc, srdtest_setup, srdtest_teardown); - tcase_add_test(tc, test_init_exit); - tcase_add_test(tc, test_init_exit_2); - tcase_add_test(tc, test_init_exit_3); - suite_add_tcase(s, tc); - - return s; -} diff --git a/libsigrokdecode4DSL/tests/decoder.c b/libsigrokdecode4DSL/tests/decoder.c deleted file mode 100755 index 36784102..00000000 --- a/libsigrokdecode4DSL/tests/decoder.c +++ /dev/null @@ -1,467 +0,0 @@ -/* - * This file is part of the libsigrokdecode project. - * - * Copyright (C) 2013 Uwe Hermann - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, see . - */ - -#include -#include /* First, to avoid compiler warning. */ -#include -#include -#include "lib.h" - -/* - * Check whether srd_decoder_load_all() works. - * If it returns != SRD_OK (or segfaults) this test will fail. - */ -START_TEST(test_load_all) -{ - int ret; - - srd_init(DECODERS_TESTDIR); - ret = srd_decoder_load_all(); - fail_unless(ret == SRD_OK, "srd_decoder_load_all() failed: %d.", ret); - srd_exit(); -} -END_TEST - -/* - * Check whether srd_decoder_load_all() fails without prior srd_init(). - * If it returns != SRD_OK (or segfaults) this test will fail. - * See also: http://sigrok.org/bugzilla/show_bug.cgi?id=178 - */ -START_TEST(test_load_all_no_init) -{ - int ret; - - ret = srd_decoder_load_all(); - fail_unless(ret != SRD_OK, "srd_decoder_load_all() didn't fail properly."); -} -END_TEST - -/* - * Check whether srd_decoder_load() works. - * If it returns != SRD_OK (or segfaults) this test will fail. - */ -START_TEST(test_load) -{ - int ret; - - srd_init(DECODERS_TESTDIR); - ret = srd_decoder_load("uart"); - fail_unless(ret == SRD_OK, "srd_decoder_load(uart) failed: %d.", ret); - ret = srd_decoder_load("spi"); - fail_unless(ret == SRD_OK, "srd_decoder_load(spi) failed: %d.", ret); - ret = srd_decoder_load("usb_signalling"); - fail_unless(ret == SRD_OK, "srd_decoder_load(usb_signalling) failed: %d.", ret); - srd_exit(); -} -END_TEST - -/* - * Check whether srd_decoder_load() fails for non-existing or bogus PDs. - * If it returns SRD_OK (or segfaults) this test will fail. - */ -START_TEST(test_load_bogus) -{ - srd_init(DECODERS_TESTDIR); - /* http://sigrok.org/bugzilla/show_bug.cgi?id=176 */ - fail_unless(srd_decoder_load(NULL) != SRD_OK); - fail_unless(srd_decoder_load("") != SRD_OK); - fail_unless(srd_decoder_load(" ") != SRD_OK); - fail_unless(srd_decoder_load("nonexisting") != SRD_OK); - fail_unless(srd_decoder_load("UART") != SRD_OK); - fail_unless(srd_decoder_load("UaRt") != SRD_OK); - fail_unless(srd_decoder_load("u a r t") != SRD_OK); - fail_unless(srd_decoder_load("uart ") != SRD_OK); - fail_unless(srd_decoder_load(" uart") != SRD_OK); - fail_unless(srd_decoder_load(" uart ") != SRD_OK); - fail_unless(srd_decoder_load("uart spi") != SRD_OK); - srd_exit(); -} -END_TEST - -/* - * Check whether srd_decoder_load() works/fails for valid/bogus PDs. - * If it returns incorrect values (or segfaults) this test will fail. - */ -START_TEST(test_load_valid_and_bogus) -{ - srd_init(DECODERS_TESTDIR); - fail_unless(srd_decoder_load("") != SRD_OK); - fail_unless(srd_decoder_load("uart") == SRD_OK); - fail_unless(srd_decoder_load("") != SRD_OK); - fail_unless(srd_decoder_load("spi") == SRD_OK); - fail_unless(srd_decoder_load("") != SRD_OK); - fail_unless(srd_decoder_load("can") == SRD_OK); - fail_unless(srd_decoder_load("") != SRD_OK); - srd_exit(); -} -END_TEST - -/* - * Check whether srd_decoder_load() fails when run multiple times. - * If it returns a value != SRD_OK (or segfaults) this test will fail. - * See also: http://sigrok.org/bugzilla/show_bug.cgi?id=177 - */ -START_TEST(test_load_multiple) -{ - int ret; - - srd_init(DECODERS_TESTDIR); - ret = srd_decoder_load("uart"); - fail_unless(ret == SRD_OK, "Loading uart PD 1x failed: %d", ret); - ret = srd_decoder_load("uart"); - fail_unless(ret == SRD_OK, "Loading uart PD 2x failed: %d", ret); - ret = srd_decoder_load("uart"); - fail_unless(ret == SRD_OK, "Loading uart PD 3x failed: %d", ret); - srd_exit(); -} -END_TEST - -/* - * Check whether srd_decoder_load() fails if a non-existing PD dir is used. - * If it returns SRD_OK (or segfaults) this test will fail. - */ -START_TEST(test_load_nonexisting_pd_dir) -{ -#if 0 - /* TODO: Build libsigrokdecode with no default PD dir. */ - srd_init("/nonexisting_dir"); - fail_unless(srd_decoder_load("spi") != SRD_OK); - fail_unless(g_slist_length((GSList *)srd_decoder_list()) == 0); - srd_exit(); -#endif -} -END_TEST - -/* - * Check whether srd_decoder_unload_all() works. - * If it returns != SRD_OK (or segfaults) this test will fail. - */ -START_TEST(test_unload_all) -{ - int ret; - - srd_init(DECODERS_TESTDIR); - ret = srd_decoder_load_all(); - fail_unless(ret == SRD_OK, "srd_decoder_load_all() failed: %d.", ret); - ret = srd_decoder_unload_all(); - fail_unless(ret == SRD_OK, "srd_decoder_unload_all() failed: %d.", ret); - srd_exit(); -} -END_TEST - -/* - * Check whether srd_decoder_unload_all() works without prior srd_init(). - * If it returns != SRD_OK (or segfaults) this test will fail. - */ -START_TEST(test_unload_all_no_init) -{ - int ret; - - ret = srd_decoder_unload_all(); - fail_unless(ret == SRD_OK, "srd_decoder_unload_all() failed: %d.", ret); -} -END_TEST - -/* - * Check whether srd_decoder_unload_all() works multiple times. - * If it returns != SRD_OK (or segfaults) this test will fail. - */ -START_TEST(test_unload_all_multiple) -{ - int ret, i; - - srd_init(DECODERS_TESTDIR); - for (i = 0; i < 10; i++) { - ret = srd_decoder_load_all(); - fail_unless(ret == SRD_OK, "srd_decoder_load_all() failed: %d.", ret); - ret = srd_decoder_unload_all(); - fail_unless(ret == SRD_OK, "srd_decoder_unload_all() failed: %d.", ret); - } - srd_exit(); -} -END_TEST - -/* - * Check whether srd_decoder_unload_all() works multiple times (no load). - * If it returns != SRD_OK (or segfaults) this test will fail. - */ -START_TEST(test_unload_all_multiple_noload) -{ - int ret, i; - - srd_init(DECODERS_TESTDIR); - for (i = 0; i < 10; i++) { - ret = srd_decoder_unload_all(); - fail_unless(ret == SRD_OK, "srd_decoder_unload_all() failed: %d.", ret); - } - srd_exit(); -} -END_TEST - -/* - * Check whether srd_decoder_unload() works. - * If it returns != SRD_OK (or segfaults) this test will fail. - */ -START_TEST(test_unload) -{ - int ret; - struct srd_decoder *dec; - - srd_init(DECODERS_TESTDIR); - ret = srd_decoder_load("uart"); - fail_unless(ret == SRD_OK, "srd_decoder_load(uart) failed: %d.", ret); - dec = srd_decoder_get_by_id("uart"); - fail_unless(dec != NULL); - ret = srd_decoder_unload(dec); - fail_unless(ret == SRD_OK, "srd_decoder_unload() failed: %d.", ret); - srd_exit(); -} -END_TEST - -/* - * Check whether srd_decoder_unload(NULL) fails. - * If it returns SRD_OK (or segfaults) this test will fail. - */ -START_TEST(test_unload_null) -{ - srd_init(DECODERS_TESTDIR); - fail_unless(srd_decoder_unload(NULL) != SRD_OK); - srd_exit(); -} -END_TEST - -/* - * Check whether srd_decoder_unload(NULL) fails without prior srd_init(). - * If it returns SRD_OK (or segfaults) this test will fail. - */ -START_TEST(test_unload_null_no_init) -{ - fail_unless(srd_decoder_unload(NULL) != SRD_OK); -} -END_TEST - -/* - * Check whether srd_decoder_list() returns a non-empty list. - * If it returns an empty list (or segfaults) this test will fail. - */ -START_TEST(test_decoder_list) -{ - srd_init(DECODERS_TESTDIR); - srd_decoder_load_all(); - fail_unless(srd_decoder_list() != NULL); - srd_exit(); -} -END_TEST - -/* - * Check whether srd_decoder_list() without prior srd_decoder_load_all() - * returns an empty list (return value != NULL). - * If it returns a non-empty list (or segfaults) this test will fail. - */ -START_TEST(test_decoder_list_no_load) -{ - srd_init(DECODERS_TESTDIR); - fail_unless(srd_decoder_list() == NULL); - srd_exit(); -} -END_TEST - -/* - * Check whether srd_decoder_list() without prior srd_init() - * returns an empty list. - * If it returns a non-empty list (or segfaults) this test will fail. - * See also: http://sigrok.org/bugzilla/show_bug.cgi?id=178 - */ -START_TEST(test_decoder_list_no_init) -{ - srd_decoder_load_all(); - fail_unless(srd_decoder_list() == NULL); -} -END_TEST - -/* - * Check whether srd_decoder_list() without prior srd_init() and without - * prior srd_decoder_load_all() returns an empty list. - * If it returns a non-empty list (or segfaults) this test will fail. - */ -START_TEST(test_decoder_list_no_init_no_load) -{ - fail_unless(srd_decoder_list() == NULL); -} -END_TEST - -/* - * Check whether srd_decoder_list() returns the correct number of PDs. - * If it returns a wrong number (or segfaults) this test will fail. - */ -START_TEST(test_decoder_list_correct_numbers) -{ - srd_init(DECODERS_TESTDIR); - fail_unless(g_slist_length((GSList *)srd_decoder_list()) == 0); - srd_decoder_load("spi"); - fail_unless(g_slist_length((GSList *)srd_decoder_list()) == 1); - srd_decoder_load("uart"); - fail_unless(g_slist_length((GSList *)srd_decoder_list()) == 2); - srd_decoder_load("can"); - fail_unless(g_slist_length((GSList *)srd_decoder_list()) == 3); - srd_decoder_load("can"); /* Load same PD twice. */ - fail_unless(g_slist_length((GSList *)srd_decoder_list()) == 3); - srd_exit(); -} -END_TEST - -/* - * Check whether srd_decoder_get_by_id() works. - * If it returns NULL for valid PDs (or segfaults) this test will fail. - */ -START_TEST(test_get_by_id) -{ - srd_init(DECODERS_TESTDIR); - srd_decoder_load("uart"); - fail_unless(srd_decoder_get_by_id("uart") != NULL); - fail_unless(srd_decoder_get_by_id("can") == NULL); - srd_decoder_load("can"); - fail_unless(srd_decoder_get_by_id("uart") != NULL); - fail_unless(srd_decoder_get_by_id("can") != NULL); - srd_exit(); -} -END_TEST - -/* - * Check whether srd_decoder_get_by_id() works multiple times in a row. - * If it returns NULL for valid PDs (or segfaults) this test will fail. - */ -START_TEST(test_get_by_id_multiple) -{ - srd_init(DECODERS_TESTDIR); - srd_decoder_load("uart"); - fail_unless(srd_decoder_get_by_id("uart") != NULL); - fail_unless(srd_decoder_get_by_id("uart") != NULL); - fail_unless(srd_decoder_get_by_id("uart") != NULL); - fail_unless(srd_decoder_get_by_id("uart") != NULL); - srd_exit(); -} -END_TEST - -/* - * Check whether srd_decoder_get_by_id() fails for bogus PDs. - * If it returns a value != NULL (or segfaults) this test will fail. - */ -START_TEST(test_get_by_id_bogus) -{ - srd_init(DECODERS_TESTDIR); - fail_unless(srd_decoder_get_by_id(NULL) == NULL); - fail_unless(srd_decoder_get_by_id("") == NULL); - fail_unless(srd_decoder_get_by_id(" ") == NULL); - fail_unless(srd_decoder_get_by_id("nonexisting") == NULL); - fail_unless(srd_decoder_get_by_id("sPi") == NULL); - fail_unless(srd_decoder_get_by_id("SPI") == NULL); - fail_unless(srd_decoder_get_by_id("s p i") == NULL); - fail_unless(srd_decoder_get_by_id(" spi") == NULL); - fail_unless(srd_decoder_get_by_id("spi ") == NULL); - fail_unless(srd_decoder_get_by_id(" spi ") == NULL); - fail_unless(srd_decoder_get_by_id("spi uart") == NULL); - srd_exit(); -} -END_TEST - -/* - * Check whether srd_decoder_doc_get() works. - * If it returns NULL for valid PDs (or segfaults) this test will fail. - */ -START_TEST(test_doc_get) -{ - struct srd_decoder *dec; - char *doc; - - srd_init(DECODERS_TESTDIR); - srd_decoder_load("uart"); - dec = srd_decoder_get_by_id("uart"); - doc = srd_decoder_doc_get(dec); - fail_unless(doc != NULL); - g_free(doc); - srd_exit(); -} -END_TEST - -/* - * Check whether srd_decoder_doc_get() fails with NULL as argument. - * If it returns a value != NULL (or segfaults) this test will fail. - * See also: http://sigrok.org/bugzilla/show_bug.cgi?id=179 - */ -START_TEST(test_doc_get_null) -{ - srd_init(DECODERS_TESTDIR); - fail_unless(srd_decoder_doc_get(NULL) == NULL); - srd_exit(); -} -END_TEST - -Suite *suite_decoder(void) -{ - Suite *s; - TCase *tc; - - s = suite_create("decoder"); - - tc = tcase_create("load"); - tcase_set_timeout(tc, 0); - tcase_add_checked_fixture(tc, srdtest_setup, srdtest_teardown); - tcase_add_test(tc, test_load_all); - tcase_add_test(tc, test_load_all_no_init); - tcase_add_test(tc, test_load); - tcase_add_test(tc, test_load_bogus); - tcase_add_test(tc, test_load_valid_and_bogus); - tcase_add_test(tc, test_load_multiple); - tcase_add_test(tc, test_load_nonexisting_pd_dir); - suite_add_tcase(s, tc); - - tc = tcase_create("unload"); - tcase_add_checked_fixture(tc, srdtest_setup, srdtest_teardown); - tcase_add_test(tc, test_unload_all); - tcase_add_test(tc, test_unload_all_no_init); - tcase_add_test(tc, test_unload_all_multiple); - tcase_add_test(tc, test_unload_all_multiple_noload); - tcase_add_test(tc, test_unload); - tcase_add_test(tc, test_unload_null); - tcase_add_test(tc, test_unload_null_no_init); - suite_add_tcase(s, tc); - - tc = tcase_create("list"); - tcase_add_checked_fixture(tc, srdtest_setup, srdtest_teardown); - tcase_add_test(tc, test_decoder_list); - tcase_add_test(tc, test_decoder_list_no_load); - tcase_add_test(tc, test_decoder_list_no_init); - tcase_add_test(tc, test_decoder_list_no_init_no_load); - tcase_add_test(tc, test_decoder_list_correct_numbers); - suite_add_tcase(s, tc); - - tc = tcase_create("get_by_id"); - tcase_add_test(tc, test_get_by_id); - tcase_add_test(tc, test_get_by_id_multiple); - tcase_add_test(tc, test_get_by_id_bogus); - suite_add_tcase(s, tc); - - tc = tcase_create("doc_get"); - tcase_add_test(tc, test_doc_get); - tcase_add_test(tc, test_doc_get_null); - suite_add_tcase(s, tc); - - return s; -} diff --git a/libsigrokdecode4DSL/tests/inst.c b/libsigrokdecode4DSL/tests/inst.c deleted file mode 100755 index fd8f709a..00000000 --- a/libsigrokdecode4DSL/tests/inst.c +++ /dev/null @@ -1,163 +0,0 @@ -/* - * This file is part of the libsigrokdecode project. - * - * Copyright (C) 2013 Uwe Hermann - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, see . - */ - -#include -#include /* First, to avoid compiler warning. */ -#include -#include -#include "lib.h" - -/* - * Check whether srd_inst_new() works. - * If it returns NULL (or segfaults) this test will fail. - */ -START_TEST(test_inst_new) -{ - struct srd_session *sess; - struct srd_decoder_inst *inst; - - srd_init(DECODERS_TESTDIR); - srd_decoder_load("uart"); - srd_session_new(&sess); - inst = srd_inst_new(sess, "uart", NULL); - fail_unless(inst != NULL, "srd_inst_new() failed."); - srd_exit(); -} -END_TEST - -/* - * Check whether multiple srd_inst_new() calls work. - * If any of them returns NULL (or segfaults) this test will fail. - */ -START_TEST(test_inst_new_multiple) -{ - struct srd_session *sess; - struct srd_decoder_inst *inst1, *inst2, *inst3; - - inst1 = inst2 = inst3 = NULL; - - srd_init(DECODERS_TESTDIR); - srd_decoder_load_all(); - srd_session_new(&sess); - - /* Multiple srd_inst_new() calls must work. */ - inst1 = srd_inst_new(sess, "uart", NULL); - fail_unless(inst1 != NULL, "srd_inst_new() 1 failed."); - inst2 = srd_inst_new(sess, "spi", NULL); - fail_unless(inst2 != NULL, "srd_inst_new() 2 failed."); - inst3 = srd_inst_new(sess, "can", NULL); - fail_unless(inst3 != NULL, "srd_inst_new() 3 failed."); - - /* The returned instance pointers must not be the same. */ - fail_unless(inst1 != inst2); - fail_unless(inst1 != inst3); - fail_unless(inst2 != inst3); - - /* Each instance must have another py_inst than any of the others. */ - fail_unless(inst1->py_inst != inst2->py_inst); - fail_unless(inst1->py_inst != inst3->py_inst); - fail_unless(inst2->py_inst != inst3->py_inst); - - srd_exit(); -} -END_TEST - -/* - * Check whether srd_inst_option_set() works for an empty options hash. - * If it returns != SRD_OK (or segfaults) this test will fail. - */ -START_TEST(test_inst_option_set_empty) -{ - int ret; - struct srd_session *sess; - struct srd_decoder_inst *inst; - GHashTable *options; - - srd_init(DECODERS_TESTDIR); - srd_decoder_load_all(); - srd_session_new(&sess); - inst = srd_inst_new(sess, "uart", NULL); - options = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, - (GDestroyNotify)g_variant_unref); - ret = srd_inst_option_set(inst, options); - fail_unless(ret == SRD_OK, "srd_inst_option_set() with empty options " - "hash failed: %d.", ret); - srd_exit(); -} -END_TEST - -/* - * Check whether srd_inst_option_set() works for bogus options. - * If it returns != SRD_OK (or segfaults) this test will fail. - */ -START_TEST(test_inst_option_set_bogus) -{ - int ret; - struct srd_session *sess; - struct srd_decoder_inst *inst; - GHashTable *options; - - srd_init(DECODERS_TESTDIR); - srd_decoder_load_all(); - srd_session_new(&sess); - inst = srd_inst_new(sess, "uart", NULL); - - options = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, - (GDestroyNotify)g_variant_unref); - - /* NULL instance. */ - ret = srd_inst_option_set(NULL, options); - fail_unless(ret != SRD_OK, "srd_inst_option_set() with NULL " - "instance failed: %d.", ret); - - /* NULL 'options' GHashTable. */ - ret = srd_inst_option_set(inst, NULL); - fail_unless(ret != SRD_OK, "srd_inst_option_set() with NULL " - "options hash failed: %d.", ret); - - /* NULL instance and NULL 'options' GHashTable. */ - ret = srd_inst_option_set(NULL, NULL); - fail_unless(ret != SRD_OK, "srd_inst_option_set() with NULL " - "instance and NULL options hash failed: %d.", ret); - - srd_exit(); -} -END_TEST - -Suite *suite_inst(void) -{ - Suite *s; - TCase *tc; - - s = suite_create("inst"); - - tc = tcase_create("new"); - tcase_add_checked_fixture(tc, srdtest_setup, srdtest_teardown); - tcase_add_test(tc, test_inst_new); - tcase_add_test(tc, test_inst_new_multiple); - suite_add_tcase(s, tc); - - tc = tcase_create("option"); - tcase_add_checked_fixture(tc, srdtest_setup, srdtest_teardown); - tcase_add_test(tc, test_inst_option_set_empty); - tcase_add_test(tc, test_inst_option_set_bogus); - suite_add_tcase(s, tc); - - return s; -} diff --git a/libsigrokdecode4DSL/tests/main.c b/libsigrokdecode4DSL/tests/main.c deleted file mode 100755 index 879440c9..00000000 --- a/libsigrokdecode4DSL/tests/main.c +++ /dev/null @@ -1,56 +0,0 @@ -/* - * This file is part of the libsigrokdecode project. - * - * Copyright (C) 2013 Uwe Hermann - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, see . - */ - -#include -#include /* First, to avoid compiler warning. */ -#include -#include -#include "lib.h" - -void srdtest_setup(void) -{ - /* Silence libsigrokdecode while the unit tests run. */ - srd_log_loglevel_set(SRD_LOG_NONE); -} - -void srdtest_teardown(void) -{ -} - -int main(void) -{ - int ret; - Suite *s; - SRunner *srunner; - - s = suite_create("mastersuite"); - srunner = srunner_create(s); - - /* Add all testsuites to the master suite. */ - srunner_add_suite(srunner, suite_core()); - srunner_add_suite(srunner, suite_decoder()); - srunner_add_suite(srunner, suite_inst()); - srunner_add_suite(srunner, suite_session()); - - srunner_run_all(srunner, CK_VERBOSE); - ret = srunner_ntests_failed(srunner); - srunner_free(srunner); - - return (ret == 0) ? EXIT_SUCCESS : EXIT_FAILURE; -} diff --git a/libsigrokdecode4DSL/tests/session.c b/libsigrokdecode4DSL/tests/session.c deleted file mode 100755 index 73b7669e..00000000 --- a/libsigrokdecode4DSL/tests/session.c +++ /dev/null @@ -1,290 +0,0 @@ -/* - * This file is part of the libsigrokdecode project. - * - * Copyright (C) 2013 Uwe Hermann - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, see . - */ - -#include -#include /* First, to avoid compiler warning. */ -#include -#include -#include -#include -#include "lib.h" - -/* - * Check whether srd_session_new() works. - * If it returns != SRD_OK (or segfaults) this test will fail. - */ -START_TEST(test_session_new) -{ - int ret; - struct srd_session *sess; - - srd_init(NULL); - ret = srd_session_new(&sess); - fail_unless(ret == SRD_OK, "srd_session_new() failed: %d.", ret); - srd_exit(); -} -END_TEST - -/* - * Check whether srd_session_new() fails for bogus parameters. - * If it returns SRD_OK (or segfaults) this test will fail. - */ -START_TEST(test_session_new_bogus) -{ - int ret; - - srd_init(NULL); - ret = srd_session_new(NULL); - fail_unless(ret != SRD_OK, "srd_session_new(NULL) worked."); - srd_exit(); -} -END_TEST - -/* - * Check whether multiple srd_session_new() calls work. - * If any call returns != SRD_OK (or segfaults) this test will fail. - */ -START_TEST(test_session_new_multiple) -{ - int ret; - struct srd_session *sess1, *sess2, *sess3; - - sess1 = sess2 = sess3 = NULL; - - srd_init(NULL); - - /* Multiple srd_session_new() calls must work. */ - ret = srd_session_new(&sess1); - fail_unless(ret == SRD_OK, "srd_session_new() 1 failed: %d.", ret); - ret = srd_session_new(&sess2); - fail_unless(ret == SRD_OK, "srd_session_new() 2 failed: %d.", ret); - ret = srd_session_new(&sess3); - fail_unless(ret == SRD_OK, "srd_session_new() 3 failed: %d.", ret); - - /* The returned session pointers must all be non-NULL. */ - fail_unless(sess1 != NULL); - fail_unless(sess2 != NULL); - fail_unless(sess3 != NULL); - - /* The returned session pointers must not be the same. */ - fail_unless(sess1 != sess2); - fail_unless(sess1 != sess3); - fail_unless(sess2 != sess3); - - /* Each session must have another ID than any other session. */ - fail_unless(sess1->session_id != sess2->session_id); - fail_unless(sess1->session_id != sess3->session_id); - fail_unless(sess2->session_id != sess3->session_id); - - /* Destroying any of the sessions must work. */ - ret = srd_session_destroy(sess1); - fail_unless(ret == SRD_OK, "srd_session_destroy() 1 failed: %d.", ret); - ret = srd_session_destroy(sess2); - fail_unless(ret == SRD_OK, "srd_session_destroy() 2 failed: %d.", ret); - ret = srd_session_destroy(sess3); - fail_unless(ret == SRD_OK, "srd_session_destroy() 3 failed: %d.", ret); - - srd_exit(); -} -END_TEST - -/* - * Check whether srd_session_destroy() works. - * If it returns != SRD_OK (or segfaults) this test will fail. - */ -START_TEST(test_session_destroy) -{ - int ret; - struct srd_session *sess; - - srd_init(NULL); - srd_session_new(&sess); - ret = srd_session_destroy(sess); - fail_unless(ret == SRD_OK, "srd_session_destroy() failed: %d.", ret); - srd_exit(); -} -END_TEST - -/* - * Check whether srd_session_destroy() fails for bogus sessions. - * If it returns SRD_OK (or segfaults) this test will fail. - */ -START_TEST(test_session_destroy_bogus) -{ - int ret; - - srd_init(NULL); - ret = srd_session_destroy(NULL); - fail_unless(ret != SRD_OK, "srd_session_destroy() failed: %d.", ret); - srd_exit(); -} -END_TEST - -static void conf_check_ok(struct srd_session *sess, int key, uint64_t x) -{ - int ret; - - ret = srd_session_metadata_set(sess, key, g_variant_new_uint64(x)); - fail_unless(ret == SRD_OK, "srd_session_metadata_set(%p, %d, %" - PRIu64 ") failed: %d.", sess, key, x, ret); -} - -static void conf_check_fail(struct srd_session *sess, int key, uint64_t x) -{ - int ret; - GVariant *value = g_variant_new_uint64(x); - - ret = srd_session_metadata_set(sess, key, value); - fail_unless(ret != SRD_OK, "srd_session_metadata_set(%p, %d, %" - PRIu64 ") worked.", sess, key, x); - if (ret != SRD_OK) - g_variant_unref(value); -} - -static void conf_check_fail_null(struct srd_session *sess, int key) -{ - int ret; - - ret = srd_session_metadata_set(sess, key, NULL); - fail_unless(ret != SRD_OK, - "srd_session_metadata_set(NULL) for key %d worked.", key); -} - -static void conf_check_fail_str(struct srd_session *sess, int key, const char *s) -{ - int ret; - GVariant *value = g_variant_new_string(s); - - ret = srd_session_metadata_set(sess, key, value); - fail_unless(ret != SRD_OK, "srd_session_metadata_set() for key %d " - "failed: %d.", key, ret); - if (ret != SRD_OK) - g_variant_unref(value); -} - -/* - * Check whether srd_session_metadata_set() works. - * If it returns != SRD_OK (or segfaults) this test will fail. - */ -START_TEST(test_session_metadata_set) -{ - uint64_t i; - struct srd_session *sess; - - srd_init(NULL); - srd_session_new(&sess); - /* Try a bunch of values. */ - for (i = 0; i < 1000; i++) - conf_check_ok(sess, SRD_CONF_SAMPLERATE, i); - /* Try the max. possible value. */ - conf_check_ok(sess, SRD_CONF_SAMPLERATE, UINT64_MAX); - srd_session_destroy(sess); - srd_exit(); -} -END_TEST - -/* - * Check whether srd_session_metadata_set() fails with invalid input. - * If it returns SRD_OK (or segfaults) this test will fail. - */ -START_TEST(test_session_metadata_set_bogus) -{ - struct srd_session *sess; - - srd_init(NULL); - srd_session_new(&sess); - - /* Incorrect GVariant type (currently only uint64 is used). */ - conf_check_fail_str(sess, SRD_CONF_SAMPLERATE, ""); - conf_check_fail_str(sess, SRD_CONF_SAMPLERATE, "Foo"); - - /* NULL data pointer. */ - conf_check_fail_null(sess, SRD_CONF_SAMPLERATE); - - /* NULL session. */ - conf_check_fail(NULL, SRD_CONF_SAMPLERATE, 0); - - /* Invalid keys. */ - conf_check_fail(sess, -1, 0); - conf_check_fail(sess, 9, 0); - conf_check_fail(sess, 123, 0); - - srd_session_destroy(sess); - srd_exit(); -} -END_TEST - -/* - * Check whether srd_session_terminate_reset() succeeds on newly created - * sessions, as well as after calling start() and meta(). No data is fed - * to decoders here. - */ -START_TEST(test_session_reset_nodata) -{ - struct srd_session *sess; - int ret; - GVariant *data; - - srd_init(NULL); - srd_session_new(&sess); - ret = srd_session_terminate_reset(sess); - fail_unless(ret == SRD_OK, "srd_session_terminate_reset() failed: %d.", ret); - ret = srd_session_start(sess); - fail_unless(ret == SRD_OK, "srd_session_start() failed: %d.", ret); - ret = srd_session_terminate_reset(sess); - fail_unless(ret == SRD_OK, "srd_session_terminate_reset() failed: %d.", ret); - data = g_variant_new_uint64(1000000); - ret = srd_session_metadata_set(sess, SRD_CONF_SAMPLERATE, data); - fail_unless(ret == SRD_OK, "srd_session_metadata_set() failed: %d.", ret); - ret = srd_session_terminate_reset(sess); - fail_unless(ret == SRD_OK, "srd_session_terminate_reset() failed: %d.", ret); - ret = srd_session_destroy(sess); - fail_unless(ret == SRD_OK, "srd_session_destroy() failed: %d.", ret); - srd_exit(); -} -END_TEST - -Suite *suite_session(void) -{ - Suite *s; - TCase *tc; - - s = suite_create("session"); - - tc = tcase_create("new_destroy"); - tcase_add_checked_fixture(tc, srdtest_setup, srdtest_teardown); - tcase_add_test(tc, test_session_new); - tcase_add_test(tc, test_session_new_bogus); - tcase_add_test(tc, test_session_new_multiple); - tcase_add_test(tc, test_session_destroy); - tcase_add_test(tc, test_session_destroy_bogus); - suite_add_tcase(s, tc); - - tc = tcase_create("config"); - tcase_add_checked_fixture(tc, srdtest_setup, srdtest_teardown); - tcase_add_test(tc, test_session_metadata_set); - tcase_add_test(tc, test_session_metadata_set_bogus); - suite_add_tcase(s, tc); - - tc = tcase_create("reset"); - tcase_add_test(tc, test_session_reset_nodata); - suite_add_tcase(s, tc); - - return s; -} diff --git a/libsigrokdecode4DSL/type_decoder.c b/libsigrokdecode4DSL/type_decoder.c index d4b9782b..6199652b 100755 --- a/libsigrokdecode4DSL/type_decoder.c +++ b/libsigrokdecode4DSL/type_decoder.c @@ -53,6 +53,92 @@ static void release_annotation(struct srd_proto_data_annotation *pda) g_strfreev(pda->ann_text); } +static int py_parse_ann_data(PyObject *list_obj, char ***out_strv, int list_size, char *hex_str_buf, long long *numberic_value) +{ + PyObject *py_item, *py_bytes; + char **strv, *str; + PyGILState_STATE gstate; + int ret = SRD_ERR_PYTHON; + int ijmp = 0; + int text_num = 0; + PyObject* text_items[10]; + PyObject *py_tmp; + PyObject *py_numobj = NULL; + int i; + long long lv; + + gstate = PyGILState_Ensure(); + + str = NULL; + strv = NULL; + + //get annotation text count + for (i = 0; i < list_size; i++){ + py_tmp = PyList_GetItem(list_obj, i); + + //is a string + if (PyUnicode_Check(py_tmp)){ + text_items[text_num] = py_tmp; + text_num++; + } + else if (PyLong_Check(py_tmp)){ + py_numobj = py_tmp; + } + } + + if (py_numobj == NULL && text_num == 0){ + srd_err("list element type must be string or numberical"); + goto err; + } + + if (py_numobj != NULL){ + lv = PyLong_AsLongLong(py_numobj); + sprintf(hex_str_buf, "%02llX", lv); + *numberic_value = lv; + } + + //have no text, only one numberical + if (text_num == 0){ + PyGILState_Release(gstate); + return SRD_OK; + } + + //more annotation text + strv = g_try_new0(char *, text_num + 1); + if (!strv) { + srd_err("Failed to allocate result string vector."); + ret = SRD_ERR_MALLOC; + goto err; + } + + for (i = 0; i < text_num; i++) { + py_bytes = PyUnicode_AsUTF8String(text_items[i]); + if (!py_bytes) + goto err; + + str = g_strdup(PyBytes_AsString(py_bytes)); + Py_DECREF(py_bytes); + if (!str) + goto err; + + strv[i] = str; + } + + *out_strv = strv; + PyGILState_Release(gstate); + return SRD_OK; + +err: + if (strv) + g_strfreev(strv); + srd_exception_catch(NULL, "Failed to obtain string item"); + PyGILState_Release(gstate); + return ret; +} + +/* + @obj is the fourth param from python calls put() +*/ static int convert_annotation(struct srd_decoder_inst *di, PyObject *obj, struct srd_proto_data *pdata) { @@ -62,6 +148,9 @@ static int convert_annotation(struct srd_decoder_inst *di, PyObject *obj, char **ann_text; gpointer ann_type_ptr; PyGILState_STATE gstate; + int ann_size; + + pda = pdata->data; gstate = PyGILState_Ensure(); @@ -96,27 +185,39 @@ static int convert_annotation(struct srd_decoder_inst *di, PyObject *obj, // "annotation class %d.", di->decoder->name, ann_class); // return SRD_ERR_PYTHON; // } - if (ann_class >= g_slist_length(di->decoder->ann_types)) { + if (ann_class >= g_slist_length(di->decoder->ann_types) || ann_class < 0) { srd_err("Protocol decoder %s submitted data to unregistered " "annotation class %d.", di->decoder->name, ann_class); goto err; } ann_type_ptr = g_slist_nth_data(di->decoder->ann_types, ann_class); - /* Second element must be a list. */ + /* + Second element must be a list. + */ py_tmp = PyList_GetItem(obj, 1); if (!PyList_Check(py_tmp)) { srd_err("Protocol decoder %s submitted annotation list, but " "second element was not a list.", di->decoder->name); goto err; } - if (py_strseq_to_char(py_tmp, &ann_text) != SRD_OK) { + + ann_size = PyList_Size(py_tmp); + if (ann_size == 0){ + srd_err("Protocol decoder %s, put() param, the annotation list is empty.", di->decoder->name); + goto err; + } + + pda->str_number_hex[0] = 0; + ann_text = NULL; + pda->numberic_value = 0; + + if (py_parse_ann_data(py_tmp, &ann_text, ann_size, pda->str_number_hex, &pda->numberic_value) != SRD_OK) { srd_err("Protocol decoder %s submitted annotation list, but " "second element was malformed.", di->decoder->name); goto err; } - - pda = pdata->data; + pda->ann_class = ann_class; pda->ann_type = GPOINTER_TO_INT(ann_type_ptr); pda->ann_text = ann_text; @@ -334,7 +435,7 @@ static PyObject *Decoder_put(PyObject *self, PyObject *args) struct srd_pd_callback *cb; PyGILState_STATE gstate; - py_data = NULL; + py_data = NULL; //the fourth param from python gstate = PyGILState_Ensure(); @@ -394,17 +495,20 @@ static PyObject *Decoder_put(PyObject *self, PyObject *args) case SRD_OUTPUT_PYTHON: for (l = di->next_di; l; l = l->next) { next_di = l->data; + srd_spew("Instance %s put %" PRIu64 "-%" PRIu64 " %s " "on oid %d (%s) to instance %s.", di->inst_id, start_sample, end_sample, output_type_name(pdo->output_type), output_id, pdo->proto_id, next_di->inst_id); + if (!(py_res = PyObject_CallMethod( next_di->py_inst, "decode", "KKO", start_sample, end_sample, py_data))) { srd_exception_catch(NULL, "Calling %s decode() failed", next_di->inst_id); } + Py_XDECREF(py_res); } if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) { @@ -459,6 +563,9 @@ err: return NULL; } +/* + return output info index +*/ static PyObject *Decoder_register(PyObject *self, PyObject *args, PyObject *kwargs) { @@ -612,7 +719,9 @@ static int get_current_pinvalues(const struct srd_decoder_inst *di) for (i = 0; i < di->dec_num_channels; i++) { /* A channelmap value of -1 means "unused optional channel". */ if (di->dec_channelmap[i] == -1) { - /* Value of unused channel is 0xff, instead of 0 or 1. */ + /* Value of unused channel is 0xff, instead of 0 or 1. + Done set -1 by srd_inst_channel_set_all() + */ PyTuple_SetItem(di->py_pinvalues, i, PyLong_FromLong(0xff)); } else { if (*(di->inbuf + i) == NULL) { @@ -905,6 +1014,7 @@ static PyObject *Decoder_wait(PyObject *self, PyObject *args) while (!di->got_new_samples && !di->want_wait_terminate) g_cond_wait(&di->got_new_samples_cond, &di->data_mutex); + /* * Check whether any of the current condition(s) match. * Arrange for termination requests to take a code path which @@ -915,7 +1025,7 @@ static PyObject *Decoder_wait(PyObject *self, PyObject *args) found_match = FALSE; /* Ignore return value for now, should never be negative. */ - (void)process_samples_until_condition_match(di, &found_match); + process_samples_until_condition_match(di, &found_match); Py_END_ALLOW_THREADS @@ -940,7 +1050,7 @@ static PyObject *Decoder_wait(PyObject *self, PyObject *args) Py_INCREF(di->py_pinvalues); return (PyObject *)di->py_pinvalues; } - + /* No match, reset state for the next chunk. */ di->got_new_samples = FALSE; di->handled_all_samples = TRUE; @@ -1032,12 +1142,16 @@ err: static PyMethodDef Decoder_methods[] = { { "put", Decoder_put, METH_VARARGS, "Accepts a dictionary with the following keys: startsample, endsample, data" }, + { "register", (PyCFunction)Decoder_register, METH_VARARGS|METH_KEYWORDS, "Register a new output stream" }, + { "wait", Decoder_wait, METH_VARARGS, "Wait for one or more conditions to occur" }, + { "has_channel", Decoder_has_channel, METH_VARARGS, "Report whether a channel was supplied" }, + {NULL, NULL, 0, NULL} }; diff --git a/libsigrokdecode4DSL/util.c b/libsigrokdecode4DSL/util.c index 45fb2d1c..3211fae5 100755 --- a/libsigrokdecode4DSL/util.c +++ b/libsigrokdecode4DSL/util.c @@ -39,13 +39,13 @@ SRD_PRIV PyObject *py_import_by_name(const char *name) PyGILState_STATE gstate; gstate = PyGILState_Ensure(); - + py_modname = PyUnicode_FromString(name); if (!py_modname) { PyGILState_Release(gstate); return NULL; - } - + } + py_mod = PyImport_Import(py_modname); Py_DECREF(py_modname); diff --git a/libsigrokdecode4DSL/version.h b/libsigrokdecode4DSL/version.h new file mode 100644 index 00000000..d131411e --- /dev/null +++ b/libsigrokdecode4DSL/version.h @@ -0,0 +1,71 @@ +/* version.h. Generated from version.h.in by configure. */ +/* + * This file is part of the libsigrokdecode project. + * + * Copyright (C) 2010 Uwe Hermann + * Copyright (C) 2012 Bert Vermeulen + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef LIBSIGROKDECODE_VERSION_H +#define LIBSIGROKDECODE_VERSION_H + +/** + * @file + * + * Version number definitions and macros. + */ + +/** + * @ingroup grp_versions + * + * @{ + */ + +/* + * Package version macros (can be used for conditional compilation). + */ + +/** The libsigrokdecode package 'major' version number. */ +#define SRD_PACKAGE_VERSION_MAJOR 0 + +/** The libsigrokdecode package 'minor' version number. */ +#define SRD_PACKAGE_VERSION_MINOR 6 + +/** The libsigrokdecode package 'micro' version number. */ +#define SRD_PACKAGE_VERSION_MICRO 0 + +/** The libsigrokdecode package version ("major.minor.micro") as string. */ +#define SRD_PACKAGE_VERSION_STRING "0.6.0-git-c708a00" + +/* + * Library/libtool version macros (can be used for conditional compilation). + */ + +/** The libsigrokdecode libtool 'current' version number. */ +#define SRD_LIB_VERSION_CURRENT 4 + +/** The libsigrokdecode libtool 'revision' version number. */ +#define SRD_LIB_VERSION_REVISION 0 + +/** The libsigrokdecode libtool 'age' version number. */ +#define SRD_LIB_VERSION_AGE 0 + +/** The libsigrokdecode libtool version ("current:revision:age") as string. */ +#define SRD_LIB_VERSION_STRING "4:0:0" + +/** @} */ + +#endif diff --git a/logo-win.ico b/logo-win.ico new file mode 100644 index 00000000..881489ad Binary files /dev/null and b/logo-win.ico differ diff --git a/qtpro/DSView-mac.pro b/qtpro/DSView-mac.pro new file mode 100644 index 00000000..b5d06417 --- /dev/null +++ b/qtpro/DSView-mac.pro @@ -0,0 +1,361 @@ +#------------------------------------------------- +# +# Project created by QtCreator 2013-07-24T17:32:25 +# +#------------------------------------------------- + +QT += core gui +CONFIG -= lib_bundle +CONFIG += app_bundle +macx { +QT += svg +#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 +#CONFIG += sdk_no_version_check +} +CONFIG += exceptions +CONFIG += object_parallel_to_source +CONFIG += c++11 +QT += widgets +#QT+= core5compat + +#QMAKE_CFLAGS_ISYSTEM = -I + +TARGET = DSView +TEMPLATE = app + +TRANSLATIONS = my_CN.ts + +CONFIG += decoders +DEFINES += decoders + +macx: { +INCLUDEPATH += /usr/local/include/ +INCLUDEPATH += /usr/local/Cellar/glib/2.70.1/include/glib-2.0 +INCLUDEPATH += /usr/local/Cellar/glib/2.70.1/lib/glib-2.0/include +INCLUDEPATH += /usr/local/Cellar/libusb/1.0.24/include/libusb-1.0 +INCLUDEPATH += /usr/local/Cellar/boost/1.76.0/include +INCLUDEPATH += /usr/local/Cellar/python@3.9/3.9.9/frameworks/Python.framework/versions/3.9/include/python3.9 +INCLUDEPATH += /usr/local/Cellar/libzip/1.8.0_1/include +INCLUDEPATH += /usr/local/Cellar/fftw/3.3.10/include +INCLUDEPATH += /usr/local/Cellar/zlib/1.2.11/include + +INCLUDEPATH += .. +INCLUDEPATH += ../libsigrok4DSL +INCLUDEPATH += ../DSView +INCLUDEPATH += ../DSView/pv/dialogs + +LIBS += /usr/local/Cellar/glib/2.70.1/lib/libglib-2.0.dylib +LIBS += /usr/local/Cellar/libusb/1.0.24/lib/libusb-1.0.dylib +LIBS += /usr/local/Cellar/python@3.9/3.9.9/frameworks/Python.framework/versions/3.9/lib/libpython3.9.dylib +LIBS += /usr/local/Cellar/fftw/3.3.10/lib/libfftw3.a +LIBS += /usr/local/Cellar/zlib/1.2.11/lib/libz.1.2.11.dylib +LIBS += /usr/local/Cellar/libzip/1.8.0_1/lib/libzip.5.4.dylib +} + +SOURCES += \ + ../DSView/main.cpp \ + ../DSView/pv/sigsession.cpp \ + ../DSView/pv/mainwindow.cpp \ + ../DSView/pv/devicemanager.cpp \ + ../DSView/pv/data/snapshot.cpp \ + ../DSView/pv/data/signaldata.cpp \ + ../DSView/pv/data/logicsnapshot.cpp \ + ../DSView/pv/data/logic.cpp \ + ../DSView/pv/data/analogsnapshot.cpp \ + ../DSView/pv/data/analog.cpp \ + ../DSView/pv/dialogs/deviceoptions.cpp \ + ../DSView/pv/prop/property.cpp \ + ../DSView/pv/prop/int.cpp \ + ../DSView/pv/prop/enum.cpp \ + ../DSView/pv/prop/double.cpp \ + ../DSView/pv/prop/bool.cpp \ + ../DSView/pv/prop/binding/binding.cpp \ + ../DSView/pv/toolbars/samplingbar.cpp \ + ../DSView/pv/ui/dscombobox.cpp \ + ../DSView/pv/view/viewport.cpp \ + ../DSView/pv/view/view.cpp \ + ../DSView/pv/view/timemarker.cpp \ + ../DSView/pv/view/signal.cpp \ + ../DSView/pv/view/ruler.cpp \ + ../DSView/pv/view/logicsignal.cpp \ + ../DSView/pv/view/header.cpp \ + ../DSView/pv/view/cursor.cpp \ + ../DSView/pv/view/analogsignal.cpp \ + ../DSView/pv/prop/binding/deviceoptions.cpp \ + ../DSView/pv/toolbars/trigbar.cpp \ + ../DSView/pv/toolbars/filebar.cpp \ + ../DSView/pv/dock/triggerdock.cpp \ + ../DSView/pv/dock/measuredock.cpp \ + ../DSView/pv/dock/searchdock.cpp \ + ../DSView/pv/toolbars/logobar.cpp \ + ../DSView/pv/data/groupsnapshot.cpp \ + ../DSView/pv/view/groupsignal.cpp \ + ../DSView/pv/data/group.cpp \ + ../DSView/pv/dialogs/about.cpp \ + ../DSView/pv/dialogs/search.cpp \ + ../DSView/pv/data/dsosnapshot.cpp \ + ../DSView/pv/data/dso.cpp \ + ../DSView/pv/view/dsosignal.cpp \ + ../DSView/pv/view/dsldial.cpp \ + ../DSView/pv/dock/dsotriggerdock.cpp \ + ../DSView/pv/view/trace.cpp \ + ../DSView/pv/view/selectableitem.cpp \ + ../DSView/pv/widgets/fakelineedit.cpp \ + ../DSView/pv/prop/string.cpp \ + ../DSView/pv/device/sessionfile.cpp \ + ../DSView/pv/device/inputfile.cpp \ + ../DSView/pv/device/file.cpp \ + ../DSView/pv/device/devinst.cpp \ + ../DSView/pv/dialogs/storeprogress.cpp \ + ../DSView/pv/storesession.cpp \ + ../DSView/pv/view/devmode.cpp \ + ../DSView/pv/device/device.cpp \ + ../DSView/pv/dialogs/waitingdialog.cpp \ + ../DSView/pv/dialogs/dsomeasure.cpp \ + ../DSView/pv/dialogs/calibration.cpp \ + ../DSView/pv/dialogs/fftoptions.cpp \ + ../DSView/dsapplication.cpp \ + ../DSView/pv/toolbars/titlebar.cpp \ + ../DSView/pv/mainframe.cpp \ + ../DSView/pv/widgets/border.cpp \ + ../DSView/pv/dialogs/dsmessagebox.cpp \ + ../DSView/pv/dialogs/shadow.cpp \ + ../DSView/pv/dialogs/dsdialog.cpp \ + ../DSView/pv/dialogs/interval.cpp \ + ../DSView/pv/prop/binding/probeoptions.cpp \ + ../DSView/pv/view/xcursor.cpp \ + ../DSView/pv/view/viewstatus.cpp \ + ../DSView/pv/dialogs/lissajousoptions.cpp \ + ../DSView/pv/view/lissajoustrace.cpp \ + ../DSView/pv/view/spectrumtrace.cpp \ + ../DSView/pv/data/spectrumstack.cpp \ + ../DSView/pv/view/mathtrace.cpp \ + ../DSView/pv/dialogs/mathoptions.cpp \ + ../DSView/pv/data/mathstack.cpp \ + ../DSView/pv/dialogs/regionoptions.cpp \ + ../DSView/pv/ZipMaker.cpp \ + ../DSView/pv/data/decode/AnnotationResTable.cpp \ + ../DSView/pv/ui/msgbox.cpp \ + ../DSView/pv/dock/protocolitemlayer.cpp \ + ../DSView/pv/config/appconfig.cpp \ + ../DSView/pv/dsvdef.cpp \ + ../DSView/pv/minizip/zip.c \ + ../DSView/pv/minizip/unzip.c \ + ../DSView/pv/minizip/ioapi.c \ + ../DSView/pv/dialogs/applicationpardlg.cpp \ + ../DSView/pv/appcontrol.cpp \ + ../DSView/pv/eventobject.cpp \ + ../DSView/pv/dstimer.cpp + +HEADERS += \ + ../DSView/extdef.h \ + ../DSView/config.h \ + ../DSView/pv/sigsession.h \ + ../DSView/pv/mainwindow.h \ + ../DSView/pv/devicemanager.h \ + ../DSView/pv/data/snapshot.h \ + ../DSView/pv/data/signaldata.h \ + ../DSView/pv/data/logicsnapshot.h \ + ../DSView/pv/data/logic.h \ + ../DSView/pv/data/analogsnapshot.h \ + ../DSView/pv/data/analog.h \ + ../DSView/pv/dialogs/deviceoptions.h \ + ../DSView/pv/prop/property.h \ + ../DSView/pv/prop/int.h \ + ../DSView/pv/prop/enum.h \ + ../DSView/pv/prop/double.h \ + ../DSView/pv/prop/bool.h \ + ../DSView/pv/prop/binding/deviceoptions.h \ + ../DSView/pv/prop/binding/binding.h \ + ../DSView/pv/toolbars/samplingbar.h \ + ../DSView/pv/ui/dscombobox.h \ + ../DSView/pv/view/viewport.h \ + ../DSView/pv/view/view.h \ + ../DSView/pv/view/timemarker.h \ + ../DSView/pv/view/signal.h \ + ../DSView/pv/view/ruler.h \ + ../DSView/pv/view/logicsignal.h \ + ../DSView/pv/view/header.h \ + ../DSView/pv/view/cursor.h \ + ../DSView/pv/view/analogsignal.h \ + ../DSView/pv/toolbars/trigbar.h \ + ../DSView/pv/toolbars/filebar.h \ + ../DSView/pv/dock/triggerdock.h \ + ../DSView/pv/dock/measuredock.h \ + ../DSView/pv/dock/searchdock.h \ + ../DSView/pv/toolbars/logobar.h \ + ../DSView/pv/data/groupsnapshot.h \ + ../DSView/pv/view/groupsignal.h \ + ../DSView/pv/data/group.h \ + ../DSView/pv/dialogs/about.h \ + ../DSView/pv/dialogs/search.h \ + ../DSView/pv/data/dso.h \ + ../DSView/pv/data/dsosnapshot.h \ + ../DSView/pv/view/dsosignal.h \ + ../DSView/pv/view/dsldial.h \ + ../DSView/pv/dock/dsotriggerdock.h \ + ../DSView/pv/view/trace.h \ + ../DSView/pv/view/selectableitem.h \ + ../DSView/pv/widgets/fakelineedit.h \ + ../DSView/pv/prop/string.h \ + ../DSView/pv/device/sessionfile.h \ + ../DSView/pv/device/inputfile.h \ + ../DSView/pv/device/file.h \ + ../DSView/pv/device/devinst.h \ + ../DSView/pv/dialogs/storeprogress.h \ + ../DSView/pv/storesession.h \ + ../DSView/pv/view/devmode.h \ + ../DSView/pv/device/device.h \ + ../DSView/pv/dialogs/waitingdialog.h \ + ../DSView/pv/dialogs/dsomeasure.h \ + ../DSView/pv/dialogs/calibration.h \ + ../DSView/pv/dialogs/fftoptions.h \ + ../DSView/dsapplication.h \ + ../DSView/pv/toolbars/titlebar.h \ + ../DSView/pv/mainframe.h \ + ../DSView/pv/widgets/border.h \ + ../DSView/pv/dialogs/dsmessagebox.h \ + ../DSView/pv/dialogs/shadow.h \ + ../DSView/pv/dialogs/dsdialog.h \ + ../DSView/pv/dialogs/interval.h \ + ../DSView/config.h \ + ../libsigrok4DSL/config.h \ + ../DSView/pv/prop/binding/probeoptions.h \ + ../libsigrok4DSL/hardware/demo/demo.h \ + ../DSView/pv/view/xcursor.h \ + ../DSView/pv/view/viewstatus.h \ + ../DSView/pv/dialogs/lissajousoptions.h \ + ../DSView/pv/view/lissajoustrace.h \ + ../DSView/pv/view/spectrumtrace.h \ + ../DSView/pv/data/spectrumstack.h \ + ../DSView/pv/view/mathtrace.h \ + ../DSView/pv/dialogs/mathoptions.h \ + ../DSView/pv/data/mathstack.h \ + ../DSView/pv/dialogs/regionoptions.h \ + ../DSView/mystyle.h \ + ../DSView/pv/ZipMaker.h \ + ../DSView/pv/data/decode/AnnotationResTable.h \ + ../DSView/pv/ui/msgbox.h \ + ../DSView/pv/dock/protocolitemlayer.h \ + ../DSView/pv/config/appconfig.h \ + ../DSView/pv/dsvdef.h \ + ../DSView/pv/minizip/zip.h \ + ../DSView/pv/minizip/unzip.h \ + ../DSView/pv/minizip/ioapi.h \ + ../DSView/pv/dialogs/applicationpardlg.h \ + ../DSView/pv/appcontrol.h \ + ../DSView/pv/eventobject.h \ + ../DSView/pv/dstimer.h + +SOURCES += \ + ../libsigrok4DSL/version.c \ + ../libsigrok4DSL/strutil.c \ + ../libsigrok4DSL/std.c \ + ../libsigrok4DSL/session_file.c \ + ../libsigrok4DSL/session_driver.c \ + ../libsigrok4DSL/session.c \ + ../libsigrok4DSL/log.c \ + ../libsigrok4DSL/hwdriver.c \ + ../libsigrok4DSL/error.c \ + ../libsigrok4DSL/backend.c \ + ../libsigrok4DSL/output/output.c \ + ../libsigrok4DSL/input/input.c \ + ../libsigrok4DSL/hardware/demo/demo.c \ + ../libsigrok4DSL/input/in_binary.c \ + ../libsigrok4DSL/input/in_vcd.c \ + ../libsigrok4DSL/input/in_wav.c \ + ../libsigrok4DSL/output/csv.c \ + ../libsigrok4DSL/output/gnuplot.c \ + ../libsigrok4DSL/output/srzip.c \ + ../libsigrok4DSL/output/vcd.c \ + ../libsigrok4DSL/hardware/DSL/dslogic.c \ + ../libsigrok4DSL/hardware/common/usb.c \ + ../libsigrok4DSL/hardware/common/ezusb.c \ + ../libsigrok4DSL/trigger.c \ + ../libsigrok4DSL/dsdevice.c \ + ../libsigrok4DSL/hardware/DSL/dscope.c \ + ../libsigrok4DSL/hardware/DSL/command.c \ + ../libsigrok4DSL/hardware/DSL/dsl.c + +HEADERS += \ + ../libsigrok4DSL/version.h \ + ../libsigrok4DSL/proto.h \ + ../libsigrok4DSL/libsigrok-internal.h \ + ../libsigrok4DSL/libsigrok.h \ + ../libsigrok4DSL/config.h \ + ../libsigrok4DSL/hardware/DSL/command.h \ + ../libsigrok4DSL/hardware/DSL/dsl.h + +decoders { +DEFINES += ENABLE_DECODE +SOURCES += \ + ../DSView/pv/data/decoderstack.cpp \ + ../DSView/pv/data/decode/rowdata.cpp \ + ../DSView/pv/data/decode/row.cpp \ + ../DSView/pv/data/decode/decoder.cpp \ + ../DSView/pv/data/decode/annotation.cpp \ + ../DSView/pv/view/decodetrace.cpp \ + ../DSView/pv/prop/binding/decoderoptions.cpp \ + ../DSView/pv/dock/protocoldock.cpp \ + ../DSView/pv/dialogs/protocollist.cpp \ + ../DSView/pv/dialogs/protocolexp.cpp \ + ../DSView/pv/widgets/decodermenu.cpp \ + ../DSView/pv/widgets/decodergroupbox.cpp \ + ../DSView/pv/data/decodermodel.cpp + +HEADERS += \ + ../DSView/pv/data/decoderstack.h \ + ../DSView/pv/data/decode/rowdata.h \ + ../DSView/pv/data/decode/row.h \ + ../DSView/pv/data/decode/decoder.h \ + ../DSView/pv/data/decode/annotation.h \ + ../DSView/pv/view/decodetrace.h \ + ../DSView/pv/prop/binding/decoderoptions.h \ + ../DSView/pv/dock/protocoldock.h \ + ../DSView/pv/dialogs/protocollist.h \ + ../DSView/pv/dialogs/protocolexp.h \ + ../DSView/pv/widgets/decodermenu.h \ + ../DSView/pv/widgets/decodergroupbox.h \ + ../DSView/pv/data/decodermodel.h + + +#unix:!macx { +#}else{ +SOURCES += \ + #../libsigrokdecode4DSL/type_logic.c \ + ../libsigrokdecode4DSL/type_decoder.c \ + ../libsigrokdecode4DSL/srd.c \ + ../libsigrokdecode4DSL/module_sigrokdecode.c \ + ../libsigrokdecode4DSL/decoder.c \ + ../libsigrokdecode4DSL/error.c \ + ../libsigrokdecode4DSL/exception.c \ + ../libsigrokdecode4DSL/instance.c \ + ../libsigrokdecode4DSL/log.c \ + ../libsigrokdecode4DSL/session.c \ + ../libsigrokdecode4DSL/util.c \ + ../libsigrokdecode4DSL/version.c + +HEADERS += \ + ../libsigrokdecode4DSL/libsigrokdecode-internal.h \ + ../libsigrokdecode4DSL/libsigrokdecode.h \ + ../libsigrokdecode4DSL/config.h \ + ../libsigrokdecode4DSL/version.h +#} +} + +FORMS += + +RESOURCES += \ + ../DSView/DSView.qrc \ + ../DSView/themes/breeze.qrc \ + language.qrc + +ICON = DSView.icns + +MOC_DIR = ../../DSView-build/MOC_DIR +RCC_DIR = ../../DSView-build/RCC_DIR +UI_HEADERS_DIR = ../../DSView-build/UI_HEADERS_DIR +UI_SOURCES_DIR = ../../DSView-build/UI_SOURCES_DIR +UI_DIR = ../../DSView-build/UI_DIR +OBJECTS_DIR = ../../DSView-build/OBJECTS_DIR +DESTDIR = ../../DSView-build/bin diff --git a/qtpro/DSView.icns b/qtpro/DSView.icns new file mode 100644 index 00000000..d98f5351 Binary files /dev/null and b/qtpro/DSView.icns differ diff --git a/qtpro/DSView.pro b/qtpro/DSView.pro new file mode 100644 index 00000000..3ee34059 --- /dev/null +++ b/qtpro/DSView.pro @@ -0,0 +1,410 @@ +#------------------------------------------------- +# +# Project created by QtCreator 2013-07-24T17:32:25 +# +#------------------------------------------------- + +QT += core gui + +win32{ +QT += winextras +QT += svg +QMAKE_LFLAGS += -static +}else{ +CONFIG -= lib_bundle +CONFIG += app_bundle +} + +macx { +QT += svg +#QMAKE_MACOSX_DEPLOYMENT_TARGET = 10.12 +QMAKE_CXXFLAGS += -fvisibility=hidden +QMAKE_CXXFLAGS += -fvisibility-inlines-hidden +} + +CONFIG += exceptions +CONFIG += object_parallel_to_source + +#QT += core5compat +#CONFIG += console thread + +CONFIG += c++11 +QT += widgets +QMAKE_CFLAGS_ISYSTEM = -I + +CONFIG += release + +TARGET = DSView +TEMPLATE = app + +TRANSLATIONS = my_CN.ts + +CONFIG += decoders +DEFINES += decoders + +win32:{ +#INCLUDEPATH += C:\Qt\Tools\mingw730_32\i686-w64-mingw32\include +INCLUDEPATH += D:\msys64\mingw32\lib\glib-2.0\include +INCLUDEPATH += D:\msys64\mingw32\include\glib-2.0 +INCLUDEPATH += D:\msys64\mingw32\include +INCLUDEPATH += D:\msys64\mingw32\include\libusb-1.0 +INCLUDEPATH += C:\Python\Python310-32\include +INCLUDEPATH += D:\msys64\mingw32\include\boost +INCLUDEPATH += .. + +LIBS += D:\msys64\mingw32\lib\libglib-2.0.a +LIBS += D:\msys64\mingw32\lib\libzip.a +LIBS += D:\msys64\mingw32\lib\libusb-1.0.a +LIBS += D:\msys64\mingw32\lib\libz.a +LIBS += D:\msys64\mingw32\lib\libfftw3.a +LIBS += C:\Python\Python310-32\libs\python310.lib +} + +unix:!macx { +INCLUDEPATH += /usr/include/glib-2.0 +INCLUDEPATH += /usr/lib/x86_64-linux-gnu/glib-2.0/include +INCLUDEPATH += /usr/include/libusb-1.0 +INCLUDEPATH += /usr/include/boost +INCLUDEPATH += /usr/include/python3.8 +INCLUDEPATH += .. + +LIBS += /usr/lib/x86_64-linux-gnu/libglib-2.0.so +LIBS += /usr/lib/x86_64-linux-gnu/libusb-1.0.so +LIBS += /usr/lib/x86_64-linux-gnu/libpython3.8.so +LIBS += /usr/lib/x86_64-linux-gnu/libfftw3.so +LIBS += /usr/local/lib/libz.so.1.2.11 +LIBS += /usr/local/lib/libzip.so.5.4 +} + +macx: { +INCLUDEPATH += /usr/local/include/ +INCLUDEPATH += /usr/local/include/glib-2.0 +INCLUDEPATH += /usr/local/lib/glib-2.0/include +INCLUDEPATH += /usr/local/include/libusb-1.0 +INCLUDEPATH += /usr/local/include/boost +INCLUDEPATH += /Library/Frameworks/Python.framework/Versions/3.4/include/python3.4m +INCLUDEPATH += .. + +LIBS += /usr/local/lib/libglib-2.0.dylib +LIBS += /usr/local/lib/libusb-1.0.dylib +#LIBS += /usr/local/lib/libboost_atomic-mt.a +#LIBS += /usr/local/lib/libboost_thread-mt.a +#LIBS += /usr/local/lib/libboost_system-mt.a +#LIBS += /usr/local/lib/libboost_filesystem-mt.a +LIBS += /Library/Frameworks/Python.framework/Versions/3.4/lib/libpython3.4.dylib +LIBS += /usr/local/lib/libfftw3.a +} + +SOURCES += \ + ../DSView/main.cpp \ + ../DSView/pv/sigsession.cpp \ + ../DSView/pv/mainwindow.cpp \ + ../DSView/pv/devicemanager.cpp \ + ../DSView/pv/data/snapshot.cpp \ + ../DSView/pv/data/signaldata.cpp \ + ../DSView/pv/data/logicsnapshot.cpp \ + ../DSView/pv/data/logic.cpp \ + ../DSView/pv/data/analogsnapshot.cpp \ + ../DSView/pv/data/analog.cpp \ + ../DSView/pv/dialogs/deviceoptions.cpp \ + ../DSView/pv/prop/property.cpp \ + ../DSView/pv/prop/int.cpp \ + ../DSView/pv/prop/enum.cpp \ + ../DSView/pv/prop/double.cpp \ + ../DSView/pv/prop/bool.cpp \ + ../DSView/pv/prop/binding/binding.cpp \ + ../DSView/pv/toolbars/samplingbar.cpp \ + ../DSView/pv/view/viewport.cpp \ + ../DSView/pv/view/view.cpp \ + ../DSView/pv/view/timemarker.cpp \ + ../DSView/pv/view/signal.cpp \ + ../DSView/pv/view/ruler.cpp \ + ../DSView/pv/view/logicsignal.cpp \ + ../DSView/pv/view/header.cpp \ + ../DSView/pv/view/cursor.cpp \ + ../DSView/pv/view/analogsignal.cpp \ + ../DSView/pv/prop/binding/deviceoptions.cpp \ + ../DSView/pv/toolbars/trigbar.cpp \ + ../DSView/pv/toolbars/filebar.cpp \ + ../DSView/pv/dock/triggerdock.cpp \ + ../DSView/pv/dock/measuredock.cpp \ + ../DSView/pv/dock/searchdock.cpp \ + ../DSView/pv/toolbars/logobar.cpp \ + ../DSView/pv/data/groupsnapshot.cpp \ + ../DSView/pv/view/groupsignal.cpp \ + ../DSView/pv/data/group.cpp \ + ../DSView/pv/dialogs/about.cpp \ + ../DSView/pv/dialogs/search.cpp \ + ../DSView/pv/data/dsosnapshot.cpp \ + ../DSView/pv/data/dso.cpp \ + ../DSView/pv/view/dsosignal.cpp \ + ../DSView/pv/view/dsldial.cpp \ + ../DSView/pv/dock/dsotriggerdock.cpp \ + ../DSView/pv/view/trace.cpp \ + ../DSView/pv/view/selectableitem.cpp \ + ../DSView/pv/widgets/fakelineedit.cpp \ + ../DSView/pv/prop/string.cpp \ + ../DSView/pv/device/sessionfile.cpp \ + ../DSView/pv/device/inputfile.cpp \ + ../DSView/pv/device/file.cpp \ + ../DSView/pv/device/devinst.cpp \ + ../DSView/pv/dialogs/storeprogress.cpp \ + ../DSView/pv/storesession.cpp \ + ../DSView/pv/view/devmode.cpp \ + ../DSView/pv/device/device.cpp \ + ../DSView/pv/dialogs/waitingdialog.cpp \ + ../DSView/pv/dialogs/dsomeasure.cpp \ + ../DSView/pv/dialogs/calibration.cpp \ + ../DSView/pv/dialogs/fftoptions.cpp \ + ../DSView/dsapplication.cpp \ + ../DSView/pv/toolbars/titlebar.cpp \ + ../DSView/pv/mainframe.cpp \ + ../DSView/pv/widgets/border.cpp \ + ../DSView/pv/dialogs/dsmessagebox.cpp \ + ../DSView/pv/dialogs/shadow.cpp \ + ../DSView/pv/dialogs/dsdialog.cpp \ + ../DSView/pv/dialogs/interval.cpp \ + ../DSView/pv/prop/binding/probeoptions.cpp \ + ../DSView/pv/view/xcursor.cpp \ + ../DSView/pv/view/viewstatus.cpp \ + ../DSView/pv/dialogs/lissajousoptions.cpp \ + ../DSView/pv/view/lissajoustrace.cpp \ + ../DSView/pv/view/spectrumtrace.cpp \ + ../DSView/pv/data/spectrumstack.cpp \ + ../DSView/pv/view/mathtrace.cpp \ + ../DSView/pv/dialogs/mathoptions.cpp \ + ../DSView/pv/data/mathstack.cpp \ + ../DSView/pv/dialogs/regionoptions.cpp \ + ../DSView/pv/ZipMaker.cpp \ + ../DSView/pv/data/decode/AnnotationResTable.cpp \ + ../DSView/pv/ui/msgbox.cpp \ + ../DSView/pv/ui/dscombobox.cpp \ + ../DSView/pv/dock/protocolitemlayer.cpp \ + ../DSView/pv/config/appconfig.cpp \ + ../DSView/pv/dsvdef.cpp \ + ../DSView/pv/minizip/zip.c \ + ../DSView/pv/minizip/unzip.c \ + ../DSView/pv/minizip/ioapi.c \ + ../DSView/pv/dialogs/applicationpardlg.cpp \ + ../DSView/pv/appcontrol.cpp \ + ../DSView/pv/eventobject.cpp \ + ../DSView/pv/dstimer.cpp + +HEADERS += \ + ../DSView/pv/extdef.h \ + ../DSView/config.h \ + ../DSView/pv/sigsession.h \ + ../DSView/pv/mainwindow.h \ + ../DSView/pv/devicemanager.h \ + ../DSView/pv/data/snapshot.h \ + ../DSView/pv/data/signaldata.h \ + ../DSView/pv/data/logicsnapshot.h \ + ../DSView/pv/data/logic.h \ + ../DSView/pv/data/analogsnapshot.h \ + ../DSView/pv/data/analog.h \ + ../DSView/pv/dialogs/deviceoptions.h \ + ../DSView/pv/prop/property.h \ + ../DSView/pv/prop/int.h \ + ../DSView/pv/prop/enum.h \ + ../DSView/pv/prop/double.h \ + ../DSView/pv/prop/bool.h \ + ../DSView/pv/prop/binding/deviceoptions.h \ + ../DSView/pv/prop/binding/binding.h \ + ../DSView/pv/toolbars/samplingbar.h \ + ../DSView/pv/view/viewport.h \ + ../DSView/pv/view/view.h \ + ../DSView/pv/view/timemarker.h \ + ../DSView/pv/view/signal.h \ + ../DSView/pv/view/ruler.h \ + ../DSView/pv/view/logicsignal.h \ + ../DSView/pv/view/header.h \ + ../DSView/pv/view/cursor.h \ + ../DSView/pv/view/analogsignal.h \ + ../DSView/pv/toolbars/trigbar.h \ + ../DSView/pv/toolbars/filebar.h \ + ../DSView/pv/dock/triggerdock.h \ + ../DSView/pv/dock/measuredock.h \ + ../DSView/pv/dock/searchdock.h \ + ../DSView/pv/toolbars/logobar.h \ + ../DSView/pv/data/groupsnapshot.h \ + ../DSView/pv/view/groupsignal.h \ + ../DSView/pv/data/group.h \ + ../DSView/pv/dialogs/about.h \ + ../DSView/pv/dialogs/search.h \ + ../DSView/pv/data/dso.h \ + ../DSView/pv/data/dsosnapshot.h \ + ../DSView/pv/view/dsosignal.h \ + ../DSView/pv/view/dsldial.h \ + ../DSView/pv/dock/dsotriggerdock.h \ + ../DSView/pv/view/trace.h \ + ../DSView/pv/view/selectableitem.h \ + ../DSView/pv/widgets/fakelineedit.h \ + ../DSView/pv/prop/string.h \ + ../DSView/pv/device/sessionfile.h \ + ../DSView/pv/device/inputfile.h \ + ../DSView/pv/device/file.h \ + ../DSView/pv/device/devinst.h \ + ../DSView/pv/dialogs/storeprogress.h \ + ../DSView/pv/storesession.h \ + ../DSView/pv/view/devmode.h \ + ../DSView/pv/device/device.h \ + ../DSView/pv/dialogs/waitingdialog.h \ + ../DSView/pv/dialogs/dsomeasure.h \ + ../DSView/pv/dialogs/calibration.h \ + ../DSView/pv/dialogs/fftoptions.h \ + ../DSView/dsapplication.h \ + ../DSView/pv/toolbars/titlebar.h \ + ../DSView/pv/mainframe.h \ + ../DSView/pv/widgets/border.h \ + ../DSView/pv/dialogs/dsmessagebox.h \ + ../DSView/pv/dialogs/shadow.h \ + ../DSView/pv/dialogs/dsdialog.h \ + ../DSView/pv/dialogs/interval.h \ + ../DSView/config.h \ + ../libsigrok4DSL/config.h \ + ../DSView/pv/prop/binding/probeoptions.h \ + ../libsigrok4DSL/hardware/demo/demo.h \ + ../DSView/pv/view/xcursor.h \ + ../DSView/pv/view/viewstatus.h \ + ../DSView/pv/dialogs/lissajousoptions.h \ + ../DSView/pv/view/lissajoustrace.h \ + ../DSView/pv/view/spectrumtrace.h \ + ../DSView/pv/data/spectrumstack.h \ + ../DSView/pv/view/mathtrace.h \ + ../DSView/pv/dialogs/mathoptions.h \ + ../DSView/pv/data/mathstack.h \ + ../DSView/pv/dialogs/regionoptions.h \ + ../DSView/mystyle.h \ + ../DSView/pv/ZipMaker.h \ + ../DSView/pv/data/decode/AnnotationResTable.h \ + ../DSView/pv/ui/msgbox.h \ + ../DSView/pv/ui/dscombobox.h \ + ../DSView/pv/dock/protocolitemlayer.h \ + ../DSView/pv/config/appconfig.h \ + ../DSView/pv/dsvdef.h \ + ../DSView/pv/minizip/zip.h \ + ../DSView/pv/minizip/unzip.h \ + ../DSView/pv/minizip/ioapi.h \ + ../DSView/pv/dialogs/applicationpardlg.h \ + ../DSView/pv/appcontrol.h \ + ../DSView/pv/eventobject.h \ + ../DSView/pv/dstimer.h + +SOURCES += \ + ../libsigrok4DSL/version.c \ + ../libsigrok4DSL/strutil.c \ + ../libsigrok4DSL/std.c \ + ../libsigrok4DSL/session_file.c \ + ../libsigrok4DSL/session_driver.c \ + ../libsigrok4DSL/session.c \ + ../libsigrok4DSL/log.c \ + ../libsigrok4DSL/hwdriver.c \ + ../libsigrok4DSL/error.c \ + ../libsigrok4DSL/backend.c \ + ../libsigrok4DSL/output/output.c \ + ../libsigrok4DSL/input/input.c \ + ../libsigrok4DSL/hardware/demo/demo.c \ + ../libsigrok4DSL/input/in_binary.c \ + ../libsigrok4DSL/input/in_vcd.c \ + ../libsigrok4DSL/input/in_wav.c \ + ../libsigrok4DSL/output/csv.c \ + ../libsigrok4DSL/output/gnuplot.c \ + ../libsigrok4DSL/output/srzip.c \ + ../libsigrok4DSL/output/vcd.c \ + ../libsigrok4DSL/hardware/DSL/dslogic.c \ + ../libsigrok4DSL/hardware/common/usb.c \ + ../libsigrok4DSL/hardware/common/ezusb.c \ + ../libsigrok4DSL/trigger.c \ + ../libsigrok4DSL/dsdevice.c \ + ../libsigrok4DSL/hardware/DSL/dscope.c \ + ../libsigrok4DSL/hardware/DSL/command.c \ + ../libsigrok4DSL/hardware/DSL/dsl.c + +HEADERS += \ + ../libsigrok4DSL/version.h \ + ../libsigrok4DSL/proto.h \ + ../libsigrok4DSL/libsigrok-internal.h \ + ../libsigrok4DSL/libsigrok.h \ + ../libsigrok4DSL/config.h \ + ../libsigrok4DSL/hardware/DSL/command.h \ + ../libsigrok4DSL/hardware/DSL/dsl.h + +decoders { +DEFINES += ENABLE_DECODE +SOURCES += \ + ../DSView/pv/data/decoderstack.cpp \ + ../DSView/pv/data/decode/rowdata.cpp \ + ../DSView/pv/data/decode/row.cpp \ + ../DSView/pv/data/decode/decoder.cpp \ + ../DSView/pv/data/decode/annotation.cpp \ + ../DSView/pv/view/decodetrace.cpp \ + ../DSView/pv/prop/binding/decoderoptions.cpp \ + ../DSView/pv/dock/protocoldock.cpp \ + ../DSView/pv/dialogs/protocollist.cpp \ + ../DSView/pv/dialogs/protocolexp.cpp \ + ../DSView/pv/widgets/decodermenu.cpp \ + ../DSView/pv/widgets/decodergroupbox.cpp \ + ../DSView/pv/data/decodermodel.cpp + +HEADERS += \ + ../DSView/pv/data/decoderstack.h \ + ../DSView/pv/data/decode/rowdata.h \ + ../DSView/pv/data/decode/row.h \ + ../DSView/pv/data/decode/decoder.h \ + ../DSView/pv/data/decode/annotation.h \ + ../DSView/pv/view/decodetrace.h \ + ../DSView/pv/prop/binding/decoderoptions.h \ + ../DSView/pv/dock/protocoldock.h \ + ../DSView/pv/dialogs/protocollist.h \ + ../DSView/pv/dialogs/protocolexp.h \ + ../DSView/pv/widgets/decodermenu.h \ + ../DSView/pv/widgets/decodergroupbox.h \ + ../DSView/pv/data/decodermodel.h + + +#unix:!macx { +#}else{ +SOURCES += \ + #../libsigrokdecode4DSL/type_logic.c \ + ../libsigrokdecode4DSL/type_decoder.c \ + ../libsigrokdecode4DSL/srd.c \ + ../libsigrokdecode4DSL/module_sigrokdecode.c \ + ../libsigrokdecode4DSL/decoder.c \ + ../libsigrokdecode4DSL/error.c \ + ../libsigrokdecode4DSL/exception.c \ + ../libsigrokdecode4DSL/instance.c \ + ../libsigrokdecode4DSL/log.c \ + ../libsigrokdecode4DSL/session.c \ + ../libsigrokdecode4DSL/util.c \ + ../libsigrokdecode4DSL/version.c + +HEADERS += \ + ../libsigrokdecode4DSL/libsigrokdecode-internal.h \ + ../libsigrokdecode4DSL/libsigrokdecode.h \ + ../libsigrokdecode4DSL/config.h \ + ../libsigrokdecode4DSL/version.h +#} +} + + +RESOURCES += \ + ../DSView/DSView.qrc \ + ../DSView/themes/breeze.qrc \ + language.qrc + +# make app logo on windows + +win32 { +RC_FILE += ../applogo.rc +}else{ +ICON = DSView.icns +} + +MOC_DIR = ../../DSView-build/MOC_DIR +RCC_DIR = ../../DSView-build/RCC_DIR +UI_HEADERS_DIR = ../../DSView-build/UI_HEADERS_DIR +UI_SOURCES_DIR = ../../DSView-build/UI_SOURCES_DIR +UI_DIR = ../../DSView-build/UI_DIR +OBJECTS_DIR = ../../DSView-build/OBJECTS_DIR +DESTDIR = ../../DSView-build/bin + diff --git a/qtpro/DSView.pro.user b/qtpro/DSView.pro.user new file mode 100644 index 00000000..99eacae7 --- /dev/null +++ b/qtpro/DSView.pro.user @@ -0,0 +1,334 @@ + + + + + + EnvironmentId + {e94b86d6-950b-4ba2-9fb4-d7b4ccc4fe74} + + + ProjectExplorer.Project.ActiveTarget + 0 + + + ProjectExplorer.Project.EditorSettings + + true + false + true + + Cpp + + CppGlobal + + + + QmlJS + + QmlJSGlobal + + + 2 + UTF-8 + false + 4 + false + 80 + true + true + 1 + true + false + 0 + true + true + 0 + 8 + true + 1 + true + true + true + false + + + + ProjectExplorer.Project.PluginSettings + + + true + true + true + true + + 0 + true + + true + + true + Builtin.TidyAndClazy + 4 + + + + true + + + + + ProjectExplorer.Project.Target.0 + + 桌面 + 桌面 + {ce867f0c-ef0e-4256-b807-c2554ad78bbf} + 1 + 0 + 0 + + /home/lala/workdir/DSView/build-DSView-unknown-Debug + + + true + QtProjectManager.QMakeBuildStep + true + + false + false + false + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Debug + Qt4ProjectManager.Qt4BuildConfiguration + 2 + + + /home/lala/workdir/DSView/build-DSView-unknown-Release + + + true + QtProjectManager.QMakeBuildStep + false + + false + false + false + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Release + Qt4ProjectManager.Qt4BuildConfiguration + 0 + + + /home/lala/workdir/DSView/build-DSView-unknown-Profile + + + true + QtProjectManager.QMakeBuildStep + true + + false + true + false + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Profile + Qt4ProjectManager.Qt4BuildConfiguration + 0 + + 3 + + + 0 + Deploy + Deploy + ProjectExplorer.BuildSteps.Deploy + + 1 + ProjectExplorer.DefaultDeployConfiguration + + 1 + + + dwarf + + cpu-cycles + + + 250 + + -e + cpu-cycles + --call-graph + dwarf,4096 + -F + 250 + + -F + true + 4096 + false + false + 1000 + + true + + false + false + false + false + true + 0.01 + 10 + true + kcachegrind + 1 + 25 + + 1 + true + false + true + valgrind + + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + + 2 + + Qt4ProjectManager.Qt4RunConfiguration:/home/lala/workdir/DSView/qtpro/DSView.pro + /home/lala/workdir/DSView/qtpro/DSView.pro + + false + + false + true + true + false + false + true + + /home/lala/workdir/DSView-build/bin + + 1 + + + + ProjectExplorer.Project.TargetCount + 1 + + + ProjectExplorer.Project.Updater.FileVersion + 22 + + + Version + 22 + + diff --git a/qtpro/language.qrc b/qtpro/language.qrc new file mode 100644 index 00000000..e0eacdf8 --- /dev/null +++ b/qtpro/language.qrc @@ -0,0 +1,6 @@ + + + my_25.qm + qt_25.qm + + diff --git a/qtpro/my_25.qm b/qtpro/my_25.qm new file mode 100644 index 00000000..2430370f Binary files /dev/null and b/qtpro/my_25.qm differ diff --git a/qtpro/my_CN.ts b/qtpro/my_CN.ts new file mode 100644 index 00000000..849c5c17 --- /dev/null +++ b/qtpro/my_CN.ts @@ -0,0 +1,2579 @@ + + + + + About + + About + 关于 + + + + DSApplication + + + + Application Error + 应用程序错误 + + + + An unexpected error occurred + 未知的错误 + + + + File + + &Load Session... + 导入配置(&L)... + + + S&tore Session... + 存储配置(&T)... + + + &Load... + 导入(&L)... + + + S&tore... + 导出(&T)... + + + &Default... + 载入默认(&D)... + + + &Open... + 打开(&O)... + + + &Save... + 保存(&S)... + + + &Export... + 导出(&E)... + + + &Capture... + 截屏(&C)... + + + &About... + 关于(&A)... + + + &Manual + 手册(&M) + + + &Bug Report + 报告问题(&B) + + + &Wiki + &Wiki页面 + + + + Math + + &FFT + &FFT + + + + QObject + + + Hz + + + + + Sampling + + &Single + 单次 + + + &Repetitive + 重复 + + + + pv::MainFrame + + + Document + 文档 + + + + Not Show Again + 不再显示 + + + + Ignore + 忽略 + + + + Open + 打开 + + + + pv::MainWindow + + + + Protocol + 协议 + + + + + + + Trigger Setting... + 触发设置... + + + + + Measurement + 测量 + + + + + Search... + 搜索... + + + + + + + + Set Default Device failed + 启用默认设备失败 + + + + Hotplug failed + 热插拔失败 + + + + Attension + 注意 + + + + Current loading file has an old format. This will lead to a slow loading speed. Please resave it after loaded. + 正在载入老版本格式的文件,载入速度可能较慢,请打开后重新存为新的文件格式。 + + + + Failed to capture file data! + 无法载入文件数据! + + + + Failed to load + 无法加载 + + + + + Capture failed + 采集失败 + + + + Hardware Operation Failed + 硬件操作失败 + + + + Please replug device to refresh hardware configuration! + 请重新插拔硬件来刷新硬件配置! + + + + Data Error + 数据错误 + + + + the received data are not consist with pre-defined test data! + 接收的数据和预定义的测试数据不一致! + + + + 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 + 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 + + + + Trigger + 触发 + + + + Trigger setted on multiple channels! Capture will Only triggered when all setted channels fullfill at one sample + 同时设置了多个通道的简单触发!只有在同一个采样点所有被设置通道的触发条件同时满足时才会触发。 + + + + Not Show Again + 不再显示 + + + Not Show again + 不再显示 + + + + Clear Trig + 清除触发 + + + + Continue + 继续 + + + the received data are not consist with pre-defined test data! + + 接收的数据和预定义的测试数据不一致! + + + 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 + + 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 + + + + Packet Error + 数据包错误 + + + + the content of received packet are not expected! + 接收到了非法格式的数据包! + + + + Data Overflow + 数据溢出 + + + + USB bandwidth can not support current sample rate! +Please reduce the sample rate! + 当前的USB带宽受限,请降低采样频率或者减少采样通道,重新开始采样! + + + + Undefined Error + 未定义的错误类型 + + + + Not expected error! + 未知错误! + + + the receive data are not consist with pre-defined test data + 接收的数据和预定义的数据不一致 + + + + Malloc Error + 内存申请错误 + + + + Memory is not enough for this sample! +Please reduce the sample depth! + 无法申请到足够的内存完成此次采样!请减少采样深度后重试! + + + Hardware Connect Failed + 硬件连接问题 + + + Please check hardware connection! + 请检查硬件连接! + + + RLE Mode Warning + RLE压缩模式警告 + + + Hardware buffer is full! +Actually received samples is less than setted sample depth! + 硬件缓存已满!实际收到的采样个数少于设置的采样深度! + + + + Save As + 另存为 + + + + %1 Files (*.%2);;All Files (*) + + + + Save File + 保存文件 + + + File Error + 文件错误 + + + Couldn't open session file! + 无法打开配置文件! + + + + Session Error + 配置错误 + + + + Session File is not compatible with current device or mode! + 配置文件和当前的设备或者模式不兼容! + + + Couldn't open session file to write! + 无法写入配置文件! + + + + pv::SigSession + + Exporting data... It can take a while. + 正在导出数据...请稍等。 + + + Cancel + 取消 + + + Save Capture to File... It can take a while. + 正在保存文件...请稍等. + + + + No probes enabled. + 没有使能的通道. + + + + pv::StoreSession + + + DSView does not currently supportfile saving for multiple data types. + DSView暂不支持同时保存多种类型的数据。 + + + + + + + No data to save. + 没有数据需要保存. + + + + Save File + 保存文件 + + + + DSView Data (*.dsl) + DSView Data (*.dsl) + + + + .dsl + .dsl + + + + Generate temp file failed. + 生成临时文件失败。 + + + + + + Failed to create zip file. Please check write permission of this path. + 无法创建压缩文件,请确认此文件路径的写入权限。 + + + + + Failed to create zip file. Malloc error. + 无法创建压缩文件,内存申请错误。 + + + Malloc failed. + 内存分配失败。 + + + zip_open error. + zip_open错误 + + + sr_session_append error + sr_session_append错误 + + + zip_close error + zip_close错误 + + + + DSView does not currently supportfile export for multiple data types. + DSView暂不支持同时保存多种类型的数据。 + + + + Export Data + 导出数据 + + + + . + . + + + + Invalid export format. + 无效的导出格式。 + + + + data type don't support. + 数据类型不支持。 + + + + xbuffer malloc failed. + xbuffer内存分配失败。 + + + DSView currently only has support for storing a single data stream. + DSView目前只支持保存单个数据流. + + + DSView currently only has support for storing a logic data. + DSView目前只支持保存LA模式下面的数据. + + + No snapshots to save. + 没有截图需要保存. + + + Error while saving. + 保存文件错误. + + + + pv::data::DecoderStack + + + One or more required channels have not been specified + 没有指定协议需要的通道 + + + + At least one of selected channels are not enabled. + 协议使用中的通道未被使能。 + + + Decoder reported an error + 协议分析仪遇到问题 + + + + Failed to create decoder instance + 无法创建协议解析器 + + + + pv::data::MathStack + + Rectangle + 矩形窗 + + + Hann + 汉宁窗 + + + Hamming + 海明窗 + + + Blackman + 布莱克曼窗 + + + Flat_top + 平顶窗 + + + + + + + + + pv::data::SpectrumStack + + + Rectangle + 矩形窗 + + + + Hann + 汉宁窗 + + + + Hamming + 海明窗 + + + + Blackman + 布莱克曼窗 + + + + Flat_top + 平顶窗 + + + + pv::device::DevInst + + + Failed to start session. + 无法开始采样,请检查驱动程序和硬件连接. + + + + pv::device::Device + + + Failed to use device. + 无法使用指定设备. + + + + pv::device::InputFile + + Failed to add session device. + 无法添加指定设备. + + + + Not a valid DSView data file. + 非法的数据文件。 + + + No supported input formats available. + 没有可用的输入格式。 + + + Error: no matching input module found. + 错误:没有找到相应的输入模块。 + + + + + + Failed to load file + 无法加载指定文件 + + + + Failed to allocate input module. + 无法指定输入模块. + + + + pv::device::SessionFile + + + Failed to open file. + + 无法打开指定文件. + + + + Failed to start session. + 无法开始采样,请检查驱动程序和硬件连接. + + + + pv::dialogs::About + + + <font size=24>DSView %1 (%2)</font><br /> + <font size=24>DSView %1 (%2)</font><br /> + + + Website: <a href="%1" style="color:#C0C0C0">%1</a><br />Gitbub: <a href="%2" style="color:#C0C0C0">%2</a><br /><br /><br /> + 网站: <a href="%1" style="color:#C0C0C0">%1</a><br />Gitbub: <a href="%2" style="color:#C0C0C0">%2</a><br /><br /><br /> + + + + <font size=16>Special Thanks</font><br /><a href="%1" style="color:#C0C0C0">All backers on kickstarter</a><br /><a href="%2" style="color:#C0C0C0">All members of Sigrok project</a><br />All contributors of all open-source projects</a><br /><br /><br /> + <font size=16>特别感谢</font><br /><a href="%1" style="color:#C0C0C0">我们众筹项目的所有支持者</a><br /><a href="%2" style="color:#C0C0C0"> Sigrok项目的所有成员</a><br />所有开源项目的贡献者</a><br /><br /><br /> + + + <font size=16>Special Thanks</font><br /><a href="%1" style="color:#C0C0C0">All backers on kickstarter</a><br /><a href="%1" style="color:#C0C0C0">All members of Sigrok project</a><br />All contributors of open-source projects</a><br /><br /><br /> + <font size=16>特别感谢</font><br /><a href="%1" style="color:#C0C0C0">我们众筹项目的所有支持者</a><br /><a href="%1" style="color:#C0C0C0"> Sigrok项目的所有成员</a><br />所有开源项目的贡献者</a><br /><br /><br /> + + + + Website: <a href="%1" style="color:#C0C0C0">%1</a><br />Gitbub: <a href="%2" style="color:#C0C0C0">%2</a><br />Copyright:<a href="%3" style="color:#C0C0C0">%3</a><br /><br /><br /> + 官网: <a href="%1" style="color:#C0C0C0">%1</a><br />Gitbub: <a href="%2" style="color:#C0C0C0">%2</a><br />版权:<a href="%3" style="color:#C0C0C0">%3</a><br /><br /><br /> + + + + © DreamSourceLab. All rights reserved. + ©深圳市梦源科技有限公司 版权所有 + + + + <font size=16>Changelogs</font><br /> + <font size=16>更新日志</font><br /> + + + + About + 关于 + + + + pv::dialogs::Calibration + + + VGAIN + 增益 + + + + VOFF + 偏置 + + + + VCOMB + 单通道增益 + + + + Save + 保存 + + + + Abort + 放弃 + + + + Reset + 重置 + + + + Exit + 退出 + + + + Manual Calibration + 手动校准 + + + + + + Channel + 通道 + + + + Save calibration results... It can take a while. + 正在保持校准结果...请稍等。 + + + + Reload last calibration results... It can take a while. + 重新载入上一次的校准结果...请稍等。 + + + + Attention + 注意 + + + + All calibration settings will become the defualt values! + 恢复所有的校准参数到默认状态! + + + + Ok + 确定 + + + Save Calibration Result... It can take a while. + 正在保存校准结果...请稍等. + + + + + + Cancel + 取消 + + + Reset Calibration Result... It can take a while. + 正在重置校准设置...请稍等. + + + + pv::dialogs::DSMessageBox + + + Message + 消息 + + + + pv::dialogs::DeviceOptions + + Configure Device + 配置设备 + + + + Mode + 模式 + + + + + Channels + 通道 + + + Zero Adjustment + 自动校准 + + + + Auto Calibration + 自动校准 + + + + Manual Calibration + 手动校准 + + + + Device Options + 设备选项 + + + + Attention + 注意 + + + + All channel disabled! Please enable at least one channel. + 已关闭所有通道!需要至少使能一个通道。 + + + + Operation Mode + 运行模式 + + + + Enable All + 打开所有通道 + + + + Disable All + 关闭所有通道 + + + + + Information + 提示 + + + + Current mode only suppport max + 当前模式最大只支持 + + + + channels! + 个通道! + + + + Calibration + 校准 + + + Undefined + 未定义 + + + + Enable: + 启用: + + + Zero adjustment program will be started. Please keep all channels out of singal input. It can take a while! + 将启动调零程序,请勿连接探头,保持输入处于悬空状态,调零期间请耐心等待! + + + Zero adjustment program will be started. This may take a few minutes! + 即将启动零点校准程序.这个过程可能需要花几分钟完成! + + + + + + Ok + 确定 + + + + Auto Calibration program will be started. Please keep all channels out of singal input. It can take a while! + 将开启自动校准程序,请拔下探头,保持所有通道处于悬空状态。 + + + + Cancel + 取消 + + + + pv::dialogs::DsoMeasure + + DSO Measure Options + 示波器测量选项 + + + + Measurements + 测量 + + + + NULL + + + + + Freq + 频率 + + + + Period + 周期 + + + + +Duty + +占空比 + + + + -Duty + -占空比 + + + + +Count + +脉冲数 + + + + Rise + 上升沿 + + + + Fall + 下降沿 + + + + +Width + +脉宽 + + + + -Width + -脉宽 + + + + BrstW + 突发脉宽 + + + + Ampl + 幅度 + + + + High + 高电平 + + + + Low + 低电平 + + + + RMS + 有效值 + + + + Mean + 平均值 + + + + PK-PK + 峰峰值 + + + + Max + 最大值 + + + + Min + 最小值 + + + + +Over + +过冲 + + + + -Over + -过冲 + + + + pv::dialogs::FftOptions + + + FFT Enable: + FFT使能: + + + + FFT Length: + FFT长度: + + + + Sample Interval: + 抽样间隔: + + + + FFT Source: + FFT通道: + + + + FFT Window: + FFT加窗: + + + + DC Ignored: + 忽略直流: + + + + Y-axis Mode: + Y轴模式: + + + + DBV Range: + DBV范围: + + + + FFT Options + FFT选项 + + + + pv::dialogs::Interval + + + Interval(s): + 间隔(s): + + + + Repetitive Interval + 重复间隔 + + + + pv::dialogs::LissajousOptions + + + Enable + 使能 + + + + X-axis + X轴 + + + + Y-axis + Y轴 + + + + Lissajous Options + 李萨茹图 + + + + pv::dialogs::MathOptions + + + Add + + + + + Substract + + + + + Multiply + + + + + Divide + + + + + Enable + 使能 + + + + Math Type + 运算类型 + + + + 1st Source + 第一操作数 + + + + 2nd Source + 第二操作数 + + + + Math Options + 数学运算选项 + + + + pv::dialogs::ProtocolExp + + + Comma-Separated Values (*.csv) + Comma-Separated Values (*.csv) + + + + Text files (*.txt) + Text files (*.txt) + + + + Export Format: + 导出格式: + + + + Protocol Export + 协议导出 + + + + Export Data + 导出数据 + + + + . + + + + + Export Protocol List Result... It can take a while. + 正在导出协议分析的结果...请稍等. + + + + Cancel + 取消 + + + + pv::dialogs::ProtocolList + + + Fit to Window + 适应窗口大小 + + + + Fixed + 固定 + + + + Map Zoom: + 缩放: + + + + Decoded Protocols: + 已解析的协议: + + + + Protocol List Viewer + 协议列表显示 + + + + pv::dialogs::RegionOptions + + + Start + 开始 + + + + End + 结束 + + + + Cursor + 光标 + + + + Region + 区域 + + + + pv::dialogs::Search + + Search Value: + 搜索值: + + + + X: Don't care +0: Low level +1: High level +R: Rising edge +F: Falling edge +C: Rising/Falling edge + X: 不关心 +0: 低电平 +1: 高电平 +R: 上升沿 +F: 下降沿 +C: 上升/下降沿 + + + + Search Options + 搜索选项 + + + + pv::dialogs::StoreProgress + + + Saving... + 保存... + + + + Exporting... + 导出... + + + Cancel + 取消 + + + Failed to save session. + 无法保存当前内容. + + + + Failed to save data. + 保存数据失败。 + + + + pv::dialogs::StreamOptions + + Stream Mode Options + Stream模式选项 + + + Stream Mode Active! + Stream模式已激活! + + + Buffer Mode Active! + Buffer模式已激活! + + + 16 Channels, Max 10MHz sample rate + 16通道,最大10MHz采样率 + + + 8 Channels, Max 25MHz sample rate + 8通道,最大25MHz采样率 + + + + pv::dialogs::WaitingDialog + + + Waiting + 稍等 + + + + Finished! + 完成! + + + + Save calibration Result... It can take a while. + 正在保存校准结果...请稍等. + + + + Load current setting... It can take a while. + 正在载入当前设置...请稍等. + + + Zero Adjustment + 零点校准 + + + + Auto Calibration + 自动校准 + + + Save Auto Zero Result... It can take a while. + 正在保存校准结果...请稍等. + + + + + Cancel + 取消 + + + Load Current Setting... It can take a while. + 正在载入当前设置...请稍等. + + + + pv::dock::DsoTriggerDock + + + Trigger Position: + 触发位置: + + + Trigger Hold Off Time: + 触发释抑时间: + + + + Hold Off Time: + 触发释抑时间: + + + + uS + 微秒 + + + + mS + 毫秒 + + + + S + + + + + Noise Sensitivity: + 触发灵敏度: + + + + Trigger Sources: + 触发源: + + + + Auto + 自动 + + + + Channel 0 + 通道0 + + + + Channel 1 + 通道1 + + + + Channel 0 && 1 + 通道0&&1 + + + + Channel 0 | 1 + 通道0|1 + + + Channel 0 && Channel 1 + 通道0&&通道1 + + + Channel 0 | Channel 1 + 通道0|通道1 + + + + Trigger Types: + 触发类型: + + + + Rising Edge + 上升沿触发 + + + + Falling Edge + 下降沿触发 + + + + % + + + + + + + + + + Trigger Setting Issue + 触发设置遇到问题 + + + + Change horiz trigger position failed! + 无法改变触发位置的设置! + + + + Change trigger hold off time failed! + 无法改变触发释抑时间的设置! + + + + Change trigger value sensitivity failed! + 无法改变触发灵敏度的设置! + + + + Change trigger source failed! + 无法改变触发源的设置! + + + + Change trigger channel failed! + 无法改变触发通道的设置! + + + + Change trigger type failed! + 无法改变触发类型的设置! + + + + pv::dock::MeasureDock + + + Mouse measurement + 鼠标测量 + + + + Enable floating measurement + 使能鼠标跟随测量 + + + Width: + 宽度: + + + Period: + 周期: + + + Frequency: + 频率: + + + Duty Cycle: + 占空比: + + + Cursor measurement + 光标测量 + + + Delta Samples: + 采样间隔: + + + + Cursors + 光标 + + + + + Time/Samples + 时间/采样点位置 + + + + W: + 宽度: + + + + P: + 周期: + + + + F: + 频率: + + + + D: + 占空比: + + + + Cursor Distance + 距离测量 + + + + Edges + 边沿统计 + + + + Channel + 通道 + + + + Rising/Falling/Edges + 上升沿/下降沿/所有边沿 + + + + + + + + + + + + + - + - + + + + @ + @ + + + + Information + 提示 + + + + Please insert cursor before using cursor measure. + 使用光标测量前,请先在波形窗口插入光标。 + + + + Ok + 确定 + + + Cursor + 光标 + + + + pv::dock::ProtocolDock + + + Protocol List Viewer + 协议列表显示 + + + + search + 搜索 + + + + Matching Items: + 匹配项: + + + + + Protocol Analyzer + 协议分析 + + + + Protocol Analyzer is only valid in Digital Mode! + 协议分析功能只在LA模式下有效! + + + + No Protocol Analyzer to delete! + 没有协议分析需要删除! + + + + (Out of Memory) + (内存不足) + + + + Searching... + 搜索中... + + + + Cancel + 取消 + + + + pv::dock::SearchDock + + + search + 搜索 + + + + + + + + + Search + 搜索 + + + + Search cursor at the start position! + 搜索光标已处于起始位置! + + + + + Pattern not found! + 未找到指定波形! + + + + + No Sample data! + 没有采样数据! + + + + Search Previous... + 搜索上一个... + + + + + Cancel + 取消 + + + Pattern + 模式 + + + not found! + 没有找到! + + + + Search cursor at the end position! + 搜索光标已处于结束位置! + + + + Search Next... + 搜索下一个... + + + + pv::dock::TriggerDock + + + Simple Trigger + 简单触发模式 + + + + Advanced Trigger + 高级触发模式 + + + + Trigger Position: + 触发位置: + + + + Total Trigger Stages: + 总触发等级: + + + + Or + + + + + And + + + + + + == + + + + + + != + + + + + Inv + 取反 + + + + Counter + 计数 + + + + Contiguous + 连续 + + + + + X: Don't care +0: Low level +1: High level +R: Rising edge +F: Falling edge +C: Rising/Falling edge + X: 不关心 +0: 低电平 +1: 高电平 +R: 上升沿 +F: 下降沿 +C: 上升/下降沿 + + + + Stage + 等级 + + + + Start Flag: + 开始条件: + + + + Stop Flag: + 停止条件: + + + + Clock Flag: + 时钟设置: + + + + Data Channel: + 数据通道: + + + + Data Value: + 数据值: + + + + Data Bits + 数据位宽 + + + counter + 计数 + + + + + + Serial Trigger + 串行触发 + + + + + Stage Trigger + 多级触发 + + + + % + % + + + + + Trigger + 触发 + + + + Stream Mode Don't Support Advanced Trigger! + Stream模式不支持高级触发功能! + + + Stram Mode Don't Support Advanced Trigger! + Stream模式不支持高级触发! + + + + Advanced Trigger need DSLogic Hardware Support! + 高级触发功能需要DSLogic硬件支持! + + + + pv::toolbars::FileBar + + Session + 配置 + + + + Open File + 打开文件 + + + Data Export + 数据导出 + + + No Data to Save! + 没有需要保存的数据! + + + Export Data + 导出数据 + + + File Save + 文件保存 + + + DSView currently only support saving logic data to file! + DSView目前只支持保存逻辑分析仪的数据到文件,其它模式可选择导出数据! + + + + Settings + 配置 + + + Save File + 保存文件 + + + + File + 文件 + + + + &Load... + 导入(&L)... + + + + S&tore... + 导出(&T)... + + + + &Default... + 载入默认(&D)... + + + + &Open... + 打开(&O)... + + + + &Save... + 保存(&S)... + + + + &Export... + 导出(&E)... + + + + &Capture... + 截屏(&C)... + + + + DSView Data (*.dsl) + + + + + Open Session + 打开配置文件 + + + + + DSView Session (*.dsc) + + + + + Session Load + 配置载入 + + + + Cannot find default session file for this device! + 无法找到当前设备的默认配置文件! + + + + Save Session + 保存配置文件 + + + + .dsc + + + + + pv::toolbars::LogoBar + + + Help + 帮助 + + + + &Language + 语言(&L) + + + + &About... + 关于(&A)... + + + + &Manual + 手册(&M) + + + + &Bug Report + 报告问题(&B) + + + + pv::toolbars::SamplingBar + + + run_stop_button + + + + + @ + + + + Zero Adjustment + 零点校准 + + + + (RLE) + (压缩) + + + + / div + 每格 + + + + Options + 选项 + + + + Mode + 模式 + + + + + + Stop + 停止 + + + + + Single + 单次 + + + + + Instant + 立即 + + + + + Start + 开始 + + + + &Single + 单次(&S) + + + + &Repetitive + 重复(&R) + + + + + Auto Calibration + 自动校准 + + + + Please adjust zero skew and save the result! + 请调整零点偏移并保存结果! + + + + + Ok + 确定 + + + + + Skip + 跳过 + + + + Auto Calibration program will be started. Please keep all channels out of singal input. It can take a while! + 将开启自动校准程序,请拔下探头,保持所有通道处于悬空状态。 + + + + Failed to select + 无法选择 + + + Zero adjustment program will be started. Please keep all channels out of singal input. It can take a while! + 将启动调零程序,请勿连接探头,保持输入处于悬空状态,调零过程请耐心等待! + + + Please adjust zero skew and save the result! +Please left both of channels unconnect for zero adjustment! + 请调整零点偏移并保存结果!在此过程中请保持通道输入处于悬空状态! + + + Failed to Select + 无法选择 + + + + pv::toolbars::TrigBar + + + Trigger + 触发 + + + + Decode + 解码 + + + + Measure + 测量 + + + + Search + 搜索 + + + + Function + 函数 + + + + Display + 显示 + + + + Themes + 主题 + + + + Dark + 暗黑 + + + + Light + 清新 + + + + &Lissajous + 李萨茹图(&L) + + + + FFT + FFT + + + + Math + 数学运算 + + + + pv::view::DecodeTrace + + + Start + 采样起始 + + + + End + 采样结束 + + + + Unshown + 已隐藏 + + + + Decoder Options + 解码器选项 + + + + <p><i>No decoders in the stack</i></p> + 没有协议解析器 + + + + <i>* Required channels</i> + *必要的通道 + + + + Cursor + 光标 + + + + Decode Start From + 解码起始位置 + + + + Decode End to + 解码结束位置 + + + + Stack Decoder + 多层协议 + + + + Zoom in for details + 放大查看细节 + + + Zoom in For Detials + 放大查看细节 + + + + Error: + 错误: + + + + Error: ... + 错误: ... + + + + <b>%1</b> (%2) * + + + + + <b>%1</b> (%2) + + + + + pv::view::DsoSignal + + + EN + 启用 + + + + DIS + 禁用 + + + + GND + 接地 + + + + DC + 直流 + + + + AC + 交流 + + + + AUTO + 自动 + + + Vmax: + 最大值: + + + Vmin: + 最小值: + + + Perd: + 周期: + + + Freq: + 频率: + + + Vp-p: + 峰-峰值: + + + Vrms: + 有效值: + + + Vmean: + 平均值: + + + Vmax: ##### + 最大值:##### + + + Vmin: ##### + 最小值:##### + + + Perd: ##### + 周期:##### + + + Freq: ##### + 频率:##### + + + Vp-p: ##### + 峰-峰值:##### + + + Vrms: ##### + 有效值:##### + + + Vmean: ##### + 平均值:##### + + + Max: + 最大值: + + + Min: + 最小值: + + + Period: + 周期: + + + Frequency: + 频率: + + + + pv::view::Header + + + Add Group + 增加组信号 + + + + Del Group + 删除组信号 + + + + Set Channel Colour + 设置通道颜色 + + + + pv::view::LissajousTrace + + + Lissajous Figure + 李萨茹图 + + + + Data source error. + 数据源错误 + + + + pv::view::View + + + ViewArea_center + + + + + ViewArea_ruler + + + + + ViewArea_header + + + + + pv::view::ViewStatus + + + Measure + 测量 + + + + Trigger Time: + 触发时间: + + + + Samples Captured! + 个数据被采集! + + + + Triggered! + 已触发! + + + + + % Captured + % 已采集 + + + + Waiting for Trigger! + 等待触发! + + + + pv::view::Viewport + + + Add Y-cursor + 添加Y轴光标 + + + + Add X-cursor + 添加X轴光标 + + + + Triggered! + 已触发! + + + + + % Captured + % 已采集 + + + + Waiting for Trigger! + 等待触发! + + + + Rising: + 上升沿: + + + + Falling: + 下降沿: + + + + Edges: + 跳变沿: + + + + Width: + 宽度: + + + + Period: + 周期: + + + + Frequency: + 频率: + + + + Duty Cycle: + 占空比: + + + + pv::view::dslDial + + / div + 每格 + + + + /div + /格 + + + + pv::widgets::ViewStatus + + Trigger Time: + 触发时间: + + + Triggered! + 已触发! + + + % Captured + % 已采集 + + + Waiting for Trigger! + 等待触发! + + + RLE FULL: + RLE缓存已满: + + + Samples Captured! + 个数据被采集! + + + diff --git a/qtpro/qt_25.qm b/qtpro/qt_25.qm new file mode 100644 index 00000000..3e5c146b Binary files /dev/null and b/qtpro/qt_25.qm differ