Changeset - 71441196d1c5
[Not reviewed]
Merge longmem
3 54 7
Hasan Yavuz ÖZDERYA - 6 years ago 2020-01-29 14:59:28
hy@ozderya.net
Merge with default
64 files changed with 1694 insertions and 433 deletions:
0 comments (0 inline, 0 general)
CMakeLists.txt
Show inline comments
 
#
 
# Copyright © 2018 Hasan Yavuz Özderya
 
# Copyright © 2019 Hasan Yavuz Özderya
 
#
 
# This file is part of serialplot.
 
#
 
# serialplot 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
 
@@ -41,37 +41,17 @@ set(BUILD_QWT true CACHE BOOL "Download 
 
if (BUILD_QWT)
 
  include(BuildQwt)
 
else (BUILD_QWT)
 
    find_package(Qwt 6.1 REQUIRED)
 
endif (BUILD_QWT)
 

	
 
# If set, cmake will download QtColorWidgets over git, build and use it as a static library.
 
set(BUILD_QTCOLORWIDGETS true CACHE BOOL "Download and build QtColorWidgets library automatically.")
 
if (BUILD_QTCOLORWIDGETS)
 
  include(BuildQColorWidgets)
 
else ()
 
  find_package(QtColorWidgets REQUIRED)
 
endif ()
 

	
 
set(BUILD_LEDWIDGET true CACHE BOOL "Download and build LedWidget automatically.")
 
if (BUILD_LEDWIDGET)
 
  include(BuildLedWidget)
 
else (BUILD_LEDWIDGET)
 
  include(FindLedWidget)
 
endif (BUILD_LEDWIDGET)
 

	
 
# includes
 
include_directories("./src"
 
  ${QWT_INCLUDE_DIR}
 
  ${QTCOLORWIDGETS_INCLUDE_DIRS}
 
  ${LEDWIDGET_INCLUDE_DIR}
 
  )
 

	
 
# flags
 
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${QTCOLORWIDGETS_FLAGS}")
 

	
 
# wrap UI and resource files
 
qt5_wrap_ui(UI_FILES
 
  src/mainwindow.ui
 
  src/portcontrol.ui
 
  src/about_dialog.ui
 
  src/snapshotview.ui
 
@@ -84,12 +64,13 @@ qt5_wrap_ui(UI_FILES
 
  src/endiannessbox.ui
 
  src/binarystreamreadersettings.ui
 
  src/asciireadersettings.ui
 
  src/framedreadersettings.ui
 
  src/demoreadersettings.ui
 
  src/updatecheckdialog.ui
 
  src/datatextview.ui
 
  )
 

	
 
if (WIN32)
 
  qt5_add_resources(RES_FILES misc/icons.qrc misc/winicons.qrc)
 
else (WIN32)
 
  qt5_add_resources(RES_FILES misc/icons.qrc)
 
@@ -123,12 +104,13 @@ add_executable(${PROGRAM_NAME} WIN32
 
  src/stream.cpp
 
  src/streamchannel.cpp
 
  src/channelinfomodel.cpp
 
  src/ringbuffer.cpp
 
  src/ringbuffer.cpp
 
  src/indexbuffer.cpp
 
  src/linindexbuffer.cpp
 
  src/readonlybuffer.cpp
 
  src/framebufferseries.cpp
 
  src/numberformatbox.cpp
 
  src/endiannessbox.cpp
 
  src/abstractreader.cpp
 
  src/binarystreamreader.cpp
 
@@ -149,38 +131,30 @@ add_executable(${PROGRAM_NAME} WIN32
 
  src/versionnumber.cpp
 
  src/updatecheckdialog.cpp
 
  src/samplepack.cpp
 
  src/source.cpp
 
  src/sink.cpp
 
  src/samplecounter.cpp
 
  src/ledwidget.cpp
 
  src/datatextview.cpp
 
  src/bpslabel.cpp
 
  misc/windows_icon.rc
 
  ${UI_FILES}
 
  ${RES_FILES}
 
  )
 

	
 
# Use the Widgets module from Qt 5.
 
target_link_libraries(${PROGRAM_NAME}
 
  ${QWT_LIBRARY}
 
  ${QTCOLORWIDGETS_LIBRARIES}
 
  ${LEDWIDGET_LIBRARY}
 
  )
 
qt5_use_modules(${PROGRAM_NAME} Widgets SerialPort Network)
 

	
 
if (BUILD_QWT)
 
  add_dependencies(${PROGRAM_NAME} QWT)
 
endif ()
 

	
 
if (BUILD_QTCOLORWIDGETS)
 
  add_dependencies(${PROGRAM_NAME} QCW)
 
endif ()
 

	
 
if (BUILD_LEDWIDGET)
 
  add_dependencies(${PROGRAM_NAME} LEDW)
 
endif (BUILD_LEDWIDGET)
 

	
 

	
 
# set compiler flags
 
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall")
 

	
 
# Enable C++11 support, fail if not supported
 
include(CheckCXXCompilerFlag)
 
CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
 
@@ -202,12 +176,13 @@ include(GetVersion)
 

	
 
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DVERSION_STRING=\\\"${VERSION_STRING}\\\" ")
 
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DVERSION_MAJOR=${VERSION_MAJOR} ")
 
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DVERSION_MINOR=${VERSION_MINOR} ")
 
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DVERSION_PATCH=${VERSION_PATCH} ")
 
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DVERSION_REVISION=\\\"${VERSION_REVISION}\\\" ")
 
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DPROGRAM_NAME=\\\"${PROGRAM_NAME}\\\" ")
 

	
 
# add make run target
 
