id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
13,683
|
IpcTests.cpp
|
deskflow_deskflow/src/test/integtests/ipc/IpcTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2012 Nick Bolton
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
// TODO: fix, tests failing intermittently on mac.
#ifndef WINAPI_CARBON
#define TEST_ENV
#include "arch/Arch.h"
#include "base/EventQueue.h"
#include "base/Log.h"
#include "base/String.h"
#include "base/TMethodEventJob.h"
#include "base/TMethodJob.h"
#include "common/ipc.h"
#include "ipc/IpcClient.h"
#include "ipc/IpcClientProxy.h"
#include "ipc/IpcMessage.h"
#include "ipc/IpcServer.h"
#include "ipc/IpcServerProxy.h"
#include "mt/Thread.h"
#include "net/SocketMultiplexer.h"
#include "test/shared/TestEventQueue.h"
#include <gtest/gtest.h>
const int kTestPort = 24802;
class IpcTests : public ::testing::Test
{
public:
IpcTests();
virtual ~IpcTests();
void connectToServer_handleMessageReceived(const Event &, void *);
void sendMessageToServer_serverHandleMessageReceived(const Event &, void *);
void sendMessageToClient_serverHandleClientConnected(const Event &, void *);
void sendMessageToClient_clientHandleMessageReceived(const Event &, void *);
public:
SocketMultiplexer m_multiplexer;
bool m_connectToServer_helloMessageReceived;
bool m_connectToServer_hasClientNode;
IpcServer *m_connectToServer_server;
String m_sendMessageToServer_receivedString;
String m_sendMessageToClient_receivedString;
IpcClient *m_sendMessageToServer_client;
IpcServer *m_sendMessageToClient_server;
TestEventQueue m_events;
};
TEST_F(IpcTests, connectToServer)
{
SocketMultiplexer socketMultiplexer;
IpcServer server(&m_events, &socketMultiplexer, kTestPort);
server.listen();
m_connectToServer_server = &server;
m_events.adoptHandler(
m_events.forIpcServer().messageReceived(), &server,
new TMethodEventJob<IpcTests>(this, &IpcTests::connectToServer_handleMessageReceived)
);
IpcClient client(&m_events, &socketMultiplexer, kTestPort);
client.connect();
m_events.initQuitTimeout(5);
m_events.loop();
m_events.removeHandler(m_events.forIpcServer().messageReceived(), &server);
m_events.cleanupQuitTimeout();
EXPECT_EQ(true, m_connectToServer_helloMessageReceived);
EXPECT_EQ(true, m_connectToServer_hasClientNode);
}
TEST_F(IpcTests, sendMessageToServer)
{
SocketMultiplexer socketMultiplexer;
IpcServer server(&m_events, &socketMultiplexer, kTestPort);
server.listen();
// event handler sends "test" command to server.
m_events.adoptHandler(
m_events.forIpcServer().messageReceived(), &server,
new TMethodEventJob<IpcTests>(this, &IpcTests::sendMessageToServer_serverHandleMessageReceived)
);
IpcClient client(&m_events, &socketMultiplexer, kTestPort);
client.connect();
m_sendMessageToServer_client = &client;
m_events.initQuitTimeout(5);
m_events.loop();
m_events.removeHandler(m_events.forIpcServer().messageReceived(), &server);
m_events.cleanupQuitTimeout();
EXPECT_EQ("test", m_sendMessageToServer_receivedString);
}
TEST_F(IpcTests, sendMessageToClient)
{
SocketMultiplexer socketMultiplexer;
IpcServer server(&m_events, &socketMultiplexer, kTestPort);
server.listen();
m_sendMessageToClient_server = &server;
// event handler sends "test" log line to client.
m_events.adoptHandler(
m_events.forIpcServer().messageReceived(), &server,
new TMethodEventJob<IpcTests>(this, &IpcTests::sendMessageToClient_serverHandleClientConnected)
);
IpcClient client(&m_events, &socketMultiplexer, kTestPort);
client.connect();
m_events.adoptHandler(
m_events.forIpcClient().messageReceived(), &client,
new TMethodEventJob<IpcTests>(this, &IpcTests::sendMessageToClient_clientHandleMessageReceived)
);
m_events.initQuitTimeout(5);
m_events.loop();
m_events.removeHandler(m_events.forIpcServer().messageReceived(), &server);
m_events.removeHandler(m_events.forIpcClient().messageReceived(), &client);
m_events.cleanupQuitTimeout();
EXPECT_EQ("test", m_sendMessageToClient_receivedString);
}
IpcTests::IpcTests()
: m_connectToServer_helloMessageReceived(false),
m_connectToServer_hasClientNode(false),
m_connectToServer_server(nullptr),
m_sendMessageToClient_server(nullptr),
m_sendMessageToServer_client(nullptr)
{
}
IpcTests::~IpcTests()
{
}
void IpcTests::connectToServer_handleMessageReceived(const Event &e, void *)
{
IpcMessage *m = static_cast<IpcMessage *>(e.getDataObject());
if (m->type() == IpcMessageType::Hello) {
m_connectToServer_hasClientNode = m_connectToServer_server->hasClients(IpcClientType::Node);
m_connectToServer_helloMessageReceived = true;
m_events.raiseQuitEvent();
}
}
void IpcTests::sendMessageToServer_serverHandleMessageReceived(const Event &e, void *)
{
IpcMessage *m = static_cast<IpcMessage *>(e.getDataObject());
if (m->type() == IpcMessageType::Hello) {
LOG((CLOG_DEBUG "client said hello, sending test to server"));
IpcCommandMessage m("test", true);
m_sendMessageToServer_client->send(m);
} else if (m->type() == IpcMessageType::Command) {
IpcCommandMessage *cm = static_cast<IpcCommandMessage *>(m);
LOG((CLOG_DEBUG "got ipc command message, %d", cm->command().c_str()));
m_sendMessageToServer_receivedString = cm->command();
m_events.raiseQuitEvent();
}
}
void IpcTests::sendMessageToClient_serverHandleClientConnected(const Event &e, void *)
{
IpcMessage *m = static_cast<IpcMessage *>(e.getDataObject());
if (m->type() == IpcMessageType::Hello) {
LOG((CLOG_DEBUG "client said hello, sending test to client"));
IpcLogLineMessage m("test");
m_sendMessageToClient_server->send(m, IpcClientType::Node);
}
}
void IpcTests::sendMessageToClient_clientHandleMessageReceived(const Event &e, void *)
{
IpcMessage *m = static_cast<IpcMessage *>(e.getDataObject());
if (m->type() == IpcMessageType::LogLine) {
IpcLogLineMessage *llm = static_cast<IpcLogLineMessage *>(m);
LOG((CLOG_DEBUG "got ipc log message, %d", llm->logLine().c_str()));
m_sendMessageToClient_receivedString = llm->logLine();
m_events.raiseQuitEvent();
}
}
#endif // WINAPI_CARBON
| 6,707
|
C++
|
.cpp
| 173
| 35.820809
| 101
| 0.76211
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
13,684
|
MSWindowsClipboardTests.cpp
|
deskflow_deskflow/src/test/integtests/platform/MSWindowsClipboardTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2011 Nick Bolton
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "platform/IMSWindowsClipboardFacade.h"
#include "platform/MSWindowsClipboard.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
class MSWindowsClipboardTests : public ::testing::Test
{
protected:
virtual void SetUp()
{
emptyClipboard();
}
virtual void TearDown()
{
emptyClipboard();
}
private:
void emptyClipboard()
{
MSWindowsClipboard clipboard(NULL);
clipboard.open(0);
clipboard.empty();
}
};
class MockFacade : public IMSWindowsClipboardFacade
{
public:
MOCK_METHOD2(write, void(HANDLE, UINT));
};
TEST_F(MSWindowsClipboardTests, emptyUnowned_openCalled_returnsTrue)
{
MSWindowsClipboard clipboard(NULL);
clipboard.open(0);
bool actual = clipboard.emptyUnowned();
EXPECT_EQ(true, actual);
}
TEST_F(MSWindowsClipboardTests, empty_openCalled_returnsTrue)
{
MSWindowsClipboard clipboard(NULL);
clipboard.open(0);
bool actual = clipboard.empty();
EXPECT_EQ(true, actual);
}
TEST_F(MSWindowsClipboardTests, empty_singleFormat_hasReturnsFalse)
{
MSWindowsClipboard clipboard(NULL);
clipboard.open(0);
clipboard.add(MSWindowsClipboard::kText, "synergy rocks!");
clipboard.empty();
bool actual = clipboard.has(MSWindowsClipboard::kText);
EXPECT_EQ(false, actual);
}
TEST_F(MSWindowsClipboardTests, add_newValue_valueWasStored)
{
MSWindowsClipboard clipboard(NULL);
clipboard.open(0);
clipboard.add(IClipboard::kText, "synergy rocks!");
String actual = clipboard.get(IClipboard::kText);
EXPECT_EQ("synergy rocks!", actual);
}
TEST_F(MSWindowsClipboardTests, add_newValue_writeWasCalled)
{
MockFacade facade;
EXPECT_CALL(facade, write(testing::_, testing::_));
MSWindowsClipboard clipboard(NULL);
clipboard.setFacade(facade);
clipboard.open(0);
clipboard.add(IClipboard::kText, "synergy rocks!");
}
TEST_F(MSWindowsClipboardTests, add_replaceValue_valueWasReplaced)
{
MSWindowsClipboard clipboard(NULL);
clipboard.open(0);
clipboard.add(IClipboard::kText, "synergy rocks!");
clipboard.add(IClipboard::kText, "maxivista sucks"); // haha, just kidding.
String actual = clipboard.get(IClipboard::kText);
EXPECT_EQ("maxivista sucks", actual);
}
TEST_F(MSWindowsClipboardTests, open_timeIsZero_returnsTrue)
{
MSWindowsClipboard clipboard(NULL);
bool actual = clipboard.open(0);
EXPECT_EQ(true, actual);
}
TEST_F(MSWindowsClipboardTests, open_timeIsOne_returnsTrue)
{
MSWindowsClipboard clipboard(NULL);
bool actual = clipboard.open(1);
EXPECT_EQ(true, actual);
}
TEST_F(MSWindowsClipboardTests, close_isOpen_noErrors)
{
MSWindowsClipboard clipboard(NULL);
clipboard.open(0);
clipboard.close();
// can't assert anything
}
// TODO: fix intermittently failing tests
#if 0
TEST_F(MSWindowsClipboardTests, getTime_openWithNoEmpty_returnsOne)
{
MSWindowsClipboard clipboard(NULL);
clipboard.open(1);
MSWindowsClipboard::Time actual = clipboard.getTime();
// this behavior is different to that of Clipboard which only
// returns the value passed into open(t) after empty() is called.
EXPECT_EQ(1, actual);
}
TEST_F(MSWindowsClipboardTests, getTime_openAndEmpty_returnsOne)
{
MSWindowsClipboard clipboard(NULL);
clipboard.open(1);
clipboard.empty();
MSWindowsClipboard::Time actual = clipboard.getTime();
EXPECT_EQ(1, actual);
}
#endif
TEST_F(MSWindowsClipboardTests, has_withFormatAdded_returnsTrue)
{
MSWindowsClipboard clipboard(NULL);
clipboard.open(0);
clipboard.empty();
clipboard.add(IClipboard::kText, "synergy rocks!");
bool actual = clipboard.has(IClipboard::kText);
EXPECT_EQ(true, actual);
}
TEST_F(MSWindowsClipboardTests, has_withNoFormats_returnsFalse)
{
MSWindowsClipboard clipboard(NULL);
clipboard.open(0);
clipboard.empty();
bool actual = clipboard.has(IClipboard::kText);
EXPECT_EQ(false, actual);
}
TEST_F(MSWindowsClipboardTests, get_withNoFormats_returnsEmpty)
{
MSWindowsClipboard clipboard(NULL);
clipboard.open(0);
clipboard.empty();
String actual = clipboard.get(IClipboard::kText);
EXPECT_EQ("", actual);
}
TEST_F(MSWindowsClipboardTests, get_withFormatAdded_returnsExpected)
{
MSWindowsClipboard clipboard(NULL);
clipboard.open(0);
clipboard.empty();
clipboard.add(IClipboard::kText, "synergy rocks!");
String actual = clipboard.get(IClipboard::kText);
EXPECT_EQ("synergy rocks!", actual);
}
TEST_F(MSWindowsClipboardTests, isOwnedByDeskflow_defaultState_noError)
{
MSWindowsClipboard clipboard(NULL);
clipboard.open(0);
bool actual = clipboard.isOwnedByDeskflow();
EXPECT_EQ(true, actual);
}
| 5,312
|
C++
|
.cpp
| 174
| 27.873563
| 77
| 0.77203
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,685
|
XWindowsClipboardTests.cpp
|
deskflow_deskflow/src/test/integtests/platform/XWindowsClipboardTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2011 Nick Bolton
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "platform/XWindowsClipboard.h"
#include "test/shared/undef_x11_macros.h"
#include <gtest/gtest.h>
#include <memory>
// TODO: fix segfault in release mode
#if 0
class XWindowsClipboardTests : public ::testing::Test {
protected:
void SetUp() override {
m_display = XOpenDisplay(nullptr);
int screen = DefaultScreen(m_display);
Window root = XRootWindow(m_display, screen);
XSetWindowAttributes attr;
attr.do_not_propagate_mask = 0;
attr.override_redirect = True;
attr.cursor = Cursor();
m_window = XCreateWindow(
m_display, root, 0, 0, 1, 1, 0, 0, InputOnly, nullptr, 0, &attr);
m_clipboard = std::make_unique<XWindowsClipboard>(m_display, m_window, 0);
m_clipboard->open(0);
m_clipboard->empty();
}
void TearDown() override {
XDestroyWindow(m_display, m_window);
XCloseDisplay(m_display);
}
XWindowsClipboard &getClipboard() { return *m_clipboard; }
private:
Display *m_display;
Window m_window;
std::unique_ptr<XWindowsClipboard> m_clipboard;
};
TEST_F(XWindowsClipboardTests, empty_openCalled_returnsTrue) {
XWindowsClipboard &clipboard = getClipboard();
bool actual = clipboard.empty();
EXPECT_EQ(true, actual);
}
TEST_F(XWindowsClipboardTests, empty_singleFormat_hasReturnsFalse) {
XWindowsClipboard &clipboard = getClipboard();
clipboard.add(XWindowsClipboard::kText, "synergy rocks!");
clipboard.empty();
bool actual = clipboard.has(XWindowsClipboard::kText);
EXPECT_FALSE(actual);
}
TEST_F(XWindowsClipboardTests, add_newValue_valueWasStored) {
XWindowsClipboard &clipboard = getClipboard();
clipboard.add(IClipboard::kText, "synergy rocks!");
String actual = clipboard.get(IClipboard::kText);
EXPECT_EQ("synergy rocks!", actual);
}
TEST_F(XWindowsClipboardTests, add_replaceValue_valueWasReplaced) {
XWindowsClipboard &clipboard = getClipboard();
clipboard.add(IClipboard::kText, "synergy rocks!");
clipboard.add(IClipboard::kText, "maxivista sucks"); // haha, just kidding.
String actual = clipboard.get(IClipboard::kText);
EXPECT_EQ("maxivista sucks", actual);
}
TEST_F(XWindowsClipboardTests, close_isOpen_noErrors) {
XWindowsClipboard &clipboard = getClipboard();
// clipboard opened in createClipboard()
clipboard.close();
// can't assert anything
}
TEST_F(XWindowsClipboardTests, has_withFormatAdded_returnsTrue) {
XWindowsClipboard &clipboard = getClipboard();
clipboard.add(IClipboard::kText, "synergy rocks!");
bool actual = clipboard.has(IClipboard::kText);
EXPECT_EQ(true, actual);
}
TEST_F(XWindowsClipboardTests, has_withNoFormats_returnsFalse) {
XWindowsClipboard &clipboard = getClipboard();
bool actual = clipboard.has(IClipboard::kText);
EXPECT_FALSE(actual);
}
TEST_F(XWindowsClipboardTests, get_withNoFormats_returnsEmpty) {
XWindowsClipboard &clipboard = getClipboard();
String actual = clipboard.get(IClipboard::kText);
EXPECT_EQ("", actual);
}
TEST_F(XWindowsClipboardTests, get_withFormatAdded_returnsExpected) {
XWindowsClipboard &clipboard = getClipboard();
clipboard.add(IClipboard::kText, "synergy rocks!");
String actual = clipboard.get(IClipboard::kText);
EXPECT_EQ("synergy rocks!", actual);
}
#endif
| 3,957
|
C++
|
.cpp
| 103
| 35.466019
| 78
| 0.756488
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,686
|
XWindowsScreenSaverTests.cpp
|
deskflow_deskflow/src/test/integtests/platform/XWindowsScreenSaverTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2011 Nick Bolton
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
// TODO: fix tests
#if 0
#include "platform/XWindowsScreenSaver.h"
#include "test/mock/deskflow/MockEventQueue.h"
#include <X11/Xlib.h>
#include <gtest/gtest.h>
using ::testing::_;
// TODO: not working on build machine for some reason
TEST(CXWindowsScreenSaverTests, activate_defaultScreen_todo)
{
Display* display = XOpenDisplay(":0.0");
Window window = DefaultRootWindow(display);
MockEventQueue eventQueue;
EXPECT_CALL(eventQueue, removeHandler(_, _)).Times(1);
CXWindowsScreenSaver screenSaver(
display, window, NULL, &eventQueue);
screenSaver.activate();
bool isActive = screenSaver.isActive();
screenSaver.deactivate();
ASSERT_EQ(true, isActive);
}
#endif
| 1,440
|
C++
|
.cpp
| 39
| 34.153846
| 72
| 0.751437
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,687
|
OSXClipboardTests.cpp
|
deskflow_deskflow/src/test/integtests/platform/OSXClipboardTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2011 Nick Bolton
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
// TODO: fix failing tests (e.g. add_newValue_valueWasStored)
#if 0
#include "platform/OSXClipboard.h"
#include <gtest/gtest.h>
TEST(OSXClipboardTests, empty_openCalled_returnsTrue) {
OSXClipboard clipboard;
clipboard.open(0);
bool actual = clipboard.empty();
EXPECT_EQ(true, actual);
}
TEST(OSXClipboardTests, empty_singleFormat_hasReturnsFalse) {
OSXClipboard clipboard;
clipboard.open(0);
clipboard.add(OSXClipboard::kText, "synergy rocks!");
clipboard.empty();
bool actual = clipboard.has(OSXClipboard::kText);
EXPECT_EQ(false, actual);
}
TEST(OSXClipboardTests, add_newValue_valueWasStored) {
OSXClipboard clipboard;
clipboard.open(0);
clipboard.add(IClipboard::kText, "synergy rocks!");
String actual = clipboard.get(IClipboard::kText);
EXPECT_EQ("synergy rocks!", actual);
}
TEST(OSXClipboardTests, add_replaceValue_valueWasReplaced) {
OSXClipboard clipboard;
clipboard.open(0);
clipboard.add(IClipboard::kText, "synergy rocks!");
clipboard.add(IClipboard::kText, "maxivista sucks"); // haha, just kidding.
String actual = clipboard.get(IClipboard::kText);
EXPECT_EQ("maxivista sucks", actual);
}
TEST(OSXClipboardTests, open_timeIsZero_returnsTrue) {
OSXClipboard clipboard;
bool actual = clipboard.open(0);
EXPECT_EQ(true, actual);
}
TEST(OSXClipboardTests, open_timeIsOne_returnsTrue) {
OSXClipboard clipboard;
bool actual = clipboard.open(1);
EXPECT_EQ(true, actual);
}
TEST(OSXClipboardTests, close_isOpen_noErrors) {
OSXClipboard clipboard;
clipboard.open(0);
clipboard.close();
// can't assert anything
}
TEST(OSXClipboardTests, getTime_openWithNoEmpty_returnsOne) {
OSXClipboard clipboard;
clipboard.open(1);
OSXClipboard::Time actual = clipboard.getTime();
// this behavior is different to that of Clipboard which only
// returns the value passed into open(t) after empty() is called.
EXPECT_EQ((UInt32)1, actual);
}
TEST(OSXClipboardTests, getTime_openAndEmpty_returnsOne) {
OSXClipboard clipboard;
clipboard.open(1);
clipboard.empty();
OSXClipboard::Time actual = clipboard.getTime();
EXPECT_EQ((UInt32)1, actual);
}
TEST(OSXClipboardTests, has_withFormatAdded_returnsTrue) {
OSXClipboard clipboard;
clipboard.open(0);
clipboard.empty();
clipboard.add(IClipboard::kText, "synergy rocks!");
bool actual = clipboard.has(IClipboard::kText);
EXPECT_EQ(true, actual);
}
TEST(OSXClipboardTests, has_withNoFormats_returnsFalse) {
OSXClipboard clipboard;
clipboard.open(0);
clipboard.empty();
bool actual = clipboard.has(IClipboard::kText);
EXPECT_EQ(false, actual);
}
TEST(OSXClipboardTests, get_withNoFormats_returnsEmpty) {
OSXClipboard clipboard;
clipboard.open(0);
clipboard.empty();
String actual = clipboard.get(IClipboard::kText);
EXPECT_EQ("", actual);
}
TEST(OSXClipboardTests, get_withFormatAdded_returnsExpected) {
OSXClipboard clipboard;
clipboard.open(0);
clipboard.empty();
clipboard.add(IClipboard::kText, "synergy rocks!");
String actual = clipboard.get(IClipboard::kText);
EXPECT_EQ("synergy rocks!", actual);
}
#endif
| 3,842
|
C++
|
.cpp
| 112
| 31.642857
| 77
| 0.76654
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,688
|
XWindowsKeyStateTests.cpp
|
deskflow_deskflow/src/test/integtests/platform/XWindowsKeyStateTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2011 Nick Bolton
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
// TODO: fix Assertion `s_instance != nullptr' failed.
#if 0
#define TEST_ENV
#include "test/mock/deskflow/MockEventQueue.h"
#include "test/mock/deskflow/MockKeyMap.h"
#include "base/Log.h"
#include "platform/XWindowsKeyState.h"
#define XK_LATIN1
#define XK_MISCELLANY
#include <X11/keysymdef.h>
#if HAVE_XKB_EXTENSION
#include <X11/XKBlib.h>
#endif
#include <errno.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
class XWindowsKeyStateTests : public ::testing::Test {
protected:
XWindowsKeyStateTests() : m_display(NULL) {}
~XWindowsKeyStateTests() {
if (m_display != NULL) {
LOG((CLOG_DEBUG "closing display"));
XCloseDisplay(m_display);
}
}
virtual void SetUp() {
// open the display only once for the entire test suite
if (this->m_display == NULL) {
LOG((CLOG_DEBUG "opening display"));
this->m_display = XOpenDisplay(NULL);
ASSERT_TRUE(this->m_display != NULL)
<< "unable to open display: " << errno;
}
}
virtual void TearDown() {}
Display *m_display;
};
TEST_F(XWindowsKeyStateTests, setActiveGroup_pollAndSet_groupIsZero) {
MockKeyMap keyMap;
MockEventQueue eventQueue;
XWindowsKeyState keyState(m_display, true, &eventQueue, keyMap);
keyState.setActiveGroup(XWindowsKeyState::kGroupPollAndSet);
ASSERT_EQ(0, keyState.group());
}
TEST_F(XWindowsKeyStateTests, setActiveGroup_poll_groupIsNotSet) {
MockKeyMap keyMap;
MockEventQueue eventQueue;
XWindowsKeyState keyState(m_display, true, &eventQueue, keyMap);
keyState.setActiveGroup(XWindowsKeyState::kGroupPoll);
ASSERT_LE(-1, keyState.group());
}
TEST_F(XWindowsKeyStateTests, setActiveGroup_customGroup_groupWasSet) {
MockKeyMap keyMap;
MockEventQueue eventQueue;
XWindowsKeyState keyState(m_display, true, &eventQueue, keyMap);
keyState.setActiveGroup(1);
ASSERT_EQ(1, keyState.group());
}
TEST_F(XWindowsKeyStateTests, mapModifiersFromX_zeroState_zeroMask) {
MockKeyMap keyMap;
MockEventQueue eventQueue;
XWindowsKeyState keyState(m_display, true, &eventQueue, keyMap);
int mask = keyState.mapModifiersFromX(0);
ASSERT_EQ(0, mask);
}
TEST_F(XWindowsKeyStateTests, mapModifiersToX_zeroMask_resultIsTrue) {
MockKeyMap keyMap;
MockEventQueue eventQueue;
XWindowsKeyState keyState(m_display, true, &eventQueue, keyMap);
unsigned int modifiers = 0;
bool result = keyState.mapModifiersToX(0, modifiers);
ASSERT_TRUE(result);
}
TEST_F(XWindowsKeyStateTests, fakeCtrlAltDel_default_returnsFalse) {
MockKeyMap keyMap;
MockEventQueue eventQueue;
XWindowsKeyState keyState(m_display, true, &eventQueue, keyMap);
bool result = keyState.fakeCtrlAltDel();
ASSERT_FALSE(result);
}
TEST_F(XWindowsKeyStateTests, pollActiveModifiers_defaultState_returnsZero) {
MockKeyMap keyMap;
MockEventQueue eventQueue;
XWindowsKeyState keyState(m_display, true, &eventQueue, keyMap);
KeyModifierMask actual = keyState.pollActiveModifiers();
ASSERT_EQ(0, actual);
}
#if 0 // TODO: fix, causes sigsegv
TEST_F(XWindowsKeyStateTests, pollActiveModifiers_shiftKeyDownThenUp_masksAreCorrect)
{
MockKeyMap keyMap;
MockEventQueue eventQueue;
XWindowsKeyState keyState(
m_display, true, &eventQueue, keyMap);
// set mock modifier mapping
std::fill(keyState.modifierFromX().begin(), keyState.modifierFromX().end(), 0);
keyState.modifierFromX()[ShiftMapIndex] = KeyModifierShift;
KeyCode key = XKeysymToKeycode(m_display, XK_Shift_L);
// fake shift key down (without using deskflow)
XTestFakeKeyEvent(m_display, key, true, CurrentTime);
// function under test (1st call)
KeyModifierMask modDown = keyState.pollActiveModifiers();
// fake shift key up (without using deskflow)
XTestFakeKeyEvent(m_display, key, false, CurrentTime);
// function under test (2nd call)
KeyModifierMask modUp = keyState.pollActiveModifiers();
EXPECT_TRUE((modDown & KeyModifierShift) == KeyModifierShift)
<< "shift key not in mask - key was not pressed";
EXPECT_TRUE((modUp & KeyModifierShift) == 0)
<< "shift key still in mask - make sure no keys are being held down";
}
#endif
TEST_F(XWindowsKeyStateTests, pollActiveGroup_defaultState_returnsZero) {
MockKeyMap keyMap;
MockEventQueue eventQueue;
XWindowsKeyState keyState(m_display, true, &eventQueue, keyMap);
SInt32 actual = keyState.pollActiveGroup();
ASSERT_EQ(0, actual);
}
TEST_F(XWindowsKeyStateTests, pollActiveGroup_positiveGroup_returnsGroup) {
MockKeyMap keyMap;
MockEventQueue eventQueue;
XWindowsKeyState keyState(m_display, true, &eventQueue, keyMap);
keyState.group(3);
SInt32 actual = keyState.pollActiveGroup();
ASSERT_EQ(3, actual);
}
TEST_F(XWindowsKeyStateTests, pollActiveGroup_xkb_areEqual) {
#if HAVE_XKB_EXTENSION
MockKeyMap keyMap;
MockEventQueue eventQueue;
XWindowsKeyState keyState(m_display, true, &eventQueue, keyMap);
// reset the group
keyState.group(-1);
XkbStateRec state;
// compare pollActiveGroup() with XkbGetState()
if (XkbGetState(m_display, XkbUseCoreKbd, &state) == Success) {
SInt32 actual = keyState.pollActiveGroup();
ASSERT_EQ(state.group, actual);
} else {
FAIL() << "XkbGetState() returned error " << errno;
}
#else
SUCCEED() << "Xkb extension not installed";
#endif
}
#endif
| 6,054
|
C++
|
.cpp
| 164
| 33.695122
| 85
| 0.758225
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
13,689
|
MSWindowsKeyStateTests.cpp
|
deskflow_deskflow/src/test/integtests/platform/MSWindowsKeyStateTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2011 Nick Bolton
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
// TODO: fix Assertion failed: s_instance != nullptr
#if 0
#define TEST_ENV
#include "base/TMethodJob.h"
#include "platform/MSWindowsDesks.h"
#include "platform/MSWindowsKeyState.h"
#include "platform/MSWindowsScreen.h"
#include "platform/MSWindowsScreenSaver.h"
#include "test/mock/deskflow/MockEventQueue.h"
#include "test/mock/deskflow/MockKeyMap.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
// wParam = flags, HIBYTE(lParam) = virtual key, LOBYTE(lParam) = scan code
#define DESKFLOW_MSG_FAKE_KEY DESKFLOW_HOOK_LAST_MSG + 4
using ::testing::_;
using ::testing::NiceMock;
class MSWindowsKeyStateTests : public ::testing::Test {
protected:
virtual void SetUp() {
m_hook.loadLibrary();
m_screensaver = new MSWindowsScreenSaver();
}
virtual void TearDown() { delete m_screensaver; }
MSWindowsDesks *newDesks(IEventQueue *eventQueue) {
return new MSWindowsDesks(
true, false, m_screensaver, eventQueue,
new TMethodJob<MSWindowsKeyStateTests>(
this, &MSWindowsKeyStateTests::updateKeysCB),
false);
}
void *getEventTarget() const {
return const_cast<MSWindowsKeyStateTests *>(this);
}
private:
void updateKeysCB(void *) {}
IScreenSaver *m_screensaver;
MSWindowsHook m_hook;
};
TEST_F(MSWindowsKeyStateTests, disable_eventQueueNotUsed) {
NiceMock<MockEventQueue> eventQueue;
MSWindowsDesks *desks = newDesks(&eventQueue);
MockKeyMap keyMap;
MSWindowsKeyState keyState(
desks, getEventTarget(), &eventQueue, keyMap, {"en"}, true);
EXPECT_CALL(eventQueue, removeHandler(_, _)).Times(0);
keyState.disable();
delete desks;
}
TEST_F(
MSWindowsKeyStateTests,
testAutoRepeat_noRepeatAndButtonIsZero_resultIsTrue) {
NiceMock<MockEventQueue> eventQueue;
MSWindowsDesks *desks = newDesks(&eventQueue);
MockKeyMap keyMap;
MSWindowsKeyState keyState(
desks, getEventTarget(), &eventQueue, keyMap, {"en"}, true);
keyState.setLastDown(1);
bool actual = keyState.testAutoRepeat(true, false, 1);
ASSERT_TRUE(actual);
delete desks;
}
TEST_F(MSWindowsKeyStateTests, testAutoRepeat_pressFalse_lastDownIsZero) {
NiceMock<MockEventQueue> eventQueue;
MSWindowsDesks *desks = newDesks(&eventQueue);
MockKeyMap keyMap;
MSWindowsKeyState keyState(
desks, getEventTarget(), &eventQueue, keyMap, {"en"}, true);
keyState.setLastDown(1);
keyState.testAutoRepeat(false, false, 1);
ASSERT_EQ(0, keyState.getLastDown());
delete desks;
}
TEST_F(MSWindowsKeyStateTests, saveModifiers_noModifiers_savedModifiers0) {
NiceMock<MockEventQueue> eventQueue;
MSWindowsDesks *desks = newDesks(&eventQueue);
MockKeyMap keyMap;
MSWindowsKeyState keyState(
desks, getEventTarget(), &eventQueue, keyMap, {"en"}, true);
keyState.saveModifiers();
ASSERT_EQ(0, keyState.getSavedModifiers());
delete desks;
}
TEST_F(
MSWindowsKeyStateTests, testKoreanLocale_inputModeKey_resultCorrectKeyID) {
NiceMock<MockEventQueue> eventQueue;
MSWindowsDesks *desks = newDesks(&eventQueue);
MockKeyMap keyMap;
MSWindowsKeyState keyState(
desks, getEventTarget(), &eventQueue, keyMap, {"en"}, true);
keyState.setKeyLayout((HKL)0x00000412u); // for ko-KR local ID
ASSERT_EQ(
0xEF31, keyState.getKeyID(0x15u, 0x1f2u)); // VK_HANGUL from Hangul key
ASSERT_EQ(
0xEF34, keyState.getKeyID(0x19u, 0x1f1u)); // VK_HANJA from Hanja key
ASSERT_EQ(
0xEF31, keyState.getKeyID(0x15u, 0x11du)); // VK_HANGUL from R-Alt key
ASSERT_EQ(
0xEF34, keyState.getKeyID(0x19u, 0x138u)); // VK_HANJA from R-Ctrl key
keyState.setKeyLayout((HKL)0x00000411); // for ja-jp locale ID
ASSERT_EQ(0xEF26, keyState.getKeyID(0x15u, 0x1du)); // VK_KANA
ASSERT_EQ(0xEF2A, keyState.getKeyID(0x19u, 0x38u)); // VK_KANJI
delete desks;
}
#endif
| 4,532
|
C++
|
.cpp
| 121
| 34.239669
| 79
| 0.750627
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,690
|
XWindowsScreenTests.cpp
|
deskflow_deskflow/src/test/integtests/platform/XWindowsScreenTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2011 Nick Bolton
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "test/mock/deskflow/MockEventQueue.h"
#include <gtest/gtest.h>
#include "platform/XWindowsScreen.h"
using ::testing::_;
// TODO: fix failing tests
#if 0
TEST(CXWindowsScreenTests, fakeMouseMove_nonPrimary_getCursorPosValuesCorrect) {
MockEventQueue eventQueue;
EXPECT_CALL(eventQueue, adoptHandler(_, _, _)).Times(2);
EXPECT_CALL(eventQueue, adoptBuffer(_)).Times(2);
EXPECT_CALL(eventQueue, removeHandler(_, _)).Times(2);
XWindowsScreen screen(
":0.0", false, false, 0, &eventQueue);
screen.fakeMouseMove(10, 20);
int x, y;
screen.getCursorPos(x, y);
ASSERT_EQ(10, x);
ASSERT_EQ(20, y);
}
#endif
| 1,364
|
C++
|
.cpp
| 37
| 34.540541
| 80
| 0.746212
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,691
|
OSXScreenTests.cpp
|
deskflow_deskflow/src/test/integtests/platform/OSXScreenTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "arch/Arch.h"
#include "base/EventQueue.h"
#include "platform/OSXScreen.h"
#include <gtest/gtest.h>
// TODO: fix intermittently failing test
// return value of CGCursorIsVisible is unreliable
#if 0
TEST(OSXScreenTests, hideCursor_notPrimary)
{
EventQueue queue;
OSXScreen screen(true, false);
screen.hideCursor();
EXPECT_EQ(false, CGCursorIsVisible());
// workaround for screen class race condition.
ARCH->sleep(.1f);
}
TEST(OSXScreenTests, showCursor_notPrimary)
{
EventQueue queue;
OSXScreen screen(false, false);
screen.showCursor();
EXPECT_EQ(true, CGCursorIsVisible());
// workaround for screen class race condition.
ARCH->sleep(.1f);
}
#endif
| 1,409
|
C++
|
.cpp
| 42
| 30.761905
| 72
| 0.751292
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,692
|
OSXKeyStateTests.cpp
|
deskflow_deskflow/src/test/integtests/platform/OSXKeyStateTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2011 Nick Bolton
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "base/Log.h"
#include "platform/OSXKeyState.h"
#include "test/mock/deskflow/MockEventQueue.h"
#include "test/mock/deskflow/MockKeyMap.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#define SHIFT_ID_L kKeyShift_L
#define SHIFT_ID_R kKeyShift_R
#define SHIFT_BUTTON 57
#define A_CHAR_ID 0x00000061
#define A_CHAR_BUTTON 001
class OSXKeyStateTests : public ::testing::Test
{
public:
static bool isKeyPressed(const OSXKeyState &keyState, KeyButton button);
};
// fakeAndPoll_shift seems to always fail on osx10.6
#if __MAC_OS_X_VERSION_MIN_REQUIRED > 1060
TEST_F(OSXKeyStateTests, fakeAndPoll_shift)
{
deskflow::KeyMap keyMap;
MockEventQueue eventQueue;
OSXKeyState keyState(&eventQueue, keyMap, {"en"}, true);
keyState.updateKeyMap();
keyState.fakeKeyDown(SHIFT_ID_L, 0, 1, "en");
EXPECT_TRUE(isKeyPressed(keyState, SHIFT_BUTTON));
keyState.fakeKeyUp(1);
EXPECT_TRUE(!isKeyPressed(keyState, SHIFT_BUTTON));
keyState.fakeKeyDown(SHIFT_ID_R, 0, 2, "en");
EXPECT_TRUE(isKeyPressed(keyState, SHIFT_BUTTON));
keyState.fakeKeyUp(2);
EXPECT_TRUE(!isKeyPressed(keyState, SHIFT_BUTTON));
}
TEST_F(OSXKeyStateTests, fakeAndPoll_charKey)
{
deskflow::KeyMap keyMap;
MockEventQueue eventQueue;
OSXKeyState keyState(&eventQueue, keyMap, {"en"}, true);
keyState.updateKeyMap();
keyState.fakeKeyDown(A_CHAR_ID, 0, 1, "en");
EXPECT_TRUE(isKeyPressed(keyState, A_CHAR_BUTTON));
keyState.fakeKeyUp(1);
EXPECT_TRUE(!isKeyPressed(keyState, A_CHAR_BUTTON));
// HACK: delete the key in case it was typed into a text editor.
// we should really set focus to an invisible window.
keyState.fakeKeyDown(kKeyBackSpace, 0, 2, "en");
keyState.fakeKeyUp(2);
}
TEST_F(OSXKeyStateTests, fakeAndPoll_charKeyAndModifier)
{
deskflow::KeyMap keyMap;
MockEventQueue eventQueue;
OSXKeyState keyState(&eventQueue, keyMap, {"en"}, true);
keyState.updateKeyMap();
keyState.fakeKeyDown(A_CHAR_ID, KeyModifierShift, 1, "en");
EXPECT_TRUE(isKeyPressed(keyState, A_CHAR_BUTTON));
keyState.fakeKeyUp(1);
EXPECT_TRUE(!isKeyPressed(keyState, A_CHAR_BUTTON));
// HACK: delete the key in case it was typed into a text editor.
// we should really set focus to an invisible window.
keyState.fakeKeyDown(kKeyBackSpace, 0, 2, "en");
keyState.fakeKeyUp(2);
}
bool OSXKeyStateTests::isKeyPressed(const OSXKeyState &keyState, KeyButton button)
{
// HACK: allow os to realize key state changes.
ARCH->sleep(.2);
IKeyState::KeyButtonSet pressed;
keyState.pollPressedKeys(pressed);
IKeyState::KeyButtonSet::const_iterator it;
for (it = pressed.begin(); it != pressed.end(); ++it) {
LOG((CLOG_DEBUG "checking key %d", *it));
if (*it == button) {
return true;
}
}
return false;
}
#endif
| 3,491
|
C++
|
.cpp
| 96
| 33.84375
| 82
| 0.752446
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
13,693
|
dotenv_tests.cpp
|
deskflow_deskflow/src/test/integtests/gui/dotenv_tests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "gui/dotenv.h"
#include <QFile>
#include <QTextStream>
#include <gtest/gtest.h>
TEST(dotenv_tests, dotenv_fileDoesNotExist_doesNotLoadEnvVar)
{
const QString envFile = "tmp/test/.env";
deskflow::gui::dotenv(envFile);
const QString actualValue = qEnvironmentVariable("TEST_ENV_VAR");
EXPECT_TRUE(actualValue.isEmpty());
}
TEST(dotenv_tests, dotenv_envFileWithEntry_loadsEnvVar)
{
const QString envFile = "tmp/test/.env";
QFile file(envFile);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
FAIL() << "Failed to create: " << envFile.toStdString();
}
const QString key = "TEST_ENV_VAR";
const QString value = R"("test value")";
const QString entry = key + " = " + value;
QTextStream out(&file);
out << " # Comment" << Qt::endl;
out << "FOOBAR" << Qt::endl;
out << entry << Qt::endl;
file.close();
deskflow::gui::dotenv(envFile);
const QString actualValue = qEnvironmentVariable(qPrintable(key));
EXPECT_EQ("test value", actualValue.toStdString());
QFile::remove(envFile);
}
| 1,732
|
C++
|
.cpp
| 47
| 34.340426
| 72
| 0.728033
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,694
|
MainWindowTests.cpp
|
deskflow_deskflow/src/test/integtests/gui/MainWindowTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#if 0 // TODO: reintroduce main window integ test once moved to the `gui` lib
// TODO: fix test freezing only on windows
#ifndef WIN32
#include "MainWindow.h"
#include "test/shared/gui/QtTest.h"
#include <gtest/gtest.h>
#include <memory>
class MainWindowTests : public QtTest {
public:
static void SetUpTestSuite() {
QtTest::SetUpTestSuite();
qRegisterMetaType<Edition>("Edition");
}
};
class TestMainWindow {
public:
class MainWindowProxy : public MainWindow {
public:
explicit MainWindowProxy(AppConfig &appConfig) : MainWindow(appConfig) {}
bool _checkSecureSocket(const char *test) {
return MainWindow::checkSecureSocket(test);
}
};
TestMainWindow() {
m_mainWindow = std::make_shared<MainWindowProxy>(m_appConfig);
}
AppConfig m_appConfig;
std::shared_ptr<MainWindowProxy> m_mainWindow;
};
TEST_F(MainWindowTests, checkSecureSocket_noMatch_expectFalse) {
TestMainWindow testMainWindow;
bool result = testMainWindow.m_mainWindow->_checkSecureSocket("test");
EXPECT_FALSE(result);
}
TEST_F(MainWindowTests, checkSecureSocket_match_expectTrue) {
TestMainWindow testMainWindow;
const char *test = "network encryption protocol: test";
bool result = testMainWindow.m_mainWindow->_checkSecureSocket(test);
EXPECT_TRUE(result);
}
#endif // WIN32
#endif // 0
| 2,020
|
C++
|
.cpp
| 58
| 32.189655
| 77
| 0.762346
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,695
|
CommandProcessTests.cpp
|
deskflow_deskflow/src/test/integtests/gui/core/CommandProcessTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "gui/core/CommandProcess.h"
#include <gtest/gtest.h>
TEST(CommandProcessTests, run_commandSucceeds_returnsOutput)
{
// it seems that on windows, you can sometimes just call echo (this worked
// with windows 2022), but on windows 10 you can't call echo directly.
#if defined(Q_OS_WIN)
const QString command = "cmd";
const QStringList arguments = {"/C", "echo Hello, World!"};
const QString input = "";
#elif defined(Q_OS_UNIX)
const QString command = "echo";
const QStringList arguments = {"Hello, World!"};
const QString input = "";
#endif // Q_OS_WIN
CommandProcess commandProcess(command, arguments, input);
const QString actual = commandProcess.run();
EXPECT_EQ("Hello, World!", actual.toStdString());
}
| 1,431
|
C++
|
.cpp
| 35
| 38.628571
| 76
| 0.74586
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,696
|
CoreToolTests.cpp
|
deskflow_deskflow/src/test/integtests/gui/core/CoreToolTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "gui/core/CoreTool.h"
#include "shared/gui/TestQtCoreApp.h"
#include <gtest/gtest.h>
TEST(CoreToolTests, getProfileDir_noMock_returnsNonEmpty)
{
TestQtCoreApp app;
CoreTool coreTool;
QString profileDir = coreTool.getProfileDir();
EXPECT_FALSE(profileDir.isEmpty());
}
TEST(CoreToolTests, getInstalledDir_noMock_returnsNonEmpty)
{
TestQtCoreApp app;
CoreTool coreTool;
QString installedDir = coreTool.getInstalledDir();
EXPECT_FALSE(installedDir.isEmpty());
}
TEST(CoreToolTests, getArch_noMock_returnsNonEmpty)
{
TestQtCoreApp app;
CoreTool coreTool;
QString arch = coreTool.getArch();
EXPECT_FALSE(arch.isEmpty());
}
| 1,348
|
C++
|
.cpp
| 40
| 31.45
| 72
| 0.779491
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,697
|
NetworkTests.cpp
|
deskflow_deskflow/src/test/integtests/net/NetworkTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2013-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
// TODO: fix, tests failing intermittently and/or with segfault
#if 0
#define TEST_ENV
#include "base/Log.h"
#include "base/TMethodEventJob.h"
#include "base/TMethodJob.h"
#include "client/Client.h"
#include "common/stdexcept.h"
#include "deskflow/FileChunk.h"
#include "deskflow/StreamChunker.h"
#include "mt/Thread.h"
#include "net/NetworkAddress.h"
#include "net/SocketMultiplexer.h"
#include "net/TCPSocketFactory.h"
#include "server/ClientListener.h"
#include "server/ClientProxy.h"
#include "server/Server.h"
#include "test/mock/deskflow/MockScreen.h"
#include "test/mock/server/MockConfig.h"
#include "test/mock/server/MockInputFilter.h"
#include "test/mock/server/MockPrimaryClient.h"
#include "test/shared/TestEventQueue.h"
#include <fstream>
#include <gtest/gtest.h>
#include <iostream>
#include <stdio.h>
using namespace std;
using ::testing::_;
using ::testing::Invoke;
using ::testing::NiceMock;
using ::testing::Return;
#define TEST_PORT 24803
#define TEST_HOST "localhost"
const size_t kMockDataSize = 1024 * 1024 * 10; // 10MB
const UInt16 kMockDataChunkIncrement = 1024; // 1KB
const char *kMockFilename = "tmp/test/NetworkTests.mock";
const size_t kMockFileSize = 1024 * 1024 * 10; // 10MB
void getScreenShape(SInt32 &x, SInt32 &y, SInt32 &w, SInt32 &h);
void getCursorPos(SInt32 &x, SInt32 &y);
UInt8 *newMockData(size_t size);
void createFile(fstream &file, const char *filename, size_t size);
class NetworkTests : public ::testing::Test {
public:
NetworkTests() : m_mockData(NULL), m_mockDataSize(0), m_mockFileSize(0) {
m_mockData = newMockData(kMockDataSize);
createFile(m_mockFile, kMockFilename, kMockFileSize);
}
~NetworkTests() {
remove(kMockFilename);
delete[] m_mockData;
}
void sendMockData(void *eventTarget);
void
sendToClient_mockData_handleClientConnected(const Event &, void *vlistener);
void sendToClient_mockData_fileRecieveCompleted(const Event &, void *);
void
sendToClient_mockFile_handleClientConnected(const Event &, void *vlistener);
void sendToClient_mockFile_fileRecieveCompleted(const Event &event, void *);
void
sendToServer_mockData_handleClientConnected(const Event &, void *vlistener);
void sendToServer_mockData_fileRecieveCompleted(const Event &event, void *);
void
sendToServer_mockFile_handleClientConnected(const Event &, void *vlistener);
void sendToServer_mockFile_fileRecieveCompleted(const Event &event, void *);
public:
TestEventQueue m_events;
UInt8 *m_mockData;
size_t m_mockDataSize;
fstream m_mockFile;
size_t m_mockFileSize;
};
TEST_F(NetworkTests, sendToClient_mockData) {
// server and client
NetworkAddress serverAddress(TEST_HOST, TEST_PORT);
serverAddress.resolve();
// server
SocketMultiplexer serverSocketMultiplexer;
TCPSocketFactory *serverSocketFactory =
new TCPSocketFactory(&m_events, &serverSocketMultiplexer);
ClientListener listener(serverAddress, serverSocketFactory, &m_events, false);
NiceMock<MockScreen> serverScreen;
NiceMock<MockPrimaryClient> primaryClient;
NiceMock<MockConfig> serverConfig;
NiceMock<MockInputFilter> serverInputFilter;
m_events.adoptHandler(
m_events.forClientListener().connected(), &listener,
new TMethodEventJob<NetworkTests>(
this, &NetworkTests::sendToClient_mockData_handleClientConnected,
&listener));
ON_CALL(serverConfig, isScreen(_)).WillByDefault(Return(true));
ON_CALL(serverConfig, getInputFilter())
.WillByDefault(Return(&serverInputFilter));
deskflow::ServerArgs serverArgs;
serverArgs.m_enableDragDrop = true;
Server server(
serverConfig, &primaryClient, &serverScreen, &m_events, serverArgs);
server.m_mock = true;
listener.setServer(&server);
// client
NiceMock<MockScreen> clientScreen;
SocketMultiplexer clientSocketMultiplexer;
TCPSocketFactory *clientSocketFactory =
new TCPSocketFactory(&m_events, &clientSocketMultiplexer);
ON_CALL(clientScreen, getShape(_, _, _, _))
.WillByDefault(Invoke(getScreenShape));
ON_CALL(clientScreen, getCursorPos(_, _)).WillByDefault(Invoke(getCursorPos));
deskflow::ClientArgs clientArgs;
clientArgs.m_enableDragDrop = true;
clientArgs.m_enableCrypto = false;
Client client(
&m_events, "stub", serverAddress, clientSocketFactory, &clientScreen,
clientArgs);
m_events.adoptHandler(
m_events.forFile().fileRecieveCompleted(), &client,
new TMethodEventJob<NetworkTests>(
this, &NetworkTests::sendToClient_mockData_fileRecieveCompleted));
client.connect();
m_events.initQuitTimeout(10);
m_events.loop();
m_events.removeHandler(m_events.forClientListener().connected(), &listener);
m_events.removeHandler(m_events.forFile().fileRecieveCompleted(), &client);
m_events.cleanupQuitTimeout();
}
TEST_F(NetworkTests, sendToClient_mockFile) {
// server and client
NetworkAddress serverAddress(TEST_HOST, TEST_PORT);
serverAddress.resolve();
// server
SocketMultiplexer serverSocketMultiplexer;
TCPSocketFactory *serverSocketFactory =
new TCPSocketFactory(&m_events, &serverSocketMultiplexer);
ClientListener listener(serverAddress, serverSocketFactory, &m_events, false);
NiceMock<MockScreen> serverScreen;
NiceMock<MockPrimaryClient> primaryClient;
NiceMock<MockConfig> serverConfig;
NiceMock<MockInputFilter> serverInputFilter;
m_events.adoptHandler(
m_events.forClientListener().connected(), &listener,
new TMethodEventJob<NetworkTests>(
this, &NetworkTests::sendToClient_mockFile_handleClientConnected,
&listener));
ON_CALL(serverConfig, isScreen(_)).WillByDefault(Return(true));
ON_CALL(serverConfig, getInputFilter())
.WillByDefault(Return(&serverInputFilter));
deskflow::ServerArgs serverArgs;
serverArgs.m_enableDragDrop = true;
Server server(
serverConfig, &primaryClient, &serverScreen, &m_events, serverArgs);
server.m_mock = true;
listener.setServer(&server);
// client
NiceMock<MockScreen> clientScreen;
SocketMultiplexer clientSocketMultiplexer;
TCPSocketFactory *clientSocketFactory =
new TCPSocketFactory(&m_events, &clientSocketMultiplexer);
ON_CALL(clientScreen, getShape(_, _, _, _))
.WillByDefault(Invoke(getScreenShape));
ON_CALL(clientScreen, getCursorPos(_, _)).WillByDefault(Invoke(getCursorPos));
deskflow::ClientArgs clientArgs;
clientArgs.m_enableDragDrop = true;
clientArgs.m_enableCrypto = false;
Client client(
&m_events, "stub", serverAddress, clientSocketFactory, &clientScreen,
clientArgs);
m_events.adoptHandler(
m_events.forFile().fileRecieveCompleted(), &client,
new TMethodEventJob<NetworkTests>(
this, &NetworkTests::sendToClient_mockFile_fileRecieveCompleted));
client.connect();
m_events.initQuitTimeout(10);
m_events.loop();
m_events.removeHandler(m_events.forClientListener().connected(), &listener);
m_events.removeHandler(m_events.forFile().fileRecieveCompleted(), &client);
m_events.cleanupQuitTimeout();
}
TEST_F(NetworkTests, sendToServer_mockData) {
// server and client
NetworkAddress serverAddress(TEST_HOST, TEST_PORT);
serverAddress.resolve();
// server
SocketMultiplexer serverSocketMultiplexer;
TCPSocketFactory *serverSocketFactory =
new TCPSocketFactory(&m_events, &serverSocketMultiplexer);
ClientListener listener(serverAddress, serverSocketFactory, &m_events, false);
NiceMock<MockScreen> serverScreen;
NiceMock<MockPrimaryClient> primaryClient;
NiceMock<MockConfig> serverConfig;
NiceMock<MockInputFilter> serverInputFilter;
ON_CALL(serverConfig, isScreen(_)).WillByDefault(Return(true));
ON_CALL(serverConfig, getInputFilter())
.WillByDefault(Return(&serverInputFilter));
deskflow::ServerArgs serverArgs;
serverArgs.m_enableDragDrop = true;
Server server(
serverConfig, &primaryClient, &serverScreen, &m_events, serverArgs);
server.m_mock = true;
listener.setServer(&server);
// client
NiceMock<MockScreen> clientScreen;
SocketMultiplexer clientSocketMultiplexer;
TCPSocketFactory *clientSocketFactory =
new TCPSocketFactory(&m_events, &clientSocketMultiplexer);
ON_CALL(clientScreen, getShape(_, _, _, _))
.WillByDefault(Invoke(getScreenShape));
ON_CALL(clientScreen, getCursorPos(_, _)).WillByDefault(Invoke(getCursorPos));
deskflow::ClientArgs clientArgs;
clientArgs.m_enableDragDrop = true;
clientArgs.m_enableCrypto = false;
Client client(
&m_events, "stub", serverAddress, clientSocketFactory, &clientScreen,
clientArgs);
m_events.adoptHandler(
m_events.forClientListener().connected(), &listener,
new TMethodEventJob<NetworkTests>(
this, &NetworkTests::sendToServer_mockData_handleClientConnected,
&client));
m_events.adoptHandler(
m_events.forFile().fileRecieveCompleted(), &server,
new TMethodEventJob<NetworkTests>(
this, &NetworkTests::sendToServer_mockData_fileRecieveCompleted));
client.connect();
m_events.initQuitTimeout(10);
m_events.loop();
m_events.removeHandler(m_events.forClientListener().connected(), &listener);
m_events.removeHandler(m_events.forFile().fileRecieveCompleted(), &server);
m_events.cleanupQuitTimeout();
}
TEST_F(NetworkTests, sendToServer_mockFile) {
// server and client
NetworkAddress serverAddress(TEST_HOST, TEST_PORT);
serverAddress.resolve();
// server
SocketMultiplexer serverSocketMultiplexer;
TCPSocketFactory *serverSocketFactory =
new TCPSocketFactory(&m_events, &serverSocketMultiplexer);
ClientListener listener(serverAddress, serverSocketFactory, &m_events, false);
NiceMock<MockScreen> serverScreen;
NiceMock<MockPrimaryClient> primaryClient;
NiceMock<MockConfig> serverConfig;
NiceMock<MockInputFilter> serverInputFilter;
ON_CALL(serverConfig, isScreen(_)).WillByDefault(Return(true));
ON_CALL(serverConfig, getInputFilter())
.WillByDefault(Return(&serverInputFilter));
deskflow::ServerArgs serverArgs;
serverArgs.m_enableDragDrop = true;
Server server(
serverConfig, &primaryClient, &serverScreen, &m_events, serverArgs);
server.m_mock = true;
listener.setServer(&server);
// client
NiceMock<MockScreen> clientScreen;
SocketMultiplexer clientSocketMultiplexer;
TCPSocketFactory *clientSocketFactory =
new TCPSocketFactory(&m_events, &clientSocketMultiplexer);
ON_CALL(clientScreen, getShape(_, _, _, _))
.WillByDefault(Invoke(getScreenShape));
ON_CALL(clientScreen, getCursorPos(_, _)).WillByDefault(Invoke(getCursorPos));
deskflow::ClientArgs clientArgs;
clientArgs.m_enableDragDrop = true;
clientArgs.m_enableCrypto = false;
Client client(
&m_events, "stub", serverAddress, clientSocketFactory, &clientScreen,
clientArgs);
m_events.adoptHandler(
m_events.forClientListener().connected(), &listener,
new TMethodEventJob<NetworkTests>(
this, &NetworkTests::sendToServer_mockFile_handleClientConnected,
&client));
m_events.adoptHandler(
m_events.forFile().fileRecieveCompleted(), &server,
new TMethodEventJob<NetworkTests>(
this, &NetworkTests::sendToServer_mockFile_fileRecieveCompleted));
client.connect();
m_events.initQuitTimeout(10);
m_events.loop();
m_events.removeHandler(m_events.forClientListener().connected(), &listener);
m_events.removeHandler(m_events.forFile().fileRecieveCompleted(), &server);
m_events.cleanupQuitTimeout();
}
void NetworkTests::sendToClient_mockData_handleClientConnected(
const Event &, void *vlistener) {
ClientListener *listener = static_cast<ClientListener *>(vlistener);
Server *server = listener->getServer();
ClientProxy *client = listener->getNextClient();
if (client == NULL) {
throw runtime_error("client is null");
}
BaseClientProxy *bcp = client;
server->adoptClient(bcp);
server->setActive(bcp);
sendMockData(server);
}
void NetworkTests::sendToClient_mockData_fileRecieveCompleted(
const Event &event, void *) {
Client *client = static_cast<Client *>(event.getTarget());
EXPECT_TRUE(client->isReceivedFileSizeValid());
m_events.raiseQuitEvent();
}
void NetworkTests::sendToClient_mockFile_handleClientConnected(
const Event &, void *vlistener) {
ClientListener *listener = static_cast<ClientListener *>(vlistener);
Server *server = listener->getServer();
ClientProxy *client = listener->getNextClient();
if (client == NULL) {
throw runtime_error("client is null");
}
BaseClientProxy *bcp = client;
server->adoptClient(bcp);
server->setActive(bcp);
server->sendFileToClient(kMockFilename);
}
void NetworkTests::sendToClient_mockFile_fileRecieveCompleted(
const Event &event, void *) {
Client *client = static_cast<Client *>(event.getTarget());
EXPECT_TRUE(client->isReceivedFileSizeValid());
m_events.raiseQuitEvent();
}
void NetworkTests::sendToServer_mockData_handleClientConnected(
const Event &, void *vclient) {
Client *client = static_cast<Client *>(vclient);
sendMockData(client);
}
void NetworkTests::sendToServer_mockData_fileRecieveCompleted(
const Event &event, void *) {
Server *server = static_cast<Server *>(event.getTarget());
EXPECT_TRUE(server->isReceivedFileSizeValid());
m_events.raiseQuitEvent();
}
void NetworkTests::sendToServer_mockFile_handleClientConnected(
const Event &, void *vclient) {
Client *client = static_cast<Client *>(vclient);
client->sendFileToServer(kMockFilename);
}
void NetworkTests::sendToServer_mockFile_fileRecieveCompleted(
const Event &event, void *) {
Server *server = static_cast<Server *>(event.getTarget());
EXPECT_TRUE(server->isReceivedFileSizeValid());
m_events.raiseQuitEvent();
}
void NetworkTests::sendMockData(void *eventTarget) {
// send first message (file size)
String size = deskflow::string::sizeTypeToString(kMockDataSize);
FileChunk *sizeMessage = FileChunk::start(size);
m_events.addEvent(
Event(m_events.forFile().fileChunkSending(), eventTarget, sizeMessage));
// send chunk messages with incrementing chunk size
size_t lastSize = 0;
size_t sentLength = 0;
while (true) {
size_t dataSize = lastSize + kMockDataChunkIncrement;
// make sure we don't read too much from the mock data.
if (sentLength + dataSize > kMockDataSize) {
dataSize = kMockDataSize - sentLength;
}
// first byte is the chunk mark, last is \0
FileChunk *chunk = FileChunk::data(m_mockData, dataSize);
m_events.addEvent(
Event(m_events.forFile().fileChunkSending(), eventTarget, chunk));
sentLength += dataSize;
lastSize = dataSize;
if (sentLength == kMockDataSize) {
break;
}
}
// send last message
FileChunk *transferFinished = FileChunk::end();
m_events.addEvent(Event(
m_events.forFile().fileChunkSending(), eventTarget, transferFinished));
}
UInt8 *newMockData(size_t size) {
UInt8 *buffer = new UInt8[size];
UInt8 *data = buffer;
const UInt8 head[] = "mock head... ";
size_t headSize = sizeof(head) - 1;
const UInt8 tail[] = "... mock tail";
size_t tailSize = sizeof(tail) - 1;
const UInt8 deskflowRocks[] = "deskflow\0 rocks! ";
size_t deskflowRocksSize = sizeof(deskflowRocks) - 1;
memcpy(data, head, headSize);
data += headSize;
size_t times = (size - headSize - tailSize) / deskflowRocksSize;
for (size_t i = 0; i < times; ++i) {
memcpy(data, deskflowRocks, deskflowRocksSize);
data += deskflowRocksSize;
}
size_t remainder = (size - headSize - tailSize) % deskflowRocksSize;
if (remainder != 0) {
memset(data, '.', remainder);
data += remainder;
}
memcpy(data, tail, tailSize);
return buffer;
}
void createFile(fstream &file, const char *filename, size_t size) {
UInt8 *buffer = newMockData(size);
file.open(filename, ios::out | ios::binary);
if (!file.is_open()) {
throw runtime_error("file not open");
}
file.write(reinterpret_cast<char *>(buffer), size);
file.close();
delete[] buffer;
}
void getScreenShape(SInt32 &x, SInt32 &y, SInt32 &w, SInt32 &h) {
x = 0;
y = 0;
w = 1;
h = 1;
}
void getCursorPos(SInt32 &x, SInt32 &y) {
x = 0;
y = 0;
}
#endif // WINAPI_CARBON
| 16,946
|
C++
|
.cpp
| 430
| 35.760465
| 80
| 0.753381
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
13,698
|
main.cpp
|
deskflow_deskflow/src/test/unittests/main.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012 Symless Ltd.
* Copyright (C) 2011 Nick Bolton
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "arch/Arch.h"
#include "base/Log.h"
#include "shared/ExitTimeout.h"
#if SYSAPI_WIN32
#include "arch/win32/ArchMiscWindows.h"
#endif
#include <filesystem>
#include <gtest/gtest.h>
using deskflow::test::ExitTimeout;
const auto testDir = "tmp/test";
int main(int argc, char **argv)
{
// HACK: Unit tests should not use the filesystem.
std::filesystem::create_directories(testDir);
ExitTimeout exitTimeout(1, "Unit tests");
#if SYSAPI_WIN32
// HACK: shouldn't be needed, but logging fails without this.
ArchMiscWindows::setInstanceWin32(GetModuleHandle(NULL));
#endif
Arch arch;
arch.init();
Log log;
log.setFilter(kDEBUG4);
::testing::GTEST_FLAG(throw_on_failure) = true;
testing::InitGoogleTest(&argc, argv);
// return code 1 means the test failed.
// any other non-zero code is probably a memory error.
return RUN_ALL_TESTS();
}
| 1,597
|
C++
|
.cpp
| 46
| 32.5
| 72
| 0.753086
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,699
|
ArgParserTests.cpp
|
deskflow_deskflow/src/test/unittests/deskflow/ArgParserTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2014-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include <array>
#include <functional>
#include "common/constants.h"
#include "deskflow/ArgParser.h"
#include "deskflow/ArgsBase.h"
#include "deskflow/ClientArgs.h"
#include "deskflow/ServerArgs.h"
#include <gtest/gtest.h>
TEST(ArgParserTests, isArg_abbreviationsArg_returnTrue)
{
int i = 1;
const int argc = 2;
const char *argv[argc] = {"stub", "-t"};
bool result = ArgParser::isArg(i, argc, argv, "-t", NULL);
EXPECT_EQ(true, result);
}
TEST(ArgParserTests, isArg_fullArg_returnTrue)
{
int i = 1;
const int argc = 2;
const char *argv[argc] = {"stub", "--test"};
bool result = ArgParser::isArg(i, argc, argv, NULL, "--test");
EXPECT_EQ(true, result);
}
TEST(ArgParserTests, isArg_missingArgs_returnFalse)
{
int i = 1;
const int argc = 2;
const char *argv[argc] = {"stub", "-t"};
static deskflow::ArgsBase argsBase;
ArgParser argParser(NULL);
argParser.setArgsBase(argsBase);
bool result = ArgParser::isArg(i, argc, argv, "-t", NULL, 1);
EXPECT_FALSE(result);
EXPECT_EQ(true, argsBase.m_shouldExitFail);
}
TEST(ArgParserTests, searchDoubleQuotes_doubleQuotedArg_returnTrue)
{
String command("\"stub\"");
size_t left = 0;
size_t right = 0;
bool result = ArgParser::searchDoubleQuotes(command, left, right);
EXPECT_EQ(true, result);
EXPECT_EQ(0, left);
EXPECT_EQ(5, right);
}
TEST(ArgParserTests, searchDoubleQuotes_noDoubleQuotedArg_returnfalse)
{
String command("stub");
size_t left = 0;
size_t right = 0;
bool result = ArgParser::searchDoubleQuotes(command, left, right);
EXPECT_FALSE(result);
EXPECT_EQ(0, left);
EXPECT_EQ(0, right);
}
TEST(ArgParserTests, searchDoubleQuotes_oneDoubleQuoteArg_returnfalse)
{
String command("\"stub");
size_t left = 0;
size_t right = 0;
bool result = ArgParser::searchDoubleQuotes(command, left, right);
EXPECT_FALSE(result);
EXPECT_EQ(0, left);
EXPECT_EQ(0, right);
}
TEST(ArgParserTests, splitCommandString_oneArg_returnArgv)
{
String command("stub");
std::vector<String> argv;
ArgParser::splitCommandString(command, argv);
EXPECT_EQ(1, argv.size());
EXPECT_EQ("stub", argv.at(0));
}
TEST(ArgParserTests, splitCommandString_twoArgs_returnArgv)
{
String command("stub1 stub2");
std::vector<String> argv;
ArgParser::splitCommandString(command, argv);
EXPECT_EQ(2, argv.size());
EXPECT_EQ("stub1", argv.at(0));
EXPECT_EQ("stub2", argv.at(1));
}
TEST(ArgParserTests, splitCommandString_doubleQuotedArgs_returnArgv)
{
String command("\"stub1\" stub2 \"stub3\"");
std::vector<String> argv;
ArgParser::splitCommandString(command, argv);
EXPECT_EQ(3, argv.size());
EXPECT_EQ("stub1", argv.at(0));
EXPECT_EQ("stub2", argv.at(1));
EXPECT_EQ("stub3", argv.at(2));
}
TEST(ArgParserTests, splitCommandString_spaceDoubleQuotedArgs_returnArgv)
{
String command("\"stub1\" stub2 \"stub3 space\"");
std::vector<String> argv;
ArgParser::splitCommandString(command, argv);
EXPECT_EQ(3, argv.size());
EXPECT_EQ("stub1", argv.at(0));
EXPECT_EQ("stub2", argv.at(1));
EXPECT_EQ("stub3 space", argv.at(2));
}
TEST(ArgParserTests, getArgv_stringArray_return2DArray)
{
std::vector<String> argArray;
argArray.push_back("stub1");
argArray.push_back("stub2");
argArray.push_back("stub3 space");
const char **argv = ArgParser::getArgv(argArray);
String row1(argv[0]);
String row2(argv[1]);
String row3(argv[2]);
EXPECT_EQ("stub1", row1);
EXPECT_EQ("stub2", row2);
EXPECT_EQ("stub3 space", row3);
delete[] argv;
}
TEST(ArgParserTests, assembleCommand_stringArray_returnCommand)
{
std::vector<String> argArray;
argArray.push_back("stub1");
argArray.push_back("stub2");
String command = ArgParser::assembleCommand(argArray);
EXPECT_EQ("stub1 stub2", command);
}
TEST(ArgParserTests, assembleCommand_ignoreSecondArg_returnCommand)
{
std::vector<String> argArray;
argArray.push_back("stub1");
argArray.push_back("stub2");
String command = ArgParser::assembleCommand(argArray, "stub2");
EXPECT_EQ("stub1", command);
}
TEST(ArgParserTests, assembleCommand_ignoreSecondArgWithOneParameter_returnCommand)
{
std::vector<String> argArray;
argArray.push_back("stub1");
argArray.push_back("stub2");
argArray.push_back("stub3");
argArray.push_back("stub4");
String command = ArgParser::assembleCommand(argArray, "stub2", 1);
EXPECT_EQ("stub1 stub4", command);
}
TEST(ArgParserTests, assembleCommand_stringArrayWithSpace_returnCommand)
{
std::vector<String> argArray;
argArray.push_back("stub1 space");
argArray.push_back("stub2");
argArray.push_back("stub3 space");
String command = ArgParser::assembleCommand(argArray);
EXPECT_EQ("\"stub1 space\" stub2 \"stub3 space\"", command);
}
TEST(ArgParserTests, parseServerArgs_parses_each_category)
{
ArgParser parser(nullptr);
deskflow::ServerArgs args;
args.m_daemon = false;
char const *argv[] = {
"deskflow", "--help"
#if WINAPI_MSWINDOWS
,
"--exit-pause"
#elif WINAPI_XWINDOWS
,
"--no-xinitthreads"
#endif
,
"--res-w", "888"
};
EXPECT_TRUE(parser.parseServerArgs(args, sizeof(argv) / sizeof(argv[0]), argv));
EXPECT_EQ(args.m_shouldExitOk, true);
}
TEST(ArgParserTests, parseClientArgs_parses_single_help)
{
ArgParser parser(nullptr);
deskflow::ClientArgs args;
args.m_daemon = false;
char const *argv[] = {
kAppId,
"--help"
#if WINAPI_MSWINDOWS
,
"--exit-pause"
#elif WINAPI_XWINDOWS
,
"--no-xinitthreads"
#endif
,
"--res-w",
"888",
"127.0.0.1"
};
EXPECT_TRUE(parser.parseClientArgs(args, sizeof(argv) / sizeof(argv[0]), argv));
EXPECT_EQ(args.m_shouldExitOk, true);
}
| 6,378
|
C++
|
.cpp
| 212
| 27.245283
| 83
| 0.720797
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,700
|
ClientArgsParsingTests.cpp
|
deskflow_deskflow/src/test/unittests/deskflow/ClientArgsParsingTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2014-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "deskflow/ArgParser.h"
#include "deskflow/ClientArgs.h"
#include "test/mock/deskflow/MockArgParser.h"
#include <gtest/gtest.h>
#include <array>
using ::testing::_;
using ::testing::Invoke;
using ::testing::NiceMock;
bool client_stubParseGenericArgs(int, const char *const *, int &)
{
return false;
}
bool client_stubCheckUnexpectedArgs()
{
return false;
}
TEST(ClientArgsParsingTests, parseClientArgs_yScrollArg_setYScroll)
{
NiceMock<MockArgParser> argParser;
ON_CALL(argParser, parseGenericArgs(_, _, _)).WillByDefault(Invoke(client_stubParseGenericArgs));
ON_CALL(argParser, checkUnexpectedArgs()).WillByDefault(Invoke(client_stubCheckUnexpectedArgs));
deskflow::ClientArgs clientArgs;
const int argc = 3;
const char *kYScrollCmd[argc] = {"stub", "--yscroll", "1"};
argParser.parseClientArgs(clientArgs, argc, kYScrollCmd);
EXPECT_EQ(1, clientArgs.m_yscroll);
}
TEST(ClientArgsParsingTests, parseClientArgs_setLangSync)
{
NiceMock<MockArgParser> argParser;
ON_CALL(argParser, parseGenericArgs(_, _, _)).WillByDefault(Invoke(client_stubParseGenericArgs));
ON_CALL(argParser, checkUnexpectedArgs()).WillByDefault(Invoke(client_stubCheckUnexpectedArgs));
deskflow::ClientArgs clientArgs;
clientArgs.m_enableLangSync = false;
const int argc = 2;
std::array<const char *, argc> kLangCmd = {"stub", "--sync-language"};
argParser.parseClientArgs(clientArgs, argc, kLangCmd.data());
EXPECT_TRUE(clientArgs.m_enableLangSync);
}
TEST(ClientArgsParsingTests, parseClientArgs_setInvertScroll)
{
NiceMock<MockArgParser> argParser;
deskflow::ClientArgs clientArgs;
const int argc = 2;
std::array<const char *, argc> kLangCmd = {"stub", "--invert-scroll"};
argParser.parseClientArgs(clientArgs, argc, kLangCmd.data());
EXPECT_EQ(clientArgs.m_clientScrollDirection, deskflow::ClientScrollDirection::INVERT_SERVER);
}
TEST(ClientArgsParsingTests, parseClientArgs_setCommonArgs)
{
NiceMock<MockArgParser> argParser;
ON_CALL(argParser, parseGenericArgs(_, _, _)).WillByDefault(Invoke(client_stubParseGenericArgs));
ON_CALL(argParser, checkUnexpectedArgs()).WillByDefault(Invoke(client_stubCheckUnexpectedArgs));
deskflow::ClientArgs clientArgs;
clientArgs.m_enableLangSync = false;
const int argc = 9;
std::array<const char *, argc> kLangCmd = {"stub", "--enable-crypto", "--profile-dir",
"profileDir", "--plugin-dir", "pluginDir",
"--tls-cert", "tlsCertPath", "--prevent-sleep"};
argParser.parseClientArgs(clientArgs, argc, kLangCmd.data());
EXPECT_TRUE(clientArgs.m_enableCrypto);
EXPECT_EQ(clientArgs.m_profileDirectory, "profileDir");
EXPECT_EQ(clientArgs.m_pluginDirectory, "pluginDir");
EXPECT_EQ(clientArgs.m_tlsCertFile, "tlsCertPath");
EXPECT_TRUE(clientArgs.m_preventSleep);
}
TEST(ClientArgsParsingTests, parseClientArgs_addressArg_setDeskflowAddress)
{
NiceMock<MockArgParser> argParser;
ON_CALL(argParser, parseGenericArgs(_, _, _)).WillByDefault(Invoke(client_stubParseGenericArgs));
ON_CALL(argParser, checkUnexpectedArgs()).WillByDefault(Invoke(client_stubCheckUnexpectedArgs));
deskflow::ClientArgs clientArgs;
const int argc = 2;
const char *kAddressCmd[argc] = {"stub", "mock_address"};
bool result = argParser.parseClientArgs(clientArgs, argc, kAddressCmd);
EXPECT_EQ("mock_address", clientArgs.m_serverAddress);
EXPECT_EQ(true, result);
}
TEST(ClientArgsParsingTests, parseClientArgs_noAddressArg_returnFalse)
{
NiceMock<MockArgParser> argParser;
ON_CALL(argParser, parseGenericArgs(_, _, _)).WillByDefault(Invoke(client_stubParseGenericArgs));
ON_CALL(argParser, checkUnexpectedArgs()).WillByDefault(Invoke(client_stubCheckUnexpectedArgs));
deskflow::ClientArgs clientArgs;
const int argc = 1;
const char *kNoAddressCmd[argc] = {"stub"};
bool result = argParser.parseClientArgs(clientArgs, argc, kNoAddressCmd);
EXPECT_FALSE(result);
}
TEST(ClientArgsParsingTests, parseClientArgs_unrecognizedArg_returnFalse)
{
NiceMock<MockArgParser> argParser;
ON_CALL(argParser, parseGenericArgs(_, _, _)).WillByDefault(Invoke(client_stubParseGenericArgs));
ON_CALL(argParser, checkUnexpectedArgs()).WillByDefault(Invoke(client_stubCheckUnexpectedArgs));
deskflow::ClientArgs clientArgs;
const int argc = 3;
const char *kUnrecognizedCmd[argc] = {"stub", "mock_arg", "mock_address"};
bool result = argParser.parseClientArgs(clientArgs, argc, kUnrecognizedCmd);
EXPECT_FALSE(result);
}
| 5,232
|
C++
|
.cpp
| 116
| 41.887931
| 99
| 0.764047
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,701
|
GenericArgsParsingTests.cpp
|
deskflow_deskflow/src/test/unittests/deskflow/GenericArgsParsingTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2014-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "deskflow/ArgParser.h"
#include "deskflow/ArgsBase.h"
#include "test/mock/deskflow/MockApp.h"
#include <gtest/gtest.h>
using namespace deskflow;
using ::testing::_;
using ::testing::Invoke;
using ::testing::NiceMock;
bool g_helpShowed = false;
bool g_versionShowed = false;
void showMockHelp()
{
g_helpShowed = true;
}
void showMockVersion()
{
g_versionShowed = true;
}
class GenericArgsParsingTests : public ::testing::Test
{
public:
void SetUp()
{
m_argParser = new ArgParser(nullptr);
m_argParser->setArgsBase(argsBase);
}
void TearDown()
{
delete m_argParser;
}
static deskflow::ArgsBase argsBase;
ArgParser *m_argParser = nullptr;
};
deskflow::ArgsBase GenericArgsParsingTests::argsBase;
TEST_F(GenericArgsParsingTests, parseGenericArgs_logLevelCmd_setLogLevel)
{
int i = 1;
const int argc = 3;
const char *kLogLevelCmd[argc] = {"stub", "--debug", "DEBUG"};
m_argParser->parseGenericArgs(argc, kLogLevelCmd, i);
String logFilter(argsBase.m_logFilter);
EXPECT_EQ("DEBUG", logFilter);
EXPECT_EQ(2, i);
}
TEST_F(GenericArgsParsingTests, parseGenericArgs_logFileCmd_saveLogFilename)
{
int i = 1;
const int argc = 3;
const char *kLogFileCmd[argc] = {"stub", "--log", "mock_filename"};
m_argParser->parseGenericArgs(argc, kLogFileCmd, i);
String logFile(argsBase.m_logFile);
EXPECT_EQ("mock_filename", logFile);
EXPECT_EQ(2, i);
}
TEST_F(GenericArgsParsingTests, parseGenericArgs_logFileCmdWithSpace_saveLogFilename)
{
int i = 1;
const int argc = 3;
const char *kLogFileCmdWithSpace[argc] = {"stub", "--log", "mo ck_filename"};
m_argParser->parseGenericArgs(argc, kLogFileCmdWithSpace, i);
String logFile(argsBase.m_logFile);
EXPECT_EQ("mo ck_filename", logFile);
EXPECT_EQ(2, i);
}
TEST_F(GenericArgsParsingTests, parseGenericArgs_noDeamonCmd_daemonFalse)
{
int i = 1;
const int argc = 2;
const char *kNoDeamonCmd[argc] = {"stub", "-f"};
m_argParser->parseGenericArgs(argc, kNoDeamonCmd, i);
EXPECT_FALSE(argsBase.m_daemon);
EXPECT_EQ(1, i);
}
TEST_F(GenericArgsParsingTests, parseGenericArgs_deamonCmd_daemonTrue)
{
int i = 1;
const int argc = 2;
const char *kDeamonCmd[argc] = {"stub", "--daemon"};
m_argParser->parseGenericArgs(argc, kDeamonCmd, i);
EXPECT_EQ(true, argsBase.m_daemon);
EXPECT_EQ(1, i);
}
TEST_F(GenericArgsParsingTests, parseGenericArgs_nameCmd_saveName)
{
int i = 1;
const int argc = 3;
const char *kNameCmd[argc] = {"stub", "--name", "mock"};
m_argParser->parseGenericArgs(argc, kNameCmd, i);
EXPECT_EQ("mock", argsBase.m_name);
EXPECT_EQ(2, i);
}
TEST_F(GenericArgsParsingTests, parseGenericArgs_noRestartCmd_restartFalse)
{
int i = 1;
const int argc = 2;
const char *kNoRestartCmd[argc] = {"stub", "--no-restart"};
m_argParser->parseGenericArgs(argc, kNoRestartCmd, i);
EXPECT_FALSE(argsBase.m_restartable);
EXPECT_EQ(1, i);
}
TEST_F(GenericArgsParsingTests, parseGenericArgs_restartCmd_restartTrue)
{
int i = 1;
const int argc = 2;
const char *kRestartCmd[argc] = {"stub", "--restart"};
m_argParser->parseGenericArgs(argc, kRestartCmd, i);
EXPECT_EQ(true, argsBase.m_restartable);
EXPECT_EQ(1, i);
}
TEST_F(GenericArgsParsingTests, parseGenericArgs_backendCmd_rejected)
{
int i = 1;
const int argc = 2;
const char *kBackendCmd[argc] = {"stub", "-z"};
EXPECT_FALSE(m_argParser->parseGenericArgs(argc, kBackendCmd, i));
}
TEST_F(GenericArgsParsingTests, parseGenericArgs_noHookCmd_noHookTrue)
{
int i = 1;
const int argc = 2;
const char *kNoHookCmd[argc] = {"stub", "--no-hooks"};
m_argParser->parseGenericArgs(argc, kNoHookCmd, i);
EXPECT_EQ(true, argsBase.m_noHooks);
EXPECT_EQ(1, i);
}
TEST_F(GenericArgsParsingTests, parseGenericArgs_helpCmd_showHelp)
{
g_helpShowed = false;
int i = 1;
const int argc = 2;
const char *kHelpCmd[argc] = {"stub", "--help"};
NiceMock<MockApp> app;
ArgParser argParser(&app);
argParser.setArgsBase(argsBase);
ON_CALL(app, help()).WillByDefault(Invoke(showMockHelp));
argParser.parseGenericArgs(argc, kHelpCmd, i);
EXPECT_EQ(true, g_helpShowed);
EXPECT_EQ(1, i);
}
TEST_F(GenericArgsParsingTests, parseGenericArgs_versionCmd_showVersion)
{
g_versionShowed = false;
int i = 1;
const int argc = 2;
const char *kVersionCmd[argc] = {"stub", "--version"};
NiceMock<MockApp> app;
ArgParser argParser(&app);
argParser.setArgsBase(argsBase);
ON_CALL(app, version()).WillByDefault(Invoke(showMockVersion));
argParser.parseGenericArgs(argc, kVersionCmd, i);
EXPECT_EQ(true, g_versionShowed);
EXPECT_EQ(1, i);
}
TEST_F(GenericArgsParsingTests, parseGenericArgs_noTrayCmd_disableTrayTrue)
{
int i = 1;
const int argc = 2;
const char *kNoTrayCmd[argc] = {"stub", "--no-tray"};
m_argParser->parseGenericArgs(argc, kNoTrayCmd, i);
EXPECT_EQ(true, argsBase.m_disableTray);
EXPECT_EQ(1, i);
}
TEST_F(GenericArgsParsingTests, parseGenericArgs_ipcCmd_enableIpcTrue)
{
int i = 1;
const int argc = 2;
const char *kIpcCmd[argc] = {"stub", "--ipc"};
m_argParser->parseGenericArgs(argc, kIpcCmd, i);
EXPECT_EQ(true, argsBase.m_enableIpc);
EXPECT_EQ(1, i);
}
#ifndef WINAPI_XWINDOWS
TEST_F(GenericArgsParsingTests, parseGenericArgs_dragDropCmdOnNonLinux_enableDragDropTrue)
{
int i = 1;
const int argc = 2;
const char *kDragDropCmd[argc] = {"stub", "--enable-drag-drop"};
m_argParser->parseGenericArgs(argc, kDragDropCmd, i);
EXPECT_EQ(true, argsBase.m_enableDragDrop);
EXPECT_EQ(1, i);
}
#endif
#ifdef WINAPI_XWINDOWS
TEST_F(GenericArgsParsingTests, parseGenericArgs_dragDropCmdOnLinux_enableDragDropFalse)
{
int i = 1;
const int argc = 2;
const char *kDragDropCmd[argc] = {"stub", "--enable-drag-drop"};
m_argParser->parseGenericArgs(argc, kDragDropCmd, i);
EXPECT_FALSE(argsBase.m_enableDragDrop);
EXPECT_EQ(1, i);
}
#endif
| 6,564
|
C++
|
.cpp
| 209
| 28.870813
| 90
| 0.738205
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,702
|
IKeyStateTests.cpp
|
deskflow_deskflow/src/test/unittests/deskflow/IKeyStateTests.cpp
|
#include "lib/deskflow/IKeyState.h"
#include <gtest/gtest.h>
TEST(IKeyStateTests, KeyInfo_alloc_destinations)
{
auto info = IKeyState::KeyInfo::alloc(1, 2, 3, 4, {"test1", "test2"});
EXPECT_STREQ(info->m_screensBuffer, ":test1:test2:");
}
| 246
|
C++
|
.cpp
| 7
| 33.142857
| 72
| 0.720339
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,703
|
ClipboardTests.cpp
|
deskflow_deskflow/src/test/unittests/deskflow/ClipboardTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2011 Nick Bolton
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "deskflow/Clipboard.h"
#include <gtest/gtest.h>
TEST(ClipboardTests, empty_openCalled_returnsTrue)
{
Clipboard clipboard;
clipboard.open(0);
bool actual = clipboard.empty();
EXPECT_EQ(true, actual);
}
TEST(ClipboardTests, empty_singleFormat_hasReturnsFalse)
{
Clipboard clipboard;
clipboard.open(0);
clipboard.add(Clipboard::kText, "synergy rocks!");
clipboard.empty();
bool actual = clipboard.has(Clipboard::kText);
EXPECT_FALSE(actual);
}
TEST(ClipboardTests, add_newValue_valueWasStored)
{
Clipboard clipboard;
clipboard.open(0);
clipboard.add(IClipboard::kText, "synergy rocks!");
String actual = clipboard.get(IClipboard::kText);
EXPECT_EQ("synergy rocks!", actual);
}
TEST(ClipboardTests, add_replaceValue_valueWasReplaced)
{
Clipboard clipboard;
clipboard.open(0);
clipboard.add(IClipboard::kText, "synergy rocks!");
clipboard.add(IClipboard::kText, "maxivista sucks"); // haha, just kidding.
String actual = clipboard.get(IClipboard::kText);
EXPECT_EQ("maxivista sucks", actual);
}
TEST(ClipboardTests, open_timeIsZero_returnsTrue)
{
Clipboard clipboard;
bool actual = clipboard.open(0);
EXPECT_EQ(true, actual);
}
TEST(ClipboardTests, open_timeIsOne_returnsTrue)
{
Clipboard clipboard;
bool actual = clipboard.open(1);
EXPECT_EQ(true, actual);
}
TEST(ClipboardTests, close_isOpen_noErrors)
{
Clipboard clipboard;
clipboard.open(0);
clipboard.close();
// can't assert anything
}
TEST(ClipboardTests, getTime_openWithNoEmpty_returnsZero)
{
Clipboard clipboard;
clipboard.open(1);
Clipboard::Time actual = clipboard.getTime();
EXPECT_EQ(0, actual);
}
TEST(ClipboardTests, getTime_openAndEmpty_returnsOne)
{
Clipboard clipboard;
clipboard.open(1);
clipboard.empty();
Clipboard::Time actual = clipboard.getTime();
EXPECT_EQ(1, actual);
}
TEST(ClipboardTests, has_withFormatAdded_returnsTrue)
{
Clipboard clipboard;
clipboard.open(0);
clipboard.add(IClipboard::kText, "synergy rocks!");
bool actual = clipboard.has(IClipboard::kText);
EXPECT_EQ(true, actual);
}
TEST(ClipboardTests, has_withNoFormats_returnsFalse)
{
Clipboard clipboard;
clipboard.open(0);
bool actual = clipboard.has(IClipboard::kText);
EXPECT_FALSE(actual);
}
TEST(ClipboardTests, get_withNoFormats_returnsEmpty)
{
Clipboard clipboard;
clipboard.open(0);
String actual = clipboard.get(IClipboard::kText);
EXPECT_EQ("", actual);
}
TEST(ClipboardTests, get_withFormatAdded_returnsExpected)
{
Clipboard clipboard;
clipboard.open(0);
clipboard.add(IClipboard::kText, "synergy rocks!");
String actual = clipboard.get(IClipboard::kText);
EXPECT_EQ("synergy rocks!", actual);
}
TEST(ClipboardTests, marshall_addNotCalled_firstCharIsZero)
{
Clipboard clipboard;
String actual = clipboard.marshall();
// seems to return "\0\0\0\0" but EXPECT_EQ can't assert this,
// so instead, just assert that first char is '\0'.
EXPECT_EQ(0, (int)actual[0]);
}
TEST(ClipboardTests, marshall_withTextAdded_typeCharIsText)
{
Clipboard clipboard;
clipboard.open(0);
clipboard.add(IClipboard::kText, "synergy rocks!");
clipboard.close();
String actual = clipboard.marshall();
// string contains other data, but 8th char should be kText.
EXPECT_EQ(IClipboard::kText, (int)actual[7]);
}
TEST(ClipboardTests, marshall_withTextAdded_lastSizeCharIs14)
{
Clipboard clipboard;
clipboard.open(0);
clipboard.add(IClipboard::kText, "synergy rocks!"); // 14 chars
clipboard.close();
String actual = clipboard.marshall();
EXPECT_EQ(14, (int)actual[11]);
}
// TODO: there's some integer -> char encoding going on here. i find it
// hard to believe that the clipboard is the only thing doing this. maybe
// we should refactor this stuff out of the clipboard.
TEST(ClipboardTests, marshall_withTextSize285_sizeCharsValid)
{
// 285 chars
String data;
data.append("Synergy is Free and Open Source Software that lets you ");
data.append("easily share your mouse and keyboard between multiple ");
data.append("computers, where each computer has it's own display. No ");
data.append("special hardware is required, all you need is a local area ");
data.append("network. Synergy is supported on Windows, Mac OS X and Linux.");
Clipboard clipboard;
clipboard.open(0);
clipboard.add(IClipboard::kText, data);
clipboard.close();
String actual = clipboard.marshall();
// 4 asserts here, but that's ok because we're really just asserting 1
// thing. the 32-bit size value is split into 4 chars. if the size is 285
// (29 more than the 8-bit max size), the last char "rolls over" to 29
// (this is caused by a bit-wise & on 0xff and 8-bit truncation). each
// char before the last stores a bit-shifted version of the number, each
// 1 more power than the last, which is done by bit-shifting [0] by 24,
// [1] by 16, [2] by 8 ([3] is not bit-shifted).
EXPECT_EQ(0, actual[8]); // 285 >> 24 = 285 / (256^3) = 0
EXPECT_EQ(0, actual[9]); // 285 >> 16 = 285 / (256^2) = 0
EXPECT_EQ(1, actual[10]); // 285 >> 8 = 285 / (256^1) = 1(.11328125)
EXPECT_EQ(29, actual[11]); // 285 - 256 = 29
}
TEST(ClipboardTests, marshall_withHtmlAdded_typeCharIsHtml)
{
Clipboard clipboard;
clipboard.open(0);
clipboard.add(IClipboard::kHTML, "html sucks");
clipboard.close();
String actual = clipboard.marshall();
// string contains other data, but 8th char should be kHTML.
EXPECT_EQ(IClipboard::kHTML, (int)actual[7]);
}
TEST(ClipboardTests, marshall_withHtmlAndText_has2Formats)
{
Clipboard clipboard;
clipboard.open(0);
clipboard.add(IClipboard::kText, "synergy rocks");
clipboard.add(IClipboard::kHTML, "html sucks");
clipboard.close();
String actual = clipboard.marshall();
// the number of formats is stored inside the first 4 chars.
// the writeUInt32 function right-aligns numbers in 4 chars,
// so if you right align 2, it will be "\0\0\0\2" in a string.
// we assert that the char at the 4th index is 2 (the number of
// formats that we've added).
EXPECT_EQ(2, (int)actual[3]);
}
TEST(ClipboardTests, marshall_withTextAdded_endsWithAdded)
{
Clipboard clipboard;
clipboard.open(0);
clipboard.add(IClipboard::kText, "synergy rocks!");
clipboard.close();
String actual = clipboard.marshall();
// string contains other data, but should end in the string we added.
EXPECT_EQ("synergy rocks!", actual.substr(12));
}
TEST(ClipboardTests, unmarshall_emptyData_hasTextIsFalse)
{
Clipboard clipboard;
String data;
data += (char)0;
data += (char)0;
data += (char)0;
data += (char)0; // 0 formats added
clipboard.unmarshall(data, 0);
clipboard.open(0);
bool actual = clipboard.has(IClipboard::kText);
EXPECT_FALSE(actual);
}
TEST(ClipboardTests, unmarshall_withTextSize285_getTextIsValid)
{
Clipboard clipboard;
// 285 chars
String text;
text.append("Synergy is Free and Open Source Software that lets you ");
text.append("easily share your mouse and keyboard between multiple ");
text.append("computers, where each computer has it's own display. No ");
text.append("special hardware is required, all you need is a local area ");
text.append("network. Synergy is supported on Windows, Mac OS X and Linux.");
String data;
data += (char)0;
data += (char)0;
data += (char)0;
data += (char)1; // 1 format added
data += (char)0;
data += (char)0;
data += (char)0;
data += (char)IClipboard::kText;
data += (char)0; // 285 >> 24 = 285 / (256^3) = 0
data += (char)0; // 285 >> 16 = 285 / (256^2) = 0
data += (char)1; // 285 >> 8 = 285 / (256^1) = 1(.11328125)
data += (char)29; // 285 - 256 = 29
data += text;
clipboard.unmarshall(data, 0);
clipboard.open(0);
String actual = clipboard.get(IClipboard::kText);
EXPECT_EQ(text, actual);
}
TEST(ClipboardTests, unmarshall_withTextAndHtml_getTextIsValid)
{
Clipboard clipboard;
String data;
data += (char)0;
data += (char)0;
data += (char)0;
data += (char)2; // 2 formats added
data += (char)0;
data += (char)0;
data += (char)0;
data += (char)IClipboard::kText;
data += (char)0;
data += (char)0;
data += (char)0;
data += (char)14;
data += "synergy rocks!";
data += (char)0;
data += (char)0;
data += (char)0;
data += (char)IClipboard::kHTML;
data += (char)0;
data += (char)0;
data += (char)0;
data += (char)10;
data += "html sucks";
clipboard.unmarshall(data, 0);
clipboard.open(0);
String actual = clipboard.get(IClipboard::kText);
EXPECT_EQ("synergy rocks!", actual);
}
TEST(ClipboardTests, unmarshall_withTextAndHtml_getHtmlIsValid)
{
Clipboard clipboard;
String data;
data += (char)0;
data += (char)0;
data += (char)0;
data += (char)2; // 2 formats added
data += (char)0;
data += (char)0;
data += (char)0;
data += (char)IClipboard::kText;
data += (char)0;
data += (char)0;
data += (char)0;
data += (char)14;
data += "synergy rocks!";
data += (char)0;
data += (char)0;
data += (char)0;
data += (char)IClipboard::kHTML;
data += (char)0;
data += (char)0;
data += (char)0;
data += (char)10;
data += "html sucks";
clipboard.unmarshall(data, 0);
clipboard.open(0);
String actual = clipboard.get(IClipboard::kHTML);
EXPECT_EQ("html sucks", actual);
}
TEST(ClipboardTests, copy_withSingleText_clipboardsAreEqual)
{
Clipboard clipboard1;
clipboard1.open(0);
clipboard1.add(Clipboard::kText, "synergy rocks!");
clipboard1.close();
Clipboard clipboard2;
Clipboard::copy(&clipboard2, &clipboard1);
clipboard2.open(0);
String actual = clipboard2.get(Clipboard::kText);
EXPECT_EQ("synergy rocks!", actual);
}
| 10,403
|
C++
|
.cpp
| 323
| 29.50774
| 79
| 0.717772
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
13,704
|
KeyStateTests.cpp
|
deskflow_deskflow/src/test/unittests/deskflow/KeyStateTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2011 Nick Bolton
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "test/mock/deskflow/MockEventQueue.h"
#include "test/mock/deskflow/MockKeyMap.h"
#include "test/mock/deskflow/MockKeyState.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using ::testing::_;
using ::testing::Invoke;
using ::testing::NiceMock;
using ::testing::Return;
using ::testing::ReturnRef;
using ::testing::SaveArg;
void stubPollPressedKeys(IKeyState::KeyButtonSet &pressedKeys);
void assertMaskIsOne(ForeachKeyCallback cb, void *userData);
const deskflow::KeyMap::KeyItem *stubMapKey(
deskflow::KeyMap::Keystrokes &keys, KeyID id, SInt32 group, deskflow::KeyMap::ModifierToKeys &activeModifiers,
KeyModifierMask ¤tState, KeyModifierMask desiredMask, bool isAutoRepeat, const String &lang
);
deskflow::KeyMap::Keystroke s_stubKeystroke(1, false, false);
deskflow::KeyMap::KeyItem s_stubKeyItem;
TEST(CKeyStateTests, onKey_aKeyDown_keyStateOne)
{
MockKeyMap keyMap;
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
keyState.onKey(1, true, KeyModifierAlt);
EXPECT_EQ(1, keyState.getKeyState(1));
}
TEST(KeyStateTests, onKey_aKeyUp_keyStateZero)
{
MockKeyMap keyMap;
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
keyState.onKey(1, false, KeyModifierAlt);
EXPECT_EQ(0, keyState.getKeyState(1));
}
TEST(KeyStateTests, onKey_invalidKey_keyStateZero)
{
MockKeyMap keyMap;
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
keyState.onKey(0, true, KeyModifierAlt);
EXPECT_EQ(0, keyState.getKeyState(0));
}
TEST(KeyStateTests, sendKeyEvent_halfDuplexAndRepeat_addEventNotCalled)
{
NiceMock<MockKeyMap> keyMap;
NiceMock<MockEventQueue> eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
ON_CALL(keyMap, isHalfDuplex(_, _)).WillByDefault(Return(true));
EXPECT_CALL(eventQueue, addEvent(_)).Times(0);
keyState.sendKeyEvent(NULL, false, true, kKeyCapsLock, 0, 0, 0);
}
TEST(KeyStateTests, sendKeyEvent_halfDuplex_addEventCalledTwice)
{
NiceMock<MockKeyMap> keyMap;
NiceMock<MockEventQueue> eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
IKeyStateEvents keyStateEvents;
keyStateEvents.setEvents(&eventQueue);
ON_CALL(keyMap, isHalfDuplex(_, _)).WillByDefault(Return(true));
ON_CALL(eventQueue, forIKeyState()).WillByDefault(ReturnRef(keyStateEvents));
EXPECT_CALL(eventQueue, addEvent(_)).Times(2);
keyState.sendKeyEvent(NULL, false, false, kKeyCapsLock, 0, 0, 0);
}
TEST(KeyStateTests, sendKeyEvent_keyRepeat_addEventCalledOnce)
{
NiceMock<MockKeyMap> keyMap;
NiceMock<MockEventQueue> eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
IKeyStateEvents keyStateEvents;
keyStateEvents.setEvents(&eventQueue);
ON_CALL(eventQueue, forIKeyState()).WillByDefault(ReturnRef(keyStateEvents));
EXPECT_CALL(eventQueue, addEvent(_)).Times(1);
keyState.sendKeyEvent(NULL, false, true, 1, 0, 0, 0);
}
TEST(KeyStateTests, sendKeyEvent_keyDown_addEventCalledOnce)
{
NiceMock<MockKeyMap> keyMap;
NiceMock<MockEventQueue> eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
IKeyStateEvents keyStateEvents;
keyStateEvents.setEvents(&eventQueue);
ON_CALL(eventQueue, forIKeyState()).WillByDefault(ReturnRef(keyStateEvents));
EXPECT_CALL(eventQueue, addEvent(_)).Times(1);
keyState.sendKeyEvent(NULL, true, false, 1, 0, 0, 0);
}
TEST(KeyStateTests, sendKeyEvent_keyUp_addEventCalledOnce)
{
NiceMock<MockKeyMap> keyMap;
NiceMock<MockEventQueue> eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
IKeyStateEvents keyStateEvents;
keyStateEvents.setEvents(&eventQueue);
ON_CALL(eventQueue, forIKeyState()).WillByDefault(ReturnRef(keyStateEvents));
EXPECT_CALL(eventQueue, addEvent(_)).Times(1);
keyState.sendKeyEvent(NULL, false, false, 1, 0, 0, 0);
}
TEST(KeyStateTests, updateKeyMap_mockKeyMap_keyMapGotMock)
{
NiceMock<MockKeyMap> keyMap;
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
// key map member gets a new key map via swap()
EXPECT_CALL(keyMap, swap(_));
keyState.updateKeyMap();
}
TEST(KeyStateTests, updateKeyState_pollInsertsSingleKey_keyIsDown)
{
NiceMock<MockKeyMap> keyMap;
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
ON_CALL(keyState, pollPressedKeys(_)).WillByDefault(Invoke(stubPollPressedKeys));
keyState.updateKeyState();
bool actual = keyState.isKeyDown(1);
ASSERT_TRUE(actual);
}
TEST(KeyStateTests, updateKeyState_pollDoesNothing_keyNotSet)
{
NiceMock<MockKeyMap> keyMap;
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
keyState.updateKeyState();
bool actual = keyState.isKeyDown(1);
ASSERT_FALSE(actual);
}
TEST(KeyStateTests, updateKeyState_activeModifiers_maskSet)
{
NiceMock<MockKeyMap> keyMap;
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
ON_CALL(keyState, pollActiveModifiers()).WillByDefault(Return(KeyModifierAlt));
keyState.updateKeyState();
KeyModifierMask actual = keyState.getActiveModifiers();
ASSERT_EQ(KeyModifierAlt, actual);
}
TEST(KeyStateTests, updateKeyState_activeModifiers_maskNotSet)
{
NiceMock<MockKeyMap> keyMap;
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
keyState.updateKeyState();
KeyModifierMask actual = keyState.getActiveModifiers();
ASSERT_EQ(0, actual);
}
TEST(KeyStateTests, updateKeyState_activeModifiers_keyMapGotModifers)
{
MockKeyMap keyMap;
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
ON_CALL(keyState, pollActiveModifiers()).WillByDefault(Return(1));
ON_CALL(keyMap, foreachKey(_, _)).WillByDefault(Invoke(assertMaskIsOne));
// key map gets new modifiers via foreachKey()
EXPECT_CALL(keyMap, foreachKey(_, _));
keyState.updateKeyState();
}
TEST(KeyStateTests, setHalfDuplexMask_capsLock_halfDuplexCapsLockAdded)
{
MockKeyMap keyMap;
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
EXPECT_CALL(keyMap, addHalfDuplexModifier(kKeyCapsLock));
keyState.setHalfDuplexMask(KeyModifierCapsLock);
}
TEST(KeyStateTests, setHalfDuplexMask_numLock_halfDuplexNumLockAdded)
{
MockKeyMap keyMap;
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
EXPECT_CALL(keyMap, addHalfDuplexModifier(kKeyNumLock));
keyState.setHalfDuplexMask(KeyModifierNumLock);
}
TEST(KeyStateTests, setHalfDuplexMask_scrollLock_halfDuplexScollLockAdded)
{
MockKeyMap keyMap;
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
EXPECT_CALL(keyMap, addHalfDuplexModifier(kKeyScrollLock));
keyState.setHalfDuplexMask(KeyModifierScrollLock);
}
TEST(KeyStateTests, fakeKeyDown_serverKeyAlreadyDown_fakeKeyCalledTwice)
{
NiceMock<MockKeyMap> keyMap;
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
s_stubKeyItem.m_client = 0;
s_stubKeyItem.m_button = 1;
ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)).WillByDefault(Invoke(stubMapKey));
// 2 calls to fakeKeyDown should still call fakeKey, even though
// repeated keys are handled differently.
EXPECT_CALL(keyState, fakeKey(_)).Times(2);
// call twice to simulate server key already down (a misreported autorepeat).
keyState.fakeKeyDown(1, 0, 0, "en");
keyState.fakeKeyDown(1, 0, 0, "en");
}
TEST(KeyStateTests, fakeKeyDown_isIgnoredKey_fakeKeyNotCalled)
{
MockKeyMap keyMap;
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
EXPECT_CALL(keyState, fakeKey(_)).Times(0);
keyState.fakeKeyDown(kKeyCapsLock, 0, 0, "en");
}
TEST(KeyStateTests, fakeKeyDown_mapReturnsKeystrokes_fakeKeyCalled)
{
NiceMock<MockKeyMap> keyMap;
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
s_stubKeyItem.m_button = 0;
s_stubKeyItem.m_client = 0;
ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)).WillByDefault(Invoke(stubMapKey));
EXPECT_CALL(keyState, fakeKey(_)).Times(1);
keyState.fakeKeyDown(1, 0, 0, "en");
}
TEST(KeyStateTests, fakeKeyRepeat_invalidKey_returnsFalse)
{
MockKeyMap keyMap;
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
bool actual = keyState.fakeKeyRepeat(0, 0, 0, 0, "en");
ASSERT_FALSE(actual);
}
TEST(KeyStateTests, fakeKeyRepeat_nullKey_returnsFalse)
{
NiceMock<MockKeyMap> keyMap;
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
// set the key to down (we need to make mapKey return a valid key to do this).
deskflow::KeyMap::KeyItem keyItem;
keyItem.m_client = 0;
keyItem.m_button = 1;
ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)).WillByDefault(Return(&keyItem));
keyState.fakeKeyDown(1, 0, 0, "en");
// change mapKey to return NULL so that fakeKeyRepeat exits early.
deskflow::KeyMap::KeyItem *nullKeyItem = NULL;
ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)).WillByDefault(Return(nullKeyItem));
bool actual = keyState.fakeKeyRepeat(1, 0, 0, 0, "en");
ASSERT_FALSE(actual);
}
TEST(KeyStateTests, fakeKeyRepeat_invalidButton_returnsFalse)
{
NiceMock<MockKeyMap> keyMap;
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
// set the key to down (we need to make mapKey return a valid key to do this).
deskflow::KeyMap::KeyItem keyItem;
keyItem.m_client = 0;
keyItem.m_button = 1; // set to 1 to make fakeKeyDown work.
ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)).WillByDefault(Return(&keyItem));
keyState.fakeKeyDown(1, 0, 0, "en");
// change button to 0 so that fakeKeyRepeat will return early.
keyItem.m_button = 0;
ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)).WillByDefault(Return(&keyItem));
bool actual = keyState.fakeKeyRepeat(1, 0, 0, 0, "en");
ASSERT_FALSE(actual);
}
TEST(KeyStateTests, fakeKeyRepeat_validKey_returnsTrue)
{
NiceMock<MockKeyMap> keyMap;
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
s_stubKeyItem.m_client = 0;
s_stubKeystroke.m_type = deskflow::KeyMap::Keystroke::kButton;
s_stubKeystroke.m_data.m_button.m_button = 2;
// set the button to 1 for fakeKeyDown call
s_stubKeyItem.m_button = 1;
ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)).WillByDefault(Invoke(stubMapKey));
keyState.fakeKeyDown(1, 0, 0, "en");
// change the button to 2
s_stubKeyItem.m_button = 2;
ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)).WillByDefault(Invoke(stubMapKey));
bool actual = keyState.fakeKeyRepeat(1, 0, 0, 0, "en");
ASSERT_TRUE(actual);
}
TEST(KeyStateTests, fakeKeyUp_buttonNotDown_returnsFalse)
{
MockKeyMap keyMap;
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
bool actual = keyState.fakeKeyUp(0);
ASSERT_FALSE(actual);
}
TEST(KeyStateTests, fakeKeyUp_buttonAlreadyDown_returnsTrue)
{
NiceMock<MockKeyMap> keyMap;
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
// press alt down so we get full coverage.
ON_CALL(keyState, pollActiveModifiers()).WillByDefault(Return(KeyModifierAlt));
keyState.updateKeyState();
// press button 1 down.
s_stubKeyItem.m_button = 1;
ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)).WillByDefault(Invoke(stubMapKey));
keyState.fakeKeyDown(1, 0, 1, "en");
// this takes the button id, which is the 3rd arg of fakeKeyDown
bool actual = keyState.fakeKeyUp(1);
ASSERT_TRUE(actual);
}
TEST(KeyStateTests, fakeAllKeysUp_keysWereDown_keysAreUp)
{
NiceMock<MockKeyMap> keyMap;
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
// press button 1 down.
s_stubKeyItem.m_button = 1;
ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)).WillByDefault(Invoke(stubMapKey));
keyState.fakeKeyDown(1, 0, 1, "en");
// method under test
keyState.fakeAllKeysUp();
bool actual = keyState.isKeyDown(1);
ASSERT_FALSE(actual);
}
TEST(KeyStateTests, isKeyDown_keyDown_returnsTrue)
{
NiceMock<MockKeyMap> keyMap;
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
// press button 1 down.
s_stubKeyItem.m_button = 1;
ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)).WillByDefault(Invoke(stubMapKey));
keyState.fakeKeyDown(1, 0, 1, "en");
// method under test
bool actual = keyState.isKeyDown(1);
ASSERT_TRUE(actual);
}
TEST(KeyStateTests, isKeyDown_noKeysDown_returnsFalse)
{
MockKeyMap keyMap;
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
// method under test
bool actual = keyState.isKeyDown(1);
ASSERT_FALSE(actual);
}
TEST(KeyStateTests, updateKeyMap_exercised)
{
deskflow::KeyMap keyMap;
deskflow::KeyMap::KeyItem keyItem;
keyItem.m_button = 'A';
keyItem.m_group = 1;
keyItem.m_id = 'A';
keyMap.addKeyEntry(keyItem);
keyMap.finish();
MockEventQueue eventQueue;
KeyStateImpl keyState(eventQueue, keyMap);
keyState.updateKeyMap(&keyMap);
}
void stubPollPressedKeys(IKeyState::KeyButtonSet &pressedKeys)
{
pressedKeys.insert(1);
}
void assertMaskIsOne(ForeachKeyCallback cb, void *userData)
{
ASSERT_EQ(1, ((KeyState::AddActiveModifierContext *)userData)->m_mask);
}
const deskflow::KeyMap::KeyItem *
stubMapKey(deskflow::KeyMap::Keystrokes &keys, KeyID, SInt32, deskflow::KeyMap::ModifierToKeys &, KeyModifierMask &, KeyModifierMask, bool, const String &)
{
keys.push_back(s_stubKeystroke);
return &s_stubKeyItem;
}
| 13,989
|
C++
|
.cpp
| 377
| 34.461538
| 155
| 0.769521
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,706
|
ServerArgsParsingTests.cpp
|
deskflow_deskflow/src/test/unittests/deskflow/ServerArgsParsingTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2014-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "deskflow/ArgParser.h"
#include "deskflow/ServerArgs.h"
#include "test/mock/deskflow/MockArgParser.h"
#include <array>
#include <gtest/gtest.h>
using ::testing::_;
using ::testing::Invoke;
using ::testing::NiceMock;
bool server_stubParseGenericArgs(int, const char *const *, int &)
{
return false;
}
bool server_stubCheckUnexpectedArgs()
{
return false;
}
TEST(ServerArgs, ServerArgs_will_construct_from_copy)
{
deskflow::ServerArgs serverArgs;
serverArgs.m_display = "display0";
deskflow::ServerArgs serverArgs2{serverArgs};
EXPECT_EQ(serverArgs.m_display, serverArgs2.m_display);
}
TEST(ServerArgsParsingTests, parseServerArgs_addressArg_setDeskflowAddress)
{
NiceMock<MockArgParser> argParser;
ON_CALL(argParser, parseGenericArgs(_, _, _)).WillByDefault(Invoke(server_stubParseGenericArgs));
ON_CALL(argParser, checkUnexpectedArgs()).WillByDefault(Invoke(server_stubCheckUnexpectedArgs));
deskflow::ServerArgs serverArgs;
const int argc = 3;
const char *kAddressCmd[argc] = {"stub", "--address", "mock_address"};
argParser.parseServerArgs(serverArgs, argc, kAddressCmd);
EXPECT_EQ("mock_address", serverArgs.m_deskflowAddress);
}
TEST(ServerArgsParsingTests, parseServerArgs_configArg_setConfigFile)
{
NiceMock<MockArgParser> argParser;
ON_CALL(argParser, parseGenericArgs(_, _, _)).WillByDefault(Invoke(server_stubParseGenericArgs));
ON_CALL(argParser, checkUnexpectedArgs()).WillByDefault(Invoke(server_stubCheckUnexpectedArgs));
deskflow::ServerArgs serverArgs;
const int argc = 3;
const char *kConfigCmd[argc] = {"stub", "--config", "mock_configFile"};
argParser.parseServerArgs(serverArgs, argc, kConfigCmd);
EXPECT_EQ("mock_configFile", serverArgs.m_configFile);
}
TEST(ServerArgsParsingTests, parseServerArgs_checkUnexpectedParams)
{
NiceMock<MockArgParser> argParser;
ON_CALL(argParser, parseGenericArgs(_, _, _)).WillByDefault(Invoke(server_stubParseGenericArgs));
ON_CALL(argParser, checkUnexpectedArgs()).WillByDefault(Invoke(server_stubCheckUnexpectedArgs));
deskflow::ServerArgs serverArgs;
const int argc = 2;
std::array<const char *, argc> kUnknownCmd = {"stub", "--unknown"};
EXPECT_FALSE(argParser.parseServerArgs(serverArgs, argc, kUnknownCmd.data()));
}
| 2,948
|
C++
|
.cpp
| 71
| 39.295775
| 99
| 0.78065
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,707
|
DeprecatedArgsParsingTests.cpp
|
deskflow_deskflow/src/test/unittests/deskflow/DeprecatedArgsParsingTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2015-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "deskflow/ArgParser.h"
#include <gtest/gtest.h>
using namespace deskflow;
TEST(DeprecatedArgsParsingTests, parseDeprecatedArgs_cryptoPass_returnTrue)
{
int i = 1;
const int argc = 3;
const char *kCryptoPassCmd[argc] = {"stub", "--crypto-pass", "mock_pass"};
ArgParser argParser(NULL);
bool result = argParser.parseDeprecatedArgs(argc, kCryptoPassCmd, i);
EXPECT_EQ(true, result);
EXPECT_EQ(2, i);
}
TEST(DeprecatedArgsParsingTests, parseDeprecatedArgs_cryptoPass_returnFalse)
{
int i = 1;
const int argc = 3;
const char *kCryptoPassCmd[argc] = {"stub", "--mock-arg", "mock_value"};
ArgParser argParser(NULL);
bool result = argParser.parseDeprecatedArgs(argc, kCryptoPassCmd, i);
EXPECT_FALSE(result);
EXPECT_EQ(1, i);
}
| 1,459
|
C++
|
.cpp
| 39
| 35.025641
| 76
| 0.753726
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,708
|
KeyMapTests.cpp
|
deskflow_deskflow/src/test/unittests/deskflow/KeyMapTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2016 Symless
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#define TEST_ENV
#include "deskflow/KeyMap.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using ::testing::_;
using ::testing::Invoke;
using ::testing::NiceMock;
using ::testing::Return;
using ::testing::ReturnRef;
using ::testing::SaveArg;
namespace deskflow {
TEST(KeyMapTests, findBestKey_requiredDown_matchExactFirstItem)
{
KeyMap keyMap;
KeyMap::KeyEntryList entryList;
KeyMap::KeyItemList itemList;
KeyMap::KeyItem item;
item.m_required = KeyModifierShift;
item.m_sensitive = KeyModifierShift;
KeyModifierMask desiredState = KeyModifierShift;
itemList.push_back(item);
entryList.push_back(itemList);
EXPECT_EQ(0, keyMap.findBestKey(entryList, desiredState));
}
TEST(KeyMapTests, findBestKey_requiredAndExtraSensitiveDown_matchExactFirstItem)
{
KeyMap keyMap;
KeyMap::KeyEntryList entryList;
KeyMap::KeyItemList itemList;
KeyMap::KeyItem item;
item.m_required = KeyModifierShift;
item.m_sensitive = KeyModifierShift | KeyModifierAlt;
KeyModifierMask desiredState = KeyModifierShift;
itemList.push_back(item);
entryList.push_back(itemList);
EXPECT_EQ(0, keyMap.findBestKey(entryList, desiredState));
}
TEST(KeyMapTests, findBestKey_requiredAndExtraSensitiveDown_matchExactSecondItem)
{
KeyMap keyMap;
KeyMap::KeyEntryList entryList;
KeyMap::KeyItemList itemList1;
KeyMap::KeyItem item1;
item1.m_required = KeyModifierAlt;
item1.m_sensitive = KeyModifierShift | KeyModifierAlt;
KeyMap::KeyItemList itemList2;
KeyMap::KeyItem item2;
item2.m_required = KeyModifierShift;
item2.m_sensitive = KeyModifierShift | KeyModifierAlt;
KeyModifierMask desiredState = KeyModifierShift;
itemList1.push_back(item1);
itemList2.push_back(item2);
entryList.push_back(itemList1);
entryList.push_back(itemList2);
EXPECT_EQ(1, keyMap.findBestKey(entryList, desiredState));
}
TEST(KeyMapTests, findBestKey_extraSensitiveDown_matchExactSecondItem)
{
KeyMap keyMap;
KeyMap::KeyEntryList entryList;
KeyMap::KeyItemList itemList1;
KeyMap::KeyItem item1;
item1.m_required = 0;
item1.m_sensitive = KeyModifierAlt;
KeyMap::KeyItemList itemList2;
KeyMap::KeyItem item2;
item2.m_required = 0;
item2.m_sensitive = KeyModifierShift;
KeyModifierMask desiredState = KeyModifierAlt;
itemList1.push_back(item1);
itemList2.push_back(item2);
entryList.push_back(itemList1);
entryList.push_back(itemList2);
EXPECT_EQ(1, keyMap.findBestKey(entryList, desiredState));
}
TEST(KeyMapTests, findBestKey_noRequiredDown_matchOneRequiredChangeItem)
{
KeyMap keyMap;
KeyMap::KeyEntryList entryList;
KeyMap::KeyItemList itemList1;
KeyMap::KeyItem item1;
item1.m_required = KeyModifierShift | KeyModifierAlt;
item1.m_sensitive = KeyModifierShift | KeyModifierAlt;
KeyMap::KeyItemList itemList2;
KeyMap::KeyItem item2;
item2.m_required = KeyModifierShift;
item2.m_sensitive = KeyModifierShift | KeyModifierAlt;
KeyModifierMask desiredState = 0;
itemList1.push_back(item1);
itemList2.push_back(item2);
entryList.push_back(itemList1);
entryList.push_back(itemList2);
EXPECT_EQ(1, keyMap.findBestKey(entryList, desiredState));
}
TEST(KeyMapTests, findBestKey_onlyOneRequiredDown_matchTwoRequiredChangesItem)
{
KeyMap keyMap;
KeyMap::KeyEntryList entryList;
KeyMap::KeyItemList itemList1;
KeyMap::KeyItem item1;
item1.m_required = KeyModifierShift | KeyModifierAlt | KeyModifierControl;
item1.m_sensitive = KeyModifierShift | KeyModifierAlt | KeyModifierControl;
KeyMap::KeyItemList itemList2;
KeyMap::KeyItem item2;
item2.m_required = KeyModifierShift | KeyModifierAlt;
item2.m_sensitive = KeyModifierShift | KeyModifierAlt | KeyModifierControl;
KeyModifierMask desiredState = 0;
itemList1.push_back(item1);
itemList2.push_back(item2);
entryList.push_back(itemList1);
entryList.push_back(itemList2);
EXPECT_EQ(1, keyMap.findBestKey(entryList, desiredState));
}
TEST(KeyMapTests, findBestKey_noRequiredDown_cannotMatch)
{
KeyMap keyMap;
KeyMap::KeyEntryList entryList;
KeyMap::KeyItemList itemList;
KeyMap::KeyItem item;
item.m_required = 0xffffffff;
item.m_sensitive = 0xffffffff;
KeyModifierMask desiredState = 0;
itemList.push_back(item);
entryList.push_back(itemList);
EXPECT_EQ(-1, keyMap.findBestKey(entryList, desiredState));
}
TEST(KeyMapTests, isCommand_shiftMask_returnFalse)
{
KeyMap keyMap;
KeyModifierMask mask = KeyModifierShift;
EXPECT_FALSE(keyMap.isCommand(mask));
}
TEST(KeyMapTests, isCommand_controlMask_returnTrue)
{
KeyMap keyMap;
KeyModifierMask mask = KeyModifierControl;
EXPECT_EQ(true, keyMap.isCommand(mask));
}
TEST(KeyMapTests, isCommand_alternateMask_returnTrue)
{
KeyMap keyMap;
KeyModifierMask mask = KeyModifierAlt;
EXPECT_EQ(true, keyMap.isCommand(mask));
}
TEST(KeyMapTests, isCommand_alternateGraphicMask_returnTrue)
{
KeyMap keyMap;
KeyModifierMask mask = KeyModifierAltGr;
EXPECT_EQ(true, keyMap.isCommand(mask));
}
TEST(KeyMapTests, isCommand_metaMask_returnTrue)
{
KeyMap keyMap;
KeyModifierMask mask = KeyModifierMeta;
EXPECT_EQ(true, keyMap.isCommand(mask));
}
TEST(KeyMapTests, isCommand_superMask_returnTrue)
{
KeyMap keyMap;
KeyModifierMask mask = KeyModifierSuper;
EXPECT_EQ(true, keyMap.isCommand(mask));
}
TEST(KeyMapTests, mapkey_handles_setmodifier_with_no_mapped)
{
KeyMap keyMap{};
KeyMap::Keystroke stroke('A', true, false, 1);
KeyMap::KeyItem keyItem;
keyItem.m_button = 'A';
keyItem.m_group = 1;
keyItem.m_id = 'A';
keyMap.addKeyEntry(keyItem);
keyMap.finish();
KeyMap::Keystrokes strokes{stroke};
KeyMap::ModifierToKeys activeModifiers{};
KeyModifierMask currentState{};
KeyModifierMask desiredMask{};
auto result = keyMap.mapKey(strokes, kKeySetModifiers, 1, activeModifiers, currentState, desiredMask, false, "en");
EXPECT_FALSE(result == nullptr);
desiredMask = KeyModifierControl;
result = keyMap.mapKey(strokes, kKeySetModifiers, 1, activeModifiers, currentState, desiredMask, false, "en");
EXPECT_TRUE(result == nullptr);
}
} // namespace deskflow
| 6,735
|
C++
|
.cpp
| 199
| 31.306533
| 117
| 0.791481
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,709
|
ServerAppTests.cpp
|
deskflow_deskflow/src/test/unittests/deskflow/ServerAppTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2014-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#define TEST_ENV
#include "deskflow/ArgParser.h"
#include "deskflow/ServerApp.h"
#include "deskflow/ServerArgs.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using ::testing::NiceMock;
class MockServerApp : public ServerApp
{
public:
MockServerApp() : ServerApp(nullptr, nullptr)
{
}
};
TEST(ServerAppTests, runInner_will_handle_configuration_lifetime)
{
NiceMock<MockServerApp> app;
EXPECT_FALSE(app.args().m_config);
const char *argv[]{"deskflow-server"};
app.runInner(1, const_cast<char **>(argv), nullptr, [](int, char **) { return 0; });
EXPECT_TRUE(app.args().m_config);
}
TEST(ServerAppTests, version_printsYear)
{
NiceMock<MockServerApp> app;
std::stringstream buffer;
std::streambuf *old = std::cout.rdbuf(buffer.rdbuf());
app.version();
std::cout.rdbuf(old);
#ifdef WIN32
// regex is god awful on windows, so just check that there is a copyright
EXPECT_THAT(buffer.str(), testing::HasSubstr("Symless Ltd."));
#else
std::string expectedPattern = ".*Copyright \\(C\\) [0-9]{4}-[0-9]{4} Symless Ltd.*";
EXPECT_THAT(buffer.str(), testing::MatchesRegex(expectedPattern));
#endif // WIN32
}
| 1,839
|
C++
|
.cpp
| 53
| 32.528302
| 86
| 0.739425
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,710
|
ProtocolUtilTests.cpp
|
deskflow_deskflow/src/test/unittests/deskflow/ProtocolUtilTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2014-2020 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "deskflow/ProtocolUtil.h"
#include "test/mock/io/MockStream.h"
#include <array>
#include <gtest/gtest.h>
using ::testing::_;
using ::testing::DoAll;
using ::testing::ElementsAreArray;
using ::testing::Eq;
using ::testing::Pointee;
using ::testing::Return;
using ::testing::SetArgPointee;
using ::testing::StrEq;
using ::testing::TypedEq;
ACTION_P2(SetValueToVoidPointerArg0, value, size)
{
memcpy(arg0, value, size);
}
MATCHER_P(EqVoidPointeeInt8, expected, "")
{
const UInt8 Actual8 = (*static_cast<const UInt8 *>(arg));
return (expected == Actual8);
}
MATCHER_P(EqVoidPointeeInt16, expected, "")
{
const UInt16 Actual16 = (*static_cast<const UInt16 *>(arg));
return (expected == (Actual16 >> 8));
}
MATCHER_P(EqVoidPointeeInt32, expected, "")
{
const UInt32 Actual32 = (*static_cast<const UInt32 *>(arg));
return (expected == (Actual32 >> 24));
}
MATCHER_P(EqVoidVectorInt1byte, expected, "")
{
bool Result = true;
const UInt8 *Actual = (static_cast<const UInt8 *>(arg)) + 4;
const size_t Size = *(Actual - 1);
if (Size == expected.size()) {
for (size_t i = 0; i < expected.size(); ++i) {
if (expected[i] != Actual[i]) {
Result = false;
break;
}
}
} else {
Result = false;
}
return Result;
}
MATCHER_P(EqVoidVectorInt2bytes, expected, "")
{
bool Result = true;
const UInt16 *Actual = (static_cast<const UInt16 *>(arg)) + 2;
const size_t Size = *(Actual - 1) >> 8;
if (Size == expected.size()) {
for (size_t i = 0; i < expected.size(); ++i) {
if (expected[i] != (Actual[i] >> 8)) {
Result = false;
break;
}
}
} else {
Result = false;
}
return Result;
}
MATCHER_P(EqVoidVectorInt4bytes, expected, "")
{
bool Result = true;
const UInt32 *Actual = (static_cast<const UInt32 *>(arg)) + 1;
const size_t Size = *(Actual - 1) >> 24;
if (Size == expected.size()) {
for (size_t i = 0; i < expected.size(); ++i) {
if (expected[i] != (Actual[i] >> 24)) {
Result = false;
break;
}
}
} else {
Result = false;
}
return Result;
}
MATCHER_P(EqVectorSymbols, expected, "")
{
bool Result = true;
const UInt8 *Actual = (static_cast<const UInt8 *>(arg));
for (size_t i = 0; i < expected.size(); ++i) {
if (expected[i] != (Actual[i])) {
Result = false;
break;
}
}
return Result;
}
ACTION(ThrowBadAlloc)
{
throw std::bad_alloc();
}
class ProtocolUtilTests : public ::testing::Test
{
public:
MockStream stream;
UInt8 ActualInt8 = 0;
UInt16 ActualInt16 = 0;
UInt32 ActualInt32 = 0;
std::string ActualString;
};
// TODO: fix tests causing segmentation fault
#if 0
TEST_F(ProtocolUtilTests, readf__XIOEndOfStream_exception) {
ON_CALL(stream, read(_, _)).WillByDefault(Return(0));
EXPECT_FALSE(ProtocolUtil::readf(&stream, "%s", &ActualString));
EXPECT_TRUE(ActualString.empty());
}
TEST_F(ProtocolUtilTests, readf_XIOReadMismatch_exception) {
EXPECT_CALL(stream, read(_, _))
.WillOnce(DoAll(SetValueToVoidPointerArg0("b", 1), Return(1)));
EXPECT_FALSE(ProtocolUtil::readf(&stream, "a%s", &ActualString));
EXPECT_TRUE(ActualString.empty());
}
TEST_F(ProtocolUtilTests, readf_bad_alloc_exception) {
ON_CALL(stream, read(_, _)).WillByDefault(ThrowBadAlloc());
EXPECT_FALSE(ProtocolUtil::readf(&stream, "a%s", &ActualString));
EXPECT_TRUE(ActualString.empty());
}
TEST_F(ProtocolUtilTests, readf_asserts) {
ASSERT_DEBUG_DEATH(
{ ProtocolUtil::readf(&stream, "%x", &ActualString); },
"invalid format specifier");
ASSERT_DEBUG_DEATH(
{ ProtocolUtil::readf(&stream, "%5i", &ActualString); },
"length to be read is wrong:");
ASSERT_DEBUG_DEATH(
{ ProtocolUtil::readf(&stream, "%5I", &ActualString); }, "");
}
TEST_F(ProtocolUtilTests, readf_params_validation) {
EXPECT_FALSE(ProtocolUtil::readf(NULL, "%x", NULL));
EXPECT_FALSE(ProtocolUtil::readf(&stream, NULL, NULL));
}
TEST_F(ProtocolUtilTests, readf_string) {
const UInt8 Length = 200;
const std::string Expected(Length, 'x');
std::array<UInt8, 4> StringSize{{0, 0, 0, Length}};
EXPECT_CALL(stream, read(_, _))
.WillOnce(
DoAll(SetValueToVoidPointerArg0(StringSize.data(), StringSize.size()),
Return(StringSize.size())))
.WillOnce(
DoAll(SetValueToVoidPointerArg0(Expected.c_str(), Expected.length()),
Return(Expected.length())));
EXPECT_TRUE(ProtocolUtil::readf(&stream, "%s", &ActualString));
EXPECT_EQ(Expected, ActualString);
}
class ReadfIntTestFixture
: public ::testing::TestWithParam<std::tuple<const char *, int>> {
public:
MockStream stream;
UInt8 StreamData1Byte = 10;
std::array<UInt8, 2> StreamData2Bytes{{0, 10}};
std::array<UInt8, 4> StreamData4Bytes{{0, 0, 0, 10}};
UInt8 *getStreamData(int size) {
UInt8 *StreamData = nullptr;
switch (size) {
case 2:
StreamData = StreamData2Bytes.data();
break;
case 4:
StreamData = StreamData4Bytes.data();
break;
default:
StreamData = &StreamData1Byte;
break;
}
return StreamData;
}
};
TEST_P(ReadfIntTestFixture, readf_int) {
int Actual = 0;
const int Expected = 10;
const char *Format = std::get<0>(GetParam());
int StreamDataSize = std::get<1>(GetParam());
UInt8 *StreamData = getStreamData(StreamDataSize);
ON_CALL(stream, read(_, _))
.WillByDefault(
DoAll(SetValueToVoidPointerArg0(StreamData, StreamDataSize),
Return(StreamDataSize)));
EXPECT_TRUE(ProtocolUtil::readf(&stream, Format, &Actual));
EXPECT_EQ(Expected, Actual);
}
INSTANTIATE_TEST_SUITE_P(ReadfIntTests, ReadfIntTestFixture,
::testing::Values(std::make_tuple("%1i", 1),
std::make_tuple("%2i", 2),
std::make_tuple("%4i", 4)));
class ReadfIntVectorTestFixture : public ReadfIntTestFixture {};
TEST_P(ReadfIntVectorTestFixture, readf_int_vector) {
std::vector<UInt8> Actual1Byte = {};
std::vector<UInt16> Actual2Bytes = {};
std::vector<UInt32> Actual4Bytes = {};
const std::vector<UInt8> Expected1Byte = {10, 10};
const std::vector<UInt16> Expected2Bytes = {10, 10};
const std::vector<UInt32> Expected4Bytes = {10, 10};
std::array<UInt8, 4> StreamVectorSize{{0, 0, 0, 2}};
const char *Format = std::get<0>(GetParam());
int StreamDataSize = std::get<1>(GetParam());
UInt8 *StreamData = getStreamData(StreamDataSize);
MockStream stream;
EXPECT_CALL(stream, read(_, _))
.WillOnce(DoAll(SetValueToVoidPointerArg0(StreamVectorSize.data(),
StreamVectorSize.size()),
Return(StreamVectorSize.size())))
.WillRepeatedly(
DoAll(SetValueToVoidPointerArg0(StreamData, StreamDataSize),
Return(StreamDataSize)));
switch (StreamDataSize) {
case 2:
EXPECT_TRUE(ProtocolUtil::readf(&stream, Format, &Actual2Bytes));
EXPECT_EQ(Expected2Bytes, Actual2Bytes);
break;
case 4:
EXPECT_TRUE(ProtocolUtil::readf(&stream, Format, &Actual4Bytes));
EXPECT_EQ(Expected4Bytes, Actual4Bytes);
break;
default:
EXPECT_TRUE(ProtocolUtil::readf(&stream, Format, &Actual1Byte));
EXPECT_EQ(Expected1Byte, Actual1Byte);
break;
}
}
INSTANTIATE_TEST_SUITE_P(ReadfIntVectorTests, ReadfIntVectorTestFixture,
::testing::Values(std::make_tuple("%1I", 1),
std::make_tuple("%2I", 2),
std::make_tuple("%4I", 4)));
class ReadfIntAndStringTest : public ReadfIntTestFixture {
public:
UInt8 ActualInt8 = 0;
UInt16 ActualInt16 = 0;
UInt32 ActualInt32 = 32;
std::string ActualString;
};
TEST_P(ReadfIntAndStringTest, readf_int_and_string) {
const int ExpectedInt = 10;
const UInt8 StringLength = 200;
const std::string ExpectedString(StringLength, 'x');
std::array<UInt8, 4> StringSize{{0, 0, 0, StringLength}};
const char *Format = std::get<0>(GetParam());
int StreamDataSize = std::get<1>(GetParam());
UInt8 *StreamData = getStreamData(StreamDataSize);
EXPECT_CALL(stream, read(_, _))
.WillOnce(DoAll(SetValueToVoidPointerArg0(StreamData, StreamDataSize),
Return(StreamDataSize)))
.WillOnce(
DoAll(SetValueToVoidPointerArg0(StringSize.data(), StringSize.size()),
Return(StringSize.size())))
.WillOnce(DoAll(SetValueToVoidPointerArg0(ExpectedString.c_str(),
ExpectedString.length()),
Return(ExpectedString.length())));
switch (StreamDataSize) {
case 2:
EXPECT_TRUE(
ProtocolUtil::readf(&stream, Format, &ActualInt16, &ActualString));
EXPECT_EQ(ExpectedInt, ActualInt16);
break;
case 4:
EXPECT_TRUE(
ProtocolUtil::readf(&stream, Format, &ActualInt32, &ActualString));
EXPECT_EQ(ExpectedInt, ActualInt32);
break;
default:
EXPECT_TRUE(
ProtocolUtil::readf(&stream, Format, &ActualInt8, &ActualString));
EXPECT_EQ(ExpectedInt, ActualInt8);
break;
}
EXPECT_EQ(ExpectedString, ActualString);
}
INSTANTIATE_TEST_SUITE_P(IntAndStringTest, ReadfIntAndStringTest,
::testing::Values(std::make_tuple("%1i%s", 1),
std::make_tuple("%2i%s", 2),
std::make_tuple("%4i%s", 4)));
TEST_F(ProtocolUtilTests, readf_string_and_int4bytes) {
const UInt8 ExpectedInt = 10;
std::array<UInt8, 4> StreamIntData{{0, 0, 0, ExpectedInt}};
const std::string ExpectedStr(32768, 'x');
std::array<UInt8, 4> Size{{0, 0, 128, 0}};
EXPECT_CALL(stream, read(_, _))
.WillOnce(DoAll(SetValueToVoidPointerArg0(Size.data(), Size.size()),
Return(Size.size())))
.WillOnce(DoAll(
SetValueToVoidPointerArg0(ExpectedStr.c_str(), ExpectedStr.length()),
Return(ExpectedStr.length())))
.WillOnce(DoAll(
SetValueToVoidPointerArg0(StreamIntData.data(), StreamIntData.size()),
Return(StreamIntData.size())));
EXPECT_TRUE(
ProtocolUtil::readf(&stream, "%s%4i", &ActualString, &ActualInt32));
EXPECT_EQ(ExpectedStr, ActualString);
EXPECT_EQ(ExpectedInt, ActualInt32);
}
TEST_F(ProtocolUtilTests, readf_string_and_vector_int4bytes) {
std::vector<UInt32> Actual = {};
const std::vector<UInt32> Expected4Bytes = {10, 10};
std::array<UInt8, 4> StreamVectorSize{{0, 0, 0, 2}};
std::array<UInt8, 4> StreamData4Bytes{{0, 0, 0, 10}};
const std::string ExpString(32768, 'x');
std::array<UInt8, 4> SizeString{{0, 0, 128, 0}};
EXPECT_CALL(stream, read(_, _))
.WillOnce(
DoAll(SetValueToVoidPointerArg0(SizeString.data(), SizeString.size()),
Return(SizeString.size())))
.WillOnce(DoAll(
SetValueToVoidPointerArg0(ExpString.c_str(), ExpString.length()),
Return(ExpString.length())))
.WillOnce(DoAll(SetValueToVoidPointerArg0(StreamVectorSize.data(),
StreamVectorSize.size()),
Return(StreamVectorSize.size())))
.WillRepeatedly(DoAll(SetValueToVoidPointerArg0(StreamData4Bytes.data(),
StreamData4Bytes.size()),
Return(StreamData4Bytes.size())));
EXPECT_TRUE(ProtocolUtil::readf(&stream, "%s%4I", &ActualString, &Actual));
EXPECT_EQ(ExpString, ActualString);
EXPECT_EQ(Expected4Bytes, Actual);
}
TEST_F(ProtocolUtilTests, readf_vector_int4bytes_and_string) {
std::vector<UInt32> Actual4Bytes = {};
const std::vector<UInt32> Expected4Bytes = {10, 10};
std::array<UInt8, 4> StreamVectorSize{{0, 0, 0, 2}};
std::array<UInt8, 4> StreamData4Bytes{{0, 0, 0, 10}};
const std::string ExpectedString(32768, 'x');
std::array<UInt8, 4> StringSize{{0, 0, 128, 0}};
EXPECT_CALL(stream, read(_, _))
.WillOnce(DoAll(SetValueToVoidPointerArg0(StreamVectorSize.data(),
StreamVectorSize.size()),
Return(StreamVectorSize.size())))
.WillOnce(DoAll(SetValueToVoidPointerArg0(StreamData4Bytes.data(),
StreamData4Bytes.size()),
Return(StreamData4Bytes.size())))
.WillOnce(DoAll(SetValueToVoidPointerArg0(StreamData4Bytes.data(),
StreamData4Bytes.size()),
Return(StreamData4Bytes.size())))
.WillOnce(
DoAll(SetValueToVoidPointerArg0(StringSize.data(), StringSize.size()),
Return(StringSize.size())))
.WillOnce(DoAll(SetValueToVoidPointerArg0(ExpectedString.c_str(),
ExpectedString.length()),
Return(ExpectedString.length())));
EXPECT_TRUE(
ProtocolUtil::readf(&stream, "%4I%s", &Actual4Bytes, &ActualString));
EXPECT_EQ(ExpectedString, ActualString);
EXPECT_EQ(Expected4Bytes, Actual4Bytes);
}
class WriteIntTest
: public ::testing::TestWithParam<std::tuple<const char *, int>> {
public:
MockStream stream;
UInt8 Expected1Byte = 5;
UInt16 Expected2Bytes = 10;
UInt32 Expected4Bytes = 15;
};
TEST_P(WriteIntTest, write_int) {
const char *Format = std::get<0>(GetParam());
const int DataSize = std::get<1>(GetParam());
switch (DataSize) {
case 2:
EXPECT_CALL(stream,
write(EqVoidPointeeInt16(Expected2Bytes), Eq(DataSize)));
ProtocolUtil::writef(&stream, Format, Expected2Bytes);
break;
case 4:
EXPECT_CALL(stream,
write(EqVoidPointeeInt32(Expected4Bytes), Eq(DataSize)));
ProtocolUtil::writef(&stream, Format, Expected4Bytes);
break;
default:
EXPECT_CALL(stream, write(EqVoidPointeeInt8(Expected1Byte), Eq(DataSize)));
ProtocolUtil::writef(&stream, Format, Expected1Byte);
break;
}
}
INSTANTIATE_TEST_SUITE_P(WriteIntTest, WriteIntTest,
::testing::Values(std::make_tuple("%1i", 1),
std::make_tuple("%2i", 2),
std::make_tuple("%4i", 4)));
class WriteIntVectorTest
: public ::testing::TestWithParam<std::tuple<const char *, int>> {
public:
MockStream stream;
const std::vector<UInt8> Expected1Byte = {10, 20, 30};
const std::vector<UInt16> Expected2Byte = {40, 50, 60};
const std::vector<UInt32> Expected4Byte = {70, 80, 90};
};
TEST_P(WriteIntVectorTest, write_vector_int) {
const char *Format = std::get<0>(GetParam());
const int Type = std::get<1>(GetParam());
switch (Type) {
case 2:
EXPECT_CALL(stream,
write(EqVoidVectorInt2bytes(Expected2Byte),
Eq(Type * Expected2Byte.size() + sizeof(UInt32))));
ProtocolUtil::writef(&stream, Format, &Expected2Byte);
break;
case 4:
EXPECT_CALL(stream,
write(EqVoidVectorInt4bytes(Expected4Byte),
Eq(Type * Expected4Byte.size() + sizeof(UInt32))));
ProtocolUtil::writef(&stream, Format, &Expected4Byte);
break;
default:
EXPECT_CALL(stream, write(EqVoidVectorInt1byte(Expected1Byte),
Eq(Expected1Byte.size() + sizeof(UInt32))));
ProtocolUtil::writef(&stream, Format, &Expected1Byte);
break;
}
}
INSTANTIATE_TEST_SUITE_P(WriteIntVectorTest, WriteIntVectorTest,
::testing::Values(std::make_tuple("%1I", 1),
std::make_tuple("%2I", 2),
std::make_tuple("%4I", 4)));
TEST_F(ProtocolUtilTests, write_string_test) {
const String Expected = "Expected";
const std::vector<UInt8> ExpectedVector = {'E', 'x', 'p', 'e',
'c', 't', 'e', 'd'};
EXPECT_CALL(stream, write(EqVoidVectorInt1byte(ExpectedVector),
Expected.size() + sizeof(UInt32)));
ProtocolUtil::writef(&stream, "%s", &Expected);
}
TEST_F(ProtocolUtilTests, write_raw_bytes_test) {
const UInt32 Size = 5;
const std::array<UInt8, Size> Expected{{10, 20, 30, 40, 50}};
EXPECT_CALL(stream, write(EqVoidVectorInt1byte(Expected),
Expected.size() + sizeof(UInt32)));
ProtocolUtil::writef(&stream, "%S", Size, &Expected);
}
TEST_F(ProtocolUtilTests, write_symbols_from_format_test) {
const std::vector<UInt8> Expected = {'%', '1', '2', '3', '4', '5'};
EXPECT_CALL(stream, write(EqVectorSymbols(Expected), Expected.size()));
ProtocolUtil::writef(&stream, "%%12345");
}
#endif
| 17,460
|
C++
|
.cpp
| 455
| 31.586813
| 80
| 0.63914
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,711
|
X11LayoutParserTests.cpp
|
deskflow_deskflow/src/test/unittests/deskflow/X11LayoutParserTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2014-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#if WINAPI_XWINDOWS
#include "deskflow/unix/X11LayoutsParser.h"
#include <fstream>
#include <gtest/gtest.h>
const std::string testDir = "tmp/test";
void createTestFiles()
{
std::ofstream correctEvdevFile(testDir + "/correctEvdev.xml");
if (!correctEvdevFile.is_open()) {
FAIL();
}
correctEvdevFile << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl;
correctEvdevFile << "<xkbConfigRegistry version=\"1.1\">" << std::endl;
correctEvdevFile << " <layoutList>" << std::endl;
correctEvdevFile << " <layout>" << std::endl;
correctEvdevFile << " <configItem>" << std::endl;
correctEvdevFile << " <name>us</name>" << std::endl;
correctEvdevFile << " <!-- Keyboard indicator for English layouts -->" << std::endl;
correctEvdevFile << " <shortDescription>en</shortDescription>" << std::endl;
correctEvdevFile << " <description>English (US)</description>" << std::endl;
correctEvdevFile << " <languageList>" << std::endl;
correctEvdevFile << " <iso639Id>eng</iso639Id>" << std::endl;
correctEvdevFile << " </languageList>" << std::endl;
correctEvdevFile << " </configItem>" << std::endl;
correctEvdevFile << " <variantList>" << std::endl;
correctEvdevFile << " <variant>" << std::endl;
correctEvdevFile << " <configItem>" << std::endl;
correctEvdevFile << " <name>eng</name>" << std::endl;
correctEvdevFile << " <shortDescription>eng</shortDescription>" << std::endl;
correctEvdevFile << " <description>Cherokee</description>" << std::endl;
correctEvdevFile << " <languageList>" << std::endl;
correctEvdevFile << " <iso639Id>eng</iso639Id>" << std::endl;
correctEvdevFile << " </languageList>" << std::endl;
correctEvdevFile << " </configItem>" << std::endl;
correctEvdevFile << " </variant>" << std::endl;
correctEvdevFile << " </variantList>" << std::endl;
correctEvdevFile << " </layout>" << std::endl;
correctEvdevFile << " <layout>" << std::endl;
correctEvdevFile << " <configItem>" << std::endl;
correctEvdevFile << " <name>ru</name>" << std::endl;
correctEvdevFile << " <!-- Keyboard indicator for Russian layouts -->" << std::endl;
correctEvdevFile << " <shortDescription>ru</shortDescription>" << std::endl;
correctEvdevFile << " <description>Russian</description>" << std::endl;
correctEvdevFile << " <languageList>" << std::endl;
correctEvdevFile << " <iso639Id>rus</iso639Id>" << std::endl;
correctEvdevFile << " </languageList>" << std::endl;
correctEvdevFile << " </configItem>" << std::endl;
correctEvdevFile << " </layout>" << std::endl;
correctEvdevFile << " </layoutList>" << std::endl;
correctEvdevFile << "</xkbConfigRegistry>" << std::endl;
correctEvdevFile.close();
std::ofstream evdevFromFutureFile(testDir + "/evdevFromFuture.xml");
if (!evdevFromFutureFile.is_open()) {
FAIL();
}
evdevFromFutureFile << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl;
evdevFromFutureFile << "<xkbConfigRegistry version=\"1.1\">" << std::endl;
evdevFromFutureFile << " <layoutList>" << std::endl;
evdevFromFutureFile << " <layout>" << std::endl;
evdevFromFutureFile << " <configItem>" << std::endl;
evdevFromFutureFile << " <name>futureLangName</name>" << std::endl;
evdevFromFutureFile << " <languageList>" << std::endl;
evdevFromFutureFile << " <iso639Id>fln</iso639Id>" << std::endl;
evdevFromFutureFile << " </languageList>" << std::endl;
evdevFromFutureFile << " </configItem>" << std::endl;
evdevFromFutureFile << " </layout>" << std::endl;
evdevFromFutureFile << " </layoutList>" << std::endl;
evdevFromFutureFile << "</xkbConfigRegistry>" << std::endl;
evdevFromFutureFile.close();
std::ofstream incorrectEvdevFile1(testDir + "/incorrectEvdev1.xml");
if (!incorrectEvdevFile1.is_open()) {
FAIL();
}
incorrectEvdevFile1 << "<incorrectRootTag></incorrectRootTag>" << std::endl;
incorrectEvdevFile1.close();
std::ofstream incorrectEvdevFile2(testDir + "/incorrectEvdev2.xml");
if (!incorrectEvdevFile2.is_open()) {
FAIL();
}
incorrectEvdevFile2 << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl;
incorrectEvdevFile2 << "<xkbConfigRegistry version=\"1.1\">" << std::endl;
incorrectEvdevFile2 << "</xkbConfigRegistry>" << std::endl;
incorrectEvdevFile2.close();
std::ofstream incorrectEvdevFile3(testDir + "/incorrectEvdev3.xml");
if (!incorrectEvdevFile3.is_open()) {
FAIL();
}
incorrectEvdevFile3 << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl;
incorrectEvdevFile3 << "<xkbConfigRegistry version=\"1.1\">" << std::endl;
incorrectEvdevFile3 << " <layoutList>" << std::endl;
incorrectEvdevFile3 << " <layout>" << std::endl;
incorrectEvdevFile3 << " </layout>" << std::endl;
incorrectEvdevFile3 << " </layoutList>" << std::endl;
incorrectEvdevFile3 << "</xkbConfigRegistry>" << std::endl;
incorrectEvdevFile3.close();
}
TEST(X11LayoutsParsingTests, xmlCorrectParsingTest)
{
createTestFiles();
std::vector<String> expectedResult = {"en", "ru"};
auto parsedResult = X11LayoutsParser::getX11LanguageList(testDir + "/correctEvdev.xml");
EXPECT_EQ(parsedResult, parsedResult);
}
TEST(X11LayoutsParsingTests, xmlParsingMissedEvdevFileTest)
{
auto parsedResult = X11LayoutsParser::getX11LanguageList(testDir + "/missedFile");
EXPECT_TRUE(parsedResult.empty());
}
TEST(X11LayoutsParsingTests, xmlParsingIncorrectEvdevFileTest)
{
std::vector<String> parsedResult;
parsedResult = X11LayoutsParser::getX11LanguageList(testDir + "/incorrectEvdev1.xml");
EXPECT_TRUE(parsedResult.empty());
parsedResult = X11LayoutsParser::getX11LanguageList(testDir + "/incorrectEvdev2.xml");
EXPECT_TRUE(parsedResult.empty());
parsedResult = X11LayoutsParser::getX11LanguageList(testDir + "/incorrectEvdev3.xml");
EXPECT_TRUE(parsedResult.empty());
}
TEST(X11LayoutsParsingTests, layoutConvertTest)
{
EXPECT_EQ(X11LayoutsParser::convertLayotToISO(testDir + "/correctEvdev.xml", "us", true), "en");
EXPECT_EQ(X11LayoutsParser::convertLayotToISO(testDir + "/incorrectEvdev1.xml", "us", true), "");
EXPECT_EQ(X11LayoutsParser::convertLayotToISO(testDir + "/evdevFromFuture.xml", "us", true), "");
}
#endif
| 7,150
|
C++
|
.cpp
| 141
| 47.921986
| 99
| 0.672818
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,712
|
LanguageManagerTests.cpp
|
deskflow_deskflow/src/test/unittests/deskflow/languages/LanguageManagerTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2014-2021 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "deskflow/languages/LanguageManager.h"
#include <gtest/gtest.h>
TEST(LanguageManager, RemoteLanguagesTest)
{
std::string remoteLanguages = "ruenuk";
deskflow::languages::LanguageManager manager({"ru", "en", "uk"});
manager.setRemoteLanguages(remoteLanguages);
EXPECT_EQ((std::vector<std::string>{"ru", "en", "uk"}), manager.getRemoteLanguages());
manager.setRemoteLanguages(String());
EXPECT_TRUE(manager.getRemoteLanguages().empty());
}
TEST(LanguageManager, LocalLanguagesTest)
{
std::vector<String> localLanguages = {"ru", "en", "uk"};
deskflow::languages::LanguageManager manager(localLanguages);
EXPECT_EQ((std::vector<std::string>{"ru", "en", "uk"}), manager.getLocalLanguages());
}
TEST(LanguageManager, MissedLanguagesTest)
{
String remoteLanguages = "ruenuk";
std::vector<String> localLanguages = {"en"};
deskflow::languages::LanguageManager manager(localLanguages);
manager.setRemoteLanguages(remoteLanguages);
EXPECT_EQ("ru, uk", manager.getMissedLanguages());
}
TEST(LanguageManager, SerializeLocalLanguagesTest)
{
std::vector<String> localLanguages = {"ru", "en", "uk"};
deskflow::languages::LanguageManager manager(localLanguages);
EXPECT_EQ("ruenuk", manager.getSerializedLocalLanguages());
}
TEST(LanguageManager, LanguageInstalledTest)
{
std::vector<String> localLanguages = {"ru", "en", "uk"};
deskflow::languages::LanguageManager manager(localLanguages);
EXPECT_FALSE(manager.isLanguageInstalled("us"));
EXPECT_TRUE(manager.isLanguageInstalled("en"));
}
| 2,228
|
C++
|
.cpp
| 54
| 38.962963
| 88
| 0.761684
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,713
|
IArchStringTests.cpp
|
deskflow_deskflow/src/test/unittests/arch/IArchStringTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2014-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "lib/arch/IArchString.h"
#include <gtest/gtest.h>
class SampleIArchString : public IArchString
{
public:
EWideCharEncoding getWideCharEncoding() override
{
return kUTF16;
}
};
TEST(IArchStringTests, convStringWCToMB_will_work_do_simple_conversions)
{
SampleIArchString as;
char buff[20];
bool errors;
auto converted = as.convStringWCToMB(buff, L"Hello", 6, &errors);
EXPECT_STREQ(buff, "Hello");
EXPECT_EQ(converted, 6);
EXPECT_EQ(errors, false);
}
TEST(IArchStringTests, convStringWCToMB_will_work_do_simple_conversions_noresult)
{
SampleIArchString as;
bool errors;
auto converted = as.convStringWCToMB(nullptr, L"Hello", 6, &errors);
EXPECT_EQ(converted, 6);
EXPECT_EQ(errors, false);
}
TEST(IArchStringTests, convStringMBToWC_will_work_do_simple_conversions)
{
SampleIArchString as;
wchar_t buff[20];
bool errors;
auto converted = as.convStringMBToWC(buff, "Hello", 6, &errors);
EXPECT_STREQ(buff, L"Hello");
EXPECT_EQ(converted, 6);
EXPECT_EQ(errors, false);
}
| 1,720
|
C++
|
.cpp
| 54
| 29.574074
| 81
| 0.760241
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,714
|
ArchNetworkBSDTests.cpp
|
deskflow_deskflow/src/test/unittests/arch/unix/ArchNetworkBSDTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2014-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "arch/IArchNetwork.h"
#include "lib/arch/unix/ArchNetworkBSD.h"
#include "lib/arch/XArch.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <memory>
#include <netinet/in.h>
#include <sys/types.h>
using ::testing::_;
using ::testing::NiceMock;
using PollEntries = std::vector<IArchNetwork::PollEntry>;
using PollFD = struct pollfd[];
namespace {
struct MockDeps : public ArchNetworkBSD::Deps
{
std::shared_ptr<PollFD> m_pollFD;
MockDeps()
{
ON_CALL(*this, makePollFD(_)).WillByDefault([this](nfds_t n) {
m_pollFD = ArchNetworkBSD::Deps::makePollFD(n);
return m_pollFD;
});
}
static std::shared_ptr<NiceMock<MockDeps>> makeNice()
{
return std::make_shared<NiceMock<MockDeps>>();
}
MOCK_METHOD(void, sleep, (double), (override));
MOCK_METHOD(int, poll, (struct pollfd *, nfds_t, int), (override));
MOCK_METHOD(std::shared_ptr<PollFD>, makePollFD, (nfds_t), (override));
MOCK_METHOD(ssize_t, read, (int, void *, size_t), (override));
MOCK_METHOD(void, testCancelThread, (), (override));
};
} // namespace
TEST(ArchNetworkBSDTests, pollSocket_zeroEntries_callsSleep)
{
auto deps = MockDeps::makeNice();
ArchNetworkBSD networkBSD(deps);
EXPECT_CALL(*deps, sleep(1)).Times(1);
auto result = networkBSD.pollSocket(nullptr, 0, 1);
EXPECT_EQ(result, 0);
}
TEST(ArchNetworkBSDTests, pollSocket_mockAccessError_throws)
{
auto deps = MockDeps::makeNice();
ON_CALL(*deps, poll(_, _, _)).WillByDefault([]() {
errno = EACCES;
return -1;
});
ArchNetworkBSD networkBSD(deps);
PollEntries entries{{nullptr, 0, 0}};
const auto f = [&] { networkBSD.pollSocket(entries.data(), static_cast<int>(entries.size()), 1); };
EXPECT_THROW({ f(); }, XArchNetworkAccess);
}
TEST(ArchNetworkBSDTests, pollSocket_pfdHasRevents_copiedToEntries)
{
auto deps = MockDeps::makeNice();
ON_CALL(*deps, poll(_, _, _)).WillByDefault([](auto pfd, auto, auto) {
pfd[0].revents = POLLIN | POLLOUT | POLLERR | POLLNVAL;
return 0;
});
ArchNetworkBSD networkBSD(deps);
PollEntries entries{{nullptr, 0, 0}};
networkBSD.pollSocket(entries.data(), static_cast<int>(entries.size()), 1);
const auto expect = IArchNetwork::kPOLLIN | IArchNetwork::kPOLLOUT | IArchNetwork::kPOLLERR | IArchNetwork::kPOLLNVAL;
EXPECT_EQ(entries[0].m_revents, expect);
}
TEST(ArchNetworkBSDTests, pollSocket_nullSocket_fdIsNegativeOne)
{
auto deps = MockDeps::makeNice();
ArchNetworkBSD networkBSD(deps);
PollEntries entries{{nullptr, 0, 0}};
networkBSD.pollSocket(entries.data(), static_cast<int>(entries.size()), 1);
EXPECT_EQ(deps->m_pollFD[0].fd, -1);
}
TEST(ArchNetworkBSDTests, pollSocket_socketSet_fdWasSet)
{
auto deps = MockDeps::makeNice();
ArchNetworkBSD networkBSD(deps);
ArchSocketImpl socket{1, 0};
PollEntries entries{{&socket, 0, 0}};
networkBSD.pollSocket(entries.data(), static_cast<int>(entries.size()), 1);
EXPECT_EQ(deps->m_pollFD[0].fd, 1);
}
TEST(ArchNetworkBSDTests, pollSocket_eventHasPollInBit_bitWasSet)
{
auto deps = MockDeps::makeNice();
ArchNetworkBSD networkBSD(deps);
ArchSocketImpl socket{1, 0};
PollEntries entries{{&socket, IArchNetwork::kPOLLIN, 0}};
networkBSD.pollSocket(entries.data(), static_cast<int>(entries.size()), 1);
EXPECT_EQ(deps->m_pollFD[0].events, POLLIN);
}
TEST(ArchNetworkBSDTests, pollSocket_eventHasPollOutBit_bitWasSet)
{
auto deps = MockDeps::makeNice();
ArchNetworkBSD networkBSD(deps);
ArchSocketImpl socket{1, 0};
PollEntries entries{{&socket, IArchNetwork::kPOLLOUT, 0}};
networkBSD.pollSocket(entries.data(), static_cast<int>(entries.size()), 1);
EXPECT_EQ(deps->m_pollFD[0].events, POLLOUT);
}
TEST(ArchNetworkBSDTests, pollSocket_nullSocket_unblockPipeAppended)
{
auto deps = MockDeps::makeNice();
ArchNetworkBSD networkBSD(deps);
PollEntries entries{{nullptr, 0, 0}};
networkBSD.pollSocket(entries.data(), static_cast<int>(entries.size()), 1);
// interesting: unblock pipe fd comes from `getNetworkDataForThread` which
// seems to differ depending on linux distro.
EXPECT_GT(deps->m_pollFD[1].fd, -1);
}
TEST(ArchNetworkBSDTests, pollSocket_unblockPipeReventsError_readCalled)
{
const auto unblockPipeIndex = 1;
auto deps = MockDeps::makeNice();
ON_CALL(*deps, poll(_, _, _)).WillByDefault([](auto pfd, auto, auto) {
pfd[unblockPipeIndex].revents = POLLIN;
return 1;
});
ON_CALL(*deps, read(_, _, _)).WillByDefault([]() {
errno = EAGAIN;
return 0;
});
ArchNetworkBSD networkBSD(deps);
PollEntries entries{{nullptr, 0, 0}};
EXPECT_CALL(*deps, read(_, _, _)).Times(1);
networkBSD.pollSocket(entries.data(), static_cast<int>(entries.size()), 1);
}
TEST(ArchNetworkBSDTests, pollSocket_interruptSystemCall_testCancelThread)
{
auto deps = MockDeps::makeNice();
ON_CALL(*deps, poll(_, _, _)).WillByDefault([]() {
errno = EINTR;
return -1;
});
ArchNetworkBSD networkBSD(deps);
PollEntries entries{{nullptr, 0, 0}};
EXPECT_CALL(*deps, testCancelThread()).Times(1);
networkBSD.pollSocket(entries.data(), static_cast<int>(entries.size()), 1);
}
TEST(ArchNetworkBSDTests, isAnyAddr_goodAddress_returnsTrue)
{
auto deps = MockDeps::makeNice();
ArchNetworkBSD networkBSD(deps);
std::unique_ptr<ArchNetAddressImpl> addr;
addr.reset(networkBSD.newAnyAddr(IArchNetwork::kINET6));
auto result = networkBSD.isAnyAddr(addr.get());
EXPECT_TRUE(result);
}
TEST(ArchNetworkBSDTests, isAnyAddr_badAddress_returnsFalse)
{
auto deps = MockDeps::makeNice();
ArchNetworkBSD networkBSD(deps);
std::unique_ptr<ArchNetAddressImpl> addr;
addr.reset(networkBSD.newAnyAddr(IArchNetwork::kINET6));
auto scratch = (char *)&addr->m_addr;
std::string badAddr = "badaddr";
std::ranges::copy(badAddr, scratch + 2);
auto result = networkBSD.isAnyAddr(addr.get());
EXPECT_FALSE(result);
}
| 6,544
|
C++
|
.cpp
| 178
| 34.02809
| 120
| 0.72976
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,715
|
ServerTests.cpp
|
deskflow_deskflow/src/test/unittests/server/ServerTests.cpp
|
#include "lib/server/Server.h"
#include <gtest/gtest.h>
TEST(ServerTests, SwitchToScreenInfo_alloc_screen)
{
auto info = Server::SwitchToScreenInfo::alloc("test");
EXPECT_STREQ(info->m_screen, "test");
}
TEST(ServerTests, KeyboardBroadcastInfo_alloc_stateAndSceens)
{
auto info = Server::KeyboardBroadcastInfo::alloc(Server::KeyboardBroadcastInfo::State::kOn, "test");
EXPECT_EQ(info->m_state, Server::KeyboardBroadcastInfo::State::kOn);
EXPECT_STREQ(info->m_screens, "test");
}
| 494
|
C++
|
.cpp
| 13
| 35.846154
| 102
| 0.768908
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,716
|
ConfigTests.cpp
|
deskflow_deskflow/src/test/unittests/server/ConfigTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2014-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
// TODO: fix integ tests masquerading as unit tests
#if 0
#include "lib/server/Config.h"
#include "net/XSocket.h"
#include <gtest/gtest.h>
class OnlySystemFilter : public InputFilter::Condition {
public:
Condition *clone() const override { return new OnlySystemFilter(); }
String format() const override { return ""; }
InputFilter::EFilterStatus match(const Event &ev) override {
return ev.getType() == Event::kSystem ? InputFilter::kActivate
: InputFilter::kNoMatch;
}
};
TEST(ServerConfigTests,
serverconfig_will_deem_inequal_configs_with_different_map_size) {
Config a(nullptr);
Config b(nullptr);
a.addScreen("screenA");
EXPECT_FALSE(a == b);
EXPECT_FALSE(b == a);
}
TEST(ServerConfigTests,
serverconfig_will_deem_inequal_configs_with_different_cell_names) {
Config a(nullptr);
Config b(nullptr);
a.addScreen("screenA");
b.addScreen("screenB");
EXPECT_FALSE(a == b);
EXPECT_FALSE(b == a);
}
TEST(ServerConfigTests,
serverconfig_will_deem_equal_configs_with_same_cell_names) {
Config a(nullptr);
Config b(nullptr);
EXPECT_TRUE(a.addScreen("screenA"));
EXPECT_TRUE(a.addScreen("screenB"));
EXPECT_TRUE(a.addScreen("screenC"));
EXPECT_TRUE(a.connect("screenA", EDirection::kBottom, 0.0f, 0.5f, "screenB",
0.5f, 1.0f));
EXPECT_TRUE(a.connect("screenB", EDirection::kLeft, 0.0f, 0.5f, "screenB",
0.5f, 1.0f));
EXPECT_TRUE(b.addScreen("screenA"));
EXPECT_TRUE(b.addScreen("screenB"));
EXPECT_TRUE(b.addScreen("screenC"));
EXPECT_TRUE(b.connect("screenA", EDirection::kBottom, 0.0f, 0.5f, "screenB",
0.5f, 1.0f));
EXPECT_TRUE(b.connect("screenB", EDirection::kLeft, 0.0f, 0.5f, "screenB",
0.5f, 1.0f));
a.addOption("screenA", kOptionClipboardSharing, 1);
b.addOption("screenA", kOptionClipboardSharing, 1);
a.addOption(std::string(), kOptionClipboardSharing, 1);
b.addOption(std::string(), kOptionClipboardSharing, 1);
a.getInputFilter()->addFilterRule(InputFilter::Rule{new OnlySystemFilter()});
b.getInputFilter()->addFilterRule(InputFilter::Rule{new OnlySystemFilter()});
a.addAlias("screenA", "aliasA");
b.addAlias("screenA", "aliasA");
NetworkAddress addr1("localhost", 8080);
addr1.resolve();
NetworkAddress addr2("localhost", 8080);
addr2.resolve();
a.setDeskflowAddress(addr1);
b.setDeskflowAddress(addr2);
EXPECT_TRUE(a == b);
EXPECT_TRUE(b == a);
}
TEST(NetworkAddress, hostname_valid_parsing) {
const int validPort = 24900;
const String portStr = std::to_string(validPort);
// list of test cases. 1 param - hostname for parsing, 2 param - port, 3 param
// - expected hostname
const std::initializer_list<std::tuple<String, int, String>> validTestCases = {
std::make_tuple(String("127.0.0.1"), validPort, "127.0.0.1"),
std::make_tuple(String("127.0.0.1:") + portStr, 0, "127.0.0.1"),
std::make_tuple(String("localhost"), validPort, "localhost"),
std::make_tuple(String("localhost:") + portStr, 0, "localhost"),
std::make_tuple(String(""), validPort, ""),
std::make_tuple(String(":") + portStr, 0, ""),
// Temporary disabled tests for ipv6
// std::make_tuple(String("[::1]:") + portStr, 0, "::1"),
// std::make_tuple(String("[fe80::a156:9f36:793:7bfb%14]:") + portStr,
// 0, "fe80::a156:9f36:793:7bfb%14"),
// std::make_tuple(String("::1"), validPort, "::1"),
// std::make_tuple(String("fe80::a156:9f36:793:7bfb%14"), validPort,
// "fe80::a156:9f36:793:7bfb%14"),
// std::make_tuple(String("fe80:0000:0000:0000:a156:9f36:793:7bfb%14"),
// validPort, "fe80:0000:0000:0000:a156:9f36:793:7bfb%14"),
};
for (const auto &caseParams : validTestCases) {
NetworkAddress addr(std::get<0>(caseParams), std::get<1>(caseParams));
addr.resolve();
EXPECT_TRUE(addr.getHostname() == std::get<2>(caseParams));
EXPECT_TRUE(addr.getPort() == validPort);
EXPECT_TRUE(addr.getAddress() != nullptr);
}
// list of non valid hostnames
const std::initializer_list<String> nonValidTestCases = {
":nonValidPort", ":",
// Temporary disabled tests for ipv6
//"[::1]:",
//"[::1]:nonValidPort",
//"fe80::1",
//"[::1]:-1",
//"[::1]:65536"
};
for (const auto &caseParam : nonValidTestCases) {
bool flag = false;
try {
NetworkAddress addr(caseParam, validPort);
} catch (const XSocketAddress &) {
flag = true;
}
EXPECT_TRUE(flag);
}
}
TEST(
ServerConfigTests,
serverconfig_will_deem_different_configs_with_same_cell_names_different_options) {
Config a(nullptr);
Config b(nullptr);
a.addScreen("screenA");
b.addScreen("screenA");
a.addOption("screenA", kOptionClipboardSharing, 0);
b.addOption("screenA", kOptionClipboardSharing, 1);
EXPECT_FALSE(a == b);
EXPECT_FALSE(b == a);
}
TEST(
ServerConfigTests,
serverconfig_will_deem_different_configs_with_same_cell_names_different_aliases1) {
Config a(nullptr);
Config b(nullptr);
a.addScreen("screenA");
b.addScreen("screenA");
b.addAlias("screenA", "aliasA");
EXPECT_FALSE(a == b);
EXPECT_FALSE(b == a);
}
TEST(
ServerConfigTests,
serverconfig_will_deem_different_configs_with_same_cell_names_different_aliases2) {
Config a(nullptr);
Config b(nullptr);
a.addScreen("screenA");
b.addScreen("screenA");
a.addAlias("screenA", "aliasA");
b.addAlias("screenA", "aliasB");
EXPECT_FALSE(a == b);
EXPECT_FALSE(b == a);
}
TEST(ServerConfigTests,
serverconfig_will_deem_different_configs_with_different_global_options) {
Config a(nullptr);
Config b(nullptr);
a.addScreen("screenA");
b.addScreen("screenA");
a.addOption(std::string(), kOptionClipboardSharing, 0);
b.addOption(std::string(), kOptionClipboardSharing, 1);
EXPECT_FALSE(a == b);
EXPECT_FALSE(b == a);
}
TEST(ServerConfigTests,
serverconfig_will_deem_different_configs_with_different_filters) {
Config a(nullptr);
Config b(nullptr);
a.addScreen("screenA");
b.addScreen("screenA");
a.getInputFilter()->addFilterRule(InputFilter::Rule{new OnlySystemFilter()});
EXPECT_FALSE(a == b);
EXPECT_FALSE(b == a);
}
TEST(ServerConfigTests,
serverconfig_will_deem_different_configs_with_different_address) {
Config a(nullptr);
Config b(nullptr);
a.addScreen("screenA");
b.addScreen("screenA");
a.setDeskflowAddress(NetworkAddress(8080));
b.setDeskflowAddress(NetworkAddress(1010));
EXPECT_FALSE(a == b);
EXPECT_FALSE(b == a);
}
TEST(ServerConfigTests, serverconfig_will_deem_different_cell_neighbours1) {
Config a(nullptr);
Config b(nullptr);
EXPECT_TRUE(a.addScreen("screenA"));
EXPECT_TRUE(a.addScreen("screenB"));
EXPECT_TRUE(a.connect("screenA", EDirection::kBottom, 0.0f, 0.5f, "screenB",
0.5f, 1.0f));
EXPECT_TRUE(b.addScreen("screenA"));
EXPECT_TRUE(b.addScreen("screenB"));
EXPECT_FALSE(a == b);
EXPECT_FALSE(b == a);
}
TEST(ServerConfigTests, serverconfig_will_deem_different_cell_neighbours2) {
Config a(nullptr);
Config b(nullptr);
EXPECT_TRUE(a.addScreen("screenA"));
EXPECT_TRUE(a.addScreen("screenB"));
EXPECT_TRUE(a.connect("screenA", EDirection::kBottom, 0.0f, 0.5f, "screenB",
0.5f, 1.0f));
EXPECT_TRUE(b.addScreen("screenA"));
EXPECT_TRUE(b.addScreen("screenB"));
EXPECT_TRUE(b.connect("screenA", EDirection::kBottom, 0.0f, 0.25f, "screenB",
0.25f, 1.0f));
EXPECT_FALSE(a == b);
EXPECT_FALSE(b == a);
}
TEST(ServerConfigTests, serverconfig_will_deem_different_cell_neighbours3) {
Config a(nullptr);
Config b(nullptr);
EXPECT_TRUE(a.addScreen("screenA"));
EXPECT_TRUE(a.addScreen("screenB"));
EXPECT_TRUE(a.addScreen("screenC"));
EXPECT_TRUE(a.connect("screenA", EDirection::kBottom, 0.0f, 0.5f, "screenB",
0.5f, 1.0f));
EXPECT_TRUE(b.addScreen("screenA"));
EXPECT_TRUE(b.addScreen("screenB"));
EXPECT_TRUE(b.addScreen("screenC"));
EXPECT_TRUE(b.connect("screenA", EDirection::kBottom, 0.0f, 0.5f, "screenC",
0.5f, 1.0f));
EXPECT_FALSE(a == b);
EXPECT_FALSE(b == a);
}
#endif
| 8,952
|
C++
|
.cpp
| 241
| 32.792531
| 87
| 0.675495
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,717
|
IpcLogOutputterTests.cpp
|
deskflow_deskflow/src/test/unittests/ipc/IpcLogOutputterTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2015-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#define TEST_ENV
#include "test/mock/ipc/MockIpcServer.h"
#include "base/String.h"
#include "common/common.h"
#include "ipc/IpcLogOutputter.h"
#include "mt/Thread.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
// HACK: ipc logging only used on windows anyway
#if WINAPI_MSWINDOWS
using ::testing::_;
using ::testing::AtLeast;
using ::testing::Matcher;
using ::testing::MatcherCast;
using ::testing::Property;
using ::testing::Return;
using ::testing::StrEq;
using namespace deskflow;
// TODO Fix the IPC Tests for windows, see #6709
// Tests disabled due to gtest/gmock update causing build problems
// Decision to disable tests and create issue instead due to time constraints
// inline const Matcher<const IpcMessage&> IpcLogLineMessageEq(const String& s)
// {
// const Matcher<const IpcLogLineMessage&> m(
// Property(&IpcLogLineMessage::logLine, StrEq(s)));
// return MatcherCast<const IpcMessage&>(m);
// }
//
// TEST(IpcLogOutputterTests, write_threadingEnabled_bufferIsSent)
//{
// MockIpcServer mockServer;
// mockServer.delegateToFake();
//
// ON_CALL(mockServer, hasClients(_)).WillByDefault(Return(true));
//
// EXPECT_CALL(mockServer, hasClients(_)).Times(AtLeast(3));
// EXPECT_CALL(mockServer, send(IpcLogLineMessageEq("mock 1\n"),
// _)).Times(1); EXPECT_CALL(mockServer, send(IpcLogLineMessageEq("mock
// 2\n"), _)).Times(1);
//
// IpcLogOutputter outputter(mockServer, IpcClientType::Unknown, true);
// outputter.write(kNOTE, "mock 1");
// mockServer.waitForSend();
// outputter.write(kNOTE, "mock 2");
// mockServer.waitForSend();
// }
//
// TEST(IpcLogOutputterTests, write_overBufferMaxSize_firstLineTruncated)
//{
// MockIpcServer mockServer;
//
// ON_CALL(mockServer, hasClients(_)).WillByDefault(Return(true));
// EXPECT_CALL(mockServer, hasClients(_)).Times(1);
// EXPECT_CALL(mockServer, send(IpcLogLineMessageEq("mock 2\nmock 3\n"),
// _)).Times(1);
//
// IpcLogOutputter outputter(mockServer, IpcClientType::Unknown, false);
// outputter.bufferMaxSize(2);
//
// // log more lines than the buffer can contain
// outputter.write(kNOTE, "mock 1");
// outputter.write(kNOTE, "mock 2");
// outputter.write(kNOTE, "mock 3");
// outputter.sendBuffer();
// }
//
// TEST(IpcLogOutputterTests, write_underBufferMaxSize_allLinesAreSent)
//{
// MockIpcServer mockServer;
//
// ON_CALL(mockServer, hasClients(_)).WillByDefault(Return(true));
//
// EXPECT_CALL(mockServer, hasClients(_)).Times(1);
// EXPECT_CALL(mockServer, send(IpcLogLineMessageEq("mock 1\nmock 2\n"),
// _)).Times(1);
//
// IpcLogOutputter outputter(mockServer, IpcClientType::Unknown, false);
// outputter.bufferMaxSize(2);
//
// // log more lines than the buffer can contain
// outputter.write(kNOTE, "mock 1");
// outputter.write(kNOTE, "mock 2");
// outputter.sendBuffer();
// }
//
//// HACK: temporarily disable this intermittently failing unit test.
//// when the build machine is under heavy load, a race condition
//// usually happens.
// #if 0
// TEST(IpcLogOutputterTests, write_overBufferRateLimit_lastLineTruncated)
//{
// MockIpcServer mockServer;
//
// ON_CALL(mockServer, hasClients(_)).WillByDefault(Return(true));
//
// EXPECT_CALL(mockServer, hasClients(_)).Times(2);
// EXPECT_CALL(mockServer, send(IpcLogLineMessageEq("mock 1\nmock 2\n"),
// _)).Times(1); EXPECT_CALL(mockServer, send(IpcLogLineMessageEq("mock
// 4\nmock 5\n"), _)).Times(1);
//
// IpcLogOutputter outputter(mockServer, false);
// outputter.bufferRateLimit(2, 1); // 1s
//
// // log 1 more line than the buffer can accept in time limit.
// outputter.write(kNOTE, "mock 1");
// outputter.write(kNOTE, "mock 2");
// outputter.write(kNOTE, "mock 3");
//
// outputter.sendBuffer();
//
// // after waiting the time limit send another to make sure
// // we can log after the time limit passes.
// // HACK: sleep causes the unit test to fail intermittently,
// // so lets try 100ms (there must be a better way to solve this)
// ARCH->sleep(2); // 2s
// outputter.write(kNOTE, "mock 4");
// outputter.write(kNOTE, "mock 5");
// outputter.write(kNOTE, "mock 6");
//
// outputter.sendBuffer();
// }
// #endif
//
// TEST(IpcLogOutputterTests, write_underBufferRateLimit_allLinesAreSent)
//{
// MockIpcServer mockServer;
//
// ON_CALL(mockServer, hasClients(_)).WillByDefault(Return(true));
//
// EXPECT_CALL(mockServer, hasClients(_)).Times(2);
// EXPECT_CALL(mockServer, send(IpcLogLineMessageEq("mock 1\nmock 2\n"),
// _)).Times(1); EXPECT_CALL(mockServer, send(IpcLogLineMessageEq("mock
// 3\nmock 4\n"), _)).Times(1);
//
// IpcLogOutputter outputter(mockServer, IpcClientType::Unknown, false);
// outputter.bufferRateLimit(4, 1); // 1s (should be plenty of time)
//
// // log 1 more line than the buffer can accept in time limit.
// outputter.write(kNOTE, "mock 1");
// outputter.write(kNOTE, "mock 2");
// outputter.sendBuffer();
//
// // after waiting the time limit send another to make sure
// // we can log after the time limit passes.
// outputter.write(kNOTE, "mock 3");
// outputter.write(kNOTE, "mock 4");
// outputter.sendBuffer();
// }
#endif // WINAPI_MSWINDOWS
| 6,059
|
C++
|
.cpp
| 165
| 35.575758
| 79
| 0.693458
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,718
|
IpcSettingMessageTests.cpp
|
deskflow_deskflow/src/test/unittests/ipc/IpcSettingMessageTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2015-2022 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#define TEST_ENV
#include "ipc/IpcSettingMessage.h"
#include <gtest/gtest.h>
TEST(IpcSettingMessage, testIpcSettingMessage)
{
const std::string expected_name = "test";
const std::string expected_value = "test_value";
IpcSettingMessage message("test", "test_value");
EXPECT_EQ(expected_name, message.getName());
EXPECT_EQ(expected_value, message.getValue());
}
| 1,067
|
C++
|
.cpp
| 27
| 37.37037
| 72
| 0.761122
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,719
|
OSXClipboardUTF8ConverterTest.cpp
|
deskflow_deskflow/src/test/unittests/platform/OSXClipboardUTF8ConverterTest.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2011 Nick Bolton
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "platform/OSXClipboardUTF8Converter.h"
#include <gtest/gtest.h>
TEST(OSXClipboardUTF8ConverterTests, test_Format)
{
OSXClipboardUTF8Converter converter;
EXPECT_EQ(IClipboard::kText, converter.getFormat());
EXPECT_EQ(CFSTR("public.utf8-plain-text"), converter.getOSXFormat());
}
TEST(OSXClipboardUTF8ConverterTests, test_readWriteClipboard)
{
OSXClipboardUTF8Converter converter;
EXPECT_EQ("test data\r", converter.fromIClipboard("test data\n"));
EXPECT_EQ("test data\n", converter.toIClipboard("test data\r"));
}
| 1,263
|
C++
|
.cpp
| 31
| 38.709677
| 72
| 0.776873
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,720
|
XWindowsClipboardTests.cpp
|
deskflow_deskflow/src/test/unittests/platform/XWindowsClipboardTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "platform/XWindowsClipboard.h"
#include "test/shared/undef_x11_macros.h"
#include <gtest/gtest.h>
const auto None = 0L;
class TestXWindowsClipboard : public XWindowsClipboard
{
public:
class TestCICCCMGetClipboard : public CICCCMGetClipboard
{
public:
TestCICCCMGetClipboard() : CICCCMGetClipboard(None, None, None)
{
}
};
};
TEST(XWindowsClipboardTests_CICCCMGetClipboard, ctor_default_errorNone)
{
TestXWindowsClipboard::TestCICCCMGetClipboard clipboard;
EXPECT_EQ(None, clipboard.error());
}
| 1,221
|
C++
|
.cpp
| 36
| 31.638889
| 72
| 0.775042
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,721
|
OSXKeyStateTests.cpp
|
deskflow_deskflow/src/test/unittests/platform/OSXKeyStateTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2011 Nick Bolton
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "platform/OSXKeyState.h"
#include "test/mock/deskflow/MockEventQueue.h"
#include "test/mock/deskflow/MockKeyMap.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
TEST(OSXKeyStateTests, mapModifiersFromOSX_OSXMask_returnDeskflowMask)
{
deskflow::KeyMap keyMap;
MockEventQueue eventQueue;
OSXKeyState keyState(&eventQueue, keyMap, {"en"}, true);
KeyModifierMask outMask = 0;
UInt32 shiftMask = 0 | kCGEventFlagMaskShift;
outMask = keyState.mapModifiersFromOSX(shiftMask);
EXPECT_EQ(KeyModifierShift, outMask);
UInt32 ctrlMask = 0 | kCGEventFlagMaskControl;
outMask = keyState.mapModifiersFromOSX(ctrlMask);
EXPECT_EQ(KeyModifierControl, outMask);
UInt32 altMask = 0 | kCGEventFlagMaskAlternate;
outMask = keyState.mapModifiersFromOSX(altMask);
EXPECT_EQ(KeyModifierAlt, outMask);
UInt32 cmdMask = 0 | kCGEventFlagMaskCommand;
outMask = keyState.mapModifiersFromOSX(cmdMask);
EXPECT_EQ(KeyModifierSuper, outMask);
UInt32 capsMask = 0 | kCGEventFlagMaskAlphaShift;
outMask = keyState.mapModifiersFromOSX(capsMask);
EXPECT_EQ(KeyModifierCapsLock, outMask);
UInt32 numMask = 0 | kCGEventFlagMaskNumericPad;
outMask = keyState.mapModifiersFromOSX(numMask);
EXPECT_EQ(KeyModifierNumLock, outMask);
}
| 1,983
|
C++
|
.cpp
| 47
| 39.702128
| 72
| 0.787643
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,722
|
LoggerTests.cpp
|
deskflow_deskflow/src/test/unittests/gui/LoggerTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "gui/Logger.h"
#include "gmock/gmock.h"
#include <gtest/gtest.h>
using namespace testing;
using namespace deskflow::gui;
TEST(LoggerTests, handleMessage_withDebugEnvVarOn_emitsNewLine)
{
Logger logger;
std::string newLineEmitted;
QObject::connect(
&logger, &Logger::newLine, //
[&newLineEmitted](const QString &line) { newLineEmitted = line.toStdString(); }
);
qputenv("DESKFLOW_GUI_DEBUG", "true");
logger.loadEnvVars();
logger.handleMessage(QtDebugMsg, "stub", "test");
EXPECT_THAT(newLineEmitted, HasSubstr("test"));
qputenv("DESKFLOW_GUI_DEBUG", "");
}
TEST(LoggerTests, handleMessage_withDebugEnvVarOff_doesNotEmitNewLine)
{
Logger logger;
bool newLineEmitted = false;
QObject::connect(
&logger, &Logger::newLine, //
[&newLineEmitted](const QString &line) { newLineEmitted = true; }
);
qputenv("DESKFLOW_GUI_DEBUG", "false");
logger.loadEnvVars();
logger.handleMessage(QtDebugMsg, "stub", "test");
EXPECT_FALSE(newLineEmitted);
qputenv("DESKFLOW_GUI_DEBUG", "");
}
| 1,736
|
C++
|
.cpp
| 49
| 32.673469
| 85
| 0.741647
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,723
|
byte_utils_tests.cpp
|
deskflow_deskflow/src/test/unittests/gui/byte_utils_tests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "gui/byte_utils.h"
#include <gtest/gtest.h>
using namespace deskflow::gui;
TEST(byte_utils_tests, bytesToInt_size4)
{
char buffer[4] = {0x01, 0x02, 0x03, 0x04};
const auto i = bytesToInt(buffer, 4);
EXPECT_EQ(i, 0x01020304);
}
TEST(byte_utils_tests, intToBytes_size4)
{
QByteArray bytes = intToBytes(0x01020304);
EXPECT_EQ(bytes.size(), 4);
EXPECT_EQ(bytes[0], 0x01);
EXPECT_EQ(bytes[1], 0x02);
EXPECT_EQ(bytes[2], 0x03);
EXPECT_EQ(bytes[3], 0x04);
}
| 1,172
|
C++
|
.cpp
| 34
| 32.264706
| 72
| 0.739823
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,724
|
VersionCheckerTests.cpp
|
deskflow_deskflow/src/test/unittests/gui/VersionCheckerTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "gui/VersionChecker.h"
#include "shared/gui/TestQtCoreApp.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using namespace deskflow::gui::proxy;
using namespace testing;
class VersionCheckerTests : public ::testing::Test
{
protected:
int compareVersions(const QString &left, const QString &right)
{
return VersionChecker::compareVersions(left, right);
}
};
class MockNetworkAccessManager : public QNetworkAccessManagerProxy
{
public:
MOCK_METHOD(void, init, (), (override));
MOCK_METHOD(void, get, (const QNetworkRequest &request), (const, override));
};
TEST_F(VersionCheckerTests, checkLatest_callsNetworkGet)
{
TestQtCoreApp app;
const auto network = std::make_shared<NiceMock<MockNetworkAccessManager>>();
const VersionChecker checker(network);
EXPECT_CALL(*network, get(testing::_)).Times(1);
checker.checkLatest();
}
TEST_F(VersionCheckerTests, compareVersions_major_isValid)
{
EXPECT_EQ(compareVersions("1.0.0", "2.0.0"), 1);
EXPECT_EQ(compareVersions("2.0.0", "1.0.0"), -1);
EXPECT_EQ(compareVersions("1.0.0", "1.0.0"), 0);
}
TEST_F(VersionCheckerTests, compareVersions_minor_isValid)
{
EXPECT_EQ(compareVersions("1.1.0", "1.2.0"), 1);
EXPECT_EQ(compareVersions("1.2.0", "1.1.0"), -1);
EXPECT_EQ(compareVersions("1.1.0", "1.1.0"), 0);
}
TEST_F(VersionCheckerTests, compareVersions_patch_isValid)
{
EXPECT_EQ(compareVersions("1.0.1", "1.0.2"), 1);
EXPECT_EQ(compareVersions("1.0.2", "1.0.1"), -1);
EXPECT_EQ(compareVersions("1.0.1", "1.0.1"), 0);
}
| 2,208
|
C++
|
.cpp
| 62
| 33.516129
| 78
| 0.740047
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,725
|
WaylandWarningsTests.cpp
|
deskflow_deskflow/src/test/unittests/gui/core/WaylandWarningsTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "gui/core/WaylandWarnings.h"
#include "gui/core/CoreProcess.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using namespace deskflow::gui;
using namespace deskflow::gui::core;
namespace {
struct MockDeps : public WaylandWarnings::Deps
{
MOCK_METHOD(void, showWaylandLibraryError, (QWidget *), (override));
};
} // namespace
TEST(WaylandWarningsTests, showOnce_serverNoEi_showLibraryError)
{
const auto deps = std::make_shared<MockDeps>();
const bool hasEi = false;
const bool hasPortal = false;
const bool hasPortalIC = false;
WaylandWarnings waylandWarnings(deps);
EXPECT_CALL(*deps, showWaylandLibraryError(nullptr)).Times(1);
waylandWarnings.showOnce(nullptr, CoreProcess::Mode::Server, hasEi, hasPortal, hasPortalIC);
}
TEST(WaylandWarningsTests, showOnce_serverNoPortal_showLibraryError)
{
const auto deps = std::make_shared<MockDeps>();
const bool hasEi = true;
const bool hasPortal = false;
const bool hasPortalIC = false;
WaylandWarnings waylandWarnings(deps);
EXPECT_CALL(*deps, showWaylandLibraryError(nullptr)).Times(1);
waylandWarnings.showOnce(nullptr, CoreProcess::Mode::Server, hasEi, hasPortal, hasPortalIC);
}
TEST(WaylandWarningsTests, showOnce_serverNoPortalIc_showLibraryError)
{
const auto deps = std::make_shared<MockDeps>();
const bool hasEi = true;
const bool hasPortal = true;
const bool hasPortalIC = false;
WaylandWarnings waylandWarnings(deps);
EXPECT_CALL(*deps, showWaylandLibraryError(nullptr)).Times(1);
waylandWarnings.showOnce(nullptr, CoreProcess::Mode::Server, hasEi, hasPortal, hasPortalIC);
}
TEST(WaylandWarningsTests, showOnce_failureCalledTwice_messageOnlyShownOnce)
{
const auto deps = std::make_shared<MockDeps>();
const bool hasEi = false;
const bool hasPortal = false;
const bool hasPortalIC = false;
WaylandWarnings waylandWarnings(deps);
EXPECT_CALL(*deps, showWaylandLibraryError(nullptr)).Times(1);
waylandWarnings.showOnce(nullptr, CoreProcess::Mode::Server, hasEi, hasPortal, hasPortalIC);
waylandWarnings.showOnce(nullptr, CoreProcess::Mode::Server, hasEi, hasPortal, hasPortalIC);
}
| 2,814
|
C++
|
.cpp
| 69
| 38.434783
| 94
| 0.782912
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,726
|
CoreProcessTests.cpp
|
deskflow_deskflow/src/test/unittests/gui/core/CoreProcessTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "gui/config/IAppConfig.h"
#include "gui/core/CoreProcess.h"
#include "gui/ipc/IQIpcClient.h"
#include "gui/proxy/QProcessProxy.h"
#include "shared/gui/mocks/AppConfigMock.h"
#include "shared/gui/mocks/ServerConfigMock.h"
#include "gmock/gmock.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using namespace deskflow::gui;
using namespace testing;
namespace {
class QProcessProxyMock : public proxy::QProcessProxy
{
public:
operator bool() const override
{
return toBool();
}
QProcessProxyMock()
{
ON_CALL(*this, toBool()).WillByDefault(Return(true));
ON_CALL(*this, state()).WillByDefault(Return(QProcess::ProcessState::Running));
ON_CALL(*this, waitForStarted()).WillByDefault(Return(true));
}
MOCK_METHOD(bool, toBool, (), (const));
MOCK_METHOD(void, create, (), (override));
MOCK_METHOD(void, start, (const QString &program, const QStringList &arguments), (override));
MOCK_METHOD(bool, waitForStarted, (), (override));
MOCK_METHOD(QProcess::ProcessState, state, (), (const, override));
MOCK_METHOD(void, close, (), (override));
MOCK_METHOD(QString, readAllStandardOutput, (), (override));
MOCK_METHOD(QString, readAllStandardError, (), (override));
};
class QIpcClientMock : public ipc::IQIpcClient
{
public:
QIpcClientMock()
{
ON_CALL(*this, isConnected()).WillByDefault(Return(true));
}
MOCK_METHOD(void, sendHello, (), (const, override));
MOCK_METHOD(void, sendCommand, (const QString &command, ElevateMode elevate), (const, override));
MOCK_METHOD(void, connectToHost, (), (override));
MOCK_METHOD(void, disconnectFromHost, (), (override));
MOCK_METHOD(bool, isConnected, (), (const, override));
};
class DepsMock : public CoreProcess::Deps
{
public:
DepsMock()
{
ON_CALL(*this, process()).WillByDefault(ReturnRef(m_process));
ON_CALL(*this, ipcClient()).WillByDefault(ReturnRef(m_ipcClient));
ON_CALL(*this, appPath(_)).WillByDefault(Return("stub app path"));
ON_CALL(*this, fileExists(_)).WillByDefault(Return(true));
ON_CALL(*this, getProfileRoot()).WillByDefault(Return("stub profile"));
}
MOCK_METHOD(proxy::QProcessProxy &, process, (), (override));
MOCK_METHOD(ipc::IQIpcClient &, ipcClient, (), (override));
MOCK_METHOD(QString, appPath, (const QString &name), (const, override));
MOCK_METHOD(bool, fileExists, (const QString &path), (const, override));
MOCK_METHOD(QString, getProfileRoot, (), (const, override));
NiceMock<QProcessProxyMock> m_process;
NiceMock<QIpcClientMock> m_ipcClient;
};
class CoreProcessTests : public Test
{
public:
CoreProcessTests() : m_coreProcess(m_appConfig, m_serverConfig, m_pDeps)
{
}
NiceMock<AppConfigMock> m_appConfig;
NiceMock<ServerConfigMock> m_serverConfig;
std::shared_ptr<NiceMock<DepsMock>> m_pDeps = std::make_shared<NiceMock<DepsMock>>();
CoreProcess m_coreProcess;
};
} // namespace
TEST_F(CoreProcessTests, start_serverDesktop_callsProcessStart)
{
m_coreProcess.setMode(CoreProcess::Mode::Server);
EXPECT_CALL(m_pDeps->m_process, start(_, _)).Times(1);
m_coreProcess.start(ProcessMode::kDesktop);
}
TEST_F(CoreProcessTests, start_serverService_callsSendCommand)
{
m_coreProcess.setMode(CoreProcess::Mode::Server);
EXPECT_CALL(m_pDeps->m_ipcClient, sendCommand(_, _)).Times(1);
m_coreProcess.start(ProcessMode::kService);
}
TEST_F(CoreProcessTests, start_clientDesktop_callsProcessStart)
{
m_coreProcess.setMode(CoreProcess::Mode::Client);
m_coreProcess.setAddress("stub address");
EXPECT_CALL(m_pDeps->m_process, start(_, _)).Times(1);
m_coreProcess.start(ProcessMode::kDesktop);
}
TEST_F(CoreProcessTests, start_clientService_callsSendCommand)
{
m_coreProcess.setMode(CoreProcess::Mode::Client);
m_coreProcess.setAddress("stub address");
EXPECT_CALL(m_pDeps->m_ipcClient, sendCommand(_, _)).Times(1);
m_coreProcess.start(ProcessMode::kService);
}
TEST_F(CoreProcessTests, stop_serverDesktop_callsProcessClose)
{
m_coreProcess.setMode(CoreProcess::Mode::Server);
m_coreProcess.start();
EXPECT_CALL(m_pDeps->m_process, close()).Times(1);
m_coreProcess.stop(ProcessMode::kDesktop);
}
TEST_F(CoreProcessTests, stop_serverService_callsSendCommand)
{
m_coreProcess.setMode(CoreProcess::Mode::Server);
m_coreProcess.start();
EXPECT_CALL(m_pDeps->m_ipcClient, sendCommand(_, _)).Times(1);
m_coreProcess.stop(ProcessMode::kService);
}
TEST_F(CoreProcessTests, stop_clientDesktop_callsProcessClose)
{
m_coreProcess.setMode(CoreProcess::Mode::Client);
m_coreProcess.setAddress("stub address");
m_coreProcess.start();
EXPECT_CALL(m_pDeps->m_process, close()).Times(1);
m_coreProcess.stop(ProcessMode::kDesktop);
}
TEST_F(CoreProcessTests, stop_clientService_callsSendCommand)
{
m_coreProcess.setMode(CoreProcess::Mode::Client);
m_coreProcess.setAddress("stub address");
m_coreProcess.start();
EXPECT_CALL(m_pDeps->m_ipcClient, sendCommand(_, _)).Times(1);
m_coreProcess.stop(ProcessMode::kService);
}
TEST_F(CoreProcessTests, restart_serverDesktop_callsProcessStart)
{
ON_CALL(m_appConfig, processMode()).WillByDefault(Return(ProcessMode::kDesktop));
m_coreProcess.setMode(CoreProcess::Mode::Server);
m_coreProcess.start();
EXPECT_CALL(m_pDeps->m_process, close()).Times(1);
EXPECT_CALL(m_pDeps->m_process, start(_, _)).Times(1);
m_coreProcess.restart();
}
| 6,046
|
C++
|
.cpp
| 159
| 35.446541
| 99
| 0.748503
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,727
|
ClientConnectionTests.cpp
|
deskflow_deskflow/src/test/unittests/gui/core/ClientConnectionTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "gui/core/ClientConnection.h"
#include "shared/gui/mocks/AppConfigMock.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
class QWidget;
using testing::_;
using testing::NiceMock;
using namespace deskflow::gui;
using enum messages::ClientError;
namespace {
struct DepsMock : public ClientConnection::Deps
{
MOCK_METHOD(
void, showError, (QWidget * parent, messages::ClientError error, const QString &address), (const, override)
);
};
} // namespace
class ClientConnectionTests : public testing::Test
{
public:
ClientConnectionTests()
{
ON_CALL(m_appConfig, serverHostname()).WillByDefault(testing::ReturnRef(stub));
}
std::shared_ptr<DepsMock> m_pDeps = std::make_shared<NiceMock<DepsMock>>();
NiceMock<AppConfigMock> m_appConfig;
private:
const QString stub = "stub";
};
TEST_F(ClientConnectionTests, handleLogLine_alreadyConnected_showError)
{
ClientConnection clientConnection(nullptr, m_appConfig, m_pDeps);
const QString serverName = "test server";
ON_CALL(m_appConfig, serverHostname()).WillByDefault(testing::ReturnRef(serverName));
EXPECT_CALL(*m_pDeps, showError(_, AlreadyConnected, serverName));
clientConnection.handleLogLine("failed to connect to server\n"
"server already has a connected client with our name");
}
TEST_F(ClientConnectionTests, handleLogLine_withHostname_showError)
{
ClientConnection clientConnection(nullptr, m_appConfig, m_pDeps);
const QString serverName = "test-hostname";
ON_CALL(m_appConfig, serverHostname()).WillByDefault(testing::ReturnRef(serverName));
EXPECT_CALL(*m_pDeps, showError(_, HostnameError, serverName));
clientConnection.handleLogLine("failed to connect to server");
}
TEST_F(ClientConnectionTests, handleLogLine_withIpAddress_showError)
{
ClientConnection clientConnection(nullptr, m_appConfig, m_pDeps);
const QString serverName = "1.1.1.1";
ON_CALL(m_appConfig, serverHostname()).WillByDefault(testing::ReturnRef(serverName));
EXPECT_CALL(*m_pDeps, showError(_, GenericError, serverName));
clientConnection.handleLogLine("failed to connect to server");
}
TEST_F(ClientConnectionTests, handleLogLine_messageShown_shouldNotShowAgain)
{
ClientConnection clientConnection(nullptr, m_appConfig, m_pDeps);
clientConnection.handleLogLine("failed to connect to server");
EXPECT_CALL(*m_pDeps, showError(_, _, _)).Times(0);
clientConnection.handleLogLine("failed to connect to server");
}
TEST_F(ClientConnectionTests, handleLogLine_serverRefusedClient_shouldNotShowError)
{
ClientConnection clientConnection(nullptr, m_appConfig, m_pDeps);
EXPECT_CALL(*m_pDeps, showError(_, _, _)).Times(0);
clientConnection.handleLogLine("failed to connect to server\n"
"server refused client with our name");
}
TEST_F(ClientConnectionTests, handleLogLine_connected_shouldPreventFutureError)
{
ClientConnection clientConnection(nullptr, m_appConfig, m_pDeps);
clientConnection.handleLogLine("connected to server");
EXPECT_CALL(*m_pDeps, showError(_, _, _)).Times(0);
clientConnection.handleLogLine("failed to connect to server");
}
TEST_F(ClientConnectionTests, handleLogLine_otherMessage_shouldNotShowError)
{
ClientConnection clientConnection(nullptr, m_appConfig, m_pDeps);
EXPECT_CALL(*m_pDeps, showError(_, _, _)).Times(0);
clientConnection.handleLogLine("hello world");
}
| 4,092
|
C++
|
.cpp
| 97
| 39.14433
| 113
| 0.77057
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,728
|
ServerConnectionTests.cpp
|
deskflow_deskflow/src/test/unittests/gui/core/ServerConnectionTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "gui/config/ServerConfigDialogState.h"
#include "gui/core/ServerConnection.h"
#include "shared/gui/mocks/AppConfigMock.h"
#include "shared/gui/mocks/ServerConfigMock.h"
#include "gmock/gmock.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using testing::_;
using testing::NiceMock;
using namespace deskflow::gui;
class QWidget;
namespace {
struct DepsMock : public ServerConnection::Deps
{
MOCK_METHOD(
messages::NewClientPromptResult, showNewClientPrompt, (QWidget * parent, const QString &clientName),
(const, override)
);
};
} // namespace
class ServerConnectionTests : public testing::Test
{
public:
std::shared_ptr<DepsMock> m_pDeps = std::make_shared<NiceMock<DepsMock>>();
NiceMock<AppConfigMock> m_appConfig;
NiceMock<ServerConfigMock> m_serverConfig;
config::ServerConfigDialogState m_serverConfigDialogState;
};
TEST_F(ServerConnectionTests, handleLogLine_newClient_shouldShowPrompt)
{
ServerConnection serverConnection(nullptr, m_appConfig, m_serverConfig, m_serverConfigDialogState, m_pDeps);
QString clientName = "test client";
EXPECT_CALL(*m_pDeps, showNewClientPrompt(_, clientName));
serverConnection.handleLogLine(R"(unrecognised client name "test client")");
}
TEST_F(ServerConnectionTests, handleLogLine_ignoredClient_shouldNotShowPrompt)
{
ServerConnection serverConnection(nullptr, m_appConfig, m_serverConfig, m_serverConfigDialogState, m_pDeps);
ON_CALL(*m_pDeps, showNewClientPrompt(_, _)).WillByDefault(testing::Return(messages::NewClientPromptResult::Ignore));
serverConnection.handleLogLine(R"(unrecognised client name "stub")");
EXPECT_CALL(*m_pDeps, showNewClientPrompt(_, _)).Times(0);
serverConnection.handleLogLine(R"(unrecognised client name "stub")");
}
TEST_F(ServerConnectionTests, handleLogLine_serverConfigFull_shouldNotShowPrompt)
{
ServerConnection serverConnection(nullptr, m_appConfig, m_serverConfig, m_serverConfigDialogState, m_pDeps);
ON_CALL(m_serverConfig, isFull()).WillByDefault(testing::Return(true));
EXPECT_CALL(*m_pDeps, showNewClientPrompt(_, _)).Times(0);
serverConnection.handleLogLine(R"(unrecognised client name "test client")");
}
TEST_F(ServerConnectionTests, handleLogLine_screenExists_shouldNotShowPrompt)
{
ServerConnection serverConnection(nullptr, m_appConfig, m_serverConfig, m_serverConfigDialogState, m_pDeps);
ON_CALL(m_serverConfig, screenExists(_)).WillByDefault(testing::Return(true));
EXPECT_CALL(*m_pDeps, showNewClientPrompt(_, _)).Times(0);
serverConnection.handleLogLine(R"(unrecognised client name "test client")");
}
| 3,276
|
C++
|
.cpp
| 73
| 42.589041
| 119
| 0.789755
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,729
|
QIpcClientTests.cpp
|
deskflow_deskflow/src/test/unittests/gui/ipc/QIpcClientTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "gui/ipc/QIpcClient.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using testing::_;
using testing::StrEq;
namespace {
class MockStream : public QDataStreamProxy
{
public:
MOCK_METHOD(qint64, writeRawData, (const char *, int), (override));
};
} // namespace
TEST(QIpcClientTests, sendCommand_anyCommand_commandSent)
{
auto mockStream = std::make_shared<MockStream>();
QIpcClient::StreamProvider streamProvider = [&mockStream]() { return mockStream; };
EXPECT_CALL(*mockStream, writeRawData(_, _)).Times(3);
EXPECT_CALL(*mockStream, writeRawData(StrEq("test"), 4)).Times(1);
QIpcClient ipcClient(streamProvider);
ipcClient.sendCommand("test", ElevateMode::kAutomatic);
}
| 1,394
|
C++
|
.cpp
| 37
| 35.648649
| 85
| 0.758902
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,730
|
AppConfigTests.cpp
|
deskflow_deskflow/src/test/unittests/gui/config/AppConfigTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "gui/config/AppConfig.h"
#include "gui/proxy/QSettingsProxy.h"
#include "gmock/gmock.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using namespace testing;
using namespace deskflow::gui::proxy;
namespace {
class ConfigScopesMock : public deskflow::gui::IConfigScopes
{
using QSettingsProxy = deskflow::gui::proxy::QSettingsProxy;
public:
MOCK_METHOD(void, signalReady, (), (override));
MOCK_METHOD(bool, scopeContains, (const QString &name, Scope scope), (const, override));
MOCK_METHOD(
QVariant, getFromScope, (const QString &name, const QVariant &defaultValue, Scope scope), (const, override)
);
MOCK_METHOD(void, setInScope, (const QString &name, const QVariant &value, Scope scope), (override));
MOCK_METHOD(Scope, activeScope, (), (const, override));
MOCK_METHOD(void, setActiveScope, (Scope scope), (override));
MOCK_METHOD(bool, isActiveScopeWritable, (), (const, override));
MOCK_METHOD(const QSettingsProxy &, activeSettings, (), (const, override));
MOCK_METHOD(QSettingsProxy &, activeSettings, (), (override));
MOCK_METHOD(void, save, (bool), (override));
MOCK_METHOD(QString, activeFilePath, (), (const, override));
};
struct DepsMock : public AppConfig::Deps
{
DepsMock()
{
ON_CALL(*this, defaultTlsCertPath()).WillByDefault(Return("stub"));
ON_CALL(*this, hostname()).WillByDefault(Return("stub"));
}
static std::shared_ptr<NiceMock<DepsMock>> makeNice()
{
return std::make_shared<NiceMock<DepsMock>>();
}
MOCK_METHOD(QString, defaultTlsCertPath, (), (const, override));
MOCK_METHOD(QString, hostname, (), (const, override));
};
} // namespace
class AppConfigTests : public Test
{
};
TEST_F(AppConfigTests, ctor_byDefault_screenNameIsHostname)
{
NiceMock<ConfigScopesMock> scopes;
auto deps = DepsMock::makeNice();
ON_CALL(*deps, hostname()).WillByDefault(Return("test hostname"));
AppConfig appConfig(scopes, deps);
ASSERT_EQ(appConfig.screenName().toStdString(), "test hostname");
}
TEST_F(AppConfigTests, ctor_byDefault_getsFromScope)
{
NiceMock<ConfigScopesMock> scopes;
auto deps = DepsMock::makeNice();
ON_CALL(scopes, scopeContains(_, _)).WillByDefault(Return(true));
ON_CALL(scopes, getFromScope(_, _, _)).WillByDefault(Return(QVariant("test screen")));
EXPECT_CALL(scopes, getFromScope(_, _, _)).Times(AnyNumber());
AppConfig appConfig(scopes, deps);
ASSERT_EQ(appConfig.screenName().toStdString(), "test screen");
}
TEST_F(AppConfigTests, commit_byDefault_setsToScope)
{
NiceMock<ConfigScopesMock> scopes;
auto deps = DepsMock::makeNice();
AppConfig appConfig(scopes, deps);
ON_CALL(scopes, isActiveScopeWritable()).WillByDefault(Return(true));
EXPECT_CALL(scopes, setInScope(_, _, _)).Times(AnyNumber());
appConfig.commit();
}
| 3,473
|
C++
|
.cpp
| 87
| 37.390805
| 113
| 0.741379
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,731
|
ConfigScopesTests.cpp
|
deskflow_deskflow/src/test/unittests/gui/config/ConfigScopesTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "gui/config/ConfigScopes.h"
#include "gmock/gmock.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <memory>
using namespace testing;
using namespace deskflow::gui;
using namespace deskflow::gui::proxy;
namespace {
class QSettingsProxyMock : public QSettingsProxy
{
public:
MOCK_METHOD(void, loadSystem, (), (override));
MOCK_METHOD(void, loadUser, (), (override));
MOCK_METHOD(QString, fileName, (), (const, override));
MOCK_METHOD(void, sync, (), (override));
MOCK_METHOD(bool, isWritable, (), (const, override));
MOCK_METHOD(bool, contains, (const QString &), (const, override));
MOCK_METHOD(QVariant, value, (const QString &), (const, override));
MOCK_METHOD(QVariant, value, (const QString &, const QVariant &), (const, override));
MOCK_METHOD(void, setValue, (const QString &, const QVariant &), (override));
};
struct DepsMock : public ConfigScopes::Deps
{
DepsMock()
{
ON_CALL(*this, makeUserSettings()).WillByDefault(Return(m_pUserSettings));
ON_CALL(*this, makeSystemSettings()).WillByDefault(Return(m_pSystemSettings));
}
MOCK_METHOD(std::shared_ptr<QSettingsProxy>, makeUserSettings, (), (override));
MOCK_METHOD(std::shared_ptr<QSettingsProxy>, makeSystemSettings, (), (override));
std::shared_ptr<QSettingsProxyMock> m_pUserSettings = std::make_shared<NiceMock<QSettingsProxyMock>>();
std::shared_ptr<QSettingsProxyMock> m_pSystemSettings = std::make_shared<NiceMock<QSettingsProxyMock>>();
};
} // namespace
TEST(ConfigScopesTests, ctor_callsMakeUserSettings)
{
auto deps = std::make_shared<NiceMock<DepsMock>>();
EXPECT_CALL(*deps, makeUserSettings()).Times(1);
ConfigScopes configScopes(deps);
}
TEST(ConfigScopesTests, ctor_callsMakeSystemSettings)
{
auto deps = std::make_shared<NiceMock<DepsMock>>();
EXPECT_CALL(*deps, makeSystemSettings()).Times(1);
ConfigScopes configScopes(deps);
}
TEST(ConfigScopesTests, save_syncsBothScopes)
{
auto deps = std::make_shared<NiceMock<DepsMock>>();
ConfigScopes configScopes(deps);
EXPECT_CALL(*deps->m_pUserSettings, sync()).Times(1);
EXPECT_CALL(*deps->m_pSystemSettings, sync()).Times(1);
configScopes.save();
}
TEST(ConfigScopesTests, activeSettings_returnsUserSettingsByDefault)
{
auto deps = std::make_shared<NiceMock<DepsMock>>();
ConfigScopes configScopes(deps);
EXPECT_EQ(&configScopes.activeSettings(), deps->m_pUserSettings.get());
}
TEST(ConfigScopesTests, activeSettings_returnsSystemSettingsWhenSystemScope)
{
auto deps = std::make_shared<NiceMock<DepsMock>>();
ConfigScopes configScopes(deps);
configScopes.setActiveScope(ConfigScopes::Scope::System);
EXPECT_EQ(&configScopes.activeSettings(), deps->m_pSystemSettings.get());
}
TEST(ConfigScopesTests, setActiveScope_setsCurrentScope)
{
auto deps = std::make_shared<NiceMock<DepsMock>>();
ConfigScopes configScopes(deps);
configScopes.setActiveScope(ConfigScopes::Scope::System);
EXPECT_EQ(configScopes.activeScope(), ConfigScopes::Scope::System);
}
TEST(ConfigScopesTests, isActiveScopeWritable_returnsTrueWhenUserSettingsWritable)
{
auto deps = std::make_shared<NiceMock<DepsMock>>();
ConfigScopes configScopes(deps);
EXPECT_CALL(*deps->m_pUserSettings, isWritable()).WillOnce(Return(true));
EXPECT_TRUE(configScopes.isActiveScopeWritable());
}
TEST(ConfigScopesTests, scopeContains_byDefault_returnsTrueWhenUserSettingsContainsKey)
{
auto deps = std::make_shared<NiceMock<DepsMock>>();
ON_CALL(*deps->m_pUserSettings, contains(_)).WillByDefault(Return(true));
ConfigScopes configScopes(deps);
EXPECT_TRUE(configScopes.scopeContains("stub"));
}
TEST(ConfigScopesTests, scopeContains_userScope_returnsTrueWhenUserSettingsContainsKey)
{
auto deps = std::make_shared<NiceMock<DepsMock>>();
ON_CALL(*deps->m_pUserSettings, contains(_)).WillByDefault(Return(true));
ConfigScopes configScopes(deps);
EXPECT_TRUE(configScopes.scopeContains("stub", ConfigScopes::Scope::User));
}
TEST(ConfigScopesTests, scopeContains_systemScope_returnsTrueWhenSystemSettingsContainsKey)
{
auto deps = std::make_shared<NiceMock<DepsMock>>();
ON_CALL(*deps->m_pSystemSettings, contains(_)).WillByDefault(Return(true));
ConfigScopes configScopes(deps);
EXPECT_TRUE(configScopes.scopeContains("stub", ConfigScopes::Scope::System));
}
TEST(ConfigScopesTests, activeFilePath_returnsUserSettingsFileNameByDefault)
{
auto deps = std::make_shared<NiceMock<DepsMock>>();
ON_CALL(*deps->m_pUserSettings, fileName()).WillByDefault(Return("test"));
ConfigScopes configScopes(deps);
EXPECT_EQ(configScopes.activeFilePath(), "test");
}
TEST(ConfigScopesTests, getFromScope_byDefault_returnsValueFromActiveSettings)
{
auto deps = std::make_shared<NiceMock<DepsMock>>();
ON_CALL(*deps->m_pUserSettings, value(_, _)).WillByDefault(Return("test"));
ConfigScopes configScopes(deps);
EXPECT_EQ(configScopes.getFromScope("stub"), "test");
}
TEST(ConfigScopesTests, setInScope_byDefault_setsValueInActiveSettings)
{
auto deps = std::make_shared<NiceMock<DepsMock>>();
ConfigScopes configScopes(deps);
EXPECT_CALL(*deps->m_pUserSettings, setValue(_, _)).Times(1);
configScopes.setInScope("stub", "test");
}
| 5,887
|
C++
|
.cpp
| 140
| 39.55
| 107
| 0.771258
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,732
|
ScreenTests.cpp
|
deskflow_deskflow/src/test/unittests/gui/config/ScreenTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "gui/config/Screen.h"
#include "gui/proxy/QSettingsProxy.h"
#include "shared/gui/TestQtCoreApp.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using namespace deskflow::gui::proxy;
using namespace testing;
class QSettingsProxyMock : public QSettingsProxy
{
public:
MOCK_METHOD(int, beginReadArray, (const QString &prefix), (override));
MOCK_METHOD(void, beginWriteArray, (const QString &prefix), (override));
MOCK_METHOD(void, setArrayIndex, (int i), (override));
MOCK_METHOD(QVariant, value, (const QString &key), (const, override));
MOCK_METHOD(QVariant, value, (const QString &key, const QVariant &defaultValue), (const, override));
MOCK_METHOD(void, endArray, (), (override));
MOCK_METHOD(void, setValue, (const QString &key, const QVariant &value), (override));
MOCK_METHOD(void, beginGroup, (const QString &prefix), (override));
MOCK_METHOD(void, endGroup, (), (override));
MOCK_METHOD(void, remove, (const QString &key), (override));
MOCK_METHOD(bool, isWritable, (), (const, override));
MOCK_METHOD(bool, contains, (const QString &key), (const, override));
};
TEST(ScreenTests, loadSettings_whenHasSetting_readsArray)
{
TestQtCoreApp app;
NiceMock<QSettingsProxyMock> settings;
Screen screen;
ON_CALL(settings, value(_)).WillByDefault(Return("stub"));
EXPECT_CALL(settings, beginReadArray(_)).Times(4);
screen.loadSettings(settings);
}
TEST(ScreenTests, saveSettings_whenNameIsSet_writesArray)
{
TestQtCoreApp app;
NiceMock<QSettingsProxyMock> settings;
Screen screen;
screen.setName("stub");
EXPECT_CALL(settings, beginWriteArray(_)).Times(4);
screen.saveSettings(settings);
}
| 2,345
|
C++
|
.cpp
| 57
| 38.842105
| 102
| 0.754941
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,733
|
XBaseTests.cpp
|
deskflow_deskflow/src/test/unittests/base/XBaseTests.cpp
|
#include "base/XBase.h"
#include <gtest/gtest.h>
TEST(XBaseTests, what_emptyWhat_returnsWhatFromGetWhat)
{
XBase xbase;
const char *result = xbase.what();
EXPECT_STREQ("", result);
}
TEST(XBaseTests, what_nonEmptyWhat_returnsWhatFromGetWhat)
{
XBase xbase("test");
const char *result = xbase.what();
EXPECT_STREQ("test", result);
}
| 351
|
C++
|
.cpp
| 14
| 22.714286
| 58
| 0.745455
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,734
|
PathTests.cpp
|
deskflow_deskflow/src/test/unittests/base/PathTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2014-2021 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "base/Path.h"
#include <fstream>
#include <gtest/gtest.h>
const std::string testDir = "tmp/test";
const std::wstring testDirW = L"tmp/test";
TEST(PathTests, open_file_using_path)
{
std::string utf8FileName = testDir + "/тіás.txt";
#if SYSAPI_WIN32
// Windows uses UTF-16 for file path and names
std::wstring fileName = testDirW + L"/\x0442\x0456\x00E1\x0073\x002E\x0074\x0078\x0074";
#else
std::string fileName = utf8FileName;
#endif
std::fstream file(fileName, std::fstream::out);
file << "test";
file.close();
std::ifstream inFile(deskflow::filesystem::path(utf8FileName));
EXPECT_TRUE(inFile.is_open());
}
| 1,336
|
C++
|
.cpp
| 36
| 34.944444
| 90
| 0.745933
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,735
|
LogTests.cpp
|
deskflow_deskflow/src/test/unittests/base/LogTests.cpp
|
#include "base/Log.h"
#include "gmock/gmock-matchers.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#define LEVEL_PRINT "%z\057"
#define LEVEL_ERR "%z\061"
#define LEVEL_INFO "%z\064"
using testing::EndsWith;
using testing::HasSubstr;
using testing::internal::CaptureStderr;
using testing::internal::CaptureStdout;
using testing::internal::GetCapturedStderr;
using testing::internal::GetCapturedStdout;
TEST(LogTests, print_withErrorLevel_outputIsValid)
{
CaptureStderr();
Log log(false);
log.print(nullptr, 0, LEVEL_ERR "test message");
EXPECT_THAT(GetCapturedStderr(), EndsWith("ERROR: test message\n"));
}
TEST(LogTests, print_simpleString_outputIsValid)
{
CaptureStdout();
Log log(false);
log.print(nullptr, 0, LEVEL_PRINT "test message");
EXPECT_THAT(GetCapturedStdout(), EndsWith("test message\n"));
}
TEST(LogTests, print_withArgs_outputIsValid)
{
CaptureStdout();
Log log(false);
log.print(nullptr, 0, LEVEL_INFO "test %d %.2f %s", 1, 1.234, "test arg");
EXPECT_THAT(GetCapturedStdout(), HasSubstr("INFO: test 1 1.23 test arg\n"));
}
TEST(LogTests, print_withPrintLevel_outputIsValid)
{
CaptureStdout();
Log log(false);
log.print(nullptr, 0, LEVEL_PRINT "test message");
EXPECT_THAT(GetCapturedStdout(), "test message\n");
}
TEST(LogTests, print_longMessage_outputIsValid)
{
CaptureStdout();
Log log(false);
auto longString = std::string(10000, 'a');
log.print(nullptr, 0, LEVEL_INFO "%s", longString.c_str());
EXPECT_THAT(GetCapturedStdout(), HasSubstr("INFO: " + longString + "\n"));
}
TEST(LogTests, print_highestLevel_noOutput)
{
CaptureStdout();
Log log(false);
log.print(CLOG_DEBUG5 "test message");
EXPECT_EQ(GetCapturedStdout(), "");
}
TEST(LogTests, print_infoWithFileAndLine_outputIsValid)
{
CaptureStdout();
Log log(false);
log.print("test file", 123, LEVEL_INFO "test message");
EXPECT_THAT(GetCapturedStdout(), EndsWith("INFO: test message\n\ttest file:123\n"));
}
TEST(LogTests, print_errorWithFileAndLine_outputIsValid)
{
CaptureStderr();
Log log(false);
log.print("test file", 123, LEVEL_ERR "test message");
EXPECT_THAT(GetCapturedStderr(), EndsWith("ERROR: test message\n\ttest file:123\n"));
}
| 2,220
|
C++
|
.cpp
| 70
| 29.385714
| 87
| 0.74423
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,736
|
UnicodeTests.cpp
|
deskflow_deskflow/src/test/unittests/base/UnicodeTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2014-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "arch/IArchString.h"
#include "base/Unicode.h"
#include <gtest/gtest.h>
TEST(UnicodeTests, doUTF32ToUTF8_will_convert_simple_string)
{
bool errors;
auto result = Unicode::UTF32ToUTF8(String("h\0\0\0e\0\0\0l\0\0\0l\0\0\0o\0\0\0", 20), &errors);
EXPECT_FALSE(errors);
EXPECT_STREQ(result.c_str(), "hello");
}
TEST(UnicodeTests, doUTF16ToUTF8_will_convert_simple_string)
{
bool errors;
auto result = Unicode::UTF16ToUTF8(String("h\0e\0l\0l\0o\0", 10), &errors);
EXPECT_FALSE(errors);
EXPECT_STREQ(result.c_str(), "hello");
}
TEST(UnicodeTests, doUCS2ToUTF8_will_convert_simple_string_kUCS2)
{
bool errors;
auto result = Unicode::textToUTF8("hello", &errors, IArchString::kUCS2);
EXPECT_FALSE(errors);
#ifdef _WIN32
EXPECT_EQ(result, String("hello", 5)); // mixed-platform expected result
#else
EXPECT_EQ(result, String("h\0e\0l", 5)); // mixed-platform expected result
#endif // _WIN32
}
TEST(UnicodeTests, doUCS2ToUTF8_will_convert_simple_string_any_platform)
{
bool errors;
auto result = Unicode::textToUTF8("hello", &errors);
EXPECT_FALSE(errors);
EXPECT_EQ(result, String("hello", 5)); // mixed-platform expected result
}
| 1,863
|
C++
|
.cpp
| 51
| 34.45098
| 97
| 0.744186
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,737
|
StringTests.cpp
|
deskflow_deskflow/src/test/unittests/base/StringTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2014-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "base/String.h"
#include <gtest/gtest.h>
using namespace deskflow;
TEST(StringTests, format_formatWithArguments_formatedString)
{
const char *format = "%%%{1}=%{2}";
const char *arg1 = "answer";
const char *arg2 = "42";
String result = string::format(format, arg1, arg2);
EXPECT_EQ("%answer=42", result);
}
TEST(StringTests, findReplaceAll_inputString_replacedString)
{
String subject = "foobar";
String find = "bar";
String replace = "baz";
string::findReplaceAll(subject, find, replace);
EXPECT_EQ("foobaz", subject);
}
TEST(StringTests, sprintf_formatWithArgument_formatedString)
{
const char *format = "%s=%d";
const char *arg1 = "answer";
int arg2 = 42;
String result = string::sprintf(format, arg1, arg2);
EXPECT_EQ("answer=42", result);
}
TEST(StringTests, toHex_plaintext_hexString)
{
String subject = "foobar";
int width = 2;
string::toHex(subject, width);
EXPECT_EQ("666f6f626172", subject);
}
TEST(StringTests, uppercase_lowercaseInput_uppercaseOutput)
{
String subject = "12foo3BaR";
string::uppercase(subject);
EXPECT_EQ("12FOO3BAR", subject);
}
TEST(StringTests, removeChar_inputString_removeAllSpecifiedCharactors)
{
String subject = "foobar";
const char c = 'o';
string::removeChar(subject, c);
EXPECT_EQ("fbar", subject);
}
TEST(StringTests, intToString_inputInt_outputString)
{
size_t value = 123;
String number = string::sizeTypeToString(value);
EXPECT_EQ("123", number);
}
TEST(StringTests, stringToUint_inputString_outputInt)
{
String number = "123";
size_t value = string::stringToSizeType(number);
EXPECT_EQ(123, value);
}
TEST(StringTests, splitString_twoSeparator_returnThreeParts)
{
String string = "stub1:stub2:stub3";
std::vector<String> results = string::splitString(string, ':');
EXPECT_EQ(3, results.size());
EXPECT_EQ("stub1", results[0]);
EXPECT_EQ("stub2", results[1]);
EXPECT_EQ("stub3", results[2]);
}
TEST(StringTests, splitString_oneSeparator_returnTwoParts)
{
String string = "stub1:stub2";
std::vector<String> results = string::splitString(string, ':');
EXPECT_EQ(2, results.size());
EXPECT_EQ("stub1", results[0]);
EXPECT_EQ("stub2", results[1]);
}
TEST(StringTests, splitString_noSeparator_returnOriginalString)
{
String string = "stub1";
std::vector<String> results = string::splitString(string, ':');
EXPECT_EQ(1, results.size());
EXPECT_EQ("stub1", results[0]);
}
TEST(StringTests, splitString_emptyString_returnEmptyVector)
{
String string;
std::vector<String> results = string::splitString(string, ':');
EXPECT_EQ(0, results.size());
}
TEST(StringTests, splitString_tailSeparator_returnTwoParts)
{
String string = "stub1:stub2:";
std::vector<String> results = string::splitString(string, ':');
EXPECT_EQ(2, results.size());
EXPECT_EQ("stub1", results[0]);
EXPECT_EQ("stub2", results[1]);
}
TEST(StringTests, splitString_headSeparator_returnTwoParts)
{
String string = ":stub1:stub2";
std::vector<String> results = string::splitString(string, ':');
EXPECT_EQ(2, results.size());
EXPECT_EQ("stub1", results[0]);
EXPECT_EQ("stub2", results[1]);
}
TEST(StringTests, splitString_headAndTailSeparators_returnTwoParts)
{
String string = ":stub1:stub2:";
std::vector<String> results = string::splitString(string, ':');
EXPECT_EQ(2, results.size());
EXPECT_EQ("stub1", results[0]);
EXPECT_EQ("stub2", results[1]);
}
| 4,132
|
C++
|
.cpp
| 129
| 29.534884
| 72
| 0.732491
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,738
|
HelloBackTests.cpp
|
deskflow_deskflow/src/test/unittests/client/HelloBackTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
*
* SPDX-FileCopyrightText: Copyright (C) 2024 Symless Ltd.
* SPDX-License-Identifier: GPL-2.0
*/
#include "client/HelloBack.h"
#include "common/basic_types.h"
#include "mock/io/MockStream.h"
#include <array>
#include <cstring>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <iomanip>
#include <sstream>
using HelloBack = deskflow::client::HelloBack;
using namespace testing;
namespace {
class MockDeps : public HelloBack::Deps
{
public:
~MockDeps() override = default;
MOCK_METHOD(void, invalidHello, (), (override));
MOCK_METHOD(void, incompatible, (int major, int minor), (override));
};
void intTo2ByteBuf(SInt16 value, std::array<char, 2> &buf)
{
buf[0] = static_cast<char>((value >> 8) & 0xFF); // MSB
buf[1] = static_cast<char>(value & 0xFF); // LSB
}
void intTo4ByteBuf(SInt32 value, std::array<char, 4> &buf)
{
buf[0] = static_cast<char>((value >> 24) & 0xFF); // MSB
buf[1] = static_cast<char>((value >> 16) & 0xFF);
buf[2] = static_cast<char>((value >> 8) & 0xFF);
buf[3] = static_cast<char>(value & 0xFF); // LSB
}
std::string printAsHex(const char *buffer, size_t size)
{
std::ostringstream hexStream;
for (size_t i = 0; i < size; ++i) {
hexStream << std::hex << std::setw(2) << std::setfill('0')
<< static_cast<int>(static_cast<unsigned char>(buffer[i])) << " ";
}
return hexStream.str();
}
void setupMockHelloRead(
MockStream &stream, const std::string &protocolName, const SInt16 majorVersion, const SInt16 minorVersion
)
{
std::array<char, 2> majorBuf;
std::array<char, 2> minorBuf;
intTo2ByteBuf(majorVersion, majorBuf);
intTo2ByteBuf(minorVersion, minorBuf);
EXPECT_CALL(stream, read(_, _))
.WillOnce(DoAll(
WithArg<0>([protocolName](void *vbuffer) {
auto buffer = static_cast<char *>(vbuffer);
std::copy(protocolName.begin(), protocolName.end(), buffer);
}),
Return(7)
))
.WillOnce(DoAll(
WithArg<0>([majorBuf](void *vbuffer) {
auto buffer = static_cast<char *>(vbuffer);
std::memcpy(buffer, majorBuf.data(), majorBuf.size());
}),
Return(2)
))
.WillOnce(DoAll(
WithArg<0>([minorBuf](void *vbuffer) {
auto buffer = static_cast<char *>(vbuffer);
std::memcpy(buffer, minorBuf.data(), minorBuf.size());
}),
Return(2)
));
}
void setupMockHelloBackWrite(
MockStream &stream, const std::string &protocolName, const SInt16 majorVersion, const SInt16 minorVersion,
const std::string &name
)
{
std::array<char, 2> majorBuf;
std::array<char, 2> minorBuf;
std::array<char, 4> nameLenBuf;
intTo2ByteBuf(majorVersion, majorBuf);
intTo2ByteBuf(minorVersion, minorBuf);
intTo4ByteBuf(static_cast<SInt32>(name.size()), nameLenBuf);
const auto versionIntSize = 4;
const auto clientNameIntSize = 4;
const UInt32 helloBackSize =
static_cast<UInt32>(protocolName.size() + versionIntSize + clientNameIntSize + name.size());
std::vector<char> expect;
expect.reserve(helloBackSize);
expect.insert(expect.end(), protocolName.begin(), protocolName.end());
expect.insert(expect.end(), majorBuf.begin(), majorBuf.end());
expect.insert(expect.end(), minorBuf.begin(), minorBuf.end());
expect.insert(expect.end(), nameLenBuf.begin(), nameLenBuf.end());
expect.insert(expect.end(), name.begin(), name.end());
EXPECT_CALL(stream, write(_, helloBackSize)).WillOnce(WithArg<0>([expect, helloBackSize](const void *vbuffer) {
const auto buffer = static_cast<const char *>(vbuffer);
EXPECT_TRUE(std::memcmp(expect.data(), buffer, helloBackSize) == 0)
<< "Buffer mismatch\n"
<< "Expected: " << printAsHex(expect.data(), helloBackSize) << "\n"
<< "Actual: " << printAsHex(buffer, helloBackSize) << "\n";
}));
}
} // namespace
TEST(HelloBackTests, handleHello_nastyProtocol_invalidHello)
{
auto deps = std::make_shared<NiceMock<MockDeps>>();
HelloBack helloBack(deps);
NiceMock<MockStream> stream;
const std::string clientName = "stub";
setupMockHelloRead(stream, "ShareMouse", 0, 0);
EXPECT_CALL(*deps, invalidHello()).Times(1);
helloBack.handleHello(&stream, clientName);
}
TEST(HelloBackTests, handleHello_synergyProtocolCurrent_validMessage)
{
auto deps = std::make_shared<NiceMock<MockDeps>>();
HelloBack helloBack(deps, 1, 2);
NiceMock<MockStream> stream;
const std::string clientName = "stub";
setupMockHelloRead(stream, "Synergy", 1, 2);
EXPECT_CALL(*deps, incompatible(_, _)).Times(0);
EXPECT_CALL(*deps, invalidHello()).Times(0);
helloBack.handleHello(&stream, clientName);
}
TEST(HelloBackTests, handleHello_barrierProtocolCurrent_validMessage)
{
auto deps = std::make_shared<NiceMock<MockDeps>>();
HelloBack helloBack(deps, 1, 2);
NiceMock<MockStream> stream;
const std::string clientName = "stub";
setupMockHelloRead(stream, "Barrier", 1, 2);
EXPECT_CALL(*deps, incompatible(_, _)).Times(0);
EXPECT_CALL(*deps, invalidHello()).Times(0);
helloBack.handleHello(&stream, clientName);
}
TEST(HelloBackTests, handleHello_synergyProtocolOlder_validMessage)
{
auto deps = std::make_shared<NiceMock<MockDeps>>();
HelloBack helloBack(deps, 1, 2);
NiceMock<MockStream> stream;
const std::string clientName = "stub";
setupMockHelloRead(stream, "Synergy", 1, 1);
EXPECT_CALL(*deps, incompatible(1, 1)).Times(1);
helloBack.handleHello(&stream, clientName);
}
TEST(HelloBackTests, handleHello_synergyProtocolCurrent_wroteHelloBack)
{
auto deps = std::make_shared<NiceMock<MockDeps>>();
HelloBack helloBack(deps, 1, 2);
NiceMock<MockStream> stream;
const std::string clientName = "test client";
setupMockHelloRead(stream, "Synergy", 1, 2);
setupMockHelloBackWrite(stream, "Synergy", 1, 2, "test client");
helloBack.handleHello(&stream, clientName);
}
TEST(HelloBackTests, handleHello_barrierProtocolCurrent_wroteHelloBack)
{
auto deps = std::make_shared<NiceMock<MockDeps>>();
HelloBack helloBack(deps, 1, 2);
NiceMock<MockStream> stream;
const std::string clientName = "test client";
setupMockHelloRead(stream, "Barrier", 1, 2);
setupMockHelloBackWrite(stream, "Barrier", 1, 2, "test client");
helloBack.handleHello(&stream, clientName);
}
// If the client is protocol version 1.8 and the server is 1.6, the client
// should downgrade and respond with the server version.
TEST(HelloBackTests, handleHello_synergyProtocolCompat_wroteHelloBack)
{
auto deps = std::make_shared<NiceMock<MockDeps>>();
HelloBack helloBack(deps, 1, 8);
NiceMock<MockStream> stream;
const std::string clientName = "test client";
setupMockHelloRead(stream, "Synergy", 1, 6);
setupMockHelloBackWrite(stream, "Synergy", 1, 6, "test client");
helloBack.handleHello(&stream, clientName);
}
| 6,905
|
C++
|
.cpp
| 182
| 34.236264
| 113
| 0.704164
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,739
|
TestEventQueue.cpp
|
deskflow_deskflow/src/test/shared/TestEventQueue.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2013-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "test/shared/TestEventQueue.h"
#include "base/TMethodEventJob.h"
#include "common/stdexcept.h"
void TestEventQueue::raiseQuitEvent()
{
addEvent(Event(Event::kQuit));
}
void TestEventQueue::initQuitTimeout(double timeout)
{
assert(m_pQuitTimeoutTimer == nullptr);
m_pQuitTimeoutTimer = newOneShotTimer(timeout, NULL);
adoptHandler(
Event::kTimer, m_pQuitTimeoutTimer, new TMethodEventJob<TestEventQueue>(this, &TestEventQueue::handleQuitTimeout)
);
}
void TestEventQueue::cleanupQuitTimeout()
{
removeHandler(Event::kTimer, m_pQuitTimeoutTimer);
deleteTimer(m_pQuitTimeoutTimer);
m_pQuitTimeoutTimer = nullptr;
}
void TestEventQueue::handleQuitTimeout(const Event &, void *vclient)
{
throw std::runtime_error("test event queue timeout");
}
| 1,469
|
C++
|
.cpp
| 41
| 33.731707
| 119
| 0.779184
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,740
|
ExitTimeout.cpp
|
deskflow_deskflow/src/test/shared/ExitTimeout.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "ExitTimeout.h"
#include <chrono>
#include <iostream>
#include <memory>
#include <string_view>
#include <thread>
namespace deskflow::test {
const auto checkMilliseconds = std::chrono::milliseconds(100);
using std::chrono::duration_cast;
using std::chrono::steady_clock;
bool timeoutReached(const steady_clock::time_point &start, const int minutes)
{
auto now = steady_clock::now();
auto duration = duration_cast<std::chrono::minutes>(now - start);
return duration.count() >= minutes;
}
ExitTimeout::ExitTimeout(const int minutes, const std::string_view &name)
: m_minutes(minutes),
m_name(name),
m_thread(std::make_unique<std::thread>([this]() { run(); }))
{
}
ExitTimeout::~ExitTimeout()
{
m_running = false;
m_thread->join();
}
void ExitTimeout::run() const
{
auto start = steady_clock::now();
while (m_running) {
std::this_thread::sleep_for(checkMilliseconds);
if (timeoutReached(start, m_minutes)) {
std::cerr << m_name << " timed out after " << m_minutes << " minute(s)" << std::endl;
std::exit(EXIT_FAILURE);
}
}
}
} // namespace deskflow::test
| 1,812
|
C++
|
.cpp
| 55
| 30.472727
| 91
| 0.718947
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,741
|
deskflow-core.cpp
|
deskflow_deskflow/src/cmd/deskflow-core/deskflow-core.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2022 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "arch/Arch.h"
#include "base/EventQueue.h"
#include "base/Log.h"
#include "deskflow/ClientApp.h"
#include "deskflow/ServerApp.h"
#include <iostream>
#if SYSAPI_WIN32
#include "arch/win32/ArchMiscWindows.h"
#endif
void showHelp()
{
std::cout << "Usage: " CORE_BINARY_NAME " <server | client> [...options]" << std::endl;
std::cout << "server - start as a server ( deskflow-server)" << std::endl;
std::cout << "client - start as a client ( deslflow-client)" << std::endl;
std::cout << "use deskflow-core <server|client> --help for more information." << std::endl;
}
bool isServer(int argc, char **argv)
{
return (argc > 1 && argv[1] == std::string("server"));
}
bool isClient(int argc, char **argv)
{
return (argc > 1 && argv[1] == std::string("client"));
}
int main(int argc, char **argv)
{
#if SYSAPI_WIN32
ArchMiscWindows::setInstanceWin32(GetModuleHandle(NULL));
#endif
Arch arch;
arch.init();
Log log;
EventQueue events;
if (isServer(argc, argv)) {
ServerApp app(&events, nullptr);
return app.run(argc, argv);
} else if (isClient(argc, argv)) {
ClientApp app(&events, nullptr);
return app.run(argc, argv);
} else {
showHelp();
}
return 0;
}
| 1,943
|
C++
|
.cpp
| 61
| 29.590164
| 93
| 0.707955
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,742
|
deskflows.cpp
|
deskflow_deskflow/src/cmd/deskflows/deskflows.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "arch/Arch.h"
#include "base/EventQueue.h"
#include "base/Log.h"
#include "deskflow/ServerApp.h"
#if SYSAPI_WIN32
#include "arch/win32/ArchMiscWindows.h"
#endif
#if WINAPI_MSWINDOWS
#include "MSWindowsServerTaskBarReceiver.h"
#elif WINAPI_XWINDOWS
#include "XWindowsServerTaskBarReceiver.h"
#elif WINAPI_CARBON
#include "OSXServerTaskBarReceiver.h"
#else
#error Platform not supported.
#endif
int main(int argc, char **argv)
{
#if SYSAPI_WIN32
// record window instance for tray icon, etc
ArchMiscWindows::setInstanceWin32(GetModuleHandle(NULL));
#endif
Arch arch;
arch.init();
Log log;
EventQueue events;
ServerApp app(&events, createTaskBarReceiver);
return app.run(argc, argv);
}
| 1,445
|
C++
|
.cpp
| 46
| 29.565217
| 72
| 0.778017
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,743
|
XWindowsServerTaskBarReceiver.cpp
|
deskflow_deskflow/src/cmd/deskflows/XWindowsServerTaskBarReceiver.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2003 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "XWindowsServerTaskBarReceiver.h"
#include "arch/Arch.h"
//
// CXWindowsServerTaskBarReceiver
//
CXWindowsServerTaskBarReceiver::CXWindowsServerTaskBarReceiver(const BufferedLogOutputter *, IEventQueue *events)
: ServerTaskBarReceiver(events)
{
// add ourself to the task bar
ARCH->addReceiver(this);
}
CXWindowsServerTaskBarReceiver::~CXWindowsServerTaskBarReceiver()
{
ARCH->removeReceiver(this);
}
void CXWindowsServerTaskBarReceiver::showStatus()
{
// do nothing
}
void CXWindowsServerTaskBarReceiver::runMenu(int, int)
{
// do nothing
}
void CXWindowsServerTaskBarReceiver::primaryAction()
{
// do nothing
}
const IArchTaskBarReceiver::Icon CXWindowsServerTaskBarReceiver::getIcon() const
{
return NULL;
}
IArchTaskBarReceiver *createTaskBarReceiver(const BufferedLogOutputter *logBuffer, IEventQueue *events)
{
return new CXWindowsServerTaskBarReceiver(logBuffer, events);
}
| 1,649
|
C++
|
.cpp
| 52
| 29.846154
| 113
| 0.799118
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| true
| false
| false
| true
| false
| false
|
13,744
|
MSWindowsServerTaskBarReceiver.cpp
|
deskflow_deskflow/src/cmd/deskflows/MSWindowsServerTaskBarReceiver.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2003 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "MSWindowsServerTaskBarReceiver.h"
#include "arch/Arch.h"
#include "arch/win32/ArchMiscWindows.h"
#include "arch/win32/ArchTaskBarWindows.h"
#include "base/EventQueue.h"
#include "base/EventTypes.h"
#include "base/IEventQueue.h"
#include "base/log_outputters.h"
#include "platform/MSWindowsClipboard.h"
#include "platform/MSWindowsScreen.h"
#include "resource.h"
#include "server/Server.h"
//
// MSWindowsServerTaskBarReceiver
//
const UINT MSWindowsServerTaskBarReceiver::s_stateToIconID[kMaxState] = {
IDI_TASKBAR_NOT_RUNNING, IDI_TASKBAR_NOT_WORKING, IDI_TASKBAR_NOT_CONNECTED, IDI_TASKBAR_CONNECTED
};
MSWindowsServerTaskBarReceiver::MSWindowsServerTaskBarReceiver(
HINSTANCE appInstance, const BufferedLogOutputter *logBuffer, IEventQueue *events
)
: ServerTaskBarReceiver(events),
m_events(events),
m_appInstance(appInstance),
m_window(NULL),
m_logBuffer(logBuffer)
{
for (UInt32 i = 0; i < kMaxState; ++i) {
m_icon[i] = loadIcon(s_stateToIconID[i]);
}
m_menu = LoadMenu(m_appInstance, MAKEINTRESOURCE(IDR_TASKBAR));
// don't create the window yet. we'll create it on demand. this
// has the side benefit of being created in the thread used for
// the task bar. that's good because it means the existence of
// the window won't prevent changing the main thread's desktop.
// add ourself to the task bar
ARCH->addReceiver(this);
}
void MSWindowsServerTaskBarReceiver::cleanup()
{
ARCH->removeReceiver(this);
for (UInt32 i = 0; i < kMaxState; ++i) {
deleteIcon(m_icon[i]);
}
DestroyMenu(m_menu);
destroyWindow();
}
MSWindowsServerTaskBarReceiver::~MSWindowsServerTaskBarReceiver()
{
cleanup();
}
void MSWindowsServerTaskBarReceiver::showStatus()
{
// create the window
createWindow();
// lock self while getting status
lock();
// get the current status
std::string status = getToolTip();
// get the connect clients, if any
const Clients &clients = getClients();
// done getting status
unlock();
// update dialog
HWND child = GetDlgItem(m_window, IDC_TASKBAR_STATUS_STATUS);
SendMessage(child, WM_SETTEXT, 0, (LPARAM)status.c_str());
child = GetDlgItem(m_window, IDC_TASKBAR_STATUS_CLIENTS);
SendMessage(child, LB_RESETCONTENT, 0, 0);
for (Clients::const_iterator index = clients.begin(); index != clients.end();) {
const char *client = index->c_str();
if (++index == clients.end()) {
SendMessage(child, LB_ADDSTRING, 0, (LPARAM)client);
} else {
SendMessage(child, LB_INSERTSTRING, (WPARAM)-1, (LPARAM)client);
}
}
if (!IsWindowVisible(m_window)) {
// position it by the mouse
POINT cursorPos;
GetCursorPos(&cursorPos);
RECT windowRect;
GetWindowRect(m_window, &windowRect);
int x = cursorPos.x;
int y = cursorPos.y;
int fw = GetSystemMetrics(SM_CXDLGFRAME);
int fh = GetSystemMetrics(SM_CYDLGFRAME);
int ww = windowRect.right - windowRect.left;
int wh = windowRect.bottom - windowRect.top;
int sw = GetSystemMetrics(SM_CXFULLSCREEN);
int sh = GetSystemMetrics(SM_CYFULLSCREEN);
if (fw < 1) {
fw = 1;
}
if (fh < 1) {
fh = 1;
}
if (x + ww - fw > sw) {
x -= ww - fw;
} else {
x -= fw;
}
if (x < 0) {
x = 0;
}
if (y + wh - fh > sh) {
y -= wh - fh;
} else {
y -= fh;
}
if (y < 0) {
y = 0;
}
SetWindowPos(m_window, HWND_TOPMOST, x, y, ww, wh, SWP_SHOWWINDOW);
}
}
void MSWindowsServerTaskBarReceiver::runMenu(int x, int y)
{
// do popup menu. we need a window to pass to TrackPopupMenu().
// the SetForegroundWindow() and SendMessage() calls around
// TrackPopupMenu() are to get the menu to be dismissed when
// another window gets activated and are just one of those
// win32 weirdnesses.
createWindow();
SetForegroundWindow(m_window);
HMENU menu = GetSubMenu(m_menu, 0);
SetMenuDefaultItem(menu, IDC_TASKBAR_STATUS, FALSE);
HMENU logLevelMenu = GetSubMenu(menu, 3);
CheckMenuRadioItem(logLevelMenu, 0, 6, CLOG->getFilter() - kERROR, MF_BYPOSITION);
int n =
TrackPopupMenu(menu, TPM_NONOTIFY | TPM_RETURNCMD | TPM_LEFTBUTTON | TPM_RIGHTBUTTON, x, y, 0, m_window, NULL);
SendMessage(m_window, WM_NULL, 0, 0);
// perform the requested operation
switch (n) {
case IDC_TASKBAR_STATUS:
showStatus();
break;
case IDC_TASKBAR_LOG:
copyLog();
break;
case IDC_TASKBAR_SHOW_LOG:
ARCH->showConsole(true);
break;
case IDC_RELOAD_CONFIG:
m_events->addEvent(Event(m_events->forServerApp().reloadConfig(), m_events->getSystemTarget()));
break;
case IDC_FORCE_RECONNECT:
m_events->addEvent(Event(m_events->forServerApp().forceReconnect(), m_events->getSystemTarget()));
break;
case ID_DESKFLOW_RESETSERVER:
m_events->addEvent(Event(m_events->forServerApp().resetServer(), m_events->getSystemTarget()));
break;
case IDC_TASKBAR_LOG_LEVEL_ERROR:
CLOG->setFilter(kERROR);
break;
case IDC_TASKBAR_LOG_LEVEL_WARNING:
CLOG->setFilter(kWARNING);
break;
case IDC_TASKBAR_LOG_LEVEL_NOTE:
CLOG->setFilter(kNOTE);
break;
case IDC_TASKBAR_LOG_LEVEL_INFO:
CLOG->setFilter(kINFO);
break;
case IDC_TASKBAR_LOG_LEVEL_DEBUG:
CLOG->setFilter(kDEBUG);
break;
case IDC_TASKBAR_LOG_LEVEL_DEBUG1:
CLOG->setFilter(kDEBUG1);
break;
case IDC_TASKBAR_LOG_LEVEL_DEBUG2:
CLOG->setFilter(kDEBUG2);
break;
case IDC_TASKBAR_QUIT:
quit();
break;
}
}
void MSWindowsServerTaskBarReceiver::primaryAction()
{
showStatus();
}
const IArchTaskBarReceiver::Icon MSWindowsServerTaskBarReceiver::getIcon() const
{
return static_cast<Icon>(m_icon[getStatus()]);
}
void MSWindowsServerTaskBarReceiver::copyLog() const
{
if (m_logBuffer != NULL) {
// collect log buffer
String data;
for (BufferedLogOutputter::const_iterator index = m_logBuffer->begin(); index != m_logBuffer->end(); ++index) {
data += *index;
data += "\n";
}
// copy log to clipboard
if (!data.empty()) {
MSWindowsClipboard clipboard(m_window);
clipboard.open(0);
clipboard.emptyUnowned();
clipboard.add(IClipboard::kText, data);
clipboard.close();
}
}
}
void MSWindowsServerTaskBarReceiver::onStatusChanged()
{
if (IsWindowVisible(m_window)) {
showStatus();
}
}
HICON
MSWindowsServerTaskBarReceiver::loadIcon(UINT id)
{
HANDLE icon = LoadImage(m_appInstance, MAKEINTRESOURCE(id), IMAGE_ICON, 0, 0, LR_DEFAULTCOLOR);
return static_cast<HICON>(icon);
}
void MSWindowsServerTaskBarReceiver::deleteIcon(HICON icon)
{
if (icon != NULL) {
DestroyIcon(icon);
}
}
void MSWindowsServerTaskBarReceiver::createWindow()
{
// ignore if already created
if (m_window != NULL) {
return;
}
// get the status dialog
m_window = CreateDialogParam(
m_appInstance, MAKEINTRESOURCE(IDD_TASKBAR_STATUS), NULL, (DLGPROC)&MSWindowsServerTaskBarReceiver::staticDlgProc,
reinterpret_cast<LPARAM>(static_cast<void *>(this))
);
// window should appear on top of everything, including (especially)
// the task bar.
LONG_PTR style = GetWindowLongPtr(m_window, GWL_EXSTYLE);
style |= WS_EX_TOOLWINDOW | WS_EX_TOPMOST;
SetWindowLongPtr(m_window, GWL_EXSTYLE, style);
// tell the task bar about this dialog
ArchTaskBarWindows::addDialog(m_window);
}
void MSWindowsServerTaskBarReceiver::destroyWindow()
{
if (m_window != NULL) {
ArchTaskBarWindows::removeDialog(m_window);
DestroyWindow(m_window);
m_window = NULL;
}
}
BOOL MSWindowsServerTaskBarReceiver::dlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM)
{
switch (msg) {
case WM_INITDIALOG:
// use default focus
return TRUE;
case WM_ACTIVATE:
// hide when another window is activated
if (LOWORD(wParam) == WA_INACTIVE) {
ShowWindow(hwnd, SW_HIDE);
}
break;
}
return FALSE;
}
BOOL CALLBACK MSWindowsServerTaskBarReceiver::staticDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
// if msg is WM_INITDIALOG, extract the MSWindowsServerTaskBarReceiver*
// and put it in the extra window data then forward the call.
MSWindowsServerTaskBarReceiver *self = NULL;
if (msg == WM_INITDIALOG) {
self = static_cast<MSWindowsServerTaskBarReceiver *>(reinterpret_cast<void *>(lParam));
SetWindowLongPtr(hwnd, GWLP_USERDATA, lParam);
} else {
// get the extra window data and forward the call
LONG_PTR data = GetWindowLongPtr(hwnd, GWLP_USERDATA);
if (data != 0) {
self = static_cast<MSWindowsServerTaskBarReceiver *>(reinterpret_cast<void *>(data));
}
}
// forward the message
if (self != NULL) {
return self->dlgProc(hwnd, msg, wParam, lParam);
} else {
return (msg == WM_INITDIALOG) ? TRUE : FALSE;
}
}
IArchTaskBarReceiver *createTaskBarReceiver(const BufferedLogOutputter *logBuffer, IEventQueue *events)
{
ArchMiscWindows::setIcons(
(HICON)LoadImage(ArchMiscWindows::instanceWin32(), MAKEINTRESOURCE(IDI_DESKFLOW), IMAGE_ICON, 32, 32, LR_SHARED),
(HICON)LoadImage(ArchMiscWindows::instanceWin32(), MAKEINTRESOURCE(IDI_DESKFLOW), IMAGE_ICON, 16, 16, LR_SHARED)
);
return new MSWindowsServerTaskBarReceiver(MSWindowsScreen::getWindowInstance(), logBuffer, events);
}
| 10,037
|
C++
|
.cpp
| 311
| 28.652733
| 120
| 0.712514
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
13,745
|
OSXServerTaskBarReceiver.cpp
|
deskflow_deskflow/src/cmd/deskflows/OSXServerTaskBarReceiver.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2004 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "OSXServerTaskBarReceiver.h"
#include "arch/Arch.h"
//
// OSXServerTaskBarReceiver
//
OSXServerTaskBarReceiver::OSXServerTaskBarReceiver(const BufferedLogOutputter *, IEventQueue *events)
: ServerTaskBarReceiver(events)
{
// add ourself to the task bar
ARCH->addReceiver(this);
}
OSXServerTaskBarReceiver::~OSXServerTaskBarReceiver()
{
ARCH->removeReceiver(this);
}
void OSXServerTaskBarReceiver::showStatus()
{
// do nothing
}
void OSXServerTaskBarReceiver::runMenu(int, int)
{
// do nothing
}
void OSXServerTaskBarReceiver::primaryAction()
{
// do nothing
}
const IArchTaskBarReceiver::Icon OSXServerTaskBarReceiver::getIcon() const
{
return NULL;
}
IArchTaskBarReceiver *createTaskBarReceiver(const BufferedLogOutputter *logBuffer, IEventQueue *events)
{
return new OSXServerTaskBarReceiver(logBuffer, events);
}
| 1,584
|
C++
|
.cpp
| 52
| 28.596154
| 103
| 0.790545
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| true
| false
| false
| true
| false
| false
|
13,746
|
deskflowd.cpp
|
deskflow_deskflow/src/cmd/deskflowd/deskflowd.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2012 Nick Bolton
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "deskflow/DaemonApp.h"
#include <iostream>
#ifdef SYSAPI_UNIX
int main(int argc, char **argv)
{
DaemonApp app;
return app.run(argc, argv);
}
#elif SYSAPI_WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
DaemonApp app;
return app.run(__argc, __argv);
}
#endif
| 1,070
|
C++
|
.cpp
| 34
| 29.529412
| 72
| 0.755837
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,747
|
OSXClientTaskBarReceiver.cpp
|
deskflow_deskflow/src/cmd/deskflowc/OSXClientTaskBarReceiver.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2004 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "OSXClientTaskBarReceiver.h"
#include "arch/Arch.h"
//
// OSXClientTaskBarReceiver
//
OSXClientTaskBarReceiver::OSXClientTaskBarReceiver(const BufferedLogOutputter *, IEventQueue *events)
: ClientTaskBarReceiver(events)
{
// add ourself to the task bar
ARCH->addReceiver(this);
}
OSXClientTaskBarReceiver::~OSXClientTaskBarReceiver()
{
ARCH->removeReceiver(this);
}
void OSXClientTaskBarReceiver::showStatus()
{
// do nothing
}
void OSXClientTaskBarReceiver::runMenu(int, int)
{
// do nothing
}
void OSXClientTaskBarReceiver::primaryAction()
{
// do nothing
}
const IArchTaskBarReceiver::Icon OSXClientTaskBarReceiver::getIcon() const
{
return NULL;
}
IArchTaskBarReceiver *createTaskBarReceiver(const BufferedLogOutputter *logBuffer, IEventQueue *events)
{
return new OSXClientTaskBarReceiver(logBuffer, events);
}
| 1,584
|
C++
|
.cpp
| 52
| 28.596154
| 103
| 0.790545
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| true
| false
| false
| true
| false
| false
|
13,748
|
XWindowsClientTaskBarReceiver.cpp
|
deskflow_deskflow/src/cmd/deskflowc/XWindowsClientTaskBarReceiver.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2003 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "XWindowsClientTaskBarReceiver.h"
#include "arch/Arch.h"
//
// CXWindowsClientTaskBarReceiver
//
CXWindowsClientTaskBarReceiver::CXWindowsClientTaskBarReceiver(const BufferedLogOutputter *, IEventQueue *events)
: ClientTaskBarReceiver(events)
{
// add ourself to the task bar
ARCH->addReceiver(this);
}
CXWindowsClientTaskBarReceiver::~CXWindowsClientTaskBarReceiver()
{
ARCH->removeReceiver(this);
}
void CXWindowsClientTaskBarReceiver::showStatus()
{
// do nothing
}
void CXWindowsClientTaskBarReceiver::runMenu(int, int)
{
// do nothing
}
void CXWindowsClientTaskBarReceiver::primaryAction()
{
// do nothing
}
const IArchTaskBarReceiver::Icon CXWindowsClientTaskBarReceiver::getIcon() const
{
return NULL;
}
IArchTaskBarReceiver *createTaskBarReceiver(const BufferedLogOutputter *logBuffer, IEventQueue *events)
{
return new CXWindowsClientTaskBarReceiver(logBuffer, events);
}
| 1,649
|
C++
|
.cpp
| 52
| 29.846154
| 113
| 0.799118
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| true
| false
| false
| true
| false
| false
|
13,749
|
deskflowc.cpp
|
deskflow_deskflow/src/cmd/deskflowc/deskflowc.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "arch/Arch.h"
#include "base/EventQueue.h"
#include "base/Log.h"
#include "deskflow/ClientApp.h"
#if SYSAPI_WIN32
#include "arch/win32/ArchMiscWindows.h"
#endif
#if WINAPI_MSWINDOWS
#include "MSWindowsClientTaskBarReceiver.h"
#elif WINAPI_XWINDOWS
#include "XWindowsClientTaskBarReceiver.h"
#elif WINAPI_CARBON
#include "OSXClientTaskBarReceiver.h"
#else
#error Platform not supported.
#endif
int main(int argc, char **argv)
{
#if SYSAPI_WIN32
// record window instance for tray icon, etc
ArchMiscWindows::setInstanceWin32(GetModuleHandle(NULL));
#endif
Arch arch;
arch.init();
Log log;
EventQueue events;
ClientApp app(&events, createTaskBarReceiver);
return app.run(argc, argv);
}
| 1,445
|
C++
|
.cpp
| 46
| 29.565217
| 72
| 0.778017
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,750
|
MSWindowsClientTaskBarReceiver.cpp
|
deskflow_deskflow/src/cmd/deskflowc/MSWindowsClientTaskBarReceiver.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2003 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "MSWindowsClientTaskBarReceiver.h"
#include "arch/Arch.h"
#include "arch/win32/ArchMiscWindows.h"
#include "arch/win32/ArchTaskBarWindows.h"
#include "base/EventQueue.h"
#include "base/EventTypes.h"
#include "base/log_outputters.h"
#include "client/Client.h"
#include "platform/MSWindowsClipboard.h"
#include "platform/MSWindowsScreen.h"
#include "resource.h"
//
// MSWindowsClientTaskBarReceiver
//
const UINT MSWindowsClientTaskBarReceiver::s_stateToIconID[kMaxState] = {
IDI_TASKBAR_NOT_RUNNING, IDI_TASKBAR_NOT_WORKING, IDI_TASKBAR_NOT_CONNECTED, IDI_TASKBAR_NOT_CONNECTED,
IDI_TASKBAR_CONNECTED
};
MSWindowsClientTaskBarReceiver::MSWindowsClientTaskBarReceiver(
HINSTANCE appInstance, const BufferedLogOutputter *logBuffer, IEventQueue *events
)
: ClientTaskBarReceiver(events),
m_appInstance(appInstance),
m_window(NULL),
m_logBuffer(logBuffer)
{
for (UInt32 i = 0; i < kMaxState; ++i) {
m_icon[i] = loadIcon(s_stateToIconID[i]);
}
m_menu = LoadMenu(m_appInstance, MAKEINTRESOURCE(IDR_TASKBAR));
// don't create the window yet. we'll create it on demand. this
// has the side benefit of being created in the thread used for
// the task bar. that's good because it means the existence of
// the window won't prevent changing the main thread's desktop.
// add ourself to the task bar
ARCH->addReceiver(this);
}
MSWindowsClientTaskBarReceiver::~MSWindowsClientTaskBarReceiver()
{
cleanup();
}
void MSWindowsClientTaskBarReceiver::cleanup()
{
ARCH->removeReceiver(this);
for (UInt32 i = 0; i < kMaxState; ++i) {
deleteIcon(m_icon[i]);
}
DestroyMenu(m_menu);
destroyWindow();
}
void MSWindowsClientTaskBarReceiver::showStatus()
{
// create the window
createWindow();
// lock self while getting status
lock();
// get the current status
std::string status = getToolTip();
// done getting status
unlock();
// update dialog
HWND child = GetDlgItem(m_window, IDC_TASKBAR_STATUS_STATUS);
SendMessage(child, WM_SETTEXT, 0, (LPARAM)status.c_str());
if (!IsWindowVisible(m_window)) {
// position it by the mouse
POINT cursorPos;
GetCursorPos(&cursorPos);
RECT windowRect;
GetWindowRect(m_window, &windowRect);
int x = cursorPos.x;
int y = cursorPos.y;
int fw = GetSystemMetrics(SM_CXDLGFRAME);
int fh = GetSystemMetrics(SM_CYDLGFRAME);
int ww = windowRect.right - windowRect.left;
int wh = windowRect.bottom - windowRect.top;
int sw = GetSystemMetrics(SM_CXFULLSCREEN);
int sh = GetSystemMetrics(SM_CYFULLSCREEN);
if (fw < 1) {
fw = 1;
}
if (fh < 1) {
fh = 1;
}
if (x + ww - fw > sw) {
x -= ww - fw;
} else {
x -= fw;
}
if (x < 0) {
x = 0;
}
if (y + wh - fh > sh) {
y -= wh - fh;
} else {
y -= fh;
}
if (y < 0) {
y = 0;
}
SetWindowPos(m_window, HWND_TOPMOST, x, y, ww, wh, SWP_SHOWWINDOW);
}
}
void MSWindowsClientTaskBarReceiver::runMenu(int x, int y)
{
// do popup menu. we need a window to pass to TrackPopupMenu().
// the SetForegroundWindow() and SendMessage() calls around
// TrackPopupMenu() are to get the menu to be dismissed when
// another window gets activated and are just one of those
// win32 weirdnesses.
createWindow();
SetForegroundWindow(m_window);
HMENU menu = GetSubMenu(m_menu, 0);
SetMenuDefaultItem(menu, IDC_TASKBAR_STATUS, FALSE);
HMENU logLevelMenu = GetSubMenu(menu, 3);
CheckMenuRadioItem(logLevelMenu, 0, 6, CLOG->getFilter() - kERROR, MF_BYPOSITION);
int n =
TrackPopupMenu(menu, TPM_NONOTIFY | TPM_RETURNCMD | TPM_LEFTBUTTON | TPM_RIGHTBUTTON, x, y, 0, m_window, NULL);
SendMessage(m_window, WM_NULL, 0, 0);
// perform the requested operation
switch (n) {
case IDC_TASKBAR_STATUS:
showStatus();
break;
case IDC_TASKBAR_LOG:
copyLog();
break;
case IDC_TASKBAR_SHOW_LOG:
ARCH->showConsole(true);
break;
case IDC_TASKBAR_LOG_LEVEL_ERROR:
CLOG->setFilter(kERROR);
break;
case IDC_TASKBAR_LOG_LEVEL_WARNING:
CLOG->setFilter(kWARNING);
break;
case IDC_TASKBAR_LOG_LEVEL_NOTE:
CLOG->setFilter(kNOTE);
break;
case IDC_TASKBAR_LOG_LEVEL_INFO:
CLOG->setFilter(kINFO);
break;
case IDC_TASKBAR_LOG_LEVEL_DEBUG:
CLOG->setFilter(kDEBUG);
break;
case IDC_TASKBAR_LOG_LEVEL_DEBUG1:
CLOG->setFilter(kDEBUG1);
break;
case IDC_TASKBAR_LOG_LEVEL_DEBUG2:
CLOG->setFilter(kDEBUG2);
break;
case IDC_TASKBAR_QUIT:
quit();
break;
}
}
void MSWindowsClientTaskBarReceiver::primaryAction()
{
showStatus();
}
const IArchTaskBarReceiver::Icon MSWindowsClientTaskBarReceiver::getIcon() const
{
return static_cast<Icon>(m_icon[getStatus()]);
}
void MSWindowsClientTaskBarReceiver::copyLog() const
{
if (m_logBuffer != NULL) {
// collect log buffer
String data;
for (BufferedLogOutputter::const_iterator index = m_logBuffer->begin(); index != m_logBuffer->end(); ++index) {
data += *index;
data += "\n";
}
// copy log to clipboard
if (!data.empty()) {
MSWindowsClipboard clipboard(m_window);
clipboard.open(0);
clipboard.emptyUnowned();
clipboard.add(IClipboard::kText, data);
clipboard.close();
}
}
}
void MSWindowsClientTaskBarReceiver::onStatusChanged()
{
if (IsWindowVisible(m_window)) {
showStatus();
}
}
HICON
MSWindowsClientTaskBarReceiver::loadIcon(UINT id)
{
HANDLE icon = LoadImage(m_appInstance, MAKEINTRESOURCE(id), IMAGE_ICON, 0, 0, LR_DEFAULTCOLOR);
return static_cast<HICON>(icon);
}
void MSWindowsClientTaskBarReceiver::deleteIcon(HICON icon)
{
if (icon != NULL) {
DestroyIcon(icon);
}
}
void MSWindowsClientTaskBarReceiver::createWindow()
{
// ignore if already created
if (m_window != NULL) {
return;
}
// get the status dialog
m_window = CreateDialogParam(
m_appInstance, MAKEINTRESOURCE(IDD_TASKBAR_STATUS), NULL, (DLGPROC)&MSWindowsClientTaskBarReceiver::staticDlgProc,
reinterpret_cast<LPARAM>(static_cast<void *>(this))
);
// window should appear on top of everything, including (especially)
// the task bar.
LONG_PTR style = GetWindowLongPtr(m_window, GWL_EXSTYLE);
style |= WS_EX_TOOLWINDOW | WS_EX_TOPMOST;
SetWindowLongPtr(m_window, GWL_EXSTYLE, style);
// tell the task bar about this dialog
ArchTaskBarWindows::addDialog(m_window);
}
void MSWindowsClientTaskBarReceiver::destroyWindow()
{
if (m_window != NULL) {
ArchTaskBarWindows::removeDialog(m_window);
DestroyWindow(m_window);
m_window = NULL;
}
}
BOOL MSWindowsClientTaskBarReceiver::dlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM)
{
switch (msg) {
case WM_INITDIALOG:
// use default focus
return TRUE;
case WM_ACTIVATE:
// hide when another window is activated
if (LOWORD(wParam) == WA_INACTIVE) {
ShowWindow(hwnd, SW_HIDE);
}
break;
}
return FALSE;
}
BOOL CALLBACK MSWindowsClientTaskBarReceiver::staticDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
// if msg is WM_INITDIALOG, extract the MSWindowsClientTaskBarReceiver*
// and put it in the extra window data then forward the call.
MSWindowsClientTaskBarReceiver *self = NULL;
if (msg == WM_INITDIALOG) {
self = static_cast<MSWindowsClientTaskBarReceiver *>(reinterpret_cast<void *>(lParam));
SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)lParam);
} else {
// get the extra window data and forward the call
LONG_PTR data = GetWindowLongPtr(hwnd, GWLP_USERDATA);
if (data != 0) {
self = (MSWindowsClientTaskBarReceiver *)data;
}
}
// forward the message
if (self != NULL) {
return self->dlgProc(hwnd, msg, wParam, lParam);
} else {
return (msg == WM_INITDIALOG) ? TRUE : FALSE;
}
}
IArchTaskBarReceiver *createTaskBarReceiver(const BufferedLogOutputter *logBuffer, IEventQueue *events)
{
ArchMiscWindows::setIcons(
(HICON)LoadImage(ArchMiscWindows::instanceWin32(), MAKEINTRESOURCE(IDI_DESKFLOW), IMAGE_ICON, 32, 32, LR_SHARED),
(HICON)LoadImage(ArchMiscWindows::instanceWin32(), MAKEINTRESOURCE(IDI_DESKFLOW), IMAGE_ICON, 16, 16, LR_SHARED)
);
return new MSWindowsClientTaskBarReceiver(MSWindowsScreen::getWindowInstance(), logBuffer, events);
}
| 9,062
|
C++
|
.cpp
| 289
| 27.799308
| 120
| 0.714826
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
13,751
|
QUtility.cpp
|
deskflow_deskflow/src/gui/src/QUtility.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2013 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "QUtility.h"
#include "ProcessorArch.h"
#if defined(Q_OS_LINUX)
#include <QFile>
#include <QProcess>
#endif
#if defined(Q_OS_WIN)
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#endif
void setIndexFromItemData(QComboBox *comboBox, const QVariant &itemData)
{
for (int i = 0; i < comboBox->count(); ++i) {
if (comboBox->itemData(i) == itemData) {
comboBox->setCurrentIndex(i);
return;
}
}
}
QString hash(const QString &string)
{
QByteArray data = string.toUtf8();
QByteArray hash = QCryptographicHash::hash(data, QCryptographicHash::Md5);
return hash.toHex();
}
qProcessorArch getProcessorArch()
{
#if defined(Q_OS_WIN)
SYSTEM_INFO systemInfo;
GetNativeSystemInfo(&systemInfo);
switch (systemInfo.wProcessorArchitecture) {
case PROCESSOR_ARCHITECTURE_INTEL:
return kProcessorArchWin32;
case PROCESSOR_ARCHITECTURE_IA64:
return kProcessorArchWin64;
case PROCESSOR_ARCHITECTURE_AMD64:
return kProcessorArchWin64;
default:
return kProcessorArchUnknown;
}
#endif
#if defined(Q_OS_LINUX)
#ifdef __i386__
return kProcessorArchLinux32;
#else
return kProcessorArchLinux64;
#endif
#endif
return kProcessorArchUnknown;
}
| 1,885
|
C++
|
.cpp
| 66
| 26.151515
| 76
| 0.763405
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,752
|
Hotkey.cpp
|
deskflow_deskflow/src/gui/src/Hotkey.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2008 Volker Lanz (vl@fidra.de)
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "Hotkey.h"
#include <QSettings>
Hotkey::Hotkey() : m_KeySequence(), m_Actions()
{
}
QString Hotkey::text() const
{
QString text = keySequence().toString();
if (keySequence().isMouseButton())
return "mousebutton(" + text + ")";
return "keystroke(" + text + ")";
}
void Hotkey::loadSettings(QSettings &settings)
{
keySequence().loadSettings(settings);
actions().clear();
int num = settings.beginReadArray("actions");
for (int i = 0; i < num; i++) {
settings.setArrayIndex(i);
Action a;
a.loadSettings(settings);
actions().append(a);
}
settings.endArray();
}
void Hotkey::saveSettings(QSettings &settings) const
{
keySequence().saveSettings(settings);
settings.beginWriteArray("actions");
for (int i = 0; i < actions().size(); i++) {
settings.setArrayIndex(i);
actions()[i].saveSettings(settings);
}
settings.endArray();
}
bool Hotkey::operator==(const Hotkey &hk) const
{
return m_KeySequence == hk.m_KeySequence && m_Actions == hk.m_Actions;
}
QTextStream &operator<<(QTextStream &outStream, const Hotkey &hotkey)
{
for (int i = 0; i < hotkey.actions().size(); i++)
outStream << "\t" << hotkey.text() << " = " << hotkey.actions()[i] << Qt::endl;
return outStream;
}
| 1,993
|
C++
|
.cpp
| 62
| 29.596774
| 83
| 0.705269
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
13,753
|
main.cpp
|
deskflow_deskflow/src/gui/src/main.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012 Symless Ltd.
* Copyright (C) 2008 Volker Lanz (vl@fidra.de)
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "MainWindow.h"
#include "SetupWizard.h"
#include "common/constants.h"
#include "common/version.h"
#include "gui/Logger.h"
#include "gui/config/AppConfig.h"
#include "gui/config/ConfigScopes.h"
#include "gui/constants.h"
#include "gui/diagnostic.h"
#include "gui/dotenv.h"
#include "gui/messages.h"
#include "gui/string_utils.h"
#include "gui_config.h" // IWYU pragma: keep
#ifdef DESKFLOW_GUI_HOOK_HEADER
#include DESKFLOW_GUI_HOOK_HEADER
#endif
#include <QApplication>
#include <QDebug>
#include <QGuiApplication>
#include <QMessageBox>
#include <QObject>
#include <QtGlobal>
#if defined(Q_OS_MAC)
#include <Carbon/Carbon.h>
#include <cstdlib>
#endif
using namespace deskflow::gui;
class QThreadImpl : public QThread
{
public:
static void msleep(unsigned long msecs)
{
QThread::msleep(msecs);
}
};
#if defined(Q_OS_MAC)
bool checkMacAssistiveDevices();
#endif
bool hasArg(const QString &arg, const QStringList &args)
{
return std::ranges::any_of(args, [&arg](const QString &a) { return a == arg; });
}
int main(int argc, char *argv[])
{
#if defined(Q_OS_MAC)
/* Workaround for QTBUG-40332 - "High ping when QNetworkAccessManager is
* instantiated" */
::setenv("QT_BEARER_POLL_TIMEOUT", "-1", 1);
#endif
QCoreApplication::setApplicationName(kAppName);
QCoreApplication::setOrganizationName(kAppName);
QGuiApplication::setDesktopFileName(QStringLiteral("org.deskflow.deskflow"));
// used as a prefix for settings paths, and must not be a url.
QCoreApplication::setOrganizationDomain(kOrgDomain);
QApplication app(argc, argv);
#if !defined(Q_OS_MAC)
// causes dark mode to be used on some DE's
if (qEnvironmentVariable("XDG_CURRENT_DESKTOP") != QLatin1String("KDE")) {
qApp->setStyle("fusion");
}
#endif
qInstallMessageHandler(deskflow::gui::messages::messageHandler);
QString version = QString::fromStdString(deskflow::version());
qInfo("%s v%s", kAppName, qPrintable(version));
dotenv();
Logger::instance().loadEnvVars();
#if defined(Q_OS_MAC)
if (app.applicationDirPath().startsWith("/Volumes/")) {
QString msgBody = QStringLiteral("Please drag %1 to the Applications folder, "
"and open it from there.");
QMessageBox::information(NULL, kAppName, msgBody.arg(kAppName));
return 1;
}
if (!checkMacAssistiveDevices()) {
return 1;
}
#endif
ConfigScopes configScopes;
// --no-reset
QStringList arguments = QCoreApplication::arguments();
const auto noReset = hasArg("--no-reset", arguments);
const auto resetEnvVar = strToTrue(qEnvironmentVariable("DESKFLOW_RESET_ALL"));
if (resetEnvVar && !noReset) {
diagnostic::clearSettings(configScopes, false);
}
AppConfig appConfig(configScopes);
QObject::connect(
&configScopes, &ConfigScopes::saving, &appConfig, [&appConfig]() { appConfig.commit(); }, Qt::DirectConnection
);
if (appConfig.wizardShouldRun()) {
SetupWizard wizard(appConfig);
auto result = wizard.exec();
if (result != QDialog::Accepted) {
qInfo("wizard cancelled, exiting");
return 0;
}
configScopes.save();
}
MainWindow mainWindow(configScopes, appConfig);
mainWindow.open();
#ifdef DESKFLOW_GUI_HOOK_START
DESKFLOW_GUI_HOOK_START
#endif
return qApp->exec();
}
#if defined(Q_OS_MAC)
bool checkMacAssistiveDevices()
{
#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 // mavericks
// new in mavericks, applications are trusted individually
// with use of the accessibility api. this call will show a
// prompt which can show the security/privacy/accessibility
// tab, with a list of allowed applications. deskflow should
// show up there automatically, but will be unchecked.
if (AXIsProcessTrusted()) {
return true;
}
const void *keys[] = {kAXTrustedCheckOptionPrompt};
const void *trueValue[] = {kCFBooleanTrue};
CFDictionaryRef options = CFDictionaryCreate(NULL, keys, trueValue, 1, NULL, NULL);
bool result = AXIsProcessTrustedWithOptions(options);
CFRelease(options);
return result;
#else
// now deprecated in mavericks.
bool result = AXAPIEnabled();
if (!result) {
QString msgBody = QString("Please enable access to assistive devices "
"System Preferences -> Security & Privacy -> "
"Privacy -> Accessibility, then re-open %1.");
QMessageBox::information(NULL, kAppName, msgBody.arg(kAppName));
}
return result;
#endif
}
#endif
| 5,208
|
C++
|
.cpp
| 153
| 30.777778
| 116
| 0.728631
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,754
|
MainWindow.cpp
|
deskflow_deskflow/src/gui/src/MainWindow.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012 Symless Ltd.
* Copyright (C) 2008 Volker Lanz (vl@fidra.de)
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "MainWindow.h"
#include "ui_MainWindow.h"
#include "dialogs/AboutDialog.h"
#include "dialogs/ServerConfigDialog.h"
#include "dialogs/SettingsDialog.h"
#include "common/constants.h"
#include "gui/Logger.h"
#include "gui/config/ConfigScopes.h"
#include "gui/constants.h"
#include "gui/core/CoreProcess.h"
#include "gui/diagnostic.h"
#include "gui/messages.h"
#include "gui/string_utils.h"
#include "gui/styles.h"
#include "gui/tls/TlsFingerprint.h"
#include "platform/wayland.h"
#if defined(Q_OS_MAC)
#include "gui/OSXHelpers.h"
#endif
#if defined(Q_OS_LINUX)
#include "config.h"
#endif
#include <QApplication>
#include <QDesktopServices>
#include <QFileDialog>
#include <QMenu>
#include <QMenuBar>
#include <QMessageBox>
#include <QNetworkAccessManager>
#include <QNetworkInterface>
#include <QPushButton>
#include <QRegularExpression>
#include <QScrollBar>
#include <memory>
#if defined(Q_OS_MAC)
#include <ApplicationServices/ApplicationServices.h>
#endif
using namespace deskflow::gui;
using CoreMode = CoreProcess::Mode;
using CoreConnectionState = CoreProcess::ConnectionState;
using CoreProcessState = CoreProcess::ProcessState;
const auto kIconFile = ":/icons/128x128/tray.png";
#ifdef Q_OS_MAC
const auto kLightIconFile = ":/icons/128x128/tray-light.png";
const auto kDarkIconFile = ":/icons/128x128/tray-dark.png";
#endif // Q_OS_MAC
MainWindow::MainWindow(ConfigScopes &configScopes, AppConfig &appConfig)
: ui{std::make_unique<Ui::MainWindow>()},
m_ConfigScopes(configScopes),
m_AppConfig(appConfig),
m_ServerConfig(appConfig, *this),
m_CoreProcess(appConfig, m_ServerConfig),
m_ServerConnection(this, appConfig, m_ServerConfig, m_ServerConfigDialogState),
m_ClientConnection(this, appConfig),
m_TlsUtility(appConfig),
m_WindowSaveTimer(this)
{
ui->setupUi(this);
createMenuBar();
setupControls();
connectSlots();
// handled by `onCreated`
Q_EMIT created();
}
MainWindow::~MainWindow()
{
m_CoreProcess.cleanup();
}
void MainWindow::restoreWindow()
{
const auto &windowSize = m_AppConfig.mainWindowSize();
if (windowSize.has_value()) {
qDebug("restoring main window size");
resize(windowSize.value());
}
const auto &windowPosition = m_AppConfig.mainWindowPosition();
if (windowPosition.has_value()) {
qDebug("restoring main window position");
move(windowPosition.value());
} else {
// center main window in middle of screen
const auto screen = QGuiApplication::primaryScreen();
QRect screenGeometry = screen->geometry();
move(screenGeometry.center() - rect().center());
}
// give the window chance to restore its size and position before the window
// size and position are saved. this prevents the window from being saved
// with the wrong size and position.
m_SaveWindow = true;
}
void MainWindow::saveWindow()
{
if (!m_SaveWindow) {
qDebug("not yet ready to save window size and position, skipping");
return;
}
qDebug("saving window size and position");
m_AppConfig.setMainWindowSize(size());
m_AppConfig.setMainWindowPosition(pos());
m_ConfigScopes.save();
}
void MainWindow::setupControls()
{
setWindowTitle(kAppName);
ui->m_pActionHelp->setText(tr("Report a Bug"));
secureSocket(false);
updateLocalFingerprint();
ui->m_pLabelUpdate->setStyleSheet(kStyleNoticeLabel);
ui->m_pLabelUpdate->hide();
ui->m_pLabelNotice->setStyleSheet(kStyleNoticeLabel);
ui->m_pLabelNotice->hide();
ui->m_pLabelIpAddresses->setText(QString("This computer's IP addresses: %1").arg(getIPAddresses()));
if (m_AppConfig.lastVersion() != DESKFLOW_VERSION) {
m_AppConfig.setLastVersion(DESKFLOW_VERSION);
}
#if defined(Q_OS_MAC)
ui->m_pRadioGroupServer->setAttribute(Qt::WA_MacShowFocusRect, 0);
ui->m_pRadioGroupClient->setAttribute(Qt::WA_MacShowFocusRect, 0);
#endif
}
//////////////////////////////////////////////////////////////////////////////
// Begin slots
//////////////////////////////////////////////////////////////////////////////
// remember: using queued connection allows the render loop to run before
// executing the slot. the default is to instantly call the slot when the
// signal is emitted from the thread that owns the receiver's object.
void MainWindow::connectSlots()
{
connect(
&Logger::instance(), &Logger::newLine, this, //
[this](const QString &line) { handleLogLine(line); }
);
connect(this, &MainWindow::created, this, &MainWindow::onCreated);
connect(this, &MainWindow::shown, this, &MainWindow::onShown, Qt::QueuedConnection);
connect(&m_ConfigScopes, &ConfigScopes::saving, this, &MainWindow::onConfigScopesSaving, Qt::DirectConnection);
connect(&m_AppConfig, &AppConfig::tlsChanged, this, &MainWindow::onAppConfigTlsChanged);
connect(&m_AppConfig, &AppConfig::screenNameChanged, this, &MainWindow::onAppConfigScreenNameChanged);
connect(&m_AppConfig, &AppConfig::invertConnectionChanged, this, &MainWindow::onAppConfigInvertConnection);
connect(&m_CoreProcess, &CoreProcess::starting, this, &MainWindow::onCoreProcessStarting, Qt::DirectConnection);
connect(&m_CoreProcess, &CoreProcess::error, this, &MainWindow::onCoreProcessError);
connect(
&m_CoreProcess, &CoreProcess::logLine, this, //
[this](const QString &line) { handleLogLine(line); }
);
connect(&m_CoreProcess, &CoreProcess::processStateChanged, this, &MainWindow::onCoreProcessStateChanged);
connect(&m_CoreProcess, &CoreProcess::connectionStateChanged, this, &MainWindow::onCoreConnectionStateChanged);
connect(&m_CoreProcess, &CoreProcess::secureSocket, this, &MainWindow::onCoreProcessSecureSocket);
connect(ui->m_pActionMinimize, &QAction::triggered, this, &MainWindow::hide);
connect(
ui->m_pActionRestore, &QAction::triggered, this, //
[this]() { showAndActivate(); }
);
connect(ui->m_pActionQuit, &QAction::triggered, qApp, [this] {
qDebug("quitting application");
m_Quitting = true;
QApplication::quit();
});
connect(&m_VersionChecker, &VersionChecker::updateFound, this, &MainWindow::onVersionCheckerUpdateFound);
connect(&m_WindowSaveTimer, &QTimer::timeout, this, &MainWindow::onWindowSaveTimerTimeout);
connect(&m_TrayIcon, &TrayIcon::activated, this, &MainWindow::onTrayIconActivated);
connect(
&m_ServerConnection, &ServerConnection::configureClient, this, &MainWindow::onServerConnectionConfigureClient
);
connect(&m_ServerConnection, &ServerConnection::messageShowing, this, [this]() { showAndActivate(); });
connect(&m_ClientConnection, &ClientConnection::messageShowing, this, [this]() { showAndActivate(); });
}
void MainWindow::onAppAboutToQuit()
{
if (m_SaveOnExit) {
m_ConfigScopes.save();
}
}
void MainWindow::onCreated()
{
setIcon();
m_ConfigScopes.signalReady();
applyCloseToTray();
updateScreenName();
applyConfig();
restoreWindow();
qDebug().noquote() << "active settings path:" << m_ConfigScopes.activeFilePath();
}
void MainWindow::onShown()
{
// if a critical error was shown just before the main window (i.e. on app
// load), it will be hidden behind the main window. therefore we need to raise
// it up in front of the main window.
// HACK: because the `onShown` event happens just as the window is shown, the
// message box has a chance of being raised under the main window. to solve
// this we delay the error dialog raise by a split second. this seems a bit
// hacky and fragile, so maybe there's a better approach.
const auto kCriticalDialogDelay = 100;
QTimer::singleShot(kCriticalDialogDelay, this, [] { messages::raiseCriticalDialog(); });
}
void MainWindow::onConfigScopesSaving()
{
m_ServerConfig.commit();
}
void MainWindow::onAppConfigTlsChanged()
{
updateLocalFingerprint();
if (m_TlsUtility.isEnabled()) {
m_TlsUtility.generateCertificate();
}
}
void MainWindow::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
if (reason == QSystemTrayIcon::DoubleClick) {
if (isVisible()) {
hide();
} else {
showAndActivate();
}
}
}
void MainWindow::onVersionCheckerUpdateFound(const QString &version)
{
const auto link = QString(kLinkDownload).arg(kUrlDownload, kColorWhite);
const auto text = QString("A new version is available (v%1). %2").arg(version, link);
ui->m_pLabelUpdate->show();
ui->m_pLabelUpdate->setText(text);
}
void MainWindow::onAppConfigScreenNameChanged()
{
updateScreenName();
}
void MainWindow::onAppConfigInvertConnection()
{
applyConfig();
}
void MainWindow::onCoreProcessError(CoreProcess::Error error)
{
if (error == CoreProcess::Error::AddressMissing) {
QMessageBox::warning(
this, QString("Address missing"), QString("Please enter the hostname or IP address of the other computer.")
);
} else if (error == CoreProcess::Error::StartFailed) {
show();
QMessageBox::warning(
this, QString("Core cannot be started"),
"The Core executable could not be successfully started, "
"although it does exist. "
"Please check if you have sufficient permissions to run this program."
);
}
}
void MainWindow::on_m_pActionStartCore_triggered()
{
m_ClientConnection.setShowMessage();
m_CoreProcess.start();
}
void MainWindow::on_m_pActionStopCore_triggered()
{
qDebug("stopping core process");
m_CoreProcess.stop();
}
void MainWindow::on_m_pActionTestFatalError_triggered() const
{
qFatal("test fatal error");
}
void MainWindow::on_m_pActionTestCriticalError_triggered() const
{
qCritical("test critical error");
}
void MainWindow::on_m_pActionClearSettings_triggered()
{
if (!messages::showClearSettings(this)) {
qDebug("clear settings cancelled");
return;
}
m_CoreProcess.stop();
m_Quitting = true;
m_SaveOnExit = false;
diagnostic::clearSettings(m_ConfigScopes, true);
}
bool MainWindow::on_m_pActionSave_triggered()
{
QString fileName = QFileDialog::getSaveFileName(this, QString("Save configuration as..."));
if (!fileName.isEmpty() && !m_ServerConfig.save(fileName)) {
QMessageBox::warning(this, QString("Save failed"), QString("Could not save configuration to file."));
return true;
}
return false;
}
void MainWindow::on_m_pActionAbout_triggered()
{
AboutDialog about(this);
about.exec();
}
void MainWindow::on_m_pActionHelp_triggered() const
{
QDesktopServices::openUrl(QUrl(kUrlHelp));
}
void MainWindow::on_m_pActionSettings_triggered()
{
auto dialog = SettingsDialog(this, m_AppConfig, m_ServerConfig, m_CoreProcess);
if (dialog.exec() == QDialog::Accepted) {
m_ConfigScopes.save();
applyConfig();
applyCloseToTray();
if (m_CoreProcess.isStarted()) {
m_CoreProcess.restart();
}
}
}
void MainWindow::on_m_pButtonConfigureServer_clicked()
{
showConfigureServer();
}
void MainWindow::on_m_pLineEditHostname_returnPressed()
{
ui->m_pButtonConnect->click();
}
void MainWindow::on_m_pLineEditClientIp_returnPressed()
{
ui->m_pButtonConnectToClient->click();
}
void MainWindow::on_m_pLineEditHostname_textChanged(const QString &text)
{
m_CoreProcess.setAddress(text);
}
void MainWindow::on_m_pLineEditClientIp_textChanged(const QString &text)
{
m_CoreProcess.setAddress(text);
}
void MainWindow::on_m_pButtonApply_clicked()
{
m_ClientConnection.setShowMessage();
m_CoreProcess.restart();
}
void MainWindow::on_m_pLabelComputerName_linkActivated(const QString &)
{
ui->m_pActionSettings->trigger();
}
void MainWindow::on_m_pLabelFingerprint_linkActivated(const QString &)
{
QMessageBox::information(this, "TLS fingerprint", TlsFingerprint::local().readFirst());
}
void MainWindow::on_m_pRadioGroupServer_clicked(bool)
{
enableServer(true);
enableClient(false);
m_ConfigScopes.save();
}
void MainWindow::on_m_pRadioGroupClient_clicked(bool)
{
enableClient(true);
enableServer(false);
m_ConfigScopes.save();
}
void MainWindow::on_m_pButtonConnect_clicked()
{
on_m_pButtonApply_clicked();
}
void MainWindow::on_m_pButtonConnectToClient_clicked()
{
on_m_pButtonApply_clicked();
}
void MainWindow::onWindowSaveTimerTimeout()
{
saveWindow();
}
void MainWindow::onServerConnectionConfigureClient(const QString &clientName)
{
m_ServerConfigDialogState.setVisible(true);
ServerConfigDialog dialog(this, m_ServerConfig, m_AppConfig);
if (dialog.addClient(clientName) && dialog.exec() == QDialog::Accepted) {
m_CoreProcess.restart();
}
m_ServerConfigDialogState.setVisible(false);
}
//////////////////////////////////////////////////////////////////////////////
// End slots
//////////////////////////////////////////////////////////////////////////////
void MainWindow::resizeEvent(QResizeEvent *event)
{
QMainWindow::resizeEvent(event);
// postpone save so that settings are not written every delta change.
m_WindowSaveTimer.setSingleShot(true);
m_WindowSaveTimer.start(1000);
}
void MainWindow::moveEvent(QMoveEvent *event)
{
QMainWindow::moveEvent(event);
// postpone save so that settings are not written every delta change.
m_WindowSaveTimer.setSingleShot(true);
m_WindowSaveTimer.start(1000);
}
void MainWindow::open()
{
std::vector<QAction *> trayMenu = {ui->m_pActionStartCore, ui->m_pActionStopCore, nullptr,
ui->m_pActionMinimize, ui->m_pActionRestore, nullptr,
ui->m_pActionQuit};
m_TrayIcon.create(trayMenu);
if (m_AppConfig.autoHide()) {
hide();
} else {
showAndActivate();
}
if (!m_AppConfig.enableUpdateCheck().has_value()) {
m_AppConfig.setEnableUpdateCheck(messages::showUpdateCheckOption(this));
m_ConfigScopes.save();
}
if (m_AppConfig.enableUpdateCheck().value()) {
m_VersionChecker.checkLatest();
} else {
qDebug("update check disabled");
}
if (m_AppConfig.startedBefore()) {
m_CoreProcess.start();
}
}
void MainWindow::onCoreProcessStarting()
{
if (deskflow::platform::isWayland()) {
m_WaylandWarnings.showOnce(this, m_CoreProcess.mode());
}
saveSettings();
}
void MainWindow::setStatus(const QString &status)
{
ui->m_pStatusLabel->setText(status);
}
void MainWindow::createMenuBar()
{
m_pMenuBar = new QMenuBar(this);
m_pMenuFile = new QMenu("File", m_pMenuBar);
m_pMenuEdit = new QMenu("Edit", m_pMenuBar);
m_pMenuWindow = new QMenu("Window", m_pMenuBar);
m_pMenuHelp = new QMenu("Help", m_pMenuBar);
m_pMenuBar->addAction(m_pMenuFile->menuAction());
m_pMenuBar->addAction(m_pMenuEdit->menuAction());
#if !defined(Q_OS_MAC)
m_pMenuBar->addAction(m_pMenuWindow->menuAction());
#endif
m_pMenuBar->addAction(m_pMenuHelp->menuAction());
m_pMenuFile->addAction(ui->m_pActionStartCore);
m_pMenuFile->addAction(ui->m_pActionStopCore);
m_pMenuFile->addSeparator();
m_pMenuFile->addAction(ui->m_pActionSave);
m_pMenuFile->addSeparator();
m_pMenuFile->addAction(ui->m_pActionQuit);
m_pMenuEdit->addAction(ui->m_pActionSettings);
m_pMenuWindow->addAction(ui->m_pActionMinimize);
m_pMenuWindow->addAction(ui->m_pActionRestore);
m_pMenuHelp->addAction(ui->m_pActionAbout);
m_pMenuHelp->addAction(ui->m_pActionHelp);
m_pMenuFile->addSeparator();
m_pMenuHelp->addAction(ui->m_pActionClearSettings);
ui->m_pActionAbout->setText(QString("About %1...").arg(kAppName));
const auto enableTestMenu = strToTrue(qEnvironmentVariable("DESKFLOW_TEST_MENU"));
if (enableTestMenu || kDebugBuild) {
auto testMenu = new QMenu("Test", m_pMenuBar);
m_pMenuBar->addMenu(testMenu);
testMenu->addAction(ui->m_pActionTestFatalError);
testMenu->addAction(ui->m_pActionTestCriticalError);
}
setMenuBar(m_pMenuBar);
}
void MainWindow::applyConfig()
{
enableServer(m_AppConfig.serverGroupChecked());
enableClient(m_AppConfig.clientGroupChecked());
ui->m_pLineEditHostname->setText(m_AppConfig.serverHostname());
ui->m_pLineEditClientIp->setText(m_ServerConfig.getClientAddress());
}
void MainWindow::applyCloseToTray() const
{
QApplication::setQuitOnLastWindowClosed(!m_AppConfig.closeToTray());
}
void MainWindow::saveSettings()
{
m_AppConfig.setServerGroupChecked(ui->m_pRadioGroupServer->isChecked());
m_AppConfig.setClientGroupChecked(ui->m_pRadioGroupClient->isChecked());
m_AppConfig.setServerHostname(ui->m_pLineEditHostname->text());
m_ServerConfig.setClientAddress(ui->m_pLineEditClientIp->text());
m_ConfigScopes.save();
}
void MainWindow::setIcon()
{
QIcon icon;
#ifdef Q_OS_MAC
switch (getOSXIconsTheme()) {
case IconsTheme::ICONS_DARK:
icon.addFile(kDarkIconFile);
break;
case IconsTheme::ICONS_LIGHT:
icon.addFile(kLightIconFile);
break;
case IconsTheme::ICONS_TEMPLATE:
default:
icon.addFile(kDarkIconFile);
icon.setIsMask(true);
break;
}
#else
icon.addFile(kIconFile);
#endif
m_TrayIcon.setIcon(icon);
}
void MainWindow::handleLogLine(const QString &line)
{
const int kScrollBottomThreshold = 2;
QScrollBar *verticalScroll = ui->m_pLogOutput->verticalScrollBar();
int currentScroll = verticalScroll->value();
int maxScroll = verticalScroll->maximum();
const auto scrollAtBottom = qAbs(currentScroll - maxScroll) <= kScrollBottomThreshold;
// only trim end instead of the whole line to prevent tab-indented debug
// filenames from losing their indentation.
ui->m_pLogOutput->appendPlainText(trimEnd(line));
if (scrollAtBottom) {
verticalScroll->setValue(verticalScroll->maximum());
ui->m_pLogOutput->horizontalScrollBar()->setValue(0);
}
updateFromLogLine(line);
}
void MainWindow::updateFromLogLine(const QString &line)
{
checkConnected(line);
checkFingerprint(line);
}
void MainWindow::checkConnected(const QString &line)
{
if (ui->m_pRadioGroupServer->isChecked()) {
m_ServerConnection.handleLogLine(line);
ui->m_pLabelServerState->updateServerState(line);
} else {
m_ClientConnection.handleLogLine(line);
ui->m_pLabelClientState->updateClientState(line);
}
}
void MainWindow::checkFingerprint(const QString &line)
{
static const QRegularExpression re(".*server fingerprint: ([A-F0-9:]+)");
auto match = re.match(line);
if (!match.hasMatch()) {
return;
}
auto fingerprint = match.captured(1);
if (TlsFingerprint::trustedServers().isTrusted(fingerprint)) {
return;
}
static bool messageBoxAlreadyShown = false;
if (!messageBoxAlreadyShown) {
m_CoreProcess.stop();
messageBoxAlreadyShown = true;
QMessageBox::StandardButton fingerprintReply = QMessageBox::information(
this, QString("Security question"),
QString("<p>You are connecting to a server.</p>"
"<p>Here is it's TLS fingerprint:</p>"
"<p>%1</p>"
"<p>Compare this fingerprint to the one on your server's screen. "
"If the two don't match exactly, then it's probably not the server "
"you're expecting (it could be a malicious user).</p>"
"<p>Do you want to trust this fingerprint for future "
"connections? If you don't, a connection cannot be made.</p>")
.arg(fingerprint),
QMessageBox::Yes | QMessageBox::No
);
if (fingerprintReply == QMessageBox::Yes) {
// start core process again after trusting fingerprint.
TlsFingerprint::trustedServers().trust(fingerprint);
m_CoreProcess.start();
}
messageBoxAlreadyShown = false;
}
}
QString MainWindow::getTimeStamp() const
{
QDateTime current = QDateTime::currentDateTime();
return '[' + current.toString(Qt::ISODate) + ']';
}
void MainWindow::showEvent(QShowEvent *event)
{
QMainWindow::showEvent(event);
Q_EMIT shown();
}
void MainWindow::closeEvent(QCloseEvent *event)
{
if (m_Quitting) {
qDebug("skipping close event handle on quit");
return;
}
if (!m_AppConfig.closeToTray()) {
qDebug("window will not hide to tray");
return;
}
if (m_AppConfig.showCloseReminder()) {
messages::showCloseReminder(this);
m_AppConfig.setShowCloseReminder(false);
}
m_ConfigScopes.save();
qDebug("window should hide to tray");
}
void MainWindow::showFirstConnectedMessage()
{
if (m_AppConfig.startedBefore()) {
return;
}
m_AppConfig.setStartedBefore(true);
m_ConfigScopes.save();
const auto isServer = m_CoreProcess.mode() == CoreMode::Server;
messages::showFirstConnectedMessage(this, m_AppConfig.closeToTray(), m_AppConfig.enableService(), isServer);
}
void MainWindow::onCoreProcessSecureSocket(bool enabled)
{
secureSocket(enabled);
}
void MainWindow::updateStatus()
{
const auto connection = m_CoreProcess.connectionState();
const auto process = m_CoreProcess.processState();
switch (process) {
using enum CoreProcessState;
case Starting:
setStatus(QString("%1 is starting...").arg(kAppName));
break;
case RetryPending:
setStatus(QString("%1 will retry in a moment...").arg(kAppName));
break;
case Stopping:
setStatus(QString("%1 is stopping...").arg(kAppName));
break;
case Stopped:
setStatus(QString("%1 is not running").arg(kAppName));
break;
case Started: {
switch (connection) {
using enum CoreConnectionState;
case Listening: {
if (m_CoreProcess.mode() == CoreMode::Server) {
setStatus(QString("%1 is waiting for clients").arg(kAppName));
}
break;
}
case Connecting:
setStatus(QString("%1 is connecting...").arg(kAppName));
break;
case Connected: {
if (m_SecureSocket) {
setStatus(QString("%1 is connected (with %2)").arg(kAppName, m_CoreProcess.secureSocketVersion()));
} else {
setStatus(QString("%1 is connected (without TLS encryption)").arg(kAppName));
}
break;
}
case Disconnected:
setStatus(QString("%1 is disconnected").arg(kAppName));
break;
}
} break;
}
}
void MainWindow::onCoreProcessStateChanged(CoreProcessState state)
{
updateStatus();
if (state == CoreProcessState::Started) {
qDebug("recording that core has started");
m_AppConfig.setStartedBefore(true);
m_ConfigScopes.save();
}
if (state == CoreProcessState::Started || state == CoreProcessState::Starting ||
state == CoreProcessState::RetryPending) {
disconnect(ui->m_pButtonToggleStart, &QPushButton::clicked, ui->m_pActionStartCore, &QAction::trigger);
connect(ui->m_pButtonToggleStart, &QPushButton::clicked, ui->m_pActionStopCore, &QAction::trigger);
ui->m_pButtonToggleStart->setText(QString("&Stop"));
ui->m_pButtonApply->setEnabled(true);
ui->m_pActionStartCore->setEnabled(false);
ui->m_pActionStopCore->setEnabled(true);
} else {
disconnect(ui->m_pButtonToggleStart, &QPushButton::clicked, ui->m_pActionStopCore, &QAction::trigger);
connect(ui->m_pButtonToggleStart, &QPushButton::clicked, ui->m_pActionStartCore, &QAction::trigger);
ui->m_pButtonToggleStart->setText(QString("&Start"));
ui->m_pButtonApply->setEnabled(false);
ui->m_pActionStartCore->setEnabled(true);
ui->m_pActionStopCore->setEnabled(false);
}
}
void MainWindow::onCoreConnectionStateChanged(CoreConnectionState state)
{
qDebug("core connection state changed: %d", static_cast<int>(state));
updateStatus();
// always assume connection is not secure when connection changes
// to anything except connected. the only way the padlock shows is
// when the correct TLS version string is detected.
if (state != CoreConnectionState::Connected) {
secureSocket(false);
} else if (isVisible()) {
showFirstConnectedMessage();
}
}
void MainWindow::setVisible(bool visible)
{
QMainWindow::setVisible(visible);
ui->m_pActionMinimize->setEnabled(visible);
ui->m_pActionRestore->setEnabled(!visible);
#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 // lion
// dock hide only supported on lion :(
ProcessSerialNumber psn = {0, kCurrentProcess};
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
GetCurrentProcess(&psn);
#pragma GCC diagnostic pop
if (visible)
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
else
TransformProcessType(&psn, kProcessTransformToBackgroundApplication);
#endif
}
QString MainWindow::getIPAddresses() const
{
QStringList result;
bool hinted = false;
const auto localnet = QHostAddress::parseSubnet("192.168.0.0/16");
const QList<QHostAddress> addresses = QNetworkInterface::allAddresses();
for (const auto &address : addresses) {
if (address.protocol() == QAbstractSocket::IPv4Protocol && address != QHostAddress(QHostAddress::LocalHost) &&
!address.isInSubnet(QHostAddress::parseSubnet("169.254.0.0/16"))) {
// usually 192.168.x.x is a useful ip for the user, so indicate
// this by making it bold.
if (!hinted && address.isInSubnet(localnet)) {
QString format = R"(<span style="color:%1;">%2</span>)";
result.append(format.arg(kColorTertiary, address.toString()));
hinted = true;
} else {
result.append(address.toString());
}
}
}
if (result.isEmpty()) {
result.append("Unknown");
}
return result.join(", ");
}
void MainWindow::updateLocalFingerprint()
{
bool fingerprintExists = false;
try {
fingerprintExists = TlsFingerprint::local().fileExists();
} catch (const std::exception &e) {
qDebug() << e.what();
qFatal("failed to check if fingerprint exists");
}
if (m_AppConfig.tlsEnabled() && fingerprintExists && ui->m_pRadioGroupServer->isChecked()) {
ui->m_pLabelFingerprint->setVisible(true);
} else {
ui->m_pLabelFingerprint->setVisible(false);
}
}
void MainWindow::autoAddScreen(const QString name)
{
int r = m_ServerConfig.autoAddScreen(name);
if (r != kAutoAddScreenOk) {
switch (r) {
case kAutoAddScreenManualServer:
showConfigureServer(QString("Please add the server (%1) to the grid.").arg(m_AppConfig.screenName()));
break;
case kAutoAddScreenManualClient:
showConfigureServer(QString("Please drag the new client screen (%1) "
"to the desired position on the grid.")
.arg(name));
break;
}
}
}
void MainWindow::showConfigureServer(const QString &message)
{
ServerConfigDialog dialog(this, serverConfig(), m_AppConfig);
dialog.message(message);
if ((dialog.exec() == QDialog::Accepted) && m_CoreProcess.isStarted()) {
m_CoreProcess.restart();
}
}
void MainWindow::secureSocket(bool secureSocket)
{
m_SecureSocket = secureSocket;
if (secureSocket) {
ui->m_pLabelPadlock->show();
} else {
ui->m_pLabelPadlock->hide();
}
}
void MainWindow::updateScreenName()
{
ui->m_pLabelComputerName->setText(QString("This computer's name: %1 "
R"((<a href="#" style="color: %2">change</a>))")
.arg(m_AppConfig.screenName(), kColorSecondary));
m_ServerConfig.updateServerName();
}
void MainWindow::enableServer(bool enable)
{
qDebug(enable ? "server enabled" : "server disabled");
m_AppConfig.setServerGroupChecked(enable);
ui->m_pRadioGroupServer->setChecked(enable);
ui->m_pWidgetServer->setEnabled(enable);
ui->m_pWidgetServerInput->setVisible(m_AppConfig.invertConnection());
if (enable) {
ui->m_pButtonToggleStart->setEnabled(true);
ui->m_pActionStartCore->setEnabled(true);
m_CoreProcess.setMode(CoreProcess::Mode::Server);
// The server can run without any clients configured, and this is actually
// what you'll want to do the first time since you'll be prompted when an
// unrecognized client tries to connect.
if (!m_AppConfig.startedBefore()) {
qDebug("auto-starting core server for first time");
m_CoreProcess.start();
messages::showFirstServerStartMessage(this);
}
}
}
void MainWindow::enableClient(bool enable)
{
qDebug(enable ? "client enabled" : "client disabled");
m_AppConfig.setClientGroupChecked(enable);
ui->m_pRadioGroupClient->setChecked(enable);
ui->m_pWidgetClientInput->setEnabled(enable);
ui->m_pWidgetClientInput->setVisible(!m_AppConfig.invertConnection());
if (enable) {
ui->m_pButtonToggleStart->setEnabled(true);
ui->m_pActionStartCore->setEnabled(true);
m_CoreProcess.setMode(CoreProcess::Mode::Client);
}
}
void MainWindow::showAndActivate()
{
if (!isMinimized() && !isHidden()) {
qDebug("window already visible");
return;
}
showNormal();
raise();
activateWindow();
}
| 29,274
|
C++
|
.cpp
| 850
| 30.849412
| 115
| 0.722061
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,755
|
ServerConfig.cpp
|
deskflow_deskflow/src/gui/src/ServerConfig.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012 Symless Ltd.
* Copyright (C) 2008 Volker Lanz (vl@fidra.de)
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "ServerConfig.h"
#include "Hotkey.h"
#include "MainWindow.h"
#include "dialogs/AddClientDialog.h"
#include <QAbstractButton>
#include <QMessageBox>
#include <QPushButton>
using namespace deskflow::gui::proxy;
using enum ScreenConfig::Modifier;
using enum ScreenConfig::SwitchCorner;
using enum ScreenConfig::Fix;
static const struct
{
int x;
int y;
const char *name;
} neighbourDirs[] = {
{1, 0, "right"},
{-1, 0, "left"},
{0, -1, "up"},
{0, 1, "down"},
};
const int serverDefaultIndex = 7;
ServerConfig::ServerConfig(AppConfig &appConfig, MainWindow &mainWindow, int columns, int rows)
: m_pAppConfig(&appConfig),
m_pMainWindow(&mainWindow),
m_Screens(columns),
m_Columns(columns),
m_Rows(rows),
m_ClipboardSharingSize(defaultClipboardSharingSize())
{
recall();
}
bool ServerConfig::save(const QString &fileName) const
{
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
return false;
save(file);
file.close();
return true;
}
bool ServerConfig::operator==(const ServerConfig &sc) const
{
return m_Screens == sc.m_Screens && //
m_Columns == sc.m_Columns && //
m_Rows == sc.m_Rows && //
m_HasHeartbeat == sc.m_HasHeartbeat && //
m_Heartbeat == sc.m_Heartbeat && //
m_Protocol == sc.m_Protocol && //
m_RelativeMouseMoves == sc.m_RelativeMouseMoves && //
m_Win32KeepForeground == sc.m_Win32KeepForeground && //
m_HasSwitchDelay == sc.m_HasSwitchDelay && //
m_SwitchDelay == sc.m_SwitchDelay && //
m_HasSwitchDoubleTap == sc.m_HasSwitchDoubleTap && //
m_SwitchDoubleTap == sc.m_SwitchDoubleTap && //
m_SwitchCornerSize == sc.m_SwitchCornerSize && //
m_SwitchCorners == sc.m_SwitchCorners && //
m_Hotkeys == sc.m_Hotkeys && //
m_pAppConfig == sc.m_pAppConfig && //
m_EnableDragAndDrop == sc.m_EnableDragAndDrop && //
m_DisableLockToScreen == sc.m_DisableLockToScreen && //
m_ClipboardSharing == sc.m_ClipboardSharing && //
m_ClipboardSharingSize == sc.m_ClipboardSharingSize && //
m_pMainWindow == sc.m_pMainWindow;
}
void ServerConfig::save(QFile &file) const
{
QTextStream outStream(&file);
outStream << *this;
}
void ServerConfig::setupScreens()
{
switchCorners().clear();
screens().clear();
hotkeys().clear();
// m_NumSwitchCorners is used as a fixed size array. See Screen::init()
for (int i = 0; i < static_cast<int>(NumSwitchCorners); i++)
switchCorners() << false;
// There must always be screen objects for each cell in the screens QList.
// Unused screens are identified by having an empty name.
for (int i = 0; i < numColumns() * numRows(); i++)
addScreen(Screen());
}
void ServerConfig::commit()
{
qDebug("committing server config");
settings().beginGroup("internalConfig");
settings().remove("");
settings().setValue("numColumns", numColumns());
settings().setValue("numRows", numRows());
settings().setValue("hasHeartbeat", hasHeartbeat());
settings().setValue("heartbeat", heartbeat());
settings().setValue("protocol", static_cast<int>(protocol()));
settings().setValue("relativeMouseMoves", relativeMouseMoves());
settings().setValue("win32KeepForeground", win32KeepForeground());
settings().setValue("hasSwitchDelay", hasSwitchDelay());
settings().setValue("switchDelay", switchDelay());
settings().setValue("hasSwitchDoubleTap", hasSwitchDoubleTap());
settings().setValue("switchDoubleTap", switchDoubleTap());
settings().setValue("switchCornerSize", switchCornerSize());
settings().setValue("disableLockToScreen", disableLockToScreen());
settings().setValue("enableDragAndDrop", enableDragAndDrop());
settings().setValue("clipboardSharing", clipboardSharing());
settings().setValue("clipboardSharingSize", QVariant::fromValue(clipboardSharingSize()));
if (!getClientAddress().isEmpty()) {
settings().setValue("clientAddress", getClientAddress());
}
writeSettings(settings(), switchCorners(), "switchCorner");
settings().beginWriteArray("screens");
for (int i = 0; i < screens().size(); i++) {
settings().setArrayIndex(i);
auto &screen = screens()[i];
screen.saveSettings(settings());
if (screen.isServer() && m_pAppConfig->screenName() != screen.name()) {
m_pAppConfig->setScreenName(screen.name());
}
}
settings().endArray();
settings().beginWriteArray("hotkeys");
for (int i = 0; i < hotkeys().size(); i++) {
settings().setArrayIndex(i);
hotkeys()[i].saveSettings(settings().get());
}
settings().endArray();
settings().endGroup();
}
void ServerConfig::recall()
{
qDebug("recalling server config");
settings().beginGroup("internalConfig");
setNumColumns(settings().value("numColumns", 5).toInt());
setNumRows(settings().value("numRows", 3).toInt());
// we need to know the number of columns and rows before we can set up
// ourselves
setupScreens();
haveHeartbeat(settings().value("hasHeartbeat", false).toBool());
setHeartbeat(settings().value("heartbeat", 5000).toInt());
setProtocol(static_cast<ServerProtocol>(settings().value("protocol", static_cast<int>(protocol())).toInt()));
setRelativeMouseMoves(settings().value("relativeMouseMoves", false).toBool());
setWin32KeepForeground(settings().value("win32KeepForeground", false).toBool());
haveSwitchDelay(settings().value("hasSwitchDelay", false).toBool());
setSwitchDelay(settings().value("switchDelay", 250).toInt());
haveSwitchDoubleTap(settings().value("hasSwitchDoubleTap", false).toBool());
setSwitchDoubleTap(settings().value("switchDoubleTap", 250).toInt());
setSwitchCornerSize(settings().value("switchCornerSize").toInt());
setDisableLockToScreen(settings().value("disableLockToScreen", false).toBool());
setEnableDragAndDrop(settings().value("enableDragAndDrop", false).toBool());
setClipboardSharingSize(
settings().value("clipboardSharingSize", (int)ServerConfig::defaultClipboardSharingSize()).toULongLong()
);
setClipboardSharing(settings().value("clipboardSharing", true).toBool());
setClientAddress(settings().value("clientAddress", "").toString());
readSettings(settings(), switchCorners(), "switchCorner", 0, static_cast<int>(NumSwitchCorners));
int numScreens = settings().beginReadArray("screens");
Q_ASSERT(numScreens <= screens().size());
for (int i = 0; i < numScreens; i++) {
settings().setArrayIndex(i);
screens()[i].loadSettings(settings());
if (getServerName() == screens()[i].name()) {
screens()[i].markAsServer();
}
}
settings().endArray();
int numHotkeys = settings().beginReadArray("hotkeys");
for (int i = 0; i < numHotkeys; i++) {
settings().setArrayIndex(i);
Hotkey h;
h.loadSettings(settings().get());
hotkeys().append(h);
}
settings().endArray();
settings().endGroup();
}
int ServerConfig::adjacentScreenIndex(int idx, int deltaColumn, int deltaRow) const
{
if (screens()[idx].isNull())
return -1;
// if we're at the left or right end of the table, don't find results going
// further left or right
if ((deltaColumn > 0 && (idx + 1) % numColumns() == 0) || (deltaColumn < 0 && idx % numColumns() == 0))
return -1;
int arrayPos = idx + deltaColumn + deltaRow * numColumns();
if (arrayPos >= screens().size() || arrayPos < 0)
return -1;
return arrayPos;
}
QTextStream &operator<<(QTextStream &outStream, const ServerConfig &config)
{
using enum synergy::gui::ServerProtocol;
outStream << "section: screens" << Qt::endl;
for (const Screen &s : config.screens()) {
if (!s.isNull())
s.writeScreensSection(outStream);
}
outStream << "end" << Qt::endl << Qt::endl;
outStream << "section: aliases" << Qt::endl;
for (const Screen &s : config.screens()) {
if (!s.isNull())
s.writeAliasesSection(outStream);
}
outStream << "end" << Qt::endl << Qt::endl;
outStream << "section: links" << Qt::endl;
for (int i = 0; i < config.screens().size(); i++) {
if (!config.screens()[i].isNull()) {
outStream << "\t" << config.screens()[i].name() << ":" << Qt::endl;
for (unsigned int j = 0; j < sizeof(neighbourDirs) / sizeof(neighbourDirs[0]); j++) {
int idx = config.adjacentScreenIndex(i, neighbourDirs[j].x, neighbourDirs[j].y);
if (idx != -1 && !config.screens()[idx].isNull())
outStream << "\t\t" << neighbourDirs[j].name << " = " << config.screens()[idx].name() << Qt::endl;
}
}
}
outStream << "end" << Qt::endl << Qt::endl;
outStream << "section: options" << Qt::endl;
if (config.hasHeartbeat())
outStream << "\t" << "heartbeat = " << config.heartbeat() << Qt::endl;
if (config.protocol() == kSynergy) {
outStream << "\t" << "protocol = synergy" << Qt::endl;
} else if (config.protocol() == kBarrier) {
outStream << "\t" << "protocol = barrier" << Qt::endl;
} else {
qFatal("unrecognized protocol when writing config");
}
outStream << "\t"
<< "relativeMouseMoves = " << (config.relativeMouseMoves() ? "true" : "false") << Qt::endl;
outStream << "\t"
<< "win32KeepForeground = " << (config.win32KeepForeground() ? "true" : "false") << Qt::endl;
outStream << "\t"
<< "disableLockToScreen = " << (config.disableLockToScreen() ? "true" : "false") << Qt::endl;
outStream << "\t"
<< "clipboardSharing = " << (config.clipboardSharing() ? "true" : "false") << Qt::endl;
outStream << "\t"
<< "clipboardSharingSize = " << config.clipboardSharingSize() << Qt::endl;
if (!config.getClientAddress().isEmpty()) {
outStream << "\t"
<< "clientAddress = " << config.getClientAddress() << Qt::endl;
}
if (config.hasSwitchDelay())
outStream << "\t"
<< "switchDelay = " << config.switchDelay() << Qt::endl;
if (config.hasSwitchDoubleTap())
outStream << "\t"
<< "switchDoubleTap = " << config.switchDoubleTap() << Qt::endl;
outStream << "\t"
<< "switchCorners = none ";
for (int i = 0; i < config.switchCorners().size(); i++)
if (config.switchCorners()[i])
outStream << "+" << config.switchCornerName(i) << " ";
outStream << Qt::endl;
outStream << "\t"
<< "switchCornerSize = " << config.switchCornerSize() << Qt::endl;
for (const Hotkey &hotkey : config.hotkeys())
outStream << hotkey;
outStream << "end" << Qt::endl << Qt::endl;
return outStream;
}
int ServerConfig::numScreens() const
{
int rval = 0;
for (const Screen &s : screens()) {
if (!s.isNull())
rval++;
}
return rval;
}
int ServerConfig::autoAddScreen(const QString name)
{
int serverIndex = -1;
int targetIndex = -1;
if (!findScreenName(m_pAppConfig->screenName(), serverIndex) &&
!fixNoServer(m_pAppConfig->screenName(), serverIndex)) {
return kAutoAddScreenManualServer;
}
if (findScreenName(name, targetIndex)) {
qDebug("ignoring screen already in config: %s", qPrintable(name));
return kAutoAddScreenIgnore;
}
int result = showAddClientDialog(name);
if (result == kAddClientIgnore) {
return kAutoAddScreenIgnore;
}
if (result == kAddClientOther) {
addToFirstEmptyGrid(name);
return kAutoAddScreenManualClient;
}
bool success = false;
int startIndex = serverIndex;
int offset = 1;
int dirIndex = 0;
if (result == kAddClientLeft) {
offset = -1;
dirIndex = 1;
} else if (result == kAddClientUp) {
offset = -5;
dirIndex = 2;
} else if (result == kAddClientDown) {
offset = 5;
dirIndex = 3;
}
int idx = adjacentScreenIndex(startIndex, neighbourDirs[dirIndex].x, neighbourDirs[dirIndex].y);
while (idx != -1) {
if (screens()[idx].isNull()) {
m_Screens[idx].setName(name);
success = true;
break;
}
startIndex += offset;
idx = adjacentScreenIndex(startIndex, neighbourDirs[dirIndex].x, neighbourDirs[dirIndex].y);
}
if (!success) {
addToFirstEmptyGrid(name);
return kAutoAddScreenManualClient;
}
return kAutoAddScreenOk;
}
const QString &ServerConfig::getServerName() const
{
return m_pAppConfig->screenName();
}
void ServerConfig::updateServerName()
{
for (auto &screen : screens()) {
if (screen.isServer()) {
screen.setName(m_pAppConfig->screenName());
break;
}
}
}
const QString &ServerConfig::configFile() const
{
return m_pAppConfig->configFile();
}
bool ServerConfig::useExternalConfig() const
{
return m_pAppConfig->useExternalConfig();
}
bool ServerConfig::isFull() const
{
bool isFull = true;
for (const auto &screen : screens()) {
if (screen.isNull()) {
isFull = false;
break;
}
}
return isFull;
}
bool ServerConfig::screenExists(const QString &screenName) const
{
bool isExists = false;
for (const auto &screen : screens()) {
if (!screen.isNull() && screen.name() == screenName) {
isExists = true;
break;
}
}
return isExists;
}
void ServerConfig::addClient(const QString &clientName)
{
int serverIndex = -1;
if (findScreenName(m_pAppConfig->screenName(), serverIndex)) {
m_Screens[serverIndex].markAsServer();
} else {
fixNoServer(m_pAppConfig->screenName(), serverIndex);
}
m_Screens.addScreenByPriority(Screen(clientName));
}
void ServerConfig::setConfigFile(const QString &configFile)
{
m_pAppConfig->setConfigFile(configFile);
}
void ServerConfig::setUseExternalConfig(bool useExternalConfig)
{
m_pAppConfig->setUseExternalConfig(useExternalConfig);
}
bool ServerConfig::findScreenName(const QString &name, int &index)
{
bool found = false;
for (int i = 0; i < screens().size(); i++) {
if (!screens()[i].isNull() && screens()[i].name().compare(name) == 0) {
index = i;
found = true;
break;
}
}
return found;
}
bool ServerConfig::fixNoServer(const QString &name, int &index)
{
bool fixed = false;
if (screens()[serverDefaultIndex].isNull()) {
m_Screens[serverDefaultIndex].setName(name);
m_Screens[serverDefaultIndex].markAsServer();
index = serverDefaultIndex;
fixed = true;
}
return fixed;
}
int ServerConfig::showAddClientDialog(const QString &clientName)
{
int result = kAddClientIgnore;
if (!m_pMainWindow->isActiveWindow()) {
m_pMainWindow->showNormal();
m_pMainWindow->activateWindow();
}
AddClientDialog addClientDialog(clientName, m_pMainWindow);
addClientDialog.exec();
result = addClientDialog.addResult();
return result;
}
void ::ServerConfig::addToFirstEmptyGrid(const QString &clientName)
{
for (int i = 0; i < screens().size(); i++) {
if (screens()[i].isNull()) {
m_Screens[i].setName(clientName);
break;
}
}
}
size_t ServerConfig::defaultClipboardSharingSize()
{
return 3 * 1024; // 3 MiB
}
size_t ServerConfig::setClipboardSharingSize(size_t size)
{
if (size) {
size += 512; // Round up to the nearest megabyte
size /= 1024;
size *= 1024;
setClipboardSharing(true);
} else {
setClipboardSharing(false);
}
using std::swap;
swap(size, m_ClipboardSharingSize);
return size;
}
void ServerConfig::setClientAddress(const QString &address)
{
if (m_pAppConfig->invertConnection()) {
m_ClientAddress = address;
}
}
QString ServerConfig::getClientAddress() const
{
QString clientAddress;
if (m_pAppConfig->invertConnection()) {
clientAddress = m_ClientAddress.trimmed();
}
return clientAddress;
}
QSettingsProxy &ServerConfig::settings()
{
return m_pAppConfig->scopes().activeSettings();
}
| 16,660
|
C++
|
.cpp
| 474
| 31.227848
| 111
| 0.665174
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
13,756
|
DataDownloader.cpp
|
deskflow_deskflow/src/gui/src/DataDownloader.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2014-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "DataDownloader.h"
DataDownloader::DataDownloader(QObject *parent) : QObject(parent), m_pReply(nullptr), m_IsFinished(false)
{
connect(&m_NetworkManager, &QNetworkAccessManager::finished, this, &DataDownloader::complete);
}
DataDownloader::~DataDownloader()
{
}
void DataDownloader::complete(QNetworkReply *reply)
{
m_Data = reply->readAll();
reply->deleteLater();
m_pReply = nullptr;
if (!m_Data.isEmpty()) {
m_IsFinished = true;
Q_EMIT isComplete();
}
}
QByteArray DataDownloader::data() const
{
return m_Data;
}
void DataDownloader::cancel()
{
if (m_pReply != nullptr) {
m_pReply->abort();
}
}
void DataDownloader::download(QUrl url)
{
QNetworkRequest request(url);
m_pReply = m_NetworkManager.get(request);
}
| 1,455
|
C++
|
.cpp
| 49
| 27.530612
| 105
| 0.747496
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,757
|
SetupWizard.cpp
|
deskflow_deskflow/src/gui/src/SetupWizard.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
*
* SPDX-FileCopyrightText: Copyright (C) 2024 Chris Rizzitello <sithlord48@gmail.com>
* SPDX-FileCopyrightText: Copyright (C) 2012 Symless Ltd.
* SPDX-License-Identifier: GPL-2.0
*/
#include "SetupWizard.h"
#include <QApplication>
#include <QFormLayout>
#include <QPushButton>
#include "common/constants.h"
#include "gui/config/AppConfig.h"
#include "gui/styles.h"
#include "gui/validators/ScreenNameValidator.h"
#include "gui/validators/ValidationError.h"
SetupWizard::SetupWizard(AppConfig &appConfig)
: m_appConfig{appConfig},
m_lblError{new QLabel(this)},
m_lineName{new QLineEdit(this)},
m_btnApply{new QPushButton(tr("Continue"), this)}
{
setWindowTitle(tr("Setup %1").arg(kAppName));
setFixedSize(740, 550);
auto headerFont = QFont(QStringLiteral("Cantarell"), 18, 600);
auto labelTitle = new QLabel(this);
labelTitle->setFont(headerFont);
labelTitle->setText(tr("Name your computer"));
labelTitle->setAlignment(Qt::AlignHCenter | Qt::AlignHCenter);
auto labelName = new QLabel(this);
labelName->setText(tr("Computer Name"));
auto formLayout = new QFormLayout();
formLayout->addRow(labelName, m_lineName);
formLayout->addWidget(m_lblError);
formLayout->addWidget(new QLabel(tr("Call your computer something short and meaningful, but it must have:"), this));
formLayout->addWidget(new QLabel(tr("\t⬤ No spaces"), this));
formLayout->addWidget(new QLabel(tr("\t⬤ Only these special characters: _ - ."), this));
formLayout->addWidget(new QLabel(tr("\t⬤ Only English characters and numbers"), this));
formLayout->addWidget(new QLabel(tr("\t⬤ A different name from other computers"), this));
auto labelImage = new QLabel(this);
labelImage->setPixmap(QPixmap(QStringLiteral(":/image/welcome.png")));
auto mainLayout = new QVBoxLayout();
mainLayout->setContentsMargins(9, 30, 9, 9);
mainLayout->addWidget(labelImage, 0, Qt::AlignHCenter);
mainLayout->addWidget(labelTitle);
mainLayout->addLayout(formLayout);
mainLayout->addSpacerItem(new QSpacerItem(0, 25, QSizePolicy::Fixed, QSizePolicy::Fixed));
mainLayout->addWidget(m_btnApply);
setLayout(mainLayout);
m_lblError->setStyleSheet(deskflow::gui::kStyleErrorActiveLabel);
m_lineName->setText(appConfig.screenName());
m_lineName->setValidator(
new validators::ScreenNameValidator(m_lineName, new validators::ValidationError(this, m_lblError))
);
connect(m_btnApply, &QPushButton::clicked, this, &SetupWizard::accept);
connect(m_lineName, &QLineEdit::textChanged, this, &SetupWizard::nameChanged);
}
void SetupWizard::accept()
{
m_appConfig.setWizardHasRun();
m_appConfig.setScreenName(m_lineName->text());
QDialog::accept();
}
void SetupWizard::nameChanged(const QString &error)
{
m_btnApply->setEnabled(m_lineName->hasAcceptableInput());
}
void SetupWizard::reject()
{
QDialog::reject();
QApplication::exit();
}
| 2,955
|
C++
|
.cpp
| 72
| 38.125
| 118
| 0.753938
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,758
|
TrayIcon.cpp
|
deskflow_deskflow/src/gui/src/TrayIcon.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2021 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "TrayIcon.h"
#include "common/constants.h"
#include "gui/Logger.h"
namespace deskflow::gui {
const auto kShowRetryInterval = 1000;
void TrayIcon::setIcon(const QIcon &icon)
{
m_icon = icon;
if (m_pTrayIcon && !icon.isNull()) {
m_pTrayIcon->setIcon(icon);
}
}
void TrayIcon::showRetryLoop()
{
// HACK: apparently this is needed to create a dbus connection, and the hide
// is needed to make use of the object so the dbus connection doesn't get
// optimized away by the compiler.
// TODO: we should verify that this hack actually works.
QSystemTrayIcon trayIcon;
trayIcon.hide();
if (QSystemTrayIcon::isSystemTrayAvailable()) {
m_pTrayIcon->show();
} else {
// on some platforms, it's not always possible to create the tray when the
// app starts, so keep trying until it is possible.
logVerbose(QString("system tray not ready yet, retrying in %1 ms").arg(kShowRetryInterval));
QTimer::singleShot(kShowRetryInterval, this, &TrayIcon::showRetryLoop);
}
}
void TrayIcon::create(std::vector<QAction *> const &actions)
{
m_pTrayIconMenu = std::make_unique<QMenu>();
for (auto action : actions) {
if (action) {
m_pTrayIconMenu->addAction(action);
} else {
m_pTrayIconMenu->addSeparator();
}
}
m_pTrayIcon = std::make_unique<QSystemTrayIcon>();
setIcon(m_icon);
connect(m_pTrayIcon.get(), &QSystemTrayIcon::activated, this, &TrayIcon::activated);
m_pTrayIcon->setContextMenu(m_pTrayIconMenu.get());
m_pTrayIcon->setToolTip(kAppName);
showRetryLoop();
}
} // namespace deskflow::gui
| 2,273
|
C++
|
.cpp
| 63
| 33.190476
| 96
| 0.732696
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,759
|
KeySequence.cpp
|
deskflow_deskflow/src/gui/src/KeySequence.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2008 Volker Lanz (vl@fidra.de)
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "KeySequence.h"
#include <QSettings>
// this table originally comes from Qt sources (gui/kernel/qkeysequence.cpp)
// and is heavily modified for Deskflow
static const struct
{
int key;
const char *name;
} keyname[] = {
{Qt::Key_Space, "Space"},
{Qt::Key_Escape, "Escape"},
{Qt::Key_Tab, "Tab"},
{Qt::Key_Backtab, "LeftTab"},
{Qt::Key_Backspace, "BackSpace"},
{Qt::Key_Return, "Return"},
{Qt::Key_Insert, "Insert"},
{Qt::Key_Delete, "Delete"},
{Qt::Key_Pause, "Pause"},
{Qt::Key_Print, "Print"},
{Qt::Key_SysReq, "SysReq"},
{Qt::Key_Home, "Home"},
{Qt::Key_End, "End"},
{Qt::Key_Left, "Left"},
{Qt::Key_Up, "Up"},
{Qt::Key_Right, "Right"},
{Qt::Key_Down, "Down"},
{Qt::Key_PageUp, "PageUp"},
{Qt::Key_PageDown, "PageDown"},
{Qt::Key_CapsLock, "CapsLock"},
{Qt::Key_NumLock, "NumLock"},
{Qt::Key_ScrollLock, "ScrollLock"},
{Qt::Key_Menu, "Menu"},
{Qt::Key_Help, "Help"},
{Qt::Key_Enter, "KP_Enter"},
{Qt::Key_Clear, "Clear"},
{Qt::Key_Back, "WWWBack"},
{Qt::Key_Forward, "WWWForward"},
{Qt::Key_Stop, "WWWStop"},
{Qt::Key_Refresh, "WWWRefresh"},
{Qt::Key_VolumeDown, "AudioDown"},
{Qt::Key_VolumeMute, "AudioMute"},
{Qt::Key_VolumeUp, "AudioUp"},
{Qt::Key_MediaPlay, "AudioPlay"},
{Qt::Key_MediaStop, "AudioStop"},
{Qt::Key_MediaPrevious, "AudioPrev"},
{Qt::Key_MediaNext, "AudioNext"},
{Qt::Key_HomePage, "WWWHome"},
{Qt::Key_Favorites, "WWWFavorites"},
{Qt::Key_Search, "WWWSearch"},
{Qt::Key_Standby, "Sleep"},
{Qt::Key_LaunchMail, "AppMail"},
{Qt::Key_LaunchMedia, "AppMedia"},
{Qt::Key_Launch0, "AppUser1"},
{Qt::Key_Launch1, "AppUser2"},
{Qt::Key_Select, "Select"},
{0, 0}
};
KeySequence::KeySequence() : m_Sequence(), m_Modifiers(0), m_IsValid(false)
{
}
bool KeySequence::isMouseButton() const
{
return !m_Sequence.isEmpty() && m_Sequence.last() < Qt::Key_Space;
}
QString KeySequence::toString() const
{
QString result;
for (int i = 0; i < m_Sequence.size(); i++) {
result += keyToString(m_Sequence[i]);
if (i != m_Sequence.size() - 1)
result += "+";
}
return result;
}
bool KeySequence::appendMouseButton(int button)
{
return appendKey(button, 0);
}
bool KeySequence::appendKey(int key, int modifiers)
{
if (m_Sequence.size() == 4)
return true;
switch (key) {
case Qt::Key_AltGr:
return false;
case Qt::Key_Control:
case Qt::Key_Alt:
case Qt::Key_Shift:
case Qt::Key_Meta:
case Qt::Key_Menu: {
int mod = modifiers & (~m_Modifiers);
if (mod) {
m_Sequence.append(mod);
m_Modifiers |= mod;
}
} break;
default:
// see if we can handle this key, if not, don't accept it
if (keyToString(key).isEmpty())
break;
m_Sequence.append(key);
setValid(true);
return true;
}
return false;
}
void KeySequence::loadSettings(QSettings &settings)
{
sequence().clear();
int num = settings.beginReadArray("keys");
for (int i = 0; i < num; i++) {
settings.setArrayIndex(i);
sequence().append(settings.value("key", 0).toInt());
}
settings.endArray();
setModifiers(0);
setValid(true);
}
void KeySequence::saveSettings(QSettings &settings) const
{
settings.beginWriteArray("keys");
for (int i = 0; i < sequence().size(); i++) {
settings.setArrayIndex(i);
settings.setValue("key", sequence()[i]);
}
settings.endArray();
}
QString KeySequence::keyToString(int key)
{
// nothing there?
if (key == 0)
return "";
// a hack to handle mouse buttons as if they were keys
if (key < Qt::Key_Space) {
switch (key) {
case Qt::LeftButton:
return "1";
case Qt::RightButton:
return "2";
case Qt::MiddleButton:
return "3";
}
return "4"; // qt only knows three mouse buttons, so assume it's an unknown
// fourth one
}
// modifiers?
if (key & Qt::ShiftModifier)
return "Shift";
if (key & Qt::ControlModifier)
return "Control";
if (key & Qt::AltModifier)
return "Alt";
if (key & Qt::MetaModifier)
return "Meta";
// treat key pad like normal keys (FIXME: we should have another lookup table
// for keypad keys instead)
key &= ~Qt::KeypadModifier;
// a printable 7 bit character?
if (key < 0x80 && key != Qt::Key_Space)
return QChar(key & 0x7f).toLower();
// a function key?
if (key >= Qt::Key_F1 && key <= Qt::Key_F35)
return QString::fromUtf8("F%1").arg(key - Qt::Key_F1 + 1);
// a special key?
int i = 0;
while (keyname[i].name) {
if (key == keyname[i].key)
return QString::fromUtf8(keyname[i].name);
i++;
}
// representable in ucs2?
if (key < 0x10000)
return QString("\\u%1").arg(QChar(key).toLower().unicode(), 4, 16, QChar('0'));
// give up, deskflow probably won't handle this
return "";
}
bool KeySequence::operator==(const KeySequence &ks) const
{
return m_Sequence == ks.m_Sequence && m_Modifiers == ks.m_Modifiers && m_IsValid == ks.m_IsValid;
}
| 5,794
|
C++
|
.cpp
| 197
| 25.649746
| 99
| 0.640482
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,760
|
Action.cpp
|
deskflow_deskflow/src/gui/src/Action.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2008 Volker Lanz (vl@fidra.de)
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "Action.h"
#include <QSettings>
#include <QTextStream>
const char *Action::m_ActionTypeNames[] = {
"keyDown", "keyUp", "keystroke", "switchToScreen", "switchInDirection", "lockCursorToScreen",
"restartServer", "mouseDown", "mouseUp", "mousebutton"
};
const char *Action::m_SwitchDirectionNames[] = {"left", "right", "up", "down"};
const char *Action::m_LockCursorModeNames[] = {"toggle", "on", "off"};
Action::Action()
: m_KeySequence(),
m_Type(keystroke),
m_TypeScreenNames(),
m_SwitchScreenName(),
m_SwitchDirection(switchLeft),
m_LockCursorMode(lockCursorToggle),
m_ActiveOnRelease(false),
m_HasScreens(false)
{
}
QString Action::text() const
{
QString text = QString(m_ActionTypeNames[keySequence().isMouseButton() ? type() + 6 : type()]) + "(";
switch (type()) {
case keyDown:
case keyUp:
case keystroke: {
text += keySequence().toString();
if (!keySequence().isMouseButton()) {
const QStringList &screens = typeScreenNames();
if (haveScreens() && !screens.isEmpty()) {
text += ",";
for (int i = 0; i < screens.size(); i++) {
text += screens[i];
if (i != screens.size() - 1)
text += ":";
}
} else
text += ",*";
}
} break;
case switchToScreen:
text += switchScreenName();
break;
case switchInDirection:
text += m_SwitchDirectionNames[m_SwitchDirection];
break;
case lockCursorToScreen:
text += m_LockCursorModeNames[m_LockCursorMode];
break;
case restartAllConnections:
text += "restart";
break;
default:
Q_ASSERT(0);
break;
}
text += ")";
return text;
}
void Action::loadSettings(QSettings &settings)
{
keySequence().loadSettings(settings);
setType(settings.value("type", keyDown).toInt());
typeScreenNames().clear();
int numTypeScreens = settings.beginReadArray("typeScreenNames");
for (int i = 0; i < numTypeScreens; i++) {
settings.setArrayIndex(i);
typeScreenNames().append(settings.value("typeScreenName").toString());
}
settings.endArray();
setSwitchScreenName(settings.value("switchScreenName").toString());
setSwitchDirection(settings.value("switchInDirection", switchLeft).toInt());
setLockCursorMode(settings.value("lockCursorToScreen", lockCursorToggle).toInt());
setActiveOnRelease(settings.value("activeOnRelease", false).toBool());
setHaveScreens(settings.value("hasScreens", false).toBool());
setRestartServer(settings.value("restartServer", false).toBool());
}
void Action::saveSettings(QSettings &settings) const
{
keySequence().saveSettings(settings);
settings.setValue("type", type());
settings.beginWriteArray("typeScreenNames");
for (int i = 0; i < typeScreenNames().size(); i++) {
settings.setArrayIndex(i);
settings.setValue("typeScreenName", typeScreenNames()[i]);
}
settings.endArray();
settings.setValue("switchScreenName", switchScreenName());
settings.setValue("switchInDirection", switchDirection());
settings.setValue("lockCursorToScreen", lockCursorMode());
settings.setValue("activeOnRelease", activeOnRelease());
settings.setValue("hasScreens", haveScreens());
settings.setValue("restartServer", restartServer());
}
bool Action::operator==(const Action &a) const
{
return m_KeySequence == a.m_KeySequence && m_Type == a.m_Type && m_TypeScreenNames == a.m_TypeScreenNames &&
m_SwitchScreenName == a.m_SwitchScreenName && m_SwitchDirection == a.m_SwitchDirection &&
m_LockCursorMode == a.m_LockCursorMode && m_ActiveOnRelease == a.m_ActiveOnRelease &&
m_HasScreens == a.m_HasScreens && m_restartServer == a.m_restartServer;
}
QTextStream &operator<<(QTextStream &outStream, const Action &action)
{
if (action.activeOnRelease())
outStream << ";";
outStream << action.text();
return outStream;
}
| 4,636
|
C++
|
.cpp
| 126
| 32.920635
| 110
| 0.700557
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,761
|
ScreenSetupModel.cpp
|
deskflow_deskflow/src/gui/src/ScreenSetupModel.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012 Symless Ltd.
* Copyright (C) 2008 Volker Lanz (vl@fidra.de)
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "ScreenSetupModel.h"
#include <QIODevice>
#include <QIcon>
#include <QMimeData>
#include "gui/config/Screen.h"
const QString ScreenSetupModel::m_MimeType = "application/x-deskflow-screen";
ScreenSetupModel::ScreenSetupModel(ScreenList &screens, int numColumns, int numRows)
: QAbstractTableModel(NULL),
m_Screens(screens),
m_NumColumns(numColumns),
m_NumRows(numRows)
{
// bound rows and columns to prevent multiply overflow.
// this is unlikely to happen, as the grid size is only 3x9.
if (m_NumColumns > 100 || m_NumRows > 100) {
qFatal("grid size out of bounds: %d columns x %d rows", m_NumColumns, m_NumRows);
return;
}
const long span = static_cast<long>(m_NumColumns) * m_NumRows;
if (span > screens.size()) {
qFatal("scrren list (%lld) too small for %d columns x %d rows", screens.size(), m_NumColumns, m_NumRows);
}
}
QVariant ScreenSetupModel::data(const QModelIndex &index, int role) const
{
if (index.isValid() && index.row() < m_NumRows && index.column() < m_NumColumns) {
switch (role) {
case Qt::DecorationRole:
if (screen(index).isNull())
break;
return QIcon(screen(index).pixmap());
case Qt::ToolTipRole:
if (screen(index).isNull())
break;
return QString(tr("<center>Screen: <b>%1</b></center>"
"<br>Double click to edit settings"
"<br>Drag screen to the trashcan to remove it"))
.arg(screen(index).name());
case Qt::DisplayRole:
if (screen(index).isNull())
break;
return screen(index).name();
}
}
return QVariant();
}
Qt::ItemFlags ScreenSetupModel::flags(const QModelIndex &index) const
{
if (!index.isValid() || index.row() >= m_NumRows || index.column() >= m_NumColumns)
return Qt::NoItemFlags;
if (!screen(index).isNull())
return Qt::ItemIsEnabled | Qt::ItemIsDragEnabled | Qt::ItemIsSelectable | Qt::ItemIsDropEnabled;
return Qt::ItemIsDropEnabled;
}
Qt::DropActions ScreenSetupModel::supportedDropActions() const
{
return Qt::MoveAction | Qt::CopyAction;
}
QStringList ScreenSetupModel::mimeTypes() const
{
return QStringList() << m_MimeType;
}
QMimeData *ScreenSetupModel::mimeData(const QModelIndexList &indexes) const
{
QMimeData *pMimeData = new QMimeData();
QByteArray encodedData;
QDataStream stream(&encodedData, QIODevice::WriteOnly);
for (const QModelIndex &index : indexes) {
if (index.isValid())
stream << index.column() << index.row() << screen(index);
}
pMimeData->setData(m_MimeType, encodedData);
return pMimeData;
}
bool ScreenSetupModel::dropMimeData(
const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent
)
{
if (action == Qt::IgnoreAction)
return true;
if (!data->hasFormat(m_MimeType))
return false;
if (!parent.isValid() || row != -1 || column != -1)
return false;
QByteArray encodedData = data->data(m_MimeType);
QDataStream stream(&encodedData, QIODevice::ReadOnly);
int sourceColumn = -1;
int sourceRow = -1;
stream >> sourceColumn;
stream >> sourceRow;
// don't drop screen onto itself
if (sourceColumn == parent.column() && sourceRow == parent.row())
return false;
Screen droppedScreen;
stream >> droppedScreen;
auto oldScreen = Screen(screen(parent.column(), parent.row()));
if (!oldScreen.isNull() && sourceColumn != -1 && sourceRow != -1) {
// mark the screen so it isn't deleted after the dragndrop succeeded
// see ScreenSetupView::startDrag()
oldScreen.setSwapped(true);
screen(sourceColumn, sourceRow) = oldScreen;
}
screen(parent.column(), parent.row()) = droppedScreen;
Q_EMIT screensChanged();
return true;
}
void ScreenSetupModel::addScreen(const Screen &newScreen)
{
m_Screens.addScreenByPriority(newScreen);
Q_EMIT screensChanged();
}
bool ScreenSetupModel::isFull() const
{
auto emptyScreen =
std::find_if(m_Screens.cbegin(), m_Screens.cend(), [](const Screen &item) { return item.isNull(); });
return (emptyScreen == m_Screens.cend());
}
| 4,842
|
C++
|
.cpp
| 134
| 32.343284
| 109
| 0.704623
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,762
|
ActionDialog.cpp
|
deskflow_deskflow/src/gui/src/dialogs/ActionDialog.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2008 Volker Lanz (vl@fidra.de)
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "ActionDialog.h"
#include "ui_ActionDialog.h"
#include "Action.h"
#include "Hotkey.h"
#include "KeySequence.h"
#include "ServerConfig.h"
#include <QButtonGroup>
ActionDialog::ActionDialog(QWidget *parent, ServerConfig &config, Hotkey &hotkey, Action &action)
: QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint),
ui{std::make_unique<Ui::ActionDialog>()},
m_ServerConfig(config),
m_Hotkey(hotkey),
m_Action(action),
m_pButtonGroupType(new QButtonGroup(this))
{
ui->setupUi(this);
// work around Qt Designer's lack of a QButtonGroup; we need it to get
// at the button id of the checked radio button
QRadioButton *const typeButtons[] = {
ui->m_pRadioPress,
ui->m_pRadioRelease,
ui->m_pRadioPressAndRelease,
ui->m_pRadioSwitchToScreen,
ui->m_pRadioSwitchInDirection,
ui->m_pRadioLockCursorToScreen,
ui->m_pRadioRestartAllConnections
};
for (unsigned int i = 0; i < sizeof(typeButtons) / sizeof(typeButtons[0]); i++)
m_pButtonGroupType->addButton(typeButtons[i], i);
ui->m_pKeySequenceWidgetHotkey->setText(m_Action.keySequence().toString());
ui->m_pKeySequenceWidgetHotkey->setKeySequence(m_Action.keySequence());
m_pButtonGroupType->button(m_Action.type())->setChecked(true);
ui->m_pComboSwitchInDirection->setCurrentIndex(m_Action.switchDirection());
ui->m_pComboLockCursorToScreen->setCurrentIndex(m_Action.lockCursorMode());
if (m_Action.activeOnRelease())
ui->m_pRadioHotkeyReleased->setChecked(true);
else
ui->m_pRadioHotkeyPressed->setChecked(true);
ui->m_pGroupBoxScreens->setChecked(m_Action.haveScreens());
int idx = 0;
for (const Screen &screen : serverConfig().screens()) {
if (!screen.isNull()) {
QListWidgetItem *pListItem = new QListWidgetItem(screen.name());
ui->m_pListScreens->addItem(pListItem);
if (m_Action.typeScreenNames().indexOf(screen.name()) != -1)
ui->m_pListScreens->setCurrentItem(pListItem);
ui->m_pComboSwitchToScreen->addItem(screen.name());
if (screen.name() == m_Action.switchScreenName())
ui->m_pComboSwitchToScreen->setCurrentIndex(idx);
idx++;
}
}
}
void ActionDialog::accept()
{
if (!sequenceWidget()->valid() && m_pButtonGroupType->checkedId() >= 0 && m_pButtonGroupType->checkedId() < 3)
return;
m_Action.setKeySequence(sequenceWidget()->keySequence());
m_Action.setType(m_pButtonGroupType->checkedId());
m_Action.setHaveScreens(ui->m_pGroupBoxScreens->isChecked());
m_Action.typeScreenNames().clear();
const auto &selection = ui->m_pListScreens->selectedItems();
for (const QListWidgetItem *pItem : selection)
m_Action.typeScreenNames().append(pItem->text());
m_Action.setSwitchScreenName(ui->m_pComboSwitchToScreen->currentText());
m_Action.setSwitchDirection(ui->m_pComboSwitchInDirection->currentIndex());
m_Action.setLockCursorMode(ui->m_pComboLockCursorToScreen->currentIndex());
m_Action.setActiveOnRelease(ui->m_pRadioHotkeyReleased->isChecked());
m_Action.setRestartServer(ui->m_pRadioRestartAllConnections->isChecked());
QDialog::accept();
}
void ActionDialog::on_m_pKeySequenceWidgetHotkey_keySequenceChanged()
{
if (sequenceWidget()->keySequence().isMouseButton()) {
ui->m_pGroupBoxScreens->setEnabled(false);
ui->m_pListScreens->setEnabled(false);
} else {
ui->m_pGroupBoxScreens->setEnabled(true);
ui->m_pListScreens->setEnabled(true);
}
}
const KeySequenceWidget *ActionDialog::sequenceWidget() const
{
return ui->m_pKeySequenceWidgetHotkey;
}
ActionDialog::~ActionDialog() = default;
| 4,360
|
C++
|
.cpp
| 103
| 38.640777
| 112
| 0.739141
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,763
|
ScreenSettingsDialog.cpp
|
deskflow_deskflow/src/gui/src/dialogs/ScreenSettingsDialog.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012 Symless Ltd.
* Copyright (C) 2008 Volker Lanz (vl@fidra.de)
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "ScreenSettingsDialog.h"
#include "ui_ScreenSettingsDialog.h"
#include "gui/config/Screen.h"
#include "gui/styles.h"
#include "gui/validators/AliasValidator.h"
#include "gui/validators/ScreenNameValidator.h"
#include "gui/validators/ValidationError.h"
#include <QMessageBox>
using namespace deskflow::gui;
using enum ScreenConfig::Modifier;
using enum ScreenConfig::SwitchCorner;
using enum ScreenConfig::Fix;
ScreenSettingsDialog::~ScreenSettingsDialog() = default;
ScreenSettingsDialog::ScreenSettingsDialog(QWidget *parent, Screen *pScreen, const ScreenList *pScreens)
: QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint),
ui_{std::make_unique<Ui::ScreenSettingsDialog>()},
m_pScreen(pScreen)
{
ui_->setupUi(this);
ui_->m_pLabelAliasError->setStyleSheet(kStyleErrorActiveLabel);
ui_->m_pLabelNameError->setStyleSheet(kStyleErrorActiveLabel);
ui_->m_pLineEditName->setText(m_pScreen->name());
ui_->m_pLineEditName->setValidator(new validators::ScreenNameValidator(
ui_->m_pLineEditName, new validators::ValidationError(this, ui_->m_pLabelNameError), pScreens
));
ui_->m_pLineEditName->selectAll();
ui_->m_pLineEditAlias->setValidator(new validators::AliasValidator(
ui_->m_pLineEditAlias, new validators::ValidationError(this, ui_->m_pLabelAliasError)
));
for (int i = 0; i < m_pScreen->aliases().count(); i++)
new QListWidgetItem(m_pScreen->aliases()[i], ui_->m_pListAliases);
ui_->m_pComboBoxShift->setCurrentIndex(m_pScreen->modifier(static_cast<int>(Shift)));
ui_->m_pComboBoxCtrl->setCurrentIndex(m_pScreen->modifier(static_cast<int>(Ctrl)));
ui_->m_pComboBoxAlt->setCurrentIndex(m_pScreen->modifier(static_cast<int>(Alt)));
ui_->m_pComboBoxMeta->setCurrentIndex(m_pScreen->modifier(static_cast<int>(Meta)));
ui_->m_pComboBoxSuper->setCurrentIndex(m_pScreen->modifier(static_cast<int>(Super)));
ui_->m_pCheckBoxCornerTopLeft->setChecked(m_pScreen->switchCorner(static_cast<int>(TopLeft)));
ui_->m_pCheckBoxCornerTopRight->setChecked(m_pScreen->switchCorner(static_cast<int>(TopRight)));
ui_->m_pCheckBoxCornerBottomLeft->setChecked(m_pScreen->switchCorner(static_cast<int>(BottomLeft)));
ui_->m_pCheckBoxCornerBottomRight->setChecked(m_pScreen->switchCorner(static_cast<int>(BottomRight)));
ui_->m_pSpinBoxSwitchCornerSize->setValue(m_pScreen->switchCornerSize());
ui_->m_pCheckBoxCapsLock->setChecked(m_pScreen->fix(CapsLock));
ui_->m_pCheckBoxNumLock->setChecked(m_pScreen->fix(NumLock));
ui_->m_pCheckBoxScrollLock->setChecked(m_pScreen->fix(ScrollLock));
ui_->m_pCheckBoxXTest->setChecked(m_pScreen->fix(XTest));
}
void ScreenSettingsDialog::accept()
{
if (ui_->m_pLineEditName->text().isEmpty()) {
QMessageBox::warning(
this, tr("Screen name is empty"),
tr("The screen name cannot be empty. "
"Please either fill in a name or cancel the dialog.")
);
return;
} else if (!ui_->m_pLabelNameError->text().isEmpty()) {
return;
}
m_pScreen->init();
m_pScreen->setName(ui_->m_pLineEditName->text());
for (int i = 0; i < ui_->m_pListAliases->count(); i++) {
QString alias(ui_->m_pListAliases->item(i)->text());
if (alias == ui_->m_pLineEditName->text()) {
QMessageBox::warning(
this, tr("Screen name matches alias"),
tr("The screen name cannot be the same as an alias. "
"Please either remove the alias or change the screen name.")
);
return;
}
m_pScreen->addAlias(alias);
}
m_pScreen->setModifier(static_cast<int>(Shift), ui_->m_pComboBoxShift->currentIndex());
m_pScreen->setModifier(static_cast<int>(Ctrl), ui_->m_pComboBoxCtrl->currentIndex());
m_pScreen->setModifier(static_cast<int>(Alt), ui_->m_pComboBoxAlt->currentIndex());
m_pScreen->setModifier(static_cast<int>(Meta), ui_->m_pComboBoxMeta->currentIndex());
m_pScreen->setModifier(static_cast<int>(Super), ui_->m_pComboBoxSuper->currentIndex());
m_pScreen->setSwitchCorner(static_cast<int>(TopLeft), ui_->m_pCheckBoxCornerTopLeft->isChecked());
m_pScreen->setSwitchCorner(static_cast<int>(TopRight), ui_->m_pCheckBoxCornerTopRight->isChecked());
m_pScreen->setSwitchCorner(static_cast<int>(BottomLeft), ui_->m_pCheckBoxCornerBottomLeft->isChecked());
m_pScreen->setSwitchCorner(static_cast<int>(BottomRight), ui_->m_pCheckBoxCornerBottomRight->isChecked());
m_pScreen->setSwitchCornerSize(ui_->m_pSpinBoxSwitchCornerSize->value());
m_pScreen->setFix(static_cast<int>(CapsLock), ui_->m_pCheckBoxCapsLock->isChecked());
m_pScreen->setFix(static_cast<int>(NumLock), ui_->m_pCheckBoxNumLock->isChecked());
m_pScreen->setFix(static_cast<int>(ScrollLock), ui_->m_pCheckBoxScrollLock->isChecked());
m_pScreen->setFix(static_cast<int>(XTest), ui_->m_pCheckBoxXTest->isChecked());
QDialog::accept();
}
void ScreenSettingsDialog::on_m_pButtonAddAlias_clicked()
{
if (!ui_->m_pLineEditAlias->text().isEmpty() &&
ui_->m_pListAliases->findItems(ui_->m_pLineEditAlias->text(), Qt::MatchFixedString).isEmpty()) {
new QListWidgetItem(ui_->m_pLineEditAlias->text(), ui_->m_pListAliases);
ui_->m_pLineEditAlias->clear();
}
}
void ScreenSettingsDialog::on_m_pLineEditAlias_textChanged(const QString &text)
{
ui_->m_pButtonAddAlias->setEnabled(!text.isEmpty() && ui_->m_pLabelAliasError->text().isEmpty());
}
void ScreenSettingsDialog::on_m_pButtonRemoveAlias_clicked()
{
QList<QListWidgetItem *> items = ui_->m_pListAliases->selectedItems();
for (int i = 0; i < items.count(); i++)
delete items[i];
}
void ScreenSettingsDialog::on_m_pListAliases_itemSelectionChanged()
{
ui_->m_pButtonRemoveAlias->setEnabled(!ui_->m_pListAliases->selectedItems().isEmpty());
}
| 6,454
|
C++
|
.cpp
| 127
| 47.401575
| 108
| 0.735556
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,764
|
AboutDialog.cpp
|
deskflow_deskflow/src/gui/src/dialogs/AboutDialog.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Chris Rizzitello <sithlord48@gmail.com>
* Copyright (C) 2012 Symless Ltd.
* Copyright (C) 2008 Volker Lanz (vl@fidra.de)
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "AboutDialog.h"
#include "common/copyright.h"
#include "common/version.h"
#include "gui/style_utils.h"
#include <QClipboard>
#include <QDateTime>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QStyle>
AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent)
{
setWindowTitle(tr("About Deskflow"));
QString version = QString::fromStdString(deskflow::version());
auto copyIcon = QIcon::fromTheme(
QIcon::ThemeIcon::EditCopy, deskflow::gui::isDarkMode() ? QIcon(s_darkCopy) : QIcon(s_lightCopy)
);
auto btnCopyVersion = new QPushButton(copyIcon, QString(), this);
btnCopyVersion->setFlat(true);
connect(btnCopyVersion, &QPushButton::clicked, this, [version] { qApp->clipboard()->setText(version); });
auto versionLayout = new QHBoxLayout();
versionLayout->addWidget(new QLabel(tr("Version:")));
versionLayout->addWidget(new QLabel(version));
versionLayout->addWidget(btnCopyVersion);
versionLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Fixed));
auto lblLogo = new QLabel(this);
lblLogo->setPixmap(deskflow::gui::isDarkMode() ? s_darkLogo : s_lightLogo);
auto lblCopyright = new QLabel(QString::fromStdString(deskflow::kCopyright));
auto boldFont = font();
boldFont.setBold(true);
auto lblDevsTitle = new QLabel(tr("Important developers"));
lblDevsTitle->setFont(boldFont);
auto lblDevsBody = new QLabel(QStringLiteral("%1\n").arg(s_awesomeDevs.join(", ")));
lblDevsBody->setWordWrap(true);
auto btnOk = new QPushButton(tr("Ok"), this);
btnOk->setDefault(true);
connect(btnOk, &QPushButton::clicked, this, [this] { close(); });
auto mainLayout = new QVBoxLayout();
mainLayout->addWidget(lblLogo);
mainLayout->addLayout(versionLayout);
mainLayout->addWidget(new QLabel(tr("Keyboard and mouse sharing application"), this));
mainLayout->addWidget(lblCopyright);
mainLayout->addWidget(lblDevsTitle);
mainLayout->addWidget(lblDevsBody);
mainLayout->addWidget(btnOk);
setLayout(mainLayout);
adjustSize();
setFixedSize(size());
}
| 2,882
|
C++
|
.cpp
| 67
| 40.38806
| 107
| 0.754555
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,765
|
SettingsDialog.cpp
|
deskflow_deskflow/src/gui/src/dialogs/SettingsDialog.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012 Symless Ltd.
* Copyright (C) 2008 Volker Lanz (vl@fidra.de)
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "SettingsDialog.h"
#include "ui_SettingsDialog.h"
#include "gui/core/CoreProcess.h"
#include "gui/messages.h"
#include "gui/tls/TlsCertificate.h"
#include "gui/tls/TlsUtility.h"
#include "gui/validators/ScreenNameValidator.h"
#include "gui/validators/ValidationError.h"
#include "gui_config.h" // IWYU pragma: keep
#ifdef DESKFLOW_GUI_HOOK_HEADER
#include DESKFLOW_GUI_HOOK_HEADER
#endif
#include <QDir>
#include <QFileDialog>
#include <QMessageBox>
using namespace deskflow::gui;
SettingsDialog::SettingsDialog(
QWidget *parent, AppConfig &appConfig, const IServerConfig &serverConfig, const CoreProcess &coreProcess
)
: QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint),
ui{std::make_unique<Ui::SettingsDialog>()},
m_appConfig(appConfig),
m_serverConfig(serverConfig),
m_coreProcess(coreProcess),
m_tlsUtility(appConfig)
{
ui->setupUi(this);
const auto folderIcon =
QIcon::fromTheme(QIcon::ThemeIcon::DocumentOpen, QIcon(QStringLiteral(":/icons/64x64/folder.png")));
ui->m_pPushButtonTlsCertPath->setIcon(folderIcon);
ui->m_pButtonBrowseLog->setIcon(folderIcon);
// force the first tab, since qt creator sets the active tab as the last one
// the developer was looking at, and it's easy to accidentally save that.
ui->m_pTabWidget->setCurrentIndex(0);
loadFromConfig();
m_wasOriginallySystemScope = m_appConfig.isActiveScopeSystem();
updateControls();
m_pScreenNameError = new validators::ValidationError(this);
ui->m_pLineEditScreenName->setValidator(
new validators::ScreenNameValidator(ui->m_pLineEditScreenName, m_pScreenNameError, &serverConfig.screens())
);
connect(ui->m_pCheckBoxEnableTls, &QCheckBox::toggled, this, &SettingsDialog::updateTlsControlsEnabled);
connect(
this, &SettingsDialog::shown, this,
[this] {
if (!m_appConfig.isActiveScopeWritable()) {
showReadOnlyMessage();
}
},
Qt::QueuedConnection
);
#ifdef DESKFLOW_GUI_HOOK_SETTINGS
DESKFLOW_GUI_HOOK_SETTINGS
#endif
}
//
// Auto-connect slots
//
void SettingsDialog::on_m_pCheckBoxLogToFile_stateChanged(int i)
{
bool checked = i == 2;
ui->m_pLabelLogPath->setEnabled(checked);
ui->m_pLineEditLogFilename->setEnabled(checked);
ui->m_pButtonBrowseLog->setEnabled(checked);
}
void SettingsDialog::on_m_pButtonBrowseLog_clicked()
{
QString fileName = QFileDialog::getSaveFileName(
this, tr("Save log file to..."), ui->m_pLineEditLogFilename->text(), "Logs (*.log *.txt)"
);
if (!fileName.isEmpty()) {
ui->m_pLineEditLogFilename->setText(fileName);
}
}
void SettingsDialog::on_m_pCheckBoxEnableTls_clicked(bool)
{
updateTlsControlsEnabled();
}
void SettingsDialog::on_m_pRadioSystemScope_toggled(bool checked)
{
// We only need to test the System scoped Radio as they are connected
m_appConfig.setLoadFromSystemScope(checked);
loadFromConfig();
updateControls();
if (isVisible() && !m_appConfig.isActiveScopeWritable()) {
showReadOnlyMessage();
}
}
void SettingsDialog::on_m_pPushButtonTlsCertPath_clicked()
{
QString fileName = QFileDialog::getSaveFileName(
this, tr("Select a TLS certificate to use..."), ui->m_pLineEditTlsCertPath->text(), "Cert (*.pem)", nullptr,
QFileDialog::DontConfirmOverwrite
);
if (!fileName.isEmpty()) {
ui->m_pLineEditTlsCertPath->setText(fileName);
if (QFile(fileName).exists()) {
updateKeyLengthOnFile(fileName);
} else {
qDebug("no tls certificate file at: %s", qUtf8Printable(fileName));
}
}
}
void SettingsDialog::on_m_pPushButtonTlsRegenCert_clicked()
{
if (m_tlsUtility.generateCertificate()) {
QMessageBox::information(this, tr("TLS Certificate Regenerated"), tr("TLS certificate regenerated successfully."));
}
}
void SettingsDialog::on_m_pCheckBoxServiceEnabled_toggled(bool)
{
updateControls();
}
//
// End of auto-connect slots
//
void SettingsDialog::showEvent(QShowEvent *event)
{
QDialog::showEvent(event);
Q_EMIT shown();
}
void SettingsDialog::showReadOnlyMessage()
{
const auto activeScopeFilename = m_appConfig.scopes().activeFilePath();
messages::showReadOnlySettings(this, activeScopeFilename);
}
void SettingsDialog::accept()
{
if (!ui->m_pLineEditScreenName->hasAcceptableInput()) {
QMessageBox::warning(this, tr("Invalid screen name"), m_pScreenNameError->message());
return;
}
m_appConfig.setLoadFromSystemScope(ui->m_pRadioSystemScope->isChecked());
m_appConfig.setScreenName(ui->m_pLineEditScreenName->text());
m_appConfig.setPort(ui->m_pSpinBoxPort->value());
m_appConfig.setNetworkInterface(ui->m_pLineEditInterface->text());
m_appConfig.setLogLevel(ui->m_pComboLogLevel->currentIndex());
m_appConfig.setLogToFile(ui->m_pCheckBoxLogToFile->isChecked());
m_appConfig.setLogFilename(ui->m_pLineEditLogFilename->text());
m_appConfig.setElevateMode(static_cast<ElevateMode>(ui->m_pComboElevate->currentIndex()));
m_appConfig.setAutoHide(ui->m_pCheckBoxAutoHide->isChecked());
m_appConfig.setEnableUpdateCheck(ui->m_pCheckBoxAutoUpdate->isChecked());
m_appConfig.setPreventSleep(ui->m_pCheckBoxPreventSleep->isChecked());
m_appConfig.setTlsCertPath(ui->m_pLineEditTlsCertPath->text());
m_appConfig.setTlsKeyLength(ui->m_pComboBoxTlsKeyLength->currentText().toInt());
m_appConfig.setTlsEnabled(ui->m_pCheckBoxEnableTls->isChecked());
m_appConfig.setLanguageSync(ui->m_pCheckBoxLanguageSync->isChecked());
m_appConfig.setInvertScrollDirection(ui->m_pCheckBoxScrollDirection->isChecked());
m_appConfig.setEnableService(ui->m_pCheckBoxServiceEnabled->isChecked());
m_appConfig.setCloseToTray(ui->m_pCheckBoxCloseToTray->isChecked());
m_appConfig.setInvertConnection(ui->m_pInvertConnection->isChecked());
QDialog::accept();
}
void SettingsDialog::reject()
{
// restore original system scope value on reject.
if (m_appConfig.isActiveScopeSystem() != m_wasOriginallySystemScope) {
m_appConfig.setLoadFromSystemScope(m_wasOriginallySystemScope);
}
QDialog::reject();
}
void SettingsDialog::loadFromConfig()
{
ui->m_pLineEditScreenName->setText(m_appConfig.screenName());
ui->m_pSpinBoxPort->setValue(m_appConfig.port());
ui->m_pLineEditInterface->setText(m_appConfig.networkInterface());
ui->m_pComboLogLevel->setCurrentIndex(m_appConfig.logLevel());
ui->m_pCheckBoxLogToFile->setChecked(m_appConfig.logToFile());
ui->m_pLineEditLogFilename->setText(m_appConfig.logFilename());
ui->m_pCheckBoxAutoHide->setChecked(m_appConfig.autoHide());
ui->m_pCheckBoxPreventSleep->setChecked(m_appConfig.preventSleep());
ui->m_pCheckBoxLanguageSync->setChecked(m_appConfig.languageSync());
ui->m_pCheckBoxScrollDirection->setChecked(m_appConfig.invertScrollDirection());
ui->m_pCheckBoxServiceEnabled->setChecked(m_appConfig.enableService());
ui->m_pCheckBoxCloseToTray->setChecked(m_appConfig.closeToTray());
ui->m_pComboElevate->setCurrentIndex(static_cast<int>(m_appConfig.elevateMode()));
if (m_appConfig.enableUpdateCheck().has_value()) {
ui->m_pCheckBoxAutoUpdate->setChecked(m_appConfig.enableUpdateCheck().value());
} else {
ui->m_pCheckBoxAutoUpdate->setChecked(false);
}
if (m_appConfig.isActiveScopeSystem()) {
ui->m_pRadioSystemScope->setChecked(true);
} else {
ui->m_pRadioUserScope->setChecked(true);
}
ui->m_pInvertConnection->setChecked(m_appConfig.invertConnection());
updateTlsControls();
}
void SettingsDialog::updateTlsControls()
{
if (QFile(m_appConfig.tlsCertPath()).exists()) {
updateKeyLengthOnFile(m_appConfig.tlsCertPath());
} else {
const auto keyLengthText = QString::number(m_appConfig.tlsKeyLength());
ui->m_pComboBoxTlsKeyLength->setCurrentIndex(ui->m_pComboBoxTlsKeyLength->findText(keyLengthText));
}
const auto tlsEnabled = m_tlsUtility.isEnabled();
const auto writable = m_appConfig.isActiveScopeWritable();
ui->m_pCheckBoxEnableTls->setEnabled(writable);
ui->m_pCheckBoxEnableTls->setChecked(writable && tlsEnabled);
ui->m_pLineEditTlsCertPath->setText(m_appConfig.tlsCertPath());
}
void SettingsDialog::updateTlsControlsEnabled()
{
const auto writable = m_appConfig.isActiveScopeWritable();
const auto clientMode = m_appConfig.clientGroupChecked();
const auto tlsChecked = ui->m_pCheckBoxEnableTls->isChecked();
auto enabled = writable && tlsChecked && !clientMode;
ui->m_pLabelTlsKeyLength->setEnabled(enabled);
ui->m_pComboBoxTlsKeyLength->setEnabled(enabled);
ui->m_pLabelTlsCert->setEnabled(enabled);
ui->m_pLineEditTlsCertPath->setEnabled(enabled);
ui->m_pPushButtonTlsCertPath->setEnabled(enabled);
ui->m_pPushButtonTlsRegenCert->setEnabled(enabled);
}
bool SettingsDialog::isClientMode() const
{
return m_coreProcess.mode() == deskflow::gui::CoreProcess::Mode::Client;
}
void SettingsDialog::updateKeyLengthOnFile(const QString &path)
{
TlsCertificate ssl;
if (!QFile(path).exists()) {
qFatal("tls certificate file not found: %s", qUtf8Printable(path));
}
auto length = ssl.getCertKeyLength(path);
auto index = ui->m_pComboBoxTlsKeyLength->findText(QString::number(length));
ui->m_pComboBoxTlsKeyLength->setCurrentIndex(index);
m_appConfig.setTlsKeyLength(length);
}
void SettingsDialog::updateControls()
{
#if defined(Q_OS_WIN)
const auto serviceAvailable = true;
#else
// service not supported on unix yet, so always disable.
const auto serviceAvailable = false;
ui->m_pGroupService->setTitle("Service (Windows only)");
#endif
const bool writable = m_appConfig.isActiveScopeWritable();
const bool serviceChecked = ui->m_pCheckBoxServiceEnabled->isChecked();
const bool logToFile = ui->m_pCheckBoxLogToFile->isChecked();
ui->m_pLineEditScreenName->setEnabled(writable);
ui->m_pSpinBoxPort->setEnabled(writable);
ui->m_pLineEditInterface->setEnabled(writable);
ui->m_pComboLogLevel->setEnabled(writable);
ui->m_pCheckBoxLogToFile->setEnabled(writable);
ui->m_pCheckBoxAutoHide->setEnabled(writable);
ui->m_pCheckBoxAutoUpdate->setEnabled(writable);
ui->m_pCheckBoxPreventSleep->setEnabled(writable);
ui->m_pLineEditTlsCertPath->setEnabled(writable);
ui->m_pComboBoxTlsKeyLength->setEnabled(writable);
ui->m_pCheckBoxCloseToTray->setEnabled(writable);
ui->m_pCheckBoxServiceEnabled->setEnabled(writable && serviceAvailable);
ui->m_pLabelElevate->setEnabled(writable && serviceChecked && serviceAvailable);
ui->m_pComboElevate->setEnabled(writable && serviceChecked && serviceAvailable);
ui->m_pCheckBoxLanguageSync->setEnabled(writable && isClientMode());
ui->m_pCheckBoxScrollDirection->setEnabled(writable && isClientMode());
ui->m_pLabelLogPath->setEnabled(writable && logToFile);
ui->m_pLineEditLogFilename->setEnabled(writable && logToFile);
ui->m_pButtonBrowseLog->setEnabled(writable && logToFile);
updateTlsControls();
}
SettingsDialog::~SettingsDialog() = default;
| 11,623
|
C++
|
.cpp
| 282
| 38.219858
| 119
| 0.766885
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,766
|
ServerConfigDialog.cpp
|
deskflow_deskflow/src/gui/src/dialogs/ServerConfigDialog.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2008 Volker Lanz (vl@fidra.de)
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "ServerConfigDialog.h"
#include "ui_ServerConfigDialog.h"
#include "common/constants.h"
#include "dialogs/ActionDialog.h"
#include "dialogs/HotkeyDialog.h"
#include "dialogs/ScreenSettingsDialog.h"
#include "ServerConfig.h"
#include <QFileDialog>
#include <QMessageBox>
using enum ScreenConfig::SwitchCorner;
using ServerProtocol = synergy::gui::ServerProtocol;
ServerConfigDialog::ServerConfigDialog(QWidget *parent, ServerConfig &config, AppConfig &appConfig)
: QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint),
ui{std::make_unique<Ui::ServerConfigDialog>()},
m_OriginalServerConfig(config),
m_OriginalServerConfigIsExternal(config.useExternalConfig()),
m_OriginalServerConfigUsesExternalFile(config.configFile()),
m_ServerConfig(config),
m_ScreenSetupModel(serverConfig().screens(), serverConfig().numColumns(), serverConfig().numRows()),
m_Message(""),
m_appConfig(appConfig)
{
ui->setupUi(this);
const auto folderIcon =
QIcon::fromTheme(QIcon::ThemeIcon::DocumentOpen, QIcon(QStringLiteral(":/icons/64x64/folder.png")));
ui->m_pButtonBrowseConfigFile->setIcon(folderIcon);
// force the first tab, since qt creator sets the active tab as the last one
// the developer was looking at, and it's easy to accidentally save that.
ui->m_pTabWidget->setCurrentIndex(0);
ui->m_pEditConfigFile->setText(serverConfig().configFile());
ui->m_pCheckBoxUseExternalConfig->setChecked(serverConfig().useExternalConfig());
ui->m_pCheckBoxHeartbeat->setChecked(serverConfig().hasHeartbeat());
ui->m_pRadioProtocolSynergy->setChecked(serverConfig().protocol() == ServerProtocol::kSynergy);
ui->m_pRadioProtocolBarrier->setChecked(serverConfig().protocol() == ServerProtocol::kBarrier);
ui->m_pSpinBoxHeartbeat->setValue(serverConfig().heartbeat());
ui->m_pCheckBoxRelativeMouseMoves->setChecked(serverConfig().relativeMouseMoves());
ui->m_pCheckBoxWin32KeepForeground->setChecked(serverConfig().win32KeepForeground());
ui->m_pCheckBoxSwitchDelay->setChecked(serverConfig().hasSwitchDelay());
ui->m_pSpinBoxSwitchDelay->setValue(serverConfig().switchDelay());
ui->m_pCheckBoxSwitchDoubleTap->setChecked(serverConfig().hasSwitchDoubleTap());
ui->m_pSpinBoxSwitchDoubleTap->setValue(serverConfig().switchDoubleTap());
ui->m_pCheckBoxCornerTopLeft->setChecked(serverConfig().switchCorner(static_cast<int>(TopLeft)));
ui->m_pCheckBoxCornerTopRight->setChecked(serverConfig().switchCorner(static_cast<int>(TopRight)));
ui->m_pCheckBoxCornerBottomLeft->setChecked(serverConfig().switchCorner(static_cast<int>(BottomLeft)));
ui->m_pCheckBoxCornerBottomRight->setChecked(serverConfig().switchCorner(static_cast<int>(BottomRight)));
ui->m_pSpinBoxSwitchCornerSize->setValue(serverConfig().switchCornerSize());
ui->m_pCheckBoxDisableLockToScreen->setChecked(serverConfig().disableLockToScreen());
ui->m_pCheckBoxEnableClipboard->setChecked(serverConfig().clipboardSharing());
int clipboardSharingSizeM = static_cast<int>(serverConfig().clipboardSharingSize() / 1024);
ui->m_pSpinBoxClipboardSizeLimit->setValue(clipboardSharingSizeM);
ui->m_pSpinBoxClipboardSizeLimit->setEnabled(serverConfig().clipboardSharing());
for (const Hotkey &hotkey : std::as_const(serverConfig().hotkeys()))
ui->m_pListHotkeys->addItem(hotkey.text());
ui->m_pScreenSetupView->setModel(&m_ScreenSetupModel);
auto &screens = serverConfig().screens();
auto server = std::find_if(screens.begin(), screens.end(), [this](const Screen &screen) {
return (screen.name() == serverConfig().getServerName());
});
if (server == screens.end()) {
Screen serverScreen(serverConfig().getServerName());
serverScreen.markAsServer();
model().screen(serverConfig().numColumns() / 2, serverConfig().numRows() / 2) = serverScreen;
} else {
server->markAsServer();
}
ui->m_pButtonAddComputer->setEnabled(!model().isFull());
connect(ui->m_pTrashScreenWidget, &TrashScreenWidget::screenRemoved, this, &ServerConfigDialog::onScreenRemoved);
onChange();
// computers
connect(&m_ScreenSetupModel, &ScreenSetupModel::screensChanged, this, &ServerConfigDialog::onChange);
// Above Qt 6.7 the checkbox signal signature has changed from int to Qt::CheckState
#if QT_VERSION <= QT_VERSION_CHECK(6, 7, 0)
// advanced
connect(ui->m_pCheckBoxSwitchDelay, &QCheckBox::stateChanged, this, [this](const int &v) {
serverConfig().haveSwitchDelay(v);
onChange();
});
connect(ui->m_pCheckBoxSwitchDoubleTap, &QCheckBox::stateChanged, this, [this](const int &v) {
serverConfig().haveSwitchDoubleTap(v);
onChange();
});
connect(ui->m_pCheckBoxEnableClipboard, &QCheckBox::stateChanged, this, [this](const int &v) {
serverConfig().setClipboardSharing(v);
onChange();
});
connect(ui->m_pCheckBoxHeartbeat, &QCheckBox::stateChanged, this, [this](const int &v) {
serverConfig().haveHeartbeat(v);
onChange();
});
connect(ui->m_pCheckBoxRelativeMouseMoves, &QCheckBox::stateChanged, this, [this](const int &v) {
serverConfig().setRelativeMouseMoves(v);
onChange();
});
connect(ui->m_pCheckBoxWin32KeepForeground, &QCheckBox::stateChanged, this, [this](const int &v) {
serverConfig().setWin32KeepForeground(v);
onChange();
});
connect(ui->m_pCheckBoxDisableLockToScreen, &QCheckBox::stateChanged, this, [this](const int &v) {
serverConfig().setDisableLockToScreen(v);
onChange();
});
connect(ui->m_pCheckBoxCornerTopLeft, &QCheckBox::stateChanged, this, [this](const int &v) {
serverConfig().setSwitchCorner(static_cast<int>(TopLeft), v);
onChange();
});
connect(ui->m_pCheckBoxCornerTopRight, &QCheckBox::stateChanged, this, [this](const int &v) {
serverConfig().setSwitchCorner(static_cast<int>(TopRight), v);
onChange();
});
connect(ui->m_pCheckBoxCornerBottomLeft, &QCheckBox::stateChanged, this, [this](const int &v) {
serverConfig().setSwitchCorner(static_cast<int>(BottomLeft), v);
onChange();
});
connect(ui->m_pCheckBoxCornerBottomRight, &QCheckBox::stateChanged, this, [this](const int &v) {
serverConfig().setSwitchCorner(static_cast<int>(BottomRight), v);
onChange();
});
// config
connect(ui->m_pCheckBoxUseExternalConfig, &QCheckBox::stateChanged, this, [this](const int &v) {
serverConfig().setUseExternalConfig(v);
onChange();
});
#else
connect(ui->m_pCheckBoxSwitchDelay, &QCheckBox::checkStateChanged, this, [this](const Qt::CheckState &v) {
serverConfig().haveSwitchDelay(v == Qt::Checked);
onChange();
});
connect(ui->m_pCheckBoxSwitchDoubleTap, &QCheckBox::checkStateChanged, this, [this](const Qt::CheckState &v) {
serverConfig().haveSwitchDoubleTap(v == Qt::Checked);
onChange();
});
connect(ui->m_pCheckBoxEnableClipboard, &QCheckBox::checkStateChanged, this, [this](const Qt::CheckState &v) {
serverConfig().setClipboardSharing(v == Qt::Checked);
onChange();
});
connect(ui->m_pCheckBoxHeartbeat, &QCheckBox::checkStateChanged, this, [this](const Qt::CheckState &v) {
serverConfig().haveHeartbeat(v == Qt::Checked);
onChange();
});
connect(ui->m_pCheckBoxRelativeMouseMoves, &QCheckBox::checkStateChanged, this, [this](const Qt::CheckState &v) {
serverConfig().setRelativeMouseMoves(v == Qt::Checked);
onChange();
});
connect(ui->m_pCheckBoxWin32KeepForeground, &QCheckBox::checkStateChanged, this, [this](const Qt::CheckState &v) {
serverConfig().setWin32KeepForeground(v == Qt::Checked);
onChange();
});
connect(ui->m_pCheckBoxDisableLockToScreen, &QCheckBox::checkStateChanged, this, [this](const Qt::CheckState &v) {
serverConfig().setDisableLockToScreen(v == Qt::Checked);
onChange();
});
connect(ui->m_pCheckBoxCornerTopLeft, &QCheckBox::checkStateChanged, this, [this](const Qt::CheckState &v) {
serverConfig().setSwitchCorner(static_cast<int>(TopLeft), v == Qt::Checked);
onChange();
});
connect(ui->m_pCheckBoxCornerTopRight, &QCheckBox::checkStateChanged, this, [this](const Qt::CheckState &v) {
serverConfig().setSwitchCorner(static_cast<int>(TopRight), v == Qt::Checked);
onChange();
});
connect(ui->m_pCheckBoxCornerBottomLeft, &QCheckBox::checkStateChanged, this, [this](const Qt::CheckState &v) {
serverConfig().setSwitchCorner(static_cast<int>(BottomLeft), v == Qt::Checked);
onChange();
});
connect(ui->m_pCheckBoxCornerBottomRight, &QCheckBox::checkStateChanged, this, [this](const Qt::CheckState &v) {
serverConfig().setSwitchCorner(static_cast<int>(BottomRight), v == Qt::Checked);
onChange();
});
// config
connect(ui->m_pCheckBoxUseExternalConfig, &QCheckBox::checkStateChanged, this, [this](const Qt::CheckState &v) {
serverConfig().setUseExternalConfig(v == Qt::Checked);
onChange();
});
#endif
connect(
ui->m_pSpinBoxSwitchDelay, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this,
[this](const int &v) {
serverConfig().setSwitchDelay(v);
onChange();
}
);
connect(
ui->m_pSpinBoxSwitchDoubleTap, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this,
[this](const int &v) {
serverConfig().setSwitchDoubleTap(v);
onChange();
}
);
connect(
ui->m_pSpinBoxClipboardSizeLimit, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this,
[this](const int &v) {
serverConfig().setClipboardSharingSize(v * 1024);
onChange();
}
);
connect(
ui->m_pSpinBoxHeartbeat, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this,
[this](const int &v) {
serverConfig().setHeartbeat(v);
onChange();
}
);
connect(
ui->m_pSpinBoxSwitchCornerSize, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this,
[this](const int &v) {
serverConfig().setSwitchCornerSize(v);
onChange();
}
);
connect(ui->m_pRadioProtocolSynergy, &QRadioButton::toggled, this, [this](const bool &v) {
if (v) {
serverConfig().setProtocol(ServerProtocol::kSynergy);
onChange();
}
});
connect(ui->m_pRadioProtocolBarrier, &QRadioButton::toggled, this, [this](const bool &v) {
if (v) {
serverConfig().setProtocol(ServerProtocol::kBarrier);
onChange();
}
});
connect(ui->m_pEditConfigFile, &QLineEdit::textChanged, this, [this]() {
serverConfig().setConfigFile(ui->m_pEditConfigFile->text());
onChange();
});
}
ServerConfigDialog::~ServerConfigDialog() = default;
bool ServerConfigDialog::addClient(const QString &clientName)
{
return addComputer(clientName, true);
}
void ServerConfigDialog::accept()
{
if (ui->m_pCheckBoxUseExternalConfig->isChecked() && !QFile::exists(ui->m_pEditConfigFile->text())) {
auto selectedButton = QMessageBox::warning(
this, "Filename invalid", "Please select a valid configuration file.", QMessageBox::Ok | QMessageBox::Ignore
);
if (selectedButton != QMessageBox::Ok || !on_m_pButtonBrowseConfigFile_clicked()) {
return;
}
}
// now that the dialog has been accepted, copy the new server config to the
// original one, which is a reference to the one in MainWindow.
setOriginalServerConfig(serverConfig());
QDialog::accept();
}
void ServerConfigDialog::reject()
{
serverConfig().setUseExternalConfig(m_OriginalServerConfigIsExternal);
serverConfig().setConfigFile(m_OriginalServerConfigUsesExternalFile);
QDialog::reject();
}
void ServerConfigDialog::on_m_pButtonNewHotkey_clicked()
{
Hotkey hotkey;
HotkeyDialog dlg(this, hotkey);
if (dlg.exec() == QDialog::Accepted) {
serverConfig().hotkeys().append(hotkey);
ui->m_pListHotkeys->addItem(hotkey.text());
onChange();
}
}
void ServerConfigDialog::on_m_pButtonEditHotkey_clicked()
{
int idx = ui->m_pListHotkeys->currentRow();
Q_ASSERT(idx >= 0 && idx < serverConfig().hotkeys().size());
Hotkey &hotkey = serverConfig().hotkeys()[idx];
HotkeyDialog dlg(this, hotkey);
if (dlg.exec() == QDialog::Accepted) {
ui->m_pListHotkeys->currentItem()->setText(hotkey.text());
onChange();
}
}
void ServerConfigDialog::on_m_pButtonRemoveHotkey_clicked()
{
int idx = ui->m_pListHotkeys->currentRow();
Q_ASSERT(idx >= 0 && idx < serverConfig().hotkeys().size());
serverConfig().hotkeys().removeAt(idx);
ui->m_pListActions->clear();
delete ui->m_pListHotkeys->item(idx);
onChange();
}
void ServerConfigDialog::on_m_pListHotkeys_itemSelectionChanged()
{
bool itemsSelected = !ui->m_pListHotkeys->selectedItems().isEmpty();
ui->m_pButtonEditHotkey->setEnabled(itemsSelected);
ui->m_pButtonRemoveHotkey->setEnabled(itemsSelected);
ui->m_pButtonNewAction->setEnabled(itemsSelected);
if (itemsSelected && serverConfig().hotkeys().size() > 0) {
ui->m_pListActions->clear();
int idx = ui->m_pListHotkeys->row(ui->m_pListHotkeys->selectedItems()[0]);
// There's a bug somewhere around here: We get idx == 1 right after we
// deleted the next to last item, so idx can only possibly be 0. GDB shows
// we got called indirectly from the delete line in
// on_m_pButtonRemoveHotkey_clicked() above, but the delete is of course
// necessary and seems correct. The while() is a generalized workaround for
// all that and shouldn't be required.
while (idx >= 0 && idx >= serverConfig().hotkeys().size())
idx--;
Q_ASSERT(idx >= 0 && idx < serverConfig().hotkeys().size());
const Hotkey &hotkey = serverConfig().hotkeys()[idx];
for (const Action &action : hotkey.actions())
ui->m_pListActions->addItem(action.text());
}
}
void ServerConfigDialog::on_m_pButtonNewAction_clicked()
{
int idx = ui->m_pListHotkeys->currentRow();
Q_ASSERT(idx >= 0 && idx < serverConfig().hotkeys().size());
Hotkey &hotkey = serverConfig().hotkeys()[idx];
Action action;
ActionDialog dlg(this, serverConfig(), hotkey, action);
if (dlg.exec() == QDialog::Accepted) {
hotkey.actions().append(action);
ui->m_pListActions->addItem(action.text());
onChange();
}
}
void ServerConfigDialog::on_m_pButtonEditAction_clicked()
{
int idxHotkey = ui->m_pListHotkeys->currentRow();
Q_ASSERT(idxHotkey >= 0 && idxHotkey < serverConfig().hotkeys().size());
Hotkey &hotkey = serverConfig().hotkeys()[idxHotkey];
int idxAction = ui->m_pListActions->currentRow();
Q_ASSERT(idxAction >= 0 && idxAction < hotkey.actions().size());
Action &action = hotkey.actions()[idxAction];
ActionDialog dlg(this, serverConfig(), hotkey, action);
if (dlg.exec() == QDialog::Accepted) {
ui->m_pListActions->currentItem()->setText(action.text());
onChange();
}
}
void ServerConfigDialog::on_m_pButtonRemoveAction_clicked()
{
int idxHotkey = ui->m_pListHotkeys->currentRow();
Q_ASSERT(idxHotkey >= 0 && idxHotkey < serverConfig().hotkeys().size());
Hotkey &hotkey = serverConfig().hotkeys()[idxHotkey];
int idxAction = ui->m_pListActions->currentRow();
Q_ASSERT(idxAction >= 0 && idxAction < hotkey.actions().size());
hotkey.actions().removeAt(idxAction);
delete ui->m_pListActions->currentItem();
onChange();
}
void ServerConfigDialog::on_m_pCheckBoxEnableClipboard_stateChanged(int const state)
{
ui->m_pSpinBoxClipboardSizeLimit->setEnabled(state == Qt::Checked);
if ((state == Qt::Checked) && (!ui->m_pSpinBoxClipboardSizeLimit->value())) {
int size = static_cast<int>((serverConfig().defaultClipboardSharingSize() + 512) / 1024);
ui->m_pSpinBoxClipboardSizeLimit->setValue(size ? size : 1);
}
}
void ServerConfigDialog::on_m_pListActions_itemSelectionChanged()
{
ui->m_pButtonEditAction->setEnabled(!ui->m_pListActions->selectedItems().isEmpty());
ui->m_pButtonRemoveAction->setEnabled(!ui->m_pListActions->selectedItems().isEmpty());
}
void ServerConfigDialog::on_m_pButtonAddComputer_clicked()
{
addComputer("", false);
}
void ServerConfigDialog::onScreenRemoved()
{
ui->m_pButtonAddComputer->setEnabled(true);
onChange();
}
void ServerConfigDialog::on_m_pCheckBoxUseExternalConfig_toggled(bool checked)
{
ui->m_pLabelConfigFile->setEnabled(checked);
ui->m_pEditConfigFile->setEnabled(checked);
ui->m_pButtonBrowseConfigFile->setEnabled(checked);
ui->m_pTabWidget->setTabEnabled(0, !checked);
ui->m_pTabWidget->setTabEnabled(1, !checked);
ui->m_pTabWidget->setTabEnabled(2, !checked);
}
bool ServerConfigDialog::on_m_pButtonBrowseConfigFile_clicked()
{
#if defined(Q_OS_WIN)
static const auto configExt = QStringLiteral("sgc");
#else
static const auto configExt = QStringLiteral("conf");
#endif
static const auto deskflowConfigFilter = QStringLiteral("%1 Configurations (*.%2);;All files (*.*)");
QString fileName =
QFileDialog::getOpenFileName(this, "Browse for a config file", "", deskflowConfigFilter.arg(kAppName, configExt));
if (!fileName.isEmpty()) {
ui->m_pEditConfigFile->setText(fileName);
return true;
}
return false;
}
bool ServerConfigDialog::addComputer(const QString &clientName, bool doSilent)
{
bool isAccepted = false;
Screen newScreen(clientName);
ScreenSettingsDialog dlg(this, &newScreen, &model().m_Screens);
if (doSilent || dlg.exec() == QDialog::Accepted) {
model().addScreen(newScreen);
isAccepted = true;
}
ui->m_pButtonAddComputer->setEnabled(!model().isFull());
return isAccepted;
}
void ServerConfigDialog::onChange()
{
bool isAppConfigDataEqual = m_OriginalServerConfigIsExternal == serverConfig().useExternalConfig() &&
m_OriginalServerConfigUsesExternalFile == serverConfig().configFile();
ui->m_pButtonBox->button(QDialogButtonBox::Ok)
->setEnabled(!isAppConfigDataEqual || !(m_OriginalServerConfig == m_ServerConfig));
}
| 18,513
|
C++
|
.cpp
| 425
| 39.84
| 120
| 0.725422
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,767
|
HotkeyDialog.cpp
|
deskflow_deskflow/src/gui/src/dialogs/HotkeyDialog.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2008 Volker Lanz (vl@fidra.de)
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "HotkeyDialog.h"
#include "ui_HotkeyDialog.h"
HotkeyDialog::HotkeyDialog(QWidget *parent, Hotkey &hotkey)
: QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint),
ui{std::make_unique<Ui::HotkeyDialog>()},
m_Hotkey(hotkey)
{
ui->setupUi(this);
ui->m_pKeySequenceWidgetHotkey->setText(m_Hotkey.text());
}
HotkeyDialog::~HotkeyDialog() = default;
void HotkeyDialog::accept()
{
if (!sequenceWidget()->valid())
return;
hotkey().setKeySequence(sequenceWidget()->keySequence());
QDialog::accept();
}
const KeySequenceWidget *HotkeyDialog::sequenceWidget() const
{
return ui->m_pKeySequenceWidgetHotkey;
}
| 1,395
|
C++
|
.cpp
| 39
| 33.358974
| 72
| 0.750927
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,768
|
AddClientDialog.cpp
|
deskflow_deskflow/src/gui/src/dialogs/AddClientDialog.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2014-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "AddClientDialog.h"
#include "ui_AddClientDialog.h"
#include <QLabel>
#include <QPushButton>
AddClientDialog::AddClientDialog(const QString &clientName, QWidget *parent)
: QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint),
ui{std::make_unique<Ui::AddClientDialog>()},
m_AddResult(kAddClientIgnore)
{
ui->setupUi(this);
ui->m_pLabelHead->setText(
"A client wants to connect. "
"Please choose a location for " +
clientName + "."
);
QIcon icon(":res/icons/64x64/video-display.png");
QSize IconSize(32, 32);
m_pButtonLeft = new QPushButton(this);
m_pButtonLeft->setIcon(icon);
m_pButtonLeft->setIconSize(IconSize);
ui->gridLayout->addWidget(m_pButtonLeft, 2, 0, 1, 1, Qt::AlignCenter);
connect(m_pButtonLeft, &QPushButton::clicked, this, &AddClientDialog::handleButtonLeft);
m_pButtonUp = new QPushButton(this);
m_pButtonUp->setIcon(icon);
m_pButtonUp->setIconSize(IconSize);
ui->gridLayout->addWidget(m_pButtonUp, 1, 1, 1, 1, Qt::AlignCenter);
connect(m_pButtonUp, &QPushButton::clicked, this, &AddClientDialog::handleButtonUp);
m_pButtonRight = new QPushButton(this);
m_pButtonRight->setIcon(icon);
m_pButtonRight->setIconSize(IconSize);
ui->gridLayout->addWidget(m_pButtonRight, 2, 2, 1, 1, Qt::AlignCenter);
connect(m_pButtonRight, &QPushButton::clicked, this, &AddClientDialog::handleButtonRight);
m_pButtonDown = new QPushButton(this);
m_pButtonDown->setIcon(icon);
m_pButtonDown->setIconSize(IconSize);
ui->gridLayout->addWidget(m_pButtonDown, 3, 1, 1, 1, Qt::AlignCenter);
connect(m_pButtonDown, &QPushButton::clicked, this, &AddClientDialog::handleButtonDown);
m_pLabelCenter = new QLabel(this);
m_pLabelCenter->setPixmap(QPixmap(":res/icons/64x64/video-display.png"));
ui->gridLayout->addWidget(m_pLabelCenter, 2, 1, 1, 1, Qt::AlignCenter);
#if defined(Q_OS_MAC)
ui->m_pDialogButtonBox->setLayoutDirection(Qt::RightToLeft);
#endif
QPushButton *advanced = ui->m_pDialogButtonBox->addButton("Advanced", QDialogButtonBox::HelpRole);
connect(advanced, &QPushButton::clicked, this, &AddClientDialog::handleButtonAdvanced);
}
AddClientDialog::~AddClientDialog() = default;
void AddClientDialog::handleButtonLeft()
{
m_AddResult = kAddClientLeft;
close();
}
void AddClientDialog::handleButtonUp()
{
m_AddResult = kAddClientUp;
close();
}
void AddClientDialog::handleButtonRight()
{
m_AddResult = kAddClientRight;
close();
}
void AddClientDialog::handleButtonDown()
{
m_AddResult = kAddClientDown;
close();
}
void AddClientDialog::handleButtonAdvanced()
{
m_AddResult = kAddClientOther;
close();
}
| 3,344
|
C++
|
.cpp
| 88
| 35.306818
| 100
| 0.754169
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,769
|
ServerStateLabel.cpp
|
deskflow_deskflow/src/gui/src/widgets/ServerStateLabel.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2021 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "ServerStateLabel.h"
#include "gui/core/ServerMessage.h"
using namespace deskflow::gui;
namespace deskflow::gui::widgets {
ServerStateLabel::ServerStateLabel(QWidget *parent) : QLabel(parent)
{
}
void ServerStateLabel::updateServerState(const QString &line)
{
ServerMessage message(line);
if (message.isExitMessage()) {
m_clients.clear();
} else if (message.isConnectedMessage()) {
m_clients.append(message.getClientName());
} else if (message.isDisconnectedMessage()) {
m_clients.removeAll(message.getClientName());
}
if (m_clients.isEmpty()) {
setText(tr("No clients connected"));
} else {
// unfortunately, we can't rely on the clients list because we don't always
// catch the connect/disconnect messages. so clients tend to get stuck in
// the list even though they're offline.
// in order to properly show a list of clients, we would need the core to
// print a list of connected clients on every connect/disconnect event,
// which could be a bit noisy in the logs (perhaps an ipc message would be
// needed).
setText(tr("Client(s) are connected"));
}
}
} // namespace deskflow::gui::widgets
| 1,866
|
C++
|
.cpp
| 47
| 36.829787
| 79
| 0.740884
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,770
|
ScreenSetupView.cpp
|
deskflow_deskflow/src/gui/src/widgets/ScreenSetupView.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012 Symless Ltd.
* Copyright (C) 2008 Volker Lanz (vl@fidra.de)
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "ScreenSetupView.h"
#include "ScreenSetupModel.h"
#include "dialogs/ScreenSettingsDialog.h"
#include <QDrag>
#include <QDragEnterEvent>
#include <QDragMoveEvent>
#include <QHeaderView>
#include <QMimeData>
#include <QMouseEvent>
#include <QResizeEvent>
ScreenSetupView::ScreenSetupView(QWidget *parent) : QTableView(parent)
{
setDropIndicatorShown(true);
setDragDropMode(DragDrop);
setSelectionMode(SingleSelection);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setIconSize(QSize(64, 64));
horizontalHeader()->hide();
verticalHeader()->hide();
}
void ScreenSetupView::setModel(QAbstractItemModel *model)
{
QTableView::setModel(model);
setTableSize();
}
ScreenSetupModel *ScreenSetupView::model() const
{
return qobject_cast<ScreenSetupModel *>(QTableView::model());
}
void ScreenSetupView::setTableSize()
{
for (int i = 0; i < model()->columnCount(); i++)
setColumnWidth(i, width() / model()->columnCount());
for (int i = 0; i < model()->rowCount(); i++)
setRowHeight(i, height() / model()->rowCount());
}
void ScreenSetupView::resizeEvent(QResizeEvent *event)
{
setTableSize();
event->ignore();
}
void ScreenSetupView::mouseDoubleClickEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton) {
int col = columnAt(event->pos().x());
int row = rowAt(event->pos().y());
if (!model()->screen(col, row).isNull()) {
ScreenSettingsDialog dlg(this, &model()->screen(col, row), &model()->m_Screens);
dlg.exec();
Q_EMIT model()->screensChanged();
}
} else
event->ignore();
}
void ScreenSetupView::dragEnterEvent(QDragEnterEvent *event)
{
// we accept anything that enters us by a drag as long as the
// mime type is okay. anything else is dealt with in dragMoveEvent()
if (event->mimeData()->hasFormat(ScreenSetupModel::mimeType()))
event->accept();
else
event->ignore();
}
void ScreenSetupView::dragMoveEvent(QDragMoveEvent *event)
{
if (event->mimeData()->hasFormat(ScreenSetupModel::mimeType())) {
// where does the event come from? myself or someone else?
if (event->source() == this) {
// myself is ok, but then it must be a move action, never a copy
event->setDropAction(Qt::MoveAction);
event->accept();
} else {
const auto &point = event->position().toPoint();
int col = columnAt(point.x());
int row = rowAt(point.y());
// a drop from outside is not allowed if there's a screen already there.
if (!model()->screen(col, row).isNull())
event->ignore();
else
event->acceptProposedAction();
}
} else
event->ignore();
}
// this is reimplemented from QAbstractItemView::startDrag()
void ScreenSetupView::startDrag(Qt::DropActions)
{
QModelIndexList indexes = selectedIndexes();
if (indexes.count() != 1)
return;
QMimeData *pData = model()->mimeData(indexes);
if (pData == NULL)
return;
const QPixmap &pixmap = model()->screen(indexes[0]).pixmap();
QDrag *pDrag = new QDrag(this);
pDrag->setPixmap(pixmap);
pDrag->setMimeData(pData);
pDrag->setHotSpot(QPoint(pixmap.width() / 2, pixmap.height() / 2));
if (pDrag->exec(Qt::MoveAction, Qt::MoveAction) == Qt::MoveAction) {
selectionModel()->clear();
// make sure to only delete the drag source if screens weren't swapped
// see ScreenSetupModel::dropMimeData
if (!model()->screen(indexes[0]).swapped())
model()->screen(indexes[0]) = Screen();
else
model()->screen(indexes[0]).setSwapped(false);
Q_EMIT model()->screensChanged();
}
}
void ScreenSetupView::initViewItemOption(QStyleOptionViewItem *option) const
{
option->showDecorationSelected = true;
option->decorationPosition = QStyleOptionViewItem::Top;
option->displayAlignment = Qt::AlignCenter;
option->textElideMode = Qt::ElideMiddle;
}
| 4,636
|
C++
|
.cpp
| 134
| 31.328358
| 86
| 0.714381
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,771
|
KeySequenceWidget.cpp
|
deskflow_deskflow/src/gui/src/widgets/KeySequenceWidget.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2008 Volker Lanz (vl@fidra.de)
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "KeySequenceWidget.h"
#include <QMouseEvent>
#include <iostream>
KeySequenceWidget::KeySequenceWidget(QWidget *parent, const KeySequence &seq)
: QPushButton(parent),
m_KeySequence(seq),
m_BackupSequence(seq),
m_Status(Stopped),
m_MousePrefix("mousebutton("),
m_MousePostfix(")"),
m_KeyPrefix("keystroke("),
m_KeyPostfix(")")
{
setFocusPolicy(Qt::NoFocus);
updateOutput();
}
void KeySequenceWidget::setKeySequence(const KeySequence &seq)
{
keySequence() = seq;
backupSequence() = seq;
setStatus(Stopped);
updateOutput();
}
void KeySequenceWidget::mousePressEvent(QMouseEvent *event)
{
event->accept();
if (status() == Stopped) {
startRecording();
return;
}
if (m_KeySequence.appendMouseButton(event->button()))
stopRecording();
updateOutput();
}
void KeySequenceWidget::startRecording()
{
keySequence() = KeySequence();
setDown(true);
setFocus();
grabKeyboard();
setStatus(Recording);
}
void KeySequenceWidget::stopRecording()
{
if (!keySequence().valid()) {
keySequence() = backupSequence();
updateOutput();
}
setDown(false);
focusNextChild();
releaseKeyboard();
setStatus(Stopped);
Q_EMIT keySequenceChanged();
}
bool KeySequenceWidget::event(QEvent *event)
{
if (status() == Recording) {
switch (event->type()) {
case QEvent::KeyPress:
keyPressEvent(static_cast<QKeyEvent *>(event));
return true;
case QEvent::MouseButtonRelease:
event->accept();
return true;
case QEvent::ShortcutOverride:
event->accept();
return true;
case QEvent::FocusOut:
stopRecording();
if (!valid()) {
keySequence() = backupSequence();
updateOutput();
}
break;
default:
break;
}
}
return QPushButton::event(event);
}
void KeySequenceWidget::keyPressEvent(QKeyEvent *event)
{
event->accept();
if (status() == Stopped)
return;
if (m_KeySequence.appendKey(event->key(), event->modifiers()))
stopRecording();
updateOutput();
}
void KeySequenceWidget::updateOutput()
{
QString s;
if (m_KeySequence.isMouseButton())
s = mousePrefix() + m_KeySequence.toString() + mousePostfix();
else
s = keyPrefix() + m_KeySequence.toString() + keyPostfix();
setText(s);
}
| 3,061
|
C++
|
.cpp
| 115
| 23
| 77
| 0.702157
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
13,772
|
ClientStateLabel.cpp
|
deskflow_deskflow/src/gui/src/widgets/ClientStateLabel.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2021 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "ClientStateLabel.h"
namespace deskflow::gui::widgets {
ClientStateLabel::ClientStateLabel(QWidget *parent) : QLabel(parent)
{
hide();
}
void ClientStateLabel::updateClientState(const QString &line)
{
if (line.contains("connected to server")) {
show();
} else if (line.contains("disconnected from server") || line.contains("process exited")) {
hide();
}
}
} // namespace deskflow::gui::widgets
| 1,110
|
C++
|
.cpp
| 31
| 33.645161
| 92
| 0.749534
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,773
|
TrashScreenWidget.cpp
|
deskflow_deskflow/src/gui/src/widgets/TrashScreenWidget.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2008 Volker Lanz (vl@fidra.de)
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#include "TrashScreenWidget.h"
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QMimeData>
#include "ScreenSetupModel.h"
void TrashScreenWidget::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasFormat(ScreenSetupModel::mimeType())) {
event->setDropAction(Qt::MoveAction);
event->accept();
} else
event->ignore();
}
void TrashScreenWidget::dropEvent(QDropEvent *event)
{
if (event->mimeData()->hasFormat(ScreenSetupModel::mimeType())) {
event->acceptProposedAction();
Q_EMIT screenRemoved();
} else {
event->ignore();
}
}
| 1,327
|
C++
|
.cpp
| 39
| 31.615385
| 72
| 0.748246
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,774
|
ServerArgs.h
|
deskflow_deskflow/src/lib/deskflow/ServerArgs.h
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2014-2020 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#pragma once
#include "ArgsBase.h"
#include "server/Config.h"
#include <memory>
namespace deskflow {
class ServerArgs : public ArgsBase
{
using Config = deskflow::server::Config;
public:
ServerArgs();
ServerArgs(ServerArgs const &src) = default;
ServerArgs(ServerArgs &&) = default;
~ServerArgs() override;
ServerArgs &operator=(ServerArgs const &) = default;
ServerArgs &operator=(ServerArgs &&) = default;
public:
String m_configFile = "";
std::shared_ptr<Config> m_config;
};
} // namespace deskflow
| 1,221
|
C++
|
.h
| 36
| 31.75
| 72
| 0.752551
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,775
|
XDeskflow.h
|
deskflow_deskflow/src/lib/deskflow/XDeskflow.h
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#pragma once
#include "base/XBase.h"
//! Generic deskflow exception
XBASE_SUBCLASS(XDeskflow, XBase);
//! Subscription error
/*!
Thrown when there is a problem with the subscription.
*/
XBASE_SUBCLASS(XSubscription, XDeskflow);
//! Client error exception
/*!
Thrown when the client fails to follow the protocol.
*/
XBASE_SUBCLASS_WHAT(XBadClient, XDeskflow);
//! Server protocol error
/*!
Thrown when the server protocol is unrecognized.
*/
XBASE_SUBCLASS_WHAT(XInvalidProtocol, XDeskflow);
//! Incompatible client exception
/*!
Thrown when a client attempting to connect has an incompatible version.
*/
class XIncompatibleClient : public XDeskflow
{
public:
XIncompatibleClient(int major, int minor);
//! @name accessors
//@{
//! Get client's major version number
int getMajor() const throw();
//! Get client's minor version number
int getMinor() const throw();
//@}
protected:
virtual String getWhat() const throw();
private:
int m_major;
int m_minor;
};
//! Client already connected exception
/*!
Thrown when a client attempting to connect is using the same name as
a client that is already connected.
*/
class XDuplicateClient : public XDeskflow
{
public:
XDuplicateClient(const String &name);
virtual ~XDuplicateClient() _NOEXCEPT
{
}
//! @name accessors
//@{
//! Get client's name
virtual const String &getName() const throw();
//@}
protected:
virtual String getWhat() const throw();
private:
String m_name;
};
//! Client not in map exception
/*!
Thrown when a client attempting to connect is using a name that is
unknown to the server.
*/
class XUnknownClient : public XDeskflow
{
public:
XUnknownClient(const String &name);
virtual ~XUnknownClient() _NOEXCEPT
{
}
//! @name accessors
//@{
//! Get the client's name
virtual const String &getName() const throw();
//@}
protected:
virtual String getWhat() const throw();
private:
String m_name;
};
//! Generic exit eception
/*!
Thrown when we want to abort, with the opportunity to clean up. This is a
little bit of a hack, but it's a better way of exiting, than just calling
exit(int).
*/
class XExitApp : public XDeskflow
{
public:
XExitApp(int code);
virtual ~XExitApp() _NOEXCEPT
{
}
//! Get the exit code
int getCode() const throw();
protected:
virtual String getWhat() const throw();
private:
int m_code;
};
| 3,109
|
C++
|
.h
| 121
| 23.652893
| 73
| 0.747297
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
13,776
|
ISecondaryScreen.h
|
deskflow_deskflow/src/lib/deskflow/ISecondaryScreen.h
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2003 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#pragma once
#include "base/Event.h"
#include "base/EventTypes.h"
#include "common/IInterface.h"
#include "deskflow/mouse_types.h"
//! Secondary screen interface
/*!
This interface defines the methods common to all platform dependent
secondary screen implementations.
*/
class ISecondaryScreen : public IInterface
{
public:
//! @name accessors
//@{
//! Fake mouse press/release
/*!
Synthesize a press or release of mouse button \c id.
*/
virtual void fakeMouseButton(ButtonID id, bool press) = 0;
//! Fake mouse move
/*!
Synthesize a mouse move to the absolute coordinates \c x,y.
*/
virtual void fakeMouseMove(SInt32 x, SInt32 y) = 0;
//! Fake mouse move
/*!
Synthesize a mouse move to the relative coordinates \c dx,dy.
*/
virtual void fakeMouseRelativeMove(SInt32 dx, SInt32 dy) const = 0;
//! Fake mouse wheel
/*!
Synthesize a mouse wheel event of amount \c xDelta and \c yDelta.
*/
virtual void fakeMouseWheel(SInt32 xDelta, SInt32 yDelta) const = 0;
//@}
};
| 1,748
|
C++
|
.h
| 54
| 30.074074
| 72
| 0.742586
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
13,777
|
option_types.h
|
deskflow_deskflow/src/lib/deskflow/option_types.h
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#pragma once
#include "base/EventTypes.h"
#include "common/stdvector.h"
//! Option ID
/*!
Type to hold an option identifier.
*/
typedef UInt32 OptionID;
//! Option Value
/*!
Type to hold an option value.
*/
typedef SInt32 OptionValue;
// for now, options are just pairs of integers
typedef std::vector<UInt32> OptionsList;
// macro for packing 4 character strings into 4 byte integers
#define OPTION_CODE(_s) \
(static_cast<UInt32>(static_cast<unsigned char>(_s[0]) << 24) | \
static_cast<UInt32>(static_cast<unsigned char>(_s[1]) << 16) | \
static_cast<UInt32>(static_cast<unsigned char>(_s[2]) << 8) | \
static_cast<UInt32>(static_cast<unsigned char>(_s[3])))
//! @name Option identifiers
//@{
static const OptionID kOptionHalfDuplexCapsLock = OPTION_CODE("HDCL");
static const OptionID kOptionHalfDuplexNumLock = OPTION_CODE("HDNL");
static const OptionID kOptionHalfDuplexScrollLock = OPTION_CODE("HDSL");
static const OptionID kOptionModifierMapForShift = OPTION_CODE("MMFS");
static const OptionID kOptionModifierMapForControl = OPTION_CODE("MMFC");
static const OptionID kOptionModifierMapForAlt = OPTION_CODE("MMFA");
static const OptionID kOptionModifierMapForAltGr = OPTION_CODE("MMFG");
static const OptionID kOptionModifierMapForMeta = OPTION_CODE("MMFM");
static const OptionID kOptionModifierMapForSuper = OPTION_CODE("MMFR");
static const OptionID kOptionHeartbeat = OPTION_CODE("HART");
static const OptionID kOptionProtocol = OPTION_CODE("PROT");
static const OptionID kOptionScreenSwitchCorners = OPTION_CODE("SSCM");
static const OptionID kOptionScreenSwitchCornerSize = OPTION_CODE("SSCS");
static const OptionID kOptionScreenSwitchDelay = OPTION_CODE("SSWT");
static const OptionID kOptionScreenSwitchTwoTap = OPTION_CODE("SSTT");
static const OptionID kOptionScreenSwitchNeedsShift = OPTION_CODE("SSNS");
static const OptionID kOptionScreenSwitchNeedsControl = OPTION_CODE("SSNC");
static const OptionID kOptionScreenSwitchNeedsAlt = OPTION_CODE("SSNA");
static const OptionID kOptionXTestXineramaUnaware = OPTION_CODE("XTXU");
static const OptionID kOptionScreenPreserveFocus = OPTION_CODE("SFOC");
static const OptionID kOptionRelativeMouseMoves = OPTION_CODE("MDLT");
static const OptionID kOptionWin32KeepForeground = OPTION_CODE("_KFW");
static const OptionID kOptionDisableLockToScreen = OPTION_CODE("DLTS");
static const OptionID kOptionClipboardSharing = OPTION_CODE("CLPS");
static const OptionID kOptionClipboardSharingSize = OPTION_CODE("CLSZ");
//@}
//! @name Screen switch corner enumeration
//@{
enum EScreenSwitchCorners
{
kNoCorner,
kTopLeft,
kTopRight,
kBottomLeft,
kBottomRight,
kFirstCorner = kTopLeft,
kLastCorner = kBottomRight
};
//@}
//! @name Screen switch corner masks
//@{
enum EScreenSwitchCornerMasks
{
kNoCornerMask = 0,
kTopLeftMask = 1 << (kTopLeft - kFirstCorner),
kTopRightMask = 1 << (kTopRight - kFirstCorner),
kBottomLeftMask = 1 << (kBottomLeft - kFirstCorner),
kBottomRightMask = 1 << (kBottomRight - kFirstCorner),
kAllCornersMask = kTopLeftMask | kTopRightMask | kBottomLeftMask | kBottomRightMask
};
//@}
//! @name Network protocol
//@{
enum class ENetworkProtocol
{
kSynergy,
kBarrier
};
//@}
#undef OPTION_CODE
| 4,213
|
C++
|
.h
| 100
| 40.45
| 120
| 0.731594
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,778
|
StreamChunker.h
|
deskflow_deskflow/src/lib/deskflow/StreamChunker.h
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2013-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#pragma once
#include "base/String.h"
#include "deskflow/clipboard_types.h"
class IEventQueue;
class Mutex;
class StreamChunker
{
public:
static void sendFile(char *filename, IEventQueue *events, void *eventTarget);
static void
sendClipboard(String &data, size_t size, ClipboardID id, UInt32 sequence, IEventQueue *events, void *eventTarget);
static void interruptFile();
private:
static bool s_isChunkingFile;
static bool s_interruptFile;
static Mutex *s_interruptMutex;
};
| 1,185
|
C++
|
.h
| 33
| 33.878788
| 116
| 0.775065
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,779
|
Screen.h
|
deskflow_deskflow/src/lib/deskflow/Screen.h
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#pragma once
#include "base/String.h"
#include "deskflow/DragInformation.h"
#include "deskflow/IScreen.h"
#include "deskflow/clipboard_types.h"
#include "deskflow/key_types.h"
#include "deskflow/mouse_types.h"
#include "deskflow/option_types.h"
class IClipboard;
class IPlatformScreen;
class IEventQueue;
namespace deskflow {
//! Platform independent screen
/*!
This is a platform independent screen. It can work as either a
primary or secondary screen.
*/
class Screen : public IScreen
{
public:
Screen(IPlatformScreen *platformScreen, IEventQueue *events);
Screen(Screen const &) = delete;
Screen(Screen &&) = delete;
virtual ~Screen();
Screen &operator&(Screen const &) = delete;
Screen &operator&(Screen &&) = delete;
#ifdef TEST_ENV
Screen() : m_mock(true)
{
}
#endif
//! @name manipulators
//@{
//! Activate screen
/*!
Activate the screen, preparing it to report system and user events.
For a secondary screen it also means disabling the screen saver if
synchronizing it and preparing to synthesize events.
*/
virtual void enable();
//! Deactivate screen
/*!
Undoes the operations in activate() and events are no longer
reported. It also releases keys that are logically pressed.
*/
virtual void disable();
//! Enter screen
/*!
Called when the user navigates to this screen. \p toggleMask has the
toggle keys that should be turned on on the secondary screen.
*/
void enter(KeyModifierMask toggleMask);
//! Leave screen
/*!
Called when the user navigates off this screen.
*/
bool leave();
//! Update configuration
/*!
This is called when the configuration has changed. \c activeSides
is a bitmask of EDirectionMask indicating which sides of the
primary screen are linked to clients.
*/
void reconfigure(UInt32 activeSides);
//! Warp cursor
/*!
Warps the cursor to the absolute coordinates \c x,y. Also
discards input events up to and including the warp before
returning.
*/
void warpCursor(SInt32 x, SInt32 y);
//! Set clipboard
/*!
Sets the system's clipboard contents. This is usually called
soon after an enter().
*/
void setClipboard(ClipboardID, const IClipboard *);
//! Grab clipboard
/*!
Grabs (i.e. take ownership of) the system clipboard.
*/
void grabClipboard(ClipboardID);
//! Activate/deactivate screen saver
/*!
Forcibly activates the screen saver if \c activate is true otherwise
forcibly deactivates it.
*/
void screensaver(bool activate) const;
//! Notify of key press
/*!
Synthesize key events to generate a press of key \c id. If possible
match the given modifier mask. The KeyButton identifies the physical
key on the server that generated this key down. The client must
ensure that a key up or key repeat that uses the same KeyButton will
synthesize an up or repeat for the same client key synthesized by
keyDown().
*/
void keyDown(KeyID id, KeyModifierMask, KeyButton, const String &);
//! Notify of key repeat
/*!
Synthesize key events to generate a press and release of key \c id
\c count times. If possible match the given modifier mask.
*/
void keyRepeat(KeyID id, KeyModifierMask, SInt32 count, KeyButton, const String &lang);
//! Notify of key release
/*!
Synthesize key events to generate a release of key \c id. If possible
match the given modifier mask.
*/
void keyUp(KeyID id, KeyModifierMask, KeyButton);
//! Notify of mouse press
/*!
Synthesize mouse events to generate a press of mouse button \c id.
*/
void mouseDown(ButtonID id);
//! Notify of mouse release
/*!
Synthesize mouse events to generate a release of mouse button \c id.
*/
void mouseUp(ButtonID id);
//! Notify of mouse motion
/*!
Synthesize mouse events to generate mouse motion to the absolute
screen position \c xAbs,yAbs.
*/
void mouseMove(SInt32 xAbs, SInt32 yAbs);
//! Notify of mouse motion
/*!
Synthesize mouse events to generate mouse motion by the relative
amount \c xRel,yRel.
*/
void mouseRelativeMove(SInt32 xRel, SInt32 yRel);
//! Notify of mouse wheel motion
/*!
Synthesize mouse events to generate mouse wheel motion of \c xDelta
and \c yDelta. Deltas are positive for motion away from the user or
to the right and negative for motion towards the user or to the left.
Each wheel click should generate a delta of +/-120.
*/
void mouseWheel(SInt32 xDelta, SInt32 yDelta) const;
//! Notify of options changes
/*!
Resets all options to their default values.
*/
virtual void resetOptions();
//! Notify of options changes
/*!
Set options to given values. Ignores unknown options and doesn't
modify options that aren't given in \c options.
*/
virtual void setOptions(const OptionsList &options);
//! Set clipboard sequence number
/*!
Sets the sequence number to use in subsequent clipboard events.
*/
void setSequenceNumber(UInt32);
//! Register a system hotkey
/*!
Registers a system-wide hotkey for key \p key with modifiers \p mask.
Returns an id used to unregister the hotkey.
*/
UInt32 registerHotKey(KeyID key, KeyModifierMask mask);
//! Unregister a system hotkey
/*!
Unregisters a previously registered hot key.
*/
void unregisterHotKey(UInt32 id);
//! Prepare to synthesize input on primary screen
/*!
Prepares the primary screen to receive synthesized input. We do not
want to receive this synthesized input as user input so this method
ensures that we ignore it. Calls to \c fakeInputBegin() may not be
nested.
*/
void fakeInputBegin();
//! Done synthesizing input on primary screen
/*!
Undoes whatever \c fakeInputBegin() did.
*/
void fakeInputEnd();
//! Change dragging status
void setDraggingStarted(bool started);
//! Fake a files dragging operation
void startDraggingFiles(DragFileList &fileList);
void setEnableDragDrop(bool enabled);
//! Determine the name of the app causing a secure input state
/*!
On MacOS check which app causes a secure input state to be enabled. No
alternative on other platforms
*/
String getSecureInputApp() const;
//@}
//! @name accessors
//@{
//! Test if cursor on screen
/*!
Returns true iff the cursor is on the screen.
*/
bool isOnScreen() const;
//! Get screen lock state
/*!
Returns true if there's any reason that the user should not be
allowed to leave the screen (usually because a button or key is
pressed). If this method returns true it logs a message as to
why at the CLOG_DEBUG level.
*/
bool isLockedToScreen() const;
//! Get jump zone size
/*!
Return the jump zone size, the size of the regions on the edges of
the screen that cause the cursor to jump to another screen.
*/
SInt32 getJumpZoneSize() const;
//! Get cursor center position
/*!
Return the cursor center position which is where we park the
cursor to compute cursor motion deltas and should be far from
the edges of the screen, typically the center.
*/
void getCursorCenter(SInt32 &x, SInt32 &y) const;
//! Get the active modifiers
/*!
Returns the modifiers that are currently active according to our
shadowed state.
*/
KeyModifierMask getActiveModifiers() const;
//! Get the active modifiers from OS
/*!
Returns the modifiers that are currently active according to the
operating system.
*/
KeyModifierMask pollActiveModifiers() const;
//! Test if file is dragged on primary screen
bool isDraggingStarted() const;
//! Test if file is dragged on secondary screen
bool isFakeDraggingStarted() const;
//! Get the filename of the file being dragged
String &getDraggingFilename() const;
//! Clear the filename of the file that was dragged
void clearDraggingFilename();
//! Get the drop target directory
const String &getDropTarget() const;
//@}
// IScreen overrides
virtual void *getEventTarget() const;
virtual bool getClipboard(ClipboardID id, IClipboard *) const;
virtual void getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const;
virtual void getCursorPos(SInt32 &x, SInt32 &y) const;
IPlatformScreen *getPlatformScreen()
{
return m_screen;
}
protected:
void enablePrimary();
void enableSecondary();
void disablePrimary();
void disableSecondary();
void enterPrimary();
void enterSecondary(KeyModifierMask toggleMask);
void leavePrimary();
void leaveSecondary();
private:
// our platform dependent screen
IPlatformScreen *m_screen;
// true if screen is being used as a primary screen, false otherwise
bool m_isPrimary;
// true if screen is enabled
bool m_enabled;
// true if the cursor is on this screen
bool m_entered;
// note toggle keys that toggles on up/down (false) or on
// transition (true)
KeyModifierMask m_halfDuplex;
// true if we're faking input on a primary screen
bool m_fakeInput;
IEventQueue *m_events;
bool m_mock;
bool m_enableDragDrop;
};
} // namespace deskflow
| 9,746
|
C++
|
.h
| 297
| 29.835017
| 89
| 0.741877
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,780
|
FileChunk.h
|
deskflow_deskflow/src/lib/deskflow/FileChunk.h
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2015-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#pragma once
#include "base/String.h"
#include "common/basic_types.h"
#include "deskflow/Chunk.h"
#define FILE_CHUNK_META_SIZE 2
namespace deskflow {
class IStream;
};
class FileChunk : public Chunk
{
public:
FileChunk(size_t size);
static FileChunk *start(const String &size);
static FileChunk *data(UInt8 *data, size_t dataSize);
static FileChunk *end();
static int assemble(deskflow::IStream *stream, String &dataCached, size_t &expectedSize);
static void send(deskflow::IStream *stream, UInt8 mark, char *data, size_t dataSize);
};
| 1,245
|
C++
|
.h
| 34
| 34.647059
| 91
| 0.761826
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,781
|
PacketStreamFilter.h
|
deskflow_deskflow/src/lib/deskflow/PacketStreamFilter.h
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2004 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#pragma once
#include "io/StreamBuffer.h"
#include "io/StreamFilter.h"
#include "mt/Mutex.h"
class IEventQueue;
//! Packetizing stream filter
/*!
Filters a stream to read and write packets.
*/
class PacketStreamFilter : public StreamFilter
{
public:
PacketStreamFilter(IEventQueue *events, deskflow::IStream *stream, bool adoptStream = true);
~PacketStreamFilter();
// IStream overrides
virtual void close();
virtual UInt32 read(void *buffer, UInt32 n);
virtual void write(const void *buffer, UInt32 n);
virtual void shutdownInput();
virtual bool isReady() const;
virtual UInt32 getSize() const;
protected:
// StreamFilter overrides
virtual void filterEvent(const Event &);
private:
bool isReadyNoLock() const;
void readPacketSize();
bool readMore();
private:
Mutex m_mutex;
UInt32 m_size;
StreamBuffer m_buffer;
bool m_inputShutdown;
IEventQueue *m_events;
};
| 1,637
|
C++
|
.h
| 52
| 29.288462
| 94
| 0.764743
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
13,782
|
DragInformation.h
|
deskflow_deskflow/src/lib/deskflow/DragInformation.h
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2013-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#pragma once
#include "base/EventTypes.h"
#include "base/String.h"
#include "common/stdvector.h"
class DragInformation;
typedef std::vector<DragInformation> DragFileList;
class DragInformation
{
public:
DragInformation();
~DragInformation()
{
}
String &getFilename()
{
return m_filename;
}
void setFilename(String &name)
{
m_filename = name;
}
size_t getFilesize()
{
return m_filesize;
}
void setFilesize(size_t size)
{
m_filesize = size;
}
static void parseDragInfo(DragFileList &dragFileList, UInt32 fileNum, String data);
static String getDragFileExtension(String filename);
// helper function to setup drag info
// example: filename1,filesize1,filename2,filesize2,
// return file count
static int setupDragInfo(DragFileList &fileList, String &output);
static bool isFileValid(String filename);
private:
static size_t stringToNum(String &str);
static String getFileSize(String &filename);
private:
String m_filename;
size_t m_filesize;
};
| 1,712
|
C++
|
.h
| 59
| 26.423729
| 85
| 0.757908
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
13,783
|
ClipboardChunk.h
|
deskflow_deskflow/src/lib/deskflow/ClipboardChunk.h
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2015-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package 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/>.
*/
#pragma once
#include "base/String.h"
#include "common/basic_types.h"
#include "deskflow/Chunk.h"
#include "deskflow/clipboard_types.h"
#define CLIPBOARD_CHUNK_META_SIZE 7
namespace deskflow {
class IStream;
};
class ClipboardChunk : public Chunk
{
public:
ClipboardChunk(size_t size);
static ClipboardChunk *start(ClipboardID id, UInt32 sequence, const String &size);
static ClipboardChunk *data(ClipboardID id, UInt32 sequence, const String &data);
static ClipboardChunk *end(ClipboardID id, UInt32 sequence);
static int assemble(deskflow::IStream *stream, String &dataCached, ClipboardID &id, UInt32 &sequence);
static void send(deskflow::IStream *stream, void *data);
static size_t getExpectedSize()
{
return s_expectedSize;
}
private:
static size_t s_expectedSize;
};
| 1,498
|
C++
|
.h
| 41
| 34.341463
| 104
| 0.771251
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.