chore: code format by clang-format

This commit is contained in:
rankun 2020-03-29 02:13:01 +08:00
parent 35b85f7804
commit 827c529b36
68 changed files with 1517 additions and 1346 deletions

227
.clang-format Normal file
View file

@ -0,0 +1,227 @@
---
# 语言: None, Cpp, Java, JavaScript, ObjC, Proto, TableGen, TextProto
Language: Cpp
# BasedOnStyle: WebKit
# 访问说明符(public、private等)的偏移
AccessModifierOffset: -4
# 开括号(开圆括号、开尖括号、开方括号)后的对齐: Align, DontAlign, AlwaysBreak(总是在开括号后换行)
AlignAfterOpenBracket: AlwaysBreak
# 连续赋值时,对齐所有等号
AlignConsecutiveAssignments: false
# 连续声明时,对齐所有声明的变量名
AlignConsecutiveDeclarations: false
# 左对齐逃脱换行(使用反斜杠换行)的反斜杠
AlignEscapedNewlines: Right
# 水平对齐二元和三元表达式的操作数
AlignOperands: true
# 对齐连续的尾随的注释
AlignTrailingComments: true
# 允许函数声明的所有参数在放在下一行
AllowAllParametersOfDeclarationOnNextLine: false
# 允许短的块放在同一行
AllowShortBlocksOnASingleLine: false
# 允许短的case标签放在同一行
AllowShortCaseLabelsOnASingleLine: false
# 允许短的函数放在同一行: None, InlineOnly(定义在类中), Empty(空函数), Inline(定义在类中,空函数), All
AllowShortFunctionsOnASingleLine: Empty
# 允许短的if语句保持在同一行
AllowShortIfStatementsOnASingleLine: false
# 允许短的循环保持在同一行
AllowShortLoopsOnASingleLine: false
# 总是在定义返回类型后换行(deprecated)
AlwaysBreakAfterDefinitionReturnType: None
# 总是在返回类型后换行: None, All, TopLevel(顶级函数,不包括在类中的函数),
# AllDefinitions(所有的定义,不包括声明), TopLevelDefinitions(所有的顶级函数的定义)
AlwaysBreakAfterReturnType: None
# 总是在多行string字面量前换行
AlwaysBreakBeforeMultilineStrings: false
# 总是在template声明后换行
AlwaysBreakTemplateDeclarations: true
# false表示函数实参要么都在同一行要么都各自一行
BinPackArguments: false
# false表示所有形参要么都在同一行要么都各自一行
BinPackParameters: false
# 在大括号前换行: Attach(始终将大括号附加到周围的上下文), Linux(除函数、命名空间和类定义与Attach类似),
# Mozilla(除枚举、函数、记录定义与Attach类似), Stroustrup(除函数定义、catch、else与Attach类似),
# Allman(总是在大括号前换行), GNU(总是在大括号前换行,并对于控制语句的大括号增加额外的缩进), WebKit(在函数前换行), Custom
# 注:这里认为语句块也属于函数
BreakBeforeBraces: Custom
# 大括号换行只有当BreakBeforeBraces设置为Custom时才有效
BraceWrapping:
# class定义后面
AfterClass: true
# 控制语句后面
AfterControlStatement: false
# enum定义后面
AfterEnum: true
# 函数定义后面
AfterFunction: true
# 命名空间定义后面
AfterNamespace: true
# ObjC定义后面
AfterObjCDeclaration: false
# struct定义后面
AfterStruct: true
# union定义后面
AfterUnion: true
# extern 定义后面
AfterExternBlock: true
# catch之前
BeforeCatch: false
# else 之前
BeforeElse: false
# 缩进大括号
IndentBraces: false
# 在二元运算符前换行: None(在操作符后换行), NonAssignment(在非赋值的操作符前换行), All(在操作符前换行)
BreakBeforeBinaryOperators: All
# 继承列表的逗号前换行
BreakBeforeInheritanceComma: true
# 继承列表换行
#BreakInheritanceList: BeforeColon
# 在三元运算符前换行
BreakBeforeTernaryOperators: true
# 在构造函数的初始化列表的逗号前换行
BreakConstructorInitializersBeforeComma: true
# 初始化列表前换行
BreakConstructorInitializers: BeforeComma
# Java注解后换行
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
# 每行字符的限制0表示没有限制
ColumnLimit: 160
# 描述具有特殊意义的注释的正则表达式,它不应该被分割为多行或以其它方式改变
CommentPragmas: '^ IWYU pragma:'
# 紧凑 命名空间
CompactNamespaces: false
# 构造函数的初始化列表要么都在同一行,要么都各自一行
ConstructorInitializerAllOnOneLineOrOnePerLine: true
# 构造函数的初始化列表的缩进宽度
ConstructorInitializerIndentWidth: 4
# 延续的行的缩进宽度
ContinuationIndentWidth: 4
# 去除C++11的列表初始化的大括号{后和}前的空格
Cpp11BracedListStyle: false
# 继承最常用的指针和引用的对齐方式
DerivePointerAlignment: false
# 关闭格式化
DisableFormat: false
# 自动检测函数的调用和定义是否被格式为每行一个参数(Experimental)
ExperimentalAutoDetectBinPacking: false
# 固定命名空间注释
FixNamespaceComments: true
# 需要被解读为foreach循环而不是函数调用的宏
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IncludeBlocks: Preserve
# 对#include进行排序匹配了某正则表达式的#include拥有对应的优先级匹配不到的则默认优先级为INT_MAX(优先级越小排序越靠前)
# 可以定义负数优先级从而保证某些#include永远在最前面
IncludeCategories:
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 2
- Regex: '^(<|"(gtest|gmock|isl|json)/)'
Priority: 3
- Regex: 'stdafx\.'
Priority: 1
- Regex: '.*'
Priority: 1
IncludeIsMainRegex: '(Test)?$'
# 缩进case标签
IndentCaseLabels: false
IndentPPDirectives: None
# 缩进宽度
IndentWidth: 4
# 函数返回类型换行时,缩进函数声明或函数定义的函数名
IndentWrappedFunctionNames: true
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
# 保留在块开始处的空行
KeepEmptyLinesAtTheStartOfBlocks: true
# 开始一个块的宏的正则表达式
MacroBlockBegin: ''
# 结束一个块的宏的正则表达式
MacroBlockEnd: ''
# 连续空行的最大数量
MaxEmptyLinesToKeep: 1
# 命名空间的缩进: None, Inner(缩进嵌套的命名空间中的内容), All
NamespaceIndentation: All
ObjCBinPackProtocolList: Auto
# 使用ObjC块时缩进宽度
ObjCBlockIndentWidth: 4
# 在ObjC的@property后添加一个空格
ObjCSpaceAfterProperty: true
# 在ObjC的protocol列表前添加一个空格
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
# 在一个注释中引入换行的penalty
PenaltyBreakComment: 300
# 第一次在<<前换行的penalty
PenaltyBreakFirstLessLess: 120
# 在一个字符串字面量中引入换行的penalty
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
# 对于每个在行字符数限制之外的字符的penalty
PenaltyExcessCharacter: 1000000
# 将函数的返回类型放到它自己的行的penalty
PenaltyReturnTypeOnItsOwnLine: 60
# 指针和引用的对齐: Left, Right, Middle
PointerAlignment: Right
#RawStringFormats:
# - Delimiter: pb
# Language: TextProto
# BasedOnStyle: google
# 允许重新排版注释
ReflowComments: false
# 允许排序#include
SortIncludes: true
SortUsingDeclarations: true
# 在C风格类型转换后添加空格
SpaceAfterCStyleCast: false
# 模板关键字后面添加空格
SpaceAfterTemplateKeyword: true
# 在赋值运算符之前添加空格
SpaceBeforeAssignmentOperators: true
# 开圆括号之前添加一个空格: Never, ControlStatements, Always
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true
# 在空的圆括号中添加空格
SpaceInEmptyParentheses: false
# 在尾随的评论前添加的空格数(只适用于//)
SpacesBeforeTrailingComments: 1
# 在尖括号的<后和>前添加空格
SpacesInAngles: false
# 在容器(ObjC和JavaScript的数组和字典等)字面量中添加空格
SpacesInContainerLiterals: true
# 在C风格类型转换的括号中添加空格
SpacesInCStyleCastParentheses: false
# 在圆括号的(后和)前添加空格
SpacesInParentheses: false
# 在方括号的[后和]前添加空格lamda表达式和未指明大小的数组的声明不受影响
SpacesInSquareBrackets: false
# 标准: Cpp03, Cpp11, Auto
Standard: Cpp11
# tab宽度
TabWidth: 4
# 使用tab字符: Never, ForIndentation, ForContinuationAndIndentation, Always
UseTab: Never
...

View file

@ -1,15 +1,14 @@
#include <QProcess>
#include <QCoreApplication> #include <QCoreApplication>
#include <QDebug> #include <QDebug>
#include <QFileInfo>
#include <QDir> #include <QDir>
#include <QFileInfo>
#include <QProcess>
#include "adbprocess.h" #include "adbprocess.h"
QString AdbProcess::s_adbPath = ""; QString AdbProcess::s_adbPath = "";
AdbProcess::AdbProcess(QObject *parent) AdbProcess::AdbProcess(QObject *parent) : QProcess(parent)
: QProcess(parent)
{ {
initSignals(); initSignals();
} }
@ -38,8 +37,7 @@ void AdbProcess::initSignals()
// aboutToQuit not exit event loop, so deletelater is ok // aboutToQuit not exit event loop, so deletelater is ok
//connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit, this, &AdbProcess::deleteLater); //connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit, this, &AdbProcess::deleteLater);
connect(this, static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished), this, connect(this, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished), this, [this](int exitCode, QProcess::ExitStatus exitStatus) {
[this](int exitCode, QProcess::ExitStatus exitStatus){
if (NormalExit == exitStatus && 0 == exitCode) { if (NormalExit == exitStatus && 0 == exitCode) {
emit adbProcessResult(AER_SUCCESS_EXEC); emit adbProcessResult(AER_SUCCESS_EXEC);
} else { } else {
@ -49,8 +47,7 @@ void AdbProcess::initSignals()
qDebug() << "adb return " << exitCode << "exit status " << exitStatus; qDebug() << "adb return " << exitCode << "exit status " << exitStatus;
}); });
connect(this, &QProcess::errorOccurred, this, connect(this, &QProcess::errorOccurred, this, [this](QProcess::ProcessError error) {
[this](QProcess::ProcessError error){
if (QProcess::FailedToStart == error) { if (QProcess::FailedToStart == error) {
emit adbProcessResult(AER_ERROR_MISSING_BINARY); emit adbProcessResult(AER_ERROR_MISSING_BINARY);
} else { } else {
@ -60,24 +57,19 @@ void AdbProcess::initSignals()
} }
}); });
connect(this, &QProcess::readyReadStandardError, this, connect(this, &QProcess::readyReadStandardError, this, [this]() {
[this](){
QString tmp = QString::fromUtf8(readAllStandardError()).trimmed(); QString tmp = QString::fromUtf8(readAllStandardError()).trimmed();
m_errorOutput += tmp; m_errorOutput += tmp;
qWarning(QString("AdbProcess::error:%1").arg(tmp).toStdString().data()); qWarning(QString("AdbProcess::error:%1").arg(tmp).toStdString().data());
}); });
connect(this, &QProcess::readyReadStandardOutput, this, connect(this, &QProcess::readyReadStandardOutput, this, [this]() {
[this](){
QString tmp = QString::fromUtf8(readAllStandardOutput()).trimmed(); QString tmp = QString::fromUtf8(readAllStandardOutput()).trimmed();
m_standardOutput += tmp; m_standardOutput += tmp;
qInfo(QString("AdbProcess::out:%1").arg(tmp).toStdString().data()); qInfo(QString("AdbProcess::out:%1").arg(tmp).toStdString().data());
}); });
connect(this, &QProcess::started, this, connect(this, &QProcess::started, this, [this]() { emit adbProcessResult(AER_SUCCESS_START); });
[this](){
emit adbProcessResult(AER_SUCCESS_START);
});
} }
void AdbProcess::execute(const QString &serial, const QStringList &args) void AdbProcess::execute(const QString &serial, const QStringList &args)
@ -105,7 +97,11 @@ bool AdbProcess::isRuning()
void AdbProcess::setShowTouchesEnabled(const QString &serial, bool enabled) void AdbProcess::setShowTouchesEnabled(const QString &serial, bool enabled)
{ {
QStringList adbArgs; QStringList adbArgs;
adbArgs << "shell" << "settings" << "put" << "system" << "show_touches"; adbArgs << "shell"
<< "settings"
<< "put"
<< "system"
<< "show_touches";
adbArgs << (enabled ? "1" : "0"); adbArgs << (enabled ? "1" : "0");
execute(serial, adbArgs); execute(serial, adbArgs);
} }

View file