add_custom_target(run
 
    COMMAND ${PROGRAM_NAME}
 
    DEPENDS ${PROGRAM_NAME}
 
    WORKING_DIRECTORY ${CMAKE_PROJECT_DIR}
cmake/modules/BuildLedWidget.cmake
Show inline comments
 
deleted file
cmake/modules/BuildQColorWidgets.cmake
Show inline comments
 
deleted file
cmake/modules/BuildQwt.cmake
Show inline comments
 
#
 
# Copyright © 2016 Hasan Yavuz Özderya
 
# Copyright © 2019 Hasan Yavuz Özderya
 
#
 
# This file is part of serialplot.
 
#
 
# serialplot 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
 
@@ -18,13 +18,14 @@
 
#
 

	
 
include(ExternalProject)
 

	
 
ExternalProject_Add(QWT
 
  PREFIX qwt
 
  SVN_REPOSITORY svn://svn.code.sf.net/p/qwt/code/branches/qwt-6.1
 
  # SVN_REPOSITORY svn://svn.code.sf.net/p/qwt/code/branches/qwt-6.1
 
  URL https://sourceforge.net/projects/qwt/files/qwt/6.1.4/qwt-6.1.4.tar.bz2
 
  # disable QwtDesigner plugin and enable static build
 
  PATCH_COMMAND sed -i -r -e "s/QWT_CONFIG\\s*\\+=\\s*QwtDesigner/#&/"
 
                          -e "s/QWT_CONFIG\\s*\\+=\\s*QwtDll/#&/"
 
                          -e "s/QWT_CONFIG\\s*\\+=\\s*QwtSvg/#&/"
 
                          -e "s/QWT_CONFIG\\s*\\+=\\s*QwtOpenGL/#&/"
 
						  -e "s|QWT_INSTALL_PREFIX\\s*=.*|QWT_INSTALL_PREFIX = <INSTALL_DIR>|"
cmake/modules/FindQtColorWidgets.cmake
Show inline comments
 
deleted file
cmake/modules/FindQwt.cmake
Show inline comments
 
#
 
# Copyright © 2017 Hasan Yavuz Özderya
 
# Copyright © 2019 Hasan Yavuz Özderya
 
#
 
# This file is part of serialplot.
 
#
 
# serialplot 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
 
@@ -63,14 +63,13 @@ if(qwt_roots)
 
	endif(qwt_version_string)
 
  endforeach(qwt_root ${qwt_roots})
 
endif(qwt_roots)
 

	
 
if(QWT_ROOT)
 
  set(QWT_INCLUDE_DIR "${QWT_ROOT}/include")
 
  find_library(QWT_LIBRARY "qwt-qt5"
 
	PATHS "${QWT_ROOT}/lib")
 
  find_library(QWT_LIBRARY NAMES "qwt-qt5" "qwt" PATHS "${QWT_ROOT}/lib")
 
else (QWT_ROOT)
 
  ## Look into system locations
 
  find_path(QWT_INCLUDE_DIR qwt_plot.h PATHS /usr/include/qwt)
 
  # try extracting version information
 
  if (QWT_INCLUDE_DIR)
 
	unset(qwt_version_string)
 
@@ -87,36 +86,55 @@ else (QWT_ROOT)
 
		  set(QWT_INCLUDE_DIR "NOTFOUND")
 
		endif()
 
	  endif(Qwt_FIND_VERSION)
 
	endif(qwt_version_string)
 
  endif (QWT_INCLUDE_DIR)
 
  # look into system locations for lib file
 
  find_library(QWT_LIBRARY "qwt-qt5" PATHS /usr/lib)
 
  find_library(QWT_LIBRARY NAMES "qwt-qt5" "qwt" PATHS /usr/lib)
 
endif(QWT_ROOT)
 

	
 
# set version variables
 
if(QWT_VERSION)
 
  string(REGEX REPLACE "([0-9]+)\\.([0-9]+)\\.([0-9]+)" "\\1"
 
	QWT_MAJOR_VERSION ${QWT_VERSION})
 
  string(REGEX REPLACE "([0-9]+)\\.([0-9]+)\\.([0-9]+)" "\\2"
 
	QWT_MINOR_VERSION ${QWT_VERSION})
 
  string(REGEX REPLACE "([0-9]+)\\.([0-9]+)\\.([0-9]+)" "\\3"
 
	QWT_PATCH_VERSION ${QWT_VERSION})
 
endif(QWT_VERSION)
 

	
 
# check Qwt library 'Qt' version
 
if (QWT_LIBRARY)
 
  include(GetPrerequisites)
 
  GET_PREREQUISITES(${QWT_LIBRARY} qwt_lib_deps 0 0 "" "")
 
  set(qwt_is_qt5 FALSE)
 
  foreach (dep ${qwt_lib_deps})
 
    if (${dep} MATCHES "libQt5Gui")
 
      set(qwt_is_qt5 TRUE)
 
    endif()
 
  endforeach ()
 
  if (NOT qwt_is_qt5)
 
    message(WARNING "Found qwt library (${QWT_LIBRARY}) isn't compiled with Qt5!")
 
    LIST_PREREQUISITES(${QWT_LIBRARY})
 
  endif()
 
endif (QWT_LIBRARY)
 

	
 
# set QWT_FOUND
 
if(QWT_INCLUDE_DIR AND QWT_LIBRARY)
 
if(QWT_INCLUDE_DIR AND QWT_LIBRARY AND qwt_is_qt5)
 
  set(QWT_INCLUDE_DIRS ${QWT_INCLUDE_DIR})
 
  set(QWT_LIBRARIES ${QWT_LIBRARY})
 
  set(QWT_FOUND true)
 
else()
 
  set(QWT_FOUND false)
 
endif()
 

	
 
# errors
 
if(NOT QWT_FOUND)
 
  unset(QWT_INCLUDE_DIR CACHE)
 
  unset(QWT_LIBRARY CACHE)
 

	
 
  if(Qwt_FIND_QUIET)
 
	message(WARNING "Couldn't find Qwt.")
 
  elseif(Qwt_FIND_REQUIRED)
 
	message(FATAL_ERROR "Couldn't find Qwt.")
 
  endif(Qwt_FIND_QUIET)
 
endif(NOT QWT_FOUND)
serialplot.pro
Show inline comments
 
#
 
# Copyright © 2015 Hasan Yavuz Özderya
 
# Copyright © 2019 Hasan Yavuz Özderya
 
#
 
# This file is part of serialplot.
 
#
 
# serialplot 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
 
@@ -20,69 +20,93 @@
 
#-------------------------------------------------
 
#
 
# Project created by QtCreator 2015-03-04T08:20:06
 
#
 
#-------------------------------------------------
 

	
 
QT       += core gui serialport
 
QT       += core gui serialport network svg
 

	
 
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
 

	
 
TARGET = serialplot
 
TEMPLATE = app
 

	
 
CONFIG += qwt
 
# LIBS += -lqwt # enable this line if qwt pri files aren't installed
 

	
 
DEFINES += PROGRAM_NAME="\\\"serialplot\\\""
 

	
 
DEFINES += VERSION_MAJOR=10 VERSION_MINOR=0 VERSION_PATCH=0 VERSION_STRING=\\\"10.0.0\\\"
 

	
 
SOURCES += \
 
    src/main.cpp\
 
    src/main.cpp \
 
    src/mainwindow.cpp \
 
    src/portcontrol.cpp \
 
    src/plot.cpp \
 
    src/zoomer.cpp \
 
    src/scrollzoomer.cpp \
 
    src/scrollbar.cpp \
 
    src/hidabletabwidget.cpp \
 
    src/framebuffer.cpp \
 
    src/scalepicker.cpp \
 
    src/scalezoomer.cpp \
 
    src/portlist.cpp \
 
    src/snapshot.cpp \
 
    src/snapshotview.cpp \
 
    src/snapshotmanager.cpp \
 
    src/snapshot.cpp \
 
    src/plotsnapshotoverlay.cpp \
 
    src/commandpanel.cpp \
 
    src/commandwidget.cpp \
 
    src/commandedit.cpp \
 
    src/dataformatpanel.cpp \
 
    src/plotcontrolpanel.cpp \
 
    src/recordpanel.cpp \
 
    src/datarecorder.cpp \
 
    src/tooltipfilter.cpp \
 
    src/sneakylineedit.cpp \
 
    src/channelmanager.cpp \
 
    src/stream.cpp \
 
    src/streamchannel.cpp \
 
    src/channelinfomodel.cpp \
 
    src/ringbuffer.cpp \
 
    src/indexbuffer.cpp \
 
    src/linindexbuffer.cpp \
 
    src/readonlybuffer.cpp \
 
    src/framebufferseries.cpp \
 
    src/plotcontrolpanel.cpp \
 
    src/numberformatbox.cpp \
 
    src/endiannessbox.cpp \
 
    src/framedreadersettings.cpp \
 
    src/abstractreader.cpp \
 
    src/binarystreamreader.cpp \
 
    src/binarystreamreadersettings.cpp \
 
    src/asciireader.cpp \
 
    src/asciireadersettings.cpp \
 
    src/asciireader.cpp \
 
    src/demoreader.cpp \
 
    src/demoreadersettings.cpp \
 
    src/framedreader.cpp \
 
    src/framedreadersettings.cpp \
 
    src/plotmanager.cpp \
 
    src/plotmenu.cpp \
 
    src/barplot.cpp \
 
    src/barchart.cpp \
 
    src/barscaledraw.cpp \
 
    src/numberformat.cpp \
 
    src/recordpanel.cpp \
 
    src/updatechecker.cpp \
 
    src/versionnumber.cpp \
 
    src/updatecheckdialog.cpp \
 
    src/demoreadersettings.cpp
 
    src/samplepack.cpp \
 
    src/source.cpp \
 
    src/sink.cpp \
 
    src/samplecounter.cpp \
 
    src/ledwidget.cpp \
 
    src/datatextview.cpp \
 
    src/bpslabel.cpp
 

	
 
HEADERS += \
 
    src/mainwindow.h \
 
    src/utils.h \
 
    src/portcontrol.h \
 
    src/floatswap.h \
 
    src/plot.h \
 
    src/zoomer.h \
 
    src/hidabletabwidget.h \
 
    src/framebuffer.h \
 
    src/scalepicker.h \
 
    src/scalezoomer.h \
 
    src/portlist.h \
 
    src/snapshotview.h \
 
@@ -92,13 +116,12 @@ HEADERS += \
 
    src/commandpanel.h \
 
    src/commandwidget.h \
 
    src/commandedit.h \
 
    src/dataformatpanel.h \
 
    src/tooltipfilter.h \
 
    src/sneakylineedit.h \
 
    src/channelmanager.h \
 
    src/framebufferseries.h \
 
    src/plotcontrolpanel.h \
 
    src/numberformatbox.h \
 
    src/endiannessbox.h \
 
    src/framedreadersettings.h \
 
    src/abstractreader.h \
 
@@ -111,13 +134,38 @@ HEADERS += \
 
    src/plotmanager.h \
 
    src/setting_defines.h \
 
    src/numberformat.h \
 
    src/recordpanel.h \
 
    src/updatechecker.h \
 
    src/updatecheckdialog.h \
 
    src/demoreadersettings.h
 
    src/demoreadersettings.h \
 
    src/datatextview.h \
 
    src/bpslabel.h \
 
    src/barchart.h \
 
    src/barplot.h \
 
    src/barscaledraw.h \
 
    src/channelinfomodel.h \
 
    src/datarecorder.h \
 
    src/defines.h \
 
    src/indexbuffer.h \
 
    src/ledwidget.h \
 
    src/linindexbuffer.h \
 
    src/plotmenu.h \
 
    src/readonlybuffer.h \
 
    src/ringbuffer.h \
 
    src/samplecounter.h \
 
    src/samplepack.h \
 
    src/scrollbar.h \
 
    src/scrollzoomer.h \
 
    src/sink.h \
 
    src/source.h \
 
    src/streamchannel.h \
 
    src/stream.h \
 
    src/version.h \
 
    src/versionnumber.h \
 
    src/zoomer.h
 

	
 
FORMS += \
 
    src/mainwindow.ui \
 
    src/about_dialog.ui \
 
    src/portcontrol.ui \
 
    src/snapshotview.ui \
 
@@ -129,13 +177,14 @@ FORMS += \
 
    src/endiannessbox.ui \
 
    src/framedreadersettings.ui \
 
    src/binarystreamreadersettings.ui \
 
    src/asciireadersettings.ui \
 
    src/recordpanel.ui \
 
    src/updatecheckdialog.ui \
 
    src/demoreadersettings.ui
 
    src/demoreadersettings.ui \
 
    src/datatextview.ui
 

	
 
INCLUDEPATH += qmake/ src/
 

	
 
CONFIG += c++11
 

	
 
RESOURCES += misc/icons.qrc
src/abstractreader.cpp
Show inline comments
 
/*
 
  Copyright © 2018 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -20,12 +20,13 @@
 
#include "abstractreader.h"
 

	
 
AbstractReader::AbstractReader(QIODevice* device, QObject* parent) :
 
    QObject(parent)
 
{
 
    _device = device;
 
    bytesRead = 0;
 
}
 

	
 
void AbstractReader::pause(bool enabled)
 
{
 
    paused = enabled;
 
}
 
@@ -40,6 +41,18 @@ void AbstractReader::enable(bool enabled
 
    else
 
    {
 
        QObject::disconnect(_device, 0, this, 0);
 
        disconnectSinks();
 
    }
 
}
 

	
 
void AbstractReader::onDataReady()
 
{
 
    bytesRead += readData();
 
}
 

	
 
unsigned AbstractReader::getBytesRead()
 
{
 
    unsigned r = bytesRead;
 
    bytesRead = 0;
 
    return r;
 
}
src/abstractreader.h
Show inline comments
 
/*
 
  Copyright © 2018 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -46,12 +46,15 @@ public:
 
    /// 'disabled'.
 
    virtual void enable(bool enabled = true);
 

	
 
    /// None of the current readers support X channel at the moment
 
    bool hasX() const final { return false; };
 

	
 
    /// Read and 'zero' the byte counter
 
    unsigned getBytesRead();
 

	
 
signals:
 
    // TODO: should we keep this?
 
    void numOfChannelsChanged(unsigned);
 

	
 
public slots:
 
    /**
 
@@ -60,15 +63,28 @@ public slots:
 
     * Reader should actually continue reading to keep the
 
     * synchronization but shouldn't commit data.
 
     */
 
    void pause(bool enabled);
 

	
 
protected:
 
    /// Reader should read from this device in `readData()` function.
 
    QIODevice* _device;
 

	
 
    /// Reader should check this variable to determine if reading is
 
    /// paused in `readData()`
 
    bool paused;
 

	
 
protected slots:
 
    /// all derived readers has to override this function
 
    virtual void onDataReady() = 0;
 
    /**
 
     * Called when `readyRead` is signaled by the device. This is
 
     * where the implementors should read the data and return the
 
     * exact number of bytes read from the device.
 
     */
 
    virtual unsigned readData() = 0;
 

	
 
private:
 
    unsigned bytesRead;
 

	
 
private slots:
 
    void onDataReady();
 
};
 

	
 
#endif // ABSTRACTREADER_H
src/asciireader.cpp
Show inline comments
 
/*
 
  Copyright © 2018 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -67,27 +67,26 @@ unsigned AsciiReader::numChannels() cons
 

	
 
void AsciiReader::enable(bool enabled)
 
{
 
    if (enabled)
 
    {
 
        firstReadAfterEnable = true;
 
        QObject::connect(_device, &QIODevice::readyRead,
 
                         this, &AsciiReader::onDataReady);
 
    }
 
    else
 
    {
 
        QObject::disconnect(_device, 0, this, 0);
 
        disconnectSinks();
 
    }
 

	
 
    AbstractReader::enable(enabled);
 
}
 

	
 
void AsciiReader::onDataReady()
 
unsigned AsciiReader::readData()
 
{
 
    unsigned numBytesRead = 0;
 

	
 
    while(_device->canReadLine())
 
    {
 
        QString line = QString(_device->readLine());
 
        QByteArray bytes = _device->readLine();
 
        QString line = QString(bytes);
 
        numBytesRead += bytes.size();
 

	
 
        // discard only once when we just started reading
 
        if (firstReadAfterEnable)
 
        {
 
            firstReadAfterEnable = false;
 
            continue;
 
@@ -124,14 +123,17 @@ void AsciiReader::onDataReady()
 
            }
 

	
 
            Q_ASSERT(samples->numChannels() == _numChannels);
 

	
 
            // commit data
 
            feedOut(*samples);
 
            delete samples;
 
        }
 
    }
 

	
 
    return numBytesRead;
 
}
 

	
 
SamplePack* AsciiReader::parseLine(const QString& line) const
 
{
 
    auto separatedValues = line.split(delimiter, QString::SkipEmptyParts);
 
    unsigned numComingChannels = separatedValues.length();
src/asciireader.h
Show inline comments
 
/*
 
  Copyright © 2018 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -47,14 +47,16 @@ private:
 
    /// number of channels will be determined from incoming data
 
    unsigned autoNumOfChannels;
 
    QChar delimiter; ///< selected column delimiter
 

	
 
    bool firstReadAfterEnable = false;
 

	
 
    unsigned readData() override;
 

	
 
private slots:
 
    void onDataReady() override;
 

	
 
    /**
 
     * Parses given line and returns sample pack.
 
     *
 
     * Returns `nullptr` in case of error.
 
     */
 
    SamplePack* parseLine(const QString& line) const;
src/asciireadersettings.cpp
Show inline comments
 
/*
 
  Copyright © 2017 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -18,12 +18,13 @@
 
*/
 

	
 
#include <QRegularExpressionValidator>
 
#include <QRegularExpression>
 

	
 
#include "utils.h"
 
#include "defines.h"
 
#include "setting_defines.h"
 

	
 
#include "asciireadersettings.h"
 
#include "ui_asciireadersettings.h"
 

	
 
AsciiReaderSettings::AsciiReaderSettings(QWidget *parent) :
 
@@ -32,12 +33,14 @@ AsciiReaderSettings::AsciiReaderSettings
 
{
 
    ui->setupUi(this);
 

	
 
    auto validator = new QRegularExpressionValidator(QRegularExpression("[^\\d]?"), this);
 
    ui->leDelimiter->setValidator(validator);
 

	
 
    ui->spNumOfChannels->setMaximum(MAX_NUM_CHANNELS);
 

	
 
    connect(ui->rbComma, &QAbstractButton::toggled,
 
            this, &AsciiReaderSettings::delimiterToggled);
 
    connect(ui->rbSpace, &QAbstractButton::toggled,
 
            this, &AsciiReaderSettings::delimiterToggled);
 
    connect(ui->rbTab, &QAbstractButton::toggled,
 
            this, &AsciiReaderSettings::delimiterToggled);
src/binarystreamreader.cpp
Show inline comments
 
/*
 
  Copyright © 2018 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -104,56 +104,64 @@ void BinaryStreamReader::onNumOfChannels
 
{
 
    _numChannels = value;
 
    updateNumChannels();
 
    emit numOfChannelsChanged(value);
 
}
 

	
 
void BinaryStreamReader::onDataReady()
 
unsigned BinaryStreamReader::readData()
 
{
 
    // a package is a set of channel data like {CHAN0_SAMPLE, CHAN1_SAMPLE...}
 
    int packageSize = sampleSize * _numChannels;
 
    int bytesAvailable = _device->bytesAvailable();
 
    unsigned packageSize = sampleSize * _numChannels;
 
    unsigned bytesAvailable = _device->bytesAvailable();
 
    unsigned totalRead = 0;
 

	
 
    // skip 1 byte if requested
 
    if (skipByteRequested && bytesAvailable > 0)
 
    {
 
        _device->read(1);
 
        totalRead++;
 
        skipByteRequested = false;
 
        bytesAvailable--;
 
    }
 

	
 
    // skip 1 sample (channel) if requested
 
    if (skipSampleRequested && bytesAvailable >= (int) sampleSize)
 
    if (skipSampleRequested && bytesAvailable >= sampleSize)
 
    {
 
        _device->read(sampleSize);
 
        totalRead += sampleSize;
 
        skipSampleRequested = false;
 
        bytesAvailable -= sampleSize;
 
    }
 

	
 
    if (bytesAvailable < packageSize) return;
 
    if (bytesAvailable < packageSize) return totalRead;
 

	
 
    int numOfPackagesToRead =
 
    unsigned numOfPackagesToRead =
 
        (bytesAvailable - (bytesAvailable % packageSize)) / packageSize;
 
    unsigned numBytesToRead = numOfPackagesToRead * packageSize;
 

	
 
    totalRead += numBytesToRead;
 

	
 
    if (paused)
 
    {
 
        // read and discard data
 
        _device->read(numOfPackagesToRead*packageSize);
 
        return;
 
        _device->read(numBytesToRead);
 
        return totalRead;
 
    }
 

	
 
    // actual reading
 
    SamplePack samples(numOfPackagesToRead, _numChannels);
 
    for (int i = 0; i < numOfPackagesToRead; i++)
 
    for (unsigned i = 0; i < numOfPackagesToRead; i++)
 
    {
 
        for (unsigned int ci = 0; ci < _numChannels; ci++)
 
        for (unsigned ci = 0; ci < _numChannels; ci++)
 
        {
 
            samples.data(ci)[i] = (this->*readSample)();
 
        }
 
    }
 
    feedOut(samples);
 

	
 
    return totalRead;
 
}
 

	
 
template<typename T> double BinaryStreamReader::readSampleAs()
 
{
 
    T data;
 

	
src/binarystreamreader.h
Show inline comments
 
/*
 
  Copyright © 2018 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -57,13 +57,14 @@ private:
 
     *
 
     * @note Device should already have enough bytes present before
 
     * calling this function.
 
     */
 
    template<typename T> double readSampleAs();
 

	
 
    unsigned readData() override;
 

	
 
private slots:
 
    void onNumberFormatChanged(NumberFormat numberFormat);
 
    void onNumOfChannelsChanged(unsigned value);
 
    void onDataReady() override;
 
};
 

	
 
#endif // BINARYSTREAMREADER_H
src/binarystreamreadersettings.cpp
Show inline comments
 
/*
 
  Copyright © 2016 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -18,20 +18,23 @@
 
*/
 

	
 
#include "binarystreamreadersettings.h"
 
#include "ui_binarystreamreadersettings.h"
 

	
 
#include "utils.h"
 
#include "defines.h"
 
#include "setting_defines.h"
 

	
 
BinaryStreamReaderSettings::BinaryStreamReaderSettings(QWidget *parent) :
 
    QWidget(parent),
 
    ui(new Ui::BinaryStreamReaderSettings)
 
{
 
    ui->setupUi(this);
 

	
 
    ui->spNumOfChannels->setMaximum(MAX_NUM_CHANNELS);
 

	
 
    // Note: if directly connected we get a runtime warning on incompatible signal arguments
 
    connect(ui->spNumOfChannels, SELECT<int>::OVERLOAD_OF(&QSpinBox::valueChanged),
 
            [this](int value)
 
            {
 
                emit numOfChannelsChanged(value);
 
            });
src/bpslabel.cpp
Show inline comments
 
new file 100644
 
/*
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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.
 

	
 
  serialplot 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 serialplot.  If not, see <http://www.gnu.org/licenses/>.
 
*/
 

	
 
#include "bpslabel.h"
 

	
 
const char* BPS_TOOLTIP = "bits per second";
 
const char* BPS_TOOLTIP_ERR = "Maximum baud rate may be reached!";
 

	
 
BPSLabel::BPSLabel(PortControl* portControl,
 
                   DataFormatPanel* dataFormatPanel,
 
                   QWidget *parent) :
 
    QLabel(parent)
 
{
 
    _portControl = portControl;
 
    _dataFormatPanel = dataFormatPanel;
 
    prevBytesRead = 0;
 

	
 
    setText("0bps");
 
    setToolTip(tr(BPS_TOOLTIP));
 

	
 
    connect(&bpsTimer, &QTimer::timeout,
 
            this, &BPSLabel::onBpsTimeout);
 

	
 
    connect(portControl, &PortControl::portToggled,
 
            this, &BPSLabel::onPortToggled);
 
}
 

	
 
void BPSLabel::onBpsTimeout()
 
{
 
    uint64_t curBytesRead = _dataFormatPanel->bytesRead();
 
    uint64_t bytesRead = curBytesRead - prevBytesRead;
 
    prevBytesRead = curBytesRead;
 

	
 
    unsigned bits = bytesRead * 8;
 
    unsigned maxBps = _portControl->maxBitRate();
 
    QString str;
 
    if (bits >= maxBps)
 
    {
 
        // TODO: an icon for bps warning
 
        str = QString(tr("!%1/%2bps")).arg(bits).arg(maxBps);
 
        setToolTip(tr(BPS_TOOLTIP_ERR));
 
    }
 
    else
 
    {
 
        str = QString(tr("%1bps")).arg(bits);
 
        setToolTip(tr(BPS_TOOLTIP));
 
    }
 
    setText(str);
 
}
 

	
 
void BPSLabel::onPortToggled(bool open)
 
{
 
    if (open)
 
    {
 
        bpsTimer.start(1000);
 
    }
 
    else
 
    {
 
        bpsTimer.stop();
 
        // if not cleared last displayed value is stuck
 
        setText("0bps");
 
        setToolTip(tr(BPS_TOOLTIP));
 
    }
 
}
src/bpslabel.h
Show inline comments
 
new file 100644
 
/*
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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.
 

	
 
  serialplot 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 serialplot.  If not, see <http://www.gnu.org/licenses/>.
 
*/
 

	
 
#ifndef BPSLABEL_H
 
#define BPSLABEL_H
 

	
 
#include <QLabel>
 
#include <QTimer>
 

	
 
#include "portcontrol.h"
 
#include "dataformatpanel.h"
 

	
 
/**
 
 * Displays bits per second read from device.
 
 *
 
 * Displays a warning if maximum bit rate is reached.
 
 */
 
class BPSLabel : public QLabel
 
{
 
    Q_OBJECT
 

	
 
public:
 
    explicit BPSLabel(PortControl* portControl,
 
                      DataFormatPanel* dataFormatPanel,
 
                      QWidget *parent = 0);
 

	
 
private:
 
    PortControl* _portControl;
 
    DataFormatPanel* _dataFormatPanel;
 
    QTimer bpsTimer;
 

	
 
    uint64_t prevBytesRead;
 

	
 
private slots:
 
    void onBpsTimeout();
 
    void onPortToggled(bool open);
 
};
 

	
 
#endif // BPSLABEL_H
src/dataformatpanel.cpp
Show inline comments
 
/*
 
  Copyright © 2018 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -36,12 +36,13 @@ DataFormatPanel::DataFormatPanel(QSerial
 
{
 
    ui->setupUi(this);
 

	
 
    serialPort = port;
 
    paused = false;
 
    readerBeforeDemo = nullptr;
 
    _bytesRead = 0;
 

	
 
    // initalize default reader
 
    currentReader = &bsReader;
 
    bsReader.enable();
 
    ui->rbBinary->setChecked(true);
 
    ui->horizontalLayout->addWidget(bsReader.settingsWidget(), 1);
 
@@ -127,12 +128,18 @@ void DataFormatPanel::selectReader(Abstr
 
    reader->pause(paused);
 

	
 
    currentReader = reader;
 
    emit sourceChanged(currentReader);
 
}
 

	
 
uint64_t DataFormatPanel::bytesRead()
 
{
 
    _bytesRead += currentReader->getBytesRead();
 
    return _bytesRead;
 
}
 

	
 
void DataFormatPanel::saveSettings(QSettings* settings)
 
{
 
    settings->beginGroup(SettingGroup_DataFormat);
 

	
 
    // save selected data format (current reader)
 
    QString format;
src/dataformatpanel.h
Show inline comments
 
/*
 
  Copyright © 2018 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -17,15 +17,15 @@
 
  along with serialplot.  If not, see <http://www.gnu.org/licenses/>.
 
*/
 

	
 
#ifndef DATAFORMATPANEL_H
 
#define DATAFORMATPANEL_H
 

	
 
#include <stdint.h>
 
#include <QWidget>
 
#include <QButtonGroup>
 
#include <QTimer>
 
#include <QSerialPort>
 
#include <QList>
 
#include <QSettings>
 
#include <QtGlobal>
 

	
 
#include "binarystreamreader.h"
 
@@ -47,12 +47,14 @@ public:
 
    ~DataFormatPanel();
 

	
 
    /// Returns currently selected number of channels
 
    unsigned numChannels() const;
 
    /// Returns active source (reader)
 
    Source* activeSource();
 
    /// Returns total number of bytes read
 
    uint64_t bytesRead();
 
    /// Stores data format panel settings into a `QSettings`
 
    void saveSettings(QSettings* settings);
 
    /// Loads data format panel settings from a `QSettings`.
 
    void loadSettings(QSettings* settings);
 

	
 
public slots:
 
@@ -74,12 +76,13 @@ private:
 
    /// Currently selected reader
 
    AbstractReader* currentReader;
 
    /// Disable current reader and enable a another one
 
    void selectReader(AbstractReader* reader);
 

	
 
    bool paused;
 
    uint64_t _bytesRead;
 

	
 
    DemoReader demoReader;
 
    AbstractReader* readerBeforeDemo;
 

	
 
    bool isDemoEnabled() const;
 
};
src/datatextview.cpp
Show inline comments
 
new file 100644
 
/*
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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.
 

	
 
  serialplot 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 serialplot.  If not, see <http://www.gnu.org/licenses/>.
 
*/
 

	
 
#include "datatextview.h"
 
#include "ui_datatextview.h"
 

	
 
#include "setting_defines.h"
 
#include "utils.h"
 

	
 
class DataTextViewSink : public Sink
 
{
 
public:
 
    DataTextViewSink(DataTextView* textView)
 
    {
 
        _textView = textView;
 
    }
 

	
 
protected:
 
    virtual void feedIn(const SamplePack& data) override
 
    {
 
        _textView->addData(data);
 
    };
 

	
 
private:
 
    DataTextView* _textView;
 
};
 

	
 
DataTextView::DataTextView(Stream* stream, QWidget *parent) :
 
    QWidget(parent),
 
    ui(new Ui::DataTextView)
 
{
 
    _stream = stream;
 
    ui->setupUi(this);
 
    sink = new DataTextViewSink(this);
 

	
 
    connect(ui->cbEnable, &QCheckBox::toggled, [this](bool checked)
 
            {
 
                if (checked)
 
                {
 
                    _stream->connectFollower(sink);
 
                }
 
                else
 
                {
 
                    _stream->disconnectFollower(sink);
 
                }
 
            });
 

	
 
    ui->textView->setMaximumBlockCount(ui->spNumLines->value());
 
    connect(ui->spNumLines, SELECT<int>::OVERLOAD_OF(&QSpinBox::valueChanged),
 
            [this](int value)
 
            {
 
                ui->textView->setMaximumBlockCount(value);
 
            });
 

	
 
    connect(ui->pbClear, &QPushButton::clicked, ui->textView, &QPlainTextEdit::clear);
 
}
 

	
 
DataTextView::~DataTextView()
 
{
 
    delete sink;
 
    delete ui;
 
}
 

	
 
void DataTextView::addData(const SamplePack& data)
 
{
 
    for (unsigned int i = 0; i < data.numSamples(); i++)
 
    {
 
        QString str;
 
        for (unsigned ci = 0; ci < data.numChannels(); ci++)
 
        {
 
            str += QString::number(data.data(ci)[i], 'f', ui->spDecimals->value());
 
            if (ci != data.numChannels()-1) str += " ";
 
        }
 
        ui->textView->appendPlainText(str);
 
    }
 
}
 

	
 
void DataTextView::saveSettings(QSettings* settings)
 
{
 
    settings->beginGroup(SettingGroup_Plot);
 
    settings->setValue(SG_TextView_NumLines, ui->spNumLines->value());
 
    settings->setValue(SG_TextView_Decimals, ui->spDecimals->value());
 
    settings->endGroup();
 
}
 

	
 
void DataTextView::loadSettings(QSettings* settings)
 
{
 
    settings->beginGroup(SettingGroup_Plot);
 
    ui->spNumLines->setValue(
 
        settings->value(SG_TextView_NumLines, ui->spNumLines->value()).toInt());
 
    ui->spDecimals->setValue(
 
        settings->value(SG_TextView_Decimals, ui->spDecimals->value()).toInt());
 
    settings->endGroup();
 
}
src/datatextview.h
Show inline comments
 
new file 100644
 
/*
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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.
 

	
 
  serialplot 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 serialplot.  If not, see <http://www.gnu.org/licenses/>.
 
*/
 

	
 
#ifndef DATATEXTVIEW_H
 
#define DATATEXTVIEW_H
 

	
 
#include <QWidget>
 

	
 
#include "stream.h"
 

	
 
namespace Ui {
 
class DataTextView;
 
}
 

	
 
class DataTextViewSink;
 

	
 
class DataTextView : public QWidget
 
{
 
    Q_OBJECT
 

	
 
public:
 
    explicit DataTextView(Stream* stream, QWidget *parent = 0);
 
    ~DataTextView();
 

	
 
    /// Stores settings into a `QSettings`
 
    void saveSettings(QSettings* settings);
 
    /// Loads settings from a `QSettings`.
 
    void loadSettings(QSettings* settings);
 

	
 
protected:
 
    void addData(const SamplePack& data);
 

	
 
    friend DataTextViewSink;
 

	
 
private:
 
    Ui::DataTextView *ui;
 
    DataTextViewSink* sink;
 
    Stream* _stream;
 
};
 

	
 
#endif // DATATEXTVIEW_H
src/datatextview.ui
Show inline comments
 
new file 100644
 
<?xml version="1.0" encoding="UTF-8"?>
 
<ui version="4.0">
 
 <class>DataTextView</class>
 
 <widget class="QWidget" name="DataTextView">
 
  <property name="geometry">
 
   <rect>
 
    <x>0</x>
 
    <y>0</y>
 
    <width>451</width>
 
    <height>212</height>
 
   </rect>
 
  </property>
 
  <property name="windowTitle">
 
   <string>Form</string>
 
  </property>
 
  <layout class="QHBoxLayout" name="horizontalLayout">
 
   <item>
 
    <layout class="QVBoxLayout" name="verticalLayout">
 
     <item>
 
      <widget class="QCheckBox" name="cbEnable">
 
       <property name="toolTip">
 
        <string>Enable display of plotted data as text.</string>
 
       </property>
 
       <property name="text">
 
        <string>Enable</string>
 
       </property>
 
      </widget>
 
     </item>
 
     <item>
 
      <widget class="QLabel" name="label">
 
       <property name="text">
 
        <string>Num. Lines:</string>
 
       </property>
 
      </widget>
 
     </item>
 
     <item>
 
      <widget class="QSpinBox" name="spNumLines">
 
       <property name="minimum">
 
        <number>1</number>
 
       </property>
 
       <property name="maximum">
 
        <number>10000</number>
 
       </property>
 
       <property name="value">
 
        <number>1000</number>
 
       </property>
 
      </widget>
 
     </item>
 
     <item>
 
      <widget class="QLabel" name="label_2">
 
       <property name="text">
 
        <string>Decimals:</string>
 
       </property>
 
      </widget>
 
     </item>
 
     <item>
 
      <widget class="QSpinBox" name="spDecimals">
 
       <property name="maximum">
 
        <number>9</number>
 
       </property>
 
       <property name="value">
 
        <number>6</number>
 
       </property>
 
      </widget>
 
     </item>
 
     <item>
 
      <spacer name="verticalSpacer">
 
       <property name="orientation">
 
        <enum>Qt::Vertical</enum>
 
       </property>
 
       <property name="sizeHint" stdset="0">
 
        <size>
 
         <width>20</width>
 
         <height>1</height>
 
        </size>
 
       </property>
 
      </spacer>
 
     </item>
 
     <item>
 
      <widget class="QPushButton" name="pbClear">
 
       <property name="text">
 
        <string>Clear</string>
 
       </property>
 
      </widget>
 
     </item>
 
    </layout>
 
   </item>
 
   <item>
 
    <widget class="QPlainTextEdit" name="textView">
 
     <property name="readOnly">
 
      <bool>true</bool>
 
     </property>
 
    </widget>
 
   </item>
 
  </layout>
 
 </widget>
 
 <resources/>
 
 <connections/>
 
</ui>
src/defines.h
Show inline comments
 
/*
 
  Copyright © 2016 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -14,7 +14,15 @@
 
  GNU General Public License for more details.
 

	
 
  You should have received a copy of the GNU General Public License
 
  along with serialplot.  If not, see <http://www.gnu.org/licenses/>.
 
*/
 

	
 
const char* BUG_REPORT_URL = "https://bitbucket.org/hyOzd/serialplot/issues/new";
 
#ifndef DEFINES_H
 
#define DEFINES_H
 

	
 
const char BUG_REPORT_URL[] = "https://bitbucket.org/hyOzd/serialplot/issues/new";
 

	
 
/// Maximum number of channels that can be set by user
 
const unsigned MAX_NUM_CHANNELS = 64;
 

	
 
#endif  // DEFINES_H
src/demoreader.cpp
Show inline comments
 
/*
 
  Copyright © 2018 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -50,14 +50,15 @@ void DemoReader::enable(bool enabled)
 
    {
 
        timer.start();
 
    }
 
    else
 
    {
 
        timer.stop();
 
        disconnectSinks();
 
    }
 

	
 
    AbstractReader::enable(enabled);
 
}
 

	
 
unsigned DemoReader::numChannels() const
 
{
 
    return _numChannels;
 
}
 
@@ -88,10 +89,11 @@ void DemoReader::demoTimerTimeout()
 
void DemoReader::onNumChannelsChanged(unsigned value)
 
{
 
    _numChannels = value;
 
    updateNumChannels();
 
}
 

	
 
void DemoReader::onDataReady()
 
unsigned DemoReader::readData()
 
{
 
    // intentionally empty, required by AbstractReader
 
    return 0;
 
}
src/demoreader.h
Show inline comments
 
/*
 
  Copyright © 2018 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -52,13 +52,14 @@ private:
 
    DemoReaderSettings _settingsWidget;
 

	
 
    unsigned _numChannels;
 
    QTimer timer;
 
    int count;
 

	
 
    unsigned readData() override;
 

	
 
private slots:
 
    void demoTimerTimeout();
 
    void onNumChannelsChanged(unsigned value);
 
    void onDataReady() override;
 
};
 

	
 
#endif // DEMOREADER_H
src/demoreadersettings.cpp
Show inline comments
 
/*
 
  Copyright © 2018 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -18,19 +18,22 @@
 
*/
 

	
 
#include "demoreadersettings.h"
 
#include "ui_demoreadersettings.h"
 

	
 
#include "utils.h"
 
#include "defines.h"
 

	
 
DemoReaderSettings::DemoReaderSettings(QWidget *parent) :
 
    QWidget(parent),
 
    ui(new Ui::DemoReaderSettings)
 
{
 
    ui->setupUi(this);
 

	
 
    ui->spNumChannels->setMaximum(MAX_NUM_CHANNELS);
 

	
 
    connect(ui->spNumChannels, SELECT<int>::OVERLOAD_OF(&QSpinBox::valueChanged),
 
            [this](int value)
 
            {
 
                emit numChannelsChanged(value);
 
            });
 
}
src/floatswap.h
Show inline comments
 
#include <QtGlobal>
 

	
 
#if (QT_VERSION < QT_VERSION_CHECK(5, 12, 0))
 

	
 
template <> inline float qbswap<float>(float source)
 
{
 
    float result;
 
    char* s = (char*) &source;
 
    char* t = (char*) &result;
 
    t[0] = s[3];
 
    t[1] = s[2];
 
    t[2] = s[1];
 
    t[3] = s[0];
 
    return result;
 
}
 

	
 
#endif
src/framebuffer.h
Show inline comments
 
@@ -58,7 +58,27 @@ class WFrameBuffer : public ResizableBuf
 
    /// Add samples to the buffer
 
    virtual void addSamples(double* samples, unsigned n) = 0;
 
    /// Reset all data to 0
 
    virtual void clear() = 0;
 
};
 

	
 
