8 Commits
v0.8 ... dev

Author SHA1 Message Date
fb1a30fc94 添加creeper-qt最新依赖 2025-11-25 15:59:47 +08:00
0ec07218ab feat:完成设置界面和主界面的参数配置 2025-11-25 15:58:04 +08:00
b2350a3b35 feat:export data while running or close 2025-11-05 10:42:43 +08:00
7517f79c07 dev update 2025-11-05 09:44:58 +08:00
a07ff7d6b7 feat:heapmap with value;fix:qcustomplot warning 2025-11-04 10:47:41 +08:00
f411ab21cb update .gitignore 2025-10-29 14:12:11 +08:00
c6cef3d89d feat:data slove and update heatmap 2025-10-29 14:09:28 +08:00
c50b44efe2 update .gitignore 2025-10-29 14:08:18 +08:00
122 changed files with 47477 additions and 45372 deletions

View File

@@ -1,14 +1,147 @@
# 基础样式LLVMGoogleChromiumMozillaWebKit
BasedOnStyle: LLVM
# 类似于下面这行还没有实现未来希望clang提供分号;后不会强制换行的功能
# BreakAfterSemicolon: false
---
# 要使用的预处理器指令缩进样式
IndentPPDirectives: AfterHash
# 缩进宽度
IndentWidth: 4
Language: Cpp
# 标准: Cpp03, Cpp11, Auto
Standard: Latest
# tab宽度
TabWidth: 2
# 使用ObjC块时缩进宽度
ObjCBlockIndentWidth: 2
# 构造函数的初始化列表的缩进宽度
ConstructorInitializerIndentWidth: 2
# 延续的行的缩进宽度
ContinuationIndentWidth: 0
# 在ObjC的@property后添加一个空格
ObjCSpaceAfterProperty: false
# 在ObjC的protocol列表前添加一个空格
ObjCSpaceBeforeProtocolList: true
# 访问说明符的偏移
AccessModifierOffset: -2
# 连续的空行保留几行
MaxEmptyLinesToKeep: 2
# 调整连续行中的分配操作符(对齐等号)
AlignConsecutiveAssignments: true
# 校准连续的声明(对齐局部变量)
AlignConsecutiveDeclarations: true
# 允许排序#include
SortIncludes: false
# 允许排序 using 声明
SortUsingDeclarations: false
# 继承的符号后是否换行 类别AfterComma,AfterColon
BreakInheritanceList: AfterComma
# 总是在多行string字面量前换行
AlwaysBreakBeforeMultilineStrings: false
# 使用反斜杠换行对齐 RightDontAlign
AlignEscapedNewlines: DontAlign
# Align, DontAlign, AlwaysBreak(总是在开括号后换行)
AlignAfterOpenBracket: DontAlign
# 左对齐换行(使用反斜杠换行)的反斜杠
AlignEscapedNewlinesLeft: true
# 对齐连续的尾随的注释
AlignTrailingComments: true
# 允许短的case标签放在同一行
AllowShortCaseLabelsOnASingleLine: false
# 允许函数声明的所有参数在放在下一行
AllowAllParametersOfDeclarationOnNextLine: false
# 允许短的块放在同一行Empty
AllowShortBlocksOnASingleLine: true
# 在构造函数的初始化列表的逗号前换行
BreakConstructorInitializersBeforeComma: false
# 在构造函数的初始化列表的冒号后换行
BreakConstructorInitializers: AfterColon
# 在圆括号的(后和)前添加空格
SpacesInParentheses: false
# 允许在单行上使用短枚举
AllowShortEnumsOnASingleLine: true
# 允许短的函数放在同一行: None, InlineOnly(定义在类中), Empty(空函数), Inline(定义在类中,空函数), All
AllowShortFunctionsOnASingleLine: All
# 去除C++11的列表初始化的大括号{后和}前的空格
Cpp11BracedListStyle: false
# 继承最常用的指针和引用的对齐方式
DerivePointerAlignment: false
# 指针的*的位置
PointerAlignment: Left
CompileFlags:
Add: []
Remove: [-mno-direct-extern-access, -mdirect-extern-access]
# 允许在单行上使用简短的If语句
AllowShortIfStatementsOnASingleLine: WithoutElse
# 中括号两边空格 []
SpacesInSquareBrackets: false
# 等号两边的空格
SpaceBeforeAssignmentOperators: true
# 容器类的空格
SpacesInContainerLiterals: false
# 缩进包装函数名
IndentWrappedFunctionNames: false
# 在块的开头保留空行
KeepEmptyLinesAtTheStartOfBlocks: true
# 括号后添加空格
SpaceAfterCStyleCast: false
# 缩进case 标签
IndentCaseLabels: true
# 允许短的循环保持在同一行
AllowShortLoopsOnASingleLine: true
# 在模板声明“template<...>”后总是换行
AlwaysBreakTemplateDeclarations: Yes
# 二进制运算符之前的中断非赋值NonAssignment
BreakBeforeBinaryOperators: NonAssignment
# 三元运算符将被放置在换行后
BreakBeforeTernaryOperators: false
# 每行字符的限制0表示没有限制
ColumnLimit: 0
# 只有定义成Custom下面的大括号才会生效
BreakBeforeBraces: Custom
# 大括号后的分行
BraceWrapping :
# class定义后面
AfterClass: false
# 控制语句后面
AfterControlStatement: false
# enum定义后面
AfterEnum: false
# 函数定义后面
AfterFunction: false
# 命名空间定义后面
AfterNamespace: false
# ObjC定义后面
AfterObjCDeclaration: false
# struct定义后面
AfterStruct: false
# union定义后面
AfterUnion: false
# catch之前
BeforeCatch: true
# else之前
BeforeElse: true
# 缩进大括号
IndentBraces: false
# 语言: Cpp, Java, JavaScript, ObjC, Proto
Language: Cpp
# 模板关键字后的空格false
SpaceAfterTemplateKeyword: false
# 指针限定符周围的空格:之后
SpaceAroundPointerQualifiers: After
# 大小写冒号前的空格false
SpaceBeforeCaseColon: false
# C到r初始值设定项冒号前的空格false
SpaceBeforeCtorInitializerColon: false
# 继承冒号前的空格false
SpaceBeforeInheritanceColon: false
# 开圆括号之前添加一个空格: Never, ControlStatements, Always
SpaceBeforeParens: ControlStatements
# 基于范围的循环冒号前的空格false
SpaceBeforeRangeBasedForLoopColon: false
# 在尖括号的<>后和前添加空格
SpacesInAngles: false
# 收拾格子参数
BinPackArguments : false
# 纸盒包装参数
BinPackParameters : false
# 当格式化时,总是对字面量字符串换行
BreakStringLiterals : false
# Never, ForIndentation, ForContinuationAndIndentation, Always
UseTab: Never

3
.gitignore vendored
View File

@@ -2,7 +2,8 @@
.vscode/
.vs/
.idea/
.VSCodeCounter/
mingw-build/
cmake-build-*/
build/
output/

View File