@ -8,7 +8,8 @@ class AdbProcess : public QProcess
Q_OBJECT Q_OBJECT
public: public:
enum ADB_EXEC_RESULT { enum ADB_EXEC_RESULT
{
AER_SUCCESS_START, // 启动成功 AER_SUCCESS_START, // 启动成功
AER_ERROR_START, // 启动失败 AER_ERROR_START, // 启动失败
AER_SUCCESS_EXEC, // 执行成功 AER_SUCCESS_EXEC, // 执行成功

View file

@ -0,0 +1,84 @@
#!/bin/bash
#
# clang-format-all: a tool to run clang-format on an entire project
# Copyright (C) 2016 Evan Klitzke <evan@eklitzke.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
function usage {
echo "Usage: $0 DIR..."
exit 1
}
if [ $# -eq 0 ]; then
usage
fi
# Variable that will hold the name of the clang-format command
FMT=""
# Some distros just call it clang-format. Others (e.g. Ubuntu) are insistent
# that the version number be part of the command. We prefer clang-format if
# that's present, otherwise we work backwards from highest version to lowest
# version.
for clangfmt in clang-format{,-{4,3}.{9,8,7,6,5,4,3,2,1,0}}; do
if which "$clangfmt" &>/dev/null; then
FMT="$clangfmt"
break
fi
done
# Check if we found a working clang-format
if [ -z "$FMT" ]; then
echo "failed to find clang-format"
exit 1
fi
# Check all of the arguments first to make sure they're all directories
for dir in "$@"; do
if [ ! -d "${dir}" ]; then
echo "${dir} is not a directory"
usage
fi
done
# Find a dominating file, starting from a given directory and going up.
find-dominating-file() {
if [ -r "$1"/"$2" ]; then
return 0
fi
if [ "$1" = "/" ]; then
return 1
fi
find-dominating-file "$(realpath "$1"/..)" "$2"
return $?
}
# Run clang-format -i on all of the things
for dir in "$@"; do
pushd "${dir}" &>/dev/null
if ! find-dominating-file . .clang-format; then
echo "Failed to find dominating .clang-format starting at $PWD"
continue
fi
find . \
\( -name '*.c' \
-o -name '*.cc' \
-o -name '*.cpp' \
-o -name '*.h' \
-o -name '*.hh' \
-o -name '*.hpp' \) \
-exec "${FMT}" -i '{}' \;
popd &>/dev/null
done

View file

@ -5,7 +5,8 @@
class QScrcpyEvent : public QEvent class QScrcpyEvent : public QEvent
{ {
public: public:
enum Type { enum Type
{
VideoSocket = QEvent::User + 1, VideoSocket = QEvent::User + 1,
Control, Control,
}; };

View file

@ -23,7 +23,8 @@
/** /**
* Meta key / modifer state. * Meta key / modifer state.
*/ */
enum AndroidMetastate { enum AndroidMetastate
{
/** No meta keys are pressed. */ /** No meta keys are pressed. */
AMETA_NONE = 0, AMETA_NONE = 0,
@ -82,7 +83,8 @@ enum AndroidMetastate {
/** /**
* Input event types. * Input event types.
*/ */
enum AndroidInputEventType { enum AndroidInputEventType
{
/** Indicates that the input event is a key event. */ /** Indicates that the input event is a key event. */
AINPUT_EVENT_TYPE_KEY = 1, AINPUT_EVENT_TYPE_KEY = 1,
/** Indicates that the input event is a motion event. */ /** Indicates that the input event is a motion event. */
@ -92,7 +94,8 @@ enum AndroidInputEventType {
/** /**
* Key event actions. * Key event actions.
*/ */
enum AndroidKeyeventAction { enum AndroidKeyeventAction
{
/** The key has been pressed down. */ /** The key has been pressed down. */
AKEY_EVENT_ACTION_DOWN = 0, AKEY_EVENT_ACTION_DOWN = 0,
@ -111,7 +114,8 @@ enum AndroidKeyeventAction {
/** /**
* Key event flags. * Key event flags.
*/ */
enum AndroidKeyeventFlags { enum AndroidKeyeventFlags
{
/** This mask is set if the device woke because of this key event. */ /** This mask is set if the device woke because of this key event. */
AKEY_EVENT_FLAG_WOKE_HERE = 0x1, AKEY_EVENT_FLAG_WOKE_HERE = 0x1,
@ -195,7 +199,8 @@ enum AndroidKeyeventFlags {
#define AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT 8 #define AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT 8
/** Motion event actions */ /** Motion event actions */
enum AndroidMotioneventAction { enum AndroidMotioneventAction
{
/** Bit mask of the parts of the action code that are the action itself. */ /** Bit mask of the parts of the action code that are the action itself. */
AMOTION_EVENT_ACTION_MASK = 0xff, AMOTION_EVENT_ACTION_MASK = 0xff,
@ -281,7 +286,8 @@ enum AndroidMotioneventAction {
/** /**
* Motion event flags. * Motion event flags.
*/ */
enum AndroidMotioneventFlags { enum AndroidMotioneventFlags
{
/** /**
* This flag indicates that the window that received this motion event is partly * This flag indicates that the window that received this motion event is partly
* or wholly obscured by another visible window above it. This flag is set to true * or wholly obscured by another visible window above it. This flag is set to true
@ -298,7 +304,8 @@ enum AndroidMotioneventFlags {
/** /**
* Motion event edge touch flags. * Motion event edge touch flags.
*/ */
enum AndroidMotioneventEdgeTouchTlags { enum AndroidMotioneventEdgeTouchTlags
{
/** No edges intersected. */ /** No edges intersected. */
AMOTION_EVENT_EDGE_FLAG_NONE = 0, AMOTION_EVENT_EDGE_FLAG_NONE = 0,
@ -319,7 +326,8 @@ enum AndroidMotioneventEdgeTouchTlags {
* Constants that identify each individual axis of a motion event. * Constants that identify each individual axis of a motion event.
* @anchor AMOTION_EVENT_AXIS * @anchor AMOTION_EVENT_AXIS
*/ */
enum AndroidMotioneventAxis { enum AndroidMotioneventAxis
{
/** /**
* Axis constant: X axis of a motion event. * Axis constant: X axis of a motion event.
* *
@ -688,7 +696,8 @@ enum AndroidMotioneventAxis {
* Constants that identify buttons that are associated with motion events. * Constants that identify buttons that are associated with motion events.
* Refer to the documentation on the MotionEvent class for descriptions of each button. * Refer to the documentation on the MotionEvent class for descriptions of each button.
*/ */
enum AndroidMotioneventButtons { enum AndroidMotioneventButtons
{
/** primary */ /** primary */
AMOTION_EVENT_BUTTON_PRIMARY = 1 << 0, AMOTION_EVENT_BUTTON_PRIMARY = 1 << 0,
/** secondary */ /** secondary */
@ -707,7 +716,8 @@ enum AndroidMotioneventButtons {
* Constants that identify tool types. * Constants that identify tool types.
* Refer to the documentation on the MotionEvent class for descriptions of each tool type. * Refer to the documentation on the MotionEvent class for descriptions of each tool type.
*/ */
enum AndroidMotioneventToolType { enum AndroidMotioneventToolType
{
/** unknown */ /** unknown */
AMOTION_EVENT_TOOL_TYPE_UNKNOWN = 0, AMOTION_EVENT_TOOL_TYPE_UNKNOWN = 0,
/** finger */ /** finger */
@ -726,7 +736,8 @@ enum AndroidMotioneventToolType {
* Refer to the documentation on android.view.InputDevice for more details about input sources * Refer to the documentation on android.view.InputDevice for more details about input sources
* and their correct interpretation. * and their correct interpretation.
*/ */
enum AndroidInputSourceClass { enum AndroidInputSourceClass
{
/** mask */ /** mask */
AINPUT_SOURCE_CLASS_MASK = 0x000000ff, AINPUT_SOURCE_CLASS_MASK = 0x000000ff,
@ -747,7 +758,8 @@ enum AndroidInputSourceClass {
/** /**
* Input sources. * Input sources.
*/ */
enum AndroidInputSource { enum AndroidInputSource
{
/** unknown */ /** unknown */
AINPUT_SOURCE_UNKNOWN = 0x00000000, AINPUT_SOURCE_UNKNOWN = 0x00000000,
@ -784,7 +796,8 @@ enum AndroidInputSource {
* *
* Refer to the documentation on android.view.InputDevice for more details. * Refer to the documentation on android.view.InputDevice for more details.
*/ */
enum AndroidKeyboardType { enum AndroidKeyboardType
{
/** none */ /** none */
AINPUT_KEYBOARD_TYPE_NONE = 0, AINPUT_KEYBOARD_TYPE_NONE = 0,
/** non alphabetic */ /** non alphabetic */
@ -802,7 +815,8 @@ enum AndroidKeyboardType {
* *
* @deprecated These constants are deprecated. Use {@link AMOTION_EVENT_AXIS AMOTION_EVENT_AXIS_*} constants instead. * @deprecated These constants are deprecated. Use {@link AMOTION_EVENT_AXIS AMOTION_EVENT_AXIS_*} constants instead.
*/ */
enum AndroidMotionRange { enum AndroidMotionRange
{
/** x */ /** x */
AINPUT_MOTION_RANGE_X = AMOTION_EVENT_AXIS_X, AINPUT_MOTION_RANGE_X = AMOTION_EVENT_AXIS_X,
/** y */ /** y */

View file

@ -23,7 +23,8 @@
/** /**
* Key codes. * Key codes.
*/ */
enum AndroidKeycode { enum AndroidKeycode
{
/** Unknown key code. */ /** Unknown key code. */
AKEYCODE_UNKNOWN = 0, AKEYCODE_UNKNOWN = 0,
/** Soft Left key. /** Soft Left key.

View file

@ -2,10 +2,10 @@
#include <QClipboard> #include <QClipboard>
#include "controller.h" #include "controller.h"
#include "videosocket.h"
#include "controlmsg.h" #include "controlmsg.h"
#include "receiver.h"
#include "inputconvertgame.h" #include "inputconvertgame.h"
#include "receiver.h"
#include "videosocket.h"
Controller::Controller(QString gameScript, QObject *parent) : QObject(parent) Controller::Controller(QString gameScript, QObject *parent) : QObject(parent)
{ {
@ -15,10 +15,7 @@ Controller::Controller(QString gameScript, QObject* parent) : QObject(parent)
updateScript(gameScript); updateScript(gameScript);
} }
Controller::~Controller() Controller::~Controller() {}
{
}
void Controller::setControlSocket(QTcpSocket *controlSocket) void Controller::setControlSocket(QTcpSocket *controlSocket)
{ {
@ -39,10 +36,7 @@ void Controller::postControlMsg(ControlMsg *controlMsg)
void Controller::test(QRect rc) void Controller::test(QRect rc)
{ {
ControlMsg *controlMsg = new ControlMsg(ControlMsg::CMT_INJECT_TOUCH); ControlMsg *controlMsg = new ControlMsg(ControlMsg::CMT_INJECT_TOUCH);
controlMsg->setInjectTouchMsgData(POINTER_ID_MOUSE, controlMsg->setInjectTouchMsgData(POINTER_ID_MOUSE, AMOTION_EVENT_ACTION_DOWN, AMOTION_EVENT_BUTTON_PRIMARY, rc, 1.0f);
AMOTION_EVENT_ACTION_DOWN,
AMOTION_EVENT_BUTTON_PRIMARY,
rc, 1.0f);
postControlMsg(controlMsg); postControlMsg(controlMsg);
} }

View file

@ -1,22 +1,19 @@
#include <QDebug> #include <QDebug>
#include "controlmsg.h"
#include "bufferutil.h" #include "bufferutil.h"
#include "controlmsg.h"
ControlMsg::ControlMsg(ControlMsgType controlMsgType) ControlMsg::ControlMsg(ControlMsgType controlMsgType) : QScrcpyEvent(Control)
: QScrcpyEvent(Control)
{ {
m_data.type = controlMsgType; m_data.type = controlMsgType;
} }
ControlMsg::~ControlMsg() ControlMsg::~ControlMsg()
{ {
if (CMT_SET_CLIPBOARD == m_data.type if (CMT_SET_CLIPBOARD == m_data.type && Q_NULLPTR != m_data.setClipboard.text) {
&& Q_NULLPTR != m_data.setClipboard.text) {
delete m_data.setClipboard.text; delete m_data.setClipboard.text;
m_data.setClipboard.text = Q_NULLPTR; m_data.setClipboard.text = Q_NULLPTR;
} else if (CMT_INJECT_TEXT == m_data.type } else if (CMT_INJECT_TEXT == m_data.type && Q_NULLPTR != m_data.injectText.text) {
&& Q_NULLPTR != m_data.injectText.text){
delete m_data.injectText.text; delete m_data.injectText.text;
m_data.injectText.text = Q_NULLPTR; m_data.injectText.text = Q_NULLPTR;
} }
@ -113,16 +110,14 @@ QByteArray ControlMsg::serializeData()
BufferUtil::write16(buffer, strlen(m_data.injectText.text)); BufferUtil::write16(buffer, strlen(m_data.injectText.text));
buffer.write(m_data.injectText.text, strlen(m_data.injectText.text)); buffer.write(m_data.injectText.text, strlen(m_data.injectText.text));
break; break;
case CMT_INJECT_TOUCH: case CMT_INJECT_TOUCH: {
{
buffer.putChar(m_data.injectTouch.action); buffer.putChar(m_data.injectTouch.action);
BufferUtil::write64(buffer, m_data.injectTouch.id); BufferUtil::write64(buffer, m_data.injectTouch.id);
writePosition(buffer, m_data.injectTouch.position); writePosition(buffer, m_data.injectTouch.position);
quint16 pressure = toFixedPoint16(m_data.injectTouch.pressure); quint16 pressure = toFixedPoint16(m_data.injectTouch.pressure);
BufferUtil::write16(buffer, pressure); BufferUtil::write16(buffer, pressure);
BufferUtil::write32(buffer, m_data.injectTouch.buttons); BufferUtil::write32(buffer, m_data.injectTouch.buttons);
} } break;
break;
case CMT_INJECT_SCROLL: case CMT_INJECT_SCROLL:
writePosition(buffer, m_data.injectScroll.position); writePosition(buffer, m_data.injectScroll.position);
BufferUtil::write32(buffer, m_data.injectScroll.hScroll); BufferUtil::write32(buffer, m_data.injectScroll.hScroll);

View file

@ -1,13 +1,13 @@
#ifndef CONTROLMSG_H #ifndef CONTROLMSG_H
#define CONTROLMSG_H #define CONTROLMSG_H
#include <QBuffer>
#include <QRect> #include <QRect>
#include <QString> #include <QString>
#include <QBuffer>
#include "qscrcpyevent.h"
#include "input.h" #include "input.h"
#include "keycodes.h" #include "keycodes.h"
#include "qscrcpyevent.h"
#define CONTROL_MSG_TEXT_MAX_LENGTH 300 #define CONTROL_MSG_TEXT_MAX_LENGTH 300
#define CONTROL_MSG_CLIPBOARD_TEXT_MAX_LENGTH 4093 #define CONTROL_MSG_CLIPBOARD_TEXT_MAX_LENGTH 4093
@ -16,7 +16,8 @@
class ControlMsg : public QScrcpyEvent class ControlMsg : public QScrcpyEvent
{ {
public: public:
enum ControlMsgType { enum ControlMsgType
{
CMT_NULL = -1, CMT_NULL = -1,
CMT_INJECT_KEYCODE = 0, CMT_INJECT_KEYCODE = 0,
CMT_INJECT_TEXT, CMT_INJECT_TEXT,
@ -30,7 +31,8 @@ public:
CMT_SET_SCREEN_POWER_MODE CMT_SET_SCREEN_POWER_MODE
}; };
enum ScreenPowerMode { enum ScreenPowerMode
{
// see <https://android.googlesource.com/platform/frameworks/base.git/+/pie-release-2/core/java/android/view/SurfaceControl.java#305> // see <https://android.googlesource.com/platform/frameworks/base.git/+/pie-release-2/core/java/android/view/SurfaceControl.java#305>
SPM_OFF = 0, SPM_OFF = 0,
SPM_NORMAL = 2, SPM_NORMAL = 2,
@ -56,33 +58,41 @@ private:
quint16 toFixedPoint16(float f); quint16 toFixedPoint16(float f);
private: private:
struct ControlMsgData { struct ControlMsgData
{
ControlMsgType type = CMT_NULL; ControlMsgType type = CMT_NULL;
union { union
struct { {
struct
{
AndroidKeyeventAction action; AndroidKeyeventAction action;
AndroidKeycode keycode; AndroidKeycode keycode;
AndroidMetastate metastate; AndroidMetastate metastate;
} injectKeycode; } injectKeycode;
struct { struct
{
char *text = Q_NULLPTR; char *text = Q_NULLPTR;
} injectText; } injectText;
struct { struct
{
quint64 id; quint64 id;
AndroidMotioneventAction action; AndroidMotioneventAction action;
AndroidMotioneventButtons buttons; AndroidMotioneventButtons buttons;
QRect position; QRect position;
float pressure; float pressure;
} injectTouch; } injectTouch;
struct { struct
{
QRect position; QRect position;
qint32 hScroll; qint32 hScroll;
qint32 vScroll; qint32 vScroll;
} injectScroll; } injectScroll;
struct { struct
{
char *text = Q_NULLPTR; char *text = Q_NULLPTR;
} setClipboard; } setClipboard;
struct { struct
{
ScreenPowerMode mode; ScreenPowerMode mode;
} setScreenPowerMode; } setScreenPowerMode;
}; };

View file

@ -1,17 +1,12 @@
#include "inputconvertbase.h" #include "inputconvertbase.h"
#include "controller.h" #include "controller.h"
InputConvertBase::InputConvertBase(Controller* controller) InputConvertBase::InputConvertBase(Controller *controller) : QObject(controller), m_controller(controller)
: QObject(controller)
, m_controller(controller)
{ {
Q_ASSERT(controller); Q_ASSERT(controller);
} }
InputConvertBase::~InputConvertBase() InputConvertBase::~InputConvertBase() {}
{
}
void InputConvertBase::sendControlMsg(ControlMsg *msg) void InputConvertBase::sendControlMsg(ControlMsg *msg)
{ {
@ -19,4 +14,3 @@ void InputConvertBase::sendControlMsg(ControlMsg *msg)
m_controller->postControlMsg(msg); m_controller->postControlMsg(msg);
} }
} }

View file

@ -1,10 +1,10 @@
#ifndef INPUTCONVERTBASE_H #ifndef INPUTCONVERTBASE_H
#define INPUTCONVERTBASE_H #define INPUTCONVERTBASE_H
#include <QMouseEvent>
#include <QWheelEvent>
#include <QKeyEvent> #include <QKeyEvent>
#include <QMouseEvent>
#include <QPointer> #include <QPointer>
#include <QWheelEvent>
#include "controlmsg.h" #include "controlmsg.h"

View file

@ -6,16 +6,9 @@
#define CURSOR_POS_CHECK 50 #define CURSOR_POS_CHECK 50
InputConvertGame::InputConvertGame(Controller* controller) InputConvertGame::InputConvertGame(Controller *controller) : InputConvertNormal(controller) {}
: InputConvertNormal(controller)
{
} InputConvertGame::~InputConvertGame() {}
InputConvertGame::~InputConvertGame()
{
}
void InputConvertGame::mouseEvent(const QMouseEvent *from, const QSize &frameSize, const QSize &showSize) void InputConvertGame::mouseEvent(const QMouseEvent *from, const QSize &frameSize, const QSize &showSize)
{ {
@ -70,9 +63,7 @@ void InputConvertGame::keyEvent(const QKeyEvent *from, const QSize& frameSize, c
const KeyMap::KeyMapNode &node = m_keyMap.getKeyMapNodeKey(from->key()); const KeyMap::KeyMapNode &node = m_keyMap.getKeyMapNodeKey(from->key());
// 处理特殊按键:可以在按键映射和普通映射间切换的按键 // 处理特殊按键:可以在按键映射和普通映射间切换的按键
if (m_needSwitchGameAgain if (m_needSwitchGameAgain && KeyMap::KMT_CLICK == node.type && node.data.click.switchMap) {
&& KeyMap::KMT_CLICK == node.type
&& node.data.click.switchMap) {
updateSize(frameSize, showSize); updateSize(frameSize, showSize);
// Qt::Key_Tab Qt::Key_M for PUBG mobile // Qt::Key_Tab Qt::Key_M for PUBG mobile
processKeyClick(node.data.click.keyNode.pos, false, node.data.click.switchMap, from); processKeyClick(node.data.click.keyNode.pos, false, node.data.click.switchMap, from);
@ -151,11 +142,8 @@ void InputConvertGame::sendTouchEvent(int id, QPointF pos, AndroidMotioneventAct
if (!controlMsg) { if (!controlMsg) {
return; return;
} }
controlMsg->setInjectTouchMsgData(static_cast<quint64>(id), controlMsg->setInjectTouchMsgData(
action, static_cast<quint64>(id), action, static_cast<AndroidMotioneventButtons>(0), QRect(calcFrameAbsolutePos(pos).toPoint(), m_frameSize), 1.0f);
static_cast<AndroidMotioneventButtons>(0),
QRect(calcFrameAbsolutePos(pos).toPoint(),m_frameSize),
1.0f);
sendControlMsg(controlMsg); sendControlMsg(controlMsg);
} }
@ -268,8 +256,7 @@ void InputConvertGame::processSteerWheel(const KeyMap::KeyMapNode &node, const Q
// -------- key event -------- // -------- key event --------
void InputConvertGame::processKeyClick( void InputConvertGame::processKeyClick(const QPointF &clickPos, bool clickTwice, bool switchMap, const QKeyEvent *from)
const QPointF& clickPos, bool clickTwice, bool switchMap, const QKeyEvent *from)
{ {
if (switchMap && QEvent::KeyRelease == from->type()) { if (switchMap && QEvent::KeyRelease == from->type()) {
m_needSwitchGameAgain = !m_needSwitchGameAgain; m_needSwitchGameAgain = !m_needSwitchGameAgain;
@ -353,9 +340,7 @@ bool InputConvertGame::processMouseMove(const QMouseEvent *from)
m_ctrlMouseMove.lastConverPos.setX(m_ctrlMouseMove.lastConverPos.x() + distance.x() / m_showSize.width()); m_ctrlMouseMove.lastConverPos.setX(m_ctrlMouseMove.lastConverPos.x() + distance.x() / m_showSize.width());
m_ctrlMouseMove.lastConverPos.setY(m_ctrlMouseMove.lastConverPos.y() + distance.y() / m_showSize.height()); m_ctrlMouseMove.lastConverPos.setY(m_ctrlMouseMove.lastConverPos.y() + distance.y() / m_showSize.height());
if (m_ctrlMouseMove.lastConverPos.x() < 0.1 if (m_ctrlMouseMove.lastConverPos.x() < 0.1 || m_ctrlMouseMove.lastConverPos.x() > 0.8 || m_ctrlMouseMove.lastConverPos.y() < 0.1
|| m_ctrlMouseMove.lastConverPos.x() > 0.8
|| m_ctrlMouseMove.lastConverPos.y() < 0.1
|| m_ctrlMouseMove.lastConverPos.y() > 0.8) { || m_ctrlMouseMove.lastConverPos.y() > 0.8) {
mouseMoveStopTouch(); mouseMoveStopTouch();
mouseMoveStartTouch(from); mouseMoveStartTouch(from);

View file

@ -67,7 +67,8 @@ private:
KeyMap m_keyMap; KeyMap m_keyMap;
// steer wheel // steer wheel
struct { struct
{
// the first key pressed // the first key pressed
int touchKey = Qt::Key_unknown; int touchKey = Qt::Key_unknown;
bool pressedUp = false; bool pressedUp = false;
@ -79,7 +80,8 @@ private:
} m_ctrlSteerWheel; } m_ctrlSteerWheel;
// mouse move // mouse move
struct { struct
{
QPointF lastConverPos; QPointF lastConverPos;
QPointF lastPos = { 0.0, 0.0 }; QPointF lastPos = { 0.0, 0.0 };
bool touching = false; bool touching = false;

View file

@ -2,16 +2,9 @@
#include "inputconvertnormal.h" #include "inputconvertnormal.h"
InputConvertNormal::InputConvertNormal(Controller* controller) InputConvertNormal::InputConvertNormal(Controller *controller) : InputConvertBase(controller) {}
: InputConvertBase(controller)
{
} InputConvertNormal::~InputConvertNormal() {}
InputConvertNormal::~InputConvertNormal()
{
}
void InputConvertNormal::mouseEvent(const QMouseEvent *from, const QSize &frameSize, const QSize &showSize) void InputConvertNormal::mouseEvent(const QMouseEvent *from, const QSize &frameSize, const QSize &showSize)
{ {

View file

@ -1,25 +1,18 @@
#include <QFile>
#include <QJsonDocument>
#include <QJsonArray>
#include <QMetaEnum>
#include <QFileInfo>
#include <QCoreApplication> #include <QCoreApplication>
#include <QDebug> #include <QDebug>
#include <QFile>
#include <QFileInfo>
#include <QJsonArray>
#include <QJsonDocument>
#include <QMetaEnum>
#include "keymap.h" #include "keymap.h"
QString KeyMap::s_keyMapPath = ""; QString KeyMap::s_keyMapPath = "";
KeyMap::KeyMap(QObject *parent) KeyMap::KeyMap(QObject *parent) : QObject(parent) {}
: QObject(parent)
{
} KeyMap::~KeyMap() {}
KeyMap::~KeyMap()
{
}
const QString &KeyMap::getKeyMapPath() const QString &KeyMap::getKeyMapPath()
{ {
@ -110,8 +103,7 @@ void KeyMap::loadKeyMap(const QString &json)
KeyMap::KeyMapType type = getItemKeyMapType(node, "type"); KeyMap::KeyMapType type = getItemKeyMapType(node, "type");
switch (type) { switch (type) {
case KeyMap::KMT_CLICK: case KeyMap::KMT_CLICK: {
{
// safe check // safe check
if (!checkForClick(node)) { if (!checkForClick(node)) {
qWarning() << "json error: keyMapNodes node format error"; qWarning() << "json error: keyMapNodes node format error";
@ -129,10 +121,8 @@ void KeyMap::loadKeyMap(const QString &json)
keyMapNode.data.click.keyNode.pos = getItemPos(node, "pos"); keyMapNode.data.click.keyNode.pos = getItemPos(node, "pos");
keyMapNode.data.click.switchMap = getItemBool(node, "switchMap"); keyMapNode.data.click.switchMap = getItemBool(node, "switchMap");
m_keyMapNodes.push_back(keyMapNode); m_keyMapNodes.push_back(keyMapNode);
} } break;
break; case KeyMap::KMT_CLICK_TWICE: {
case KeyMap::KMT_CLICK_TWICE:
{
// safe check // safe check
if (!checkForClickTwice(node)) { if (!checkForClickTwice(node)) {
qWarning() << "json error: keyMapNodes node format error"; qWarning() << "json error: keyMapNodes node format error";
@ -151,10 +141,8 @@ void KeyMap::loadKeyMap(const QString &json)
keyMapNode.data.click.keyNode.pos = getItemPos(node, "pos"); keyMapNode.data.click.keyNode.pos = getItemPos(node, "pos");
keyMapNode.data.click.switchMap = getItemBool(node, "switchMap"); keyMapNode.data.click.switchMap = getItemBool(node, "switchMap");
m_keyMapNodes.push_back(keyMapNode); m_keyMapNodes.push_back(keyMapNode);
} } break;
break; case KeyMap::KMT_STEER_WHEEL: {
case KeyMap::KMT_STEER_WHEEL:
{
// safe check // safe check
if (!checkForSteerWhell(node)) { if (!checkForSteerWhell(node)) {
qWarning() << "json error: keyMapNodes node format error"; qWarning() << "json error: keyMapNodes node format error";
@ -164,8 +152,7 @@ void KeyMap::loadKeyMap(const QString &json)
QPair<ActionType, int> rightKey = getItemKey(node, "rightKey"); QPair<ActionType, int> rightKey = getItemKey(node, "rightKey");
QPair<ActionType, int> upKey = getItemKey(node, "upKey"); QPair<ActionType, int> upKey = getItemKey(node, "upKey");
QPair<ActionType, int> downKey = getItemKey(node, "downKey"); QPair<ActionType, int> downKey = getItemKey(node, "downKey");
if (leftKey.first == AT_INVALID || rightKey.first == AT_INVALID if (leftKey.first == AT_INVALID || rightKey.first == AT_INVALID || upKey.first == AT_INVALID || downKey.first == AT_INVALID) {
|| upKey.first == AT_INVALID || downKey.first == AT_INVALID) {
if (leftKey.first == AT_INVALID) { if (leftKey.first == AT_INVALID) {
qWarning() << "json error: keyMapNodes node invalid key: " << node.value("leftKey").toString(); qWarning() << "json error: keyMapNodes node invalid key: " << node.value("leftKey").toString();
} }
@ -184,26 +171,16 @@ void KeyMap::loadKeyMap(const QString &json)
KeyMapNode keyMapNode; KeyMapNode keyMapNode;
keyMapNode.type = type; keyMapNode.type = type;
keyMapNode.data.steerWheel.left = { leftKey.first, leftKey.second, keyMapNode.data.steerWheel.left = { leftKey.first, leftKey.second, QPointF(0, 0), QPointF(0, 0), getItemDouble(node, "leftOffset") };
QPointF(0, 0), QPointF(0, 0), keyMapNode.data.steerWheel.right = { rightKey.first, rightKey.second, QPointF(0, 0), QPointF(0, 0), getItemDouble(node, "rightOffset") };
getItemDouble(node, "leftOffset") }; keyMapNode.data.steerWheel.up = { upKey.first, upKey.second, QPointF(0, 0), QPointF(0, 0), getItemDouble(node, "upOffset") };
keyMapNode.data.steerWheel.right = { rightKey.first, rightKey.second, keyMapNode.data.steerWheel.down = { downKey.first, downKey.second, QPointF(0, 0), QPointF(0, 0), getItemDouble(node, "downOffset") };
QPointF(0, 0), QPointF(0, 0),
getItemDouble(node, "rightOffset") };
keyMapNode.data.steerWheel.up = { upKey.first, upKey.second,
QPointF(0, 0), QPointF(0, 0),
getItemDouble(node, "upOffset") };
keyMapNode.data.steerWheel.down = { downKey.first, downKey.second,
QPointF(0, 0), QPointF(0, 0),
getItemDouble(node, "downOffset") };
keyMapNode.data.steerWheel.centerPos = getItemPos(node, "centerPos"); keyMapNode.data.steerWheel.centerPos = getItemPos(node, "centerPos");
m_idxSteerWheel = m_keyMapNodes.size(); m_idxSteerWheel = m_keyMapNodes.size();
m_keyMapNodes.push_back(keyMapNode); m_keyMapNodes.push_back(keyMapNode);
} } break;
break; case KeyMap::KMT_DRAG: {
case KeyMap::KMT_DRAG:
{
// safe check // safe check
if (!checkForDrag(node)) { if (!checkForDrag(node)) {
qWarning() << "json error: keyMapNodes node format error"; qWarning() << "json error: keyMapNodes node format error";
@ -292,20 +269,15 @@ void KeyMap::makeReverseMap()
for (int i = 0; i < m_keyMapNodes.size(); ++i) { for (int i = 0; i < m_keyMapNodes.size(); ++i) {
auto &node = m_keyMapNodes[i]; auto &node = m_keyMapNodes[i];
switch (node.type) { switch (node.type) {
case KMT_CLICK: case KMT_CLICK: {
{
QMultiHash<int, KeyMapNode *> &m = node.data.click.keyNode.type == AT_KEY ? m_rmapKey : m_rmapMouse; QMultiHash<int, KeyMapNode *> &m = node.data.click.keyNode.type == AT_KEY ? m_rmapKey : m_rmapMouse;
m.insert(node.data.click.keyNode.key, &node); m.insert(node.data.click.keyNode.key, &node);
} } break;
break; case KMT_CLICK_TWICE: {
case KMT_CLICK_TWICE:
{
QMultiHash<int, KeyMapNode *> &m = node.data.clickTwice.keyNode.type == AT_KEY ? m_rmapKey : m_rmapMouse; QMultiHash<int, KeyMapNode *> &m = node.data.clickTwice.keyNode.type == AT_KEY ? m_rmapKey : m_rmapMouse;
m.insert(node.data.clickTwice.keyNode.key, &node); m.insert(node.data.clickTwice.keyNode.key, &node);
} } break;
break; case KMT_STEER_WHEEL: {
case KMT_STEER_WHEEL:
{
QMultiHash<int, KeyMapNode *> &ml = node.data.steerWheel.left.type == AT_KEY ? m_rmapKey : m_rmapMouse; QMultiHash<int, KeyMapNode *> &ml = node.data.steerWheel.left.type == AT_KEY ? m_rmapKey : m_rmapMouse;
ml.insert(node.data.steerWheel.left.key, &node); ml.insert(node.data.steerWheel.left.key, &node);
QMultiHash<int, KeyMapNode *> &mr = node.data.steerWheel.right.type == AT_KEY ? m_rmapKey : m_rmapMouse; QMultiHash<int, KeyMapNode *> &mr = node.data.steerWheel.right.type == AT_KEY ? m_rmapKey : m_rmapMouse;
@ -314,14 +286,11 @@ void KeyMap::makeReverseMap()
mu.insert(node.data.steerWheel.up.key, &node); mu.insert(node.data.steerWheel.up.key, &node);
QMultiHash<int, KeyMapNode *> &md = node.data.steerWheel.down.type == AT_KEY ? m_rmapKey : m_rmapMouse; QMultiHash<int, KeyMapNode *> &md = node.data.steerWheel.down.type == AT_KEY ? m_rmapKey : m_rmapMouse;
md.insert(node.data.steerWheel.down.key, &node); md.insert(node.data.steerWheel.down.key, &node);
} } break;
break; case KMT_DRAG: {
case KMT_DRAG:
{
QMultiHash<int, KeyMapNode *> &m = node.data.drag.keyNode.type == AT_KEY ? m_rmapKey : m_rmapMouse; QMultiHash<int, KeyMapNode *> &m = node.data.drag.keyNode.type == AT_KEY ? m_rmapKey : m_rmapMouse;
m.insert(node.data.drag.keyNode.key, &node); m.insert(node.data.drag.keyNode.key, &node);
} } break;
break;
default: default:
break; break;
} }
@ -398,8 +367,7 @@ bool KeyMap::checkItemPos(const QJsonObject& node, const QString& name)
{ {
if (node.contains(name) && node.value(name).isObject()) { if (node.contains(name) && node.value(name).isObject()) {
QJsonObject pos = node.value(name).toObject(); QJsonObject pos = node.value(name).toObject();
return pos.contains("x") && pos.value("x").isDouble() return pos.contains("x") && pos.value("x").isDouble() && pos.contains("y") && pos.value("y").isDouble();
&& pos.contains("y") && pos.value("y").isDouble();
} }
return false; return false;
} }
@ -416,16 +384,12 @@ bool KeyMap::checkForClickTwice(const QJsonObject& node)
bool KeyMap::checkForSteerWhell(const QJsonObject &node) bool KeyMap::checkForSteerWhell(const QJsonObject &node)
{ {
return checkItemString(node, "leftKey") && checkItemString(node, "rightKey") return checkItemString(node, "leftKey") && checkItemString(node, "rightKey") && checkItemString(node, "upKey") && checkItemString(node, "downKey")
&& checkItemString(node, "upKey") && checkItemString(node, "downKey") && checkItemDouble(node, "leftOffset") && checkItemDouble(node, "rightOffset") && checkItemDouble(node, "upOffset")
&& checkItemDouble(node, "leftOffset") && checkItemDouble(node, "rightOffset") && checkItemDouble(node, "downOffset") && checkItemPos(node, "centerPos");
&& checkItemDouble(node, "upOffset") && checkItemDouble(node, "downOffset")
&& checkItemPos(node, "centerPos");
} }
bool KeyMap::checkForDrag(const QJsonObject &node) bool KeyMap::checkForDrag(const QJsonObject &node)
{ {
return checkItemString(node, "key") return checkItemString(node, "key") && checkItemPos(node, "startPos") && checkItemPos(node, "endPos");
&& checkItemPos(node, "startPos") && checkItemPos(node, "endPos");
} }

View file

@ -1,19 +1,20 @@
#ifndef KEYMAP_H #ifndef KEYMAP_H
#define KEYMAP_H #define KEYMAP_H
#include <QObject> #include <QJsonObject>
#include <QPointF>
#include <QVector>
#include <QRectF>
#include <QPair>
#include <QMetaEnum> #include <QMetaEnum>
#include <QMultiHash> #include <QMultiHash>
#include <QJsonObject> #include <QObject>
#include <QPair>
#include <QPointF>
#include <QRectF>
#include <QVector>
class KeyMap : public QObject class KeyMap : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
enum KeyMapType { enum KeyMapType
{
KMT_INVALID = -1, KMT_INVALID = -1,
KMT_CLICK = 0, KMT_CLICK = 0,
KMT_CLICK_TWICE, KMT_CLICK_TWICE,
@ -23,53 +24,58 @@ public:
}; };
Q_ENUM(KeyMapType) Q_ENUM(KeyMapType)
enum ActionType { enum ActionType
{
AT_INVALID = -1, AT_INVALID = -1,
AT_KEY = 0, AT_KEY = 0,
AT_MOUSE = 1, AT_MOUSE = 1,
}; };
Q_ENUM(ActionType) Q_ENUM(ActionType)
struct KeyNode { struct KeyNode
{
ActionType type = AT_INVALID; ActionType type = AT_INVALID;
int key = Qt::Key_unknown; int key = Qt::Key_unknown;
QPointF pos = QPointF(0, 0); // normal key QPointF pos = QPointF(0, 0); // normal key
QPointF extendPos = QPointF(0, 0); // for drag QPointF extendPos = QPointF(0, 0); // for drag
double extendOffset = 0.0; // for steerWheel double extendOffset = 0.0; // for steerWheel
KeyNode(ActionType type = AT_INVALID, KeyNode(
ActionType type = AT_INVALID,
int key = Qt::Key_unknown, int key = Qt::Key_unknown,
QPointF pos = QPointF(0, 0), QPointF pos = QPointF(0, 0),
QPointF extendPos = QPointF(0, 0), QPointF extendPos = QPointF(0, 0),
double extendOffset = 0.0) double extendOffset = 0.0)
: type(type) : type(type), key(key), pos(pos), extendPos(extendPos), extendOffset(extendOffset)
, key(key)
, pos(pos)
, extendPos(extendPos)
, extendOffset(extendOffset)
{ {
} }
}; };
struct KeyMapNode { struct KeyMapNode
{
KeyMapType type = KMT_INVALID; KeyMapType type = KMT_INVALID;
union DATA { union DATA
struct { {
struct
{
KeyNode keyNode; KeyNode keyNode;
bool switchMap = false; bool switchMap = false;
} click; } click;
struct { struct
{
KeyNode keyNode; KeyNode keyNode;
} clickTwice; } clickTwice;
struct { struct
{
QPointF centerPos = { 0.0, 0.0 }; QPointF centerPos = { 0.0, 0.0 };
KeyNode left, right, up, down; KeyNode left, right, up, down;
} steerWheel; } steerWheel;
struct { struct
{
KeyNode keyNode; KeyNode keyNode;
} drag; } drag;
struct { struct
{
QPointF startPos = { 0.0, 0.0 }; QPointF startPos = { 0.0, 0.0 };
int speedRatio = 1; int speedRatio = 1;
} mouseMove; } mouseMove;

View file

@ -1,17 +1,13 @@
#include <QDebug> #include <QDebug>
#include "devicemsg.h"
#include "bufferutil.h" #include "bufferutil.h"
#include "devicemsg.h"
DeviceMsg::DeviceMsg(QObject *parent) : QObject(parent) DeviceMsg::DeviceMsg(QObject *parent) : QObject(parent) {}
{
}
DeviceMsg::~DeviceMsg() DeviceMsg::~DeviceMsg()
{ {
if (DMT_GET_CLIPBOARD == m_data.type if (DMT_GET_CLIPBOARD == m_data.type && Q_NULLPTR != m_data.clipboardMsg.text) {
&& Q_NULLPTR != m_data.clipboardMsg.text) {
delete m_data.clipboardMsg.text; delete m_data.clipboardMsg.text;
m_data.clipboardMsg.text = Q_NULLPTR; m_data.clipboardMsg.text = Q_NULLPTR;
} }

View file

@ -11,7 +11,8 @@ class DeviceMsg : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
enum DeviceMsgType { enum DeviceMsgType
{
DMT_NULL = -1, DMT_NULL = -1,
// 和服务端对应 // 和服务端对应
DMT_GET_CLIPBOARD = 0, DMT_GET_CLIPBOARD = 0,
@ -25,10 +26,13 @@ public:
qint32 deserialize(QByteArray &byteArray); qint32 deserialize(QByteArray &byteArray);
private: private:
struct DeviceMsgData { struct DeviceMsgData
{
DeviceMsgType type = DMT_NULL; DeviceMsgType type = DMT_NULL;
union { union
struct { {
struct
{
char *text = Q_NULLPTR; char *text = Q_NULLPTR;
} clipboardMsg; } clipboardMsg;
}; };

View file

@ -1,18 +1,13 @@
#include <QTcpSocket>
#include <QApplication> #include <QApplication>
#include <QClipboard> #include <QClipboard>
#include <QTcpSocket> #include <QTcpSocket>
#include "receiver.h"
#include "devicemsg.h" #include "devicemsg.h"
#include "receiver.h"
Receiver::Receiver(QObject *parent) : QObject(parent) Receiver::Receiver(QObject *parent) : QObject(parent) {}
{
}
Receiver::~Receiver() Receiver::~Receiver() {}
{
}
void Receiver::setControlSocket(QTcpSocket *controlSocket) void Receiver::setControlSocket(QTcpSocket *controlSocket)
{ {
@ -44,8 +39,7 @@ void Receiver::onReadyRead()
void Receiver::processMsg(DeviceMsg *deviceMsg) void Receiver::processMsg(DeviceMsg *deviceMsg)
{ {
switch (deviceMsg->type()) { switch (deviceMsg->type()) {
case DeviceMsg::DMT_GET_CLIPBOARD: case DeviceMsg::DMT_GET_CLIPBOARD: {
{
qInfo("Device clipboard copied"); qInfo("Device clipboard copied");
QClipboard *board = QApplication::clipboard(); QClipboard *board = QApplication::clipboard();
QString text; QString text;

View file

@ -2,15 +2,9 @@
#include "avframeconvert.h" #include "avframeconvert.h"
AVFrameConvert::AVFrameConvert() AVFrameConvert::AVFrameConvert() {}
{
} AVFrameConvert::~AVFrameConvert() {}
AVFrameConvert::~AVFrameConvert()
{
}
void AVFrameConvert::setSrcFrameInfo(int srcWidth, int srcHeight, AVPixelFormat srcFormat) void AVFrameConvert::setSrcFrameInfo(int srcWidth, int srcHeight, AVPixelFormat srcFormat)
{ {
@ -46,8 +40,7 @@ bool AVFrameConvert::init()
if (m_convertCtx) { if (m_convertCtx) {
return true; return true;
} }
m_convertCtx = sws_getContext(m_srcWidth, m_srcHeight, m_srcFormat, m_dstWidth, m_dstHeight, m_dstFormat, m_convertCtx = sws_getContext(m_srcWidth, m_srcHeight, m_srcFormat, m_dstWidth, m_dstHeight, m_dstFormat, SWS_BICUBIC, Q_NULLPTR, Q_NULLPTR, Q_NULLPTR);
SWS_BICUBIC, Q_NULLPTR, Q_NULLPTR, Q_NULLPTR);
if (!m_convertCtx) { if (!m_convertCtx) {
return false; return false;
} }
@ -72,10 +65,8 @@ bool AVFrameConvert::convert(const AVFrame* srcFrame, AVFrame* dstFrame)
if (!m_convertCtx || !srcFrame || !dstFrame) { if (!m_convertCtx || !srcFrame || !dstFrame) {
return false; return false;
} }
qint32 ret = sws_scale(m_convertCtx, qint32 ret
static_cast<const uint8_t* const*>(srcFrame->data), = sws_scale(m_convertCtx, static_cast<const uint8_t *const *>(srcFrame->data), srcFrame->linesize, 0, m_srcHeight, dstFrame->data, dstFrame->linesize);
srcFrame->linesize, 0, m_srcHeight, dstFrame->data,
dstFrame->linesize);
if (0 == ret) { if (0 == ret) {
return false; return false;
} }

View file

@ -5,8 +5,8 @@
extern "C" extern "C"
{ {
#include "libavcodec/avcodec.h" #include "libavcodec/avcodec.h"
#include "libswscale/swscale.h"
#include "libavutil/frame.h" #include "libavutil/frame.h"
#include "libswscale/swscale.h"
} }
class AVFrameConvert class AVFrameConvert

View file

@ -1,20 +1,12 @@
#include <QDebug> #include <QDebug>
#include "compat.h" #include "compat.h"
#include "videobuffer.h"
#include "decoder.h" #include "decoder.h"
#include "videobuffer.h"
Decoder::Decoder(VideoBuffer* vb, QObject *parent) Decoder::Decoder(VideoBuffer *vb, QObject *parent) : QObject(parent), m_vb(vb) {}
: QObject(parent)
, m_vb(vb)
{
} Decoder::~Decoder() {}
Decoder::~Decoder()
{
}
bool Decoder::open(const AVCodec *codec) bool Decoder::open(const AVCodec *codec)
{ {

View file

@ -1,17 +1,11 @@
#include <QTimerEvent>
#include <QDebug> #include <QDebug>
#include <QTimerEvent>
#include "fpscounter.h" #include "fpscounter.h"
FpsCounter::FpsCounter(QObject* parent) : QObject(parent) FpsCounter::FpsCounter(QObject *parent) : QObject(parent) {}
{
} FpsCounter::~FpsCounter() {}
FpsCounter::~FpsCounter()
{
}
void FpsCounter::start() void FpsCounter::start()
{ {

View file

@ -1,19 +1,13 @@
#include "videobuffer.h" #include "videobuffer.h"
extern "C" extern "C"
{ {
#include "libavutil/avutil.h"
#include "libavformat/avformat.h" #include "libavformat/avformat.h"
#include "libavutil/avutil.h"
} }
VideoBuffer::VideoBuffer() VideoBuffer::VideoBuffer() {}
{
} VideoBuffer::~VideoBuffer() {}
VideoBuffer::~VideoBuffer()
{
}
bool VideoBuffer::init(bool renderExpiredFrames) bool VideoBuffer::init(bool renderExpiredFrames)
{ {

View file

@ -1,27 +1,25 @@
#include <QTimer>
#include <QMessageBox>
#include <QDir> #include <QDir>
#include <QMessageBox>
#include <QTimer>
#include "avframeconvert.h"
#include "config.h"
#include "controller.h"
#include "decoder.h"
#include "device.h" #include "device.h"
#include "filehandler.h"
#include "mousetap/mousetap.h"
#include "recorder.h" #include "recorder.h"
#include "server.h" #include "server.h"
#include "videobuffer.h"
#include "decoder.h"
#include "filehandler.h"
#include "stream.h" #include "stream.h"
#include "videobuffer.h"
#include "videoform.h" #include "videoform.h"
#include "controller.h"
#include "config.h"
#include "avframeconvert.h"
#include "mousetap/mousetap.h"
extern "C" extern "C"
{ {
#include "libavutil/imgutils.h" #include "libavutil/imgutils.h"
} }
Device::Device(DeviceParams params, QObject *parent) Device::Device(DeviceParams params, QObject *parent) : QObject(parent), m_params(params)
: QObject(parent)
, m_params(params)
{ {
if (!params.display && m_params.recordFileName.trimmed().isEmpty()) { if (!params.display && m_params.recordFileName.trimmed().isEmpty()) {
qCritical("not display must be recorded"); qCritical("not display must be recorded");
@ -266,14 +264,19 @@ void Device::initSignals()
if (m_decoder && m_vb) { if (m_decoder && m_vb) {
// must be Qt::QueuedConnection, ui update must be main thread // must be Qt::QueuedConnection, ui update must be main thread
connect(m_decoder, &Decoder::onNewFrame, this, [this](){ connect(
m_decoder,
&Decoder::onNewFrame,
this,
[this]() {
m_vb->lock(); m_vb->lock();
const AVFrame *frame = m_vb->consumeRenderedFrame(); const AVFrame *frame = m_vb->consumeRenderedFrame();
if (m_videoForm) { if (m_videoForm) {
m_videoForm->updateRender(frame); m_videoForm->updateRender(frame);
} }
m_vb->unLock(); m_vb->unLock();
},Qt::QueuedConnection); },
Qt::QueuedConnection);
} }
} }

View file

@ -22,7 +22,8 @@ class Device : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
struct DeviceParams { struct DeviceParams
{
QString recordFileName = ""; // 视频录制文件名 QString recordFileName = ""; // 视频录制文件名
QString serial = ""; // 设备序列号 QString serial = ""; // 设备序列号
quint16 localPort = 27183; // reverse时本地监听端口 quint16 localPort = 27183; // reverse时本地监听端口
@ -35,7 +36,8 @@ public:
QString gameScript = ""; // 游戏映射脚本 QString gameScript = ""; // 游戏映射脚本
bool renderExpiredFrames = false; // 是否渲染延迟视频帧 bool renderExpiredFrames = false; // 是否渲染延迟视频帧
}; };
enum GroupControlState { enum GroupControlState
{
GCS_FREE = 0, GCS_FREE = 0,
GCS_HOST, GCS_HOST,
GCS_CLIENT, GCS_CLIENT,

View file

@ -1,7 +1,6 @@
#include "filehandler.h" #include "filehandler.h"
FileHandler::FileHandler(QObject *parent) FileHandler::FileHandler(QObject *parent) : QObject(parent)
: QObject (parent)
{ {
connect(&m_adb, &AdbProcess::adbProcessResult, this, [this](AdbProcess::ADB_EXEC_RESULT processResult) { connect(&m_adb, &AdbProcess::adbProcessResult, this, [this](AdbProcess::ADB_EXEC_RESULT processResult) {
switch (processResult) { switch (processResult) {
@ -19,10 +18,7 @@ FileHandler::FileHandler(QObject *parent)
}); });
} }
FileHandler::~FileHandler() FileHandler::~FileHandler() {}
{
}
void FileHandler::onPushFileRequest(const QString &serial, const QString &file, const QString &devicePath) void FileHandler::onPushFileRequest(const QString &serial, const QString &file, const QString &devicePath)
{ {

View file

@ -8,7 +8,8 @@ class FileHandler : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
enum FILE_HANDLER_RESULT { enum FILE_HANDLER_RESULT
{
FAR_IS_RUNNING, // 正在执行 FAR_IS_RUNNING, // 正在执行
FAR_SUCCESS_EXEC, // 执行成功 FAR_SUCCESS_EXEC, // 执行成功
FAR_ERROR_EXEC, // 执行失败 FAR_ERROR_EXEC, // 执行失败

View file

@ -1,24 +1,18 @@
#include <QCoreApplication>
#include <QDebug> #include <QDebug>
#include <QFileInfo> #include <QFileInfo>
#include <QCoreApplication>
#include "compat.h" #include "compat.h"
#include "recorder.h" #include "recorder.h"
static const AVRational SCRCPY_TIME_BASE = { 1, 1000000 }; // timestamps in us static const AVRational SCRCPY_TIME_BASE = { 1, 1000000 }; // timestamps in us
Recorder::Recorder(const QString& fileName, QObject* parent) Recorder::Recorder(const QString &fileName, QObject *parent) : QThread(parent), m_fileName(fileName), m_format(guessRecordFormat(fileName)) {}
: QThread(parent)
, m_fileName(fileName)
, m_format(guessRecordFormat(fileName))
{
}
Recorder::~Recorder() Recorder::~Recorder() {}
{
}
AVPacket* Recorder::packetNew(const AVPacket *packet) { AVPacket *Recorder::packetNew(const AVPacket *packet)
{
AVPacket *rec = new AVPacket; AVPacket *rec = new AVPacket;
if (!rec) { if (!rec) {
return Q_NULLPTR; return Q_NULLPTR;
@ -34,7 +28,8 @@ AVPacket* Recorder::packetNew(const AVPacket *packet) {
return rec; return rec;
} }
void Recorder::packetDelete(AVPacket* packet) { void Recorder::packetDelete(AVPacket *packet)
{
av_packet_unref(packet); av_packet_unref(packet);
delete packet; delete packet;
} }
@ -80,8 +75,7 @@ bool Recorder::open(const AVCodec* inputCodec)
m_formatCtx->oformat = (AVOutputFormat *)format; m_formatCtx->oformat = (AVOutputFormat *)format;
QString comment = "Recorded by QtScrcpy " + QCoreApplication::applicationVersion(); QString comment = "Recorded by QtScrcpy " + QCoreApplication::applicationVersion();
av_dict_set(&m_formatCtx->metadata, "comment", av_dict_set(&m_formatCtx->metadata, "comment", comment.toUtf8(), 0);
comment.toUtf8(), 0);
AVStream *outStream = avformat_new_stream(m_formatCtx, inputCodec); AVStream *outStream = avformat_new_stream(m_formatCtx, inputCodec);
if (!outStream) { if (!outStream) {
@ -104,8 +98,7 @@ bool Recorder::open(const AVCodec* inputCodec)
outStream->codec->height = m_declaredFrameSize.height(); outStream->codec->height = m_declaredFrameSize.height();
#endif #endif
int ret = avio_open(&m_formatCtx->pb, m_fileName.toUtf8().toStdString().c_str(), int ret = avio_open(&m_formatCtx->pb, m_fileName.toUtf8().toStdString().c_str(), AVIO_FLAG_WRITE);
AVIO_FLAG_WRITE);
if (ret < 0) { if (ret < 0) {
char errorbuf[255] = { 0 }; char errorbuf[255] = { 0 };
av_strerror(ret, errorbuf, 254); av_strerror(ret, errorbuf, 254);
@ -217,9 +210,12 @@ void Recorder::recorderRescalePacket(AVPacket* packet)
QString Recorder::recorderGetFormatName(Recorder::RecorderFormat format) QString Recorder::recorderGetFormatName(Recorder::RecorderFormat format)
{ {
switch (format) { switch (format) {
case RECORDER_FORMAT_MP4: return "mp4"; case RECORDER_FORMAT_MP4:
case RECORDER_FORMAT_MKV: return "matroska"; return "mp4";
default: return ""; case RECORDER_FORMAT_MKV:
return "matroska";
default:
return "";
} }
} }
@ -240,7 +236,8 @@ Recorder::RecorderFormat Recorder::guessRecordFormat(const QString &fileName)
return Recorder::RECORDER_FORMAT_NULL; return Recorder::RECORDER_FORMAT_NULL;
} }
void Recorder::run() { void Recorder::run()
{
for (;;) { for (;;) {
AVPacket *rec = Q_NULLPTR; AVPacket *rec = Q_NULLPTR;
{ {
@ -281,8 +278,7 @@ void Recorder::run() {
} }
// config packets have no PTS, we must ignore them // config packets have no PTS, we must ignore them
if (rec->pts != AV_NOPTS_VALUE if (rec->pts != AV_NOPTS_VALUE && previous->pts != AV_NOPTS_VALUE) {
&& previous->pts != AV_NOPTS_VALUE) {
// we now know the duration of the previous packet // we now know the duration of the previous packet
previous->duration = rec->pts - previous->pts; previous->duration = rec->pts - previous->pts;
} }
@ -302,18 +298,21 @@ void Recorder::run() {
qDebug("Recorder thread ended"); qDebug("Recorder thread ended");
} }
bool Recorder::startRecorder() { bool Recorder::startRecorder()
{
start(); start();
return true; return true;
} }
void Recorder::stopRecorder() { void Recorder::stopRecorder()
{
QMutexLocker locker(&m_mutex); QMutexLocker locker(&m_mutex);
m_stopped = true; m_stopped = true;
m_recvDataCond.wakeOne(); m_recvDataCond.wakeOne();
} }
bool Recorder::push(const AVPacket *packet) { bool Recorder::push(const AVPacket *packet)
{
QMutexLocker locker(&m_mutex); QMutexLocker locker(&m_mutex);
Q_ASSERT(!m_stopped); Q_ASSERT(!m_stopped);

View file

@ -1,11 +1,11 @@
#ifndef RECORDER_H #ifndef RECORDER_H
#define RECORDER_H #define RECORDER_H
#include <QString>
#include <QSize>
#include <QThread>
#include <QMutex> #include <QMutex>
#include <QWaitCondition>
#include <QQueue> #include <QQueue>
#include <QSize>
#include <QString>
#include <QThread>
#include <QWaitCondition>
extern "C" extern "C"
{ {
@ -16,7 +16,8 @@ class Recorder : public QThread
{ {
Q_OBJECT Q_OBJECT
public: public:
enum RecorderFormat { enum RecorderFormat
{
RECORDER_FORMAT_NULL = 0, RECORDER_FORMAT_NULL = 0,
RECORDER_FORMAT_MP4, RECORDER_FORMAT_MP4,
RECORDER_FORMAT_MKV, RECORDER_FORMAT_MKV,

View file

@ -14,18 +14,30 @@ static const GLfloat coordinate[] = {
// GL_TRIANGLE_STRIP的绘制方式 // GL_TRIANGLE_STRIP的绘制方式
// 使用前3个坐标绘制一个三角形使用后三个坐标绘制一个三角形正好为一个矩形 // 使用前3个坐标绘制一个三角形使用后三个坐标绘制一个三角形正好为一个矩形
// x y z // x y z
-1.0f, -1.0f, 0.0f, -1.0f,
1.0f, -1.0f, 0.0f, -1.0f,
-1.0f, 1.0f, 0.0f, 0.0f,
1.0f, 1.0f, 0.0f, 1.0f,
-1.0f,
0.0f,
-1.0f,
1.0f,
0.0f,
1.0f,
1.0f,
0.0f,
// 纹理坐标存储4个xy坐标 // 纹理坐标存储4个xy坐标
// 坐标范围为[0,1],左下角为 0,0 // 坐标范围为[0,1],左下角为 0,0
// TODO 为什么这个顺序指定四个顶点?顶点坐标和纹理坐标如何映射的? // TODO 为什么这个顺序指定四个顶点?顶点坐标和纹理坐标如何映射的?
0.0f, 1.0f, 0.0f,
1.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f,
1.0f, 0.0f 1.0f,
0.0f,
0.0f,
1.0f,
0.0f
}; };
// 顶点着色器 // 顶点着色器

View file

@ -1,11 +1,13 @@
#ifndef QYUVOPENGLWIDGET_H #ifndef QYUVOPENGLWIDGET_H
#define QYUVOPENGLWIDGET_H #define QYUVOPENGLWIDGET_H
#include <QOpenGLWidget> #include <QOpenGLBuffer>
#include <QOpenGLFunctions> #include <QOpenGLFunctions>
#include <QOpenGLShaderProgram> #include <QOpenGLShaderProgram>
#include <QOpenGLBuffer> #include <QOpenGLWidget>
class QYUVOpenGLWidget : public QOpenGLWidget, protected QOpenGLFunctions class QYUVOpenGLWidget
: public QOpenGLWidget
, protected QOpenGLFunctions
{ {
Q_OBJECT Q_OBJECT
public: public:

View file

@ -1,12 +1,12 @@
#include <QDebug>
#include <QTimer>
#include <QThread>
#include <QTimerEvent>
#include <QCoreApplication> #include <QCoreApplication>
#include <QDebug>
#include <QFileInfo> #include <QFileInfo>
#include <QThread>
#include <QTimer>
#include <QTimerEvent>
#include "server.h"
#include "config.h" #include "config.h"
#include "server.h"
#define DEVICE_NAME_FIELD_LENGTH 64 #define DEVICE_NAME_FIELD_LENGTH 64
#define SOCKET_NAME "scrcpy" #define SOCKET_NAME "scrcpy"
@ -45,10 +45,7 @@ Server::Server(QObject *parent) : QObject(parent)
}); });
} }
Server:: ~Server() Server::~Server() {}
{
}
const QString &Server::getServerPath() const QString &Server::getServerPath()
{ {

View file

@ -5,15 +5,16 @@
#include <QPointer> #include <QPointer>
#include <QSize> #include <QSize>
#include "adbprocess.h"
#include "tcpserver.h" #include "tcpserver.h"
#include "videosocket.h" #include "videosocket.h"
#include "adbprocess.h"
class Server : public QObject class Server : public QObject
{ {
Q_OBJECT Q_OBJECT
enum SERVER_START_STEP { enum SERVER_START_STEP
{
SSS_NULL, SSS_NULL,
SSS_PUSH, SSS_PUSH,
SSS_ENABLE_TUNNEL_REVERSE, SSS_ENABLE_TUNNEL_REVERSE,
@ -21,8 +22,10 @@ class Server : public QObject
SSS_EXECUTE_SERVER, SSS_EXECUTE_SERVER,
SSS_RUNNING, SSS_RUNNING,
}; };
public: public:
struct ServerParams { struct ServerParams
{
QString serial = ""; // 设备序列号 QString serial = ""; // 设备序列号
quint16 localPort = 27183; // reverse时本地监听端口 quint16 localPort = 27183; // reverse时本地监听端口
quint16 maxSize = 720; // 视频分辨率 quint16 maxSize = 720; // 视频分辨率

View file

@ -1,15 +1,9 @@
#include "tcpserver.h" #include "tcpserver.h"
#include "videosocket.h" #include "videosocket.h"
TcpServer::TcpServer(QObject *parent) : QTcpServer(parent) TcpServer::TcpServer(QObject *parent) : QTcpServer(parent) {}
{
} TcpServer::~TcpServer() {}
TcpServer::~TcpServer()
{
}
void TcpServer::incomingConnection(qintptr handle) void TcpServer::incomingConnection(qintptr handle)
{ {

View file

@ -1,6 +1,6 @@
#include <QCoreApplication> #include <QCoreApplication>
#include <QThread>
#include <QDebug> #include <QDebug>
#include <QThread>
#include "qscrcpyevent.h" #include "qscrcpyevent.h"
#include "videosocket.h" #include "videosocket.h"

View file

@ -2,8 +2,8 @@
#define VIDEOSOCKET_H #define VIDEOSOCKET_H
#include <QEvent> #include <QEvent>
#include <QTcpSocket>
#include <QMutex> #include <QMutex>
#include <QTcpSocket>
#include <QWaitCondition> #include <QWaitCondition>
class VideoSocket : public QTcpSocket class VideoSocket : public QTcpSocket

View file

@ -2,10 +2,10 @@
#include <QTime> #include <QTime>
#include "compat.h" #include "compat.h"
#include "stream.h"
#include "decoder.h" #include "decoder.h"
#include "videosocket.h"
#include "recorder.h" #include "recorder.h"
#include "stream.h"
#include "videosocket.h"
#define BUFSIZE 0x10000 #define BUFSIZE 0x10000
#define HEADER_SIZE 12 #define HEADER_SIZE 12
@ -13,16 +13,12 @@
typedef qint32 (*ReadPacketFunc)(void *, quint8 *, qint32); typedef qint32 (*ReadPacketFunc)(void *, quint8 *, qint32);
Stream::Stream(QObject *parent) Stream::Stream(QObject *parent) : QThread(parent) {}
: QThread(parent)
{
}
Stream::~Stream() Stream::~Stream() {}
{
}
static void avLogCallback(void *avcl, int level, const char *fmt, va_list vl) { static void avLogCallback(void *avcl, int level, const char *fmt, va_list vl)
{
Q_UNUSED(avcl) Q_UNUSED(avcl)
Q_UNUSED(vl) Q_UNUSED(vl)
@ -73,11 +69,13 @@ void Stream::setDecoder(Decoder* decoder)
m_decoder = decoder; m_decoder = decoder;
} }
static quint32 bufferRead32be(quint8* buf) { static quint32 bufferRead32be(quint8 *buf)
{
return (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3]; return (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
} }
static quint64 bufferRead64be(quint8* buf) { static quint64 bufferRead64be(quint8 *buf)
{
quint32 msb = bufferRead32be(buf); quint32 msb = bufferRead32be(buf);
quint32 lsb = bufferRead32be(&buf[4]); quint32 lsb = bufferRead32be(&buf[4]);
return ((quint64)msb << 32) | lsb; return ((quint64)msb << 32) | lsb;
@ -324,9 +322,7 @@ bool Stream::parse(AVPacket *packet)
int inLen = packet->size; int inLen = packet->size;
quint8 *outData = Q_NULLPTR; quint8 *outData = Q_NULLPTR;
int outLen = 0; int outLen = 0;
int r = av_parser_parse2(m_parser, m_codecCtx, int r = av_parser_parse2(m_parser, m_codecCtx, &outData, &outLen, inData, inLen, AV_NOPTS_VALUE, AV_NOPTS_VALUE, -1);
&outData, &outLen, inData, inLen,
AV_NOPTS_VALUE, AV_NOPTS_VALUE, -1);
// PARSER_FLAG_COMPLETE_FRAMES is set // PARSER_FLAG_COMPLETE_FRAMES is set
Q_ASSERT(r == inLen); Q_ASSERT(r == inLen);

View file

@ -1,8 +1,8 @@
#ifndef STREAM_H #ifndef STREAM_H
#define STREAM_H #define STREAM_H
#include <QThread>
#include <QPointer> #include <QPointer>
#include <QThread>
extern "C" extern "C"
{ {

View file

@ -1,16 +1,14 @@
#include <QMouseEvent>
#include <QDebug> #include <QDebug>
#include <QShowEvent>
#include <QHideEvent> #include <QHideEvent>
#include <QMouseEvent>
#include <QShowEvent>
#include "device.h"
#include "iconhelper.h"
#include "toolform.h" #include "toolform.h"
#include "ui_toolform.h" #include "ui_toolform.h"
#include "iconhelper.h"
#include "device.h"
ToolForm::ToolForm(QWidget* adsorbWidget, AdsorbPositions adsorbPos) ToolForm::ToolForm(QWidget *adsorbWidget, AdsorbPositions adsorbPos) : MagneticWidget(adsorbWidget, adsorbPos), ui(new Ui::ToolForm)
: MagneticWidget(adsorbWidget, adsorbPos)
, ui(new Ui::ToolForm)
{ {
ui->setupUi(this); ui->setupUi(this);
setWindowFlags(windowFlags() | Qt::FramelessWindowHint); setWindowFlags(windowFlags() | Qt::FramelessWindowHint);

View file

@ -1,13 +1,14 @@
#ifndef TOOLFORM_H #ifndef TOOLFORM_H
#define TOOLFORM_H #define TOOLFORM_H
#include <QWidget>
#include <QPointer> #include <QPointer>
#include <QWidget>
#include "magneticwidget.h"
#include "device.h" #include "device.h"
#include "magneticwidget.h"
namespace Ui { namespace Ui
{
class ToolForm; class ToolForm;
} }

View file

@ -1,34 +1,31 @@
#include <QDesktopWidget> #include <QDesktopWidget>
#include <QMouseEvent>
#include <QTimer>
#include <QStyle>
#include <QStyleOption>
#include <QPainter>
#include <QtWidgets/QHBoxLayout>
#include <QMimeData>
#include <QFileInfo> #include <QFileInfo>
#include <QMessageBox> #include <QMessageBox>
#include <QShortcut> #include <QMimeData>
#include <QWindow> #include <QMouseEvent>
#include <QPainter>
#include <QScreen> #include <QScreen>
#include <QShortcut>
#include <QStyle>
#include <QStyleOption>
#include <QTimer>
#include <QWindow>
#include <QtWidgets/QHBoxLayout>
#include "videoform.h"
#include "qyuvopenglwidget.h"
#include "ui_videoform.h"
#include "iconhelper.h"
#include "toolform.h"
#include "device.h"
#include "controller.h"
#include "config.h" #include "config.h"
#include "controller.h"
#include "device.h"
#include "iconhelper.h"
#include "qyuvopenglwidget.h"
#include "toolform.h"
#include "ui_videoform.h"
#include "videoform.h"
extern "C" extern "C"
{ {
#include "libavutil/frame.h" #include "libavutil/frame.h"
} }
VideoForm::VideoForm(bool framelessWindow, bool skin, QWidget *parent) VideoForm::VideoForm(bool framelessWindow, bool skin, QWidget *parent) : QWidget(parent), ui(new Ui::videoForm), m_skin(skin)
: QWidget(parent)
, ui(new Ui::videoForm)
, m_skin(skin)
{ {
ui->setupUi(this); ui->setupUi(this);
initUI(); initUI();
@ -80,8 +77,7 @@ QRect VideoForm::getGrabCursorRect()
{ {
QRect rc; QRect rc;
#if defined(Q_OS_WIN32) #if defined(Q_OS_WIN32)
rc = QRect(m_videoWidget->mapToGlobal(m_videoWidget->pos()) rc = QRect(m_videoWidget->mapToGlobal(m_videoWidget->pos()), m_videoWidget->size());
, m_videoWidget->size());
// high dpi support // high dpi support
rc.setTopLeft(rc.topLeft() * m_videoWidget->devicePixelRatio()); rc.setTopLeft(rc.topLeft() * m_videoWidget->devicePixelRatio());
rc.setBottomRight(rc.bottomRight() * m_videoWidget->devicePixelRatio()); rc.setBottomRight(rc.bottomRight() * m_videoWidget->devicePixelRatio());
@ -130,8 +126,7 @@ void VideoForm::updateRender(const AVFrame *frame)
updateShowSize(QSize(frame->width, frame->height)); updateShowSize(QSize(frame->width, frame->height));
m_videoWidget->setFrameSize(QSize(frame->width, frame->height)); m_videoWidget->setFrameSize(QSize(frame->width, frame->height));
m_videoWidget->updateTextures(frame->data[0], frame->data[1], frame->data[2], m_videoWidget->updateTextures(frame->data[0], frame->data[1], frame->data[2], frame->linesize[0], frame->linesize[1], frame->linesize[2]);
frame->linesize[0], frame->linesize[1], frame->linesize[2]);
} }
void VideoForm::showToolForm(bool show) void VideoForm::showToolForm(bool show)
@ -170,16 +165,11 @@ void VideoForm::installShortcut()
// resizeSquare // resizeSquare
shortcut = new QShortcut(QKeySequence("Ctrl+g"), this); shortcut = new QShortcut(QKeySequence("Ctrl+g"), this);
connect(shortcut, &QShortcut::activated, this, [this](){ connect(shortcut, &QShortcut::activated, this, [this]() { resizeSquare(); });
resizeSquare();
});
// removeBlackRect // removeBlackRect
shortcut = new QShortcut(QKeySequence("Ctrl+x"), this); shortcut = new QShortcut(QKeySequence("Ctrl+x"), this);
connect(shortcut, &QShortcut::activated, this, [this](){ connect(shortcut, &QShortcut::activated, this, [this]() { removeBlackRect(); });
removeBlackRect();
});
// postGoHome // postGoHome
shortcut = new QShortcut(QKeySequence("Ctrl+h"), this); shortcut = new QShortcut(QKeySequence("Ctrl+h"), this);
@ -527,8 +517,7 @@ void VideoForm::mouseMoveEvent(QMouseEvent *event)
void VideoForm::mouseDoubleClickEvent(QMouseEvent *event) void VideoForm::mouseDoubleClickEvent(QMouseEvent *event)
{ {
if (event->button() == Qt::LeftButton if (event->button() == Qt::LeftButton && !m_videoWidget->geometry().contains(event->pos())) {
&& !m_videoWidget->geometry().contains(event->pos())) {
removeBlackRect(); removeBlackRect();
} }
@ -549,8 +538,7 @@ void VideoForm::wheelEvent(QWheelEvent *event)
Qt::MouseButtons buttons, Qt::KeyboardModifiers modifiers, Qt::MouseButtons buttons, Qt::KeyboardModifiers modifiers,
Qt::Orientation orient = Qt::Vertical); Qt::Orientation orient = Qt::Vertical);
*/ */
QWheelEvent wheelEvent(pos, event->globalPosF(), event->delta(), QWheelEvent wheelEvent(pos, event->globalPosF(), event->delta(), event->buttons(), event->modifiers(), event->orientation());
event->buttons(), event->modifiers(), event->orientation());
emit m_device->wheelEvent(&wheelEvent, m_videoWidget->frameSize(), m_videoWidget->size()); emit m_device->wheelEvent(&wheelEvent, m_videoWidget->frameSize(), m_videoWidget->size());
} }
} }
@ -560,9 +548,7 @@ void VideoForm::keyPressEvent(QKeyEvent *event)
if (!m_device) { if (!m_device) {
return; return;
} }
if (Qt::Key_Escape == event->key() if (Qt::Key_Escape == event->key() && !event->isAutoRepeat() && isFullScreen()) {
&& !event->isAutoRepeat()
&& isFullScreen()) {
emit m_device->switchFullScreen(); emit m_device->switchFullScreen();
} }

View file

@ -1,10 +1,11 @@
#ifndef VIDEOFORM_H #ifndef VIDEOFORM_H
#define VIDEOFORM_H #define VIDEOFORM_H
#include <QWidget>
#include <QPointer> #include <QPointer>
#include <QWidget>
namespace Ui { namespace Ui
{
class videoForm; class videoForm;
} }

View file

@ -1,7 +1,7 @@
#include <QDebug> #include <QDebug>
#include <QKeyEvent>
#include <QMouseEvent> #include <QMouseEvent>
#include <QWheelEvent> #include <QWheelEvent>
#include <QKeyEvent>
#include "devicemanage.h" #include "devicemanage.h"
#include "server.h" #include "server.h"
@ -9,15 +9,9 @@
#define DM_MAX_DEVICES_NUM 16 #define DM_MAX_DEVICES_NUM 16
DeviceManage::DeviceManage(QObject *parent) : QObject(parent) DeviceManage::DeviceManage(QObject *parent) : QObject(parent) {}
{
} DeviceManage::~DeviceManage() {}
DeviceManage::~DeviceManage()
{
}
bool DeviceManage::connectDevice(Device::DeviceParams params) bool DeviceManage::connectDevice(Device::DeviceParams params)
{ {
@ -195,8 +189,7 @@ void DeviceManage::onControlStateChange(Device *device, Device::GroupControlStat
return; return;
} }
// free to host // free to host
if (oldState == Device::GroupControlState::GCS_FREE if (oldState == Device::GroupControlState::GCS_FREE && newState == Device::GroupControlState::GCS_HOST) {
&& newState == Device::GroupControlState::GCS_HOST) {
// install direct control signals // install direct control signals
setGroupControlHost(device, true); setGroupControlHost(device, true);
// install convert control signals(frameSize need convert) // install convert control signals(frameSize need convert)
@ -206,8 +199,7 @@ void DeviceManage::onControlStateChange(Device *device, Device::GroupControlStat
return; return;
} }
// host to free // host to free
if (oldState == Device::GroupControlState::GCS_HOST if (oldState == Device::GroupControlState::GCS_HOST && newState == Device::GroupControlState::GCS_FREE) {
&& newState == Device::GroupControlState::GCS_FREE) {
// uninstall direct control signals // uninstall direct control signals
setGroupControlHost(device, false); setGroupControlHost(device, false);
// uninstall convert control signals(frameSize need convert) // uninstall convert control signals(frameSize need convert)
@ -275,9 +267,7 @@ quint16 DeviceManage::getFreePort()
while (i.hasNext()) { while (i.hasNext()) {
i.next(); i.next();
auto device = i.value(); auto device = i.value();
if (device && device->getServer() if (device && device->getServer() && device->getServer()->isReverse() && port == device->getServer()->getParams().localPort) {
&& device->getServer()->isReverse()
&& port == device->getServer()->getParams().localPort) {
used = true; used = true;
break; break;
} }

View file

@ -1,8 +1,8 @@
#ifndef DEVICEMANAGE_H #ifndef DEVICEMANAGE_H
#define DEVICEMANAGE_H #define DEVICEMANAGE_H
#include <QPointer>
#include <QMap> #include <QMap>
#include <QPointer>
#include "device.h" #include "device.h"

View file

@ -1,20 +1,18 @@
#include <QFile>
#include <QTime>
#include <QKeyEvent>
#include <QFileDialog>
#include <QTimer>
#include <QDebug> #include <QDebug>
#include <QFile>
#include <QFileDialog>
#include <QKeyEvent>
#include <QTime>
#include <QTimer>
#include "dialog.h"
#include "ui_dialog.h"
#include "device.h"
#include "videoform.h"
#include "keymap.h"
#include "config.h" #include "config.h"
#include "device.h"
#include "dialog.h"
#include "keymap.h"
#include "ui_dialog.h"
#include "videoform.h"
Dialog::Dialog(QWidget *parent) : Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog)
QDialog(parent),
ui(new Ui::Dialog)
{ {
ui->setupUi(this); ui->setupUi(this);
initUI(); initUI();
@ -134,8 +132,7 @@ void Dialog::execAdbCmd()
QString Dialog::getGameScript(const QString &fileName) QString Dialog::getGameScript(const QString &fileName)
{ {
QFile loadFile(KeyMap::getKeyMapPath() + "/" + fileName); QFile loadFile(KeyMap::getKeyMapPath() + "/" + fileName);
if(!loadFile.open(QIODevice::ReadOnly)) if (!loadFile.open(QIODevice::ReadOnly)) {
{
outLog("open file failed:" + fileName, true); outLog("open file failed:" + fileName, true);
return ""; return "";
} }
@ -324,10 +321,7 @@ void Dialog::on_wirelessDisConnectBtn_clicked()
void Dialog::on_selectRecordPathBtn_clicked() void Dialog::on_selectRecordPathBtn_clicked()
{ {
QFileDialog::Options options = QFileDialog::DontResolveSymlinks | QFileDialog::ShowDirsOnly; QFileDialog::Options options = QFileDialog::DontResolveSymlinks | QFileDialog::ShowDirsOnly;
QString directory = QFileDialog::getExistingDirectory(this, QString directory = QFileDialog::getExistingDirectory(this, tr("select path"), "", options);
tr("select path"),
"",
options);
ui->recordPathEdt->setText(directory); ui->recordPathEdt->setText(directory);
} }

View file

@ -7,7 +7,8 @@
#include "adbprocess.h" #include "adbprocess.h"
#include "devicemanage.h" #include "devicemanage.h"
namespace Ui { namespace Ui
{
class Dialog; class Dialog;
} }

View file

@ -1,8 +1,7 @@
#include "iconhelper.h" #include "iconhelper.h"
IconHelper *IconHelper::_instance = 0; IconHelper *IconHelper::_instance = 0;
IconHelper::IconHelper(QObject*): IconHelper::IconHelper(QObject *) : QObject(qApp)
QObject(qApp)
{ {
int fontId = QFontDatabase::addApplicationFont(":/font/fontawesome-webfont.ttf"); int fontId = QFontDatabase::addApplicationFont(":/font/fontawesome-webfont.ttf");
QString fontName = QFontDatabase::applicationFontFamilies(fontId).at(0); QString fontName = QFontDatabase::applicationFontFamilies(fontId).at(0);

View file

@ -1,13 +1,13 @@
#ifndef ICONHELPER_H #ifndef ICONHELPER_H
#define ICONHELPER_H #define ICONHELPER_H
#include <QObject> #include <QApplication>
#include <QFont> #include <QFont>
#include <QFontDatabase> #include <QFontDatabase>
#include <QMutex>
#include <QLabel> #include <QLabel>
#include <QMutex>
#include <QObject>
#include <QPushButton> #include <QPushButton>
#include <QApplication>
class IconHelper : public QObject class IconHelper : public QObject
{ {
@ -31,7 +31,6 @@ public:
void SetIcon(QLabel *lab, QChar c, int size = 10); void SetIcon(QLabel *lab, QChar c, int size = 10);
void SetIcon(QPushButton *btn, QChar c, int size = 10); void SetIcon(QPushButton *btn, QChar c, int size = 10);
}; };
#endif // ICONHELPER_H #endif // ICONHELPER_H

View file

@ -1,15 +1,15 @@
#include <QApplication> #include <QApplication>
#include <QDebug> #include <QDebug>
#include <QTcpSocket>
#include <QTcpServer>
#include <QTranslator>
#include <QFile> #include <QFile>
#include <QSurfaceFormat> #include <QSurfaceFormat>
#include <QTcpServer>
#include <QTcpSocket>
#include <QTranslator>
#include "dialog.h"
#include "stream.h"
#include "mousetap/mousetap.h"
#include "config.h" #include "config.h"
#include "dialog.h"
#include "mousetap/mousetap.h"
#include "stream.h"
static Dialog *g_mainDlg = Q_NULLPTR; static Dialog *g_mainDlg = Q_NULLPTR;
@ -98,7 +98,9 @@ int main(int argc, char *argv[])
g_mainDlg->setWindowTitle(Config::getInstance().getTitle()); g_mainDlg->setWindowTitle(Config::getInstance().getTitle());
g_mainDlg->show(); g_mainDlg->show();
qInfo(QObject::tr("This software is completely open source and free. Strictly used for illegal purposes, or at your own risk. You can download it at the following address:").toUtf8()); qInfo(QObject::tr("This software is completely open source and free. Strictly used for illegal purposes, or at your own risk. You can download it at the "
"following address:")
.toUtf8());
qInfo(QString("QtScrcpy %1 <https://github.com/barry-ran/QtScrcpy>").arg(QCoreApplication::applicationVersion()).toUtf8()); qInfo(QString("QtScrcpy %1 <https://github.com/barry-ran/QtScrcpy>").arg(QCoreApplication::applicationVersion()).toUtf8());
int ret = a.exec(); int ret = a.exec();
@ -111,7 +113,8 @@ int main(int argc, char *argv[])
return ret; return ret;
} }
void installTranslator() { void installTranslator()
{
static QTranslator translator; static QTranslator translator;
QLocale locale; QLocale locale;
QLocale::Language language = locale.language(); QLocale::Language language = locale.language();

View file

@ -3,16 +3,9 @@
#include "keepradiowidget.h" #include "keepradiowidget.h"
KeepRadioWidget::KeepRadioWidget(QWidget *parent) : KeepRadioWidget::KeepRadioWidget(QWidget *parent) : QWidget(parent) {}
QWidget(parent)
{
} KeepRadioWidget::~KeepRadioWidget() {}
KeepRadioWidget::~KeepRadioWidget()
{
}
void KeepRadioWidget::setWidget(QWidget *w) void KeepRadioWidget::setWidget(QWidget *w)
{ {

View file

@ -1,8 +1,8 @@
#ifndef KEEPRADIOWIDGET_H #ifndef KEEPRADIOWIDGET_H
#define KEEPRADIOWIDGET_H #define KEEPRADIOWIDGET_H
#include <QWidget>
#include <QPointer> #include <QPointer>
#include <QWidget>
class KeepRadioWidget : public QWidget class KeepRadioWidget : public QWidget
{ {
@ -23,7 +23,6 @@ private:
float m_widthHeightRadio = -1.0f; float m_widthHeightRadio = -1.0f;
QPointer<QWidget> m_subWidget; QPointer<QWidget> m_subWidget;
QSize m_goodSize; QSize m_goodSize;
}; };
#endif // KEEPRADIOWIDGET_H #endif // KEEPRADIOWIDGET_H

View file

@ -4,17 +4,13 @@
#include "magneticwidget.h" #include "magneticwidget.h"
MagneticWidget::MagneticWidget(QWidget* adsorbWidget, AdsorbPositions adsorbPos) MagneticWidget::MagneticWidget(QWidget *adsorbWidget, AdsorbPositions adsorbPos) : QWidget(Q_NULLPTR), m_adsorbPos(adsorbPos), m_adsorbWidget(adsorbWidget)
: QWidget(Q_NULLPTR)
, m_adsorbPos(adsorbPos)
, m_adsorbWidget(adsorbWidget)
{ {
Q_ASSERT(m_adsorbWidget); Q_ASSERT(m_adsorbWidget);
setParent(m_adsorbWidget); setParent(m_adsorbWidget);
setWindowFlags(windowFlags() | Qt::Tool); setWindowFlags(windowFlags() | Qt::Tool);
m_adsorbWidget->installEventFilter(this); m_adsorbWidget->installEventFilter(this);
} }
MagneticWidget::~MagneticWidget() MagneticWidget::~MagneticWidget()
@ -110,65 +106,50 @@ void MagneticWidget::moveEvent(QMoveEvent *event)
m_adsorbed = false; m_adsorbed = false;
if (m_adsorbPos & AP_INSIDE_LEFT if (m_adsorbPos & AP_INSIDE_LEFT && parentRect.intersects(targetRect) && qAbs(parentLeft - targetLeft) < adsorbDistance) {
&& parentRect.intersects(targetRect)
&& qAbs(parentLeft - targetLeft) < adsorbDistance) {
finalPosition.setX(parentLeft); finalPosition.setX(parentLeft);
m_adsorbed |= true; m_adsorbed |= true;
m_curAdsorbPosition = AP_INSIDE_LEFT; m_curAdsorbPosition = AP_INSIDE_LEFT;
} }
if (m_adsorbPos & AP_OUTSIDE_RIGHT if (m_adsorbPos & AP_OUTSIDE_RIGHT && parentRect.intersects(targetRect.translated(-adsorbDistance, 0)) && qAbs(parentRight - targetLeft) < adsorbDistance) {
&& parentRect.intersects(targetRect.translated(-adsorbDistance, 0))
&& qAbs(parentRight - targetLeft) < adsorbDistance) {
finalPosition.setX(parentRight); finalPosition.setX(parentRight);
m_adsorbed |= true; m_adsorbed |= true;
m_curAdsorbPosition = AP_OUTSIDE_RIGHT; m_curAdsorbPosition = AP_OUTSIDE_RIGHT;
} }
if (m_adsorbPos & AP_OUTSIDE_LEFT if (m_adsorbPos & AP_OUTSIDE_LEFT && parentRect.intersects(targetRect.translated(adsorbDistance, 0)) && qAbs(parentLeft - targetRight) < adsorbDistance) {
&& parentRect.intersects(targetRect.translated(adsorbDistance, 0))
&& qAbs(parentLeft - targetRight) < adsorbDistance) {
finalPosition.setX(parentLeft - targetRect.width()); finalPosition.setX(parentLeft - targetRect.width());
m_adsorbed |= true; m_adsorbed |= true;
m_curAdsorbPosition = AP_OUTSIDE_LEFT; m_curAdsorbPosition = AP_OUTSIDE_LEFT;
} }
if (m_adsorbPos & AP_INSIDE_RIGHT if (m_adsorbPos & AP_INSIDE_RIGHT && parentRect.intersects(targetRect) && qAbs(parentRight - targetRight) < adsorbDistance) {
&& parentRect.intersects(targetRect)
&& qAbs(parentRight - targetRight) < adsorbDistance) {
finalPosition.setX(parentRight - targetRect.width()); finalPosition.setX(parentRight - targetRect.width());
m_adsorbed |= true; m_adsorbed |= true;
m_curAdsorbPosition = AP_INSIDE_RIGHT; m_curAdsorbPosition = AP_INSIDE_RIGHT;
} }
if (m_adsorbPos & AP_INSIDE_TOP if (m_adsorbPos & AP_INSIDE_TOP && parentRect.intersects(targetRect) && qAbs(parentTop - targetTop) < adsorbDistance) {
&& parentRect.intersects(targetRect)
&& qAbs(parentTop - targetTop) < adsorbDistance) {
finalPosition.setY(parentTop); finalPosition.setY(parentTop);
m_adsorbed |= true; m_adsorbed |= true;
m_curAdsorbPosition = AP_INSIDE_TOP; m_curAdsorbPosition = AP_INSIDE_TOP;
} }
if (m_adsorbPos & AP_OUTSIDE_TOP if (m_adsorbPos & AP_OUTSIDE_TOP && parentRect.intersects(targetRect.translated(0, adsorbDistance)) && qAbs(parentTop - targetBottom) < adsorbDistance) {
&& parentRect.intersects(targetRect.translated(0, adsorbDistance))
&& qAbs(parentTop - targetBottom) < adsorbDistance) {
finalPosition.setY(parentTop - targetRect.height()); finalPosition.setY(parentTop - targetRect.height());
m_adsorbed |= true; m_adsorbed |= true;
m_curAdsorbPosition = AP_OUTSIDE_TOP; m_curAdsorbPosition = AP_OUTSIDE_TOP;
} }
if (m_adsorbPos & AP_OUTSIDE_BOTTOM if (m_adsorbPos & AP_OUTSIDE_BOTTOM && parentRect.intersects(targetRect.translated(0, -adsorbDistance))
&& parentRect.intersects(targetRect.translated(0, -adsorbDistance))
&& qAbs(parentBottom - targetTop) < adsorbDistance) { && qAbs(parentBottom - targetTop) < adsorbDistance) {
finalPosition.setY(parentBottom); finalPosition.setY(parentBottom);
m_adsorbed |= true; m_adsorbed |= true;
m_curAdsorbPosition = AP_OUTSIDE_BOTTOM; m_curAdsorbPosition = AP_OUTSIDE_BOTTOM;
} }
if (m_adsorbPos & AP_INSIDE_BOTTOM if (m_adsorbPos & AP_INSIDE_BOTTOM && parentRect.intersects(targetRect) && qAbs(parentBottom - targetBottom) < adsorbDistance) {
&& parentRect.intersects(targetRect)
&& qAbs(parentBottom - targetBottom) < adsorbDistance) {
finalPosition.setY(parentBottom - targetRect.height()); finalPosition.setY(parentBottom - targetRect.height());
m_adsorbed |= true; m_adsorbed |= true;
m_curAdsorbPosition = AP_INSIDE_BOTTOM; m_curAdsorbPosition = AP_INSIDE_BOTTOM;
@ -191,4 +172,3 @@ void MagneticWidget::getGeometry(QRect &relativeWidgetRect, QRect &targetWidgetR
targetWidgetRect.setWidth(width()); targetWidgetRect.setWidth(width());
targetWidgetRect.setHeight(height()); targetWidgetRect.setHeight(height());
} }

View file

@ -1,8 +1,8 @@
#ifndef MAGNETICWIDGET_H #ifndef MAGNETICWIDGET_H
#define MAGNETICWIDGET_H #define MAGNETICWIDGET_H
#include <QWidget>
#include <QPointer> #include <QPointer>
#include <QWidget>
/* /*
* a magnetic widget * a magnetic widget
@ -14,7 +14,8 @@ class MagneticWidget : public QWidget
Q_OBJECT Q_OBJECT
public: public:
enum AdsorbPosition { enum AdsorbPosition
{
AP_OUTSIDE_LEFT = 0x01, // 吸附外部左边框 AP_OUTSIDE_LEFT = 0x01, // 吸附外部左边框
AP_OUTSIDE_TOP = 0x02, // 吸附外部上边框 AP_OUTSIDE_TOP = 0x02, // 吸附外部上边框
AP_OUTSIDE_RIGHT = 0x04, // 吸附外部右边框 AP_OUTSIDE_RIGHT = 0x04, // 吸附外部右边框

View file

@ -53,5 +53,6 @@ quint64 BufferUtil::read64(QBuffer &buffer)
quint32 msb = read32(buffer); quint32 msb = read32(buffer);
quint32 lsb = read32(buffer); quint32 lsb = read32(buffer);
return ((quint64) msb << 32) | lsb;; return ((quint64)msb << 32) | lsb;
;
} }

View file

@ -6,8 +6,7 @@
// In ffmpeg/doc/APIchanges: // In ffmpeg/doc/APIchanges:
// 2016-04-11 - 6f69f7a / 9200514 - lavf 57.33.100 / 57.5.0 - avformat.h // 2016-04-11 - 6f69f7a / 9200514 - lavf 57.33.100 / 57.5.0 - avformat.h
// Add AVStream.codecpar, deprecate AVStream.codec. // Add AVStream.codecpar, deprecate AVStream.codec.
#if (LIBAVFORMAT_VERSION_MICRO >= 100 /* FFmpeg */ && \ #if (LIBAVFORMAT_VERSION_MICRO >= 100 /* FFmpeg */ && LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 33, 100)) \
LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 33, 100)) \
|| (LIBAVFORMAT_VERSION_MICRO < 100 && /* Libav */ \ || (LIBAVFORMAT_VERSION_MICRO < 100 && /* Libav */ \
LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 5, 0)) LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 5, 0))
#define QTSCRCPY_LAVF_HAS_NEW_CODEC_PARAMS_API #define QTSCRCPY_LAVF_HAS_NEW_CODEC_PARAMS_API

View file

@ -1,6 +1,6 @@
#include <QSettings>
#include <QCoreApplication> #include <QCoreApplication>
#include <QFileInfo> #include <QFileInfo>
#include <QSettings>
#include "config.h" #include "config.h"
@ -261,6 +261,3 @@ QString Config::getTitle()
m_settings->endGroup(); m_settings->endGroup();
return title; return title;
} }

View file

@ -1,13 +1,15 @@
#ifndef COCOAMOUSETAP_H #ifndef COCOAMOUSETAP_H
#define COCOAMOUSETAP_H #define COCOAMOUSETAP_H
#include <QThread>
#include <QSemaphore> #include <QSemaphore>
#include <QThread>
#include "mousetap.h" #include "mousetap.h"
struct MouseEventTapData; struct MouseEventTapData;
class QWidget; class QWidget;
class CocoaMouseTap : public MouseTap, public QThread class CocoaMouseTap
: public MouseTap
, public QThread
{ {
public: public:
CocoaMouseTap(QObject *parent = Q_NULLPTR); CocoaMouseTap(QObject *parent = Q_NULLPTR);

View file

@ -3,7 +3,8 @@
#include <QRect> #include <QRect>
class QWidget; class QWidget;
class MouseTap { class MouseTap
{
public: public:
static MouseTap *getInstance(); static MouseTap *getInstance();
virtual void initMouseEventTap() = 0; virtual void initMouseEventTap() = 0;

View file

@ -1,28 +1,16 @@
#include <Windows.h>
#include <QWidget>
#include <QDebug> #include <QDebug>
#include <QWidget>
#include <Windows.h>
#include "winmousetap.h" #include "winmousetap.h"
WinMouseTap::WinMouseTap() WinMouseTap::WinMouseTap() {}
{
} WinMouseTap::~WinMouseTap() {}
WinMouseTap::~WinMouseTap() void WinMouseTap::initMouseEventTap() {}
{
} void WinMouseTap::quitMouseEventTap() {}
void WinMouseTap::initMouseEventTap()
{
}
void WinMouseTap::quitMouseEventTap()
{
}
void WinMouseTap::enableMouseEventTap(QRect rc, bool enabled) void WinMouseTap::enableMouseEventTap(QRect rc, bool enabled)
{ {