/**
 
 * Abstract base class for X buffers.
 
 *
 
 * These buffers only contain increasing or equal (to previous) values.
 
 */
 
class XFrameBuffer : public ResizableBuffer
 
{
 
public:
 
    enum Index {OUT_OF_RANGE = -1};
 

	
 
    /**
 
     * Finds index for given value.
 
     *
 
     * If given value is bigger than max or smaller than minimum
 
     * returns `OUT_OF_RANGE`. If it's in between values, smaller
 
     * index is returned (not closer one).
 
     */
 
    virtual int findIndex(double value) const = 0;
 
};
 

	
 
#endif // FRAMEBUFFER_H
src/framebufferseries.cpp
Show inline comments
 
@@ -17,78 +17,67 @@
 
  along with serialplot.  If not, see <http://www.gnu.org/licenses/>.
 
*/
 

	
 
#include <math.h>
 
#include "framebufferseries.h"
 

	
 
FrameBufferSeries::FrameBufferSeries(const FrameBuffer* buffer)
 
FrameBufferSeries::FrameBufferSeries(const XFrameBuffer* x, const FrameBuffer* y)
 
{
 
    xAsIndex = true;
 
    _xmin = 0;
 
    _xmax = 1;
 
    _buffer = buffer;
 
    _x = x;
 
    _y = y;
 

	
 
    int_index_start = 0;
 
    int_index_end = _buffer->size();
 
    int_index_end = _y->size();
 
}
 

	
 
void FrameBufferSeries::setXAxis(bool asIndex, double xmin, double xmax)
 
void FrameBufferSeries::setX(const XFrameBuffer* x)
 
{
 
    xAsIndex = asIndex;
 
    _xmin = xmin;
 
    _xmax = xmax;
 
    _x = x;
 
}
 

	
 
size_t FrameBufferSeries::size() const
 
{
 
    return int_index_end - int_index_start;
 
    return int_index_end - int_index_start + 1;
 
}
 

	
 
QPointF FrameBufferSeries::sample(size_t i) const
 
{
 
    i += int_index_start;
 
    if (xAsIndex)
 
    {
 
        return QPointF(i, _buffer->sample(i));
 
    }
 
    else
 
    {
 
        return QPointF(i * (_xmax - _xmin) / _buffer->size() + _xmin, _buffer->sample(i));
 
    }
 
    return QPointF(_x->sample(i), _y->sample(i));
 
}
 

	
 
QRectF FrameBufferSeries::boundingRect() const
 
{
 
    QRectF rect;
 
    auto yLim = _buffer->limits();
 
    auto yLim = _y->limits();
 
    auto xLim = _x->limits();
 
    rect.setBottom(yLim.start);
 
    rect.setTop(yLim.end);
 
    if (xAsIndex)
 
    {
 
        rect.setLeft(0);
 
        rect.setRight(size());
 
    }
 
    else
 
    {
 
        rect.setLeft(_xmin);
 
        rect.setRight(_xmax);
 
    }
 
    rect.setLeft(xLim.start);
 
    rect.setRight(xLim.end);
 

	
 
    return rect.normalized();
 
}
 

	
 
void FrameBufferSeries::setRectOfInterest(const QRectF& rect)
 
{
 
    if (xAsIndex)
 
    int_index_start = _x->findIndex(rect.left());
 
    int_index_end = _x->findIndex(rect.right());
 

	
 
    if (int_index_start == XFrameBuffer::OUT_OF_RANGE)
 
    {
 
        int_index_start = floor(rect.left())-1;
 
        int_index_end = ceil(rect.right())+1;
 
        int_index_start = 0;
 
    }
 
    else
 
    else if (int_index_start > 0)
 
    {
 
        double xsize = _xmax - _xmin;
 
        size_t bsize = _buffer->size();
 
        int_index_start =  floor(bsize * (rect.left()-_xmin) / xsize)-1;
 
        int_index_end = ceil(bsize * (rect.right()-_xmin) / xsize)+1;
 
        int_index_start -= 1;
 
    }
 

	
 
    int_index_start = std::max(int_index_start, 0);
 
    int_index_end = std::min((int) _buffer->size(), int_index_end);
 
    if (int_index_end == XFrameBuffer::OUT_OF_RANGE)
 
    {
 
        int_index_end = _x->size()-1;
 
    }
 
    else if (int_index_end < (int)_x->size()-1)
 
    {
 
        int_index_end += 1;
 
    }
 
}
src/framebufferseries.h
Show inline comments
 
@@ -32,28 +32,25 @@
 
 * isolated from Qwt. Otherwise QwtPlotCurve owns FrameBuffer
 
 * structures.
 
 */
 
class FrameBufferSeries : public QwtSeriesData<QPointF>
 
{
 
public:
 
    FrameBufferSeries(const FrameBuffer* buffer);
 
    FrameBufferSeries(const XFrameBuffer* x, const FrameBuffer* y);
 

	
 
    /// Behavior of X axis
 
    void setXAxis(bool asIndex, double xmin, double xmax);
 
    void setX(const XFrameBuffer* x);
 

	
 
    // QwtSeriesData implementations
 
    size_t size() const;
 
    QPointF sample(size_t i) const;
 
    QRectF boundingRect() const;
 
    void setRectOfInterest(const QRectF& rect);
 

	
 
private:
 
    const FrameBuffer* _buffer;
 
    bool xAsIndex;
 
    double _xmin;
 
    double _xmax;
 
    const XFrameBuffer* _x;
 
    const FrameBuffer* _y;
 

	
 
    int int_index_start; ///< starting index of "rectangle of interest"
 
    int int_index_end;   ///< ending index of "rectangle of interest"
 
};
 

	
 
#endif // FRAMEBUFFERSERIES_H
src/framedreader.cpp
Show inline comments
 
/*
 
  Copyright © 2018 Hasan Yavuz Özderya
 
  Copyright © 2020 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -156,12 +156,13 @@ void FramedReader::checkSettings()
 

	
 
void FramedReader::onNumOfChannelsChanged(unsigned value)
 
{
 
    _numChannels = value;
 
    checkSettings();
 
    reset();
 
    updateNumChannels();
 
    emit numOfChannelsChanged(value);
 
}
 

	
 
void FramedReader::onSyncWordChanged(QByteArray word)
 
{
 
    syncWord = word;
 
@@ -181,24 +182,27 @@ void FramedReader::onFrameSizeChanged(un
 
        frameSize = value;
 
    }
 
    checkSettings();
 
    reset();
 
}
 

	
 
void FramedReader::onDataReady()
 
unsigned FramedReader::readData()
 
{
 
    if (settingsInvalid) return;
 
    unsigned numBytesRead = 0;
 

	
 
    if (settingsInvalid) return numBytesRead;
 

	
 
    // loop until we run out of bytes or more bytes is required
 
    unsigned bytesAvailable;
 
    while ((bytesAvailable = _device->bytesAvailable()))
 
    {
 
        if (!gotSync) // read sync word
 
        {
 
            char c;
 
            _device->getChar(&c);
 
            numBytesRead++;
 
            if (c == syncWord[sync_i]) // correct sync byte?
 
            {
 
                sync_i++;
 
                if (sync_i == (unsigned) syncWord.length())
 
                {
 
                    gotSync = true;
 
@@ -210,12 +214,13 @@ void FramedReader::onDataReady()
 
            }
 
        }
 
        else if (hasSizeByte && !gotSize) // skipped if fixed frame size
 
        {
 
            frameSize = 0;
 
            _device->getChar((char*) &frameSize);
 
            numBytesRead++;
 

	
 
            if (frameSize == 0) // check size
 
            {
 
                qCritical() << "Frame size is 0!";
 
                reset();
 
            }
 
@@ -239,16 +244,19 @@ void FramedReader::onDataReady()
 
            {
 
                break;
 
            }
 
            else // read data bytes and checksum
 
            {
 
                readFrameDataAndCheck();
 
                numBytesRead += checksumEnabled ? frameSize+1 : frameSize;
 
                reset();
 
            }
 
        }
 
    }
 

	
 
    return numBytesRead;
 
}
 

	
 
void FramedReader::reset()
 
{
 
    sync_i = 0;
 
    gotSync = false;
 
@@ -260,13 +268,13 @@ void FramedReader::reset()
 
// Important: this function assumes device has enough bytes to read a full frames data and checksum
 
void FramedReader::readFrameDataAndCheck()
 
{
 
    // if paused just read and waste data
 
    if (paused)
 
    {
 
        _device->read((checksumEnabled ? frameSize+1 : frameSize));
 
        _device->read(checksumEnabled ? frameSize+1 : frameSize);
 
        return;
 
    }
 

	
 
    // a package is 1 set of samples for all channels
 
    unsigned numOfPackagesToRead = frameSize / (_numChannels * sampleSize);
 
    SamplePack samples(numOfPackagesToRead, _numChannels);
src/framedreader.h
Show inline comments
 
/*
 
  Copyright © 2018 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -76,14 +76,15 @@ private:
 
    double (FramedReader::*readSample)();
 
    template<typename T> double readSampleAs();
 
    /// reads payload portion of the frame, calculates checksum and commits data
 
    /// @note should be called only if there are enough bytes on device
 
    void readFrameDataAndCheck();
 

	
 
    unsigned readData() override;
 

	
 
private slots:
 
    void onDataReady() override;
 

	
 
    void onNumberFormatChanged(NumberFormat numberFormat);
 
    void onNumOfChannelsChanged(unsigned value);
 
    void onSyncWordChanged(QByteArray);
 
    void onFrameSizeChanged(unsigned);
 
};
src/framedreadersettings.cpp
Show inline comments
 
/*
 
  Copyright © 2016 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -17,24 +17,26 @@
 
  along with serialplot.  If not, see <http://www.gnu.org/licenses/>.
 
*/
 

	
 
#include <QButtonGroup>
 

	
 
#include "utils.h"
 
#include "defines.h"
 
#include "setting_defines.h"
 
#include "framedreadersettings.h"
 
#include "ui_framedreadersettings.h"
 

	
 
FramedReaderSettings::FramedReaderSettings(QWidget *parent) :
 
    QWidget(parent),
 
    ui(new Ui::FramedReaderSettings)
 