@@ -15,8 +15,7 @@ set(CMAKE_AUTORCC ON)
add_compile_options(-Os -O3)
list(APPEND CMAKE_PREFIX_PATH
"D:/Environment/include"
"D:/Environment/lib"
"C:/msys64/mingw64/include"
)
find_package(${QT_VERSION} REQUIRED COMPONENTS Widgets Network PrintSupport)
@@ -25,18 +24,16 @@ find_package(Eigen3 REQUIRED)
qt_standard_project_setup()
file(
GLOB_RECURSE MODERN_QT_SOURCES
GLOB_RECURSE creeper_QT_SOURCES
CONFIGURE_DEPENDS
"modern-qt/*.cc"
"creeper-qt/*.cc"
)
set(MODERN_QT_HEADERS
modern-qt/widget/select.hh
modern-qt/widget/select.impl.hh
modern-qt/widget/sliders.hh
set(creeper_QT_HEADERS
creeper-qt/widget/sliders.hh
)
add_library(modern-qt SHARED ${MODERN_QT_SOURCES} ${MODERN_QT_HEADERS})
target_include_directories(modern-qt PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(modern-qt
add_library(creeper-qt SHARED ${creeper_QT_SOURCES} ${creeper_QT_HEADERS})
target_include_directories(creeper-qt PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(creeper-qt
PUBLIC
${QT_VERSION}::Widgets
${QT_VERSION}::Network
@@ -69,17 +66,26 @@ file(
"dlog/*.cc"
)
file(
GLOB_RECURSE BASE_SOURCES
CONFIGURE_DEPENDS
"base/*.cc"
)
set(FFMSEP_SOURCES
components/ffmsep/cpdecoder.cc
components/ffmsep/cpstream_core.cc
components/ffmsep/presist/presist.cc
components/ffmsep/tactile/tacdec.cc
)
set(FFMSEP_HEADERS
components/ffmsep/cpdecoder.hh
components/ffmsep/cpstream_core.hh
components/ffmsep/presist/presist.hh
components/ffmsep/tactile/tacdec.hh
)
set(FFMSEP_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/components/ffmsep")
set(BASE_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/base")
set(TOUCHSENSOR_HEADERS
component.hh
@@ -87,6 +93,7 @@ set(TOUCHSENSOR_HEADERS
components/charts/heatmap.impl.hh
dlog/dlog.hh
${FFMSEP_HEADERS}
components/setting.cc
)
qt6_add_resources(APP_RESOURCES resources.qrc)
@@ -95,6 +102,7 @@ add_executable(${PROJECT_NAME}
${COMPONENT_SOURCES}
${UTILITY_SOURCES}
${TOUCHSENSOR_HEADERS}
${BASE_SOURCES}
main.cc
)
target_sources(${PROJECT_NAME} PRIVATE ${APP_RESOURCES})
@@ -102,12 +110,13 @@ target_include_directories(${PROJECT_NAME}
PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}
${FFMSEP_INCLUDE_DIR}
${BASE_INCLUDE_DIR}
)
target_link_libraries(${PROJECT_NAME}
PRIVATE
${QT_VERSION}::Widgets
${QT_VERSION}::Network
modern-qt
creeper-qt
qcustomplot
serial
setupapi

159
base/globalhelper.cc Normal file
View File

@@ -0,0 +1,159 @@
#include "globalhelper.hh"
#include "qdir.h"
#include "qsettings.h"
#include "qstandardpaths.h"
#include <array>
#include <QDir>
#include <QStandardPaths>
#include <QSettings>
#include <qt6/QtCore/qcontainerfwd.h>
#include <algorithm>
#include <vector>
const QString IPC_CONFIG_BASEDIR = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation) + "/tactile";
const QString IPC_CONFIG = "sensor_ipc_config.ini";
const QString APP_VERSION = "0.2.0";
const QString PROFILES_GROUP = "profile";
namespace {
QString tactileTypeToString(Tactile_TYPE type) {
switch (type) {
case Tactile_TYPE::PiezoresistiveA:
return "压阻A型";
case Tactile_TYPE::PiezoresistiveB:
return "压阻B型";
case Tactile_TYPE::Hall:
return "霍尔型";
}
return "霍尔型";
}
Tactile_TYPE tactileTypeFromString(const QString& type) {
if (type == "压阻A型") {
return Tactile_TYPE::PiezoresistiveA;
}
if (type == "压阻B型") {
return Tactile_TYPE::PiezoresistiveB;
}
return Tactile_TYPE::Hall;
}
} // namespace
GlobalHelper& GlobalHelper::instance() {
static GlobalHelper instance;
return instance;
}
GlobalHelper::GlobalHelper() {
QDir().mkpath(IPC_CONFIG_BASEDIR);
// qDebug() << "QDir: " << IPC_CONFIG_BASEDIR;
// ConfigProfile cfg{
// .name = "default",
// .type = Tactile_TYPE::Hall,
// .matrix_width = 3,
// .matrix_height = 4,
// .range_left = 200,
// .range_right = 300,
// .baud_rate = 115200
// };
// save_profile(cfg, 0);
load_profiles();
}
void GlobalHelper::load_profiles() {
QString str_ipc_config_filename = IPC_CONFIG_BASEDIR + "/" + IPC_CONFIG;
QSettings settings(str_ipc_config_filename, QSettings::IniFormat);
config_vec.clear();
settings.beginGroup(PROFILES_GROUP);
const auto profile_names = settings.childGroups();
for (const auto& profile_group_name : profile_names) {
settings.beginGroup(profile_group_name);
ConfigProfile profile;
profile.name = settings.value("profile_name", profile_group_name).toString();
profile.type = tactileTypeFromString(settings.value("type").toString());
profile.matrix_width = settings.value("matrix_width", 0).toInt();
profile.matrix_height = settings.value("matrix_height", 0).toInt();
profile.range_left = settings.value("range_left", 0).toInt();
profile.range_right = settings.value("range_right", 0).toInt();
profile.baud_rate = settings.value("baud_rate", 0).toInt();
config_vec.push_back(profile);
settings.endGroup();
}
settings.endGroup();
qDebug() << "profiles: " << config_vec.size();
}
void GlobalHelper::reload_profiles() {
load_profiles();
}
void GlobalHelper::save_profile(const ConfigProfile& profile, int is_default) {
QString str_ipc_config_filename = IPC_CONFIG_BASEDIR + "/" + IPC_CONFIG;
QSettings settings(str_ipc_config_filename, QSettings::IniFormat);
settings.beginGroup(PROFILES_GROUP);
settings.beginGroup(profile.name);
settings.setValue("profile_name", profile.name);
settings.setValue("type", tactileTypeToString(profile.type));
settings.setValue("matrix_width", profile.matrix_width);
settings.setValue("matrix_height", profile.matrix_height);
settings.setValue("range_left", profile.range_left);
settings.setValue("range_right", profile.range_right);
settings.setValue("baud_rate", profile.baud_rate);
settings.setValue("is_default", is_default);
settings.endGroup();
settings.endGroup();
}
bool GlobalHelper::add_new_profile(QString name, Tactile_TYPE type, int width, int height, int rl, int rr, int baud) {
ConfigProfile cfg{
.name = name,
.type = type,
.matrix_width = width,
.matrix_height = height,
.range_left = rl,
.range_right = rr,
.baud_rate = baud
};
return add_new_profile(cfg);
}
bool GlobalHelper::add_new_profile(const ConfigProfile& profile) {
auto item_find = std::find_if(config_vec.begin(), config_vec.end(), [profile](const ConfigProfile& p) {
return p.name == profile.name;
});
if (item_find == config_vec.end()) {
save_profile(profile);
config_vec.push_back(profile);
return true;
}
return false;
}
void GlobalHelper::remove_profile(const QString& name) {
auto item_find = std::find_if(config_vec.begin(), config_vec.end(), [name](const ConfigProfile& p){
return p.name == name;
});
if (item_find != config_vec.end()) {
config_vec.erase(item_find);
QString str_ipc_config_filename = IPC_CONFIG_BASEDIR + "/" + IPC_CONFIG;
QSettings settings(str_ipc_config_filename, QSettings::IniFormat);
settings.beginGroup(PROFILES_GROUP);
settings.remove(name);
settings.endGroup();
}
}
std::vector<ConfigProfile>& GlobalHelper::get_all_profile() {
return config_vec;
}

46
base/globalhelper.hh Normal file
View File

@@ -0,0 +1,46 @@
#pragma once
#include <QStringList>
#include <array>
#include <vector>
// 热力图宽
// 热力图高
// 量程
// baud
enum class Tactile_TYPE {
PiezoresistiveA,
PiezoresistiveB,
Hall,
};
typedef struct ConfigProfile {
QString name;
Tactile_TYPE type;
int matrix_width;
int matrix_height;
int range_left;
int range_right;
int baud_rate;
} ConfigProfile;
class GlobalHelper {
public:
static GlobalHelper& instance();
GlobalHelper(const GlobalHelper&) = delete;
GlobalHelper& operator=(const GlobalHelper&) = delete;
GlobalHelper(GlobalHelper&&) = delete;
GlobalHelper& operator=(GlobalHelper&&) = delete;
bool add_new_profile(QString name, Tactile_TYPE type, int width, int height, int rl, int rr, int baud);
bool add_new_profile(const ConfigProfile& profile);
void remove_profile(const QString& name);
void save_profile(const ConfigProfile& profile, int is_default = 0);
std::vector<ConfigProfile>& get_all_profile();
void reload_profiles();
private:
GlobalHelper();
void load_profiles();
std::vector<ConfigProfile> config_vec;
};

View File

@@ -1,7 +1,8 @@
#pragma once
#include <modern-qt/utility/theme/theme.hh>
#include <creeper-qt/utility/theme/theme.hh>
#include <qwidget.h>
#include <string_view>
template <typename T>
using raw_pointer = T*;
@@ -9,8 +10,8 @@ using raw_pointer = T*;
struct NavComponentState {
creeper::ThemeManager& manager;
std::function<void(int, const std::string_view&)> switch_callback;
std::vector<std::tuple<std::string_view, std::string_view>> buttons_context;
std::function<void(int)> stacked_callback;
};
auto NavComponent(NavComponentState&) noexcept -> raw_pointer<QWidget>;
@@ -19,3 +20,16 @@ struct ViewComponentState {
creeper::ThemeManager& manager;
};
auto ViewComponent(ViewComponentState&) noexcept -> raw_pointer<QWidget>;
struct SettingComponentState {
creeper::ThemeManager& manager;
};
auto SettingComponent(SettingComponentState&) noexcept -> raw_pointer<QWidget>;
struct HandViewComponentState {
creeper::ThemeManager& manager;
};
auto HandViewComponent(HandViewComponentState&) noexcept -> raw_pointer<QWidget>;
// 让其他模块可触发视图层的串口/配置刷新
void RefreshProfilesForView();

View File

@@ -5,12 +5,12 @@
#ifndef TOUCHSENSOR_HEATMAP_H
#define TOUCHSENSOR_HEATMAP_H
#include "modern-qt/utility/theme/theme.hh"
#include "modern-qt/utility/wrapper/common.hh"
#include "modern-qt/utility/wrapper/pimpl.hh"
#include "modern-qt/utility/wrapper/property.hh"
#include "creeper-qt/utility/theme/theme.hh"
#include "creeper-qt/utility/wrapper/common.hh"
#include "creeper-qt/utility/wrapper/pimpl.hh"
#include "creeper-qt/utility/wrapper/property.hh"
#include "qcustomplot/qcustomplot.h"
#include "modern-qt/utility/wrapper/widget.hh"
#include "creeper-qt/utility/wrapper/widget.hh"
#include <concepts>
#include <qcontainerfwd.h>
#include <qvector.h>
@@ -82,8 +82,11 @@ namespace plot_widget::pro {
}
};
using Data = common::pro::Vector<Token, PointData,
[](auto& self, const auto& data) {
// using Data = common::pro::Vector<Token, PointData,
// [](auto& self, const auto& data) {
// self.set_data(data);
// }>;
using Data = DerivedProp<Token, QVector<QString>, [](auto& self, const auto& data) {
self.set_data(data);
}>;
@@ -107,11 +110,15 @@ namespace plot_widget::pro {
template<class PlotWidget>
concept trait = std::derived_from<PlotWidget, Token>;
using PlotData = common::pro::Vector<Token, PointData, [](auto& self, const auto& vec) {
self.set_data(vec);
}>;
// using PlotData = common::pro::Vector<Token, PointData, [](auto& self, const auto& vec) {
// self.set_data(vec);
// }>;
using PlotData = DerivedProp<Token, QVector<PointData>, [](auto& self, const auto& vec){self.set_data(vec);}>;
using DataRange = common::pro::Array<Token, int, 2, [](auto& self, const auto& arr) {
// using DataRange = common::pro::Array<Token, int, 2, [](auto& self, const auto& arr) {
// self.set_color_gradient_range(arr[0], arr[1]);
// }>;
using DataRange = DerivedProp<Token, std::array<int, 2>, [](auto& self, const auto& arr) {
self.set_color_gradient_range(arr[0], arr[1]);
}>;

View File

@@ -6,17 +6,23 @@
#define TOUCHSENSOR_HEATMAP_IMPL_HH
#include "heatmap.hh"
#include "modern-qt/utility/theme/theme.hh"
#include "modern-qt/widget/sliders.hh"
#include "creeper-qt/utility/theme/theme.hh"
#include "creeper-qt/widget/sliders.hh"
#include "qcustomplot/qcustomplot.h"
#include <algorithm>
#include <memory>
#include <optional>
#include <qcolor.h>
#include <qdebug.h>
#include <qfont.h>
#include <vector>
using namespace creeper::plot_widget::internal;
struct BasicPlot::Impl {
explicit Impl(BasicPlot& self) noexcept : self{self}, initialized(false), matrix_size(QSize{3, 4}) {}
public:
std::optional<creeper::ColorScheme> scheme;
auto set_xlabel_text(const QString& text) -> void {
xlabel = text;
if (initialized) {
@@ -36,7 +42,6 @@ public:
auto set_matrix_size(const QSize& size) -> void {
matrix_size = size;
if (initialized) {
// 重新初始化热力图以适应新的矩阵大小
reset_plot();
if (!data_points.isEmpty()) {
set_data(data_points);
@@ -46,7 +51,8 @@ public:
auto load_theme_manager(ThemeManager& mgr) -> void {
mgr.append_handler(&self, [this](const ThemeManager& mgr) {
// 可以根据主题更新颜色渐变等
scheme = mgr.color_scheme();
apply_color_scheme();
if (initialized) {
self.replot();
}
@@ -54,9 +60,8 @@ public:
}
auto set_color_gradient_range(const double& min, const double& max) -> void {
if (initialized && self.plottableCount() > 0) {
auto* cpmp = static_cast<QCPColorMap*>(self.plottable(0));
cpmp->setDataRange(QCPRange(min, max));
if (initialized && color_map) {
color_map->setDataRange(QCPRange(min, max));
self.replot();
}
color_min = min;
@@ -65,7 +70,7 @@ public:
auto set_data(const QVector<PointData>& data) -> void {
data_points = data;
if (initialized) {
if (initialized && color_map) {
update_plot_data();
}
}
@@ -73,13 +78,12 @@ public:
auto initialize_plot() -> void {
if (initialized) return;
// 创建颜色映射
QCPColorMap* cpmp = new QCPColorMap(self.xAxis, self.yAxis);
color_map = new QCPColorMap(self.xAxis, self.yAxis);
auto* cpmp = color_map;
cpmp->data()->setSize(matrix_size.width(), matrix_size.height());
cpmp->data()->setRange(QCPRange(0.5, matrix_size.width() - 0.5),
QCPRange(0.5, matrix_size.height() - 0.5));
// 配置坐标轴
QSharedPointer<QCPAxisTickerText> xticker(new QCPAxisTickerText);
QSharedPointer<QCPAxisTickerText> yticker(new QCPAxisTickerText);
xticker->setSubTickCount(1);
@@ -89,7 +93,6 @@ public:
self.xAxis->setTicker(xticker);
self.yAxis->setTicker(yticker);
// 设置网格
self.xAxis->grid()->setPen(Qt::NoPen);
self.yAxis->grid()->setPen(Qt::NoPen);
self.xAxis->grid()->setSubGridVisible(true);
@@ -101,38 +104,45 @@ public:
self.xAxis->setSubTickLength(6);
self.yAxis->setSubTickLength(6);
// 设置范围
self.xAxis->setRange(0, matrix_size.width());
self.yAxis->setRange(0, matrix_size.height());
// 设置标签
if (!xlabel.isEmpty()) self.xAxis->setLabel(xlabel);
if (!ylabel.isEmpty()) self.yAxis->setLabel(ylabel);
// 添加颜色刻度
QCPColorScale* color_scale = new QCPColorScale(&self);
if (!color_scale) {
color_scale = new QCPColorScale(&self);
color_scale->setType(QCPAxis::atBottom);
}
if (self.plotLayout()) {
auto existing = self.plotLayout()->element(1, 0);
if (existing && existing != color_scale) {
self.plotLayout()->take(existing);
}
if (!existing || existing != color_scale) {
self.plotLayout()->addElement(1, 0, color_scale);
}
}
cpmp->setColorScale(color_scale);
// 设置颜色渐变
QCPColorGradient gradient;
gradient.setColorStopAt(0.0, QColor(246, 239, 166)); // F6EFA6
gradient.setColorStopAt(1.0, QColor(191, 68, 76)); // BF444C
gradient.setColorStopAt(0.0, QColor(240, 246, 255)); // 低值淡色
gradient.setColorStopAt(0.35, QColor(142, 197, 252));
gradient.setColorStopAt(0.7, QColor(56, 128, 199));
gradient.setColorStopAt(1.0, QColor(8, 36, 95)); // 高值深色
cpmp->setGradient(gradient);
// 设置数据范围
cpmp->setDataRange(QCPRange(color_min, color_max));
cpmp->setInterpolate(false);
// 配置边距
QCPMarginGroup *margin_group = new QCPMarginGroup(&self);
self.axisRect()->setMarginGroup(QCP::msLeft | QCP::msRight, margin_group);
color_scale->setMarginGroup(QCP::msLeft | QCP::msRight, margin_group);
initialized = true;
apply_color_scheme();
// 如果已有数据,更新图表
if (!data_points.isEmpty()) {
update_plot_data();
}
@@ -144,25 +154,36 @@ public:
self.clearGraphs();
self.clearItems();
self.clearFocus();
color_map = nullptr;
cell_labels.clear();
// 重新初始化
initialized = false;
initialize_plot();
}
auto update_plot_data() -> void {
if (!initialized || self.plottableCount() == 0) return;
if (!initialized || !color_map) return;
auto* cpmp = static_cast<QCPColorMap*>(self.plottable(0));
ensure_labels();
const int width = matrix_size.width();
const int height = matrix_size.height();
const int expected = width * height;
std::vector<double> values(static_cast<std::size_t>(expected), 0.0);
// 设置新数据
for (const auto& item : data_points) {
if (item.x >= 0 && item.x < matrix_size.width() &&
item.y >= 0 && item.y < matrix_size.height()) {
cpmp->data()->setCell(item.x, item.y, item.z);
color_map->data()->setCell(item.x, item.y, item.z);
const int idx = static_cast<int>(item.y) * width + static_cast<int>(item.x);
if (idx >= 0 && idx < expected) {
values[static_cast<std::size_t>(idx)] = item.z;
}
}
}
update_label_values(values);
// 重绘
self.replot();
@@ -182,9 +203,113 @@ private:
QSize matrix_size;
QVector<PointData> data_points;
double color_min = 0.0;
double color_max = 15.0;
double color_max = 800.0;
bool initialized;
BasicPlot& self;
QCPColorScale* color_scale = nullptr;
QCPColorMap* color_map = nullptr;
QVector<QCPItemText*> cell_labels;
QColor label_text_color = QColor(0, 0, 0);
void apply_color_scheme() {
QColor text_color = QColor(30, 30, 30);
if (scheme.has_value()) {
if (scheme->on_surface.isValid()) {
text_color = scheme->on_surface;
}
}
label_text_color = QColor(0, 0, 0); // 固定黑色
const auto pen = QPen(text_color);
self.xAxis->setTickLabelColor(text_color);
self.yAxis->setTickLabelColor(text_color);
self.xAxis->setLabelColor(text_color);
self.yAxis->setLabelColor(text_color);
self.xAxis->setBasePen(pen);
self.yAxis->setBasePen(pen);
self.xAxis->setTickPen(pen);
self.yAxis->setTickPen(pen);
if (color_scale && color_scale->axis()) {
color_scale->axis()->setTickLabelColor(text_color);
color_scale->axis()->setLabelColor(text_color);
color_scale->axis()->setBasePen(pen);
color_scale->axis()->setTickPen(pen);
}
// 已有标签更新
for (auto* label : cell_labels) {
if (!label) continue;
label->setColor(label_text_color);
}
}
void clear_labels() {
for (auto* label : cell_labels) {
if (label) {
self.removeItem(label);
}
}
cell_labels.clear();
}
void ensure_labels() {
const int width = matrix_size.width();
const int height = matrix_size.height();
const int expected = width * height;
if (expected <= 0) {
clear_labels();
return;
}
if (cell_labels.size() == expected) {
return;
}
clear_labels();
cell_labels.reserve(expected);
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
auto* label = new QCPItemText(&self);
label->position->setType(QCPItemPosition::ptPlotCoords);
label->setClipToAxisRect(true);
label->setClipAxisRect(self.axisRect());
label->setPositionAlignment(Qt::AlignCenter);
label->position->setCoords(x + 0.5, y + 0.5);
label->setBrush(Qt::NoBrush);
label->setPen(Qt::NoPen);
QFont font = label->font();
if (font.pointSize() > 0) {
font.setPointSize(std::max(font.pointSize() - 1, 6));
} else {
font.setPointSize(8);
}
label->setFont(font);
label->setColor(label_text_color);
label->setSelectable(false);
cell_labels.push_back(label);
}
}
}
void update_label_values(const std::vector<double>& values) {
const int width = matrix_size.width();
const int height = matrix_size.height();
const double range = std::max(color_max - color_min, 1.0);
const int expected = width * height;
for (int idx = 0; idx < expected && idx < cell_labels.size(); ++idx) {
auto* label = cell_labels[idx];
if (!label) {
continue;
}
const double value = values.size() > static_cast<std::size_t>(idx)
? values[static_cast<std::size_t>(idx)]
: 0.0;
label->setText(QString::number(value, 'f', 0));
const int x = idx % width;
const int y = idx / width;
label->position->setCoords(x + 0.5, y + 0.5);
}
}
};
#endif // TOUCHSENSOR_HEATMAP_IMPL_HH

View File

@@ -173,10 +173,6 @@ int cpcodec_close(CPCodecContext *ctx) {
ctx->codec->close(ctx);
}
if (ctx->codec && ctx->codec->close) {
ctx->codec->close(ctx);
}
ctx->is_open = false;
ctx->release_priv_storage();
ctx->codec_type = CPMediaType::Unknow;

View File

@@ -1,11 +1,6 @@
#pragma once
#include "components/ffmsep/cpdecoder.hh"
#include <cstdint>
#include <cstddef>
#include <mutex>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
#include <initializer_list>
@@ -109,7 +104,6 @@ private:
friend int cpcodec_open(CPCodecContext*, const CPCodec*);
friend int cpcodec_close(CPCodecContext*);
};
void cpcodec_register(const CPCodec* codec);
void cpcodec_register_many(std::initializer_list<const CPCodec*> codecs);
const CPCodec* cpcodec_find_decoder(CPCodecID id);

View File

@@ -1,5 +1,8 @@
#include "components/ffmsep/cpstream_core.hh"
#include "components/ffmsep/presist/presist.hh"
#include "dlog/dlog.hh"
#include <algorithm>
#include <atomic>
#include <chrono>
@@ -7,19 +10,21 @@
#include <cstddef>
#include <cstdint>
#include <deque>
#include <future>
#include <memory>
#include <mutex>
#include <optional>
#include <thread>
#include <utility>
#include <vector>
using namespace std::chrono_literals;
namespace ffmsep {
namespace {
constexpr auto kReaderIdleSleep = std::chrono::milliseconds(5);
constexpr auto kDecoderIdleSleep = std::chrono::milliseconds(1);
constexpr auto kReaderIdleSleep = 5ms;
constexpr auto kDecoderIdleSleep = 1ms;
const CPCodec* resolve_requested_codec(const CPStreamConfig& config) {
if (!config.codec_name.empty()) {
@@ -48,6 +53,7 @@ struct CPStreamCore::Impl {
explicit Impl(CPStreamConfig config)
: config_(std::move(config)) {
normalize_config();
frame_writer_ = std::make_unique<persist::JsonWritter>();
}
~Impl() = default;
@@ -62,6 +68,9 @@ struct CPStreamCore::Impl {
if (config_.frame_queue_capacity == 0U) {
config_.frame_queue_capacity = 1U;
}
if (config_.slave_request_interval.count() < 0) {
config_.slave_request_interval = 0ms;
}
frame_queue_capacity_ = config_.frame_queue_capacity;
}
@@ -106,11 +115,13 @@ struct CPStreamCore::Impl {
config_.parity,
config_.stopbits,
config_.flowcontrol);
if (!serial->isOpen()) {
serial->open();
}
serial->flush();
{
std::lock_guard lock(serial_mutex_);
std::lock_guard<std::mutex> lock(serial_mutex_);
serial_ = std::move(serial);
}
} catch (const serial::IOException& ex) {
@@ -134,11 +145,11 @@ struct CPStreamCore::Impl {
}
{
std::lock_guard lock(packet_mutex_);
std::lock_guard<std::mutex> lock(packet_mutex_);
packet_queue_.clear();
}
{
std::lock_guard lock(frame_mutex_);
std::lock_guard<std::mutex> lock(frame_mutex_);
frame_queue_.clear();
}
pts_counter_.store(0, std::memory_order_relaxed);
@@ -159,7 +170,7 @@ struct CPStreamCore::Impl {
stop();
{
std::lock_guard lock(serial_mutex_);
std::lock_guard<std::mutex> lock(serial_mutex_);
if (serial_) {
try {
if (serial_->isOpen()) {
@@ -179,12 +190,13 @@ struct CPStreamCore::Impl {
}
{
std::lock_guard lock(packet_mutex_);
std::lock_guard<std::mutex> lock(packet_mutex_);
packet_queue_.clear();
}
{
std::lock_guard lock(frame_mutex_);
std::lock_guard<std::mutex> lock(frame_mutex_);
frame_queue_.clear();
frame_record_queue_.clear();
}
}
@@ -195,7 +207,7 @@ struct CPStreamCore::Impl {
std::shared_ptr<serial::Serial> serial_copy;
{
std::lock_guard lock(serial_mutex_);
std::lock_guard<std::mutex> lock(serial_mutex_);
serial_copy = serial_;
}
if (!serial_copy || !serial_copy->isOpen()) {
@@ -213,6 +225,9 @@ struct CPStreamCore::Impl {
reader_thread_ = std::thread(&Impl::reader_loop, this);
decoder_thread_ = std::thread(&Impl::decoder_loop, this);
if (!config_.slave_request_command.empty()) {
slave_thread_ = std::thread(&Impl::slave_loop, this);
}
return true;
}
@@ -227,6 +242,9 @@ struct CPStreamCore::Impl {
if (reader_thread_.joinable()) {
reader_thread_.join();
}
if (slave_thread_.joinable()) {
slave_thread_.join();
}
signal_decoder_flush(true);
packet_cv_.notify_all();
@@ -238,7 +256,7 @@ struct CPStreamCore::Impl {
stop_requested_.store(false, std::memory_order_release);
{
std::lock_guard lock(packet_mutex_);
std::lock_guard<std::mutex> lock(packet_mutex_);
packet_queue_.clear();
}
@@ -248,7 +266,7 @@ struct CPStreamCore::Impl {
}
bool is_open() const {
std::lock_guard lock(serial_mutex_);
std::lock_guard<std::mutex> lock(serial_mutex_);
return serial_ && serial_->isOpen();
}
@@ -267,7 +285,7 @@ struct CPStreamCore::Impl {
std::shared_ptr<serial::Serial> serial_copy;
{
std::lock_guard lock(serial_mutex_);
std::lock_guard<std::mutex> lock(serial_mutex_);
serial_copy = serial_;
}
@@ -289,17 +307,17 @@ struct CPStreamCore::Impl {
return false;
}
std::optional<DecodedFrame> try_pop_frame() {
std::lock_guard lock(frame_mutex_);
std::optional<std::shared_ptr<DecodedFrame>> try_pop_frame() {
std::lock_guard<std::mutex> lock(frame_mutex_);
if (frame_queue_.empty()) {
return std::nullopt;
}
DecodedFrame frame = std::move(frame_queue_.front());
std::shared_ptr<DecodedFrame> frame = std::move(frame_queue_.front());
frame_queue_.pop_front();
return frame;
}
bool wait_for_frame(DecodedFrame& frame, std::chrono::milliseconds timeout) {
bool wait_for_frame(std::shared_ptr<DecodedFrame>& frame, std::chrono::milliseconds timeout) {
std::unique_lock lock(frame_mutex_);
if (!frame_cv_.wait_for(lock, timeout, [&] {
return !frame_queue_.empty();
@@ -312,7 +330,7 @@ struct CPStreamCore::Impl {
}
void clear_frames() {
std::lock_guard lock(frame_mutex_);
std::lock_guard<std::mutex> lock(frame_mutex_);
frame_queue_.clear();
}
@@ -321,7 +339,7 @@ struct CPStreamCore::Impl {
capacity = 1U;
}
{
std::lock_guard lock(frame_mutex_);
std::lock_guard<std::mutex> lock(frame_mutex_);
frame_queue_capacity_ = capacity;
config_.frame_queue_capacity = capacity;
while (frame_queue_.size() > frame_queue_capacity_) {
@@ -330,8 +348,46 @@ struct CPStreamCore::Impl {
}
}
void clear_recorded_frames() {
std::lock_guard<std::mutex> lock(frame_mutex_);
frame_record_queue_.clear();
}
std::size_t recorded_frame_count() const {
std::lock_guard<std::mutex> lock(frame_mutex_);
return frame_record_queue_.size();
}
std::future<persist::WriteResult> export_recorded_frames(const std::string& path, bool clear_after_export) {
if (!frame_writer_) {
frame_writer_ = std::make_unique<persist::JsonWritter>();
}
std::deque<std::shared_ptr<DecodedFrame>> snapshot;
{
std::lock_guard<std::mutex> lock(frame_mutex_);
snapshot = frame_record_queue_;
if (clear_after_export) {
frame_record_queue_.clear();
}
}
if (snapshot.empty()) {
std::promise<persist::WriteResult> promise;
auto future = promise.get_future();
promise.set_value(persist::WriteResult{
false,
"no recorded frames available",
path
});
return future;
}
return frame_writer_->enqueue(path, std::move(snapshot));
}
void set_frame_callback(FrameCallback callback) {
std::lock_guard lock(callback_mutex_);
std::lock_guard<std::mutex> lock(callback_mutex_);
frame_callback_ = std::move(callback);
}
@@ -340,7 +396,7 @@ struct CPStreamCore::Impl {
}
std::string last_error() const {
std::lock_guard lock(last_error_mutex_);
std::lock_guard<std::mutex> lock(last_error_mutex_);
return last_error_;
}
@@ -354,7 +410,7 @@ struct CPStreamCore::Impl {
while (!stop_requested_.load(std::memory_order_acquire)) {
std::shared_ptr<serial::Serial> serial_copy;
{
std::lock_guard lock(serial_mutex_);
std::lock_guard<std::mutex> lock(serial_mutex_);
serial_copy = serial_;
}
if (!serial_copy || !serial_copy->isOpen()) {
@@ -389,7 +445,7 @@ struct CPStreamCore::Impl {
packet.pts = pts_counter_.fetch_add(1, std::memory_order_relaxed);
{
std::lock_guard lock(packet_mutex_);
std::lock_guard<std::mutex> lock(packet_mutex_);
if (packet_queue_.size() >= config_.packet_queue_capacity) {
packet_queue_.pop_front();
}
@@ -399,6 +455,33 @@ struct CPStreamCore::Impl {
}
}
void slave_loop() {
const auto command = config_.slave_request_command;
auto interval = config_.slave_request_interval;
if (interval.count() < 0) {
interval = 0ms;
}
const bool repeat = interval.count() > 0;
while (!stop_requested_.load(std::memory_order_acquire)) {
const bool success = send(command);
if (!success) {
std::this_thread::sleep_for(kReaderIdleSleep);
continue;
}
if (!repeat) {
break;
}
auto remaining = interval;
while (remaining.count() > 0 && !stop_requested_.load(std::memory_order_acquire)) {
const auto step = std::min(remaining, kReaderIdleSleep);
std::this_thread::sleep_for(step);
remaining -= step;
}
}
}
void decoder_loop() {
while (true) {
Packet packet;
@@ -446,14 +529,24 @@ struct CPStreamCore::Impl {
CPFrame frame;
rc = cpcodec_receive_frame(codec_ctx_, &frame);
if (rc == CP_SUCCESS) {
DecodedFrame decoded;
decoded.pts = frame.pts;
decoded.received_at = std::chrono::steady_clock::now();
decoded.frame = std::move(frame);
auto decoded = std::make_shared<DecodedFrame>();
decoded->pts = frame.pts;
decoded->received_at = std::chrono::steady_clock::now();
decoded->frame = std::move(frame);
decoded->id = codec_descriptor_ ? codec_descriptor_->id : CPCodecID::Unknow;
if (decoded->id == CPCodecID::Tactile) {
if (auto parsed = tactile::parse_frame(decoded->frame)) {
decoded->tactile = parsed;
decoded->tactile_pressures = tactile::parse_pressure_values(*parsed);
if (auto matrix = tactile::parse_matrix_size_payload(*parsed)) {
decoded->tactile_matrix_size = matrix;
}
}
}
FrameCallback callback_copy;
{
std::lock_guard lock(callback_mutex_);
std::lock_guard<std::mutex> lock(callback_mutex_);
callback_copy = frame_callback_;
}
if (callback_copy) {
@@ -461,11 +554,14 @@ struct CPStreamCore::Impl {
}
{
std::lock_guard lock(frame_mutex_);
std::lock_guard<std::mutex> lock(frame_mutex_);
if (frame_queue_.size() >= frame_queue_capacity_) {
frame_queue_.pop_front();
}
frame_queue_.push_back(std::move(decoded));
frame_queue_.push_back(decoded);
if (decoded->id == CPCodecID::Tactile) {
frame_record_queue_.push_back(decoded);
}
}
frame_cv_.notify_one();
} else if (rc == CP_ERROR_EAGAIN) {
@@ -489,7 +585,7 @@ struct CPStreamCore::Impl {
packet.flush = true;
packet.end_of_stream = end_of_stream;
{
std::lock_guard lock(packet_mutex_);
std::lock_guard<std::mutex> lock(packet_mutex_);
packet_queue_.push_back(std::move(packet));
}
packet_cv_.notify_one();
@@ -507,7 +603,7 @@ struct CPStreamCore::Impl {
}
void set_last_error(std::string message) {
std::lock_guard lock(last_error_mutex_);
std::lock_guard<std::mutex> lock(last_error_mutex_);
last_error_ = std::move(message);
}
@@ -520,15 +616,19 @@ struct CPStreamCore::Impl {
CPCodecContext* codec_ctx_ = nullptr;
std::thread reader_thread_;
std::thread slave_thread_;
std::thread decoder_thread_;
std::mutex packet_mutex_;
std::condition_variable packet_cv_;
std::deque<Packet> packet_queue_;
std::mutex frame_mutex_;
mutable std::mutex frame_mutex_;
std::condition_variable frame_cv_;
std::deque<DecodedFrame> frame_queue_;
// std::deque<DecodedFrame> frame_queue_;
// 更新为智能指针,我们需要更长的生命周期😊
std::deque<std::shared_ptr<DecodedFrame>> frame_queue_;
std::deque<std::shared_ptr<DecodedFrame>> frame_record_queue_;
std::size_t frame_queue_capacity_ = 16;
FrameCallback frame_callback_;
@@ -540,6 +640,8 @@ struct CPStreamCore::Impl {
std::string last_error_;
mutable std::mutex last_error_mutex_;
std::unique_ptr<persist::JsonWritter> frame_writer_;
};
CPStreamCore::CPStreamCore(CPStreamConfig config)
@@ -592,11 +694,11 @@ bool CPStreamCore::send(const std::uint8_t* data, std::size_t size) {
return impl_->send(data, size);
}
std::optional<DecodedFrame> CPStreamCore::try_pop_frame() {
std::optional<std::shared_ptr<DecodedFrame>> CPStreamCore::try_pop_frame() {
return impl_->try_pop_frame();
}
bool CPStreamCore::wait_for_frame(DecodedFrame& frame, std::chrono::milliseconds timeout) {
bool CPStreamCore::wait_for_frame(std::shared_ptr<DecodedFrame>& frame, std::chrono::milliseconds timeout) {
return impl_->wait_for_frame(frame, timeout);
}
@@ -608,6 +710,18 @@ void CPStreamCore::set_frame_queue_capacity(std::size_t capacity) {
impl_->set_frame_queue_capacity(capacity);
}
void CPStreamCore::clear_recorded_frames() {
impl_->clear_recorded_frames();
}
std::size_t CPStreamCore::recorded_frame_count() const {
return impl_->recorded_frame_count();
}
std::future<persist::WriteResult> CPStreamCore::export_recorded_frames(const std::string& path, bool clear_after_export) {
return impl_->export_recorded_frames(path, clear_after_export);
}
void CPStreamCore::set_frame_callback(FrameCallback callback) {
impl_->set_frame_callback(std::move(callback));
}

View File

@@ -1,21 +1,32 @@
#pragma once
#include "components/ffmsep/cpdecoder.hh"
#include "components/ffmsep/tactile/tacdec.hh"
#include <chrono>
#include <cstdint>
#include <functional>
#include <future>
#include <memory>
#include <optional>
#include <serial/serial.h>
#include <string>
#include <vector>
using namespace std::chrono_literals;
namespace ffmsep {
namespace persist {
struct WriteResult;
} // namespace persist
struct DecodedFrame {
CPFrame frame;
CPCodecID id = CPCodecID::Unknow;
std::chrono::steady_clock::time_point received_at{};
std::int64_t pts = 0;
std::optional<tactile::TactileFrame> tactile;
std::vector<std::uint16_t> tactile_pressures;
std::optional<tactile::MatrixSize> tactile_matrix_size;
};
struct CPStreamConfig {
@@ -31,11 +42,13 @@ struct CPStreamConfig {
std::size_t frame_queue_capacity = 16;
CPCodecID codec_id = CPCodecID::Unknow;
std::string codec_name;
std::vector<std::uint8_t> slave_request_command{};
std::chrono::milliseconds slave_request_interval{200ms};
};
class CPStreamCore {
public:
using FrameCallback = std::function<void(const DecodedFrame&)>;
using FrameCallback = std::function<void(std::shared_ptr<DecodedFrame>)>;
explicit CPStreamCore(CPStreamConfig config = {});
~CPStreamCore();
@@ -57,10 +70,14 @@ public:
bool send(const std::vector<std::uint8_t>& data);
bool send(const std::uint8_t* data, std::size_t size);
std::optional<DecodedFrame> try_pop_frame();
bool wait_for_frame(DecodedFrame& frame, std::chrono::milliseconds timeout);
std::optional<std::shared_ptr<DecodedFrame>> try_pop_frame();
bool wait_for_frame(std::shared_ptr<DecodedFrame>& frame, std::chrono::milliseconds timeout);
void clear_frames();
void set_frame_queue_capacity(std::size_t capacity);
void clear_recorded_frames();
[[nodiscard]] std::size_t recorded_frame_count() const;
std::future<persist::WriteResult> export_recorded_frames(const std::string& path,
bool clear_after_export = false);
void set_frame_callback(FrameCallback callback);
@@ -69,6 +86,8 @@ public:
static std::vector<serial::PortInfo> list_available_ports();
private:
struct Impl;
std::unique_ptr<Impl> impl_;

View File

@@ -0,0 +1,255 @@
//
// Created by Lenn on 2025/10/31.
//
#include "components/ffmsep/presist/presist.hh"
#include "components/ffmsep/cpstream_core.hh"
#include <algorithm>
#include <chrono>
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <system_error>
#include <nlohmann/json.hpp>
namespace ffmsep::persist {
namespace {
using nlohmann::json;
bool is_simple_array(const json& value) {
if (!value.is_array()) {
return false;
}
return std::all_of(value.begin(), value.end(), [](const json& item) {
return item.is_primitive();
});
}
void dump_compact_json(std::ostream& out,
const json& value,
int indent = 0,
int indent_step = 2) {
const auto indent_str = std::string(static_cast<std::size_t>(indent), ' ');
const auto child_indent = indent + indent_step;
const auto child_indent_str = std::string(static_cast<std::size_t>(child_indent), ' ');
if (value.is_object()) {
out << "{\n";
bool first = true;
for (auto it = value.begin(); it != value.end(); ++it) {
if (!first) {
out << ",\n";
}
first = false;
out << child_indent_str << json(it.key()).dump() << ": ";
dump_compact_json(out, it.value(), child_indent, indent_step);
}
out << '\n' << indent_str << '}';
return;
}
if (value.is_array()) {
if (value.empty()) {
out << "[]";
return;
}
if (is_simple_array(value)) {
out << '[';
for (std::size_t idx = 0; idx < value.size(); ++idx) {
if (idx != 0U) {
out << ", ";
}
out << value[static_cast<json::size_type>(idx)].dump();
}
out << ']';
return;
}
out << "[\n";
bool first = true;
for (const auto& item : value) {
if (!first) {
out << ",\n";
}
first = false;
out << child_indent_str;
dump_compact_json(out, item, child_indent, indent_step);
}
out << '\n' << indent_str << ']';
return;
}
out << value.dump();
}
json serialize_tactile_frame(const DecodedFrame& frame) {
json result = {
{"pts", frame.pts},
{"raw_frame", frame.frame.data},
{"pressures", frame.tactile_pressures},
};
const auto received = frame.received_at.time_since_epoch();
result["received_at_ns"] =
std::chrono::duration_cast<std::chrono::nanoseconds>(received).count();
if (frame.tactile_matrix_size) {
result["matrix"] = {
{"long_edge", frame.tactile_matrix_size->long_edge},
{"short_edge", frame.tactile_matrix_size->short_edge},
};
}
if (frame.tactile) {
const auto& tactile = *frame.tactile;
result["tactile"] = {
{"device_address", tactile.device_address},
{"response_function", tactile.response_function},
{"function", static_cast<std::uint8_t>(tactile.function)},
{"start_address", tactile.start_address},
{"return_byte_count", tactile.return_byte_count},
{"status", tactile.status},
{"payload", tactile.payload},
};
}
return result;
}
} // namespace
bool WriteQueue::push(WriteRequest&& req) {
{
std::lock_guard<std::mutex> lock(mutex_);
if (stopped_) {
return false;
}
queue_.push(std::move(req));
}
cond_.notify_one();
return true;
}
bool WriteQueue::pop(WriteRequest& out) {
std::unique_lock lock(mutex_);
cond_.wait(lock, [&] {
return stopped_ || !queue_.empty();
});
if (queue_.empty()) {
return false;
}
out = std::move(queue_.front());
queue_.pop();
return true;
}
void WriteQueue::stop() {
{
std::lock_guard<std::mutex> lock(mutex_);
stopped_ = true;
}
cond_.notify_all();
}
JsonWritter::JsonWritter()
: write_thread_([this] { run(); }) {}
JsonWritter::~JsonWritter() {
stop();
}
std::future<WriteResult> JsonWritter::enqueue(std::string path,
std::deque<std::shared_ptr<DecodedFrame>> frames) {
std::promise<WriteResult> promise;
auto future = promise.get_future();
WriteRequest request{std::move(path), std::move(frames), std::move(promise)};
if (!write_queue_.push(std::move(request))) {
WriteResult result{false, "writer has been stopped", request.path};
request.promise.set_value(std::move(result));
}
return future;
}
void JsonWritter::run() {
WriteRequest request;
while (write_queue_.pop(request)) {
try {
auto result = write_once(request.path, std::move(request.frames));
request.promise.set_value(std::move(result));
} catch (const std::exception& ex) {
request.promise.set_value(WriteResult{false, ex.what(), request.path});
} catch (...) {
request.promise.set_value(WriteResult{false, "unknown error", request.path});
}
}
}
WriteResult JsonWritter::write_once(const std::string& path,
std::deque<std::shared_ptr<DecodedFrame>> frames) {
if (path.empty()) {
return {false, "export path is empty", path};
}
json tactile_frames = json::array();
for (const auto& frame : frames) {
if (!frame) {
continue;
}
if (frame->id != CPCodecID::Tactile || !frame->tactile) {
continue;
}
tactile_frames.push_back(serialize_tactile_frame(*frame));
}
if (tactile_frames.empty()) {
return {false, "no tactile frames available for export", path};
}
json root;
root["codec"] = "tactile";
root["frames"] = std::move(tactile_frames);
std::filesystem::path fs_path(path);
if (fs_path.has_parent_path()) {
std::error_code ec;
std::filesystem::create_directories(fs_path.parent_path(), ec);
if (ec) {
return {false, "failed to create export directory: " + ec.message(), path};
}
}
std::ofstream stream(path, std::ios::binary | std::ios::trunc);
if (!stream.is_open()) {
return {false, "failed to open export file", path};
}
dump_compact_json(stream, root);
stream << '\n';
stream.flush();
if (!stream.good()) {
return {false, "failed to write export file", path};
}
return {true, {}, path};
}
void JsonWritter::stop() {
if (!stopped_.exchange(true)) {
write_queue_.stop();
if (write_thread_.joinable()) {
write_thread_.join();
}
}
}
} // namespace ffmsep::persist

View File

@@ -0,0 +1,86 @@
//
// Created by Lenn on 2025/10/31.
//
#ifndef TOUCHSENSOR_PRESIST_HH
#define TOUCHSENSOR_PRESIST_HH
#include <atomic>
#include <condition_variable>
#include <deque>
#include <future>
#include <memory>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
namespace ffmsep {
struct DecodedFrame;
namespace persist {
struct WriteResult {
bool ok = false;
std::string error;
std::string path;
};
struct WriteRequest {
WriteRequest() = default;
WriteRequest(std::string p,
std::deque<std::shared_ptr<DecodedFrame>> f,
std::promise<WriteResult>&& pr)
: path(std::move(p))
, frames(std::move(f))
, promise(std::move(pr)) {}
WriteRequest(const WriteRequest&) = delete;
WriteRequest& operator=(const WriteRequest&) = delete;
WriteRequest(WriteRequest&&) noexcept = default;
WriteRequest& operator=(WriteRequest&&) noexcept = default;
std::string path;
std::deque<std::shared_ptr<DecodedFrame>> frames;
std::promise<WriteResult> promise;
};
class WriteQueue {
public:
bool push(WriteRequest&& req);
bool pop(WriteRequest& out);
void stop();
private:
std::mutex mutex_;
std::condition_variable cond_;
std::queue<WriteRequest> queue_;
bool stopped_ = false;
};
class JsonWritter {
public:
JsonWritter();
~JsonWritter();
std::future<WriteResult> enqueue(std::string path,
std::deque<std::shared_ptr<DecodedFrame>> frames);
void stop();
private:
void run();
WriteResult write_once(const std::string& path,
std::deque<std::shared_ptr<DecodedFrame>> frames);
private:
std::thread write_thread_;
WriteQueue write_queue_;
std::atomic_bool stopped_{false};
};
} // namespace persist
} // namespace ffmsep
#endif // TOUCHSENSOR_PRESIST_HH

View File

@@ -1,6 +1,7 @@
#include "tacdec.hh"
#include "components/ffmsep/cpdecoder.hh"
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <new>
@@ -10,16 +11,16 @@
namespace ffmsep::tactile {
namespace {
constexpr std::size_t kMinimumFrameSize = 1
+ 1
+ 1
+ 1
+ 0
+ 2
+ 2;
constexpr std::uint16_t kCrcInitial = 0xFFFF;
constexpr std::uint16_t kCrcPolynomial = 0xA001;
constexpr std::size_t kHeaderSize = 4U; // start bytes + length field
constexpr std::size_t kFixedSectionSize = 1U + 1U + 1U + 4U + 2U + 1U; // address..status
constexpr std::size_t kMinimumFrameSize = kHeaderSize + kFixedSectionSize + 1U; // + CRC byte
constexpr std::uint8_t kCrcPolynomial = 0x07U;
constexpr std::uint8_t kCrcInitial = 0x00U;
constexpr std::uint8_t kCrcXorOut = 0xA9U;
constexpr std::array<std::uint8_t, 2> kStartSequence{
kStartByteFirst,
kStartByteSecond
};
struct TactileDecoderContext {
std::vector<std::uint8_t> fifo;
@@ -27,28 +28,23 @@ struct TactileDecoderContext {
std::int64_t next_pts = 0;
};
std::size_t frame_length_from_payload(std::uint8_t payload_length) {
return 1U + 1U + 1U + 1U + payload_length + 2U + 2U;
}
const std::uint8_t* buffer_data(const std::vector<std::uint8_t>& buf) {
return buf.empty() ? nullptr : buf.data();
}
std::uint16_t crc16_modbus(const std::uint8_t* data, std::size_t length) {
std::uint16_t crc = kCrcInitial;
std::uint8_t crc8_with_xorout(const std::uint8_t* data, std::size_t length) {
std::uint8_t reg = kCrcInitial;
for (std::size_t i = 0; i < length; ++i) {
crc ^= static_cast<std::uint16_t>(data[i]);
reg ^= data[i];
for (int bit = 0; bit < 8; ++bit) {
if ((crc & 0x0001U) != 0U) {
crc = static_cast<std::uint16_t>((crc >> 1U) ^ kCrcPolynomial);
}
else {
crc = static_cast<std::uint16_t>(crc >> 1U);
if ((reg & 0x80U) != 0U) {
reg = static_cast<std::uint8_t>((reg << 1U) ^ kCrcPolynomial);
} else {
reg = static_cast<std::uint8_t>(reg << 1U);
}
}
}
return crc;
return static_cast<std::uint8_t>(reg ^ kCrcXorOut);
}
TactileDecoderContext* get_priv(CPCodecContext* ctx) {
@@ -115,7 +111,8 @@ int tactile_receive_frame(CPCodecContext* ctx, CPFrame& frame) {
return CP_ERROR_EAGAIN;
}
auto start_it = std::find(buf.begin(), buf.end(), kStartByte);
const auto start_it = std::search(buf.begin(), buf.end(),
kStartSequence.begin(), kStartSequence.end());
if (start_it == buf.end()) {
buf.clear();
if (priv->end_of_stream) {
@@ -129,7 +126,7 @@ int tactile_receive_frame(CPCodecContext* ctx, CPFrame& frame) {
buf.erase(buf.begin(), start_it);
}
if (buf.size() < kMinimumFrameSize) {
if (buf.size() < kHeaderSize) {
if (priv->end_of_stream) {
buf.clear();
priv->end_of_stream = false;
@@ -139,11 +136,21 @@ int tactile_receive_frame(CPCodecContext* ctx, CPFrame& frame) {
}
const std::uint8_t* data = buffer_data(buf);
const std::uint8_t address = data[1U];
const FunctionCode function = static_cast<FunctionCode>(data[2U]);
const std::uint8_t payload_length = data[3U];
const std::size_t total_frame_length = frame_length_from_payload(payload_length);
if (!data) {
buf.clear();
continue;
}
const std::uint16_t data_length =
static_cast<std::uint16_t>(data[2]) |
static_cast<std::uint16_t>(static_cast<std::uint16_t>(data[3]) << 8U);
if (data_length < kFixedSectionSize) {
buf.erase(buf.begin());
continue;
}
const std::size_t total_frame_length = kHeaderSize + static_cast<std::size_t>(data_length) + 1U;
if (buf.size() < total_frame_length) {
if (priv->end_of_stream) {
buf.clear();
@@ -153,33 +160,13 @@ int tactile_receive_frame(CPCodecContext* ctx, CPFrame& frame) {
return CP_ERROR_EAGAIN;
}
const std::size_t payload_offset = 4U;
const std::size_t crc_offset = payload_offset + payload_length;
const std::size_t end_offset = crc_offset + 2U;
const std::uint8_t crc_lo = data[crc_offset];
const std::uint8_t crc_hi = data[crc_offset + 1U];
const std::uint16_t crc_value = static_cast<std::uint16_t>(crc_lo) |
static_cast<std::uint16_t>(crc_hi << 8U);
const std::uint8_t end_first = data[end_offset];
const std::uint8_t end_second = data[end_offset + 1U];
if (end_first != kEndByteFirst || end_second != kEndByteSecond) {
const std::uint8_t computed_crc = crc8_with_xorout(data + kHeaderSize, data_length);
const std::uint8_t frame_crc = data[kHeaderSize + static_cast<std::size_t>(data_length)];
if (computed_crc != frame_crc) {
buf.erase(buf.begin());
continue;
}
const std::size_t crc_region_length = 3U + payload_length;
const std::uint16_t computed_crc = crc16_modbus(data + 1U, crc_region_length);
if (computed_crc != crc_value) {
buf.erase(buf.begin());
continue;
}
(void)address;
(void)function;
frame.data.assign(buf.begin(), buf.begin() + static_cast<std::ptrdiff_t>(total_frame_length));
frame.pts = priv->next_pts++;
frame.key_frame = true;
@@ -210,35 +197,63 @@ std::optional<TactileFrame> parse_frame(const CPFrame& frame) {
const auto* bytes = frame.data.data();
const std::size_t size = frame.data.size();
if (bytes[0] != kStartByte) {
if (bytes[0] != kStartByteFirst || bytes[1] != kStartByteSecond) {
return std::nullopt;
}
if (bytes[size - 2] != kEndByteFirst || bytes[size - 1] != kEndByteSecond) {
const std::uint16_t data_length =
static_cast<std::uint16_t>(bytes[2]) |
static_cast<std::uint16_t>(static_cast<std::uint16_t>(bytes[3]) << 8U);
if (data_length < kFixedSectionSize) {
return std::nullopt;
}
if (size < 4U) {
const std::size_t expected_size = kHeaderSize + static_cast<std::size_t>(data_length) + 1U;
if (size != expected_size) {
return std::nullopt;
}
const std::uint8_t length = bytes[3];
if (frame_length_from_payload(length) != size) {
const std::uint8_t crc_byte = bytes[size - 1U];
const std::uint8_t computed_crc = crc8_with_xorout(bytes + kHeaderSize, data_length);
if (computed_crc != crc_byte) {
return std::nullopt;
}
const std::uint8_t device_address = bytes[4];
const std::uint8_t reserved = bytes[5];
const std::uint8_t response_function = bytes[6];
const std::uint32_t start_address =
static_cast<std::uint32_t>(bytes[7]) |
(static_cast<std::uint32_t>(bytes[8]) << 8U) |
(static_cast<std::uint32_t>(bytes[9]) << 16U) |
(static_cast<std::uint32_t>(bytes[10]) << 24U);
const std::uint16_t return_byte_count =
static_cast<std::uint16_t>(bytes[11]) |
(static_cast<std::uint16_t>(bytes[12]) << 8U);
const std::uint8_t status = bytes[13];
const std::size_t payload_offset = kHeaderSize + kFixedSectionSize;
const std::size_t payload_length = static_cast<std::size_t>(data_length) - kFixedSectionSize;
if (payload_length != return_byte_count) {
return std::nullopt;
}
const std::uint8_t address = bytes[1];
const FunctionCode function = static_cast<FunctionCode>(bytes[2]);
const std::size_t payload_offset = 4U;
TactileFrame parsed{};
parsed.device_address = address;
parsed.function = function;
parsed.data_length = length;
parsed.payload.assign(bytes + payload_offset, bytes + payload_offset + length);
parsed.device_address = device_address;
parsed.reserved = reserved;
parsed.response_function = response_function;
parsed.function = static_cast<FunctionCode>(response_function & 0x7FU);
parsed.start_address = start_address;
parsed.return_byte_count = return_byte_count;
parsed.status = status;
parsed.payload.assign(bytes + payload_offset, bytes + payload_offset + payload_length);
return parsed;
}
std::vector<std::uint16_t> parse_pressure_values(const TactileFrame& frame) {
if (frame.payload.size() != frame.return_byte_count) {
return {};
}
if (frame.payload.empty() || (frame.payload.size() % 2U != 0U)) {
return {};
}

View File

@@ -6,9 +6,8 @@
#include <vector>
namespace ffmsep::tactile {
inline constexpr std::uint8_t kStartByte = 0x3A;
inline constexpr std::uint8_t kEndByteFirst = 0x0D;
inline constexpr std::uint8_t kEndByteSecond = 0x0A;
inline constexpr std::uint8_t kStartByteFirst = 0xAA;
inline constexpr std::uint8_t kStartByteSecond = 0x55;
enum class FunctionCode : std::uint8_t {
Unknown = 0x00,
@@ -27,16 +26,21 @@ struct MatrixSize {
struct TactileFrame {
std::uint8_t device_address = 0;
std::uint8_t reserved = 0;
std::uint8_t response_function = 0;
FunctionCode function = FunctionCode::Unknown;
std::uint8_t data_length = 0;
std::uint32_t start_address = 0;
std::uint16_t return_byte_count = 0;
std::uint8_t status = 0;
std::vector<std::uint8_t> payload;
};
std::optional<TactileFrame> parse_frame(const CPFrame &frame);
std::vector<std::uint16_t> parse_pressure_values(const TactileFrame &frame);
std::optional<MatrixSize> parse_matrix_size_payload(const TactileFrame &frame);
std::optional<MatrixSize> parse_patrix_coordinate_payload(const TactileFrame& frame);
std::optional<MatrixSize>
parse_patrix_coordinate_payload(const TactileFrame &frame);
const CPCodec *tactile_codec();
void register_tactile_codec();
}
} // namespace ffmsep::tactile

44
components/hand-view.cc Normal file
View File

@@ -0,0 +1,44 @@
//
// Created by Lenn on 2025/11/24.
//
#include "component.hh"
#include "base/globalhelper.hh"
#include "creeper-qt/utility/theme/theme.hh"
#include "creeper-qt/utility/wrapper/layout.hh"
#include "creeper-qt/utility/wrapper/widget.hh"
#include "creeper-qt/layout/flow.hh"
#include "creeper-qt/layout/linear.hh"
#include "creeper-qt/widget/cards/basic-card.hh"
#include <concepts>
#include <creeper-qt/utility/material-icon.hh>
#include <creeper-qt/utility/wrapper/mutable-value.hh>
#include <creeper-qt/widget/buttons/icon-button.hh>
#include <creeper-qt/widget/cards/filled-card.hh>
#include <creeper-qt/widget/cards/outlined-card.hh>
#include <creeper-qt/widget/dropdown-menu.hh>
#include <creeper-qt/widget/image.hh>
#include <creeper-qt/widget/shape/wave-circle.hh>
#include <creeper-qt/widget/sliders.hh>
#include <creeper-qt/widget/switch.hh>
#include <creeper-qt/widget/text-fields.hh>
#include <creeper-qt/widget/text.hh>
#include <creeper-qt/widget/buttons/icon-button.hh>
#include <cstddef>
#include <iterator>
#include <qcontainerfwd.h>
#include <qlogging.h>
#include <qnamespace.h>
#include <ranges>
#include <utility>
using namespace creeper;
namespace capro = card::pro;
namespace lnpro = linear::pro;
namespace ibpro = icon_button::pro;
auto HandViewComponent(HandViewComponentState& state) noexcept -> raw_pointer<QWidget> {
return new FilledCard {
capro::ThemeManager{state.manager},
capro::SizePolicy {QSizePolicy::Expanding},
};
}

View File

@@ -1,14 +1,14 @@
#include "component.hh"
#include "modern-qt/core/application.hh"
#include "modern-qt/layout/group.hh"
#include "modern-qt/layout/linear.hh"
#include "modern-qt/layout/mutual-exclusion-group.hh"
#include "modern-qt/utility/material-icon.hh"
#include "modern-qt/utility/theme/theme.hh"
#include "modern-qt/widget/buttons/icon-button.hh"
#include "modern-qt/widget/cards/filled-card.hh"
#include "modern-qt/widget/image.hh"
#include "creeper-qt/core/application.hh"
#include "creeper-qt/layout/group.hh"
#include "creeper-qt/layout/linear.hh"
#include "creeper-qt/layout/mutual-exclusion-group.hh"
#include "creeper-qt/utility/material-icon.hh"
#include "creeper-qt/utility/theme/theme.hh"
#include "creeper-qt/widget/buttons/icon-button.hh"
#include "creeper-qt/widget/cards/filled-card.hh"
#include "creeper-qt/widget/image.hh"
using namespace creeper;
namespace fc = filled_card::pro;
@@ -26,7 +26,6 @@ auto NavComponent(NavComponentState& state) noexcept -> raw_pointer<QWidget> {
im::BorderWidth {3},
im::PainterResource {
":/images/images/logo.png",
// "./images/logo.png",
},
};
state.manager.append_handler(AvatarComponent, [AvatarComponent](const ThemeManager& manager) {
@@ -74,7 +73,10 @@ auto NavComponent(NavComponentState& state) noexcept -> raw_pointer<QWidget> {
navigation_icons_config,
status,
ic::FontIcon(icon.data()),
ic::Clickable {[=]{state.switch_callback(index, name);}},
ic::Clickable {[=] {
// state.switch_callback(index, name);
state.stacked_callback(index);
}},
};
},
Qt::AlignHCenter,

437
components/setting.cc Normal file
View File

@@ -0,0 +1,437 @@
//
// Created by Lenn on 2025/11/21.
//
#include "component.hh"
#include "base/globalhelper.hh"
#include "creeper-qt/utility/theme/theme.hh"
#include "creeper-qt/utility/wrapper/layout.hh"
#include "creeper-qt/utility/wrapper/widget.hh"
#include "creeper-qt/layout/flow.hh"
#include "creeper-qt/layout/linear.hh"
#include "creeper-qt/layout/scroll.hh"
#include "creeper-qt/widget/buttons/filled-button.hh"
#include "creeper-qt/widget/cards/basic-card.hh"
#include <concepts>
#include <creeper-qt/utility/material-icon.hh>
#include <creeper-qt/utility/wrapper/mutable-value.hh>
#include <creeper-qt/widget/buttons/icon-button.hh>
#include <creeper-qt/widget/cards/filled-card.hh>
#include <creeper-qt/widget/cards/outlined-card.hh>
#include <creeper-qt/widget/dropdown-menu.hh>
#include <creeper-qt/widget/image.hh>
#include <creeper-qt/widget/shape/wave-circle.hh>
#include <creeper-qt/widget/sliders.hh>
#include <creeper-qt/widget/switch.hh>
#include <creeper-qt/widget/text-fields.hh>
#include <creeper-qt/widget/text.hh>
#include <creeper-qt/widget/buttons/icon-button.hh>
#include <cstddef>
#include <iterator>
#include <qcontainerfwd.h>
#include <qlogging.h>
#include <qnamespace.h>
#include <ranges>
#include <utility>
#include "globalhelper.hh"
#include <functional>
#include <memory>
#include <QComboBox>
#include <QDialog>
#include <QDialogButtonBox>
#include <QFormLayout>
#include <QLineEdit>
#include <QSpinBox>
#include <QVBoxLayout>
#include <sys/stat.h>
namespace repest_literals {
template<class F>
concept IndexInvocable = std::invocable<F, std::size_t>;
template<IndexInvocable F>
void operator*(F&& f, std::size_t n) {
std::ranges::for_each(std::views::iota(std::size_t{ 0 }, n), std::forward<F>(f));
}
template<IndexInvocable F>
void operator*(std::size_t n, F&& f) {
std::ranges::for_each(std::views::iota(std::size_t{ 0 }, n), std::forward<F>(f));
}
} // namespace repest_literals
using namespace creeper;
namespace capro = card::pro;
namespace lnpro = linear::pro;
namespace ibpro = icon_button::pro;
namespace fbpro = filled_button::pro;
static std::weak_ptr<MutableValue<std::vector<ConfigProfile>>> g_profiles_store;
static std::function<void()> g_profiles_refresh;
static void ShowEditProfileDialog(
const ConfigProfile& current,
const std::shared_ptr<MutableValue<std::vector<ConfigProfile>>>& profiles_store) {
QDialog dialog;
dialog.setWindowTitle(QStringLiteral("修改配置"));
auto* layout = new QVBoxLayout(&dialog);
auto* form = new QFormLayout();
auto* name_edit = new QLineEdit(&dialog);
name_edit->setText(current.name);
auto* type_combo = new QComboBox(&dialog);
type_combo->addItem(QStringLiteral("压阻A型"));
type_combo->addItem(QStringLiteral("压阻B型"));
type_combo->addItem(QStringLiteral("霍尔型"));
switch (current.type) {
case Tactile_TYPE::PiezoresistiveA:
type_combo->setCurrentIndex(0);
break;
case Tactile_TYPE::PiezoresistiveB:
type_combo->setCurrentIndex(1);
break;
case Tactile_TYPE::Hall:
type_combo->setCurrentIndex(2);
break;
}
auto* width_spin = new QSpinBox(&dialog);
auto* height_spin = new QSpinBox(&dialog);
width_spin->setRange(1, 64);
height_spin->setRange(1, 64);
width_spin->setValue(current.matrix_width);
height_spin->setValue(current.matrix_height);
auto* left_spin = new QSpinBox(&dialog);
auto* right_spin = new QSpinBox(&dialog);
left_spin->setRange(-100000, 100000);
right_spin->setRange(-100000, 100000);
left_spin->setValue(current.range_left);
right_spin->setValue(current.range_right);
auto* baud_spin = new QSpinBox(&dialog);
baud_spin->setRange(1200, 10000000);
baud_spin->setValue(current.baud_rate);
form->addRow(QStringLiteral("名称"), name_edit);
form->addRow(QStringLiteral("类型"), type_combo);
form->addRow(QStringLiteral(""), width_spin);
form->addRow(QStringLiteral(""), height_spin);
form->addRow(QStringLiteral("量程左"), left_spin);
form->addRow(QStringLiteral("量程右"), right_spin);
form->addRow(QStringLiteral("波特率"), baud_spin);
layout->addLayout(form);
auto* buttons =
new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, &dialog);
layout->addWidget(buttons);
QObject::connect(buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
QObject::connect(buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
if (dialog.exec() == QDialog::Accepted) {
ConfigProfile updated = current;
updated.name = name_edit->text();
updated.type = [idx = type_combo->currentIndex()] {
switch (idx) {
case 0:
return Tactile_TYPE::PiezoresistiveA;
case 1:
return Tactile_TYPE::PiezoresistiveB;
default:
return Tactile_TYPE::Hall;
}
}();
updated.matrix_width = width_spin->value();
updated.matrix_height = height_spin->value();
updated.range_left = left_spin->value();
updated.range_right = right_spin->value();
updated.baud_rate = baud_spin->value();
GlobalHelper::instance().remove_profile(current.name);
GlobalHelper::instance().add_new_profile(updated);
GlobalHelper::instance().reload_profiles();
if (profiles_store) {
profiles_store->set(GlobalHelper::instance().get_all_profile());
}
RefreshProfilesForView();
if (g_profiles_refresh) {
g_profiles_refresh();
}
}
}
static void ShowAddProfileDialog() {
QDialog dialog;
dialog.setWindowTitle(QStringLiteral("添加配置"));
auto* layout = new QVBoxLayout(&dialog);
auto* form = new QFormLayout();
auto* name_edit = new QLineEdit(&dialog);
auto* type_combo = new QComboBox(&dialog);
type_combo->addItem(QStringLiteral("压阻A型"));
type_combo->addItem(QStringLiteral("压阻B型"));
type_combo->addItem(QStringLiteral("霍尔型"));
auto* width_spin = new QSpinBox(&dialog);
auto* height_spin = new QSpinBox(&dialog);
width_spin->setRange(1, 64);
height_spin->setRange(1, 64);
auto* left_spin = new QSpinBox(&dialog);
auto* right_spin = new QSpinBox(&dialog);
left_spin->setRange(-100000, 100000);
right_spin->setRange(-100000, 100000);
auto* baud_spin = new QSpinBox(&dialog);
baud_spin->setRange(1200, 10000000);
baud_spin->setValue(115200);
form->addRow(QStringLiteral("名称"), name_edit);
form->addRow(QStringLiteral("类型"), type_combo);
form->addRow(QStringLiteral(""), width_spin);
form->addRow(QStringLiteral(""), height_spin);
form->addRow(QStringLiteral("量程左"), left_spin);
form->addRow(QStringLiteral("量程右"), right_spin);
form->addRow(QStringLiteral("波特率"), baud_spin);
layout->addLayout(form);
auto* buttons =
new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, &dialog);
layout->addWidget(buttons);
QObject::connect(buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
QObject::connect(buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
if (dialog.exec() == QDialog::Accepted) {
ConfigProfile profile;
profile.name = name_edit->text();
profile.type = [idx = type_combo->currentIndex()] {
switch (idx) {
case 0:
return Tactile_TYPE::PiezoresistiveA;
case 1:
return Tactile_TYPE::PiezoresistiveB;
default:
return Tactile_TYPE::Hall;
}
}();
profile.matrix_width = width_spin->value();
profile.matrix_height = height_spin->value();
profile.range_left = left_spin->value();
profile.range_right = right_spin->value();
profile.baud_rate = baud_spin->value();
GlobalHelper::instance().add_new_profile(profile);
GlobalHelper::instance().reload_profiles();
if (auto store = g_profiles_store.lock()) {
store->set(GlobalHelper::instance().get_all_profile());
}
RefreshProfilesForView();
if (g_profiles_refresh) {
g_profiles_refresh();
}
}
}
static auto AddProfileLongItem(creeper::ThemeManager& manager) {
return new FilledButton {
fbpro::ThemeManager {manager},
fbpro::Text {QStringLiteral("添加配置")},
widget::pro::SizePolicy {QSizePolicy::Fixed, QSizePolicy::Expanding},
widget::pro::MinimumHeight {40},
widget::pro::MinimumWidth {320},
fbpro::Radius {12},
fbpro::Clickable {[]{ ShowAddProfileDialog(); }},
};
}
static auto ProfileItemComponent(creeper::ThemeManager& manager, ConfigProfile& profile,
const std::shared_ptr<MutableValue<std::vector<ConfigProfile>>>& profiles_store) {
QString matrix_size = "规格:" + QString{ "%1 * %2" }.arg(profile.matrix_width).arg(profile.matrix_height);
QString value_range = "量程:" + QString{ "%1 ~ %2" }.arg(profile.range_left).arg(profile.range_right);
QString tactile_type = [profile]() -> QString {
switch (profile.type) {
case Tactile_TYPE::PiezoresistiveA:
return "类型压阻A型";
case Tactile_TYPE::PiezoresistiveB:
return "类型压阻B型";
case Tactile_TYPE::Hall:
return "类型:霍尔型";
}
return "错误";
}();
QString baud_rate = "波特率:" + QString::number(profile.baud_rate);
return new FilledCard{
card::pro::SizePolicy {
QSizePolicy::Expanding,
},
card::pro::MinimumSize {
300, 50
},
// card::pro::FixedSize {
// 200, 100
// },
card::pro::ThemeManager{ manager },
card::pro::SizePolicy { QSizePolicy::Expanding },
card::pro::LevelLow,
card::pro::Layout<Col>{
lnpro::Item<Row>{
// row::pro::Stretch {1},
row::pro::Item<Text>{
text::pro::AdjustSize {},
text::pro::Text{ QString{ profile.name } },
text::pro::Apply{
[&manager](Text& self) {
manager.append_handler(&self, [&](const ThemeManager& manager) {
const auto scheme = manager.color_scheme();
self.set_color(scheme.primary);
});
} },
},
row::pro::Item<IconButton>{
ibpro::ThemeManager{ manager },
ibpro::FixedSize{ 30, 30 },
ibpro::Font{ material::kRegularExtraSmallFont },
icon_button::pro::FontIcon{ material::icon::kBorderColor },
ibpro::Clickable{ [profiles_store, current = profile] {
ShowEditProfileDialog(current, profiles_store);
} },
},
row::pro::Item<IconButton>{
ibpro::ThemeManager{ manager },
ibpro::FixedSize{ 30, 30 },
ibpro::Font{ material::kRegularExtraSmallFont },
icon_button::pro::FontIcon{ material::icon::kDelete },
ibpro::Clickable{ [profiles_store, name = profile.name, &manager] {
GlobalHelper::instance().remove_profile(name);
GlobalHelper::instance().reload_profiles();
if (profiles_store) {
profiles_store->set(GlobalHelper::instance().get_all_profile());
}
RefreshProfilesForView();
manager.apply_theme();
} },
}
},
lnpro::Item<Text>{
text::pro::Text{ tactile_type },
text::pro::Apply{
[&manager](Text& self) {
manager.append_handler(&self, [&](const ThemeManager& manager) {
const auto scheme = manager.color_scheme();
self.set_color(scheme.primary);
});
} } },
lnpro::Item<Text>{
text::pro::AdjustSize {},
text::pro::Text{ matrix_size },
text::pro::Apply{
[&manager](Text& self) {
manager.append_handler(&self, [&](const ThemeManager& manager) {
const auto scheme = manager.color_scheme();
self.set_color(scheme.primary);
});
} }
},
lnpro::Item<Text>{
text::pro::Text{ value_range },
text::pro::Apply{
[&manager](Text& self) {
manager.append_handler(&self, [&](const ThemeManager& manager) {
const auto scheme = manager.color_scheme();
self.set_color(scheme.primary);
});
} } },
lnpro::Item<Text>{
text::pro::Text{ baud_rate },
text::pro::Apply{
[&manager](Text& self) {
manager.append_handler(&self, [&](const ThemeManager& manager) {
const auto scheme = manager.color_scheme();
self.set_color(scheme.primary);
});
} }
},
},
};
}
static void PopulateProfiles(Flow& flow, creeper::ThemeManager& manager,
const std::vector<ConfigProfile>& profiles,
const std::shared_ptr<MutableValue<std::vector<ConfigProfile>>>& profiles_store) {
while (auto item = flow.takeAt(0)) {
if (auto* w = item->widget()) {
w->deleteLater();
}
delete item;
}
using namespace repest_literals;
profiles.size() * [&](auto i) {
flow.addWidget(ProfileItemComponent(manager, const_cast<ConfigProfile&>(profiles[i]), profiles_store));
};
flow.update();
}
static void AttachProfilesObserver(const std::shared_ptr<MutableValue<std::vector<ConfigProfile>>>& store,
Flow& flow, creeper::ThemeManager& manager) {
struct Functor : creeper::MutableValue<std::vector<ConfigProfile>>::Functor {
Flow& flow;
creeper::ThemeManager& manager;
std::weak_ptr<MutableValue<std::vector<ConfigProfile>>> store_ptr;
Functor(Flow& f, creeper::ThemeManager& m,
std::weak_ptr<MutableValue<std::vector<ConfigProfile>>> s) noexcept
: flow(f)
, manager(m)
, store_ptr(std::move(s)) { }
void update(const std::vector<ConfigProfile>& value) override {
PopulateProfiles(flow, manager, value, store_ptr.lock());
manager.apply_theme();
}
};
auto functor = std::make_unique<Functor>(flow, manager, store);
store->callbacks[&flow] = std::move(functor);
auto alive = std::weak_ptr { store->alive };
QObject::connect(&flow, &QObject::destroyed, [store, alive](auto* key) {
if (alive.lock()) store->callbacks.erase(key);
});
}
auto SettingComponent(SettingComponentState& state) noexcept -> raw_pointer<QWidget> {
auto profiles_ctx = std::make_shared<MutableValue<std::vector<ConfigProfile>>>(
GlobalHelper::instance().get_all_profile()
);
g_profiles_store = profiles_ctx;
g_profiles_refresh = [profiles_ctx]() {
if (auto store = profiles_ctx) {
store->set(GlobalHelper::instance().get_all_profile());
}
};
auto* profiles_flow = new Flow {
flow::pro::RowSpacing{ 10 },
flow::pro::ColSpacing{ 10 },
flow::pro::RowLimit{ 10 },
};
PopulateProfiles(*profiles_flow, state.manager, profiles_ctx->get(), profiles_ctx);
AttachProfilesObserver(profiles_ctx, *profiles_flow, state.manager);
return new FilledCard {
capro::ThemeManager{ state.manager },
capro::SizePolicy{ QSizePolicy::Expanding },
capro::Layout<Col>{
lnpro::Alignment {Qt::AlignTop},
lnpro::Margin {10},
lnpro::Spacing {10},
lnpro::Item{
AddProfileLongItem(state.manager)
},
col::pro::Item<ScrollArea>{
scroll::pro::ThemeManager { state.manager },
scroll::pro::HorizontalScrollBarPolicy { Qt::ScrollBarAlwaysOff },
scroll::pro::Item {
profiles_flow
},
},
},
};
}

View File

@@ -2,49 +2,561 @@
// Created by Lenn on 2025/10/14.
//
#include <algorithm>
#include <array>
#include <cmath>
#include <cstdint>
#include <exception>
#include <future>
#include <memory>
#include <mutex>
#include <thread>
#include <QString>
#include <QObject>
#include <QMetaObject>
#include <QStringList>
#include <QtCore/Qt>
#include <QCoreApplication>
#include <QDateTime>
#include <QDir>
#include <QFileDialog>
#include <QMessageBox>
#include <QStandardPaths>
#include <QPair>
#include <optional>
#include <string>
#include <qsize.h>
#include <qsizepolicy.h>
#include <random>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <sstream>
#include "component.hh"
#include "modern-qt/utility/theme/theme.hh"
#include "modern-qt/utility/wrapper/layout.hh"
#include "modern-qt/utility/wrapper/widget.hh"
#include "cpstream_core.hh"
#include "base/globalhelper.hh"
#include "creeper-qt/utility/theme/theme.hh"
#include "creeper-qt/utility/wrapper/layout.hh"
#include "creeper-qt/utility/wrapper/widget.hh"
#include "components/charts/heatmap.hh"
#include <modern-qt/layout/flow.hh>
#include <modern-qt/layout/linear.hh>
#include <modern-qt/utility/material-icon.hh>
#include <modern-qt/utility/wrapper/mutable-value.hh>
#include <modern-qt/widget/buttons/icon-button.hh>
#include <modern-qt/widget/cards/filled-card.hh>
#include <modern-qt/widget/cards/outlined-card.hh>
#include <modern-qt/widget/image.hh>
#include <modern-qt/widget/shape/wave-circle.hh>
#include <modern-qt/widget/sliders.hh>
#include <modern-qt/widget/switch.hh>
#include <modern-qt/widget/text-fields.hh>
#include <modern-qt/widget/text.hh>
#include <modern-qt/widget/select.hh>
#include <creeper-qt/layout/flow.hh>
#include <creeper-qt/layout/linear.hh>
#include <creeper-qt/utility/material-icon.hh>
#include <creeper-qt/utility/wrapper/mutable-value.hh>
#include <creeper-qt/widget/buttons/icon-button.hh>
#include <creeper-qt/widget/buttons/filled-button.hh>
#include <creeper-qt/widget/cards/filled-card.hh>
#include <creeper-qt/widget/cards/outlined-card.hh>
#include <creeper-qt/widget/image.hh>
#include <creeper-qt/widget/shape/wave-circle.hh>
#include <creeper-qt/widget/sliders.hh>
#include <creeper-qt/widget/switch.hh>
#include <creeper-qt/widget/text-fields.hh>
#include <creeper-qt/widget/text.hh>
#include <creeper-qt/widget/dropdown-menu.hh>
#include "components/ffmsep/presist/presist.hh"
#include "components/ffmsep/tactile/tacdec.hh"
#include <qstringliteral.h>
#define DEBUG 0
using namespace creeper;
namespace capro = card::pro;
namespace lnpro = linear::pro;
namespace impro = image::pro;
namespace ibpro = icon_button::pro;
namespace slpro = select_widget::pro;
namespace fbpro = filled_button::pro;
namespace dmpro = dropdown_menu::pro;
namespace pwpro = plot_widget::pro;
static auto ComConfigComponent(ThemeManager& manager, auto&& callback) {
auto slogen_context = std::make_shared<MutableValue<QString>>();
slogen_context->set_silent("BanG Bream! It's MyGo!!!");
namespace {
auto select_com_context = std::make_shared<MutableValue<QStringList>>();
select_com_context->set_silent(QStringList {"COM1", "COM2", "COM3", "COM4", "COM5"});
constexpr std::array<std::uint8_t, 14> kSlaveRequestCommand{
0x55,
0xAA,
0x09,
0x00,
0x34,
0x00,
0xFB,
0x00,
0x1C,
0x00,
0x00,
0x18,
0x00,
0x7A
};
auto select_baud_context = std::make_shared<MutableValue<QStringList>>();
select_baud_context->set_silent(QStringList {"9600", "115200"});
QVector<PointData> make_flat_points(const QSize& size, double value = 0.0) {
const int width = std::max(size.width(), 1);
const int height = std::max(size.height(), 1);
QVector<PointData> points;
points.reserve(static_cast<int>(width * height));
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
points.append(PointData{
static_cast<double>(x),
static_cast<double>(y),
value });
}
}
return points;
}
std::once_flag& codec_registration_flag() {
static std::once_flag flag;
return flag;
}
class SensorStreamController: public QObject {
public:
SensorStreamController(std::shared_ptr<MutableValue<QVector<PointData>>> heatmap_data,
std::shared_ptr<MutableValue<QSize>> matrix_context,
QObject* parent = nullptr): QObject(parent), heatmap_data_(std::move(heatmap_data)), matrix_context_(std::move(matrix_context)) {
std::call_once(codec_registration_flag(), [] {
ffmsep::tactile::register_tactile_codec();
});
}
~SensorStreamController() override {
reset_core();
}
bool start(const QString& requested_port, std::uint32_t baudrate) {
if (is_connected()) {
return true;
}
const auto ports = ffmsep::CPStreamCore::list_available_ports();
std::string port_utf8;
if (!requested_port.isEmpty()) {
port_utf8 = requested_port.toStdString();
const auto it = std::find_if(
ports.begin(), ports.end(), [&](const serial::PortInfo& info) { return info.port == port_utf8; });
if (it == ports.end()) {
if (ports.empty()) {
#if DEBUG
std::cerr << "SensorStreamController: requested port '" << port_utf8 << "' not available and no other ports detected.\n";
#endif
last_error_ = QString::fromUtf8("未检测到串口");
return false;
}
#if DEBUG
std::cerr << "SensorStreamController: requested port '" << port_utf8 << "' not available, falling back to first detected port.\n";
#endif
port_utf8 = ports.front().port;
}
}
else if (!ports.empty()) {
port_utf8 = ports.front().port;
}
else {
#if DEBUG
std::cerr << "SensorStreamController: no serial ports available\n";
#endif
last_error_ = QString::fromUtf8("未检测到串口");
return false;
}
const std::uint32_t baud = baudrate == 0U ? 115200U : baudrate;
ffmsep::CPStreamConfig cfg;
cfg.port = port_utf8;
cfg.baudrate = baud;
cfg.codec_id = ffmsep::CPCodecID::Tactile;
cfg.read_chunk_size = 256;
cfg.packet_queue_capacity = 128;
cfg.frame_queue_capacity = 32;
cfg.slave_request_command.assign(kSlaveRequestCommand.begin(), kSlaveRequestCommand.end());
cfg.slave_request_interval = 3ms;
reset_core();
core_ = std::make_unique<ffmsep::CPStreamCore>();
if (!core_->open(cfg)) {
last_error_ = QString::fromStdString(core_->last_error());
std::cerr << "SensorStreamController: open failed - " << core_->last_error() << "\n";
reset_core();
return false;
}
core_->set_frame_callback([this](std::shared_ptr<ffmsep::DecodedFrame> frame) {
handle_frame(frame);
});
if (!core_->start()) {
last_error_ = QString::fromStdString(core_->last_error());
std::cerr << "SensorStreamController: start failed - " << core_->last_error() << "\n";
reset_core();
return false;
}
active_port_ = QString::fromStdString(cfg.port);
last_error_.clear();
connected_ = true;
return true;
}
void stop() {
if (!core_) {
active_port_.clear();
if (heatmap_data_ && matrix_context_) {
heatmap_data_->set(make_flat_points(matrix_context_->get()));
}
connected_ = false;
return;
}
core_->set_frame_callback({});
if (core_->is_running()) {
core_->stop();
}
core_->clear_frames();
connected_ = false;
active_port_.clear();
if (heatmap_data_ && matrix_context_) {
heatmap_data_->set(make_flat_points(matrix_context_->get()));
}
}
[[nodiscard]] bool is_running() const noexcept {
return core_ && core_->is_running();
}
[[nodiscard]] bool is_connected() const noexcept {
return connected_;
}
[[nodiscard]] QString active_port() const {
return active_port_;
}
[[nodiscard]] QString last_error() const {
return last_error_;
}
std::future<ffmsep::persist::WriteResult> export_frames(const QString& path,
bool clear_after_export) {
if (path.isEmpty()) {
return make_failed_future(path, "export path is empty");
}
if (!core_) {
return make_failed_future(path, "stream is not active");
}
if (core_->recorded_frame_count() == 0U) {
return make_failed_future(path, "no tactile frames recorded");
}
const auto normalized = QDir::toNativeSeparators(path);
return core_->export_recorded_frames(normalized.toStdString(), clear_after_export);
}
private:
void reset_core() {
connected_ = false;
if (!core_) {
return;
}
core_->set_frame_callback({});
if (core_->is_running()) {
core_->stop();
}
if (core_->is_open()) {
core_->close();
}
core_.reset();
}
static QSize to_qsize(const ffmsep::tactile::MatrixSize& m) {
return QSize{
static_cast<int>(m.long_edge),
static_cast<int>(m.short_edge)
};
}
void handle_frame(std::shared_ptr<ffmsep::DecodedFrame> frame) {
if (!frame->tactile || frame->tactile_pressures.empty()) {
return;
}
auto pressures = frame->tactile_pressures;
auto frame_bytes = frame->frame.data;
std::vector<std::uint8_t> raw_payload;
if (frame->tactile) {
raw_payload = frame->tactile->payload;
}
QMetaObject::invokeMethod(
this,
[this,
pressures = std::move(pressures),
frame_bytes = std::move(frame_bytes),
raw_payload = std::move(raw_payload)]() mutable {
const auto format_raw = [](const std::vector<std::uint8_t>& data) -> std::string {
if (data.empty()) {
return "[]";
}
std::ostringstream oss;
oss << '[';
oss << std::uppercase << std::setfill('0');
for (std::size_t idx = 0; idx < data.size(); ++idx) {
if (idx != 0U) {
oss << ' ';
}
oss << std::setw(2) << std::hex << static_cast<unsigned int>(data[idx]);
}
oss << ']';
return oss.str();
};
std::cout << "[Sensor] frame=" << format_raw(frame_bytes);
std::cout << " payload=" << format_raw(raw_payload);
std::cout << " received " << pressures.size() << " pressure values";
const std::size_t preview = std::min<std::size_t>(pressures.size(), 12);
if (preview > 0) {
std::cout << " values=[";
for (std::size_t idx = 0; idx < preview; ++idx) {
if (idx != 0U) {
std::cout << ", ";
}
std::cout << pressures[idx];
}
if (preview < pressures.size()) {
std::cout << ", ...";
}
std::cout << "]";
}
std::cout << std::endl;
auto matrix = matrix_context_->get();
const auto cells_exp = static_cast<std::size_t>(std::max(1, matrix.width()) *
std::max(1, matrix.height()));
if (cells_exp == 0) return;
if (pressures.size() > cells_exp) {
pressures.resize(cells_exp);
} else if (pressures.size() < cells_exp) {
pressures.resize(cells_exp, 0);
}
QVector<PointData> points;
points.reserve(matrix.width() * matrix.height());
for (int y = 0; y < matrix.height(); ++y) {
for (int x = 0; x < matrix.width(); ++x) {
const int idx = y * matrix.width() + x;
if (idx >= static_cast<int>(pressures.size())) {
break;
}
const auto value = static_cast<double>(pressures[static_cast<std::size_t>(idx)]);
points.append(PointData{
static_cast<double>(x),
static_cast<double>(y),
value });
}
}
matrix_context_->set(matrix);
heatmap_data_->set(std::move(points));
},
Qt::QueuedConnection);
}
[[nodiscard]] QSize normalize_matrix(QSize candidate, std::size_t value_count) const {
if (value_count == 0U) {
return QSize{};
}
const auto adapt_from = [value_count](const QSize& hint) -> std::optional<QSize> {
if (hint.width() <= 0 && hint.height() <= 0) {
return std::nullopt;
}
if (hint.width() > 0 && hint.height() > 0) {
const auto cells = static_cast<std::size_t>(hint.width()) * static_cast<std::size_t>(hint.height());
if (cells == value_count) {
return hint;
}
}
if (hint.width() > 0) {
const auto width = static_cast<std::size_t>(hint.width());
if (width != 0U && (value_count % width) == 0U) {
const auto height = static_cast<int>(value_count / width);
return QSize{ hint.width(), height };
}
}
if (hint.height() > 0) {
const auto height = static_cast<std::size_t>(hint.height());
if (height != 0U && (value_count % height) == 0U) {
const auto width = static_cast<int>(value_count / height);
return QSize{ width, hint.height() };
}
}
return std::nullopt;
};
if (auto adjusted = adapt_from(candidate)) {
return *adjusted;
}
if (auto adjusted = adapt_from(matrix_context_->get())) {
return *adjusted;
}
const auto root = static_cast<int>(std::sqrt(static_cast<double>(value_count)));
for (int width = root; width >= 1; --width) {
const auto divisor = static_cast<std::size_t>(width);
if (divisor == 0U) {
continue;
}
if ((value_count % divisor) == 0U) {
const auto height = static_cast<int>(value_count / divisor);
return QSize{ width, height };
}
}
return QSize{ static_cast<int>(value_count), 1 };
}
std::shared_ptr<MutableValue<QVector<PointData>>> heatmap_data_;
std::shared_ptr<MutableValue<QSize>> matrix_context_;
std::unique_ptr<ffmsep::CPStreamCore> core_;
QString active_port_;
QString last_error_;
bool connected_ = false;
static std::future<ffmsep::persist::WriteResult> make_failed_future(
const QString& path,
std::string message) {
std::promise<ffmsep::persist::WriteResult> promise;
auto future = promise.get_future();
ffmsep::persist::WriteResult result{
false,
std::move(message),
path.toStdString()
};
promise.set_value(std::move(result));
return future;
}
};
struct SensorUiState {
std::shared_ptr<MutableValue<QString>> link_icon =
std::make_shared<MutableValue<QString>>(QString::fromLatin1(material::icon::kAddLink));
std::shared_ptr<MutableValue<QVector<PointData>>> heatmap_data =
std::make_shared<MutableValue<QVector<PointData>>>();
std::shared_ptr<MutableValue<QSize>> heatmap_matrix =
std::make_shared<MutableValue<QSize>>();
std::shared_ptr<MutableValue<QPair<int, int>>> heatmap_range =
std::make_shared<MutableValue<QPair<int, int>>>(QPair<int, int>{0, 300});
std::shared_ptr<MutableValue<QStringList>> port_items =
std::make_shared<MutableValue<QStringList>>();
std::shared_ptr<MutableValue<QStringList>> profile_items =
std::make_shared<MutableValue<QStringList>>();
QString selected_port;
QString selected_profile;
std::uint32_t selected_baud = 115200;
std::unique_ptr<SensorStreamController> controller;
SensorUiState() {
const QSize size{ 3, 4 };
heatmap_matrix->set_silent(size);
heatmap_data->set_silent(make_flat_points(size));
// 初始化串口列表
QStringList ports_list;
const auto ports = ffmsep::CPStreamCore::list_available_ports();
ports_list.reserve(static_cast<qsizetype>(ports.size()));
for (const auto& info: ports) {
ports_list.emplace_back(QString::fromStdString(info.port));
}
port_items->set_silent(ports_list);
if (selected_port.isEmpty() && !ports_list.isEmpty()) {
selected_port = ports_list.front();
}
GlobalHelper::instance().reload_profiles();
QStringList profile_list;
const auto& profiles = GlobalHelper::instance().get_all_profile();
profile_list.reserve(static_cast<qsizetype>(profiles.size()));
for (const auto& p : profiles) {
profile_list << p.name;
}
profile_items->set_silent(profile_list);
if (selected_profile.isEmpty() && !profile_list.isEmpty()) {
selected_profile = profile_list.front();
if (!profiles.empty()) {
const auto size = QSize { std::max(1, profiles.front().matrix_width),
std::max(1, profiles.front().matrix_height) };
selected_baud = profiles.front().baud_rate == 0 ? 115200U : static_cast<std::uint32_t>(profiles.front().baud_rate);
heatmap_matrix->set_silent(size);
heatmap_data->set_silent(make_flat_points(size));
const int range_min = profiles.front().range_left;
const int range_max = (profiles.front().range_right == profiles.front().range_left)
? profiles.front().range_left + 1
: profiles.front().range_right;
heatmap_range->set_silent(QPair<int, int>{range_min, range_max});
}
}
controller = std::make_unique<SensorStreamController>(heatmap_data, heatmap_matrix);
}
};
SensorUiState& sensor_state() {
static SensorUiState state;
return state;
}
} // namespace
void RefreshProfilesForView() {
auto& sensor = sensor_state();
GlobalHelper::instance().reload_profiles();
QStringList profile_list;
const auto& profiles = GlobalHelper::instance().get_all_profile();
profile_list.reserve(static_cast<qsizetype>(profiles.size()));
for (const auto& p : profiles) {
profile_list << p.name;
}
if (!sensor.selected_profile.isEmpty()) {
const bool exists = profile_list.contains(sensor.selected_profile);
if (!exists) {
sensor.selected_profile = profile_list.isEmpty() ? QString{} : profile_list.front();
}
}
else if (!profile_list.isEmpty()) {
sensor.selected_profile = profile_list.front();
}
if (!sensor.selected_profile.isEmpty()) {
const auto it = std::find_if(profiles.begin(), profiles.end(),
[&](const ConfigProfile& p) { return p.name == sensor.selected_profile; });
if (it != profiles.end()) {
sensor.selected_baud = it->baud_rate == 0 ? 115200U : static_cast<std::uint32_t>(it->baud_rate);
const auto size = QSize { std::max(1, it->matrix_width), std::max(1, it->matrix_height) };
sensor.heatmap_matrix->set(size);
sensor.heatmap_data->set(make_flat_points(size));
const int range_min = it->range_left;
const int range_max = (it->range_right == it->range_left) ? it->range_left + 1 : it->range_right;
sensor.heatmap_range->set(QPair<int, int>{range_min, range_max});
}
}
sensor.profile_items->set(std::move(profile_list));
}
static auto ComConfigComponent(ThemeManager& manager) {
auto& sensor = sensor_state();
auto link_icon_context = sensor.link_icon;
if (sensor.selected_port.isEmpty() && !sensor.port_items->get().isEmpty()) {
sensor.selected_port = sensor.port_items->get().front();
}
if (sensor.selected_baud == 0U) {
sensor.selected_baud = 115200U;
}
const auto row = new Row{
// lnpro::Item<FilledTextField> {
@@ -55,151 +567,227 @@ static auto ComConfigComponent(ThemeManager& manager, auto&& callback) {
// slogen_context,
// },
// },
lnpro::Item<MatSelect> {
slpro::ThemeManager {manager},
slpro::LeadingIcon {material::icon::kArrowDropDown, material::regular::font},
slpro::IndexChanged {[&](auto& self){ qDebug() << self.currentIndex();}},
slpro::LeadingText {"COM"},
MutableForward {
slpro::SelectItems {},
select_com_context,
lnpro::Item<FilledDropdownMenu>{
dmpro::ThemeManager{ manager },
dmpro::LeadingIcon{ material::icon::kArrowDropDown, material::regular::font },
dmpro::TextChanged{ [sensor_ptr = &sensor](QString text) {
// const auto text = self.currentText();
if (!text.isEmpty()) {
sensor_ptr->selected_port = text;
}
} },
dmpro::LabelText{ "COM" },
MutableForward{
dmpro::Items{},
sensor.port_items,
},
lnpro::Item<MatSelect> {
slpro::ThemeManager {manager },
slpro::LeadingIcon { material::icon::kArrowDropDown, material::regular::font},
slpro::IndexChanged {[&](auto& self){ qDebug() << self.currentIndex();}},
slpro::LeadingText {"Baud"},
MutableForward {
slpro::SelectItems {},
select_baud_context,
},
lnpro::Item<FilledDropdownMenu>{
dmpro::ThemeManager{ manager },
dmpro::LeadingIcon{ material::icon::kArrowDropDown, material::regular::font },
dmpro::TextChanged{ [sensor_ptr = &sensor](QString text) {
if (!text.isEmpty()) {
sensor_ptr->selected_profile = text;
const auto& profiles = GlobalHelper::instance().get_all_profile();
const auto it = std::find_if(profiles.begin(), profiles.end(),
[&text](const ConfigProfile& p) { return p.name == text; });
if (it != profiles.end()) {
const auto baud = it->baud_rate == 0 ? 115200U : static_cast<std::uint32_t>(it->baud_rate);
sensor_ptr->selected_baud = baud;
const auto size = QSize { std::max(1, it->matrix_width), std::max(1, it->matrix_height) };
sensor_ptr->heatmap_matrix->set(size);
sensor_ptr->heatmap_data->set(make_flat_points(size));
const int range_min = it->range_left;
const int range_max = (it->range_right == it->range_left) ? it->range_left + 1 : it->range_right;
sensor_ptr->heatmap_range->set(QPair<int, int>{range_min, range_max});
}
}
} },
dmpro::LabelText{ "Profile" },
MutableForward{
dmpro::Items{},
sensor.profile_items,
},
},
lnpro::SpacingItem{ 20 },
lnpro::Item<IconButton>{
ibpro::ThemeManager{ manager },
ibpro::FixedSize{ 40, 40 },
ibpro::Color{ IconButton::Color::TONAL },
ibpro::Font { material::kRoundSmallFont },
ibpro::FontIcon { material::icon::kAddLink },
ibpro::Clickable {[slogen_context] {
constexpr auto random_slogen = [] {
constexpr auto slogens = std::array {
"为什么要演奏《春日影》!",
"我从来不觉得玩乐队开心过。",
"我好想…成为人啊!",
"那你愿意……跟我组一辈子的乐队吗?",
"过去软弱的我…已经死了。",
};
static std::random_device rd;
static std::mt19937 gen(rd());
std::uniform_int_distribution<> dist(0, slogens.size() - 1);
return QString::fromUtf8(slogens[dist(gen)]);
};
*slogen_context = random_slogen();
}},
ibpro::Font{ material::kRegularExtraSmallFont },
MutableForward{
icon_button::pro::FontIcon{},
link_icon_context,
},
ibpro::Clickable{ [sensor_ptr = &sensor, link_icon_context] {
auto& sensor = *sensor_ptr;
if (!sensor.controller) {
return;
}
if (sensor.controller->is_connected()) {
sensor.controller->stop();
link_icon_context->set(QString::fromLatin1(material::icon::kAddLink));
}
else {
const auto port = sensor.selected_port;
const auto baud = sensor.selected_baud == 0U ? 115200U : sensor.selected_baud;
if (sensor.controller->start(port, baud)) {
sensor.selected_port = sensor.controller->active_port();
link_icon_context->set(QString::fromLatin1(material::icon::kLinkOff));
}
else {
std::cerr << "Failed to start sensor stream: "
<< sensor.controller->last_error().toStdString()
<< "\n";
}
}
} } },
lnpro::Item<IconButton>{
ibpro::ThemeManager{ manager },
ibpro::FixedSize{ 40, 40 },
ibpro::Color{ IconButton::Color::TONAL },
ibpro::Font { material::kRoundSmallFont },
ibpro::Font{ material::kRegularExtraSmallFont },
ibpro::FontIcon{ material::icon::kRefresh },
ibpro::Clickable {[select_baud_context] {
static constexpr auto options_group1 = std::array {
"第一组选项1", "第一组选项2", "第一组选项3"
};
static constexpr auto options_group2 = std::array {
"第二组选项A", "第二组选项B", "第二组选项C", "第二组选项D"
};
static std::random_device rd;
static std::mt19937 gen(rd());
std::uniform_int_distribution<> dist(0, 1);
QStringList new_options;
if (dist(gen) == 0) {
for (const auto& option : options_group1) {
new_options << QString::fromUtf8(option);
ibpro::Clickable{ [&sensor] {
QStringList ports_list;
const auto ports = ffmsep::CPStreamCore::list_available_ports();
ports_list.reserve(static_cast<qsizetype>(ports.size()));
for (const auto& info: ports) {
ports_list.emplace_back(QString::fromStdString(info.port));
}
} else {
for (const auto& option : options_group2) {
new_options << QString::fromUtf8(option);
if (!sensor.selected_port.isEmpty()) {
const bool exists = ports_list.contains(sensor.selected_port);
if (!exists) {
sensor.selected_port = ports_list.isEmpty() ? QString{} : ports_list.front();
}
}
*select_baud_context = new_options;
else if (!ports_list.isEmpty()) {
sensor.selected_port = ports_list.front();
}
sensor.port_items->set(std::move(ports_list));
RefreshProfilesForView();
} },
},
lnpro::Item<FilledButton>{
fbpro::ThemeManager{ manager },
fbpro::FixedSize{ 40, 40 },
fbpro::Radius{ 8.0 },
// fbpro::Color { IconButton::Color::TONAL },
fbpro::Font{ material::kRegularExtraSmallFont },
fbpro::Text{ "drive_file_move" },
fbpro::Clickable{ [&sensor] {
auto* controller = sensor.controller.get();
if (!controller) {
QMessageBox::warning(nullptr,
QStringLiteral("导出失败"),
QStringLiteral("当前串流尚未初始化。"));
return;
}
const auto documents = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
const auto timestamp = QDateTime::currentDateTime().toString(QStringLiteral("yyyyMMdd_HHmmss"));
QString suggested_name = QStringLiteral("touchsensor_%1.json").arg(timestamp);
QString initial_path = documents.isEmpty() ? suggested_name : QDir(documents).filePath(suggested_name);
const QString chosen_path = QFileDialog::getSaveFileName(
nullptr,
QStringLiteral("导出触觉帧"),
initial_path,
QStringLiteral("JSON 文件 (*.json)"));
if (chosen_path.isEmpty()) {
return;
}
auto future = controller->export_frames(chosen_path, false);
std::thread([future = std::move(future)]() mutable {
ffmsep::persist::WriteResult result{};
try {
result = future.get();
}
catch (const std::exception& ex) {
result.ok = false;
result.error = ex.what();
}
catch (...) {
result.ok = false;
result.error = "unknown export failure";
}
if (auto* app = QCoreApplication::instance()) {
QMetaObject::invokeMethod(app, [res = std::move(result)]() {
if (res.ok) {
QMessageBox::information(
nullptr,
QStringLiteral("导出成功"),
QStringLiteral("触觉帧已导出至:\n%1")
.arg(QString::fromStdString(res.path)));
} else {
const auto error = QString::fromStdString(
res.error.empty() ? std::string{"unknown error"} : res.error);
const auto target = QString::fromStdString(res.path);
const auto message = target.isEmpty()
? QStringLiteral("原因:%1").arg(error)
: QStringLiteral("原因:%1\n目标:%2").arg(error, target);
QMessageBox::warning(nullptr,
QStringLiteral("导出失败"),
message);
} }, Qt::QueuedConnection);
}
})
.detach();
} } }
};
return new Widget{
widget::pro::Layout{ row },
};
}
static auto DisplayComponent(ThemeManager& manager, int index = 0) noexcept {
auto heatmap_context = std::make_shared<MutableValue<QVector<PointData>>>();
heatmap_context->set_silent(QVector<PointData>{
PointData{0, 0, 1}, PointData{1, 0, 2}, PointData{2, 0, 3},
PointData{0, 1, 3}, PointData{1, 1, 4}, PointData{2, 1, 5},
PointData{0, 2, 6}, PointData{1, 2, 7}, PointData{2, 2, 8},
PointData{0, 3, 9}, PointData{1, 3, 10}, PointData{2, 3, 11},
});
static auto DisplayComponent(ThemeManager& manager, int /*index*/ = 0) noexcept {
auto& sensor = sensor_state();
const auto row = new Row{
lnpro::Item<HeatMapPlot>{
plot_widget::pro::SizePolicy{
QSizePolicy::Expanding,
},
plot_widget::pro::ThemeManager{ manager },
MutableForward{
plot_widget::pro::PlotData{},
heatmap_context,
sensor.heatmap_data,
},
pwpro::MatrixSize{
QSize{3, 4}
sensor.heatmap_matrix->get() },
MutableTransform{
[](auto& widget, const QSize& size) {
pwpro::MatrixSize{ size }.apply(widget);
},
sensor.heatmap_matrix },
MutableTransform{
[](auto& widget, const QPair<int, int>& range) {
const double min = static_cast<double>(range.first);
const double max = static_cast<double>(range.second);
widget.set_color_gradient_range(min, max);
},
sensor.heatmap_range },
},
};
return new Widget{
widget::pro::Layout{ row },
};
}
auto ViewComponent(ViewComponentState& state) noexcept -> raw_pointer<QWidget> {
const auto texts = std::array {
std::make_shared<MutableValue<QString>>("0.500"),
std::make_shared<MutableValue<QString>>("0.500"),
std::make_shared<MutableValue<QString>>("0.500"),
};
const auto progresses = std::array {
std::make_shared<MutableValue<double>>(0.5),
std::make_shared<MutableValue<double>>(0.5),
std::make_shared<MutableValue<double>>(0.5),
};
return new FilledCard{
capro::ThemeManager{ state.manager },
capro::SizePolicy{ QSizePolicy::Expanding },
capro::Layout<Col>{
lnpro::Alignment{ Qt::AlignTop },
lnpro::Margin {10},
lnpro::Spacing {10},
// lnpro::Margin {10},
// lnpro::Spacing {10},
lnpro::Item{
ComConfigComponent(state.manager,
[texts, progresses] {
constexpr auto random_unit = []() {
static std::random_device rd;
static std::mt19937 gen(rd());
static std::uniform_real_distribution<double> dist(0.0, 1.0);
return dist(gen);
};
for (auto&& [string, number] : std::views::zip(texts, progresses)) {
auto v = random_unit();
*number = v;
*string = QString::number(v, 'f', 3);
}
}),
ComConfigComponent(state.manager),
},
lnpro::Item<Row>{
lnpro::Item{
DisplayComponent(state.manager),

View File

@@ -1,7 +1,7 @@
#pragma once
#include "modern-qt/utility/wrapper/common.hh"
#include "modern-qt/utility/wrapper/property.hh"
#include "creeper-qt/utility/wrapper/common.hh"
#include "creeper-qt/utility/wrapper/property.hh"
#include <qapplication.h>
#include <qcoreapplication.h>

View File

@@ -1,7 +1,7 @@
#pragma once
#include "modern-qt/utility/wrapper/common.hh"
#include "modern-qt/utility/wrapper/layout.hh"
#include "modern-qt/utility/wrapper/pimpl.hh"
#include "creeper-qt/utility/wrapper/common.hh"
#include "creeper-qt/utility/wrapper/layout.hh"
#include "creeper-qt/utility/wrapper/pimpl.hh"
#include <qlayout.h>
namespace creeper::flow::internal {

View File

@@ -1,7 +1,7 @@
#pragma once
#include "modern-qt/utility/wrapper/common.hh"
#include "modern-qt/utility/wrapper/property.hh"
#include "creeper-qt/utility/wrapper/common.hh"
#include "creeper-qt/utility/wrapper/property.hh"
#include <qgridlayout.h>

View File

@@ -1,7 +1,7 @@
#pragma once
#include "modern-qt/utility/trait/widget.hh"
#include "modern-qt/utility/wrapper/common.hh"
#include "modern-qt/utility/wrapper/property.hh"
#include "creeper-qt/utility/trait/widget.hh"
#include "creeper-qt/utility/wrapper/common.hh"
#include "creeper-qt/utility/wrapper/property.hh"
namespace creeper::group::internal {

View File

@@ -1,11 +1,12 @@
#pragma once
#include "modern-qt/utility/trait/widget.hh"
#include "modern-qt/utility/wrapper/common.hh"
#include "modern-qt/utility/wrapper/layout.hh"
#include "modern-qt/utility/wrapper/property.hh"
#include "creeper-qt/utility/trait/widget.hh"
#include "creeper-qt/utility/wrapper/common.hh"
#include "creeper-qt/utility/wrapper/layout.hh"
#include "creeper-qt/utility/wrapper/property.hh"
#include <qboxlayout.h>
#include <qstackedlayout.h>
namespace creeper::linear::pro {
@@ -98,10 +99,18 @@ using Col = BoxLayout<QVBoxLayout>;
namespace row = linear;
namespace col = linear;
using HBoxLayout = Row;
using VBoxLayout = Col;
namespace h_box_layout = linear;
namespace v_box_layout = linear;
namespace internal {
inline auto use_the_namespace_alias_to_eliminate_warnings() {
std::ignore = row::pro::Token {};
std::ignore = col::pro::Token {};
std::ignore = h_box_layout::pro::Token {};
std::ignore = v_box_layout::pro::Token {};
}
}

View File

@@ -3,10 +3,10 @@
#include <qpainter.h>
#include <qpainterpath.h>
#include "modern-qt/utility/animation/animatable.hh"
#include "modern-qt/utility/animation/state/pid.hh"
#include "modern-qt/utility/animation/transition.hh"
#include "modern-qt/utility/wrapper/widget.hh"
#include "creeper-qt/utility/animation/animatable.hh"
#include "creeper-qt/utility/animation/state/pid.hh"
#include "creeper-qt/utility/animation/transition.hh"
#include "creeper-qt/utility/wrapper/widget.hh"
namespace creeper::mixer::internal {

View File

@@ -1,6 +1,6 @@
#pragma once
#include <modern-qt/layout/group.hh>
#include <modern-qt/utility/wrapper/layout.hh>
#include <creeper-qt/layout/group.hh>
#include <creeper-qt/utility/wrapper/layout.hh>
#include <ranges>
namespace creeper::mutual_exclusion_group::internal {

View File

@@ -1,9 +1,9 @@
#pragma once
#include "modern-qt/utility/theme/theme.hh"
#include "modern-qt/utility/trait/widget.hh"
#include "modern-qt/utility/wrapper/common.hh"
#include "modern-qt/utility/wrapper/property.hh"
#include "modern-qt/widget/widget.hh"
#include "creeper-qt/utility/theme/theme.hh"
#include "creeper-qt/utility/trait/widget.hh"
#include "creeper-qt/utility/wrapper/common.hh"
#include "creeper-qt/utility/wrapper/property.hh"
#include "creeper-qt/widget/widget.hh"
#include <qscrollarea.h>
#include <qscrollbar.h>
@@ -13,8 +13,8 @@ namespace creeper::scroll::internal {
class ScrollArea : public QScrollArea {
public:
explicit ScrollArea() noexcept {
viewport()->setStyleSheet("background:transparent;");
setStyleSheet("QScrollArea{background:transparent;}");
viewport()->setStyleSheet("background:transparent;border:none;");
setStyleSheet("QScrollArea{background:transparent;border:none;}");
setWidgetResizable(true);
}

View File

@@ -0,0 +1,53 @@
#pragma once
#include "creeper-qt/utility/trait/widget.hh"
#include "creeper-qt/utility/wrapper/common.hh"
#include "creeper-qt/utility/wrapper/layout.hh"
#include "creeper-qt/utility/wrapper/property.hh"
#include <concepts>
#include <qstackedlayout.h>
namespace creeper::stacked::internal {
class Stacked : public QStackedLayout { };
}
namespace creeper::stacked::pro {
using Token = common::Token<internal::Stacked>;
/// @note: currentChanged(int index)
template <typename F>
using IndexChanged = common::pro::SignalInjection<F, Token, &internal::Stacked::currentChanged>;
using CurrentIndex =
SetterProp<Token, int, [](auto& self, auto index) { self.setCurrentIndex(index); }>;
template <typename T>
concept trait = std::derived_from<T, Token> || layout::pro::trait<T>;
template <item_trait T>
struct Item : Token {
T* item_pointer = nullptr;
explicit Item(T* pointer) noexcept
: item_pointer { pointer } { }
explicit Item(auto&&... args) noexcept
requires std::constructible_from<T, decltype(args)...>
: item_pointer { new T { std::forward<decltype(args)>(args)... } } { }
void apply(stacked_trait auto& layout) const {
if constexpr (widget_trait<T>) {
layout.addWidget(item_pointer);
}
}
};
CREEPER_DEFINE_CHECKER(trait);
using namespace layout::pro;
}
namespace creeper {
using Stacked = Declarative<stacked::internal::Stacked, stacked::pro::checker>;
using NavHost = Stacked;
}

View File

@@ -1,5 +1,4 @@
#include "animatable.hh"
#include <qdebug.h>
using namespace creeper;
#include <qtimer.h>

View File

@@ -1,6 +1,6 @@
#pragma once
#include "modern-qt/utility/wrapper/pimpl.hh"
#include "creeper-qt/utility/wrapper/pimpl.hh"
#include <qwidget.h>
namespace creeper {

View File

@@ -1,6 +1,6 @@
#pragma once
#include "modern-qt/utility/animation/math.hh"
#include "modern-qt/utility/animation/state/accessor.hh"
#include "creeper-qt/utility/animation/math.hh"
#include "creeper-qt/utility/animation/state/accessor.hh"
#include <chrono>

View File

@@ -1,6 +1,6 @@
#pragma once
#include "modern-qt/utility/animation/math.hh"
#include "modern-qt/utility/animation/state/accessor.hh"
#include "creeper-qt/utility/animation/math.hh"
#include "creeper-qt/utility/animation/state/accessor.hh"
#include <chrono>

View File

@@ -1,6 +1,6 @@
#pragma once
#include "modern-qt/utility/animation/math.hh"
#include "modern-qt/utility/animation/state/accessor.hh"
#include "creeper-qt/utility/animation/math.hh"
#include "creeper-qt/utility/animation/state/accessor.hh"
#include <chrono>

View File

@@ -1,7 +1,7 @@
#pragma once
#include "modern-qt/utility/animation/state/accessor.hh"
#include "modern-qt/utility/animation/transition.hh"
#include "creeper-qt/utility/animation/state/accessor.hh"
#include "creeper-qt/utility/animation/transition.hh"
#include <QColor>
#include <QPainter>

View File

@@ -1,5 +1,4 @@
#pragma once
#include <qdebug.h>
#include <qpixmap.h>
namespace creeper {

View File

@@ -27,15 +27,12 @@ namespace material {
private:
static QString get_font_family(int fontId, const QString& fallback) {
if (fontId == -1) {
qWarning() << "Failed to load font:" << fallback;
return fallback;
}
QStringList families = QFontDatabase::applicationFontFamilies(fontId);
if (families.isEmpty()) {
qWarning() << "No families found for font:" << fallback;
return fallback;
}
qDebug() << "families found for font:" << families;
return families.first();
}
};
@@ -99,6 +96,13 @@ namespace material {
inline const auto kOutlinedLargeFont = outlined::font_3;
inline const auto kOutlinedExtraLargeFont = outlined::font_4;
constexpr auto kRegularFontName = regular::font;
inline const auto kRegularExtraSmallFont = regular::font_0;
inline const auto kRegularSmallFont = regular::font_1;
inline const auto kRegularMediumFont = regular::font_2;
inline const auto kRegularLargeFont = regular::font_3;
inline const auto kRegularExtraLargeFont = regular::font_4;
namespace icon {
// Function
@@ -114,6 +118,7 @@ namespace material {
constexpr auto kNotifications = "notifications";
constexpr auto kDashboard = "dashboard";
constexpr auto kExtension = "extension";
constexpr auto kPets = "pets";
// Shape
constexpr auto kFavorite = "favorite";
@@ -143,6 +148,7 @@ namespace material {
constexpr auto kLogout = "logout";
constexpr auto kRoutine = "routine";
constexpr auto kDarkMode = "dark_mode";
constexpr auto kFileExport = "file_export";
// File
constexpr auto kFolder = "folder";
@@ -164,6 +170,9 @@ namespace material {
// sensor icon
constexpr auto kTouchSensor = "touch_app";
// setting page
constexpr auto kBorderColor = "border_color";
}
}
}

View File

@@ -1,5 +1,5 @@
#pragma once
#include "modern-qt/utility/wrapper/property.hh"
#include "creeper-qt/utility/wrapper/property.hh"
#include <qpainter.h>
@@ -14,6 +14,7 @@ using align = Qt::Alignment;
using string = QString;
using font = QFont;
using text_option = QTextOption;
using icon = QIcon;
}
namespace creeper::painter {

View File

@@ -1,14 +1,12 @@
#pragma once
#include "modern-qt/utility/painter/common.hh"
#include "creeper-qt/utility/painter/common.hh"
namespace creeper::painter {
// 核心容器结构体,现在继承自 Impl使其满足 drawable_trait (假设 Impl 继承了所需的属性)
template <class Impl, drawable_trait... Ts>
struct Container : public Impl {
std::tuple<std::decay_t<Ts>...> drawable;
// 唯一构造函数:接受 Impl 实例和可变参数包
constexpr explicit Container(const Impl& impl, Ts&&... drawable)
: Impl { impl }
, drawable { std::make_tuple(std::forward<Ts>(drawable)...) } { }
@@ -47,7 +45,7 @@ struct MakeLayoutFunction {
};
// ----------------------------------------------------------------------
// SurfaceImpl (仅平移)
// SurfaceImpl
// ----------------------------------------------------------------------
struct SurfaceImpl : public MakeLayoutFunction, ContainerProps {
@@ -162,13 +160,12 @@ struct BoxImpl : public MakeLayoutFunction, ContainerProps {
// ----------------------------------------------------------------------
struct RowImpl : public MakeLayoutFunction, ContainerProps {
// 主轴对齐 (Horizontal)
const qt::align main_align;
constexpr explicit RowImpl(
const qt::size& size,
const qt::align& main_align = Qt::AlignLeft, // 主轴对齐AlignLeft/AlignRight/AlignHCenter
const qt::align& cross_align = Qt::AlignVCenter, // 非主轴对齐AlignTop/AlignBottom/AlignVCenter
const qt::align& main_align = Qt::AlignLeft,
const qt::align& cross_align = Qt::AlignVCenter,
const qt::point& origin = {})
: ContainerProps {
.size = size,
@@ -207,7 +204,7 @@ struct RowImpl : public MakeLayoutFunction, ContainerProps {
}
auto make(drawable_trait auto& drawable) {
const auto container_cross_align = align; // 非主轴对齐 (垂直)
const auto container_cross_align = align;
const auto container_size = size;
const auto container_origin = origin;
@@ -235,17 +232,16 @@ struct RowImpl : public MakeLayoutFunction, ContainerProps {
// ----------------------------------------------------------------------
struct ColImpl : public MakeLayoutFunction, ContainerProps {
// 主轴对齐 (Vertical)
const qt::align main_align;
constexpr explicit ColImpl(
const qt::size& size,
const qt::align& main_align = Qt::AlignTop, // 主轴对齐AlignTop/AlignBottom/AlignVCenter
const qt::align& cross_align = Qt::AlignHCenter, // 非主轴对齐AlignLeft/AlignRight/AlignHCenter
const qt::align& main_align = Qt::AlignTop,
const qt::align& cross_align = Qt::AlignHCenter,
const qt::point& origin = {})
: ContainerProps {
.size = size,
.align = cross_align, // ContainerProps::align 存储非主轴对齐
.align = cross_align,
.origin = origin,
}
, main_align(main_align) // 存储主轴对齐

View File

@@ -1,4 +1,4 @@
#include "modern-qt/utility/painter/helper.hh"
#include "creeper-qt/utility/painter/helper.hh"
#include <qdebug.h>
namespace creeper::util {

View File

@@ -1,5 +1,6 @@
#pragma once
#include "modern-qt/utility/painter/common.hh"
#include "creeper-qt/utility/painter/common.hh"
#include <qicon.h>
#include <qpainterpath.h>
namespace creeper::painter::internal {
@@ -160,11 +161,52 @@ struct Text : CommonProps {
}
};
struct Icon : CommonProps {
using IconSource = qt::icon;
using FontSource = std::tuple<qt::string, qt::string>;
using MutiSource = std::variant<FontSource, IconSource>;
MutiSource source;
qt::color color = Qt::black;
auto operator()(qt::painter& painter) const noexcept {
if (size.isEmpty()) return;
painter.save();
const auto rect = qt::rect { origin, size };
std::visit(
[&](auto& value) {
using T = std::decay_t<decltype(value)>;
if constexpr (std::is_same_v<T, FontSource>) {
const auto& [font_family, code] = value;
auto font = qt::font { font_family };
font.setPointSizeF(std::min(size.height(), size.width()));
auto option = qt::text_option {};
option.setAlignment(Qt::AlignCenter);
painter.setFont(font);
painter.setPen(color);
painter.setBrush(Qt::NoBrush);
painter.drawText(rect, code, option);
} else if constexpr (std::is_same_v<T, IconSource>) {
const auto& icon_source = value;
icon_source.paint(&painter, rect.toRect());
}
},
source);
painter.restore();
}
};
}
namespace creeper::painter {
/// Export Rounded Rectangle
using RadiusTL = SetterProp<common::pro::Token, double,
[](auto& self, auto radius) { self.radius_tl = radius; }>;
using RadiusTR = SetterProp<common::pro::Token, double,
@@ -189,12 +231,27 @@ using Scale = SetterProp<common::pro::Token, qt::real,
using TextOption = DerivedProp<common::pro::Token, qt::text_option,
[](auto& self, const auto& option) { self.text_option = option; }>;
/// Export Icon
struct Icon : common::pro::Token {
using T = internal::Icon;
T::MutiSource source;
constexpr explicit Icon(const qt::string& font, const qt::string& code) noexcept
: source { T::FontSource { font, code } } { }
constexpr explicit Icon(const qt::icon& icon) noexcept
: source { T::IconSource { icon } } { }
auto apply(auto& self) const noexcept { self.source = source; }
};
namespace Paint {
using EraseRectangle = Declarative<internal::EraseRectangle, CheckerOr<common::pro::checker>>;
using Rectangle = Declarative<internal::Rectangle, CheckerOr<common::pro::checker>>;
using RoundedRectangle =
Declarative<internal::RoundedRectangle, CheckerOr<common::pro::checker>>;
using Text = Declarative<internal::Text, CheckerOr<common::pro::checker>>;
using Icon = Declarative<internal::Icon, CheckerOr<common::pro::checker>>;
}
}

View File

@@ -1,6 +1,6 @@
#pragma once
#include "modern-qt/utility/theme/theme.hh"
#include "creeper-qt/utility/theme/theme.hh"
namespace creeper {

View File

@@ -1,6 +1,6 @@
#pragma once
#include "modern-qt/utility/theme/theme.hh"
#include "creeper-qt/utility/theme/theme.hh"
namespace creeper {

View File

@@ -1,6 +1,6 @@
#pragma once
#include "modern-qt/utility/theme/theme.hh"
#include "creeper-qt/utility/theme/theme.hh"
namespace creeper {

View File

@@ -1,4 +1,4 @@
#include "modern-qt/utility/theme/theme.hh"
#include "creeper-qt/utility/theme/theme.hh"
using namespace creeper::theme;
using Handler = ThemeManager::Handler;

View File

@@ -2,15 +2,10 @@
#include <qwidget.h>
// #include "utility/theme/color-scheme.hh"
// #include "utility/wrapper/common.hh"
// #include "utility/wrapper/pimpl.hh"
// #include "utility/wrapper/property.hh"
#include "modern-qt/utility/theme/color-scheme.hh"
#include "modern-qt/utility/wrapper/common.hh"
#include "modern-qt/utility/wrapper/pimpl.hh"
#include "modern-qt/utility/wrapper/property.hh"
#include <memory>
#include "creeper-qt/utility/theme/color-scheme.hh"
#include "creeper-qt/utility/wrapper/common.hh"
#include "creeper-qt/utility/wrapper/pimpl.hh"
#include "creeper-qt/utility/wrapper/property.hh"
namespace creeper::theme {
@@ -32,17 +27,8 @@ struct ThemePack {
};
class ThemeManager {
// CREEPER_PIMPL_DEFINITION(ThemeManager)
CREEPER_PIMPL_DEFINITION(ThemeManager)
public:
ThemeManager();
~ThemeManager();
ThemeManager(const ThemeManager&) = delete;
ThemeManager& operator=(const ThemeManager&) = delete;
private:
struct Impl;
std::unique_ptr<Impl> pimpl;
public:
explicit ThemeManager(const ThemePack& pack, ColorMode mode = ColorMode::LIGHT);
void apply_theme() const;

View File

@@ -1,6 +1,7 @@
#pragma once
#include <concepts>
#include <qwidget.h>
#include <utility>
namespace creeper {
@@ -25,6 +26,12 @@ concept linear_trait = requires(T t) {
{ t.addLayout(std::declval<QLayout*>(), int {}) };
};
template <class T>
concept stacked_trait = requires(T t) {
{t.addWidget(std::declval<QWidget*>())};
{t.insertWidget(int {}, std::declval<QWidget*>())};
};
template <class T>
concept area_trait = requires(T t) {
{ t.setWidget(std::declval<QWidget*>()) };

View File

@@ -1,26 +1,22 @@
#pragma once
#include "property.hh"
#include <qbitmap.h>
#include <qvector.h>
#include <qdebug.h>
#include <qicon.h>
#include <qwidget.h>
namespace creeper::common {
template <typename Instance>
struct Token {
void apply(auto& self) const {
const auto self_name = typeid(self).name();
const auto prop_name = typeid(this).name();
qDebug() << "Unimplemented" << prop_name << "is called by" << self_name;
// qDebug() << "Unimplemented" << prop_name << "is called by" << self_name;
}
};
namespace pro {
// 设置组透明度
// 设置组透明度
template <class Token>
using Opacity = SetterProp<Token, double, [](auto& self, double v) { self.set_opacity(v); }>;
@@ -115,44 +111,6 @@ namespace pro {
}
};
template <class Token, typename T, auto setter>
struct Vector : public QVector<T>, Token {
using QVector<T>::QVector;
explicit Vector(const QVector<T>& vec) noexcept
: QVector<T> { vec } { }
explicit Vector(const std::vector<T>& vec) noexcept
: QVector<T> { vec } { }
void apply(auto& self) const
requires requires {setter(self, *this); }
{
setter(self, *this);
}
};
template <class Token, typename T, std::size_t N, auto setter>
struct Array : public std::array<T, N>, Token {
using std::array<T, N>::array;
explicit Array(const std::array<T, N>& arr) noexcept
: std::array<T, N> { arr } { }
template <typename... Args>
requires (sizeof...(Args) == N)
explicit Array(Args&&... args) noexcept
: std::array<T, N> {
std::forward<Args>(args)...} {}
void apply(auto& self) const
requires requires {setter(self, *this);}
{
setter(self, *this);
}
};
// template<class Token, typename T, auto setter>
// Vector<Token, T, setter>::Vector(const QVector<T> &vec) noexcept:QVector { vec } { }
template <class Token>
using Text = String<Token, [](auto& self, const auto& string) { self.setText(string); }>;
@@ -182,22 +140,7 @@ namespace pro {
}
};
template <typename Callback, class Token>
struct IndexChanged : Token {
Callback callback;
explicit IndexChanged(Callback callback) noexcept
: callback {std::move(callback)} {}
auto apply(auto& self) const noexcept -> void
requires std::invocable<Callback, decltype(self)> || std::invocable<Callback> {
using widget_t = std::remove_cvref_t<decltype(self)>;
QObject::connect(&self, &widget_t::currentIndexChanged, [function = callback, &self] {
if constexpr (std::invocable<Callback, decltype(self)>) function(self);
});
}
};
// 自定义信号回调注册
namespace internal {
template <typename T>
struct FunctionArgs;

View File

@@ -1,7 +1,7 @@
#pragma once
#include "modern-qt/utility/qt_wrapper/margin_setter.hh"
#include "modern-qt/utility/trait/widget.hh"
#include "modern-qt/utility/wrapper/common.hh"
#include "creeper-qt/utility/qt_wrapper/margin-setter.hh"
#include "creeper-qt/utility/trait/widget.hh"
#include "creeper-qt/utility/wrapper/common.hh"
namespace creeper::layout::pro {

View File

@@ -1,5 +1,5 @@
#pragma once
#include "modern-qt/utility/wrapper/widget.hh"
#include "creeper-qt/utility/wrapper/widget.hh"
#include <qobject.h>
#include <unordered_map>

View File

@@ -45,7 +45,7 @@ struct SetterProp : Token {
requires std::assignable_from<T&, O>
{
value = std::forward<O>(other);
return *this; // x= y =6
return *this;
}
auto apply(auto& self) const noexcept -> void

View File

@@ -1,7 +1,7 @@
#pragma once
#include "modern-qt/utility/wrapper/common.hh"
#include "modern-qt/utility/wrapper/property.hh"
#include "creeper-qt/utility/wrapper/common.hh"
#include "creeper-qt/utility/wrapper/property.hh"
#include <qgraphicseffect.h>
#include <qscreen.h>

View File

@@ -1,7 +1,7 @@
#pragma once
#include "modern-qt/utility/wrapper/common.hh"
#include "modern-qt/utility/wrapper/property.hh"
#include "creeper-qt/utility/wrapper/common.hh"
#include "creeper-qt/utility/wrapper/property.hh"
namespace creeper::button::pro {

View File

@@ -1,11 +1,13 @@
#include "filled-button.hh"
#include "modern-qt/utility/animation/math.hh"
#include "modern-qt/utility/animation/state/pid.hh"
#include "modern-qt/utility/animation/transition.hh"
#include "modern-qt/utility/animation/water-ripple.hh"
#include "modern-qt/utility/painter/helper.hh"
#include "modern-qt/utility/theme/theme.hh"
#include "creeper-qt/utility/animation/math.hh"
#include "creeper-qt/utility/animation/state/pid.hh"
#include "creeper-qt/utility/animation/transition.hh"
#include "creeper-qt/utility/animation/water-ripple.hh"
#include "creeper-qt/utility/painter/helper.hh"
#include "creeper-qt/utility/theme/theme.hh"
#include <qevent.h>
namespace creeper::filled_button::internal {
@@ -16,7 +18,7 @@ public:
bool enable_water_ripple = true;
double water_ripple_step = 5.;
double radius = 0;
double radius = -1;
QColor text_color = Qt::black;
QColor background = Qt::white;

View File

@@ -1,11 +1,11 @@
#pragma once
#include "modern-qt/utility/qt_wrapper/enter_event.hh"
#include "modern-qt/utility/theme/theme.hh"
#include "modern-qt/utility/wrapper/pimpl.hh"
#include "modern-qt/utility/wrapper/property.hh"
#include "modern-qt/utility/wrapper/widget.hh"
#include "modern-qt/widget/buttons/button.hh"
#include "creeper-qt/utility/qt_wrapper/enter-event.hh"
#include "creeper-qt/utility/theme/theme.hh"
#include "creeper-qt/utility/wrapper/pimpl.hh"
#include "creeper-qt/utility/wrapper/property.hh"
#include "creeper-qt/utility/wrapper/widget.hh"
#include "creeper-qt/widget/buttons/button.hh"
#include "qabstractbutton.h"
namespace creeper::filled_button::internal {

View File

@@ -3,12 +3,12 @@
#include <qabstractbutton.h>
#include <qpainter.h>
#include "modern-qt/utility/qt_wrapper/enter_event.hh"
#include "modern-qt/utility/theme/theme.hh"
#include "modern-qt/utility/wrapper/common.hh"
#include "modern-qt/utility/wrapper/pimpl.hh"
#include "modern-qt/utility/wrapper/property.hh"
#include "modern-qt/utility/wrapper/widget.hh"
#include "creeper-qt/utility/qt_wrapper/enter-event.hh"
#include "creeper-qt/utility/theme/theme.hh"
#include "creeper-qt/utility/wrapper/common.hh"
#include "creeper-qt/utility/wrapper/pimpl.hh"
#include "creeper-qt/utility/wrapper/property.hh"
#include "creeper-qt/utility/wrapper/widget.hh"
namespace creeper::icon_button::internal {
class IconButton : public QAbstractButton {

View File

@@ -2,13 +2,12 @@
#include "icon-button.hh"
#include "modern-qt/utility/animation/animatable.hh"
#include "modern-qt/utility/animation/state/pid.hh"
#include "modern-qt/utility/animation/state/spring.hh"
#include "modern-qt/utility/animation/transition.hh"
#include "modern-qt/utility/animation/water-ripple.hh"
#include "modern-qt/utility/material-icon.hh"
#include "modern-qt/utility/painter/helper.hh"
#include "creeper-qt/utility/animation/animatable.hh"
#include "creeper-qt/utility/animation/state/pid.hh"
#include "creeper-qt/utility/animation/state/spring.hh"
#include "creeper-qt/utility/animation/transition.hh"
#include "creeper-qt/utility/animation/water-ripple.hh"
#include "creeper-qt/utility/painter/helper.hh"
using namespace creeper::icon_button::internal;

View File

@@ -35,7 +35,7 @@ public:
namespace creeper {
namespace outlined_button::pro {
using namespace filled_button;
using namespace filled_button::pro;
}
using OutlinedButton =

View File

@@ -1,6 +1,6 @@
#pragma once
#include "modern-qt/utility/theme/theme.hh"
#include "modern-qt/widget/shape/rounded-rect.hh"
#include "creeper-qt/utility/theme/theme.hh"
#include "creeper-qt/widget/shape/rounded-rect.hh"
namespace creeper::card::internal {

View File

@@ -0,0 +1,61 @@
#include "dropdown-menu.impl.hh"
DropdownMenu::DropdownMenu()
: pimpl { std::make_unique<Impl>(*this) } { }
DropdownMenu::~DropdownMenu() = default;
void DropdownMenu::set_color_scheme(const ColorScheme& scheme) { pimpl->set_color_scheme(scheme); }
void DropdownMenu::load_theme_manager(ThemeManager& manager) { pimpl->load_theme_manager(manager); }
void DropdownMenu::set_label_text(const QString& text) { pimpl->set_label_text(text); }
void DropdownMenu::set_leading_icon(const QIcon&) { }
void DropdownMenu::set_leading_icon(const QString& code, const QString& font) {
pimpl->set_leading_icon(code, font);
}
void DropdownMenu::resizeEvent(QResizeEvent* event) { QComboBox::resizeEvent(event); }
void DropdownMenu::enterEvent(qt::EnterEvent* enter_event) {
pimpl->enter_event(enter_event);
QComboBox::enterEvent(enter_event);
}
void DropdownMenu::leaveEvent(QEvent* event) {
pimpl->leave_event(event);
QComboBox::leaveEvent(event);
}
void DropdownMenu::focusInEvent(QFocusEvent* focus_event) {
pimpl->focus_in(focus_event);
QComboBox::focusInEvent(focus_event);
}
void DropdownMenu::focusOutEvent(QFocusEvent* event) {
pimpl->focus_out(event);
QComboBox::focusOutEvent(event);
}
void DropdownMenu::changeEvent(QEvent* event) { QComboBox::changeEvent(event); }
void DropdownMenu::showPopup() { pimpl->show_popup(); }
void DropdownMenu::hidePopup() { pimpl->hide_popup(); }
auto DropdownMenu::set_measurements(const Measurements& measurements) noexcept -> void {
pimpl->set_measurements(measurements);
}
void DropdownMenu::setTextMargins(const QMargins& margins) { this->margins = margins; }
QMargins DropdownMenu::textMargins() const { return margins; }
using namespace creeper;
void FilledDropdownMenu::paintEvent(QPaintEvent* event) {
pimpl->paint_filled(event);
// QComboBox::paintEvent(event);
}

View File

@@ -1,26 +1,23 @@
//
// Created by Lenn on 2025/10/14.
//
#pragma once
#ifndef TOUCHSENSOR_COMBO_BOX_HH
#define TOUCHSENSOR_COMBO_BOX_HH
#include "modern-qt/utility/qt_wrapper/enter_event.hh"
#include "modern-qt/utility/theme/theme.hh"
#include "modern-qt/utility/wrapper/common.hh"
#include "modern-qt/utility/wrapper/widget.hh"
#include "modern-qt/utility/wrapper/mutable-value.hh"
#include "creeper-qt/utility/qt_wrapper/enter-event.hh"
#include "creeper-qt/utility/theme/theme.hh"
#include "creeper-qt/utility/wrapper/common.hh"
#include "creeper-qt/utility/wrapper/pimpl.hh"
#include "creeper-qt/utility/wrapper/property.hh"
#include "creeper-qt/utility/wrapper/widget.hh"
#include <qcombobox.h>
namespace creeper {
class MatSelect;
namespace select_widget::internal {
class BasicSelect : public QComboBox {
CREEPER_PIMPL_DEFINITION(BasicSelect);
class FilledDropdownMenu;
friend MatSelect;
namespace dropdown_menu::internal {
class DropdownMenu : public QComboBox {
CREEPER_PIMPL_DEFINITION(DropdownMenu);
friend FilledDropdownMenu;
public:
struct ColorSpace {
@@ -35,7 +32,6 @@ namespace select_widget::internal {
QColor supporting_text;
QColor leading_icon;
QColor outline;
QColor itemlist_bg;
@@ -58,12 +54,12 @@ namespace select_widget::internal {
int icon_rect_size = 24;
int input_rect_size = 24;
int label_rect_size = 16;
int label_rect_size = 24;
int standard_font_height = 18;
int col_padding = 8;
int row_padding_without_icons = 16;
int row_padding_widthout_icons = 16;
int row_padding_with_icons = 12;
int row_padding_populated_label_text = 4;
@@ -72,10 +68,9 @@ namespace select_widget::internal {
int supporting_text_and_character_counter_top_padding = 4;
int supporting_text_and_character_counter_row_padding = 16;
auto icon_size() const { return QSize { icon_rect_size, icon_rect_size }; }
auto icon_size() const -> QSize { return QSize { icon_rect_size, icon_rect_size }; };
};
void set_color_scheme(const ColorScheme&);
auto set_color_scheme(const ColorScheme&) -> void;
void load_theme_manager(ThemeManager&);
@@ -90,13 +85,13 @@ namespace select_widget::internal {
protected:
void resizeEvent(QResizeEvent* event) override;
void enterEvent(qt::EnterEvent*) override;
void enterEvent(qt::EnterEvent* event) override;
void leaveEvent(QEvent* event) override;
void focusInEvent(QFocusEvent*) override;
void focusOutEvent(QFocusEvent* event) override;
void changeEvent(QEvent *) override;
void changeEvent(QEvent* event) override;
void showPopup() override;
void hidePopup() override;
@@ -105,57 +100,61 @@ namespace select_widget::internal {
friend struct Impl;
public:
void setTextMargins(int left, int top, int right, int bottom);
void setTextMargins(const QMargins& margins);
QMargins textMargins() const;
private:
QMargins margins { 13, 24, 13, 0 };
};
}
namespace select_widget::pro {
using Token = common::Token<internal::BasicSelect>;
namespace dropdown_menu::pro {
using Token = common::Token<internal::DropdownMenu>;
using LabelText = common::pro::String<Token,
[](auto& self, const auto& string) { self.set_label_text(string); }>;
struct LeadingIcon : Token {
QString code;
QString font;
explicit LeadingIcon(const QString& code, const QString& font)
: code {code}, font {font} {}
: code { code }
, font { font } { }
void apply(auto& self) const { self.set_leading_icon(code, font); }
};
struct LeadingText : Token {
QString text;
explicit LeadingText(const QString& text) : text {text} {}
void apply(auto& self) const {self.set_label_text(text);};
};
/// @note: currentIndexChanged(int index)
template <typename F>
using IndexChanged =
common::pro::SignalInjection<F, Token, &internal::DropdownMenu::currentIndexChanged>;
template<class Select>
concept trait = std::derived_from<Select, Token>;
template <typename F>
using TextChanged = common::pro::SignalInjection<F, Token, &internal::DropdownMenu::currentTextChanged>;
template<class Callback>
using IndexChanged = common::pro::IndexChanged<Callback, Token>;
using SelectItems = common::pro::Vector<Token, QString,
[](auto& self, const auto& vec) {self.clear();
using Items = DerivedProp<Token, QVector<QString>, //
[](auto& self, const auto& vec) {
self.clear();
self.addItems(vec);
self.setCurrentIndex(-1);
}>;
template <class Select>
concept trait = std::derived_from<Select, Token>;
CREEPER_DEFINE_CHECKER(trait);
using namespace widget::pro;
using namespace theme::pro;
}
struct MatSelect
: public Declarative<select_widget::internal::BasicSelect,
CheckerOr<select_widget::pro::checker, widget::pro::checker, theme::pro::checker>> {
struct FilledDropdownMenu
: public Declarative<dropdown_menu::internal::DropdownMenu,
CheckerOr<dropdown_menu::pro::checker, widget::pro::checker, theme::pro::checker>> {
using Declarative::Declarative;
void paintEvent(QPaintEvent* event) override;
};
namespace filled_dropdown_menu::pro {
using namespace dropdown_menu::pro;
}
}
#endif //TOUCHSENSOR_COMBO_BOX_HH

View File

@@ -0,0 +1,387 @@
/// TODO:
/// 显然的,原生 QComboBox 的下拉列表样式并不符合 Material Design
/// 规范,未来必须切换成自定义的组件,相关参考:
/// - https://m3.material.io/components/menus/guidelines
/// - https://api.flutter.dev/flutter/material/DropdownMenu-class.html
#pragma once
#include "dropdown-menu.hh"
#include "creeper-qt/utility/animation/animatable.hh"
#include "creeper-qt/utility/animation/state/pid.hh"
#include "creeper-qt/utility/animation/transition.hh"
#include "creeper-qt/utility/material-icon.hh"
#include "creeper-qt/utility/painter/helper.hh"
#include <qabstractitemview.h>
#include <qfontmetrics.h>
using namespace creeper::dropdown_menu::internal;
struct DropdownMenu::Impl {
public:
explicit Impl(DropdownMenu& self) noexcept
: animatable(self)
, self { self } {
{
auto state = std::make_shared<PidState<double>>();
state->config.kp = 20.0;
state->config.ki = 00.0;
state->config.kd = 00.0;
state->config.epsilon = 1e-2;
label_position = make_transition(animatable, std::move(state));
}
set_measurements(Measurements {});
}
auto set_color_scheme(const ColorScheme& scheme) -> void {
color_space.enabled.container = scheme.surface_container_highest;
color_space.enabled.label_text = scheme.on_surface_variant;
color_space.enabled.selected_text = scheme.on_surface;
color_space.enabled.leading_icon = scheme.on_surface_variant;
color_space.enabled.active_indicator = scheme.on_surface_variant;
color_space.enabled.supporting_text = scheme.on_surface_variant;
color_space.enabled.input_text = scheme.on_surface;
color_space.enabled.caret = scheme.primary;
color_space.enabled.outline = scheme.outline;
color_space.disabled.container = scheme.on_surface;
color_space.disabled.container.setAlphaF(0.04);
color_space.disabled.label_text = scheme.on_surface;
color_space.disabled.label_text.setAlphaF(0.38);
color_space.disabled.selected_text = scheme.on_surface;
color_space.disabled.selected_text.setAlphaF(0.38);
color_space.disabled.leading_icon = scheme.on_surface;
color_space.disabled.leading_icon.setAlphaF(0.38);
color_space.disabled.supporting_text = scheme.on_surface;
color_space.disabled.supporting_text.setAlphaF(0.38);
color_space.disabled.input_text = scheme.on_surface;
color_space.disabled.input_text.setAlphaF(0.38);
color_space.disabled.active_indicator = scheme.on_surface;
color_space.disabled.active_indicator.setAlphaF(0.38);
color_space.disabled.outline = scheme.outline;
color_space.disabled.outline.setAlphaF(0.38);
color_space.focused.container = scheme.surface_container_highest;
color_space.focused.label_text = scheme.primary;
color_space.focused.selected_text = scheme.on_surface;
color_space.focused.leading_icon = scheme.on_surface_variant;
color_space.focused.input_text = scheme.on_surface;
color_space.focused.supporting_text = scheme.on_surface_variant;
color_space.focused.active_indicator = scheme.primary;
color_space.focused.outline = scheme.primary;
color_space.error.container = scheme.surface_container_highest;
color_space.error.active_indicator = scheme.error;
color_space.error.label_text = scheme.error;
color_space.error.selected_text = scheme.on_surface;
color_space.error.input_text = scheme.on_surface;
color_space.error.supporting_text = scheme.error;
color_space.error.leading_icon = scheme.on_surface_variant;
color_space.error.caret = scheme.error;
color_space.error.outline = scheme.error;
color_space.state_layer = scheme.on_surface;
color_space.state_layer.setAlphaF(0.08);
const auto& color = get_color_tokens();
sync_basic_text_style(color.input_text, scheme.surface_container_highest, color.input_text,
color_space.state_layer);
}
auto load_theme_manager(ThemeManager& manager) {
manager.append_handler(&self,
[this](const ThemeManager& manager) { set_color_scheme(manager.color_scheme()); });
}
auto set_label_text(const QString& text) { label_text = text; }
auto set_leading_icon(const QString& code, const QString& font) {
leading_icon_code = code;
leading_icon_font = font;
is_update_component_status = false;
}
auto set_measurements(const Measurements& measurements) -> void {
this->measurements = measurements;
self.setFixedHeight(measurements.container_height + measurements.standard_font_height);
is_update_component_status = false;
}
auto paint_filled(QPaintEvent*) -> void {
const auto widget_rect = self.rect();
const auto color = get_color_tokens();
constexpr auto container_radius = 5;
update_component_status();
auto painter = QPainter { &self };
// Draw container with fixed measurements height and vertically centered
const auto container_rect = QRect { widget_rect.left(),
widget_rect.top() + (widget_rect.height() - measurements.container_height) / 2,
widget_rect.width(), measurements.container_height };
{
util::PainterHelper { painter }
.set_render_hint(QPainter::Antialiasing)
.rounded_rectangle(color.container, Qt::transparent, 0, container_rect,
container_radius, container_radius, 0, 0);
}
// Active indicator at container bottom
{
const auto p0 = container_rect.bottomLeft();
const auto p1 = container_rect.bottomRight();
painter.setBrush(Qt::NoBrush);
painter.setPen({ color.active_indicator, filled_line_width() });
painter.drawLine(p0, p1);
}
// Icon positioned relative to container_rect
const auto rect_icon = QRectF {
container_rect.right() - self.textMargins().right() - measurements.icon_rect_size * 1.,
container_rect.top() + (container_rect.height() - measurements.icon_rect_size) * 0.5,
1. * measurements.icon_rect_size,
1. * measurements.icon_rect_size,
};
const auto icon_center = rect_icon.center();
const bool is_active = (self.view() && self.view()->isVisible());
painter.save();
painter.setBrush(Qt::NoBrush);
painter.setPen(QPen { color.leading_icon });
painter.setFont(leading_icon_font);
painter.translate(icon_center);
painter.rotate(is_active ? 180.0 : 0.0);
painter.translate(-icon_center);
painter.drawText(rect_icon, leading_icon_code, { Qt::AlignCenter });
painter.restore();
if (!label_text.isEmpty()) {
const auto margins = self.textMargins();
const auto center_label_y = container_rect.top()
+ (measurements.container_height - measurements.label_rect_size) / 2.0;
const auto rect_center = QRectF {
QPointF { static_cast<double>(margins.left()), center_label_y },
QPointF(container_rect.right() - margins.right(),
center_label_y + measurements.label_rect_size),
};
const auto rect_top = QRectF {
QPointF(margins.left(), container_rect.top() + measurements.col_padding),
QPointF(container_rect.right() - margins.right(),
container_rect.top() + measurements.col_padding + measurements.label_rect_size),
};
const auto position = self.currentText().isEmpty() ? *label_position : 1.;
const auto label_rect = animate::interpolate(rect_center, rect_top, position);
const auto scale = 1. - position * 0.25;
const auto label_anchor = QPointF { label_rect.left(), label_rect.center().y() };
painter.save();
painter.translate(label_anchor);
painter.scale(scale, scale);
painter.translate(-label_anchor);
painter.setBrush(Qt::NoBrush);
painter.setPen(QPen { color.label_text });
painter.setFont(standard_text_font);
painter.setRenderHint(QPainter::Antialiasing);
painter.drawText(label_rect, label_text, { Qt::AlignVCenter | Qt::AlignLeading });
painter.restore();
if (self.currentIndex() != -1) {
painter.save();
// Place selected text in the input area (below the floating label)
const auto input_top =
container_rect.top() + measurements.col_padding + measurements.label_rect_size;
const auto input_bottom = container_rect.bottom() - measurements.col_padding;
const auto rect_center_selected = QRectF {
QPointF { static_cast<double>(margins.left()), static_cast<double>(input_top) },
QPointF(container_rect.right() - margins.right(),
static_cast<double>(input_bottom)),
};
// Draw selected text with input text color
painter.setBrush(Qt::NoBrush);
painter.setPen(QPen { color.selected_text });
painter.setFont(standard_text_font);
painter.setRenderHint(QPainter::Antialiasing);
painter.drawText(
rect_center_selected, self.currentText(), Qt::AlignVCenter | Qt::AlignLeading);
painter.restore();
}
} else if (label_text.isEmpty() && self.currentIndex() != -1) {
const auto margins = self.textMargins();
const auto input_top = container_rect.top()
+ (container_rect.height() - measurements.input_rect_size) / 2.0;
const auto input_bottom = input_top + measurements.input_rect_size;
const auto rect_selected = QRectF {
QPointF(margins.left(), input_top),
QPointF(container_rect.right() - margins.right(), input_bottom),
};
// Draw selected text
painter.save();
painter.setBrush(Qt::NoBrush);
painter.setPen(QPen { color.selected_text });
painter.setFont(standard_text_font);
painter.setRenderHint(QPainter::Antialiasing);
painter.drawText(
rect_selected, self.currentText(), Qt::AlignVCenter | Qt::AlignLeading);
painter.restore();
}
if (is_hovered) {
util::PainterHelper { painter }
.set_render_hint(QPainter::Antialiasing)
.rounded_rectangle(color_space.state_layer, Qt::transparent, 0, container_rect,
container_radius, container_radius, 0, 0);
}
}
auto enter_event(qt::EnterEvent*) {
is_hovered = true;
self.update();
}
auto leave_event(QEvent*) {
is_hovered = false;
self.update();
}
auto focus_in(QFocusEvent*) {
is_focused = true;
update_label_position();
self.update();
}
auto focus_out(QFocusEvent*) {
is_focused = false;
update_label_position();
self.update();
}
auto show_popup() {
if (self.count() == 0) {
return;
}
is_active = true;
self.QComboBox::showPopup();
update_label_position();
self.update();
}
auto hide_popup() -> void {
is_active = false;
self.QComboBox::hidePopup();
update_label_position();
self.update();
}
private:
auto update_component_status() -> void {
if (is_update_component_status) {
return;
}
auto font = self.font();
font.setPixelSize(measurements.standard_font_height);
self.setFont(font);
standard_text_font = self.font();
standard_text_font.setPixelSize(measurements.standard_font_height);
is_update_component_status = true;
}
auto update_label_position() -> void {
if ((is_focused || is_active) && self.currentIndex() != -1) {
label_position->transition_to(1.0);
} else if (is_focused || is_active) {
label_position->transition_to(1.0);
} else {
label_position->transition_to(0.0);
}
}
auto sync_basic_text_style(const QColor& text, const QColor& background,
const QColor& selection_text, const QColor& selection_background) -> void {
constexpr auto to_rgba = [](const QColor& color) {
return QStringLiteral("rgba(%1, %2, %3, %4)")
.arg(color.red())
.arg(color.green())
.arg(color.blue())
.arg(color.alpha());
};
constexpr auto kQComboBoxStyle = R"(
QComboBox {
border: none;
border-radius: 5px;
selection-color: %3;
selection-background-color: %4;
}
QComboBox QAbstractItemView {
border: none;
border-radius: 3px;
padding-top: 8px;
padding-bottom: 8px;
color: %1;
background-color: %2;
}
)";
self.setStyleSheet(QString { kQComboBoxStyle }
.arg(to_rgba(text))
.arg(to_rgba(background))
.arg(to_rgba(selection_text))
.arg(to_rgba(selection_background)));
}
auto get_color_tokens() const -> ColorSpace::Tokens const& {
return is_disable ? color_space.disabled
: is_error ? color_space.error
: is_active ? color_space.focused
: is_focused ? color_space.focused
: color_space.enabled;
}
auto filled_line_width() const -> double { return 1.5; }
static constexpr auto measure_text(
const QFont& font, const QString& text, const QTextOption& options) {
const auto fm = QFontMetricsF(font);
const auto size = fm.size(Qt::TextSingleLine, text);
return size.width();
}
private:
Measurements measurements;
ColorSpace color_space;
bool is_disable = false;
bool is_hovered = false;
bool is_focused = false;
bool is_error = false;
bool is_active = false;
bool is_update_component_status = false;
QString label_text;
QIcon leading_icon;
QString leading_icon_code = material::icon::kArrowDropDown;
QFont leading_icon_font = material::round::font_1;
QFont standard_text_font;
Animatable animatable;
std::unique_ptr<TransitionValue<PidState<double>>> label_position;
DropdownMenu& self;
};

View File

@@ -1,9 +1,9 @@
#pragma once
#include "modern-qt/utility/content-scale.hh"
#include "modern-qt/utility/painter-resource.hh"
#include "modern-qt/utility/wrapper/common.hh"
#include "modern-qt/utility/wrapper/pimpl.hh"
#include "modern-qt/utility/wrapper/widget.hh"
#include "creeper-qt/utility/content-scale.hh"
#include "creeper-qt/utility/painter-resource.hh"
#include "creeper-qt/utility/wrapper/common.hh"
#include "creeper-qt/utility/wrapper/pimpl.hh"
#include "creeper-qt/utility/wrapper/widget.hh"
namespace creeper {
namespace image::internal {

View File

@@ -1,4 +1,4 @@
#include "modern-qt/utility/painter/helper.hh"
#include "creeper-qt/utility/painter/helper.hh"
#include "image.hh"
#include <qevent.h>

View File

@@ -1,7 +1,7 @@
#pragma once
#include "modern-qt/utility/wrapper/common.hh"
#include "modern-qt/utility/wrapper/pimpl.hh"
#include "modern-qt/widget/widget.hh"
#include "creeper-qt/utility/wrapper/common.hh"
#include "creeper-qt/utility/wrapper/pimpl.hh"
#include "creeper-qt/widget/widget.hh"
namespace creeper::circular_progress_indicator::internal {

View File

@@ -1,11 +1,11 @@
#pragma once
#include <qmainwindow.h>
#include "modern-qt/utility/trait/widget.hh"
#include "modern-qt/utility/wrapper/common.hh"
#include "modern-qt/utility/wrapper/pimpl.hh"
#include "modern-qt/utility/wrapper/property.hh"
#include "modern-qt/utility/wrapper/widget.hh"
#include "creeper-qt/utility/trait/widget.hh"
#include "creeper-qt/utility/wrapper/common.hh"
#include "creeper-qt/utility/wrapper/pimpl.hh"
#include "creeper-qt/utility/wrapper/property.hh"
#include "creeper-qt/utility/wrapper/widget.hh"
namespace creeper::main_window::internal {

View File

@@ -1,9 +1,9 @@
#pragma once
#include "modern-qt/utility/painter/helper.hh"
#include "modern-qt/utility/wrapper/property.hh"
#include "modern-qt/widget/shape/shape.hh"
#include "modern-qt/widget/widget.hh"
#include "creeper-qt/utility/painter/helper.hh"
#include "creeper-qt/utility/wrapper/property.hh"
#include "creeper-qt/widget/shape/shape.hh"
#include "creeper-qt/widget/widget.hh"
namespace creeper {

View File

@@ -1,9 +1,9 @@
#pragma once
#include "modern-qt/utility/painter/helper.hh"
#include "modern-qt/utility/wrapper/property.hh"
#include "modern-qt/utility/wrapper/widget.hh"
#include "modern-qt/widget/shape/shape.hh"
#include "creeper-qt/utility/painter/helper.hh"
#include "creeper-qt/utility/wrapper/property.hh"
#include "creeper-qt/utility/wrapper/widget.hh"
#include "creeper-qt/widget/shape/shape.hh"
namespace creeper::rounded_rect::internal {

View File

@@ -1,10 +1,10 @@
#pragma once
#include "modern-qt/utility/solution/round-angle.hh"
#include "modern-qt/utility/wrapper/common.hh"
#include "modern-qt/utility/wrapper/property.hh"
#include "modern-qt/widget/shape/shape.hh"
#include "modern-qt/widget/widget.hh"
#include "creeper-qt/utility/solution/round-angle.hh"
#include "creeper-qt/utility/wrapper/common.hh"
#include "creeper-qt/utility/wrapper/property.hh"
#include "creeper-qt/widget/shape/shape.hh"
#include "creeper-qt/widget/widget.hh"
#include <cmath>
#include <qpainterpath.h>

View File

@@ -24,14 +24,14 @@ auto Slider::get_progress() const noexcept -> double {
auto Slider::mousePressEvent(QMouseEvent* event) -> void {
pimpl->mouse_press_event(event);
Widget::mousePressEvent(event);
QWidget::mousePressEvent(event);
}
auto Slider::mouseReleaseEvent(QMouseEvent* event) -> void {
pimpl->mouse_release_event(event);
Widget::mouseReleaseEvent(event);
QWidget::mouseReleaseEvent(event);
}
auto Slider::mouseMoveEvent(QMouseEvent* event) -> void {
pimpl->mouse_move_event(event);
Widget::mouseMoveEvent(event);
QWidget::mouseMoveEvent(event);
}
auto Slider::paintEvent(QPaintEvent* event) -> void { pimpl->paint_event(event); }

View File

@@ -1,13 +1,13 @@
#pragma once
#include "modern-qt/utility/theme/theme.hh"
#include "modern-qt/utility/wrapper/common.hh"
#include "modern-qt/utility/wrapper/pimpl.hh"
#include "modern-qt/widget/widget.hh"
#include "creeper-qt/utility/theme/theme.hh"
#include "creeper-qt/utility/wrapper/common.hh"
#include "creeper-qt/utility/wrapper/pimpl.hh"
#include "creeper-qt/utility/wrapper/widget.hh"
namespace creeper::slider::internal {
class Slider : public Widget {
class Slider : public QWidget {
Q_OBJECT
CREEPER_PIMPL_DEFINITION(Slider)
@@ -95,6 +95,8 @@ public:
auto set_progress(double) noexcept -> void;
auto get_progress() const noexcept -> double;
/// @bug Signals can not be exported on Windows
/// TODO: Fix it
signals:
auto signal_value_change(double) -> void;
auto signal_value_change_finished(double) -> void;

View File

@@ -1,9 +1,9 @@
#include "sliders.hh"
#include "modern-qt/utility/animation/animatable.hh"
#include "modern-qt/utility/animation/state/pid.hh"
#include "modern-qt/utility/animation/transition.hh"
#include "modern-qt/utility/painter/helper.hh"
#include "creeper-qt/utility/animation/animatable.hh"
#include "creeper-qt/utility/animation/state/pid.hh"
#include "creeper-qt/utility/animation/transition.hh"
#include "creeper-qt/utility/painter/helper.hh"
#include <qevent.h>
#include <qnamespace.h>

View File

@@ -1,11 +1,11 @@
#pragma once
#include "modern-qt/utility/qt_wrapper/enter_event.hh"
#include "modern-qt/utility/theme/theme.hh"
#include "modern-qt/utility/wrapper/common.hh"
#include "modern-qt/utility/wrapper/pimpl.hh"
#include "modern-qt/utility/wrapper/property.hh"
#include "modern-qt/utility/wrapper/widget.hh"
#include "creeper-qt/utility/qt_wrapper/enter-event.hh"
#include "creeper-qt/utility/theme/theme.hh"
#include "creeper-qt/utility/wrapper/common.hh"
#include "creeper-qt/utility/wrapper/pimpl.hh"
#include "creeper-qt/utility/wrapper/property.hh"
#include "creeper-qt/utility/wrapper/widget.hh"
#include <qabstractbutton.h>

View File

@@ -3,11 +3,11 @@
#include <qpainter.h>
#include "modern-qt/utility/animation/animatable.hh"
#include "modern-qt/utility/animation/state/pid.hh"
#include "modern-qt/utility/animation/state/spring.hh"
#include "modern-qt/utility/animation/transition.hh"
#include "modern-qt/utility/painter/helper.hh"
#include "creeper-qt/utility/animation/animatable.hh"
#include "creeper-qt/utility/animation/state/pid.hh"
#include "creeper-qt/utility/animation/state/spring.hh"
#include "creeper-qt/utility/animation/transition.hh"
#include "creeper-qt/utility/painter/helper.hh"
using namespace creeper::_switch::internal;

Some files were not shown because too many files have changed in this diff Show More