{
 
    ui->setupUi(this);
 

	
 
    ui->leSyncWord->setMode(false); // hex mode
 
    ui->leSyncWord->setText("AA BB");
 
    ui->spNumOfChannels->setMaximum(MAX_NUM_CHANNELS);
 

	
 
    connect(ui->cbChecksum, &QCheckBox::toggled,
 
            [this](bool enabled)
 
            {
 
                emit checksumChanged(enabled);
 
            });
src/indexbuffer.cpp
Show inline comments
 
/*
 
  Copyright © 2017 Hasan Yavuz Özderya
 
  Copyright © 2018 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -44,6 +44,18 @@ double IndexBuffer::sample(unsigned i) c
 
}
 

	
 
Range IndexBuffer::limits() const
 
{
 
    return Range{0, _size-1.};
 
}
 

	
 
int IndexBuffer::findIndex(double value) const
 
{
 
    if (value < 0 || value > size() - 1)
 
    {
 
        return OUT_OF_RANGE;
 
    }
 
    else
 
    {
 
        return value;
 
    }
 
}
src/indexbuffer.h
Show inline comments
 
@@ -23,21 +23,22 @@
 
#include "framebuffer.h"
 

	
 
/// A simple frame buffer that simply returns requested index as
 
/// sample value.
 
///
 
/// @note This buffer isn't for storing data.
 
class IndexBuffer : public ResizableBuffer
 
class IndexBuffer : public XFrameBuffer
 
{
 
public:
 
    IndexBuffer(unsigned n);
 

	
 
    unsigned size() const;
 
    double sample(unsigned i) const;
 
    Range limits() const;
 
    void resize(unsigned n);
 
    unsigned size() const override;
 
    double sample(unsigned i) const override;
 
    Range limits() const override;
 
    void resize(unsigned n) override;
 
    int findIndex(double value) const override;
 

	
 
private:
 
    unsigned _size;
 
};
 

	
 
#endif
src/ledwidget.cpp
Show inline comments
 
new file 100644
 
/*
 
  Copyright © 2018 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  ledwidget 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.
 

	
 
  ledwidget 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 ledwidget.  If not, see <http://www.gnu.org/licenses/>.
 
*/
 

	
 
#include "ledwidget.h"
 
#include <QPainter>
 
#include <QPainterPath>
 
#include <QRadialGradient>
 

	
 
LedWidget::LedWidget(QWidget* parent) : QWidget(parent),
 
    m_color(107,223,51),
 
    m_on(true)
 
{
 
    resize(20,20);
 
}
 

	
 
QSize LedWidget::sizeHint() const
 
{
 
    return QSize(20,20);
 
}
 

	
 
QSize LedWidget::minimumSizeHint() const
 
{
 
    return QSize(10, 10);
 
}
 

	
 
void LedWidget::setColor(QColor ledColor)
 
{
 
    if (m_color == ledColor) return;
 
    m_color = ledColor;
 
    update();
 
    emit colorChanged(m_color);
 
}
 

	
 
bool LedWidget::isOn()
 
{
 
    return m_on;
 
}
 

	
 
void LedWidget::setOn(bool on)
 
{
 
    if (on == m_on) return;
 
    m_on = on;
 
    update();
 
    emit onChanged(on);
 
}
 

	
 
void LedWidget::turnOn()
 
{
 
    setOn(true);
 
}
 

	
 
void LedWidget::turnOff()
 
{
 
    setOn(false);
 
}
 

	
 
void LedWidget::toggle()
 
{
 
    setOn(!m_on);
 
}
 

	
 
void LedWidget::paintEvent(QPaintEvent* event)
 
{
 
    Q_UNUSED(event)
 

	
 
    const qreal r = std::min(width(), height()) / 2; // maximum radius including glow
 
    const qreal glowOffset = std::max(2., r/5.);
 
    const qreal borderOffset = std::max(1., r/10.);
 
    const qreal shineOffset = std::max(1., r/20.);
 
    const QPointF center(width()/2, height()/2);
 

	
 
    const qreal gr = r;
 
    const qreal br = gr - glowOffset;   // border shape radius
 
    const qreal ir = br - borderOffset; // inner fill radius
 
    const qreal sr = ir - shineOffset;
 

	
 
    QColor borderColor(130,130,130);
 
    QColor shineColor(255, 255, 255, m_on ? 200 : 50);
 
    QColor fillColor(m_color);
 

	
 
    QPainter painter(this);
 
    painter.setRenderHints(QPainter::Antialiasing);
 

	
 
    // draw border
 
    painter.setPen(Qt::NoPen);
 
    painter.setBrush(borderColor);
 
    painter.drawEllipse(center, br, br);
 

	
 
    // draw infill
 
    if (!m_on) fillColor = fillColor.darker();
 
    painter.setBrush(fillColor);
 
    painter.drawEllipse(center, ir, ir);
 

	
 
    // draw glow
 
    if (m_on)
 
    {
 
        QColor glowColor(m_color);
 
        glowColor.setAlphaF(0.5);
 
        QRadialGradient glowGradient(center, gr, center);
 
        glowGradient.setColorAt(0, glowColor);
 
        glowGradient.setColorAt((r-glowOffset)/r, glowColor);
 
        glowGradient.setColorAt(1, Qt::transparent);
 
        painter.setBrush(glowGradient);
 
        painter.drawEllipse(center, gr, gr);
 
    }
 

	
 
    // draw shine
 
    QRadialGradient shineGradient(center, sr, center-QPoint(sr/2,sr/2));
 
    shineGradient.setColorAt(0, shineColor);
 
    shineGradient.setColorAt(1, Qt::transparent);
 
    painter.setBrush(shineGradient);
 
    painter.drawEllipse(center, sr, sr);
 
}
src/ledwidget.h
Show inline comments
 
new file 100644
 
/*
 
  Copyright © 2018 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  ledwidget 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.
 

	
 
  ledwidget 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 ledwidget.  If not, see <http://www.gnu.org/licenses/>.
 
*/
 

	
 
#ifndef LEDWIDGET_H
 
#define LEDWIDGET_H
 

	
 
#include <QWidget>
 
#include <QSize>
 
#include <QColor>
 

	
 
class LedWidget : public QWidget
 
{
 
    Q_OBJECT
 

	
 
    Q_PROPERTY(QColor color MEMBER m_color WRITE setColor NOTIFY colorChanged)
 
    Q_PROPERTY(bool on READ isOn WRITE setOn NOTIFY onChanged)
 

	
 
public:
 
    explicit LedWidget(QWidget *parent = 0);
 

	
 
    void setColor(QColor ledColor);
 
    bool isOn();
 

	
 
    QSize sizeHint() const Q_DECL_OVERRIDE;
 
    QSize minimumSizeHint() const Q_DECL_OVERRIDE;
 

	
 
signals:
 
    void colorChanged(QColor ledColor);
 
    void onChanged(bool on);
 

	
 
public slots:
 
    void setOn(bool on);
 
    void turnOn();
 
    void turnOff();
 
    void toggle();
 

	
 
protected:
 
    void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE;
 

	
 
private:
 
    QColor m_color;
 
    bool m_on;
 
};
 

	
 
#endif // LEDWIDGET_H
src/linindexbuffer.cpp
Show inline comments
 
 /*
 
  Copyright © 2017 Hasan Yavuz Özderya
 
  Copyright © 2018 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -15,18 +15,20 @@
 

	
 
  You should have received a copy of the GNU General Public License
 
  along with serialplot.  If not, see <http://www.gnu.org/licenses/>.
 
*/
 

	
 
#include <QtGlobal>
 
#include <algorithm>
 

	
 
#include "linindexbuffer.h"
 

	
 
LinIndexBuffer::LinIndexBuffer(unsigned n, Range lim)
 
{
 
    Q_ASSERT(n > 0);
 
    // Note that calculation of _step would cause divide by 0
 
    Q_ASSERT(n > 1);
 

	
 
    _size = n;
 
    setLimits(lim);
 
}
 

	
 
unsigned LinIndexBuffer::size() const
 
@@ -47,11 +49,23 @@ Range LinIndexBuffer::limits() const
 
void LinIndexBuffer::resize(unsigned n)
 
{
 
    _size = n;
 
    setLimits(_limits);         // called to update `_step`
 
}
 

	
 
int LinIndexBuffer::findIndex(double value) const
 
{
 
    if (value < _limits.start || value > _limits.end)
 
    {
 
        return OUT_OF_RANGE;
 
    }
 

	
 
    int r = (value - _limits.start) / _step;
 
    // Note: we are limiting return value because of floating point in-accuracies
 
    return std::min<int>(std::max<int>(r, 0), (_size-1));
 
}
 

	
 
void LinIndexBuffer::setLimits(Range lim)
 
{
 
    _limits = lim;
 
    _step = (lim.end - lim.start) / (_size-1);
 
}
src/linindexbuffer.h
Show inline comments
 
@@ -23,23 +23,25 @@
 
#include "framebuffer.h"
 

	
 
/// A dynamic frame buffer that start and end values can be set and
 
/// intermediate values are calculated linearly.
 
///
 
/// @note This buffer isn't for storing data.
 
class LinIndexBuffer : public ResizableBuffer
 
class LinIndexBuffer : public XFrameBuffer
 
{
 
public:
 
    LinIndexBuffer(unsigned n, Range lim);
 
    LinIndexBuffer(unsigned n, double min, double max) :
 
        LinIndexBuffer(n, {min, max}) {};
 

	
 
    unsigned size() const;
 
    double sample(unsigned i) const;
 
    Range limits() const;
 
    void resize(unsigned n);
 
    unsigned size() const override;
 
    double sample(unsigned i) const override;
 
    Range limits() const override;
 
    void resize(unsigned n) override;
 
    int findIndex(double value) const override;
 

	
 
    /// Sets minimum and maximum sample values of the buffer.
 
    void setLimits(Range lim);
 

	
 
private:
 
    unsigned _size;
 
    Range _limits;
src/main.cpp
Show inline comments
 
@@ -16,34 +16,70 @@
 
  You should have received a copy of the GNU General Public License
 
  along with serialplot.  If not, see <http://www.gnu.org/licenses/>.
 
*/
 

	
 
#include <QApplication>
 
#include <QtGlobal>
 
#include <iostream>
 

	
 
#include "mainwindow.h"
 
#include "tooltipfilter.h"
 
#include "version.h"
 

	
 
MainWindow* pMainWindow;
 
MainWindow* pMainWindow = nullptr;
 

	
 
void messageHandler(QtMsgType type, const QMessageLogContext &context,
 
                    const QString &msg)
 
{
 
    // TODO: don't call MainWindow::messageHandler if window is destroyed
 
    pMainWindow->messageHandler(type, context, msg);
 
    QString logString;
 

	
 
    switch (type)
 
    {
 
#if (QT_VERSION >= QT_VERSION_CHECK(5, 5, 0))
 
        case QtInfoMsg:
 
            logString = "[Info] " + msg;
 
            break;
 
#endif
 
        case QtDebugMsg:
 
            logString = "[Debug] " + msg;
 
            break;
 
        case QtWarningMsg:
 
            logString = "[Warning] " + msg;
 
            break;
 
        case QtCriticalMsg:
 
            logString = "[Error] " + msg;
 
            break;
 
        case QtFatalMsg:
 
            logString = "[Fatal] " + msg;
 
            break;
 
    }
 

	
 
    std::cerr << logString.toStdString() << std::endl;
 

	
 
    if (pMainWindow != nullptr)
 
    {
 
        // TODO: don't call MainWindow::messageHandler if window is destroyed
 
        pMainWindow->messageHandler(type, logString, msg);
 
    }
 

	
 
    if (type == QtFatalMsg)
 
    {
 
        __builtin_trap();
 
    }
 
}
 

	
 
int main(int argc, char *argv[])
 
{
 
    QApplication a(argc, argv);
 
    QApplication::setApplicationName(PROGRAM_NAME);
 
    QApplication::setApplicationVersion(VERSION_STRING);
 

	
 
    qInstallMessageHandler(messageHandler);
 
    MainWindow w;
 
    pMainWindow = &w;
 

	
 
    qInstallMessageHandler(messageHandler);
 

	
 
    ToolTipFilter ttf;
 
    a.installEventFilter(&ttf);
 

	
 
    // log application information
 
    qDebug() << "SerialPlot" << VERSION_STRING;
 
    qDebug() << "Revision" << VERSION_REVISION;
src/mainwindow.cpp
Show inline comments
 
/*
 
  Copyright © 2018 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -26,16 +26,19 @@
 
#include <QFile>
 
#include <QTextStream>
 
#include <QMenu>
 
#include <QDesktopServices>
 
#include <QMap>
 
#include <QtDebug>
 
#include <QCommandLineParser>
 
#include <QFileInfo>
 
#include <qwt_plot.h>
 
#include <limits.h>
 
#include <cmath>
 
#include <iostream>
 
#include <cstdlib>
 

	
 
#include <plot.h>
 
#include <barplot.h>
 

	
 
#include "framebufferseries.h"
 
#include "utils.h"
 
@@ -52,36 +55,40 @@ Q_IMPORT_PLUGIN(QWindowsIntegrationPlugi
 
const QMap<int, QString> panelSettingMap({
 
        {0, "Port"},
 
        {1, "DataFormat"},
 
        {2, "Plot"},
 
        {3, "Commands"},
 
        {4, "Record"},
 
        {5, "Log"}
 
        {5, "TextView"},
 
        {6, "Log"}
 
    });
 

	
 
MainWindow::MainWindow(QWidget *parent) :
 
    QMainWindow(parent),
 
    ui(new Ui::MainWindow),
 
    aboutDialog(this),
 
    portControl(&serialPort),
 
    secondaryPlot(NULL),
 
    snapshotMan(this, &stream),
 
    commandPanel(&serialPort),
 
    dataFormatPanel(&serialPort),
 
    recordPanel(&stream),
 
    updateCheckDialog(this)
 
    textView(&stream),
 
    updateCheckDialog(this),
 
    bpsLabel(&portControl, &dataFormatPanel, this)
 
{
 
    ui->setupUi(this);
 

	
 
    plotMan = new PlotManager(ui->plotArea, &plotMenu, &stream);
 

	
 
    ui->tabWidget->insertTab(0, &portControl, "Port");
 
    ui->tabWidget->insertTab(1, &dataFormatPanel, "Data Format");
 
    ui->tabWidget->insertTab(2, &plotControlPanel, "Plot");
 
    ui->tabWidget->insertTab(3, &commandPanel, "Commands");
 
    ui->tabWidget->insertTab(4, &recordPanel, "Record");
 
    ui->tabWidget->insertTab(5, &textView, "Text View");
 
    ui->tabWidget->setCurrentIndex(0);
 
    auto tbPortControl = portControl.toolBar();
 
    addToolBar(tbPortControl);
 
    addToolBar(recordPanel.toolbar());
 

	
 
    ui->plotToolBar->addAction(snapshotMan.takeSnapshotAction());
 
@@ -166,12 +173,15 @@ MainWindow::MainWindow(QWidget *parent) 
 
            plotMan, &PlotManager::setNumOfSamples);
 

	
 
    connect(&plotControlPanel, &PlotControlPanel::yScaleChanged,
 
            plotMan, &PlotManager::setYAxis);
 

	
 
    connect(&plotControlPanel, &PlotControlPanel::xScaleChanged,
 
            &stream, &Stream::setXAxis);
 

	
 
    connect(&plotControlPanel, &PlotControlPanel::xScaleChanged,
 
            plotMan, &PlotManager::setXAxis);
 

	
 
    connect(&plotControlPanel, &PlotControlPanel::plotWidthChanged,
 
            plotMan, &PlotManager::setPlotWidth);
 

	
 
    // plot toolbar signals
 
@@ -212,26 +222,37 @@ MainWindow::MainWindow(QWidget *parent) 
 
    // init plot
 
    numOfSamples = plotControlPanel.numOfSamples();
 
    stream.setNumSamples(numOfSamples);
 
    plotControlPanel.setChannelInfoModel(stream.infoModel());
 

	
 
    // init scales
 
    stream.setXAxis(plotControlPanel.xAxisAsIndex(),
 
                    plotControlPanel.xMin(), plotControlPanel.xMax());
 

	
 
    plotMan->setYAxis(plotControlPanel.autoScale(),
 
                      plotControlPanel.yMin(), plotControlPanel.yMax());
 
    plotMan->setXAxis(plotControlPanel.xAxisAsIndex(),
 
                      plotControlPanel.xMin(), plotControlPanel.xMax());
 
    plotMan->setNumOfSamples(numOfSamples);
 
    plotMan->setPlotWidth(plotControlPanel.plotWidth());
 

	
 
    // init bps (bits per second) counter
 
    ui->statusBar->addPermanentWidget(&bpsLabel);
 

	
 
    // Init sps (sample per second) counter
 
    spsLabel.setText("0sps");
 
    spsLabel.setToolTip("samples per second (per channel)");
 
    spsLabel.setToolTip(tr("samples per second (per channel)"));
 
    ui->statusBar->addPermanentWidget(&spsLabel);
 
    connect(&sampleCounter, &SampleCounter::spsChanged,
 
            this, &MainWindow::onSpsChanged);
 

	
 
    bpsLabel.setMinimumWidth(70);
 
    bpsLabel.setAlignment(Qt::AlignRight);
 
    spsLabel.setMinimumWidth(70);
 
    spsLabel.setAlignment(Qt::AlignRight);
 

	
 
    // init demo
 
    QObject::connect(ui->actionDemoMode, &QAction::toggled,
 
                     this, &MainWindow::enableDemo);
 

	
 
    QObject::connect(ui->actionDemoMode, &QAction::toggled,
 
                     plotMan, &PlotManager::showDemoIndicator);
 
@@ -239,15 +260,17 @@ MainWindow::MainWindow(QWidget *parent) 
 
    // init stream connections
 
    connect(&dataFormatPanel, &DataFormatPanel::sourceChanged,
 
            this, &MainWindow::onSourceChanged);
 
    onSourceChanged(dataFormatPanel.activeSource());
 

	
 
    // load default settings
 
    QSettings settings("serialplot", "serialplot");
 
    QSettings settings(PROGRAM_NAME, PROGRAM_NAME);
 
    loadAllSettings(&settings);
 

	
 
    handleCommandLineOptions(*QApplication::instance());
 

	
 
    // ensure command panel has 1 command if none loaded
 
    if (!commandPanel.numOfCommands())
 
    {
 
        commandPanel.newCommandAction()->trigger();
 
    }
 

	
 
@@ -288,13 +311,13 @@ void MainWindow::closeEvent(QCloseEvent 
 
            event->ignore();
 
            return;
 
        }
 
    }
 

	
 
    // save settings
 
    QSettings settings("serialplot", "serialplot");
 
    QSettings settings(PROGRAM_NAME, PROGRAM_NAME);
 
    saveAllSettings(&settings);
 
    settings.sync();
 

	
 
    if (settings.status() != QSettings::NoError)
 
    {
 
        QString errorText;
 
@@ -343,12 +366,17 @@ void MainWindow::setupAboutDialog()
 

	
 
void MainWindow::onPortToggled(bool open)
 
{
 
    // make sure demo mode is disabled
 
    if (open && isDemoRunning()) enableDemo(false);
 
    ui->actionDemoMode->setEnabled(!open);
 

	
 
    if (!open)
 
    {
 
        spsLabel.setText("0sps");
 
    }
 
}
 

	
 
void MainWindow::onSourceChanged(Source* source)
 
{
 
    source->connectSink(&stream);
 
    source->connectSink(&sampleCounter);
 
@@ -462,62 +490,35 @@ void MainWindow::onExportCsv()
 
PlotViewSettings MainWindow::viewSettings() const
 
{
 
    return plotMenu.viewSettings();
 
}
 

	
 
void MainWindow::messageHandler(QtMsgType type,
 
                                const QMessageLogContext &context,
 
                                const QString &logString,
 
                                const QString &msg)
 
{
 
    QString logString;
 

	
 
    switch (type)
 
    {
 
#if (QT_VERSION >= QT_VERSION_CHECK(5, 5, 0))
 
        case QtInfoMsg:
 
            logString = "[Info] " + msg;
 
            break;
 
#endif
 
        case QtDebugMsg:
 
            logString = "[Debug] " + msg;
 
            break;
 
        case QtWarningMsg:
 
            logString = "[Warning] " + msg;
 
            break;
 
        case QtCriticalMsg:
 
            logString = "[Error] " + msg;
 
            break;
 
        case QtFatalMsg:
 
            logString = "[Fatal] " + msg;
 
            break;
 
    }
 

	
 
    if (ui != NULL) ui->ptLog->appendPlainText(logString);
 
    std::cerr << logString.toStdString() << std::endl;
 
    if (ui != NULL)
 
        ui->ptLog->appendPlainText(logString);
 

	
 
    if (type != QtDebugMsg && ui != NULL)
 
    {
 
        ui->statusBar->showMessage(msg, 5000);
 
    }
 

	
 
    if (type == QtFatalMsg)
 
    {
 
        __builtin_trap();
 
    }
 
}
 

	
 
void MainWindow::saveAllSettings(QSettings* settings)
 
{
 
    saveMWSettings(settings);
 
    portControl.saveSettings(settings);
 
    dataFormatPanel.saveSettings(settings);
 
    stream.saveSettings(settings);
 
    plotControlPanel.saveSettings(settings);
 
    plotMenu.saveSettings(settings);
 
    commandPanel.saveSettings(settings);
 
    recordPanel.saveSettings(settings);
 
    textView.saveSettings(settings);
 
    updateCheckDialog.saveSettings(settings);
 
}
 

	
 
void MainWindow::loadAllSettings(QSettings* settings)
 
{
 
    loadMWSettings(settings);
 
@@ -525,12 +526,13 @@ void MainWindow::loadAllSettings(QSettin
 
    dataFormatPanel.loadSettings(settings);
 
    stream.loadSettings(settings);
 
    plotControlPanel.loadSettings(settings);
 
    plotMenu.loadSettings(settings);
 
    commandPanel.loadSettings(settings);
 
    recordPanel.loadSettings(settings);
 
    textView.loadSettings(settings);
 
    updateCheckDialog.loadSettings(settings);
 
}
 

	
 
void MainWindow::saveMWSettings(QSettings* settings)
 
{
 
    // save window geometry
 
@@ -602,6 +604,59 @@ void MainWindow::onLoadSettings()
 
    if (!fileName.isNull()) // user canceled
 
    {
 
        QSettings settings(fileName, QSettings::IniFormat);
 
        loadAllSettings(&settings);
 
    }
 
}
 

	
 
void MainWindow::handleCommandLineOptions(const QCoreApplication &app)
 
{
 
    QCommandLineParser parser;
 
    parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsCompactedShortOptions);
 
    parser.setApplicationDescription("Small and simple software for plotting data from serial port in realtime.");
 
    parser.addHelpOption();
 
    parser.addVersionOption();
 

	
 
    QCommandLineOption configOpt({"c", "config"}, "Load configuration from file.", "filename");
 
    QCommandLineOption portOpt({"p", "port"}, "Set port name.", "port name");
 
    QCommandLineOption baudrateOpt({"b" ,"baudrate"}, "Set port baud rate.", "baud rate");
 
    QCommandLineOption openPortOpt({"o", "open"}, "Open serial port.");
 

	
 
    parser.addOption(configOpt);
 
    parser.addOption(portOpt);
 
    parser.addOption(baudrateOpt);
 
    parser.addOption(openPortOpt);
 

	
 
    parser.process(app);
 

	
 
    if (parser.isSet(configOpt))
 
    {
 
        QString fileName = parser.value(configOpt);
 
        QFileInfo fileInfo(fileName);
 

	
 
        if (fileInfo.exists() && fileInfo.isFile())
 
        {
 
            QSettings settings(fileName, QSettings::IniFormat);
 
            loadAllSettings(&settings);
 
        }
 
        else
 
        {
 
            qCritical() << "Configuration file not exist. Closing application.";
 
            std::exit(1);
 
        }
 
    }
 

	
 
    if (parser.isSet(portOpt))
 
    {
 
        portControl.selectPort(parser.value(portOpt));
 
    }
 

	
 
    if (parser.isSet(baudrateOpt))
 
    {
 
        portControl.selectBaudrate(parser.value(baudrateOpt));
 
    }
 

	
 
    if (parser.isSet(openPortOpt))
 
    {
 
        portControl.openPort();
 
    }
 
}
src/mainwindow.h
Show inline comments
 
/*
 
  Copyright © 2018 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -43,12 +43,14 @@
 
#include "stream.h"
 
#include "snapshotmanager.h"
 
#include "plotmanager.h"
 
#include "plotmenu.h"
 
#include "updatecheckdialog.h"
 
#include "samplecounter.h"
 
#include "datatextview.h"
 
#include "bpslabel.h"
 

	
 
namespace Ui {
 
class MainWindow;
 
}
 

	
 
class MainWindow : public QMainWindow
 
@@ -58,14 +60,13 @@ class MainWindow : public QMainWindow
 
public:
 
    explicit MainWindow(QWidget *parent = 0);
 
    ~MainWindow();
 

	
 
    PlotViewSettings viewSettings() const;
 

	
 
    void messageHandler(QtMsgType type, const QMessageLogContext &context,
 
                        const QString &msg);
 
    void messageHandler(QtMsgType type, const QString &logString, const QString &msg);
 

	
 
private:
 
    Ui::MainWindow *ui;
 

	
 
    QDialog aboutDialog;
 
    void setupAboutDialog();
 
@@ -86,13 +87,17 @@ private:
 
    QLabel spsLabel;
 
    CommandPanel commandPanel;
 
    DataFormatPanel dataFormatPanel;
 
    RecordPanel recordPanel;
 
    PlotControlPanel plotControlPanel;
 
    PlotMenu plotMenu;
 
    DataTextView textView;
 
    UpdateCheckDialog updateCheckDialog;
 
    BPSLabel bpsLabel;
 

	
 
    void handleCommandLineOptions(const QCoreApplication &app);
 

	
 
    /// Returns true if demo is running
 
    bool isDemoRunning();
 
    /// Display a secondary plot in the splitter, removing and
 
    /// deleting previous one if it exists
 
    void showSecondary(QWidget* wid);
src/plot.cpp
Show inline comments
 
/*
 
  Copyright © 2017 Hasan Yavuz Özderya
 
  Copyright © 2018 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -88,12 +88,17 @@ Plot::Plot(QWidget* parent) :
 

	
 
Plot::~Plot()
 
{
 
    if (snapshotOverlay != NULL) delete snapshotOverlay;
 
}
 

	
 
void Plot::setDispChannels(QVector<const StreamChannel*> channels)
 
{
 
    zoomer.setDispChannels(channels);
 
}
 

	
 
void Plot::setYAxis(bool autoScaled, double yAxisMin, double yAxisMax)
 
{
 
    this->isAutoScaled = autoScaled;
 

	
 
    if (!autoScaled)
 
    {
src/plot.h
Show inline comments
 
/*
 
  Copyright © 2017 Hasan Yavuz Özderya
 
  Copyright © 2018 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -47,12 +47,15 @@ public:
 
        ShowSymbolsHide
 
    };
 

	
 
    Plot(QWidget* parent = 0);
 
    ~Plot();
 

	
 
    /// Set displayed channels for value tracking (can be null)
 
    void setDispChannels(QVector<const StreamChannel*> channels);
 

	
 
public slots:
 
    void showGrid(bool show = true);
 
    void showMinorGrid(bool show = true);
 
    void showLegend(bool show = true);
 
    void showDemoIndicator(bool show = true);
 
    void showNoChannel(bool show = true);
src/plotcontrolpanel.cpp
Show inline comments
 
/*
 
  Copyright © 2018 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -18,16 +18,16 @@
 
*/
 

	
 
#include <QVariant>
 
#include <QMessageBox>
 
#include <QCheckBox>
 
#include <QStyledItemDelegate>
 
#include <QColorDialog>
 

	
 
#include <math.h>
 

	
 
#include "color_selector.hpp"
 
#include "plotcontrolpanel.h"
 
#include "ui_plotcontrolpanel.h"
 
#include "setting_defines.h"
 

	
 
/// Confirm if #samples is being set to a value greater than this
 
const int NUMSAMPLES_CONFIRM_AT = 1000000;
 
@@ -159,15 +159,15 @@ PlotControlPanel::PlotControlPanel(QWidg
 
    ui->cbRangePresets->addItem("0 to +100", QVariant::fromValue(Range{0, +100}));
 

	
 
    QObject::connect(ui->cbRangePresets, SIGNAL(activated(int)),
 
                     this, SLOT(onRangeSelected()));
 

	
 
    // color selector starts disabled until a channel is selected
 
    ui->colorSelector->setColor(QColor(0,0,0,0));
 
    ui->colorSelector->setDisplayMode(color_widgets::ColorPreview::AllAlpha);
 
    ui->colorSelector->setDisabled(true);
 
    ui->pbColorSel->setDisabled(true);
 
    setSelectorColor(QColor(0,0,0,0));
 
    connect(ui->pbColorSel, &QPushButton::clicked, this, &PlotControlPanel::onColorSelect);
 

	
 
    // reset buttons
 
    resetAct.setToolTip(tr("Reset channel names and colors"));
 
    resetMenu.addAction(&resetNamesAct);
 
    resetMenu.addAction(&resetColorsAct);
 
    resetMenu.addAction(&resetGainsAct);
 
@@ -238,12 +238,36 @@ bool PlotControlPanel::askNSConfirmation
 

	
 
    mb.setCheckBox(cb);
 

	
 
    return mb.exec() == QMessageBox::Apply;
 
}
 

	
 
void PlotControlPanel::setSelectorColor(QColor color)
 
{
 
    ui->pbColorSel->setStyleSheet(QString("background-color: %1;").arg(color.name()));
 
}
 

	
 
void PlotControlPanel::onColorSelect()
 
{
 
    auto selection = ui->tvChannelInfo->selectionModel()->currentIndex();
 
    // no selection
 
    if (!selection.isValid()) return;
 

	
 
    // current color
 
    auto model = ui->tvChannelInfo->model();
 
    QColor color = model->data(selection, Qt::ForegroundRole).value<QColor>();
 

	
 
    // show dialog
 
    color = QColorDialog::getColor(color, this);
 

	
 
    if (color.isValid())        // color is set to invalid if user cancels
 
    {
 
        ui->tvChannelInfo->model()->setData(selection, color, Qt::ForegroundRole);
 
    }
 
}
 

	
 
void PlotControlPanel::onAutoScaleChecked(bool checked)
 
{
 
    if (checked)
 
    {
 
        ui->lYmin->setEnabled(false);
 
        ui->lYmax->setEnabled(false);
 
@@ -370,63 +394,45 @@ void PlotControlPanel::setChannelInfoMod
 
            {
 
                // TODO: duplicate with below lambda
 
                QColor color(0,0,0,0); // transparent
 

	
 
                if (current.isValid())
 
                {
 
                    ui->colorSelector->setEnabled(true);
 
                    ui->pbColorSel->setEnabled(true);
 
                    auto model = ui->tvChannelInfo->model();
 
                    color = model->data(current, Qt::ForegroundRole).value<QColor>();
 
                }
 
                else
 
                {
 
                    ui->colorSelector->setDisabled(true);
 
                    ui->pbColorSel->setDisabled(true);
 
                }
 

	
 
                // temporarily block signals because `setColor` emits `colorChanged`
 
                bool wasBlocked = ui->colorSelector->blockSignals(true);
 
                ui->colorSelector->setColor(color);
 
                ui->colorSelector->blockSignals(wasBlocked);
 
                setSelectorColor(color);
 
            });
 

	
 
    connect(ui->tvChannelInfo->selectionModel(), &QItemSelectionModel::selectionChanged,
 
            [this](const QItemSelection & selected, const QItemSelection & deselected)
 
            {
 
                if (!selected.length())
 
                {
 
                    ui->colorSelector->setDisabled(true);
 

	
 
                    // temporarily block signals because `setColor` emits `colorChanged`
 
                    bool wasBlocked = ui->colorSelector->blockSignals(true);
 
                    ui->colorSelector->setColor(QColor(0,0,0,0));
 
                    ui->colorSelector->blockSignals(wasBlocked);
 
                    ui->pbColorSel->setDisabled(true);
 
                    setSelectorColor(QColor(0,0,0,0));
 
                }
 
            });
 

	
 
    connect(ui->colorSelector, &color_widgets::ColorSelector::colorChanged,
 
            [this](QColor color)
 
            {
 
                auto index = ui->tvChannelInfo->selectionModel()->currentIndex();
 
                ui->tvChannelInfo->model()->setData(index, color, Qt::ForegroundRole);
 
            });
 

	
 
    connect(model, &QAbstractItemModel::dataChanged,
 
            [this](const QModelIndex & topLeft, const QModelIndex & bottomRight, const QVector<int> & roles = QVector<int> ())
 
            {
 
                auto current = ui->tvChannelInfo->selectionModel()->currentIndex();
 

	
 
                // no current selection
 
                if (!current.isValid()) return;
 

	
 
                auto mod = ui->tvChannelInfo->model();
 
                QColor color = mod->data(current, Qt::ForegroundRole).value<QColor>();
 

	
 
                // temporarily block signals because `setColor` emits `colorChanged`
 
                bool wasBlocked = ui->colorSelector->blockSignals(true);
 
                ui->colorSelector->setColor(color);
 
                ui->colorSelector->blockSignals(wasBlocked);
 
                setSelectorColor(color);
 
            });
 

	
 
    // reset actions
 
    connect(&resetAct, &QAction::triggered, model, &ChannelInfoModel::resetInfos);
 
    connect(&resetNamesAct, &QAction::triggered, model, &ChannelInfoModel::resetNames);
 
    connect(&resetColorsAct, &QAction::triggered, model, &ChannelInfoModel::resetColors);
src/plotcontrolpanel.h
Show inline comments
 
/*
 
  Copyright © 2018 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -76,17 +76,21 @@ private:
 
    QMenu resetMenu;
 
    QStyledItemDelegate* delegate;
 

	
 
    /// Show a confirmation dialog before setting #samples to a big value
 
    bool askNSConfirmation(int value);
 

	
 
    /// Set the color displayed by color selector button
 
    void setSelectorColor(QColor color);
 

	
 
private slots:
 
    void onNumOfSamples(int value);
 
    void onAutoScaleChecked(bool checked);
 
    void onYScaleChanged();
 
    void onRangeSelected();
 
    void onIndexChecked(bool checked);
 
    void onXScaleChanged();
 
    void onPlotWidthChanged();
 
    void onColorSelect();
 
};
 

	
 
#endif // PLOTCONTROLPANEL_H
src/plotcontrolpanel.ui
Show inline comments
 
@@ -4,13 +4,13 @@
 
 <widget class="QWidget" name="PlotControlPanel">
 
  <property name="geometry">
 
   <rect>
 
    <x>0</x>
 
    <y>0</y>
 
    <width>704</width>
 
    <height>195</height>
 
    <height>220</height>
 
   </rect>
 
  </property>
 
  <property name="windowTitle">
 
   <string>Form</string>
 
  </property>
 
  <layout class="QHBoxLayout" name="horizontalLayout">
 
@@ -66,15 +66,15 @@
 
         <number>3</number>
 
        </property>
 
        <property name="sizeConstraint">
 
         <enum>QLayout::SetMaximumSize</enum>
 
        </property>
 
        <item>
 
         <widget class="color_widgets::ColorSelector" name="colorSelector" native="true">
 
         <widget class="QPushButton" name="pbColorSel">
 
          <property name="sizePolicy">
 
           <sizepolicy hsizetype="Maximum" vsizetype="Preferred">
 
           <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
 
            <horstretch>0</horstretch>
 
            <verstretch>0</verstretch>
 
           </sizepolicy>
 
          </property>
 
          <property name="minimumSize">
 
           <size>
 
@@ -85,12 +85,21 @@
 
          <property name="maximumSize">
 
           <size>
 
            <width>20</width>
 
            <height>20</height>
 
           </size>
 
          </property>
 
          <property name="styleSheet">
 
           <string notr="true">background-color: rgb(70, 141, 255);</string>
 
          </property>
 
          <property name="text">
 
           <string/>
 
          </property>
 
          <property name="flat">
 
           <bool>false</bool>
 
          </property>
 
         </widget>
 
        </item>
 
        <item>
 
         <spacer name="horizontalSpacer">
 
          <property name="orientation">
 
           <enum>Qt::Horizontal</enum>
 
@@ -408,17 +417,9 @@
 
      </widget>
 
     </item>
 
    </layout>
 
   </item>
 
  </layout>
 
 </widget>
 
 <customwidgets>
 
  <customwidget>
 
   <class>color_widgets::ColorSelector</class>
 
   <extends>QWidget</extends>
 
   <header>color_selector.hpp</header>
 
   <container>1</container>
 
  </customwidget>
 
 </customwidgets>
 
 <resources/>
 
 <connections/>
 
</ui>
src/plotmanager.cpp
Show inline comments
 
/*
 
  Copyright © 2018 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -16,27 +16,26 @@
 
  You should have received a copy of the GNU General Public License
 
  along with serialplot.  If not, see <http://www.gnu.org/licenses/>.
 
*/
 

	
 
#include <algorithm>
 
#include <QMetaEnum>
 
#include <QtDebug>
 
#include "qwt_symbol.h"
 

	
 
#include "plot.h"
 
#include "plotmanager.h"
 
#include "utils.h"
 
#include "setting_defines.h"
 

	
 
PlotManager::PlotManager(QWidget* plotArea, PlotMenu* menu,
 
                         const Stream* stream, QObject* parent) :
 
    QObject(parent)
 
{
 
    _stream = stream;
 
    construct(plotArea, menu);
 
    _stream = stream;
 
    if (_stream == NULL) return;
 
    if (_stream == nullptr) return;
 

	
 
    // connect to ChannelInfoModel
 
    infoModel = _stream->infoModel();
 
    connect(infoModel, &QAbstractItemModel::dataChanged,
 
                this, &PlotManager::onChannelInfoChanged);
 
    connect(infoModel, &QAbstractItemModel::modelReset,
 
@@ -50,34 +49,37 @@ PlotManager::PlotManager(QWidget* plotAr
 
    connect(stream, &Stream::numChannelsChanged, this, &PlotManager::onNumChannelsChanged);
 
    connect(stream, &Stream::dataAdded, this, &PlotManager::replot);
 

	
 
    // add initial curves if any?
 
    for (unsigned int i = 0; i < stream->numChannels(); i++)
 
    {
 
        addCurve(stream->channel(i)->name(), stream->channel(i)->yData());
 
        addCurve(stream->channel(i)->name(), stream->channel(i)->xData(), stream->channel(i)->yData());
 
    }
 

	
 
}
 

	
 
PlotManager::PlotManager(QWidget* plotArea, PlotMenu* menu,
 
                         Snapshot* snapshot, QObject *parent) :
 
    QObject(parent)
 
{
 
    _stream = nullptr;
 
    construct(plotArea, menu);
 

	
 
    setNumOfSamples(snapshot->numSamples());
 
    setPlotWidth(snapshot->numSamples());
 
    infoModel = snapshot->infoModel();
 

	
 
    for (unsigned ci = 0; ci < snapshot->numChannels(); ci++)
 
    {
 
        addCurve(snapshot->channelName(ci), snapshot->yData[ci]);
 
        addCurve(snapshot->channelName(ci), snapshot->xData[ci], snapshot->yData[ci]);
 
    }
 

	
 
    connect(infoModel, &QAbstractItemModel::dataChanged,
 
            this, &PlotManager::onChannelInfoChanged);
 

	
 
    // TODO: remove when snapshot view supports multi display
 
    checkNoVisChannels();
 
}
 

	
 
void PlotManager::construct(QWidget* plotArea, PlotMenu* menu)
 
{
 
    _menu = menu;
 
    _plotArea = plotArea;
 
@@ -91,14 +93,12 @@ void PlotManager::construct(QWidget* plo
 
    showSymbols = Plot::ShowSymbolsAuto;
 
    emptyPlot = NULL;
 

	
 
    // initalize layout and single widget
 
    isMulti = false;
 
    scrollArea = NULL;
 
    setupLayout(isMulti);
 
    addPlotWidget();
 

	
 
    // connect to  menu
 
    connect(menu, &PlotMenu::symbolShowChanged, this, &PlotManager:: setSymbols);
 

	
 
    connect(&menu->showGridAction, SELECT<bool>::OVERLOAD_OF(&QAction::toggled),
 
            this, &PlotManager::showGrid);
 
@@ -145,13 +145,13 @@ void PlotManager::onNumChannelsChanged(u
 

	
 
    if (numOfChannels > oldNum)
 
    {
 
        // add new channels
 
        for (unsigned int i = oldNum; i < numOfChannels; i++)
 
        {
 
            addCurve(_stream->channel(i)->name(), _stream->channel(i)->yData());
 
            addCurve(_stream->channel(i)->name(), _stream->channel(i)->xData(), _stream->channel(i)->yData());
 
        }
 
    }
 
    else if(numOfChannels < oldNum)
 
    {
 
        removeCurves(oldNum - numOfChannels);
 
    }
 
@@ -214,14 +214,12 @@ void PlotManager::checkNoVisChannels()
 
        plotWidgets[0]->setVisible(true);
 
    }
 
}
 

	
 
void PlotManager::setMulti(bool enabled)
 
{
 
    if (enabled == isMulti) return;
 

	
 
    isMulti = enabled;
 

	
 
    // detach all curves
 
    for (auto curve : curves)
 
    {
 
        curve->detach();
 
@@ -236,24 +234,32 @@ void PlotManager::setMulti(bool enabled)
 
    // setup new layout
 
    setupLayout(isMulti);
 

	
 
    if (isMulti)
 
    {
 
        // add new widgets and attach
 
        int i = 0;
 
        for (auto curve : curves)
 
        {
 
            auto plot = addPlotWidget();
 
            plot->setVisible(curve->isVisible());
 
            plot->setDispChannels(QVector<const StreamChannel*>(1, _stream->channel(i)));
 
            curve->attach(plot);
 
            i++;
 
        }
 
    }
 
    else
 
    {
 
        // add a single widget
 
        auto plot = addPlotWidget();
 

	
 
        if (_stream != nullptr)
 
        {
 
            plot->setDispChannels(_stream->allChannels());
 
        }
 

	
 
        // attach all curves
 
        for (auto curve : curves)
 
        {
 
            curve->attach(plot);
 
        }
 
    }
 
@@ -329,17 +335,16 @@ Plot* PlotManager::addPlotWidget()
 
        plot->setXAxis(_xMin, _xMax);
 
    }
 

	
 
    return plot;
 
}
 

	
 
void PlotManager::addCurve(QString title, const FrameBuffer* buffer)
 
void PlotManager::addCurve(QString title, const XFrameBuffer* xBuf, const FrameBuffer* yBuf)
 
{
 
    auto curve = new QwtPlotCurve(title);
 
    auto series = new FrameBufferSeries(buffer);
 
    series->setXAxis(_xAxisAsIndex, _xMin, _xMax);
 
    auto series = new FrameBufferSeries(xBuf, yBuf);
 
    curve->setSamples(series);
 
    _addCurve(curve);
 
}
 

	
 
void PlotManager::_addCurve(QwtPlotCurve* curve)
 
{
 
@@ -359,19 +364,43 @@ void PlotManager::_addCurve(QwtPlotCurve
 
    }
 
    else
 
    {
 
        plot = plotWidgets[0];
 
    }
 

	
 
    if (_stream != nullptr)     // not displaying snapshot
 
    {
 
        QVector<const StreamChannel*> dispChannels;
 
        if (isMulti)
 
        {
 
            dispChannels = QVector<const StreamChannel*>(1, _stream->channel(index));
 
        }
 
        else
 
        {
 
            dispChannels = _stream->allChannels();
 
        }
 
        plot->setDispChannels(dispChannels);
 
    }
 

	
 
    // show the curve
 
    curve->attach(plot);
 
    plot->replot();
 
}
 

	
 
void PlotManager::removeCurves(unsigned number)
 
{
 
    if (_stream != nullptr)     // not displaying snapshot
 
    {
 
        if (! isMulti)
 
        {
 
            QVector<const StreamChannel*> dispChannels;
 
            dispChannels = _stream->allChannels();
 
            plotWidgets[0]->setDispChannels(dispChannels);
 
        }
 
    }
 

	
 
    for (unsigned i = 0; i < number; i++)
 
    {
 
        if (!curves.isEmpty())
 
        {
 
            delete curves.takeLast();
 
            if (isMulti) // delete corresponding widget as well
 
@@ -478,16 +507,19 @@ void PlotManager::setYAxis(bool autoScal
 

	
 
void PlotManager::setXAxis(bool asIndex, double xMin, double xMax)
 
{
 
    _xAxisAsIndex = asIndex;
 
    _xMin = xMin;
 
    _xMax = xMax;
 

	
 
    int ci = 0;
 
    for (auto curve : curves)
 
    {
 
        FrameBufferSeries* series = static_cast<FrameBufferSeries*>(curve->data());
 
        series->setXAxis(asIndex, xMin, xMax);
 
        series->setX(_stream->channel(ci)->xData());
 
        ci++;
 
    }
 
    for (auto plot : plotWidgets)
 
    {
 
        if (asIndex)
 
        {
 
            plot->setXAxis(0, _numOfSamples);
src/plotmanager.h
Show inline comments
 
@@ -38,21 +38,21 @@
 
class PlotManager : public QObject
 
{
 
    Q_OBJECT
 

	
 
public:
 
    explicit PlotManager(QWidget* plotArea, PlotMenu* menu,
 
                         const Stream* stream = NULL,
 
                         const Stream* stream = nullptr,
 
                         QObject *parent = 0);
 
    explicit PlotManager(QWidget* plotArea, PlotMenu* menu,
 
                         Snapshot* snapshot,
 
                         QObject *parent = 0);
 
    ~PlotManager();
 
    /// Add a new curve with title and buffer. A color is
 
    /// automatically chosen for curve.
 
    void addCurve(QString title, const FrameBuffer* buffer);
 
    void addCurve(QString title, const XFrameBuffer* xBuf, const FrameBuffer* yBuf);
 
    /// Removes curves from the end
 
    void removeCurves(unsigned number);
 
    /// Returns current number of curves known by plot manager
 
    unsigned numOfCurves();
 

	
 
public slots:
 
@@ -79,13 +79,13 @@ private:
 
    PlotMenu* _menu;
 
    QVBoxLayout* layout; ///< layout of the `plotArea`
 
    QScrollArea* scrollArea;
 
    QList<QwtPlotCurve*> curves;
 
    QList<Plot*> plotWidgets;
 
    Plot* emptyPlot;  ///< for displaying when all channels are hidden
 
    const Stream* _stream;       ///< attached stream, can be `NULL`
 
    const Stream* _stream;       ///< attached stream, can be `nullptr`
 
    const ChannelInfoModel* infoModel;
 
    bool isDemoShown;
 
    bool _autoScaled;
 
    double _yMin;
 
    double _yMax;
 
    bool _xAxisAsIndex;
src/plotmenu.cpp
Show inline comments
 
/*
 
  Copyright © 2017 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -63,32 +63,32 @@ PlotMenu::PlotMenu(QWidget* parent) :
 
            &showMinorGridAction, &QAction::setEnabled);
 

	
 
    // setup set symbols menu
 
    setSymbolsMenu.addAction(&setSymbolsAutoAct);
 
    setSymbolsAutoAct.setCheckable(true);
 
    setSymbolsAutoAct.setChecked(true);
 
    connect(&setSymbolsAutoAct, SELECT<bool>::OVERLOAD_OF(&QAction::triggered),
 
    connect(&setSymbolsAutoAct, SELECT<bool>::OVERLOAD_OF(&QAction::toggled),
 
            [this](bool checked)
 
            {
 
                if (checked) emit symbolShowChanged(Plot::ShowSymbolsAuto);
 
            });
 

	
 
    setSymbolsMenu.addAction(&setSymbolsShowAct);
 
    setSymbolsShowAct.setCheckable(true);
 
    connect(&setSymbolsShowAct, SELECT<bool>::OVERLOAD_OF(&QAction::triggered),
 
    connect(&setSymbolsShowAct, SELECT<bool>::OVERLOAD_OF(&QAction::toggled),
 
            [this](bool checked)
 
            {
 
                if (checked) symbolShowChanged(Plot::ShowSymbolsShow);
 
                if (checked) emit symbolShowChanged(Plot::ShowSymbolsShow);
 
            });
 

	
 
    setSymbolsMenu.addAction(&setSymbolsHideAct);
 
    setSymbolsHideAct.setCheckable(true);
 
    connect(&setSymbolsHideAct, SELECT<bool>::OVERLOAD_OF(&QAction::triggered),
 
    connect(&setSymbolsHideAct, SELECT<bool>::OVERLOAD_OF(&QAction::toggled),
 
            [this](bool checked)
 
            {
 
                if (checked) symbolShowChanged(Plot::ShowSymbolsHide);
 
                if (checked) emit symbolShowChanged(Plot::ShowSymbolsHide);
 
            });
 

	
 
    // add symbol actions to same group so that they appear as radio buttons
 
    auto group = new QActionGroup(this);
 
    group->addAction(&setSymbolsAutoAct);
 
    group->addAction(&setSymbolsShowAct);
 
@@ -199,26 +199,23 @@ void PlotMenu::loadSettings(QSettings* s
 
    showMultiAction.setChecked(
 
        settings->value(SG_Plot_MultiPlot, showMultiAction.isChecked()).toBool());
 

	
 
    QString showSymbolsStr = settings->value(SG_Plot_Symbols, QString()).toString();
 
    if (showSymbolsStr == "auto")
 
    {
 
        // setSymbols(Plot::ShowSymbolsAuto);
 
        setSymbolsAutoAct.setChecked(true);
 
    }
 
    else if (showSymbolsStr == "show")
 
    {
 
        // setSymbols(Plot::ShowSymbolsShow);
 
        setSymbolsShowAct.setChecked(true);
 
    }
 
    else if (showSymbolsStr == "hide")
 
    {
 
        // setSymbols(Plot::ShowSymbolsHide);
 
        setSymbolsHideAct.setChecked(true);
 
    }
 
    else
 
    else if (!showSymbolsStr.isEmpty())
 
    {
 
        qCritical() << "Invalid symbol setting:" << showSymbolsStr;
 
    }
 

	
 
    settings->endGroup();
 
}
src/portcontrol.cpp
Show inline comments
 
/*
 
  Copyright © 2017 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -76,25 +76,25 @@ PortControl::PortControl(QSerialPort* po
 
                     this, &PortControl::onCbPortListActivated);
 
    QObject::connect(&tbPortList,
 
                     SELECT<int>::OVERLOAD_OF(&QComboBox::activated),
 
                     this, &PortControl::onTbPortListActivated);
 
    QObject::connect(ui->cbPortList,
 
                     SELECT<const QString&>::OVERLOAD_OF(&QComboBox::activated),
 
                     this, &PortControl::selectPort);
 
                     this, &PortControl::selectListedPort);
 
    QObject::connect(&tbPortList,
 
                     SELECT<const QString&>::OVERLOAD_OF(&QComboBox::activated),
 
                     this, &PortControl::selectPort);
 
                     this, &PortControl::selectListedPort);
 

	
 
    // setup buttons
 
    ui->pbOpenPort->setDefaultAction(&openAction);
 
    ui->pbReloadPorts->setDefaultAction(&loadPortListAction);
 

	
 
    // setup baud rate selection widget
 
    QObject::connect(ui->cbBaudRate,
 
                     SELECT<const QString&>::OVERLOAD_OF(&QComboBox::activated),
 
                     this, &PortControl::selectBaudRate);
 
                     this, &PortControl::_selectBaudRate);
 

	
 
    // setup parity selection buttons
 
    parityButtons.addButton(ui->rbNoParity, (int) QSerialPort::NoParity);
 
    parityButtons.addButton(ui->rbEvenParity, (int) QSerialPort::EvenParity);
 
    parityButtons.addButton(ui->rbOddParity, (int) QSerialPort::OddParity);
 

	
 
@@ -195,13 +195,13 @@ void PortControl::loadBaudRateList()
 
    for (auto baudRate : QSerialPortInfo::standardBaudRates())
 
    {
 
        ui->cbBaudRate->addItem(QString::number(baudRate));
 
    }
 
}
 

	
 
void PortControl::selectBaudRate(QString baudRate)
 
void PortControl::_selectBaudRate(QString baudRate)
 
{
 
    if (serialPort->isOpen())
 
    {
 
        if (!serialPort->setBaudRate(baudRate.toInt()))
 
        {
 
            qCritical() << "Can't set baud rate!";
 
@@ -286,13 +286,13 @@ void PortControl::togglePort()
 
        serialPort->setPortName(ui->cbPortList->currentData(PortNameRole).toString());
 

	
 
        // open port
 
        if (serialPort->open(QIODevice::ReadWrite))
 
        {
 
            // set port settings
 
            selectBaudRate(ui->cbBaudRate->currentText());
 
            _selectBaudRate(ui->cbBaudRate->currentText());
 
            selectParity((QSerialPort::Parity) parityButtons.checkedId());
 
            selectDataBits((QSerialPort::DataBits) dataBitsButtons.checkedId());
 
            selectStopBits((QSerialPort::StopBits) stopBitsButtons.checkedId());
 
            selectFlowControl((QSerialPort::FlowControl) flowControlButtons.checkedId());
 

	
 
            // set output signals
 
@@ -307,16 +307,23 @@ void PortControl::togglePort()
 
            emit portToggled(true);
 
        }
 
    }
 
    openAction.setChecked(serialPort->isOpen());
 
}
 

	
 
void PortControl::selectPort(QString portName)
 
void PortControl::selectListedPort(QString portName)
 
{
 
    // portName may be coming from combobox
 
    portName = portName.split(" ")[0];
 

	
 
    QSerialPortInfo portInfo(portName);
 
    if (portInfo.isNull())
 
    {
 
        qWarning() << "Device doesn't exists:" << portName;
 
    }
 

	
 
    // has selection actually changed
 
    if (portName != serialPort->portName())
 
    {
 
        // if another port is already open, close it by toggling
 
        if (serialPort->isOpen())
 
        {
 
@@ -363,12 +370,19 @@ void PortControl::onTbPortListActivated(
 
{
 
    ui->cbPortList->setCurrentIndex(index);
 
}
 

	
 
void PortControl::onPortError(QSerialPort::SerialPortError error)
 
{
 
#ifdef Q_OS_UNIX
 
    // For suppressing "Invalid argument" errors that happens with pseudo terminals
 
    auto isPtsInvalidArgErr = [this] () -> bool {
 
        return serialPort->portName().contains("pts/") && serialPort->errorString().contains("Invalid argument");
 
    };
 
#endif
 

	
 
    switch(error)
 
    {
 
        case QSerialPort::NoError :
 
            break;
 
        case QSerialPort::ResourceError :
 
            qWarning() << "Port error: resource unavaliable; most likely device removed.";
 
@@ -405,18 +419,28 @@ required privileges or device is already
 
            qCritical() << "An error occurred while writing data.";
 
            break;
 
        case QSerialPort::ReadError:
 
            qCritical() << "An error occurred while reading data.";
 
            break;
 
        case QSerialPort::UnsupportedOperationError:
 
#ifdef Q_OS_UNIX
 
            // Qt 5.5 gives "Invalid argument" with 'UnsupportedOperationError'
 
            if (isPtsInvalidArgErr())
 
                break;
 
#endif
 
            qCritical() << "Operation is not supported.";
 
            break;
 
        case QSerialPort::TimeoutError:
 
            qCritical() << "A timeout error occurred.";
 
            break;
 
        case QSerialPort::UnknownError:
 
#ifdef Q_OS_UNIX
 
            // Qt 5.2 gives "Invalid argument" with 'UnknownError'
 
            if (isPtsInvalidArgErr())
 
                break;
 
#endif
 
            qCritical() << "Unknown error! Error: " << serialPort->errorString();
 
            break;
 
        default:
 
            qCritical() << "Unhandled port error: " << error;
 
            break;
 
    }
 
@@ -450,12 +474,70 @@ QString PortControl::currentFlowControlT
 
    else // no parity
 
    {
 
        return "none";
 
    }
 
}
 

	
 
void PortControl::selectPort(QString portName)
 
{
 
    int portIndex = portList.indexOfName(portName);
 
    if (portIndex < 0) // not in list, add to model and update the selections
 
    {
 
        portList.appendRow(new PortListItem(portName));
 
        portIndex = portList.rowCount()-1;
 
    }
 

	
 
    ui->cbPortList->setCurrentIndex(portIndex);
 
    tbPortList.setCurrentIndex(portIndex);
 

	
 
    selectListedPort(portName);
 
}
 

	
 
void PortControl::selectBaudrate(QString baudRate)
 
{
 
    int baudRateIndex = ui->cbBaudRate->findText(baudRate);
 
    if (baudRateIndex < 0)
 
    {
 
        ui->cbBaudRate->setCurrentText(baudRate);
 
    }
 
    else
 
    {
 
        ui->cbBaudRate->setCurrentIndex(baudRateIndex);
 
    }
 
    _selectBaudRate(baudRate);
 
}
 

	
 
void PortControl::openPort()
 
{
 
    if (!serialPort->isOpen())
 
    {
 
        openAction.trigger();
 
    }
 
}
 

	
 
unsigned PortControl::maxBitRate() const
 
{
 
    float baud = serialPort->baudRate();
 
    float dataBits = serialPort->dataBits();
 
    float parityBits = serialPort->parity() == QSerialPort::NoParity ? 0 : 1;
 

	
 
    float stopBits;
 
    if (serialPort->stopBits() == QSerialPort::OneAndHalfStop)
 
    {
 
        stopBits = 1.5;
 
    }
 
    else
 
    {
 
        stopBits = serialPort->stopBits();
 
    }
 

	
 
    float frame_size = 1 /* start bit */ + dataBits + parityBits + stopBits;
 

	
 
    return float(baud) / frame_size;
 
}
 

	
 
void PortControl::saveSettings(QSettings* settings)
 
{
 
    settings->beginGroup(SettingGroup_Port);
 
    settings->setValue(SG_Port_SelectedPort, selectedPortName());
 
    settings->setValue(SG_Port_BaudRate, ui->cbBaudRate->currentText());
 
    settings->setValue(SG_Port_Parity, currentParityText());
 
@@ -491,13 +573,13 @@ void PortControl::loadSettings(QSettings
 
        settings->value(SG_Port_Parity, currentParityText()).toString();
 
    QSerialPort::Parity paritySetting = paritySettingMap.key(
 
        parityText, (QSerialPort::Parity) parityButtons.checkedId());
 
    parityButtons.button(paritySetting)->setChecked(true);
 

	
 
    // load number of bits
 
    int dataBits = settings->value(SG_Port_Parity, dataBitsButtons.checkedId()).toInt();
 
    int dataBits = settings->value(SG_Port_DataBits, dataBitsButtons.checkedId()).toInt();
 
    if (dataBits >=5 && dataBits <= 8)
 
    {
 
        dataBitsButtons.button((QSerialPort::DataBits) dataBits)->setChecked(true);
 
    }
 

	
 
    // load stop bits
src/portcontrol.h
Show inline comments
 
/*
 
  Copyright © 2017 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -44,12 +44,18 @@ public:
 
    explicit PortControl(QSerialPort* port, QWidget* parent = 0);
 
    ~PortControl();
 

	
 
    QSerialPort* serialPort;
 
    QToolBar* toolBar();
 

	
 
    void selectPort(QString portName);
 
    void selectBaudrate(QString baudRate);
 
    void openPort();
 
    /// Returns maximum bit rate for current baud rate
 
    unsigned maxBitRate() const;
 

	
 
    /// Stores port settings into a `QSettings`
 
    void saveSettings(QSettings* settings);
 
    /// Loads port settings from a `QSettings`. If open serial port is closed.
 
    void loadSettings(QSettings* settings);
 

	
 
private:
 
@@ -73,25 +79,24 @@ private:
 
    QString selectedPortName();
 
    /// Returns currently selected parity as text to be saved in settings
 
    QString currentParityText();
 
    /// Returns currently selected flow control as text to be saved in settings
 
    QString currentFlowControlText();
 

	
 
public slots:
 
private slots:
 
    void loadPortList();
 
    void loadBaudRateList();
 
    void togglePort();
 
    void selectPort(QString portName);
 
    void selectListedPort(QString portName);
 

	
 
    void selectBaudRate(QString baudRate);
 
    void _selectBaudRate(QString baudRate);
 
    void selectParity(int parity); // parity must be one of QSerialPort::Parity
 
    void selectDataBits(int dataBits); // bits must be one of QSerialPort::DataBits
 
    void selectStopBits(int stopBits); // stopBits must be one of QSerialPort::StopBits
 
    void selectFlowControl(int flowControl); // flowControl must be one of QSerialPort::FlowControl
 

	
 
private slots:
 
    void openActionTriggered(bool checked);
 
    void onCbPortListActivated(int index);
 
    void onTbPortListActivated(int index);
 
    void onPortError(QSerialPort::SerialPortError error);
 
    void updatePinLeds(void);
 

	
src/setting_defines.h
Show inline comments
 
/*
 
  Copyright © 2018 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -27,12 +27,13 @@ const char SettingGroup_Binary[] = "Data
 
const char SettingGroup_ASCII[] = "DataFormat_ASCII";
 
const char SettingGroup_CustomFrame[] = "DataFormat_CustomFrame";
 
const char SettingGroup_Channels[] = "Channels";
 
const char SettingGroup_Plot[] = "Plot";
 
const char SettingGroup_Commands[] = "Commands";
 
const char SettingGroup_Record[] = "Record";
 
const char SettingGroup_TextView[] = "TextView";
 
const char SettingGroup_UpdateCheck[] = "UpdateCheck";
 

	
 
// mainwindow setting keys
 
const char SG_MainWindow_Size[] = "size";
 
const char SG_MainWindow_Pos[] = "pos";
 
const char SG_MainWindow_ActivePanel[] = "activePanel";
 
@@ -109,11 +110,15 @@ const char SG_Record_RecordPaused[]     
 
const char SG_Record_StopOnClose[]      = "stopOnClose";
 
const char SG_Record_Header[]           = "header";
 
const char SG_Record_Separator[]        = "separator";
 
const char SG_Record_DisableBuffering[] = "disableBuffering";
 
const char SG_Record_Timestamp[]        = "timestamp";
 

	
 
// text view settings keys
 
const char SG_TextView_NumLines[] = "numLines";
 
const char SG_TextView_Decimals[] = "decimals";
 

	
 
// update check settings keys
 
const char SG_UpdateCheck_Periodic[]  = "periodicCheck";
 
const char SG_UpdateCheck_LastCheck[] = "lastCheck";
 

	
 
#endif // SETTING_DEFINES_H
src/snapshot.h
Show inline comments
 
@@ -25,25 +25,27 @@
 
#include <QVector>
 
#include <QString>
 
#include <QStringList>
 

	
 
#include "channelinfomodel.h"
 
#include "readonlybuffer.h"
 
#include "indexbuffer.h"
 

	
 
class SnapshotView;
 
class MainWindow;
 

	
 
class Snapshot : public QObject
 
{
 
    Q_OBJECT
 

	
 
public:
 
    Snapshot(MainWindow* parent, QString name, ChannelInfoModel infoModel, bool saved = false);
 
    ~Snapshot();
 

	
 
    // TODO: yData of snapshot shouldn't be public, preferable should be handled in constructor
 
    // TODO: yData and xData of snapshot shouldn't be public, preferable should be handled in constructor
 
    QVector<IndexBuffer*> xData;
 
    QVector<ReadOnlyBuffer*> yData;
 
    QAction* showAction();
 
    QAction* deleteAction();
 

	
 
    QString name();
 
    QString displayName(); ///< `name()` plus '*' if snapshot is not saved
src/snapshotmanager.cpp
Show inline comments
 
/*
 
  Copyright © 2018 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -68,12 +68,13 @@ Snapshot* SnapshotManager::makeSnapshot(
 
{
 
    QString name = QTime::currentTime().toString("'Snapshot ['HH:mm:ss']'");
 
    auto snapshot = new Snapshot(_mainWindow, name, *(_stream->infoModel()));
 

	
 
    for (unsigned ci = 0; ci < _stream->numChannels(); ci++)
 
    {
 
        snapshot->xData.append(new IndexBuffer(_stream->numSamples()));
 
        snapshot->yData.append(new ReadOnlyBuffer(_stream->channel(ci)->yData()));
 
    }
 

	
 
    return snapshot;
 
}
 

	
 
@@ -153,14 +154,22 @@ void SnapshotManager::loadSnapshotFromFi
 

	
 
    // read data
 
    QVector<QVector<double>> data(numOfChannels);
 
    QTextStream ts(&file);
 
    QString line;
 
    unsigned lineNum = 1;
 

	
 
#if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
 
    while (ts.readLineInto(&line))
 
    {
 
#else
 
    while (true)
 
    {
 
        line = ts.readLine();
 
        if (line.isNull()) break;
 
#endif
 
        // parse line
 
        auto split = line.split(',');
 

	
 
        if (split.size() != (int) numOfChannels)
 
        {
 
            qCritical() << "Parsing error at line " << lineNum
 
@@ -191,12 +200,13 @@ void SnapshotManager::loadSnapshotFromFi
 
    auto snapshot = new Snapshot(
 
        _mainWindow, QFileInfo(fileName).baseName(),
 
        ChannelInfoModel(channelNames), true);
 

	
 
    for (unsigned ci = 0; ci < numOfChannels; ci++)
 
    {
 
        snapshot->xData.append(new IndexBuffer(data[ci].size()));
 
        snapshot->yData.append(new ReadOnlyBuffer(data[ci].data(), data[ci].size()));
 
    }
 

	
 
    addSnapshot(snapshot, false);
 
}
 

	
src/stream.cpp
Show inline comments
 
@@ -17,28 +17,34 @@
 
  along with serialplot.  If not, see <http://www.gnu.org/licenses/>.
 
*/
 

	
 
#include "stream.h"
 
#include "ringbuffer.h"
 
#include "indexbuffer.h"
 
#include "linindexbuffer.h"
 

	
 
Stream::Stream(unsigned nc, bool x, unsigned ns) :
 
    _infoModel(nc)
 
{
 
    _numSamples = ns;
 
    _paused = false;
 

	
 
    xAsIndex = true;
 
    xMin = 0;
 
    xMax = 1;
 

	
 
    // create xdata buffer
 
    _hasx = x;
 
    if (x)
 
    {
 
        xData = new RingBuffer(ns);
 
        // TODO: implement XRingBuffer (binary search)
 
        Q_ASSERT(false);
 
    }
 
    else
 
    {
 
        xData = new IndexBuffer(ns);
 
        xData = makeXBuffer();
 
    }
 

	
 
    // create channels
 
    for (unsigned i = 0; i < nc; i++)
 
    {
 
        auto c = new StreamChannel(i, xData, new RingBuffer(ns), &_infoModel);
 
@@ -78,12 +84,22 @@ const StreamChannel* Stream::channel(uns
 

	
 
StreamChannel* Stream::channel(unsigned index)
 
{
 
    return const_cast<StreamChannel*>(static_cast<const Stream&>(*this).channel(index));
 
}
 

	
 
QVector<const StreamChannel*> Stream::allChannels() const
 
{
 
    QVector<const StreamChannel*> result(numChannels());
 
    for (unsigned ci = 0; ci < numChannels(); ci++)
 
    {
 
        result[ci] = channel(ci);
 
    }
 
    return result;
 
}
 

	
 
const ChannelInfoModel* Stream::infoModel() const
 
{
 
    return &_infoModel;
 
}
 

	
 
ChannelInfoModel* Stream::infoModel()
 
@@ -115,17 +131,18 @@ void Stream::setNumChannels(unsigned nc,
 

	
 
    // change the xdata
 
    if (x != _hasx)
 
    {
 
        if (x)
 
        {
 
            xData = new RingBuffer(_numSamples);
 
            // TODO: implement XRingBuffer (binary search)
 
            Q_ASSERT(false);
 
        }
 
        else
 
        {
 
            xData = new IndexBuffer(_numSamples);
 
            xData = makeXBuffer();
 
        }
 

	
 
        for (auto c : channels)
 
        {
 
            c->setX(xData);
 
        }
 
@@ -139,12 +156,24 @@ void Stream::setNumChannels(unsigned nc,
 
        emit numChannelsChanged(nc);
 
    }
 

	
 
    Sink::setNumChannels(nc, x);
 
}
 

	
 
XFrameBuffer* Stream::makeXBuffer() const
 
{
 
    if (xAsIndex)
 
    {
 
        return new IndexBuffer(_numSamples);
 
    }
 
    else
 
    {
 
        return new LinIndexBuffer(_numSamples, xMin, xMax);
 
    }
 
}
 

	
 
const SamplePack* Stream::applyGainOffset(const SamplePack& pack) const
 
{
 
    Q_ASSERT(infoModel()->gainOrOffsetEn());
 

	
 
    SamplePack* mPack = new SamplePack(pack);
 
    unsigned ns = pack.numSamples();
 
@@ -188,13 +217,15 @@ void Stream::feedIn(const SamplePack& pa
 

	
 
    if (_paused) return;
 

	
 
    unsigned ns = pack.numSamples();
 
    if (_hasx)
 
    {
 
        static_cast<RingBuffer*>(xData)->addSamples(pack.xData(), ns);
 
        // TODO: implement XRingBuffer (binary search)
 
        Q_ASSERT(false);
 
        // static_cast<RingBuffer*>(xData)->addSamples(pack.xData(), ns);
 
    }
 

	
 
    // modified pack that gain and offset is applied to
 
    const SamplePack* mPack = nullptr;
 
    if (infoModel()->gainOrOffsetEn())
 
        mPack = applyGainOffset(pack);
 
@@ -234,12 +265,30 @@ void Stream::setNumSamples(unsigned valu
 
    for (auto c : channels)
 
    {
 
        static_cast<RingBuffer*>(c->yData())->resize(value);
 
    }
 
}
 

	
 
void Stream::setXAxis(bool asIndex, double min, double max)
 
{
 
    xAsIndex = asIndex;
 
    xMin = min;
 
    xMax = max;
 

	
 
    // Note that x axis scaling is ignored when X is provided from source as data
 
    // TODO: assert (UI options for x axis should be disabled)
 
    if (!hasX())
 
    {
 
        xData = makeXBuffer();
 
        for (auto c : channels)
 
        {
 
            c->setX(xData);
 
        }
 
    }
 
}
 

	
 
void Stream::saveSettings(QSettings* settings) const
 
{
 
    _infoModel.saveSettings(settings);
 
}
 

	
 
void Stream::loadSettings(QSettings* settings)
src/stream.h
Show inline comments
 
@@ -45,22 +45,22 @@ class Stream : public QObject, public Si
 
public:
 
    /**
 
     * @param nc number of channels
 
     * @param x has X data input
 
     * @param ns number of samples
 
     */
 
    Stream(unsigned nc = 0, bool x = false, unsigned ns = 0);
 
    Stream(unsigned nc = 1, bool x = false, unsigned ns = 2);
 
    ~Stream();
 

	
 
    // implementations for `Source`
 
    virtual bool hasX() const;
 
    virtual unsigned numChannels() const;
 
    bool hasX() const;
 
    unsigned numChannels() const;
 

	
 
    unsigned numSamples() const;
 
    const StreamChannel* channel(unsigned index) const;
 
    StreamChannel* channel(unsigned index);
 
    QVector<const StreamChannel*> allChannels() const;
 
    const ChannelInfoModel* infoModel() const;
 
    ChannelInfoModel* infoModel();
 

	
 
    /// Saves channel information
 
    void saveSettings(QSettings* settings) const;
 
    /// Load channel information
 
@@ -76,42 +76,51 @@ signals:
 
    void numSamplesChanged(unsigned value);
 
    void channelAdded(const StreamChannel* chan);
 
    void channelNameChanged(unsigned channel, QString name); // TODO: does it stay?
 
    void dataAdded(); ///< emitted when data added to channel man.
 

	
 
public slots:
 
    // TODO: these won't be public
 
    // void setNumChannels(unsigned number);
 
    /// Change number of samples (buffer size)
 
    void setNumSamples(unsigned value);
 

	
 
    /// Change X axis style
 
    /// @note Ignored when X is provided by source (hasX == true)
 
    void setXAxis(bool asIndex, double min, double max);
 

	
 
    /// When paused data feed is ignored
 
    void pause(bool paused);
 

	
 
    /// Clears buffer data (fills with 0)
 
    void clear();
 

	
 
private:
 
    unsigned _numSamples;
 
    bool _paused;
 

	
 
    bool _hasx;
 
    ResizableBuffer* xData;
 
    XFrameBuffer* xData;
 
    QList<StreamChannel*> channels;
 

	
 
    ChannelInfoModel _infoModel;
 

	
 
    bool xAsIndex;
 
    double xMin, xMax;
 

	
 
    /**
 
     * Applies gain and offset to given pack.
 
     *
 
     * Caller is responsible for deleting returned `SamplePack`.
 
     *
 
     * @note Should be called only when gain or offset is enabled. Guard with
 
     * `ChannelInfoModel::gainOrOffsetEn()`.
 
     *
 
     * @param pack input data
 
     * @return modified data
 
     */
 
    const SamplePack* applyGainOffset(const SamplePack& pack) const;
 

	
 
    /// Returns a new virtual X buffer for settings
 
    XFrameBuffer* makeXBuffer() const;
 
};
 

	
 

	
 
#endif // STREAM_H
src/streamchannel.cpp
Show inline comments
 
@@ -14,15 +14,16 @@
 
  GNU General Public License for more details.
 

	
 
  You should have received a copy of the GNU General Public License
 
  along with serialplot.  If not, see <http://www.gnu.org/licenses/>.
 
*/
 

	
 
#include <limits>
 
#include "streamchannel.h"
 

	
 
StreamChannel::StreamChannel(unsigned i, const FrameBuffer* x,
 
StreamChannel::StreamChannel(unsigned i, const XFrameBuffer* x,
 
              FrameBuffer* y, ChannelInfoModel* info)
 
{
 
    _index = i;
 
    _x = x;
 
    _y = y;
 
    _info = info;
 
@@ -34,11 +35,40 @@ StreamChannel::~StreamChannel()
 
}
 

	
 
unsigned StreamChannel::index() const {return _index;}
 
QString StreamChannel::name() const {return _info->name(_index);};
 
QColor StreamChannel::color() const {return _info->color(_index);};
 
bool StreamChannel::visible() const {return _info->isVisible(_index);};
 
const FrameBuffer* StreamChannel::xData() const {return _x;}
 
const XFrameBuffer* StreamChannel::xData() const {return _x;}
 
const FrameBuffer* StreamChannel::yData() const {return _y;}
 
FrameBuffer* StreamChannel::yData() {return _y;}
 
const ChannelInfoModel* StreamChannel::info() const {return _info;}
 
void StreamChannel::setX(const FrameBuffer* x) {_x = x;};
 
void StreamChannel::setX(const XFrameBuffer* x) {_x = x;};
 

	
 
double StreamChannel::findValue(double x) const
 
{
 
    int index = _x->findIndex(x);
 
    Q_ASSERT(index < (int) _x->size());
 

	
 
    if (index >= 0)
 
    {
 
        // can't do estimation for last sample
 
        if (index == (int) _x->size() - 1)
 
        {
 
            return _y->sample(index);
 
        }
 
        else
 
        {
 
            // calculate middle of the line
 
            double prev_x = _x->sample(index);
 
            double next_x = _x->sample(index+1);
 
            double ratio = (x - prev_x) / (next_x - prev_x);
 
            double prev_y = _y->sample(index);
 
            double next_y = _y->sample(index+1);
 
            return ratio * (next_y - prev_y) + prev_y;
 
        }
 
    }
 
    else
 
    {
 
        return std::numeric_limits<double>::quiet_NaN();
 
    }
 
}
src/streamchannel.h
Show inline comments
 
@@ -32,29 +32,37 @@ public:
 
     * @param i index of the channel
 
     * @param x x axis buffer
 
     * @param y data buffer of this channel, takes ownership
 
     * @param info channel info model
 
     */
 
    StreamChannel(unsigned i,
 
                  const FrameBuffer* x,
 
                  const XFrameBuffer* x,
 
                  FrameBuffer* y,
 
                  ChannelInfoModel* info);
 
    ~StreamChannel();
 

	
 
    unsigned index() const;
 
    QString name() const;
 
    QColor color() const;
 
    bool visible() const;
 
    const FrameBuffer* xData() const;
 
    const XFrameBuffer* xData() const;
 
    FrameBuffer* yData();
 
    const FrameBuffer* yData() const;
 
    const ChannelInfoModel* info() const;
 
    void setX(const FrameBuffer* x);
 
    void setX(const XFrameBuffer* x);
 

	
 
    /**
 
     * Returns sample value for `x`.
 
     *
 
     * If `x` is out of range `NaN` is returned. A calculated (linear)
 
     * value is returned when `x` is in between two data points.
 
     */
 
    double findValue(double x) const;
 

	
 
private:
 
    unsigned _index;
 
    const FrameBuffer* _x;
 
    const XFrameBuffer* _x;
 
    FrameBuffer* _y;
 
    ChannelInfoModel* _info;
 
};
 

	
 
#endif // STREAMCHANNEL_H
src/updatechecker.cpp
Show inline comments
 
@@ -115,13 +115,13 @@ bool UpdateChecker::parseData(const QJso
 
       }, ... ]
 
    }
 
    */
 

	
 
    if (!data.isObject()) return false;
 

	
 
    auto values = data.object()["values"];
 
    auto values = data.object().value("values");
 
    if (values == QJsonValue::Undefined || !values.isArray()) return false;
 

	
 
    for (auto value : values.toArray())
 
    {
 
        if (!value.isObject()) return false;
 

	
src/zoomer.cpp
Show inline comments
 
/*
 
  Copyright © 2017 Hasan Yavuz Özderya
 
  Copyright © 2020 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -16,15 +16,19 @@
 
  You should have received a copy of the GNU General Public License
 
  along with serialplot.  If not, see <http://www.gnu.org/licenses/>.
 
*/
 

	
 
#include "zoomer.h"
 
#include <qwt_plot.h>
 
#include <QtDebug>
 
#include <QPen>
 
#include <QMouseEvent>
 
#include <QtMath>
 
#include <algorithm>
 

	
 
#include <QMouseEvent>
 
static const int VALUE_POINT_DIAM = 4;
 
static const int VALUE_TEXT_MARGIN = VALUE_POINT_DIAM + 2;
 

	
 
Zoomer::Zoomer(QWidget* widget, bool doReplot) :
 
    ScrollZoomer(widget)
 
{
 
    is_panning = false;
 

	
 
@@ -56,12 +60,17 @@ void Zoomer::zoom( const QRectF & rect)
 
        this->setZoomBase(false);
 
    }
 

	
 
    ScrollZoomer::zoom(rect);
 
}
 

	
 
void Zoomer::setDispChannels(QVector<const StreamChannel*> channels)
 
{
 
    dispChannels = channels;
 
}
 

	
 
QwtText Zoomer::trackerTextF(const QPointF& pos) const
 
{
 
    QwtText b = ScrollZoomer::trackerTextF(pos);
 

	
 
    const QPolygon pa = selection();
 
    if (!isActive() || pa.count() < 2)
 
@@ -99,12 +108,231 @@ QRegion Zoomer::rubberBandMask() const
 
        return QRegion();
 
    }
 
    const QRect r = QRect(pa.first(), pa.last()).normalized().adjusted(0, 0, 1, 1);
 
    return QRegion(r);
 
}
 

	
 
void Zoomer::drawTracker(QPainter* painter) const
 
{
 
    if (isActive())
 
    {
 
        QwtPlotZoomer::drawTracker(painter);
 
    }
 
    else if (dispChannels.length())
 
    {
 
        drawValues(painter);
 
    }
 
}
 

	
 
QList<const StreamChannel*> Zoomer::visChannels() const
 
{
 
    QList<const StreamChannel*> result;
 

	
 
    for (unsigned ci = 0; ci < (unsigned) dispChannels.length(); ci++)
 
    {
 
        if (dispChannels[ci]->visible())
 
            result.append(dispChannels[ci]);
 
    }
 

	
 
    return result;
 
}
 

	
 
const double ValueLabelHeight = 12; // TODO: calculate
 

	
 
struct ChannelValue
 
{
 
    const StreamChannel* ch;
 
    double value;
 
    double y;
 
    double top() const {return y;};
 
    double bottom() const {return y + ValueLabelHeight;};
 
};
 

	
 
static void layoutValues(QList<ChannelValue>& values)
 
{
 
    typedef ChannelValue LayItem;
 
    typedef QList<LayItem*> LayItemList;
 

	
 
    struct LayGroup
 
    {
 
        struct VRange {double top, bottom;};
 
        LayItemList items;
 
        LayGroup(LayItem* initialItem) {items.append(initialItem);}
 
        unsigned numItems() const {return items.size();}
 
        double top() const {return items.first()->top();}
 
        double bottom() const {return items.last()->bottom();}
 
        VRange vRange() const {return {top(), bottom()};}
 
        double overlap(const LayGroup* otrGroup) const
 
            {
 
                auto myr = vRange();
 
                auto otr = otrGroup->vRange();
 

	
 
                double a = myr.bottom - otr.top;
 
                double b = otr.bottom - myr.top;
 
                if (a > 0 and b > 0)
 
                {
 
                    return std::min(a, b);
 
                }
 
                return 0;
 
            }
 
        void moveBy(double y) {for (auto it : items) it->y += y;}
 
        void join(LayGroup* other)
 
            {
 
                // assumes other group is below this one and they overlap
 
                double ovr_h = overlap(other);
 

	
 
                // groups are moved less if they have more items and vice versa
 
                double ratio = double(numItems()) / double(numItems() + other->numItems());
 
                double self_off = ovr_h * (1. - ratio);
 

	
 
                // make sure we don't go out of screen (above) after the shift
 
                double final_top = top() - self_off;
 
                if (final_top < 0)
 
                    self_off += final_top;
 

	
 
                // move groups
 
                moveBy(-self_off);                // up
 
                other->moveBy(ovr_h - self_off);  // down
 

	
 
                // finalize the merge by gettin items from other
 
                do
 
                {
 
                    items.append(other->items.takeFirst());
 
                } while (!other->items.isEmpty());
 
            }
 
    };
 

	
 
    // create initial groups (1 group per item)
 
    QList<LayGroup*> groups;
 
    for (auto& val : values)
 
        groups.append(new LayGroup(&val));
 

	
 
    // sort groups according to their items position
 
    struct {
 
        bool operator()(LayGroup* a, LayGroup* b) const
 
            {
 
                return a->top() < b->top();
 
            }
 
    } compTops;
 

	
 
    std::sort(groups.begin(), groups.end(), compTops);
 

	
 
    // do spacing
 
    bool somethingOverlaps = true;
 
    while (somethingOverlaps and groups.size() > 1)
 
    {
 
        somethingOverlaps = false;
 
        for (int i = 0; i < groups.size() - 1; i++)
 
        {
 
            auto a = groups[i];
 
            auto b = groups[i + 1];
 

	
 
            // make sure nothing is over the top
 
            if (a->top() < 0)
 
                a->moveBy(-a->top());
 

	
 
            // join if groups overlap
 
            if (a->overlap(b))
 
            {
 
                somethingOverlaps = true;
 
                a->join(b);
 
                delete groups.takeAt(i + 1);
 
                break;
 
            }
 
        }
 
    }
 

	
 
    // cleanup
 
    do
 
    {
 
        delete groups.takeFirst();
 
    } while (!groups.isEmpty());
 
};
 

	
 
void Zoomer::drawValues(QPainter* painter) const
 
{
 
    auto tpos = trackerPosition();
 
    if (tpos.x() < 0) return;   // cursor not on window
 

	
 
    // find Y values for current cursor X position
 
    double x = invTransform(tpos).x();
 
    auto channels = visChannels();
 
    QList<ChannelValue> values;
 
    for (auto ch : channels)
 
    {
 
        double value = ch->findValue(x);
 
        if (!std::isnan(value))
 
        {
 
            auto point = transform(QPointF(x, value));
 
            values.append({ch, value, double(point.y())});
 
        }
 
    }
 

	
 
    // TODO should keep?
 
    if (values.isEmpty())
 
    {
 
        return;
 
    }
 

	
 
    layoutValues(values);
 

	
 
    painter->save();
 

	
 
    // draw vertical line
 
    auto linePen = rubberBandPen();
 
    linePen.setStyle(Qt::DotLine);
 
    painter->setPen(linePen);
 
    const QRect pRect = pickArea().boundingRect().toRect();
 
    int px = tpos.x();
 
    painter->drawLine(px, pRect.top(), px, pRect.bottom());
 

	
 
    // draw sample values
 
    for (auto value : values)
 
    {
 
        double val = value.value;
 
        auto ch = value.ch;
 

	
 
        auto point = transform(QPointF(x, val));
 

	
 
        painter->setBrush(ch->color());
 
        painter->setPen(Qt::NoPen);
 
        painter->drawEllipse(point, VALUE_POINT_DIAM, VALUE_POINT_DIAM);
 

	
 
        painter->setPen(rubberBandPen());
 
        // We give a very small (1x1) rectangle but disable clipping
 
        painter->drawText(QRectF(point.x() + VALUE_TEXT_MARGIN, value.y, 1, 1),
 
                          Qt::AlignVCenter | Qt::TextDontClip,
 
                          QString("%1").arg(val));
 
    }
 

	
 
    painter->restore();
 
}
 

	
 
QRect Zoomer::trackerRect(const QFont& font) const
 
{
 
    if (isActive())
 
    {
 
        return QwtPlotZoomer::trackerRect(font);
 
    }
 
    else
 
    {
 
        return valueTrackerRect(font);
 
    }
 
}
 

	
 
QRect Zoomer::valueTrackerRect(const QFont& font) const
 
{
 
    // TODO: consider using actual tracker values for width calculation
 
    const int textWidth = qCeil(QwtText("-8.8888888").textSize(font).width());
 
    const int width = textWidth + VALUE_POINT_DIAM + VALUE_TEXT_MARGIN;
 
    const int x = trackerPosition().x() - VALUE_POINT_DIAM;
 
    const auto pickRect = pickArea().boundingRect();
 

	
 
    return QRect(x, pickRect.y(), width, pickRect.height());
 
}
 

	
 
void Zoomer::widgetMousePressEvent(QMouseEvent* mouseEvent)
 
{
 
    if (mouseEvent->modifiers() & Qt::ControlModifier)
 
    {
 
        is_panning = true;
 
        parentWidget()->setCursor(Qt::ClosedHandCursor);
src/zoomer.h
Show inline comments
 
/*
 
  Copyright © 2017 Hasan Yavuz Özderya
 
  Copyright © 2019 Hasan Yavuz Özderya
 

	
 
  This file is part of serialplot.
 

	
 
  serialplot 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
 
@@ -17,40 +17,60 @@
 
  along with serialplot.  If not, see <http://www.gnu.org/licenses/>.
 
*/
 

	
 
#ifndef ZOOMER_H
 
#define ZOOMER_H
 

	
 
#include <scrollzoomer.h>
 
#include <QVector>
 
#include <QList>
 
#include <QRect>
 

	
 
#include "scrollzoomer.h"
 
#include "streamchannel.h"
 

	
 
class Zoomer : public ScrollZoomer
 
{
 
    Q_OBJECT
 

	
 
public:
 
    Zoomer(QWidget *, bool doReplot=true);
 
    Zoomer(QWidget*, bool doReplot=true);
 
    void zoom(int up);
 
    void zoom( const QRectF & );
 
    void zoom(const QRectF&);
 
    /// Set displayed channels for value tracking (can be null)
 
    void setDispChannels(QVector<const StreamChannel*> channels);
 

	
 
signals:
 
    void unzoomed();
 

	
 
protected:
 
    /// Re-implemented to display selection size in the tracker text.
 
    QwtText trackerTextF(const QPointF &pos) const;
 
    QwtText trackerTextF(const QPointF &pos) const override;
 
    /// Re-implemented for sample value tracker
 
    QRect trackerRect(const QFont&) const override;
 
    /// Re-implemented for alpha background
 
    void drawRubberBand(QPainter* painter) const;
 
    void drawRubberBand(QPainter* painter) const override;
 
    /// Re-implemented to draw sample values
 
    void drawTracker(QPainter* painter) const override;
 
    /// Re-implemented for alpha background (masking is basically disabled)
 
    QRegion rubberBandMask() const;
 
    /// Overloaded for panning
 
    void widgetMousePressEvent(QMouseEvent* mouseEvent);
 
    /// Overloaded for panning
 
    void widgetMouseReleaseEvent(QMouseEvent* mouseEvent);
 
    /// Overloaded for panning
 
    void widgetMouseMoveEvent(QMouseEvent* mouseEvent);
 

	
 
private:
 
    bool is_panning;
 
    QPointF pan_point;
 
    /// displayed channels for value tracking
 
    QVector<const StreamChannel*> dispChannels;
 

	
 
    /// Get a list of visible channels
 
    QList<const StreamChannel*> visChannels() const;
 
    /// Draw sample values
 
    void drawValues(QPainter* painter) const;
 
    /// Returns trackerRect for value tracker
 
    QRect valueTrackerRect(const QFont& font) const;
 
};
 

	
 
#endif // ZOOMER_H
tests/test.cpp
Show inline comments
 
@@ -221,12 +221,20 @@ TEST_CASE("LinIndexBuffer", "[memory, bu
 
    l = buf.limits();
 
    REQUIRE(l.start == -5.0);
 
    REQUIRE(l.end == 5.0);
 

	
 
    REQUIRE(buf.sample(0) == -5.0);
 
    REQUIRE(buf.sample(19) == 5.0);
 

	
 
    buf.resize(10);
 
    buf.setLimits({0., 3.});
 
    REQUIRE(buf.findIndex(0.01) == 0);
 
    REQUIRE(buf.findIndex(1.51) == 4);
 
    REQUIRE(buf.findIndex(2.99) == 8);
 
    REQUIRE(buf.findIndex(3.01) == XFrameBuffer::OUT_OF_RANGE);
 
    REQUIRE(buf.findIndex(-0.01) == XFrameBuffer::OUT_OF_RANGE);
 
}
 

	
 
TEST_CASE("RingBuffer sizing", "[memory, buffer]")
 
{
 
    RingBuffer buf(10);
 

	
tests/test_stream.cpp
Show inline comments
 
@@ -24,23 +24,23 @@
 

	
 
TEST_CASE("construction of stream with default values", "[memory, stream]")
 
{
 
    // default values are an empty stream with no channels
 
    Stream s;
 

	
 
    REQUIRE(s.numChannels() == 0);
 
    REQUIRE(s.numChannels() == 1);
 
    REQUIRE(!s.hasX());
 
    REQUIRE(s.numSamples() == 0);
 
    REQUIRE(s.numSamples() == 2);
 
}
 

	
 
TEST_CASE("construction of stream with parameters", "[memory, stream]")
 
{
 
    Stream s(4, true, 100);
 
    Stream s(4, false, 100);
 

	
 
    REQUIRE(s.numChannels() == 4);
 
    REQUIRE(s.hasX());
 
    REQUIRE(!s.hasX());
 
    REQUIRE(s.numSamples() == 100);
 

	
 
    for (unsigned i = 0; i < 4; i++)
 
    {
 
        const StreamChannel* c = s.channel(i);
 
        REQUIRE(c != NULL);
 
@@ -61,24 +61,27 @@ TEST_CASE("changing stream number of cha
 
    {
 
        const StreamChannel* c = s.channel(i);
 
        REQUIRE(c != NULL);
 
        REQUIRE(c->index() == i);
 
    }
 

	
 
// TODO: enable test when `Stream` supports X channel
 
#if 0
 
    // increase nc value, add X
 
    so._setNumChannels(5, true);
 

	
 
    REQUIRE(s.numChannels() == 5);
 
    REQUIRE(s.hasX());
 

	
 
    for (unsigned i = 0; i < 5; i++)
 
    {
 
        const StreamChannel* c = s.channel(i);
 
        REQUIRE(c != NULL);
 
        REQUIRE(c->index() == i);
 
    }
 
#endif
 

	
 
    // reduce nc value, remove X
 
    so._setNumChannels(1, false);
 

	
 
    REQUIRE(s.numChannels() == 1);
 
    REQUIRE(!s.hasX());
 
@@ -124,15 +127,17 @@ TEST_CASE("adding data to a stream with 
 
        {
 
            REQUIRE(y->sample(i) == i-5);
 
        }
 
    }
 
}
 

	
 
// TODO: enable test when `Stream` supports X channel
 
#if 0
 
TEST_CASE("adding data to a stream with X", "[memory, stream, data, sink]")
 
{
 
    Stream s(3, true, 10);
 
    Stream s(3, false, 10);
 

	
 
    // prepare data
 
    SamplePack pack(5, 3, true);
 
    for (unsigned ci = 0; ci < 3; ci++)
 
    {
 
        for (unsigned i = 0; i < 5; i++)
 
@@ -144,13 +149,13 @@ TEST_CASE("adding data to a stream with 
 
    for (unsigned i = 0; i < 5; i++)
 
    {
 
        pack.xData()[i] = i+10;
 
    }
 

	
 
    TestSource so(3, true);
 
    so.connectSink(&s);
 
    REQUIRE_THROWS(so.connectSink(&s));
 

	
 
    // test
 
    so._feed(pack);
 

	
 
    for (unsigned ci = 0; ci < 3; ci++)
 
    {
 
@@ -175,12 +180,13 @@ TEST_CASE("adding data to a stream with 
 
    }
 
    for (unsigned i = 5; i < 10; i++)
 
    {
 
        REQUIRE(x->sample(i) == (i-5)+10);
 
    }
 
}
 
#endif
 

	
 
TEST_CASE("paused stream shouldn't store data", "[memory, stream, pause]")
 
{
 
    Stream s(3, false, 10);
 

	
 
    // prepare data
0 comments (0 inline, 0 general)