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,481
|
Chunk.cpp
|
deskflow_deskflow/src/lib/deskflow/Chunk.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/Chunk.h"
#include "base/String.h"
Chunk::Chunk(size_t size) : m_dataSize(0)
{
m_chunk = new char[size];
memset(m_chunk, 0, size);
}
Chunk::~Chunk()
{
delete[] m_chunk;
}
| 889
|
C++
|
.cpp
| 27
| 31.037037
| 72
| 0.74156
|
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,482
|
ClientArgs.cpp
|
deskflow_deskflow/src/lib/deskflow/ClientArgs.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 "ClientArgs.h"
namespace deskflow {
ClientArgs::~ClientArgs()
{
}
ClientArgs::ClientArgs()
{
m_classType = kClient;
}
} // namespace deskflow
| 848
|
C++
|
.cpp
| 26
| 30.807692
| 72
| 0.760391
|
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,483
|
XDeskflow.cpp
|
deskflow_deskflow/src/lib/deskflow/XDeskflow.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 "deskflow/XDeskflow.h"
#include "base/String.h"
//
// XBadClient
//
String XBadClient::getWhat() const throw()
{
return "XBadClient";
}
//
// XInvalidProtocol
//
String XInvalidProtocol::getWhat() const throw()
{
return "XInvalidProtocol";
}
//
// XIncompatibleClient
//
XIncompatibleClient::XIncompatibleClient(int major, int minor) : m_major(major), m_minor(minor)
{
// do nothing
}
int XIncompatibleClient::getMajor() const throw()
{
return m_major;
}
int XIncompatibleClient::getMinor() const throw()
{
return m_minor;
}
String XIncompatibleClient::getWhat() const throw()
{
return format(
"XIncompatibleClient", "incompatible client %{1}.%{2}", deskflow::string::sprintf("%d", m_major).c_str(),
deskflow::string::sprintf("%d", m_minor).c_str()
);
}
//
// XDuplicateClient
//
XDuplicateClient::XDuplicateClient(const String &name) : m_name(name)
{
// do nothing
}
const String &XDuplicateClient::getName() const throw()
{
return m_name;
}
String XDuplicateClient::getWhat() const throw()
{
return format("XDuplicateClient", "duplicate client %{1}", m_name.c_str());
}
//
// XUnknownClient
//
XUnknownClient::XUnknownClient(const String &name) : m_name(name)
{
// do nothing
}
const String &XUnknownClient::getName() const throw()
{
return m_name;
}
String XUnknownClient::getWhat() const throw()
{
return format("XUnknownClient", "unknown client %{1}", m_name.c_str());
}
//
// XExitApp
//
XExitApp::XExitApp(int code) : m_code(code)
{
// do nothing
}
int XExitApp::getCode() const throw()
{
return m_code;
}
String XExitApp::getWhat() const throw()
{
return format("XExitApp", "exiting with code %{1}", deskflow::string::sprintf("%d", m_code).c_str());
}
| 2,465
|
C++
|
.cpp
| 100
| 22.83
| 111
| 0.731541
|
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,484
|
StreamChunker.cpp
|
deskflow_deskflow/src/lib/deskflow/StreamChunker.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 "deskflow/StreamChunker.h"
#include "base/Event.h"
#include "base/EventTypes.h"
#include "base/IEventQueue.h"
#include "base/Log.h"
#include "base/Stopwatch.h"
#include "base/String.h"
#include "common/stdexcept.h"
#include "deskflow/ClipboardChunk.h"
#include "deskflow/FileChunk.h"
#include "deskflow/protocol_types.h"
#include "mt/Lock.h"
#include "mt/Mutex.h"
#include <fstream>
using namespace std;
static const size_t g_chunkSize = 512 * 1024; // 512kb
bool StreamChunker::s_isChunkingFile = false;
bool StreamChunker::s_interruptFile = false;
Mutex *StreamChunker::s_interruptMutex = NULL;
void StreamChunker::sendFile(char *filename, IEventQueue *events, void *eventTarget)
{
s_isChunkingFile = true;
std::fstream file(static_cast<char *>(filename), std::ios::in | std::ios::binary);
if (!file.is_open()) {
throw runtime_error("failed to open file");
}
// check file size
file.seekg(0, std::ios::end);
size_t size = (size_t)file.tellg();
// send first message (file size)
String fileSize = deskflow::string::sizeTypeToString(size);
FileChunk *sizeMessage = FileChunk::start(fileSize);
events->addEvent(Event(events->forFile().fileChunkSending(), eventTarget, sizeMessage));
// send chunk messages with a fixed chunk size
size_t sentLength = 0;
size_t chunkSize = g_chunkSize;
file.seekg(0, std::ios::beg);
while (true) {
if (s_interruptFile) {
s_interruptFile = false;
LOG((CLOG_DEBUG "file transmission interrupted"));
break;
}
events->addEvent(Event(events->forFile().keepAlive(), eventTarget));
// make sure we don't read too much from the mock data.
if (sentLength + chunkSize > size) {
chunkSize = size - sentLength;
}
char *chunkData = new char[chunkSize];
file.read(chunkData, chunkSize);
UInt8 *data = reinterpret_cast<UInt8 *>(chunkData);
FileChunk *fileChunk = FileChunk::data(data, chunkSize);
delete[] chunkData;
events->addEvent(Event(events->forFile().fileChunkSending(), eventTarget, fileChunk));
sentLength += chunkSize;
file.seekg(sentLength, std::ios::beg);
if (sentLength == size) {
break;
}
}
// send last message
FileChunk *end = FileChunk::end();
events->addEvent(Event(events->forFile().fileChunkSending(), eventTarget, end));
file.close();
s_isChunkingFile = false;
}
void StreamChunker::sendClipboard(
String &data, size_t size, ClipboardID id, UInt32 sequence, IEventQueue *events, void *eventTarget
)
{
// send first message (data size)
String dataSize = deskflow::string::sizeTypeToString(size);
ClipboardChunk *sizeMessage = ClipboardChunk::start(id, sequence, dataSize);
events->addEvent(Event(events->forClipboard().clipboardSending(), eventTarget, sizeMessage));
// send clipboard chunk with a fixed size
size_t sentLength = 0;
size_t chunkSize = g_chunkSize;
while (true) {
events->addEvent(Event(events->forFile().keepAlive(), eventTarget));
// make sure we don't read too much from the mock data.
if (sentLength + chunkSize > size) {
chunkSize = size - sentLength;
}
String chunk(data.substr(sentLength, chunkSize).c_str(), chunkSize);
ClipboardChunk *dataChunk = ClipboardChunk::data(id, sequence, chunk);
events->addEvent(Event(events->forClipboard().clipboardSending(), eventTarget, dataChunk));
sentLength += chunkSize;
if (sentLength == size) {
break;
}
}
// send last message
ClipboardChunk *end = ClipboardChunk::end(id, sequence);
events->addEvent(Event(events->forClipboard().clipboardSending(), eventTarget, end));
LOG((CLOG_DEBUG "sent clipboard size=%d", sentLength));
}
void StreamChunker::interruptFile()
{
if (s_isChunkingFile) {
s_interruptFile = true;
LOG((CLOG_INFO "previous dragged file has become invalid"));
}
}
| 4,549
|
C++
|
.cpp
| 119
| 34.815126
| 102
| 0.723487
|
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,485
|
PacketStreamFilter.cpp
|
deskflow_deskflow/src/lib/deskflow/PacketStreamFilter.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 "deskflow/PacketStreamFilter.h"
#include "base/IEventQueue.h"
#include "base/TMethodEventJob.h"
#include "mt/Lock.h"
#include <cstring>
#include <memory>
//
// PacketStreamFilter
//
PacketStreamFilter::PacketStreamFilter(IEventQueue *events, deskflow::IStream *stream, bool adoptStream)
: StreamFilter(events, stream, adoptStream),
m_size(0),
m_inputShutdown(false),
m_events(events)
{
// do nothing
}
PacketStreamFilter::~PacketStreamFilter()
{
// do nothing
}
void PacketStreamFilter::close()
{
Lock lock(&m_mutex);
m_size = 0;
m_buffer.pop(m_buffer.getSize());
StreamFilter::close();
}
UInt32 PacketStreamFilter::read(void *buffer, UInt32 n)
{
if (n == 0) {
return 0;
}
Lock lock(&m_mutex);
// if not enough data yet then give up
if (!isReadyNoLock()) {
return 0;
}
// read no more than what's left in the buffered packet
if (n > m_size) {
n = m_size;
}
// read it
if (buffer != NULL) {
memcpy(buffer, m_buffer.peek(n), n);
}
m_buffer.pop(n);
m_size -= n;
// get next packet's size if we've finished with this packet and
// there's enough data to do so.
readPacketSize();
if (m_inputShutdown && m_size == 0) {
m_events->addEvent(Event(m_events->forIStream().inputShutdown(), getEventTarget()));
}
return n;
}
void PacketStreamFilter::write(const void *buffer, UInt32 count)
{
// write the length of the payload
UInt8 length[4];
length[0] = (UInt8)((count >> 24) & 0xff);
length[1] = (UInt8)((count >> 16) & 0xff);
length[2] = (UInt8)((count >> 8) & 0xff);
length[3] = (UInt8)(count & 0xff);
getStream()->write(length, sizeof(length));
// write the payload
getStream()->write(buffer, count);
}
void PacketStreamFilter::shutdownInput()
{
Lock lock(&m_mutex);
m_size = 0;
m_buffer.pop(m_buffer.getSize());
StreamFilter::shutdownInput();
}
bool PacketStreamFilter::isReady() const
{
Lock lock(&m_mutex);
return isReadyNoLock();
}
UInt32 PacketStreamFilter::getSize() const
{
Lock lock(&m_mutex);
return isReadyNoLock() ? m_size : 0;
}
bool PacketStreamFilter::isReadyNoLock() const
{
return (m_size != 0 && m_buffer.getSize() >= m_size);
}
void PacketStreamFilter::readPacketSize()
{
// note -- m_mutex must be locked on entry
if (m_size == 0 && m_buffer.getSize() >= 4) {
UInt8 buffer[4];
memcpy(buffer, m_buffer.peek(sizeof(buffer)), sizeof(buffer));
m_buffer.pop(sizeof(buffer));
m_size = ((UInt32)buffer[0] << 24) | ((UInt32)buffer[1] << 16) | ((UInt32)buffer[2] << 8) | (UInt32)buffer[3];
}
}
bool PacketStreamFilter::readMore()
{
// note if we have whole packet
bool wasReady = isReadyNoLock();
// read more data
char buffer[4096];
UInt32 n = getStream()->read(buffer, sizeof(buffer));
while (n > 0) {
m_buffer.write(buffer, n);
n = getStream()->read(buffer, sizeof(buffer));
}
// if we don't yet have the next packet size then get it,
// if possible.
readPacketSize();
// note if we now have a whole packet
bool isReady = isReadyNoLock();
// if we weren't ready before but now we are then send a
// input ready event apparently from the filtered stream.
return (wasReady != isReady);
}
void PacketStreamFilter::filterEvent(const Event &event)
{
if (event.getType() == m_events->forIStream().inputReady()) {
Lock lock(&m_mutex);
if (!readMore()) {
return;
}
} else if (event.getType() == m_events->forIStream().inputShutdown()) {
// discard this if we have buffered data
Lock lock(&m_mutex);
m_inputShutdown = true;
if (m_size != 0) {
return;
}
}
// pass event
StreamFilter::filterEvent(event);
}
| 4,414
|
C++
|
.cpp
| 154
| 25.785714
| 114
| 0.687308
|
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,486
|
IPrimaryScreen.cpp
|
deskflow_deskflow/src/lib/deskflow/IPrimaryScreen.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 "deskflow/IPrimaryScreen.h"
#include "base/EventQueue.h"
#include <cstdlib>
//
// IPrimaryScreen::ButtonInfo
//
IPrimaryScreen::ButtonInfo *IPrimaryScreen::ButtonInfo::alloc(ButtonID id, KeyModifierMask mask)
{
ButtonInfo *info = (ButtonInfo *)malloc(sizeof(ButtonInfo));
info->m_button = id;
info->m_mask = mask;
return info;
}
IPrimaryScreen::ButtonInfo *IPrimaryScreen::ButtonInfo::alloc(const ButtonInfo &x)
{
ButtonInfo *info = (ButtonInfo *)malloc(sizeof(ButtonInfo));
info->m_button = x.m_button;
info->m_mask = x.m_mask;
return info;
}
bool IPrimaryScreen::ButtonInfo::equal(const ButtonInfo *a, const ButtonInfo *b)
{
return (a->m_button == b->m_button && a->m_mask == b->m_mask);
}
//
// IPrimaryScreen::MotionInfo
//
IPrimaryScreen::MotionInfo *IPrimaryScreen::MotionInfo::alloc(SInt32 x, SInt32 y)
{
MotionInfo *info = (MotionInfo *)malloc(sizeof(MotionInfo));
info->m_x = x;
info->m_y = y;
return info;
}
//
// IPrimaryScreen::WheelInfo
//
IPrimaryScreen::WheelInfo *IPrimaryScreen::WheelInfo::alloc(SInt32 xDelta, SInt32 yDelta)
{
WheelInfo *info = (WheelInfo *)malloc(sizeof(WheelInfo));
info->m_xDelta = xDelta;
info->m_yDelta = yDelta;
return info;
}
//
// IPrimaryScreen::HotKeyInfo
//
IPrimaryScreen::HotKeyInfo *IPrimaryScreen::HotKeyInfo::alloc(UInt32 id)
{
HotKeyInfo *info = (HotKeyInfo *)malloc(sizeof(HotKeyInfo));
info->m_id = id;
return info;
}
//
// IPrimaryScreen::EiConnectInfo
//
IPrimaryScreen::EiConnectInfo *IPrimaryScreen::EiConnectInfo::alloc(int fd)
{
EiConnectInfo *info = (EiConnectInfo *)malloc(sizeof(EiConnectInfo));
info->m_fd = fd;
return info;
}
| 2,390
|
C++
|
.cpp
| 79
| 28.291139
| 96
| 0.746626
|
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,487
|
Config.cpp
|
deskflow_deskflow/src/lib/deskflow/Config.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 "Config.h"
#include "base/Log.h"
#include <cstring>
#include <filesystem>
#include <string>
#include <vector>
// Use .h for fallback with 3.3.0
#include <toml++/toml.h>
namespace deskflow {
Config::Config(const std::string &filename, const std::string §ion) : m_filename(filename), m_section(section)
{
}
const char *const *Config::argv() const
{
return m_argv.data();
}
int Config::argc() const
{
return static_cast<int>(m_argv.size());
}
bool Config::load(const std::string &firstArg)
{
if (!firstArg.empty()) {
m_args.push_back(firstArg);
}
if (m_filename.empty()) {
throw NoConfigFilenameError();
}
if (!std::filesystem::exists(m_filename)) {
LOG((CLOG_ERR "config file not found: %s", m_filename.c_str()));
return false;
}
toml::table configTable;
try {
LOG((CLOG_INFO "loading config file: %s", m_filename.c_str()));
configTable = toml::parse_file(m_filename);
} catch (const toml::parse_error &err) {
LOG((CLOG_ERR "toml parse error: %s", err.what()));
throw ParseError();
} catch (const std::exception &err) {
LOG((CLOG_ERR "unknown parse error: %s", err.what()));
throw ParseError();
}
if (!configTable.contains(m_section)) {
LOG((CLOG_WARN "no %s section found in config file", m_section.c_str()));
return false;
}
const auto §ion = configTable[m_section];
const auto args = section["args"];
if (!args.is_table()) {
LOG((CLOG_WARN "no args table found in config file"));
return false;
}
std::string specialLastArg = "";
const auto &table = *(args.as_table());
for (const auto &pair : table) {
const auto &key = pair.first;
if (key.str() == "_last") {
specialLastArg = pair.second.as_string()->get();
continue;
}
m_args.push_back("--" + std::string(key.str()));
if (pair.second.is_string()) {
const auto value = pair.second.as_string()->get();
m_args.push_back(value);
}
}
if (!specialLastArg.empty()) {
m_args.push_back(specialLastArg);
}
if (m_args.empty()) {
LOG((CLOG_WARN "no args loaded from config file"));
return false;
}
for (const auto &arg : m_args) {
m_argv.push_back(arg.c_str());
}
return true;
}
} // namespace deskflow
| 2,951
|
C++
|
.cpp
| 96
| 27.458333
| 114
| 0.672554
|
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,488
|
ServerApp.cpp
|
deskflow_deskflow/src/lib/deskflow/ServerApp.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012 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 "deskflow/ServerApp.h"
#include "arch/Arch.h"
#include "base/IEventQueue.h"
#include "base/Log.h"
#include "base/Path.h"
#include "base/TMethodEventJob.h"
#include "common/constants.h"
#include "deskflow/App.h"
#include "deskflow/ArgParser.h"
#include "deskflow/Screen.h"
#include "deskflow/ServerArgs.h"
#include "deskflow/ServerTaskBarReceiver.h"
#include "deskflow/XScreen.h"
#include "net/InverseSockets/InverseSocketFactory.h"
#include "net/SocketMultiplexer.h"
#include "net/TCPSocketFactory.h"
#include "net/XSocket.h"
#include "server/ClientListener.h"
#include "server/ClientProxy.h"
#include "server/Config.h"
#include "server/PrimaryClient.h"
#include "server/Server.h"
#if SYSAPI_WIN32
#include "arch/win32/ArchMiscWindows.h"
#endif
#if WINAPI_MSWINDOWS
#include "platform/MSWindowsScreen.h"
#endif
#if WINAPI_XWINDOWS
#include "platform/XWindowsScreen.h"
#endif
#if WINAPI_LIBEI
#include "platform/EiScreen.h"
#endif
#if WINAPI_CARBON
#include "platform/OSXDragSimulator.h"
#include "platform/OSXScreen.h"
#endif
#if defined(WINAPI_XWINDOWS) or defined(WINAPI_LIBEI)
#include "platform/wayland.h"
#endif
#if defined(MAC_OS_X_VERSION_10_7)
#include "base/TMethodJob.h"
#include "mt/Thread.h"
#endif
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdio.h>
using namespace deskflow::server;
//
// ServerApp
//
ServerApp::ServerApp(IEventQueue *events, CreateTaskBarReceiverFunc createTaskBarReceiver)
: App(events, createTaskBarReceiver, new deskflow::ServerArgs()),
m_server(NULL),
m_serverState(kUninitialized),
m_serverScreen(NULL),
m_primaryClient(NULL),
m_listener(NULL),
m_timer(NULL),
m_deskflowAddress(NULL)
{
}
ServerApp::~ServerApp()
{
}
void ServerApp::parseArgs(int argc, const char *const *argv)
{
ArgParser argParser(this);
bool result = argParser.parseServerArgs(args(), argc, argv);
if (!result || args().m_shouldExitOk || args().m_shouldExitFail) {
if (args().m_shouldExitOk) {
m_bye(kExitSuccess);
} else {
m_bye(kExitArgs);
}
} else {
if (!args().m_deskflowAddress.empty()) {
try {
*m_deskflowAddress = NetworkAddress(args().m_deskflowAddress, kDefaultPort);
m_deskflowAddress->resolve();
} catch (XSocketAddress &e) {
LOG((CLOG_CRIT "%s: %s" BYE, args().m_pname, e.what(), args().m_pname));
m_bye(kExitArgs);
}
}
}
}
void ServerApp::help()
{
const auto userConfig = ARCH->concatPath(ARCH->getUserDirectory(), CONFIG_NAME);
const auto sysConfig = ARCH->concatPath(ARCH->getSystemDirectory(), CONFIG_NAME);
std::stringstream help;
help << "Usage: " << args().m_pname
<< " [--address <address>]"
<< " [--config <pathname>]"
#if WINAPI_XWINDOWS
<< " [--display <display>] [--no-xinitthreads]"
#endif
#ifdef WINAPI_LIBEI
<< " [--no-wayland-ei]"
#endif
<< HELP_SYS_ARGS HELP_COMMON_ARGS "\n\n"
<< "Start the " << kAppName << " mouse/keyboard sharing server.\n"
<< "\n"
<< " -a, --address <address> listen for clients on the given address.\n"
<< " -c, --config <pathname> use the named configuration file "
<< "instead.\n" HELP_COMMON_INFO_1
#if WINAPI_XWINDOWS
<< " --display <display> when in X mode, connect to the X server\n"
<< " at <display>.\n"
<< " --no-xinitthreads do not call XInitThreads()\n"
#endif
<< HELP_SYS_INFO HELP_COMMON_INFO_2 "\n"
<< "* marks defaults.\n"
<< kHelpNoWayland
<< "\n"
<< "The argument for --address is of the form: [<hostname>][:<port>]. "
"The\n"
<< "hostname must be the address or hostname of an interface on the "
<< "system.\n"
<< "The default is to listen on all interfaces. The port overrides the\n"
<< "default port, " << kDefaultPort << ".\n"
<< "\n"
<< "If no configuration file pathname is provided then the first of the\n"
<< "following to load successfully sets the configuration:\n"
<< " " << userConfig << "\n"
<< " " << sysConfig << "\n";
LOG((CLOG_PRINT "%s", help.str().c_str()));
}
void ServerApp::reloadSignalHandler(Arch::ESignal, void *)
{
IEventQueue *events = App::instance().getEvents();
events->addEvent(Event(events->forServerApp().reloadConfig(), events->getSystemTarget()));
}
void ServerApp::reloadConfig(const Event &, void *)
{
LOG((CLOG_DEBUG "reload configuration"));
if (loadConfig(args().m_configFile)) {
if (m_server != NULL) {
m_server->setConfig(*args().m_config);
}
LOG((CLOG_NOTE "reloaded configuration"));
}
}
void ServerApp::loadConfig()
{
bool loaded = false;
std::string path;
// load the config file, if specified
if (!args().m_configFile.empty()) {
path = args().m_configFile;
loaded = loadConfig(path);
}
// load the default configuration if no explicit file given
else {
// get the user's home directory
path = ARCH->getUserDirectory();
if (!path.empty()) {
// complete path
path = ARCH->concatPath(path, CONFIG_NAME);
// now try loading the user's configuration
if (loadConfig(path)) {
loaded = true;
args().m_configFile = path;
}
}
if (!loaded) {
// try the system-wide config file
path = ARCH->getSystemDirectory();
if (!path.empty()) {
path = ARCH->concatPath(path, CONFIG_NAME);
if (loadConfig(path)) {
loaded = true;
args().m_configFile = path;
}
}
}
}
if (!loaded) {
LOG((CLOG_CRIT "%s: failed to load config: %s", args().m_pname, path.c_str()));
m_bye(kExitConfig);
}
}
bool ServerApp::loadConfig(const String &pathname)
{
try {
// load configuration
LOG((CLOG_DEBUG "opening configuration \"%s\"", pathname.c_str()));
std::ifstream configStream(deskflow::filesystem::path(pathname));
if (!configStream.is_open()) {
// report failure to open configuration as a debug message
// since we try several paths and we expect some to be
// missing.
LOG((CLOG_DEBUG "cannot open configuration \"%s\"", pathname.c_str()));
return false;
}
configStream >> *args().m_config;
LOG((CLOG_DEBUG "configuration read successfully"));
return true;
} catch (XConfigRead &e) {
// report error in configuration file
LOG((CLOG_ERR "cannot read configuration \"%s\": %s", pathname.c_str(), e.what()));
}
return false;
}
void ServerApp::forceReconnect(const Event &, void *)
{
if (m_server != NULL) {
m_server->disconnect();
}
}
void ServerApp::handleClientConnected(const Event &, void *vlistener)
{
ClientListener *listener = static_cast<ClientListener *>(vlistener);
ClientProxy *client = listener->getNextClient();
if (client != NULL) {
m_server->adoptClient(client);
updateStatus();
}
}
void ServerApp::handleClientsDisconnected(const Event &, void *)
{
m_events->addEvent(Event(Event::kQuit));
}
void ServerApp::closeServer(Server *server)
{
if (server == NULL) {
return;
}
// tell all clients to disconnect
server->disconnect();
// wait for clients to disconnect for up to timeout seconds
double timeout = 3.0;
EventQueueTimer *timer = m_events->newOneShotTimer(timeout, NULL);
m_events->adoptHandler(
Event::kTimer, timer, new TMethodEventJob<ServerApp>(this, &ServerApp::handleClientsDisconnected)
);
m_events->adoptHandler(
m_events->forServer().disconnected(), server,
new TMethodEventJob<ServerApp>(this, &ServerApp::handleClientsDisconnected)
);
m_events->loop();
m_events->removeHandler(Event::kTimer, timer);
m_events->deleteTimer(timer);
m_events->removeHandler(m_events->forServer().disconnected(), server);
// done with server
delete server;
}
void ServerApp::stopRetryTimer()
{
if (m_timer != NULL) {
m_events->removeHandler(Event::kTimer, m_timer);
m_events->deleteTimer(m_timer);
m_timer = NULL;
}
}
void ServerApp::updateStatus()
{
updateStatus("");
}
void ServerApp::updateStatus(const String &msg)
{
if (m_taskBarReceiver) {
m_taskBarReceiver->updateStatus(m_server, msg);
}
}
void ServerApp::closeClientListener(ClientListener *listen)
{
if (listen != NULL) {
m_events->removeHandler(m_events->forClientListener().connected(), listen);
delete listen;
}
}
void ServerApp::stopServer()
{
if (m_serverState == kStarted) {
closeServer(m_server);
closeClientListener(m_listener);
m_server = NULL;
m_listener = NULL;
m_serverState = kInitialized;
} else if (m_serverState == kStarting) {
stopRetryTimer();
m_serverState = kInitialized;
}
assert(m_server == NULL);
assert(m_listener == NULL);
}
void ServerApp::closePrimaryClient(PrimaryClient *primaryClient)
{
delete primaryClient;
}
void ServerApp::closeServerScreen(deskflow::Screen *screen)
{
if (screen != NULL) {
m_events->removeHandler(m_events->forIScreen().error(), screen->getEventTarget());
m_events->removeHandler(m_events->forIScreen().suspend(), screen->getEventTarget());
m_events->removeHandler(m_events->forIScreen().resume(), screen->getEventTarget());
delete screen;
}
}
void ServerApp::cleanupServer()
{
stopServer();
if (m_serverState == kInitialized) {
closePrimaryClient(m_primaryClient);
closeServerScreen(m_serverScreen);
m_primaryClient = NULL;
m_serverScreen = NULL;
m_serverState = kUninitialized;
} else if (m_serverState == kInitializing || m_serverState == kInitializingToStart) {
stopRetryTimer();
m_serverState = kUninitialized;
}
assert(m_primaryClient == NULL);
assert(m_serverScreen == NULL);
assert(m_serverState == kUninitialized);
}
void ServerApp::retryHandler(const Event &, void *)
{
// discard old timer
assert(m_timer != NULL);
stopRetryTimer();
// try initializing/starting the server again
switch (m_serverState) {
case kUninitialized:
case kInitialized:
case kStarted:
assert(0 && "bad internal server state");
break;
case kInitializing:
LOG((CLOG_DEBUG1 "retry server initialization"));
m_serverState = kUninitialized;
if (!initServer()) {
m_events->addEvent(Event(Event::kQuit));
}
break;
case kInitializingToStart:
LOG((CLOG_DEBUG1 "retry server initialization"));
m_serverState = kUninitialized;
if (!initServer()) {
m_events->addEvent(Event(Event::kQuit));
} else if (m_serverState == kInitialized) {
LOG((CLOG_DEBUG1 "starting server"));
if (!startServer()) {
m_events->addEvent(Event(Event::kQuit));
}
}
break;
case kStarting:
LOG((CLOG_DEBUG1 "retry starting server"));
m_serverState = kInitialized;
if (!startServer()) {
m_events->addEvent(Event(Event::kQuit));
}
break;
}
}
bool ServerApp::initServer()
{
// skip if already initialized or initializing
if (m_serverState != kUninitialized) {
return true;
}
double retryTime;
deskflow::Screen *serverScreen = NULL;
PrimaryClient *primaryClient = NULL;
try {
String name = args().m_config->getCanonicalName(args().m_name);
serverScreen = openServerScreen();
primaryClient = openPrimaryClient(name, serverScreen);
m_serverScreen = serverScreen;
m_primaryClient = primaryClient;
m_serverState = kInitialized;
updateStatus();
return true;
} catch (XScreenUnavailable &e) {
LOG((CLOG_WARN "primary screen unavailable: %s", e.what()));
closePrimaryClient(primaryClient);
closeServerScreen(serverScreen);
updateStatus(String("primary screen unavailable: ") + e.what());
retryTime = e.getRetryTime();
} catch (XScreenOpenFailure &e) {
LOG((CLOG_CRIT "failed to start server: %s", e.what()));
closePrimaryClient(primaryClient);
closeServerScreen(serverScreen);
return false;
} catch (XBase &e) {
LOG((CLOG_CRIT "failed to start server: %s", e.what()));
closePrimaryClient(primaryClient);
closeServerScreen(serverScreen);
return false;
}
if (args().m_restartable) {
// install a timer and handler to retry later
assert(m_timer == NULL);
LOG((CLOG_DEBUG "retry in %.0f seconds", retryTime));
m_timer = m_events->newOneShotTimer(retryTime, NULL);
m_events->adoptHandler(Event::kTimer, m_timer, new TMethodEventJob<ServerApp>(this, &ServerApp::retryHandler));
m_serverState = kInitializing;
return true;
} else {
// don't try again
return false;
}
}
deskflow::Screen *ServerApp::openServerScreen()
{
deskflow::Screen *screen = createScreen();
screen->setEnableDragDrop(argsBase().m_enableDragDrop);
m_events->adoptHandler(
m_events->forIScreen().error(), screen->getEventTarget(),
new TMethodEventJob<ServerApp>(this, &ServerApp::handleScreenError)
);
m_events->adoptHandler(
m_events->forIScreen().suspend(), screen->getEventTarget(),
new TMethodEventJob<ServerApp>(this, &ServerApp::handleSuspend)
);
m_events->adoptHandler(
m_events->forIScreen().resume(), screen->getEventTarget(),
new TMethodEventJob<ServerApp>(this, &ServerApp::handleResume)
);
return screen;
}
bool ServerApp::startServer()
{
// skip if already started or starting
if (m_serverState == kStarting || m_serverState == kStarted) {
return true;
}
// initialize if necessary
if (m_serverState != kInitialized) {
if (!initServer()) {
// hard initialization failure
return false;
}
if (m_serverState == kInitializing) {
// not ready to start
m_serverState = kInitializingToStart;
return true;
}
assert(m_serverState == kInitialized);
}
ClientListener *listener = NULL;
try {
listener = openClientListener(args().m_config->getDeskflowAddress());
m_server = openServer(*args().m_config, m_primaryClient);
listener->setServer(m_server);
m_server->setListener(listener);
m_listener = listener;
updateStatus();
LOG((CLOG_NOTE "started server, waiting for clients"));
m_serverState = kStarted;
return true;
} catch (XSocketAddressInUse &e) {
if (args().m_restartable) {
LOG((CLOG_ERR "cannot listen for clients: %s", e.what()));
} else {
LOG((CLOG_CRIT "cannot listen for clients: %s", e.what()));
}
closeClientListener(listener);
updateStatus(String("cannot listen for clients: ") + e.what());
} catch (XBase &e) {
LOG((CLOG_CRIT "failed to start server: %s", e.what()));
closeClientListener(listener);
return false;
}
if (args().m_restartable) {
// install a timer and handler to retry later
assert(m_timer == NULL);
const auto retryTime = 10.0;
LOG((CLOG_DEBUG "retry in %.0f seconds", retryTime));
m_timer = m_events->newOneShotTimer(retryTime, NULL);
m_events->adoptHandler(Event::kTimer, m_timer, new TMethodEventJob<ServerApp>(this, &ServerApp::retryHandler));
m_serverState = kStarting;
return true;
} else {
// don't try again
return false;
}
}
deskflow::Screen *ServerApp::createScreen()
{
#if WINAPI_MSWINDOWS
return new deskflow::Screen(
new MSWindowsScreen(true, args().m_noHooks, args().m_stopOnDeskSwitch, m_events), m_events
);
#endif
#if defined(WINAPI_XWINDOWS) or defined(WINAPI_LIBEI)
if (deskflow::platform::isWayland()) {
#if WINAPI_LIBEI
LOG((CLOG_INFO "using ei screen for wayland"));
return new deskflow::Screen(new deskflow::EiScreen(true, m_events, true), m_events);
#else
throw XNoEiSupport();
#endif
}
#endif
#if WINAPI_XWINDOWS
LOG((CLOG_INFO "using legacy x windows screen"));
return new deskflow::Screen(
new XWindowsScreen(args().m_display, true, args().m_disableXInitThreads, 0, m_events), m_events
);
#elif WINAPI_CARBON
return new deskflow::Screen(new OSXScreen(m_events, true), m_events);
#endif
}
PrimaryClient *ServerApp::openPrimaryClient(const String &name, deskflow::Screen *screen)
{
LOG((CLOG_DEBUG1 "creating primary screen"));
return new PrimaryClient(name, screen);
}
void ServerApp::handleScreenError(const Event &, void *)
{
LOG((CLOG_CRIT "error on screen"));
m_events->addEvent(Event(Event::kQuit));
}
void ServerApp::handleSuspend(const Event &, void *)
{
if (!m_suspended) {
LOG((CLOG_INFO "suspend"));
stopServer();
m_suspended = true;
}
}
void ServerApp::handleResume(const Event &, void *)
{
if (m_suspended) {
LOG((CLOG_INFO "resume"));
startServer();
m_suspended = false;
}
}
ClientListener *ServerApp::openClientListener(const NetworkAddress &address)
{
ClientListener *listen = new ClientListener(getAddress(address), getSocketFactory(), m_events, args().m_enableCrypto);
m_events->adoptHandler(
m_events->forClientListener().connected(), listen,
new TMethodEventJob<ServerApp>(this, &ServerApp::handleClientConnected, listen)
);
return listen;
}
Server *ServerApp::openServer(ServerConfig &config, PrimaryClient *primaryClient)
{
Server *server = new Server(config, primaryClient, m_serverScreen, m_events, args());
try {
m_events->adoptHandler(
m_events->forServer().disconnected(), server, new TMethodEventJob<ServerApp>(this, &ServerApp::handleNoClients)
);
m_events->adoptHandler(
m_events->forServer().screenSwitched(), server,
new TMethodEventJob<ServerApp>(this, &ServerApp::handleScreenSwitched)
);
} catch (std::bad_alloc &ba) {
delete server;
throw ba;
}
return server;
}
void ServerApp::handleNoClients(const Event &, void *)
{
updateStatus();
}
void ServerApp::handleScreenSwitched(const Event &e, void *)
{
}
ISocketFactory *ServerApp::getSocketFactory() const
{
ISocketFactory *socketFactory = nullptr;
if (args().m_config->isClientMode()) {
socketFactory = new InverseSocketFactory(m_events, getSocketMultiplexer());
} else {
socketFactory = new TCPSocketFactory(m_events, getSocketMultiplexer());
}
return socketFactory;
}
NetworkAddress ServerApp::getAddress(const NetworkAddress &address) const
{
if (args().m_config->isClientMode()) {
const auto clientAddress = args().m_config->getClientAddress();
NetworkAddress addr(clientAddress.c_str(), kDefaultPort);
addr.resolve();
return addr;
} else {
return address;
}
}
int ServerApp::mainLoop()
{
// create socket multiplexer. this must happen after daemonization
// on unix because threads evaporate across a fork().
SocketMultiplexer multiplexer;
setSocketMultiplexer(&multiplexer);
// if configuration has no screens then add this system
// as the default
if (args().m_config->begin() == args().m_config->end()) {
args().m_config->addScreen(args().m_name);
}
// set the contact address, if provided, in the config.
// otherwise, if the config doesn't have an address, use
// the default.
if (m_deskflowAddress->isValid()) {
args().m_config->setDeskflowAddress(*m_deskflowAddress);
} else if (!args().m_config->getDeskflowAddress().isValid()) {
args().m_config->setDeskflowAddress(NetworkAddress(kDefaultPort));
}
// canonicalize the primary screen name
String primaryName = args().m_config->getCanonicalName(args().m_name);
if (primaryName.empty()) {
LOG((CLOG_CRIT "unknown screen name `%s'", args().m_name.c_str()));
return kExitFailed;
}
// start server, etc
appUtil().startNode();
// init ipc client after node start, since create a new screen wipes out
// the event queue (the screen ctors call adoptBuffer).
if (argsBase().m_enableIpc) {
initIpcClient();
}
// handle hangup signal by reloading the server's configuration
ARCH->setSignalHandler(Arch::kHANGUP, &reloadSignalHandler, NULL);
m_events->adoptHandler(
m_events->forServerApp().reloadConfig(), m_events->getSystemTarget(),
new TMethodEventJob<ServerApp>(this, &ServerApp::reloadConfig)
);
// handle force reconnect event by disconnecting clients. they'll
// reconnect automatically.
m_events->adoptHandler(
m_events->forServerApp().forceReconnect(), m_events->getSystemTarget(),
new TMethodEventJob<ServerApp>(this, &ServerApp::forceReconnect)
);
// to work around the sticky meta keys problem, we'll give users
// the option to reset the state of the server.
m_events->adoptHandler(
m_events->forServerApp().resetServer(), m_events->getSystemTarget(),
new TMethodEventJob<ServerApp>(this, &ServerApp::resetServer)
);
// run event loop. if startServer() failed we're supposed to retry
// later. the timer installed by startServer() will take care of
// that.
DAEMON_RUNNING(true);
#if defined(MAC_OS_X_VERSION_10_7)
Thread thread(new TMethodJob<ServerApp>(this, &ServerApp::runEventsLoop, NULL));
// wait until carbon loop is ready
OSXScreen *screen = dynamic_cast<OSXScreen *>(m_serverScreen->getPlatformScreen());
screen->waitForCarbonLoop();
runCocoaApp();
#else
m_events->loop();
#endif
DAEMON_RUNNING(false);
// close down
LOG((CLOG_DEBUG1 "stopping server"));
m_events->removeHandler(m_events->forServerApp().forceReconnect(), m_events->getSystemTarget());
m_events->removeHandler(m_events->forServerApp().reloadConfig(), m_events->getSystemTarget());
cleanupServer();
updateStatus();
LOG((CLOG_NOTE "stopped server"));
if (argsBase().m_enableIpc) {
cleanupIpcClient();
}
return kExitSuccess;
}
void ServerApp::resetServer(const Event &, void *)
{
LOG((CLOG_DEBUG1 "resetting server"));
stopServer();
cleanupServer();
startServer();
}
int ServerApp::runInner(int argc, char **argv, ILogOutputter *outputter, StartupFunc startup)
{
// general initialization
m_deskflowAddress = new NetworkAddress;
args().m_config = std::make_shared<Config>(m_events);
args().m_pname = ARCH->getBasename(argv[0]);
// install caller's output filter
if (outputter != NULL) {
CLOG->insert(outputter);
}
// run
int result = startup(argc, argv);
if (m_taskBarReceiver) {
// done with task bar receiver
delete m_taskBarReceiver;
}
delete m_deskflowAddress;
return result;
}
int daemonMainLoopStatic(int argc, const char **argv)
{
return ServerApp::instance().daemonMainLoop(argc, argv);
}
int ServerApp::standardStartup(int argc, char **argv)
{
initApp(argc, argv);
// daemonize if requested
if (args().m_daemon) {
return ARCH->daemonize(daemonName(), daemonMainLoopStatic);
} else {
return mainLoop();
}
}
int ServerApp::foregroundStartup(int argc, char **argv)
{
initApp(argc, argv);
// never daemonize
return mainLoop();
}
const char *ServerApp::daemonName() const
{
#if SYSAPI_WIN32
return "Deskflow Server";
#elif SYSAPI_UNIX
return "deskflow-server";
#endif
}
const char *ServerApp::daemonInfo() const
{
#if SYSAPI_WIN32
return "Shares this computers mouse and keyboard with other computers.";
#elif SYSAPI_UNIX
return "";
#endif
}
void ServerApp::startNode()
{
// start the server. if this return false then we've failed and
// we shouldn't retry.
LOG((CLOG_DEBUG1 "starting server"));
if (!startServer()) {
m_bye(kExitFailed);
}
}
| 23,932
|
C++
|
.cpp
| 753
| 28.116866
| 120
| 0.696414
|
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,489
|
KeyMap.cpp
|
deskflow_deskflow/src/lib/deskflow/KeyMap.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2005 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 "deskflow/KeyMap.h"
#include "base/Log.h"
#include "deskflow/App.h"
#include "deskflow/ArgsBase.h"
#include "deskflow/key_types.h"
#include <assert.h>
#include <cctype>
#include <cstdlib>
namespace deskflow {
KeyMap::NameToKeyMap *KeyMap::s_nameToKeyMap = NULL;
KeyMap::NameToModifierMap *KeyMap::s_nameToModifierMap = NULL;
KeyMap::KeyToNameMap *KeyMap::s_keyToNameMap = NULL;
KeyMap::ModifierToNameMap *KeyMap::s_modifierToNameMap = NULL;
KeyMap::KeyMap() : m_numGroups(0), m_composeAcrossGroups(false)
{
m_modifierKeyItem.m_id = kKeyNone;
m_modifierKeyItem.m_group = 0;
m_modifierKeyItem.m_button = 0;
m_modifierKeyItem.m_required = 0;
m_modifierKeyItem.m_sensitive = 0;
m_modifierKeyItem.m_generates = 0;
m_modifierKeyItem.m_dead = false;
m_modifierKeyItem.m_lock = false;
m_modifierKeyItem.m_client = 0;
}
KeyMap::~KeyMap()
{
// do nothing
}
void KeyMap::swap(KeyMap &x)
{
m_keyIDMap.swap(x.m_keyIDMap);
m_modifierKeys.swap(x.m_modifierKeys);
m_halfDuplex.swap(x.m_halfDuplex);
m_halfDuplexMods.swap(x.m_halfDuplexMods);
SInt32 tmp1 = m_numGroups;
m_numGroups = x.m_numGroups;
x.m_numGroups = tmp1;
bool tmp2 = m_composeAcrossGroups;
m_composeAcrossGroups = x.m_composeAcrossGroups;
x.m_composeAcrossGroups = tmp2;
}
void KeyMap::addKeyEntry(const KeyItem &item)
{
// ignore kKeyNone
if (item.m_id == kKeyNone) {
return;
}
// resize number of groups for key
SInt32 numGroups = item.m_group + 1;
if (getNumGroups() > numGroups) {
numGroups = getNumGroups();
}
KeyGroupTable &groupTable = m_keyIDMap[item.m_id];
if (groupTable.size() < static_cast<size_t>(numGroups)) {
groupTable.resize(numGroups);
}
// make a list from the item
KeyItemList items;
items.push_back(item);
// set group and dead key flag on the item
KeyItem &newItem = items.back();
newItem.m_dead = isDeadKey(item.m_id);
// mask the required bits with the sensitive bits
newItem.m_required &= newItem.m_sensitive;
// see if we already have this item; just return if so
KeyEntryList &entries = groupTable[item.m_group];
for (size_t i = 0, n = entries.size(); i < n; ++i) {
if (entries[i].size() == 1 && newItem == entries[i][0]) {
return;
}
}
// add item list
entries.push_back(items);
LOG(
(CLOG_DEBUG5 "add key: %04x %d %03x %04x (%04x %04x %04x)%s", newItem.m_id, newItem.m_group, newItem.m_button,
newItem.m_client, newItem.m_required, newItem.m_sensitive, newItem.m_generates, newItem.m_dead ? " dead" : "")
);
}
void KeyMap::addKeyAliasEntry(
KeyID targetID, SInt32 group, KeyModifierMask targetRequired, KeyModifierMask targetSensitive, KeyID sourceID,
KeyModifierMask sourceRequired, KeyModifierMask sourceSensitive
)
{
// if we can already generate the target as desired then we're done.
if (findCompatibleKey(targetID, group, targetRequired, targetSensitive) != NULL) {
return;
}
// find a compatible source, preferably in the same group
for (SInt32 gd = 0, n = getNumGroups(); gd < n; ++gd) {
SInt32 eg = getEffectiveGroup(group, gd);
const KeyItemList *sourceEntry = findCompatibleKey(sourceID, eg, sourceRequired, sourceSensitive);
if (sourceEntry != NULL && sourceEntry->size() == 1) {
KeyMap::KeyItem targetItem = sourceEntry->back();
targetItem.m_id = targetID;
targetItem.m_group = eg;
addKeyEntry(targetItem);
break;
}
}
}
bool KeyMap::addKeyCombinationEntry(KeyID id, SInt32 group, const KeyID *keys, UInt32 numKeys)
{
// disallow kKeyNone
if (id == kKeyNone) {
return false;
}
SInt32 numGroups = group + 1;
if (getNumGroups() > numGroups) {
numGroups = getNumGroups();
}
KeyGroupTable &groupTable = m_keyIDMap[id];
if (groupTable.size() < static_cast<size_t>(numGroups)) {
groupTable.resize(numGroups);
}
if (!groupTable[group].empty()) {
// key is already in the table
return false;
}
// convert to buttons
KeyItemList items;
for (UInt32 i = 0; i < numKeys; ++i) {
KeyIDMap::const_iterator gtIndex = m_keyIDMap.find(keys[i]);
if (gtIndex == m_keyIDMap.end()) {
return false;
}
const KeyGroupTable &groupTable = gtIndex->second;
// if we allow group switching during composition then search all
// groups for keys, otherwise search just the given group.
SInt32 n = 1;
if (m_composeAcrossGroups) {
n = (SInt32)groupTable.size();
}
bool found = false;
for (SInt32 gd = 0; gd < n && !found; ++gd) {
SInt32 eg = (group + gd) % getNumGroups();
const KeyEntryList &entries = groupTable[eg];
for (size_t j = 0; j < entries.size(); ++j) {
if (entries[j].size() == 1) {
found = true;
items.push_back(entries[j][0]);
break;
}
}
}
if (!found) {
// required key is not in keyboard group
return false;
}
}
// add key
groupTable[group].push_back(items);
return true;
}
void KeyMap::allowGroupSwitchDuringCompose()
{
m_composeAcrossGroups = true;
}
void KeyMap::addHalfDuplexButton(KeyButton button)
{
m_halfDuplex.insert(button);
}
void KeyMap::clearHalfDuplexModifiers()
{
m_halfDuplexMods.clear();
}
void KeyMap::addHalfDuplexModifier(KeyID key)
{
m_halfDuplexMods.insert(key);
}
void KeyMap::finish()
{
m_numGroups = findNumGroups();
// make sure every key has the same number of groups
for (KeyIDMap::iterator i = m_keyIDMap.begin(); i != m_keyIDMap.end(); ++i) {
i->second.resize(m_numGroups);
}
// compute keys that generate each modifier
setModifierKeys();
}
void KeyMap::foreachKey(ForeachKeyCallback cb, void *userData)
{
for (KeyIDMap::iterator i = m_keyIDMap.begin(); i != m_keyIDMap.end(); ++i) {
KeyGroupTable &groupTable = i->second;
for (size_t group = 0; group < groupTable.size(); ++group) {
KeyEntryList &entryList = groupTable[group];
for (size_t j = 0; j < entryList.size(); ++j) {
KeyItemList &itemList = entryList[j];
for (size_t k = 0; k < itemList.size(); ++k) {
(*cb)(i->first, static_cast<SInt32>(group), itemList[k], userData);
}
}
}
}
}
const KeyMap::KeyItem *KeyMap::mapKey(
Keystrokes &keys, KeyID id, SInt32 group, ModifierToKeys &activeModifiers, KeyModifierMask ¤tState,
KeyModifierMask desiredMask, bool isAutoRepeat, const String &lang
) const
{
LOG(
(CLOG_DEBUG1 "mapKey %04x (%d) with mask %04x, start state: %04x, group: %d", id, id, desiredMask, currentState,
group)
);
// handle group change
if (id == kKeyNextGroup) {
keys.push_back(Keystroke(1, false, false));
return NULL;
} else if (id == kKeyPrevGroup) {
keys.push_back(Keystroke(-1, false, false));
return NULL;
}
const KeyItem *item;
switch (id) {
case kKeyShift_L:
case kKeyShift_R:
case kKeyControl_L:
case kKeyControl_R:
case kKeyAlt_L:
case kKeyAlt_R:
case kKeyMeta_L:
case kKeyMeta_R:
case kKeySuper_L:
case kKeySuper_R:
case kKeyAltGr:
case kKeyCapsLock:
case kKeyNumLock:
case kKeyScrollLock:
item = mapModifierKey(keys, id, group, activeModifiers, currentState, desiredMask, isAutoRepeat, lang);
break;
case kKeySetModifiers:
if (!keysForModifierState(0, group, activeModifiers, currentState, desiredMask, desiredMask, 0, keys)) {
LOG((CLOG_DEBUG1 "unable to set modifiers %04x", desiredMask));
return NULL;
}
return &m_modifierKeyItem;
case kKeyClearModifiers:
if (!keysForModifierState(
0, group, activeModifiers, currentState, currentState & ~desiredMask, desiredMask, 0, keys
)) {
LOG((CLOG_DEBUG1 "unable to clear modifiers %04x", desiredMask));
return NULL;
}
return &m_modifierKeyItem;
default:
if (isCommand(desiredMask)) {
item = mapCommandKey(keys, id, group, activeModifiers, currentState, desiredMask, isAutoRepeat, lang);
} else {
item = mapCharacterKey(keys, id, group, activeModifiers, currentState, desiredMask, isAutoRepeat, lang);
}
break;
}
if (item != NULL) {
LOG((CLOG_DEBUG1 "mapped to %03x, new state %04x", item->m_button, currentState));
}
return item;
}
void KeyMap::setLanguageData(std::vector<String> layouts)
{
m_keyboardLayouts = std::move(layouts);
}
SInt32 KeyMap::getLanguageGroupID(SInt32 group, const String &lang) const
{
SInt32 id = group;
auto it = std::find(m_keyboardLayouts.begin(), m_keyboardLayouts.end(), lang);
if (it != m_keyboardLayouts.end()) {
id = static_cast<int>(std::distance(m_keyboardLayouts.begin(), it));
LOG((CLOG_DEBUG1 "language %s has group id %d", lang.c_str(), id));
} else {
LOG((CLOG_DEBUG1 "could not found requested language"));
}
return id;
}
SInt32 KeyMap::getNumGroups() const
{
return m_numGroups;
}
SInt32 KeyMap::getEffectiveGroup(SInt32 group, SInt32 offset) const
{
return (group + offset + getNumGroups()) % getNumGroups();
}
const KeyMap::KeyItemList *
KeyMap::findCompatibleKey(KeyID id, SInt32 group, KeyModifierMask required, KeyModifierMask sensitive) const
{
assert(group >= 0 && group < getNumGroups());
KeyIDMap::const_iterator i = m_keyIDMap.find(id);
if (i == m_keyIDMap.end()) {
return NULL;
}
const KeyEntryList &entries = i->second[group];
for (size_t j = 0; j < entries.size(); ++j) {
if ((entries[j].back().m_sensitive & sensitive) == 0 ||
(entries[j].back().m_required & sensitive) == (required & sensitive)) {
return &entries[j];
}
}
return NULL;
}
bool KeyMap::isHalfDuplex(KeyID key, KeyButton button) const
{
return (m_halfDuplex.count(button) + m_halfDuplexMods.count(key) > 0);
}
bool KeyMap::isCommand(KeyModifierMask mask) const
{
return ((mask & getCommandModifiers()) != 0);
}
KeyModifierMask KeyMap::getCommandModifiers() const
{
// we currently treat ctrl, alt, meta and super as command modifiers.
// some platforms may have a more limited set (OS X only needs Alt)
// but this works anyway.
return KeyModifierControl | KeyModifierAlt | KeyModifierAltGr | KeyModifierMeta | KeyModifierSuper;
}
void KeyMap::collectButtons(const ModifierToKeys &mods, ButtonToKeyMap &keys)
{
keys.clear();
for (ModifierToKeys::const_iterator i = mods.begin(); i != mods.end(); ++i) {
keys.insert(std::make_pair(i->second.m_button, &i->second));
}
}
void KeyMap::initModifierKey(KeyItem &item)
{
item.m_generates = 0;
item.m_lock = false;
switch (item.m_id) {
case kKeyShift_L:
case kKeyShift_R:
item.m_generates = KeyModifierShift;
break;
case kKeyControl_L:
case kKeyControl_R:
item.m_generates = KeyModifierControl;
break;
case kKeyAlt_L:
case kKeyAlt_R:
item.m_generates = KeyModifierAlt;
break;
case kKeyMeta_L:
case kKeyMeta_R:
item.m_generates = KeyModifierMeta;
break;
case kKeySuper_L:
case kKeySuper_R:
item.m_generates = KeyModifierSuper;
break;
case kKeyAltGr:
item.m_generates = KeyModifierAltGr;
break;
case kKeyCapsLock:
item.m_generates = KeyModifierCapsLock;
item.m_lock = true;
break;
case kKeyNumLock:
item.m_generates = KeyModifierNumLock;
item.m_lock = true;
break;
case kKeyScrollLock:
item.m_generates = KeyModifierScrollLock;
item.m_lock = true;
break;
default:
// not a modifier
break;
}
}
SInt32 KeyMap::findNumGroups() const
{
size_t max = 0;
for (KeyIDMap::const_iterator i = m_keyIDMap.begin(); i != m_keyIDMap.end(); ++i) {
if (i->second.size() > max) {
max = i->second.size();
}
}
return static_cast<SInt32>(max);
}
void KeyMap::setModifierKeys()
{
m_modifierKeys.clear();
m_modifierKeys.resize(kKeyModifierNumBits * getNumGroups());
for (KeyIDMap::const_iterator i = m_keyIDMap.begin(); i != m_keyIDMap.end(); ++i) {
const KeyGroupTable &groupTable = i->second;
for (size_t g = 0; g < groupTable.size(); ++g) {
const KeyEntryList &entries = groupTable[g];
for (size_t j = 0; j < entries.size(); ++j) {
// skip multi-key sequences
if (entries[j].size() != 1) {
continue;
}
// skip keys that don't generate a modifier
const KeyItem &item = entries[j].back();
if (item.m_generates == 0) {
continue;
}
// add key to each indicated modifier in this group
for (SInt32 b = 0; b < kKeyModifierNumBits; ++b) {
// skip if item doesn't generate bit b
if (((1u << b) & item.m_generates) != 0) {
SInt32 mIndex = (SInt32)g * kKeyModifierNumBits + b;
m_modifierKeys[mIndex].push_back(&item);
}
}
}
}
}
}
const KeyMap::KeyItem *KeyMap::mapCommandKey(
Keystrokes &keys, KeyID id, SInt32 group, ModifierToKeys &activeModifiers, KeyModifierMask ¤tState,
KeyModifierMask desiredMask, bool isAutoRepeat, const String &lang
) const
{
static const KeyModifierMask s_overrideModifiers = 0xffffu;
// find KeySym in table
KeyIDMap::const_iterator i = m_keyIDMap.find(id);
if (i == m_keyIDMap.end()) {
// unknown key
LOG((CLOG_DEBUG1 "key %04x is not on keyboard", id));
return NULL;
}
const KeyGroupTable &keyGroupTable = i->second;
// find the first key that generates this KeyID
const KeyItem *keyItem = NULL;
SInt32 numGroups = getNumGroups();
for (SInt32 groupOffset = 0; groupOffset < numGroups; ++groupOffset) {
SInt32 effectiveGroup = getEffectiveGroup(group, groupOffset);
const KeyEntryList &entryList = keyGroupTable[effectiveGroup];
for (size_t i = 0; i < entryList.size(); ++i) {
if (entryList[i].size() != 1) {
// ignore multikey entries
continue;
}
// match based on shift and make sure all required modifiers,
// except shift, are already in the desired mask; we're
// after the right button not the right character.
// we'll use desiredMask as-is, overriding the key's required
// modifiers, when synthesizing this button.
const KeyItem &item = entryList[i].back();
KeyModifierMask desiredShiftMask = KeyModifierShift & desiredMask;
KeyModifierMask requiredIgnoreShiftMask = item.m_required & ~KeyModifierShift;
if ((item.m_required & desiredShiftMask) == (item.m_sensitive & desiredShiftMask) &&
((requiredIgnoreShiftMask & desiredMask) == requiredIgnoreShiftMask)) {
LOG((CLOG_DEBUG1 "found key in group %d", effectiveGroup));
keyItem = &item;
break;
}
}
if (keyItem != NULL) {
break;
}
}
if (keyItem == NULL) {
// no mapping for this keysym
LOG((CLOG_DEBUG1 "no mapping for key %04x", id));
return NULL;
}
// make working copy of modifiers
ModifierToKeys newModifiers = activeModifiers;
KeyModifierMask newState = currentState;
SInt32 newGroup = group;
// don't try to change CapsLock
desiredMask = (desiredMask & ~KeyModifierCapsLock) | (currentState & KeyModifierCapsLock);
// add the key
if (!keysForKeyItem(
*keyItem, newGroup, newModifiers, newState, desiredMask, s_overrideModifiers, isAutoRepeat, keys, lang
)) {
LOG((CLOG_DEBUG1 "can't map key"));
keys.clear();
return NULL;
}
// add keystrokes to restore modifier keys
if (!keysToRestoreModifiers(*keyItem, group, newModifiers, newState, activeModifiers, keys)) {
LOG((CLOG_DEBUG1 "failed to restore modifiers"));
keys.clear();
return NULL;
}
// save new modifiers
activeModifiers = newModifiers;
currentState = newState;
return keyItem;
}
const KeyMap::KeyItemList *
KeyMap::getKeyItemList(const KeyMap::KeyGroupTable &keyGroupTable, SInt32 group, KeyModifierMask desiredMask) const
{
const KeyItemList *itemList = nullptr;
// find best key in any group, starting with the active group
for (SInt32 groupOffset = 0; groupOffset < getNumGroups(); ++groupOffset) {
auto effectiveGroup = getEffectiveGroup(group, groupOffset);
auto keyIndex = findBestKey(keyGroupTable[effectiveGroup], desiredMask);
if (keyIndex != -1) {
LOG((CLOG_DEBUG1 "found key in group %d", effectiveGroup));
itemList = &keyGroupTable[effectiveGroup][keyIndex];
break;
}
}
return itemList;
}
const KeyMap::KeyItem *KeyMap::mapCharacterKey(
Keystrokes &keys, KeyID id, SInt32 group, ModifierToKeys &activeModifiers, KeyModifierMask ¤tState,
KeyModifierMask desiredMask, bool isAutoRepeat, const String &lang
) const
{
// find KeySym in table
KeyIDMap::const_iterator i = m_keyIDMap.find(id);
if (i == m_keyIDMap.end()) {
// unknown key
LOG((CLOG_DEBUG1 "key %04x is not on keyboard", id));
return NULL;
}
// get keys to press for key
auto itemList = getKeyItemList(i->second, getLanguageGroupID(group, lang), desiredMask);
if (!itemList || itemList->empty()) {
// no mapping for this keysym
LOG((CLOG_DEBUG1 "no mapping for key %04x", id));
return NULL;
}
const KeyItem &keyItem = itemList->back();
// make working copy of modifiers
ModifierToKeys newModifiers = activeModifiers;
KeyModifierMask newState = currentState;
SInt32 newGroup = group;
// add each key
for (size_t j = 0; j < itemList->size(); ++j) {
if (!keysForKeyItem(itemList->at(j), newGroup, newModifiers, newState, desiredMask, 0, isAutoRepeat, keys, lang)) {
LOG((CLOG_DEBUG1 "can't map key"));
keys.clear();
return NULL;
}
}
// add keystrokes to restore modifier keys
if (!keysToRestoreModifiers(keyItem, group, newModifiers, newState, activeModifiers, keys)) {
LOG((CLOG_DEBUG1 "failed to restore modifiers"));
keys.clear();
return NULL;
}
// save new modifiers
activeModifiers = newModifiers;
currentState = newState;
return &keyItem;
}
void KeyMap::addGroupToKeystroke(Keystrokes &keys, SInt32 &group, const String &lang) const
{
group = getLanguageGroupID(group, lang);
keys.push_back(Keystroke(group, true, false));
}
const KeyMap::KeyItem *KeyMap::mapModifierKey(
Keystrokes &keys, KeyID id, SInt32 group, ModifierToKeys &activeModifiers, KeyModifierMask ¤tState,
KeyModifierMask desiredMask, bool isAutoRepeat, const String &lang
) const
{
return mapCharacterKey(keys, id, group, activeModifiers, currentState, desiredMask, isAutoRepeat, lang);
}
SInt32 KeyMap::findBestKey(const KeyEntryList &entryList, KeyModifierMask desiredState) const
{
// check for an item that can accommodate the desiredState exactly
for (SInt32 i = 0; i < (SInt32)entryList.size(); ++i) {
const KeyItem &item = entryList[i].back();
if ((item.m_required & desiredState) == item.m_required &&
(item.m_required & desiredState) == (item.m_sensitive & desiredState)) {
LOG((CLOG_DEBUG1 "best key index %d of %d (exact)", i + 1, entryList.size()));
return i;
}
}
// choose the item that requires the fewest modifier changes
SInt32 bestCount = 32;
SInt32 bestIndex = -1;
for (SInt32 i = 0; i < (SInt32)entryList.size(); ++i) {
const KeyItem &item = entryList[i].back();
KeyModifierMask change = ((item.m_required ^ desiredState) & item.m_sensitive);
SInt32 n = getNumModifiers(change);
if (n < bestCount) {
bestCount = n;
bestIndex = i;
}
}
if (bestIndex != -1) {
LOG((CLOG_DEBUG1 "best key index %d of %d (%d modifiers)", bestIndex + 1, entryList.size(), bestCount));
}
return bestIndex;
}
const KeyMap::KeyItem *KeyMap::keyForModifier(KeyButton button, SInt32 group, SInt32 modifierBit) const
{
assert(modifierBit >= 0 && modifierBit < kKeyModifierNumBits);
assert(group >= 0 && group < getNumGroups());
// find a key that generates the given modifier in the given group
// but doesn't use the given button, presumably because we're trying
// to generate a KeyID that's only bound the the given button.
// this is important when a shift button is modified by shift; we
// must use the other shift button to do the shifting.
const ModifierKeyItemList &items = m_modifierKeys[group * kKeyModifierNumBits + modifierBit];
for (ModifierKeyItemList::const_iterator i = items.begin(); i != items.end(); ++i) {
if ((*i)->m_button != button) {
return (*i);
}
}
return NULL;
}
bool KeyMap::keysForKeyItem(
const KeyItem &keyItem, SInt32 &group, ModifierToKeys &activeModifiers, KeyModifierMask ¤tState,
KeyModifierMask desiredState, KeyModifierMask overrideModifiers, bool isAutoRepeat, Keystrokes &keystrokes,
const String &lang
) const
{
static const KeyModifierMask s_notRequiredMask = KeyModifierAltGr | KeyModifierNumLock | KeyModifierScrollLock;
// add keystrokes to adjust the group
if (group != keyItem.m_group) {
group = keyItem.m_group;
addGroupToKeystroke(keystrokes, group, lang);
}
EKeystroke type;
if (keyItem.m_dead) {
// adjust modifiers for dead key
if (!keysForModifierState(
keyItem.m_button, group, activeModifiers, currentState, keyItem.m_required, keyItem.m_sensitive, 0,
keystrokes
)) {
LOG((CLOG_DEBUG1 "unable to match modifier state for dead key %d", keyItem.m_button));
return false;
}
// press and release the dead key
type = kKeystrokeClick;
} else {
// if this a command key then we don't have to match some of the
// key's required modifiers.
KeyModifierMask sensitive = keyItem.m_sensitive & ~overrideModifiers;
// XXX -- must handle pressing a modifier. in particular, if we want
// to synthesize a KeyID on level 1 of a KeyButton that has Shift_L
// mapped to level 0 then we must release that button if it's down
// (in order to satisfy a shift modifier) then press a different
// button (any other button) mapped to the shift modifier and then
// the Shift_L button.
// match key's required state
LOG((CLOG_DEBUG1 "state: %04x,%04x,%04x", currentState, keyItem.m_required, sensitive));
if (!keysForModifierState(
keyItem.m_button, group, activeModifiers, currentState, keyItem.m_required, sensitive, 0, keystrokes
)) {
LOG(
(CLOG_DEBUG1 "unable to match modifier state (%04x,%04x) for key %d", keyItem.m_required, keyItem.m_sensitive,
keyItem.m_button)
);
return false;
}
// match desiredState as closely as possible. we must not
// change any modifiers in keyItem.m_sensitive. and if the key
// is a modifier, we don't want to change that modifier.
LOG(
(CLOG_DEBUG1 "desired state: %04x %04x,%04x,%04x", desiredState, currentState, keyItem.m_required,
keyItem.m_sensitive)
);
if (!keysForModifierState(
keyItem.m_button, group, activeModifiers, currentState, desiredState, ~(sensitive | keyItem.m_generates),
s_notRequiredMask, keystrokes
)) {
LOG(
(CLOG_DEBUG1 "unable to match desired modifier state (%04x,%04x) for key %d", desiredState,
~keyItem.m_sensitive & 0xffffu, keyItem.m_button)
);
return false;
}
// repeat or press of key
type = isAutoRepeat ? kKeystrokeRepeat : kKeystrokePress;
}
addKeystrokes(type, keyItem, activeModifiers, currentState, keystrokes);
return true;
}
bool KeyMap::keysToRestoreModifiers(
const KeyItem &keyItem, SInt32, ModifierToKeys &activeModifiers, KeyModifierMask ¤tState,
const ModifierToKeys &desiredModifiers, Keystrokes &keystrokes
) const
{
// XXX -- we're not considering modified modifiers here
ModifierToKeys oldModifiers = activeModifiers;
// get the pressed modifier buttons before and after
ButtonToKeyMap oldKeys, newKeys;
collectButtons(oldModifiers, oldKeys);
collectButtons(desiredModifiers, newKeys);
// release unwanted keys
for (ModifierToKeys::const_iterator i = oldModifiers.begin(); i != oldModifiers.end(); ++i) {
KeyButton button = i->second.m_button;
if (button != keyItem.m_button && newKeys.count(button) == 0) {
EKeystroke type = kKeystrokeRelease;
if (i->second.m_lock) {
type = kKeystrokeUnmodify;
}
addKeystrokes(type, i->second, activeModifiers, currentState, keystrokes);
}
}
// press wanted keys
for (ModifierToKeys::const_iterator i = desiredModifiers.begin(); i != desiredModifiers.end(); ++i) {
KeyButton button = i->second.m_button;
if (button != keyItem.m_button && oldKeys.count(button) == 0) {
EKeystroke type = kKeystrokePress;
if (i->second.m_lock) {
type = kKeystrokeModify;
}
addKeystrokes(type, i->second, activeModifiers, currentState, keystrokes);
}
}
return true;
}
bool KeyMap::keysForModifierState(
KeyButton button, SInt32 group, ModifierToKeys &activeModifiers, KeyModifierMask ¤tState,
KeyModifierMask requiredState, KeyModifierMask sensitiveMask, KeyModifierMask notRequiredMask,
Keystrokes &keystrokes
) const
{
// compute which modifiers need changing
KeyModifierMask flipMask = ((currentState ^ requiredState) & sensitiveMask);
// if a modifier is not required then don't even try to match it. if
// we don't mask out notRequiredMask then we'll try to match those
// modifiers but succeed if we can't. however, this is known not
// to work if the key itself is a modifier (the numlock toggle can
// interfere) so we don't try to match at all.
flipMask &= ~notRequiredMask;
LOG(
(CLOG_DEBUG1 "flip: %04x (%04x vs %04x in %04x - %04x)", flipMask, currentState, requiredState,
sensitiveMask & 0xffffu, notRequiredMask & 0xffffu)
);
if (flipMask == 0) {
return true;
}
// fix modifiers. this is complicated by the fact that a modifier may
// be sensitive to other modifiers! (who thought that up?)
//
// we'll assume that modifiers with higher bits are affected by modifiers
// with lower bits. there's not much basis for that assumption except
// that we're pretty sure shift isn't changed by other modifiers.
SInt32 bit = kKeyModifierNumBits;
while (bit-- > 0) {
KeyModifierMask mask = (1u << bit);
if ((flipMask & mask) == 0) {
// modifier is already correct
continue;
}
// do we want the modifier active or inactive?
bool active = ((requiredState & mask) != 0);
// get the KeyItem for the modifier in the group
const KeyItem *keyItem = keyForModifier(button, group, bit);
if (keyItem == NULL) {
if ((mask & notRequiredMask) == 0) {
LOG((CLOG_DEBUG1 "no key for modifier %04x", mask));
return false;
} else {
continue;
}
}
// if this modifier is sensitive to modifiers then adjust those
// modifiers. also check if our assumption was correct. note
// that we only need to adjust the modifiers on key down.
KeyModifierMask sensitive = keyItem->m_sensitive;
if ((sensitive & mask) != 0) {
// modifier is sensitive to itself. that makes no sense
// so ignore it.
LOG((CLOG_DEBUG1 "modifier %04x modified by itself", mask));
sensitive &= ~mask;
}
if (sensitive != 0) {
if (sensitive > mask) {
// our assumption is incorrect
LOG((CLOG_DEBUG1 "modifier %04x modified by %04x", mask, sensitive));
return false;
}
if (active &&
!keysForModifierState(
button, group, activeModifiers, currentState, keyItem->m_required, sensitive, notRequiredMask, keystrokes
)) {
return false;
} else if (!active) {
// release the modifier
// XXX -- this doesn't work! if Alt and Meta are mapped
// to one key and we want to release Meta we can't do
// that without also releasing Alt.
// need to think about support for modified modifiers.
}
}
// current state should match required state
if ((currentState & sensitive) != (keyItem->m_required & sensitive)) {
LOG(
(CLOG_DEBUG1 "unable to match modifier state for modifier %04x (%04x "
"vs %04x in %04x)",
mask, currentState, keyItem->m_required, sensitive)
);
return false;
}
// add keystrokes
EKeystroke type = active ? kKeystrokeModify : kKeystrokeUnmodify;
addKeystrokes(type, *keyItem, activeModifiers, currentState, keystrokes);
}
return true;
}
void KeyMap::addKeystrokes(
EKeystroke type, const KeyItem &keyItem, ModifierToKeys &activeModifiers, KeyModifierMask ¤tState,
Keystrokes &keystrokes
) const
{
KeyButton button = keyItem.m_button;
UInt32 data = keyItem.m_client;
switch (type) {
case kKeystrokePress:
keystrokes.push_back(Keystroke(button, true, false, data));
if (keyItem.m_generates != 0) {
if (!keyItem.m_lock || (currentState & keyItem.m_generates) == 0) {
// add modifier key and activate modifier
activeModifiers.insert(std::make_pair(keyItem.m_generates, keyItem));
currentState |= keyItem.m_generates;
} else {
// deactivate locking modifier
activeModifiers.erase(keyItem.m_generates);
currentState &= ~keyItem.m_generates;
}
}
break;
case kKeystrokeRelease:
keystrokes.push_back(Keystroke(button, false, false, data));
if (keyItem.m_generates != 0 && !keyItem.m_lock) {
// remove key from active modifiers
std::pair<ModifierToKeys::iterator, ModifierToKeys::iterator> range =
activeModifiers.equal_range(keyItem.m_generates);
for (ModifierToKeys::iterator i = range.first; i != range.second; ++i) {
if (i->second.m_button == button) {
activeModifiers.erase(i);
break;
}
}
// if no more keys for this modifier then deactivate modifier
if (activeModifiers.count(keyItem.m_generates) == 0) {
currentState &= ~keyItem.m_generates;
}
}
break;
case kKeystrokeRepeat:
keystrokes.push_back(Keystroke(button, false, true, data));
keystrokes.push_back(Keystroke(button, true, true, data));
// no modifier changes on key repeat
break;
case kKeystrokeClick:
keystrokes.push_back(Keystroke(button, true, false, data));
keystrokes.push_back(Keystroke(button, false, false, data));
// no modifier changes on key click
break;
case kKeystrokeModify:
case kKeystrokeUnmodify:
if (keyItem.m_lock) {
// we assume there's just one button for this modifier
if (m_halfDuplex.count(button) > 0) {
if (type == kKeystrokeModify) {
// turn half-duplex toggle on (press)
keystrokes.push_back(Keystroke(button, true, false, data));
} else {
// turn half-duplex toggle off (release)
keystrokes.push_back(Keystroke(button, false, false, data));
}
} else {
// toggle (click)
keystrokes.push_back(Keystroke(button, true, false, data));
keystrokes.push_back(Keystroke(button, false, false, data));
}
} else if (type == kKeystrokeModify) {
// press modifier
keystrokes.push_back(Keystroke(button, true, false, data));
} else {
// release all the keys that generate the modifier that are
// currently down
std::pair<ModifierToKeys::const_iterator, ModifierToKeys::const_iterator> range =
activeModifiers.equal_range(keyItem.m_generates);
for (ModifierToKeys::const_iterator i = range.first; i != range.second; ++i) {
keystrokes.push_back(Keystroke(i->second.m_button, false, false, i->second.m_client));
}
}
if (type == kKeystrokeModify) {
activeModifiers.insert(std::make_pair(keyItem.m_generates, keyItem));
currentState |= keyItem.m_generates;
} else {
activeModifiers.erase(keyItem.m_generates);
currentState &= ~keyItem.m_generates;
}
break;
}
}
SInt32 KeyMap::getNumModifiers(KeyModifierMask state)
{
SInt32 n = 0;
for (; state != 0; state >>= 1) {
if ((state & 1) != 0) {
++n;
}
}
return n;
}
bool KeyMap::isDeadKey(KeyID key)
{
return (key == kKeyCompose || (key >= 0x0300 && key <= 0x036f));
}
KeyID KeyMap::getDeadKey(KeyID key)
{
if (isDeadKey(key)) {
// already dead
return key;
}
switch (key) {
case '`':
return kKeyDeadGrave;
case '\'':
case 0xb4u:
return kKeyDeadAcute;
case '^':
case 0x2c6:
return kKeyDeadCircumflex;
case '~':
case 0x2dcu:
return kKeyDeadTilde;
case 0xafu:
return kKeyDeadMacron;
case 0x2d8u:
return kKeyDeadBreve;
case 0x2d9u:
return kKeyDeadAbovedot;
case 0xa8u:
return kKeyDeadDiaeresis;
case 0xb0u:
case 0x2dau:
return kKeyDeadAbovering;
case '\"':
case 0x2ddu:
return kKeyDeadDoubleacute;
case 0x2c7u:
return kKeyDeadCaron;
case 0xb8u:
return kKeyDeadCedilla;
case 0x2dbu:
return kKeyDeadOgonek;
default:
// unknown
return kKeyNone;
}
}
String KeyMap::formatKey(KeyID key, KeyModifierMask mask)
{
// initialize tables
initKeyNameMaps();
String x;
for (SInt32 i = 0; i < kKeyModifierNumBits; ++i) {
KeyModifierMask mod = (1u << i);
if ((mask & mod) != 0 && s_modifierToNameMap->count(mod) > 0) {
x += s_modifierToNameMap->find(mod)->second;
x += "+";
}
}
if (key != kKeyNone) {
if (s_keyToNameMap->count(key) > 0) {
x += s_keyToNameMap->find(key)->second;
}
// XXX -- we're assuming ASCII here
else if (key >= 33 && key < 127) {
x += (char)key;
} else {
x += deskflow::string::sprintf("\\u%04x", key);
}
} else if (!x.empty()) {
// remove trailing '+'
x.erase(x.size() - 1);
}
return x;
}
bool KeyMap::parseKey(const String &x, KeyID &key)
{
// initialize tables
initKeyNameMaps();
// parse the key
key = kKeyNone;
if (s_nameToKeyMap->count(x) > 0) {
key = s_nameToKeyMap->find(x)->second;
}
// XXX -- we're assuming ASCII encoding here
else if (x.size() == 1) {
if (!isgraph(x[0])) {
// unknown key
return false;
}
key = (KeyID)x[0];
} else if (x.size() == 6 && x[0] == '\\' && x[1] == 'u') {
// escaped unicode (\uXXXX where XXXX is a hex number)
char *end;
key = (KeyID)strtol(x.c_str() + 2, &end, 16);
if (*end != '\0') {
return false;
}
} else if (!x.empty()) {
// unknown key
return false;
}
return true;
}
bool KeyMap::parseModifiers(String &x, KeyModifierMask &mask)
{
// initialize tables
initKeyNameMaps();
mask = 0;
String::size_type tb = x.find_first_not_of(" \t", 0);
while (tb != String::npos) {
// get next component
String::size_type te = x.find_first_of(" \t+)", tb);
if (te == String::npos) {
te = x.size();
}
String c = x.substr(tb, te - tb);
if (c.empty()) {
// missing component
return false;
}
if (s_nameToModifierMap->count(c) > 0) {
KeyModifierMask mod = s_nameToModifierMap->find(c)->second;
if ((mask & mod) != 0) {
// modifier appears twice
return false;
}
mask |= mod;
} else {
// unknown string
x.erase(0, tb);
String::size_type tb = x.find_first_not_of(" \t");
String::size_type te = x.find_last_not_of(" \t");
if (tb == String::npos) {
x = "";
} else {
x = x.substr(tb, te - tb + 1);
}
return true;
}
// check for '+' or end of string
tb = x.find_first_not_of(" \t", te);
if (tb != String::npos) {
if (x[tb] != '+') {
// expected '+'
return false;
}
tb = x.find_first_not_of(" \t", tb + 1);
}
}
// parsed the whole thing
x = "";
return true;
}
void KeyMap::initKeyNameMaps()
{
// initialize tables
if (s_nameToKeyMap == NULL) {
s_nameToKeyMap = new NameToKeyMap;
s_keyToNameMap = new KeyToNameMap;
for (const KeyNameMapEntry *i = kKeyNameMap; i->m_name != NULL; ++i) {
(*s_nameToKeyMap)[i->m_name] = i->m_id;
(*s_keyToNameMap)[i->m_id] = i->m_name;
}
}
if (s_nameToModifierMap == NULL) {
s_nameToModifierMap = new NameToModifierMap;
s_modifierToNameMap = new ModifierToNameMap;
for (const KeyModifierNameMapEntry *i = kModifierNameMap; i->m_name != NULL; ++i) {
(*s_nameToModifierMap)[i->m_name] = i->m_mask;
(*s_modifierToNameMap)[i->m_mask] = i->m_name;
}
}
}
//
// KeyMap::KeyItem
//
bool KeyMap::KeyItem::operator==(const KeyItem &x) const
{
return (
m_id == x.m_id && m_group == x.m_group && m_button == x.m_button && m_required == x.m_required &&
m_sensitive == x.m_sensitive && m_generates == x.m_generates && m_dead == x.m_dead && m_lock == x.m_lock &&
m_client == x.m_client
);
}
//
// KeyMap::Keystroke
//
KeyMap::Keystroke::Keystroke(KeyButton button, bool press, bool repeat, UInt32 data) : m_type(kButton)
{
m_data.m_button.m_button = button;
m_data.m_button.m_press = press;
m_data.m_button.m_repeat = repeat;
m_data.m_button.m_client = data;
}
KeyMap::Keystroke::Keystroke(SInt32 group, bool absolute, bool restore) : m_type(kGroup)
{
m_data.m_group.m_group = group;
m_data.m_group.m_absolute = absolute;
m_data.m_group.m_restore = restore;
}
} // namespace deskflow
| 37,968
|
C++
|
.cpp
| 1,106
| 29.778481
| 120
| 0.673696
|
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,490
|
ServerTaskBarReceiver.cpp
|
deskflow_deskflow/src/lib/deskflow/ServerTaskBarReceiver.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 "deskflow/ServerTaskBarReceiver.h"
#include "arch/Arch.h"
#include "base/IEventQueue.h"
#include "base/String.h"
#include "common/constants.h"
#include "mt/Lock.h"
#include "server/Server.h"
//
// ServerTaskBarReceiver
//
ServerTaskBarReceiver::ServerTaskBarReceiver(IEventQueue *events) : m_state(kNotRunning), m_events(events)
{
// do nothing
}
ServerTaskBarReceiver::~ServerTaskBarReceiver()
{
// do nothing
}
void ServerTaskBarReceiver::updateStatus(Server *server, const String &errorMsg)
{
{
// update our status
m_errorMessage = errorMsg;
if (server == NULL) {
if (m_errorMessage.empty()) {
m_state = kNotRunning;
} else {
m_state = kNotWorking;
}
} else {
m_clients.clear();
server->getClients(m_clients);
if (m_clients.size() <= 1) {
m_state = kNotConnected;
} else {
m_state = kConnected;
}
}
// let subclasses have a go
onStatusChanged(server);
}
// tell task bar
ARCH->updateReceiver(this);
}
ServerTaskBarReceiver::EState ServerTaskBarReceiver::getStatus() const
{
return m_state;
}
const String &ServerTaskBarReceiver::getErrorMessage() const
{
return m_errorMessage;
}
const ServerTaskBarReceiver::Clients &ServerTaskBarReceiver::getClients() const
{
return m_clients;
}
void ServerTaskBarReceiver::quit()
{
m_events->addEvent(Event(Event::kQuit));
}
void ServerTaskBarReceiver::onStatusChanged(Server *)
{
// do nothing
}
void ServerTaskBarReceiver::lock() const
{
// do nothing
}
void ServerTaskBarReceiver::unlock() const
{
// do nothing
}
std::string ServerTaskBarReceiver::getToolTip() const
{
switch (m_state) {
case kNotRunning:
return deskflow::string::sprintf("%s: Not running", kAppName);
case kNotWorking:
return deskflow::string::sprintf("%s: %s", kAppName, m_errorMessage.c_str());
case kNotConnected:
return deskflow::string::sprintf("%s: Waiting for clients", kAppName);
case kConnected:
return deskflow::string::sprintf("%s: Connected", kAppName);
default:
return "";
}
}
| 2,833
|
C++
|
.cpp
| 104
| 24.288462
| 106
| 0.725092
|
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,491
|
IClipboard.cpp
|
deskflow_deskflow/src/lib/deskflow/IClipboard.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 "deskflow/IClipboard.h"
#include "common/stdvector.h"
//
// IClipboard
//
void IClipboard::unmarshall(IClipboard *clipboard, const String &data, Time time)
{
assert(clipboard != NULL);
const char *index = data.data();
if (clipboard->open(time)) {
// clear existing data
clipboard->empty();
// read the number of formats
const UInt32 numFormats = readUInt32(index);
index += 4;
// read each format
for (UInt32 i = 0; i < numFormats; ++i) {
// get the format id
IClipboard::EFormat format = static_cast<IClipboard::EFormat>(readUInt32(index));
index += 4;
// get the size of the format data
UInt32 size = readUInt32(index);
index += 4;
// save the data if it's a known format. if either the client
// or server supports more clipboard formats than the other
// then one of them will get a format >= kNumFormats here.
if (format < IClipboard::kNumFormats) {
clipboard->add(format, String(index, size));
}
index += size;
}
// done
clipboard->close();
}
}
String IClipboard::marshall(const IClipboard *clipboard)
{
// return data format:
// 4 bytes => number of formats included
// 4 bytes => format enum
// 4 bytes => clipboard data size n
// n bytes => clipboard data
// back to the second 4 bytes if there is another format
assert(clipboard != NULL);
String data;
std::vector<String> formatData;
formatData.resize(IClipboard::kNumFormats);
// FIXME -- use current time
if (clipboard->open(0)) {
// compute size of marshalled data
UInt32 size = 4;
UInt32 numFormats = 0;
for (UInt32 format = 0; format != IClipboard::kNumFormats; ++format) {
if (clipboard->has(static_cast<IClipboard::EFormat>(format))) {
++numFormats;
formatData[format] = clipboard->get(static_cast<IClipboard::EFormat>(format));
size += 4 + 4 + (UInt32)formatData[format].size();
}
}
// allocate space
data.reserve(size);
// marshall the data
writeUInt32(&data, numFormats);
for (UInt32 format = 0; format != IClipboard::kNumFormats; ++format) {
if (clipboard->has(static_cast<IClipboard::EFormat>(format))) {
writeUInt32(&data, format);
writeUInt32(&data, (UInt32)formatData[format].size());
data += formatData[format];
}
}
clipboard->close();
}
return data;
}
bool IClipboard::copy(IClipboard *dst, const IClipboard *src)
{
assert(dst != NULL);
assert(src != NULL);
return copy(dst, src, src->getTime());
}
bool IClipboard::copy(IClipboard *dst, const IClipboard *src, Time time)
{
assert(dst != NULL);
assert(src != NULL);
bool success = false;
if (src->open(time)) {
if (dst->open(time)) {
if (dst->empty()) {
for (SInt32 format = 0; format != IClipboard::kNumFormats; ++format) {
IClipboard::EFormat eFormat = (IClipboard::EFormat)format;
if (src->has(eFormat)) {
dst->add(eFormat, src->get(eFormat));
}
}
success = true;
}
dst->close();
}
src->close();
}
return success;
}
UInt32 IClipboard::readUInt32(const char *buf)
{
const unsigned char *ubuf = reinterpret_cast<const unsigned char *>(buf);
return (static_cast<UInt32>(ubuf[0]) << 24) | (static_cast<UInt32>(ubuf[1]) << 16) |
(static_cast<UInt32>(ubuf[2]) << 8) | static_cast<UInt32>(ubuf[3]);
}
void IClipboard::writeUInt32(String *buf, UInt32 v)
{
*buf += static_cast<UInt8>((v >> 24) & 0xff);
*buf += static_cast<UInt8>((v >> 16) & 0xff);
*buf += static_cast<UInt8>((v >> 8) & 0xff);
*buf += static_cast<UInt8>(v & 0xff);
}
| 4,431
|
C++
|
.cpp
| 132
| 29.143939
| 87
| 0.65723
|
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,492
|
KeyState.cpp
|
deskflow_deskflow/src/lib/deskflow/KeyState.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 "deskflow/KeyState.h"
#include "base/Log.h"
#include "deskflow/ClientApp.h"
#include "deskflow/ClientArgs.h"
#include <algorithm>
#include <cstring>
#include <iterator>
#include <list>
static const KeyButton kButtonMask = (KeyButton)(IKeyState::kNumButtons - 1);
static const KeyID s_decomposeTable[] = {
// spacing version of dead keys
0x0060, 0x0300, 0x0020,
0, // grave, dead_grave, space
0x00b4, 0x0301, 0x0020,
0, // acute, dead_acute, space
0x005e, 0x0302, 0x0020,
0, // asciicircum, dead_circumflex, space
0x007e, 0x0303, 0x0020,
0, // asciitilde, dead_tilde, space
0x00a8, 0x0308, 0x0020,
0, // diaeresis, dead_diaeresis, space
0x00b0, 0x030a, 0x0020,
0, // degree, dead_abovering, space
0x00b8, 0x0327, 0x0020,
0, // cedilla, dead_cedilla, space
0x02db, 0x0328, 0x0020,
0, // ogonek, dead_ogonek, space
0x02c7, 0x030c, 0x0020,
0, // caron, dead_caron, space
0x02d9, 0x0307, 0x0020,
0, // abovedot, dead_abovedot, space
0x02dd, 0x030b, 0x0020,
0, // doubleacute, dead_doubleacute, space
0x02d8, 0x0306, 0x0020,
0, // breve, dead_breve, space
0x00af, 0x0304, 0x0020,
0, // macron, dead_macron, space
// Latin-1 (ISO 8859-1)
0x00c0, 0x0300, 0x0041,
0, // Agrave, dead_grave, A
0x00c1, 0x0301, 0x0041,
0, // Aacute, dead_acute, A
0x00c2, 0x0302, 0x0041,
0, // Acircumflex, dead_circumflex, A
0x00c3, 0x0303, 0x0041,
0, // Atilde, dead_tilde, A
0x00c4, 0x0308, 0x0041,
0, // Adiaeresis, dead_diaeresis, A
0x00c5, 0x030a, 0x0041,
0, // Aring, dead_abovering, A
0x00c7, 0x0327, 0x0043,
0, // Ccedilla, dead_cedilla, C
0x00c8, 0x0300, 0x0045,
0, // Egrave, dead_grave, E
0x00c9, 0x0301, 0x0045,
0, // Eacute, dead_acute, E
0x00ca, 0x0302, 0x0045,
0, // Ecircumflex, dead_circumflex, E
0x00cb, 0x0308, 0x0045,
0, // Ediaeresis, dead_diaeresis, E
0x00cc, 0x0300, 0x0049,
0, // Igrave, dead_grave, I
0x00cd, 0x0301, 0x0049,
0, // Iacute, dead_acute, I
0x00ce, 0x0302, 0x0049,
0, // Icircumflex, dead_circumflex, I
0x00cf, 0x0308, 0x0049,
0, // Idiaeresis, dead_diaeresis, I
0x00d1, 0x0303, 0x004e,
0, // Ntilde, dead_tilde, N
0x00d2, 0x0300, 0x004f,
0, // Ograve, dead_grave, O
0x00d3, 0x0301, 0x004f,
0, // Oacute, dead_acute, O
0x00d4, 0x0302, 0x004f,
0, // Ocircumflex, dead_circumflex, O
0x00d5, 0x0303, 0x004f,
0, // Otilde, dead_tilde, O
0x00d6, 0x0308, 0x004f,
0, // Odiaeresis, dead_diaeresis, O
0x00d9, 0x0300, 0x0055,
0, // Ugrave, dead_grave, U
0x00da, 0x0301, 0x0055,
0, // Uacute, dead_acute, U
0x00db, 0x0302, 0x0055,
0, // Ucircumflex, dead_circumflex, U
0x00dc, 0x0308, 0x0055,
0, // Udiaeresis, dead_diaeresis, U
0x00dd, 0x0301, 0x0059,
0, // Yacute, dead_acute, Y
0x00e0, 0x0300, 0x0061,
0, // agrave, dead_grave, a
0x00e1, 0x0301, 0x0061,
0, // aacute, dead_acute, a
0x00e2, 0x0302, 0x0061,
0, // acircumflex, dead_circumflex, a
0x00e3, 0x0303, 0x0061,
0, // atilde, dead_tilde, a
0x00e4, 0x0308, 0x0061,
0, // adiaeresis, dead_diaeresis, a
0x00e5, 0x030a, 0x0061,
0, // aring, dead_abovering, a
0x00e7, 0x0327, 0x0063,
0, // ccedilla, dead_cedilla, c
0x00e8, 0x0300, 0x0065,
0, // egrave, dead_grave, e
0x00e9, 0x0301, 0x0065,
0, // eacute, dead_acute, e
0x00ea, 0x0302, 0x0065,
0, // ecircumflex, dead_circumflex, e
0x00eb, 0x0308, 0x0065,
0, // ediaeresis, dead_diaeresis, e
0x00ec, 0x0300, 0x0069,
0, // igrave, dead_grave, i
0x00ed, 0x0301, 0x0069,
0, // iacute, dead_acute, i
0x00ee, 0x0302, 0x0069,
0, // icircumflex, dead_circumflex, i
0x00ef, 0x0308, 0x0069,
0, // idiaeresis, dead_diaeresis, i
0x00f1, 0x0303, 0x006e,
0, // ntilde, dead_tilde, n
0x00f2, 0x0300, 0x006f,
0, // ograve, dead_grave, o
0x00f3, 0x0301, 0x006f,
0, // oacute, dead_acute, o
0x00f4, 0x0302, 0x006f,
0, // ocircumflex, dead_circumflex, o
0x00f5, 0x0303, 0x006f,
0, // otilde, dead_tilde, o
0x00f6, 0x0308, 0x006f,
0, // odiaeresis, dead_diaeresis, o
0x00f9, 0x0300, 0x0075,
0, // ugrave, dead_grave, u
0x00fa, 0x0301, 0x0075,
0, // uacute, dead_acute, u
0x00fb, 0x0302, 0x0075,
0, // ucircumflex, dead_circumflex, u
0x00fc, 0x0308, 0x0075,
0, // udiaeresis, dead_diaeresis, u
0x00fd, 0x0301, 0x0079,
0, // yacute, dead_acute, y
0x00ff, 0x0308, 0x0079,
0, // ydiaeresis, dead_diaeresis, y
// Latin-2 (ISO 8859-2)
0x0104, 0x0328, 0x0041,
0, // Aogonek, dead_ogonek, A
0x013d, 0x030c, 0x004c,
0, // Lcaron, dead_caron, L
0x015a, 0x0301, 0x0053,
0, // Sacute, dead_acute, S
0x0160, 0x030c, 0x0053,
0, // Scaron, dead_caron, S
0x015e, 0x0327, 0x0053,
0, // Scedilla, dead_cedilla, S
0x0164, 0x030c, 0x0054,
0, // Tcaron, dead_caron, T
0x0179, 0x0301, 0x005a,
0, // Zacute, dead_acute, Z
0x017d, 0x030c, 0x005a,
0, // Zcaron, dead_caron, Z
0x017b, 0x0307, 0x005a,
0, // Zabovedot, dead_abovedot, Z
0x0105, 0x0328, 0x0061,
0, // aogonek, dead_ogonek, a
0x013e, 0x030c, 0x006c,
0, // lcaron, dead_caron, l
0x015b, 0x0301, 0x0073,
0, // sacute, dead_acute, s
0x0161, 0x030c, 0x0073,
0, // scaron, dead_caron, s
0x015f, 0x0327, 0x0073,
0, // scedilla, dead_cedilla, s
0x0165, 0x030c, 0x0074,
0, // tcaron, dead_caron, t
0x017a, 0x0301, 0x007a,
0, // zacute, dead_acute, z
0x017e, 0x030c, 0x007a,
0, // zcaron, dead_caron, z
0x017c, 0x0307, 0x007a,
0, // zabovedot, dead_abovedot, z
0x0154, 0x0301, 0x0052,
0, // Racute, dead_acute, R
0x0102, 0x0306, 0x0041,
0, // Abreve, dead_breve, A
0x0139, 0x0301, 0x004c,
0, // Lacute, dead_acute, L
0x0106, 0x0301, 0x0043,
0, // Cacute, dead_acute, C
0x010c, 0x030c, 0x0043,
0, // Ccaron, dead_caron, C
0x0118, 0x0328, 0x0045,
0, // Eogonek, dead_ogonek, E
0x011a, 0x030c, 0x0045,
0, // Ecaron, dead_caron, E
0x010e, 0x030c, 0x0044,
0, // Dcaron, dead_caron, D
0x0143, 0x0301, 0x004e,
0, // Nacute, dead_acute, N
0x0147, 0x030c, 0x004e,
0, // Ncaron, dead_caron, N
0x0150, 0x030b, 0x004f,
0, // Odoubleacute, dead_doubleacute, O
0x0158, 0x030c, 0x0052,
0, // Rcaron, dead_caron, R
0x016e, 0x030a, 0x0055,
0, // Uring, dead_abovering, U
0x0170, 0x030b, 0x0055,
0, // Udoubleacute, dead_doubleacute, U
0x0162, 0x0327, 0x0054,
0, // Tcedilla, dead_cedilla, T
0x0155, 0x0301, 0x0072,
0, // racute, dead_acute, r
0x0103, 0x0306, 0x0061,
0, // abreve, dead_breve, a
0x013a, 0x0301, 0x006c,
0, // lacute, dead_acute, l
0x0107, 0x0301, 0x0063,
0, // cacute, dead_acute, c
0x010d, 0x030c, 0x0063,
0, // ccaron, dead_caron, c
0x0119, 0x0328, 0x0065,
0, // eogonek, dead_ogonek, e
0x011b, 0x030c, 0x0065,
0, // ecaron, dead_caron, e
0x010f, 0x030c, 0x0064,
0, // dcaron, dead_caron, d
0x0144, 0x0301, 0x006e,
0, // nacute, dead_acute, n
0x0148, 0x030c, 0x006e,
0, // ncaron, dead_caron, n
0x0151, 0x030b, 0x006f,
0, // odoubleacute, dead_doubleacute, o
0x0159, 0x030c, 0x0072,
0, // rcaron, dead_caron, r
0x016f, 0x030a, 0x0075,
0, // uring, dead_abovering, u
0x0171, 0x030b, 0x0075,
0, // udoubleacute, dead_doubleacute, u
0x0163, 0x0327, 0x0074,
0, // tcedilla, dead_cedilla, t
// Latin-3 (ISO 8859-3)
0x0124, 0x0302, 0x0048,
0, // Hcircumflex, dead_circumflex, H
0x0130, 0x0307, 0x0049,
0, // Iabovedot, dead_abovedot, I
0x011e, 0x0306, 0x0047,
0, // Gbreve, dead_breve, G
0x0134, 0x0302, 0x004a,
0, // Jcircumflex, dead_circumflex, J
0x0125, 0x0302, 0x0068,
0, // hcircumflex, dead_circumflex, h
0x011f, 0x0306, 0x0067,
0, // gbreve, dead_breve, g
0x0135, 0x0302, 0x006a,
0, // jcircumflex, dead_circumflex, j
0x010a, 0x0307, 0x0043,
0, // Cabovedot, dead_abovedot, C
0x0108, 0x0302, 0x0043,
0, // Ccircumflex, dead_circumflex, C
0x0120, 0x0307, 0x0047,
0, // Gabovedot, dead_abovedot, G
0x011c, 0x0302, 0x0047,
0, // Gcircumflex, dead_circumflex, G
0x016c, 0x0306, 0x0055,
0, // Ubreve, dead_breve, U
0x015c, 0x0302, 0x0053,
0, // Scircumflex, dead_circumflex, S
0x010b, 0x0307, 0x0063,
0, // cabovedot, dead_abovedot, c
0x0109, 0x0302, 0x0063,
0, // ccircumflex, dead_circumflex, c
0x0121, 0x0307, 0x0067,
0, // gabovedot, dead_abovedot, g
0x011d, 0x0302, 0x0067,
0, // gcircumflex, dead_circumflex, g
0x016d, 0x0306, 0x0075,
0, // ubreve, dead_breve, u
0x015d, 0x0302, 0x0073,
0, // scircumflex, dead_circumflex, s
// Latin-4 (ISO 8859-4)
0x0156, 0x0327, 0x0052,
0, // Rcedilla, dead_cedilla, R
0x0128, 0x0303, 0x0049,
0, // Itilde, dead_tilde, I
0x013b, 0x0327, 0x004c,
0, // Lcedilla, dead_cedilla, L
0x0112, 0x0304, 0x0045,
0, // Emacron, dead_macron, E
0x0122, 0x0327, 0x0047,
0, // Gcedilla, dead_cedilla, G
0x0157, 0x0327, 0x0072,
0, // rcedilla, dead_cedilla, r
0x0129, 0x0303, 0x0069,
0, // itilde, dead_tilde, i
0x013c, 0x0327, 0x006c,
0, // lcedilla, dead_cedilla, l
0x0113, 0x0304, 0x0065,
0, // emacron, dead_macron, e
0x0123, 0x0327, 0x0067,
0, // gcedilla, dead_cedilla, g
0x0100, 0x0304, 0x0041,
0, // Amacron, dead_macron, A
0x012e, 0x0328, 0x0049,
0, // Iogonek, dead_ogonek, I
0x0116, 0x0307, 0x0045,
0, // Eabovedot, dead_abovedot, E
0x012a, 0x0304, 0x0049,
0, // Imacron, dead_macron, I
0x0145, 0x0327, 0x004e,
0, // Ncedilla, dead_cedilla, N
0x014c, 0x0304, 0x004f,
0, // Omacron, dead_macron, O
0x0136, 0x0327, 0x004b,
0, // Kcedilla, dead_cedilla, K
0x0172, 0x0328, 0x0055,
0, // Uogonek, dead_ogonek, U
0x0168, 0x0303, 0x0055,
0, // Utilde, dead_tilde, U
0x016a, 0x0304, 0x0055,
0, // Umacron, dead_macron, U
0x0101, 0x0304, 0x0061,
0, // amacron, dead_macron, a
0x012f, 0x0328, 0x0069,
0, // iogonek, dead_ogonek, i
0x0117, 0x0307, 0x0065,
0, // eabovedot, dead_abovedot, e
0x012b, 0x0304, 0x0069,
0, // imacron, dead_macron, i
0x0146, 0x0327, 0x006e,
0, // ncedilla, dead_cedilla, n
0x014d, 0x0304, 0x006f,
0, // omacron, dead_macron, o
0x0137, 0x0327, 0x006b,
0, // kcedilla, dead_cedilla, k
0x0173, 0x0328, 0x0075,
0, // uogonek, dead_ogonek, u
0x0169, 0x0303, 0x0075,
0, // utilde, dead_tilde, u
0x016b, 0x0304, 0x0075,
0, // umacron, dead_macron, u
// Latin-8 (ISO 8859-14)
0x1e02, 0x0307, 0x0042,
0, // Babovedot, dead_abovedot, B
0x1e03, 0x0307, 0x0062,
0, // babovedot, dead_abovedot, b
0x1e0a, 0x0307, 0x0044,
0, // Dabovedot, dead_abovedot, D
0x1e80, 0x0300, 0x0057,
0, // Wgrave, dead_grave, W
0x1e82, 0x0301, 0x0057,
0, // Wacute, dead_acute, W
0x1e0b, 0x0307, 0x0064,
0, // dabovedot, dead_abovedot, d
0x1ef2, 0x0300, 0x0059,
0, // Ygrave, dead_grave, Y
0x1e1e, 0x0307, 0x0046,
0, // Fabovedot, dead_abovedot, F
0x1e1f, 0x0307, 0x0066,
0, // fabovedot, dead_abovedot, f
0x1e40, 0x0307, 0x004d,
0, // Mabovedot, dead_abovedot, M
0x1e41, 0x0307, 0x006d,
0, // mabovedot, dead_abovedot, m
0x1e56, 0x0307, 0x0050,
0, // Pabovedot, dead_abovedot, P
0x1e81, 0x0300, 0x0077,
0, // wgrave, dead_grave, w
0x1e57, 0x0307, 0x0070,
0, // pabovedot, dead_abovedot, p
0x1e83, 0x0301, 0x0077,
0, // wacute, dead_acute, w
0x1e60, 0x0307, 0x0053,
0, // Sabovedot, dead_abovedot, S
0x1ef3, 0x0300, 0x0079,
0, // ygrave, dead_grave, y
0x1e84, 0x0308, 0x0057,
0, // Wdiaeresis, dead_diaeresis, W
0x1e85, 0x0308, 0x0077,
0, // wdiaeresis, dead_diaeresis, w
0x1e61, 0x0307, 0x0073,
0, // sabovedot, dead_abovedot, s
0x0174, 0x0302, 0x0057,
0, // Wcircumflex, dead_circumflex, W
0x1e6a, 0x0307, 0x0054,
0, // Tabovedot, dead_abovedot, T
0x0176, 0x0302, 0x0059,
0, // Ycircumflex, dead_circumflex, Y
0x0175, 0x0302, 0x0077,
0, // wcircumflex, dead_circumflex, w
0x1e6b, 0x0307, 0x0074,
0, // tabovedot, dead_abovedot, t
0x0177, 0x0302, 0x0079,
0, // ycircumflex, dead_circumflex, y
// Latin-9 (ISO 8859-15)
0x0178, 0x0308, 0x0059,
0, // Ydiaeresis, dead_diaeresis, Y
// Compose key sequences
0x00c6, kKeyCompose, 0x0041, 0x0045,
0, // AE, A, E
0x00c1, kKeyCompose, 0x0041, 0x0027,
0, // Aacute, A, apostrophe
0x00c2, kKeyCompose, 0x0041, 0x0053,
0, // Acircumflex, A, asciicircum
0x00c3, kKeyCompose, 0x0041, 0x0022,
0, // Adiaeresis, A, quotedbl
0x00c0, kKeyCompose, 0x0041, 0x0060,
0, // Agrave, A, grave
0x00c5, kKeyCompose, 0x0041, 0x002a,
0, // Aring, A, asterisk
0x00c3, kKeyCompose, 0x0041, 0x007e,
0, // Atilde, A, asciitilde
0x00c7, kKeyCompose, 0x0043, 0x002c,
0, // Ccedilla, C, comma
0x00d0, kKeyCompose, 0x0044, 0x002d,
0, // ETH, D, minus
0x00c9, kKeyCompose, 0x0045, 0x0027,
0, // Eacute, E, apostrophe
0x00ca, kKeyCompose, 0x0045, 0x0053,
0, // Ecircumflex, E, asciicircum
0x00cb, kKeyCompose, 0x0045, 0x0022,
0, // Ediaeresis, E, quotedbl
0x00c8, kKeyCompose, 0x0045, 0x0060,
0, // Egrave, E, grave
0x00cd, kKeyCompose, 0x0049, 0x0027,
0, // Iacute, I, apostrophe
0x00ce, kKeyCompose, 0x0049, 0x0053,
0, // Icircumflex, I, asciicircum
0x00cf, kKeyCompose, 0x0049, 0x0022,
0, // Idiaeresis, I, quotedbl
0x00cc, kKeyCompose, 0x0049, 0x0060,
0, // Igrave, I, grave
0x00d1, kKeyCompose, 0x004e, 0x007e,
0, // Ntilde, N, asciitilde
0x00d3, kKeyCompose, 0x004f, 0x0027,
0, // Oacute, O, apostrophe
0x00d4, kKeyCompose, 0x004f, 0x0053,
0, // Ocircumflex, O, asciicircum
0x00d6, kKeyCompose, 0x004f, 0x0022,
0, // Odiaeresis, O, quotedbl
0x00d2, kKeyCompose, 0x004f, 0x0060,
0, // Ograve, O, grave
0x00d8, kKeyCompose, 0x004f, 0x002f,
0, // Ooblique, O, slash
0x00d5, kKeyCompose, 0x004f, 0x007e,
0, // Otilde, O, asciitilde
0x00de, kKeyCompose, 0x0054, 0x0048,
0, // THORN, T, H
0x00da, kKeyCompose, 0x0055, 0x0027,
0, // Uacute, U, apostrophe
0x00db, kKeyCompose, 0x0055, 0x0053,
0, // Ucircumflex, U, asciicircum
0x00dc, kKeyCompose, 0x0055, 0x0022,
0, // Udiaeresis, U, quotedbl
0x00d9, kKeyCompose, 0x0055, 0x0060,
0, // Ugrave, U, grave
0x00dd, kKeyCompose, 0x0059, 0x0027,
0, // Yacute, Y, apostrophe
0x00e1, kKeyCompose, 0x0061, 0x0027,
0, // aacute, a, apostrophe
0x00e2, kKeyCompose, 0x0061, 0x0053,
0, // acircumflex, a, asciicircum
0x00b4, kKeyCompose, 0x0027, 0x0027,
0, // acute, apostrophe, apostrophe
0x00e4, kKeyCompose, 0x0061, 0x0022,
0, // adiaeresis, a, quotedbl
0x00e6, kKeyCompose, 0x0061, 0x0065,
0, // ae, a, e
0x00e0, kKeyCompose, 0x0061, 0x0060,
0, // agrave, a, grave
0x00e5, kKeyCompose, 0x0061, 0x002a,
0, // aring, a, asterisk
0x0040, kKeyCompose, 0x0041, 0x0054,
0, // at, A, T
0x00e3, kKeyCompose, 0x0061, 0x007e,
0, // atilde, a, asciitilde
0x005c, kKeyCompose, 0x002f, 0x002f,
0, // backslash, slash, slash
0x007c, kKeyCompose, 0x004c, 0x0056,
0, // bar, L, V
0x007b, kKeyCompose, 0x0028, 0x002d,
0, // braceleft, parenleft, minus
0x007d, kKeyCompose, 0x0029, 0x002d,
0, // braceright, parenright, minus
0x005b, kKeyCompose, 0x0028, 0x0028,
0, // bracketleft, parenleft, parenleft
0x005d, kKeyCompose, 0x0029, 0x0029,
0, // bracketright, parenright, parenright
0x00a6, kKeyCompose, 0x0042, 0x0056,
0, // brokenbar, B, V
0x00e7, kKeyCompose, 0x0063, 0x002c,
0, // ccedilla, c, comma
0x00b8, kKeyCompose, 0x002c, 0x002c,
0, // cedilla, comma, comma
0x00a2, kKeyCompose, 0x0063, 0x002f,
0, // cent, c, slash
0x00a9, kKeyCompose, 0x0028, 0x0063,
0, // copyright, parenleft, c
0x00a4, kKeyCompose, 0x006f, 0x0078,
0, // currency, o, x
0x00b0, kKeyCompose, 0x0030, 0x0053,
0, // degree, 0, asciicircum
0x00a8, kKeyCompose, 0x0022, 0x0022,
0, // diaeresis, quotedbl, quotedbl
0x00f7, kKeyCompose, 0x003a, 0x002d,
0, // division, colon, minus
0x00e9, kKeyCompose, 0x0065, 0x0027,
0, // eacute, e, apostrophe
0x00ea, kKeyCompose, 0x0065, 0x0053,
0, // ecircumflex, e, asciicircum
0x00eb, kKeyCompose, 0x0065, 0x0022,
0, // ediaeresis, e, quotedbl
0x00e8, kKeyCompose, 0x0065, 0x0060,
0, // egrave, e, grave
0x00f0, kKeyCompose, 0x0064, 0x002d,
0, // eth, d, minus
0x00a1, kKeyCompose, 0x0021, 0x0021,
0, // exclamdown, exclam, exclam
0x00ab, kKeyCompose, 0x003c, 0x003c,
0, // guillemotleft, less, less
0x00bb, kKeyCompose, 0x003e, 0x003e,
0, // guillemotright, greater, greater
0x0023, kKeyCompose, 0x002b, 0x002b,
0, // numbersign, plus, plus
0x00ad, kKeyCompose, 0x002d, 0x002d,
0, // hyphen, minus, minus
0x00ed, kKeyCompose, 0x0069, 0x0027,
0, // iacute, i, apostrophe
0x00ee, kKeyCompose, 0x0069, 0x0053,
0, // icircumflex, i, asciicircum
0x00ef, kKeyCompose, 0x0069, 0x0022,
0, // idiaeresis, i, quotedbl
0x00ec, kKeyCompose, 0x0069, 0x0060,
0, // igrave, i, grave
0x00af, kKeyCompose, 0x002d, 0x0053,
0, // macron, minus, asciicircum
0x00ba, kKeyCompose, 0x006f, 0x005f,
0, // masculine, o, underscore
0x00b5, kKeyCompose, 0x0075, 0x002f,
0, // mu, u, slash
0x00d7, kKeyCompose, 0x0078, 0x0078,
0, // multiply, x, x
0x00a0, kKeyCompose, 0x0020, 0x0020,
0, // nobreakspace, space, space
0x00ac, kKeyCompose, 0x002c, 0x002d,
0, // notsign, comma, minus
0x00f1, kKeyCompose, 0x006e, 0x007e,
0, // ntilde, n, asciitilde
0x00f3, kKeyCompose, 0x006f, 0x0027,
0, // oacute, o, apostrophe
0x00f4, kKeyCompose, 0x006f, 0x0053,
0, // ocircumflex, o, asciicircum
0x00f6, kKeyCompose, 0x006f, 0x0022,
0, // odiaeresis, o, quotedbl
0x00f2, kKeyCompose, 0x006f, 0x0060,
0, // ograve, o, grave
0x00bd, kKeyCompose, 0x0031, 0x0032,
0, // onehalf, 1, 2
0x00bc, kKeyCompose, 0x0031, 0x0034,
0, // onequarter, 1, 4
0x00b9, kKeyCompose, 0x0031, 0x0053,
0, // onesuperior, 1, asciicircum
0x00aa, kKeyCompose, 0x0061, 0x005f,
0, // ordfeminine, a, underscore
0x00f8, kKeyCompose, 0x006f, 0x002f,
0, // oslash, o, slash
0x00f5, kKeyCompose, 0x006f, 0x007e,
0, // otilde, o, asciitilde
0x00b6, kKeyCompose, 0x0070, 0x0021,
0, // paragraph, p, exclam
0x00b7, kKeyCompose, 0x002e, 0x002e,
0, // periodcentered, period, period
0x00b1, kKeyCompose, 0x002b, 0x002d,
0, // plusminus, plus, minus
0x00bf, kKeyCompose, 0x003f, 0x003f,
0, // questiondown, question, question
0x00ae, kKeyCompose, 0x0028, 0x0072,
0, // registered, parenleft, r
0x00a7, kKeyCompose, 0x0073, 0x006f,
0, // section, s, o
0x00df, kKeyCompose, 0x0073, 0x0073,
0, // ssharp, s, s
0x00a3, kKeyCompose, 0x004c, 0x002d,
0, // sterling, L, minus
0x00fe, kKeyCompose, 0x0074, 0x0068,
0, // thorn, t, h
0x00be, kKeyCompose, 0x0033, 0x0034,
0, // threequarters, 3, 4
0x00b3, kKeyCompose, 0x0033, 0x0053,
0, // threesuperior, 3, asciicircum
0x00b2, kKeyCompose, 0x0032, 0x0053,
0, // twosuperior, 2, asciicircum
0x00fa, kKeyCompose, 0x0075, 0x0027,
0, // uacute, u, apostrophe
0x00fb, kKeyCompose, 0x0075, 0x0053,
0, // ucircumflex, u, asciicircum
0x00fc, kKeyCompose, 0x0075, 0x0022,
0, // udiaeresis, u, quotedbl
0x00f9, kKeyCompose, 0x0075, 0x0060,
0, // ugrave, u, grave
0x00fd, kKeyCompose, 0x0079, 0x0027,
0, // yacute, y, apostrophe
0x00ff, kKeyCompose, 0x0079, 0x0022,
0, // ydiaeresis, y, quotedbl
0x00a5, kKeyCompose, 0x0079, 0x003d,
0, // yen, y, equal
// end of table
0
};
static const KeyID s_numpadTable[] = {
kKeyKP_Space, 0x0020, kKeyKP_Tab, kKeyTab, kKeyKP_Enter, kKeyReturn, kKeyKP_F1, kKeyF1,
kKeyKP_F2, kKeyF2, kKeyKP_F3, kKeyF3, kKeyKP_F4, kKeyF4, kKeyKP_Home, kKeyHome,
kKeyKP_Left, kKeyLeft, kKeyKP_Up, kKeyUp, kKeyKP_Right, kKeyRight, kKeyKP_Down, kKeyDown,
kKeyKP_PageUp, kKeyPageUp, kKeyKP_PageDown, kKeyPageDown, kKeyKP_End, kKeyEnd, kKeyKP_Begin, kKeyBegin,
kKeyKP_Insert, kKeyInsert, kKeyKP_Delete, kKeyDelete, kKeyKP_Equal, 0x003d, kKeyKP_Multiply, 0x002a,
kKeyKP_Add, 0x002b, kKeyKP_Separator, 0x002c, kKeyKP_Subtract, 0x002d, kKeyKP_Decimal, 0x002e,
kKeyKP_Divide, 0x002f, kKeyKP_0, 0x0030, kKeyKP_1, 0x0031, kKeyKP_2, 0x0032,
kKeyKP_3, 0x0033, kKeyKP_4, 0x0034, kKeyKP_5, 0x0035, kKeyKP_6, 0x0036,
kKeyKP_7, 0x0037, kKeyKP_8, 0x0038, kKeyKP_9, 0x0039
};
//
// KeyState
//
KeyState::KeyState(IEventQueue *events, std::vector<String> layouts, bool isLangSyncEnabled)
: IKeyState(events),
m_keyMapPtr(new deskflow::KeyMap()),
m_keyMap(*m_keyMapPtr),
m_mask(0),
m_events(events),
m_isLangSyncEnabled(isLangSyncEnabled)
{
m_keyMap.setLanguageData(std::move(layouts));
init();
}
KeyState::KeyState(IEventQueue *events, deskflow::KeyMap &keyMap, std::vector<String> layouts, bool isLangSyncEnabled)
: IKeyState(events),
m_keyMapPtr(0),
m_keyMap(keyMap),
m_mask(0),
m_events(events),
m_isLangSyncEnabled(isLangSyncEnabled)
{
m_keyMap.setLanguageData(std::move(layouts));
init();
}
KeyState::~KeyState()
{
if (m_keyMapPtr)
delete m_keyMapPtr;
}
void KeyState::init()
{
memset(&m_keys, 0, sizeof(m_keys));
memset(&m_syntheticKeys, 0, sizeof(m_syntheticKeys));
memset(&m_keyClientData, 0, sizeof(m_keyClientData));
memset(&m_serverKeys, 0, sizeof(m_serverKeys));
}
void KeyState::onKey(KeyButton button, bool down, KeyModifierMask newState)
{
// update modifier state
m_mask = newState;
LOG((CLOG_DEBUG1 "new mask: 0x%04x", m_mask));
// ignore bogus buttons
button &= kButtonMask;
if (button == 0) {
return;
}
// update key state
if (down) {
m_keys[button] = 1;
m_syntheticKeys[button] = 1;
} else {
m_keys[button] = 0;
m_syntheticKeys[button] = 0;
}
}
void KeyState::sendKeyEvent(
void *target, bool press, bool isAutoRepeat, KeyID key, KeyModifierMask mask, SInt32 count, KeyButton button
)
{
if (m_keyMap.isHalfDuplex(key, button)) {
if (isAutoRepeat) {
// ignore auto-repeat on half-duplex keys
} else {
m_events->addEvent(Event(m_events->forIKeyState().keyDown(), target, KeyInfo::alloc(key, mask, button, 1)));
m_events->addEvent(Event(m_events->forIKeyState().keyUp(), target, KeyInfo::alloc(key, mask, button, 1)));
}
} else {
if (isAutoRepeat) {
m_events->addEvent(Event(m_events->forIKeyState().keyRepeat(), target, KeyInfo::alloc(key, mask, button, count)));
} else if (press) {
m_events->addEvent(Event(m_events->forIKeyState().keyDown(), target, KeyInfo::alloc(key, mask, button, 1)));
} else {
m_events->addEvent(Event(m_events->forIKeyState().keyUp(), target, KeyInfo::alloc(key, mask, button, 1)));
}
}
}
void KeyState::updateKeyMap(deskflow::KeyMap *existing)
{
if (existing) {
m_keyMap.swap(*existing);
} else {
// get the current keyboard map
deskflow::KeyMap keyMap;
getKeyMap(keyMap);
m_keyMap.swap(keyMap);
m_keyMap.finish();
}
// add special keys
addCombinationEntries();
addKeypadEntries();
addAliasEntries();
}
void KeyState::updateKeyState()
{
// reset our state
memset(&m_keys, 0, sizeof(m_keys));
memset(&m_syntheticKeys, 0, sizeof(m_syntheticKeys));
memset(&m_keyClientData, 0, sizeof(m_keyClientData));
memset(&m_serverKeys, 0, sizeof(m_serverKeys));
m_activeModifiers.clear();
// get the current keyboard state
KeyButtonSet keysDown;
pollPressedKeys(keysDown);
for (KeyButtonSet::const_iterator i = keysDown.begin(); i != keysDown.end(); ++i) {
m_keys[*i] = 1;
}
// get the current modifier state
m_mask = pollActiveModifiers();
// set active modifiers
AddActiveModifierContext addModifierContext(pollActiveGroup(), m_mask, m_activeModifiers);
m_keyMap.foreachKey(&KeyState::addActiveModifierCB, &addModifierContext);
LOG((CLOG_DEBUG1 "modifiers on update: 0x%04x", m_mask));
}
void KeyState::addActiveModifierCB(KeyID, SInt32 group, deskflow::KeyMap::KeyItem &keyItem, void *vcontext)
{
AddActiveModifierContext *context = static_cast<AddActiveModifierContext *>(vcontext);
if (group == context->m_activeGroup && (keyItem.m_generates & context->m_mask) != 0) {
context->m_activeModifiers.insert(std::make_pair(keyItem.m_generates, keyItem));
}
}
void KeyState::setHalfDuplexMask(KeyModifierMask mask)
{
m_keyMap.clearHalfDuplexModifiers();
if ((mask & KeyModifierCapsLock) != 0) {
m_keyMap.addHalfDuplexModifier(kKeyCapsLock);
}
if ((mask & KeyModifierNumLock) != 0) {
m_keyMap.addHalfDuplexModifier(kKeyNumLock);
}
if ((mask & KeyModifierScrollLock) != 0) {
m_keyMap.addHalfDuplexModifier(kKeyScrollLock);
}
}
void KeyState::fakeKeyDown(KeyID id, KeyModifierMask mask, KeyButton serverID, const String &lang)
{
// if this server key is already down then this is probably a
// mis-reported autorepeat.
serverID &= kButtonMask;
if (m_serverKeys[serverID] != 0) {
fakeKeyRepeat(id, mask, 1, serverID, lang);
return;
}
// ignore certain keys
if (isIgnoredKey(id, mask)) {
LOG((CLOG_DEBUG1 "ignored key %04x %04x", id, mask));
return;
}
Keystrokes keys;
ModifierToKeys oldActiveModifiers = m_activeModifiers;
const deskflow::KeyMap::KeyItem *keyItem =
m_keyMap.mapKey(keys, id, pollActiveGroup(), m_activeModifiers, getActiveModifiersRValue(), mask, false, lang);
if (keyItem == nullptr) {
// a media key won't be mapped on mac, so we need to fake it in a
// special way
if (id == kKeyAudioDown || id == kKeyAudioUp || id == kKeyAudioMute || id == kKeyAudioPlay || id == kKeyAudioPrev ||
id == kKeyAudioNext || id == kKeyBrightnessDown || id == kKeyBrightnessUp) {
LOG((CLOG_DEBUG1 "emulating media key"));
fakeMediaKey(id);
}
return;
}
KeyButton localID = (KeyButton)(keyItem->m_button & kButtonMask);
updateModifierKeyState(localID, oldActiveModifiers, m_activeModifiers);
if (localID != 0) {
// note keys down
++m_keys[localID];
++m_syntheticKeys[localID];
m_keyClientData[localID] = keyItem->m_client;
m_serverKeys[serverID] = localID;
}
// generate key events
fakeKeys(keys, 1);
}
bool KeyState::fakeKeyRepeat(KeyID id, KeyModifierMask mask, SInt32 count, KeyButton serverID, const String &lang)
{
LOG((CLOG_DEBUG2 "fakeKeyRepeat"));
serverID &= kButtonMask;
// if we haven't seen this button go down then ignore it
KeyButton oldLocalID = m_serverKeys[serverID];
if (oldLocalID == 0) {
return false;
}
// get keys for key repeat
Keystrokes keys;
ModifierToKeys oldActiveModifiers = m_activeModifiers;
const deskflow::KeyMap::KeyItem *keyItem =
m_keyMap.mapKey(keys, id, pollActiveGroup(), m_activeModifiers, getActiveModifiersRValue(), mask, true, lang);
if (keyItem == NULL) {
return false;
}
KeyButton localID = (KeyButton)(keyItem->m_button & kButtonMask);
if (localID == 0) {
return false;
}
// if the KeyButton for the auto-repeat is not the same as for the
// initial press then mark the initial key as released and the new
// key as pressed. this can happen when we auto-repeat after a
// dead key. for example, a dead accent followed by 'a' will
// generate an 'a with accent' followed by a repeating 'a'. the
// KeyButtons for the two KeyIDs might be different.
if (localID != oldLocalID) {
// replace key up with previous KeyButton but leave key down
// alone so it uses the new KeyButton.
for (Keystrokes::iterator index = keys.begin(); index != keys.end(); ++index) {
if (index->m_type == Keystroke::kButton && index->m_data.m_button.m_button == localID) {
index->m_data.m_button.m_button = oldLocalID;
break;
}
}
// note that old key is now up
--m_keys[oldLocalID];
--m_syntheticKeys[oldLocalID];
// note keys down
updateModifierKeyState(localID, oldActiveModifiers, m_activeModifiers);
++m_keys[localID];
++m_syntheticKeys[localID];
m_keyClientData[localID] = keyItem->m_client;
m_serverKeys[serverID] = localID;
}
// generate key events
fakeKeys(keys, count);
return true;
}
bool KeyState::fakeKeyUp(KeyButton serverID)
{
// if we haven't seen this button go down then ignore it
KeyButton localID = m_serverKeys[serverID & kButtonMask];
if (localID == 0) {
return false;
}
// get the sequence of keys to simulate key release
Keystrokes keys;
keys.push_back(Keystroke(localID, false, false, m_keyClientData[localID]));
// note keys down
--m_keys[localID];
--m_syntheticKeys[localID];
m_serverKeys[serverID] = 0;
// check if this is a modifier
ModifierToKeys::iterator i = m_activeModifiers.begin();
while (i != m_activeModifiers.end()) {
if (i->second.m_button == localID && !i->second.m_lock) {
// modifier is no longer down
KeyModifierMask mask = i->first;
ModifierToKeys::iterator tmp = i;
++i;
m_activeModifiers.erase(tmp);
if (m_activeModifiers.count(mask) == 0) {
// no key for modifier is down so deactivate modifier
m_mask &= ~mask;
LOG((CLOG_DEBUG1 "new state %04x", m_mask));
}
} else {
++i;
}
}
// generate key events
fakeKeys(keys, 1);
return true;
}
void KeyState::fakeAllKeysUp()
{
Keystrokes keys;
for (KeyButton i = 0; i < IKeyState::kNumButtons; ++i) {
if (m_syntheticKeys[i] > 0) {
keys.push_back(Keystroke(i, false, false, m_keyClientData[i]));
m_keys[i] = 0;
m_syntheticKeys[i] = 0;
}
}
fakeKeys(keys, 1);
memset(&m_serverKeys, 0, sizeof(m_serverKeys));
m_activeModifiers.clear();
m_mask = pollActiveModifiers();
}
bool KeyState::fakeMediaKey(KeyID id)
{
return false;
}
bool KeyState::isKeyDown(KeyButton button) const
{
return (m_keys[button & kButtonMask] > 0);
}
KeyModifierMask KeyState::getActiveModifiers() const
{
return m_mask;
}
KeyModifierMask &KeyState::getActiveModifiersRValue()
{
return m_mask;
}
SInt32 KeyState::getEffectiveGroup(SInt32 group, SInt32 offset) const
{
return m_keyMap.getEffectiveGroup(group, offset);
}
bool KeyState::isIgnoredKey(KeyID key, KeyModifierMask) const
{
switch (key) {
case kKeyCapsLock:
case kKeyNumLock:
case kKeyScrollLock:
return true;
default:
return false;
}
}
KeyButton KeyState::getButton(KeyID id, SInt32 group) const
{
const deskflow::KeyMap::KeyItemList *items = m_keyMap.findCompatibleKey(id, group, 0, 0);
if (items == NULL) {
return 0;
} else {
return items->back().m_button;
}
}
void KeyState::addAliasEntries()
{
for (SInt32 g = 0, n = m_keyMap.getNumGroups(); g < n; ++g) {
// if we can't shift any kKeyTab key in a particular group but we can
// shift kKeyLeftTab then add a shifted kKeyTab entry that matches a
// shifted kKeyLeftTab entry.
m_keyMap.addKeyAliasEntry(
kKeyTab, g, KeyModifierShift, KeyModifierShift, kKeyLeftTab, KeyModifierShift, KeyModifierShift
);
// if we have no kKeyLeftTab but we do have a kKeyTab that can be
// shifted then add kKeyLeftTab that matches a kKeyTab.
m_keyMap.addKeyAliasEntry(kKeyLeftTab, g, KeyModifierShift, KeyModifierShift, kKeyTab, 0, KeyModifierShift);
// map non-breaking space to space
m_keyMap.addKeyAliasEntry(0x20, g, 0, 0, 0xa0, 0, 0);
}
}
void KeyState::addKeypadEntries()
{
// map every numpad key to its equivalent non-numpad key if it's not
// on the keyboard.
for (SInt32 g = 0, n = m_keyMap.getNumGroups(); g < n; ++g) {
for (size_t i = 0; i < sizeof(s_numpadTable) / sizeof(s_numpadTable[0]); i += 2) {
m_keyMap.addKeyCombinationEntry(s_numpadTable[i], g, s_numpadTable + i + 1, 1);
}
}
}
void KeyState::addCombinationEntries()
{
for (SInt32 g = 0, n = m_keyMap.getNumGroups(); g < n; ++g) {
// add dead and compose key composition sequences
const KeyID *i = s_decomposeTable;
while (*i != 0) {
// count the decomposed keys for this key
UInt32 numKeys = 0;
const KeyID *j = i;
while (*++j != 0) {
++numKeys;
}
// add an entry for this key
m_keyMap.addKeyCombinationEntry(*i, g, i + 1, numKeys);
// next key
i += numKeys + 1;
++i;
}
}
}
void KeyState::fakeKeys(const Keystrokes &keys, UInt32 count)
{
// do nothing if no keys or no repeats
if (count == 0 || keys.empty()) {
return;
}
// generate key events
LOG((CLOG_DEBUG1 "keystrokes:"));
for (Keystrokes::const_iterator k = keys.begin(); k != keys.end();) {
if (k->m_type == Keystroke::kButton && k->m_data.m_button.m_repeat) {
// repeat from here up to but not including the next key
// with m_repeat == false count times.
Keystrokes::const_iterator start = k;
while (count-- > 0) {
// send repeating events
for (k = start; k != keys.end() && k->m_type == Keystroke::kButton && k->m_data.m_button.m_repeat; ++k) {
fakeKey(*k);
}
}
// note -- k is now on the first non-repeat key after the
// repeat keys, exactly where we'd like to continue from.
} else if (k->m_type != Keystroke::kGroup || (!k->m_data.m_group.m_restore && m_isLangSyncEnabled)) {
// send event
fakeKey(*k);
// next key
++k;
} else {
LOG((CLOG_DEBUG1 "skipping keystroke, language sync is disabled"));
++k;
}
}
}
void KeyState::updateModifierKeyState(
KeyButton button, const ModifierToKeys &oldModifiers, const ModifierToKeys &newModifiers
)
{
// get the pressed modifier buttons before and after
deskflow::KeyMap::ButtonToKeyMap oldKeys, newKeys;
for (ModifierToKeys::const_iterator i = oldModifiers.begin(); i != oldModifiers.end(); ++i) {
oldKeys.insert(std::make_pair(i->second.m_button, &i->second));
}
for (ModifierToKeys::const_iterator i = newModifiers.begin(); i != newModifiers.end(); ++i) {
newKeys.insert(std::make_pair(i->second.m_button, &i->second));
}
// get the modifier buttons that were pressed or released
deskflow::KeyMap::ButtonToKeyMap pressed, released;
std::set_difference(
oldKeys.begin(), oldKeys.end(), newKeys.begin(), newKeys.end(), std::inserter(released, released.end()),
ButtonToKeyLess()
);
std::set_difference(
newKeys.begin(), newKeys.end(), oldKeys.begin(), oldKeys.end(), std::inserter(pressed, pressed.end()),
ButtonToKeyLess()
);
// update state
for (deskflow::KeyMap::ButtonToKeyMap::const_iterator i = released.begin(); i != released.end(); ++i) {
if (i->first != button) {
m_keys[i->first] = 0;
m_syntheticKeys[i->first] = 0;
}
}
for (deskflow::KeyMap::ButtonToKeyMap::const_iterator i = pressed.begin(); i != pressed.end(); ++i) {
if (i->first != button) {
m_keys[i->first] = 1;
m_syntheticKeys[i->first] = 1;
m_keyClientData[i->first] = i->second->m_client;
}
}
}
//
// KeyState::AddActiveModifierContext
//
KeyState::AddActiveModifierContext::AddActiveModifierContext(
SInt32 group, KeyModifierMask mask, ModifierToKeys &activeModifiers
)
: m_activeGroup(group),
m_mask(mask),
m_activeModifiers(activeModifiers)
{
// do nothing
}
| 39,381
|
C++
|
.cpp
| 1,079
| 32.008341
| 120
| 0.616508
|
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,493
|
ArgParser.cpp
|
deskflow_deskflow/src/lib/deskflow/ArgParser.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 "base/Log.h"
#include "base/String.h"
#include "deskflow/App.h"
#include "deskflow/ArgsBase.h"
#include "deskflow/ClientArgs.h"
#include "deskflow/ServerArgs.h"
#ifdef WINAPI_MSWINDOWS
#include <VersionHelpers.h>
#endif
deskflow::ArgsBase *ArgParser::m_argsBase = nullptr;
ArgParser::ArgParser(App *app) : m_app(app)
{
}
bool ArgParser::parseServerArgs(deskflow::ServerArgs &args, int argc, const char *const *argv)
{
setArgsBase(args);
updateCommonArgs(argv);
int i = 1;
while (i < argc) {
if (parsePlatformArgs(args, argc, argv, i, true)) {
++i;
continue;
} else if (parseGenericArgs(argc, argv, i)) {
++i;
continue;
} else if (parseDeprecatedArgs(argc, argv, i)) {
++i;
continue;
} else if (isArg(i, argc, argv, "-c", "--config", 1)) {
// save configuration file path
args.m_configFile = argv[++i];
} else if (isArg(i, argc, argv, nullptr, "server")) {
++i;
continue;
} else {
LOG((CLOG_CRIT "%s: unrecognized option `%s'" BYE, args.m_pname, argv[i], args.m_pname));
return false;
}
++i;
}
if (checkUnexpectedArgs()) {
return false;
}
return true;
}
bool ArgParser::parseClientArgs(deskflow::ClientArgs &args, int argc, const char *const *argv)
{
setArgsBase(args);
updateCommonArgs(argv);
int i{1};
while (i < argc) {
if (parsePlatformArgs(args, argc, argv, i, false)) {
++i;
continue;
} else if (parseGenericArgs(argc, argv, i)) {
++i;
continue;
} else if (parseDeprecatedArgs(argc, argv, i)) {
++i;
continue;
} else if (isArg(i, argc, argv, nullptr, "--camp")) {
// ignore -- included for backwards compatibility
} else if (isArg(i, argc, argv, nullptr, "--no-camp")) {
// ignore -- included for backwards compatibility
} else if (isArg(i, argc, argv, nullptr, "--yscroll", 1)) {
// define scroll
args.m_yscroll = atoi(argv[++i]);
} else if (isArg(i, argc, argv, nullptr, "--sync-language")) {
args.m_enableLangSync = true;
} else if (isArg(i, argc, argv, nullptr, "--invert-scroll")) {
args.m_clientScrollDirection = deskflow::ClientScrollDirection::INVERT_SERVER;
} else if (isArg(i, argc, argv, nullptr, "--host")) {
args.m_hostMode = true;
} else if (isArg(i, argc, argv, nullptr, "client")) {
++i;
continue;
} else {
if (i + 1 == argc) {
args.m_serverAddress = argv[i];
return true;
}
LOG((CLOG_CRIT "%s: unrecognized option `%s'" BYE, args.m_pname, argv[i], args.m_pname));
return false;
}
++i;
}
// exactly one non-option argument (server-address)
if (i == argc && !args.m_shouldExitFail && !args.m_shouldExitOk) {
LOG((CLOG_CRIT "%s: a server address or name is required" BYE, args.m_pname, args.m_pname));
return false;
}
if (checkUnexpectedArgs()) {
return false;
}
return true;
}
bool ArgParser::parsePlatformArgs(
deskflow::ArgsBase &argsBase, const int &argc, const char *const *argv, int &i, bool isServer
)
{
#if WINAPI_MSWINDOWS
if (isArg(i, argc, argv, nullptr, "--exit-pause")) {
argsBase.m_pauseOnExit = true;
} else if (isArg(i, argc, argv, nullptr, "--stop-on-desk-switch")) {
argsBase.m_stopOnDeskSwitch = true;
} else {
// option not supported here
return false;
}
return true;
#elif WINAPI_XWINDOWS
if (isArg(i, argc, argv, "-display", "--display", 1)) {
// use alternative display
argsBase.m_display = argv[++i];
}
else if (isArg(i, argc, argv, nullptr, "--no-xinitthreads")) {
argsBase.m_disableXInitThreads = true;
}
else {
// option not supported here
return false;
}
return true;
#elif WINAPI_CARBON
// no options for carbon
return false;
#endif
}
bool ArgParser::parseGenericArgs(int argc, const char *const *argv, int &i)
{
if (isArg(i, argc, argv, "-a", "--address", 1)) {
argsBase().m_deskflowAddress = argv[++i];
} else if (isArg(i, argc, argv, "-d", "--debug", 1)) {
// change logging level
argsBase().m_logFilter = argv[++i];
} else if (isArg(i, argc, argv, "-l", "--log", 1)) {
argsBase().m_logFile = argv[++i];
} else if (isArg(i, argc, argv, "-f", "--no-daemon")) {
// not a daemon
argsBase().m_daemon = false;
} else if (isArg(i, argc, argv, nullptr, "--daemon")) {
// daemonize
argsBase().m_daemon = true;
} else if (isArg(i, argc, argv, "-n", "--name", 1)) {
// save screen name
argsBase().m_name = argv[++i];
} else if (isArg(i, argc, argv, "-1", "--no-restart")) {
// don't try to restart
argsBase().m_restartable = false;
} else if (isArg(i, argc, argv, nullptr, "--restart")) {
// try to restart
argsBase().m_restartable = true;
} else if (isArg(i, argc, argv, nullptr, "--no-hooks")) {
argsBase().m_noHooks = true;
} else if (isArg(i, argc, argv, "-h", "--help")) {
if (m_app) {
m_app->help();
}
argsBase().m_shouldExitOk = true;
} else if (isArg(i, argc, argv, nullptr, "--version")) {
if (m_app) {
m_app->version();
}
argsBase().m_shouldExitOk = true;
} else if (isArg(i, argc, argv, nullptr, "--no-tray")) {
argsBase().m_disableTray = true;
} else if (isArg(i, argc, argv, nullptr, "--ipc")) {
argsBase().m_enableIpc = true;
} else if (isArg(i, argc, argv, nullptr, "--server")) {
// HACK: stop error happening when using portable (deskflowp)
} else if (isArg(i, argc, argv, nullptr, "--client")) {
// HACK: stop error happening when using portable (deskflowp)
} else if (isArg(i, argc, argv, nullptr, "--enable-drag-drop")) {
bool useDragDrop = true;
#ifdef WINAPI_XWINDOWS
useDragDrop = false;
LOG((CLOG_INFO "ignoring --enable-drag-drop, not supported on linux."));
#endif
#ifdef WINAPI_MSWINDOWS
if (!IsWindowsVistaOrGreater()) {
useDragDrop = false;
LOG((CLOG_INFO "ignoring --enable-drag-drop, not supported below vista."));
}
#endif
if (useDragDrop) {
argsBase().m_enableDragDrop = true;
}
} else if (isArg(i, argc, argv, nullptr, "--enable-crypto")) {
argsBase().m_enableCrypto = true;
} else if (isArg(i, argc, argv, nullptr, "--profile-dir", 1)) {
argsBase().m_profileDirectory = argv[++i];
} else if (isArg(i, argc, argv, nullptr, "--plugin-dir", 1)) {
argsBase().m_pluginDirectory = argv[++i];
} else if (isArg(i, argc, argv, nullptr, "--tls-cert", 1)) {
argsBase().m_tlsCertFile = argv[++i];
} else if (isArg(i, argc, argv, nullptr, "--prevent-sleep")) {
argsBase().m_preventSleep = true;
} else {
// option not supported here
return false;
}
return true;
}
bool ArgParser::parseDeprecatedArgs(int argc, const char *const *argv, int &i)
{
static const std::vector<const char *> deprecatedArgs = {
"--crypto-pass", "--res-w", "--res-h", "--prm-wc", "--prm-hc"
};
for (auto &arg : deprecatedArgs) {
if (isArg(i, argc, argv, nullptr, arg)) {
LOG((CLOG_NOTE "%s is deprecated", arg));
i++;
return true;
}
}
return false;
}
bool ArgParser::isArg(
int argi, int argc, const char *const *argv, const char *name1, const char *name2, int minRequiredParameters
)
{
const auto match1 = (name1 != nullptr && strcmp(argv[argi], name1) == 0);
const auto match2 = (name2 != nullptr && strcmp(argv[argi], name2) == 0);
if (match1 || match2) {
// match. check args left.
if (argi + minRequiredParameters >= argc) {
LOG((CLOG_PRINT "%s: missing arguments for `%s'" BYE, argsBase().m_pname, argv[argi], argsBase().m_pname));
argsBase().m_shouldExitFail = true;
return false;
}
return true;
}
// no match
return false;
}
void ArgParser::splitCommandString(String &command, std::vector<String> &argv)
{
if (command.empty()) {
return;
}
size_t leftDoubleQuote = 0;
size_t rightDoubleQuote = 0;
searchDoubleQuotes(command, leftDoubleQuote, rightDoubleQuote);
size_t startPos = 0;
size_t space = command.find(" ", startPos);
while (space != String::npos) {
bool ignoreThisSpace = false;
// check if the space is between two double quotes
if (space > leftDoubleQuote && space < rightDoubleQuote) {
ignoreThisSpace = true;
} else if (space > rightDoubleQuote) {
searchDoubleQuotes(command, leftDoubleQuote, rightDoubleQuote, rightDoubleQuote + 1);
}
if (!ignoreThisSpace) {
String subString = command.substr(startPos, space - startPos);
removeDoubleQuotes(subString);
argv.push_back(subString);
}
// find next space
if (ignoreThisSpace) {
space = command.find(" ", rightDoubleQuote + 1);
} else {
startPos = space + 1;
space = command.find(" ", startPos);
}
}
String subString = command.substr(startPos, command.size());
removeDoubleQuotes(subString);
argv.push_back(subString);
}
bool ArgParser::searchDoubleQuotes(String &command, size_t &left, size_t &right, size_t startPos)
{
bool result = false;
left = String::npos;
right = String::npos;
left = command.find("\"", startPos);
if (left != String::npos) {
right = command.find("\"", left + 1);
if (right != String::npos) {
result = true;
}
}
if (!result) {
left = 0;
right = 0;
}
return result;
}
void ArgParser::removeDoubleQuotes(String &arg)
{
// if string is surrounded by double quotes, remove them
if (arg[0] == '\"' && arg[arg.size() - 1] == '\"') {
arg = arg.substr(1, arg.size() - 2);
}
}
const char **ArgParser::getArgv(std::vector<String> &argsArray)
{
size_t argc = argsArray.size();
// caller is responsible for deleting the outer array only
// we use the c string pointers from argsArray and assign
// them to the inner array. So caller only need to use
// delete[] to delete the outer array
const char **argv = new const char *[argc];
for (size_t i = 0; i < argc; i++) {
argv[i] = argsArray[i].c_str();
}
return argv;
}
String ArgParser::assembleCommand(std::vector<String> &argsArray, String ignoreArg, int parametersRequired)
{
String result;
for (std::vector<String>::iterator it = argsArray.begin(); it != argsArray.end(); ++it) {
if (it->compare(ignoreArg) == 0) {
it = it + parametersRequired;
continue;
}
// if there is a space in this arg, use double quotes surround it
if ((*it).find(" ") != String::npos) {
(*it).insert(0, "\"");
(*it).push_back('\"');
}
result.append(*it);
// add space to saperate args
result.append(" ");
}
if (!result.empty()) {
// remove the tail space
result = result.substr(0, result.size() - 1);
}
return result;
}
void ArgParser::updateCommonArgs(const char *const *argv)
{
argsBase().m_name = ARCH->getHostName();
argsBase().m_pname = ARCH->getBasename(argv[0]);
}
bool ArgParser::checkUnexpectedArgs()
{
#if SYSAPI_WIN32
// suggest that user installs as a windows service. when launched as
// service, process should automatically detect that it should run in
// daemon mode.
if (argsBase().m_daemon) {
LOG(
(CLOG_ERR "the --daemon argument is not supported on windows. "
"instead, install %s as a service (--service install)",
argsBase().m_pname)
);
return true;
}
#endif
return false;
}
| 12,101
|
C++
|
.cpp
| 370
| 28.613514
| 113
| 0.639877
|
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,494
|
AppUtil.cpp
|
deskflow_deskflow/src/lib/deskflow/AppUtil.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 "deskflow/AppUtil.h"
#include "algorithm"
AppUtil *AppUtil::s_instance = nullptr;
AppUtil::AppUtil() : m_app(nullptr)
{
s_instance = this;
}
AppUtil::~AppUtil()
{
}
void AppUtil::adoptApp(IApp *app)
{
app->setByeFunc(&exitAppStatic);
m_app = app;
}
IApp &AppUtil::app() const
{
assert(m_app != nullptr);
return *m_app;
}
AppUtil &AppUtil::instance()
{
assert(s_instance != nullptr);
return *s_instance;
}
| 1,166
|
C++
|
.cpp
| 42
| 25.857143
| 72
| 0.741039
|
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,495
|
DragInformation.cpp
|
deskflow_deskflow/src/lib/deskflow/DragInformation.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 "deskflow/DragInformation.h"
#include "base/Log.h"
#include <fstream>
#include <sstream>
#include <stdexcept>
using namespace std;
DragInformation::DragInformation() : m_filename(), m_filesize(0)
{
}
void DragInformation::parseDragInfo(DragFileList &dragFileList, UInt32 fileNum, String data)
{
size_t startPos = 0;
size_t findResult1 = 0;
size_t findResult2 = 0;
dragFileList.clear();
String slash("\\");
if (data.find("/", startPos) != string::npos) {
slash = "/";
}
UInt32 index = 0;
while (index < fileNum) {
findResult1 = data.find(',', startPos);
findResult2 = data.find_last_of(slash, findResult1);
if (findResult1 == startPos) {
// TODO: file number does not match, something goes wrong
break;
}
// set filename
if (findResult1 - findResult2 > 1) {
String filename = data.substr(findResult2 + 1, findResult1 - findResult2 - 1);
DragInformation di;
di.setFilename(filename);
dragFileList.push_back(di);
}
startPos = findResult1 + 1;
// set filesize
findResult2 = data.find(',', startPos);
if (findResult2 - findResult1 > 1) {
String filesize = data.substr(findResult1 + 1, findResult2 - findResult1 - 1);
size_t size = stringToNum(filesize);
dragFileList.at(index).setFilesize(size);
}
startPos = findResult1 + 1;
++index;
}
LOG((CLOG_DEBUG "drag info received, total drag file number: %i", dragFileList.size()));
for (size_t i = 0; i < dragFileList.size(); ++i) {
LOG((CLOG_DEBUG "dragging file %i name: %s", i + 1, dragFileList.at(i).getFilename().c_str()));
}
}
String DragInformation::getDragFileExtension(String filename)
{
size_t findResult = string::npos;
findResult = filename.find_last_of(".", filename.size());
if (findResult != string::npos) {
return filename.substr(findResult + 1, filename.size() - findResult - 1);
} else {
return "";
}
}
int DragInformation::setupDragInfo(DragFileList &fileList, String &output)
{
int size = static_cast<int>(fileList.size());
for (int i = 0; i < size; ++i) {
output.append(fileList.at(i).getFilename());
output.append(",");
String filesize = getFileSize(fileList.at(i).getFilename());
output.append(filesize);
output.append(",");
}
return size;
}
bool DragInformation::isFileValid(String filename)
{
bool result = false;
std::fstream file(filename.c_str(), ios::in | ios::binary);
if (file.is_open()) {
result = true;
}
file.close();
return result;
}
size_t DragInformation::stringToNum(String &str)
{
istringstream iss(str.c_str());
size_t size;
iss >> size;
return size;
}
String DragInformation::getFileSize(String &filename)
{
std::fstream file(filename.c_str(), ios::in | ios::binary);
if (!file.is_open()) {
throw std::runtime_error("failed to get file size");
}
// check file size
file.seekg(0, std::ios::end);
size_t size = (size_t)file.tellg();
stringstream ss;
ss << size;
file.close();
return ss.str();
}
| 3,736
|
C++
|
.cpp
| 119
| 28.058824
| 99
| 0.689031
|
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,496
|
LanguageManager.cpp
|
deskflow_deskflow/src/lib/deskflow/languages/LanguageManager.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 "LanguageManager.h"
#include "base/Log.h"
#include <algorithm>
namespace {
String vectorToString(const std::vector<String> &vector, const String &delimiter = "")
{
String string;
for (const auto &item : vector) {
if (&item != &vector[0]) {
string += delimiter;
}
string += item;
}
return string;
}
} // anonymous namespace
namespace deskflow {
namespace languages {
LanguageManager::LanguageManager(const std::vector<String> &localLanguages) : m_localLanguages(localLanguages)
{
LOG((CLOG_INFO "local languages: %s", vectorToString(m_localLanguages, ", ").c_str()));
}
void LanguageManager::setRemoteLanguages(const String &remoteLanguages)
{
m_remoteLanguages.clear();
if (!remoteLanguages.empty()) {
for (size_t i = 0; i <= remoteLanguages.size() - 2; i += 2) {
m_remoteLanguages.push_back(remoteLanguages.substr(i, 2));
}
}
LOG((CLOG_INFO "remote languages: %s", vectorToString(m_remoteLanguages, ", ").c_str()));
}
const std::vector<String> &LanguageManager::getRemoteLanguages() const
{
return m_remoteLanguages;
}
const std::vector<String> &LanguageManager::getLocalLanguages() const
{
return m_localLanguages;
}
String LanguageManager::getMissedLanguages() const
{
String missedLanguages;
for (const auto &language : m_remoteLanguages) {
if (!isLanguageInstalled(language)) {
if (!missedLanguages.empty()) {
missedLanguages += ", ";
}
missedLanguages += language;
}
}
return missedLanguages;
}
String LanguageManager::getSerializedLocalLanguages() const
{
return vectorToString(m_localLanguages);
}
bool LanguageManager::isLanguageInstalled(const String &language) const
{
bool isInstalled = true;
if (!m_localLanguages.empty()) {
isInstalled = (std::find(m_localLanguages.begin(), m_localLanguages.end(), language) != m_localLanguages.end());
}
return isInstalled;
}
} // namespace languages
} // namespace deskflow
| 2,653
|
C++
|
.cpp
| 83
| 29.228916
| 116
| 0.73383
|
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,497
|
AppUtilWindows.cpp
|
deskflow_deskflow/src/lib/deskflow/win32/AppUtilWindows.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012 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 "deskflow/win32/AppUtilWindows.h"
#include "arch/IArchTaskBarReceiver.h"
#include "arch/win32/ArchMiscWindows.h"
#include "arch/win32/XArchWindows.h"
#include "base/Event.h"
#include "base/EventQueue.h"
#include "base/IEventQueue.h"
#include "base/Log.h"
#include "base/log_outputters.h"
#include "common/constants.h"
#include "deskflow/App.h"
#include "deskflow/ArgsBase.h"
#include "deskflow/Screen.h"
#include "deskflow/XDeskflow.h"
#include "platform/MSWindowsScreen.h"
#include <VersionHelpers.h>
#include <Windows.h>
#include <conio.h>
#include <iostream>
#include <memory>
#include <sstream>
#if HAVE_WINTOAST
#include "wintoastlib.h"
#endif
AppUtilWindows::AppUtilWindows(IEventQueue *events) : m_events(events), m_exitMode(kExitModeNormal)
{
if (SetConsoleCtrlHandler((PHANDLER_ROUTINE)consoleHandler, TRUE) == FALSE) {
throw XArch(new XArchEvalWindows());
}
}
AppUtilWindows::~AppUtilWindows()
{
}
BOOL WINAPI AppUtilWindows::consoleHandler(DWORD)
{
LOG((CLOG_INFO "got shutdown signal"));
IEventQueue *events = AppUtil::instance().app().getEvents();
events->addEvent(Event(Event::kQuit));
return TRUE;
}
static int mainLoopStatic()
{
return AppUtil::instance().app().mainLoop();
}
int AppUtilWindows::daemonNTMainLoop(int argc, const char **argv)
{
app().initApp(argc, argv);
debugServiceWait();
return ArchMiscWindows::runDaemon(mainLoopStatic);
}
void AppUtilWindows::exitApp(int code)
{
switch (m_exitMode) {
case kExitModeDaemon:
ArchMiscWindows::daemonFailed(code);
break;
default:
throw XExitApp(code);
}
}
int daemonNTMainLoopStatic(int argc, const char **argv)
{
return AppUtilWindows::instance().daemonNTMainLoop(argc, argv);
}
int AppUtilWindows::daemonNTStartup(int, char **)
{
SystemLogger sysLogger(app().daemonName(), false);
m_exitMode = kExitModeDaemon;
return ARCH->daemonize(app().daemonName(), daemonNTMainLoopStatic);
}
static int daemonNTStartupStatic(int argc, char **argv)
{
return AppUtilWindows::instance().daemonNTStartup(argc, argv);
}
static int foregroundStartupStatic(int argc, char **argv)
{
return AppUtil::instance().app().foregroundStartup(argc, argv);
}
void AppUtilWindows::beforeAppExit()
{
// this can be handy for debugging, since the application is launched in
// a new console window, and will normally close on exit (making it so
// that we can't see error messages).
if (app().argsBase().m_pauseOnExit) {
std::cout << std::endl << "press any key to exit..." << std::endl;
int c = _getch();
}
}
int AppUtilWindows::run(int argc, char **argv)
{
if (!IsWindowsXPSP3OrGreater()) {
throw std::runtime_error("unsupported os version, xp sp3 or greater required");
}
// record window instance for tray icon, etc
ArchMiscWindows::setInstanceWin32(GetModuleHandle(NULL));
MSWindowsScreen::init(ArchMiscWindows::instanceWin32());
Thread::getCurrentThread().setPriority(-14);
StartupFunc startup;
if (ArchMiscWindows::wasLaunchedAsService()) {
startup = &daemonNTStartupStatic;
} else {
startup = &foregroundStartupStatic;
app().argsBase().m_daemon = false;
}
return app().runInner(argc, argv, NULL, startup);
}
AppUtilWindows &AppUtilWindows::instance()
{
return (AppUtilWindows &)AppUtil::instance();
}
void AppUtilWindows::debugServiceWait()
{
if (app().argsBase().m_debugServiceWait) {
while (true) {
// this code is only executed when the process is launched via the
// windows service controller (and --debug-service-wait arg is
// used). to debug, set a breakpoint on this line so that
// execution is delayed until the debugger is attached.
ARCH->sleep(1);
LOG((CLOG_INFO "waiting for debugger to attach"));
}
}
}
void AppUtilWindows::startNode()
{
app().startNode();
}
std::vector<String> AppUtilWindows::getKeyboardLayoutList()
{
std::vector<String> layoutLangCodes;
{
auto uLayouts = GetKeyboardLayoutList(0, NULL);
auto lpList = (HKL *)LocalAlloc(LPTR, (uLayouts * sizeof(HKL)));
uLayouts = GetKeyboardLayoutList(uLayouts, lpList);
for (int i = 0; i < uLayouts; ++i) {
String code("", 2);
GetLocaleInfoA(
MAKELCID(((ULONG_PTR)lpList[i] & 0xffffffff), SORT_DEFAULT), LOCALE_SISO639LANGNAME, &code[0],
static_cast<int>(code.size())
);
layoutLangCodes.push_back(code);
}
if (lpList) {
LocalFree(lpList);
}
}
return layoutLangCodes;
}
String AppUtilWindows::getCurrentLanguageCode()
{
String code("", 2);
auto hklLayout = getCurrentKeyboardLayout();
if (hklLayout) {
auto localLayoutID = MAKELCID(LOWORD(hklLayout), SORT_DEFAULT);
GetLocaleInfoA(localLayoutID, LOCALE_SISO639LANGNAME, &code[0], static_cast<int>(code.size()));
}
return code;
}
HKL AppUtilWindows::getCurrentKeyboardLayout() const
{
HKL layout = nullptr;
GUITHREADINFO gti = {sizeof(GUITHREADINFO)};
if (GetGUIThreadInfo(0, >i) && gti.hwndActive) {
layout = GetKeyboardLayout(GetWindowThreadProcessId(gti.hwndActive, NULL));
} else {
LOG((CLOG_WARN "failed to determine current keyboard layout"));
}
return layout;
}
#if HAVE_WINTOAST
class WinToastHandler : public WinToastLib::IWinToastHandler
{
public:
WinToastHandler()
{
}
// Public interfaces
void toastActivated() const override
{
}
void toastActivated(int actionIndex) const override
{
}
void toastDismissed(WinToastDismissalReason state) const override
{
}
void toastFailed() const override
{
}
};
#endif
void AppUtilWindows::showNotification(const String &title, const String &text) const
{
#if HAVE_WINTOAST
LOG((CLOG_INFO "showing notification, title=\"%s\", text=\"%s\"", title.c_str(), text.c_str()));
if (!WinToastLib::WinToast::isCompatible()) {
LOG((CLOG_INFO "this system does not support toast notifications"));
return;
}
if (!WinToastLib::WinToast::instance()->isInitialized()) {
WinToastLib::WinToast::instance()->setAppName(L""
"Deskflow");
const auto aumi = WinToastLib::WinToast::configureAUMI(
L""
"Deskflow Developers",
L""
"Deskflow",
L""
"Deskflow",
L"1.14.1+"
);
WinToastLib::WinToast::instance()->setAppUserModelId(aumi);
if (!WinToastLib::WinToast::instance()->initialize()) {
LOG((CLOG_DEBUG "failed to initialize toast notifications"));
return;
}
}
WinToastLib::WinToast::WinToastError error;
auto handler = std::make_unique<WinToastHandler>();
WinToastLib::WinToastTemplate templ = WinToastLib::WinToastTemplate(WinToastLib::WinToastTemplate::Text02);
templ.setTextField(std::wstring(title.begin(), title.end()), WinToastLib::WinToastTemplate::FirstLine);
templ.setTextField(std::wstring(text.begin(), text.end()), WinToastLib::WinToastTemplate::SecondLine);
const bool launched = WinToastLib::WinToast::instance()->showToast(templ, handler.get(), &error);
if (!launched) {
LOG((CLOG_DEBUG "failed to show toast notification, error code: %d", error));
return;
}
#else
LOG((CLOG_INFO "toast notifications are not supported"));
#endif
}
| 7,917
|
C++
|
.cpp
| 248
| 28.657258
| 109
| 0.724472
|
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,498
|
AppUtilUnix.cpp
|
deskflow_deskflow/src/lib/deskflow/unix/AppUtilUnix.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 "deskflow/unix/AppUtilUnix.h"
#include "deskflow/ArgsBase.h"
#include <thread>
#if WINAPI_XWINDOWS
#include "deskflow/unix/X11LayoutsParser.h"
#include <X11/XKBlib.h>
#elif WINAPI_CARBON
#include <Carbon/Carbon.h>
#include <platform/OSXAutoTypes.h>
#else
#error Platform not supported.
#endif
#include "base/Log.h"
#include "base/log_outputters.h"
#include "common/constants.h"
#if HAVE_LIBNOTIFY
#include <libnotify/notify.h>
#endif
AppUtilUnix::AppUtilUnix(IEventQueue *events)
{
}
AppUtilUnix::~AppUtilUnix()
{
}
int standardStartupStatic(int argc, char **argv)
{
return AppUtil::instance().app().standardStartup(argc, argv);
}
int AppUtilUnix::run(int argc, char **argv)
{
return app().runInner(argc, argv, NULL, &standardStartupStatic);
}
void AppUtilUnix::startNode()
{
app().startNode();
}
std::vector<String> AppUtilUnix::getKeyboardLayoutList()
{
std::vector<String> layoutLangCodes;
#if WINAPI_XWINDOWS
layoutLangCodes = X11LayoutsParser::getX11LanguageList("/usr/share/X11/xkb/rules/evdev.xml");
#elif WINAPI_CARBON
CFStringRef keys[] = {kTISPropertyInputSourceCategory};
CFStringRef values[] = {kTISCategoryKeyboardInputSource};
AutoCFDictionary dict(CFDictionaryCreate(NULL, (const void **)keys, (const void **)values, 1, NULL, NULL), CFRelease);
AutoCFArray kbds(TISCreateInputSourceList(dict.get(), false), CFRelease);
for (CFIndex i = 0; i < CFArrayGetCount(kbds.get()); ++i) {
TISInputSourceRef keyboardLayout = (TISInputSourceRef)CFArrayGetValueAtIndex(kbds.get(), i);
auto layoutLanguages = (CFArrayRef)TISGetInputSourceProperty(keyboardLayout, kTISPropertyInputSourceLanguages);
char temporaryCString[128] = {0};
for (CFIndex index = 0; index < CFArrayGetCount(layoutLanguages) && layoutLanguages; index++) {
auto languageCode = (CFStringRef)CFArrayGetValueAtIndex(layoutLanguages, index);
if (!languageCode || !CFStringGetCString(languageCode, temporaryCString, 128, kCFStringEncodingUTF8)) {
continue;
}
std::string langCode(temporaryCString);
if (langCode.size() == 2 &&
std::find(layoutLangCodes.begin(), layoutLangCodes.end(), langCode) == layoutLangCodes.end()) {
layoutLangCodes.push_back(langCode);
}
// Save only first language code
break;
}
}
#endif
return layoutLangCodes;
}
String AppUtilUnix::getCurrentLanguageCode()
{
String result = "";
#if WINAPI_XWINDOWS
auto display = XOpenDisplay(nullptr);
if (!display) {
LOG((CLOG_WARN "failed to open x11 default display"));
return result;
}
auto kbdDescr = XkbAllocKeyboard();
if (!kbdDescr) {
LOG((CLOG_WARN "failed to get x11 keyboard description"));
return result;
}
XkbGetNames(display, XkbSymbolsNameMask, kbdDescr);
Atom symNameAtom = kbdDescr->names->symbols;
auto rawLayouts = std::string(XGetAtomName(display, symNameAtom));
XkbStateRec state;
XkbGetState(display, XkbUseCoreKbd, &state);
auto nedeedGroupIndex = static_cast<int>(state.group);
size_t groupIdx = 0;
size_t groupStartI = 0;
for (size_t strI = 0; strI < rawLayouts.size(); strI++) {
if (rawLayouts[strI] != '+') {
continue;
}
auto group = rawLayouts.substr(groupStartI, strI - groupStartI);
if (group.find("group", 0, 5) == std::string::npos && group.find("inet", 0, 4) == std::string::npos &&
group.find("pc", 0, 2) == std::string::npos) {
if (nedeedGroupIndex == groupIdx) {
result = group.substr(0, std::min(group.find('(', 0), group.find(':', 0)));
break;
}
groupIdx++;
}
groupStartI = strI + 1;
}
XkbFreeNames(kbdDescr, XkbSymbolsNameMask, true);
XFree(kbdDescr);
XCloseDisplay(display);
result = X11LayoutsParser::convertLayotToISO("/usr/share/X11/xkb/rules/evdev.xml", result);
#elif WINAPI_CARBON
auto layoutLanguages =
(CFArrayRef)TISGetInputSourceProperty(TISCopyCurrentKeyboardInputSource(), kTISPropertyInputSourceLanguages);
char temporaryCString[128] = {0};
for (CFIndex index = 0; index < CFArrayGetCount(layoutLanguages) && layoutLanguages; index++) {
auto languageCode = (CFStringRef)CFArrayGetValueAtIndex(layoutLanguages, index);
if (!languageCode || !CFStringGetCString(languageCode, temporaryCString, 128, kCFStringEncodingUTF8)) {
continue;
}
result = std::string(temporaryCString);
break;
}
#endif
return result;
}
void AppUtilUnix::showNotification(const String &title, const String &text) const
{
#if HAVE_LIBNOTIFY
LOG((CLOG_INFO "showing notification, title=\"%s\", text=\"%s\"", title.c_str(), text.c_str()));
if (!notify_init(kAppName)) {
LOG((CLOG_INFO "failed to initialize libnotify"));
return;
}
auto notification = notify_notification_new(title.c_str(), text.c_str(), nullptr);
if (notification == nullptr) {
LOG((CLOG_INFO "failed to create notification"));
return;
}
notify_notification_set_timeout(notification, 10000);
if (!notify_notification_show(notification, nullptr)) {
LOG((CLOG_INFO "failed to show notification"));
}
g_object_unref(G_OBJECT(notification));
notify_uninit();
#elif WINAPI_CARBON
// server and client processes are not allowed to show notifications.
// MacOS instead ask main deskflow process to show them instead.
LOG((CLOG_INFO "mac notification: %s|%s", title.c_str(), text.c_str()));
#endif
}
| 6,116
|
C++
|
.cpp
| 165
| 33.733333
| 120
| 0.728716
|
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,499
|
X11LayoutsParser.cpp
|
deskflow_deskflow/src/lib/deskflow/unix/X11LayoutsParser.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/>.
*/
#if WINAPI_XWINDOWS
#include <algorithm>
#include <fstream>
#include <sstream>
#include "DeskflowXkbKeyboard.h"
#include "ISO639Table.h"
#include "X11LayoutsParser.h"
#include "base/Log.h"
#include "pugixml.hpp"
namespace {
void splitLine(std::vector<String> &parts, const String &line, char delimiter)
{
std::stringstream stream(line);
while (stream.good()) {
String part;
getline(stream, part, delimiter);
parts.push_back(part);
}
}
} // namespace
bool X11LayoutsParser::readXMLConfigItemElem(const pugi::xml_node *root, std::vector<Lang> &langList)
{
auto configItemElem = root->child("configItem");
if (!configItemElem) {
LOG((CLOG_WARN "failed to read \"configItem\" in xml file"));
return false;
}
langList.emplace_back();
auto nameElem = configItemElem.child("name");
if (nameElem) {
langList.back().name = nameElem.text().as_string();
}
auto languageListElem = configItemElem.child("languageList");
if (languageListElem) {
for (pugi::xml_node isoElem : languageListElem.children("iso639Id")) {
langList.back().layoutBaseISO639_2.emplace_back(isoElem.text().as_string());
}
}
return true;
}
std::vector<X11LayoutsParser::Lang> X11LayoutsParser::getAllLanguageData(const String &pathToEvdevFile)
{
std::vector<Lang> allCodes;
pugi::xml_document doc;
if (!doc.load_file(pathToEvdevFile.c_str())) {
LOG((CLOG_WARN "failed to open %s", pathToEvdevFile.c_str()));
return allCodes;
}
auto xkbConfigElem = doc.child("xkbConfigRegistry");
if (!xkbConfigElem) {
LOG((CLOG_WARN "failed to read xkbConfigRegistry in %s", pathToEvdevFile.c_str()));
return allCodes;
}
auto layoutListElem = xkbConfigElem.child("layoutList");
if (!layoutListElem) {
LOG((CLOG_WARN "failed to read layoutList in %s", pathToEvdevFile.c_str()));
return allCodes;
}
for (pugi::xml_node layoutElem : layoutListElem.children("layout")) {
if (!readXMLConfigItemElem(&layoutElem, allCodes)) {
continue;
}
auto variantListElem = layoutElem.child("variantList");
if (variantListElem) {
for (pugi::xml_node variantElem : variantListElem.children("variant")) {
readXMLConfigItemElem(&variantElem, allCodes.back().variants);
}
}
}
return allCodes;
}
void X11LayoutsParser::appendVectorUniq(const std::vector<String> &source, std::vector<String> &dst)
{
for (const auto &elem : source) {
if (std::find_if(dst.begin(), dst.end(), [elem](const String &s) { return s == elem; }) == dst.end()) {
dst.push_back(elem);
}
}
};
void X11LayoutsParser::convertLayoutToISO639_2(
const String &pathToEvdevFile, bool needToReloadEvdev, const std::vector<String> &layoutNames,
const std::vector<String> &layoutVariantNames, std::vector<String> &iso639_2Codes
)
{
if (layoutNames.size() != layoutVariantNames.size()) {
LOG((CLOG_WARN "error in language layout or language layout variants list"));
return;
}
static std::vector<X11LayoutsParser::Lang> allLang;
if (allLang.empty() || needToReloadEvdev) {
allLang = getAllLanguageData(pathToEvdevFile);
}
for (size_t i = 0; i < layoutNames.size(); i++) {
const auto &layoutName = layoutNames[i];
auto langIter =
std::find_if(allLang.begin(), allLang.end(), [&layoutName](const Lang &l) { return l.name == layoutName; });
if (langIter == allLang.end()) {
LOG((CLOG_WARN "language \"%s\" is unknown", layoutNames[i].c_str()));
continue;
}
const std::vector<String> *toCopy = nullptr;
if (layoutVariantNames[i].empty()) {
toCopy = &langIter->layoutBaseISO639_2;
} else {
const auto &variantName = layoutVariantNames[i];
auto langVariantIter =
std::find_if(langIter->variants.begin(), langIter->variants.end(), [&variantName](const Lang &l) {
return l.name == variantName;
});
if (langVariantIter == langIter->variants.end()) {
LOG(
(CLOG_WARN "variant \"%s\" of language \"%s\" is unknown", layoutVariantNames[i].c_str(),
layoutNames[i].c_str())
);
continue;
}
if (langVariantIter->layoutBaseISO639_2.empty()) {
toCopy = &langIter->layoutBaseISO639_2;
} else {
toCopy = &langVariantIter->layoutBaseISO639_2;
}
}
if (toCopy) {
appendVectorUniq(*toCopy, iso639_2Codes);
}
}
}
std::vector<String> X11LayoutsParser::getX11LanguageList(const String &pathToEvdevFile)
{
std::vector<String> layoutNames;
std::vector<String> layoutVariantNames;
deskflow::linux::DeskflowXkbKeyboard keyboard;
splitLine(layoutNames, keyboard.getLayout(), ',');
splitLine(layoutVariantNames, keyboard.getVariant(), ',');
std::vector<String> iso639_2Codes;
iso639_2Codes.reserve(layoutNames.size());
convertLayoutToISO639_2(pathToEvdevFile, true, layoutNames, layoutVariantNames, iso639_2Codes);
return convertISO639_2ToISO639_1(iso639_2Codes);
}
String
X11LayoutsParser::convertLayotToISO(const String &pathToEvdevFile, const String &layoutLangCode, bool needToReloadFiles)
{
std::vector<String> iso639_2Codes;
convertLayoutToISO639_2(pathToEvdevFile, needToReloadFiles, {layoutLangCode}, {""}, iso639_2Codes);
if (iso639_2Codes.empty()) {
LOG((CLOG_WARN "failed to convert layout lang code: \"%s\"", layoutLangCode.c_str()));
return "";
}
auto iso639_1Codes = convertISO639_2ToISO639_1(iso639_2Codes);
if (iso639_1Codes.empty()) {
LOG((CLOG_WARN "failed to convert ISO639/2 lang code to ISO639/1"));
return "";
}
return *iso639_1Codes.begin();
}
std::vector<String> X11LayoutsParser::convertISO639_2ToISO639_1(const std::vector<String> &iso639_2Codes)
{
std::vector<String> result;
for (const auto &isoCode : iso639_2Codes) {
const auto &tableIter =
std::find_if(ISO_Table.begin(), ISO_Table.end(), [&isoCode](const std::pair<String, String> &c) {
return c.first == isoCode;
});
if (tableIter == ISO_Table.end()) {
LOG((CLOG_WARN "the ISO 639-2 code \"%s\" is missed in table", isoCode.c_str()));
continue;
}
appendVectorUniq({tableIter->second}, result);
}
return result;
}
#endif // WINAPI_XWINDOWS
| 6,964
|
C++
|
.cpp
| 189
| 32.761905
| 120
| 0.698888
|
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,500
|
DeskflowXkbKeyboard.cpp
|
deskflow_deskflow/src/lib/deskflow/unix/DeskflowXkbKeyboard.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2021 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/>.
*/
#if WINAPI_XWINDOWS
#include <memory>
#include "DeskflowXkbKeyboard.h"
#include "base/Log.h"
namespace deskflow {
namespace linux {
DeskflowXkbKeyboard::DeskflowXkbKeyboard()
{
using XkbDisplay = std::unique_ptr<Display, decltype(&XCloseDisplay)>;
XkbDisplay display(XkbOpenDisplay(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr), &XCloseDisplay);
if (display) {
if (!XkbRF_GetNamesProp(display.get(), nullptr, &m_data)) {
LOG((CLOG_WARN "error reading keyboard layouts"));
}
} else {
LOG((CLOG_WARN "can't open xkb display during reading languages"));
}
}
const char *DeskflowXkbKeyboard::getLayout() const
{
return m_data.layout ? m_data.layout : "us";
}
const char *DeskflowXkbKeyboard::getVariant() const
{
return m_data.variant ? m_data.variant : "";
}
DeskflowXkbKeyboard::~DeskflowXkbKeyboard()
{
std::free(m_data.model);
std::free(m_data.layout);
std::free(m_data.variant);
std::free(m_data.options);
}
} // namespace linux
} // namespace deskflow
#endif // WINAPI_XWINDOWS
| 1,770
|
C++
|
.cpp
| 53
| 31.113208
| 107
| 0.746041
|
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,501
|
ArchDaemonNone.cpp
|
deskflow_deskflow/src/lib/arch/ArchDaemonNone.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/ArchDaemonNone.h"
//
// ArchDaemonNone
//
ArchDaemonNone::ArchDaemonNone()
{
// do nothing
}
ArchDaemonNone::~ArchDaemonNone()
{
// do nothing
}
void ArchDaemonNone::installDaemon(const char *, const char *, const char *, const char *, const char *)
{
// do nothing
}
void ArchDaemonNone::uninstallDaemon(const char *)
{
// do nothing
}
int ArchDaemonNone::daemonize(const char *name, DaemonFunc func)
{
// simply forward the call to func. obviously, this doesn't
// do any daemonizing.
return func(1, &name);
}
bool ArchDaemonNone::canInstallDaemon(const char *)
{
return false;
}
bool ArchDaemonNone::isDaemonInstalled(const char *)
{
return false;
}
void ArchDaemonNone::installDaemon()
{
}
void ArchDaemonNone::uninstallDaemon()
{
}
std::string ArchDaemonNone::commandLine() const
{
return "";
}
| 1,578
|
C++
|
.cpp
| 61
| 24.081967
| 104
| 0.756811
|
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,503
|
IArchString.cpp
|
deskflow_deskflow/src/lib/arch/IArchString.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2011 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/IArchString.h"
#include "arch/Arch.h"
#include "common/common.h"
#include <climits>
#include <cstdlib>
#include <cstring>
static ArchMutex s_mutex = NULL;
//
// use C library non-reentrant multibyte conversion with mutex
//
IArchString::~IArchString()
{
if (s_mutex != NULL) {
ARCH->closeMutex(s_mutex);
s_mutex = NULL;
}
}
int IArchString::convStringWCToMB(char *dst, const wchar_t *src, UInt32 n, bool *errors)
{
ptrdiff_t len = 0;
bool dummyErrors;
if (errors == NULL) {
errors = &dummyErrors;
}
*errors = false;
if (s_mutex == NULL) {
s_mutex = ARCH->newMutex();
}
ARCH->lockMutex(s_mutex);
if (dst == NULL) {
char dummy[MB_LEN_MAX];
const wchar_t *scan = src;
for (; n > 0; --n) {
ptrdiff_t mblen = wctomb(dummy, *scan);
if (mblen == -1) {
*errors = true;
mblen = 1;
}
len += mblen;
++scan;
}
ptrdiff_t mblen = wctomb(dummy, L'\0');
if (mblen != -1) {
len += mblen - 1;
}
} else {
char *dst0 = dst;
const wchar_t *scan = src;
for (; n > 0; --n) {
ptrdiff_t mblen = wctomb(dst, *scan);
if (mblen == -1) {
*errors = true;
*dst++ = '?';
} else {
dst += mblen;
}
++scan;
}
ptrdiff_t mblen = wctomb(dst, L'\0');
if (mblen != -1) {
// don't include nul terminator
dst += mblen - 1;
}
len = dst - dst0;
}
ARCH->unlockMutex(s_mutex);
return static_cast<int>(len);
}
int IArchString::convStringMBToWC(wchar_t *dst, const char *src, UInt32 n, bool *errors)
{
ptrdiff_t len = 0;
wchar_t dummy;
bool dummyErrors;
if (errors == NULL) {
errors = &dummyErrors;
}
*errors = false;
if (s_mutex == NULL) {
s_mutex = ARCH->newMutex();
}
ARCH->lockMutex(s_mutex);
if (dst == NULL) {
const char *scan = src;
while (n > 0) {
ptrdiff_t mblen = mbtowc(&dummy, scan, n);
switch (mblen) {
case -2:
// incomplete last character. convert to unknown character.
*errors = true;
len += 1;
n = 0;
break;
case -1:
// invalid character. count one unknown character and
// start at the next byte.
*errors = true;
len += 1;
scan += 1;
n -= 1;
break;
case 0:
len += 1;
scan += 1;
n -= 1;
break;
default:
// normal character
len += 1;
scan += static_cast<int>(mblen);
n -= static_cast<int>(mblen);
break;
}
}
} else {
wchar_t *dst0 = dst;
const char *scan = src;
while (n > 0) {
ptrdiff_t mblen = mbtowc(dst, scan, n);
switch (mblen) {
case -2:
// incomplete character. convert to unknown character.
*errors = true;
*dst = (wchar_t)0xfffd;
n = 0;
break;
case -1:
// invalid character. count one unknown character and
// start at the next byte.
*errors = true;
*dst = (wchar_t)0xfffd;
scan += 1;
n -= 1;
break;
case 0:
*dst = (wchar_t)0x0000;
scan += 1;
n -= 1;
break;
default:
// normal character
scan += static_cast<int>(mblen);
n -= static_cast<int>(mblen);
break;
}
++dst;
}
len = dst - dst0;
}
ARCH->unlockMutex(s_mutex);
return static_cast<int>(len);
}
| 4,207
|
C++
|
.cpp
| 168
| 19.583333
| 88
| 0.569721
|
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,504
|
Arch.cpp
|
deskflow_deskflow/src/lib/arch/Arch.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"
#if SYSAPI_WIN32
#include "arch/win32/ArchMiscWindows.h"
#endif
//
// Arch
//
Arch *Arch::s_instance = NULL;
Arch::Arch()
{
assert(s_instance == NULL);
s_instance = this;
}
Arch::Arch(Arch *arch)
{
s_instance = arch;
}
Arch::~Arch()
{
#if SYSAPI_WIN32
ArchMiscWindows::cleanup();
#endif
}
void Arch::init()
{
ARCH_NETWORK::init();
#if SYSAPI_WIN32
ARCH_TASKBAR::init();
ArchMiscWindows::init();
#endif
}
Arch *Arch::getInstance()
{
assert(s_instance != NULL);
return s_instance;
}
| 1,261
|
C++
|
.cpp
| 53
| 21.981132
| 72
| 0.735613
|
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,505
|
ArchSystemWindows.cpp
|
deskflow_deskflow/src/lib/arch/win32/ArchSystemWindows.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 "arch/win32/ArchSystemWindows.h"
#include "arch/win32/ArchMiscWindows.h"
#include "arch/XArch.h"
#include "common/constants.h"
#include "tchar.h"
#include <string>
#include <psapi.h>
#include <windows.h>
static const char *s_settingsKeyNames[] = {_T("SOFTWARE"), _T(kAppName), NULL};
//
// ArchSystemWindows
//
ArchSystemWindows::ArchSystemWindows()
{
// do nothing
}
ArchSystemWindows::~ArchSystemWindows()
{
// do nothing
}
std::string ArchSystemWindows::getOSName() const
{
std::string osName("Microsoft Windows <unknown>");
static const TCHAR *const windowsVersionKeyNames[] = {
_T("SOFTWARE"), _T("Microsoft"), _T("Windows NT"), _T("CurrentVersion"), NULL
};
HKEY key = ArchMiscWindows::openKey(HKEY_LOCAL_MACHINE, windowsVersionKeyNames);
if (key == NULL) {
return osName;
}
std::string productName = ArchMiscWindows::readValueString(key, "ProductName");
if (osName.empty()) {
return osName;
}
return "Microsoft " + productName;
}
std::string ArchSystemWindows::getPlatformName() const
{
#ifdef _X86_
if (isWOW64())
return "x86 (WOW64)";
else
return "x86";
#else
#ifdef _AMD64_
return "x64";
#else
return "Unknown";
#endif
#endif
}
std::string ArchSystemWindows::setting(const std::string &valueName) const
{
HKEY key = ArchMiscWindows::openKey(HKEY_LOCAL_MACHINE, s_settingsKeyNames);
if (key == NULL)
return "";
return ArchMiscWindows::readValueString(key, valueName.c_str());
}
void ArchSystemWindows::setting(const std::string &valueName, const std::string &valueString) const
{
HKEY key = ArchMiscWindows::addKey(HKEY_LOCAL_MACHINE, s_settingsKeyNames);
if (key == NULL)
throw XArch(std::string("could not access registry key: ") + valueName);
ArchMiscWindows::setValue(key, valueName.c_str(), valueString.c_str());
}
bool ArchSystemWindows::isWOW64() const
{
#if WINVER >= _WIN32_WINNT_WINXP
typedef BOOL(WINAPI * LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
HMODULE hModule = GetModuleHandle(TEXT("kernel32"));
if (!hModule)
return FALSE;
LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(hModule, "IsWow64Process");
BOOL bIsWow64 = FALSE;
if (NULL != fnIsWow64Process && fnIsWow64Process(GetCurrentProcess(), &bIsWow64) && bIsWow64) {
return true;
}
#endif
return false;
}
| 3,060
|
C++
|
.cpp
| 97
| 29.175258
| 104
| 0.741508
|
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,506
|
ArchConsoleWindows.cpp
|
deskflow_deskflow/src/lib/arch/win32/ArchConsoleWindows.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/win32/ArchConsoleWindows.h"
ArchConsoleWindows::ArchConsoleWindows()
{
}
ArchConsoleWindows::~ArchConsoleWindows()
{
}
| 867
|
C++
|
.cpp
| 24
| 34.333333
| 72
| 0.772619
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| true
| false
| false
| true
| false
| false
|
13,507
|
ArchDaemonWindows.cpp
|
deskflow_deskflow/src/lib/arch/win32/ArchDaemonWindows.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/win32/ArchDaemonWindows.h"
#include "arch/Arch.h"
#include "arch/win32/ArchMiscWindows.h"
#include "arch/win32/XArchWindows.h"
#include "common/stdvector.h"
#include <sstream>
//
// ArchDaemonWindows
//
ArchDaemonWindows *ArchDaemonWindows::s_daemon = NULL;
ArchDaemonWindows::ArchDaemonWindows() : m_daemonThreadID(0)
{
m_quitMessage = RegisterWindowMessage("DeskflowDaemonExit");
}
ArchDaemonWindows::~ArchDaemonWindows()
{
// do nothing
}
int ArchDaemonWindows::runDaemon(RunFunc runFunc)
{
assert(s_daemon != NULL);
return s_daemon->doRunDaemon(runFunc);
}
void ArchDaemonWindows::daemonRunning(bool running)
{
if (s_daemon != NULL) {
s_daemon->doDaemonRunning(running);
}
}
UINT ArchDaemonWindows::getDaemonQuitMessage()
{
if (s_daemon != NULL) {
return s_daemon->doGetDaemonQuitMessage();
} else {
return 0;
}
}
void ArchDaemonWindows::daemonFailed(int result)
{
assert(s_daemon != NULL);
throw XArchDaemonRunFailed(result);
}
void ArchDaemonWindows::installDaemon(
const char *name, const char *description, const char *pathname, const char *commandLine, const char *dependencies
)
{
// open service manager
SC_HANDLE mgr = OpenSCManager(NULL, NULL, GENERIC_WRITE);
if (mgr == NULL) {
// can't open service manager
throw XArchDaemonInstallFailed(new XArchEvalWindows);
}
// create the service
SC_HANDLE service = CreateService(
mgr, name, name, 0, SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS, SERVICE_AUTO_START,
SERVICE_ERROR_NORMAL, pathname, NULL, NULL, dependencies, NULL, NULL
);
if (service == NULL) {
// can't create service
DWORD err = GetLastError();
if (err != ERROR_SERVICE_EXISTS) {
CloseServiceHandle(mgr);
throw XArchDaemonInstallFailed(new XArchEvalWindows(err));
}
} else {
// done with service (but only try to close if not null)
CloseServiceHandle(service);
}
// done with manager
CloseServiceHandle(mgr);
// open the registry key for this service
HKEY key = openNTServicesKey();
key = ArchMiscWindows::addKey(key, name);
if (key == NULL) {
// can't open key
DWORD err = GetLastError();
try {
uninstallDaemon(name);
} catch (...) {
// ignore
}
throw XArchDaemonInstallFailed(new XArchEvalWindows(err));
}
// set the description
ArchMiscWindows::setValue(key, _T("Description"), description);
// set command line
key = ArchMiscWindows::addKey(key, _T("Parameters"));
if (key == NULL) {
// can't open key
DWORD err = GetLastError();
ArchMiscWindows::closeKey(key);
try {
uninstallDaemon(name);
} catch (...) {
// ignore
}
throw XArchDaemonInstallFailed(new XArchEvalWindows(err));
}
ArchMiscWindows::setValue(key, _T("CommandLine"), commandLine);
// done with registry
ArchMiscWindows::closeKey(key);
}
void ArchDaemonWindows::uninstallDaemon(const char *name)
{
// remove parameters for this service. ignore failures.
HKEY key = openNTServicesKey();
key = ArchMiscWindows::openKey(key, name);
if (key != NULL) {
ArchMiscWindows::deleteKey(key, _T("Parameters"));
ArchMiscWindows::closeKey(key);
}
// open service manager
SC_HANDLE mgr = OpenSCManager(NULL, NULL, GENERIC_WRITE);
if (mgr == NULL) {
// can't open service manager
throw XArchDaemonUninstallFailed(new XArchEvalWindows);
}
// open the service. oddly, you must open a service to delete it.
SC_HANDLE service = OpenService(mgr, name, DELETE | SERVICE_STOP);
if (service == NULL) {
DWORD err = GetLastError();
CloseServiceHandle(mgr);
if (err != ERROR_SERVICE_DOES_NOT_EXIST) {
throw XArchDaemonUninstallFailed(new XArchEvalWindows(err));
}
throw XArchDaemonUninstallNotInstalled(new XArchEvalWindows(err));
}
// stop the service. we don't care if we fail.
SERVICE_STATUS status;
ControlService(service, SERVICE_CONTROL_STOP, &status);
// delete the service
const bool okay = (DeleteService(service) == 0);
const DWORD err = GetLastError();
// clean up
CloseServiceHandle(service);
CloseServiceHandle(mgr);
// give windows a chance to remove the service before
// we check if it still exists.
ARCH->sleep(1);
// handle failure. ignore error if service isn't installed anymore.
if (!okay && isDaemonInstalled(name)) {
if (err == ERROR_SUCCESS) {
// this seems to occur even though the uninstall was successful.
// it could be a timing issue, i.e., isDaemonInstalled is
// called too soon. i've added a sleep to try and stop this.
return;
}
if (err == ERROR_IO_PENDING) {
// this seems to be a spurious error
return;
}
if (err != ERROR_SERVICE_MARKED_FOR_DELETE) {
throw XArchDaemonUninstallFailed(new XArchEvalWindows(err));
}
throw XArchDaemonUninstallNotInstalled(new XArchEvalWindows(err));
}
}
int ArchDaemonWindows::daemonize(const char *name, DaemonFunc func)
{
assert(name != NULL);
assert(func != NULL);
// save daemon function
m_daemonFunc = func;
// construct the service entry
SERVICE_TABLE_ENTRY entry[2];
entry[0].lpServiceName = const_cast<char *>(name);
entry[0].lpServiceProc = &ArchDaemonWindows::serviceMainEntry;
entry[1].lpServiceName = NULL;
entry[1].lpServiceProc = NULL;
// hook us up to the service control manager. this won't return
// (if successful) until the processes have terminated.
s_daemon = this;
if (StartServiceCtrlDispatcher(entry) == 0) {
// StartServiceCtrlDispatcher failed
s_daemon = NULL;
throw XArchDaemonFailed(new XArchEvalWindows);
}
s_daemon = NULL;
return m_daemonResult;
}
bool ArchDaemonWindows::canInstallDaemon(const char * /*name*/)
{
// check if we can open service manager for write
SC_HANDLE mgr = OpenSCManager(NULL, NULL, GENERIC_WRITE);
if (mgr == NULL) {
return false;
}
CloseServiceHandle(mgr);
// check if we can open the registry key
HKEY key = openNTServicesKey();
ArchMiscWindows::closeKey(key);
return (key != NULL);
}
bool ArchDaemonWindows::isDaemonInstalled(const char *name)
{
// open service manager
SC_HANDLE mgr = OpenSCManager(NULL, NULL, GENERIC_READ);
if (mgr == NULL) {
return false;
}
// open the service
SC_HANDLE service = OpenService(mgr, name, GENERIC_READ);
// clean up
if (service != NULL) {
CloseServiceHandle(service);
}
CloseServiceHandle(mgr);
return (service != NULL);
}
HKEY ArchDaemonWindows::openNTServicesKey()
{
static const char *s_keyNames[] = {_T("SYSTEM"), _T("CurrentControlSet"), _T("Services"), NULL};
return ArchMiscWindows::addKey(HKEY_LOCAL_MACHINE, s_keyNames);
}
bool ArchDaemonWindows::isRunState(DWORD state)
{
switch (state) {
case SERVICE_START_PENDING:
case SERVICE_CONTINUE_PENDING:
case SERVICE_RUNNING:
return true;
default:
return false;
}
}
int ArchDaemonWindows::doRunDaemon(RunFunc run)
{
// should only be called from DaemonFunc
assert(m_serviceMutex != NULL);
assert(run != NULL);
// create message queue for this thread
MSG dummy;
PeekMessage(&dummy, NULL, 0, 0, PM_NOREMOVE);
int result = 0;
ARCH->lockMutex(m_serviceMutex);
m_daemonThreadID = GetCurrentThreadId();
while (m_serviceState != SERVICE_STOPPED) {
// wait until we're told to start
while (!isRunState(m_serviceState) && m_serviceState != SERVICE_STOP_PENDING) {
ARCH->waitCondVar(m_serviceCondVar, m_serviceMutex, -1.0);
}
// run unless told to stop
if (m_serviceState != SERVICE_STOP_PENDING) {
ARCH->unlockMutex(m_serviceMutex);
try {
result = run();
} catch (...) {
ARCH->lockMutex(m_serviceMutex);
setStatusError(0);
m_serviceState = SERVICE_STOPPED;
setStatus(m_serviceState);
ARCH->broadcastCondVar(m_serviceCondVar);
ARCH->unlockMutex(m_serviceMutex);
throw;
}
ARCH->lockMutex(m_serviceMutex);
}
// notify of new state
if (m_serviceState == SERVICE_PAUSE_PENDING) {
m_serviceState = SERVICE_PAUSED;
} else {
m_serviceState = SERVICE_STOPPED;
}
setStatus(m_serviceState);
ARCH->broadcastCondVar(m_serviceCondVar);
}
ARCH->unlockMutex(m_serviceMutex);
return result;
}
void ArchDaemonWindows::doDaemonRunning(bool running)
{
ARCH->lockMutex(m_serviceMutex);
if (running) {
m_serviceState = SERVICE_RUNNING;
setStatus(m_serviceState);
ARCH->broadcastCondVar(m_serviceCondVar);
}
ARCH->unlockMutex(m_serviceMutex);
}
UINT ArchDaemonWindows::doGetDaemonQuitMessage()
{
return m_quitMessage;
}
void ArchDaemonWindows::setStatus(DWORD state)
{
setStatus(state, 0, 0);
}
void ArchDaemonWindows::setStatus(DWORD state, DWORD step, DWORD waitHint)
{
assert(s_daemon != NULL);
SERVICE_STATUS status;
status.dwServiceType = SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS;
status.dwCurrentState = state;
status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE | SERVICE_ACCEPT_SHUTDOWN;
status.dwWin32ExitCode = NO_ERROR;
status.dwServiceSpecificExitCode = 0;
status.dwCheckPoint = step;
status.dwWaitHint = waitHint;
SetServiceStatus(s_daemon->m_statusHandle, &status);
}
void ArchDaemonWindows::setStatusError(DWORD error)
{
assert(s_daemon != NULL);
SERVICE_STATUS status;
status.dwServiceType = SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS;
status.dwCurrentState = SERVICE_STOPPED;
status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE | SERVICE_ACCEPT_SHUTDOWN;
status.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
status.dwServiceSpecificExitCode = error;
status.dwCheckPoint = 0;
status.dwWaitHint = 0;
SetServiceStatus(s_daemon->m_statusHandle, &status);
}
void ArchDaemonWindows::serviceMain(DWORD argc, LPTSTR *argvIn)
{
typedef std::vector<LPCTSTR> ArgList;
typedef std::vector<std::string> Arguments;
const char **argv = const_cast<const char **>(argvIn);
// create synchronization objects
m_serviceMutex = ARCH->newMutex();
m_serviceCondVar = ARCH->newCondVar();
// register our service handler function
m_statusHandle = RegisterServiceCtrlHandler(argv[0], &ArchDaemonWindows::serviceHandlerEntry);
if (m_statusHandle == 0) {
// cannot start as service
m_daemonResult = -1;
ARCH->closeCondVar(m_serviceCondVar);
ARCH->closeMutex(m_serviceMutex);
return;
}
// tell service control manager that we're starting
m_serviceState = SERVICE_START_PENDING;
setStatus(m_serviceState, 0, 10000);
std::string commandLine;
// if no arguments supplied then try getting them from the registry.
// the first argument doesn't count because it's the service name.
Arguments args;
ArgList myArgv;
if (argc <= 1) {
// read command line
HKEY key = openNTServicesKey();
key = ArchMiscWindows::openKey(key, argvIn[0]);
key = ArchMiscWindows::openKey(key, _T("Parameters"));
if (key != NULL) {
commandLine = ArchMiscWindows::readValueString(key, _T("CommandLine"));
}
// if the command line isn't empty then parse and use it
if (!commandLine.empty()) {
// parse, honoring double quoted substrings
std::string::size_type i = commandLine.find_first_not_of(" \t");
while (i != std::string::npos && i != commandLine.size()) {
// find end of string
std::string::size_type e;
if (commandLine[i] == '\"') {
// quoted. find closing quote.
++i;
e = commandLine.find("\"", i);
// whitespace must follow closing quote
if (e == std::string::npos ||
(e + 1 != commandLine.size() && commandLine[e + 1] != ' ' && commandLine[e + 1] != '\t')) {
args.clear();
break;
}
// extract
args.push_back(commandLine.substr(i, e - i));
i = e + 1;
} else {
// unquoted. find next whitespace.
e = commandLine.find_first_of(" \t", i);
if (e == std::string::npos) {
e = commandLine.size();
}
// extract
args.push_back(commandLine.substr(i, e - i));
i = e + 1;
}
// next argument
i = commandLine.find_first_not_of(" \t", i);
}
// service name goes first
myArgv.push_back(argv[0]);
// get pointers
for (size_t j = 0; j < args.size(); ++j) {
myArgv.push_back(args[j].c_str());
}
// adjust argc/argv
argc = (DWORD)myArgv.size();
argv = &myArgv[0];
}
}
m_commandLine = commandLine;
try {
// invoke daemon function
m_daemonResult = m_daemonFunc(static_cast<int>(argc), argv);
} catch (XArchDaemonRunFailed &e) {
setStatusError(e.m_result);
m_daemonResult = -1;
} catch (...) {
setStatusError(1);
m_daemonResult = -1;
}
// clean up
ARCH->closeCondVar(m_serviceCondVar);
ARCH->closeMutex(m_serviceMutex);
// we're going to exit now, so set status to stopped
m_serviceState = SERVICE_STOPPED;
setStatus(m_serviceState, 0, 10000);
}
void WINAPI ArchDaemonWindows::serviceMainEntry(DWORD argc, LPTSTR *argv)
{
s_daemon->serviceMain(argc, argv);
}
void ArchDaemonWindows::serviceHandler(DWORD ctrl)
{
assert(m_serviceMutex != NULL);
assert(m_serviceCondVar != NULL);
ARCH->lockMutex(m_serviceMutex);
// ignore request if service is already stopped
if (s_daemon == NULL || m_serviceState == SERVICE_STOPPED) {
if (s_daemon != NULL) {
setStatus(m_serviceState);
}
ARCH->unlockMutex(m_serviceMutex);
return;
}
switch (ctrl) {
case SERVICE_CONTROL_PAUSE:
m_serviceState = SERVICE_PAUSE_PENDING;
setStatus(m_serviceState, 0, 5000);
PostThreadMessage(m_daemonThreadID, m_quitMessage, 0, 0);
while (isRunState(m_serviceState)) {
ARCH->waitCondVar(m_serviceCondVar, m_serviceMutex, -1.0);
}
break;
case SERVICE_CONTROL_CONTINUE:
// FIXME -- maybe should flush quit messages from queue
m_serviceState = SERVICE_CONTINUE_PENDING;
setStatus(m_serviceState, 0, 5000);
ARCH->broadcastCondVar(m_serviceCondVar);
break;
case SERVICE_CONTROL_STOP:
case SERVICE_CONTROL_SHUTDOWN:
m_serviceState = SERVICE_STOP_PENDING;
setStatus(m_serviceState, 0, 5000);
PostThreadMessage(m_daemonThreadID, m_quitMessage, 0, 0);
ARCH->broadcastCondVar(m_serviceCondVar);
while (isRunState(m_serviceState)) {
ARCH->waitCondVar(m_serviceCondVar, m_serviceMutex, -1.0);
}
break;
default:
// unknown service command
// fall through
case SERVICE_CONTROL_INTERROGATE:
setStatus(m_serviceState);
break;
}
ARCH->unlockMutex(m_serviceMutex);
}
void WINAPI ArchDaemonWindows::serviceHandlerEntry(DWORD ctrl)
{
s_daemon->serviceHandler(ctrl);
}
void ArchDaemonWindows::start(const char *name)
{
// open service manager
SC_HANDLE mgr = OpenSCManager(NULL, NULL, GENERIC_READ);
if (mgr == NULL) {
throw XArchDaemonFailed(new XArchEvalWindows());
}
// open the service
SC_HANDLE service = OpenService(mgr, name, SERVICE_START);
if (service == NULL) {
CloseServiceHandle(mgr);
throw XArchDaemonFailed(new XArchEvalWindows());
}
// start the service
if (!StartService(service, 0, NULL)) {
throw XArchDaemonFailed(new XArchEvalWindows());
}
}
void ArchDaemonWindows::stop(const char *name)
{
// open service manager
SC_HANDLE mgr = OpenSCManager(NULL, NULL, GENERIC_READ);
if (mgr == NULL) {
throw XArchDaemonFailed(new XArchEvalWindows());
}
// open the service
SC_HANDLE service = OpenService(mgr, name, SERVICE_STOP | SERVICE_QUERY_STATUS);
if (service == NULL) {
CloseServiceHandle(mgr);
throw XArchDaemonFailed(new XArchEvalWindows());
}
// ask the service to stop, asynchronously
SERVICE_STATUS ss;
if (!ControlService(service, SERVICE_CONTROL_STOP, &ss)) {
DWORD dwErrCode = GetLastError();
if (dwErrCode != ERROR_SERVICE_NOT_ACTIVE) {
throw XArchDaemonFailed(new XArchEvalWindows());
}
}
}
void ArchDaemonWindows::installDaemon()
{
// install default daemon if not already installed.
if (!isDaemonInstalled(DEFAULT_DAEMON_NAME)) {
char path[MAX_PATH];
GetModuleFileName(ArchMiscWindows::instanceWin32(), path, MAX_PATH);
// wrap in quotes so a malicious user can't start \Program.exe as admin.
std::stringstream ss;
ss << '"';
ss << path;
ss << '"';
installDaemon(DEFAULT_DAEMON_NAME, DEFAULT_DAEMON_INFO, ss.str().c_str(), "", "");
}
start(DEFAULT_DAEMON_NAME);
}
void ArchDaemonWindows::uninstallDaemon()
{
// remove legacy services if installed.
if (isDaemonInstalled(LEGACY_SERVER_DAEMON_NAME)) {
uninstallDaemon(LEGACY_SERVER_DAEMON_NAME);
}
if (isDaemonInstalled(LEGACY_CLIENT_DAEMON_NAME)) {
uninstallDaemon(LEGACY_CLIENT_DAEMON_NAME);
}
// remove new service if installed.
if (isDaemonInstalled(DEFAULT_DAEMON_NAME)) {
uninstallDaemon(DEFAULT_DAEMON_NAME);
}
}
| 17,839
|
C++
|
.cpp
| 549
| 28.424408
| 118
| 0.700401
|
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,508
|
ArchMiscWindows.cpp
|
deskflow_deskflow/src/lib/arch/win32/ArchMiscWindows.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/win32/ArchMiscWindows.h"
#include "arch/win32/ArchDaemonWindows.h"
#include "base/Log.h"
#include "common/constants.h"
#include <Wtsapi32.h>
#pragma warning(disable : 4099)
#include <Userenv.h>
#pragma warning(default : 4099)
// parent process name for services in Vista
#define SERVICE_LAUNCHER "services.exe"
#ifndef ES_SYSTEM_REQUIRED
#define ES_SYSTEM_REQUIRED ((DWORD)0x00000001)
#endif
#ifndef ES_DISPLAY_REQUIRED
#define ES_DISPLAY_REQUIRED ((DWORD)0x00000002)
#endif
#ifndef ES_CONTINUOUS
#define ES_CONTINUOUS ((DWORD)0x80000000)
#endif
typedef DWORD EXECUTION_STATE;
//
// ArchMiscWindows
//
ArchMiscWindows::Dialogs *ArchMiscWindows::s_dialogs = NULL;
DWORD ArchMiscWindows::s_busyState = 0;
ArchMiscWindows::STES_t ArchMiscWindows::s_stes = NULL;
HICON ArchMiscWindows::s_largeIcon = NULL;
HICON ArchMiscWindows::s_smallIcon = NULL;
HINSTANCE ArchMiscWindows::s_instanceWin32 = NULL;
void ArchMiscWindows::cleanup()
{
delete s_dialogs;
}
void ArchMiscWindows::init()
{
// stop windows system error dialogs from showing.
SetErrorMode(SEM_FAILCRITICALERRORS);
s_dialogs = new Dialogs;
}
void ArchMiscWindows::setIcons(HICON largeIcon, HICON smallIcon)
{
s_largeIcon = largeIcon;
s_smallIcon = smallIcon;
}
void ArchMiscWindows::getIcons(HICON &largeIcon, HICON &smallIcon)
{
largeIcon = s_largeIcon;
smallIcon = s_smallIcon;
}
int ArchMiscWindows::runDaemon(RunFunc runFunc)
{
return ArchDaemonWindows::runDaemon(runFunc);
}
void ArchMiscWindows::daemonRunning(bool running)
{
ArchDaemonWindows::daemonRunning(running);
}
void ArchMiscWindows::daemonFailed(int result)
{
ArchDaemonWindows::daemonFailed(result);
}
UINT ArchMiscWindows::getDaemonQuitMessage()
{
return ArchDaemonWindows::getDaemonQuitMessage();
}
HKEY ArchMiscWindows::openKey(HKEY key, const TCHAR *keyName)
{
return openKey(key, keyName, false);
}
HKEY ArchMiscWindows::openKey(HKEY key, const TCHAR *const *keyNames)
{
return openKey(key, keyNames, false);
}
HKEY ArchMiscWindows::addKey(HKEY key, const TCHAR *keyName)
{
return openKey(key, keyName, true);
}
HKEY ArchMiscWindows::addKey(HKEY key, const TCHAR *const *keyNames)
{
return openKey(key, keyNames, true);
}
HKEY ArchMiscWindows::openKey(HKEY key, const TCHAR *keyName, bool create)
{
// ignore if parent is NULL
if (key == NULL) {
return NULL;
}
// open next key
HKEY newKey;
LSTATUS result = RegOpenKeyEx(key, keyName, 0, KEY_WRITE | KEY_QUERY_VALUE, &newKey);
if (result != ERROR_SUCCESS && create) {
DWORD disp;
result = RegCreateKeyEx(key, keyName, 0, NULL, 0, KEY_WRITE | KEY_QUERY_VALUE, NULL, &newKey, &disp);
}
if (result != ERROR_SUCCESS) {
RegCloseKey(key);
return NULL;
}
// switch to new key
RegCloseKey(key);
return newKey;
}
HKEY ArchMiscWindows::openKey(HKEY key, const TCHAR *const *keyNames, bool create)
{
for (size_t i = 0; key != NULL && keyNames[i] != NULL; ++i) {
// open next key
key = openKey(key, keyNames[i], create);
}
return key;
}
void ArchMiscWindows::closeKey(HKEY key)
{
assert(key != NULL);
if (key == NULL)
return;
RegCloseKey(key);
}
void ArchMiscWindows::deleteKey(HKEY key, const TCHAR *name)
{
assert(key != NULL);
assert(name != NULL);
if (key == NULL || name == NULL)
return;
RegDeleteKey(key, name);
}
void ArchMiscWindows::deleteValue(HKEY key, const TCHAR *name)
{
assert(key != NULL);
assert(name != NULL);
if (key == NULL || name == NULL)
return;
RegDeleteValue(key, name);
}
bool ArchMiscWindows::hasValue(HKEY key, const TCHAR *name)
{
DWORD type;
LONG result = RegQueryValueEx(key, name, 0, &type, NULL, NULL);
return (result == ERROR_SUCCESS && (type == REG_DWORD || type == REG_SZ));
}
ArchMiscWindows::EValueType ArchMiscWindows::typeOfValue(HKEY key, const TCHAR *name)
{
DWORD type;
LONG result = RegQueryValueEx(key, name, 0, &type, NULL, NULL);
if (result != ERROR_SUCCESS) {
return kNO_VALUE;
}
switch (type) {
case REG_DWORD:
return kUINT;
case REG_SZ:
return kSTRING;
case REG_BINARY:
return kBINARY;
default:
return kUNKNOWN;
}
}
void ArchMiscWindows::setValue(HKEY key, const TCHAR *name, const std::string &value)
{
assert(key != NULL);
if (key == NULL) {
// TODO: throw exception
return;
}
RegSetValueEx(key, name, 0, REG_SZ, reinterpret_cast<const BYTE *>(value.c_str()), (DWORD)value.size() + 1);
}
void ArchMiscWindows::setValue(HKEY key, const TCHAR *name, DWORD value)
{
assert(key != NULL);
if (key == NULL) {
// TODO: throw exception
return;
}
RegSetValueEx(key, name, 0, REG_DWORD, reinterpret_cast<CONST BYTE *>(&value), sizeof(DWORD));
}
void ArchMiscWindows::setValueBinary(HKEY key, const TCHAR *name, const std::string &value)
{
assert(key != NULL);
assert(name != NULL);
if (key == NULL || name == NULL) {
// TODO: throw exception
return;
}
RegSetValueEx(key, name, 0, REG_BINARY, reinterpret_cast<const BYTE *>(value.data()), (DWORD)value.size());
}
std::string ArchMiscWindows::readBinaryOrString(HKEY key, const TCHAR *name, DWORD type)
{
// get the size of the string
DWORD actualType;
DWORD size = 0;
LONG result = RegQueryValueEx(key, name, 0, &actualType, NULL, &size);
if (result != ERROR_SUCCESS || actualType != type) {
return std::string();
}
// if zero size then return empty string
if (size == 0) {
return std::string();
}
// allocate space
char *buffer = new char[size];
// read it
result = RegQueryValueEx(key, name, 0, &actualType, reinterpret_cast<BYTE *>(buffer), &size);
if (result != ERROR_SUCCESS || actualType != type) {
delete[] buffer;
return std::string();
}
// clean up and return value
if (type == REG_SZ && buffer[size - 1] == '\0') {
// don't include terminating nul; std::string will add one.
--size;
}
std::string value(buffer, size);
delete[] buffer;
return value;
}
std::string ArchMiscWindows::readValueString(HKEY key, const TCHAR *name)
{
return readBinaryOrString(key, name, REG_SZ);
}
std::string ArchMiscWindows::readValueBinary(HKEY key, const TCHAR *name)
{
return readBinaryOrString(key, name, REG_BINARY);
}
DWORD
ArchMiscWindows::readValueInt(HKEY key, const TCHAR *name)
{
DWORD type;
DWORD value;
DWORD size = sizeof(value);
LONG result = RegQueryValueEx(key, name, 0, &type, reinterpret_cast<BYTE *>(&value), &size);
if (result != ERROR_SUCCESS || type != REG_DWORD) {
return 0;
}
return value;
}
void ArchMiscWindows::addDialog(HWND hwnd)
{
s_dialogs->insert(hwnd);
}
void ArchMiscWindows::removeDialog(HWND hwnd)
{
s_dialogs->erase(hwnd);
}
bool ArchMiscWindows::processDialog(MSG *msg)
{
for (Dialogs::const_iterator index = s_dialogs->begin(); index != s_dialogs->end(); ++index) {
if (IsDialogMessage(*index, msg)) {
return true;
}
}
return false;
}
void ArchMiscWindows::addBusyState(DWORD busyModes)
{
s_busyState |= busyModes;
setThreadExecutionState(s_busyState);
}
void ArchMiscWindows::removeBusyState(DWORD busyModes)
{
s_busyState &= ~busyModes;
setThreadExecutionState(s_busyState);
}
void ArchMiscWindows::setThreadExecutionState(DWORD busyModes)
{
// look up function dynamically so we work on older systems
if (s_stes == NULL) {
HINSTANCE kernel = LoadLibrary("kernel32.dll");
if (kernel != NULL) {
s_stes = reinterpret_cast<STES_t>(GetProcAddress(kernel, "SetThreadExecutionState"));
}
if (s_stes == NULL) {
s_stes = &ArchMiscWindows::dummySetThreadExecutionState;
}
}
// convert to STES form
EXECUTION_STATE state = 0;
if ((busyModes & kSYSTEM) != 0) {
state |= ES_SYSTEM_REQUIRED;
}
if ((busyModes & kDISPLAY) != 0) {
state |= ES_DISPLAY_REQUIRED;
}
if (state != 0) {
state |= ES_CONTINUOUS;
}
// do it
s_stes(state);
}
DWORD
ArchMiscWindows::dummySetThreadExecutionState(DWORD)
{
// do nothing
return 0;
}
void ArchMiscWindows::wakeupDisplay()
{
// We can't use ::setThreadExecutionState here because it sets
// ES_CONTINUOUS, which we don't want.
if (s_stes == NULL) {
HINSTANCE kernel = LoadLibrary("kernel32.dll");
if (kernel != NULL) {
s_stes = reinterpret_cast<STES_t>(GetProcAddress(kernel, "SetThreadExecutionState"));
}
if (s_stes == NULL) {
s_stes = &ArchMiscWindows::dummySetThreadExecutionState;
}
}
s_stes(ES_DISPLAY_REQUIRED);
// restore the original execution states
setThreadExecutionState(s_busyState);
}
bool ArchMiscWindows::wasLaunchedAsService()
{
String name;
if (!getParentProcessName(name)) {
LOG((CLOG_ERR "cannot determine if process was launched as service"));
return false;
}
return (name == SERVICE_LAUNCHER);
}
bool ArchMiscWindows::getParentProcessName(String &name)
{
PROCESSENTRY32 parentEntry;
if (!getParentProcessEntry(parentEntry)) {
LOG((CLOG_ERR "could not get entry for parent process"));
return false;
}
name = parentEntry.szExeFile;
return true;
}
BOOL WINAPI ArchMiscWindows::getSelfProcessEntry(PROCESSENTRY32 &entry)
{
// get entry from current PID
return getProcessEntry(entry, GetCurrentProcessId());
}
BOOL WINAPI ArchMiscWindows::getParentProcessEntry(PROCESSENTRY32 &entry)
{
// get the current process, so we can get parent PID
PROCESSENTRY32 selfEntry;
if (!getSelfProcessEntry(selfEntry)) {
return FALSE;
}
// get entry from parent PID
return getProcessEntry(entry, selfEntry.th32ParentProcessID);
}
BOOL WINAPI ArchMiscWindows::getProcessEntry(PROCESSENTRY32 &entry, DWORD processID)
{
// first we need to take a snapshot of the running processes
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot == INVALID_HANDLE_VALUE) {
LOG((CLOG_ERR "could not get process snapshot (error: %i)", GetLastError()));
return FALSE;
}
entry.dwSize = sizeof(PROCESSENTRY32);
// get the first process, and if we can't do that then it's
// unlikely we can go any further
BOOL gotEntry = Process32First(snapshot, &entry);
if (!gotEntry) {
LOG((CLOG_ERR "could not get first process entry (error: %i)", GetLastError()));
return FALSE;
}
while (gotEntry) {
if (entry.th32ProcessID == processID) {
// found current process
return TRUE;
}
// now move on to the next entry (when we reach end, loop will stop)
gotEntry = Process32Next(snapshot, &entry);
}
return FALSE;
}
HINSTANCE
ArchMiscWindows::instanceWin32()
{
assert(s_instanceWin32 != NULL);
return s_instanceWin32;
}
void ArchMiscWindows::setInstanceWin32(HINSTANCE instance)
{
assert(instance != NULL);
s_instanceWin32 = instance;
}
| 11,445
|
C++
|
.cpp
| 399
| 25.97995
| 110
| 0.723579
|
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,509
|
ArchNetworkWinsock.cpp
|
deskflow_deskflow/src/lib/arch/win32/ArchNetworkWinsock.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/win32/ArchNetworkWinsock.h"
#include "arch/Arch.h"
#include "arch/IArchMultithread.h"
#include "arch/win32/ArchMultithreadWindows.h"
#include "arch/win32/XArchWindows.h"
#include <malloc.h>
static const int s_family[] = {
PF_UNSPEC,
PF_INET,
PF_INET6,
};
static const int s_type[] = {SOCK_DGRAM, SOCK_STREAM};
static SOCKET(PASCAL FAR *accept_winsock)(SOCKET s, struct sockaddr FAR *addr, int FAR *addrlen);
static int(PASCAL FAR *bind_winsock)(SOCKET s, const struct sockaddr FAR *addr, int namelen);
static int(PASCAL FAR *close_winsock)(SOCKET s);
static int(PASCAL FAR *connect_winsock)(SOCKET s, const struct sockaddr FAR *name, int namelen);
static int(PASCAL FAR *gethostname_winsock)(char FAR *name, int namelen);
static int(PASCAL FAR *getsockerror_winsock)(void);
static int(PASCAL FAR *getsockopt_winsock)(SOCKET s, int level, int optname, void FAR *optval, int FAR *optlen);
static u_short(PASCAL FAR *htons_winsock)(u_short v);
static char FAR *(PASCAL FAR *inet_ntoa_winsock)(struct in_addr in);
static unsigned long(PASCAL FAR *inet_addr_winsock)(const char FAR *cp);
static int(PASCAL FAR *ioctl_winsock)(SOCKET s, int cmd, void FAR *data);
static int(PASCAL FAR *listen_winsock)(SOCKET s, int backlog);
static u_short(PASCAL FAR *ntohs_winsock)(u_short v);
static int(PASCAL FAR *recv_winsock)(SOCKET s, void FAR *buf, int len, int flags);
static int(PASCAL FAR *select_winsock)(
int nfds, fd_set FAR *readfds, fd_set FAR *writefds, fd_set FAR *exceptfds, const struct timeval FAR *timeout
);
static int(PASCAL FAR *send_winsock)(SOCKET s, const void FAR *buf, int len, int flags);
static int(PASCAL FAR *setsockopt_winsock)(SOCKET s, int level, int optname, const void FAR *optval, int optlen);
static int(PASCAL FAR *shutdown_winsock)(SOCKET s, int how);
static SOCKET(PASCAL FAR *socket_winsock)(int af, int type, int protocol);
static struct hostent FAR *(PASCAL FAR *gethostbyaddr_winsock)(const char FAR *addr, int len, int type);
static struct hostent FAR *(PASCAL FAR *gethostbyname_winsock)(const char FAR *name);
static int(PASCAL FAR *WSACleanup_winsock)(void);
static int(PASCAL FAR *WSAFDIsSet_winsock)(SOCKET, fd_set FAR *fdset);
static WSAEVENT(PASCAL FAR *WSACreateEvent_winsock)(void);
static BOOL(PASCAL FAR *WSACloseEvent_winsock)(WSAEVENT);
static BOOL(PASCAL FAR *WSASetEvent_winsock)(WSAEVENT);
static BOOL(PASCAL FAR *WSAResetEvent_winsock)(WSAEVENT);
static int(PASCAL FAR *WSAEventSelect_winsock)(SOCKET, WSAEVENT, long);
static DWORD(PASCAL FAR *WSAWaitForMultipleEvents_winsock)(DWORD, const WSAEVENT FAR *, BOOL, DWORD, BOOL);
static int(PASCAL FAR *WSAEnumNetworkEvents_winsock)(SOCKET, WSAEVENT, LPWSANETWORKEVENTS);
#undef FD_ISSET
#define FD_ISSET(fd, set) WSAFDIsSet_winsock((SOCKET)(fd), (fd_set FAR *)(set))
#define setfunc(var, name, type) var = (type)netGetProcAddress(module, #name)
static HMODULE s_networkModule = NULL;
static FARPROC netGetProcAddress(HMODULE module, LPCSTR name)
{
FARPROC func = ::GetProcAddress(module, name);
if (!func) {
throw XArchNetworkSupport("");
}
return func;
}
ArchNetAddressImpl *ArchNetAddressImpl::alloc(size_t size)
{
size_t totalSize = size + ADDR_HDR_SIZE;
ArchNetAddressImpl *addr = (ArchNetAddressImpl *)malloc(totalSize);
addr->m_len = (int)size;
return addr;
}
//
// ArchNetworkWinsock
//
ArchNetworkWinsock::ArchNetworkWinsock() : m_mutex(NULL)
{
}
ArchNetworkWinsock::~ArchNetworkWinsock()
{
if (s_networkModule != NULL) {
WSACleanup_winsock();
::FreeLibrary(s_networkModule);
WSACleanup_winsock = NULL;
s_networkModule = NULL;
}
if (m_mutex != NULL) {
ARCH->closeMutex(m_mutex);
}
EventList::iterator it;
for (it = m_unblockEvents.begin(); it != m_unblockEvents.end(); it++) {
delete *it;
}
}
void ArchNetworkWinsock::init()
{
static const char *s_library[] = {"ws2_32.dll"};
assert(WSACleanup_winsock == NULL);
assert(s_networkModule == NULL);
// try each winsock library
for (size_t i = 0; i < sizeof(s_library) / sizeof(s_library[0]); ++i) {
try {
initModule((HMODULE)::LoadLibrary(s_library[i]));
m_mutex = ARCH->newMutex();
return;
} catch (XArchNetwork &) {
// ignore
}
}
// can't initialize any library
throw XArchNetworkSupport("Cannot load winsock library");
}
void ArchNetworkWinsock::initModule(HMODULE module)
{
if (module == NULL) {
throw XArchNetworkSupport("");
}
// get startup function address
int(PASCAL FAR * startup)(WORD, LPWSADATA);
setfunc(startup, WSAStartup, int(PASCAL FAR *)(WORD, LPWSADATA));
// startup network library
WORD version = MAKEWORD(2 /*major*/, 2 /*minor*/);
WSADATA data;
int err = startup(version, &data);
if (data.wVersion != version) {
throw XArchNetworkSupport(new XArchEvalWinsock(err));
}
if (err != 0) {
// some other initialization error
throwError(err);
}
// get function addresses
setfunc(accept_winsock, accept, SOCKET(PASCAL FAR *)(SOCKET s, struct sockaddr FAR * addr, int FAR *addrlen));
setfunc(bind_winsock, bind, int(PASCAL FAR *)(SOCKET s, const struct sockaddr FAR *addr, int namelen));
setfunc(close_winsock, closesocket, int(PASCAL FAR *)(SOCKET s));
setfunc(connect_winsock, connect, int(PASCAL FAR *)(SOCKET s, const struct sockaddr FAR *name, int namelen));
setfunc(gethostname_winsock, gethostname, int(PASCAL FAR *)(char FAR *name, int namelen));
setfunc(getsockerror_winsock, WSAGetLastError, int(PASCAL FAR *)(void));
setfunc(
getsockopt_winsock, getsockopt,
int(PASCAL FAR *)(SOCKET s, int level, int optname, void FAR *optval, int FAR *optlen)
);
setfunc(htons_winsock, htons, u_short(PASCAL FAR *)(u_short v));
setfunc(inet_ntoa_winsock, inet_ntoa, char FAR *(PASCAL FAR *)(struct in_addr in));
setfunc(inet_addr_winsock, inet_addr, unsigned long(PASCAL FAR *)(const char FAR *cp));
setfunc(ioctl_winsock, ioctlsocket, int(PASCAL FAR *)(SOCKET s, int cmd, void FAR *));
setfunc(listen_winsock, listen, int(PASCAL FAR *)(SOCKET s, int backlog));
setfunc(ntohs_winsock, ntohs, u_short(PASCAL FAR *)(u_short v));
setfunc(recv_winsock, recv, int(PASCAL FAR *)(SOCKET s, void FAR *buf, int len, int flags));
setfunc(
select_winsock, select,
int(PASCAL FAR *)(
int nfds, fd_set FAR *readfds, fd_set FAR *writefds, fd_set FAR *exceptfds, const struct timeval FAR *timeout
)
);
setfunc(send_winsock, send, int(PASCAL FAR *)(SOCKET s, const void FAR *buf, int len, int flags));
setfunc(
setsockopt_winsock, setsockopt,
int(PASCAL FAR *)(SOCKET s, int level, int optname, const void FAR *optval, int optlen)
);
setfunc(shutdown_winsock, shutdown, int(PASCAL FAR *)(SOCKET s, int how));
setfunc(socket_winsock, socket, SOCKET(PASCAL FAR *)(int af, int type, int protocol));
setfunc(
gethostbyaddr_winsock, gethostbyaddr, struct hostent FAR * (PASCAL FAR *)(const char FAR *addr, int len, int type)
);
setfunc(gethostbyname_winsock, gethostbyname, struct hostent FAR * (PASCAL FAR *)(const char FAR *name));
setfunc(WSACleanup_winsock, WSACleanup, int(PASCAL FAR *)(void));
setfunc(WSAFDIsSet_winsock, __WSAFDIsSet, int(PASCAL FAR *)(SOCKET, fd_set FAR *));
setfunc(WSACreateEvent_winsock, WSACreateEvent, WSAEVENT(PASCAL FAR *)(void));
setfunc(WSACloseEvent_winsock, WSACloseEvent, BOOL(PASCAL FAR *)(WSAEVENT));
setfunc(WSASetEvent_winsock, WSASetEvent, BOOL(PASCAL FAR *)(WSAEVENT));
setfunc(WSAResetEvent_winsock, WSAResetEvent, BOOL(PASCAL FAR *)(WSAEVENT));
setfunc(WSAEventSelect_winsock, WSAEventSelect, int(PASCAL FAR *)(SOCKET, WSAEVENT, long));
setfunc(
WSAWaitForMultipleEvents_winsock, WSAWaitForMultipleEvents,
DWORD(PASCAL FAR *)(DWORD, const WSAEVENT FAR *, BOOL, DWORD, BOOL)
);
setfunc(WSAEnumNetworkEvents_winsock, WSAEnumNetworkEvents, int(PASCAL FAR *)(SOCKET, WSAEVENT, LPWSANETWORKEVENTS));
s_networkModule = module;
}
ArchSocket ArchNetworkWinsock::newSocket(EAddressFamily family, ESocketType type)
{
// create socket
SOCKET fd = socket_winsock(s_family[family], s_type[type], 0);
if (fd == INVALID_SOCKET) {
throwError(getsockerror_winsock());
}
try {
setBlockingOnSocket(fd, false);
BOOL flag = 0;
int size = sizeof(flag);
if (setsockopt_winsock(fd, IPPROTO_IPV6, IPV6_V6ONLY, &flag, size) == SOCKET_ERROR) {
throwError(getsockerror_winsock());
}
} catch (...) {
close_winsock(fd);
throw;
}
// allocate socket object
ArchSocketImpl *socket = new ArchSocketImpl;
socket->m_socket = fd;
socket->m_refCount = 1;
socket->m_event = WSACreateEvent_winsock();
socket->m_pollWrite = true;
return socket;
}
ArchSocket ArchNetworkWinsock::copySocket(ArchSocket s)
{
assert(s != NULL);
// ref the socket and return it
ARCH->lockMutex(m_mutex);
++s->m_refCount;
ARCH->unlockMutex(m_mutex);
return s;
}
void ArchNetworkWinsock::closeSocket(ArchSocket s)
{
assert(s != NULL);
// unref the socket and note if it should be released
ARCH->lockMutex(m_mutex);
const bool doClose = (--s->m_refCount == 0);
ARCH->unlockMutex(m_mutex);
// close the socket if necessary
if (doClose) {
if (close_winsock(s->m_socket) == SOCKET_ERROR) {
// close failed. restore the last ref and throw.
int err = getsockerror_winsock();
ARCH->lockMutex(m_mutex);
++s->m_refCount;
ARCH->unlockMutex(m_mutex);
throwError(err);
}
WSACloseEvent_winsock(s->m_event);
delete s;
}
}
void ArchNetworkWinsock::closeSocketForRead(ArchSocket s)
{
assert(s != NULL);
if (shutdown_winsock(s->m_socket, SD_RECEIVE) == SOCKET_ERROR) {
if (getsockerror_winsock() != WSAENOTCONN) {
throwError(getsockerror_winsock());
}
}
}
void ArchNetworkWinsock::closeSocketForWrite(ArchSocket s)
{
assert(s != NULL);
if (shutdown_winsock(s->m_socket, SD_SEND) == SOCKET_ERROR) {
if (getsockerror_winsock() != WSAENOTCONN) {
throwError(getsockerror_winsock());
}
}
}
void ArchNetworkWinsock::bindSocket(ArchSocket s, ArchNetAddress addr)
{
assert(s != NULL);
assert(addr != NULL);
if (bind_winsock(s->m_socket, TYPED_ADDR(struct sockaddr, addr), addr->m_len) == SOCKET_ERROR) {
throwError(getsockerror_winsock());
}
}
void ArchNetworkWinsock::listenOnSocket(ArchSocket s)
{
assert(s != NULL);
// hardcoding backlog
if (listen_winsock(s->m_socket, 3) == SOCKET_ERROR) {
throwError(getsockerror_winsock());
}
}
ArchSocket ArchNetworkWinsock::acceptSocket(ArchSocket s, ArchNetAddress *const addr)
{
assert(s != NULL);
// create new socket and temporary address
ArchSocketImpl *socket = new ArchSocketImpl;
ArchNetAddress tmp = ArchNetAddressImpl::alloc(sizeof(struct sockaddr_in6));
// accept on socket
SOCKET fd = accept_winsock(s->m_socket, TYPED_ADDR(struct sockaddr, tmp), &tmp->m_len);
if (fd == INVALID_SOCKET) {
int err = getsockerror_winsock();
delete socket;
free(tmp);
if (addr) {
*addr = NULL;
}
if (err == WSAEWOULDBLOCK) {
return NULL;
}
throwError(err);
}
try {
setBlockingOnSocket(fd, false);
} catch (...) {
close_winsock(fd);
delete socket;
free(tmp);
if (addr) {
*addr = NULL;
}
throw;
}
// initialize socket
socket->m_socket = fd;
socket->m_refCount = 1;
socket->m_event = WSACreateEvent_winsock();
socket->m_pollWrite = true;
// copy address if requested
if (addr != NULL) {
*addr = ARCH->copyAddr(tmp);
}
free(tmp);
return socket;
}
bool ArchNetworkWinsock::connectSocket(ArchSocket s, ArchNetAddress addr)
{
assert(s != NULL);
assert(addr != NULL);
if (connect_winsock(s->m_socket, TYPED_ADDR(struct sockaddr, addr), addr->m_len) == SOCKET_ERROR) {
if (getsockerror_winsock() == WSAEISCONN) {
return true;
}
if (getsockerror_winsock() == WSAEWOULDBLOCK) {
return false;
}
throwError(getsockerror_winsock());
}
return true;
}
int ArchNetworkWinsock::pollSocket(PollEntry pe[], int num, double timeout)
{
int i;
DWORD n;
// prepare sockets and wait list
bool canWrite = false;
WSAEVENT *events = (WSAEVENT *)alloca((num + 1) * sizeof(WSAEVENT));
for (i = 0, n = 0; i < num; ++i) {
// reset return flags
pe[i].m_revents = 0;
// set invalid flag if socket is bogus then go to next socket
if (pe[i].m_socket == NULL) {
pe[i].m_revents |= kPOLLNVAL;
continue;
}
// select desired events
long socketEvents = 0;
if ((pe[i].m_events & kPOLLIN) != 0) {
socketEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;
}
if ((pe[i].m_events & kPOLLOUT) != 0) {
socketEvents |= FD_WRITE | FD_CONNECT | FD_CLOSE;
// if m_pollWrite is false then we assume the socket is
// writable. winsock doesn't signal writability except
// when the state changes from unwritable.
if (!pe[i].m_socket->m_pollWrite) {
canWrite = true;
pe[i].m_revents |= kPOLLOUT;
}
}
// if no events then ignore socket
if (socketEvents == 0) {
continue;
}
// select socket for desired events
WSAEventSelect_winsock(pe[i].m_socket->m_socket, pe[i].m_socket->m_event, socketEvents);
// add socket event to wait list
events[n++] = pe[i].m_socket->m_event;
}
// if no sockets then return immediately
if (n == 0) {
return 0;
}
// add the unblock event
ArchMultithreadWindows *mt = ArchMultithreadWindows::getInstance();
ArchThread thread = mt->newCurrentThread();
WSAEVENT *unblockEvent = (WSAEVENT *)mt->getNetworkDataForThread(thread);
ARCH->closeThread(thread);
if (unblockEvent == NULL) {
unblockEvent = new WSAEVENT;
m_unblockEvents.push_back(unblockEvent);
*unblockEvent = WSACreateEvent_winsock();
mt->setNetworkDataForCurrentThread(unblockEvent);
}
events[n++] = *unblockEvent;
// prepare timeout
DWORD t = (timeout < 0.0) ? INFINITE : (DWORD)(1000.0 * timeout);
if (canWrite) {
// if we know we can write then don't block
t = 0;
}
// wait
DWORD result = WSAWaitForMultipleEvents_winsock(n, events, FALSE, t, FALSE);
// reset the unblock event
WSAResetEvent_winsock(*unblockEvent);
// handle results
if (result == WSA_WAIT_FAILED) {
if (getsockerror_winsock() == WSAEINTR) {
// interrupted system call
ARCH->testCancelThread();
return 0;
}
throwError(getsockerror_winsock());
}
if (result == WSA_WAIT_TIMEOUT && !canWrite) {
return 0;
}
if (result == WSA_WAIT_EVENT_0 + n - 1) {
// the unblock event was signalled
return 0;
}
for (i = 0, n = 0; i < num; ++i) {
// skip events we didn't check
if (pe[i].m_socket == NULL || (pe[i].m_events & (kPOLLIN | kPOLLOUT)) == 0) {
continue;
}
// get events
WSANETWORKEVENTS info;
if (WSAEnumNetworkEvents_winsock(pe[i].m_socket->m_socket, pe[i].m_socket->m_event, &info) == SOCKET_ERROR) {
continue;
}
if ((info.lNetworkEvents & FD_READ) != 0) {
pe[i].m_revents |= kPOLLIN;
}
if ((info.lNetworkEvents & FD_ACCEPT) != 0) {
pe[i].m_revents |= kPOLLIN;
}
if ((info.lNetworkEvents & FD_WRITE) != 0) {
pe[i].m_revents |= kPOLLOUT;
// socket is now writable so don't bothing polling for
// writable until it becomes unwritable.
pe[i].m_socket->m_pollWrite = false;
}
if ((info.lNetworkEvents & FD_CONNECT) != 0) {
if (info.iErrorCode[FD_CONNECT_BIT] != 0) {
pe[i].m_revents |= kPOLLERR;
} else {
pe[i].m_revents |= kPOLLOUT;
pe[i].m_socket->m_pollWrite = false;
}
}
if ((info.lNetworkEvents & FD_CLOSE) != 0) {
if (info.iErrorCode[FD_CLOSE_BIT] != 0) {
pe[i].m_revents |= kPOLLERR;
} else {
if ((pe[i].m_events & kPOLLIN) != 0) {
pe[i].m_revents |= kPOLLIN;
}
if ((pe[i].m_events & kPOLLOUT) != 0) {
pe[i].m_revents |= kPOLLOUT;
}
}
}
if (pe[i].m_revents != 0) {
++n;
}
}
return (int)n;
}
void ArchNetworkWinsock::unblockPollSocket(ArchThread thread)
{
// set the unblock event
ArchMultithreadWindows *mt = ArchMultithreadWindows::getInstance();
WSAEVENT *unblockEvent = (WSAEVENT *)mt->getNetworkDataForThread(thread);
if (unblockEvent != NULL) {
WSASetEvent_winsock(*unblockEvent);
}
}
size_t ArchNetworkWinsock::readSocket(ArchSocket s, void *buf, size_t len)
{
assert(s != NULL);
int n = recv_winsock(s->m_socket, buf, (int)len, 0);
if (n == SOCKET_ERROR) {
int err = getsockerror_winsock();
if (err == WSAEINTR || err == WSAEWOULDBLOCK) {
return 0;
}
throwError(err);
}
return static_cast<size_t>(n);
}
size_t ArchNetworkWinsock::writeSocket(ArchSocket s, const void *buf, size_t len)
{
assert(s != NULL);
int n = send_winsock(s->m_socket, buf, (int)len, 0);
if (n == SOCKET_ERROR) {
int err = getsockerror_winsock();
if (err == WSAEINTR) {
return 0;
}
if (err == WSAEWOULDBLOCK) {
s->m_pollWrite = true;
return 0;
}
throwError(err);
}
return static_cast<size_t>(n);
}
void ArchNetworkWinsock::throwErrorOnSocket(ArchSocket s)
{
assert(s != NULL);
// get the error from the socket layer
int err = 0;
int size = sizeof(err);
if (getsockopt_winsock(s->m_socket, SOL_SOCKET, SO_ERROR, &err, &size) == SOCKET_ERROR) {
err = getsockerror_winsock();
}
// throw if there's an error
if (err != 0) {
throwError(err);
}
}
void ArchNetworkWinsock::setBlockingOnSocket(SOCKET s, bool blocking)
{
assert(s != 0);
int flag = blocking ? 0 : 1;
if (ioctl_winsock(s, FIONBIO, &flag) == SOCKET_ERROR) {
throwError(getsockerror_winsock());
}
}
bool ArchNetworkWinsock::setNoDelayOnSocket(ArchSocket s, bool noDelay)
{
assert(s != NULL);
// get old state
BOOL oflag;
int size = sizeof(oflag);
if (getsockopt_winsock(s->m_socket, IPPROTO_TCP, TCP_NODELAY, &oflag, &size) == SOCKET_ERROR) {
throwError(getsockerror_winsock());
}
// set new state
BOOL flag = noDelay ? 1 : 0;
size = sizeof(flag);
if (setsockopt_winsock(s->m_socket, IPPROTO_TCP, TCP_NODELAY, &flag, size) == SOCKET_ERROR) {
throwError(getsockerror_winsock());
}
return (oflag != 0);
}
bool ArchNetworkWinsock::setReuseAddrOnSocket(ArchSocket s, bool reuse)
{
assert(s != NULL);
// get old state
BOOL oflag;
int size = sizeof(oflag);
if (getsockopt_winsock(s->m_socket, SOL_SOCKET, SO_REUSEADDR, &oflag, &size) == SOCKET_ERROR) {
throwError(getsockerror_winsock());
}
// set new state
BOOL flag = reuse ? 1 : 0;
size = sizeof(flag);
if (setsockopt_winsock(s->m_socket, SOL_SOCKET, SO_REUSEADDR, &flag, size) == SOCKET_ERROR) {
throwError(getsockerror_winsock());
}
return (oflag != 0);
}
std::string ArchNetworkWinsock::getHostName()
{
char name[256];
if (gethostname_winsock(name, sizeof(name)) == -1) {
name[0] = '\0';
} else {
name[sizeof(name) - 1] = '\0';
}
return name;
}
ArchNetAddress ArchNetworkWinsock::newAnyAddr(EAddressFamily family)
{
ArchNetAddressImpl *addr = NULL;
switch (family) {
case kINET: {
addr = ArchNetAddressImpl::alloc(sizeof(struct sockaddr_in));
struct sockaddr_in *ipAddr = TYPED_ADDR(struct sockaddr_in, addr);
ipAddr->sin_family = AF_INET;
ipAddr->sin_port = 0;
ipAddr->sin_addr.s_addr = INADDR_ANY;
break;
}
case kINET6: {
addr = ArchNetAddressImpl::alloc(sizeof(struct sockaddr_in6));
struct sockaddr_in6 *ipAddr = TYPED_ADDR(struct sockaddr_in6, addr);
ipAddr->sin6_family = AF_INET6;
ipAddr->sin6_port = 0;
memcpy(&ipAddr->sin6_addr, &in6addr_any, sizeof(in6addr_any));
break;
}
default:
assert(0 && "invalid family");
}
return addr;
}
ArchNetAddress ArchNetworkWinsock::copyAddr(ArchNetAddress addr)
{
assert(addr != NULL);
ArchNetAddressImpl *copy = ArchNetAddressImpl::alloc(addr->m_len);
memcpy(TYPED_ADDR(void, copy), TYPED_ADDR(void, addr), addr->m_len);
return copy;
}
std::vector<ArchNetAddress> ArchNetworkWinsock::nameToAddr(const std::string &name)
{
// allocate address
std::vector<ArchNetAddressImpl *> addresses;
struct addrinfo hints;
struct addrinfo *pResult;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
int ret = -1;
ARCH->lockMutex(m_mutex);
if ((ret = getaddrinfo(name.c_str(), NULL, &hints, &pResult)) != 0) {
ARCH->unlockMutex(m_mutex);
throwNameError(ret);
}
for (auto address = pResult; address != nullptr; address = address->ai_next) {
addresses.push_back(new ArchNetAddressImpl);
if (address->ai_family == AF_INET) {
addresses.back()->m_len = (socklen_t)sizeof(struct sockaddr_in);
} else {
addresses.back()->m_len = (socklen_t)sizeof(struct sockaddr_in6);
}
memcpy(&addresses.back()->m_addr, address->ai_addr, addresses.back()->m_len);
}
freeaddrinfo(pResult);
ARCH->unlockMutex(m_mutex);
return addresses;
}
void ArchNetworkWinsock::closeAddr(ArchNetAddress addr)
{
assert(addr != NULL);
free(addr);
}
std::string ArchNetworkWinsock::addrToName(ArchNetAddress addr)
{
assert(addr != NULL);
char host[1024];
char service[20];
int ret =
getnameinfo(TYPED_ADDR(struct sockaddr, addr), addr->m_len, host, sizeof(host), service, sizeof(service), 0);
if (ret != NULL) {
throwNameError(ret);
}
// return (primary) name
std::string name = host;
return name;
}
std::string ArchNetworkWinsock::addrToString(ArchNetAddress addr)
{
assert(addr != NULL);
switch (getAddrFamily(addr)) {
case kINET: {
struct sockaddr_in *ipAddr = TYPED_ADDR(struct sockaddr_in, addr);
return inet_ntoa_winsock(ipAddr->sin_addr);
}
case kINET6: {
char strAddr[INET6_ADDRSTRLEN];
struct sockaddr_in6 *ipAddr = TYPED_ADDR(struct sockaddr_in6, addr);
inet_ntop(AF_INET6, &ipAddr->sin6_addr, strAddr, INET6_ADDRSTRLEN);
return strAddr;
}
default:
assert(0 && "unknown address family");
return "";
}
}
IArchNetwork::EAddressFamily ArchNetworkWinsock::getAddrFamily(ArchNetAddress addr)
{
assert(addr != NULL);
switch (addr->m_addr.ss_family) {
case AF_INET:
return kINET;
case AF_INET6:
return kINET6;
default:
return kUNKNOWN;
}
}
void ArchNetworkWinsock::setAddrPort(ArchNetAddress addr, int port)
{
assert(addr != NULL);
switch (getAddrFamily(addr)) {
case kINET: {
struct sockaddr_in *ipAddr = TYPED_ADDR(struct sockaddr_in, addr);
ipAddr->sin_port = htons_winsock(static_cast<u_short>(port));
break;
}
case kINET6: {
struct sockaddr_in6 *ipAddr = TYPED_ADDR(struct sockaddr_in6, addr);
ipAddr->sin6_port = htons_winsock(static_cast<u_short>(port));
break;
}
default:
assert(0 && "unknown address family");
break;
}
}
int ArchNetworkWinsock::getAddrPort(ArchNetAddress addr)
{
assert(addr != NULL);
switch (getAddrFamily(addr)) {
case kINET: {
struct sockaddr_in *ipAddr = TYPED_ADDR(struct sockaddr_in, addr);
return ntohs_winsock(ipAddr->sin_port);
}
case kINET6: {
struct sockaddr_in6 *ipAddr = TYPED_ADDR(struct sockaddr_in6, addr);
return ntohs_winsock(ipAddr->sin6_port);
}
default:
assert(0 && "unknown address family");
return 0;
}
}
bool ArchNetworkWinsock::isAnyAddr(ArchNetAddress addr)
{
assert(addr != NULL);
switch (getAddrFamily(addr)) {
case kINET: {
struct sockaddr_in *ipAddr = TYPED_ADDR(struct sockaddr_in, addr);
return (addr->m_len == sizeof(struct sockaddr_in) && ipAddr->sin_addr.s_addr == INADDR_ANY);
}
case kINET6: {
struct sockaddr_in6 *ipAddr = TYPED_ADDR(struct sockaddr_in6, addr);
return (
addr->m_len == sizeof(struct sockaddr_in) && memcmp(&ipAddr->sin6_addr, &in6addr_any, sizeof(in6addr_any)) == 0
);
}
default:
assert(0 && "unknown address family");
return true;
}
}
bool ArchNetworkWinsock::isEqualAddr(ArchNetAddress a, ArchNetAddress b)
{
return (a == b || (a->m_len == b->m_len && memcmp(&a->m_addr, &b->m_addr, a->m_len) == 0));
}
void ArchNetworkWinsock::throwError(int err)
{
switch (err) {
case WSAEACCES:
throw XArchNetworkAccess(new XArchEvalWinsock(err));
case WSAEMFILE:
case WSAENOBUFS:
case WSAENETDOWN:
throw XArchNetworkResource(new XArchEvalWinsock(err));
case WSAEPROTOTYPE:
case WSAEPROTONOSUPPORT:
case WSAEAFNOSUPPORT:
case WSAEPFNOSUPPORT:
case WSAESOCKTNOSUPPORT:
case WSAEINVAL:
case WSAENOPROTOOPT:
case WSAEOPNOTSUPP:
case WSAESHUTDOWN:
case WSANOTINITIALISED:
case WSAVERNOTSUPPORTED:
case WSASYSNOTREADY:
throw XArchNetworkSupport(new XArchEvalWinsock(err));
case WSAEADDRNOTAVAIL:
throw XArchNetworkNoAddress(new XArchEvalWinsock(err));
case WSAEADDRINUSE:
throw XArchNetworkAddressInUse(new XArchEvalWinsock(err));
case WSAEHOSTUNREACH:
case WSAENETUNREACH:
throw XArchNetworkNoRoute(new XArchEvalWinsock(err));
case WSAENOTCONN:
throw XArchNetworkNotConnected(new XArchEvalWinsock(err));
case WSAEDISCON:
throw XArchNetworkShutdown(new XArchEvalWinsock(err));
case WSAENETRESET:
case WSAECONNABORTED:
case WSAECONNRESET:
throw XArchNetworkDisconnected(new XArchEvalWinsock(err));
case WSAECONNREFUSED:
throw XArchNetworkConnectionRefused(new XArchEvalWinsock(err));
case WSAEHOSTDOWN:
case WSAETIMEDOUT:
throw XArchNetworkTimedOut(new XArchEvalWinsock(err));
case WSAHOST_NOT_FOUND:
throw XArchNetworkNameUnknown(new XArchEvalWinsock(err));
case WSANO_DATA:
throw XArchNetworkNameNoAddress(new XArchEvalWinsock(err));
case WSANO_RECOVERY:
throw XArchNetworkNameFailure(new XArchEvalWinsock(err));
case WSATRY_AGAIN:
throw XArchNetworkNameUnavailable(new XArchEvalWinsock(err));
default:
throw XArchNetwork(new XArchEvalWinsock(err));
}
}
void ArchNetworkWinsock::throwNameError(int err)
{
switch (err) {
case WSAHOST_NOT_FOUND:
throw XArchNetworkNameUnknown(new XArchEvalWinsock(err));
case WSANO_DATA:
throw XArchNetworkNameNoAddress(new XArchEvalWinsock(err));
case WSANO_RECOVERY:
throw XArchNetworkNameFailure(new XArchEvalWinsock(err));
case WSATRY_AGAIN:
throw XArchNetworkNameUnavailable(new XArchEvalWinsock(err));
default:
throw XArchNetworkName(new XArchEvalWinsock(err));
}
}
| 27,161
|
C++
|
.cpp
| 807
| 29.972739
| 120
| 0.697963
|
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,510
|
ArchLogWindows.cpp
|
deskflow_deskflow/src/lib/arch/win32/ArchLogWindows.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/win32/ArchLogWindows.h"
#include "arch/win32/ArchMiscWindows.h"
#include <string.h>
//
// ArchLogWindows
//
ArchLogWindows::ArchLogWindows() : m_eventLog(NULL)
{
// do nothing
}
ArchLogWindows::~ArchLogWindows()
{
// do nothing
}
void ArchLogWindows::openLog(const char *name)
{
if (m_eventLog == NULL) {
m_eventLog = RegisterEventSource(NULL, name);
}
}
void ArchLogWindows::closeLog()
{
if (m_eventLog != NULL) {
DeregisterEventSource(m_eventLog);
m_eventLog = NULL;
}
}
void ArchLogWindows::showLog(bool)
{
// do nothing
}
void ArchLogWindows::writeLog(ELevel level, const char *msg)
{
if (m_eventLog != NULL) {
// convert priority
WORD type;
switch (level) {
case kERROR:
type = EVENTLOG_ERROR_TYPE;
break;
case kWARNING:
type = EVENTLOG_WARNING_TYPE;
break;
default:
type = EVENTLOG_INFORMATION_TYPE;
break;
}
// log it
// FIXME -- win32 wants to use a message table to look up event
// strings. log messages aren't organized that way so we'll
// just dump our string into the raw data section of the event
// so users can at least see the message. note that we use our
// level as the event category.
ReportEvent(
m_eventLog, type, static_cast<WORD>(level),
0, // event ID
NULL, 0,
(DWORD)strlen(msg) + 1, // raw data size
NULL,
const_cast<char *>(msg)
); // raw data
}
}
| 2,211
|
C++
|
.cpp
| 80
| 24.1125
| 72
| 0.691836
|
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,511
|
ArchTaskBarWindows.cpp
|
deskflow_deskflow/src/lib/arch/win32/ArchTaskBarWindows.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 "arch/win32/ArchTaskBarWindows.h"
#include "arch/Arch.h"
#include "arch/IArchTaskBarReceiver.h"
#include "arch/XArch.h"
#include "arch/win32/ArchMiscWindows.h"
#include "deskflow/win32/AppUtilWindows.h"
#include <shellapi.h>
#include <string.h>
static const UINT kAddReceiver = WM_USER + 10;
static const UINT kRemoveReceiver = WM_USER + 11;
static const UINT kUpdateReceiver = WM_USER + 12;
static const UINT kNotifyReceiver = WM_USER + 13;
static const UINT kFirstReceiverID = WM_USER + 14;
//
// ArchTaskBarWindows
//
ArchTaskBarWindows *ArchTaskBarWindows::s_instance = NULL;
ArchTaskBarWindows::ArchTaskBarWindows()
: m_mutex(NULL),
m_condVar(NULL),
m_ready(false),
m_result(0),
m_thread(NULL),
m_hwnd(NULL),
m_taskBarRestart(0),
m_nextID(kFirstReceiverID)
{
// save the singleton instance
s_instance = this;
}
ArchTaskBarWindows::~ArchTaskBarWindows()
{
if (m_thread != NULL) {
PostMessage(m_hwnd, WM_QUIT, 0, 0);
ARCH->wait(m_thread, -1.0);
ARCH->closeThread(m_thread);
}
if (m_condVar != NULL) {
ARCH->closeCondVar(m_condVar);
}
if (m_mutex != NULL) {
ARCH->closeMutex(m_mutex);
}
s_instance = NULL;
}
void ArchTaskBarWindows::init()
{
// we need a mutex
m_mutex = ARCH->newMutex();
// and a condition variable which uses the above mutex
m_ready = false;
m_condVar = ARCH->newCondVar();
// we're going to want to get a result from the thread we're
// about to create to know if it initialized successfully.
// so we lock the condition variable.
ARCH->lockMutex(m_mutex);
// open a window and run an event loop in a separate thread.
// this has to happen in a separate thread because if we
// create a window on the current desktop with the current
// thread then the current thread won't be able to switch
// desktops if it needs to.
m_thread = ARCH->newThread(&ArchTaskBarWindows::threadEntry, this);
// wait for child thread
while (!m_ready) {
ARCH->waitCondVar(m_condVar, m_mutex, -1.0);
}
// ready
ARCH->unlockMutex(m_mutex);
}
void ArchTaskBarWindows::addDialog(HWND hwnd)
{
ArchMiscWindows::addDialog(hwnd);
}
void ArchTaskBarWindows::removeDialog(HWND hwnd)
{
ArchMiscWindows::removeDialog(hwnd);
}
void ArchTaskBarWindows::addReceiver(IArchTaskBarReceiver *receiver)
{
// ignore bogus receiver
if (receiver == NULL) {
return;
}
// add receiver if necessary
ReceiverToInfoMap::iterator index = m_receivers.find(receiver);
if (index == m_receivers.end()) {
// add it, creating a new message ID for it
ReceiverInfo info;
info.m_id = getNextID();
index = m_receivers.insert(std::make_pair(receiver, info)).first;
// add ID to receiver mapping
m_idTable.insert(std::make_pair(info.m_id, index));
}
// add receiver
PostMessage(m_hwnd, kAddReceiver, index->second.m_id, 0);
}
void ArchTaskBarWindows::removeReceiver(IArchTaskBarReceiver *receiver)
{
// find receiver
ReceiverToInfoMap::iterator index = m_receivers.find(receiver);
if (index == m_receivers.end()) {
return;
}
// remove icon. wait for this to finish before returning.
SendMessage(m_hwnd, kRemoveReceiver, index->second.m_id, 0);
// recycle the ID
recycleID(index->second.m_id);
// discard
m_idTable.erase(index->second.m_id);
m_receivers.erase(index);
}
void ArchTaskBarWindows::updateReceiver(IArchTaskBarReceiver *receiver)
{
// find receiver
ReceiverToInfoMap::const_iterator index = m_receivers.find(receiver);
if (index == m_receivers.end()) {
return;
}
// update icon and tool tip
PostMessage(m_hwnd, kUpdateReceiver, index->second.m_id, 0);
}
UINT ArchTaskBarWindows::getNextID()
{
if (m_oldIDs.empty()) {
return m_nextID++;
}
UINT id = m_oldIDs.back();
m_oldIDs.pop_back();
return id;
}
void ArchTaskBarWindows::recycleID(UINT id)
{
m_oldIDs.push_back(id);
}
void ArchTaskBarWindows::addIcon(UINT id)
{
ARCH->lockMutex(m_mutex);
CIDToReceiverMap::const_iterator index = m_idTable.find(id);
if (index != m_idTable.end()) {
modifyIconNoLock(index->second, NIM_ADD);
}
ARCH->unlockMutex(m_mutex);
}
void ArchTaskBarWindows::removeIcon(UINT id)
{
ARCH->lockMutex(m_mutex);
removeIconNoLock(id);
ARCH->unlockMutex(m_mutex);
}
void ArchTaskBarWindows::updateIcon(UINT id)
{
ARCH->lockMutex(m_mutex);
CIDToReceiverMap::const_iterator index = m_idTable.find(id);
if (index != m_idTable.end()) {
modifyIconNoLock(index->second, NIM_MODIFY);
}
ARCH->unlockMutex(m_mutex);
}
void ArchTaskBarWindows::addAllIcons()
{
ARCH->lockMutex(m_mutex);
for (ReceiverToInfoMap::const_iterator index = m_receivers.begin(); index != m_receivers.end(); ++index) {
modifyIconNoLock(index, NIM_ADD);
}
ARCH->unlockMutex(m_mutex);
}
void ArchTaskBarWindows::removeAllIcons()
{
ARCH->lockMutex(m_mutex);
for (ReceiverToInfoMap::const_iterator index = m_receivers.begin(); index != m_receivers.end(); ++index) {
removeIconNoLock(index->second.m_id);
}
ARCH->unlockMutex(m_mutex);
}
void ArchTaskBarWindows::modifyIconNoLock(ReceiverToInfoMap::const_iterator index, DWORD taskBarMessage)
{
// get receiver
UINT id = index->second.m_id;
IArchTaskBarReceiver *receiver = index->first;
// lock receiver so icon and tool tip are guaranteed to be consistent
receiver->lock();
// get icon data
HICON icon = static_cast<HICON>(const_cast<IArchTaskBarReceiver::Icon>(receiver->getIcon()));
// get tool tip
std::string toolTip = receiver->getToolTip();
// done querying
receiver->unlock();
// prepare to add icon
NOTIFYICONDATA data;
data.cbSize = sizeof(NOTIFYICONDATA);
data.hWnd = m_hwnd;
data.uID = id;
data.uFlags = NIF_MESSAGE;
data.uCallbackMessage = kNotifyReceiver;
data.hIcon = icon;
if (icon != NULL) {
data.uFlags |= NIF_ICON;
}
if (!toolTip.empty()) {
strncpy(data.szTip, toolTip.c_str(), sizeof(data.szTip));
data.szTip[sizeof(data.szTip) - 1] = '\0';
data.uFlags |= NIF_TIP;
} else {
data.szTip[0] = '\0';
}
// add icon
if (Shell_NotifyIcon(taskBarMessage, &data) == 0) {
// failed
}
}
void ArchTaskBarWindows::removeIconNoLock(UINT id)
{
NOTIFYICONDATA data;
data.cbSize = sizeof(NOTIFYICONDATA);
data.hWnd = m_hwnd;
data.uID = id;
if (Shell_NotifyIcon(NIM_DELETE, &data) == 0) {
// failed
}
}
void ArchTaskBarWindows::handleIconMessage(IArchTaskBarReceiver *receiver, LPARAM lParam)
{
// process message
switch (lParam) {
case WM_LBUTTONDOWN:
receiver->showStatus();
break;
case WM_LBUTTONDBLCLK:
receiver->primaryAction();
break;
case WM_RBUTTONUP: {
POINT p;
GetCursorPos(&p);
receiver->runMenu(p.x, p.y);
break;
}
case WM_MOUSEMOVE:
// currently unused
break;
default:
// unused
break;
}
}
bool ArchTaskBarWindows::processDialogs(MSG *msg)
{
// only one thread can be in this method on any particular object
// at any given time. that's not a problem since only our event
// loop calls this method and there's just one of those.
ARCH->lockMutex(m_mutex);
// there was previously some code here, with the comment "remove removed
// dialogs":
// m_dialogs.erase(false);
//
// it's not entirely clear what this code was doing, but it was probably
// trying to erase dialogs that had been removed (i.e. the map value was
// `false`).
for (auto it = m_dialogs.begin(); it != m_dialogs.end();) {
if (it->second == false) {
it = m_dialogs.erase(it);
} else {
++it;
}
}
// merge added dialogs into the dialog list
for (Dialogs::const_iterator index = m_addedDialogs.begin(); index != m_addedDialogs.end(); ++index) {
m_dialogs.insert(std::make_pair(index->first, index->second));
}
m_addedDialogs.clear();
ARCH->unlockMutex(m_mutex);
// check message against all dialogs until one handles it.
// note that we don't hold a lock while checking because
// the message is processed and may make calls to this
// object. that's okay because addDialog() and
// removeDialog() don't change the map itself (just the
// values of some elements).
ARCH->lockMutex(m_mutex);
for (Dialogs::const_iterator index = m_dialogs.begin(); index != m_dialogs.end(); ++index) {
if (index->second) {
ARCH->unlockMutex(m_mutex);
if (IsDialogMessage(index->first, msg)) {
return true;
}
ARCH->lockMutex(m_mutex);
}
}
ARCH->unlockMutex(m_mutex);
return false;
}
LRESULT
ArchTaskBarWindows::wndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg) {
case kNotifyReceiver: {
// lookup receiver
CIDToReceiverMap::const_iterator index = m_idTable.find((UINT)wParam);
if (index != m_idTable.end()) {
IArchTaskBarReceiver *receiver = index->second->first;
handleIconMessage(receiver, lParam);
return 0;
}
break;
}
case kAddReceiver:
addIcon((UINT)wParam);
break;
case kRemoveReceiver:
removeIcon((UINT)wParam);
break;
case kUpdateReceiver:
updateIcon((UINT)wParam);
break;
default:
if (msg == m_taskBarRestart) {
// task bar was recreated so re-add our icons
addAllIcons();
}
break;
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
LRESULT CALLBACK ArchTaskBarWindows::staticWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
// if msg is WM_NCCREATE, extract the ArchTaskBarWindows* and put
// it in the extra window data then forward the call.
ArchTaskBarWindows *self = NULL;
if (msg == WM_NCCREATE) {
CREATESTRUCT *createInfo;
createInfo = reinterpret_cast<CREATESTRUCT *>(lParam);
self = static_cast<ArchTaskBarWindows *>(createInfo->lpCreateParams);
SetWindowLongPtr(hwnd, 0, reinterpret_cast<LONG_PTR>(createInfo->lpCreateParams));
} else {
// get the extra window data and forward the call
LONG_PTR data = GetWindowLongPtr(hwnd, 0);
if (data != 0) {
self = static_cast<ArchTaskBarWindows *>(reinterpret_cast<void *>(data));
}
}
// forward the message
if (self != NULL) {
return self->wndProc(hwnd, msg, wParam, lParam);
} else {
return DefWindowProc(hwnd, msg, wParam, lParam);
}
}
void ArchTaskBarWindows::threadMainLoop()
{
// register the task bar restart message
m_taskBarRestart = RegisterWindowMessage(TEXT("TaskbarCreated"));
// register a window class
LPCTSTR className = TEXT("DeskflowTaskBar");
WNDCLASSEX classInfo;
classInfo.cbSize = sizeof(classInfo);
classInfo.style = CS_NOCLOSE;
classInfo.lpfnWndProc = &ArchTaskBarWindows::staticWndProc;
classInfo.cbClsExtra = 0;
classInfo.cbWndExtra = sizeof(ArchTaskBarWindows *);
classInfo.hInstance = instanceWin32();
classInfo.hIcon = NULL;
classInfo.hCursor = NULL;
classInfo.hbrBackground = NULL;
classInfo.lpszMenuName = NULL;
classInfo.lpszClassName = className;
classInfo.hIconSm = NULL;
ATOM windowClass = RegisterClassEx(&classInfo);
// create window
m_hwnd = CreateWindowEx(
WS_EX_TOOLWINDOW, className, TEXT("Deskflow Task Bar"), WS_POPUP, 0, 0, 1, 1, NULL, NULL, instanceWin32(),
static_cast<void *>(this)
);
// signal ready
ARCH->lockMutex(m_mutex);
m_ready = true;
ARCH->broadcastCondVar(m_condVar);
ARCH->unlockMutex(m_mutex);
// handle failure
if (m_hwnd == NULL) {
UnregisterClass(className, instanceWin32());
return;
}
// main loop
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
if (!processDialogs(&msg)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
// clean up
removeAllIcons();
DestroyWindow(m_hwnd);
UnregisterClass(className, instanceWin32());
}
void *ArchTaskBarWindows::threadEntry(void *self)
{
static_cast<ArchTaskBarWindows *>(self)->threadMainLoop();
return NULL;
}
HINSTANCE ArchTaskBarWindows::instanceWin32()
{
return ArchMiscWindows::instanceWin32();
}
| 12,692
|
C++
|
.cpp
| 419
| 27.011933
| 112
| 0.710095
|
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,512
|
ArchFileWindows.cpp
|
deskflow_deskflow/src/lib/arch/win32/ArchFileWindows.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/win32/ArchFileWindows.h"
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <shlobj.h>
#include <string.h>
#include <tchar.h>
//
// ArchFileWindows
//
ArchFileWindows::ArchFileWindows()
{
// do nothing
}
ArchFileWindows::~ArchFileWindows()
{
// do nothing
}
const char *ArchFileWindows::getBasename(const char *pathname)
{
if (pathname == NULL) {
return NULL;
}
// check for last slash
const char *basename = strrchr(pathname, '/');
if (basename != NULL) {
++basename;
} else {
basename = pathname;
}
// check for last backslash
const char *basename2 = strrchr(pathname, '\\');
if (basename2 != NULL && basename2 > basename) {
basename = basename2 + 1;
}
return basename;
}
std::string ArchFileWindows::getUserDirectory()
{
// try %HOMEPATH%
TCHAR dir[MAX_PATH];
DWORD size = sizeof(dir) / sizeof(TCHAR);
DWORD result = GetEnvironmentVariable(_T("HOMEPATH"), dir, size);
if (result != 0 && result <= size) {
// sanity check -- if dir doesn't appear to start with a
// drive letter and isn't a UNC name then don't use it
// FIXME -- allow UNC names
if (dir[0] != '\0' && (dir[1] == ':' || ((dir[0] == '\\' || dir[0] == '/') && (dir[1] == '\\' || dir[1] == '/')))) {
return dir;
}
}
// get the location of the personal files. that's as close to
// a home directory as we're likely to find.
ITEMIDLIST *idl;
if (SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_PERSONAL, &idl))) {
TCHAR *path = NULL;
if (SHGetPathFromIDList(idl, dir)) {
DWORD attr = GetFileAttributes(dir);
if (attr != 0xffffffff && (attr & FILE_ATTRIBUTE_DIRECTORY) != 0)
path = dir;
}
IMalloc *shalloc;
if (SUCCEEDED(SHGetMalloc(&shalloc))) {
shalloc->Free(idl);
shalloc->Release();
}
if (path != NULL) {
return path;
}
}
// use root of C drive as a default
return "C:";
}
std::string ArchFileWindows::getSystemDirectory()
{
// get windows directory
char dir[MAX_PATH];
if (GetWindowsDirectory(dir, sizeof(dir)) != 0) {
return dir;
} else {
// can't get it. use C:\ as a default.
return "C:";
}
}
std::string ArchFileWindows::getInstalledDirectory()
{
char fileNameBuffer[MAX_PATH];
GetModuleFileName(NULL, fileNameBuffer, MAX_PATH);
std::string fileName(fileNameBuffer);
size_t lastSlash = fileName.find_last_of("\\");
fileName = fileName.substr(0, lastSlash);
return fileName;
}
std::string ArchFileWindows::getLogDirectory()
{
return getInstalledDirectory();
}
std::string ArchFileWindows::getPluginDirectory()
{
if (!m_pluginDirectory.empty()) {
return m_pluginDirectory;
}
std::string dir = getProfileDirectory();
dir.append("\\Plugins");
return dir;
}
std::string ArchFileWindows::getProfileDirectory()
{
String dir;
if (!m_profileDirectory.empty()) {
dir = m_profileDirectory;
} else {
TCHAR result[MAX_PATH];
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, result))) {
dir = result;
} else {
dir = getUserDirectory();
}
}
// HACK: append program name, this seems wrong.
dir.append("\\Deskflow");
return dir;
}
std::string ArchFileWindows::concatPath(const std::string &prefix, const std::string &suffix)
{
std::string path;
path.reserve(prefix.size() + 1 + suffix.size());
path += prefix;
if (path.size() == 0 || (path[path.size() - 1] != '\\' && path[path.size() - 1] != '/')) {
path += '\\';
}
path += suffix;
return path;
}
void ArchFileWindows::setProfileDirectory(const String &s)
{
m_profileDirectory = s;
}
void ArchFileWindows::setPluginDirectory(const String &s)
{
m_pluginDirectory = s;
}
| 4,456
|
C++
|
.cpp
| 158
| 25.139241
| 120
| 0.676732
|
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,513
|
ArchStringWindows.cpp
|
deskflow_deskflow/src/lib/arch/win32/ArchStringWindows.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/win32/ArchStringWindows.h"
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <stdio.h>
//
// ArchStringWindows
//
#include "arch/multibyte.h"
#define HAVE_VSNPRINTF 1
#define ARCH_VSNPRINTF _vsnprintf
#include "arch/vsnprintf.h"
ArchStringWindows::ArchStringWindows()
{
}
ArchStringWindows::~ArchStringWindows()
{
}
IArchString::EWideCharEncoding ArchStringWindows::getWideCharEncoding()
{
return kUTF16;
}
| 1,169
|
C++
|
.cpp
| 38
| 29.105263
| 72
| 0.780249
|
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,514
|
ArchTimeWindows.cpp
|
deskflow_deskflow/src/lib/arch/win32/ArchTimeWindows.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/win32/ArchTimeWindows.h"
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#define MMNODRV // Disable: Installable driver support
#define MMNOSOUND // Disable: Sound support
#define MMNOWAVE // Disable: Waveform support
#define MMNOMIDI // Disable: MIDI support
#define MMNOAUX // Disable: Auxiliary audio support
#define MMNOMIXER // Disable: Mixer support
#define MMNOJOY // Disable: Joystick support
#define MMNOMCI // Disable: MCI support
#define MMNOMMIO // Disable: Multimedia file I/O support
#define MMNOMMSYSTEM // Disable: General MMSYSTEM functions
#include <MMSystem.h>
typedef WINMMAPI DWORD(WINAPI *PTimeGetTime)(void);
static double s_freq = 0.0;
static HINSTANCE s_mmInstance = NULL;
static PTimeGetTime s_tgt = NULL;
//
// ArchTimeWindows
//
ArchTimeWindows::ArchTimeWindows()
{
assert(s_freq == 0.0 || s_mmInstance == NULL);
LARGE_INTEGER freq;
if (QueryPerformanceFrequency(&freq) && freq.QuadPart != 0) {
s_freq = 1.0 / static_cast<double>(freq.QuadPart);
} else {
// load winmm.dll and get timeGetTime
s_mmInstance = LoadLibrary("winmm");
if (s_mmInstance != NULL) {
s_tgt = (PTimeGetTime)GetProcAddress(s_mmInstance, "timeGetTime");
}
}
}
ArchTimeWindows::~ArchTimeWindows()
{
s_freq = 0.0;
if (s_mmInstance == NULL) {
FreeLibrary(static_cast<HMODULE>(s_mmInstance));
s_tgt = NULL;
s_mmInstance = NULL;
}
}
double ArchTimeWindows::time()
{
// get time. we try three ways, in order of descending precision
if (s_freq != 0.0) {
LARGE_INTEGER c;
QueryPerformanceCounter(&c);
return s_freq * static_cast<double>(c.QuadPart);
} else if (s_tgt != NULL) {
return 0.001 * static_cast<double>(s_tgt());
} else {
return 0.001 * static_cast<double>(GetTickCount());
}
}
| 2,558
|
C++
|
.cpp
| 74
| 32.081081
| 72
| 0.718674
|
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,515
|
XArchWindows.cpp
|
deskflow_deskflow/src/lib/arch/win32/XArchWindows.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/win32/XArchWindows.h"
#include "arch/win32/ArchNetworkWinsock.h"
#include "base/String.h"
//
// XArchEvalWindows
//
std::string XArchEvalWindows::eval() const throw()
{
char *cmsg;
if (FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, 0, m_error,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&cmsg, 0, NULL
) == 0) {
cmsg = NULL;
return deskflow::string::sprintf("Unknown error, code %d", m_error);
}
std::string smsg(cmsg);
LocalFree(cmsg);
return smsg;
}
//
// XArchEvalWinsock
//
std::string XArchEvalWinsock::eval() const throw()
{
// built-in windows function for looking up error message strings
// may not look up network error messages correctly. we'll have
// to do it ourself.
static const struct
{
int m_code;
const char *m_msg;
} s_netErrorCodes[] = {
/* 10004 */ {WSAEINTR, "The (blocking) call was canceled via WSACancelBlockingCall"},
/* 10009 */ {WSAEBADF, "Bad file handle"},
/* 10013 */
{WSAEACCES, "The requested address is a broadcast address, but the "
"appropriate flag was not set"},
/* 10014 */ {WSAEFAULT, "WSAEFAULT"},
/* 10022 */ {WSAEINVAL, "WSAEINVAL"},
/* 10024 */ {WSAEMFILE, "No more file descriptors available"},
/* 10035 */
{WSAEWOULDBLOCK, "Socket is marked as non-blocking and no connections "
"are present or the receive operation would block"},
/* 10036 */
{WSAEINPROGRESS, "A blocking Windows Sockets operation is in progress"},
/* 10037 */
{WSAEALREADY, "The asynchronous routine being canceled has already completed"},
/* 10038 */ {WSAENOTSOCK, "At least on descriptor is not a socket"},
/* 10039 */ {WSAEDESTADDRREQ, "A destination address is required"},
/* 10040 */
{WSAEMSGSIZE, "The datagram was too large to fit into the specified "
"buffer and was truncated"},
/* 10041 */
{WSAEPROTOTYPE, "The specified protocol is the wrong type for this socket"},
/* 10042 */ {WSAENOPROTOOPT, "The option is unknown or unsupported"},
/* 10043 */
{WSAEPROTONOSUPPORT, "The specified protocol is not supported"},
/* 10044 */
{WSAESOCKTNOSUPPORT, "The specified socket type is not supported by this address family"},
/* 10045 */
{WSAEOPNOTSUPP, "The referenced socket is not a type that supports that operation"},
/* 10046 */ {WSAEPFNOSUPPORT, "BSD: Protocol family not supported"},
/* 10047 */
{WSAEAFNOSUPPORT, "The specified address family is not supported"},
/* 10048 */ {WSAEADDRINUSE, "The specified address is already in use"},
/* 10049 */
{WSAEADDRNOTAVAIL, "The specified address is not available from the local machine"},
/* 10050 */
{WSAENETDOWN, "The Windows Sockets implementation has detected that the "
"network subsystem has failed"},
/* 10051 */
{WSAENETUNREACH, "The network can't be reached from this host at this time"},
/* 10052 */
{WSAENETRESET, "The connection must be reset because the Windows Sockets "
"implementation dropped it"},
/* 10053 */
{WSAECONNABORTED, "The virtual circuit was aborted due to timeout or other failure"},
/* 10054 */
{WSAECONNRESET, "The virtual circuit was reset by the remote side"},
/* 10055 */
{WSAENOBUFS, "No buffer space is available or a buffer deadlock has "
"occured. The socket cannot be created"},
/* 10056 */ {WSAEISCONN, "The socket is already connected"},
/* 10057 */ {WSAENOTCONN, "The socket is not connected"},
/* 10058 */ {WSAESHUTDOWN, "The socket has been shutdown"},
/* 10059 */ {WSAETOOMANYREFS, "BSD: Too many references"},
/* 10060 */
{WSAETIMEDOUT, "Attempt to connect timed out without establishing a connection"},
/* 10061 */ {WSAECONNREFUSED, "Connection was refused"},
/* 10062 */ {WSAELOOP, "Undocumented WinSock error code used in BSD"},
/* 10063 */
{WSAENAMETOOLONG, "Undocumented WinSock error code used in BSD"},
/* 10064 */ {WSAEHOSTDOWN, "Undocumented WinSock error code used in BSD"},
/* 10065 */ {WSAEHOSTUNREACH, "No route to host"},
/* 10066 */ {WSAENOTEMPTY, "Undocumented WinSock error code"},
/* 10067 */ {WSAEPROCLIM, "Undocumented WinSock error code"},
/* 10068 */ {WSAEUSERS, "Undocumented WinSock error code"},
/* 10069 */ {WSAEDQUOT, "Undocumented WinSock error code"},
/* 10070 */ {WSAESTALE, "Undocumented WinSock error code"},
/* 10071 */ {WSAEREMOTE, "Undocumented WinSock error code"},
/* 10091 */
{WSASYSNOTREADY, "Underlying network subsytem is not ready for network communication"},
/* 10092 */
{WSAVERNOTSUPPORTED, "The version of WinSock API support requested is "
"not provided in this implementation"},
/* 10093 */
{WSANOTINITIALISED, "WinSock subsystem not properly initialized"},
/* 10101 */
{WSAEDISCON, "Virtual circuit has gracefully terminated connection"},
/* 11001 */ {WSAHOST_NOT_FOUND, "The specified host is unknown"},
/* 11002 */
{WSATRY_AGAIN, "A temporary error occurred on an authoritative name server"},
/* 11003 */
{WSANO_RECOVERY, "A non-recoverable name server error occurred"},
/* 11004 */
{WSANO_DATA, "The requested name is valid but does not have an IP address"},
/* end */ {0, NULL}
};
for (unsigned int i = 0; s_netErrorCodes[i].m_code != 0; ++i) {
if (s_netErrorCodes[i].m_code == m_error) {
return s_netErrorCodes[i].m_msg;
}
}
return "Unknown error";
}
| 6,545
|
C++
|
.cpp
| 143
| 39.692308
| 114
| 0.658224
|
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,516
|
ArchSleepWindows.cpp
|
deskflow_deskflow/src/lib/arch/win32/ArchSleepWindows.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/win32/ArchSleepWindows.h"
#include "arch/Arch.h"
#include "arch/win32/ArchMultithreadWindows.h"
//
// ArchSleepWindows
//
ArchSleepWindows::ArchSleepWindows()
{
// do nothing
}
ArchSleepWindows::~ArchSleepWindows()
{
// do nothing
}
void ArchSleepWindows::sleep(double timeout)
{
ARCH->testCancelThread();
if (timeout < 0.0) {
return;
}
// get the cancel event from the current thread. this only
// works if we're using the windows multithread object but
// this is windows so that's pretty certain; we'll get a
// link error if we're not, though.
ArchMultithreadWindows *mt = ArchMultithreadWindows::getInstance();
if (mt != NULL) {
HANDLE cancelEvent = mt->getCancelEventForCurrentThread();
WaitForSingleObject(cancelEvent, (DWORD)(1000.0 * timeout));
if (timeout == 0.0) {
Sleep(0);
}
} else {
Sleep((DWORD)(1000.0 * timeout));
}
ARCH->testCancelThread();
}
| 1,672
|
C++
|
.cpp
| 53
| 29.037736
| 72
| 0.733416
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| true
| false
| false
| true
| false
| false
|
13,517
|
ArchMultithreadWindows.cpp
|
deskflow_deskflow/src/lib/arch/win32/ArchMultithreadWindows.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/>.
*/
#if defined(_MSC_VER) && !defined(_MT)
#error multithreading compile option is required
#endif
#include "arch/win32/ArchMultithreadWindows.h"
#include "arch/Arch.h"
#include "arch/XArch.h"
#include <process.h>
//
// note -- implementation of condition variable taken from:
// http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
// titled "Strategies for Implementing POSIX Condition Variables
// on Win32." it also provides an implementation that doesn't
// suffer from the incorrectness problem described in our
// corresponding header but it is slower, still unfair, and
// can cause busy waiting.
//
//
// ArchThreadImpl
//
class ArchThreadImpl
{
public:
ArchThreadImpl();
~ArchThreadImpl();
public:
int m_refCount;
HANDLE m_thread;
DWORD m_id;
IArchMultithread::ThreadFunc m_func;
void *m_userData;
HANDLE m_cancel;
bool m_cancelling;
HANDLE m_exit;
void *m_result;
void *m_networkData;
};
ArchThreadImpl::ArchThreadImpl()
: m_refCount(1),
m_thread(NULL),
m_id(0),
m_func(NULL),
m_userData(NULL),
m_cancelling(false),
m_result(NULL),
m_networkData(NULL)
{
m_exit = CreateEvent(NULL, TRUE, FALSE, NULL);
m_cancel = CreateEvent(NULL, TRUE, FALSE, NULL);
}
ArchThreadImpl::~ArchThreadImpl()
{
CloseHandle(m_exit);
CloseHandle(m_cancel);
}
//
// ArchMultithreadWindows
//
ArchMultithreadWindows *ArchMultithreadWindows::s_instance = NULL;
ArchMultithreadWindows::ArchMultithreadWindows()
{
assert(s_instance == NULL);
s_instance = this;
// no signal handlers
for (size_t i = 0; i < kNUM_SIGNALS; ++i) {
m_signalFunc[i] = NULL;
m_signalUserData[i] = NULL;
}
// create mutex for thread list
m_threadMutex = newMutex();
// create thread for calling (main) thread and add it to our
// list. no need to lock the mutex since we're the only thread.
m_mainThread = new ArchThreadImpl;
m_mainThread->m_thread = NULL;
m_mainThread->m_id = GetCurrentThreadId();
insert(m_mainThread);
}
ArchMultithreadWindows::~ArchMultithreadWindows()
{
s_instance = NULL;
// clean up thread list
for (ThreadList::iterator index = m_threadList.begin(); index != m_threadList.end(); ++index) {
delete *index;
}
// done with mutex
delete m_threadMutex;
}
void ArchMultithreadWindows::setNetworkDataForCurrentThread(void *data)
{
lockMutex(m_threadMutex);
ArchThreadImpl *thread = findNoRef(GetCurrentThreadId());
thread->m_networkData = data;
unlockMutex(m_threadMutex);
}
void *ArchMultithreadWindows::getNetworkDataForThread(ArchThread thread)
{
lockMutex(m_threadMutex);
void *data = thread->m_networkData;
unlockMutex(m_threadMutex);
return data;
}
HANDLE
ArchMultithreadWindows::getCancelEventForCurrentThread()
{
lockMutex(m_threadMutex);
ArchThreadImpl *thread = findNoRef(GetCurrentThreadId());
unlockMutex(m_threadMutex);
return thread->m_cancel;
}
ArchMultithreadWindows *ArchMultithreadWindows::getInstance()
{
return s_instance;
}
ArchCond ArchMultithreadWindows::newCondVar()
{
ArchCondImpl *cond = new ArchCondImpl;
cond->m_events[ArchCondImpl::kSignal] = CreateEvent(NULL, FALSE, FALSE, NULL);
cond->m_events[ArchCondImpl::kBroadcast] = CreateEvent(NULL, TRUE, FALSE, NULL);
cond->m_waitCountMutex = newMutex();
cond->m_waitCount = 0;
return cond;
}
void ArchMultithreadWindows::closeCondVar(ArchCond cond)
{
CloseHandle(cond->m_events[ArchCondImpl::kSignal]);
CloseHandle(cond->m_events[ArchCondImpl::kBroadcast]);
closeMutex(cond->m_waitCountMutex);
delete cond;
}
void ArchMultithreadWindows::signalCondVar(ArchCond cond)
{
// is anybody waiting?
lockMutex(cond->m_waitCountMutex);
const bool hasWaiter = (cond->m_waitCount > 0);
unlockMutex(cond->m_waitCountMutex);
// wake one thread if anybody is waiting
if (hasWaiter) {
SetEvent(cond->m_events[ArchCondImpl::kSignal]);
}
}
void ArchMultithreadWindows::broadcastCondVar(ArchCond cond)
{
// is anybody waiting?
lockMutex(cond->m_waitCountMutex);
const bool hasWaiter = (cond->m_waitCount > 0);
unlockMutex(cond->m_waitCountMutex);
// wake all threads if anybody is waiting
if (hasWaiter) {
SetEvent(cond->m_events[ArchCondImpl::kBroadcast]);
}
}
bool ArchMultithreadWindows::waitCondVar(ArchCond cond, ArchMutex mutex, double timeout)
{
// prepare to wait
const DWORD winTimeout = (timeout < 0.0) ? INFINITE : static_cast<DWORD>(1000.0 * timeout);
// make a list of the condition variable events and the cancel event
// for the current thread.
HANDLE handles[4];
handles[0] = cond->m_events[ArchCondImpl::kSignal];
handles[1] = cond->m_events[ArchCondImpl::kBroadcast];
handles[2] = getCancelEventForCurrentThread();
// update waiter count
lockMutex(cond->m_waitCountMutex);
++cond->m_waitCount;
unlockMutex(cond->m_waitCountMutex);
// release mutex. this should be atomic with the wait so that it's
// impossible for another thread to signal us between the unlock and
// the wait, which would lead to a lost signal on broadcasts.
// however, we're using a manual reset event for broadcasts which
// stays set until we reset it, so we don't lose the broadcast.
unlockMutex(mutex);
// wait for a signal or broadcast
DWORD result = WaitForMultipleObjects(3, handles, FALSE, winTimeout);
// cancel takes priority
if (result != WAIT_OBJECT_0 + 2 && WaitForSingleObject(handles[2], 0) == WAIT_OBJECT_0) {
result = WAIT_OBJECT_0 + 2;
}
// update the waiter count and check if we're the last waiter
lockMutex(cond->m_waitCountMutex);
--cond->m_waitCount;
const bool last = (result == WAIT_OBJECT_0 + 1 && cond->m_waitCount == 0);
unlockMutex(cond->m_waitCountMutex);
// reset the broadcast event if we're the last waiter
if (last) {
ResetEvent(cond->m_events[ArchCondImpl::kBroadcast]);
}
// reacquire the mutex
lockMutex(mutex);
// cancel thread if necessary
if (result == WAIT_OBJECT_0 + 2) {
ARCH->testCancelThread();
}
// return success or failure
return (result == WAIT_OBJECT_0 + 0 || result == WAIT_OBJECT_0 + 1);
}
ArchMutex ArchMultithreadWindows::newMutex()
{
ArchMutexImpl *mutex = new ArchMutexImpl;
InitializeCriticalSection(&mutex->m_mutex);
return mutex;
}
void ArchMultithreadWindows::closeMutex(ArchMutex mutex)
{
DeleteCriticalSection(&mutex->m_mutex);
delete mutex;
}
void ArchMultithreadWindows::lockMutex(ArchMutex mutex)
{
EnterCriticalSection(&mutex->m_mutex);
}
void ArchMultithreadWindows::unlockMutex(ArchMutex mutex)
{
LeaveCriticalSection(&mutex->m_mutex);
}
ArchThread ArchMultithreadWindows::newThread(ThreadFunc func, void *data)
{
lockMutex(m_threadMutex);
// create thread impl for new thread
ArchThreadImpl *thread = new ArchThreadImpl;
thread->m_func = func;
thread->m_userData = data;
// create thread
unsigned int id = 0;
thread->m_thread = reinterpret_cast<HANDLE>(_beginthreadex(NULL, 0, threadFunc, (void *)thread, 0, &id));
thread->m_id = static_cast<DWORD>(id);
// check if thread was started
if (thread->m_thread == 0) {
// failed to start thread so clean up
delete thread;
thread = NULL;
} else {
// add thread to list
insert(thread);
// increment ref count to account for the thread itself
refThread(thread);
}
// note that the child thread will wait until we release this mutex
unlockMutex(m_threadMutex);
return thread;
}
ArchThread ArchMultithreadWindows::newCurrentThread()
{
lockMutex(m_threadMutex);
ArchThreadImpl *thread = find(GetCurrentThreadId());
unlockMutex(m_threadMutex);
assert(thread != NULL);
return thread;
}
void ArchMultithreadWindows::closeThread(ArchThread thread)
{
assert(thread != NULL);
// decrement ref count and clean up thread if no more references
if (--thread->m_refCount == 0) {
// close the handle (main thread has a NULL handle)
if (thread->m_thread != NULL) {
CloseHandle(thread->m_thread);
}
// remove thread from list
lockMutex(m_threadMutex);
assert(findNoRefOrCreate(thread->m_id) == thread);
erase(thread);
unlockMutex(m_threadMutex);
// done with thread
delete thread;
}
}
ArchThread ArchMultithreadWindows::copyThread(ArchThread thread)
{
refThread(thread);
return thread;
}
void ArchMultithreadWindows::cancelThread(ArchThread thread)
{
assert(thread != NULL);
// set cancel flag
SetEvent(thread->m_cancel);
}
void ArchMultithreadWindows::setPriorityOfThread(ArchThread thread, int n)
{
struct PriorityInfo
{
public:
DWORD m_class;
int m_level;
};
static const PriorityInfo s_pClass[] = {
{IDLE_PRIORITY_CLASS, THREAD_PRIORITY_IDLE},
{IDLE_PRIORITY_CLASS, THREAD_PRIORITY_LOWEST},
{IDLE_PRIORITY_CLASS, THREAD_PRIORITY_BELOW_NORMAL},
{IDLE_PRIORITY_CLASS, THREAD_PRIORITY_NORMAL},
{IDLE_PRIORITY_CLASS, THREAD_PRIORITY_ABOVE_NORMAL},
{IDLE_PRIORITY_CLASS, THREAD_PRIORITY_HIGHEST},
{NORMAL_PRIORITY_CLASS, THREAD_PRIORITY_LOWEST},
{NORMAL_PRIORITY_CLASS, THREAD_PRIORITY_BELOW_NORMAL},
{NORMAL_PRIORITY_CLASS, THREAD_PRIORITY_NORMAL},
{NORMAL_PRIORITY_CLASS, THREAD_PRIORITY_ABOVE_NORMAL},
{NORMAL_PRIORITY_CLASS, THREAD_PRIORITY_HIGHEST},
{HIGH_PRIORITY_CLASS, THREAD_PRIORITY_LOWEST},
{HIGH_PRIORITY_CLASS, THREAD_PRIORITY_BELOW_NORMAL},
{HIGH_PRIORITY_CLASS, THREAD_PRIORITY_NORMAL},
{HIGH_PRIORITY_CLASS, THREAD_PRIORITY_ABOVE_NORMAL},
{HIGH_PRIORITY_CLASS, THREAD_PRIORITY_HIGHEST},
{REALTIME_PRIORITY_CLASS, THREAD_PRIORITY_IDLE},
{REALTIME_PRIORITY_CLASS, THREAD_PRIORITY_LOWEST},
{REALTIME_PRIORITY_CLASS, THREAD_PRIORITY_BELOW_NORMAL},
{REALTIME_PRIORITY_CLASS, THREAD_PRIORITY_NORMAL},
{REALTIME_PRIORITY_CLASS, THREAD_PRIORITY_ABOVE_NORMAL},
{REALTIME_PRIORITY_CLASS, THREAD_PRIORITY_HIGHEST},
{REALTIME_PRIORITY_CLASS, THREAD_PRIORITY_TIME_CRITICAL}
};
#if defined(_DEBUG)
// don't use really high priorities when debugging
static const size_t s_pMax = 13;
#else
static const size_t s_pMax = sizeof(s_pClass) / sizeof(s_pClass[0]) - 1;
#endif
static const size_t s_pBase = 8; // index of normal priority
assert(thread != NULL);
size_t index;
if (n > 0 && s_pBase < (size_t)n) {
// lowest priority
index = 0;
} else {
index = (size_t)((int)s_pBase - n);
if (index > s_pMax) {
// highest priority
index = s_pMax;
}
}
SetPriorityClass(GetCurrentProcess(), s_pClass[index].m_class);
SetThreadPriority(thread->m_thread, s_pClass[index].m_level);
}
void ArchMultithreadWindows::testCancelThread()
{
// find current thread
lockMutex(m_threadMutex);
ArchThreadImpl *thread = findNoRef(GetCurrentThreadId());
unlockMutex(m_threadMutex);
// test cancel on thread
testCancelThreadImpl(thread);
}
bool ArchMultithreadWindows::wait(ArchThread target, double timeout)
{
assert(target != NULL);
lockMutex(m_threadMutex);
// find current thread
ArchThreadImpl *self = findNoRef(GetCurrentThreadId());
// ignore wait if trying to wait on ourself
if (target == self) {
unlockMutex(m_threadMutex);
return false;
}
// ref the target so it can't go away while we're watching it
refThread(target);
unlockMutex(m_threadMutex);
// convert timeout
DWORD t;
if (timeout < 0.0) {
t = INFINITE;
} else {
t = (DWORD)(1000.0 * timeout);
}
// wait for this thread to be cancelled or woken up or for the
// target thread to terminate.
HANDLE handles[2];
handles[0] = target->m_exit;
handles[1] = self->m_cancel;
DWORD result = WaitForMultipleObjects(2, handles, FALSE, t);
// cancel takes priority
if (result != WAIT_OBJECT_0 + 1 && WaitForSingleObject(handles[1], 0) == WAIT_OBJECT_0) {
result = WAIT_OBJECT_0 + 1;
}
// release target
closeThread(target);
// handle result
switch (result) {
case WAIT_OBJECT_0 + 0:
// target thread terminated
return true;
case WAIT_OBJECT_0 + 1:
// this thread was cancelled. does not return.
testCancelThreadImpl(self);
default:
// timeout or error
return false;
}
}
bool ArchMultithreadWindows::isSameThread(ArchThread thread1, ArchThread thread2)
{
return (thread1 == thread2);
}
bool ArchMultithreadWindows::isExitedThread(ArchThread thread)
{
// poll exit event
return (WaitForSingleObject(thread->m_exit, 0) == WAIT_OBJECT_0);
}
void *ArchMultithreadWindows::getResultOfThread(ArchThread thread)
{
lockMutex(m_threadMutex);
void *result = thread->m_result;
unlockMutex(m_threadMutex);
return result;
}
IArchMultithread::ThreadID ArchMultithreadWindows::getIDOfThread(ArchThread thread)
{
return static_cast<ThreadID>(thread->m_id);
}
void ArchMultithreadWindows::setSignalHandler(ESignal signal, SignalFunc func, void *userData)
{
lockMutex(m_threadMutex);
m_signalFunc[signal] = func;
m_signalUserData[signal] = userData;
unlockMutex(m_threadMutex);
}
void ArchMultithreadWindows::raiseSignal(ESignal signal)
{
lockMutex(m_threadMutex);
if (m_signalFunc[signal] != NULL) {
m_signalFunc[signal](signal, m_signalUserData[signal]);
ARCH->unblockPollSocket(m_mainThread);
} else if (signal == kINTERRUPT || signal == kTERMINATE) {
ARCH->cancelThread(m_mainThread);
}
unlockMutex(m_threadMutex);
}
ArchThreadImpl *ArchMultithreadWindows::find(DWORD id)
{
ArchThreadImpl *impl = findNoRef(id);
if (impl != NULL) {
refThread(impl);
}
return impl;
}
ArchThreadImpl *ArchMultithreadWindows::findNoRef(DWORD id)
{
ArchThreadImpl *impl = findNoRefOrCreate(id);
if (impl == NULL) {
// create thread for calling thread which isn't in our list and
// add it to the list. this won't normally happen but it can if
// the system calls us under a new thread, like it does when we
// run as a service.
impl = new ArchThreadImpl;
impl->m_thread = NULL;
impl->m_id = GetCurrentThreadId();
insert(impl);
}
return impl;
}
ArchThreadImpl *ArchMultithreadWindows::findNoRefOrCreate(DWORD id)
{
// linear search
for (ThreadList::const_iterator index = m_threadList.begin(); index != m_threadList.end(); ++index) {
if ((*index)->m_id == id) {
return *index;
}
}
return NULL;
}
void ArchMultithreadWindows::insert(ArchThreadImpl *thread)
{
assert(thread != NULL);
// thread shouldn't already be on the list
assert(findNoRefOrCreate(thread->m_id) == NULL);
// append to list
m_threadList.push_back(thread);
}
void ArchMultithreadWindows::erase(ArchThreadImpl *thread)
{
for (ThreadList::iterator index = m_threadList.begin(); index != m_threadList.end(); ++index) {
if (*index == thread) {
m_threadList.erase(index);
break;
}
}
}
void ArchMultithreadWindows::refThread(ArchThreadImpl *thread)
{
assert(thread != NULL);
assert(findNoRefOrCreate(thread->m_id) != NULL);
++thread->m_refCount;
}
void ArchMultithreadWindows::testCancelThreadImpl(ArchThreadImpl *thread)
{
assert(thread != NULL);
// poll cancel event. return if not set.
const DWORD result = WaitForSingleObject(thread->m_cancel, 0);
if (result != WAIT_OBJECT_0) {
return;
}
// update cancel state
lockMutex(m_threadMutex);
bool cancel = !thread->m_cancelling;
thread->m_cancelling = true;
ResetEvent(thread->m_cancel);
unlockMutex(m_threadMutex);
// unwind thread's stack if cancelling
if (cancel) {
throw XThreadCancel();
}
}
unsigned int __stdcall ArchMultithreadWindows::threadFunc(void *vrep)
{
// get the thread
ArchThreadImpl *thread = static_cast<ArchThreadImpl *>(vrep);
// run thread
s_instance->doThreadFunc(thread);
// terminate the thread
return 0;
}
void ArchMultithreadWindows::doThreadFunc(ArchThread thread)
{
// wait for parent to initialize this object
lockMutex(m_threadMutex);
unlockMutex(m_threadMutex);
void *result = NULL;
try {
// go
result = (*thread->m_func)(thread->m_userData);
}
catch (XThreadCancel &) {
// client called cancel()
} catch (...) {
// note -- don't catch (...) to avoid masking bugs
SetEvent(thread->m_exit);
closeThread(thread);
throw;
}
// thread has exited
lockMutex(m_threadMutex);
thread->m_result = result;
unlockMutex(m_threadMutex);
SetEvent(thread->m_exit);
// done with thread
closeThread(thread);
}
| 17,117
|
C++
|
.cpp
| 551
| 27.952813
| 107
| 0.728073
|
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,518
|
ArchConsoleUnix.cpp
|
deskflow_deskflow/src/lib/arch/unix/ArchConsoleUnix.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/unix/ArchConsoleUnix.h"
ArchConsoleUnix::ArchConsoleUnix()
{
}
ArchConsoleUnix::~ArchConsoleUnix()
{
}
| 851
|
C++
|
.cpp
| 24
| 33.666667
| 72
| 0.768204
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| true
| false
| false
| true
| false
| false
|
13,519
|
ArchLogUnix.cpp
|
deskflow_deskflow/src/lib/arch/unix/ArchLogUnix.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/unix/ArchLogUnix.h"
#include <syslog.h>
//
// ArchLogUnix
//
ArchLogUnix::ArchLogUnix()
{
// do nothing
}
ArchLogUnix::~ArchLogUnix()
{
// do nothing
}
void ArchLogUnix::openLog(const char *name)
{
openlog(name, 0, LOG_DAEMON);
}
void ArchLogUnix::closeLog()
{
closelog();
}
void ArchLogUnix::showLog(bool)
{
// do nothing
}
void ArchLogUnix::writeLog(ELevel level, const char *msg)
{
// convert level
int priority;
switch (level) {
case kERROR:
priority = LOG_ERR;
break;
case kWARNING:
priority = LOG_WARNING;
break;
case kNOTE:
priority = LOG_NOTICE;
break;
case kINFO:
priority = LOG_INFO;
break;
default:
priority = LOG_DEBUG;
break;
}
// log it
syslog(priority, "%s", msg);
}
| 1,513
|
C++
|
.cpp
| 66
| 20.378788
| 72
| 0.720865
|
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,520
|
ArchNetworkBSD.cpp
|
deskflow_deskflow/src/lib/arch/unix/ArchNetworkBSD.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/unix/ArchNetworkBSD.h"
#include "arch/Arch.h"
#include "arch/unix/ArchMultithreadPosix.h"
#include "arch/unix/XArchUnix.h"
#include <arpa/inet.h>
#include <cstring>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#if !defined(TCP_NODELAY)
#include <netinet/tcp.h>
#endif
#if !HAVE_INET_ATON
#include <stdio.h>
#endif
static const int s_family[] = {
PF_UNSPEC,
PF_INET,
PF_INET6,
};
static const int s_type[] = {SOCK_DGRAM, SOCK_STREAM};
#if !HAVE_INET_ATON
// parse dotted quad addresses. we don't bother with the weird BSD'ism
// of handling octal and hex and partial forms.
static in_addr_t inet_aton(const char *cp, struct in_addr *inp)
{
unsigned int a, b, c, d;
if (sscanf(cp, "%u.%u.%u.%u", &a, &b, &c, &d) != 4) {
return 0;
}
if (a >= 256 || b >= 256 || c >= 256 || d >= 256) {
return 0;
}
unsigned char *incp = (unsigned char *)inp;
incp[0] = (unsigned char)(a & 0xffu);
incp[1] = (unsigned char)(b & 0xffu);
incp[2] = (unsigned char)(c & 0xffu);
incp[3] = (unsigned char)(d & 0xffu);
return inp->s_addr;
}
#endif
//
// ArchNetworkBSD::Deps
//
void ArchNetworkBSD::Deps::sleep(double seconds)
{
//
ARCH->sleep(seconds);
}
int ArchNetworkBSD::Deps::poll(struct pollfd *fds, nfds_t nfds, int timeout)
{
return ::poll(fds, nfds, timeout);
}
std::shared_ptr<struct pollfd[]> ArchNetworkBSD::Deps::makePollFD(nfds_t n)
{
// C++20 supports std::make_shared<struct pollfd[]>(n) but this is not
// implemented on the compiler that comes with Ubuntu 22 and a few other
// distros, so use the manual new and delete until we drop those distros.
return std::shared_ptr<struct pollfd[]>(new struct pollfd[n], std::default_delete<struct pollfd[]>());
}
ssize_t ArchNetworkBSD::Deps::read(int fd, void *buf, size_t len)
{
return ::read(fd, buf, len);
}
void ArchNetworkBSD::Deps::testCancelThread()
{
ARCH->testCancelThread();
}
//
// ArchNetworkBSD
//
ArchNetworkBSD::~ArchNetworkBSD()
{
if (m_mutex)
ARCH->closeMutex(m_mutex);
}
void ArchNetworkBSD::init()
{
// create mutex to make some calls thread safe
m_mutex = ARCH->newMutex();
}
ArchSocket ArchNetworkBSD::newSocket(EAddressFamily family, ESocketType type)
{
// create socket
int fd = socket(s_family[family], s_type[type], 0);
if (fd == -1) {
throwError(errno);
}
try {
setBlockingOnSocket(fd, false);
} catch (...) {
close(fd);
throw;
}
// allocate socket object
auto *newSocket = new ArchSocketImpl;
newSocket->m_fd = fd;
newSocket->m_refCount = 1;
return newSocket;
}
ArchSocket ArchNetworkBSD::copySocket(ArchSocket s)
{
assert(s != NULL);
// ref the socket and return it
ARCH->lockMutex(m_mutex);
++s->m_refCount;
ARCH->unlockMutex(m_mutex);
return s;
}
void ArchNetworkBSD::closeSocket(ArchSocket s)
{
assert(s != NULL);
// unref the socket and note if it should be released
ARCH->lockMutex(m_mutex);
const bool doClose = (--s->m_refCount == 0);
ARCH->unlockMutex(m_mutex);
// close the socket if necessary
if (doClose) {
if (close(s->m_fd) == -1) {
// close failed. restore the last ref and throw.
int err = errno;
ARCH->lockMutex(m_mutex);
++s->m_refCount;
ARCH->unlockMutex(m_mutex);
throwError(err);
}
delete s;
}
}
void ArchNetworkBSD::closeSocketForRead(ArchSocket s)
{
assert(s != NULL);
if (shutdown(s->m_fd, 0) == -1) {
if (errno != ENOTCONN) {
throwError(errno);
}
}
}
void ArchNetworkBSD::closeSocketForWrite(ArchSocket s)
{
assert(s != NULL);
if (shutdown(s->m_fd, 1) == -1) {
if (errno != ENOTCONN) {
throwError(errno);
}
}
}
void ArchNetworkBSD::bindSocket(ArchSocket s, ArchNetAddress addr)
{
assert(s != NULL);
assert(addr != NULL);
if (bind(s->m_fd, TYPED_ADDR(struct sockaddr, addr), addr->m_len) == -1) {
throwError(errno);
}
}
void ArchNetworkBSD::listenOnSocket(ArchSocket s)
{
assert(s != NULL);
// hardcoding backlog
if (listen(s->m_fd, 3) == -1) {
throwError(errno);
}
}
ArchSocket ArchNetworkBSD::acceptSocket(ArchSocket s, ArchNetAddress *addr)
{
assert(s != NULL);
// if user passed NULL in addr then use scratch space
ArchNetAddress dummy;
if (addr == nullptr) {
addr = &dummy;
}
// create new socket and address
auto *newSocket = new ArchSocketImpl;
*addr = new ArchNetAddressImpl;
// accept on socket
auto len = ((*addr)->m_len);
int fd = accept(s->m_fd, TYPED_ADDR(struct sockaddr, (*addr)), &len);
(*addr)->m_len = len;
if (fd == -1) {
int err = errno;
delete newSocket;
delete *addr;
*addr = nullptr;
if (err == EAGAIN) {
return nullptr;
}
throwError(err);
}
try {
setBlockingOnSocket(fd, false);
} catch (...) {
close(fd);
delete newSocket;
delete *addr;
*addr = nullptr;
throw;
}
// initialize socket
newSocket->m_fd = fd;
newSocket->m_refCount = 1;
// discard address if not requested
if (addr == &dummy) {
ARCH->closeAddr(dummy);
}
return newSocket;
}
bool ArchNetworkBSD::connectSocket(ArchSocket s, ArchNetAddress addr)
{
assert(s != NULL);
assert(addr != NULL);
if (connect(s->m_fd, TYPED_ADDR(struct sockaddr, addr), addr->m_len) == -1) {
if (errno == EISCONN) {
return true;
}
if (errno == EINPROGRESS) {
return false;
}
throwError(errno);
}
return true;
}
int ArchNetworkBSD::pollSocket(PollEntry pe[], int num, double timeout)
{
assert((pe != nullptr && num > 0) || num == 0);
// return if nothing to do
if (num == 0) {
if (timeout > 0.0) {
m_pDeps->sleep(timeout);
}
return 0;
}
// allocate space for translated query
auto pfdPtr = m_pDeps->makePollFD(1 + num);
auto *pfd = pfdPtr.get();
// translate query
for (int i = 0; i < num; ++i) {
pfd[i].fd = (pe[i].m_socket == nullptr) ? -1 : pe[i].m_socket->m_fd;
pfd[i].events = 0;
if ((pe[i].m_events & kPOLLIN) != 0) {
pfd[i].events |= POLLIN;
}
if ((pe[i].m_events & kPOLLOUT) != 0) {
pfd[i].events |= POLLOUT;
}
}
int n = num;
// add the unblock pipe
const int *unblockPipe = getUnblockPipe();
if (unblockPipe != nullptr) {
pfd[n].fd = unblockPipe[0]; // test
pfd[n].events = POLLIN;
++n;
}
// prepare timeout
int t = (timeout < 0.0) ? -1 : static_cast<int>(1000.0 * timeout);
// do the poll
n = m_pDeps->poll(pfd, n, t);
// reset the unblock pipe
if (n > 0 && unblockPipe != nullptr && (pfd[num].revents & POLLIN) != 0) {
// the unblock event was signalled. flush the pipe.
char dummy[100];
do {
m_pDeps->read(unblockPipe[0], dummy, sizeof(dummy));
} while (errno != EAGAIN);
// don't count this unblock pipe in return value
--n;
}
// handle results
if (n == -1) {
if (errno == EINTR) {
// interrupted system call
m_pDeps->testCancelThread();
return 0;
}
throwError(errno);
return -1; // unreachable
}
// translate back
for (int i = 0; i < num; ++i) {
pe[i].m_revents = 0;
if ((pfd[i].revents & POLLIN) != 0) {
pe[i].m_revents |= kPOLLIN;
}
if ((pfd[i].revents & POLLOUT) != 0) {
pe[i].m_revents |= kPOLLOUT;
}
if ((pfd[i].revents & POLLERR) != 0) {
pe[i].m_revents |= kPOLLERR;
}
if ((pfd[i].revents & POLLNVAL) != 0) {
pe[i].m_revents |= kPOLLNVAL;
}
}
return n;
}
void ArchNetworkBSD::unblockPollSocket(ArchThread thread)
{
const int *unblockPipe = getUnblockPipeForThread(thread);
if (unblockPipe != nullptr) {
char dummy = 0;
int ignore;
ignore = write(unblockPipe[1], &dummy, 1);
}
}
size_t ArchNetworkBSD::readSocket(ArchSocket s, void *buf, size_t len)
{
assert(s != NULL);
ssize_t n = read(s->m_fd, buf, len);
if (n == -1) {
if (errno == EINTR || errno == EAGAIN) {
return 0;
}
throwError(errno);
}
return n;
}
size_t ArchNetworkBSD::writeSocket(ArchSocket s, const void *buf, size_t len)
{
assert(s != NULL);
ssize_t n = write(s->m_fd, buf, len);
if (n == -1) {
if (errno == EINTR || errno == EAGAIN) {
return 0;
}
throwError(errno);
}
return n;
}
void ArchNetworkBSD::throwErrorOnSocket(ArchSocket s)
{
assert(s != NULL);
// get the error from the socket layer
int err = 0;
auto size = static_cast<socklen_t>(sizeof(err));
if (getsockopt(s->m_fd, SOL_SOCKET, SO_ERROR, reinterpret_cast<optval_t *>(&err), &size) == -1) {
err = errno;
}
// throw if there's an error
if (err != 0) {
throwError(err);
}
}
void ArchNetworkBSD::setBlockingOnSocket(int fd, bool blocking)
{
assert(fd != -1);
int mode = fcntl(fd, F_GETFL, 0);
if (mode == -1) {
throwError(errno);
}
if (blocking) {
mode &= ~O_NONBLOCK;
} else {
mode |= O_NONBLOCK;
}
if (fcntl(fd, F_SETFL, mode) == -1) {
throwError(errno);
}
}
bool ArchNetworkBSD::setNoDelayOnSocket(ArchSocket s, bool noDelay)
{
assert(s != NULL);
// get old state
int oflag;
auto size = static_cast<socklen_t>(sizeof(oflag));
if (getsockopt(s->m_fd, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<optval_t *>(&oflag), &size) == -1) {
throwError(errno);
}
int flag = noDelay ? 1 : 0;
size = static_cast<socklen_t>(sizeof(flag));
if (setsockopt(s->m_fd, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<optval_t *>(&flag), size) == -1) {
throwError(errno);
}
return (oflag != 0);
}
bool ArchNetworkBSD::setReuseAddrOnSocket(ArchSocket s, bool reuse)
{
assert(s != NULL);
// get old state
int oflag;
auto size = static_cast<socklen_t>(sizeof(oflag));
if (getsockopt(s->m_fd, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<optval_t *>(&oflag), &size) == -1) {
throwError(errno);
}
int flag = reuse ? 1 : 0;
size = static_cast<socklen_t>(sizeof(flag));
if (setsockopt(s->m_fd, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<optval_t *>(&flag), size) == -1) {
throwError(errno);
}
return (oflag != 0);
}
std::string ArchNetworkBSD::getHostName()
{
char name[256];
if (gethostname(name, sizeof(name)) == -1) {
name[0] = '\0';
} else {
name[sizeof(name) - 1] = '\0';
}
return name;
}
ArchNetAddress ArchNetworkBSD::newAnyAddr(EAddressFamily family)
{
// allocate address
auto *addr = new ArchNetAddressImpl;
// fill it in
switch (family) {
case kINET: {
auto *ipAddr = TYPED_ADDR(struct sockaddr_in, addr);
ipAddr->sin_family = AF_INET;
ipAddr->sin_port = 0;
ipAddr->sin_addr.s_addr = INADDR_ANY;
addr->m_len = static_cast<socklen_t>(sizeof(struct sockaddr_in));
break;
}
case kINET6: {
struct sockaddr_in6 *ipAddr = TYPED_ADDR(struct sockaddr_in6, addr);
ipAddr->sin6_family = AF_INET6;
ipAddr->sin6_port = 0;
memcpy(&ipAddr->sin6_addr, &in6addr_any, sizeof(in6addr_any));
addr->m_len = (socklen_t)sizeof(struct sockaddr_in6);
break;
}
default:
delete addr;
assert(0 && "invalid family");
}
return addr;
}
ArchNetAddress ArchNetworkBSD::copyAddr(ArchNetAddress addr)
{
assert(addr != NULL);
// allocate and copy address
return new ArchNetAddressImpl(*addr);
}
std::vector<ArchNetAddress> ArchNetworkBSD::nameToAddr(const std::string &name)
{
struct addrinfo hints;
struct in6_addr serveraddr;
memset(&hints, 0, sizeof(hints));
hints.ai_flags = AI_NUMERICSERV;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if (inet_pton(AF_INET, name.c_str(), &serveraddr) == 1) {
hints.ai_family = AF_INET;
hints.ai_flags |= AI_NUMERICHOST;
} else if (inet_pton(AF_INET6, name.c_str(), &serveraddr) == 1) {
hints.ai_family = AF_INET6;
hints.ai_flags |= AI_NUMERICHOST;
}
// done with static buffer
ARCH->lockMutex(m_mutex);
struct addrinfo *pResult = nullptr;
int ret = getaddrinfo(name.c_str(), nullptr, &hints, &pResult);
if (ret != 0) {
ARCH->unlockMutex(m_mutex);
throwNameError(ret);
}
// allocate address
std::vector<ArchNetAddressImpl *> addresses;
for (auto address = pResult; address != nullptr; address = address->ai_next) {
addresses.push_back(new ArchNetAddressImpl);
if (address->ai_family == AF_INET) {
addresses.back()->m_len = (socklen_t)sizeof(struct sockaddr_in);
} else {
addresses.back()->m_len = (socklen_t)sizeof(struct sockaddr_in6);
}
memcpy(&addresses.back()->m_addr, address->ai_addr, addresses.back()->m_len);
}
freeaddrinfo(pResult);
ARCH->unlockMutex(m_mutex);
return addresses;
}
void ArchNetworkBSD::closeAddr(ArchNetAddress addr)
{
assert(addr != NULL);
delete addr;
}
std::string ArchNetworkBSD::addrToName(ArchNetAddress addr)
{
assert(addr != NULL);
// mutexed name lookup (ugh)
ARCH->lockMutex(m_mutex);
char host[1024];
char service[20];
int ret =
getnameinfo(TYPED_ADDR(struct sockaddr, addr), addr->m_len, host, sizeof(host), service, sizeof(service), 0);
if (ret != 0) {
ARCH->unlockMutex(m_mutex);
throwNameError(ret);
}
// save (primary) name
std::string name = host;
// done with static buffer
ARCH->unlockMutex(m_mutex);
return name;
}
std::string ArchNetworkBSD::addrToString(ArchNetAddress addr)
{
assert(addr != NULL);
switch (getAddrFamily(addr)) {
case kINET: {
auto *ipAddr = TYPED_ADDR(struct sockaddr_in, addr);
ARCH->lockMutex(m_mutex);
std::string s = inet_ntoa(ipAddr->sin_addr);
ARCH->unlockMutex(m_mutex);
return s;
}
case kINET6: {
char strAddr[INET6_ADDRSTRLEN];
struct sockaddr_in6 *ipAddr = TYPED_ADDR(struct sockaddr_in6, addr);
ARCH->lockMutex(m_mutex);
inet_ntop(AF_INET6, &ipAddr->sin6_addr, strAddr, INET6_ADDRSTRLEN);
ARCH->unlockMutex(m_mutex);
return strAddr;
}
default:
assert(0 && "unknown address family");
return "";
}
}
IArchNetwork::EAddressFamily ArchNetworkBSD::getAddrFamily(ArchNetAddress addr)
{
assert(addr != NULL);
switch (addr->m_addr.ss_family) {
case AF_INET:
return kINET;
case AF_INET6:
return kINET6;
default:
return kUNKNOWN;
}
}
void ArchNetworkBSD::setAddrPort(ArchNetAddress addr, int port)
{
assert(addr != NULL);
switch (getAddrFamily(addr)) {
case kINET: {
auto *ipAddr = TYPED_ADDR(struct sockaddr_in, addr);
ipAddr->sin_port = htons(port);
break;
}
case kINET6: {
struct sockaddr_in6 *ipAddr = TYPED_ADDR(struct sockaddr_in6, addr);
ipAddr->sin6_port = htons(port);
break;
}
default:
assert(0 && "unknown address family");
break;
}
}
int ArchNetworkBSD::getAddrPort(ArchNetAddress addr)
{
assert(addr != NULL);
switch (getAddrFamily(addr)) {
case kINET: {
auto *ipAddr = TYPED_ADDR(struct sockaddr_in, addr);
return ntohs(ipAddr->sin_port);
}
case kINET6: {
struct sockaddr_in6 *ipAddr = TYPED_ADDR(struct sockaddr_in6, addr);
return ntohs(ipAddr->sin6_port);
}
default:
assert(0 && "unknown address family");
return 0;
}
}
bool ArchNetworkBSD::isAnyAddr(ArchNetAddress addr)
{
assert(addr != NULL);
switch (getAddrFamily(addr)) {
case kINET: {
auto *ipAddr = TYPED_ADDR(struct sockaddr_in, addr);
return (ipAddr->sin_addr.s_addr == INADDR_ANY && addr->m_len == static_cast<socklen_t>(sizeof(struct sockaddr_in)));
}
case kINET6: {
struct sockaddr_in6 *ipAddr = TYPED_ADDR(struct sockaddr_in6, addr);
return (
addr->m_len == (socklen_t)sizeof(struct sockaddr_in6) &&
memcmp(
static_cast<const void *>(&ipAddr->sin6_addr), static_cast<const void *>(&in6addr_any), sizeof(in6_addr)
) == 0
);
}
default:
assert(0 && "unknown address family");
return true;
}
}
bool ArchNetworkBSD::isEqualAddr(ArchNetAddress a, ArchNetAddress b)
{
return (a->m_len == b->m_len && memcmp(&a->m_addr, &b->m_addr, a->m_len) == 0);
}
const int *ArchNetworkBSD::getUnblockPipe()
{
ArchMultithreadPosix *mt = ArchMultithreadPosix::getInstance();
ArchThread thread = mt->newCurrentThread();
const int *p = getUnblockPipeForThread(thread);
ARCH->closeThread(thread);
return p;
}
const int *ArchNetworkBSD::getUnblockPipeForThread(ArchThread thread)
{
ArchMultithreadPosix *mt = ArchMultithreadPosix::getInstance();
auto *unblockPipe = static_cast<int *>(mt->getNetworkDataForThread(thread));
if (unblockPipe == nullptr) {
unblockPipe = new int[2];
if (pipe(unblockPipe) != -1) {
try {
setBlockingOnSocket(unblockPipe[0], false);
mt->setNetworkDataForCurrentThread(unblockPipe);
} catch (...) {
delete[] unblockPipe;
unblockPipe = nullptr;
}
} else {
delete[] unblockPipe;
unblockPipe = nullptr;
}
}
return unblockPipe;
}
void ArchNetworkBSD::throwError(int err)
{
switch (err) {
case EINTR:
ARCH->testCancelThread();
throw XArchNetworkInterrupted(new XArchEvalUnix(err));
case EACCES:
case EPERM:
throw XArchNetworkAccess(new XArchEvalUnix(err));
case ENFILE:
case EMFILE:
case ENODEV:
case ENOBUFS:
case ENOMEM:
case ENETDOWN:
#if defined(ENOSR)
case ENOSR:
#endif
throw XArchNetworkResource(new XArchEvalUnix(err));
case EPROTOTYPE:
case EPROTONOSUPPORT:
case EAFNOSUPPORT:
case EPFNOSUPPORT:
case ESOCKTNOSUPPORT:
case EINVAL:
case ENOPROTOOPT:
case EOPNOTSUPP:
case ESHUTDOWN:
#if defined(ENOPKG)
case ENOPKG:
#endif
throw XArchNetworkSupport(new XArchEvalUnix(err));
case EIO:
throw XArchNetworkIO(new XArchEvalUnix(err));
case EADDRNOTAVAIL:
throw XArchNetworkNoAddress(new XArchEvalUnix(err));
case EADDRINUSE:
throw XArchNetworkAddressInUse(new XArchEvalUnix(err));
case EHOSTUNREACH:
case ENETUNREACH:
throw XArchNetworkNoRoute(new XArchEvalUnix(err));
case ENOTCONN:
throw XArchNetworkNotConnected(new XArchEvalUnix(err));
case EPIPE:
throw XArchNetworkShutdown(new XArchEvalUnix(err));
case ECONNABORTED:
case ECONNRESET:
throw XArchNetworkDisconnected(new XArchEvalUnix(err));
case ECONNREFUSED:
throw XArchNetworkConnectionRefused(new XArchEvalUnix(err));
case EHOSTDOWN:
case ETIMEDOUT:
throw XArchNetworkTimedOut(new XArchEvalUnix(err));
default:
throw XArchNetwork(new XArchEvalUnix(err));
}
}
void ArchNetworkBSD::throwNameError(int err)
{
static const char *s_msg[] = {
"The specified host is unknown", "The requested name is valid but does not have an IP address",
"A non-recoverable name server error occurred", "A temporary error occurred on an authoritative name server",
"An unknown name server error occurred"
};
switch (err) {
case HOST_NOT_FOUND:
throw XArchNetworkNameUnknown(s_msg[0]);
case NO_DATA:
throw XArchNetworkNameNoAddress(s_msg[1]);
case NO_RECOVERY:
throw XArchNetworkNameFailure(s_msg[2]);
case TRY_AGAIN:
throw XArchNetworkNameUnavailable(s_msg[3]);
default:
throw XArchNetworkName(s_msg[4]);
}
}
| 19,782
|
C++
|
.cpp
| 721
| 23.948682
| 120
| 0.671194
|
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,521
|
ArchTimeUnix.cpp
|
deskflow_deskflow/src/lib/arch/unix/ArchTimeUnix.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/unix/ArchTimeUnix.h"
#if TIME_WITH_SYS_TIME
#include <sys/time.h>
#include <time.h>
#else
#if HAVE_SYS_TIME_H
#include <sys/time.h>
#else
#include <time.h>
#endif
#endif
//
// ArchTimeUnix
//
ArchTimeUnix::ArchTimeUnix()
{
// do nothing
}
ArchTimeUnix::~ArchTimeUnix()
{
// do nothing
}
double ArchTimeUnix::time()
{
struct timeval t;
gettimeofday(&t, NULL);
return (double)t.tv_sec + 1.0e-6 * (double)t.tv_usec;
}
| 1,176
|
C++
|
.cpp
| 45
| 24.422222
| 72
| 0.745778
|
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,522
|
ArchTaskBarXWindows.cpp
|
deskflow_deskflow/src/lib/arch/unix/ArchTaskBarXWindows.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 "arch/unix/ArchTaskBarXWindows.h"
//
// ArchTaskBarXWindows
//
ArchTaskBarXWindows::ArchTaskBarXWindows()
{
// do nothing
}
ArchTaskBarXWindows::~ArchTaskBarXWindows()
{
// do nothing
}
void ArchTaskBarXWindows::addReceiver(IArchTaskBarReceiver * /*receiver*/)
{
// do nothing
}
void ArchTaskBarXWindows::removeReceiver(IArchTaskBarReceiver * /*receiver*/)
{
// do nothing
}
void ArchTaskBarXWindows::updateReceiver(IArchTaskBarReceiver * /*receiver*/)
{
// do nothing
}
| 1,227
|
C++
|
.cpp
| 41
| 28.121951
| 77
| 0.770992
|
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,523
|
ArchSystemUnix.cpp
|
deskflow_deskflow/src/lib/arch/unix/ArchSystemUnix.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 "arch/unix/ArchSystemUnix.h"
#include <array>
#include <common/constants.h>
#include <sys/utsname.h>
#ifndef __APPLE__
#include <QDBusConnection>
#include <QDBusError>
#include <QDBusInterface>
#include <QDBusReply>
#endif
//
// ArchSystemUnix
//
ArchSystemUnix::ArchSystemUnix()
{
// do nothing
}
ArchSystemUnix::~ArchSystemUnix()
{
// do nothing
}
std::string ArchSystemUnix::getOSName() const
{
#if defined(HAVE_SYS_UTSNAME_H)
struct utsname info;
if (uname(&info) == 0) {
std::string msg;
msg += info.sysname;
msg += " ";
msg += info.release;
return msg;
}
#endif
return "Unix";
}
std::string ArchSystemUnix::getPlatformName() const
{
#if defined(HAVE_SYS_UTSNAME_H)
struct utsname info;
if (uname(&info) == 0) {
return std::string(info.machine);
}
#endif
return "unknown";
}
std::string ArchSystemUnix::setting(const std::string &) const
{
return "";
}
void ArchSystemUnix::setting(const std::string &, const std::string &) const
{
}
std::string ArchSystemUnix::getLibsUsed(void) const
{
return "not implemented.\nuse lsof on shell";
}
#ifndef __APPLE__
bool ArchSystemUnix::DBusInhibitScreenCall(InhibitScreenServices serviceID, bool state, std::string &error)
{
error = "";
static const std::array<QString, 2> services = {"org.freedesktop.ScreenSaver", "org.gnome.SessionManager"};
static const std::array<QString, 2> paths = {"/org/freedesktop/ScreenSaver", "/org/gnome/SessionManager"};
static std::array<uint, 2> cookies;
auto serviceNum = static_cast<uint8_t>(serviceID);
QDBusConnection bus = QDBusConnection::sessionBus();
if (!bus.isConnected()) {
error = "bus failed to connect";
return false;
}
QDBusInterface screenSaverInterface(services[serviceNum], paths[serviceNum], services[serviceNum], bus);
if (!screenSaverInterface.isValid()) {
error = "screen saver interface failed to initialize";
return false;
}
QDBusReply<uint> reply;
if (state) {
if (cookies[serviceNum]) {
error = "coockies are not empty";
return false;
}
QString msg = "Sleep is manually prevented by the %1 preferences";
reply = screenSaverInterface.call("Inhibit", kAppName, msg.arg(kAppName));
if (reply.isValid())
cookies[serviceNum] = reply.value();
} else {
if (!cookies[serviceNum]) {
error = "coockies are empty";
return false;
}
reply = screenSaverInterface.call("UnInhibit", cookies[serviceNum]);
cookies[serviceNum] = 0;
}
if (!reply.isValid()) {
QDBusError qerror = reply.error();
error = qerror.name().toStdString() + " : " + qerror.message().toStdString();
return false;
}
return true;
}
#endif
| 3,431
|
C++
|
.cpp
| 117
| 26.495726
| 109
| 0.718276
|
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,524
|
ArchMultithreadPosix.cpp
|
deskflow_deskflow/src/lib/arch/unix/ArchMultithreadPosix.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/unix/ArchMultithreadPosix.h"
#include "arch/Arch.h"
#include "arch/XArch.h"
#include <signal.h>
#if TIME_WITH_SYS_TIME
#include <sys/time.h>
#include <time.h>
#else
#if HAVE_SYS_TIME_H
#include <sys/time.h>
#else
#include <time.h>
#endif
#endif
#include <cerrno>
#define SIGWAKEUP SIGUSR1
#if !HAVE_PTHREAD_SIGNAL
// boy, is this platform broken. forget about pthread signal
// handling and let signals through to every process. deskflow
// will not terminate cleanly when it gets SIGTERM or SIGINT.
#define pthread_sigmask sigprocmask
#define pthread_kill(tid_, sig_) kill(0, (sig_))
#define sigwait(set_, sig_)
#undef HAVE_POSIX_SIGWAIT
#define HAVE_POSIX_SIGWAIT 1
#endif
static void setSignalSet(sigset_t *sigset)
{
sigemptyset(sigset);
sigaddset(sigset, SIGHUP);
sigaddset(sigset, SIGINT);
sigaddset(sigset, SIGTERM);
sigaddset(sigset, SIGUSR2);
}
//
// ArchThreadImpl
//
class ArchThreadImpl
{
public:
ArchThreadImpl();
public:
int m_refCount;
IArchMultithread::ThreadID m_id;
pthread_t m_thread;
IArchMultithread::ThreadFunc m_func;
void *m_userData;
bool m_cancel;
bool m_cancelling;
bool m_exited;
void *m_result;
void *m_networkData;
};
ArchThreadImpl::ArchThreadImpl()
: m_refCount(1),
m_id(0),
m_func(NULL),
m_userData(NULL),
m_cancel(false),
m_cancelling(false),
m_exited(false),
m_result(NULL),
m_networkData(NULL)
{
// do nothing
}
//
// ArchMultithreadPosix
//
ArchMultithreadPosix *ArchMultithreadPosix::s_instance = NULL;
ArchMultithreadPosix::ArchMultithreadPosix() : m_newThreadCalled(false), m_nextID(0)
{
assert(s_instance == NULL);
s_instance = this;
// no signal handlers
for (size_t i = 0; i < kNUM_SIGNALS; ++i) {
m_signalFunc[i] = NULL;
m_signalUserData[i] = NULL;
}
// create mutex for thread list
m_threadMutex = newMutex();
// create thread for calling (main) thread and add it to our
// list. no need to lock the mutex since we're the only thread.
m_mainThread = new ArchThreadImpl;
m_mainThread->m_thread = pthread_self();
insert(m_mainThread);
// install SIGWAKEUP handler. this causes SIGWAKEUP to interrupt
// system calls. we use that when cancelling a thread to force it
// to wake up immediately if it's blocked in a system call. we
// won't need this until another thread is created but it's fine
// to install it now.
struct sigaction act;
sigemptyset(&act.sa_mask);
#if defined(SA_INTERRUPT)
act.sa_flags = SA_INTERRUPT;
#else
act.sa_flags = 0;
#endif
act.sa_handler = &threadCancel;
sigaction(SIGWAKEUP, &act, NULL);
// set desired signal dispositions. let SIGWAKEUP through but
// ignore SIGPIPE (we'll handle EPIPE).
sigset_t sigset;
sigemptyset(&sigset);
sigaddset(&sigset, SIGWAKEUP);
pthread_sigmask(SIG_UNBLOCK, &sigset, NULL);
sigemptyset(&sigset);
sigaddset(&sigset, SIGPIPE);
pthread_sigmask(SIG_BLOCK, &sigset, NULL);
}
ArchMultithreadPosix::~ArchMultithreadPosix()
{
assert(s_instance != NULL);
closeMutex(m_threadMutex);
s_instance = NULL;
}
void ArchMultithreadPosix::setNetworkDataForCurrentThread(void *data)
{
lockMutex(m_threadMutex);
ArchThreadImpl *thread = find(pthread_self());
thread->m_networkData = data;
unlockMutex(m_threadMutex);
}
void *ArchMultithreadPosix::getNetworkDataForThread(ArchThread thread)
{
lockMutex(m_threadMutex);
void *data = thread->m_networkData;
unlockMutex(m_threadMutex);
return data;
}
ArchMultithreadPosix *ArchMultithreadPosix::getInstance()
{
return s_instance;
}
ArchCond ArchMultithreadPosix::newCondVar()
{
ArchCondImpl *cond = new ArchCondImpl;
int status = pthread_cond_init(&cond->m_cond, NULL);
(void)status;
assert(status == 0);
return cond;
}
void ArchMultithreadPosix::closeCondVar(ArchCond cond)
{
int status = pthread_cond_destroy(&cond->m_cond);
(void)status;
assert(status == 0);
delete cond;
}
void ArchMultithreadPosix::signalCondVar(ArchCond cond)
{
int status = pthread_cond_signal(&cond->m_cond);
(void)status;
assert(status == 0);
}
void ArchMultithreadPosix::broadcastCondVar(ArchCond cond)
{
int status = pthread_cond_broadcast(&cond->m_cond);
(void)status;
assert(status == 0);
}
bool ArchMultithreadPosix::waitCondVar(ArchCond cond, ArchMutex mutex, double timeout)
{
// we can't wait on a condition variable and also wake it up for
// cancellation since we don't use posix cancellation. so we
// must wake up periodically to check for cancellation. we
// can't simply go back to waiting after the check since the
// condition may have changed and we'll have lost the signal.
// so we have to return to the caller. since the caller will
// always check for spurious wakeups the only drawback here is
// performance: we're waking up a lot more than desired.
static const double maxCancellationLatency = 0.1;
if (timeout < 0.0 || timeout > maxCancellationLatency) {
timeout = maxCancellationLatency;
}
// see if we should cancel this thread
testCancelThread();
// get final time
struct timeval now;
gettimeofday(&now, NULL);
struct timespec finalTime;
finalTime.tv_sec = now.tv_sec;
finalTime.tv_nsec = now.tv_usec * 1000;
long timeout_sec = (long)timeout;
long timeout_nsec = (long)(1.0e+9 * (timeout - timeout_sec));
finalTime.tv_sec += timeout_sec;
finalTime.tv_nsec += timeout_nsec;
if (finalTime.tv_nsec >= 1000000000) {
finalTime.tv_nsec -= 1000000000;
finalTime.tv_sec += 1;
}
// wait
int status = pthread_cond_timedwait(&cond->m_cond, &mutex->m_mutex, &finalTime);
// check for cancel again
testCancelThread();
switch (status) {
case 0:
// success
return true;
case ETIMEDOUT:
return false;
default:
assert(0 && "condition variable wait error");
return false;
}
}
ArchMutex ArchMultithreadPosix::newMutex()
{
pthread_mutexattr_t attr;
int status = pthread_mutexattr_init(&attr);
assert(status == 0);
ArchMutexImpl *mutex = new ArchMutexImpl;
status = pthread_mutex_init(&mutex->m_mutex, &attr);
assert(status == 0);
return mutex;
}
void ArchMultithreadPosix::closeMutex(ArchMutex mutex)
{
int status = pthread_mutex_destroy(&mutex->m_mutex);
(void)status;
assert(status == 0);
delete mutex;
}
void ArchMultithreadPosix::lockMutex(ArchMutex mutex)
{
int status = pthread_mutex_lock(&mutex->m_mutex);
switch (status) {
case 0:
// success
return;
case EDEADLK:
assert(0 && "lock already owned");
break;
case EAGAIN:
assert(0 && "too many recursive locks");
break;
default:
assert(0 && "unexpected error");
break;
}
}
void ArchMultithreadPosix::unlockMutex(ArchMutex mutex)
{
// TODO: S1-1767, we should use raii c++17 mutex instead of archaeic pthread
// to solve possible lock order reversal.
int status = pthread_mutex_unlock(&mutex->m_mutex);
switch (status) {
case 0:
// success
return;
case EPERM:
assert(0 && "thread doesn't own a lock");
break;
default:
assert(0 && "unexpected error");
break;
}
}
ArchThread ArchMultithreadPosix::newThread(ThreadFunc func, void *data)
{
assert(func != NULL);
// initialize signal handler. we do this here instead of the
// constructor so we can avoid daemonizing (using fork())
// when there are multiple threads. clients can safely
// use condition variables and mutexes before creating a
// new thread and they can safely use the only thread
// they have access to, the main thread, so they really
// can't tell the difference.
if (!m_newThreadCalled) {
m_newThreadCalled = true;
#if HAVE_PTHREAD_SIGNAL
startSignalHandler();
#endif
}
lockMutex(m_threadMutex);
// create thread impl for new thread
ArchThreadImpl *thread = new ArchThreadImpl;
thread->m_func = func;
thread->m_userData = data;
// create the thread. pthread_create() on RedHat 7.2 smp fails
// if passed a NULL attr so use a default attr.
pthread_attr_t attr;
int status = pthread_attr_init(&attr);
if (status == 0) {
status = pthread_create(&thread->m_thread, &attr, &ArchMultithreadPosix::threadFunc, thread);
pthread_attr_destroy(&attr);
}
// check if thread was started
if (status != 0) {
// failed to start thread so clean up
delete thread;
thread = NULL;
} else {
// add thread to list
insert(thread);
// increment ref count to account for the thread itself
refThread(thread);
}
// note that the child thread will wait until we release this mutex
unlockMutex(m_threadMutex);
return thread;
}
ArchThread ArchMultithreadPosix::newCurrentThread()
{
lockMutex(m_threadMutex);
ArchThreadImpl *thread = find(pthread_self());
unlockMutex(m_threadMutex);
assert(thread != NULL);
return thread;
}
void ArchMultithreadPosix::closeThread(ArchThread thread)
{
assert(thread != NULL);
// decrement ref count and clean up thread if no more references
if (--thread->m_refCount == 0) {
// detach from thread (unless it's the main thread)
if (thread->m_func != NULL) {
pthread_detach(thread->m_thread);
}
// remove thread from list
lockMutex(m_threadMutex);
assert(findNoRef(thread->m_thread) == thread);
erase(thread);
unlockMutex(m_threadMutex);
// done with thread
delete thread;
}
}
ArchThread ArchMultithreadPosix::copyThread(ArchThread thread)
{
refThread(thread);
return thread;
}
void ArchMultithreadPosix::cancelThread(ArchThread thread)
{
assert(thread != NULL);
// set cancel and wakeup flags if thread can be cancelled
bool wakeup = false;
lockMutex(m_threadMutex);
if (!thread->m_exited && !thread->m_cancelling) {
thread->m_cancel = true;
wakeup = true;
}
unlockMutex(m_threadMutex);
// force thread to exit system calls if wakeup is true
if (wakeup) {
pthread_kill(thread->m_thread, SIGWAKEUP);
}
}
void ArchMultithreadPosix::setPriorityOfThread(ArchThread thread, int /*n*/)
{
assert(thread != NULL);
// FIXME
}
void ArchMultithreadPosix::testCancelThread()
{
// find current thread
lockMutex(m_threadMutex);
ArchThreadImpl *thread = findNoRef(pthread_self());
unlockMutex(m_threadMutex);
// test cancel on thread
testCancelThreadImpl(thread);
}
bool ArchMultithreadPosix::wait(ArchThread target, double timeout)
{
assert(target != NULL);
lockMutex(m_threadMutex);
// find current thread
ArchThreadImpl *self = findNoRef(pthread_self());
// ignore wait if trying to wait on ourself
if (target == self) {
unlockMutex(m_threadMutex);
return false;
}
// ref the target so it can't go away while we're watching it
refThread(target);
unlockMutex(m_threadMutex);
try {
// do first test regardless of timeout
testCancelThreadImpl(self);
if (isExitedThread(target)) {
closeThread(target);
return true;
}
// wait and repeat test if there's a timeout
if (timeout != 0.0) {
const double start = ARCH->time();
do {
// wait a little
ARCH->sleep(0.05);
// repeat test
testCancelThreadImpl(self);
if (isExitedThread(target)) {
closeThread(target);
return true;
}
// repeat wait and test until timed out
} while (timeout < 0.0 || (ARCH->time() - start) <= timeout);
}
closeThread(target);
return false;
} catch (...) {
closeThread(target);
throw;
}
}
bool ArchMultithreadPosix::isSameThread(ArchThread thread1, ArchThread thread2)
{
return (thread1 == thread2);
}
bool ArchMultithreadPosix::isExitedThread(ArchThread thread)
{
lockMutex(m_threadMutex);
bool exited = thread->m_exited;
unlockMutex(m_threadMutex);
return exited;
}
void *ArchMultithreadPosix::getResultOfThread(ArchThread thread)
{
lockMutex(m_threadMutex);
void *result = thread->m_result;
unlockMutex(m_threadMutex);
return result;
}
IArchMultithread::ThreadID ArchMultithreadPosix::getIDOfThread(ArchThread thread)
{
return thread->m_id;
}
void ArchMultithreadPosix::setSignalHandler(ESignal signal, SignalFunc func, void *userData)
{
lockMutex(m_threadMutex);
m_signalFunc[signal] = func;
m_signalUserData[signal] = userData;
unlockMutex(m_threadMutex);
}
void ArchMultithreadPosix::raiseSignal(ESignal signal)
{
lockMutex(m_threadMutex);
if (m_signalFunc[signal] != NULL) {
m_signalFunc[signal](signal, m_signalUserData[signal]);
pthread_kill(m_mainThread->m_thread, SIGWAKEUP);
} else if (signal == kINTERRUPT || signal == kTERMINATE) {
ARCH->cancelThread(m_mainThread);
}
unlockMutex(m_threadMutex);
}
void ArchMultithreadPosix::startSignalHandler()
{
// set signal mask. the main thread blocks these signals and
// the signal handler thread will listen for them.
sigset_t sigset, oldsigset;
setSignalSet(&sigset);
pthread_sigmask(SIG_BLOCK, &sigset, &oldsigset);
// fire up the INT and TERM signal handler thread. we could
// instead arrange to catch and handle these signals but
// we'd be unable to cancel the main thread since no pthread
// calls are allowed in a signal handler.
pthread_attr_t attr;
int status = pthread_attr_init(&attr);
if (status == 0) {
status = pthread_create(&m_signalThread, &attr, &ArchMultithreadPosix::threadSignalHandler, NULL);
pthread_attr_destroy(&attr);
}
if (status != 0) {
// can't create thread to wait for signal so don't block
// the signals.
pthread_sigmask(SIG_UNBLOCK, &oldsigset, NULL);
}
}
ArchThreadImpl *ArchMultithreadPosix::find(pthread_t thread)
{
ArchThreadImpl *impl = findNoRef(thread);
if (impl != NULL) {
refThread(impl);
}
return impl;
}
ArchThreadImpl *ArchMultithreadPosix::findNoRef(pthread_t thread)
{
// linear search
for (ThreadList::const_iterator index = m_threadList.begin(); index != m_threadList.end(); ++index) {
if ((*index)->m_thread == thread) {
return *index;
}
}
return NULL;
}
void ArchMultithreadPosix::insert(ArchThreadImpl *thread)
{
assert(thread != NULL);
// thread shouldn't already be on the list
assert(findNoRef(thread->m_thread) == NULL);
// set thread id. note that we don't worry about m_nextID
// wrapping back to 0 and duplicating thread ID's since the
// likelihood of deskflow running that long is vanishingly
// small.
thread->m_id = ++m_nextID;
// append to list
m_threadList.push_back(thread);
}
void ArchMultithreadPosix::erase(ArchThreadImpl *thread)
{
for (ThreadList::iterator index = m_threadList.begin(); index != m_threadList.end(); ++index) {
if (*index == thread) {
m_threadList.erase(index);
break;
}
}
}
void ArchMultithreadPosix::refThread(ArchThreadImpl *thread)
{
assert(thread != NULL);
assert(findNoRef(thread->m_thread) != NULL);
++thread->m_refCount;
}
void ArchMultithreadPosix::testCancelThreadImpl(ArchThreadImpl *thread)
{
assert(thread != NULL);
// update cancel state
lockMutex(m_threadMutex);
bool cancel = false;
if (thread->m_cancel && !thread->m_cancelling) {
thread->m_cancelling = true;
thread->m_cancel = false;
cancel = true;
}
unlockMutex(m_threadMutex);
// unwind thread's stack if cancelling
if (cancel) {
throw XThreadCancel();
}
}
void *ArchMultithreadPosix::threadFunc(void *vrep)
{
// get the thread
ArchThreadImpl *thread = static_cast<ArchThreadImpl *>(vrep);
// setup pthreads
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
// run thread
s_instance->doThreadFunc(thread);
// terminate the thread
return NULL;
}
void ArchMultithreadPosix::doThreadFunc(ArchThread thread)
{
// default priority is slightly below normal
setPriorityOfThread(thread, 1);
// wait for parent to initialize this object
lockMutex(m_threadMutex);
unlockMutex(m_threadMutex);
void *result = nullptr;
try {
// go
result = (*thread->m_func)(thread->m_userData);
}
catch (XThreadCancel &) {
// client called cancel()
// set base value
result = nullptr;
} catch (...) {
// note -- don't catch (...) to avoid masking bugs
lockMutex(m_threadMutex);
thread->m_exited = true;
unlockMutex(m_threadMutex);
closeThread(thread);
throw;
}
// thread has exited
lockMutex(m_threadMutex);
thread->m_result = result;
thread->m_exited = true;
unlockMutex(m_threadMutex);
// done with thread
closeThread(thread);
}
void ArchMultithreadPosix::threadCancel(int)
{
// do nothing
}
void *ArchMultithreadPosix::threadSignalHandler(void *)
{
// detach
pthread_detach(pthread_self());
// add signal to mask
sigset_t sigset;
setSignalSet(&sigset);
// also wait on SIGABRT. on linux (others?) this thread (process)
// will persist after all the other threads evaporate due to an
// assert unless we wait on SIGABRT. that means our resources (like
// the socket we're listening on) are not released and never will be
// until the lingering thread is killed. i don't know why sigwait()
// should protect the thread from being killed. note that sigwait()
// doesn't actually return if we receive SIGABRT and, for some
// reason, we don't have to block SIGABRT.
sigaddset(&sigset, SIGABRT);
// we exit the loop via thread cancellation in sigwait()
for (;;) {
// wait
#if HAVE_POSIX_SIGWAIT
int signal = 0;
sigwait(&sigset, &signal);
#else
sigwait(&sigset);
#endif
// if we get here then the signal was raised
switch (signal) {
case SIGINT:
ARCH->raiseSignal(kINTERRUPT);
break;
case SIGTERM:
ARCH->raiseSignal(kTERMINATE);
break;
case SIGHUP:
ARCH->raiseSignal(kHANGUP);
break;
case SIGUSR2:
ARCH->raiseSignal(kUSER);
break;
default:
// ignore
break;
}
}
return NULL;
}
| 18,671
|
C++
|
.cpp
| 643
| 25.828927
| 103
| 0.717668
|
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,525
|
ArchDaemonUnix.cpp
|
deskflow_deskflow/src/lib/arch/unix/ArchDaemonUnix.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/unix/ArchDaemonUnix.h"
#include "arch/unix/XArchUnix.h"
#include "base/Log.h"
#include <cstdlib>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
//
// ArchDaemonUnix
//
ArchDaemonUnix::ArchDaemonUnix()
{
// do nothing
}
ArchDaemonUnix::~ArchDaemonUnix()
{
// do nothing
}
#ifdef __APPLE__
// In Mac OS X, fork()'d child processes can't use most APIs (the frameworks
// that Deskflow uses in fact prevent it and make the process just up and die),
// so need to exec a copy of the program that doesn't fork so isn't limited.
int execSelfNonDaemonized()
{
extern char **NXArgv;
char **selfArgv = NXArgv;
setenv("_DESKFLOW_DAEMONIZED", "", 1);
execvp(selfArgv[0], selfArgv);
return 0;
}
bool alreadyDaemonized()
{
return getenv("_DESKFLOW_DAEMONIZED") != NULL;
}
#endif
int ArchDaemonUnix::daemonize(const char *name, DaemonFunc func)
{
#ifdef __APPLE__
if (alreadyDaemonized())
return func(1, &name);
#endif
// fork so shell thinks we're done and so we're not a process
// group leader
switch (fork()) {
case -1:
// failed
throw XArchDaemonFailed(new XArchEvalUnix(errno));
case 0:
// child
break;
default:
// parent exits
exit(0);
}
// become leader of a new session
setsid();
#ifndef __APPLE__
// NB: don't run chdir on apple; causes strange behaviour.
// chdir to root so we don't keep mounted filesystems points busy
// TODO: this is a bit of a hack - can we find a better solution?
int chdirErr = chdir("/");
if (chdirErr)
// NB: file logging actually isn't working at this point!
LOG((CLOG_ERR "chdir error: %i", chdirErr));
#endif
// mask off permissions for any but owner
umask(077);
// close open files. we only expect stdin, stdout, stderr to be open.
close(0);
close(1);
close(2);
// attach file descriptors 0, 1, 2 to /dev/null so inadvertent use
// of standard I/O safely goes in the bit bucket.
open("/dev/null", O_RDONLY);
open("/dev/null", O_RDWR);
int dupErr = dup(1);
if (dupErr < 0) {
// NB: file logging actually isn't working at this point!
LOG((CLOG_ERR "dup error: %i", dupErr));
}
#ifdef __APPLE__
return execSelfNonDaemonized();
#endif
// invoke function
return func(1, &name);
}
| 3,050
|
C++
|
.cpp
| 105
| 26.495238
| 79
| 0.709589
|
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,526
|
ArchStringUnix.cpp
|
deskflow_deskflow/src/lib/arch/unix/ArchStringUnix.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/unix/ArchStringUnix.h"
#include <stdio.h>
//
// ArchStringUnix
//
#include "arch/multibyte.h"
#include "arch/vsnprintf.h"
ArchStringUnix::ArchStringUnix()
{
}
ArchStringUnix::~ArchStringUnix()
{
}
IArchString::EWideCharEncoding ArchStringUnix::getWideCharEncoding()
{
return kUCS4;
}
| 1,038
|
C++
|
.cpp
| 34
| 28.794118
| 72
| 0.771314
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| true
| false
| false
| true
| false
| false
|
13,527
|
XArchUnix.cpp
|
deskflow_deskflow/src/lib/arch/unix/XArchUnix.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/unix/XArchUnix.h"
#include <cstring>
//
// XArchEvalUnix
//
std::string XArchEvalUnix::eval() const
{
// FIXME -- not thread safe
return strerror(m_error);
}
| 911
|
C++
|
.cpp
| 27
| 31.851852
| 72
| 0.753409
|
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,528
|
ArchSleepUnix.cpp
|
deskflow_deskflow/src/lib/arch/unix/ArchSleepUnix.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/unix/ArchSleepUnix.h"
#include "arch/Arch.h"
#if TIME_WITH_SYS_TIME
#include <sys/time.h>
#include <time.h>
#else
#if HAVE_SYS_TIME_H
#include <sys/time.h>
#else
#include <time.h>
#endif
#endif
#if !HAVE_NANOSLEEP
#if HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#if HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#endif
//
// ArchSleepUnix
//
ArchSleepUnix::ArchSleepUnix()
{
// do nothing
}
ArchSleepUnix::~ArchSleepUnix()
{
// do nothing
}
void ArchSleepUnix::sleep(double timeout)
{
ARCH->testCancelThread();
if (timeout < 0.0) {
return;
}
#if HAVE_NANOSLEEP
// prep timeout
struct timespec t;
t.tv_sec = (long)timeout;
t.tv_nsec = (long)(1.0e+9 * (timeout - (double)t.tv_sec));
// wait
while (nanosleep(&t, &t) < 0)
ARCH->testCancelThread();
#else
/* emulate nanosleep() with select() */
double startTime = ARCH->time();
double timeLeft = timeout;
while (timeLeft > 0.0) {
struct timeval timeout2;
timeout2.tv_sec = static_cast<int>(timeLeft);
timeout2.tv_usec = static_cast<int>(1.0e+6 * (timeLeft - timeout2.tv_sec));
select(
(SELECT_TYPE_ARG1)0, SELECT_TYPE_ARG234 NULL, SELECT_TYPE_ARG234 NULL, SELECT_TYPE_ARG234 NULL,
SELECT_TYPE_ARG5 & timeout2
);
ARCH->testCancelThread();
timeLeft = timeout - (ARCH->time() - startTime);
}
#endif
}
| 2,133
|
C++
|
.cpp
| 82
| 23.682927
| 103
| 0.714985
|
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,529
|
ArchFileUnix.cpp
|
deskflow_deskflow/src/lib/arch/unix/ArchFileUnix.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/unix/ArchFileUnix.h"
#include "common/constants.h"
#include <cstring>
#include <filesystem>
#include <pwd.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
//
// ArchFileUnix
//
ArchFileUnix::ArchFileUnix()
{
// do nothing
}
ArchFileUnix::~ArchFileUnix()
{
// do nothing
}
const char *ArchFileUnix::getBasename(const char *pathname)
{
if (pathname == NULL) {
return NULL;
}
const char *basename = strrchr(pathname, '/');
if (basename != NULL) {
return basename + 1;
} else {
return pathname;
}
}
std::string ArchFileUnix::getUserDirectory()
{
char *buffer = NULL;
std::string dir;
#if HAVE_GETPWUID_R
struct passwd pwent;
struct passwd *pwentp{};
#if defined(_SC_GETPW_R_SIZE_MAX)
long size = sysconf(_SC_GETPW_R_SIZE_MAX);
if (size == -1) {
size = BUFSIZ;
}
#else
long size = BUFSIZ;
#endif
buffer = new char[size];
getpwuid_r(getuid(), &pwent, buffer, size, &pwentp);
#else
struct passwd *pwentp = getpwuid(getuid());
#endif
if (pwentp != NULL && pwentp->pw_dir != NULL) {
dir = pwentp->pw_dir;
}
delete[] buffer;
return dir;
}
std::string ArchFileUnix::getSystemDirectory()
{
return "/etc";
}
std::string ArchFileUnix::getInstalledDirectory()
{
#if WINAPI_XWINDOWS
return "/usr/bin";
#else
std::string rtn = "/Applications/";
rtn.append(kAppName).append(".app/Contents/MacOS");
return rtn;
#endif
}
std::string ArchFileUnix::getLogDirectory()
{
return "/var/log";
}
std::string ArchFileUnix::getPluginDirectory()
{
if (!m_pluginDirectory.empty()) {
return m_pluginDirectory;
}
#if WINAPI_XWINDOWS
return getProfileDirectory().append("/plugins");
#else
return getProfileDirectory().append("/Plugins");
#endif
}
std::string ArchFileUnix::getProfileDirectory()
{
if (!m_profileDirectory.empty()) {
return m_profileDirectory;
} else {
const std::filesystem::path homeDir = getUserDirectory();
#if WINAPI_XWINDOWS
const auto xdgDir = std::getenv("XDG_CONFIG_HOME");
if (xdgDir != nullptr) {
return std::filesystem::path(xdgDir) / kAppName;
} else {
return homeDir / ".config" / kAppName;
}
#else
return homeDir / "Library" / kAppName;
#endif
}
}
std::string ArchFileUnix::concatPath(const std::string &prefix, const std::string &suffix)
{
std::string path;
path.reserve(prefix.size() + 1 + suffix.size());
path += prefix;
if (path.size() == 0 || path[path.size() - 1] != '/') {
path += '/';
}
path += suffix;
return path;
}
void ArchFileUnix::setProfileDirectory(const String &s)
{
m_profileDirectory = s;
}
void ArchFileUnix::setPluginDirectory(const String &s)
{
m_pluginDirectory = s;
}
| 3,423
|
C++
|
.cpp
| 140
| 22.085714
| 90
| 0.708512
|
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,530
|
ClientProxy1_8.cpp
|
deskflow_deskflow/src/lib/server/ClientProxy1_8.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2015-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/Log.h"
#include "deskflow/ProtocolUtil.h"
#include "deskflow/languages/LanguageManager.h"
#include "ClientProxy1_8.h"
ClientProxy1_8::ClientProxy1_8(
const String &name, deskflow::IStream *adoptedStream, Server *server, IEventQueue *events
)
: ClientProxy1_7(name, adoptedStream, server, events)
{
synchronizeLanguages();
}
void ClientProxy1_8::synchronizeLanguages() const
{
deskflow::languages::LanguageManager languageManager;
auto localLanguages = languageManager.getSerializedLocalLanguages();
if (!localLanguages.empty()) {
LOG((CLOG_DEBUG1 "send server languages to the client: %s", localLanguages.c_str()));
ProtocolUtil::writef(getStream(), kMsgDLanguageSynchronisation, &localLanguages);
} else {
LOG((CLOG_ERR "failed to read server languages"));
}
}
void ClientProxy1_8::keyDown(KeyID key, KeyModifierMask mask, KeyButton button, const String &language)
{
LOG(
(CLOG_DEBUG1 "send key down to \"%s\" id=%d, mask=0x%04x, button=0x%04x, language=%s", getName().c_str(), key,
mask, button, language.c_str())
);
ProtocolUtil::writef(getStream(), kMsgDKeyDownLang, key, mask, button, &language);
}
| 1,865
|
C++
|
.cpp
| 46
| 38.021739
| 116
| 0.750964
|
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,531
|
ClientProxy1_4.cpp
|
deskflow_deskflow/src/lib/server/ClientProxy1_4.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2011 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 "server/ClientProxy1_4.h"
#include "base/IEventQueue.h"
#include "base/Log.h"
#include "base/TMethodEventJob.h"
#include "deskflow/ProtocolUtil.h"
#include "server/Server.h"
#include <cstring>
#include <memory>
//
// ClientProxy1_4
//
ClientProxy1_4::ClientProxy1_4(const String &name, deskflow::IStream *stream, Server *server, IEventQueue *events)
: ClientProxy1_3(name, stream, events),
m_server(server)
{
assert(m_server != NULL);
}
ClientProxy1_4::~ClientProxy1_4()
{
}
void ClientProxy1_4::keyDown(KeyID key, KeyModifierMask mask, KeyButton button, const String &lang)
{
ClientProxy1_3::keyDown(key, mask, button, lang);
}
void ClientProxy1_4::keyRepeat(KeyID key, KeyModifierMask mask, SInt32 count, KeyButton button, const String &lang)
{
ClientProxy1_3::keyRepeat(key, mask, count, button, lang);
}
void ClientProxy1_4::keyUp(KeyID key, KeyModifierMask mask, KeyButton button)
{
ClientProxy1_3::keyUp(key, mask, button);
}
void ClientProxy1_4::keepAlive()
{
ClientProxy1_3::keepAlive();
}
| 1,767
|
C++
|
.cpp
| 53
| 31.471698
| 115
| 0.76115
|
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,532
|
ClientListener.cpp
|
deskflow_deskflow/src/lib/server/ClientListener.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 "server/ClientListener.h"
#include "server/Server.h"
#include "base/IEventQueue.h"
#include "base/Log.h"
#include "base/TMethodEventJob.h"
#include "deskflow/PacketStreamFilter.h"
#include "net/IDataSocket.h"
#include "net/IListenSocket.h"
#include "net/ISocketFactory.h"
#include "net/XSocket.h"
#include "server/ClientProxy.h"
#include "server/ClientProxyUnknown.h"
//
// ClientListener
//
ClientListener::ClientListener(
const NetworkAddress &address, ISocketFactory *socketFactory, IEventQueue *events, bool enableCrypto
)
: m_socketFactory(socketFactory),
m_server(NULL),
m_events(events),
m_useSecureNetwork(enableCrypto),
m_address(address)
{
assert(m_socketFactory != NULL);
try {
start();
} catch (XSocketAddressInUse &) {
cleanupListenSocket();
delete m_socketFactory;
throw;
} catch (XBase &) {
cleanupListenSocket();
delete m_socketFactory;
throw;
}
LOG((CLOG_DEBUG1 "listening for clients"));
}
ClientListener::~ClientListener()
{
stop();
delete m_socketFactory;
}
void ClientListener::setServer(Server *server)
{
assert(server != NULL);
m_server = server;
}
ClientProxy *ClientListener::getNextClient()
{
ClientProxy *client = NULL;
if (!m_waitingClients.empty()) {
client = m_waitingClients.front();
m_waitingClients.pop_front();
m_events->removeHandler(m_events->forClientProxy().disconnected(), client);
}
return client;
}
void ClientListener::start()
{
m_listen = m_socketFactory->createListen(m_useSecureNetwork, ARCH->getAddrFamily(m_address.getAddress()));
// setup event handler
m_events->adoptHandler(
m_events->forIListenSocket().connecting(), m_listen,
new TMethodEventJob<ClientListener>(this, &ClientListener::handleClientConnecting)
);
// bind listen address
LOG((CLOG_DEBUG1 "binding listen socket"));
m_listen->bind(m_address);
}
void ClientListener::stop()
{
LOG((CLOG_DEBUG1 "stop listening for clients"));
// discard already connected clients
for (NewClients::iterator index = m_newClients.begin(); index != m_newClients.end(); ++index) {
ClientProxyUnknown *client = *index;
m_events->removeHandler(m_events->forClientProxyUnknown().success(), client);
m_events->removeHandler(m_events->forClientProxyUnknown().failure(), client);
m_events->removeHandler(m_events->forClientProxy().disconnected(), client);
delete client;
}
// discard waiting clients
ClientProxy *client = getNextClient();
while (client != nullptr) {
delete client;
client = getNextClient();
}
m_events->removeHandler(m_events->forIListenSocket().connecting(), m_listen);
cleanupListenSocket();
cleanupClientSockets();
}
void ClientListener::removeUnknownClient(ClientProxyUnknown *unknownClient)
{
if (unknownClient) {
m_events->removeHandler(m_events->forClientProxyUnknown().success(), unknownClient);
m_events->removeHandler(m_events->forClientProxyUnknown().failure(), unknownClient);
m_newClients.erase(unknownClient);
delete unknownClient;
}
}
void ClientListener::restart()
{
if (m_server && m_server->isClientMode()) {
stop();
start();
}
}
void ClientListener::handleClientConnecting(const Event &, void *)
{
// accept client connection
IDataSocket *socket = m_listen->accept();
if (socket == NULL) {
return;
}
m_clientSockets.insert(socket);
m_events->adoptHandler(
m_events->forClientListener().accepted(), socket->getEventTarget(),
new TMethodEventJob<ClientListener>(this, &ClientListener::handleClientAccepted, socket)
);
// When using non SSL, server accepts clients immediately, while SSL
// has to call secure accept which may require retry
if (!m_useSecureNetwork) {
m_events->addEvent(Event(m_events->forClientListener().accepted(), socket->getEventTarget()));
}
}
void ClientListener::handleClientAccepted(const Event &, void *vsocket)
{
LOG((CLOG_NOTE "accepted client connection"));
IDataSocket *socket = static_cast<IDataSocket *>(vsocket);
// filter socket messages, including a packetizing filter
deskflow::IStream *stream = new PacketStreamFilter(m_events, socket, false);
assert(m_server != NULL);
// create proxy for unknown client
ClientProxyUnknown *client = new ClientProxyUnknown(stream, 30.0, m_server, m_events);
m_newClients.insert(client);
// watch for events from unknown client
m_events->adoptHandler(
m_events->forClientProxyUnknown().success(), client,
new TMethodEventJob<ClientListener>(this, &ClientListener::handleUnknownClient, client)
);
m_events->adoptHandler(
m_events->forClientProxyUnknown().failure(), client,
new TMethodEventJob<ClientListener>(this, &ClientListener::handleUnknownClientFailure, client)
);
}
void ClientListener::handleUnknownClient(const Event &, void *vclient)
{
auto unknownClient = static_cast<ClientProxyUnknown *>(vclient);
// we should have the client in our new client list
assert(m_newClients.count(unknownClient) == 1);
// get the real client proxy and install it
auto client = unknownClient->orphanClientProxy();
if (client) {
// handshake was successful
m_waitingClients.push_back(client);
m_events->addEvent(Event(m_events->forClientListener().connected(), this));
// watch for client to disconnect while it's in our queue
m_events->adoptHandler(
m_events->forClientProxy().disconnected(), client,
new TMethodEventJob<ClientListener>(this, &ClientListener::handleClientDisconnected, client)
);
}
// now finished with unknown client
removeUnknownClient(unknownClient);
}
void ClientListener::handleUnknownClientFailure(const Event &, void *vclient)
{
auto unknownClient = static_cast<ClientProxyUnknown *>(vclient);
removeUnknownClient(unknownClient);
restart();
}
void ClientListener::handleClientDisconnected(const Event &, void *vclient)
{
ClientProxy *client = static_cast<ClientProxy *>(vclient);
// find client in waiting clients queue
for (WaitingClients::iterator i = m_waitingClients.begin(), n = m_waitingClients.end(); i != n; ++i) {
if (*i == client) {
m_waitingClients.erase(i);
m_events->removeHandler(m_events->forClientProxy().disconnected(), client);
// pull out the socket before deleting the client so
// we know which socket we no longer need
IDataSocket *socket = static_cast<IDataSocket *>(client->getStream());
delete client;
m_clientSockets.erase(socket);
delete socket;
break;
}
}
}
void ClientListener::cleanupListenSocket()
{
delete m_listen;
}
void ClientListener::cleanupClientSockets()
{
ClientSockets::iterator it;
for (it = m_clientSockets.begin(); it != m_clientSockets.end(); it++) {
delete *it;
}
m_clientSockets.clear();
}
| 7,568
|
C++
|
.cpp
| 218
| 31.40367
| 108
| 0.73803
|
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,533
|
ClientProxy1_7.cpp
|
deskflow_deskflow/src/lib/server/ClientProxy1_7.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 "server/ClientProxy1_7.h"
#include "base/Log.h"
#include "base/TMethodEventJob.h"
#include "deskflow/AppUtil.h"
#include "deskflow/ProtocolUtil.h"
#include "server/Server.h"
//
// ClientProxy1_7
//
ClientProxy1_7::ClientProxy1_7(const String &name, deskflow::IStream *stream, Server *server, IEventQueue *events)
: ClientProxy1_6(name, stream, server, events),
m_events(events)
{
}
void ClientProxy1_7::secureInputNotification(const String &app) const
{
LOG((CLOG_DEBUG2 "send secure input notification to \"%s\" %s", getName().c_str(), app.c_str()));
ProtocolUtil::writef(getStream(), kMsgDSecureInputNotification, &app);
}
| 1,343
|
C++
|
.cpp
| 35
| 36.428571
| 114
| 0.754601
|
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,534
|
ClientProxy1_5.cpp
|
deskflow_deskflow/src/lib/server/ClientProxy1_5.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 "server/ClientProxy1_5.h"
#include "base/Log.h"
#include "base/TMethodEventJob.h"
#include "deskflow/FileChunk.h"
#include "deskflow/ProtocolUtil.h"
#include "deskflow/StreamChunker.h"
#include "io/IStream.h"
#include "server/Server.h"
#include <sstream>
//
// ClientProxy1_5
//
ClientProxy1_5::ClientProxy1_5(const String &name, deskflow::IStream *stream, Server *server, IEventQueue *events)
: ClientProxy1_4(name, stream, server, events),
m_events(events)
{
m_events->adoptHandler(
m_events->forFile().keepAlive(), this,
new TMethodEventJob<ClientProxy1_3>(this, &ClientProxy1_3::handleKeepAlive, NULL)
);
}
ClientProxy1_5::~ClientProxy1_5()
{
m_events->removeHandler(m_events->forFile().keepAlive(), this);
}
void ClientProxy1_5::sendDragInfo(UInt32 fileCount, const char *info, size_t size)
{
String data(info, size);
ProtocolUtil::writef(getStream(), kMsgDDragInfo, fileCount, &data);
}
void ClientProxy1_5::fileChunkSending(UInt8 mark, char *data, size_t dataSize)
{
FileChunk::send(getStream(), mark, data, dataSize);
}
bool ClientProxy1_5::parseMessage(const UInt8 *code)
{
if (memcmp(code, kMsgDFileTransfer, 4) == 0) {
fileChunkReceived();
} else if (memcmp(code, kMsgDDragInfo, 4) == 0) {
dragInfoReceived();
} else {
return ClientProxy1_4::parseMessage(code);
}
return true;
}
void ClientProxy1_5::fileChunkReceived()
{
Server *server = getServer();
int result = FileChunk::assemble(getStream(), server->getReceivedFileData(), server->getExpectedFileSize());
if (result == kFinish) {
m_events->addEvent(Event(m_events->forFile().fileRecieveCompleted(), server));
} else if (result == kStart) {
if (server->getFakeDragFileList().size() > 0) {
String filename = server->getFakeDragFileList().at(0).getFilename();
LOG((CLOG_DEBUG "start receiving %s", filename.c_str()));
}
}
}
void ClientProxy1_5::dragInfoReceived()
{
// parse
UInt32 fileNum = 0;
String content;
ProtocolUtil::readf(getStream(), kMsgDDragInfo + 4, &fileNum, &content);
m_server->dragInfoReceived(fileNum, content);
}
| 2,812
|
C++
|
.cpp
| 82
| 31.695122
| 114
| 0.733604
|
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,535
|
ClientProxy.cpp
|
deskflow_deskflow/src/lib/server/ClientProxy.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 "server/ClientProxy.h"
#include "base/EventQueue.h"
#include "base/Log.h"
#include "deskflow/ProtocolUtil.h"
#include "io/IStream.h"
//
// ClientProxy
//
ClientProxy::ClientProxy(const String &name, deskflow::IStream *stream) : BaseClientProxy(name), m_stream(stream)
{
}
ClientProxy::~ClientProxy()
{
delete m_stream;
}
void ClientProxy::close(const char *msg)
{
LOG((CLOG_DEBUG1 "send close \"%s\" to \"%s\"", msg, getName().c_str()));
ProtocolUtil::writef(getStream(), msg);
// force the close to be sent before we return
getStream()->flush();
}
deskflow::IStream *ClientProxy::getStream() const
{
return m_stream;
}
void *ClientProxy::getEventTarget() const
{
return static_cast<IScreen *>(const_cast<ClientProxy *>(this));
}
| 1,492
|
C++
|
.cpp
| 47
| 29.914894
| 113
| 0.745125
|
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,536
|
BaseClientProxy.cpp
|
deskflow_deskflow/src/lib/server/BaseClientProxy.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2006 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 "server/BaseClientProxy.h"
//
// BaseClientProxy
//
BaseClientProxy::BaseClientProxy(const String &name) : m_name(name), m_x(0), m_y(0)
{
// do nothing
}
BaseClientProxy::~BaseClientProxy()
{
// do nothing
}
void BaseClientProxy::setJumpCursorPos(SInt32 x, SInt32 y)
{
m_x = x;
m_y = y;
}
void BaseClientProxy::getJumpCursorPos(SInt32 &x, SInt32 &y) const
{
x = m_x;
y = m_y;
}
String BaseClientProxy::getName() const
{
return m_name;
}
| 1,197
|
C++
|
.cpp
| 43
| 25.976744
| 83
| 0.743679
|
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,537
|
Config.cpp
|
deskflow_deskflow/src/lib/server/Config.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 "server/Config.h"
#include "base/IEventQueue.h"
#include "common/stdistream.h"
#include "common/stdostream.h"
#include "deskflow/KeyMap.h"
#include "deskflow/XDeskflow.h"
#include "deskflow/key_types.h"
#include "deskflow/option_types.h"
#include "net/XSocket.h"
#include "server/Server.h"
#include <cstdlib>
using namespace deskflow::string;
namespace deskflow::server {
const auto kSynergyProtocolOption = "synergy";
const auto kBarrierProtocolOption = "barrier";
//
// Config
//
Config::Config(IEventQueue *events) : m_inputFilter(events), m_hasLockToScreenAction(false), m_events(events)
{
// do nothing
}
Config::~Config()
{
// do nothing
}
bool Config::addScreen(const String &name)
{
// alias name must not exist
if (m_nameToCanonicalName.find(name) != m_nameToCanonicalName.end()) {
return false;
}
// add cell
m_map.insert(std::make_pair(name, Cell()));
// add name
m_nameToCanonicalName.insert(std::make_pair(name, name));
return true;
}
bool Config::renameScreen(const String &oldName, const String &newName)
{
// get canonical name and find cell
String oldCanonical = getCanonicalName(oldName);
CellMap::iterator index = m_map.find(oldCanonical);
if (index == m_map.end()) {
return false;
}
// accept if names are equal but replace with new name to maintain
// case. otherwise, the new name must not exist.
if (!CaselessCmp::equal(oldName, newName) && m_nameToCanonicalName.find(newName) != m_nameToCanonicalName.end()) {
return false;
}
// update cell
Cell tmpCell = index->second;
m_map.erase(index);
m_map.insert(std::make_pair(newName, tmpCell));
// update name
m_nameToCanonicalName.erase(oldCanonical);
m_nameToCanonicalName.insert(std::make_pair(newName, newName));
// update connections
Name oldNameObj(this, oldName);
for (index = m_map.begin(); index != m_map.end(); ++index) {
index->second.rename(oldNameObj, newName);
}
// update alias targets
if (CaselessCmp::equal(oldName, oldCanonical)) {
for (NameMap::iterator iter = m_nameToCanonicalName.begin(); iter != m_nameToCanonicalName.end(); ++iter) {
if (CaselessCmp::equal(iter->second, oldCanonical)) {
iter->second = newName;
}
}
}
return true;
}
void Config::removeScreen(const String &name)
{
// get canonical name and find cell
String canonical = getCanonicalName(name);
CellMap::iterator index = m_map.find(canonical);
if (index == m_map.end()) {
return;
}
// remove from map
m_map.erase(index);
// disconnect
Name nameObj(this, name);
for (index = m_map.begin(); index != m_map.end(); ++index) {
index->second.remove(nameObj);
}
// remove aliases (and canonical name)
for (NameMap::iterator iter = m_nameToCanonicalName.begin(); iter != m_nameToCanonicalName.end();) {
if (iter->second == canonical) {
m_nameToCanonicalName.erase(iter++);
} else {
++iter;
}
}
}
void Config::removeAllScreens()
{
m_map.clear();
m_nameToCanonicalName.clear();
}
bool Config::addAlias(const String &canonical, const String &alias)
{
// alias name must not exist
if (m_nameToCanonicalName.find(alias) != m_nameToCanonicalName.end()) {
return false;
}
// canonical name must be known
if (m_map.find(canonical) == m_map.end()) {
return false;
}
// insert alias
m_nameToCanonicalName.insert(std::make_pair(alias, canonical));
return true;
}
bool Config::removeAlias(const String &alias)
{
// must not be a canonical name
if (m_map.find(alias) != m_map.end()) {
return false;
}
// find alias
NameMap::iterator index = m_nameToCanonicalName.find(alias);
if (index == m_nameToCanonicalName.end()) {
return false;
}
// remove alias
m_nameToCanonicalName.erase(index);
return true;
}
bool Config::removeAliases(const String &canonical)
{
// must be a canonical name
if (m_map.find(canonical) == m_map.end()) {
return false;
}
// find and removing matching aliases
for (NameMap::iterator index = m_nameToCanonicalName.begin(); index != m_nameToCanonicalName.end();) {
if (index->second == canonical && index->first != canonical) {
m_nameToCanonicalName.erase(index++);
} else {
++index;
}
}
return true;
}
void Config::removeAllAliases()
{
// remove all names
m_nameToCanonicalName.clear();
// put the canonical names back in
for (CellMap::iterator index = m_map.begin(); index != m_map.end(); ++index) {
m_nameToCanonicalName.insert(std::make_pair(index->first, index->first));
}
}
bool Config::connect(
const String &srcName, EDirection srcSide, float srcStart, float srcEnd, const String &dstName, float dstStart,
float dstEnd
)
{
assert(srcSide >= kFirstDirection && srcSide <= kLastDirection);
// find source cell
CellMap::iterator index = m_map.find(getCanonicalName(srcName));
if (index == m_map.end()) {
return false;
}
// add link
CellEdge srcEdge(srcSide, Interval(srcStart, srcEnd));
CellEdge dstEdge(dstName, srcSide, Interval(dstStart, dstEnd));
return index->second.add(srcEdge, dstEdge);
}
bool Config::disconnect(const String &srcName, EDirection srcSide)
{
assert(srcSide >= kFirstDirection && srcSide <= kLastDirection);
// find source cell
CellMap::iterator index = m_map.find(srcName);
if (index == m_map.end()) {
return false;
}
// disconnect side
index->second.remove(srcSide);
return true;
}
bool Config::disconnect(const String &srcName, EDirection srcSide, float position)
{
assert(srcSide >= kFirstDirection && srcSide <= kLastDirection);
// find source cell
CellMap::iterator index = m_map.find(srcName);
if (index == m_map.end()) {
return false;
}
// disconnect side
index->second.remove(srcSide, position);
return true;
}
void Config::setDeskflowAddress(const NetworkAddress &addr)
{
m_deskflowAddress = addr;
}
bool Config::addOption(const String &name, OptionID option, OptionValue value)
{
// find options
ScreenOptions *options = NULL;
if (name.empty()) {
options = &m_globalOptions;
} else {
CellMap::iterator index = m_map.find(name);
if (index != m_map.end()) {
options = &index->second.m_options;
}
}
if (options == NULL) {
return false;
}
// add option
options->insert(std::make_pair(option, value));
return true;
}
bool Config::removeOption(const String &name, OptionID option)
{
// find options
ScreenOptions *options = NULL;
if (name.empty()) {
options = &m_globalOptions;
} else {
CellMap::iterator index = m_map.find(name);
if (index != m_map.end()) {
options = &index->second.m_options;
}
}
if (options == NULL) {
return false;
}
// remove option
options->erase(option);
return true;
}
bool Config::removeOptions(const String &name)
{
// find options
ScreenOptions *options = NULL;
if (name.empty()) {
options = &m_globalOptions;
} else {
CellMap::iterator index = m_map.find(name);
if (index != m_map.end()) {
options = &index->second.m_options;
}
}
if (options == NULL) {
return false;
}
// remove options
options->clear();
return true;
}
bool Config::isValidScreenName(const String &name) const
{
// name is valid if matches validname
// name ::= [_A-Za-z0-9] | [_A-Za-z0-9][-_A-Za-z0-9]*[_A-Za-z0-9]
// domain ::= . name
// validname ::= name domain*
// we also accept names ending in . because many OS X users have
// so misconfigured their systems.
// empty name is invalid
if (name.empty()) {
return false;
}
// check each dot separated part
String::size_type b = 0;
for (;;) {
// accept trailing .
if (b == name.size()) {
break;
}
// find end of part
String::size_type e = name.find('.', b);
if (e == String::npos) {
e = name.size();
}
// part may not be empty
if (e - b < 1) {
return false;
}
// check first and last characters
if (!(isalnum(name[b]) || name[b] == '_') || !(isalnum(name[e - 1]) || name[e - 1] == '_')) {
return false;
}
// check interior characters
for (String::size_type i = b; i < e; ++i) {
if (!isalnum(name[i]) && name[i] != '_' && name[i] != '-') {
return false;
}
}
// next part
if (e == name.size()) {
// no more parts
break;
}
b = e + 1;
}
return true;
}
Config::const_iterator Config::begin() const
{
return const_iterator(m_map.begin());
}
Config::const_iterator Config::end() const
{
return const_iterator(m_map.end());
}
Config::all_const_iterator Config::beginAll() const
{
return m_nameToCanonicalName.begin();
}
Config::all_const_iterator Config::endAll() const
{
return m_nameToCanonicalName.end();
}
bool Config::isScreen(const String &name) const
{
return (m_nameToCanonicalName.count(name) > 0);
}
bool Config::isCanonicalName(const String &name) const
{
return (!name.empty() && CaselessCmp::equal(getCanonicalName(name), name));
}
String Config::getCanonicalName(const String &name) const
{
NameMap::const_iterator index = m_nameToCanonicalName.find(name);
if (index == m_nameToCanonicalName.end()) {
return String();
} else {
return index->second;
}
}
String Config::getNeighbor(const String &srcName, EDirection srcSide, float position, float *positionOut) const
{
assert(srcSide >= kFirstDirection && srcSide <= kLastDirection);
// find source cell
CellMap::const_iterator index = m_map.find(getCanonicalName(srcName));
if (index == m_map.end()) {
return String();
}
// find edge
const CellEdge *srcEdge, *dstEdge;
if (!index->second.getLink(srcSide, position, srcEdge, dstEdge)) {
// no neighbor
return "";
} else {
// compute position on neighbor
if (positionOut != NULL) {
*positionOut = dstEdge->inverseTransform(srcEdge->transform(position));
}
// return neighbor's name
return getCanonicalName(dstEdge->getName());
}
}
bool Config::hasNeighbor(const String &srcName, EDirection srcSide) const
{
return hasNeighbor(srcName, srcSide, 0.0f, 1.0f);
}
bool Config::hasNeighbor(const String &srcName, EDirection srcSide, float start, float end) const
{
assert(srcSide >= kFirstDirection && srcSide <= kLastDirection);
// find source cell
CellMap::const_iterator index = m_map.find(getCanonicalName(srcName));
if (index == m_map.end()) {
return false;
}
return index->second.overlaps(CellEdge(srcSide, Interval(start, end)));
}
Config::link_const_iterator Config::beginNeighbor(const String &srcName) const
{
CellMap::const_iterator index = m_map.find(getCanonicalName(srcName));
assert(index != m_map.end());
return index->second.begin();
}
Config::link_const_iterator Config::endNeighbor(const String &srcName) const
{
CellMap::const_iterator index = m_map.find(getCanonicalName(srcName));
assert(index != m_map.end());
return index->second.end();
}
const NetworkAddress &Config::getDeskflowAddress() const
{
return m_deskflowAddress;
}
const Config::ScreenOptions *Config::getOptions(const String &name) const
{
// find options
const ScreenOptions *options = NULL;
if (name.empty()) {
options = &m_globalOptions;
} else {
CellMap::const_iterator index = m_map.find(name);
if (index != m_map.end()) {
options = &index->second.m_options;
}
}
// return options
return options;
}
bool Config::hasLockToScreenAction() const
{
return m_hasLockToScreenAction;
}
bool Config::operator==(const Config &x) const
{
if (m_deskflowAddress != x.m_deskflowAddress) {
return false;
}
if (m_map.size() != x.m_map.size()) {
return false;
}
if (m_nameToCanonicalName.size() != x.m_nameToCanonicalName.size()) {
return false;
}
// compare global options
if (m_globalOptions != x.m_globalOptions) {
return false;
}
auto index2map = x.m_map.cbegin();
for (auto const &index1 : m_map) {
// compare names
if (!CaselessCmp::equal(index1.first, index2map->first)) {
return false;
}
// compare cells
if (index1.second != index2map->second) {
return false;
}
++index2map;
}
auto index2 = x.m_nameToCanonicalName.cbegin();
for (auto const &index1 : m_nameToCanonicalName) {
if (index2 == x.m_nameToCanonicalName.cend()) {
return false; // second source ended
}
if (!CaselessCmp::equal(index1.first, index2->first) || !CaselessCmp::equal(index1.second, index2->second)) {
return false;
}
++index2;
}
// compare input filters
if (m_inputFilter != x.m_inputFilter) {
return false;
}
return true;
}
bool Config::operator!=(const Config &x) const
{
return !operator==(x);
}
void Config::read(ConfigReadContext &context)
{
Config tmp(m_events);
while (context.getStream()) {
tmp.readSection(context);
}
*this = tmp;
}
const char *Config::dirName(EDirection dir)
{
static const char *s_name[] = {"left", "right", "up", "down"};
assert(dir >= kFirstDirection && dir <= kLastDirection);
return s_name[dir - kFirstDirection];
}
InputFilter *Config::getInputFilter()
{
return &m_inputFilter;
}
String Config::formatInterval(const Interval &x)
{
if (x.first == 0.0f && x.second == 1.0f) {
return "";
}
return deskflow::string::sprintf("(%d,%d)", (int)(x.first * 100.0f + 0.5f), (int)(x.second * 100.0f + 0.5f));
}
String Config::getClientAddress() const
{
return m_ClientAddress;
}
bool Config::isClientMode() const
{
return (!m_ClientAddress.empty());
}
void Config::readSection(ConfigReadContext &s)
{
static const char s_section[] = "section:";
static const char s_options[] = "options";
static const char s_screens[] = "screens";
static const char s_links[] = "links";
static const char s_aliases[] = "aliases";
String line;
if (!s.readLine(line)) {
// no more sections
return;
}
// should be a section header
if (line.find(s_section) != 0) {
throw XConfigRead(s, "found data outside section");
}
// get section name
String::size_type i = line.find_first_not_of(" \t", sizeof(s_section) - 1);
if (i == String::npos) {
throw XConfigRead(s, "section name is missing");
}
String name = line.substr(i);
i = name.find_first_of(" \t");
if (i != String::npos) {
throw XConfigRead(s, "unexpected data after section name");
}
// read section
if (name == s_options) {
readSectionOptions(s);
} else if (name == s_screens) {
readSectionScreens(s);
} else if (name == s_links) {
readSectionLinks(s);
} else if (name == s_aliases) {
readSectionAliases(s);
} else {
throw XConfigRead(s, "unknown section name \"%{1}\"", name);
}
}
void Config::readSectionOptions(ConfigReadContext &s)
{
String line;
while (s.readLine(line)) {
// check for end of section
if (line == "end") {
return;
}
// parse argument: `nameAndArgs = [values][;[values]]'
// nameAndArgs := <name>[(arg[,...])]
// values := valueAndArgs[,valueAndArgs]...
// valueAndArgs := <value>[(arg[,...])]
String::size_type i = 0;
String name, value;
ConfigReadContext::ArgList nameArgs, valueArgs;
s.parseNameWithArgs("name", line, "=", i, name, nameArgs);
++i;
s.parseNameWithArgs("value", line, ",;\n", i, value, valueArgs);
bool handled = true;
if (name == "address") {
try {
m_deskflowAddress = NetworkAddress(value, kDefaultPort);
m_deskflowAddress.resolve();
} catch (XSocketAddress &e) {
throw XConfigRead(s, String("invalid address argument ") + e.what());
}
} else if (name == "heartbeat") {
addOption("", kOptionHeartbeat, s.parseInt(value));
} else if (name == "protocol") {
addOption("", kOptionProtocol, s.parseProtocol(value));
} else if (name == "switchCorners") {
addOption("", kOptionScreenSwitchCorners, s.parseCorners(value));
} else if (name == "switchCornerSize") {
addOption("", kOptionScreenSwitchCornerSize, s.parseInt(value));
} else if (name == "switchDelay") {
addOption("", kOptionScreenSwitchDelay, s.parseInt(value));
} else if (name == "switchDoubleTap") {
addOption("", kOptionScreenSwitchTwoTap, s.parseInt(value));
} else if (name == "switchNeedsShift") {
addOption("", kOptionScreenSwitchNeedsShift, s.parseBoolean(value));
} else if (name == "switchNeedsControl") {
addOption("", kOptionScreenSwitchNeedsControl, s.parseBoolean(value));
} else if (name == "switchNeedsAlt") {
addOption("", kOptionScreenSwitchNeedsAlt, s.parseBoolean(value));
} else if (name == "relativeMouseMoves") {
addOption("", kOptionRelativeMouseMoves, s.parseBoolean(value));
} else if (name == "win32KeepForeground") {
addOption("", kOptionWin32KeepForeground, s.parseBoolean(value));
} else if (name == "disableLockToScreen") {
addOption("", kOptionDisableLockToScreen, s.parseBoolean(value));
} else if (name == "clipboardSharing") {
addOption("", kOptionClipboardSharing, s.parseBoolean(value));
} else if (name == "clipboardSharingSize") {
addOption("", kOptionClipboardSharingSize, s.parseInt(value));
} else if (name == "clientAddress") {
m_ClientAddress = value;
} else {
handled = false;
}
if (handled) {
// make sure handled options aren't followed by more values
if (i < line.size() && (line[i] == ',' || line[i] == ';')) {
throw XConfigRead(s, "to many arguments to %s", name.c_str());
}
} else {
// make filter rule
InputFilter::Rule rule(parseCondition(s, name, nameArgs));
// save first action (if any)
if (!value.empty() || line[i] != ';') {
parseAction(s, value, valueArgs, rule, true);
}
// get remaining activate actions
while (i < line.length() && line[i] != ';') {
++i;
s.parseNameWithArgs("value", line, ",;\n", i, value, valueArgs);
parseAction(s, value, valueArgs, rule, true);
}
// get deactivate actions
if (i < line.length() && line[i] == ';') {
// allow trailing ';'
i = line.find_first_not_of(" \t", i + 1);
if (i == String::npos) {
i = line.length();
} else {
--i;
}
// get actions
while (i < line.length()) {
++i;
s.parseNameWithArgs("value", line, ",\n", i, value, valueArgs);
parseAction(s, value, valueArgs, rule, false);
}
}
// add rule
m_inputFilter.addFilterRule(rule);
}
}
throw XConfigRead(s, "unexpected end of options section");
}
void Config::readSectionScreens(ConfigReadContext &s)
{
String line;
String screen;
while (s.readLine(line)) {
// check for end of section
if (line == "end") {
return;
}
// see if it's the next screen
if (line[line.size() - 1] == ':') {
// strip :
screen = line.substr(0, line.size() - 1);
// verify validity of screen name
if (!isValidScreenName(screen)) {
throw XConfigRead(s, "invalid screen name \"%{1}\"", screen);
}
// add the screen to the configuration
if (!addScreen(screen)) {
throw XConfigRead(s, "duplicate screen name \"%{1}\"", screen);
}
} else if (screen.empty()) {
throw XConfigRead(s, "argument before first screen");
} else {
// parse argument: `<name>=<value>'
String::size_type i = line.find_first_of(" \t=");
if (i == 0) {
throw XConfigRead(s, "missing argument name");
}
if (i == String::npos) {
throw XConfigRead(s, "missing =");
}
String name = line.substr(0, i);
i = line.find_first_not_of(" \t", i);
if (i == String::npos || line[i] != '=') {
throw XConfigRead(s, "missing =");
}
i = line.find_first_not_of(" \t", i + 1);
String value;
if (i != String::npos) {
value = line.substr(i);
}
// handle argument
if (name == "halfDuplexCapsLock") {
addOption(screen, kOptionHalfDuplexCapsLock, s.parseBoolean(value));
} else if (name == "halfDuplexNumLock") {
addOption(screen, kOptionHalfDuplexNumLock, s.parseBoolean(value));
} else if (name == "halfDuplexScrollLock") {
addOption(screen, kOptionHalfDuplexScrollLock, s.parseBoolean(value));
} else if (name == "shift") {
addOption(screen, kOptionModifierMapForShift, s.parseModifierKey(value));
} else if (name == "ctrl") {
addOption(screen, kOptionModifierMapForControl, s.parseModifierKey(value));
} else if (name == "alt") {
addOption(screen, kOptionModifierMapForAlt, s.parseModifierKey(value));
} else if (name == "altgr") {
addOption(screen, kOptionModifierMapForAltGr, s.parseModifierKey(value));
} else if (name == "meta") {
addOption(screen, kOptionModifierMapForMeta, s.parseModifierKey(value));
} else if (name == "super") {
addOption(screen, kOptionModifierMapForSuper, s.parseModifierKey(value));
} else if (name == "xtestIsXineramaUnaware") {
addOption(screen, kOptionXTestXineramaUnaware, s.parseBoolean(value));
} else if (name == "switchCorners") {
addOption(screen, kOptionScreenSwitchCorners, s.parseCorners(value));
} else if (name == "switchCornerSize") {
addOption(screen, kOptionScreenSwitchCornerSize, s.parseInt(value));
} else if (name == "preserveFocus") {
addOption(screen, kOptionScreenPreserveFocus, s.parseBoolean(value));
} else {
// unknown argument
throw XConfigRead(s, "unknown argument \"%{1}\"", name);
}
}
}
throw XConfigRead(s, "unexpected end of screens section");
}
void Config::readSectionLinks(ConfigReadContext &s)
{
String line;
String screen;
while (s.readLine(line)) {
// check for end of section
if (line == "end") {
return;
}
// see if it's the next screen
if (line[line.size() - 1] == ':') {
// strip :
screen = line.substr(0, line.size() - 1);
// verify we know about the screen
if (!isScreen(screen)) {
throw XConfigRead(s, "unknown screen name \"%{1}\"", screen);
}
if (!isCanonicalName(screen)) {
throw XConfigRead(s, "cannot use screen name alias here");
}
} else if (screen.empty()) {
throw XConfigRead(s, "argument before first screen");
} else {
// parse argument: `<name>[(<s0>,<e0>)]=<value>[(<s1>,<e1>)]'
// the stuff in brackets is optional. interval values must be
// in the range [0,100] and start < end. if not given the
// interval is taken to be (0,100).
String::size_type i = 0;
String side, dstScreen, srcArgString, dstArgString;
ConfigReadContext::ArgList srcArgs, dstArgs;
s.parseNameWithArgs("link", line, "=", i, side, srcArgs);
++i;
s.parseNameWithArgs("screen", line, "", i, dstScreen, dstArgs);
Interval srcInterval(s.parseInterval(srcArgs));
Interval dstInterval(s.parseInterval(dstArgs));
// handle argument
EDirection dir;
if (side == "left") {
dir = kLeft;
} else if (side == "right") {
dir = kRight;
} else if (side == "up") {
dir = kTop;
} else if (side == "down") {
dir = kBottom;
} else {
// unknown argument
throw XConfigRead(s, "unknown side \"%{1}\" in link", side);
}
if (!isScreen(dstScreen)) {
throw XConfigRead(s, "unknown screen name \"%{1}\"", dstScreen);
}
if (!connect(
screen, dir, srcInterval.first, srcInterval.second, dstScreen, dstInterval.first, dstInterval.second
)) {
throw XConfigRead(s, "overlapping range");
}
}
}
throw XConfigRead(s, "unexpected end of links section");
}
void Config::readSectionAliases(ConfigReadContext &s)
{
String line;
String screen;
while (s.readLine(line)) {
// check for end of section
if (line == "end") {
return;
}
// see if it's the next screen
if (line[line.size() - 1] == ':') {
// strip :
screen = line.substr(0, line.size() - 1);
// verify we know about the screen
if (!isScreen(screen)) {
throw XConfigRead(s, "unknown screen name \"%{1}\"", screen);
}
if (!isCanonicalName(screen)) {
throw XConfigRead(s, "cannot use screen name alias here");
}
} else if (screen.empty()) {
throw XConfigRead(s, "argument before first screen");
} else {
// verify validity of screen name
if (!isValidScreenName(line)) {
throw XConfigRead(s, "invalid screen alias \"%{1}\"", line);
}
// add alias
if (!addAlias(screen, line)) {
throw XConfigRead(s, "alias \"%{1}\" is already used", line);
}
}
}
throw XConfigRead(s, "unexpected end of aliases section");
}
InputFilter::Condition *
Config::parseCondition(ConfigReadContext &s, const String &name, const std::vector<String> &args)
{
if (name == "keystroke") {
if (args.size() != 1) {
throw XConfigRead(s, "syntax for condition: keystroke(modifiers+key)");
}
IPlatformScreen::KeyInfo *keyInfo = s.parseKeystroke(args[0]);
return new InputFilter::KeystrokeCondition(m_events, keyInfo);
}
if (name == "mousebutton") {
if (args.size() != 1) {
throw XConfigRead(s, "syntax for condition: mousebutton(modifiers+button)");
}
IPlatformScreen::ButtonInfo *mouseInfo = s.parseMouse(args[0]);
return new InputFilter::MouseButtonCondition(m_events, mouseInfo);
}
if (name == "connect") {
if (args.size() != 1) {
throw XConfigRead(s, "syntax for condition: connect([screen])");
}
String screen = args[0];
if (isScreen(screen)) {
screen = getCanonicalName(screen);
} else if (!screen.empty()) {
throw XConfigRead(s, "unknown screen name \"%{1}\" in connect", screen);
}
return new InputFilter::ScreenConnectedCondition(m_events, screen);
}
throw XConfigRead(s, "unknown argument \"%{1}\"", name);
}
void Config::parseAction(
ConfigReadContext &s, const String &name, const std::vector<String> &args, InputFilter::Rule &rule, bool activate
)
{
InputFilter::Action *action;
if (name == "keystroke" || name == "keyDown" || name == "keyUp") {
if (args.size() < 1 || args.size() > 2) {
throw XConfigRead(s, "syntax for action: keystroke(modifiers+key[,screens])");
}
IPlatformScreen::KeyInfo *keyInfo;
if (args.size() == 1) {
keyInfo = s.parseKeystroke(args[0]);
} else {
std::set<String> screens;
parseScreens(s, args[1], screens);
keyInfo = s.parseKeystroke(args[0], screens);
}
if (name == "keystroke") {
IPlatformScreen::KeyInfo *keyInfo2 = IKeyState::KeyInfo::alloc(*keyInfo);
action = new InputFilter::KeystrokeAction(m_events, keyInfo2, true);
rule.adoptAction(action, true);
action = new InputFilter::KeystrokeAction(m_events, keyInfo, false);
activate = false;
} else if (name == "keyDown") {
action = new InputFilter::KeystrokeAction(m_events, keyInfo, true);
} else {
action = new InputFilter::KeystrokeAction(m_events, keyInfo, false);
}
}
else if (name == "mousebutton" || name == "mouseDown" || name == "mouseUp") {
if (args.size() != 1) {
throw XConfigRead(s, "syntax for action: mousebutton(modifiers+button)");
}
IPlatformScreen::ButtonInfo *mouseInfo = s.parseMouse(args[0]);
if (name == "mousebutton") {
IPlatformScreen::ButtonInfo *mouseInfo2 = IPlatformScreen::ButtonInfo::alloc(*mouseInfo);
action = new InputFilter::MouseButtonAction(m_events, mouseInfo2, true);
rule.adoptAction(action, true);
action = new InputFilter::MouseButtonAction(m_events, mouseInfo, false);
activate = false;
} else if (name == "mouseDown") {
action = new InputFilter::MouseButtonAction(m_events, mouseInfo, true);
} else {
action = new InputFilter::MouseButtonAction(m_events, mouseInfo, false);
}
}
/* XXX -- not supported
else if (name == "modifier") {
if (args.size() != 1) {
throw XConfigRead(s, "syntax for action:
modifier(modifiers)");
}
KeyModifierMask mask = s.parseModifier(args[0]);
action = new InputFilter::ModifierAction(mask, ~mask);
}
*/
else if (name == "switchToScreen") {
if (args.size() != 1) {
throw XConfigRead(s, "syntax for action: switchToScreen(name)");
}
String screen = args[0];
if (isScreen(screen)) {
screen = getCanonicalName(screen);
} else if (!screen.empty()) {
throw XConfigRead(s, "unknown screen name in switchToScreen");
}
action = new InputFilter::SwitchToScreenAction(m_events, screen);
}
else if (name == "switchInDirection") {
if (args.size() != 1) {
throw XConfigRead(s, "syntax for action: switchInDirection(<left|right|up|down>)");
}
EDirection direction;
if (args[0] == "left") {
direction = kLeft;
} else if (args[0] == "right") {
direction = kRight;
} else if (args[0] == "up") {
direction = kTop;
} else if (args[0] == "down") {
direction = kBottom;
} else {
throw XConfigRead(s, "unknown direction \"%{1}\" in switchToScreen", args[0]);
}
action = new InputFilter::SwitchInDirectionAction(m_events, direction);
}
else if (name == "lockCursorToScreen") {
if (args.size() > 1) {
throw XConfigRead(s, "syntax for action: lockCursorToScreen([{off|on|toggle}])");
}
InputFilter::LockCursorToScreenAction::Mode mode = InputFilter::LockCursorToScreenAction::kToggle;
if (args.size() == 1) {
if (args[0] == "off") {
mode = InputFilter::LockCursorToScreenAction::kOff;
} else if (args[0] == "on") {
mode = InputFilter::LockCursorToScreenAction::kOn;
} else if (args[0] == "toggle") {
mode = InputFilter::LockCursorToScreenAction::kToggle;
} else {
throw XConfigRead(s, "syntax for action: lockCursorToScreen([{off|on|toggle}])");
}
}
if (mode != InputFilter::LockCursorToScreenAction::kOff) {
m_hasLockToScreenAction = true;
}
action = new InputFilter::LockCursorToScreenAction(m_events, mode);
}
else if (name == "restartServer") {
if (args.size() > 1) {
throw XConfigRead(s, "syntax for action: restartServer([{{restart}}])");
}
InputFilter::RestartServer::Mode mode = InputFilter::RestartServer::restart;
if (args.size() == 1) {
if (args[0] == "restart") {
mode = InputFilter::RestartServer::restart;
} else {
throw XConfigRead(s, "syntax for action: restartServer([{restart}])");
}
}
action = new InputFilter::RestartServer(m_events, mode);
}
else if (name == "keyboardBroadcast") {
if (args.size() > 2) {
throw XConfigRead(s, "syntax for action: keyboardBroadcast([{off|on|toggle}[,screens]])");
}
InputFilter::KeyboardBroadcastAction::Mode mode = InputFilter::KeyboardBroadcastAction::kToggle;
if (args.size() >= 1) {
if (args[0] == "off") {
mode = InputFilter::KeyboardBroadcastAction::kOff;
} else if (args[0] == "on") {
mode = InputFilter::KeyboardBroadcastAction::kOn;
} else if (args[0] == "toggle") {
mode = InputFilter::KeyboardBroadcastAction::kToggle;
} else {
throw XConfigRead(
s, "syntax for action: "
"keyboardBroadcast([{off|on|toggle}[,screens]])"
);
}
}
std::set<String> screens;
if (args.size() >= 2) {
parseScreens(s, args[1], screens);
}
action = new InputFilter::KeyboardBroadcastAction(m_events, mode, screens);
}
else {
throw XConfigRead(s, "unknown action argument \"%{1}\"", name);
}
rule.adoptAction(action, activate);
}
void Config::parseScreens(ConfigReadContext &c, const String &s, std::set<String> &screens) const
{
screens.clear();
String::size_type i = 0;
while (i < s.size()) {
// find end of next screen name
String::size_type j = s.find(':', i);
if (j == String::npos) {
j = s.size();
}
// extract name
String rawName;
i = s.find_first_not_of(" \t", i);
if (i < j) {
rawName = s.substr(i, s.find_last_not_of(" \t", j - 1) - i + 1);
}
// add name
if (rawName == "*") {
screens.insert("*");
} else if (!rawName.empty()) {
String name = getCanonicalName(rawName);
if (name.empty()) {
throw XConfigRead(c, "unknown screen name \"%{1}\"", rawName);
}
screens.insert(name);
}
// next
i = j + 1;
}
}
const char *Config::getOptionName(OptionID id)
{
if (id == kOptionHalfDuplexCapsLock) {
return "halfDuplexCapsLock";
}
if (id == kOptionHalfDuplexNumLock) {
return "halfDuplexNumLock";
}
if (id == kOptionHalfDuplexScrollLock) {
return "halfDuplexScrollLock";
}
if (id == kOptionModifierMapForShift) {
return "shift";
}
if (id == kOptionModifierMapForControl) {
return "ctrl";
}
if (id == kOptionModifierMapForAlt) {
return "alt";
}
if (id == kOptionModifierMapForAltGr) {
return "altgr";
}
if (id == kOptionModifierMapForMeta) {
return "meta";
}
if (id == kOptionModifierMapForSuper) {
return "super";
}
if (id == kOptionHeartbeat) {
return "heartbeat";
}
if (id == kOptionScreenSwitchCorners) {
return "switchCorners";
}
if (id == kOptionScreenSwitchCornerSize) {
return "switchCornerSize";
}
if (id == kOptionScreenSwitchDelay) {
return "switchDelay";
}
if (id == kOptionScreenSwitchTwoTap) {
return "switchDoubleTap";
}
if (id == kOptionScreenSwitchNeedsShift) {
return "switchNeedsShift";
}
if (id == kOptionScreenSwitchNeedsControl) {
return "switchNeedsControl";
}
if (id == kOptionScreenSwitchNeedsAlt) {
return "switchNeedsAlt";
}
if (id == kOptionXTestXineramaUnaware) {
return "xtestIsXineramaUnaware";
}
if (id == kOptionRelativeMouseMoves) {
return "relativeMouseMoves";
}
if (id == kOptionWin32KeepForeground) {
return "win32KeepForeground";
}
if (id == kOptionScreenPreserveFocus) {
return "preserveFocus";
}
if (id == kOptionDisableLockToScreen) {
return "disableLockToScreen";
}
if (id == kOptionClipboardSharing) {
return "clipboardSharing";
}
if (id == kOptionClipboardSharingSize) {
return "clipboardSharingSize";
}
return NULL;
}
String Config::getOptionValue(OptionID id, OptionValue value)
{
if (id == kOptionHalfDuplexCapsLock || id == kOptionHalfDuplexNumLock || id == kOptionHalfDuplexScrollLock ||
id == kOptionScreenSwitchNeedsShift || id == kOptionScreenSwitchNeedsControl ||
id == kOptionScreenSwitchNeedsAlt || id == kOptionXTestXineramaUnaware || id == kOptionRelativeMouseMoves ||
id == kOptionWin32KeepForeground || id == kOptionScreenPreserveFocus || id == kOptionClipboardSharing ||
id == kOptionClipboardSharingSize) {
return (value != 0) ? "true" : "false";
}
if (id == kOptionModifierMapForShift || id == kOptionModifierMapForControl || id == kOptionModifierMapForAlt ||
id == kOptionModifierMapForAltGr || id == kOptionModifierMapForMeta || id == kOptionModifierMapForSuper) {
switch (value) {
case kKeyModifierIDShift:
return "shift";
case kKeyModifierIDControl:
return "ctrl";
case kKeyModifierIDAlt:
return "alt";
case kKeyModifierIDAltGr:
return "altgr";
case kKeyModifierIDMeta:
return "meta";
case kKeyModifierIDSuper:
return "super";
default:
return "none";
}
}
if (id == kOptionHeartbeat || id == kOptionScreenSwitchCornerSize || id == kOptionScreenSwitchDelay ||
id == kOptionScreenSwitchTwoTap) {
return deskflow::string::sprintf("%d", value);
}
if (id == kOptionScreenSwitchCorners) {
std::string result("none");
if ((value & kTopLeftMask) != 0) {
result += " +top-left";
}
if ((value & kTopRightMask) != 0) {
result += " +top-right";
}
if ((value & kBottomLeftMask) != 0) {
result += " +bottom-left";
}
if ((value & kBottomRightMask) != 0) {
result += " +bottom-right";
}
return result;
}
if (id == kOptionProtocol) {
using enum ENetworkProtocol;
const auto enumValue = static_cast<ENetworkProtocol>(value);
if (enumValue == kSynergy) {
return kSynergyProtocolOption;
} else if (enumValue == kBarrier) {
return kBarrierProtocolOption;
} else {
throw XInvalidProtocol();
}
}
return "";
}
//
// Config::Name
//
Config::Name::Name(Config *config, const String &name) : m_config(config), m_name(config->getCanonicalName(name))
{
// do nothing
}
bool Config::Name::operator==(const String &name) const
{
String canonical = m_config->getCanonicalName(name);
return CaselessCmp::equal(canonical, m_name);
}
//
// Config::CellEdge
//
Config::CellEdge::CellEdge(EDirection side, float position)
{
init("", side, Interval(position, position));
}
Config::CellEdge::CellEdge(EDirection side, const Interval &interval)
{
assert(interval.first >= 0.0f);
assert(interval.second <= 1.0f);
assert(interval.first < interval.second);
init("", side, interval);
}
Config::CellEdge::CellEdge(const String &name, EDirection side, const Interval &interval)
{
assert(interval.first >= 0.0f);
assert(interval.second <= 1.0f);
assert(interval.first < interval.second);
init(name, side, interval);
}
Config::CellEdge::~CellEdge()
{
// do nothing
}
void Config::CellEdge::init(const String &name, EDirection side, const Interval &interval)
{
assert(side != kNoDirection);
m_name = name;
m_side = side;
m_interval = interval;
}
Config::Interval Config::CellEdge::getInterval() const
{
return m_interval;
}
void Config::CellEdge::setName(const String &newName)
{
m_name = newName;
}
String Config::CellEdge::getName() const
{
return m_name;
}
EDirection Config::CellEdge::getSide() const
{
return m_side;
}
bool Config::CellEdge::overlaps(const CellEdge &edge) const
{
const Interval &x = m_interval;
const Interval &y = edge.m_interval;
if (m_side != edge.m_side) {
return false;
}
return (x.first >= y.first && x.first < y.second) || (x.second > y.first && x.second <= y.second) ||
(y.first >= x.first && y.first < x.second) || (y.second > x.first && y.second <= x.second);
}
bool Config::CellEdge::isInside(float x) const
{
return (x >= m_interval.first && x < m_interval.second);
}
float Config::CellEdge::transform(float x) const
{
return (x - m_interval.first) / (m_interval.second - m_interval.first);
}
float Config::CellEdge::inverseTransform(float x) const
{
return x * (m_interval.second - m_interval.first) + m_interval.first;
}
bool Config::CellEdge::operator<(const CellEdge &o) const
{
if (static_cast<int>(m_side) < static_cast<int>(o.m_side)) {
return true;
} else if (static_cast<int>(m_side) > static_cast<int>(o.m_side)) {
return false;
}
return (m_interval.first < o.m_interval.first);
}
bool Config::CellEdge::operator==(const CellEdge &x) const
{
return (m_side == x.m_side && m_interval == x.m_interval);
}
bool Config::CellEdge::operator!=(const CellEdge &x) const
{
return !operator==(x);
}
//
// Config::Cell
//
bool Config::Cell::add(const CellEdge &src, const CellEdge &dst)
{
// cannot add an edge that overlaps other existing edges but we
// can exactly replace an edge.
if (!hasEdge(src) && overlaps(src)) {
return false;
}
m_neighbors.erase(src);
m_neighbors.insert(std::make_pair(src, dst));
return true;
}
void Config::Cell::remove(EDirection side)
{
for (EdgeLinks::iterator j = m_neighbors.begin(); j != m_neighbors.end();) {
if (j->first.getSide() == side) {
m_neighbors.erase(j++);
} else {
++j;
}
}
}
void Config::Cell::remove(EDirection side, float position)
{
for (EdgeLinks::iterator j = m_neighbors.begin(); j != m_neighbors.end(); ++j) {
if (j->first.getSide() == side && j->first.isInside(position)) {
m_neighbors.erase(j);
break;
}
}
}
void Config::Cell::remove(const Name &name)
{
for (EdgeLinks::iterator j = m_neighbors.begin(); j != m_neighbors.end();) {
if (name == j->second.getName()) {
m_neighbors.erase(j++);
} else {
++j;
}
}
}
void Config::Cell::rename(const Name &oldName, const String &newName)
{
for (EdgeLinks::iterator j = m_neighbors.begin(); j != m_neighbors.end(); ++j) {
if (oldName == j->second.getName()) {
j->second.setName(newName);
}
}
}
bool Config::Cell::hasEdge(const CellEdge &edge) const
{
EdgeLinks::const_iterator i = m_neighbors.find(edge);
return (i != m_neighbors.end() && i->first == edge);
}
bool Config::Cell::overlaps(const CellEdge &edge) const
{
EdgeLinks::const_iterator i = m_neighbors.upper_bound(edge);
if (i != m_neighbors.end() && i->first.overlaps(edge)) {
return true;
}
if (i != m_neighbors.begin() && (--i)->first.overlaps(edge)) {
return true;
}
return false;
}
bool Config::Cell::getLink(EDirection side, float position, const CellEdge *&src, const CellEdge *&dst) const
{
CellEdge edge(side, position);
EdgeLinks::const_iterator i = m_neighbors.upper_bound(edge);
if (i == m_neighbors.begin()) {
return false;
}
--i;
if (i->first.getSide() == side && i->first.isInside(position)) {
src = &i->first;
dst = &i->second;
return true;
}
return false;
}
bool Config::Cell::operator==(const Cell &x) const
{
// compare options
if (m_options != x.m_options) {
return false;
}
// compare links
if (m_neighbors.size() != x.m_neighbors.size()) {
return false;
}
auto index2neighbors = x.m_neighbors.cbegin();
for (auto const &index1 : m_neighbors) {
if (index1.first != index2neighbors->first) {
return false;
}
if (index1.second != index2neighbors->second) {
return false;
}
// operator== doesn't compare names. only compare destination
// names.
if (!CaselessCmp::equal(index1.second.getName(), index2neighbors->second.getName())) {
return false;
}
++index2neighbors;
}
return true;
}
bool Config::Cell::operator!=(const Cell &x) const
{
return !operator==(x);
}
Config::Cell::const_iterator Config::Cell::begin() const
{
return m_neighbors.begin();
}
Config::Cell::const_iterator Config::Cell::end() const
{
return m_neighbors.end();
}
//
// Config I/O
//
std::istream &operator>>(std::istream &s, Config &config)
{
ConfigReadContext context(s);
config.read(context);
return s;
}
std::ostream &operator<<(std::ostream &s, const Config &config)
{
// screens section
s << "section: screens" << std::endl;
for (Config::const_iterator screen = config.begin(); screen != config.end(); ++screen) {
s << "\t" << screen->c_str() << ":" << std::endl;
const Config::ScreenOptions *options = config.getOptions(*screen);
if (options != NULL && options->size() > 0) {
for (Config::ScreenOptions::const_iterator option = options->begin(); option != options->end(); ++option) {
const char *name = Config::getOptionName(option->first);
String value = Config::getOptionValue(option->first, option->second);
if (name != NULL && !value.empty()) {
s << "\t\t" << name << " = " << value << std::endl;
}
}
}
}
s << "end" << std::endl;
// links section
String neighbor;
s << "section: links" << std::endl;
for (Config::const_iterator screen = config.begin(); screen != config.end(); ++screen) {
s << "\t" << screen->c_str() << ":" << std::endl;
for (Config::link_const_iterator link = config.beginNeighbor(*screen), nend = config.endNeighbor(*screen);
link != nend; ++link) {
s << "\t\t" << Config::dirName(link->first.getSide()) << Config::formatInterval(link->first.getInterval())
<< " = " << link->second.getName().c_str() << Config::formatInterval(link->second.getInterval()) << std::endl;
}
}
s << "end" << std::endl;
// aliases section (if there are any)
if (config.m_map.size() != config.m_nameToCanonicalName.size()) {
// map canonical to alias
typedef std::multimap<String, String, CaselessCmp> CMNameMap;
CMNameMap aliases;
for (Config::NameMap::const_iterator index = config.m_nameToCanonicalName.begin();
index != config.m_nameToCanonicalName.end(); ++index) {
if (index->first != index->second) {
aliases.insert(std::make_pair(index->second, index->first));
}
}
// dump it
String screen;
s << "section: aliases" << std::endl;
for (CMNameMap::const_iterator index = aliases.begin(); index != aliases.end(); ++index) {
if (index->first != screen) {
screen = index->first;
s << "\t" << screen.c_str() << ":" << std::endl;
}
s << "\t\t" << index->second.c_str() << std::endl;
}
s << "end" << std::endl;
}
// options section
s << "section: options" << std::endl;
const Config::ScreenOptions *options = config.getOptions("");
if (options != NULL && options->size() > 0) {
for (Config::ScreenOptions::const_iterator option = options->begin(); option != options->end(); ++option) {
const char *name = Config::getOptionName(option->first);
String value = Config::getOptionValue(option->first, option->second);
if (name != NULL && !value.empty()) {
s << "\t" << name << " = " << value << std::endl;
}
}
}
if (config.m_deskflowAddress.isValid()) {
s << "\taddress = " << config.m_deskflowAddress.getHostname().c_str() << std::endl;
}
s << config.m_inputFilter.format("\t");
s << "end" << std::endl;
return s;
}
//
// ConfigReadContext
//
ConfigReadContext::ConfigReadContext(std::istream &s, SInt32 firstLine) : m_stream(s), m_line(firstLine - 1)
{
// do nothing
}
ConfigReadContext::~ConfigReadContext()
{
// do nothing
}
bool ConfigReadContext::readLine(String &line)
{
++m_line;
while (std::getline(m_stream, line)) {
// strip leading whitespace
String::size_type i = line.find_first_not_of(" \t");
if (i != String::npos) {
line.erase(0, i);
}
// strip comments and then trailing whitespace
i = line.find('#');
if (i != String::npos) {
line.erase(i);
}
i = line.find_last_not_of(" \r\t");
if (i != String::npos) {
line.erase(i + 1);
}
// return non empty line
if (!line.empty()) {
// make sure there are no invalid characters
for (i = 0; i < line.length(); ++i) {
if (!isgraph(line[i]) && line[i] != ' ' && line[i] != '\t') {
throw XConfigRead(*this, "invalid character %{1}", deskflow::string::sprintf("%#2x", line[i]));
}
}
return true;
}
// next line
++m_line;
}
return false;
}
UInt32 ConfigReadContext::getLineNumber() const
{
return m_line;
}
bool ConfigReadContext::operator!() const
{
return !m_stream;
}
OptionValue ConfigReadContext::parseBoolean(const String &arg) const
{
if (CaselessCmp::equal(arg, "true")) {
return static_cast<OptionValue>(true);
}
if (CaselessCmp::equal(arg, "false")) {
return static_cast<OptionValue>(false);
}
throw XConfigRead(*this, "invalid boolean argument \"%{1}\"", arg);
}
OptionValue ConfigReadContext::parseInt(const String &arg) const
{
const char *s = arg.c_str();
char *end;
long tmp = strtol(s, &end, 10);
if (*end != '\0') {
// invalid characters
throw XConfigRead(*this, "invalid integer argument \"%{1}\"", arg);
}
OptionValue value = static_cast<OptionValue>(tmp);
if (value != tmp) {
// out of range
throw XConfigRead(*this, "integer argument \"%{1}\" out of range", arg);
}
return value;
}
OptionValue ConfigReadContext::parseModifierKey(const String &arg) const
{
if (CaselessCmp::equal(arg, "shift")) {
return static_cast<OptionValue>(kKeyModifierIDShift);
}
if (CaselessCmp::equal(arg, "ctrl")) {
return static_cast<OptionValue>(kKeyModifierIDControl);
}
if (CaselessCmp::equal(arg, "alt")) {
return static_cast<OptionValue>(kKeyModifierIDAlt);
}
if (CaselessCmp::equal(arg, "altgr")) {
return static_cast<OptionValue>(kKeyModifierIDAltGr);
}
if (CaselessCmp::equal(arg, "meta")) {
return static_cast<OptionValue>(kKeyModifierIDMeta);
}
if (CaselessCmp::equal(arg, "super")) {
return static_cast<OptionValue>(kKeyModifierIDSuper);
}
if (CaselessCmp::equal(arg, "none")) {
return static_cast<OptionValue>(kKeyModifierIDNull);
}
throw XConfigRead(*this, "invalid argument \"%{1}\"", arg);
}
OptionValue ConfigReadContext::parseCorner(const String &arg) const
{
if (CaselessCmp::equal(arg, "left")) {
return kTopLeftMask | kBottomLeftMask;
} else if (CaselessCmp::equal(arg, "right")) {
return kTopRightMask | kBottomRightMask;
} else if (CaselessCmp::equal(arg, "top")) {
return kTopLeftMask | kTopRightMask;
} else if (CaselessCmp::equal(arg, "bottom")) {
return kBottomLeftMask | kBottomRightMask;
} else if (CaselessCmp::equal(arg, "top-left")) {
return kTopLeftMask;
} else if (CaselessCmp::equal(arg, "top-right")) {
return kTopRightMask;
} else if (CaselessCmp::equal(arg, "bottom-left")) {
return kBottomLeftMask;
} else if (CaselessCmp::equal(arg, "bottom-right")) {
return kBottomRightMask;
} else if (CaselessCmp::equal(arg, "none")) {
return kNoCornerMask;
} else if (CaselessCmp::equal(arg, "all")) {
return kAllCornersMask;
}
throw XConfigRead(*this, "invalid argument \"%{1}\"", arg);
}
OptionValue ConfigReadContext::parseProtocol(const String &args) const
{
if (CaselessCmp::equal(args, kSynergyProtocolOption)) {
return static_cast<OptionValue>(ENetworkProtocol::kSynergy);
} else if (CaselessCmp::equal(args, kBarrierProtocolOption)) {
return static_cast<OptionValue>(ENetworkProtocol::kBarrier);
}
throw XConfigRead(*this, "invalid protocol argument \"%{1}\"", args);
}
OptionValue ConfigReadContext::parseCorners(const String &args) const
{
// find first token
String::size_type i = args.find_first_not_of(" \t", 0);
if (i == String::npos) {
throw XConfigRead(*this, "missing corner argument");
}
String::size_type j = args.find_first_of(" \t", i);
// parse first corner token
OptionValue corners = parseCorner(args.substr(i, j - i));
// get +/-
i = args.find_first_not_of(" \t", j);
while (i != String::npos) {
// parse +/-
bool add;
if (args[i] == '-') {
add = false;
} else if (args[i] == '+') {
add = true;
} else {
throw XConfigRead(*this, "invalid corner operator \"%{1}\"", String(args.c_str() + i, 1));
}
// get next corner token
i = args.find_first_not_of(" \t", i + 1);
j = args.find_first_of(" \t", i);
if (i == String::npos) {
throw XConfigRead(*this, "missing corner argument");
}
// parse next corner token
if (add) {
corners |= parseCorner(args.substr(i, j - i));
} else {
corners &= ~parseCorner(args.substr(i, j - i));
}
i = args.find_first_not_of(" \t", j);
}
return corners;
}
Config::Interval ConfigReadContext::parseInterval(const ArgList &args) const
{
if (args.size() == 0) {
return Config::Interval(0.0f, 1.0f);
}
if (args.size() != 2 || args[0].empty() || args[1].empty()) {
throw XConfigRead(*this, "invalid interval \"%{1}\"", concatArgs(args));
}
char *end;
double startValue = strtod(args[0].c_str(), &end);
if (end[0] != '\0') {
throw XConfigRead(*this, "invalid interval \"%{1}\"", concatArgs(args));
}
double endValue = strtod(args[1].c_str(), &end);
if (end[0] != '\0') {
throw XConfigRead(*this, "invalid interval \"%{1}\"", concatArgs(args));
}
if (startValue < 0 || startValue > 100 || endValue < 0 || endValue > 100 || startValue >= endValue) {
throw XConfigRead(*this, "invalid interval \"%{1}\"", concatArgs(args));
}
float startInterval = static_cast<float>(startValue / 100.0f);
float endInterval = static_cast<float>(endValue / 100.0f);
return Config::Interval(startInterval, endInterval);
}
void ConfigReadContext::parseNameWithArgs(
const String &type, const String &line, const String &delim, String::size_type &index, String &name, ArgList &args
) const
{
// skip leading whitespace
String::size_type i = line.find_first_not_of(" \t", index);
if (i == String::npos) {
throw XConfigRead(*this, String("missing ") + type);
}
// find end of name
String::size_type j = line.find_first_of(" \t(" + delim, i);
if (j == String::npos) {
j = line.length();
}
// save name
name = line.substr(i, j - i);
args.clear();
// is it okay to not find a delimiter?
bool needDelim = (!delim.empty() && delim.find('\n') == String::npos);
// skip whitespace
i = line.find_first_not_of(" \t", j);
if (i == String::npos && needDelim) {
// expected delimiter but didn't find it
throw XConfigRead(*this, String("missing ") + delim[0]);
}
if (i == String::npos) {
// no arguments
index = line.length();
return;
}
if (line[i] != '(') {
// no arguments
index = i;
return;
}
// eat '('
++i;
// parse arguments
j = line.find_first_of(",)", i);
while (j != String::npos) {
// extract arg
String arg(line.substr(i, j - i));
i = j;
// trim whitespace
j = arg.find_first_not_of(" \t");
if (j != String::npos) {
arg.erase(0, j);
}
j = arg.find_last_not_of(" \t");
if (j != String::npos) {
arg.erase(j + 1);
}
// save arg
args.push_back(arg);
// exit loop at end of arguments
if (line[i] == ')') {
break;
}
// eat ','
++i;
// next
j = line.find_first_of(",)", i);
}
// verify ')'
if (j == String::npos) {
// expected )
throw XConfigRead(*this, "missing )");
}
// eat ')'
++i;
// skip whitespace
j = line.find_first_not_of(" \t", i);
if (j == String::npos && needDelim) {
// expected delimiter but didn't find it
throw XConfigRead(*this, String("missing ") + delim[0]);
}
// verify delimiter
if (needDelim && delim.find(line[j]) == String::npos) {
throw XConfigRead(*this, String("expected ") + delim[0]);
}
if (j == String::npos) {
j = line.length();
}
index = j;
return;
}
IPlatformScreen::KeyInfo *ConfigReadContext::parseKeystroke(const String &keystroke) const
{
return parseKeystroke(keystroke, std::set<String>());
}
IPlatformScreen::KeyInfo *
ConfigReadContext::parseKeystroke(const String &keystroke, const std::set<String> &screens) const
{
String s = keystroke;
KeyModifierMask mask;
if (!deskflow::KeyMap::parseModifiers(s, mask)) {
throw XConfigRead(*this, "unable to parse key modifiers");
}
KeyID key;
if (!deskflow::KeyMap::parseKey(s, key)) {
throw XConfigRead(*this, "unable to parse key");
}
if (key == kKeyNone && mask == 0) {
throw XConfigRead(*this, "missing key and/or modifiers in keystroke");
}
return IPlatformScreen::KeyInfo::alloc(key, mask, 0, 0, screens);
}
IPlatformScreen::ButtonInfo *ConfigReadContext::parseMouse(const String &mouse) const
{
String s = mouse;
KeyModifierMask mask;
if (!deskflow::KeyMap::parseModifiers(s, mask)) {
throw XConfigRead(*this, "unable to parse button modifiers");
}
char *end;
ButtonID button = (ButtonID)strtol(s.c_str(), &end, 10);
if (*end != '\0') {
throw XConfigRead(*this, "unable to parse button");
}
if (s.empty() || button <= 0) {
throw XConfigRead(*this, "invalid button");
}
return IPlatformScreen::ButtonInfo::alloc(button, mask);
}
KeyModifierMask ConfigReadContext::parseModifier(const String &modifiers) const
{
String s = modifiers;
KeyModifierMask mask;
if (!deskflow::KeyMap::parseModifiers(s, mask)) {
throw XConfigRead(*this, "unable to parse modifiers");
}
if (mask == 0) {
throw XConfigRead(*this, "no modifiers specified");
}
return mask;
}
String ConfigReadContext::concatArgs(const ArgList &args)
{
String s("(");
for (size_t i = 0; i < args.size(); ++i) {
if (i != 0) {
s += ",";
}
s += args[i];
}
s += ")";
return s;
}
//
// Config I/O exceptions
//
XConfigRead::XConfigRead(const ConfigReadContext &context, const String &error)
: m_error(deskflow::string::sprintf("line %d: %s", context.getLineNumber(), error.c_str()))
{
// do nothing
}
XConfigRead::XConfigRead(const ConfigReadContext &context, const char *errorFmt, const String &arg)
: m_error(
deskflow::string::sprintf("line %d: ", context.getLineNumber()) +
deskflow::string::format(errorFmt, arg.c_str())
)
{
// do nothing
}
XConfigRead::~XConfigRead() _NOEXCEPT
{
// do nothing
}
String XConfigRead::getWhat() const throw()
{
return format("XConfigRead", "read error: %{1}", m_error.c_str());
}
} // namespace deskflow::server
| 58,094
|
C++
|
.cpp
| 1,838
| 27.375408
| 118
| 0.646098
|
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,538
|
ClientProxy1_6.cpp
|
deskflow_deskflow/src/lib/server/ClientProxy1_6.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 "server/ClientProxy1_6.h"
#include "base/Log.h"
#include "base/TMethodEventJob.h"
#include "deskflow/ClipboardChunk.h"
#include "deskflow/ProtocolUtil.h"
#include "deskflow/StreamChunker.h"
#include "io/IStream.h"
#include "server/Server.h"
//
// ClientProxy1_6
//
ClientProxy1_6::ClientProxy1_6(const String &name, deskflow::IStream *stream, Server *server, IEventQueue *events)
: ClientProxy1_5(name, stream, server, events),
m_events(events)
{
m_events->adoptHandler(
m_events->forClipboard().clipboardSending(), this,
new TMethodEventJob<ClientProxy1_6>(this, &ClientProxy1_6::handleClipboardSendingEvent)
);
}
ClientProxy1_6::~ClientProxy1_6()
{
}
void ClientProxy1_6::setClipboard(ClipboardID id, const IClipboard *clipboard)
{
// ignore if this clipboard is already clean
if (m_clipboard[id].m_dirty) {
// this clipboard is now clean
m_clipboard[id].m_dirty = false;
Clipboard::copy(&m_clipboard[id].m_clipboard, clipboard);
String data = m_clipboard[id].m_clipboard.marshall();
size_t size = data.size();
LOG((CLOG_DEBUG "sending clipboard %d to \"%s\"", id, getName().c_str()));
StreamChunker::sendClipboard(data, size, id, 0, m_events, this);
}
}
void ClientProxy1_6::handleClipboardSendingEvent(const Event &event, void *)
{
ClipboardChunk::send(getStream(), event.getDataObject());
}
bool ClientProxy1_6::recvClipboard()
{
// parse message
static String dataCached;
ClipboardID id;
UInt32 seq;
int r = ClipboardChunk::assemble(getStream(), dataCached, id, seq);
if (r == kStart) {
size_t size = ClipboardChunk::getExpectedSize();
LOG((CLOG_DEBUG "receiving clipboard %d size=%d", id, size));
} else if (r == kFinish) {
LOG(
(CLOG_DEBUG "received client \"%s\" clipboard %d seqnum=%d, size=%d", getName().c_str(), id, seq,
dataCached.size())
);
// save clipboard
m_clipboard[id].m_clipboard.unmarshall(dataCached, 0);
m_clipboard[id].m_sequenceNumber = seq;
// notify
ClipboardInfo *info = new ClipboardInfo;
info->m_id = id;
info->m_sequenceNumber = seq;
m_events->addEvent(Event(m_events->forClipboard().clipboardChanged(), getEventTarget(), info));
}
return true;
}
| 2,940
|
C++
|
.cpp
| 82
| 32.719512
| 114
| 0.718607
|
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,539
|
ClientProxy1_0.cpp
|
deskflow_deskflow/src/lib/server/ClientProxy1_0.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 "server/ClientProxy1_0.h"
#include "base/IEventQueue.h"
#include "base/Log.h"
#include "base/TMethodEventJob.h"
#include "deskflow/ProtocolUtil.h"
#include "deskflow/XDeskflow.h"
#include "io/IStream.h"
#include <cstring>
//
// ClientProxy1_0
//
ClientProxy1_0::ClientProxy1_0(const String &name, deskflow::IStream *stream, IEventQueue *events)
: ClientProxy(name, stream),
m_heartbeatTimer(NULL),
m_parser(&ClientProxy1_0::parseHandshakeMessage),
m_events(events)
{
// install event handlers
m_events->adoptHandler(
m_events->forIStream().inputReady(), stream->getEventTarget(),
new TMethodEventJob<ClientProxy1_0>(this, &ClientProxy1_0::handleData, NULL)
);
m_events->adoptHandler(
m_events->forIStream().outputError(), stream->getEventTarget(),
new TMethodEventJob<ClientProxy1_0>(this, &ClientProxy1_0::handleWriteError, NULL)
);
m_events->adoptHandler(
m_events->forIStream().inputShutdown(), stream->getEventTarget(),
new TMethodEventJob<ClientProxy1_0>(this, &ClientProxy1_0::handleDisconnect, NULL)
);
m_events->adoptHandler(
m_events->forIStream().outputShutdown(), stream->getEventTarget(),
new TMethodEventJob<ClientProxy1_0>(this, &ClientProxy1_0::handleWriteError, NULL)
);
m_events->adoptHandler(
Event::kTimer, this, new TMethodEventJob<ClientProxy1_0>(this, &ClientProxy1_0::handleFlatline, NULL)
);
setHeartbeatRate(kHeartRate, kHeartRate * kHeartBeatsUntilDeath);
LOG((CLOG_DEBUG1 "querying client \"%s\" info", getName().c_str()));
ProtocolUtil::writef(getStream(), kMsgQInfo);
}
ClientProxy1_0::~ClientProxy1_0()
{
removeHandlers();
}
void ClientProxy1_0::disconnect()
{
removeHandlers();
getStream()->close();
m_events->addEvent(Event(m_events->forClientProxy().disconnected(), getEventTarget()));
}
void ClientProxy1_0::removeHandlers()
{
// uninstall event handlers
m_events->removeHandler(m_events->forIStream().inputReady(), getStream()->getEventTarget());
m_events->removeHandler(m_events->forIStream().outputError(), getStream()->getEventTarget());
m_events->removeHandler(m_events->forIStream().inputShutdown(), getStream()->getEventTarget());
m_events->removeHandler(m_events->forIStream().outputShutdown(), getStream()->getEventTarget());
m_events->removeHandler(Event::kTimer, this);
// remove timer
removeHeartbeatTimer();
}
void ClientProxy1_0::addHeartbeatTimer()
{
if (m_heartbeatAlarm > 0.0) {
m_heartbeatTimer = m_events->newOneShotTimer(m_heartbeatAlarm, this);
}
}
void ClientProxy1_0::removeHeartbeatTimer()
{
if (m_heartbeatTimer != NULL) {
m_events->deleteTimer(m_heartbeatTimer);
m_heartbeatTimer = NULL;
}
}
void ClientProxy1_0::resetHeartbeatTimer()
{
// reset the alarm
removeHeartbeatTimer();
addHeartbeatTimer();
}
void ClientProxy1_0::resetHeartbeatRate()
{
setHeartbeatRate(kHeartRate, kHeartRate * kHeartBeatsUntilDeath);
}
void ClientProxy1_0::setHeartbeatRate(double, double alarm)
{
m_heartbeatAlarm = alarm;
}
void ClientProxy1_0::handleData(const Event &, void *)
{
// handle messages until there are no more. first read message code.
UInt8 code[4];
UInt32 n = getStream()->read(code, 4);
while (n != 0) {
// verify we got an entire code
if (n != 4) {
LOG((CLOG_ERR "incomplete message from \"%s\": %d bytes", getName().c_str(), n));
disconnect();
return;
}
// parse message
LOG((CLOG_DEBUG2 "msg from \"%s\": %c%c%c%c", getName().c_str(), code[0], code[1], code[2], code[3]));
if (!(this->*m_parser)(code)) {
LOG((
CLOG_ERR "invalid message from client \"%s\": %c%c%c%c", getName().c_str(), code[0], code[1], code[2], code[3]
));
// not possible to determine message boundaries
// read the whole stream to discard unkonwn data
while (getStream()->read(nullptr, 4))
;
}
// next message
n = getStream()->read(code, 4);
}
// restart heartbeat timer
resetHeartbeatTimer();
}
bool ClientProxy1_0::parseHandshakeMessage(const UInt8 *code)
{
if (memcmp(code, kMsgCNoop, 4) == 0) {
// discard no-ops
LOG((CLOG_DEBUG2 "no-op from", getName().c_str()));
return true;
} else if (memcmp(code, kMsgDInfo, 4) == 0) {
// future messages get parsed by parseMessage
m_parser = &ClientProxy1_0::parseMessage;
if (recvInfo()) {
m_events->addEvent(Event(m_events->forClientProxy().ready(), getEventTarget()));
addHeartbeatTimer();
return true;
}
}
return false;
}
bool ClientProxy1_0::parseMessage(const UInt8 *code)
{
if (memcmp(code, kMsgDInfo, 4) == 0) {
if (recvInfo()) {
m_events->addEvent(Event(m_events->forIScreen().shapeChanged(), getEventTarget()));
return true;
}
return false;
} else if (memcmp(code, kMsgCNoop, 4) == 0) {
// discard no-ops
LOG((CLOG_DEBUG2 "no-op from", getName().c_str()));
return true;
} else if (memcmp(code, kMsgCClipboard, 4) == 0) {
return recvGrabClipboard();
} else if (memcmp(code, kMsgDClipboard, 4) == 0) {
return recvClipboard();
}
return false;
}
void ClientProxy1_0::handleDisconnect(const Event &, void *)
{
LOG((CLOG_NOTE "client \"%s\" has disconnected", getName().c_str()));
disconnect();
}
void ClientProxy1_0::handleWriteError(const Event &, void *)
{
LOG((CLOG_WARN "error writing to client \"%s\"", getName().c_str()));
disconnect();
}
void ClientProxy1_0::handleFlatline(const Event &, void *)
{
// didn't get a heartbeat fast enough. assume client is dead.
LOG((CLOG_NOTE "client \"%s\" is dead", getName().c_str()));
disconnect();
}
bool ClientProxy1_0::getClipboard(ClipboardID id, IClipboard *clipboard) const
{
Clipboard::copy(clipboard, &m_clipboard[id].m_clipboard);
return true;
}
void ClientProxy1_0::getShape(SInt32 &x, SInt32 &y, SInt32 &w, SInt32 &h) const
{
x = m_info.m_x;
y = m_info.m_y;
w = m_info.m_w;
h = m_info.m_h;
}
void ClientProxy1_0::getCursorPos(SInt32 &x, SInt32 &y) const
{
// note -- this returns the cursor pos from when we last got client info
x = m_info.m_mx;
y = m_info.m_my;
}
void ClientProxy1_0::enter(SInt32 xAbs, SInt32 yAbs, UInt32 seqNum, KeyModifierMask mask, bool)
{
LOG((CLOG_DEBUG1 "send enter to \"%s\", %d,%d %d %04x", getName().c_str(), xAbs, yAbs, seqNum, mask));
ProtocolUtil::writef(getStream(), kMsgCEnter, xAbs, yAbs, seqNum, mask);
}
bool ClientProxy1_0::leave()
{
LOG((CLOG_DEBUG1 "send leave to \"%s\"", getName().c_str()));
ProtocolUtil::writef(getStream(), kMsgCLeave);
// we can never prevent the user from leaving
return true;
}
void ClientProxy1_0::setClipboard(ClipboardID id, const IClipboard *clipboard)
{
// ignore -- deprecated in protocol 1.0
}
void ClientProxy1_0::grabClipboard(ClipboardID id)
{
LOG((CLOG_DEBUG "send grab clipboard %d to \"%s\"", id, getName().c_str()));
ProtocolUtil::writef(getStream(), kMsgCClipboard, id, 0);
// this clipboard is now dirty
m_clipboard[id].m_dirty = true;
}
void ClientProxy1_0::setClipboardDirty(ClipboardID id, bool dirty)
{
m_clipboard[id].m_dirty = dirty;
}
void ClientProxy1_0::keyDown(KeyID key, KeyModifierMask mask, KeyButton, const String &)
{
LOG((CLOG_DEBUG1 "send key down to \"%s\" id=%d, mask=0x%04x", getName().c_str(), key, mask));
ProtocolUtil::writef(getStream(), kMsgDKeyDown1_0, key, mask);
}
void ClientProxy1_0::keyRepeat(KeyID key, KeyModifierMask mask, SInt32 count, KeyButton, const String &)
{
LOG((CLOG_DEBUG1 "send key repeat to \"%s\" id=%d, mask=0x%04x, count=%d", getName().c_str(), key, mask, count));
ProtocolUtil::writef(getStream(), kMsgDKeyRepeat1_0, key, mask, count);
}
void ClientProxy1_0::keyUp(KeyID key, KeyModifierMask mask, KeyButton)
{
LOG((CLOG_DEBUG1 "send key up to \"%s\" id=%d, mask=0x%04x", getName().c_str(), key, mask));
ProtocolUtil::writef(getStream(), kMsgDKeyUp1_0, key, mask);
}
void ClientProxy1_0::mouseDown(ButtonID button)
{
LOG((CLOG_DEBUG1 "send mouse down to \"%s\" id=%d", getName().c_str(), button));
ProtocolUtil::writef(getStream(), kMsgDMouseDown, button);
}
void ClientProxy1_0::mouseUp(ButtonID button)
{
LOG((CLOG_DEBUG1 "send mouse up to \"%s\" id=%d", getName().c_str(), button));
ProtocolUtil::writef(getStream(), kMsgDMouseUp, button);
}
void ClientProxy1_0::mouseMove(SInt32 xAbs, SInt32 yAbs)
{
LOG((CLOG_DEBUG2 "send mouse move to \"%s\" %d,%d", getName().c_str(), xAbs, yAbs));
ProtocolUtil::writef(getStream(), kMsgDMouseMove, xAbs, yAbs);
}
void ClientProxy1_0::mouseRelativeMove(SInt32, SInt32)
{
// ignore -- not supported in protocol 1.0
}
void ClientProxy1_0::mouseWheel(SInt32, SInt32 yDelta)
{
// clients prior to 1.3 only support the y axis
LOG((CLOG_DEBUG2 "send mouse wheel to \"%s\" %+d", getName().c_str(), yDelta));
ProtocolUtil::writef(getStream(), kMsgDMouseWheel1_0, yDelta);
}
void ClientProxy1_0::sendDragInfo(UInt32 fileCount, const char *info, size_t size)
{
// ignore -- not supported in protocol 1.0
LOG((CLOG_DEBUG "draggingInfoSending not supported"));
}
void ClientProxy1_0::fileChunkSending(UInt8 mark, char *data, size_t dataSize)
{
// ignore -- not supported in protocol 1.0
LOG((CLOG_DEBUG "fileChunkSending not supported"));
}
String ClientProxy1_0::getSecureInputApp() const
{
// ignore -- not supported on clients
LOG((CLOG_DEBUG "getSecureInputApp not supported"));
return "";
}
void ClientProxy1_0::secureInputNotification(const String &app) const
{
// ignore -- not supported in protocol 1.0
LOG((CLOG_DEBUG "secureInputNotification not supported"));
}
void ClientProxy1_0::screensaver(bool on)
{
LOG((CLOG_DEBUG1 "send screen saver to \"%s\" on=%d", getName().c_str(), on ? 1 : 0));
ProtocolUtil::writef(getStream(), kMsgCScreenSaver, on ? 1 : 0);
}
void ClientProxy1_0::resetOptions()
{
LOG((CLOG_DEBUG1 "send reset options to \"%s\"", getName().c_str()));
ProtocolUtil::writef(getStream(), kMsgCResetOptions);
// reset heart rate and death
resetHeartbeatRate();
removeHeartbeatTimer();
addHeartbeatTimer();
}
void ClientProxy1_0::setOptions(const OptionsList &options)
{
LOG((CLOG_DEBUG1 "send set options to \"%s\" size=%d", getName().c_str(), options.size()));
ProtocolUtil::writef(getStream(), kMsgDSetOptions, &options);
// check options
for (UInt32 i = 0, n = (UInt32)options.size(); i < n; i += 2) {
if (options[i] == kOptionHeartbeat) {
double rate = 1.0e-3 * static_cast<double>(options[i + 1]);
if (rate <= 0.0) {
rate = -1.0;
}
setHeartbeatRate(rate, rate * kHeartBeatsUntilDeath);
removeHeartbeatTimer();
addHeartbeatTimer();
}
}
}
bool ClientProxy1_0::recvInfo()
{
// parse the message
SInt16 x, y, w, h, dummy1, mx, my;
if (!ProtocolUtil::readf(getStream(), kMsgDInfo + 4, &x, &y, &w, &h, &dummy1, &mx, &my)) {
return false;
}
LOG((CLOG_DEBUG "received client \"%s\" info shape=%d,%d %dx%d at %d,%d", getName().c_str(), x, y, w, h, mx, my));
// validate
if (w <= 0 || h <= 0) {
return false;
}
if (mx < x || mx >= x + w || my < y || my >= y + h) {
mx = x + w / 2;
my = y + h / 2;
}
// save
m_info.m_x = x;
m_info.m_y = y;
m_info.m_w = w;
m_info.m_h = h;
m_info.m_mx = mx;
m_info.m_my = my;
// acknowledge receipt
LOG((CLOG_DEBUG1 "send info ack to \"%s\"", getName().c_str()));
ProtocolUtil::writef(getStream(), kMsgCInfoAck);
return true;
}
bool ClientProxy1_0::recvClipboard()
{
// deprecated in protocol 1.0
return false;
}
bool ClientProxy1_0::recvGrabClipboard()
{
// parse message
ClipboardID id;
UInt32 seqNum;
if (!ProtocolUtil::readf(getStream(), kMsgCClipboard + 4, &id, &seqNum)) {
return false;
}
LOG((CLOG_DEBUG "received client \"%s\" grabbed clipboard %d seqnum=%d", getName().c_str(), id, seqNum));
// validate
if (id >= kClipboardEnd) {
return false;
}
// notify
ClipboardInfo *info = new ClipboardInfo;
info->m_id = id;
info->m_sequenceNumber = seqNum;
m_events->addEvent(Event(m_events->forClipboard().clipboardGrabbed(), getEventTarget(), info));
return true;
}
//
// ClientProxy1_0::ClientClipboard
//
ClientProxy1_0::ClientClipboard::ClientClipboard() : m_clipboard(), m_sequenceNumber(0), m_dirty(true)
{
// do nothing
}
| 13,046
|
C++
|
.cpp
| 384
| 31.023438
| 120
| 0.692277
|
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,540
|
PrimaryClient.cpp
|
deskflow_deskflow/src/lib/server/PrimaryClient.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 "server/PrimaryClient.h"
#include "base/Log.h"
#include "deskflow/AppUtil.h"
#include "deskflow/Clipboard.h"
#include "deskflow/Screen.h"
//
// PrimaryClient
//
PrimaryClient::PrimaryClient(const String &name, deskflow::Screen *screen)
: BaseClientProxy(name),
m_screen(screen),
m_fakeInputCount(0)
{
// all clipboards are clean
for (UInt32 i = 0; i < kClipboardEnd; ++i) {
m_clipboardDirty[i] = false;
}
}
PrimaryClient::~PrimaryClient()
{
// do nothing
}
void PrimaryClient::reconfigure(UInt32 activeSides)
{
m_screen->reconfigure(activeSides);
}
UInt32 PrimaryClient::registerHotKey(KeyID key, KeyModifierMask mask)
{
return m_screen->registerHotKey(key, mask);
}
void PrimaryClient::unregisterHotKey(UInt32 id)
{
m_screen->unregisterHotKey(id);
}
void PrimaryClient::fakeInputBegin()
{
if (++m_fakeInputCount == 1) {
m_screen->fakeInputBegin();
}
}
void PrimaryClient::fakeInputEnd()
{
if (--m_fakeInputCount == 0) {
m_screen->fakeInputEnd();
}
}
SInt32 PrimaryClient::getJumpZoneSize() const
{
return m_screen->getJumpZoneSize();
}
void PrimaryClient::getCursorCenter(SInt32 &x, SInt32 &y) const
{
m_screen->getCursorCenter(x, y);
}
KeyModifierMask PrimaryClient::getToggleMask() const
{
return m_screen->pollActiveModifiers();
}
bool PrimaryClient::isLockedToScreen() const
{
return m_screen->isLockedToScreen();
}
void *PrimaryClient::getEventTarget() const
{
return m_screen->getEventTarget();
}
bool PrimaryClient::getClipboard(ClipboardID id, IClipboard *clipboard) const
{
return m_screen->getClipboard(id, clipboard);
}
void PrimaryClient::getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const
{
m_screen->getShape(x, y, width, height);
}
void PrimaryClient::getCursorPos(SInt32 &x, SInt32 &y) const
{
m_screen->getCursorPos(x, y);
}
void PrimaryClient::enable()
{
m_screen->enable();
}
void PrimaryClient::disable()
{
m_screen->disable();
}
void PrimaryClient::enter(SInt32 xAbs, SInt32 yAbs, UInt32 seqNum, KeyModifierMask mask, bool screensaver)
{
m_screen->setSequenceNumber(seqNum);
if (!screensaver) {
m_screen->warpCursor(xAbs, yAbs);
}
m_screen->enter(mask);
}
bool PrimaryClient::leave()
{
return m_screen->leave();
}
void PrimaryClient::setClipboard(ClipboardID id, const IClipboard *clipboard)
{
// ignore if this clipboard is already clean
if (m_clipboardDirty[id]) {
// this clipboard is now clean
m_clipboardDirty[id] = false;
// set clipboard
m_screen->setClipboard(id, clipboard);
}
}
void PrimaryClient::grabClipboard(ClipboardID id)
{
// grab clipboard
m_screen->grabClipboard(id);
// clipboard is dirty (because someone else owns it now)
m_clipboardDirty[id] = true;
}
void PrimaryClient::setClipboardDirty(ClipboardID id, bool dirty)
{
m_clipboardDirty[id] = dirty;
}
void PrimaryClient::keyDown(KeyID key, KeyModifierMask mask, KeyButton button, const String &)
{
if (m_fakeInputCount > 0) {
// XXX -- don't forward keystrokes to primary screen for now
(void)key;
(void)mask;
(void)button;
// m_screen->keyDown(key, mask, button);
}
}
void PrimaryClient::keyRepeat(KeyID, KeyModifierMask, SInt32, KeyButton, const String &)
{
// ignore
}
void PrimaryClient::keyUp(KeyID key, KeyModifierMask mask, KeyButton button)
{
if (m_fakeInputCount > 0) {
// XXX -- don't forward keystrokes to primary screen for now
(void)key;
(void)mask;
(void)button;
// m_screen->keyUp(key, mask, button);
}
}
void PrimaryClient::mouseDown(ButtonID)
{
// ignore
}
void PrimaryClient::mouseUp(ButtonID)
{
// ignore
}
void PrimaryClient::mouseMove(SInt32 x, SInt32 y)
{
m_screen->warpCursor(x, y);
}
void PrimaryClient::mouseRelativeMove(SInt32, SInt32)
{
// ignore
}
void PrimaryClient::mouseWheel(SInt32, SInt32)
{
// ignore
}
void PrimaryClient::screensaver(bool)
{
// ignore
}
void PrimaryClient::sendDragInfo(UInt32 fileCount, const char *info, size_t size)
{
// ignore
}
void PrimaryClient::fileChunkSending(UInt8 mark, char *data, size_t dataSize)
{
// ignore
}
String PrimaryClient::getSecureInputApp() const
{
return m_screen->getSecureInputApp();
}
void PrimaryClient::secureInputNotification(const String &app) const
{
if (app != "unknown") {
AppUtil::instance().showNotification(
"The client keyboards may stop working.", "'Secure input' enabled by " + app +
". "
"Close " +
app + " to continue using keyboards on the clients."
);
} else {
AppUtil::instance().showNotification(
"The client keyboards may stop working.", "'Secure input' enabled by an application. "
"Close the application to continue using keyboards on the clients."
);
}
}
void PrimaryClient::resetOptions()
{
m_screen->resetOptions();
}
void PrimaryClient::setOptions(const OptionsList &options)
{
m_screen->setOptions(options);
}
| 5,864
|
C++
|
.cpp
| 220
| 23.404545
| 117
| 0.711583
|
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,541
|
ClientProxyUnknown.cpp
|
deskflow_deskflow/src/lib/server/ClientProxyUnknown.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 "server/ClientProxyUnknown.h"
#include "base/IEventQueue.h"
#include "base/Log.h"
#include "base/TMethodEventJob.h"
#include "deskflow/AppUtil.h"
#include "deskflow/ProtocolUtil.h"
#include "deskflow/XDeskflow.h"
#include "deskflow/protocol_types.h"
#include "io/IStream.h"
#include "io/XIO.h"
#include "server/ClientProxy1_0.h"
#include "server/ClientProxy1_1.h"
#include "server/ClientProxy1_2.h"
#include "server/ClientProxy1_3.h"
#include "server/ClientProxy1_4.h"
#include "server/ClientProxy1_5.h"
#include "server/ClientProxy1_6.h"
#include "server/ClientProxy1_7.h"
#include "server/ClientProxy1_8.h"
#include "server/Server.h"
#include <iterator>
#include <sstream>
//
// ClientProxyUnknown
//
ClientProxyUnknown::ClientProxyUnknown(deskflow::IStream *stream, double timeout, Server *server, IEventQueue *events)
: m_stream(stream),
m_proxy(NULL),
m_ready(false),
m_server(server),
m_events(events)
{
assert(m_server != NULL);
m_events->adoptHandler(
Event::kTimer, this, new TMethodEventJob<ClientProxyUnknown>(this, &ClientProxyUnknown::handleTimeout, NULL)
);
m_timer = m_events->newOneShotTimer(timeout, this);
addStreamHandlers();
const auto protocol = m_server->protocolString();
const auto helloMessage = protocol + kMsgHelloArgs;
LOG_DEBUG("saying hello as %s, protocol v%d.%d", protocol.c_str(), kProtocolMajorVersion, kProtocolMinorVersion);
ProtocolUtil::writef(m_stream, helloMessage.c_str(), kProtocolMajorVersion, kProtocolMinorVersion);
}
ClientProxyUnknown::~ClientProxyUnknown()
{
removeHandlers();
removeTimer();
delete m_stream;
delete m_proxy;
}
ClientProxy *ClientProxyUnknown::orphanClientProxy()
{
if (m_ready) {
removeHandlers();
ClientProxy *proxy = m_proxy;
m_proxy = NULL;
return proxy;
} else {
return NULL;
}
}
void ClientProxyUnknown::sendSuccess()
{
m_ready = true;
removeTimer();
m_events->addEvent(Event(m_events->forClientProxyUnknown().success(), this));
}
void ClientProxyUnknown::sendFailure()
{
delete m_proxy;
m_proxy = NULL;
m_ready = false;
removeHandlers();
removeTimer();
m_events->addEvent(Event(m_events->forClientProxyUnknown().failure(), this));
}
void ClientProxyUnknown::addStreamHandlers()
{
assert(m_stream != NULL);
m_events->adoptHandler(
m_events->forIStream().inputReady(), m_stream->getEventTarget(),
new TMethodEventJob<ClientProxyUnknown>(this, &ClientProxyUnknown::handleData)
);
m_events->adoptHandler(
m_events->forIStream().outputError(), m_stream->getEventTarget(),
new TMethodEventJob<ClientProxyUnknown>(this, &ClientProxyUnknown::handleWriteError)
);
m_events->adoptHandler(
m_events->forIStream().inputShutdown(), m_stream->getEventTarget(),
new TMethodEventJob<ClientProxyUnknown>(this, &ClientProxyUnknown::handleDisconnect)
);
m_events->adoptHandler(
m_events->forIStream().outputShutdown(), m_stream->getEventTarget(),
new TMethodEventJob<ClientProxyUnknown>(this, &ClientProxyUnknown::handleWriteError)
);
}
void ClientProxyUnknown::addProxyHandlers()
{
assert(m_proxy != NULL);
m_events->adoptHandler(
m_events->forClientProxy().ready(), m_proxy,
new TMethodEventJob<ClientProxyUnknown>(this, &ClientProxyUnknown::handleReady)
);
m_events->adoptHandler(
m_events->forClientProxy().disconnected(), m_proxy,
new TMethodEventJob<ClientProxyUnknown>(this, &ClientProxyUnknown::handleDisconnect)
);
}
void ClientProxyUnknown::removeHandlers()
{
if (m_stream != NULL) {
m_events->removeHandler(m_events->forIStream().inputReady(), m_stream->getEventTarget());
m_events->removeHandler(m_events->forIStream().outputError(), m_stream->getEventTarget());
m_events->removeHandler(m_events->forIStream().inputShutdown(), m_stream->getEventTarget());
m_events->removeHandler(m_events->forIStream().outputShutdown(), m_stream->getEventTarget());
}
if (m_proxy != NULL) {
m_events->removeHandler(m_events->forClientProxy().ready(), m_proxy);
m_events->removeHandler(m_events->forClientProxy().disconnected(), m_proxy);
}
}
void ClientProxyUnknown::removeTimer()
{
if (m_timer != NULL) {
m_events->deleteTimer(m_timer);
m_events->removeHandler(Event::kTimer, this);
m_timer = NULL;
}
}
void ClientProxyUnknown::initProxy(const String &name, int major, int minor)
{
if (major == 1) {
switch (minor) {
case 0:
m_proxy = new ClientProxy1_0(name, m_stream, m_events);
break;
case 1:
m_proxy = new ClientProxy1_1(name, m_stream, m_events);
break;
case 2:
m_proxy = new ClientProxy1_2(name, m_stream, m_events);
break;
case 3:
m_proxy = new ClientProxy1_3(name, m_stream, m_events);
break;
case 4:
m_proxy = new ClientProxy1_4(name, m_stream, m_server, m_events);
break;
case 5:
m_proxy = new ClientProxy1_5(name, m_stream, m_server, m_events);
break;
case 6:
m_proxy = new ClientProxy1_6(name, m_stream, m_server, m_events);
break;
case 7:
m_proxy = new ClientProxy1_7(name, m_stream, m_server, m_events);
break;
case 8:
m_proxy = new ClientProxy1_8(name, m_stream, m_server, m_events);
break;
}
}
// hangup (with error) if version isn't supported
if (m_proxy == NULL) {
throw XIncompatibleClient(major, minor);
}
}
void ClientProxyUnknown::handleData(const Event &, void *)
{
LOG((CLOG_DEBUG1 "parsing hello reply"));
String name("<unknown>");
try {
// limit the maximum length of the hello
UInt32 n = m_stream->getSize();
if (n > kMaxHelloLength) {
LOG((CLOG_DEBUG1 "hello reply too long"));
throw XBadClient();
}
// parse the reply to hello
SInt16 major, minor;
std::string protocolName;
if (!ProtocolUtil::readf(m_stream, kMsgHelloBack, &protocolName, &major, &minor, &name)) {
throw XBadClient();
}
// disallow invalid version numbers
if (major <= 0 || minor < 0) {
throw XIncompatibleClient(major, minor);
}
// remove stream event handlers. the proxy we're about to create
// may install its own handlers and we don't want to accidentally
// remove those later.
removeHandlers();
// create client proxy for highest version supported by the client
initProxy(name, major, minor);
// the proxy is created and now proxy now owns the stream
LOG((CLOG_DEBUG1 "created proxy for client \"%s\" version %d.%d", name.c_str(), major, minor));
m_stream = NULL;
// wait until the proxy signals that it's ready or has disconnected
addProxyHandlers();
return;
} catch (XIncompatibleClient &e) {
// client is incompatible
LOG((CLOG_WARN "client \"%s\" has incompatible version %d.%d)", name.c_str(), e.getMajor(), e.getMinor()));
ProtocolUtil::writef(m_stream, kMsgEIncompatible, kProtocolMajorVersion, kProtocolMinorVersion);
} catch (XBadClient &) {
// client not behaving
LOG((CLOG_WARN "protocol error from client \"%s\"", name.c_str()));
ProtocolUtil::writef(m_stream, kMsgEBad);
} catch (XBase &e) {
// misc error
LOG((CLOG_WARN "error communicating with client \"%s\": %s", name.c_str(), e.what()));
}
sendFailure();
}
void ClientProxyUnknown::handleWriteError(const Event &, void *)
{
LOG((CLOG_NOTE "error communicating with new client"));
sendFailure();
}
void ClientProxyUnknown::handleTimeout(const Event &, void *)
{
LOG((CLOG_NOTE "new client is unresponsive"));
sendFailure();
}
void ClientProxyUnknown::handleDisconnect(const Event &, void *)
{
LOG((CLOG_NOTE "new client disconnected"));
sendFailure();
}
void ClientProxyUnknown::handleReady(const Event &, void *)
{
sendSuccess();
}
| 8,533
|
C++
|
.cpp
| 250
| 30.504
| 118
| 0.710871
|
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,542
|
ClientProxy1_3.cpp
|
deskflow_deskflow/src/lib/server/ClientProxy1_3.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2006 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 "server/ClientProxy1_3.h"
#include "base/IEventQueue.h"
#include "base/Log.h"
#include "base/TMethodEventJob.h"
#include "deskflow/ProtocolUtil.h"
#include <cstring>
#include <memory>
//
// ClientProxy1_3
//
ClientProxy1_3::ClientProxy1_3(const String &name, deskflow::IStream *stream, IEventQueue *events)
: ClientProxy1_2(name, stream, events),
m_keepAliveRate(kKeepAliveRate),
m_keepAliveTimer(NULL),
m_events(events)
{
setHeartbeatRate(kKeepAliveRate, kKeepAliveRate * kKeepAlivesUntilDeath);
}
ClientProxy1_3::~ClientProxy1_3()
{
// cannot do this in superclass or our override wouldn't get called
removeHeartbeatTimer();
}
void ClientProxy1_3::mouseWheel(SInt32 xDelta, SInt32 yDelta)
{
LOG((CLOG_DEBUG2 "send mouse wheel to \"%s\" %+d,%+d", getName().c_str(), xDelta, yDelta));
ProtocolUtil::writef(getStream(), kMsgDMouseWheel, xDelta, yDelta);
}
bool ClientProxy1_3::parseMessage(const UInt8 *code)
{
// process message
if (memcmp(code, kMsgCKeepAlive, 4) == 0) {
// reset alarm
resetHeartbeatTimer();
return true;
} else {
return ClientProxy1_2::parseMessage(code);
}
}
void ClientProxy1_3::resetHeartbeatRate()
{
setHeartbeatRate(kKeepAliveRate, kKeepAliveRate * kKeepAlivesUntilDeath);
}
void ClientProxy1_3::setHeartbeatRate(double rate, double)
{
m_keepAliveRate = rate;
ClientProxy1_2::setHeartbeatRate(rate, rate * kKeepAlivesUntilDeath);
}
void ClientProxy1_3::resetHeartbeatTimer()
{
// reset the alarm but not the keep alive timer
ClientProxy1_2::removeHeartbeatTimer();
ClientProxy1_2::addHeartbeatTimer();
}
void ClientProxy1_3::addHeartbeatTimer()
{
// create and install a timer to periodically send keep alives
if (m_keepAliveRate > 0.0) {
m_keepAliveTimer = m_events->newTimer(m_keepAliveRate, NULL);
m_events->adoptHandler(
Event::kTimer, m_keepAliveTimer,
new TMethodEventJob<ClientProxy1_3>(this, &ClientProxy1_3::handleKeepAlive, NULL)
);
}
// superclass does the alarm
ClientProxy1_2::addHeartbeatTimer();
}
void ClientProxy1_3::removeHeartbeatTimer()
{
// remove the timer that sends keep alives periodically
if (m_keepAliveTimer != NULL) {
m_events->removeHandler(Event::kTimer, m_keepAliveTimer);
m_events->deleteTimer(m_keepAliveTimer);
m_keepAliveTimer = NULL;
}
// superclass does the alarm
ClientProxy1_2::removeHeartbeatTimer();
}
void ClientProxy1_3::handleKeepAlive(const Event &, void *)
{
keepAlive();
}
void ClientProxy1_3::keepAlive()
{
ProtocolUtil::writef(getStream(), kMsgCKeepAlive);
}
| 3,322
|
C++
|
.cpp
| 103
| 29.650485
| 98
| 0.752342
|
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,543
|
ClientProxy1_2.cpp
|
deskflow_deskflow/src/lib/server/ClientProxy1_2.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 "server/ClientProxy1_2.h"
#include "base/Log.h"
#include "deskflow/ProtocolUtil.h"
//
// ClientProxy1_1
//
ClientProxy1_2::ClientProxy1_2(const String &name, deskflow::IStream *stream, IEventQueue *events)
: ClientProxy1_1(name, stream, events)
{
// do nothing
}
ClientProxy1_2::~ClientProxy1_2()
{
// do nothing
}
void ClientProxy1_2::mouseRelativeMove(SInt32 xRel, SInt32 yRel)
{
LOG((CLOG_DEBUG2 "send mouse relative move to \"%s\" %d,%d", getName().c_str(), xRel, yRel));
ProtocolUtil::writef(getStream(), kMsgDMouseRelMove, xRel, yRel);
}
| 1,301
|
C++
|
.cpp
| 37
| 33.243243
| 98
| 0.748013
|
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,544
|
Server.cpp
|
deskflow_deskflow/src/lib/server/Server.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012 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 "server/Server.h"
#include "arch/Arch.h"
#include "base/IEventQueue.h"
#include "base/Log.h"
#include "base/TMethodEventJob.h"
#include "base/TMethodJob.h"
#include "common/stdexcept.h"
#include "deskflow/AppUtil.h"
#include "deskflow/DropHelper.h"
#include "deskflow/FileChunk.h"
#include "deskflow/IPlatformScreen.h"
#include "deskflow/PacketStreamFilter.h"
#include "deskflow/Screen.h"
#include "deskflow/StreamChunker.h"
#include "deskflow/XDeskflow.h"
#include "deskflow/option_types.h"
#include "deskflow/protocol_types.h"
#include "mt/Thread.h"
#include "net/TCPSocket.h"
#include "server/ClientListener.h"
#include "server/ClientProxy.h"
#include "server/ClientProxyUnknown.h"
#include "server/PrimaryClient.h"
#include <climits>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <ctime>
using namespace deskflow::server;
//
// Server
//
Server::Server(
ServerConfig &config, PrimaryClient *primaryClient, deskflow::Screen *screen, IEventQueue *events,
deskflow::ServerArgs const &args
)
: m_mock(false),
m_primaryClient(primaryClient),
m_active(primaryClient),
m_seqNum(0),
m_xDelta(0),
m_yDelta(0),
m_xDelta2(0),
m_yDelta2(0),
m_config(&config),
m_inputFilter(config.getInputFilter()),
m_activeSaver(NULL),
m_switchDir(kNoDirection),
m_switchScreen(NULL),
m_switchWaitDelay(0.0),
m_switchWaitTimer(NULL),
m_switchTwoTapDelay(0.0),
m_switchTwoTapEngaged(false),
m_switchTwoTapArmed(false),
m_switchTwoTapZone(3),
m_switchNeedsShift(false),
m_switchNeedsControl(false),
m_switchNeedsAlt(false),
m_relativeMoves(false),
m_keyboardBroadcasting(false),
m_lockedToScreen(false),
m_screen(screen),
m_events(events),
m_sendFileThread(nullptr),
m_writeToDropDirThread(nullptr),
m_ignoreFileTransfer(false),
m_disableLockToScreen(false),
m_enableClipboard(true),
m_maximumClipboardSize(INT_MAX),
m_sendDragInfoThread(nullptr),
m_waitDragInfoThread(true),
m_args(args)
{
// must have a primary client and it must have a canonical name
assert(m_primaryClient != NULL);
assert(config.isScreen(primaryClient->getName()));
assert(m_screen != NULL);
String primaryName = getName(primaryClient);
// clear clipboards
for (ClipboardID id = 0; id < kClipboardEnd; ++id) {
ClipboardInfo &clipboard = m_clipboards[id];
clipboard.m_clipboardOwner = primaryName;
clipboard.m_clipboardSeqNum = m_seqNum;
if (clipboard.m_clipboard.open(0)) {
clipboard.m_clipboard.empty();
clipboard.m_clipboard.close();
}
clipboard.m_clipboardData = clipboard.m_clipboard.marshall();
}
// install event handlers
m_events->adoptHandler(Event::kTimer, this, new TMethodEventJob<Server>(this, &Server::handleSwitchWaitTimeout));
m_events->adoptHandler(
m_events->forIKeyState().keyDown(), m_inputFilter, new TMethodEventJob<Server>(this, &Server::handleKeyDownEvent)
);
m_events->adoptHandler(
m_events->forIKeyState().keyUp(), m_inputFilter, new TMethodEventJob<Server>(this, &Server::handleKeyUpEvent)
);
m_events->adoptHandler(
m_events->forIKeyState().keyRepeat(), m_inputFilter,
new TMethodEventJob<Server>(this, &Server::handleKeyRepeatEvent)
);
m_events->adoptHandler(
m_events->forIPrimaryScreen().buttonDown(), m_inputFilter,
new TMethodEventJob<Server>(this, &Server::handleButtonDownEvent)
);
m_events->adoptHandler(
m_events->forIPrimaryScreen().buttonUp(), m_inputFilter,
new TMethodEventJob<Server>(this, &Server::handleButtonUpEvent)
);
m_events->adoptHandler(
m_events->forIPrimaryScreen().motionOnPrimary(), m_primaryClient->getEventTarget(),
new TMethodEventJob<Server>(this, &Server::handleMotionPrimaryEvent)
);
m_events->adoptHandler(
m_events->forIPrimaryScreen().motionOnSecondary(), m_primaryClient->getEventTarget(),
new TMethodEventJob<Server>(this, &Server::handleMotionSecondaryEvent)
);
m_events->adoptHandler(
m_events->forIPrimaryScreen().wheel(), m_primaryClient->getEventTarget(),
new TMethodEventJob<Server>(this, &Server::handleWheelEvent)
);
m_events->adoptHandler(
m_events->forIPrimaryScreen().screensaverActivated(), m_primaryClient->getEventTarget(),
new TMethodEventJob<Server>(this, &Server::handleScreensaverActivatedEvent)
);
m_events->adoptHandler(
m_events->forIPrimaryScreen().screensaverDeactivated(), m_primaryClient->getEventTarget(),
new TMethodEventJob<Server>(this, &Server::handleScreensaverDeactivatedEvent)
);
m_events->adoptHandler(
m_events->forServer().switchToScreen(), m_inputFilter,
new TMethodEventJob<Server>(this, &Server::handleSwitchToScreenEvent)
);
m_events->adoptHandler(
m_events->forServer().switchInDirection(), m_inputFilter,
new TMethodEventJob<Server>(this, &Server::handleSwitchInDirectionEvent)
);
m_events->adoptHandler(
m_events->forServer().keyboardBroadcast(), m_inputFilter,
new TMethodEventJob<Server>(this, &Server::handleKeyboardBroadcastEvent)
);
m_events->adoptHandler(
m_events->forServer().lockCursorToScreen(), m_inputFilter,
new TMethodEventJob<Server>(this, &Server::handleLockCursorToScreenEvent)
);
m_events->adoptHandler(
m_events->forIPrimaryScreen().fakeInputBegin(), m_inputFilter,
new TMethodEventJob<Server>(this, &Server::handleFakeInputBeginEvent)
);
m_events->adoptHandler(
m_events->forIPrimaryScreen().fakeInputEnd(), m_inputFilter,
new TMethodEventJob<Server>(this, &Server::handleFakeInputEndEvent)
);
if (m_args.m_enableDragDrop) {
m_events->adoptHandler(
m_events->forFile().fileChunkSending(), this,
new TMethodEventJob<Server>(this, &Server::handleFileChunkSendingEvent)
);
m_events->adoptHandler(
m_events->forFile().fileRecieveCompleted(), this,
new TMethodEventJob<Server>(this, &Server::handleFileRecieveCompletedEvent)
);
}
// add connection
addClient(m_primaryClient);
// set initial configuration
setConfig(config);
// enable primary client
m_primaryClient->enable();
m_inputFilter->setPrimaryClient(m_primaryClient);
// Determine if scroll lock is already set. If so, lock the cursor to the
// primary screen
if (m_primaryClient->getToggleMask() & KeyModifierScrollLock) {
LOG((CLOG_NOTE "scroll lock is on, locking cursor to screen"));
m_lockedToScreen = true;
}
}
Server::~Server()
{
if (m_mock) {
return;
}
// remove event handlers and timers
m_events->removeHandler(m_events->forIKeyState().keyDown(), m_inputFilter);
m_events->removeHandler(m_events->forIKeyState().keyUp(), m_inputFilter);
m_events->removeHandler(m_events->forIKeyState().keyRepeat(), m_inputFilter);
m_events->removeHandler(m_events->forIPrimaryScreen().buttonDown(), m_inputFilter);
m_events->removeHandler(m_events->forIPrimaryScreen().buttonUp(), m_inputFilter);
m_events->removeHandler(m_events->forIPrimaryScreen().motionOnPrimary(), m_primaryClient->getEventTarget());
m_events->removeHandler(m_events->forIPrimaryScreen().motionOnSecondary(), m_primaryClient->getEventTarget());
m_events->removeHandler(m_events->forIPrimaryScreen().wheel(), m_primaryClient->getEventTarget());
m_events->removeHandler(m_events->forIPrimaryScreen().screensaverActivated(), m_primaryClient->getEventTarget());
m_events->removeHandler(m_events->forIPrimaryScreen().screensaverDeactivated(), m_primaryClient->getEventTarget());
m_events->removeHandler(m_events->forIPrimaryScreen().fakeInputBegin(), m_inputFilter);
m_events->removeHandler(m_events->forIPrimaryScreen().fakeInputEnd(), m_inputFilter);
m_events->removeHandler(Event::kTimer, this);
stopSwitch();
try {
// force immediate disconnection of secondary clients
disconnect();
} catch (std::exception &e) { // NOSONAR
LOG((CLOG_ERR "failed to disconnect: %s", e.what()));
}
for (OldClients::iterator index = m_oldClients.begin(); index != m_oldClients.end(); ++index) {
BaseClientProxy *client = index->first;
m_events->deleteTimer(index->second);
m_events->removeHandler(Event::kTimer, client);
m_events->removeHandler(m_events->forClientProxy().disconnected(), client);
delete client;
}
// remove input filter
m_inputFilter->setPrimaryClient(NULL);
// disable and disconnect primary client
m_primaryClient->disable();
removeClient(m_primaryClient);
}
bool Server::setConfig(const ServerConfig &config)
{
// refuse configuration if it doesn't include the primary screen
if (!config.isScreen(m_primaryClient->getName())) {
return false;
}
// close clients that are connected but being dropped from the
// configuration.
closeClients(config);
// cut over
processOptions();
// add ScrollLock as a hotkey to lock to the screen. this was a
// built-in feature in earlier releases and is now supported via
// the user configurable hotkey mechanism. if the user has already
// registered ScrollLock for something else then that will win but
// we will unfortunately generate a warning. if the user has
// configured a LockCursorToScreenAction then we don't add
// ScrollLock as a hotkey.
if (!m_disableLockToScreen && !m_config->hasLockToScreenAction()) {
IPlatformScreen::KeyInfo *key = IPlatformScreen::KeyInfo::alloc(kKeyScrollLock, 0, 0, 0);
InputFilter::Rule rule(new InputFilter::KeystrokeCondition(m_events, key));
rule.adoptAction(new InputFilter::LockCursorToScreenAction(m_events), true);
m_inputFilter->addFilterRule(rule);
}
// tell primary screen about reconfiguration
m_primaryClient->reconfigure(getActivePrimarySides());
// tell all (connected) clients about current options
for (ClientList::const_iterator index = m_clients.begin(); index != m_clients.end(); ++index) {
BaseClientProxy *client = index->second;
sendOptions(client);
}
return true;
}
void Server::adoptClient(BaseClientProxy *client)
{
assert(client != NULL);
// watch for client disconnection
m_events->adoptHandler(
m_events->forClientProxy().disconnected(), client,
new TMethodEventJob<Server>(this, &Server::handleClientDisconnected, client)
);
// name must be in our configuration
if (!m_config->isScreen(client->getName())) {
LOG((CLOG_WARN "unrecognised client name \"%s\", check server config", client->getName().c_str()));
closeClient(client, kMsgEUnknown);
return;
}
// add client to client list
if (!addClient(client)) {
// can only have one screen with a given name at any given time
LOG((CLOG_WARN "a client with name \"%s\" is already connected", getName(client).c_str()));
closeClient(client, kMsgEBusy);
return;
}
LOG((CLOG_NOTE "client \"%s\" has connected", getName(client).c_str()));
// send configuration options to client
sendOptions(client);
// activate screen saver on new client if active on the primary screen
if (m_activeSaver != NULL) {
client->screensaver(true);
}
// send notification
Server::ScreenConnectedInfo *info = new Server::ScreenConnectedInfo(getName(client));
m_events->addEvent(Event(m_events->forServer().connected(), m_primaryClient->getEventTarget(), info));
}
void Server::disconnect()
{
// close all secondary clients
if (m_clients.size() > 1 || !m_oldClients.empty()) {
Config emptyConfig(m_events);
closeClients(emptyConfig);
} else {
m_events->addEvent(Event(m_events->forServer().disconnected(), this));
}
}
std::string Server::protocolString() const
{
using enum ENetworkProtocol;
if (m_protocol == kSynergy) {
return kSynergyProtocolName;
} else if (m_protocol == kBarrier) {
return kBarrierProtocolName;
}
throw XInvalidProtocol();
}
UInt32 Server::getNumClients() const
{
return (SInt32)m_clients.size();
}
void Server::getClients(std::vector<String> &list) const
{
list.clear();
for (ClientList::const_iterator index = m_clients.begin(); index != m_clients.end(); ++index) {
list.push_back(index->first);
}
}
String Server::getName(const BaseClientProxy *client) const
{
String name = m_config->getCanonicalName(client->getName());
if (name.empty()) {
name = client->getName();
}
return name;
}
UInt32 Server::getActivePrimarySides() const
{
UInt32 sides = 0;
if (!isLockedToScreenServer()) {
if (hasAnyNeighbor(m_primaryClient, kLeft)) {
sides |= kLeftMask;
}
if (hasAnyNeighbor(m_primaryClient, kRight)) {
sides |= kRightMask;
}
if (hasAnyNeighbor(m_primaryClient, kTop)) {
sides |= kTopMask;
}
if (hasAnyNeighbor(m_primaryClient, kBottom)) {
sides |= kBottomMask;
}
}
return sides;
}
bool Server::isLockedToScreenServer() const
{
// locked if scroll-lock is toggled on
return m_lockedToScreen;
}
bool Server::isLockedToScreen() const
{
if (m_disableLockToScreen) {
return false;
}
// locked if we say we're locked
if (isLockedToScreenServer()) {
LOG((CLOG_NOTE "cursor is locked to screen, check scroll lock key"));
return true;
}
// locked if primary says we're locked
if (m_primaryClient->isLockedToScreen()) {
return true;
}
// not locked
return false;
}
SInt32 Server::getJumpZoneSize(BaseClientProxy *client) const
{
if (client == m_primaryClient) {
return m_primaryClient->getJumpZoneSize();
} else {
return 0;
}
}
void Server::switchScreen(BaseClientProxy *dst, SInt32 x, SInt32 y, bool forScreensaver)
{
assert(dst != NULL);
SInt32 dx, dy, dw, dh;
dst->getShape(dx, dy, dw, dh);
// any of these conditions seem to trigger when the portal permission dialog
// is visible on wayland. this was previously an assert, but that's pretty
// annoying since it makes the mouse unusable on the server and you'll have to
// ssh into your machine to kill it. better to just log a warning.
if (x < dx) {
LOG_WARN(
"on switch, x (%d) is less than the left boundary dx (%d)", //
x, dx
);
}
if (y < dy) {
LOG_WARN(
"on switch, y (%d) is less than the top boundary dy (%d)", //
y, dy
);
}
if (x >= dx + dw) {
LOG_WARN(
"on switch, x (%d) exceeds the right boundary (dx + width = %d)", //
x, dx + dw
);
}
if (y >= dy + dh) {
LOG_WARN(
"on switch, y (%d) exceeds the bottom boundary (dy + height = %d)", //
y, dy + dh
);
}
assert(m_active != NULL);
LOG((CLOG_INFO "switch from \"%s\" to \"%s\" at %d,%d", getName(m_active).c_str(), getName(dst).c_str(), x, y));
// stop waiting to switch
stopSwitch();
// record new position
m_x = x;
m_y = y;
m_xDelta = 0;
m_yDelta = 0;
m_xDelta2 = 0;
m_yDelta2 = 0;
// wrapping means leaving the active screen and entering it again.
// since that's a waste of time we skip that and just warp the
// mouse.
if (m_active != dst) {
// leave active screen
if (!m_active->leave()) {
// cannot leave screen
LOG((CLOG_WARN "can't leave screen"));
return;
}
// update the primary client's clipboards if we're leaving the
// primary screen.
if (m_active == m_primaryClient && m_enableClipboard) {
for (ClipboardID id = 0; id < kClipboardEnd; ++id) {
ClipboardInfo &clipboard = m_clipboards[id];
if (clipboard.m_clipboardOwner == getName(m_primaryClient)) {
onClipboardChanged(m_primaryClient, id, clipboard.m_clipboardSeqNum);
}
}
}
#if defined(__APPLE__)
if (dst != m_primaryClient) {
String secureInputApplication = m_primaryClient->getSecureInputApp();
if (secureInputApplication != "") {
// display notification on the server
m_primaryClient->secureInputNotification(secureInputApplication);
// display notification on the client
dst->secureInputNotification(secureInputApplication);
}
}
#endif
// cut over
m_active = dst;
// increment enter sequence number
++m_seqNum;
// enter new screen
m_active->enter(x, y, m_seqNum, m_primaryClient->getToggleMask(), forScreensaver);
if (m_enableClipboard) {
// send the clipboard data to new active screen
for (ClipboardID id = 0; id < kClipboardEnd; ++id) {
// Hackity hackity hack
if (m_clipboards[id].m_clipboard.marshall().size() > (m_maximumClipboardSize * 1024)) {
continue;
}
m_active->setClipboard(id, &m_clipboards[id].m_clipboard);
}
}
Server::SwitchToScreenInfo *info = Server::SwitchToScreenInfo::alloc(m_active->getName());
m_events->addEvent(Event(m_events->forServer().screenSwitched(), this, info));
} else {
m_active->mouseMove(x, y);
}
}
void Server::jumpToScreen(BaseClientProxy *newScreen)
{
assert(newScreen != NULL);
// record the current cursor position on the active screen
m_active->setJumpCursorPos(m_x, m_y);
// get the last cursor position on the target screen
SInt32 x, y;
newScreen->getJumpCursorPos(x, y);
switchScreen(newScreen, x, y, false);
}
float Server::mapToFraction(BaseClientProxy *client, EDirection dir, SInt32 x, SInt32 y) const
{
SInt32 sx, sy, sw, sh;
client->getShape(sx, sy, sw, sh);
switch (dir) {
case kLeft:
case kRight:
return static_cast<float>(y - sy + 0.5f) / static_cast<float>(sh);
case kTop:
case kBottom:
return static_cast<float>(x - sx + 0.5f) / static_cast<float>(sw);
case kNoDirection:
assert(0 && "bad direction");
break;
}
return 0.0f;
}
void Server::mapToPixel(BaseClientProxy *client, EDirection dir, float f, SInt32 &x, SInt32 &y) const
{
SInt32 sx, sy, sw, sh;
client->getShape(sx, sy, sw, sh);
switch (dir) {
case kLeft:
case kRight:
y = static_cast<SInt32>(f * sh) + sy;
break;
case kTop:
case kBottom:
x = static_cast<SInt32>(f * sw) + sx;
break;
case kNoDirection:
assert(0 && "bad direction");
break;
}
}
bool Server::hasAnyNeighbor(BaseClientProxy *client, EDirection dir) const
{
assert(client != NULL);
return m_config->hasNeighbor(getName(client), dir);
}
BaseClientProxy *Server::getNeighbor(BaseClientProxy *src, EDirection dir, SInt32 &x, SInt32 &y) const
{
// note -- must be locked on entry
assert(src != NULL);
// get source screen name
String srcName = getName(src);
assert(!srcName.empty());
LOG((CLOG_DEBUG2 "find neighbor on %s of \"%s\"", Config::dirName(dir), srcName.c_str()));
// convert position to fraction
float t = mapToFraction(src, dir, x, y);
// search for the closest neighbor that exists in direction dir
float tTmp;
for (;;) {
String dstName(m_config->getNeighbor(srcName, dir, t, &tTmp));
// if nothing in that direction then return NULL. if the
// destination is the source then we can make no more
// progress in this direction. since we haven't found a
// connected neighbor we return NULL.
if (dstName.empty()) {
LOG((CLOG_DEBUG2 "no neighbor on %s of \"%s\"", Config::dirName(dir), srcName.c_str()));
return NULL;
}
// look up neighbor cell. if the screen is connected and
// ready then we can stop.
ClientList::const_iterator index = m_clients.find(dstName);
if (index != m_clients.end()) {
LOG((CLOG_DEBUG2 "\"%s\" is on %s of \"%s\" at %f", dstName.c_str(), Config::dirName(dir), srcName.c_str(), t));
mapToPixel(index->second, dir, tTmp, x, y);
return index->second;
}
// skip over unconnected screen
LOG((CLOG_DEBUG2 "ignored \"%s\" on %s of \"%s\"", dstName.c_str(), Config::dirName(dir), srcName.c_str()));
srcName = dstName;
// use position on skipped screen
t = tTmp;
}
}
BaseClientProxy *Server::mapToNeighbor(BaseClientProxy *src, EDirection srcSide, SInt32 &x, SInt32 &y) const
{
// note -- must be locked on entry
assert(src != NULL);
// get the first neighbor
BaseClientProxy *dst = getNeighbor(src, srcSide, x, y);
if (dst == NULL) {
return NULL;
}
// get the source screen's size
SInt32 dx, dy, dw, dh;
BaseClientProxy *lastGoodScreen = src;
lastGoodScreen->getShape(dx, dy, dw, dh);
// find destination screen, adjusting x or y (but not both). the
// searches are done in a sort of canonical screen space where
// the upper-left corner is 0,0 for each screen. we adjust from
// actual to canonical position on entry to and from canonical to
// actual on exit from the search.
switch (srcSide) {
case kLeft:
x -= dx;
while (dst != NULL) {
lastGoodScreen = dst;
lastGoodScreen->getShape(dx, dy, dw, dh);
x += dw;
if (x >= 0) {
break;
}
LOG((CLOG_DEBUG2 "skipping over screen %s", getName(dst).c_str()));
dst = getNeighbor(lastGoodScreen, srcSide, x, y);
}
assert(lastGoodScreen != NULL);
x += dx;
break;
case kRight:
x -= dx;
while (dst != NULL) {
x -= dw;
lastGoodScreen = dst;
lastGoodScreen->getShape(dx, dy, dw, dh);
if (x < dw) {
break;
}
LOG((CLOG_DEBUG2 "skipping over screen %s", getName(dst).c_str()));
dst = getNeighbor(lastGoodScreen, srcSide, x, y);
}
assert(lastGoodScreen != NULL);
x += dx;
break;
case kTop:
y -= dy;
while (dst != NULL) {
lastGoodScreen = dst;
lastGoodScreen->getShape(dx, dy, dw, dh);
y += dh;
if (y >= 0) {
break;
}
LOG((CLOG_DEBUG2 "skipping over screen %s", getName(dst).c_str()));
dst = getNeighbor(lastGoodScreen, srcSide, x, y);
}
assert(lastGoodScreen != NULL);
y += dy;
break;
case kBottom:
y -= dy;
while (dst != NULL) {
y -= dh;
lastGoodScreen = dst;
lastGoodScreen->getShape(dx, dy, dw, dh);
if (y < dh) {
break;
}
LOG((CLOG_DEBUG2 "skipping over screen %s", getName(dst).c_str()));
dst = getNeighbor(lastGoodScreen, srcSide, x, y);
}
assert(lastGoodScreen != NULL);
y += dy;
break;
case kNoDirection:
assert(0 && "bad direction");
return NULL;
}
// save destination screen
assert(lastGoodScreen != NULL);
dst = lastGoodScreen;
// if entering primary screen then be sure to move in far enough
// to avoid the jump zone. if entering a side that doesn't have
// a neighbor (i.e. an asymmetrical side) then we don't need to
// move inwards because that side can't provoke a jump.
avoidJumpZone(dst, srcSide, x, y);
return dst;
}
void Server::avoidJumpZone(BaseClientProxy *dst, EDirection dir, SInt32 &x, SInt32 &y) const
{
// we only need to avoid jump zones on the primary screen
if (dst != m_primaryClient) {
return;
}
const String dstName(getName(dst));
SInt32 dx, dy, dw, dh;
dst->getShape(dx, dy, dw, dh);
float t = mapToFraction(dst, dir, x, y);
SInt32 z = getJumpZoneSize(dst);
// move in far enough to avoid the jump zone. if entering a side
// that doesn't have a neighbor (i.e. an asymmetrical side) then we
// don't need to move inwards because that side can't provoke a jump.
switch (dir) {
case kLeft:
if (!m_config->getNeighbor(dstName, kRight, t, NULL).empty() && x > dx + dw - 1 - z)
x = dx + dw - 1 - z;
break;
case kRight:
if (!m_config->getNeighbor(dstName, kLeft, t, NULL).empty() && x < dx + z)
x = dx + z;
break;
case kTop:
if (!m_config->getNeighbor(dstName, kBottom, t, NULL).empty() && y > dy + dh - 1 - z)
y = dy + dh - 1 - z;
break;
case kBottom:
if (!m_config->getNeighbor(dstName, kTop, t, NULL).empty() && y < dy + z)
y = dy + z;
break;
case kNoDirection:
assert(0 && "bad direction");
}
}
bool Server::isSwitchOkay(
BaseClientProxy *newScreen, EDirection dir, SInt32 x, SInt32 y, SInt32 xActive, SInt32 yActive
)
{
LOG((CLOG_DEBUG1 "try to leave \"%s\" on %s", getName(m_active).c_str(), Config::dirName(dir)));
// is there a neighbor?
if (newScreen == NULL) {
// there's no neighbor. we don't want to switch and we don't
// want to try to switch later.
LOG((CLOG_DEBUG1 "no neighbor %s", Config::dirName(dir)));
stopSwitch();
return false;
}
// should we switch or not?
bool preventSwitch = false;
bool allowSwitch = false;
// note if the switch direction has changed. save the new
// direction and screen if so.
bool isNewDirection = (dir != m_switchDir);
if (isNewDirection || m_switchScreen == NULL) {
m_switchDir = dir;
m_switchScreen = newScreen;
}
// is this a double tap and do we care?
if (!allowSwitch && m_switchTwoTapDelay > 0.0) {
if (isNewDirection || !isSwitchTwoTapStarted() || !shouldSwitchTwoTap()) {
// tapping a different or new edge or second tap not
// fast enough. prepare for second tap.
preventSwitch = true;
startSwitchTwoTap();
} else {
// got second tap
allowSwitch = true;
}
}
// if waiting before a switch then prepare to switch later
if (!allowSwitch && m_switchWaitDelay > 0.0) {
if (isNewDirection || !isSwitchWaitStarted()) {
startSwitchWait(x, y);
}
preventSwitch = true;
}
// are we in a locked corner? first check if screen has the option set
// and, if not, check the global options.
const Config::ScreenOptions *options = m_config->getOptions(getName(m_active));
if (options == NULL || options->count(kOptionScreenSwitchCorners) == 0) {
options = m_config->getOptions("");
}
if (options != NULL && options->count(kOptionScreenSwitchCorners) > 0) {
// get corner mask and size
Config::ScreenOptions::const_iterator i = options->find(kOptionScreenSwitchCorners);
UInt32 corners = static_cast<UInt32>(i->second);
i = options->find(kOptionScreenSwitchCornerSize);
SInt32 size = 0;
if (i != options->end()) {
size = i->second;
}
// see if we're in a locked corner
if ((getCorner(m_active, xActive, yActive, size) & corners) != 0) {
// yep, no switching
LOG((CLOG_DEBUG1 "locked in corner"));
preventSwitch = true;
stopSwitch();
}
}
// ignore if mouse is locked to screen and don't try to switch later
if (!preventSwitch && isLockedToScreen()) {
LOG((CLOG_DEBUG1 "locked to screen"));
preventSwitch = true;
stopSwitch();
}
// check for optional needed modifiers
KeyModifierMask mods = this->m_primaryClient->getToggleMask();
if (!preventSwitch && ((this->m_switchNeedsShift && ((mods & KeyModifierShift) != KeyModifierShift)) ||
(this->m_switchNeedsControl && ((mods & KeyModifierControl) != KeyModifierControl)) ||
(this->m_switchNeedsAlt && ((mods & KeyModifierAlt) != KeyModifierAlt)))) {
LOG((CLOG_DEBUG1 "need modifiers to switch"));
preventSwitch = true;
stopSwitch();
}
return !preventSwitch;
}
void Server::noSwitch(SInt32 x, SInt32 y)
{
armSwitchTwoTap(x, y);
stopSwitchWait();
}
void Server::stopSwitch()
{
if (m_switchScreen != NULL) {
m_switchScreen = NULL;
m_switchDir = kNoDirection;
stopSwitchTwoTap();
stopSwitchWait();
}
}
void Server::startSwitchTwoTap()
{
m_switchTwoTapEngaged = true;
m_switchTwoTapArmed = false;
m_switchTwoTapTimer.reset();
LOG((CLOG_DEBUG1 "waiting for second tap"));
}
void Server::armSwitchTwoTap(SInt32 x, SInt32 y)
{
if (m_switchTwoTapEngaged) {
if (m_switchTwoTapTimer.getTime() > m_switchTwoTapDelay) {
// second tap took too long. disengage.
stopSwitchTwoTap();
} else if (!m_switchTwoTapArmed) {
// still time for a double tap. see if we left the tap
// zone and, if so, arm the two tap.
SInt32 ax, ay, aw, ah;
m_active->getShape(ax, ay, aw, ah);
SInt32 tapZone = m_primaryClient->getJumpZoneSize();
if (tapZone < m_switchTwoTapZone) {
tapZone = m_switchTwoTapZone;
}
if (x >= ax + tapZone && x < ax + aw - tapZone && y >= ay + tapZone && y < ay + ah - tapZone) {
// win32 can generate bogus mouse events that appear to
// move in the opposite direction that the mouse actually
// moved. try to ignore that crap here.
switch (m_switchDir) {
case kLeft:
m_switchTwoTapArmed = (m_xDelta > 0 && m_xDelta2 > 0);
break;
case kRight:
m_switchTwoTapArmed = (m_xDelta < 0 && m_xDelta2 < 0);
break;
case kTop:
m_switchTwoTapArmed = (m_yDelta > 0 && m_yDelta2 > 0);
break;
case kBottom:
m_switchTwoTapArmed = (m_yDelta < 0 && m_yDelta2 < 0);
break;
default:
break;
}
}
}
}
}
void Server::stopSwitchTwoTap()
{
m_switchTwoTapEngaged = false;
m_switchTwoTapArmed = false;
}
bool Server::isSwitchTwoTapStarted() const
{
return m_switchTwoTapEngaged;
}
bool Server::shouldSwitchTwoTap() const
{
// this is the second tap if two-tap is armed and this tap
// came fast enough
return (m_switchTwoTapArmed && m_switchTwoTapTimer.getTime() <= m_switchTwoTapDelay);
}
void Server::startSwitchWait(SInt32 x, SInt32 y)
{
stopSwitchWait();
m_switchWaitX = x;
m_switchWaitY = y;
m_switchWaitTimer = m_events->newOneShotTimer(m_switchWaitDelay, this);
LOG((CLOG_DEBUG1 "waiting to switch"));
}
void Server::stopSwitchWait()
{
if (m_switchWaitTimer != NULL) {
m_events->deleteTimer(m_switchWaitTimer);
m_switchWaitTimer = NULL;
}
}
bool Server::isSwitchWaitStarted() const
{
return (m_switchWaitTimer != NULL);
}
UInt32 Server::getCorner(BaseClientProxy *client, SInt32 x, SInt32 y, SInt32 size) const
{
assert(client != NULL);
// get client screen shape
SInt32 ax, ay, aw, ah;
client->getShape(ax, ay, aw, ah);
// check for x,y on the left or right
SInt32 xSide;
if (x <= ax) {
xSide = -1;
} else if (x >= ax + aw - 1) {
xSide = 1;
} else {
xSide = 0;
}
// check for x,y on the top or bottom
SInt32 ySide;
if (y <= ay) {
ySide = -1;
} else if (y >= ay + ah - 1) {
ySide = 1;
} else {
ySide = 0;
}
// if against the left or right then check if y is within size
if (xSide != 0) {
if (y < ay + size) {
return (xSide < 0) ? kTopLeftMask : kTopRightMask;
} else if (y >= ay + ah - size) {
return (xSide < 0) ? kBottomLeftMask : kBottomRightMask;
}
}
// if against the left or right then check if y is within size
if (ySide != 0) {
if (x < ax + size) {
return (ySide < 0) ? kTopLeftMask : kBottomLeftMask;
} else if (x >= ax + aw - size) {
return (ySide < 0) ? kTopRightMask : kBottomRightMask;
}
}
return kNoCornerMask;
}
void Server::stopRelativeMoves()
{
if (m_relativeMoves && m_active != m_primaryClient) {
// warp to the center of the active client so we know where we are
SInt32 ax, ay, aw, ah;
m_active->getShape(ax, ay, aw, ah);
m_x = ax + (aw >> 1);
m_y = ay + (ah >> 1);
m_xDelta = 0;
m_yDelta = 0;
m_xDelta2 = 0;
m_yDelta2 = 0;
LOG((CLOG_DEBUG2 "synchronize move on %s by %d,%d", getName(m_active).c_str(), m_x, m_y));
m_active->mouseMove(m_x, m_y);
}
}
void Server::sendOptions(BaseClientProxy *client) const
{
OptionsList optionsList;
// look up options for client
const Config::ScreenOptions *options = m_config->getOptions(getName(client));
if (options != NULL) {
// convert options to a more convenient form for sending
optionsList.reserve(2 * options->size());
for (Config::ScreenOptions::const_iterator index = options->begin(); index != options->end(); ++index) {
optionsList.push_back(index->first);
optionsList.push_back(static_cast<UInt32>(index->second));
}
}
// look up global options
options = m_config->getOptions("");
if (options != NULL) {
// convert options to a more convenient form for sending
optionsList.reserve(optionsList.size() + 2 * options->size());
for (Config::ScreenOptions::const_iterator index = options->begin(); index != options->end(); ++index) {
optionsList.push_back(index->first);
optionsList.push_back(static_cast<UInt32>(index->second));
}
}
// send the options
client->resetOptions();
client->setOptions(optionsList);
}
void Server::processOptions()
{
const Config::ScreenOptions *options = m_config->getOptions("");
if (options == NULL) {
return;
}
m_switchNeedsShift = false; // it seems if i don't add these
m_switchNeedsControl = false; // lines, the 'reload config' option
m_switchNeedsAlt = false; // doesnt' work correct.
bool newRelativeMoves = m_relativeMoves;
for (Config::ScreenOptions::const_iterator index = options->begin(); index != options->end(); ++index) {
const OptionID id = index->first;
const OptionValue value = index->second;
if (id == kOptionProtocol) {
using enum ENetworkProtocol;
const auto enumValue = static_cast<ENetworkProtocol>(value);
if (enumValue == kSynergy) {
m_protocol = kSynergy;
} else if (enumValue == kBarrier) {
m_protocol = kBarrier;
} else {
throw XInvalidProtocol();
}
} else if (id == kOptionScreenSwitchDelay) {
m_switchWaitDelay = 1.0e-3 * static_cast<double>(value);
if (m_switchWaitDelay < 0.0) {
m_switchWaitDelay = 0.0;
}
stopSwitchWait();
} else if (id == kOptionScreenSwitchTwoTap) {
m_switchTwoTapDelay = 1.0e-3 * static_cast<double>(value);
if (m_switchTwoTapDelay < 0.0) {
m_switchTwoTapDelay = 0.0;
}
stopSwitchTwoTap();
} else if (id == kOptionScreenSwitchNeedsControl) {
m_switchNeedsControl = (value != 0);
} else if (id == kOptionScreenSwitchNeedsShift) {
m_switchNeedsShift = (value != 0);
} else if (id == kOptionScreenSwitchNeedsAlt) {
m_switchNeedsAlt = (value != 0);
} else if (id == kOptionRelativeMouseMoves) {
newRelativeMoves = (value != 0);
} else if (id == kOptionDisableLockToScreen) {
m_disableLockToScreen = (value != 0);
} else if (id == kOptionClipboardSharing) {
m_enableClipboard = value;
if (!m_enableClipboard) {
LOG((CLOG_NOTE "clipboard sharing is disabled"));
}
} else if (id == kOptionClipboardSharingSize) {
if (value <= 0) {
m_maximumClipboardSize = 0;
LOG((CLOG_NOTE "clipboard sharing is disabled because the "
"maximum shared clipboard size is set to 0"));
} else {
m_maximumClipboardSize = static_cast<size_t>(value);
}
}
}
if (m_relativeMoves && !newRelativeMoves) {
stopRelativeMoves();
}
m_relativeMoves = newRelativeMoves;
}
void Server::handleShapeChanged(const Event &, void *vclient)
{
// ignore events from unknown clients
BaseClientProxy *client = static_cast<BaseClientProxy *>(vclient);
if (m_clientSet.count(client) == 0) {
return;
}
LOG((CLOG_DEBUG "screen \"%s\" shape changed", getName(client).c_str()));
// update jump coordinate
SInt32 x, y;
client->getCursorPos(x, y);
client->setJumpCursorPos(x, y);
// update the mouse coordinates
if (client == m_active) {
m_x = x;
m_y = y;
}
// handle resolution change to primary screen
if (client == m_primaryClient) {
if (client == m_active) {
onMouseMovePrimary(m_x, m_y);
} else {
onMouseMoveSecondary(0, 0);
}
}
}
void Server::handleClipboardGrabbed(const Event &event, void *vclient)
{
if (!m_enableClipboard || (m_maximumClipboardSize == 0)) {
return;
}
// ignore events from unknown clients
BaseClientProxy *grabber = static_cast<BaseClientProxy *>(vclient);
if (m_clientSet.count(grabber) == 0) {
return;
}
const IScreen::ClipboardInfo *info = static_cast<const IScreen::ClipboardInfo *>(event.getData());
// ignore grab if sequence number is old. always allow primary
// screen to grab.
ClipboardInfo &clipboard = m_clipboards[info->m_id];
if (grabber != m_primaryClient && info->m_sequenceNumber < clipboard.m_clipboardSeqNum) {
LOG((CLOG_INFO "ignored screen \"%s\" grab of clipboard %d", getName(grabber).c_str(), info->m_id));
return;
}
// mark screen as owning clipboard
LOG(
(CLOG_INFO "screen \"%s\" grabbed clipboard %d from \"%s\"", getName(grabber).c_str(), info->m_id,
clipboard.m_clipboardOwner.c_str())
);
clipboard.m_clipboardOwner = getName(grabber);
clipboard.m_clipboardSeqNum = info->m_sequenceNumber;
// clear the clipboard data (since it's not known at this point)
if (clipboard.m_clipboard.open(0)) {
clipboard.m_clipboard.empty();
clipboard.m_clipboard.close();
}
clipboard.m_clipboardData = clipboard.m_clipboard.marshall();
// tell all other screens to take ownership of clipboard. tell the
// grabber that it's clipboard isn't dirty.
for (ClientList::iterator index = m_clients.begin(); index != m_clients.end(); ++index) {
BaseClientProxy *client = index->second;
if (client == grabber) {
client->setClipboardDirty(info->m_id, false);
} else {
client->grabClipboard(info->m_id);
}
}
if (grabber == m_primaryClient && m_active != m_primaryClient) {
LOG((CLOG_INFO "clipboard grabbed, but we are already changed active "
"screen. Resend clipboard data"));
for (ClipboardID id = 0; id < kClipboardEnd; ++id) {
onClipboardChanged(m_primaryClient, id, m_clipboards[id].m_clipboardSeqNum);
}
}
}
void Server::handleClipboardChanged(const Event &event, void *vclient)
{
// ignore events from unknown clients
BaseClientProxy *sender = static_cast<BaseClientProxy *>(vclient);
if (m_clientSet.count(sender) == 0) {
return;
}
const IScreen::ClipboardInfo *info = static_cast<const IScreen::ClipboardInfo *>(event.getData());
onClipboardChanged(sender, info->m_id, info->m_sequenceNumber);
}
void Server::handleKeyDownEvent(const Event &event, void *)
{
IPlatformScreen::KeyInfo *info = static_cast<IPlatformScreen::KeyInfo *>(event.getData());
auto lang = AppUtil::instance().getCurrentLanguageCode();
onKeyDown(info->m_key, info->m_mask, info->m_button, lang, info->m_screens);
}
void Server::handleKeyUpEvent(const Event &event, void *)
{
IPlatformScreen::KeyInfo *info = static_cast<IPlatformScreen::KeyInfo *>(event.getData());
onKeyUp(info->m_key, info->m_mask, info->m_button, info->m_screens);
}
void Server::handleKeyRepeatEvent(const Event &event, void *)
{
IPlatformScreen::KeyInfo *info = static_cast<IPlatformScreen::KeyInfo *>(event.getData());
auto lang = AppUtil::instance().getCurrentLanguageCode();
onKeyRepeat(info->m_key, info->m_mask, info->m_count, info->m_button, lang);
}
void Server::handleButtonDownEvent(const Event &event, void *)
{
IPlatformScreen::ButtonInfo *info = static_cast<IPlatformScreen::ButtonInfo *>(event.getData());
onMouseDown(info->m_button);
}
void Server::handleButtonUpEvent(const Event &event, void *)
{
IPlatformScreen::ButtonInfo *info = static_cast<IPlatformScreen::ButtonInfo *>(event.getData());
onMouseUp(info->m_button);
}
void Server::handleMotionPrimaryEvent(const Event &event, void *)
{
IPlatformScreen::MotionInfo *info = static_cast<IPlatformScreen::MotionInfo *>(event.getData());
onMouseMovePrimary(info->m_x, info->m_y);
}
void Server::handleMotionSecondaryEvent(const Event &event, void *)
{
IPlatformScreen::MotionInfo *info = static_cast<IPlatformScreen::MotionInfo *>(event.getData());
onMouseMoveSecondary(info->m_x, info->m_y);
}
void Server::handleWheelEvent(const Event &event, void *)
{
IPlatformScreen::WheelInfo *info = static_cast<IPlatformScreen::WheelInfo *>(event.getData());
onMouseWheel(info->m_xDelta, info->m_yDelta);
}
void Server::handleScreensaverActivatedEvent(const Event &, void *)
{
onScreensaver(true);
}
void Server::handleScreensaverDeactivatedEvent(const Event &, void *)
{
onScreensaver(false);
}
void Server::handleSwitchWaitTimeout(const Event &, void *)
{
// ignore if mouse is locked to screen
if (isLockedToScreen()) {
LOG((CLOG_DEBUG1 "locked to screen"));
stopSwitch();
return;
}
// switch screen
switchScreen(m_switchScreen, m_switchWaitX, m_switchWaitY, false);
}
void Server::handleClientDisconnected(const Event &, void *vclient)
{
// client has disconnected. it might be an old client or an
// active client. we don't care so just handle it both ways.
BaseClientProxy *client = static_cast<BaseClientProxy *>(vclient);
removeActiveClient(client);
removeOldClient(client);
delete client;
m_clientListener->restart();
}
void Server::handleClientCloseTimeout(const Event &, void *vclient)
{
// client took too long to disconnect. just dump it.
BaseClientProxy *client = static_cast<BaseClientProxy *>(vclient);
LOG((CLOG_NOTE "forced disconnection of client \"%s\"", getName(client).c_str()));
removeOldClient(client);
delete client;
}
void Server::handleSwitchToScreenEvent(const Event &event, void *)
{
SwitchToScreenInfo *info = static_cast<SwitchToScreenInfo *>(event.getData());
ClientList::const_iterator index = m_clients.find(info->m_screen);
if (index == m_clients.end()) {
LOG((CLOG_DEBUG1 "screen \"%s\" not active", info->m_screen));
} else {
jumpToScreen(index->second);
}
}
void Server::handleSwitchInDirectionEvent(const Event &event, void *)
{
SwitchInDirectionInfo *info = static_cast<SwitchInDirectionInfo *>(event.getData());
// jump to screen in chosen direction from center of this screen
SInt32 x = m_x, y = m_y;
BaseClientProxy *newScreen = getNeighbor(m_active, info->m_direction, x, y);
if (newScreen == NULL) {
LOG((CLOG_DEBUG1 "no neighbor %s", Config::dirName(info->m_direction)));
} else {
jumpToScreen(newScreen);
}
}
void Server::handleKeyboardBroadcastEvent(const Event &event, void *)
{
KeyboardBroadcastInfo *info = (KeyboardBroadcastInfo *)event.getData();
// choose new state
bool newState;
switch (info->m_state) {
case KeyboardBroadcastInfo::kOff:
newState = false;
break;
default:
case KeyboardBroadcastInfo::kOn:
newState = true;
break;
case KeyboardBroadcastInfo::kToggle:
newState = !m_keyboardBroadcasting;
break;
}
// enter new state
if (newState != m_keyboardBroadcasting || info->m_screens != m_keyboardBroadcastingScreens) {
m_keyboardBroadcasting = newState;
m_keyboardBroadcastingScreens = info->m_screens;
LOG(
(CLOG_DEBUG "keyboard broadcasting %s: %s", m_keyboardBroadcasting ? "on" : "off",
m_keyboardBroadcastingScreens.c_str())
);
}
}
void Server::handleLockCursorToScreenEvent(const Event &event, void *)
{
LockCursorToScreenInfo *info = (LockCursorToScreenInfo *)event.getData();
// choose new state
bool newState;
switch (info->m_state) {
case LockCursorToScreenInfo::kOff:
newState = false;
break;
default:
case LockCursorToScreenInfo::kOn:
newState = true;
break;
case LockCursorToScreenInfo::kToggle:
newState = !m_lockedToScreen;
break;
}
// enter new state
if (newState != m_lockedToScreen) {
m_lockedToScreen = newState;
LOG((CLOG_NOTE "cursor %s current screen", m_lockedToScreen ? "locked to" : "unlocked from"));
m_primaryClient->reconfigure(getActivePrimarySides());
if (!isLockedToScreenServer()) {
stopRelativeMoves();
}
}
}
void Server::handleFakeInputBeginEvent(const Event &, void *)
{
m_primaryClient->fakeInputBegin();
}
void Server::handleFakeInputEndEvent(const Event &, void *)
{
m_primaryClient->fakeInputEnd();
}
void Server::handleFileChunkSendingEvent(const Event &event, void *)
{
onFileChunkSending(event.getDataObject());
}
void Server::handleFileRecieveCompletedEvent(const Event &event, void *)
{
onFileRecieveCompleted();
}
void Server::onClipboardChanged(BaseClientProxy *sender, ClipboardID id, UInt32 seqNum)
{
ClipboardInfo &clipboard = m_clipboards[id];
// ignore update if sequence number is old
if (seqNum < clipboard.m_clipboardSeqNum) {
LOG((CLOG_INFO "ignored screen \"%s\" update of clipboard %d (missequenced)", getName(sender).c_str(), id));
return;
}
// should be the expected client
assert(sender == m_clients.find(clipboard.m_clipboardOwner)->second);
// get data
sender->getClipboard(id, &clipboard.m_clipboard);
String data = clipboard.m_clipboard.marshall();
if (data.size() > m_maximumClipboardSize * 1024) {
LOG(
(CLOG_NOTE "not updating clipboard because it's over the size limit "
"(%i KB) configured by the server",
m_maximumClipboardSize)
);
return;
}
// ignore if data hasn't changed
if (data == clipboard.m_clipboardData) {
LOG((CLOG_DEBUG "ignored screen \"%s\" update of clipboard %d (unchanged)", clipboard.m_clipboardOwner.c_str(), id)
);
return;
}
// got new data
LOG((CLOG_INFO "screen \"%s\" updated clipboard %d", clipboard.m_clipboardOwner.c_str(), id));
clipboard.m_clipboardData = data;
// tell all clients except the sender that the clipboard is dirty
for (ClientList::const_iterator index = m_clients.begin(); index != m_clients.end(); ++index) {
BaseClientProxy *client = index->second;
client->setClipboardDirty(id, client != sender);
}
// send the new clipboard to the active screen
m_active->setClipboard(id, &clipboard.m_clipboard);
}
void Server::onScreensaver(bool activated)
{
LOG((CLOG_DEBUG "onScreenSaver %s", activated ? "activated" : "deactivated"));
if (activated) {
// save current screen and position
m_activeSaver = m_active;
m_xSaver = m_x;
m_ySaver = m_y;
// jump to primary screen
if (m_active != m_primaryClient) {
switchScreen(m_primaryClient, 0, 0, true);
}
} else {
// jump back to previous screen and position. we must check
// that the position is still valid since the screen may have
// changed resolutions while the screen saver was running.
if (m_activeSaver != NULL && m_activeSaver != m_primaryClient) {
// check position
BaseClientProxy *screen = m_activeSaver;
SInt32 x, y, w, h;
screen->getShape(x, y, w, h);
SInt32 zoneSize = getJumpZoneSize(screen);
if (m_xSaver < x + zoneSize) {
m_xSaver = x + zoneSize;
} else if (m_xSaver >= x + w - zoneSize) {
m_xSaver = x + w - zoneSize - 1;
}
if (m_ySaver < y + zoneSize) {
m_ySaver = y + zoneSize;
} else if (m_ySaver >= y + h - zoneSize) {
m_ySaver = y + h - zoneSize - 1;
}
// jump
switchScreen(screen, m_xSaver, m_ySaver, false);
}
// reset state
m_activeSaver = NULL;
}
// send message to all clients
for (ClientList::const_iterator index = m_clients.begin(); index != m_clients.end(); ++index) {
BaseClientProxy *client = index->second;
client->screensaver(activated);
}
}
void Server::onKeyDown(KeyID id, KeyModifierMask mask, KeyButton button, const String &lang, const char *screens)
{
LOG((CLOG_DEBUG1 "onKeyDown id=%d mask=0x%04x button=0x%04x lang=%s", id, mask, button, lang.c_str()));
assert(m_active != NULL);
// relay
if (!m_keyboardBroadcasting && IKeyState::KeyInfo::isDefault(screens)) {
m_active->keyDown(id, mask, button, lang);
} else {
if (!screens && m_keyboardBroadcasting) {
screens = m_keyboardBroadcastingScreens.c_str();
if (IKeyState::KeyInfo::isDefault(screens)) {
screens = "*";
}
}
for (ClientList::const_iterator index = m_clients.begin(); index != m_clients.end(); ++index) {
if (IKeyState::KeyInfo::contains(screens, index->first)) {
index->second->keyDown(id, mask, button, lang);
}
}
}
}
void Server::onKeyUp(KeyID id, KeyModifierMask mask, KeyButton button, const char *screens)
{
LOG((CLOG_DEBUG1 "onKeyUp id=%d mask=0x%04x button=0x%04x", id, mask, button));
assert(m_active != NULL);
// relay
if (!m_keyboardBroadcasting && IKeyState::KeyInfo::isDefault(screens)) {
m_active->keyUp(id, mask, button);
} else {
if (!screens && m_keyboardBroadcasting) {
screens = m_keyboardBroadcastingScreens.c_str();
if (IKeyState::KeyInfo::isDefault(screens)) {
screens = "*";
}
}
for (ClientList::const_iterator index = m_clients.begin(); index != m_clients.end(); ++index) {
if (IKeyState::KeyInfo::contains(screens, index->first)) {
index->second->keyUp(id, mask, button);
}
}
}
}
void Server::onKeyRepeat(KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, const String &lang)
{
LOG(
(CLOG_DEBUG1 "onKeyRepeat id=%d mask=0x%04x count=%d button=0x%04x lang=\"%s\"", id, mask, count, button,
lang.c_str())
);
assert(m_active != NULL);
// relay
m_active->keyRepeat(id, mask, count, button, lang);
}
void Server::onMouseDown(ButtonID id)
{
LOG((CLOG_DEBUG1 "onMouseDown id=%d", id));
assert(m_active != NULL);
// relay
m_active->mouseDown(id);
// reset this variable back to default value true
m_waitDragInfoThread = true;
}
void Server::onMouseUp(ButtonID id)
{
LOG((CLOG_DEBUG1 "onMouseUp id=%d", id));
assert(m_active != NULL);
// relay
m_active->mouseUp(id);
if (m_ignoreFileTransfer) {
m_ignoreFileTransfer = false;
return;
}
if (m_args.m_enableDragDrop) {
if (!m_screen->isOnScreen()) {
String &file = m_screen->getDraggingFilename();
if (!file.empty()) {
sendFileToClient(file.c_str());
}
}
// always clear dragging filename
m_screen->clearDraggingFilename();
}
}
bool Server::onMouseMovePrimary(SInt32 x, SInt32 y)
{
LOG((CLOG_DEBUG4 "onMouseMovePrimary %d,%d", x, y));
// mouse move on primary (server's) screen
if (m_active != m_primaryClient) {
// stale event -- we're actually on a secondary screen
return false;
}
// save last delta
m_xDelta2 = m_xDelta;
m_yDelta2 = m_yDelta;
// save current delta
m_xDelta = x - m_x;
m_yDelta = y - m_y;
// save position
m_x = x;
m_y = y;
// get screen shape
SInt32 ax, ay, aw, ah;
m_active->getShape(ax, ay, aw, ah);
SInt32 zoneSize = getJumpZoneSize(m_active);
// clamp position to screen
SInt32 xc = x, yc = y;
if (xc < ax + zoneSize) {
xc = ax;
} else if (xc >= ax + aw - zoneSize) {
xc = ax + aw - 1;
}
if (yc < ay + zoneSize) {
yc = ay;
} else if (yc >= ay + ah - zoneSize) {
yc = ay + ah - 1;
}
// see if we should change screens
// when the cursor is in a corner, there may be a screen either
// horizontally or vertically. check both directions.
EDirection dirh = kNoDirection, dirv = kNoDirection;
SInt32 xh = x, yv = y;
if (x < ax + zoneSize) {
xh -= zoneSize;
dirh = kLeft;
} else if (x >= ax + aw - zoneSize) {
xh += zoneSize;
dirh = kRight;
}
if (y < ay + zoneSize) {
yv -= zoneSize;
dirv = kTop;
} else if (y >= ay + ah - zoneSize) {
yv += zoneSize;
dirv = kBottom;
}
if (dirh == kNoDirection && dirv == kNoDirection) {
// still on local screen
noSwitch(x, y);
return false;
}
// check both horizontally and vertically
EDirection dirs[] = {dirh, dirv};
SInt32 xs[] = {xh, x}, ys[] = {y, yv};
for (int i = 0; i < 2; ++i) {
EDirection dir = dirs[i];
if (dir == kNoDirection) {
continue;
}
x = xs[i], y = ys[i];
// get jump destination
BaseClientProxy *newScreen = mapToNeighbor(m_active, dir, x, y);
// should we switch or not?
if (isSwitchOkay(newScreen, dir, x, y, xc, yc)) {
if (m_args.m_enableDragDrop && m_screen->isDraggingStarted() && m_active != newScreen && m_waitDragInfoThread) {
if (!m_sendDragInfoThread) {
m_sendDragInfoThread.reset(new Thread(new TMethodJob<Server>(this, &Server::sendDragInfoThread, newScreen)));
}
return false;
}
// switch screen
switchScreen(newScreen, x, y, false);
m_waitDragInfoThread = true;
return true;
}
}
return false;
}
void Server::sendDragInfoThread(void *arg)
{
BaseClientProxy *newScreen = static_cast<BaseClientProxy *>(arg);
m_dragFileList.clear();
String &dragFileList = m_screen->getDraggingFilename();
if (!dragFileList.empty()) {
DragInformation di;
di.setFilename(dragFileList);
m_dragFileList.push_back(di);
}
#if defined(__APPLE__)
// on mac it seems that after faking a LMB up, system would signal back
// to deskflow a mouse up event, which doesn't happen on windows. as a
// result, deskflow would send dragging file to client twice. This variable
// is used to ignore the first file sending.
m_ignoreFileTransfer = true;
#endif
// send drag file info to client if there is any
if (m_dragFileList.size() > 0) {
sendDragInfo(newScreen);
m_dragFileList.clear();
}
m_waitDragInfoThread = false;
m_sendDragInfoThread.reset(nullptr);
}
void Server::sendDragInfo(BaseClientProxy *newScreen)
{
String infoString;
UInt32 fileCount = DragInformation::setupDragInfo(m_dragFileList, infoString);
if (fileCount > 0) {
LOG((CLOG_DEBUG2 "sending drag information to client"));
LOG((CLOG_DEBUG3 "dragging file list: %s", infoString.c_str()));
LOG((CLOG_DEBUG3 "dragging file list string size: %i", infoString.size()));
newScreen->sendDragInfo(fileCount, infoString.c_str(), infoString.size());
}
}
void Server::onMouseMoveSecondary(SInt32 dx, SInt32 dy)
{
LOG((CLOG_DEBUG2 "onMouseMoveSecondary initial %+d,%+d", dx, dy));
const char *envVal = std::getenv("DESKFLOW_MOUSE_ADJUSTMENT");
if (envVal != nullptr) {
try {
double multiplier = std::stod(envVal); // Convert to double
SInt32 adjustedDx = static_cast<SInt32>(std::round(dx * multiplier)); // Apply multiplier and round
SInt32 adjustedDy = static_cast<SInt32>(std::round(dy * multiplier));
LOG((CLOG_DEBUG2 "Adjusted to %+d,%+d using multiplier %.2f", adjustedDx, adjustedDy, multiplier));
dx = adjustedDx; // Update dx and dy to adjusted values
dy = adjustedDy;
} catch (const std::exception &e) {
// Log the error message from the exception
LOG((CLOG_ERR "Invalid DESKFLOW_MOUSE_ADJUSTMENT value: %s. Exception: %s", envVal, e.what()));
}
} else {
LOG((CLOG_DEBUG1 "DESKFLOW_MOUSE_ADJUSTMENT not set, using original values %+d,%+d", dx, dy));
}
// mouse move on secondary (client's) screen
assert(m_active != NULL);
if (m_active == m_primaryClient) {
// stale event -- we're actually on the primary screen
return;
}
// if doing relative motion on secondary screens and we're locked
// to the screen (which activates relative moves) then send a
// relative mouse motion. when we're doing this we pretend as if
// the mouse isn't actually moving because we're expecting some
// program on the secondary screen to warp the mouse on us, so we
// have no idea where it really is.
if (m_relativeMoves && isLockedToScreenServer()) {
LOG((CLOG_DEBUG2 "relative move on %s by %d,%d", getName(m_active).c_str(), dx, dy));
m_active->mouseRelativeMove(dx, dy);
return;
}
// save old position
const SInt32 xOld = m_x;
const SInt32 yOld = m_y;
// save last delta
m_xDelta2 = m_xDelta;
m_yDelta2 = m_yDelta;
// save current delta
m_xDelta = dx;
m_yDelta = dy;
// accumulate motion
m_x += dx;
m_y += dy;
// get screen shape
SInt32 ax, ay, aw, ah;
m_active->getShape(ax, ay, aw, ah);
// find direction of neighbor and get the neighbor
bool jump = true;
BaseClientProxy *newScreen;
do {
// clamp position to screen
SInt32 xc = m_x, yc = m_y;
if (xc < ax) {
xc = ax;
} else if (xc >= ax + aw) {
xc = ax + aw - 1;
}
if (yc < ay) {
yc = ay;
} else if (yc >= ay + ah) {
yc = ay + ah - 1;
}
EDirection dir;
if (m_x < ax) {
dir = kLeft;
} else if (m_x > ax + aw - 1) {
dir = kRight;
} else if (m_y < ay) {
dir = kTop;
} else if (m_y > ay + ah - 1) {
dir = kBottom;
} else {
// we haven't left the screen
newScreen = m_active;
jump = false;
// if waiting and mouse is not on the border we're waiting
// on then stop waiting. also if it's not on the border
// then arm the double tap.
if (m_switchScreen != NULL) {
bool clearWait;
SInt32 zoneSize = m_primaryClient->getJumpZoneSize();
switch (m_switchDir) {
case kLeft:
clearWait = (m_x >= ax + zoneSize);
break;
case kRight:
clearWait = (m_x <= ax + aw - 1 - zoneSize);
break;
case kTop:
clearWait = (m_y >= ay + zoneSize);
break;
case kBottom:
clearWait = (m_y <= ay + ah - 1 + zoneSize);
break;
default:
clearWait = false;
break;
}
if (clearWait) {
// still on local screen
noSwitch(m_x, m_y);
}
}
// skip rest of block
break;
}
// try to switch screen. get the neighbor.
newScreen = mapToNeighbor(m_active, dir, m_x, m_y);
// see if we should switch
if (!isSwitchOkay(newScreen, dir, m_x, m_y, xc, yc)) {
newScreen = m_active;
jump = false;
}
} while (false);
if (jump) {
if (m_sendFileThread) {
StreamChunker::interruptFile();
m_sendFileThread.reset(nullptr);
}
SInt32 newX = m_x;
SInt32 newY = m_y;
// switch screens
switchScreen(newScreen, newX, newY, false);
} else {
// same screen. clamp mouse to edge.
m_x = xOld + dx;
m_y = yOld + dy;
if (m_x < ax) {
m_x = ax;
LOG((CLOG_DEBUG2 "clamp to left of \"%s\"", getName(m_active).c_str()));
} else if (m_x > ax + aw - 1) {
m_x = ax + aw - 1;
LOG((CLOG_DEBUG2 "clamp to right of \"%s\"", getName(m_active).c_str()));
}
if (m_y < ay) {
m_y = ay;
LOG((CLOG_DEBUG2 "clamp to top of \"%s\"", getName(m_active).c_str()));
} else if (m_y > ay + ah - 1) {
m_y = ay + ah - 1;
LOG((CLOG_DEBUG2 "clamp to bottom of \"%s\"", getName(m_active).c_str()));
}
// warp cursor if it moved.
if (m_x != xOld || m_y != yOld) {
LOG((CLOG_DEBUG2 "move on %s to %d,%d", getName(m_active).c_str(), m_x, m_y));
m_active->mouseMove(m_x, m_y);
}
}
}
void Server::onMouseWheel(SInt32 xDelta, SInt32 yDelta)
{
LOG((CLOG_DEBUG1 "onMouseWheel %+d,%+d", xDelta, yDelta));
assert(m_active != NULL);
// relay
m_active->mouseWheel(xDelta, yDelta);
}
void Server::onFileChunkSending(const void *data)
{
FileChunk *chunk = static_cast<FileChunk *>(const_cast<void *>(data));
LOG((CLOG_DEBUG1 "sending file chunk"));
assert(m_active != NULL);
// relay
m_active->fileChunkSending(chunk->m_chunk[0], &chunk->m_chunk[1], chunk->m_dataSize);
}
void Server::onFileRecieveCompleted()
{
if (isReceivedFileSizeValid()) {
auto method = new TMethodJob<Server>(this, &Server::writeToDropDirThread);
m_writeToDropDirThread.reset(new Thread(method));
}
}
void Server::writeToDropDirThread(void *)
{
LOG((CLOG_DEBUG "starting write to drop dir thread"));
while (m_screen->isFakeDraggingStarted()) {
ARCH->sleep(.1f);
}
DropHelper::writeToDir(m_screen->getDropTarget(), m_fakeDragFileList, m_receivedFileData);
}
bool Server::addClient(BaseClientProxy *client)
{
String name = getName(client);
if (m_clients.count(name) != 0) {
return false;
}
// add event handlers
m_events->adoptHandler(
m_events->forIScreen().shapeChanged(), client->getEventTarget(),
new TMethodEventJob<Server>(this, &Server::handleShapeChanged, client)
);
m_events->adoptHandler(
m_events->forClipboard().clipboardGrabbed(), client->getEventTarget(),
new TMethodEventJob<Server>(this, &Server::handleClipboardGrabbed, client)
);
m_events->adoptHandler(
m_events->forClipboard().clipboardChanged(), client->getEventTarget(),
new TMethodEventJob<Server>(this, &Server::handleClipboardChanged, client)
);
// add to list
m_clientSet.insert(client);
m_clients.insert(std::make_pair(name, client));
// initialize client data
SInt32 x, y;
client->getCursorPos(x, y);
client->setJumpCursorPos(x, y);
// tell primary client about the active sides
m_primaryClient->reconfigure(getActivePrimarySides());
return true;
}
bool Server::removeClient(BaseClientProxy *client)
{
// return false if not in list
ClientSet::iterator i = m_clientSet.find(client);
if (i == m_clientSet.end()) {
return false;
}
// remove event handlers
m_events->removeHandler(m_events->forIScreen().shapeChanged(), client->getEventTarget());
m_events->removeHandler(m_events->forClipboard().clipboardGrabbed(), client->getEventTarget());
m_events->removeHandler(m_events->forClipboard().clipboardChanged(), client->getEventTarget());
// remove from list
m_clients.erase(getName(client));
m_clientSet.erase(i);
return true;
}
void Server::closeClient(BaseClientProxy *client, const char *msg)
{
assert(client != m_primaryClient);
assert(msg != NULL);
// send message to client. this message should cause the client
// to disconnect. we add this client to the closed client list
// and install a timer to remove the client if it doesn't respond
// quickly enough. we also remove the client from the active
// client list since we're not going to listen to it anymore.
// note that this method also works on clients that are not in
// the m_clients list. adoptClient() may call us with such a
// client.
LOG((CLOG_NOTE "disconnecting client \"%s\"", getName(client).c_str()));
// send message
// FIXME -- avoid type cast (kinda hard, though)
((ClientProxy *)client)->close(msg);
// install timer. wait timeout seconds for client to close.
double timeout = 5.0;
EventQueueTimer *timer = m_events->newOneShotTimer(timeout, NULL);
m_events->adoptHandler(
Event::kTimer, timer, new TMethodEventJob<Server>(this, &Server::handleClientCloseTimeout, client)
);
// move client to closing list
removeClient(client);
m_oldClients.insert(std::make_pair(client, timer));
// if this client is the active screen then we have to
// jump off of it
forceLeaveClient(client);
}
void Server::closeClients(const ServerConfig &config)
{
// collect the clients that are connected but are being dropped
// from the configuration (or who's canonical name is changing).
typedef std::set<BaseClientProxy *> RemovedClients;
RemovedClients removed;
for (ClientList::iterator index = m_clients.begin(); index != m_clients.end(); ++index) {
if (!config.isCanonicalName(index->first)) {
removed.insert(index->second);
}
}
// don't close the primary client
removed.erase(m_primaryClient);
// now close them. we collect the list then close in two steps
// because closeClient() modifies the collection we iterate over.
for (RemovedClients::iterator index = removed.begin(); index != removed.end(); ++index) {
closeClient(*index, kMsgCClose);
}
}
void Server::removeActiveClient(BaseClientProxy *client)
{
if (removeClient(client)) {
forceLeaveClient(client);
m_events->removeHandler(m_events->forClientProxy().disconnected(), client);
if (m_clients.size() == 1 && m_oldClients.empty()) {
m_events->addEvent(Event(m_events->forServer().disconnected(), this));
}
}
}
void Server::removeOldClient(BaseClientProxy *client)
{
OldClients::iterator i = m_oldClients.find(client);
if (i != m_oldClients.end()) {
m_events->removeHandler(m_events->forClientProxy().disconnected(), client);
m_events->removeHandler(Event::kTimer, i->second);
m_events->deleteTimer(i->second);
m_oldClients.erase(i);
if (m_clients.size() == 1 && m_oldClients.empty()) {
m_events->addEvent(Event(m_events->forServer().disconnected(), this));
}
}
}
void Server::forceLeaveClient(BaseClientProxy *client)
{
BaseClientProxy *active = (m_activeSaver != NULL) ? m_activeSaver : m_active;
if (active == client) {
// record new position (center of primary screen)
m_primaryClient->getCursorCenter(m_x, m_y);
// stop waiting to switch to this client
if (active == m_switchScreen) {
stopSwitch();
}
// don't notify active screen since it has probably already
// disconnected.
LOG(
(CLOG_INFO "jump from \"%s\" to \"%s\" at %d,%d", getName(active).c_str(), getName(m_primaryClient).c_str(),
m_x, m_y)
);
// cut over
m_active = m_primaryClient;
// enter new screen (unless we already have because of the
// screen saver)
if (m_activeSaver == NULL) {
m_primaryClient->enter(m_x, m_y, m_seqNum, m_primaryClient->getToggleMask(), false);
}
}
// if this screen had the cursor when the screen saver activated
// then we can't switch back to it when the screen saver
// deactivates.
if (m_activeSaver == client) {
m_activeSaver = NULL;
}
// tell primary client about the active sides
m_primaryClient->reconfigure(getActivePrimarySides());
}
//
// Server::ClipboardInfo
//
Server::ClipboardInfo::ClipboardInfo() : m_clipboard(), m_clipboardData(), m_clipboardOwner(), m_clipboardSeqNum(0)
{
// do nothing
}
//
// Server::LockCursorToScreenInfo
//
Server::LockCursorToScreenInfo *Server::LockCursorToScreenInfo::alloc(State state)
{
LockCursorToScreenInfo *info = (LockCursorToScreenInfo *)malloc(sizeof(LockCursorToScreenInfo));
info->m_state = state;
return info;
}
//
// Server::SwitchToScreenInfo
//
Server::SwitchToScreenInfo *Server::SwitchToScreenInfo::alloc(const String &screen)
{
SwitchToScreenInfo *info = (SwitchToScreenInfo *)malloc(sizeof(SwitchToScreenInfo) + screen.size());
std::copy(screen.c_str(), screen.c_str() + screen.size() + 1, info->m_screen);
return info;
}
//
// Server::SwitchInDirectionInfo
//
Server::SwitchInDirectionInfo *Server::SwitchInDirectionInfo::alloc(EDirection direction)
{
SwitchInDirectionInfo *info = (SwitchInDirectionInfo *)malloc(sizeof(SwitchInDirectionInfo));
info->m_direction = direction;
return info;
}
//
// Server::KeyboardBroadcastInfo
//
Server::KeyboardBroadcastInfo *Server::KeyboardBroadcastInfo::alloc(State state)
{
KeyboardBroadcastInfo *info = (KeyboardBroadcastInfo *)malloc(sizeof(KeyboardBroadcastInfo));
info->m_state = state;
info->m_screens[0] = '\0';
return info;
}
Server::KeyboardBroadcastInfo *Server::KeyboardBroadcastInfo::alloc(State state, const String &screens)
{
KeyboardBroadcastInfo *info = (KeyboardBroadcastInfo *)malloc(sizeof(KeyboardBroadcastInfo) + screens.size());
info->m_state = state;
std::copy(screens.c_str(), screens.c_str() + screens.size() + 1, info->m_screens);
return info;
}
bool Server::isReceivedFileSizeValid()
{
return m_expectedFileSize == m_receivedFileData.size();
}
bool Server::isClientMode() const
{
return m_args.m_config->isClientMode();
}
void Server::sendFileToClient(const char *filename)
{
if (m_sendFileThread != NULL) {
StreamChunker::interruptFile();
}
auto data = static_cast<void *>(const_cast<char *>(filename));
auto method = new TMethodJob<Server>(this, &Server::sendFileThread, data);
m_sendFileThread.reset(new Thread(method));
}
void Server::sendFileThread(void *data)
{
try {
char *filename = static_cast<char *>(data);
LOG((CLOG_DEBUG "sending file to client, filename=%s", filename));
StreamChunker::sendFile(filename, m_events, this);
} catch (std::runtime_error &error) {
LOG((CLOG_ERR "failed sending file chunks, error: %s", error.what()));
}
m_sendFileThread.reset(nullptr);
}
void Server::dragInfoReceived(UInt32 fileNum, String content)
{
if (!m_args.m_enableDragDrop) {
LOG((CLOG_DEBUG "drag drop not enabled, ignoring drag info."));
return;
}
DragInformation::parseDragInfo(m_fakeDragFileList, fileNum, content);
m_screen->startDraggingFiles(m_fakeDragFileList);
}
| 69,022
|
C++
|
.cpp
| 1,985
| 30.570277
| 119
| 0.677583
|
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,545
|
InputFilter.cpp
|
deskflow_deskflow/src/lib/server/InputFilter.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2005 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 "server/InputFilter.h"
#include "base/EventQueue.h"
#include "base/Log.h"
#include "base/TMethodEventJob.h"
#include "deskflow/KeyMap.h"
#include "server/PrimaryClient.h"
#include "server/Server.h"
#include <cstdlib>
#include <cstring>
// -----------------------------------------------------------------------------
// Input Filter Condition Classes
// -----------------------------------------------------------------------------
InputFilter::Condition::Condition()
{
// do nothing
}
InputFilter::Condition::~Condition()
{
// do nothing
}
void InputFilter::Condition::enablePrimary(PrimaryClient *)
{
// do nothing
}
void InputFilter::Condition::disablePrimary(PrimaryClient *)
{
// do nothing
}
InputFilter::KeystrokeCondition::KeystrokeCondition(IEventQueue *events, IPlatformScreen::KeyInfo *info)
: m_id(0),
m_key(info->m_key),
m_mask(info->m_mask),
m_events(events)
{
free(info);
}
InputFilter::KeystrokeCondition::KeystrokeCondition(IEventQueue *events, KeyID key, KeyModifierMask mask)
: m_id(0),
m_key(key),
m_mask(mask),
m_events(events)
{
// do nothing
}
InputFilter::KeystrokeCondition::~KeystrokeCondition()
{
// do nothing
}
KeyID InputFilter::KeystrokeCondition::getKey() const
{
return m_key;
}
KeyModifierMask InputFilter::KeystrokeCondition::getMask() const
{
return m_mask;
}
InputFilter::Condition *InputFilter::KeystrokeCondition::clone() const
{
return new KeystrokeCondition(m_events, m_key, m_mask);
}
String InputFilter::KeystrokeCondition::format() const
{
return deskflow::string::sprintf("keystroke(%s)", deskflow::KeyMap::formatKey(m_key, m_mask).c_str());
}
InputFilter::EFilterStatus InputFilter::KeystrokeCondition::match(const Event &event)
{
EFilterStatus status;
// check for hotkey events
Event::Type type = event.getType();
if (type == m_events->forIPrimaryScreen().hotKeyDown()) {
status = kActivate;
} else if (type == m_events->forIPrimaryScreen().hotKeyUp()) {
status = kDeactivate;
} else {
return kNoMatch;
}
// check if it's our hotkey
IPrimaryScreen::HotKeyInfo *kinfo = static_cast<IPlatformScreen::HotKeyInfo *>(event.getData());
if (kinfo->m_id != m_id) {
return kNoMatch;
}
return status;
}
void InputFilter::KeystrokeCondition::enablePrimary(PrimaryClient *primary)
{
m_id = primary->registerHotKey(m_key, m_mask);
}
void InputFilter::KeystrokeCondition::disablePrimary(PrimaryClient *primary)
{
primary->unregisterHotKey(m_id);
m_id = 0;
}
InputFilter::MouseButtonCondition::MouseButtonCondition(IEventQueue *events, IPlatformScreen::ButtonInfo *info)
: m_button(info->m_button),
m_mask(info->m_mask),
m_events(events)
{
free(info);
}
InputFilter::MouseButtonCondition::MouseButtonCondition(IEventQueue *events, ButtonID button, KeyModifierMask mask)
: m_button(button),
m_mask(mask),
m_events(events)
{
// do nothing
}
InputFilter::MouseButtonCondition::~MouseButtonCondition()
{
// do nothing
}
ButtonID InputFilter::MouseButtonCondition::getButton() const
{
return m_button;
}
KeyModifierMask InputFilter::MouseButtonCondition::getMask() const
{
return m_mask;
}
InputFilter::Condition *InputFilter::MouseButtonCondition::clone() const
{
return new MouseButtonCondition(m_events, m_button, m_mask);
}
String InputFilter::MouseButtonCondition::format() const
{
String key = deskflow::KeyMap::formatKey(kKeyNone, m_mask);
if (!key.empty()) {
key += "+";
}
return deskflow::string::sprintf("mousebutton(%s%d)", key.c_str(), m_button);
}
InputFilter::EFilterStatus InputFilter::MouseButtonCondition::match(const Event &event)
{
static const KeyModifierMask s_ignoreMask =
KeyModifierAltGr | KeyModifierCapsLock | KeyModifierNumLock | KeyModifierScrollLock;
EFilterStatus status;
// check for hotkey events
Event::Type type = event.getType();
if (type == m_events->forIPrimaryScreen().buttonDown()) {
status = kActivate;
} else if (type == m_events->forIPrimaryScreen().buttonUp()) {
status = kDeactivate;
} else {
return kNoMatch;
}
// check if it's the right button and modifiers. ignore modifiers
// that cannot be combined with a mouse button.
IPlatformScreen::ButtonInfo *minfo = static_cast<IPlatformScreen::ButtonInfo *>(event.getData());
if (minfo->m_button != m_button || (minfo->m_mask & ~s_ignoreMask) != m_mask) {
return kNoMatch;
}
return status;
}
InputFilter::ScreenConnectedCondition::ScreenConnectedCondition(IEventQueue *events, const String &screen)
: m_screen(screen),
m_events(events)
{
// do nothing
}
InputFilter::ScreenConnectedCondition::~ScreenConnectedCondition()
{
// do nothing
}
InputFilter::Condition *InputFilter::ScreenConnectedCondition::clone() const
{
return new ScreenConnectedCondition(m_events, m_screen);
}
String InputFilter::ScreenConnectedCondition::format() const
{
return deskflow::string::sprintf("connect(%s)", m_screen.c_str());
}
InputFilter::EFilterStatus InputFilter::ScreenConnectedCondition::match(const Event &event)
{
if (event.getType() == m_events->forServer().connected()) {
Server::ScreenConnectedInfo *info = static_cast<Server::ScreenConnectedInfo *>(event.getData());
if (m_screen == info->m_screen || m_screen.empty()) {
return kActivate;
}
}
return kNoMatch;
}
// -----------------------------------------------------------------------------
// Input Filter Action Classes
// -----------------------------------------------------------------------------
InputFilter::Action::Action()
{
// do nothing
}
InputFilter::Action::~Action()
{
// do nothing
}
InputFilter::LockCursorToScreenAction::LockCursorToScreenAction(IEventQueue *events, Mode mode)
: m_mode(mode),
m_events(events)
{
// do nothing
}
InputFilter::LockCursorToScreenAction::Mode InputFilter::LockCursorToScreenAction::getMode() const
{
return m_mode;
}
InputFilter::Action *InputFilter::LockCursorToScreenAction::clone() const
{
return new LockCursorToScreenAction(*this);
}
String InputFilter::LockCursorToScreenAction::format() const
{
static const char *s_mode[] = {"off", "on", "toggle"};
return deskflow::string::sprintf("lockCursorToScreen(%s)", s_mode[m_mode]);
}
void InputFilter::LockCursorToScreenAction::perform(const Event &event)
{
static const Server::LockCursorToScreenInfo::State s_state[] = {
Server::LockCursorToScreenInfo::kOff, Server::LockCursorToScreenInfo::kOn, Server::LockCursorToScreenInfo::kToggle
};
// send event
Server::LockCursorToScreenInfo *info = Server::LockCursorToScreenInfo::alloc(s_state[m_mode]);
m_events->addEvent(
Event(m_events->forServer().lockCursorToScreen(), event.getTarget(), info, Event::kDeliverImmediately)
);
}
InputFilter::RestartServer::RestartServer(IEventQueue *events, Mode mode) : m_mode(mode), m_events(events)
{
// do nothing
}
InputFilter::RestartServer::Mode InputFilter::RestartServer::getMode() const
{
return m_mode;
}
InputFilter::Action *InputFilter::RestartServer::clone() const
{
return new RestartServer(*this);
}
String InputFilter::RestartServer::format() const
{
static const char *s_mode[] = {"restart"};
return deskflow::string::sprintf("restartServer(%s)", s_mode[m_mode]);
}
void InputFilter::RestartServer::perform(const Event &event)
{
// HACK Super hack we should gracefully exit
exit(0);
}
InputFilter::SwitchToScreenAction::SwitchToScreenAction(IEventQueue *events, const String &screen)
: m_screen(screen),
m_events(events)
{
// do nothing
}
String InputFilter::SwitchToScreenAction::getScreen() const
{
return m_screen;
}
InputFilter::Action *InputFilter::SwitchToScreenAction::clone() const
{
return new SwitchToScreenAction(*this);
}
String InputFilter::SwitchToScreenAction::format() const
{
return deskflow::string::sprintf("switchToScreen(%s)", m_screen.c_str());
}
void InputFilter::SwitchToScreenAction::perform(const Event &event)
{
// pick screen name. if m_screen is empty then use the screen from
// event if it has one.
String screen = m_screen;
if (screen.empty() && event.getType() == m_events->forServer().connected()) {
Server::ScreenConnectedInfo *info = static_cast<Server::ScreenConnectedInfo *>(event.getData());
screen = info->m_screen;
}
// send event
Server::SwitchToScreenInfo *info = Server::SwitchToScreenInfo::alloc(screen);
m_events->addEvent(Event(m_events->forServer().switchToScreen(), event.getTarget(), info, Event::kDeliverImmediately)
);
}
InputFilter::SwitchInDirectionAction::SwitchInDirectionAction(IEventQueue *events, EDirection direction)
: m_direction(direction),
m_events(events)
{
// do nothing
}
EDirection InputFilter::SwitchInDirectionAction::getDirection() const
{
return m_direction;
}
InputFilter::Action *InputFilter::SwitchInDirectionAction::clone() const
{
return new SwitchInDirectionAction(*this);
}
String InputFilter::SwitchInDirectionAction::format() const
{
static const char *s_names[] = {"", "left", "right", "up", "down"};
return deskflow::string::sprintf("switchInDirection(%s)", s_names[m_direction]);
}
void InputFilter::SwitchInDirectionAction::perform(const Event &event)
{
Server::SwitchInDirectionInfo *info = Server::SwitchInDirectionInfo::alloc(m_direction);
m_events->addEvent(
Event(m_events->forServer().switchInDirection(), event.getTarget(), info, Event::kDeliverImmediately)
);
}
InputFilter::KeyboardBroadcastAction::KeyboardBroadcastAction(IEventQueue *events, Mode mode)
: m_mode(mode),
m_events(events)
{
// do nothing
}
InputFilter::KeyboardBroadcastAction::KeyboardBroadcastAction(
IEventQueue *events, Mode mode, const std::set<String> &screens
)
: m_mode(mode),
m_screens(IKeyState::KeyInfo::join(screens)),
m_events(events)
{
// do nothing
}
InputFilter::KeyboardBroadcastAction::Mode InputFilter::KeyboardBroadcastAction::getMode() const
{
return m_mode;
}
std::set<String> InputFilter::KeyboardBroadcastAction::getScreens() const
{
std::set<String> screens;
IKeyState::KeyInfo::split(m_screens.c_str(), screens);
return screens;
}
InputFilter::Action *InputFilter::KeyboardBroadcastAction::clone() const
{
return new KeyboardBroadcastAction(*this);
}
String InputFilter::KeyboardBroadcastAction::format() const
{
static const char *s_mode[] = {"off", "on", "toggle"};
static const char *s_name = "keyboardBroadcast";
if (m_screens.empty() || m_screens[0] == '*') {
return deskflow::string::sprintf("%s(%s)", s_name, s_mode[m_mode]);
} else {
return deskflow::string::sprintf(
"%s(%s,%.*s)", s_name, s_mode[m_mode], static_cast<int>(m_screens.size() >= 2 ? m_screens.size() - 2 : 0),
m_screens.c_str() + 1
);
}
}
void InputFilter::KeyboardBroadcastAction::perform(const Event &event)
{
static const Server::KeyboardBroadcastInfo::State s_state[] = {
Server::KeyboardBroadcastInfo::kOff, Server::KeyboardBroadcastInfo::kOn, Server::KeyboardBroadcastInfo::kToggle
};
// send event
Server::KeyboardBroadcastInfo *info = Server::KeyboardBroadcastInfo::alloc(s_state[m_mode], m_screens);
m_events->addEvent(
Event(m_events->forServer().keyboardBroadcast(), event.getTarget(), info, Event::kDeliverImmediately)
);
}
InputFilter::KeystrokeAction::KeystrokeAction(IEventQueue *events, IPlatformScreen::KeyInfo *info, bool press)
: m_keyInfo(info),
m_press(press),
m_events(events)
{
// do nothing
}
InputFilter::KeystrokeAction::~KeystrokeAction()
{
free(m_keyInfo);
}
void InputFilter::KeystrokeAction::adoptInfo(IPlatformScreen::KeyInfo *info)
{
free(m_keyInfo);
m_keyInfo = info;
}
const IPlatformScreen::KeyInfo *InputFilter::KeystrokeAction::getInfo() const
{
return m_keyInfo;
}
bool InputFilter::KeystrokeAction::isOnPress() const
{
return m_press;
}
InputFilter::Action *InputFilter::KeystrokeAction::clone() const
{
IKeyState::KeyInfo *info = IKeyState::KeyInfo::alloc(*m_keyInfo);
return new KeystrokeAction(m_events, info, m_press);
}
String InputFilter::KeystrokeAction::format() const
{
const char *type = formatName();
if (m_keyInfo->m_screens[0] == '\0') {
return deskflow::string::sprintf(
"%s(%s)", type, deskflow::KeyMap::formatKey(m_keyInfo->m_key, m_keyInfo->m_mask).c_str()
);
} else if (m_keyInfo->m_screens[0] == '*') {
return deskflow::string::sprintf(
"%s(%s,*)", type, deskflow::KeyMap::formatKey(m_keyInfo->m_key, m_keyInfo->m_mask).c_str()
);
} else {
return deskflow::string::sprintf(
"%s(%s,%.*s)", type, deskflow::KeyMap::formatKey(m_keyInfo->m_key, m_keyInfo->m_mask).c_str(),
strnlen(m_keyInfo->m_screens + 1, SIZE_MAX) - 1, m_keyInfo->m_screens + 1
);
}
}
void InputFilter::KeystrokeAction::perform(const Event &event)
{
Event::Type type = m_press ? m_events->forIKeyState().keyDown() : m_events->forIKeyState().keyUp();
m_events->addEvent(
Event(m_events->forIPrimaryScreen().fakeInputBegin(), event.getTarget(), NULL, Event::kDeliverImmediately)
);
m_events->addEvent(Event(type, event.getTarget(), m_keyInfo, Event::kDeliverImmediately | Event::kDontFreeData));
m_events->addEvent(
Event(m_events->forIPrimaryScreen().fakeInputEnd(), event.getTarget(), NULL, Event::kDeliverImmediately)
);
}
const char *InputFilter::KeystrokeAction::formatName() const
{
return (m_press ? "keyDown" : "keyUp");
}
InputFilter::MouseButtonAction::MouseButtonAction(IEventQueue *events, IPlatformScreen::ButtonInfo *info, bool press)
: m_buttonInfo(info),
m_press(press),
m_events(events)
{
// do nothing
}
InputFilter::MouseButtonAction::~MouseButtonAction()
{
free(m_buttonInfo);
}
const IPlatformScreen::ButtonInfo *InputFilter::MouseButtonAction::getInfo() const
{
return m_buttonInfo;
}
bool InputFilter::MouseButtonAction::isOnPress() const
{
return m_press;
}
InputFilter::Action *InputFilter::MouseButtonAction::clone() const
{
IPlatformScreen::ButtonInfo *info = IPrimaryScreen::ButtonInfo::alloc(*m_buttonInfo);
return new MouseButtonAction(m_events, info, m_press);
}
String InputFilter::MouseButtonAction::format() const
{
const char *type = formatName();
String key = deskflow::KeyMap::formatKey(kKeyNone, m_buttonInfo->m_mask);
return deskflow::string::sprintf("%s(%s%s%d)", type, key.c_str(), key.empty() ? "" : "+", m_buttonInfo->m_button);
}
void InputFilter::MouseButtonAction::perform(const Event &event)
{
// send modifiers
IPlatformScreen::KeyInfo *modifierInfo = NULL;
if (m_buttonInfo->m_mask != 0) {
KeyID key = m_press ? kKeySetModifiers : kKeyClearModifiers;
modifierInfo = IKeyState::KeyInfo::alloc(key, m_buttonInfo->m_mask, 0, 1);
m_events->addEvent(
Event(m_events->forIKeyState().keyDown(), event.getTarget(), modifierInfo, Event::kDeliverImmediately)
);
}
// send button
Event::Type type = m_press ? m_events->forIPrimaryScreen().buttonDown() : m_events->forIPrimaryScreen().buttonUp();
m_events->addEvent(Event(type, event.getTarget(), m_buttonInfo, Event::kDeliverImmediately | Event::kDontFreeData));
}
const char *InputFilter::MouseButtonAction::formatName() const
{
return (m_press ? "mouseDown" : "mouseUp");
}
//
// InputFilter::Rule
//
InputFilter::Rule::Rule() : m_condition(NULL)
{
// do nothing
}
InputFilter::Rule::Rule(Condition *adoptedCondition) : m_condition(adoptedCondition)
{
// do nothing
}
InputFilter::Rule::Rule(const Rule &rule) : m_condition(NULL)
{
copy(rule);
}
InputFilter::Rule::~Rule()
{
clear();
}
InputFilter::Rule &InputFilter::Rule::operator=(const Rule &rule)
{
if (&rule != this) {
copy(rule);
}
return *this;
}
void InputFilter::Rule::clear()
{
delete m_condition;
for (ActionList::iterator i = m_activateActions.begin(); i != m_activateActions.end(); ++i) {
delete *i;
}
for (ActionList::iterator i = m_deactivateActions.begin(); i != m_deactivateActions.end(); ++i) {
delete *i;
}
m_condition = NULL;
m_activateActions.clear();
m_deactivateActions.clear();
}
void InputFilter::Rule::copy(const Rule &rule)
{
clear();
if (rule.m_condition != NULL) {
m_condition = rule.m_condition->clone();
}
for (ActionList::const_iterator i = rule.m_activateActions.begin(); i != rule.m_activateActions.end(); ++i) {
m_activateActions.push_back((*i)->clone());
}
for (ActionList::const_iterator i = rule.m_deactivateActions.begin(); i != rule.m_deactivateActions.end(); ++i) {
m_deactivateActions.push_back((*i)->clone());
}
}
void InputFilter::Rule::setCondition(Condition *adopted)
{
delete m_condition;
m_condition = adopted;
}
void InputFilter::Rule::adoptAction(Action *action, bool onActivation)
{
if (action != NULL) {
if (onActivation) {
m_activateActions.push_back(action);
} else {
m_deactivateActions.push_back(action);
}
}
}
void InputFilter::Rule::removeAction(bool onActivation, UInt32 index)
{
if (onActivation) {
delete m_activateActions[index];
m_activateActions.erase(m_activateActions.begin() + index);
} else {
delete m_deactivateActions[index];
m_deactivateActions.erase(m_deactivateActions.begin() + index);
}
}
void InputFilter::Rule::replaceAction(Action *adopted, bool onActivation, UInt32 index)
{
if (adopted == NULL) {
removeAction(onActivation, index);
} else if (onActivation) {
delete m_activateActions[index];
m_activateActions[index] = adopted;
} else {
delete m_deactivateActions[index];
m_deactivateActions[index] = adopted;
}
}
void InputFilter::Rule::enable(PrimaryClient *primaryClient)
{
if (m_condition != NULL) {
m_condition->enablePrimary(primaryClient);
}
}
void InputFilter::Rule::disable(PrimaryClient *primaryClient)
{
if (m_condition != NULL) {
m_condition->disablePrimary(primaryClient);
}
}
bool InputFilter::Rule::handleEvent(const Event &event)
{
// NULL condition never matches
if (m_condition == NULL) {
return false;
}
// match
const ActionList *actions;
switch (m_condition->match(event)) {
default:
// not handled
return false;
case kActivate:
actions = &m_activateActions;
LOG((CLOG_DEBUG1 "activate actions"));
break;
case kDeactivate:
actions = &m_deactivateActions;
LOG((CLOG_DEBUG1 "deactivate actions"));
break;
}
// perform actions
for (ActionList::const_iterator i = actions->begin(); i != actions->end(); ++i) {
LOG((CLOG_DEBUG1 "hotkey: %s", (*i)->format().c_str()));
(*i)->perform(event);
}
return true;
}
String InputFilter::Rule::format() const
{
String s;
if (m_condition != NULL) {
// condition
s += m_condition->format();
s += " = ";
// activate actions
ActionList::const_iterator i = m_activateActions.begin();
if (i != m_activateActions.end()) {
s += (*i)->format();
while (++i != m_activateActions.end()) {
s += ", ";
s += (*i)->format();
}
}
// deactivate actions
if (!m_deactivateActions.empty()) {
s += "; ";
i = m_deactivateActions.begin();
if (i != m_deactivateActions.end()) {
s += (*i)->format();
while (++i != m_deactivateActions.end()) {
s += ", ";
s += (*i)->format();
}
}
}
}
return s;
}
const InputFilter::Condition *InputFilter::Rule::getCondition() const
{
return m_condition;
}
UInt32 InputFilter::Rule::getNumActions(bool onActivation) const
{
if (onActivation) {
return static_cast<UInt32>(m_activateActions.size());
} else {
return static_cast<UInt32>(m_deactivateActions.size());
}
}
const InputFilter::Action &InputFilter::Rule::getAction(bool onActivation, UInt32 index) const
{
if (onActivation) {
return *m_activateActions[index];
} else {
return *m_deactivateActions[index];
}
}
// -----------------------------------------------------------------------------
// Input Filter Class
// -----------------------------------------------------------------------------
InputFilter::InputFilter(IEventQueue *events) : m_primaryClient(NULL), m_events(events)
{
// do nothing
}
InputFilter::InputFilter(const InputFilter &x) : m_ruleList(x.m_ruleList), m_primaryClient(NULL), m_events(x.m_events)
{
setPrimaryClient(x.m_primaryClient);
}
InputFilter::~InputFilter()
{
setPrimaryClient(NULL);
}
InputFilter &InputFilter::operator=(const InputFilter &x)
{
if (&x != this) {
PrimaryClient *oldClient = m_primaryClient;
setPrimaryClient(NULL);
m_ruleList = x.m_ruleList;
setPrimaryClient(oldClient);
}
return *this;
}
void InputFilter::addFilterRule(const Rule &rule)
{
m_ruleList.push_back(rule);
if (m_primaryClient != NULL) {
m_ruleList.back().enable(m_primaryClient);
}
}
void InputFilter::removeFilterRule(UInt32 index)
{
if (m_primaryClient != NULL) {
m_ruleList[index].disable(m_primaryClient);
}
m_ruleList.erase(m_ruleList.begin() + index);
}
InputFilter::Rule &InputFilter::getRule(UInt32 index)
{
return m_ruleList[index];
}
void InputFilter::setPrimaryClient(PrimaryClient *client)
{
if (m_primaryClient == client) {
return;
}
if (m_primaryClient != NULL) {
for (RuleList::iterator rule = m_ruleList.begin(); rule != m_ruleList.end(); ++rule) {
rule->disable(m_primaryClient);
}
m_events->removeHandler(m_events->forIKeyState().keyDown(), m_primaryClient->getEventTarget());
m_events->removeHandler(m_events->forIKeyState().keyUp(), m_primaryClient->getEventTarget());
m_events->removeHandler(m_events->forIKeyState().keyRepeat(), m_primaryClient->getEventTarget());
m_events->removeHandler(m_events->forIPrimaryScreen().buttonDown(), m_primaryClient->getEventTarget());
m_events->removeHandler(m_events->forIPrimaryScreen().buttonUp(), m_primaryClient->getEventTarget());
m_events->removeHandler(m_events->forIPrimaryScreen().hotKeyDown(), m_primaryClient->getEventTarget());
m_events->removeHandler(m_events->forIPrimaryScreen().hotKeyUp(), m_primaryClient->getEventTarget());
m_events->removeHandler(m_events->forServer().connected(), m_primaryClient->getEventTarget());
}
m_primaryClient = client;
if (m_primaryClient != NULL) {
m_events->adoptHandler(
m_events->forIKeyState().keyDown(), m_primaryClient->getEventTarget(),
new TMethodEventJob<InputFilter>(this, &InputFilter::handleEvent)
);
m_events->adoptHandler(
m_events->forIKeyState().keyUp(), m_primaryClient->getEventTarget(),
new TMethodEventJob<InputFilter>(this, &InputFilter::handleEvent)
);
m_events->adoptHandler(
m_events->forIKeyState().keyRepeat(), m_primaryClient->getEventTarget(),
new TMethodEventJob<InputFilter>(this, &InputFilter::handleEvent)
);
m_events->adoptHandler(
m_events->forIPrimaryScreen().buttonDown(), m_primaryClient->getEventTarget(),
new TMethodEventJob<InputFilter>(this, &InputFilter::handleEvent)
);
m_events->adoptHandler(
m_events->forIPrimaryScreen().buttonUp(), m_primaryClient->getEventTarget(),
new TMethodEventJob<InputFilter>(this, &InputFilter::handleEvent)
);
m_events->adoptHandler(
m_events->forIPrimaryScreen().hotKeyDown(), m_primaryClient->getEventTarget(),
new TMethodEventJob<InputFilter>(this, &InputFilter::handleEvent)
);
m_events->adoptHandler(
m_events->forIPrimaryScreen().hotKeyUp(), m_primaryClient->getEventTarget(),
new TMethodEventJob<InputFilter>(this, &InputFilter::handleEvent)
);
m_events->adoptHandler(
m_events->forServer().connected(), m_primaryClient->getEventTarget(),
new TMethodEventJob<InputFilter>(this, &InputFilter::handleEvent)
);
for (RuleList::iterator rule = m_ruleList.begin(); rule != m_ruleList.end(); ++rule) {
rule->enable(m_primaryClient);
}
}
}
String InputFilter::format(const String &linePrefix) const
{
String s;
for (RuleList::const_iterator i = m_ruleList.begin(); i != m_ruleList.end(); ++i) {
s += linePrefix;
s += i->format();
s += "\n";
}
return s;
}
UInt32 InputFilter::getNumRules() const
{
return static_cast<UInt32>(m_ruleList.size());
}
bool InputFilter::operator==(const InputFilter &x) const
{
// if there are different numbers of rules then we can't be equal
if (m_ruleList.size() != x.m_ruleList.size()) {
return false;
}
// compare rule lists. the easiest way to do that is to format each
// rule into a string, sort the strings, then compare the results.
std::vector<String> aList, bList;
for (RuleList::const_iterator i = m_ruleList.begin(); i != m_ruleList.end(); ++i) {
aList.push_back(i->format());
}
for (RuleList::const_iterator i = x.m_ruleList.begin(); i != x.m_ruleList.end(); ++i) {
bList.push_back(i->format());
}
std::partial_sort(aList.begin(), aList.end(), aList.end());
std::partial_sort(bList.begin(), bList.end(), bList.end());
return (aList == bList);
}
bool InputFilter::operator!=(const InputFilter &x) const
{
return !operator==(x);
}
void InputFilter::handleEvent(const Event &event, void *)
{
// copy event and adjust target
Event myEvent(
event.getType(), this, event.getData(), event.getFlags() | Event::kDontFreeData | Event::kDeliverImmediately
);
// let each rule try to match the event until one does
for (RuleList::iterator rule = m_ruleList.begin(); rule != m_ruleList.end(); ++rule) {
if (rule->handleEvent(myEvent)) {
// handled
return;
}
}
// not handled so pass through
m_events->addEvent(myEvent);
}
| 26,452
|
C++
|
.cpp
| 815
| 29.364417
| 120
| 0.704221
|
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,546
|
ClientProxy1_1.cpp
|
deskflow_deskflow/src/lib/server/ClientProxy1_1.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 "server/ClientProxy1_1.h"
#include "deskflow/AppUtil.h"
#include "base/Log.h"
#include "deskflow/ProtocolUtil.h"
#include <cstring>
//
// ClientProxy1_1
//
ClientProxy1_1::ClientProxy1_1(const String &name, deskflow::IStream *stream, IEventQueue *events)
: ClientProxy1_0(name, stream, events)
{
// do nothing
}
ClientProxy1_1::~ClientProxy1_1()
{
// do nothing
}
void ClientProxy1_1::keyDown(KeyID key, KeyModifierMask mask, KeyButton button, const String &)
{
LOG((CLOG_DEBUG1 "send key down to \"%s\" id=%d, mask=0x%04x, button=0x%04x", getName().c_str(), key, mask, button));
ProtocolUtil::writef(getStream(), kMsgDKeyDown, key, mask, button);
}
void ClientProxy1_1::keyRepeat(KeyID key, KeyModifierMask mask, SInt32 count, KeyButton button, const String &lang)
{
LOG(
(CLOG_DEBUG1 "send key repeat to \"%s\" id=%d, mask=0x%04x, count=%d, "
"button=0x%04x, lang=\"%s\"",
getName().c_str(), key, mask, count, button, lang.c_str())
);
ProtocolUtil::writef(getStream(), kMsgDKeyRepeat, key, mask, count, button, &lang);
}
void ClientProxy1_1::keyUp(KeyID key, KeyModifierMask mask, KeyButton button)
{
LOG((CLOG_DEBUG1 "send key up to \"%s\" id=%d, mask=0x%04x, button=0x%04x", getName().c_str(), key, mask, button));
ProtocolUtil::writef(getStream(), kMsgDKeyUp, key, mask, button);
}
| 2,089
|
C++
|
.cpp
| 53
| 36.924528
| 119
| 0.720276
|
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,547
|
IpcSettingMessage.cpp
|
deskflow_deskflow/src/lib/ipc/IpcSettingMessage.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 "IpcSettingMessage.h"
IpcSettingMessage::IpcSettingMessage(const std::string &name, const std::string &value)
: IpcMessage(IpcMessageType::Setting),
m_name(name),
m_value(value)
{
}
const std::string &IpcSettingMessage::getName() const
{
return m_name;
}
const std::string &IpcSettingMessage::getValue() const
{
return m_value;
}
| 1,088
|
C++
|
.cpp
| 32
| 31.75
| 87
| 0.754753
|
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,548
|
IpcClient.cpp
|
deskflow_deskflow/src/lib/ipc/IpcClient.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012 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 "ipc/IpcClient.h"
#include "base/TMethodEventJob.h"
#include "common/ipc.h"
#include "ipc/IpcMessage.h"
#include "ipc/IpcServerProxy.h"
//
// IpcClient
//
IpcClient::IpcClient(IEventQueue *events, SocketMultiplexer *socketMultiplexer)
: m_serverAddress(NetworkAddress(kIpcHost, kIpcPort)),
m_socket(events, socketMultiplexer),
m_server(nullptr),
m_events(events)
{
init();
}
IpcClient::IpcClient(IEventQueue *events, SocketMultiplexer *socketMultiplexer, int port)
: m_serverAddress(NetworkAddress(kIpcHost, port)),
m_socket(events, socketMultiplexer),
m_server(nullptr),
m_events(events)
{
init();
}
void IpcClient::init()
{
m_serverAddress.resolve();
}
IpcClient::~IpcClient()
{
}
void IpcClient::connect()
{
m_events->adoptHandler(
m_events->forIDataSocket().connected(), m_socket.getEventTarget(),
new TMethodEventJob<IpcClient>(this, &IpcClient::handleConnected)
);
m_socket.connect(m_serverAddress);
m_server = new IpcServerProxy(m_socket, m_events);
m_events->adoptHandler(
m_events->forIpcServerProxy().messageReceived(), m_server,
new TMethodEventJob<IpcClient>(this, &IpcClient::handleMessageReceived)
);
}
void IpcClient::disconnect()
{
m_events->removeHandler(m_events->forIDataSocket().connected(), m_socket.getEventTarget());
m_events->removeHandler(m_events->forIpcServerProxy().messageReceived(), m_server);
m_server->disconnect();
delete m_server;
m_server = nullptr;
}
void IpcClient::send(const IpcMessage &message)
{
assert(m_server != nullptr);
m_server->send(message);
}
void IpcClient::handleConnected(const Event &, void *)
{
m_events->addEvent(Event(m_events->forIpcClient().connected(), this, m_server, Event::kDontFreeData));
IpcHelloMessage message(IpcClientType::Node);
send(message);
}
void IpcClient::handleMessageReceived(const Event &e, void *)
{
Event event(m_events->forIpcClient().messageReceived(), this);
event.setDataObject(e.getDataObject());
m_events->addEvent(event);
}
| 2,734
|
C++
|
.cpp
| 85
| 29.494118
| 104
| 0.748292
|
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,549
|
IpcLogOutputter.cpp
|
deskflow_deskflow/src/lib/ipc/IpcLogOutputter.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 "ipc/IpcLogOutputter.h"
#include "arch/Arch.h"
#include "arch/XArch.h"
#include "base/Event.h"
#include "base/EventQueue.h"
#include "base/TMethodEventJob.h"
#include "base/TMethodJob.h"
#include "common/ipc.h"
#include "ipc/IpcClientProxy.h"
#include "ipc/IpcMessage.h"
#include "ipc/IpcServer.h"
#include "mt/Thread.h"
enum EIpcLogOutputter
{
kBufferMaxSize = 1000,
kMaxSendLines = 100,
kBufferRateWriteLimit = 1000, // writes per kBufferRateTime
kBufferRateTimeLimit = 1 // seconds
};
IpcLogOutputter::IpcLogOutputter(IpcServer &ipcServer, IpcClientType clientType, bool useThread)
: m_ipcServer(ipcServer),
m_bufferMutex(ARCH->newMutex()),
m_sending(false),
m_bufferThread(nullptr),
m_running(false),
m_notifyCond(ARCH->newCondVar()),
m_notifyMutex(ARCH->newMutex()),
m_bufferThreadId(0),
m_bufferWaiting(false),
m_bufferMaxSize(kBufferMaxSize),
m_bufferRateWriteLimit(kBufferRateWriteLimit),
m_bufferRateTimeLimit(kBufferRateTimeLimit),
m_bufferWriteCount(0),
m_bufferRateStart(ARCH->time()),
m_clientType(clientType),
m_runningMutex(ARCH->newMutex())
{
if (useThread) {
m_bufferThread = new Thread(new TMethodJob<IpcLogOutputter>(this, &IpcLogOutputter::bufferThread));
}
}
IpcLogOutputter::~IpcLogOutputter()
{
close();
ARCH->closeMutex(m_bufferMutex);
if (m_bufferThread != nullptr) {
m_bufferThread->cancel();
m_bufferThread->wait();
delete m_bufferThread;
}
ARCH->closeCondVar(m_notifyCond);
ARCH->closeMutex(m_notifyMutex);
}
void IpcLogOutputter::open(const char *title)
{
}
void IpcLogOutputter::close()
{
if (m_bufferThread != nullptr) {
ArchMutexLock lock(m_runningMutex);
m_running = false;
notifyBuffer();
m_bufferThread->wait(5);
}
}
void IpcLogOutputter::show(bool showIfEmpty)
{
}
bool IpcLogOutputter::write(ELevel, const char *text)
{
// ignore events from the buffer thread (would cause recursion).
if (m_bufferThread != nullptr && Thread::getCurrentThread().getID() == m_bufferThreadId) {
return true;
}
appendBuffer(text);
notifyBuffer();
return true;
}
void IpcLogOutputter::appendBuffer(const String &text)
{
ArchMutexLock lock(m_bufferMutex);
double elapsed = ARCH->time() - m_bufferRateStart;
if (elapsed < m_bufferRateTimeLimit) {
if (m_bufferWriteCount >= m_bufferRateWriteLimit) {
// discard the log line if we've logged too much.
return;
}
} else {
m_bufferWriteCount = 0;
m_bufferRateStart = ARCH->time();
}
if (m_buffer.size() >= m_bufferMaxSize) {
// if the queue is exceeds size limit,
// throw away the oldest item
m_buffer.pop_front();
}
m_buffer.push_back(text);
m_bufferWriteCount++;
}
bool IpcLogOutputter::isRunning()
{
ArchMutexLock lock(m_runningMutex);
return m_running;
}
void IpcLogOutputter::bufferThread(void *)
{
m_bufferThreadId = m_bufferThread->getID();
m_running = true;
try {
while (isRunning()) {
if (m_buffer.empty() || !m_ipcServer.hasClients(m_clientType)) {
ArchMutexLock lock(m_notifyMutex);
ARCH->waitCondVar(m_notifyCond, m_notifyMutex, -1);
}
sendBuffer();
}
} catch (XArch &e) {
LOG((CLOG_ERR "ipc log buffer thread error, %s", e.what()));
}
LOG((CLOG_DEBUG "ipc log buffer thread finished"));
}
void IpcLogOutputter::notifyBuffer()
{
ArchMutexLock lock(m_notifyMutex);
ARCH->broadcastCondVar(m_notifyCond);
}
String IpcLogOutputter::getChunk(size_t count)
{
ArchMutexLock lock(m_bufferMutex);
if (m_buffer.size() < count) {
count = m_buffer.size();
}
String chunk;
for (size_t i = 0; i < count; i++) {
chunk.append(m_buffer.front());
chunk.append("\n");
m_buffer.pop_front();
}
return chunk;
}
void IpcLogOutputter::sendBuffer()
{
if (m_buffer.empty() || !m_ipcServer.hasClients(m_clientType)) {
return;
}
IpcLogLineMessage message(getChunk(kMaxSendLines));
m_sending = true;
m_ipcServer.send(message, IpcClientType::GUI);
m_sending = false;
}
void IpcLogOutputter::bufferMaxSize(UInt16 bufferMaxSize)
{
m_bufferMaxSize = bufferMaxSize;
}
UInt16 IpcLogOutputter::bufferMaxSize() const
{
return m_bufferMaxSize;
}
void IpcLogOutputter::bufferRateLimit(UInt16 writeLimit, double timeLimit)
{
m_bufferRateWriteLimit = writeLimit;
m_bufferRateTimeLimit = timeLimit;
}
| 5,150
|
C++
|
.cpp
| 180
| 25.411111
| 103
| 0.720737
|
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,550
|
IpcServerProxy.cpp
|
deskflow_deskflow/src/lib/ipc/IpcServerProxy.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 "ipc/IpcServerProxy.h"
#include "base/Log.h"
#include "base/TMethodEventJob.h"
#include "common/ipc.h"
#include "deskflow/ProtocolUtil.h"
#include "io/IStream.h"
#include "ipc/IpcMessage.h"
//
// IpcServerProxy
//
IpcServerProxy::IpcServerProxy(deskflow::IStream &stream, IEventQueue *events) : m_stream(stream), m_events(events)
{
m_events->adoptHandler(
m_events->forIStream().inputReady(), stream.getEventTarget(),
new TMethodEventJob<IpcServerProxy>(this, &IpcServerProxy::handleData)
);
}
IpcServerProxy::~IpcServerProxy()
{
m_events->removeHandler(m_events->forIStream().inputReady(), m_stream.getEventTarget());
}
void IpcServerProxy::handleData(const Event &, void *)
{
LOG((CLOG_DEBUG "start ipc handle data"));
UInt8 code[4];
UInt32 n = m_stream.read(code, 4);
while (n != 0) {
LOG((CLOG_DEBUG "ipc read: %c%c%c%c", code[0], code[1], code[2], code[3]));
IpcMessage *m = nullptr;
if (memcmp(code, kIpcMsgLogLine, 4) == 0) {
m = parseLogLine();
} else if (memcmp(code, kIpcMsgShutdown, 4) == 0) {
m = new IpcShutdownMessage();
} else {
LOG((CLOG_ERR "invalid ipc message"));
disconnect();
}
// don't delete with this event; the data is passed to a new event.
Event e(m_events->forIpcServerProxy().messageReceived(), this, NULL, Event::kDontFreeData);
e.setDataObject(m);
m_events->addEvent(e);
n = m_stream.read(code, 4);
}
LOG((CLOG_DEBUG "finished ipc handle data"));
}
void IpcServerProxy::send(const IpcMessage &message)
{
LOG((CLOG_DEBUG4 "ipc write: %d", message.type()));
switch (message.type()) {
case IpcMessageType::Hello: {
const IpcHelloMessage &hm = static_cast<const IpcHelloMessage &>(message);
ProtocolUtil::writef(&m_stream, kIpcMsgHello, hm.clientType());
break;
}
case IpcMessageType::Command: {
const IpcCommandMessage &cm = static_cast<const IpcCommandMessage &>(message);
const String command = cm.command();
ProtocolUtil::writef(&m_stream, kIpcMsgCommand, &command);
break;
}
default:
LOG((CLOG_ERR "ipc message not supported: %d", message.type()));
break;
}
}
IpcLogLineMessage *IpcServerProxy::parseLogLine()
{
String logLine;
ProtocolUtil::readf(&m_stream, kIpcMsgLogLine + 4, &logLine);
// must be deleted by event handler.
return new IpcLogLineMessage(logLine);
}
void IpcServerProxy::disconnect()
{
LOG((CLOG_DEBUG "ipc disconnect, closing stream"));
m_stream.close();
}
| 3,223
|
C++
|
.cpp
| 94
| 31.191489
| 115
| 0.713183
|
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,551
|
IpcMessage.cpp
|
deskflow_deskflow/src/lib/ipc/IpcMessage.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 "ipc/IpcMessage.h"
#include "common/ipc.h"
IpcMessage::IpcMessage(IpcMessageType type) : m_type(type)
{
}
IpcHelloMessage::IpcHelloMessage(IpcClientType clientType) : IpcMessage(IpcMessageType::Hello), m_clientType(clientType)
{
}
IpcHelloBackMessage::IpcHelloBackMessage() : IpcMessage(IpcMessageType::HelloBack)
{
}
IpcShutdownMessage::IpcShutdownMessage() : IpcMessage(IpcMessageType::Shutdown)
{
}
IpcLogLineMessage::IpcLogLineMessage(const String &logLine) : IpcMessage(IpcMessageType::LogLine), m_logLine(logLine)
{
}
IpcCommandMessage::IpcCommandMessage(const String &command, bool elevate)
: IpcMessage(IpcMessageType::Command),
m_command(command),
m_elevate(elevate)
{
}
| 1,437
|
C++
|
.cpp
| 40
| 33.95
| 120
| 0.781295
|
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,552
|
IpcServer.cpp
|
deskflow_deskflow/src/lib/ipc/IpcServer.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 "ipc/IpcServer.h"
#include "base/Event.h"
#include "base/IEventQueue.h"
#include "base/Log.h"
#include "base/TMethodEventJob.h"
#include "common/ipc.h"
#include "io/IStream.h"
#include "ipc/IpcClientProxy.h"
#include "ipc/IpcMessage.h"
#include "net/IDataSocket.h"
//
// IpcServer
//
IpcServer::IpcServer(IEventQueue *events, SocketMultiplexer *socketMultiplexer)
: m_mock(false),
m_events(events),
m_socketMultiplexer(socketMultiplexer),
m_socket(nullptr),
m_address(NetworkAddress(kIpcHost, kIpcPort))
{
init();
}
IpcServer::IpcServer(IEventQueue *events, SocketMultiplexer *socketMultiplexer, int port)
: m_mock(false),
m_events(events),
m_socketMultiplexer(socketMultiplexer),
m_address(NetworkAddress(kIpcHost, port))
{
init();
}
void IpcServer::init()
{
m_socket = new TCPListenSocket(m_events, m_socketMultiplexer, IArchNetwork::EAddressFamily::kINET);
m_clientsMutex = ARCH->newMutex();
m_address.resolve();
m_events->adoptHandler(
m_events->forIListenSocket().connecting(), m_socket,
new TMethodEventJob<IpcServer>(this, &IpcServer::handleClientConnecting)
);
}
IpcServer::~IpcServer()
{
if (m_mock) {
return;
}
if (m_socket != nullptr) {
delete m_socket;
}
ARCH->lockMutex(m_clientsMutex);
ClientList::iterator it;
for (it = m_clients.begin(); it != m_clients.end(); it++) {
deleteClient(*it);
}
m_clients.clear();
ARCH->unlockMutex(m_clientsMutex);
ARCH->closeMutex(m_clientsMutex);
m_events->removeHandler(m_events->forIListenSocket().connecting(), m_socket);
}
void IpcServer::listen()
{
m_socket->bind(m_address);
}
void IpcServer::handleClientConnecting(const Event &, void *)
{
deskflow::IStream *stream = m_socket->accept();
if (stream == NULL) {
return;
}
LOG((CLOG_DEBUG "accepted ipc client connection"));
ARCH->lockMutex(m_clientsMutex);
IpcClientProxy *proxy = new IpcClientProxy(*stream, m_events);
m_clients.push_back(proxy);
ARCH->unlockMutex(m_clientsMutex);
m_events->adoptHandler(
m_events->forIpcClientProxy().disconnected(), proxy,
new TMethodEventJob<IpcServer>(this, &IpcServer::handleClientDisconnected)
);
m_events->adoptHandler(
m_events->forIpcClientProxy().messageReceived(), proxy,
new TMethodEventJob<IpcServer>(this, &IpcServer::handleMessageReceived)
);
m_events->addEvent(Event(m_events->forIpcServer().clientConnected(), this, proxy, Event::kDontFreeData));
}
void IpcServer::handleClientDisconnected(const Event &e, void *)
{
IpcClientProxy *proxy = static_cast<IpcClientProxy *>(e.getTarget());
ArchMutexLock lock(m_clientsMutex);
m_clients.remove(proxy);
deleteClient(proxy);
LOG((CLOG_DEBUG "ipc client proxy removed, connected=%d", m_clients.size()));
}
void IpcServer::handleMessageReceived(const Event &e, void *)
{
Event event(m_events->forIpcServer().messageReceived(), this);
event.setDataObject(e.getDataObject());
m_events->addEvent(event);
}
void IpcServer::deleteClient(IpcClientProxy *proxy)
{
m_events->removeHandler(m_events->forIpcClientProxy().messageReceived(), proxy);
m_events->removeHandler(m_events->forIpcClientProxy().disconnected(), proxy);
delete proxy;
}
bool IpcServer::hasClients(IpcClientType clientType) const
{
ArchMutexLock lock(m_clientsMutex);
if (m_clients.empty()) {
return false;
}
ClientList::const_iterator it;
for (it = m_clients.begin(); it != m_clients.end(); it++) {
// at least one client is alive and type matches, there are clients.
IpcClientProxy *p = *it;
if (!p->m_disconnecting && p->m_clientType == clientType) {
return true;
}
}
// all clients must be disconnecting, no active clients.
return false;
}
void IpcServer::send(const IpcMessage &message, IpcClientType filterType)
{
ArchMutexLock lock(m_clientsMutex);
ClientList::iterator it;
for (it = m_clients.begin(); it != m_clients.end(); it++) {
IpcClientProxy *proxy = *it;
if (proxy->m_clientType == filterType) {
proxy->send(message);
}
}
}
| 4,817
|
C++
|
.cpp
| 148
| 29.493243
| 107
| 0.72839
|
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,553
|
IpcClientProxy.cpp
|
deskflow_deskflow/src/lib/ipc/IpcClientProxy.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012 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 "ipc/IpcClientProxy.h"
#include "base/Log.h"
#include "base/TMethodEventJob.h"
#include "common/ipc.h"
#include "deskflow/ProtocolUtil.h"
#include "io/IStream.h"
#include "ipc/IpcMessage.h"
#include "ipc/IpcSettingMessage.h"
//
// IpcClientProxy
//
IpcClientProxy::IpcClientProxy(deskflow::IStream &stream, IEventQueue *events) : m_stream(stream), m_events(events)
{
m_events->adoptHandler(
m_events->forIStream().inputReady(), stream.getEventTarget(),
new TMethodEventJob<IpcClientProxy>(this, &IpcClientProxy::handleData)
);
m_events->adoptHandler(
m_events->forIStream().outputError(), stream.getEventTarget(),
new TMethodEventJob<IpcClientProxy>(this, &IpcClientProxy::handleWriteError)
);
m_events->adoptHandler(
m_events->forIStream().inputShutdown(), stream.getEventTarget(),
new TMethodEventJob<IpcClientProxy>(this, &IpcClientProxy::handleDisconnect)
);
m_events->adoptHandler(
m_events->forIStream().outputShutdown(), stream.getEventTarget(),
new TMethodEventJob<IpcClientProxy>(this, &IpcClientProxy::handleWriteError)
);
}
IpcClientProxy::~IpcClientProxy()
{
m_events->removeHandler(m_events->forIStream().inputReady(), m_stream.getEventTarget());
m_events->removeHandler(m_events->forIStream().outputError(), m_stream.getEventTarget());
m_events->removeHandler(m_events->forIStream().inputShutdown(), m_stream.getEventTarget());
m_events->removeHandler(m_events->forIStream().outputShutdown(), m_stream.getEventTarget());
// don't delete the stream while it's being used.
ARCH->lockMutex(m_readMutex);
ARCH->lockMutex(m_writeMutex);
delete &m_stream;
ARCH->unlockMutex(m_readMutex);
ARCH->unlockMutex(m_writeMutex);
ARCH->closeMutex(m_readMutex);
ARCH->closeMutex(m_writeMutex);
}
void IpcClientProxy::handleDisconnect(const Event &, void *)
{
disconnect();
LOG((CLOG_DEBUG "ipc client disconnected"));
}
void IpcClientProxy::handleWriteError(const Event &, void *)
{
disconnect();
LOG((CLOG_DEBUG "ipc client write error"));
}
void IpcClientProxy::handleData(const Event &, void *)
{
// don't allow the dtor to destroy the stream while we're using it.
ArchMutexLock lock(m_readMutex);
LOG((CLOG_DEBUG "start ipc handle data"));
UInt8 code[4];
UInt32 n = m_stream.read(code, 4);
while (n != 0) {
LOG((CLOG_DEBUG "ipc read: %c%c%c%c", code[0], code[1], code[2], code[3]));
IpcMessage *m = nullptr;
if (memcmp(code, kIpcMsgHello, 4) == 0) {
m = parseHello();
} else if (memcmp(code, kIpcMsgCommand, 4) == 0) {
m = parseCommand();
} else if (memcmp(code, kIpcMsgSetting, 4) == 0) {
m = parseSetting();
} else {
LOG((CLOG_ERR "invalid ipc message"));
disconnect();
}
// don't delete with this event; the data is passed to a new event.
Event e(m_events->forIpcClientProxy().messageReceived(), this, NULL, Event::kDontFreeData);
e.setDataObject(m);
m_events->addEvent(e);
n = m_stream.read(code, 4);
}
LOG((CLOG_DEBUG "finished ipc handle data"));
}
void IpcClientProxy::send(const IpcMessage &message)
{
// don't allow other threads to write until we've finished the entire
// message. stream write is locked, but only for that single write.
// also, don't allow the dtor to destroy the stream while we're using it.
ArchMutexLock lock(m_writeMutex);
LOG((CLOG_DEBUG4 "ipc write: %d", message.type()));
switch (message.type()) {
case IpcMessageType::LogLine: {
const IpcLogLineMessage &llm = static_cast<const IpcLogLineMessage &>(message);
const String logLine = llm.logLine();
ProtocolUtil::writef(&m_stream, kIpcMsgLogLine, &logLine);
break;
}
case IpcMessageType::Shutdown:
ProtocolUtil::writef(&m_stream, kIpcMsgShutdown);
break;
case IpcMessageType::HelloBack:
ProtocolUtil::writef(&m_stream, kIpcMsgHelloBack);
break;
default:
LOG((CLOG_ERR "ipc message not supported: %d", message.type()));
break;
}
}
IpcHelloMessage *IpcClientProxy::parseHello()
{
UInt8 type;
ProtocolUtil::readf(&m_stream, kIpcMsgHello + 4, &type);
m_clientType = static_cast<IpcClientType>(type);
// must be deleted by event handler.
return new IpcHelloMessage(m_clientType);
}
IpcCommandMessage *IpcClientProxy::parseCommand()
{
String command;
UInt8 elevate;
ProtocolUtil::readf(&m_stream, kIpcMsgCommand + 4, &command, &elevate);
// must be deleted by event handler.
return new IpcCommandMessage(command, elevate != 0);
}
IpcSettingMessage *IpcClientProxy::parseSetting() const
{
String name;
String value;
ProtocolUtil::readf(&m_stream, kIpcMsgSetting + 4, &name, &value);
// must be deleted by event handler.
return new IpcSettingMessage(name, value);
}
void IpcClientProxy::disconnect()
{
LOG((CLOG_DEBUG "ipc disconnect, closing stream"));
m_disconnecting = true;
m_stream.close();
m_events->addEvent(Event(m_events->forIpcClientProxy().disconnected(), this));
}
| 5,678
|
C++
|
.cpp
| 155
| 33.425806
| 115
| 0.726676
|
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,554
|
XWindowsClipboardAnyBitmapConverter.cpp
|
deskflow_deskflow/src/lib/platform/XWindowsClipboardAnyBitmapConverter.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 "platform/XWindowsClipboardAnyBitmapConverter.h"
// BMP info header structure
struct CBMPInfoHeader
{
public:
UInt32 biSize;
SInt32 biWidth;
SInt32 biHeight;
UInt16 biPlanes;
UInt16 biBitCount;
UInt32 biCompression;
UInt32 biSizeImage;
SInt32 biXPelsPerMeter;
SInt32 biYPelsPerMeter;
UInt32 biClrUsed;
UInt32 biClrImportant;
};
// BMP is little-endian
static void toLE(UInt8 *&dst, UInt16 src)
{
dst[0] = static_cast<UInt8>(src & 0xffu);
dst[1] = static_cast<UInt8>((src >> 8) & 0xffu);
dst += 2;
}
static void toLE(UInt8 *&dst, SInt32 src)
{
dst[0] = static_cast<UInt8>(src & 0xffu);
dst[1] = static_cast<UInt8>((src >> 8) & 0xffu);
dst[2] = static_cast<UInt8>((src >> 16) & 0xffu);
dst[3] = static_cast<UInt8>((src >> 24) & 0xffu);
dst += 4;
}
static void toLE(UInt8 *&dst, UInt32 src)
{
dst[0] = static_cast<UInt8>(src & 0xffu);
dst[1] = static_cast<UInt8>((src >> 8) & 0xffu);
dst[2] = static_cast<UInt8>((src >> 16) & 0xffu);
dst[3] = static_cast<UInt8>((src >> 24) & 0xffu);
dst += 4;
}
static inline UInt16 fromLEU16(const UInt8 *data)
{
return static_cast<UInt16>(data[0]) | (static_cast<UInt16>(data[1]) << 8);
}
static inline SInt32 fromLES32(const UInt8 *data)
{
return static_cast<SInt32>(
static_cast<UInt32>(data[0]) | (static_cast<UInt32>(data[1]) << 8) | (static_cast<UInt32>(data[2]) << 16) |
(static_cast<UInt32>(data[3]) << 24)
);
}
static inline UInt32 fromLEU32(const UInt8 *data)
{
return static_cast<UInt32>(data[0]) | (static_cast<UInt32>(data[1]) << 8) | (static_cast<UInt32>(data[2]) << 16) |
(static_cast<UInt32>(data[3]) << 24);
}
//
// XWindowsClipboardAnyBitmapConverter
//
XWindowsClipboardAnyBitmapConverter::XWindowsClipboardAnyBitmapConverter()
{
// do nothing
}
XWindowsClipboardAnyBitmapConverter::~XWindowsClipboardAnyBitmapConverter()
{
// do nothing
}
IClipboard::EFormat XWindowsClipboardAnyBitmapConverter::getFormat() const
{
return IClipboard::kBitmap;
}
int XWindowsClipboardAnyBitmapConverter::getDataSize() const
{
return 8;
}
String XWindowsClipboardAnyBitmapConverter::fromIClipboard(const String &bmp) const
{
// fill BMP info header with native-endian data
CBMPInfoHeader infoHeader;
const UInt8 *rawBMPInfoHeader = reinterpret_cast<const UInt8 *>(bmp.data());
infoHeader.biSize = fromLEU32(rawBMPInfoHeader + 0);
infoHeader.biWidth = fromLES32(rawBMPInfoHeader + 4);
infoHeader.biHeight = fromLES32(rawBMPInfoHeader + 8);
infoHeader.biPlanes = fromLEU16(rawBMPInfoHeader + 12);
infoHeader.biBitCount = fromLEU16(rawBMPInfoHeader + 14);
infoHeader.biCompression = fromLEU32(rawBMPInfoHeader + 16);
infoHeader.biSizeImage = fromLEU32(rawBMPInfoHeader + 20);
infoHeader.biXPelsPerMeter = fromLES32(rawBMPInfoHeader + 24);
infoHeader.biYPelsPerMeter = fromLES32(rawBMPInfoHeader + 28);
infoHeader.biClrUsed = fromLEU32(rawBMPInfoHeader + 32);
infoHeader.biClrImportant = fromLEU32(rawBMPInfoHeader + 36);
// check that format is acceptable
if (infoHeader.biSize != 40 || infoHeader.biWidth == 0 || infoHeader.biHeight == 0 || infoHeader.biPlanes != 0 ||
infoHeader.biCompression != 0 || (infoHeader.biBitCount != 24 && infoHeader.biBitCount != 32)) {
return String();
}
// convert to image format
const UInt8 *rawBMPPixels = rawBMPInfoHeader + 40;
if (infoHeader.biBitCount == 24) {
return doBGRFromIClipboard(rawBMPPixels, infoHeader.biWidth, infoHeader.biHeight);
} else {
return doBGRAFromIClipboard(rawBMPPixels, infoHeader.biWidth, infoHeader.biHeight);
}
}
String XWindowsClipboardAnyBitmapConverter::toIClipboard(const String &image) const
{
// convert to raw BMP data
UInt32 w, h, depth;
String rawBMP = doToIClipboard(image, w, h, depth);
if (rawBMP.empty() || w == 0 || h == 0 || (depth != 24 && depth != 32)) {
return String();
}
// fill BMP info header with little-endian data
UInt8 infoHeader[40];
UInt8 *dst = infoHeader;
toLE(dst, static_cast<UInt32>(40));
toLE(dst, static_cast<SInt32>(w));
toLE(dst, static_cast<SInt32>(h));
toLE(dst, static_cast<UInt16>(1));
toLE(dst, static_cast<UInt16>(depth));
toLE(dst, static_cast<UInt32>(0)); // BI_RGB
toLE(dst, static_cast<UInt32>(image.size()));
toLE(dst, static_cast<SInt32>(2834)); // 72 dpi
toLE(dst, static_cast<SInt32>(2834)); // 72 dpi
toLE(dst, static_cast<UInt32>(0));
toLE(dst, static_cast<UInt32>(0));
// construct image
return String(reinterpret_cast<const char *>(infoHeader), sizeof(infoHeader)) + rawBMP;
}
| 5,281
|
C++
|
.cpp
| 146
| 33.60274
| 116
| 0.726295
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| true
| false
| false
| true
| false
| false
|
13,555
|
MSWindowsClipboardFacade.cpp
|
deskflow_deskflow/src/lib/platform/MSWindowsClipboardFacade.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 "platform/MSWindowsClipboardFacade.h"
#include "platform/MSWindowsClipboard.h"
void MSWindowsClipboardFacade::write(HANDLE win32Data, UINT win32Format)
{
if (SetClipboardData(win32Format, win32Data) == NULL) {
// free converted data if we couldn't put it on
// the clipboard.
// nb: couldn't cause this in integ tests.
GlobalFree(win32Data);
}
}
| 1,108
|
C++
|
.cpp
| 28
| 37.178571
| 72
| 0.758589
|
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,556
|
OSXPowerManager.cpp
|
deskflow_deskflow/src/lib/platform/OSXPowerManager.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2021 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 "OSXPowerManager.h"
#include "base/Log.h"
OSXPowerManager::OSXPowerManager()
{
}
OSXPowerManager::~OSXPowerManager()
{
enableSleep();
}
void OSXPowerManager::disableSleep()
{
if (!m_sleepPreventionAssertionID) {
CFStringRef reasonForActivity = CFSTR("Deskflow application");
IOReturn result = IOPMAssertionCreateWithName(
kIOPMAssertPreventUserIdleDisplaySleep, kIOPMAssertionLevelOn, reasonForActivity, &m_sleepPreventionAssertionID
);
if (result != kIOReturnSuccess) {
m_sleepPreventionAssertionID = 0;
LOG((CLOG_ERR "failed to disable system idle sleep"));
}
}
}
void OSXPowerManager::enableSleep()
{
if (m_sleepPreventionAssertionID) {
IOPMAssertionRelease(m_sleepPreventionAssertionID);
}
}
| 1,503
|
C++
|
.cpp
| 45
| 30.733333
| 119
| 0.763248
|
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,557
|
OSXClipboardBMPConverter.cpp
|
deskflow_deskflow/src/lib/platform/OSXClipboardBMPConverter.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2014-2016 Symless Ltd.
* Patch by Ryan Chapman
*
* 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/OSXClipboardBMPConverter.h"
#include "base/Log.h"
// BMP file header structure
struct CBMPHeader
{
public:
UInt16 type;
UInt32 size;
UInt16 reserved1;
UInt16 reserved2;
UInt32 offset;
};
// BMP is little-endian
static inline UInt32 fromLEU32(const UInt8 *data)
{
return static_cast<UInt32>(data[0]) | (static_cast<UInt32>(data[1]) << 8) | (static_cast<UInt32>(data[2]) << 16) |
(static_cast<UInt32>(data[3]) << 24);
}
static void toLE(UInt8 *&dst, char src)
{
dst[0] = static_cast<UInt8>(src);
dst += 1;
}
static void toLE(UInt8 *&dst, UInt16 src)
{
dst[0] = static_cast<UInt8>(src & 0xffu);
dst[1] = static_cast<UInt8>((src >> 8) & 0xffu);
dst += 2;
}
static void toLE(UInt8 *&dst, UInt32 src)
{
dst[0] = static_cast<UInt8>(src & 0xffu);
dst[1] = static_cast<UInt8>((src >> 8) & 0xffu);
dst[2] = static_cast<UInt8>((src >> 16) & 0xffu);
dst[3] = static_cast<UInt8>((src >> 24) & 0xffu);
dst += 4;
}
OSXClipboardBMPConverter::OSXClipboardBMPConverter()
{
// do nothing
}
OSXClipboardBMPConverter::~OSXClipboardBMPConverter()
{
// do nothing
}
IClipboard::EFormat OSXClipboardBMPConverter::getFormat() const
{
return IClipboard::kBitmap;
}
CFStringRef OSXClipboardBMPConverter::getOSXFormat() const
{
// TODO: does this only work with Windows?
return CFSTR("com.microsoft.bmp");
}
String OSXClipboardBMPConverter::fromIClipboard(const String &bmp) const
{
LOG((CLOG_DEBUG1 "getting data from clipboard"));
// create BMP image
UInt8 header[14];
UInt8 *dst = header;
toLE(dst, 'B');
toLE(dst, 'M');
toLE(dst, static_cast<UInt32>(14 + bmp.size()));
toLE(dst, static_cast<UInt16>(0));
toLE(dst, static_cast<UInt16>(0));
toLE(dst, static_cast<UInt32>(14 + 40));
return String(reinterpret_cast<const char *>(header), 14) + bmp;
}
String OSXClipboardBMPConverter::toIClipboard(const String &bmp) const
{
// make sure data is big enough for a BMP file
if (bmp.size() <= 14 + 40) {
return String();
}
// check BMP file header
const UInt8 *rawBMPHeader = reinterpret_cast<const UInt8 *>(bmp.data());
if (rawBMPHeader[0] != 'B' || rawBMPHeader[1] != 'M') {
return String();
}
// get offset to image data
UInt32 offset = fromLEU32(rawBMPHeader + 10);
// construct BMP
if (offset == 14 + 40) {
return bmp.substr(14);
} else {
return bmp.substr(14, 40) + bmp.substr(offset, bmp.size() - offset);
}
}
| 3,150
|
C++
|
.cpp
| 105
| 27.609524
| 116
| 0.7033
|
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,558
|
MSWindowsClipboardBitmapConverter.cpp
|
deskflow_deskflow/src/lib/platform/MSWindowsClipboardBitmapConverter.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 "platform/MSWindowsClipboardBitmapConverter.h"
#include "base/Log.h"
//
// MSWindowsClipboardBitmapConverter
//
MSWindowsClipboardBitmapConverter::MSWindowsClipboardBitmapConverter()
{
// do nothing
}
MSWindowsClipboardBitmapConverter::~MSWindowsClipboardBitmapConverter()
{
// do nothing
}
IClipboard::EFormat MSWindowsClipboardBitmapConverter::getFormat() const
{
return IClipboard::kBitmap;
}
UINT MSWindowsClipboardBitmapConverter::getWin32Format() const
{
return CF_DIB;
}
HANDLE
MSWindowsClipboardBitmapConverter::fromIClipboard(const String &data) const
{
// copy to memory handle
HGLOBAL gData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, data.size());
if (gData != NULL) {
// get a pointer to the allocated memory
char *dst = (char *)GlobalLock(gData);
if (dst != NULL) {
memcpy(dst, data.data(), data.size());
GlobalUnlock(gData);
} else {
GlobalFree(gData);
gData = NULL;
}
}
return gData;
}
String MSWindowsClipboardBitmapConverter::toIClipboard(HANDLE data) const
{
// get datator
LPVOID src = GlobalLock(data);
if (src == NULL) {
return String();
}
UInt32 srcSize = (UInt32)GlobalSize(data);
// check image type
const BITMAPINFO *bitmap = static_cast<const BITMAPINFO *>(src);
LOG(
(CLOG_INFO "bitmap: %dx%d %d", bitmap->bmiHeader.biWidth, bitmap->bmiHeader.biHeight,
(int)bitmap->bmiHeader.biBitCount)
);
if (bitmap->bmiHeader.biPlanes == 1 && (bitmap->bmiHeader.biBitCount == 24 || bitmap->bmiHeader.biBitCount == 32) &&
bitmap->bmiHeader.biCompression == BI_RGB) {
// already in canonical form
String image(static_cast<char const *>(src), srcSize);
GlobalUnlock(data);
return image;
}
// create a destination DIB section
LOG((CLOG_INFO "convert image from: depth=%d comp=%d", bitmap->bmiHeader.biBitCount, bitmap->bmiHeader.biCompression)
);
void *raw;
BITMAPINFOHEADER info;
LONG w = bitmap->bmiHeader.biWidth;
LONG h = bitmap->bmiHeader.biHeight;
info.biSize = sizeof(BITMAPINFOHEADER);
info.biWidth = w;
info.biHeight = h;
info.biPlanes = 1;
info.biBitCount = 32;
info.biCompression = BI_RGB;
info.biSizeImage = 0;
info.biXPelsPerMeter = 1000;
info.biYPelsPerMeter = 1000;
info.biClrUsed = 0;
info.biClrImportant = 0;
HDC dc = GetDC(NULL);
HBITMAP dst = CreateDIBSection(dc, (BITMAPINFO *)&info, DIB_RGB_COLORS, &raw, NULL, 0);
// find the start of the pixel data
const char *srcBits = (const char *)bitmap + bitmap->bmiHeader.biSize;
if (bitmap->bmiHeader.biBitCount >= 16) {
if (bitmap->bmiHeader.biCompression == BI_BITFIELDS &&
(bitmap->bmiHeader.biBitCount == 16 || bitmap->bmiHeader.biBitCount == 32)) {
srcBits += 3 * sizeof(DWORD);
}
} else if (bitmap->bmiHeader.biClrUsed != 0) {
srcBits += bitmap->bmiHeader.biClrUsed * sizeof(RGBQUAD);
} else {
// http://msdn.microsoft.com/en-us/library/ke55d167(VS.80).aspx
srcBits += (1i64 << bitmap->bmiHeader.biBitCount) * sizeof(RGBQUAD);
}
// copy source image to destination image
HDC dstDC = CreateCompatibleDC(dc);
HGDIOBJ oldBitmap = SelectObject(dstDC, dst);
SetDIBitsToDevice(dstDC, 0, 0, w, h, 0, 0, 0, h, srcBits, bitmap, DIB_RGB_COLORS);
SelectObject(dstDC, oldBitmap);
DeleteDC(dstDC);
GdiFlush();
// extract data
String image((const char *)&info, info.biSize);
image.append((const char *)raw, 4 * w * h);
// clean up GDI
DeleteObject(dst);
ReleaseDC(NULL, dc);
// release handle
GlobalUnlock(data);
return image;
}
| 4,295
|
C++
|
.cpp
| 127
| 30.653543
| 119
| 0.719277
|
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,559
|
OSXScreenSaver.cpp
|
deskflow_deskflow/src/lib/platform/OSXScreenSaver.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/>.
*/
#import "platform/OSXScreenSaver.h"
#import "base/IEventQueue.h"
#import "base/Log.h"
#import "deskflow/IPrimaryScreen.h"
#import "platform/OSXScreenSaverUtil.h"
#import <string.h>
#import <sys/sysctl.h>
// TODO: upgrade deprecated function usage in these functions.
void getProcessSerialNumber(const char *name, ProcessSerialNumber &psn);
bool isScreenSaverEngine(const ProcessSerialNumber &psn);
//
// OSXScreenSaver
//
OSXScreenSaver::OSXScreenSaver(IEventQueue *events, void *eventTarget)
: m_eventTarget(eventTarget),
m_enabled(true),
m_events(events)
{
m_autoReleasePool = screenSaverUtilCreatePool();
m_screenSaverController = screenSaverUtilCreateController();
// install launch/termination event handlers
EventTypeSpec launchEventTypes[2];
launchEventTypes[0].eventClass = kEventClassApplication;
launchEventTypes[0].eventKind = kEventAppLaunched;
launchEventTypes[1].eventClass = kEventClassApplication;
launchEventTypes[1].eventKind = kEventAppTerminated;
EventHandlerUPP launchTerminationEventHandler = NewEventHandlerUPP(launchTerminationCallback);
InstallApplicationEventHandler(
launchTerminationEventHandler, 2, launchEventTypes, this, &m_launchTerminationEventHandlerRef
);
DisposeEventHandlerUPP(launchTerminationEventHandler);
m_screenSaverPSN.highLongOfPSN = 0;
m_screenSaverPSN.lowLongOfPSN = 0;
if (isActive()) {
getProcessSerialNumber("ScreenSaverEngine", m_screenSaverPSN);
}
}
OSXScreenSaver::~OSXScreenSaver()
{
RemoveEventHandler(m_launchTerminationEventHandlerRef);
// screenSaverUtilReleaseController(m_screenSaverController);
screenSaverUtilReleasePool(m_autoReleasePool);
}
void OSXScreenSaver::enable()
{
m_enabled = true;
screenSaverUtilEnable(m_screenSaverController);
}
void OSXScreenSaver::disable()
{
m_enabled = false;
screenSaverUtilDisable(m_screenSaverController);
}
void OSXScreenSaver::activate()
{
screenSaverUtilActivate(m_screenSaverController);
}
void OSXScreenSaver::deactivate()
{
screenSaverUtilDeactivate(m_screenSaverController, m_enabled);
}
bool OSXScreenSaver::isActive() const
{
return (screenSaverUtilIsActive(m_screenSaverController) != 0);
}
void OSXScreenSaver::processLaunched(ProcessSerialNumber psn)
{
if (isScreenSaverEngine(psn)) {
m_screenSaverPSN = psn;
LOG((CLOG_DEBUG1 "screen saver engine launched, enabled=%d", m_enabled));
if (m_enabled) {
m_events->addEvent(Event(m_events->forIPrimaryScreen().screensaverActivated(), m_eventTarget));
}
}
}
void OSXScreenSaver::processTerminated(ProcessSerialNumber psn)
{
if (m_screenSaverPSN.highLongOfPSN == psn.highLongOfPSN && m_screenSaverPSN.lowLongOfPSN == psn.lowLongOfPSN) {
LOG((CLOG_DEBUG1 "screen saver engine terminated, enabled=%d", m_enabled));
if (m_enabled) {
m_events->addEvent(Event(m_events->forIPrimaryScreen().screensaverDeactivated(), m_eventTarget));
}
m_screenSaverPSN.highLongOfPSN = 0;
m_screenSaverPSN.lowLongOfPSN = 0;
}
}
pascal OSStatus
OSXScreenSaver::launchTerminationCallback(EventHandlerCallRef nextHandler, EventRef theEvent, void *userData)
{
OSStatus result;
ProcessSerialNumber psn;
EventParamType actualType;
ByteCount actualSize;
result = GetEventParameter(
theEvent, kEventParamProcessID, typeProcessSerialNumber, &actualType, sizeof(psn), &actualSize, &psn
);
if ((result == noErr) && (actualSize > 0) && (actualType == typeProcessSerialNumber)) {
OSXScreenSaver *screenSaver = (OSXScreenSaver *)userData;
UInt32 eventKind = GetEventKind(theEvent);
if (eventKind == kEventAppLaunched) {
screenSaver->processLaunched(psn);
} else if (eventKind == kEventAppTerminated) {
screenSaver->processTerminated(psn);
}
}
return (CallNextEventHandler(nextHandler, theEvent));
}
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
void getProcessSerialNumber(const char *name, ProcessSerialNumber &psn)
{
ProcessInfoRec procInfo;
Str31 procName; // pascal string. first byte holds length.
memset(&procInfo, 0, sizeof(procInfo));
procInfo.processName = procName;
procInfo.processInfoLength = sizeof(ProcessInfoRec);
ProcessSerialNumber checkPsn;
OSErr err = GetNextProcess(&checkPsn);
while (err == 0) {
memset(procName, 0, sizeof(procName));
err = GetProcessInformation(&checkPsn, &procInfo);
if (err != 0) {
break;
}
if (strcmp(name, (const char *)&procName[1]) == 0) {
psn = checkPsn;
break;
}
err = GetNextProcess(&checkPsn);
}
}
bool isScreenSaverEngine(const ProcessSerialNumber &psn)
{
CFStringRef processName;
OSStatus err = CopyProcessName(&psn, &processName);
bool result = (err == 0 && CFEqual(CFSTR("ScreenSaverEngine"), processName));
CFRelease(processName);
return result;
}
#pragma GCC diagnostic error "-Wdeprecated-declarations"
| 5,615
|
C++
|
.cpp
| 156
| 33.019231
| 113
| 0.773154
|
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,560
|
EiKeyState.cpp
|
deskflow_deskflow/src/lib/platform/EiKeyState.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2022 Red Hat, Inc.
* 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/EiKeyState.h"
#include "base/Log.h"
#include "deskflow/AppUtil.h"
#include "deskflow/ClientApp.h"
#include "platform/XWindowsUtil.h"
#include <algorithm>
#include <cstddef>
#include <memory>
#include <unistd.h>
#include <xkbcommon/xkbcommon.h>
namespace deskflow {
EiKeyState::EiKeyState(EiScreen *screen, IEventQueue *events)
: KeyState(events, AppUtil::instance().getKeyboardLayoutList(), ClientApp::instance().args().m_enableLangSync),
screen_{screen}
{
xkb_ = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
// FIXME: PrimaryClient->enable() calls into our keymap, so we must have
// one during initial startup - even before we know what our actual keymap is.
// Once we get the actual keymap from EIS, we swap it out so hopefully that's
// enough.
init_default_keymap();
}
void EiKeyState::init_default_keymap()
{
if (xkb_keymap_) {
xkb_keymap_unref(xkb_keymap_);
}
xkb_keymap_ = xkb_keymap_new_from_names(xkb_, nullptr, XKB_KEYMAP_COMPILE_NO_FLAGS);
if (xkb_state_) {
xkb_state_unref(xkb_state_);
}
xkb_state_ = xkb_state_new(xkb_keymap_);
}
void EiKeyState::init(int fd, size_t len)
{
auto buffer = std::make_unique<char[]>(len + 1);
auto sz = read(fd, buffer.get(), len);
if ((size_t)sz < len) {
LOG_NOTE("failed to create xkb context: %s", strerror(errno));
return;
}
// See xkbcommon/libxkbcommon issue #307, xkb_keymap_new_from_buffer fails if
// we have a terminating null byte. Since we can't control whether the other
// end sends that byte, enforce null-termination in our buffer and pass the
// whole thing as string.
buffer[len] = '\0'; // guarantee null-termination
auto keymap = xkb_keymap_new_from_string(xkb_, buffer.get(), XKB_KEYMAP_FORMAT_TEXT_V1, XKB_KEYMAP_COMPILE_NO_FLAGS);
if (!keymap) {
LOG_NOTE("failed to compile keymap, falling back to defaults");
// Falling back to layout "us" is a lot more useful than segfaulting
init_default_keymap();
return;
}
if (xkb_keymap_) {
xkb_keymap_unref(xkb_keymap_);
}
xkb_keymap_ = keymap;
if (xkb_state_) {
xkb_state_unref(xkb_state_);
}
xkb_state_ = xkb_state_new(xkb_keymap_);
}
EiKeyState::~EiKeyState()
{
xkb_context_unref(xkb_);
xkb_keymap_unref(xkb_keymap_);
xkb_state_unref(xkb_state_);
}
bool EiKeyState::fakeCtrlAltDel()
{
// pass keys through unchanged
return false;
}
KeyModifierMask EiKeyState::pollActiveModifiers() const
{
std::uint32_t xkb_mask = xkb_state_serialize_mods(xkb_state_, XKB_STATE_MODS_EFFECTIVE);
return convert_mod_mask(xkb_mask);
}
std::int32_t EiKeyState::pollActiveGroup() const
{
return xkb_state_serialize_layout(xkb_state_, XKB_STATE_LAYOUT_EFFECTIVE);
}
void EiKeyState::pollPressedKeys(KeyButtonSet &pressedKeys) const
{
// FIXME
return;
}
std::uint32_t EiKeyState::convert_mod_mask(std::uint32_t xkb_mask) const
{
std::uint32_t barrier_mask = 0;
for (xkb_mod_index_t xkbmod = 0; xkbmod < xkb_keymap_num_mods(xkb_keymap_); xkbmod++) {
if ((xkb_mask & (1 << xkbmod)) == 0)
continue;
const char *name = xkb_keymap_mod_get_name(xkb_keymap_, xkbmod);
if (strcmp(XKB_MOD_NAME_SHIFT, name) == 0)
barrier_mask |= (1 << kKeyModifierBitShift);
else if (strcmp(XKB_MOD_NAME_CAPS, name) == 0)
barrier_mask |= (1 << kKeyModifierBitCapsLock);
else if (strcmp(XKB_MOD_NAME_CTRL, name) == 0)
barrier_mask |= (1 << kKeyModifierBitControl);
else if (strcmp(XKB_MOD_NAME_ALT, name) == 0)
barrier_mask |= (1 << kKeyModifierBitAlt);
else if (strcmp(XKB_MOD_NAME_LOGO, name) == 0)
barrier_mask |= (1 << kKeyModifierBitSuper);
}
return barrier_mask;
}
// Only way to figure out whether a key is a modifier key is to press it,
// check if a modifier changed state and then release it again.
// Luckily xkbcommon allows us to do this in a separate state.
void EiKeyState::assign_generated_modifiers(std::uint32_t keycode, deskflow::KeyMap::KeyItem &item)
{
std::uint32_t mods_generates = 0;
auto state = xkb_state_new(xkb_keymap_);
enum xkb_state_component changed = xkb_state_update_key(state, keycode, XKB_KEY_DOWN);
if (changed) {
for (xkb_mod_index_t m = 0; m < xkb_keymap_num_mods(xkb_keymap_); m++) {
if (xkb_state_mod_index_is_active(state, m, XKB_STATE_MODS_LOCKED))
item.m_lock = true;
if (xkb_state_mod_index_is_active(state, m, XKB_STATE_MODS_EFFECTIVE)) {
mods_generates |= (1 << m);
}
}
}
xkb_state_update_key(state, keycode, XKB_KEY_UP);
xkb_state_unref(state);
item.m_generates = convert_mod_mask(mods_generates);
}
void EiKeyState::getKeyMap(deskflow::KeyMap &keyMap)
{
auto min_keycode = xkb_keymap_min_keycode(xkb_keymap_);
auto max_keycode = xkb_keymap_max_keycode(xkb_keymap_);
// X keycodes are evdev keycodes + 8 (libei gives us evdev keycodes)
for (auto keycode = min_keycode; keycode <= max_keycode; keycode++) {
// skip keys with no groups (they generate no symbols)
if (xkb_keymap_num_layouts_for_key(xkb_keymap_, keycode) == 0)
continue;
for (auto group = 0U; group < xkb_keymap_num_layouts(xkb_keymap_); group++) {
for (auto level = 0U; level < xkb_keymap_num_levels_for_key(xkb_keymap_, keycode, group); level++) {
const xkb_keysym_t *syms;
xkb_mod_mask_t masks[64];
auto nmasks = xkb_keymap_key_get_mods_for_level(xkb_keymap_, keycode, group, level, masks, 64);
auto nsyms = xkb_keymap_key_get_syms_by_level(xkb_keymap_, keycode, group, level, &syms);
if (nsyms == 0)
continue;
if (nsyms > 1)
LOG_WARN("multiple keysyms per keycode are not supported, keycode %d", keycode);
deskflow::KeyMap::KeyItem item{};
xkb_keysym_t keysym = syms[0];
KeySym sym = static_cast<KeyID>(keysym);
item.m_id = XWindowsUtil::mapKeySymToKeyID(sym);
item.m_button = static_cast<KeyButton>(keycode) - 8; // X keycode offset
item.m_group = group;
// For debugging only
char keysym_name[128] = {0};
xkb_keysym_get_name(keysym, keysym_name, sizeof(keysym_name));
// Set to all modifiers this key may be affected by
uint32_t mods_sensitive = 0;
for (auto n = 0U; n < nmasks; n++) {
mods_sensitive |= masks[n];
}
item.m_sensitive = convert_mod_mask(mods_sensitive);
uint32_t mods_required = 0;
for (std::size_t m = 0; m < nmasks; m++) {
mods_required |= masks[m];
}
item.m_required = convert_mod_mask(mods_required);
assign_generated_modifiers(keycode, item);
// add capslock version of key is sensitive to capslock
if (item.m_sensitive & KeyModifierShift && item.m_sensitive & KeyModifierCapsLock) {
item.m_required &= ~KeyModifierShift;
item.m_required |= KeyModifierCapsLock;
keyMap.addKeyEntry(item);
item.m_required |= KeyModifierShift;
item.m_required &= ~KeyModifierCapsLock;
}
keyMap.addKeyEntry(item);
}
}
}
// allow composition across groups
keyMap.allowGroupSwitchDuringCompose();
}
void EiKeyState::fakeKey(const Keystroke &keystroke)
{
switch (keystroke.m_type) {
case Keystroke::kButton:
LOG_DEBUG1(
"fake key: %03x (%08x) %s", keystroke.m_data.m_button.m_button, keystroke.m_data.m_button.m_client,
keystroke.m_data.m_button.m_press ? "down" : "up"
);
screen_->fakeKey(keystroke.m_data.m_button.m_button, keystroke.m_data.m_button.m_press);
break;
default:
break;
}
}
KeyID EiKeyState::map_key_from_keyval(uint32_t keyval) const
{
// FIXME: That might be a bit crude...?
xkb_keysym_t xkb_keysym = xkb_state_key_get_one_sym(xkb_state_, keyval);
KeySym keysym = static_cast<KeySym>(xkb_keysym);
KeyID keyid = XWindowsUtil::mapKeySymToKeyID(keysym);
LOG_DEBUG1("mapped key: code=%d keysym=0x%04lx to keyID=%d", keyval, keysym, keyid);
return keyid;
}
void EiKeyState::update_xkb_state(uint32_t keyval, bool is_pressed)
{
LOG_DEBUG1("update key state: keyval=%d pressed=%i", keyval, is_pressed);
xkb_state_update_key(xkb_state_, keyval, is_pressed ? XKB_KEY_DOWN : XKB_KEY_UP);
}
} // namespace deskflow
| 8,969
|
C++
|
.cpp
| 229
| 34.877729
| 119
| 0.685264
|
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,561
|
MSWindowsClipboardHTMLConverter.cpp
|
deskflow_deskflow/src/lib/platform/MSWindowsClipboardHTMLConverter.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 "platform/MSWindowsClipboardHTMLConverter.h"
#include "base/String.h"
//
// MSWindowsClipboardHTMLConverter
//
MSWindowsClipboardHTMLConverter::MSWindowsClipboardHTMLConverter()
{
m_format = RegisterClipboardFormat("HTML Format");
}
MSWindowsClipboardHTMLConverter::~MSWindowsClipboardHTMLConverter()
{
// do nothing
}
IClipboard::EFormat MSWindowsClipboardHTMLConverter::getFormat() const
{
return IClipboard::kHTML;
}
UINT MSWindowsClipboardHTMLConverter::getWin32Format() const
{
return m_format;
}
String MSWindowsClipboardHTMLConverter::doFromIClipboard(const String &data) const
{
// prepare to CF_HTML format prefix and suffix
String prefix("Version:0.9\r\nStartHTML:0000000105\r\n"
"EndHTML:ZZZZZZZZZZ\r\n"
"StartFragment:XXXXXXXXXX\r\nEndFragment:YYYYYYYYYY\r\n"
"<!DOCTYPE><HTML><BODY><!--StartFragment-->");
String suffix("<!--EndFragment--></BODY></HTML>\r\n");
// Get byte offsets for header
UInt32 StartFragment = (UInt32)prefix.size();
UInt32 EndFragment = StartFragment + (UInt32)data.size();
// StartHTML is constant by the design of the prefix
UInt32 EndHTML = EndFragment + (UInt32)suffix.size();
prefix.replace(prefix.find("XXXXXXXXXX"), 10, deskflow::string::sprintf("%010u", StartFragment));
prefix.replace(prefix.find("YYYYYYYYYY"), 10, deskflow::string::sprintf("%010u", EndFragment));
prefix.replace(prefix.find("ZZZZZZZZZZ"), 10, deskflow::string::sprintf("%010u", EndHTML));
// concatenate
prefix += data;
prefix += suffix;
return prefix;
}
String MSWindowsClipboardHTMLConverter::doToIClipboard(const String &data) const
{
// get fragment start/end args
String startArg = findArg(data, "StartFragment");
String endArg = findArg(data, "EndFragment");
if (startArg.empty() || endArg.empty()) {
return String();
}
// convert args to integers
SInt32 start = (SInt32)atoi(startArg.c_str());
SInt32 end = (SInt32)atoi(endArg.c_str());
if (start <= 0 || end <= 0 || start >= end) {
return String();
}
// extract the fragment
return data.substr(start, end - start);
}
String MSWindowsClipboardHTMLConverter::findArg(const String &data, const String &name) const
{
String::size_type i = data.find(name);
if (i == String::npos) {
return String();
}
i = data.find_first_of(":\r\n", i);
if (i == String::npos || data[i] != ':') {
return String();
}
i = data.find_first_of("0123456789\r\n", i + 1);
if (i == String::npos || data[i] == '\r' || data[i] == '\n') {
return String();
}
String::size_type j = data.find_first_not_of("0123456789", i);
if (j == String::npos) {
j = data.size();
}
return data.substr(i, j - i);
}
| 3,449
|
C++
|
.cpp
| 96
| 32.9375
| 99
| 0.712702
|
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,562
|
EiEventQueueBuffer.cpp
|
deskflow_deskflow/src/lib/platform/EiEventQueueBuffer.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2022 Red Hat, Inc.
* 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/EiEventQueueBuffer.h"
#include "base/Event.h"
#include "base/EventTypes.h"
#include "base/IEventQueue.h"
#include "base/Log.h"
#include "mt/Thread.h"
#include <cassert>
#include <cstdio>
#include <fcntl.h>
#include <poll.h>
#include <unistd.h>
class EventQueueTimer
{
};
namespace deskflow {
EiEventQueueBuffer::EiEventQueueBuffer(EiScreen *screen, ei *ei, IEventQueue *events) : ei_(ei_ref(ei)), events_(events)
{
// We need a pipe to signal ourselves when addEvent() is called
int pipefd[2];
int result = pipe2(pipefd, O_NONBLOCK);
assert(result == 0);
pipe_r_ = pipefd[0];
pipe_w_ = pipefd[1];
}
EiEventQueueBuffer::~EiEventQueueBuffer()
{
ei_unref(ei_);
close(pipe_r_);
close(pipe_w_);
}
void EiEventQueueBuffer::waitForEvent(double timeout_in_ms)
{
Thread::testCancel();
enum
{
EIFD,
PIPEFD,
POLLFD_COUNT, // Last element
};
struct pollfd pfds[POLLFD_COUNT];
pfds[EIFD].fd = ei_get_fd(ei_);
pfds[EIFD].events = POLLIN;
pfds[PIPEFD].fd = pipe_r_;
pfds[PIPEFD].events = POLLIN;
int timeout = (timeout_in_ms < 0.0) ? -1 : static_cast<int>(1000.0 * timeout_in_ms);
int retval = poll(pfds, POLLFD_COUNT, timeout);
if (retval > 0) {
if (pfds[EIFD].revents & POLLIN) {
std::lock_guard<std::mutex> lock(mutex_);
// libei doesn't allow ei_event_ref() because events are
// supposed to be short-lived only. So instead, we create an NULL-data
// kSystemEvent whenever there's data on the fd, shove that event
// into our event queue and once we process the event (see
// getEvent()), the EiScreen will call ei_dispatch() and process
// all actual pending ei events. In theory this means that a
// flood of ei events could starve the events added with
// addEvents() but let's hope it doesn't come to that.
queue_.push({true, 0U});
}
// the pipefd data doesn't matter, it only exists to wake up the thread
// and potentially testCancel
if (pfds[PIPEFD].revents & POLLIN) {
char buf[64];
auto result = read(pipe_r_, buf, sizeof(buf)); // discard
LOG_DEBUG2("event queue read result: %d", result);
}
}
Thread::testCancel();
}
IEventQueueBuffer::Type EiEventQueueBuffer::getEvent(Event &event, uint32_t &dataID)
{
// the addEvent/getEvent pair is a bit awkward for libei.
//
// it assumes that there's a nice queue of events sitting there that we can
// just append to and get everything back out in the same order. We *could*
// emulate that by taking the libei events immediately out of the event
// queue after dispatch (see above) and putting it into the event queue,
// intermixed with whatever addEvents() did.
//
// But this makes locking more awkward and libei isn't really designed to
// keep calling ei_dispatch() while we hold a bunch of event refs. So instead
// we just have a "something happened" event on the ei fd and the rest is
// handled by the EiScreen.
//
std::lock_guard<std::mutex> lock(mutex_);
auto pair = queue_.front();
queue_.pop();
// if this an injected special event, just return the data and exit
if (pair.first == false) {
dataID = pair.second;
return kUser;
}
event = Event(Event::kSystem, events_->getSystemTarget());
return kSystem;
}
bool EiEventQueueBuffer::addEvent(uint32_t dataID)
{
std::lock_guard<std::mutex> lock(mutex_);
queue_.push({false, dataID});
// tickle the pipe so our read thread wakes up
auto result = write(pipe_w_, "!", 1);
LOG_DEBUG2("event queue write result: %d", result);
return true;
}
bool EiEventQueueBuffer::isEmpty() const
{
std::lock_guard<std::mutex> lock(mutex_);
return queue_.empty();
}
EventQueueTimer *EiEventQueueBuffer::newTimer(double duration, bool oneShot) const
{
return new EventQueueTimer;
}
void EiEventQueueBuffer::deleteTimer(EventQueueTimer *timer) const
{
delete timer;
}
} // namespace deskflow
| 4,669
|
C++
|
.cpp
| 135
| 31.57037
| 120
| 0.711402
|
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,563
|
MSWindowsScreenSaver.cpp
|
deskflow_deskflow/src/lib/platform/MSWindowsScreenSaver.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 "platform/MSWindowsScreenSaver.h"
#include "arch/Arch.h"
#include "arch/win32/ArchMiscWindows.h"
#include "base/Log.h"
#include "base/TMethodJob.h"
#include "mt/Thread.h"
#include "platform/MSWindowsScreen.h"
#include <malloc.h>
#include <tchar.h>
#if !defined(SPI_GETSCREENSAVERRUNNING)
#define SPI_GETSCREENSAVERRUNNING 114
#endif
static const TCHAR *g_isSecureNT = "ScreenSaverIsSecure";
static const TCHAR *g_isSecure9x = "ScreenSaveUsePassword";
static const TCHAR *const g_pathScreenSaverIsSecure[] = {"Control Panel", "Desktop", NULL};
//
// MSWindowsScreenSaver
//
MSWindowsScreenSaver::MSWindowsScreenSaver()
: m_wasSecure(false),
m_wasSecureAnInt(false),
m_process(NULL),
m_watch(NULL),
m_threadID(0),
m_msg(0),
m_wParam(0),
m_lParam(0),
m_active(false)
{
// check if screen saver is enabled
SystemParametersInfo(SPI_GETSCREENSAVEACTIVE, 0, &m_wasEnabled, 0);
}
MSWindowsScreenSaver::~MSWindowsScreenSaver()
{
unwatchProcess();
}
bool MSWindowsScreenSaver::checkStarted(UINT msg, WPARAM wParam, LPARAM lParam)
{
// if already started then say it didn't just start
if (m_active) {
return false;
}
// screen saver may have started. look for it and get
// the process. if we can't find it then assume it
// didn't really start. we wait a moment before
// looking to give the screen saver a chance to start.
// this shouldn't be a problem since we only get here
// if the screen saver wants to kick in, meaning that
// the system is idle or the user deliberately started
// the screen saver.
Sleep(250);
// set parameters common to all screen saver handling
m_threadID = GetCurrentThreadId();
m_msg = msg;
m_wParam = wParam;
m_lParam = lParam;
// on the windows nt family we wait for the desktop to
// change until it's neither the Screen-Saver desktop
// nor a desktop we can't open (the login desktop).
// since windows will send the request-to-start-screen-
// saver message even when the screen saver is disabled
// we first check that the screen saver is indeed active
// before watching for it to stop.
if (!isActive()) {
LOG((CLOG_DEBUG2 "can't open screen saver desktop"));
return false;
}
watchDesktop();
return true;
}
void MSWindowsScreenSaver::enable()
{
SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, m_wasEnabled, 0, 0);
// restore password protection
if (m_wasSecure) {
setSecure(true, m_wasSecureAnInt);
}
}
void MSWindowsScreenSaver::disable()
{
SystemParametersInfo(SPI_GETSCREENSAVEACTIVE, 0, &m_wasEnabled, 0);
SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, FALSE, 0, 0);
// disable password protected screensaver
m_wasSecure = isSecure(&m_wasSecureAnInt);
if (m_wasSecure) {
setSecure(false, m_wasSecureAnInt);
}
}
void MSWindowsScreenSaver::activate()
{
// don't activate if already active
if (!isActive()) {
// activate
HWND hwnd = GetForegroundWindow();
if (hwnd != NULL) {
PostMessage(hwnd, WM_SYSCOMMAND, SC_SCREENSAVE, 0);
} else {
// no foreground window. pretend we got the event instead.
DefWindowProc(NULL, WM_SYSCOMMAND, SC_SCREENSAVE, 0);
}
}
}
void MSWindowsScreenSaver::deactivate()
{
bool killed = false;
// NT runs screen saver in another desktop
HDESK desktop = OpenDesktop("Screen-saver", 0, FALSE, DESKTOP_READOBJECTS | DESKTOP_WRITEOBJECTS);
if (desktop != NULL) {
EnumDesktopWindows(desktop, &MSWindowsScreenSaver::killScreenSaverFunc, reinterpret_cast<LPARAM>(&killed));
CloseDesktop(desktop);
}
// if above failed or wasn't tried, try the windows 95 way
if (!killed) {
// find screen saver window and close it
HWND hwnd = FindWindow("WindowsScreenSaverClass", NULL);
if (hwnd == NULL) {
// win2k may use a different class
hwnd = FindWindow("Default Screen Saver", NULL);
}
if (hwnd != NULL) {
PostMessage(hwnd, WM_CLOSE, 0, 0);
}
}
// force timer to restart
SystemParametersInfo(SPI_GETSCREENSAVEACTIVE, 0, &m_wasEnabled, 0);
SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, !m_wasEnabled, 0, SPIF_SENDWININICHANGE);
SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, m_wasEnabled, 0, SPIF_SENDWININICHANGE);
}
bool MSWindowsScreenSaver::isActive() const
{
BOOL running;
SystemParametersInfo(SPI_GETSCREENSAVERRUNNING, 0, &running, 0);
return (running != FALSE);
}
BOOL CALLBACK MSWindowsScreenSaver::killScreenSaverFunc(HWND hwnd, LPARAM arg)
{
if (IsWindowVisible(hwnd)) {
HINSTANCE instance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);
if (instance != MSWindowsScreen::getWindowInstance()) {
PostMessage(hwnd, WM_CLOSE, 0, 0);
*reinterpret_cast<bool *>(arg) = true;
}
}
return TRUE;
}
void MSWindowsScreenSaver::watchDesktop()
{
// stop watching previous process/desktop
unwatchProcess();
// watch desktop in another thread
LOG((CLOG_DEBUG "watching screen saver desktop"));
m_active = true;
m_watch = new Thread(new TMethodJob<MSWindowsScreenSaver>(this, &MSWindowsScreenSaver::watchDesktopThread));
}
void MSWindowsScreenSaver::watchProcess(HANDLE process)
{
// stop watching previous process/desktop
unwatchProcess();
// watch new process in another thread
if (process != NULL) {
LOG((CLOG_DEBUG "watching screen saver process"));
m_process = process;
m_active = true;
m_watch = new Thread(new TMethodJob<MSWindowsScreenSaver>(this, &MSWindowsScreenSaver::watchProcessThread));
}
}
void MSWindowsScreenSaver::unwatchProcess()
{
if (m_watch != NULL) {
LOG((CLOG_DEBUG "stopped watching screen saver process/desktop"));
m_watch->cancel();
m_watch->wait();
delete m_watch;
m_watch = NULL;
m_active = false;
}
if (m_process != NULL) {
CloseHandle(m_process);
m_process = NULL;
}
}
void MSWindowsScreenSaver::watchDesktopThread(void *)
{
DWORD reserved = 0;
TCHAR *name = NULL;
for (;;) {
// wait a bit
ARCH->sleep(0.2);
BOOL running;
SystemParametersInfo(SPI_GETSCREENSAVERRUNNING, 0, &running, 0);
if (running) {
continue;
}
// send screen saver deactivation message
m_active = false;
PostThreadMessage(m_threadID, m_msg, m_wParam, m_lParam);
return;
}
}
void MSWindowsScreenSaver::watchProcessThread(void *)
{
for (;;) {
Thread::testCancel();
if (WaitForSingleObject(m_process, 50) == WAIT_OBJECT_0) {
// process terminated
LOG((CLOG_DEBUG "screen saver died"));
// send screen saver deactivation message
m_active = false;
PostThreadMessage(m_threadID, m_msg, m_wParam, m_lParam);
return;
}
}
}
void MSWindowsScreenSaver::setSecure(bool secure, bool saveSecureAsInt)
{
HKEY hkey = ArchMiscWindows::addKey(HKEY_CURRENT_USER, g_pathScreenSaverIsSecure);
if (hkey == NULL) {
return;
}
if (saveSecureAsInt) {
ArchMiscWindows::setValue(hkey, g_isSecureNT, secure ? 1 : 0);
} else {
ArchMiscWindows::setValue(hkey, g_isSecureNT, secure ? "1" : "0");
}
ArchMiscWindows::closeKey(hkey);
}
bool MSWindowsScreenSaver::isSecure(bool *wasSecureFlagAnInt) const
{
// get the password protection setting key
HKEY hkey = ArchMiscWindows::openKey(HKEY_CURRENT_USER, g_pathScreenSaverIsSecure);
if (hkey == NULL) {
return false;
}
// get the value. the value may be an int or a string, depending
// on the version of windows.
bool result;
switch (ArchMiscWindows::typeOfValue(hkey, g_isSecureNT)) {
default:
result = false;
break;
case ArchMiscWindows::kUINT: {
DWORD value = ArchMiscWindows::readValueInt(hkey, g_isSecureNT);
*wasSecureFlagAnInt = true;
result = (value != 0);
break;
}
case ArchMiscWindows::kSTRING: {
std::string value = ArchMiscWindows::readValueString(hkey, g_isSecureNT);
*wasSecureFlagAnInt = false;
result = (value != "0");
break;
}
}
ArchMiscWindows::closeKey(hkey);
return result;
}
| 8,725
|
C++
|
.cpp
| 273
| 28.567766
| 112
| 0.720181
|
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,564
|
OSXClipboardAnyBitmapConverter.cpp
|
deskflow_deskflow/src/lib/platform/OSXClipboardAnyBitmapConverter.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2014-2016 Symless Ltd.
* Patch by Ryan Chapman
*
* 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/OSXClipboardAnyBitmapConverter.h"
#include <algorithm>
OSXClipboardAnyBitmapConverter::OSXClipboardAnyBitmapConverter()
{
// do nothing
}
OSXClipboardAnyBitmapConverter::~OSXClipboardAnyBitmapConverter()
{
// do nothing
}
IClipboard::EFormat OSXClipboardAnyBitmapConverter::getFormat() const
{
return IClipboard::kBitmap;
}
String OSXClipboardAnyBitmapConverter::fromIClipboard(const String &data) const
{
return doFromIClipboard(data);
}
String OSXClipboardAnyBitmapConverter::toIClipboard(const String &data) const
{
return doToIClipboard(data);
}
| 1,301
|
C++
|
.cpp
| 39
| 31.538462
| 79
| 0.798567
|
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,565
|
MSWindowsClipboardUTF16Converter.cpp
|
deskflow_deskflow/src/lib/platform/MSWindowsClipboardUTF16Converter.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 "platform/MSWindowsClipboardUTF16Converter.h"
#include "base/Unicode.h"
//
// MSWindowsClipboardUTF16Converter
//
MSWindowsClipboardUTF16Converter::MSWindowsClipboardUTF16Converter()
{
// do nothing
}
MSWindowsClipboardUTF16Converter::~MSWindowsClipboardUTF16Converter()
{
// do nothing
}
UINT MSWindowsClipboardUTF16Converter::getWin32Format() const
{
return CF_UNICODETEXT;
}
String MSWindowsClipboardUTF16Converter::doFromIClipboard(const String &data) const
{
// convert and add nul terminator
return Unicode::UTF8ToUTF16(data).append(sizeof(wchar_t), 0);
}
String MSWindowsClipboardUTF16Converter::doToIClipboard(const String &data) const
{
// convert and strip nul terminator
String dst = Unicode::UTF16ToUTF8(data);
String::size_type n = dst.find('\0');
if (n != String::npos) {
dst.erase(n);
}
return dst;
}
| 1,589
|
C++
|
.cpp
| 49
| 30.408163
| 83
| 0.778721
|
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,566
|
XWindowsUtil.cpp
|
deskflow_deskflow/src/lib/platform/XWindowsUtil.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 "platform/XWindowsUtil.h"
#include "base/Log.h"
#include "base/String.h"
#include "deskflow/key_types.h"
#include "mt/Thread.h"
#include <X11/Xatom.h>
#define XK_APL
#define XK_ARABIC
#define XK_ARMENIAN
#define XK_CAUCASUS
#define XK_CURRENCY
#define XK_CYRILLIC
#define XK_GEORGIAN
#define XK_GREEK
#define XK_HEBREW
#define XK_KATAKANA
#define XK_KOREAN
#define XK_LATIN1
#define XK_LATIN2
#define XK_LATIN3
#define XK_LATIN4
#define XK_LATIN8
#define XK_LATIN9
#define XK_MISCELLANY
#define XK_PUBLISHING
#define XK_SPECIAL
#define XK_TECHNICAL
#define XK_THAI
#define XK_VIETNAMESE
#define XK_XKB_KEYS
#include <X11/keysym.h>
#if !defined(XK_OE)
#define XK_OE 0x13bc
#endif
#if !defined(XK_oe)
#define XK_oe 0x13bd
#endif
#if !defined(XK_Ydiaeresis)
#define XK_Ydiaeresis 0x13be
#endif
/*
* This table maps keysym values into the corresponding ISO 10646
* (UCS, Unicode) values.
*
* The array keysymtab[] contains pairs of X11 keysym values for graphical
* characters and the corresponding Unicode value.
*
* Author: Markus G. Kuhn <http://www.cl.cam.ac.uk/~mgk25/>,
* University of Cambridge, April 2001
*
* Special thanks to Richard Verhoeven <river@win.tue.nl> for preparing
* an initial draft of the mapping table.
*
* This software is in the public domain. Share and enjoy!
*/
struct codepair
{
KeySym keysym;
UInt32 ucs4;
} s_keymap[] = {
{XK_Aogonek, 0x0104}, /* LATIN CAPITAL LETTER A WITH OGONEK */
{XK_breve, 0x02d8}, /* BREVE */
{XK_Lstroke, 0x0141}, /* LATIN CAPITAL LETTER L WITH STROKE */
{XK_Lcaron, 0x013d}, /* LATIN CAPITAL LETTER L WITH CARON */
{XK_Sacute, 0x015a}, /* LATIN CAPITAL LETTER S WITH ACUTE */
{XK_Scaron, 0x0160}, /* LATIN CAPITAL LETTER S WITH CARON */
{XK_Scedilla, 0x015e}, /* LATIN CAPITAL LETTER S WITH CEDILLA */
{XK_Tcaron, 0x0164}, /* LATIN CAPITAL LETTER T WITH CARON */
{XK_Zacute, 0x0179}, /* LATIN CAPITAL LETTER Z WITH ACUTE */
{XK_Zcaron, 0x017d}, /* LATIN CAPITAL LETTER Z WITH CARON */
{XK_Zabovedot, 0x017b}, /* LATIN CAPITAL LETTER Z WITH DOT ABOVE */
{XK_aogonek, 0x0105}, /* LATIN SMALL LETTER A WITH OGONEK */
{XK_ogonek, 0x02db}, /* OGONEK */
{XK_lstroke, 0x0142}, /* LATIN SMALL LETTER L WITH STROKE */
{XK_lcaron, 0x013e}, /* LATIN SMALL LETTER L WITH CARON */
{XK_sacute, 0x015b}, /* LATIN SMALL LETTER S WITH ACUTE */
{XK_caron, 0x02c7}, /* CARON */
{XK_scaron, 0x0161}, /* LATIN SMALL LETTER S WITH CARON */
{XK_scedilla, 0x015f}, /* LATIN SMALL LETTER S WITH CEDILLA */
{XK_tcaron, 0x0165}, /* LATIN SMALL LETTER T WITH CARON */
{XK_zacute, 0x017a}, /* LATIN SMALL LETTER Z WITH ACUTE */
{XK_doubleacute, 0x02dd}, /* DOUBLE ACUTE ACCENT */
{XK_zcaron, 0x017e}, /* LATIN SMALL LETTER Z WITH CARON */
{XK_zabovedot, 0x017c}, /* LATIN SMALL LETTER Z WITH DOT ABOVE */
{XK_Racute, 0x0154}, /* LATIN CAPITAL LETTER R WITH ACUTE */
{XK_Abreve, 0x0102}, /* LATIN CAPITAL LETTER A WITH BREVE */
{XK_Lacute, 0x0139}, /* LATIN CAPITAL LETTER L WITH ACUTE */
{XK_Cacute, 0x0106}, /* LATIN CAPITAL LETTER C WITH ACUTE */
{XK_Ccaron, 0x010c}, /* LATIN CAPITAL LETTER C WITH CARON */
{XK_Eogonek, 0x0118}, /* LATIN CAPITAL LETTER E WITH OGONEK */
{XK_Ecaron, 0x011a}, /* LATIN CAPITAL LETTER E WITH CARON */
{XK_Dcaron, 0x010e}, /* LATIN CAPITAL LETTER D WITH CARON */
{XK_Dstroke, 0x0110}, /* LATIN CAPITAL LETTER D WITH STROKE */
{XK_Nacute, 0x0143}, /* LATIN CAPITAL LETTER N WITH ACUTE */
{XK_Ncaron, 0x0147}, /* LATIN CAPITAL LETTER N WITH CARON */
{XK_Odoubleacute, 0x0150}, /* LATIN CAPITAL LETTER O WITH DOUBLE ACUTE */
{XK_Rcaron, 0x0158}, /* LATIN CAPITAL LETTER R WITH CARON */
{XK_Uring, 0x016e}, /* LATIN CAPITAL LETTER U WITH RING ABOVE */
{XK_Udoubleacute, 0x0170}, /* LATIN CAPITAL LETTER U WITH DOUBLE ACUTE */
{XK_Tcedilla, 0x0162}, /* LATIN CAPITAL LETTER T WITH CEDILLA */
{XK_racute, 0x0155}, /* LATIN SMALL LETTER R WITH ACUTE */
{XK_abreve, 0x0103}, /* LATIN SMALL LETTER A WITH BREVE */
{XK_lacute, 0x013a}, /* LATIN SMALL LETTER L WITH ACUTE */
{XK_cacute, 0x0107}, /* LATIN SMALL LETTER C WITH ACUTE */
{XK_ccaron, 0x010d}, /* LATIN SMALL LETTER C WITH CARON */
{XK_eogonek, 0x0119}, /* LATIN SMALL LETTER E WITH OGONEK */
{XK_ecaron, 0x011b}, /* LATIN SMALL LETTER E WITH CARON */
{XK_dcaron, 0x010f}, /* LATIN SMALL LETTER D WITH CARON */
{XK_dstroke, 0x0111}, /* LATIN SMALL LETTER D WITH STROKE */
{XK_nacute, 0x0144}, /* LATIN SMALL LETTER N WITH ACUTE */
{XK_ncaron, 0x0148}, /* LATIN SMALL LETTER N WITH CARON */
{XK_odoubleacute, 0x0151}, /* LATIN SMALL LETTER O WITH DOUBLE ACUTE */
{XK_rcaron, 0x0159}, /* LATIN SMALL LETTER R WITH CARON */
{XK_uring, 0x016f}, /* LATIN SMALL LETTER U WITH RING ABOVE */
{XK_udoubleacute, 0x0171}, /* LATIN SMALL LETTER U WITH DOUBLE ACUTE */
{XK_tcedilla, 0x0163}, /* LATIN SMALL LETTER T WITH CEDILLA */
{XK_abovedot, 0x02d9}, /* DOT ABOVE */
{XK_Hstroke, 0x0126}, /* LATIN CAPITAL LETTER H WITH STROKE */
{XK_Hcircumflex, 0x0124}, /* LATIN CAPITAL LETTER H WITH CIRCUMFLEX */
{XK_Iabovedot, 0x0130}, /* LATIN CAPITAL LETTER I WITH DOT ABOVE */
{XK_Gbreve, 0x011e}, /* LATIN CAPITAL LETTER G WITH BREVE */
{XK_Jcircumflex, 0x0134}, /* LATIN CAPITAL LETTER J WITH CIRCUMFLEX */
{XK_hstroke, 0x0127}, /* LATIN SMALL LETTER H WITH STROKE */
{XK_hcircumflex, 0x0125}, /* LATIN SMALL LETTER H WITH CIRCUMFLEX */
{XK_idotless, 0x0131}, /* LATIN SMALL LETTER DOTLESS I */
{XK_gbreve, 0x011f}, /* LATIN SMALL LETTER G WITH BREVE */
{XK_jcircumflex, 0x0135}, /* LATIN SMALL LETTER J WITH CIRCUMFLEX */
{XK_Cabovedot, 0x010a}, /* LATIN CAPITAL LETTER C WITH DOT ABOVE */
{XK_Ccircumflex, 0x0108}, /* LATIN CAPITAL LETTER C WITH CIRCUMFLEX */
{XK_Gabovedot, 0x0120}, /* LATIN CAPITAL LETTER G WITH DOT ABOVE */
{XK_Gcircumflex, 0x011c}, /* LATIN CAPITAL LETTER G WITH CIRCUMFLEX */
{XK_Ubreve, 0x016c}, /* LATIN CAPITAL LETTER U WITH BREVE */
{XK_Scircumflex, 0x015c}, /* LATIN CAPITAL LETTER S WITH CIRCUMFLEX */
{XK_cabovedot, 0x010b}, /* LATIN SMALL LETTER C WITH DOT ABOVE */
{XK_ccircumflex, 0x0109}, /* LATIN SMALL LETTER C WITH CIRCUMFLEX */
{XK_gabovedot, 0x0121}, /* LATIN SMALL LETTER G WITH DOT ABOVE */
{XK_gcircumflex, 0x011d}, /* LATIN SMALL LETTER G WITH CIRCUMFLEX */
{XK_ubreve, 0x016d}, /* LATIN SMALL LETTER U WITH BREVE */
{XK_scircumflex, 0x015d}, /* LATIN SMALL LETTER S WITH CIRCUMFLEX */
{XK_kra, 0x0138}, /* LATIN SMALL LETTER KRA */
{XK_Rcedilla, 0x0156}, /* LATIN CAPITAL LETTER R WITH CEDILLA */
{XK_Itilde, 0x0128}, /* LATIN CAPITAL LETTER I WITH TILDE */
{XK_Lcedilla, 0x013b}, /* LATIN CAPITAL LETTER L WITH CEDILLA */
{XK_Emacron, 0x0112}, /* LATIN CAPITAL LETTER E WITH MACRON */
{XK_Gcedilla, 0x0122}, /* LATIN CAPITAL LETTER G WITH CEDILLA */
{XK_Tslash, 0x0166}, /* LATIN CAPITAL LETTER T WITH STROKE */
{XK_rcedilla, 0x0157}, /* LATIN SMALL LETTER R WITH CEDILLA */
{XK_itilde, 0x0129}, /* LATIN SMALL LETTER I WITH TILDE */
{XK_lcedilla, 0x013c}, /* LATIN SMALL LETTER L WITH CEDILLA */
{XK_emacron, 0x0113}, /* LATIN SMALL LETTER E WITH MACRON */
{XK_gcedilla, 0x0123}, /* LATIN SMALL LETTER G WITH CEDILLA */
{XK_tslash, 0x0167}, /* LATIN SMALL LETTER T WITH STROKE */
{XK_ENG, 0x014a}, /* LATIN CAPITAL LETTER ENG */
{XK_eng, 0x014b}, /* LATIN SMALL LETTER ENG */
{XK_Amacron, 0x0100}, /* LATIN CAPITAL LETTER A WITH MACRON */
{XK_Iogonek, 0x012e}, /* LATIN CAPITAL LETTER I WITH OGONEK */
{XK_Eabovedot, 0x0116}, /* LATIN CAPITAL LETTER E WITH DOT ABOVE */
{XK_Imacron, 0x012a}, /* LATIN CAPITAL LETTER I WITH MACRON */
{XK_Ncedilla, 0x0145}, /* LATIN CAPITAL LETTER N WITH CEDILLA */
{XK_Omacron, 0x014c}, /* LATIN CAPITAL LETTER O WITH MACRON */
{XK_Kcedilla, 0x0136}, /* LATIN CAPITAL LETTER K WITH CEDILLA */
{XK_Uogonek, 0x0172}, /* LATIN CAPITAL LETTER U WITH OGONEK */
{XK_Utilde, 0x0168}, /* LATIN CAPITAL LETTER U WITH TILDE */
{XK_Umacron, 0x016a}, /* LATIN CAPITAL LETTER U WITH MACRON */
{XK_amacron, 0x0101}, /* LATIN SMALL LETTER A WITH MACRON */
{XK_iogonek, 0x012f}, /* LATIN SMALL LETTER I WITH OGONEK */
{XK_eabovedot, 0x0117}, /* LATIN SMALL LETTER E WITH DOT ABOVE */
{XK_imacron, 0x012b}, /* LATIN SMALL LETTER I WITH MACRON */
{XK_ncedilla, 0x0146}, /* LATIN SMALL LETTER N WITH CEDILLA */
{XK_omacron, 0x014d}, /* LATIN SMALL LETTER O WITH MACRON */
{XK_kcedilla, 0x0137}, /* LATIN SMALL LETTER K WITH CEDILLA */
{XK_uogonek, 0x0173}, /* LATIN SMALL LETTER U WITH OGONEK */
{XK_utilde, 0x0169}, /* LATIN SMALL LETTER U WITH TILDE */
{XK_umacron, 0x016b}, /* LATIN SMALL LETTER U WITH MACRON */
#if defined(XK_Babovedot)
{XK_Babovedot, 0x1e02}, /* LATIN CAPITAL LETTER B WITH DOT ABOVE */
{XK_babovedot, 0x1e03}, /* LATIN SMALL LETTER B WITH DOT ABOVE */
{XK_Dabovedot, 0x1e0a}, /* LATIN CAPITAL LETTER D WITH DOT ABOVE */
{XK_Wgrave, 0x1e80}, /* LATIN CAPITAL LETTER W WITH GRAVE */
{XK_Wacute, 0x1e82}, /* LATIN CAPITAL LETTER W WITH ACUTE */
{XK_dabovedot, 0x1e0b}, /* LATIN SMALL LETTER D WITH DOT ABOVE */
{XK_Ygrave, 0x1ef2}, /* LATIN CAPITAL LETTER Y WITH GRAVE */
{XK_Fabovedot, 0x1e1e}, /* LATIN CAPITAL LETTER F WITH DOT ABOVE */
{XK_fabovedot, 0x1e1f}, /* LATIN SMALL LETTER F WITH DOT ABOVE */
{XK_Mabovedot, 0x1e40}, /* LATIN CAPITAL LETTER M WITH DOT ABOVE */
{XK_mabovedot, 0x1e41}, /* LATIN SMALL LETTER M WITH DOT ABOVE */
{XK_Pabovedot, 0x1e56}, /* LATIN CAPITAL LETTER P WITH DOT ABOVE */
{XK_wgrave, 0x1e81}, /* LATIN SMALL LETTER W WITH GRAVE */
{XK_pabovedot, 0x1e57}, /* LATIN SMALL LETTER P WITH DOT ABOVE */
{XK_wacute, 0x1e83}, /* LATIN SMALL LETTER W WITH ACUTE */
{XK_Sabovedot, 0x1e60}, /* LATIN CAPITAL LETTER S WITH DOT ABOVE */
{XK_ygrave, 0x1ef3}, /* LATIN SMALL LETTER Y WITH GRAVE */
{XK_Wdiaeresis, 0x1e84}, /* LATIN CAPITAL LETTER W WITH DIAERESIS */
{XK_wdiaeresis, 0x1e85}, /* LATIN SMALL LETTER W WITH DIAERESIS */
{XK_sabovedot, 0x1e61}, /* LATIN SMALL LETTER S WITH DOT ABOVE */
{XK_Wcircumflex, 0x0174}, /* LATIN CAPITAL LETTER W WITH CIRCUMFLEX */
{XK_Tabovedot, 0x1e6a}, /* LATIN CAPITAL LETTER T WITH DOT ABOVE */
{XK_Ycircumflex, 0x0176}, /* LATIN CAPITAL LETTER Y WITH CIRCUMFLEX */
{XK_wcircumflex, 0x0175}, /* LATIN SMALL LETTER W WITH CIRCUMFLEX */
{XK_tabovedot, 0x1e6b}, /* LATIN SMALL LETTER T WITH DOT ABOVE */
{XK_ycircumflex, 0x0177}, /* LATIN SMALL LETTER Y WITH CIRCUMFLEX */
#endif // defined(XK_Babovedot)
#if defined(XK_overline)
{XK_overline, 0x203e}, /* OVERLINE */
{XK_kana_fullstop, 0x3002}, /* IDEOGRAPHIC FULL STOP */
{XK_kana_openingbracket, 0x300c}, /* LEFT CORNER BRACKET */
{XK_kana_closingbracket, 0x300d}, /* RIGHT CORNER BRACKET */
{XK_kana_comma, 0x3001}, /* IDEOGRAPHIC COMMA */
{XK_kana_conjunctive, 0x30fb}, /* KATAKANA MIDDLE DOT */
{XK_kana_WO, 0x30f2}, /* KATAKANA LETTER WO */
{XK_kana_a, 0x30a1}, /* KATAKANA LETTER SMALL A */
{XK_kana_i, 0x30a3}, /* KATAKANA LETTER SMALL I */
{XK_kana_u, 0x30a5}, /* KATAKANA LETTER SMALL U */
{XK_kana_e, 0x30a7}, /* KATAKANA LETTER SMALL E */
{XK_kana_o, 0x30a9}, /* KATAKANA LETTER SMALL O */
{XK_kana_ya, 0x30e3}, /* KATAKANA LETTER SMALL YA */
{XK_kana_yu, 0x30e5}, /* KATAKANA LETTER SMALL YU */
{XK_kana_yo, 0x30e7}, /* KATAKANA LETTER SMALL YO */
{XK_kana_tsu, 0x30c3}, /* KATAKANA LETTER SMALL TU */
{XK_prolongedsound, 0x30fc}, /* KATAKANA-HIRAGANA PROLONGED SOUND MARK */
{XK_kana_A, 0x30a2}, /* KATAKANA LETTER A */
{XK_kana_I, 0x30a4}, /* KATAKANA LETTER I */
{XK_kana_U, 0x30a6}, /* KATAKANA LETTER U */
{XK_kana_E, 0x30a8}, /* KATAKANA LETTER E */
{XK_kana_O, 0x30aa}, /* KATAKANA LETTER O */
{XK_kana_KA, 0x30ab}, /* KATAKANA LETTER KA */
{XK_kana_KI, 0x30ad}, /* KATAKANA LETTER KI */
{XK_kana_KU, 0x30af}, /* KATAKANA LETTER KU */
{XK_kana_KE, 0x30b1}, /* KATAKANA LETTER KE */
{XK_kana_KO, 0x30b3}, /* KATAKANA LETTER KO */
{XK_kana_SA, 0x30b5}, /* KATAKANA LETTER SA */
{XK_kana_SHI, 0x30b7}, /* KATAKANA LETTER SI */
{XK_kana_SU, 0x30b9}, /* KATAKANA LETTER SU */
{XK_kana_SE, 0x30bb}, /* KATAKANA LETTER SE */
{XK_kana_SO, 0x30bd}, /* KATAKANA LETTER SO */
{XK_kana_TA, 0x30bf}, /* KATAKANA LETTER TA */
{XK_kana_CHI, 0x30c1}, /* KATAKANA LETTER TI */
{XK_kana_TSU, 0x30c4}, /* KATAKANA LETTER TU */
{XK_kana_TE, 0x30c6}, /* KATAKANA LETTER TE */
{XK_kana_TO, 0x30c8}, /* KATAKANA LETTER TO */
{XK_kana_NA, 0x30ca}, /* KATAKANA LETTER NA */
{XK_kana_NI, 0x30cb}, /* KATAKANA LETTER NI */
{XK_kana_NU, 0x30cc}, /* KATAKANA LETTER NU */
{XK_kana_NE, 0x30cd}, /* KATAKANA LETTER NE */
{XK_kana_NO, 0x30ce}, /* KATAKANA LETTER NO */
{XK_kana_HA, 0x30cf}, /* KATAKANA LETTER HA */
{XK_kana_HI, 0x30d2}, /* KATAKANA LETTER HI */
{XK_kana_FU, 0x30d5}, /* KATAKANA LETTER HU */
{XK_kana_HE, 0x30d8}, /* KATAKANA LETTER HE */
{XK_kana_HO, 0x30db}, /* KATAKANA LETTER HO */
{XK_kana_MA, 0x30de}, /* KATAKANA LETTER MA */
{XK_kana_MI, 0x30df}, /* KATAKANA LETTER MI */
{XK_kana_MU, 0x30e0}, /* KATAKANA LETTER MU */
{XK_kana_ME, 0x30e1}, /* KATAKANA LETTER ME */
{XK_kana_MO, 0x30e2}, /* KATAKANA LETTER MO */
{XK_kana_YA, 0x30e4}, /* KATAKANA LETTER YA */
{XK_kana_YU, 0x30e6}, /* KATAKANA LETTER YU */
{XK_kana_YO, 0x30e8}, /* KATAKANA LETTER YO */
{XK_kana_RA, 0x30e9}, /* KATAKANA LETTER RA */
{XK_kana_RI, 0x30ea}, /* KATAKANA LETTER RI */
{XK_kana_RU, 0x30eb}, /* KATAKANA LETTER RU */
{XK_kana_RE, 0x30ec}, /* KATAKANA LETTER RE */
{XK_kana_RO, 0x30ed}, /* KATAKANA LETTER RO */
{XK_kana_WA, 0x30ef}, /* KATAKANA LETTER WA */
{XK_kana_N, 0x30f3}, /* KATAKANA LETTER N */
{XK_voicedsound, 0x309b}, /* KATAKANA-HIRAGANA VOICED SOUND MARK */
{XK_semivoicedsound, 0x309c}, /* KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK */
#endif // defined(XK_overline)
#if defined(XK_Farsi_0)
{XK_Farsi_0, 0x06f0}, /* EXTENDED ARABIC-INDIC DIGIT 0 */
{XK_Farsi_1, 0x06f1}, /* EXTENDED ARABIC-INDIC DIGIT 1 */
{XK_Farsi_2, 0x06f2}, /* EXTENDED ARABIC-INDIC DIGIT 2 */
{XK_Farsi_3, 0x06f3}, /* EXTENDED ARABIC-INDIC DIGIT 3 */
{XK_Farsi_4, 0x06f4}, /* EXTENDED ARABIC-INDIC DIGIT 4 */
{XK_Farsi_5, 0x06f5}, /* EXTENDED ARABIC-INDIC DIGIT 5 */
{XK_Farsi_6, 0x06f6}, /* EXTENDED ARABIC-INDIC DIGIT 6 */
{XK_Farsi_7, 0x06f7}, /* EXTENDED ARABIC-INDIC DIGIT 7 */
{XK_Farsi_8, 0x06f8}, /* EXTENDED ARABIC-INDIC DIGIT 8 */
{XK_Farsi_9, 0x06f9}, /* EXTENDED ARABIC-INDIC DIGIT 9 */
{XK_Arabic_percent, 0x066a}, /* ARABIC PERCENT */
{XK_Arabic_superscript_alef, 0x0670}, /* ARABIC LETTER SUPERSCRIPT ALEF */
{XK_Arabic_tteh, 0x0679}, /* ARABIC LETTER TTEH */
{XK_Arabic_peh, 0x067e}, /* ARABIC LETTER PEH */
{XK_Arabic_tcheh, 0x0686}, /* ARABIC LETTER TCHEH */
{XK_Arabic_ddal, 0x0688}, /* ARABIC LETTER DDAL */
{XK_Arabic_rreh, 0x0691}, /* ARABIC LETTER RREH */
{XK_Arabic_comma, 0x060c}, /* ARABIC COMMA */
{XK_Arabic_fullstop, 0x06d4}, /* ARABIC FULLSTOP */
{XK_Arabic_semicolon, 0x061b}, /* ARABIC SEMICOLON */
{XK_Arabic_0, 0x0660}, /* ARABIC 0 */
{XK_Arabic_1, 0x0661}, /* ARABIC 1 */
{XK_Arabic_2, 0x0662}, /* ARABIC 2 */
{XK_Arabic_3, 0x0663}, /* ARABIC 3 */
{XK_Arabic_4, 0x0664}, /* ARABIC 4 */
{XK_Arabic_5, 0x0665}, /* ARABIC 5 */
{XK_Arabic_6, 0x0666}, /* ARABIC 6 */
{XK_Arabic_7, 0x0667}, /* ARABIC 7 */
{XK_Arabic_8, 0x0668}, /* ARABIC 8 */
{XK_Arabic_9, 0x0669}, /* ARABIC 9 */
{XK_Arabic_question_mark, 0x061f}, /* ARABIC QUESTION MARK */
{XK_Arabic_hamza, 0x0621}, /* ARABIC LETTER HAMZA */
{XK_Arabic_maddaonalef, 0x0622}, /* ARABIC LETTER ALEF WITH MADDA ABOVE */
{XK_Arabic_hamzaonalef, 0x0623}, /* ARABIC LETTER ALEF WITH HAMZA ABOVE */
{XK_Arabic_hamzaonwaw, 0x0624}, /* ARABIC LETTER WAW WITH HAMZA ABOVE */
{XK_Arabic_hamzaunderalef, 0x0625}, /* ARABIC LETTER ALEF WITH HAMZA BELOW */
{XK_Arabic_hamzaonyeh, 0x0626}, /* ARABIC LETTER YEH WITH HAMZA ABOVE */
{XK_Arabic_alef, 0x0627}, /* ARABIC LETTER ALEF */
{XK_Arabic_beh, 0x0628}, /* ARABIC LETTER BEH */
{XK_Arabic_tehmarbuta, 0x0629}, /* ARABIC LETTER TEH MARBUTA */
{XK_Arabic_teh, 0x062a}, /* ARABIC LETTER TEH */
{XK_Arabic_theh, 0x062b}, /* ARABIC LETTER THEH */
{XK_Arabic_jeem, 0x062c}, /* ARABIC LETTER JEEM */
{XK_Arabic_hah, 0x062d}, /* ARABIC LETTER HAH */
{XK_Arabic_khah, 0x062e}, /* ARABIC LETTER KHAH */
{XK_Arabic_dal, 0x062f}, /* ARABIC LETTER DAL */
{XK_Arabic_thal, 0x0630}, /* ARABIC LETTER THAL */
{XK_Arabic_ra, 0x0631}, /* ARABIC LETTER REH */
{XK_Arabic_zain, 0x0632}, /* ARABIC LETTER ZAIN */
{XK_Arabic_seen, 0x0633}, /* ARABIC LETTER SEEN */
{XK_Arabic_sheen, 0x0634}, /* ARABIC LETTER SHEEN */
{XK_Arabic_sad, 0x0635}, /* ARABIC LETTER SAD */
{XK_Arabic_dad, 0x0636}, /* ARABIC LETTER DAD */
{XK_Arabic_tah, 0x0637}, /* ARABIC LETTER TAH */
{XK_Arabic_zah, 0x0638}, /* ARABIC LETTER ZAH */
{XK_Arabic_ain, 0x0639}, /* ARABIC LETTER AIN */
{XK_Arabic_ghain, 0x063a}, /* ARABIC LETTER GHAIN */
{XK_Arabic_tatweel, 0x0640}, /* ARABIC TATWEEL */
{XK_Arabic_feh, 0x0641}, /* ARABIC LETTER FEH */
{XK_Arabic_qaf, 0x0642}, /* ARABIC LETTER QAF */
{XK_Arabic_kaf, 0x0643}, /* ARABIC LETTER KAF */
{XK_Arabic_lam, 0x0644}, /* ARABIC LETTER LAM */
{XK_Arabic_meem, 0x0645}, /* ARABIC LETTER MEEM */
{XK_Arabic_noon, 0x0646}, /* ARABIC LETTER NOON */
{XK_Arabic_ha, 0x0647}, /* ARABIC LETTER HEH */
{XK_Arabic_waw, 0x0648}, /* ARABIC LETTER WAW */
{XK_Arabic_alefmaksura, 0x0649}, /* ARABIC LETTER ALEF MAKSURA */
{XK_Arabic_yeh, 0x064a}, /* ARABIC LETTER YEH */
{XK_Arabic_fathatan, 0x064b}, /* ARABIC FATHATAN */
{XK_Arabic_dammatan, 0x064c}, /* ARABIC DAMMATAN */
{XK_Arabic_kasratan, 0x064d}, /* ARABIC KASRATAN */
{XK_Arabic_fatha, 0x064e}, /* ARABIC FATHA */
{XK_Arabic_damma, 0x064f}, /* ARABIC DAMMA */
{XK_Arabic_kasra, 0x0650}, /* ARABIC KASRA */
{XK_Arabic_shadda, 0x0651}, /* ARABIC SHADDA */
{XK_Arabic_sukun, 0x0652}, /* ARABIC SUKUN */
{XK_Arabic_madda_above, 0x0653}, /* ARABIC MADDA ABOVE */
{XK_Arabic_hamza_above, 0x0654}, /* ARABIC HAMZA ABOVE */
{XK_Arabic_hamza_below, 0x0655}, /* ARABIC HAMZA BELOW */
{XK_Arabic_jeh, 0x0698}, /* ARABIC LETTER JEH */
{XK_Arabic_veh, 0x06a4}, /* ARABIC LETTER VEH */
{XK_Arabic_keheh, 0x06a9}, /* ARABIC LETTER KEHEH */
{XK_Arabic_gaf, 0x06af}, /* ARABIC LETTER GAF */
{XK_Arabic_noon_ghunna, 0x06ba}, /* ARABIC LETTER NOON GHUNNA */
{XK_Arabic_heh_doachashmee, 0x06be}, /* ARABIC LETTER HEH DOACHASHMEE */
{XK_Arabic_farsi_yeh, 0x06cc}, /* ARABIC LETTER FARSI YEH */
{XK_Arabic_yeh_baree, 0x06d2}, /* ARABIC LETTER YEH BAREE */
{XK_Arabic_heh_goal, 0x06c1}, /* ARABIC LETTER HEH GOAL */
#endif // defined(XK_Farsi_0)
#if defined(XK_Serbian_dje)
{XK_Serbian_dje, 0x0452}, /* CYRILLIC SMALL LETTER DJE */
{XK_Macedonia_gje, 0x0453}, /* CYRILLIC SMALL LETTER GJE */
{XK_Cyrillic_io, 0x0451}, /* CYRILLIC SMALL LETTER IO */
{XK_Ukrainian_ie, 0x0454}, /* CYRILLIC SMALL LETTER UKRAINIAN IE */
{XK_Macedonia_dse, 0x0455}, /* CYRILLIC SMALL LETTER DZE */
{XK_Ukrainian_i, 0x0456}, /* CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I */
{XK_Ukrainian_yi, 0x0457}, /* CYRILLIC SMALL LETTER YI */
{XK_Cyrillic_je, 0x0458}, /* CYRILLIC SMALL LETTER JE */
{XK_Cyrillic_lje, 0x0459}, /* CYRILLIC SMALL LETTER LJE */
{XK_Cyrillic_nje, 0x045a}, /* CYRILLIC SMALL LETTER NJE */
{XK_Serbian_tshe, 0x045b}, /* CYRILLIC SMALL LETTER TSHE */
{XK_Macedonia_kje, 0x045c}, /* CYRILLIC SMALL LETTER KJE */
#if defined(XK_Ukrainian_ghe_with_upturn)
{XK_Ukrainian_ghe_with_upturn, 0x0491}, /* CYRILLIC SMALL LETTER GHE WITH UPTURN */
#endif
{XK_Byelorussian_shortu, 0x045e}, /* CYRILLIC SMALL LETTER SHORT U */
{XK_Cyrillic_dzhe, 0x045f}, /* CYRILLIC SMALL LETTER DZHE */
{XK_numerosign, 0x2116}, /* NUMERO SIGN */
{XK_Serbian_DJE, 0x0402}, /* CYRILLIC CAPITAL LETTER DJE */
{XK_Macedonia_GJE, 0x0403}, /* CYRILLIC CAPITAL LETTER GJE */
{XK_Cyrillic_IO, 0x0401}, /* CYRILLIC CAPITAL LETTER IO */
{XK_Ukrainian_IE, 0x0404}, /* CYRILLIC CAPITAL LETTER UKRAINIAN IE */
{XK_Macedonia_DSE, 0x0405}, /* CYRILLIC CAPITAL LETTER DZE */
{XK_Ukrainian_I, 0x0406}, /* CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I */
{XK_Ukrainian_YI, 0x0407}, /* CYRILLIC CAPITAL LETTER YI */
{XK_Cyrillic_JE, 0x0408}, /* CYRILLIC CAPITAL LETTER JE */
{XK_Cyrillic_LJE, 0x0409}, /* CYRILLIC CAPITAL LETTER LJE */
{XK_Cyrillic_NJE, 0x040a}, /* CYRILLIC CAPITAL LETTER NJE */
{XK_Serbian_TSHE, 0x040b}, /* CYRILLIC CAPITAL LETTER TSHE */
{XK_Macedonia_KJE, 0x040c}, /* CYRILLIC CAPITAL LETTER KJE */
#if defined(XK_Ukrainian_GHE_WITH_UPTURN)
{XK_Ukrainian_GHE_WITH_UPTURN, 0x0490}, /* CYRILLIC CAPITAL LETTER GHE WITH UPTURN */
#endif
{XK_Byelorussian_SHORTU, 0x040e}, /* CYRILLIC CAPITAL LETTER SHORT U */
{XK_Cyrillic_DZHE, 0x040f}, /* CYRILLIC CAPITAL LETTER DZHE */
{XK_Cyrillic_yu, 0x044e}, /* CYRILLIC SMALL LETTER YU */
{XK_Cyrillic_a, 0x0430}, /* CYRILLIC SMALL LETTER A */
{XK_Cyrillic_be, 0x0431}, /* CYRILLIC SMALL LETTER BE */
{XK_Cyrillic_tse, 0x0446}, /* CYRILLIC SMALL LETTER TSE */
{XK_Cyrillic_de, 0x0434}, /* CYRILLIC SMALL LETTER DE */
{XK_Cyrillic_ie, 0x0435}, /* CYRILLIC SMALL LETTER IE */
{XK_Cyrillic_ef, 0x0444}, /* CYRILLIC SMALL LETTER EF */
{XK_Cyrillic_ghe, 0x0433}, /* CYRILLIC SMALL LETTER GHE */
{XK_Cyrillic_ha, 0x0445}, /* CYRILLIC SMALL LETTER HA */
{XK_Cyrillic_i, 0x0438}, /* CYRILLIC SMALL LETTER I */
{XK_Cyrillic_shorti, 0x0439}, /* CYRILLIC SMALL LETTER SHORT I */
{XK_Cyrillic_ka, 0x043a}, /* CYRILLIC SMALL LETTER KA */
{XK_Cyrillic_el, 0x043b}, /* CYRILLIC SMALL LETTER EL */
{XK_Cyrillic_em, 0x043c}, /* CYRILLIC SMALL LETTER EM */
{XK_Cyrillic_en, 0x043d}, /* CYRILLIC SMALL LETTER EN */
{XK_Cyrillic_o, 0x043e}, /* CYRILLIC SMALL LETTER O */
{XK_Cyrillic_pe, 0x043f}, /* CYRILLIC SMALL LETTER PE */
{XK_Cyrillic_ya, 0x044f}, /* CYRILLIC SMALL LETTER YA */
{XK_Cyrillic_er, 0x0440}, /* CYRILLIC SMALL LETTER ER */
{XK_Cyrillic_es, 0x0441}, /* CYRILLIC SMALL LETTER ES */
{XK_Cyrillic_te, 0x0442}, /* CYRILLIC SMALL LETTER TE */
{XK_Cyrillic_u, 0x0443}, /* CYRILLIC SMALL LETTER U */
{XK_Cyrillic_zhe, 0x0436}, /* CYRILLIC SMALL LETTER ZHE */
{XK_Cyrillic_ve, 0x0432}, /* CYRILLIC SMALL LETTER VE */
{XK_Cyrillic_softsign, 0x044c}, /* CYRILLIC SMALL LETTER SOFT SIGN */
{XK_Cyrillic_yeru, 0x044b}, /* CYRILLIC SMALL LETTER YERU */
{XK_Cyrillic_ze, 0x0437}, /* CYRILLIC SMALL LETTER ZE */
{XK_Cyrillic_sha, 0x0448}, /* CYRILLIC SMALL LETTER SHA */
{XK_Cyrillic_e, 0x044d}, /* CYRILLIC SMALL LETTER E */
{XK_Cyrillic_shcha, 0x0449}, /* CYRILLIC SMALL LETTER SHCHA */
{XK_Cyrillic_che, 0x0447}, /* CYRILLIC SMALL LETTER CHE */
{XK_Cyrillic_hardsign, 0x044a}, /* CYRILLIC SMALL LETTER HARD SIGN */
{XK_Cyrillic_YU, 0x042e}, /* CYRILLIC CAPITAL LETTER YU */
{XK_Cyrillic_A, 0x0410}, /* CYRILLIC CAPITAL LETTER A */
{XK_Cyrillic_BE, 0x0411}, /* CYRILLIC CAPITAL LETTER BE */
{XK_Cyrillic_TSE, 0x0426}, /* CYRILLIC CAPITAL LETTER TSE */
{XK_Cyrillic_DE, 0x0414}, /* CYRILLIC CAPITAL LETTER DE */
{XK_Cyrillic_IE, 0x0415}, /* CYRILLIC CAPITAL LETTER IE */
{XK_Cyrillic_EF, 0x0424}, /* CYRILLIC CAPITAL LETTER EF */
{XK_Cyrillic_GHE, 0x0413}, /* CYRILLIC CAPITAL LETTER GHE */
{XK_Cyrillic_HA, 0x0425}, /* CYRILLIC CAPITAL LETTER HA */
{XK_Cyrillic_I, 0x0418}, /* CYRILLIC CAPITAL LETTER I */
{XK_Cyrillic_SHORTI, 0x0419}, /* CYRILLIC CAPITAL LETTER SHORT I */
{XK_Cyrillic_KA, 0x041a}, /* CYRILLIC CAPITAL LETTER KA */
{XK_Cyrillic_EL, 0x041b}, /* CYRILLIC CAPITAL LETTER EL */
{XK_Cyrillic_EM, 0x041c}, /* CYRILLIC CAPITAL LETTER EM */
{XK_Cyrillic_EN, 0x041d}, /* CYRILLIC CAPITAL LETTER EN */
{XK_Cyrillic_O, 0x041e}, /* CYRILLIC CAPITAL LETTER O */
{XK_Cyrillic_PE, 0x041f}, /* CYRILLIC CAPITAL LETTER PE */
{XK_Cyrillic_YA, 0x042f}, /* CYRILLIC CAPITAL LETTER YA */
{XK_Cyrillic_ER, 0x0420}, /* CYRILLIC CAPITAL LETTER ER */
{XK_Cyrillic_ES, 0x0421}, /* CYRILLIC CAPITAL LETTER ES */
{XK_Cyrillic_TE, 0x0422}, /* CYRILLIC CAPITAL LETTER TE */
{XK_Cyrillic_U, 0x0423}, /* CYRILLIC CAPITAL LETTER U */
{XK_Cyrillic_ZHE, 0x0416}, /* CYRILLIC CAPITAL LETTER ZHE */
{XK_Cyrillic_VE, 0x0412}, /* CYRILLIC CAPITAL LETTER VE */
{XK_Cyrillic_SOFTSIGN, 0x042c}, /* CYRILLIC CAPITAL LETTER SOFT SIGN */
{XK_Cyrillic_YERU, 0x042b}, /* CYRILLIC CAPITAL LETTER YERU */
{XK_Cyrillic_ZE, 0x0417}, /* CYRILLIC CAPITAL LETTER ZE */
{XK_Cyrillic_SHA, 0x0428}, /* CYRILLIC CAPITAL LETTER SHA */
{XK_Cyrillic_E, 0x042d}, /* CYRILLIC CAPITAL LETTER E */
{XK_Cyrillic_SHCHA, 0x0429}, /* CYRILLIC CAPITAL LETTER SHCHA */
{XK_Cyrillic_CHE, 0x0427}, /* CYRILLIC CAPITAL LETTER CHE */
{XK_Cyrillic_HARDSIGN, 0x042a}, /* CYRILLIC CAPITAL LETTER HARD SIGN */
#endif // defined(XK_Serbian_dje)
#if defined(XK_Greek_ALPHAaccent)
{XK_Greek_ALPHAaccent, 0x0386}, /* GREEK CAPITAL LETTER ALPHA WITH TONOS */
{XK_Greek_EPSILONaccent, 0x0388}, /* GREEK CAPITAL LETTER EPSILON WITH TONOS */
{XK_Greek_ETAaccent, 0x0389}, /* GREEK CAPITAL LETTER ETA WITH TONOS */
{XK_Greek_IOTAaccent, 0x038a}, /* GREEK CAPITAL LETTER IOTA WITH TONOS */
{XK_Greek_IOTAdiaeresis, 0x03aa}, /* GREEK CAPITAL LETTER IOTA WITH DIALYTIKA */
{XK_Greek_OMICRONaccent, 0x038c}, /* GREEK CAPITAL LETTER OMICRON WITH TONOS */
{XK_Greek_UPSILONaccent, 0x038e}, /* GREEK CAPITAL LETTER UPSILON WITH TONOS */
{XK_Greek_UPSILONdieresis, 0x03ab}, /* GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA */
{XK_Greek_OMEGAaccent, 0x038f}, /* GREEK CAPITAL LETTER OMEGA WITH TONOS */
{XK_Greek_accentdieresis, 0x0385}, /* GREEK DIALYTIKA TONOS */
{XK_Greek_horizbar, 0x2015}, /* HORIZONTAL BAR */
{XK_Greek_alphaaccent, 0x03ac}, /* GREEK SMALL LETTER ALPHA WITH TONOS */
{XK_Greek_epsilonaccent, 0x03ad}, /* GREEK SMALL LETTER EPSILON WITH TONOS */
{XK_Greek_etaaccent, 0x03ae}, /* GREEK SMALL LETTER ETA WITH TONOS */
{XK_Greek_iotaaccent, 0x03af}, /* GREEK SMALL LETTER IOTA WITH TONOS */
{XK_Greek_iotadieresis, 0x03ca}, /* GREEK SMALL LETTER IOTA WITH DIALYTIKA */
{XK_Greek_iotaaccentdieresis, 0x0390}, /* GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS */
{XK_Greek_omicronaccent, 0x03cc}, /* GREEK SMALL LETTER OMICRON WITH TONOS */
{XK_Greek_upsilonaccent, 0x03cd}, /* GREEK SMALL LETTER UPSILON WITH TONOS */
{XK_Greek_upsilondieresis, 0x03cb}, /* GREEK SMALL LETTER UPSILON WITH DIALYTIKA */
{XK_Greek_upsilonaccentdieresis, 0x03b0}, /* GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS */
{XK_Greek_omegaaccent, 0x03ce}, /* GREEK SMALL LETTER OMEGA WITH TONOS */
{XK_Greek_ALPHA, 0x0391}, /* GREEK CAPITAL LETTER ALPHA */
{XK_Greek_BETA, 0x0392}, /* GREEK CAPITAL LETTER BETA */
{XK_Greek_GAMMA, 0x0393}, /* GREEK CAPITAL LETTER GAMMA */
{XK_Greek_DELTA, 0x0394}, /* GREEK CAPITAL LETTER DELTA */
{XK_Greek_EPSILON, 0x0395}, /* GREEK CAPITAL LETTER EPSILON */
{XK_Greek_ZETA, 0x0396}, /* GREEK CAPITAL LETTER ZETA */
{XK_Greek_ETA, 0x0397}, /* GREEK CAPITAL LETTER ETA */
{XK_Greek_THETA, 0x0398}, /* GREEK CAPITAL LETTER THETA */
{XK_Greek_IOTA, 0x0399}, /* GREEK CAPITAL LETTER IOTA */
{XK_Greek_KAPPA, 0x039a}, /* GREEK CAPITAL LETTER KAPPA */
{XK_Greek_LAMBDA, 0x039b}, /* GREEK CAPITAL LETTER LAMDA */
{XK_Greek_MU, 0x039c}, /* GREEK CAPITAL LETTER MU */
{XK_Greek_NU, 0x039d}, /* GREEK CAPITAL LETTER NU */
{XK_Greek_XI, 0x039e}, /* GREEK CAPITAL LETTER XI */
{XK_Greek_OMICRON, 0x039f}, /* GREEK CAPITAL LETTER OMICRON */
{XK_Greek_PI, 0x03a0}, /* GREEK CAPITAL LETTER PI */
{XK_Greek_RHO, 0x03a1}, /* GREEK CAPITAL LETTER RHO */
{XK_Greek_SIGMA, 0x03a3}, /* GREEK CAPITAL LETTER SIGMA */
{XK_Greek_TAU, 0x03a4}, /* GREEK CAPITAL LETTER TAU */
{XK_Greek_UPSILON, 0x03a5}, /* GREEK CAPITAL LETTER UPSILON */
{XK_Greek_PHI, 0x03a6}, /* GREEK CAPITAL LETTER PHI */
{XK_Greek_CHI, 0x03a7}, /* GREEK CAPITAL LETTER CHI */
{XK_Greek_PSI, 0x03a8}, /* GREEK CAPITAL LETTER PSI */
{XK_Greek_OMEGA, 0x03a9}, /* GREEK CAPITAL LETTER OMEGA */
{XK_Greek_alpha, 0x03b1}, /* GREEK SMALL LETTER ALPHA */
{XK_Greek_beta, 0x03b2}, /* GREEK SMALL LETTER BETA */
{XK_Greek_gamma, 0x03b3}, /* GREEK SMALL LETTER GAMMA */
{XK_Greek_delta, 0x03b4}, /* GREEK SMALL LETTER DELTA */
{XK_Greek_epsilon, 0x03b5}, /* GREEK SMALL LETTER EPSILON */
{XK_Greek_zeta, 0x03b6}, /* GREEK SMALL LETTER ZETA */
{XK_Greek_eta, 0x03b7}, /* GREEK SMALL LETTER ETA */
{XK_Greek_theta, 0x03b8}, /* GREEK SMALL LETTER THETA */
{XK_Greek_iota, 0x03b9}, /* GREEK SMALL LETTER IOTA */
{XK_Greek_kappa, 0x03ba}, /* GREEK SMALL LETTER KAPPA */
{XK_Greek_lambda, 0x03bb}, /* GREEK SMALL LETTER LAMDA */
{XK_Greek_mu, 0x03bc}, /* GREEK SMALL LETTER MU */
{XK_Greek_nu, 0x03bd}, /* GREEK SMALL LETTER NU */
{XK_Greek_xi, 0x03be}, /* GREEK SMALL LETTER XI */
{XK_Greek_omicron, 0x03bf}, /* GREEK SMALL LETTER OMICRON */
{XK_Greek_pi, 0x03c0}, /* GREEK SMALL LETTER PI */
{XK_Greek_rho, 0x03c1}, /* GREEK SMALL LETTER RHO */
{XK_Greek_sigma, 0x03c3}, /* GREEK SMALL LETTER SIGMA */
{XK_Greek_finalsmallsigma, 0x03c2}, /* GREEK SMALL LETTER FINAL SIGMA */
{XK_Greek_tau, 0x03c4}, /* GREEK SMALL LETTER TAU */
{XK_Greek_upsilon, 0x03c5}, /* GREEK SMALL LETTER UPSILON */
{XK_Greek_phi, 0x03c6}, /* GREEK SMALL LETTER PHI */
{XK_Greek_chi, 0x03c7}, /* GREEK SMALL LETTER CHI */
{XK_Greek_psi, 0x03c8}, /* GREEK SMALL LETTER PSI */
{XK_Greek_omega, 0x03c9}, /* GREEK SMALL LETTER OMEGA */
#endif // defined(XK_Greek_ALPHAaccent)
{XK_leftradical, 0x23b7}, /* ??? */
{XK_topleftradical, 0x250c}, /* BOX DRAWINGS LIGHT DOWN AND RIGHT */
{XK_horizconnector, 0x2500}, /* BOX DRAWINGS LIGHT HORIZONTAL */
{XK_topintegral, 0x2320}, /* TOP HALF INTEGRAL */
{XK_botintegral, 0x2321}, /* BOTTOM HALF INTEGRAL */
{XK_vertconnector, 0x2502}, /* BOX DRAWINGS LIGHT VERTICAL */
{XK_topleftsqbracket, 0x23a1}, /* ??? */
{XK_botleftsqbracket, 0x23a3}, /* ??? */
{XK_toprightsqbracket, 0x23a4}, /* ??? */
{XK_botrightsqbracket, 0x23a6}, /* ??? */
{XK_topleftparens, 0x239b}, /* ??? */
{XK_botleftparens, 0x239d}, /* ??? */
{XK_toprightparens, 0x239e}, /* ??? */
{XK_botrightparens, 0x23a0}, /* ??? */
{XK_leftmiddlecurlybrace, 0x23a8}, /* ??? */
{XK_rightmiddlecurlybrace, 0x23ac}, /* ??? */
{XK_lessthanequal, 0x2264}, /* LESS-THAN OR EQUAL TO */
{XK_notequal, 0x2260}, /* NOT EQUAL TO */
{XK_greaterthanequal, 0x2265}, /* GREATER-THAN OR EQUAL TO */
{XK_integral, 0x222b}, /* INTEGRAL */
{XK_therefore, 0x2234}, /* THEREFORE */
{XK_variation, 0x221d}, /* PROPORTIONAL TO */
{XK_infinity, 0x221e}, /* INFINITY */
{XK_nabla, 0x2207}, /* NABLA */
{XK_approximate, 0x223c}, /* TILDE OPERATOR */
{XK_similarequal, 0x2243}, /* ASYMPTOTICALLY EQUAL TO */
{XK_ifonlyif, 0x21d4}, /* LEFT RIGHT DOUBLE ARROW */
{XK_implies, 0x21d2}, /* RIGHTWARDS DOUBLE ARROW */
{XK_identical, 0x2261}, /* IDENTICAL TO */
{XK_radical, 0x221a}, /* SQUARE ROOT */
{XK_includedin, 0x2282}, /* SUBSET OF */
{XK_includes, 0x2283}, /* SUPERSET OF */
{XK_intersection, 0x2229}, /* INTERSECTION */
{XK_union, 0x222a}, /* UNION */
{XK_logicaland, 0x2227}, /* LOGICAL AND */
{XK_logicalor, 0x2228}, /* LOGICAL OR */
{XK_partialderivative, 0x2202}, /* PARTIAL DIFFERENTIAL */
{XK_function, 0x0192}, /* LATIN SMALL LETTER F WITH HOOK */
{XK_leftarrow, 0x2190}, /* LEFTWARDS ARROW */
{XK_uparrow, 0x2191}, /* UPWARDS ARROW */
{XK_rightarrow, 0x2192}, /* RIGHTWARDS ARROW */
{XK_downarrow, 0x2193}, /* DOWNWARDS ARROW */
/*{ XK_blank, ??? }, */
{XK_soliddiamond, 0x25c6}, /* BLACK DIAMOND */
{XK_checkerboard, 0x2592}, /* MEDIUM SHADE */
{XK_ht, 0x2409}, /* SYMBOL FOR HORIZONTAL TABULATION */
{XK_ff, 0x240c}, /* SYMBOL FOR FORM FEED */
{XK_cr, 0x240d}, /* SYMBOL FOR CARRIAGE RETURN */
{XK_lf, 0x240a}, /* SYMBOL FOR LINE FEED */
{XK_nl, 0x2424}, /* SYMBOL FOR NEWLINE */
{XK_vt, 0x240b}, /* SYMBOL FOR VERTICAL TABULATION */
{XK_lowrightcorner, 0x2518}, /* BOX DRAWINGS LIGHT UP AND LEFT */
{XK_uprightcorner, 0x2510}, /* BOX DRAWINGS LIGHT DOWN AND LEFT */
{XK_upleftcorner, 0x250c}, /* BOX DRAWINGS LIGHT DOWN AND RIGHT */
{XK_lowleftcorner, 0x2514}, /* BOX DRAWINGS LIGHT UP AND RIGHT */
{XK_crossinglines, 0x253c}, /* BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL */
{XK_horizlinescan1, 0x23ba}, /* HORIZONTAL SCAN LINE-1 (Unicode 3.2 draft) */
{XK_horizlinescan3, 0x23bb}, /* HORIZONTAL SCAN LINE-3 (Unicode 3.2 draft) */
{XK_horizlinescan5, 0x2500}, /* BOX DRAWINGS LIGHT HORIZONTAL */
{XK_horizlinescan7, 0x23bc}, /* HORIZONTAL SCAN LINE-7 (Unicode 3.2 draft) */
{XK_horizlinescan9, 0x23bd}, /* HORIZONTAL SCAN LINE-9 (Unicode 3.2 draft) */
{XK_leftt, 0x251c}, /* BOX DRAWINGS LIGHT VERTICAL AND RIGHT */
{XK_rightt, 0x2524}, /* BOX DRAWINGS LIGHT VERTICAL AND LEFT */
{XK_bott, 0x2534}, /* BOX DRAWINGS LIGHT UP AND HORIZONTAL */
{XK_topt, 0x252c}, /* BOX DRAWINGS LIGHT DOWN AND HORIZONTAL */
{XK_vertbar, 0x2502}, /* BOX DRAWINGS LIGHT VERTICAL */
{XK_emspace, 0x2003}, /* EM SPACE */
{XK_enspace, 0x2002}, /* EN SPACE */
{XK_em3space, 0x2004}, /* THREE-PER-EM SPACE */
{XK_em4space, 0x2005}, /* FOUR-PER-EM SPACE */
{XK_digitspace, 0x2007}, /* FIGURE SPACE */
{XK_punctspace, 0x2008}, /* PUNCTUATION SPACE */
{XK_thinspace, 0x2009}, /* THIN SPACE */
{XK_hairspace, 0x200a}, /* HAIR SPACE */
{XK_emdash, 0x2014}, /* EM DASH */
{XK_endash, 0x2013}, /* EN DASH */
/*{ XK_signifblank, ??? }, */
{XK_ellipsis, 0x2026}, /* HORIZONTAL ELLIPSIS */
{XK_doubbaselinedot, 0x2025}, /* TWO DOT LEADER */
{XK_onethird, 0x2153}, /* VULGAR FRACTION ONE THIRD */
{XK_twothirds, 0x2154}, /* VULGAR FRACTION TWO THIRDS */
{XK_onefifth, 0x2155}, /* VULGAR FRACTION ONE FIFTH */
{XK_twofifths, 0x2156}, /* VULGAR FRACTION TWO FIFTHS */
{XK_threefifths, 0x2157}, /* VULGAR FRACTION THREE FIFTHS */
{XK_fourfifths, 0x2158}, /* VULGAR FRACTION FOUR FIFTHS */
{XK_onesixth, 0x2159}, /* VULGAR FRACTION ONE SIXTH */
{XK_fivesixths, 0x215a}, /* VULGAR FRACTION FIVE SIXTHS */
{XK_careof, 0x2105}, /* CARE OF */
{XK_figdash, 0x2012}, /* FIGURE DASH */
{XK_leftanglebracket, 0x2329}, /* LEFT-POINTING ANGLE BRACKET */
/*{ XK_decimalpoint, ??? }, */
{XK_rightanglebracket, 0x232a}, /* RIGHT-POINTING ANGLE BRACKET */
/*{ XK_marker, ??? }, */
{XK_oneeighth, 0x215b}, /* VULGAR FRACTION ONE EIGHTH */
{XK_threeeighths, 0x215c}, /* VULGAR FRACTION THREE EIGHTHS */
{XK_fiveeighths, 0x215d}, /* VULGAR FRACTION FIVE EIGHTHS */
{XK_seveneighths, 0x215e}, /* VULGAR FRACTION SEVEN EIGHTHS */
{XK_trademark, 0x2122}, /* TRADE MARK SIGN */
{XK_signaturemark, 0x2613}, /* SALTIRE */
/*{ XK_trademarkincircle, ??? }, */
{XK_leftopentriangle, 0x25c1}, /* WHITE LEFT-POINTING TRIANGLE */
{XK_rightopentriangle, 0x25b7}, /* WHITE RIGHT-POINTING TRIANGLE */
{XK_emopencircle, 0x25cb}, /* WHITE CIRCLE */
{XK_emopenrectangle, 0x25af}, /* WHITE VERTICAL RECTANGLE */
{XK_leftsinglequotemark, 0x2018}, /* LEFT SINGLE QUOTATION MARK */
{XK_rightsinglequotemark, 0x2019}, /* RIGHT SINGLE QUOTATION MARK */
{XK_leftdoublequotemark, 0x201c}, /* LEFT DOUBLE QUOTATION MARK */
{XK_rightdoublequotemark, 0x201d}, /* RIGHT DOUBLE QUOTATION MARK */
{XK_prescription, 0x211e}, /* PRESCRIPTION TAKE */
{XK_minutes, 0x2032}, /* PRIME */
{XK_seconds, 0x2033}, /* DOUBLE PRIME */
{XK_latincross, 0x271d}, /* LATIN CROSS */
/*{ XK_hexagram, ??? }, */
{XK_filledrectbullet, 0x25ac}, /* BLACK RECTANGLE */
{XK_filledlefttribullet, 0x25c0}, /* BLACK LEFT-POINTING TRIANGLE */
{XK_filledrighttribullet, 0x25b6}, /* BLACK RIGHT-POINTING TRIANGLE */
{XK_emfilledcircle, 0x25cf}, /* BLACK CIRCLE */
{XK_emfilledrect, 0x25ae}, /* BLACK VERTICAL RECTANGLE */
{XK_enopencircbullet, 0x25e6}, /* WHITE BULLET */
{XK_enopensquarebullet, 0x25ab}, /* WHITE SMALL SQUARE */
{XK_openrectbullet, 0x25ad}, /* WHITE RECTANGLE */
{XK_opentribulletup, 0x25b3}, /* WHITE UP-POINTING TRIANGLE */
{XK_opentribulletdown, 0x25bd}, /* WHITE DOWN-POINTING TRIANGLE */
{XK_openstar, 0x2606}, /* WHITE STAR */
{XK_enfilledcircbullet, 0x2022}, /* BULLET */
{XK_enfilledsqbullet, 0x25aa}, /* BLACK SMALL SQUARE */
{XK_filledtribulletup, 0x25b2}, /* BLACK UP-POINTING TRIANGLE */
{XK_filledtribulletdown, 0x25bc}, /* BLACK DOWN-POINTING TRIANGLE */
{XK_leftpointer, 0x261c}, /* WHITE LEFT POINTING INDEX */
{XK_rightpointer, 0x261e}, /* WHITE RIGHT POINTING INDEX */
{XK_club, 0x2663}, /* BLACK CLUB SUIT */
{XK_diamond, 0x2666}, /* BLACK DIAMOND SUIT */
{XK_heart, 0x2665}, /* BLACK HEART SUIT */
{XK_maltesecross, 0x2720}, /* MALTESE CROSS */
{XK_dagger, 0x2020}, /* DAGGER */
{XK_doubledagger, 0x2021}, /* DOUBLE DAGGER */
{XK_checkmark, 0x2713}, /* CHECK MARK */
{XK_ballotcross, 0x2717}, /* BALLOT X */
{XK_musicalsharp, 0x266f}, /* MUSIC SHARP SIGN */
{XK_musicalflat, 0x266d}, /* MUSIC FLAT SIGN */
{XK_malesymbol, 0x2642}, /* MALE SIGN */
{XK_femalesymbol, 0x2640}, /* FEMALE SIGN */
{XK_telephone, 0x260e}, /* BLACK TELEPHONE */
{XK_telephonerecorder, 0x2315}, /* TELEPHONE RECORDER */
{XK_phonographcopyright, 0x2117}, /* SOUND RECORDING COPYRIGHT */
{XK_caret, 0x2038}, /* CARET */
{XK_singlelowquotemark, 0x201a}, /* SINGLE LOW-9 QUOTATION MARK */
{XK_doublelowquotemark, 0x201e}, /* DOUBLE LOW-9 QUOTATION MARK */
/*{ XK_cursor, ??? }, */
{XK_leftcaret, 0x003c}, /* LESS-THAN SIGN */
{XK_rightcaret, 0x003e}, /* GREATER-THAN SIGN */
{XK_downcaret, 0x2228}, /* LOGICAL OR */
{XK_upcaret, 0x2227}, /* LOGICAL AND */
{XK_overbar, 0x00af}, /* MACRON */
{XK_downtack, 0x22a5}, /* UP TACK */
{XK_upshoe, 0x2229}, /* INTERSECTION */
{XK_downstile, 0x230a}, /* LEFT FLOOR */
{XK_underbar, 0x005f}, /* LOW LINE */
{XK_jot, 0x2218}, /* RING OPERATOR */
{XK_quad, 0x2395}, /* APL FUNCTIONAL SYMBOL QUAD */
{XK_uptack, 0x22a4}, /* DOWN TACK */
{XK_circle, 0x25cb}, /* WHITE CIRCLE */
{XK_upstile, 0x2308}, /* LEFT CEILING */
{XK_downshoe, 0x222a}, /* UNION */
{XK_rightshoe, 0x2283}, /* SUPERSET OF */
{XK_leftshoe, 0x2282}, /* SUBSET OF */
{XK_lefttack, 0x22a2}, /* RIGHT TACK */
{XK_righttack, 0x22a3}, /* LEFT TACK */
#if defined(XK_hebrew_doublelowline)
{XK_hebrew_doublelowline, 0x2017}, /* DOUBLE LOW LINE */
{XK_hebrew_aleph, 0x05d0}, /* HEBREW LETTER ALEF */
{XK_hebrew_bet, 0x05d1}, /* HEBREW LETTER BET */
{XK_hebrew_gimel, 0x05d2}, /* HEBREW LETTER GIMEL */
{XK_hebrew_dalet, 0x05d3}, /* HEBREW LETTER DALET */
{XK_hebrew_he, 0x05d4}, /* HEBREW LETTER HE */
{XK_hebrew_waw, 0x05d5}, /* HEBREW LETTER VAV */
{XK_hebrew_zain, 0x05d6}, /* HEBREW LETTER ZAYIN */
{XK_hebrew_chet, 0x05d7}, /* HEBREW LETTER HET */
{XK_hebrew_tet, 0x05d8}, /* HEBREW LETTER TET */
{XK_hebrew_yod, 0x05d9}, /* HEBREW LETTER YOD */
{XK_hebrew_finalkaph, 0x05da}, /* HEBREW LETTER FINAL KAF */
{XK_hebrew_kaph, 0x05db}, /* HEBREW LETTER KAF */
{XK_hebrew_lamed, 0x05dc}, /* HEBREW LETTER LAMED */
{XK_hebrew_finalmem, 0x05dd}, /* HEBREW LETTER FINAL MEM */
{XK_hebrew_mem, 0x05de}, /* HEBREW LETTER MEM */
{XK_hebrew_finalnun, 0x05df}, /* HEBREW LETTER FINAL NUN */
{XK_hebrew_nun, 0x05e0}, /* HEBREW LETTER NUN */
{XK_hebrew_samech, 0x05e1}, /* HEBREW LETTER SAMEKH */
{XK_hebrew_ayin, 0x05e2}, /* HEBREW LETTER AYIN */
{XK_hebrew_finalpe, 0x05e3}, /* HEBREW LETTER FINAL PE */
{XK_hebrew_pe, 0x05e4}, /* HEBREW LETTER PE */
{XK_hebrew_finalzade, 0x05e5}, /* HEBREW LETTER FINAL TSADI */
{XK_hebrew_zade, 0x05e6}, /* HEBREW LETTER TSADI */
{XK_hebrew_qoph, 0x05e7}, /* HEBREW LETTER QOF */
{XK_hebrew_resh, 0x05e8}, /* HEBREW LETTER RESH */
{XK_hebrew_shin, 0x05e9}, /* HEBREW LETTER SHIN */
{XK_hebrew_taw, 0x05ea}, /* HEBREW LETTER TAV */
#endif // defined(XK_hebrew_doublelowline)
#if defined(XK_Thai_kokai)
{XK_Thai_kokai, 0x0e01}, /* THAI CHARACTER KO KAI */
{XK_Thai_khokhai, 0x0e02}, /* THAI CHARACTER KHO KHAI */
{XK_Thai_khokhuat, 0x0e03}, /* THAI CHARACTER KHO KHUAT */
{XK_Thai_khokhwai, 0x0e04}, /* THAI CHARACTER KHO KHWAI */
{XK_Thai_khokhon, 0x0e05}, /* THAI CHARACTER KHO KHON */
{XK_Thai_khorakhang, 0x0e06}, /* THAI CHARACTER KHO RAKHANG */
{XK_Thai_ngongu, 0x0e07}, /* THAI CHARACTER NGO NGU */
{XK_Thai_chochan, 0x0e08}, /* THAI CHARACTER CHO CHAN */
{XK_Thai_choching, 0x0e09}, /* THAI CHARACTER CHO CHING */
{XK_Thai_chochang, 0x0e0a}, /* THAI CHARACTER CHO CHANG */
{XK_Thai_soso, 0x0e0b}, /* THAI CHARACTER SO SO */
{XK_Thai_chochoe, 0x0e0c}, /* THAI CHARACTER CHO CHOE */
{XK_Thai_yoying, 0x0e0d}, /* THAI CHARACTER YO YING */
{XK_Thai_dochada, 0x0e0e}, /* THAI CHARACTER DO CHADA */
{XK_Thai_topatak, 0x0e0f}, /* THAI CHARACTER TO PATAK */
{XK_Thai_thothan, 0x0e10}, /* THAI CHARACTER THO THAN */
{XK_Thai_thonangmontho, 0x0e11}, /* THAI CHARACTER THO NANGMONTHO */
{XK_Thai_thophuthao, 0x0e12}, /* THAI CHARACTER THO PHUTHAO */
{XK_Thai_nonen, 0x0e13}, /* THAI CHARACTER NO NEN */
{XK_Thai_dodek, 0x0e14}, /* THAI CHARACTER DO DEK */
{XK_Thai_totao, 0x0e15}, /* THAI CHARACTER TO TAO */
{XK_Thai_thothung, 0x0e16}, /* THAI CHARACTER THO THUNG */
{XK_Thai_thothahan, 0x0e17}, /* THAI CHARACTER THO THAHAN */
{XK_Thai_thothong, 0x0e18}, /* THAI CHARACTER THO THONG */
{XK_Thai_nonu, 0x0e19}, /* THAI CHARACTER NO NU */
{XK_Thai_bobaimai, 0x0e1a}, /* THAI CHARACTER BO BAIMAI */
{XK_Thai_popla, 0x0e1b}, /* THAI CHARACTER PO PLA */
{XK_Thai_phophung, 0x0e1c}, /* THAI CHARACTER PHO PHUNG */
{XK_Thai_fofa, 0x0e1d}, /* THAI CHARACTER FO FA */
{XK_Thai_phophan, 0x0e1e}, /* THAI CHARACTER PHO PHAN */
{XK_Thai_fofan, 0x0e1f}, /* THAI CHARACTER FO FAN */
{XK_Thai_phosamphao, 0x0e20}, /* THAI CHARACTER PHO SAMPHAO */
{XK_Thai_moma, 0x0e21}, /* THAI CHARACTER MO MA */
{XK_Thai_yoyak, 0x0e22}, /* THAI CHARACTER YO YAK */
{XK_Thai_rorua, 0x0e23}, /* THAI CHARACTER RO RUA */
{XK_Thai_ru, 0x0e24}, /* THAI CHARACTER RU */
{XK_Thai_loling, 0x0e25}, /* THAI CHARACTER LO LING */
{XK_Thai_lu, 0x0e26}, /* THAI CHARACTER LU */
{XK_Thai_wowaen, 0x0e27}, /* THAI CHARACTER WO WAEN */
{XK_Thai_sosala, 0x0e28}, /* THAI CHARACTER SO SALA */
{XK_Thai_sorusi, 0x0e29}, /* THAI CHARACTER SO RUSI */
{XK_Thai_sosua, 0x0e2a}, /* THAI CHARACTER SO SUA */
{XK_Thai_hohip, 0x0e2b}, /* THAI CHARACTER HO HIP */
{XK_Thai_lochula, 0x0e2c}, /* THAI CHARACTER LO CHULA */
{XK_Thai_oang, 0x0e2d}, /* THAI CHARACTER O ANG */
{XK_Thai_honokhuk, 0x0e2e}, /* THAI CHARACTER HO NOKHUK */
{XK_Thai_paiyannoi, 0x0e2f}, /* THAI CHARACTER PAIYANNOI */
{XK_Thai_saraa, 0x0e30}, /* THAI CHARACTER SARA A */
{XK_Thai_maihanakat, 0x0e31}, /* THAI CHARACTER MAI HAN-AKAT */
{XK_Thai_saraaa, 0x0e32}, /* THAI CHARACTER SARA AA */
{XK_Thai_saraam, 0x0e33}, /* THAI CHARACTER SARA AM */
{XK_Thai_sarai, 0x0e34}, /* THAI CHARACTER SARA I */
{XK_Thai_saraii, 0x0e35}, /* THAI CHARACTER SARA II */
{XK_Thai_saraue, 0x0e36}, /* THAI CHARACTER SARA UE */
{XK_Thai_sarauee, 0x0e37}, /* THAI CHARACTER SARA UEE */
{XK_Thai_sarau, 0x0e38}, /* THAI CHARACTER SARA U */
{XK_Thai_sarauu, 0x0e39}, /* THAI CHARACTER SARA UU */
{XK_Thai_phinthu, 0x0e3a}, /* THAI CHARACTER PHINTHU */
/*{ XK_Thai_maihanakat_maitho, ??? }, */
{XK_Thai_baht, 0x0e3f}, /* THAI CURRENCY SYMBOL BAHT */
{XK_Thai_sarae, 0x0e40}, /* THAI CHARACTER SARA E */
{XK_Thai_saraae, 0x0e41}, /* THAI CHARACTER SARA AE */
{XK_Thai_sarao, 0x0e42}, /* THAI CHARACTER SARA O */
{XK_Thai_saraaimaimuan, 0x0e43}, /* THAI CHARACTER SARA AI MAIMUAN */
{XK_Thai_saraaimaimalai, 0x0e44}, /* THAI CHARACTER SARA AI MAIMALAI */
{XK_Thai_lakkhangyao, 0x0e45}, /* THAI CHARACTER LAKKHANGYAO */
{XK_Thai_maiyamok, 0x0e46}, /* THAI CHARACTER MAIYAMOK */
{XK_Thai_maitaikhu, 0x0e47}, /* THAI CHARACTER MAITAIKHU */
{XK_Thai_maiek, 0x0e48}, /* THAI CHARACTER MAI EK */
{XK_Thai_maitho, 0x0e49}, /* THAI CHARACTER MAI THO */
{XK_Thai_maitri, 0x0e4a}, /* THAI CHARACTER MAI TRI */
{XK_Thai_maichattawa, 0x0e4b}, /* THAI CHARACTER MAI CHATTAWA */
{XK_Thai_thanthakhat, 0x0e4c}, /* THAI CHARACTER THANTHAKHAT */
{XK_Thai_nikhahit, 0x0e4d}, /* THAI CHARACTER NIKHAHIT */
{XK_Thai_leksun, 0x0e50}, /* THAI DIGIT ZERO */
{XK_Thai_leknung, 0x0e51}, /* THAI DIGIT ONE */
{XK_Thai_leksong, 0x0e52}, /* THAI DIGIT TWO */
{XK_Thai_leksam, 0x0e53}, /* THAI DIGIT THREE */
{XK_Thai_leksi, 0x0e54}, /* THAI DIGIT FOUR */
{XK_Thai_lekha, 0x0e55}, /* THAI DIGIT FIVE */
{XK_Thai_lekhok, 0x0e56}, /* THAI DIGIT SIX */
{XK_Thai_lekchet, 0x0e57}, /* THAI DIGIT SEVEN */
{XK_Thai_lekpaet, 0x0e58}, /* THAI DIGIT EIGHT */
{XK_Thai_lekkao, 0x0e59}, /* THAI DIGIT NINE */
#endif // defined(XK_Thai_kokai)
#if defined(XK_Hangul_Kiyeog)
{XK_Hangul_Kiyeog, 0x3131}, /* HANGUL LETTER KIYEOK */
{XK_Hangul_SsangKiyeog, 0x3132}, /* HANGUL LETTER SSANGKIYEOK */
{XK_Hangul_KiyeogSios, 0x3133}, /* HANGUL LETTER KIYEOK-SIOS */
{XK_Hangul_Nieun, 0x3134}, /* HANGUL LETTER NIEUN */
{XK_Hangul_NieunJieuj, 0x3135}, /* HANGUL LETTER NIEUN-CIEUC */
{XK_Hangul_NieunHieuh, 0x3136}, /* HANGUL LETTER NIEUN-HIEUH */
{XK_Hangul_Dikeud, 0x3137}, /* HANGUL LETTER TIKEUT */
{XK_Hangul_SsangDikeud, 0x3138}, /* HANGUL LETTER SSANGTIKEUT */
{XK_Hangul_Rieul, 0x3139}, /* HANGUL LETTER RIEUL */
{XK_Hangul_RieulKiyeog, 0x313a}, /* HANGUL LETTER RIEUL-KIYEOK */
{XK_Hangul_RieulMieum, 0x313b}, /* HANGUL LETTER RIEUL-MIEUM */
{XK_Hangul_RieulPieub, 0x313c}, /* HANGUL LETTER RIEUL-PIEUP */
{XK_Hangul_RieulSios, 0x313d}, /* HANGUL LETTER RIEUL-SIOS */
{XK_Hangul_RieulTieut, 0x313e}, /* HANGUL LETTER RIEUL-THIEUTH */
{XK_Hangul_RieulPhieuf, 0x313f}, /* HANGUL LETTER RIEUL-PHIEUPH */
{XK_Hangul_RieulHieuh, 0x3140}, /* HANGUL LETTER RIEUL-HIEUH */
{XK_Hangul_Mieum, 0x3141}, /* HANGUL LETTER MIEUM */
{XK_Hangul_Pieub, 0x3142}, /* HANGUL LETTER PIEUP */
{XK_Hangul_SsangPieub, 0x3143}, /* HANGUL LETTER SSANGPIEUP */
{XK_Hangul_PieubSios, 0x3144}, /* HANGUL LETTER PIEUP-SIOS */
{XK_Hangul_Sios, 0x3145}, /* HANGUL LETTER SIOS */
{XK_Hangul_SsangSios, 0x3146}, /* HANGUL LETTER SSANGSIOS */
{XK_Hangul_Ieung, 0x3147}, /* HANGUL LETTER IEUNG */
{XK_Hangul_Jieuj, 0x3148}, /* HANGUL LETTER CIEUC */
{XK_Hangul_SsangJieuj, 0x3149}, /* HANGUL LETTER SSANGCIEUC */
{XK_Hangul_Cieuc, 0x314a}, /* HANGUL LETTER CHIEUCH */
{XK_Hangul_Khieuq, 0x314b}, /* HANGUL LETTER KHIEUKH */
{XK_Hangul_Tieut, 0x314c}, /* HANGUL LETTER THIEUTH */
{XK_Hangul_Phieuf, 0x314d}, /* HANGUL LETTER PHIEUPH */
{XK_Hangul_Hieuh, 0x314e}, /* HANGUL LETTER HIEUH */
{XK_Hangul_A, 0x314f}, /* HANGUL LETTER A */
{XK_Hangul_AE, 0x3150}, /* HANGUL LETTER AE */
{XK_Hangul_YA, 0x3151}, /* HANGUL LETTER YA */
{XK_Hangul_YAE, 0x3152}, /* HANGUL LETTER YAE */
{XK_Hangul_EO, 0x3153}, /* HANGUL LETTER EO */
{XK_Hangul_E, 0x3154}, /* HANGUL LETTER E */
{XK_Hangul_YEO, 0x3155}, /* HANGUL LETTER YEO */
{XK_Hangul_YE, 0x3156}, /* HANGUL LETTER YE */
{XK_Hangul_O, 0x3157}, /* HANGUL LETTER O */
{XK_Hangul_WA, 0x3158}, /* HANGUL LETTER WA */
{XK_Hangul_WAE, 0x3159}, /* HANGUL LETTER WAE */
{XK_Hangul_OE, 0x315a}, /* HANGUL LETTER OE */
{XK_Hangul_YO, 0x315b}, /* HANGUL LETTER YO */
{XK_Hangul_U, 0x315c}, /* HANGUL LETTER U */
{XK_Hangul_WEO, 0x315d}, /* HANGUL LETTER WEO */
{XK_Hangul_WE, 0x315e}, /* HANGUL LETTER WE */
{XK_Hangul_WI, 0x315f}, /* HANGUL LETTER WI */
{XK_Hangul_YU, 0x3160}, /* HANGUL LETTER YU */
{XK_Hangul_EU, 0x3161}, /* HANGUL LETTER EU */
{XK_Hangul_YI, 0x3162}, /* HANGUL LETTER YI */
{XK_Hangul_I, 0x3163}, /* HANGUL LETTER I */
{XK_Hangul_J_Kiyeog, 0x11a8}, /* HANGUL JONGSEONG KIYEOK */
{XK_Hangul_J_SsangKiyeog, 0x11a9}, /* HANGUL JONGSEONG SSANGKIYEOK */
{XK_Hangul_J_KiyeogSios, 0x11aa}, /* HANGUL JONGSEONG KIYEOK-SIOS */
{XK_Hangul_J_Nieun, 0x11ab}, /* HANGUL JONGSEONG NIEUN */
{XK_Hangul_J_NieunJieuj, 0x11ac}, /* HANGUL JONGSEONG NIEUN-CIEUC */
{XK_Hangul_J_NieunHieuh, 0x11ad}, /* HANGUL JONGSEONG NIEUN-HIEUH */
{XK_Hangul_J_Dikeud, 0x11ae}, /* HANGUL JONGSEONG TIKEUT */
{XK_Hangul_J_Rieul, 0x11af}, /* HANGUL JONGSEONG RIEUL */
{XK_Hangul_J_RieulKiyeog, 0x11b0}, /* HANGUL JONGSEONG RIEUL-KIYEOK */
{XK_Hangul_J_RieulMieum, 0x11b1}, /* HANGUL JONGSEONG RIEUL-MIEUM */
{XK_Hangul_J_RieulPieub, 0x11b2}, /* HANGUL JONGSEONG RIEUL-PIEUP */
{XK_Hangul_J_RieulSios, 0x11b3}, /* HANGUL JONGSEONG RIEUL-SIOS */
{XK_Hangul_J_RieulTieut, 0x11b4}, /* HANGUL JONGSEONG RIEUL-THIEUTH */
{XK_Hangul_J_RieulPhieuf, 0x11b5}, /* HANGUL JONGSEONG RIEUL-PHIEUPH */
{XK_Hangul_J_RieulHieuh, 0x11b6}, /* HANGUL JONGSEONG RIEUL-HIEUH */
{XK_Hangul_J_Mieum, 0x11b7}, /* HANGUL JONGSEONG MIEUM */
{XK_Hangul_J_Pieub, 0x11b8}, /* HANGUL JONGSEONG PIEUP */
{XK_Hangul_J_PieubSios, 0x11b9}, /* HANGUL JONGSEONG PIEUP-SIOS */
{XK_Hangul_J_Sios, 0x11ba}, /* HANGUL JONGSEONG SIOS */
{XK_Hangul_J_SsangSios, 0x11bb}, /* HANGUL JONGSEONG SSANGSIOS */
{XK_Hangul_J_Ieung, 0x11bc}, /* HANGUL JONGSEONG IEUNG */
{XK_Hangul_J_Jieuj, 0x11bd}, /* HANGUL JONGSEONG CIEUC */
{XK_Hangul_J_Cieuc, 0x11be}, /* HANGUL JONGSEONG CHIEUCH */
{XK_Hangul_J_Khieuq, 0x11bf}, /* HANGUL JONGSEONG KHIEUKH */
{XK_Hangul_J_Tieut, 0x11c0}, /* HANGUL JONGSEONG THIEUTH */
{XK_Hangul_J_Phieuf, 0x11c1}, /* HANGUL JONGSEONG PHIEUPH */
{XK_Hangul_J_Hieuh, 0x11c2}, /* HANGUL JONGSEONG HIEUH */
{XK_Hangul_RieulYeorinHieuh, 0x316d}, /* HANGUL LETTER RIEUL-YEORINHIEUH */
{XK_Hangul_SunkyeongeumMieum, 0x3171}, /* HANGUL LETTER KAPYEOUNMIEUM */
{XK_Hangul_SunkyeongeumPieub, 0x3178}, /* HANGUL LETTER KAPYEOUNPIEUP */
{XK_Hangul_PanSios, 0x317f}, /* HANGUL LETTER PANSIOS */
{XK_Hangul_KkogjiDalrinIeung, 0x3181}, /* HANGUL LETTER YESIEUNG */
{XK_Hangul_SunkyeongeumPhieuf, 0x3184}, /* HANGUL LETTER KAPYEOUNPHIEUPH */
{XK_Hangul_YeorinHieuh, 0x3186}, /* HANGUL LETTER YEORINHIEUH */
{XK_Hangul_AraeA, 0x318d}, /* HANGUL LETTER ARAEA */
{XK_Hangul_AraeAE, 0x318e}, /* HANGUL LETTER ARAEAE */
{XK_Hangul_J_PanSios, 0x11eb}, /* HANGUL JONGSEONG PANSIOS */
{XK_Hangul_J_KkogjiDalrinIeung, 0x11f0}, /* HANGUL JONGSEONG YESIEUNG */
{XK_Hangul_J_YeorinHieuh, 0x11f9}, /* HANGUL JONGSEONG YEORINHIEUH */
{XK_Korean_Won, 0x20a9}, /* WON SIGN */
#endif // defined(XK_Hangul_Kiyeog)
{XK_OE, 0x0152}, /* LATIN CAPITAL LIGATURE OE */
{XK_oe, 0x0153}, /* LATIN SMALL LIGATURE OE */
{XK_Ydiaeresis, 0x0178}, /* LATIN CAPITAL LETTER Y WITH DIAERESIS */
{XK_EuroSign, 0x20ac}, /* EURO SIGN */
/* combining dead keys */
{XK_dead_abovedot, 0x0307}, /* COMBINING DOT ABOVE */
{XK_dead_abovering, 0x030a}, /* COMBINING RING ABOVE */
{XK_dead_acute, 0x0301}, /* COMBINING ACUTE ACCENT */
{XK_dead_breve, 0x0306}, /* COMBINING BREVE */
{XK_dead_caron, 0x030c}, /* COMBINING CARON */
{XK_dead_cedilla, 0x0327}, /* COMBINING CEDILLA */
{XK_dead_circumflex, 0x0302}, /* COMBINING CIRCUMFLEX ACCENT */
{XK_dead_diaeresis, 0x0308}, /* COMBINING DIAERESIS */
{XK_dead_doubleacute, 0x030b}, /* COMBINING DOUBLE ACUTE ACCENT */
{XK_dead_grave, 0x0300}, /* COMBINING GRAVE ACCENT */
{XK_dead_macron, 0x0304}, /* COMBINING MACRON */
{XK_dead_ogonek, 0x0328}, /* COMBINING OGONEK */
{XK_dead_tilde, 0x0303} /* COMBINING TILDE */
};
/* XXX -- map these too
XK_Cyrillic_GHE_bar
XK_Cyrillic_ZHE_descender
XK_Cyrillic_KA_descender
XK_Cyrillic_KA_vertstroke
XK_Cyrillic_EN_descender
XK_Cyrillic_U_straight
XK_Cyrillic_U_straight_bar
XK_Cyrillic_HA_descender
XK_Cyrillic_CHE_descender
XK_Cyrillic_CHE_vertstroke
XK_Cyrillic_SHHA
XK_Cyrillic_SCHWA
XK_Cyrillic_I_macron
XK_Cyrillic_O_bar
XK_Cyrillic_U_macron
XK_Cyrillic_ghe_bar
XK_Cyrillic_zhe_descender
XK_Cyrillic_ka_descender
XK_Cyrillic_ka_vertstroke
XK_Cyrillic_en_descender
XK_Cyrillic_u_straight
XK_Cyrillic_u_straight_bar
XK_Cyrillic_ha_descender
XK_Cyrillic_che_descender
XK_Cyrillic_che_vertstroke
XK_Cyrillic_shha
XK_Cyrillic_schwa
XK_Cyrillic_i_macron
XK_Cyrillic_o_bar
XK_Cyrillic_u_macron
XK_Armenian_eternity
XK_Armenian_ligature_ew
XK_Armenian_full_stop
XK_Armenian_verjaket
XK_Armenian_parenright
XK_Armenian_parenleft
XK_Armenian_guillemotright
XK_Armenian_guillemotleft
XK_Armenian_em_dash
XK_Armenian_dot
XK_Armenian_mijaket
XK_Armenian_but
XK_Armenian_separation_mark
XK_Armenian_comma
XK_Armenian_en_dash
XK_Armenian_hyphen
XK_Armenian_yentamna
XK_Armenian_ellipsis
XK_Armenian_amanak
XK_Armenian_exclam
XK_Armenian_accent
XK_Armenian_shesht
XK_Armenian_paruyk
XK_Armenian_question
XK_Armenian_AYB
XK_Armenian_ayb
XK_Armenian_BEN
XK_Armenian_ben
XK_Armenian_GIM
XK_Armenian_gim
XK_Armenian_DA
XK_Armenian_da
XK_Armenian_YECH
XK_Armenian_yech
XK_Armenian_ZA
XK_Armenian_za
XK_Armenian_E
XK_Armenian_e
XK_Armenian_AT
XK_Armenian_at
XK_Armenian_TO
XK_Armenian_to
XK_Armenian_ZHE
XK_Armenian_zhe
XK_Armenian_INI
XK_Armenian_ini
XK_Armenian_LYUN
XK_Armenian_lyun
XK_Armenian_KHE
XK_Armenian_khe
XK_Armenian_TSA
XK_Armenian_tsa
XK_Armenian_KEN
XK_Armenian_ken
XK_Armenian_HO
XK_Armenian_ho
XK_Armenian_DZA
XK_Armenian_dza
XK_Armenian_GHAT
XK_Armenian_ghat
XK_Armenian_TCHE
XK_Armenian_tche
XK_Armenian_MEN
XK_Armenian_men
XK_Armenian_HI
XK_Armenian_hi
XK_Armenian_NU
XK_Armenian_nu
XK_Armenian_SHA
XK_Armenian_sha
XK_Armenian_VO
XK_Armenian_vo
XK_Armenian_CHA
XK_Armenian_cha
XK_Armenian_PE
XK_Armenian_pe
XK_Armenian_JE
XK_Armenian_je
XK_Armenian_RA
XK_Armenian_ra
XK_Armenian_SE
XK_Armenian_se
XK_Armenian_VEV
XK_Armenian_vev
XK_Armenian_TYUN
XK_Armenian_tyun
XK_Armenian_RE
XK_Armenian_re
XK_Armenian_TSO
XK_Armenian_tso
XK_Armenian_VYUN
XK_Armenian_vyun
XK_Armenian_PYUR
XK_Armenian_pyur
XK_Armenian_KE
XK_Armenian_ke
XK_Armenian_O
XK_Armenian_o
XK_Armenian_FE
XK_Armenian_fe
XK_Armenian_apostrophe
XK_Armenian_section_sign
XK_Georgian_an
XK_Georgian_ban
XK_Georgian_gan
XK_Georgian_don
XK_Georgian_en
XK_Georgian_vin
XK_Georgian_zen
XK_Georgian_tan
XK_Georgian_in
XK_Georgian_kan
XK_Georgian_las
XK_Georgian_man
XK_Georgian_nar
XK_Georgian_on
XK_Georgian_par
XK_Georgian_zhar
XK_Georgian_rae
XK_Georgian_san
XK_Georgian_tar
XK_Georgian_un
XK_Georgian_phar
XK_Georgian_khar
XK_Georgian_ghan
XK_Georgian_qar
XK_Georgian_shin
XK_Georgian_chin
XK_Georgian_can
XK_Georgian_jil
XK_Georgian_cil
XK_Georgian_char
XK_Georgian_xan
XK_Georgian_jhan
XK_Georgian_hae
XK_Georgian_he
XK_Georgian_hie
XK_Georgian_we
XK_Georgian_har
XK_Georgian_hoe
XK_Georgian_fi
XK_Ccedillaabovedot
XK_Xabovedot
XK_Qabovedot
XK_Ibreve
XK_IE
XK_UO
XK_Zstroke
XK_Gcaron
XK_Obarred
XK_ccedillaabovedot
XK_xabovedot
XK_Ocaron
XK_qabovedot
XK_ibreve
XK_ie
XK_uo
XK_zstroke
XK_gcaron
XK_ocaron
XK_obarred
XK_SCHWA
XK_Lbelowdot
XK_Lstrokebelowdot
XK_Gtilde
XK_lbelowdot
XK_lstrokebelowdot
XK_gtilde
XK_schwa
XK_Abelowdot
XK_abelowdot
XK_Ahook
XK_ahook
XK_Acircumflexacute
XK_acircumflexacute
XK_Acircumflexgrave
XK_acircumflexgrave
XK_Acircumflexhook
XK_acircumflexhook
XK_Acircumflextilde
XK_acircumflextilde
XK_Acircumflexbelowdot
XK_acircumflexbelowdot
XK_Abreveacute
XK_abreveacute
XK_Abrevegrave
XK_abrevegrave
XK_Abrevehook
XK_abrevehook
XK_Abrevetilde
XK_abrevetilde
XK_Abrevebelowdot
XK_abrevebelowdot
XK_Ebelowdot
XK_ebelowdot
XK_Ehook
XK_ehook
XK_Etilde
XK_etilde
XK_Ecircumflexacute
XK_ecircumflexacute
XK_Ecircumflexgrave
XK_ecircumflexgrave
XK_Ecircumflexhook
XK_ecircumflexhook
XK_Ecircumflextilde
XK_ecircumflextilde
XK_Ecircumflexbelowdot
XK_ecircumflexbelowdot
XK_Ihook
XK_ihook
XK_Ibelowdot
XK_ibelowdot
XK_Obelowdot
XK_obelowdot
XK_Ohook
XK_ohook
XK_Ocircumflexacute
XK_ocircumflexacute
XK_Ocircumflexgrave
XK_ocircumflexgrave
XK_Ocircumflexhook
XK_ocircumflexhook
XK_Ocircumflextilde
XK_ocircumflextilde
XK_Ocircumflexbelowdot
XK_ocircumflexbelowdot
XK_Ohornacute
XK_ohornacute
XK_Ohorngrave
XK_ohorngrave
XK_Ohornhook
XK_ohornhook
XK_Ohorntilde
XK_ohorntilde
XK_Ohornbelowdot
XK_ohornbelowdot
XK_Ubelowdot
XK_ubelowdot
XK_Uhook
XK_uhook
XK_Uhornacute
XK_uhornacute
XK_Uhorngrave
XK_uhorngrave
XK_Uhornhook
XK_uhornhook
XK_Uhorntilde
XK_uhorntilde
XK_Uhornbelowdot
XK_uhornbelowdot
XK_Ybelowdot
XK_ybelowdot
XK_Yhook
XK_yhook
XK_Ytilde
XK_ytilde
XK_Ohorn
XK_ohorn
XK_Uhorn
XK_uhorn
*/
// map "Internet" keys to KeyIDs
static const KeySym s_map1008FF[] = {
/* 0x00 */ 0,
0,
kKeyBrightnessUp,
kKeyBrightnessDown,
0,
0,
0,
0,
/* 0x08 */ 0,
0,
0,
0,
0,
0,
0,
0,
/* 0x10 */ 0,
kKeyAudioDown,
kKeyAudioMute,
kKeyAudioUp,
/* 0x14 */ kKeyAudioPlay,
kKeyAudioStop,
kKeyAudioPrev,
kKeyAudioNext,
/* 0x18 */ kKeyWWWHome,
kKeyAppMail,
0,
kKeyWWWSearch,
0,
0,
0,
0,
/* 0x20 */ 0,
0,
0,
0,
0,
0,
kKeyWWWBack,
kKeyWWWForward,
/* 0x28 */ kKeyWWWStop,
kKeyWWWRefresh,
0,
0,
kKeyEject,
0,
0,
0,
/* 0x30 */ kKeyWWWFavorites,
0,
kKeyAppMedia,
0,
0,
0,
0,
0,
/* 0x38 */ 0,
0,
0,
0,
0,
0,
0,
0,
/* 0x40 */ kKeyAppUser1,
kKeyAppUser2,
0,
0,
0,
0,
0,
0,
/* 0x48 */ 0,
0,
kKeyMissionControl,
kKeyLaunchpad,
0,
0,
0,
0,
/* 0x50 */ 0,
0,
0,
0,
0,
0,
0,
0,
/* 0x58 */ 0,
0,
0,
0,
0,
0,
0,
0,
/* 0x60 */ 0,
0,
0,
0,
0,
0,
0,
0,
/* 0x68 */ 0,
0,
0,
0,
0,
0,
0,
0,
/* 0x70 */ 0,
0,
0,
0,
0,
0,
0,
0,
/* 0x78 */ 0,
0,
0,
0,
0,
0,
0,
0,
/* 0x80 */ 0,
0,
0,
0,
0,
0,
0,
0,
/* 0x88 */ 0,
0,
0,
0,
0,
0,
0,
0,
/* 0x90 */ 0,
0,
0,
0,
0,
0,
0,
0,
/* 0x98 */ 0,
0,
0,
0,
0,
0,
0,
0,
/* 0xa0 */ 0,
0,
0,
0,
0,
0,
0,
0,
/* 0xa8 */ 0,
0,
0,
0,
0,
0,
0,
0,
/* 0xb0 */ 0,
0,
0,
0,
0,
0,
0,
0,
/* 0xb8 */ 0,
0,
0,
0,
0,
0,
0,
0,
/* 0xc0 */ 0,
0,
0,
0,
0,
0,
0,
0,
/* 0xc8 */ 0,
0,
0,
0,
0,
0,
0,
0,
/* 0xd0 */ 0,
0,
0,
0,
0,
0,
0,
0,
/* 0xd8 */ 0,
0,
0,
0,
0,
0,
0,
0,
/* 0xe0 */ 0,
0,
0,
0,
0,
0,
0,
0,
/* 0xe8 */ 0,
0,
0,
0,
0,
0,
0,
0,
/* 0xf0 */ 0,
0,
0,
0,
0,
0,
0,
0,
/* 0xf8 */ 0,
0,
0,
0,
0,
0,
0,
0
};
//
// XWindowsUtil
//
XWindowsUtil::KeySymMap XWindowsUtil::s_keySymToUCS4;
bool XWindowsUtil::getWindowProperty(
Display *display, Window window, Atom property, String *data, Atom *type, SInt32 *format, bool deleteProperty
)
{
assert(display != NULL);
Atom actualType;
int actualDatumSize;
// ignore errors. XGetWindowProperty() will report failure.
XWindowsUtil::ErrorLock lock(display);
// read the property
bool okay = true;
const long length = XMaxRequestSize(display);
long offset = 0;
unsigned long bytesLeft = 1;
while (bytesLeft != 0) {
// get more data
unsigned long numItems;
unsigned char *rawData;
if (XGetWindowProperty(
display, window, property, offset, length, False, AnyPropertyType, &actualType, &actualDatumSize, &numItems,
&bytesLeft, &rawData
) != Success ||
actualType == None || actualDatumSize == 0) {
// failed
okay = false;
break;
}
// compute bytes read and advance offset
unsigned long numBytes;
switch (actualDatumSize) {
case 8:
default:
numBytes = numItems;
offset += numItems / 4;
break;
case 16:
numBytes = 2 * numItems;
offset += numItems / 2;
break;
case 32:
numBytes = 4 * numItems;
offset += numItems;
break;
}
// append data
if (data != NULL) {
data->append((char *)rawData, numBytes);
} else {
// data is not required so don't try to get any more
bytesLeft = 0;
}
// done with returned data
XFree(rawData);
}
// delete the property if requested
if (deleteProperty) {
XDeleteProperty(display, window, property);
}
// save property info
if (type != NULL) {
*type = actualType;
}
if (format != NULL) {
*format = static_cast<SInt32>(actualDatumSize);
}
if (okay) {
LOG((CLOG_DEBUG2 "read property %d on window 0x%08x: bytes=%d", property, window, (data == NULL) ? 0 : data->size())
);
return true;
} else {
LOG((CLOG_DEBUG2 "can't read property %d on window 0x%08x", property, window));
return false;
}
}
bool XWindowsUtil::setWindowProperty(
Display *display, Window window, Atom property, const void *vdata, UInt32 size, Atom type, SInt32 format
)
{
const UInt32 length = 4 * XMaxRequestSize(display);
const unsigned char *data = static_cast<const unsigned char *>(vdata);
UInt32 datumSize = static_cast<UInt32>(format / 8);
// format 32 on 64bit systems is 8 bytes not 4.
if (format == 32) {
datumSize = sizeof(Atom);
}
// save errors
bool error = false;
XWindowsUtil::ErrorLock lock(display, &error);
// how much data to send in first chunk?
UInt32 chunkSize = size;
if (chunkSize > length) {
chunkSize = length;
}
// send first chunk
XChangeProperty(display, window, property, type, format, PropModeReplace, data, chunkSize / datumSize);
// append remaining chunks
data += chunkSize;
size -= chunkSize;
while (!error && size > 0) {
chunkSize = size;
if (chunkSize > length) {
chunkSize = length;
}
XChangeProperty(display, window, property, type, format, PropModeAppend, data, chunkSize / datumSize);
data += chunkSize;
size -= chunkSize;
}
return !error;
}
Time XWindowsUtil::getCurrentTime(Display *display, Window window)
{
XLockDisplay(display);
// select property events on window
XWindowAttributes attr;
XGetWindowAttributes(display, window, &attr);
XSelectInput(display, window, attr.your_event_mask | PropertyChangeMask);
// make a property name to receive dummy change
Atom atom = XInternAtom(display, "TIMESTAMP", False);
// do a zero-length append to get the current time
unsigned char dummy;
XChangeProperty(display, window, atom, XA_INTEGER, 8, PropModeAppend, &dummy, 0);
// look for property notify events with the following
PropertyNotifyPredicateInfo filter;
filter.m_window = window;
filter.m_property = atom;
// wait for reply
XEvent xevent;
XIfEvent(display, &xevent, &XWindowsUtil::propertyNotifyPredicate, (XPointer)&filter);
assert(xevent.type == PropertyNotify);
assert(xevent.xproperty.window == window);
assert(xevent.xproperty.atom == atom);
// restore event mask
XSelectInput(display, window, attr.your_event_mask);
XUnlockDisplay(display);
return xevent.xproperty.time;
}
KeyID XWindowsUtil::mapKeySymToKeyID(KeySym k)
{
initKeyMaps();
switch (k & 0xffffff00) {
case 0x0000:
// Latin-1
return static_cast<KeyID>(k);
case 0xfe00:
// ISO 9995 Function and Modifier Keys
switch (k) {
case XK_ISO_Left_Tab:
return kKeyLeftTab;
case XK_ISO_Level3_Shift:
return kKeyAltGr;
#ifdef XK_ISO_Level5_Shift
case XK_ISO_Level5_Shift:
return XK_ISO_Level5_Shift; // FIXME: there is no "usual" key for this...
#endif
case XK_ISO_Next_Group:
return kKeyNextGroup;
case XK_ISO_Prev_Group:
return kKeyPrevGroup;
case XK_dead_grave:
return kKeyDeadGrave;
case XK_dead_acute:
return kKeyDeadAcute;
case XK_dead_circumflex:
return kKeyDeadCircumflex;
case XK_dead_tilde:
return kKeyDeadTilde;
case XK_dead_macron:
return kKeyDeadMacron;
case XK_dead_breve:
return kKeyDeadBreve;
case XK_dead_abovedot:
return kKeyDeadAbovedot;
case XK_dead_diaeresis:
return kKeyDeadDiaeresis;
case XK_dead_abovering:
return kKeyDeadAbovering;
case XK_dead_doubleacute:
return kKeyDeadDoubleacute;
case XK_dead_caron:
return kKeyDeadCaron;
case XK_dead_cedilla:
return kKeyDeadCedilla;
case XK_dead_ogonek:
return kKeyDeadOgonek;
default:
return kKeyNone;
}
case 0xff00:
// MISCELLANY
return static_cast<KeyID>(k - 0xff00 + 0xef00);
case 0x1008ff00:
// "Internet" keys
return s_map1008FF[k & 0xff];
default: {
// lookup character in table
KeySymMap::const_iterator index = s_keySymToUCS4.find(k);
if (index != s_keySymToUCS4.end()) {
return static_cast<KeyID>(index->second);
}
// unknown character
return kKeyNone;
}
}
}
UInt32 XWindowsUtil::getModifierBitForKeySym(KeySym keysym)
{
switch (keysym) {
case XK_Shift_L:
case XK_Shift_R:
return kKeyModifierBitShift;
case XK_Control_L:
case XK_Control_R:
return kKeyModifierBitControl;
case XK_Alt_L:
case XK_Alt_R:
return kKeyModifierBitAlt;
case XK_Meta_L:
case XK_Meta_R:
return kKeyModifierBitMeta;
case XK_Super_L:
case XK_Super_R:
case XK_Hyper_L:
case XK_Hyper_R:
return kKeyModifierBitSuper;
case XK_Mode_switch:
case XK_ISO_Level3_Shift:
return kKeyModifierBitAltGr;
#ifdef XK_ISO_Level5_Shift
case XK_ISO_Level5_Shift:
return kKeyModifierBitLevel5Lock;
#endif
case XK_Caps_Lock:
return kKeyModifierBitCapsLock;
case XK_Num_Lock:
return kKeyModifierBitNumLock;
case XK_Scroll_Lock:
return kKeyModifierBitScrollLock;
default:
return kKeyModifierBitNone;
}
}
String XWindowsUtil::atomToString(Display *display, Atom atom)
{
if (atom == 0) {
return "None";
}
bool error = false;
XWindowsUtil::ErrorLock lock(display, &error);
char *name = XGetAtomName(display, atom);
if (error) {
return deskflow::string::sprintf("<UNKNOWN> (%d)", (int)atom);
} else {
String msg = deskflow::string::sprintf("%s (%d)", name, (int)atom);
XFree(name);
return msg;
}
}
String XWindowsUtil::atomsToString(Display *display, const Atom *atom, UInt32 num)
{
char **names = new char *[num];
bool error = false;
XWindowsUtil::ErrorLock lock(display, &error);
XGetAtomNames(display, const_cast<Atom *>(atom), (int)num, names);
String msg;
if (error) {
for (UInt32 i = 0; i < num; ++i) {
msg += deskflow::string::sprintf("<UNKNOWN> (%d), ", (int)atom[i]);
}
} else {
for (UInt32 i = 0; i < num; ++i) {
msg += deskflow::string::sprintf("%s (%d), ", names[i], (int)atom[i]);
XFree(names[i]);
}
}
delete[] names;
if (msg.size() > 2) {
msg.erase(msg.size() - 2);
}
return msg;
}
void XWindowsUtil::convertAtomProperty(String &data)
{
// as best i can tell, 64-bit systems don't pack Atoms into properties
// as 32-bit numbers but rather as the 64-bit numbers they are. that
// seems wrong but we have to cope. sometimes we'll get a list of
// atoms that's 8*n+4 bytes long, missing the trailing 4 bytes which
// should all be 0. since we're going to reference the Atoms as
// 64-bit numbers we have to ensure the last number is a full 64 bits.
if (sizeof(Atom) != 4 && ((data.size() / 4) & 1) != 0) {
UInt32 zero = 0;
data.append(reinterpret_cast<char *>(&zero), sizeof(zero));
}
}
void XWindowsUtil::appendAtomData(String &data, Atom atom)
{
data.append(reinterpret_cast<char *>(&atom), sizeof(Atom));
}
void XWindowsUtil::replaceAtomData(String &data, UInt32 index, Atom atom)
{
data.replace(index * sizeof(Atom), sizeof(Atom), reinterpret_cast<const char *>(&atom), sizeof(Atom));
}
void XWindowsUtil::appendTimeData(String &data, Time time)
{
data.append(reinterpret_cast<char *>(&time), sizeof(Time));
}
Bool XWindowsUtil::propertyNotifyPredicate(Display *, XEvent *xevent, XPointer arg)
{
PropertyNotifyPredicateInfo *filter = reinterpret_cast<PropertyNotifyPredicateInfo *>(arg);
return (xevent->type == PropertyNotify && xevent->xproperty.window == filter->m_window &&
xevent->xproperty.atom == filter->m_property && xevent->xproperty.state == PropertyNewValue)
? True
: False;
}
void XWindowsUtil::initKeyMaps()
{
if (s_keySymToUCS4.empty()) {
for (size_t i = 0; i < sizeof(s_keymap) / sizeof(s_keymap[0]); ++i) {
s_keySymToUCS4[s_keymap[i].keysym] = s_keymap[i].ucs4;
}
}
}
//
// XWindowsUtil::ErrorLock
//
XWindowsUtil::ErrorLock *XWindowsUtil::ErrorLock::s_top = NULL;
XWindowsUtil::ErrorLock::ErrorLock(Display *display) : m_display(display)
{
install(&XWindowsUtil::ErrorLock::ignoreHandler, NULL);
}
XWindowsUtil::ErrorLock::ErrorLock(Display *display, bool *flag) : m_display(display)
{
install(&XWindowsUtil::ErrorLock::saveHandler, flag);
}
XWindowsUtil::ErrorLock::ErrorLock(Display *display, ErrorHandler handler, void *data) : m_display(display)
{
install(handler, data);
}
XWindowsUtil::ErrorLock::~ErrorLock()
{
// make sure everything finishes before uninstalling handler
if (m_display != NULL) {
XSync(m_display, False);
}
// restore old handler
XSetErrorHandler(m_oldXHandler);
s_top = m_next;
}
void XWindowsUtil::ErrorLock::install(ErrorHandler handler, void *data)
{
// make sure everything finishes before installing handler
if (m_display != NULL) {
XSync(m_display, False);
}
// install handler
m_handler = handler;
m_userData = data;
m_oldXHandler = XSetErrorHandler(&XWindowsUtil::ErrorLock::internalHandler);
m_next = s_top;
s_top = this;
}
int XWindowsUtil::ErrorLock::internalHandler(Display *display, XErrorEvent *event)
{
if (s_top != NULL && s_top->m_handler != NULL) {
s_top->m_handler(display, event, s_top->m_userData);
}
return 0;
}
void XWindowsUtil::ErrorLock::ignoreHandler(Display *, XErrorEvent *e, void *)
{
LOG((CLOG_DEBUG1 "ignoring X error: %d", e->error_code));
}
void XWindowsUtil::ErrorLock::saveHandler(Display *display, XErrorEvent *e, void *flag)
{
char errtxt[1024];
XGetErrorText(display, e->error_code, errtxt, 1023);
LOG((CLOG_DEBUG1 "flagging X error: %d - %.1023s", e->error_code, errtxt));
*static_cast<bool *>(flag) = true;
}
| 80,122
|
C++
|
.cpp
| 1,879
| 38.675359
| 120
| 0.602301
|
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,567
|
OSXClipboardTextConverter.cpp
|
deskflow_deskflow/src/lib/platform/OSXClipboardTextConverter.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 "platform/OSXClipboardTextConverter.h"
#include "base/Unicode.h"
//
// OSXClipboardTextConverter
//
OSXClipboardTextConverter::OSXClipboardTextConverter()
{
// do nothing
}
OSXClipboardTextConverter::~OSXClipboardTextConverter()
{
// do nothing
}
CFStringRef OSXClipboardTextConverter::getOSXFormat() const
{
return CFSTR("public.plain-text");
}
String
OSXClipboardTextConverter::convertString(const String &data, CFStringEncoding fromEncoding, CFStringEncoding toEncoding)
{
CFStringRef stringRef = CFStringCreateWithCString(kCFAllocatorDefault, data.c_str(), fromEncoding);
if (stringRef == NULL) {
return String();
}
CFIndex buffSize;
CFRange entireString = CFRangeMake(0, CFStringGetLength(stringRef));
CFStringGetBytes(stringRef, entireString, toEncoding, 0, false, NULL, 0, &buffSize);
char *buffer = new char[buffSize];
if (buffer == NULL) {
CFRelease(stringRef);
return String();
}
CFStringGetBytes(stringRef, entireString, toEncoding, 0, false, (UInt8 *)buffer, buffSize, NULL);
String result(buffer, buffSize);
delete[] buffer;
CFRelease(stringRef);
return result;
}
String OSXClipboardTextConverter::doFromIClipboard(const String &data) const
{
return convertString(data, kCFStringEncodingUTF8, CFStringGetSystemEncoding());
}
String OSXClipboardTextConverter::doToIClipboard(const String &data) const
{
return convertString(data, CFStringGetSystemEncoding(), kCFStringEncodingUTF8);
}
| 2,204
|
C++
|
.cpp
| 63
| 32.650794
| 120
| 0.78521
|
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,568
|
PortalRemoteDesktop.cpp
|
deskflow_deskflow/src/lib/platform/PortalRemoteDesktop.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2022 Red Hat, Inc.
* 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/PortalRemoteDesktop.h"
#include "base/Log.h"
#include "base/TMethodJob.h"
#include <sys/socket.h> // for EIS fd hack, remove
#include <sys/un.h> // for EIS fd hack, remove
namespace deskflow {
PortalRemoteDesktop::PortalRemoteDesktop(EiScreen *screen, IEventQueue *events)
: screen_(screen),
events_(events),
portal_(xdp_portal_new())
{
glib_main_loop_ = g_main_loop_new(nullptr, true);
glib_thread_ = new Thread(new TMethodJob<PortalRemoteDesktop>(this, &PortalRemoteDesktop::glib_thread));
reconnect(0);
}
PortalRemoteDesktop::~PortalRemoteDesktop()
{
if (g_main_loop_is_running(glib_main_loop_))
g_main_loop_quit(glib_main_loop_);
if (glib_thread_ != nullptr) {
glib_thread_->cancel();
glib_thread_->wait();
delete glib_thread_;
glib_thread_ = nullptr;
g_main_loop_unref(glib_main_loop_);
glib_main_loop_ = nullptr;
}
if (session_signal_id_)
g_signal_handler_disconnect(session_, session_signal_id_);
if (session_ != nullptr)
g_object_unref(session_);
g_object_unref(portal_);
free(session_restore_token_);
}
gboolean PortalRemoteDesktop::timeout_handler()
{
return true; // keep re-triggering
}
void PortalRemoteDesktop::reconnect(unsigned int timeout)
{
auto init_cb = [](gpointer data) -> gboolean {
return reinterpret_cast<PortalRemoteDesktop *>(data)->init_remote_desktop_session();
};
if (timeout > 0)
g_timeout_add(timeout, init_cb, this);
else
g_idle_add(init_cb, this);
}
void PortalRemoteDesktop::cb_session_closed(XdpSession *session)
{
LOG_ERR("portal remote desktop session was closed, reconnecting");
g_signal_handler_disconnect(session, session_signal_id_);
session_signal_id_ = 0;
events_->addEvent(Event(events_->forEi().sessionClosed(), screen_->getEventTarget()));
// gcc warning "Suspicious usage of 'sizeof(A*)'" can be ignored
g_clear_object(&session_);
reconnect(1000);
}
void PortalRemoteDesktop::cb_session_started(GObject *object, GAsyncResult *res)
{
g_autoptr(GError) error = nullptr;
auto session = XDP_SESSION(object);
auto success = xdp_session_start_finish(session, res, &error);
if (!success) {
LOG_ERR("failed to start portal remote desktop session, quitting: %s", error->message);
g_main_loop_quit(glib_main_loop_);
events_->addEvent(Event::kQuit);
return;
}
session_restore_token_ = xdp_session_get_restore_token(session);
// ConnectToEIS requires version 2 of the xdg-desktop-portal (and the same
// version in the impl.portal), i.e. you'll need an updated compositor on
// top of everything...
auto fd = -1;
fd = xdp_session_connect_to_eis(session, &error);
if (fd < 0) {
g_main_loop_quit(glib_main_loop_);
events_->addEvent(Event::kQuit);
return;
}
// Socket ownership is transferred to the EiScreen
events_->addEvent(Event(events_->forEi().connected(), screen_->getEventTarget(), EiScreen::EiConnectInfo::alloc(fd)));
}
void PortalRemoteDesktop::cb_init_remote_desktop_session(GObject *object, GAsyncResult *res)
{
LOG_DEBUG("portal remote desktop session initialized");
g_autoptr(GError) error = nullptr;
auto session = xdp_portal_create_remote_desktop_session_finish(XDP_PORTAL(object), res, &error);
if (!session) {
LOG_ERR("failed to initialize remote desktop session: %s", error->message);
// This was the first attempt to connect to the RD portal - quit if that
// fails.
if (session_iteration_ == 0) {
g_main_loop_quit(glib_main_loop_);
events_->addEvent(Event::kQuit);
} else {
this->reconnect(1000);
}
return;
}
session_ = session;
++session_iteration_;
// FIXME: the lambda trick doesn't work here for unknown reasons, we need
// the static function
session_signal_id_ = g_signal_connect(G_OBJECT(session), "closed", G_CALLBACK(cb_session_closed_cb), this);
LOG_DEBUG("portal remote desktop session starting");
xdp_session_start(
session,
nullptr, // parent
nullptr, // cancellable
[](GObject *obj, GAsyncResult *res, gpointer data) {
reinterpret_cast<PortalRemoteDesktop *>(data)->cb_session_started(obj, res);
},
this
);
}
gboolean PortalRemoteDesktop::init_remote_desktop_session()
{
LOG_DEBUG("setting up remote desktop session with restore token %s", session_restore_token_);
xdp_portal_create_remote_desktop_session_full(
portal_, static_cast<XdpDeviceType>(XDP_DEVICE_POINTER | XDP_DEVICE_KEYBOARD), XDP_OUTPUT_NONE,
XDP_REMOTE_DESKTOP_FLAG_NONE, XDP_CURSOR_MODE_HIDDEN, XDP_PERSIST_MODE_TRANSIENT, session_restore_token_,
nullptr, // cancellable
[](GObject *obj, GAsyncResult *res, gpointer data) {
reinterpret_cast<PortalRemoteDesktop *>(data)->cb_init_remote_desktop_session(obj, res);
},
this
);
return false; // don't reschedule
}
void PortalRemoteDesktop::glib_thread(void *)
{
auto context = g_main_loop_get_context(glib_main_loop_);
while (g_main_loop_is_running(glib_main_loop_)) {
Thread::testCancel();
g_main_context_iteration(context, true);
}
}
} // namespace deskflow
| 5,865
|
C++
|
.cpp
| 156
| 34.070513
| 120
| 0.714562
|
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,569
|
OSXUchrKeyResource.cpp
|
deskflow_deskflow/src/lib/platform/OSXUchrKeyResource.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 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 "platform/OSXUchrKeyResource.h"
#include <Carbon/Carbon.h>
//
// OSXUchrKeyResource
//
OSXUchrKeyResource::OSXUchrKeyResource(const void *resource, UInt32 keyboardType)
: m_m(NULL),
m_cti(NULL),
m_sdi(NULL),
m_sri(NULL),
m_st(NULL)
{
m_resource = static_cast<const UCKeyboardLayout *>(resource);
if (m_resource == NULL) {
return;
}
// find the keyboard info for the current keyboard type
const UCKeyboardTypeHeader *th = NULL;
const UCKeyboardLayout *r = m_resource;
for (ItemCount i = 0; i < r->keyboardTypeCount; ++i) {
if (keyboardType >= r->keyboardTypeList[i].keyboardTypeFirst &&
keyboardType <= r->keyboardTypeList[i].keyboardTypeLast) {
th = r->keyboardTypeList + i;
break;
}
if (r->keyboardTypeList[i].keyboardTypeFirst == 0) {
// found the default. use it unless we find a match.
th = r->keyboardTypeList + i;
}
}
if (th == NULL) {
// cannot find a suitable keyboard type
return;
}
// get tables for keyboard type
const UInt8 *const base = reinterpret_cast<const UInt8 *>(m_resource);
m_m = reinterpret_cast<const UCKeyModifiersToTableNum *>(base + th->keyModifiersToTableNumOffset);
m_cti = reinterpret_cast<const UCKeyToCharTableIndex *>(base + th->keyToCharTableIndexOffset);
m_sdi = reinterpret_cast<const UCKeySequenceDataIndex *>(base + th->keySequenceDataIndexOffset);
if (th->keyStateRecordsIndexOffset != 0) {
m_sri = reinterpret_cast<const UCKeyStateRecordsIndex *>(base + th->keyStateRecordsIndexOffset);
}
if (th->keyStateTerminatorsOffset != 0) {
m_st = reinterpret_cast<const UCKeyStateTerminators *>(base + th->keyStateTerminatorsOffset);
}
// find the space key, but only if it can combine with dead keys.
// a dead key followed by a space yields the non-dead version of
// the dead key.
m_spaceOutput = 0xffffu;
UInt32 table = getTableForModifier(0);
for (UInt32 button = 0, n = getNumButtons(); button < n; ++button) {
KeyID id = getKey(table, button);
if (id == 0x20) {
UCKeyOutput c = reinterpret_cast<const UCKeyOutput *>(base + m_cti->keyToCharTableOffsets[table])[button];
if ((c & kUCKeyOutputTestForIndexMask) == kUCKeyOutputStateIndexMask) {
m_spaceOutput = (c & kUCKeyOutputGetIndexMask);
break;
}
}
}
}
bool OSXUchrKeyResource::isValid() const
{
return (m_m != NULL);
}
UInt32 OSXUchrKeyResource::getNumModifierCombinations() const
{
// only 32 (not 256) because the righthanded modifier bits are ignored
return 32;
}
UInt32 OSXUchrKeyResource::getNumTables() const
{
return m_cti->keyToCharTableCount;
}
UInt32 OSXUchrKeyResource::getNumButtons() const
{
return m_cti->keyToCharTableSize;
}
UInt32 OSXUchrKeyResource::getTableForModifier(UInt32 mask) const
{
if (mask >= m_m->modifiersCount) {
return m_m->defaultTableNum;
} else {
return m_m->tableNum[mask];
}
}
KeyID OSXUchrKeyResource::getKey(UInt32 table, UInt32 button) const
{
assert(table < getNumTables());
assert(button < getNumButtons());
const UInt8 *const base = reinterpret_cast<const UInt8 *>(m_resource);
const UCKeyOutput *cPtr = reinterpret_cast<const UCKeyOutput *>(base + m_cti->keyToCharTableOffsets[table]);
const UCKeyOutput c = cPtr[button];
KeySequence keys;
switch (c & kUCKeyOutputTestForIndexMask) {
case kUCKeyOutputStateIndexMask:
if (!getDeadKey(keys, c & kUCKeyOutputGetIndexMask)) {
return kKeyNone;
}
break;
case kUCKeyOutputSequenceIndexMask:
default:
if (!addSequence(keys, c)) {
return kKeyNone;
}
break;
}
// XXX -- no support for multiple characters
if (keys.size() != 1) {
return kKeyNone;
}
return keys.front();
}
bool OSXUchrKeyResource::getDeadKey(KeySequence &keys, UInt16 index) const
{
if (m_sri == NULL || index >= m_sri->keyStateRecordCount) {
// XXX -- should we be using some other fallback?
return false;
}
UInt16 state = 0;
if (!getKeyRecord(keys, index, state)) {
return false;
}
if (state == 0) {
// not a dead key
return true;
}
// no dead keys if we couldn't find the space key
if (m_spaceOutput == 0xffffu) {
return false;
}
// the dead key should not have put anything in the key list
if (!keys.empty()) {
return false;
}
// get the character generated by pressing the space key after the
// dead key. if we're still in a compose state afterwards then we're
// confused so we bail.
if (!getKeyRecord(keys, m_spaceOutput, state) || state != 0) {
return false;
}
// convert keys to their dead counterparts
for (KeySequence::iterator i = keys.begin(); i != keys.end(); ++i) {
*i = deskflow::KeyMap::getDeadKey(*i);
}
return true;
}
bool OSXUchrKeyResource::getKeyRecord(KeySequence &keys, UInt16 index, UInt16 &state) const
{
const UInt8 *const base = reinterpret_cast<const UInt8 *>(m_resource);
const UCKeyStateRecord *sr = reinterpret_cast<const UCKeyStateRecord *>(base + m_sri->keyStateRecordOffsets[index]);
const UCKeyStateEntryTerminal *kset = reinterpret_cast<const UCKeyStateEntryTerminal *>(sr->stateEntryData);
UInt16 nextState = 0;
bool found = false;
if (state == 0) {
found = true;
nextState = sr->stateZeroNextState;
if (!addSequence(keys, sr->stateZeroCharData)) {
return false;
}
} else {
// we have a next entry
switch (sr->stateEntryFormat) {
case kUCKeyStateEntryTerminalFormat:
for (UInt16 j = 0; j < sr->stateEntryCount; ++j) {
if (kset[j].curState == state) {
if (!addSequence(keys, kset[j].charData)) {
return false;
}
nextState = 0;
found = true;
break;
}
}
break;
case kUCKeyStateEntryRangeFormat:
// XXX -- not supported yet
break;
default:
// XXX -- unknown format
return false;
}
}
if (!found) {
// use a terminator
if (m_st != NULL && state < m_st->keyStateTerminatorCount) {
if (!addSequence(keys, m_st->keyStateTerminators[state - 1])) {
return false;
}
}
nextState = sr->stateZeroNextState;
if (!addSequence(keys, sr->stateZeroCharData)) {
return false;
}
}
// next
state = nextState;
return true;
}
bool OSXUchrKeyResource::addSequence(KeySequence &keys, UCKeyCharSeq c) const
{
if ((c & kUCKeyOutputTestForIndexMask) == kUCKeyOutputSequenceIndexMask) {
UInt16 index = (c & kUCKeyOutputGetIndexMask);
if (index < m_sdi->charSequenceCount &&
m_sdi->charSequenceOffsets[index] != m_sdi->charSequenceOffsets[index + 1]) {
// XXX -- sequences not supported yet
return false;
}
}
if (c != 0xfffe && c != 0xffff) {
KeyID id = unicharToKeyID(c);
if (id != kKeyNone) {
keys.push_back(id);
}
}
return true;
}
| 7,581
|
C++
|
.cpp
| 233
| 28.446352
| 118
| 0.688773
|
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,570
|
XWindowsClipboardTextConverter.cpp
|
deskflow_deskflow/src/lib/platform/XWindowsClipboardTextConverter.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 "platform/XWindowsClipboardTextConverter.h"
#include "base/Unicode.h"
//
// XWindowsClipboardTextConverter
//
XWindowsClipboardTextConverter::XWindowsClipboardTextConverter(Display *display, const char *name)
: m_atom(XInternAtom(display, name, False))
{
// do nothing
}
XWindowsClipboardTextConverter::~XWindowsClipboardTextConverter()
{
// do nothing
}
IClipboard::EFormat XWindowsClipboardTextConverter::getFormat() const
{
return IClipboard::kText;
}
Atom XWindowsClipboardTextConverter::getAtom() const
{
return m_atom;
}
int XWindowsClipboardTextConverter::getDataSize() const
{
return 8;
}
String XWindowsClipboardTextConverter::fromIClipboard(const String &data) const
{
return Unicode::UTF8ToText(data);
}
String XWindowsClipboardTextConverter::toIClipboard(const String &data) const
{
// convert to UTF-8
bool errors;
String utf8 = Unicode::textToUTF8(data, &errors);
// if there were decoding errors then, to support old applications
// that don't understand UTF-8 but can report the exact binary
// UTF-8 representation, see if the data appears to be UTF-8. if
// so then use it as is.
if (errors && Unicode::isUTF8(data)) {
return data;
}
return utf8;
}
| 1,959
|
C++
|
.cpp
| 61
| 30
| 98
| 0.775186
|
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,571
|
MSWindowsSession.cpp
|
deskflow_deskflow/src/lib/platform/MSWindowsSession.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 "platform/MSWindowsSession.h"
#include "arch/win32/XArchWindows.h"
#include "base/Log.h"
#include "deskflow/XDeskflow.h"
#include <Wtsapi32.h>
MSWindowsSession::MSWindowsSession() : m_activeSessionId(-1)
{
}
MSWindowsSession::~MSWindowsSession()
{
}
bool MSWindowsSession::isProcessInSession(const char *name, PHANDLE process = NULL)
{
// first we need to take a snapshot of the running processes
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot == INVALID_HANDLE_VALUE) {
LOG((CLOG_ERR "could not get process snapshot"));
throw XArch(new XArchEvalWindows());
}
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
// get the first process, and if we can't do that then it's
// unlikely we can go any further
BOOL gotEntry = Process32First(snapshot, &entry);
if (!gotEntry) {
LOG((CLOG_ERR "could not get first process entry"));
throw XArch(new XArchEvalWindows());
}
// used to record process names for debug info
std::list<std::string> nameList;
// now just iterate until we can find winlogon.exe pid
DWORD pid = 0;
while (gotEntry) {
// make sure we're not checking the system process
if (entry.th32ProcessID != 0) {
DWORD processSessionId;
BOOL pidToSidRet = ProcessIdToSessionId(entry.th32ProcessID, &processSessionId);
if (!pidToSidRet) {
// if we can not acquire session associated with a specified process,
// simply ignore it
LOG(
(CLOG_DEBUG2 "could not get session id for process: %i %s, code=%i", entry.th32ProcessID, entry.szExeFile,
GetLastError())
);
gotEntry = nextProcessEntry(snapshot, &entry);
continue;
} else {
// only pay attention to processes in the active session
if (processSessionId == m_activeSessionId) {
// store the names so we can record them for debug
nameList.push_back(entry.szExeFile);
if (_stricmp(entry.szExeFile, name) == 0) {
pid = entry.th32ProcessID;
}
}
}
}
// now move on to the next entry (if we're not at the end)
gotEntry = nextProcessEntry(snapshot, &entry);
}
std::string nameListJoin;
for (std::list<std::string>::iterator it = nameList.begin(); it != nameList.end(); it++) {
nameListJoin.append(*it);
nameListJoin.append(", ");
}
LOG((CLOG_DEBUG2 "processes in session %d: %s", m_activeSessionId, nameListJoin.c_str()));
CloseHandle(snapshot);
if (pid) {
if (process != NULL) {
// now get the process, which we'll use to get the process token.
LOG((CLOG_DEBUG "found %s in session %i", name, m_activeSessionId));
*process = OpenProcess(MAXIMUM_ALLOWED, FALSE, pid);
}
return true;
} else {
LOG((CLOG_DEBUG "did not find %s in session %i", name, m_activeSessionId));
return false;
}
}
HANDLE
MSWindowsSession::getUserToken(LPSECURITY_ATTRIBUTES security)
{
HANDLE sourceToken;
if (!WTSQueryUserToken(m_activeSessionId, &sourceToken)) {
LOG((CLOG_ERR "could not get token from session %d", m_activeSessionId));
throw XArch(new XArchEvalWindows);
}
HANDLE newToken;
if (!DuplicateTokenEx(
sourceToken, TOKEN_ASSIGN_PRIMARY | TOKEN_ALL_ACCESS, security, SecurityImpersonation, TokenPrimary, &newToken
)) {
LOG((CLOG_ERR "could not duplicate token"));
throw XArch(new XArchEvalWindows);
}
LOG((CLOG_DEBUG "duplicated, new token: %i", newToken));
return newToken;
}
BOOL MSWindowsSession::hasChanged()
{
return (m_activeSessionId != WTSGetActiveConsoleSessionId());
}
void MSWindowsSession::updateActiveSession()
{
m_activeSessionId = WTSGetActiveConsoleSessionId();
}
BOOL MSWindowsSession::nextProcessEntry(HANDLE snapshot, LPPROCESSENTRY32 entry)
{
// TODO: issue S3-2021
// resetting the error state here is acceptable, but having to do so indicates
// that a different win32 function call has failed beforehand. we should
// always check for errors after each win32 function call.
SetLastError(0);
BOOL gotEntry = Process32Next(snapshot, entry);
if (!gotEntry) {
DWORD err = GetLastError();
// only throw if it's not the end of the snapshot, if not the 'no more
// files' error then it's probably something serious.
if (err != ERROR_NO_MORE_FILES) {
LOG((CLOG_ERR "could not get next process entry"));
throw XArch(new XArchEvalWindows());
}
}
return gotEntry;
}
String MSWindowsSession::getActiveDesktopName()
{
String result;
try {
HDESK hd = OpenInputDesktop(0, TRUE, GENERIC_READ);
if (hd != NULL) {
DWORD size;
GetUserObjectInformation(hd, UOI_NAME, NULL, 0, &size);
TCHAR *name = (TCHAR *)alloca(size + sizeof(TCHAR));
GetUserObjectInformation(hd, UOI_NAME, name, size, &size);
result = name;
CloseDesktop(hd);
}
} catch (std::exception &error) {
LOG((CLOG_ERR "failed to get active desktop name: %s", error.what()));
}
return result;
}
| 5,739
|
C++
|
.cpp
| 158
| 32.012658
| 120
| 0.700793
|
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,572
|
XWindowsClipboardUCS2Converter.cpp
|
deskflow_deskflow/src/lib/platform/XWindowsClipboardUCS2Converter.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 "platform/XWindowsClipboardUCS2Converter.h"
#include "base/Unicode.h"
//
// XWindowsClipboardUCS2Converter
//
XWindowsClipboardUCS2Converter::XWindowsClipboardUCS2Converter(Display *display, const char *name)
: m_atom(XInternAtom(display, name, False))
{
// do nothing
}
XWindowsClipboardUCS2Converter::~XWindowsClipboardUCS2Converter()
{
// do nothing
}
IClipboard::EFormat XWindowsClipboardUCS2Converter::getFormat() const
{
return IClipboard::kText;
}
Atom XWindowsClipboardUCS2Converter::getAtom() const
{
return m_atom;
}
int XWindowsClipboardUCS2Converter::getDataSize() const
{
return 16;
}
String XWindowsClipboardUCS2Converter::fromIClipboard(const String &data) const
{
return Unicode::UTF8ToUCS2(data);
}
String XWindowsClipboardUCS2Converter::toIClipboard(const String &data) const
{
return Unicode::UCS2ToUTF8(data);
}
| 1,599
|
C++
|
.cpp
| 51
| 29.490196
| 98
| 0.794538
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| true
| false
| false
| true
| false
| false
|
13,573
|
OSXClipboardUTF8Converter.cpp
|
deskflow_deskflow/src/lib/platform/OSXClipboardUTF8Converter.cpp
|
#include "OSXClipboardUTF8Converter.h"
CFStringRef OSXClipboardUTF8Converter::getOSXFormat() const
{
return CFSTR("public.utf8-plain-text");
}
String OSXClipboardUTF8Converter::doFromIClipboard(const String &data) const
{
return data;
}
String OSXClipboardUTF8Converter::doToIClipboard(const String &data) const
{
return data;
}
| 338
|
C++
|
.cpp
| 13
| 24.307692
| 76
| 0.832298
|
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,574
|
OSXClipboardHTMLConverter.cpp
|
deskflow_deskflow/src/lib/platform/OSXClipboardHTMLConverter.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2014-2016 Symless Ltd.
* Patch by Ryan Chapman
*
* 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/OSXClipboardHTMLConverter.h"
#include "base/Unicode.h"
OSXClipboardHTMLConverter::OSXClipboardHTMLConverter()
{
// do nothing
}
OSXClipboardHTMLConverter::~OSXClipboardHTMLConverter()
{
// do nothing
}
IClipboard::EFormat OSXClipboardHTMLConverter::getFormat() const
{
return IClipboard::kHTML;
}
CFStringRef OSXClipboardHTMLConverter::getOSXFormat() const
{
return CFSTR("public.html");
}
String
OSXClipboardHTMLConverter::convertString(const String &data, CFStringEncoding fromEncoding, CFStringEncoding toEncoding)
{
CFStringRef stringRef = CFStringCreateWithCString(kCFAllocatorDefault, data.c_str(), fromEncoding);
if (stringRef == NULL) {
return String();
}
CFIndex buffSize;
CFRange entireString = CFRangeMake(0, CFStringGetLength(stringRef));
CFStringGetBytes(stringRef, entireString, toEncoding, 0, false, NULL, 0, &buffSize);
char *buffer = new char[buffSize];
if (buffer == NULL) {
CFRelease(stringRef);
return String();
}
CFStringGetBytes(stringRef, entireString, toEncoding, 0, false, (UInt8 *)buffer, buffSize, NULL);
String result(buffer, buffSize);
delete[] buffer;
CFRelease(stringRef);
return result;
}
String OSXClipboardHTMLConverter::doFromIClipboard(const String &data) const
{
return data;
}
String OSXClipboardHTMLConverter::doToIClipboard(const String &data) const
{
if (Unicode::isUTF8(data)) {
return data;
} else {
return convertString(data, CFStringGetSystemEncoding(), kCFStringEncodingUTF8);
}
}
| 2,244
|
C++
|
.cpp
| 68
| 30.558824
| 120
| 0.777108
|
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,575
|
MSWindowsKeyState.cpp
|
deskflow_deskflow/src/lib/platform/MSWindowsKeyState.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 "platform/MSWindowsKeyState.h"
#include "arch/win32/ArchMiscWindows.h"
#include "base/FunctionJob.h"
#include "base/IEventQueue.h"
#include "base/Log.h"
#include "base/String.h"
#include "base/TMethodEventJob.h"
#include "mt/Thread.h"
#include "platform/MSWindowsDesks.h"
// extended mouse buttons
#if !defined(VK_XBUTTON1)
#define VK_XBUTTON1 0x05
#define VK_XBUTTON2 0x06
#endif
//
// MSWindowsKeyState
//
// map virtual keys to deskflow key enumeration
const KeyID MSWindowsKeyState::s_virtualKey[] = {
/* 0x000 */ {kKeyNone}, // reserved
/* 0x001 */ {kKeyNone}, // VK_LBUTTON
/* 0x002 */ {kKeyNone}, // VK_RBUTTON
/* 0x003 */ {kKeyNone}, // VK_CANCEL
/* 0x004 */ {kKeyNone}, // VK_MBUTTON
/* 0x005 */ {kKeyNone}, // VK_XBUTTON1
/* 0x006 */ {kKeyNone}, // VK_XBUTTON2
/* 0x007 */ {kKeyNone}, // undefined
/* 0x008 */ {kKeyBackSpace}, // VK_BACK
/* 0x009 */ {kKeyTab}, // VK_TAB
/* 0x00a */ {kKeyNone}, // undefined
/* 0x00b */ {kKeyNone}, // undefined
/* 0x00c */ {kKeyClear}, // VK_CLEAR
/* 0x00d */ {kKeyReturn}, // VK_RETURN
/* 0x00e */ {kKeyNone}, // undefined
/* 0x00f */ {kKeyNone}, // undefined
/* 0x010 */ {kKeyShift_L}, // VK_SHIFT
/* 0x011 */ {kKeyControl_L}, // VK_CONTROL
/* 0x012 */ {kKeyAlt_L}, // VK_MENU
/* 0x013 */ {kKeyPause}, // VK_PAUSE
/* 0x014 */ {kKeyCapsLock}, // VK_CAPITAL
/* 0x015 */ {kKeyKana}, // VK_HANGUL, VK_KANA
/* 0x016 */ {kKeyNone}, // undefined
/* 0x017 */ {kKeyNone}, // VK_JUNJA
/* 0x018 */ {kKeyNone}, // VK_FINAL
/* 0x019 */ {kKeyKanzi}, // VK_HANJA, VK_KANJI
/* 0x01a */ {kKeyNone}, // undefined
/* 0x01b */ {kKeyEscape}, // VK_ESCAPE
/* 0x01c */ {kKeyHenkan}, // VK_CONVERT
/* 0x01d */ {kKeyNone}, // VK_NONCONVERT
/* 0x01e */ {kKeyNone}, // VK_ACCEPT
/* 0x01f */ {kKeyNone}, // VK_MODECHANGE
/* 0x020 */ {kKeyNone}, // VK_SPACE
/* 0x021 */ {kKeyKP_PageUp}, // VK_PRIOR
/* 0x022 */ {kKeyKP_PageDown}, // VK_NEXT
/* 0x023 */ {kKeyKP_End}, // VK_END
/* 0x024 */ {kKeyKP_Home}, // VK_HOME
/* 0x025 */ {kKeyKP_Left}, // VK_LEFT
/* 0x026 */ {kKeyKP_Up}, // VK_UP
/* 0x027 */ {kKeyKP_Right}, // VK_RIGHT
/* 0x028 */ {kKeyKP_Down}, // VK_DOWN
/* 0x029 */ {kKeySelect}, // VK_SELECT
/* 0x02a */ {kKeyNone}, // VK_PRINT
/* 0x02b */ {kKeyExecute}, // VK_EXECUTE
/* 0x02c */ {kKeyPrint}, // VK_SNAPSHOT
/* 0x02d */ {kKeyKP_Insert}, // VK_INSERT
/* 0x02e */ {kKeyKP_Delete}, // VK_DELETE
/* 0x02f */ {kKeyHelp}, // VK_HELP
/* 0x030 */ {kKeyNone}, // VK_0
/* 0x031 */ {kKeyNone}, // VK_1
/* 0x032 */ {kKeyNone}, // VK_2
/* 0x033 */ {kKeyNone}, // VK_3
/* 0x034 */ {kKeyNone}, // VK_4
/* 0x035 */ {kKeyNone}, // VK_5
/* 0x036 */ {kKeyNone}, // VK_6
/* 0x037 */ {kKeyNone}, // VK_7
/* 0x038 */ {kKeyNone}, // VK_8
/* 0x039 */ {kKeyNone}, // VK_9
/* 0x03a */ {kKeyNone}, // undefined
/* 0x03b */ {kKeyNone}, // undefined
/* 0x03c */ {kKeyNone}, // undefined
/* 0x03d */ {kKeyNone}, // undefined
/* 0x03e */ {kKeyNone}, // undefined
/* 0x03f */ {kKeyNone}, // undefined
/* 0x040 */ {kKeyNone}, // undefined
/* 0x041 */ {kKeyNone}, // VK_A
/* 0x042 */ {kKeyNone}, // VK_B
/* 0x043 */ {kKeyNone}, // VK_C
/* 0x044 */ {kKeyNone}, // VK_D
/* 0x045 */ {kKeyNone}, // VK_E
/* 0x046 */ {kKeyNone}, // VK_F
/* 0x047 */ {kKeyNone}, // VK_G
/* 0x048 */ {kKeyNone}, // VK_H
/* 0x049 */ {kKeyNone}, // VK_I
/* 0x04a */ {kKeyNone}, // VK_J
/* 0x04b */ {kKeyNone}, // VK_K
/* 0x04c */ {kKeyNone}, // VK_L
/* 0x04d */ {kKeyNone}, // VK_M
/* 0x04e */ {kKeyNone}, // VK_N
/* 0x04f */ {kKeyNone}, // VK_O
/* 0x050 */ {kKeyNone}, // VK_P
/* 0x051 */ {kKeyNone}, // VK_Q
/* 0x052 */ {kKeyNone}, // VK_R
/* 0x053 */ {kKeyNone}, // VK_S
/* 0x054 */ {kKeyNone}, // VK_T
/* 0x055 */ {kKeyNone}, // VK_U
/* 0x056 */ {kKeyNone}, // VK_V
/* 0x057 */ {kKeyNone}, // VK_W
/* 0x058 */ {kKeyNone}, // VK_X
/* 0x059 */ {kKeyNone}, // VK_Y
/* 0x05a */ {kKeyNone}, // VK_Z
/* 0x05b */ {kKeySuper_L}, // VK_LWIN
/* 0x05c */ {kKeySuper_R}, // VK_RWIN
/* 0x05d */ {kKeyMenu}, // VK_APPS
/* 0x05e */ {kKeyNone}, // undefined
/* 0x05f */ {kKeySleep}, // VK_SLEEP
/* 0x060 */ {kKeyKP_0}, // VK_NUMPAD0
/* 0x061 */ {kKeyKP_1}, // VK_NUMPAD1
/* 0x062 */ {kKeyKP_2}, // VK_NUMPAD2
/* 0x063 */ {kKeyKP_3}, // VK_NUMPAD3
/* 0x064 */ {kKeyKP_4}, // VK_NUMPAD4
/* 0x065 */ {kKeyKP_5}, // VK_NUMPAD5
/* 0x066 */ {kKeyKP_6}, // VK_NUMPAD6
/* 0x067 */ {kKeyKP_7}, // VK_NUMPAD7
/* 0x068 */ {kKeyKP_8}, // VK_NUMPAD8
/* 0x069 */ {kKeyKP_9}, // VK_NUMPAD9
/* 0x06a */ {kKeyKP_Multiply}, // VK_MULTIPLY
/* 0x06b */ {kKeyKP_Add}, // VK_ADD
/* 0x06c */ {kKeyKP_Separator}, // VK_SEPARATOR
/* 0x06d */ {kKeyKP_Subtract}, // VK_SUBTRACT
/* 0x06e */ {kKeyKP_Decimal}, // VK_DECIMAL
/* 0x06f */ {kKeyNone}, // VK_DIVIDE
/* 0x070 */ {kKeyF1}, // VK_F1
/* 0x071 */ {kKeyF2}, // VK_F2
/* 0x072 */ {kKeyF3}, // VK_F3
/* 0x073 */ {kKeyF4}, // VK_F4
/* 0x074 */ {kKeyF5}, // VK_F5
/* 0x075 */ {kKeyF6}, // VK_F6
/* 0x076 */ {kKeyF7}, // VK_F7
/* 0x077 */ {kKeyF8}, // VK_F8
/* 0x078 */ {kKeyF9}, // VK_F9
/* 0x079 */ {kKeyF10}, // VK_F10
/* 0x07a */ {kKeyF11}, // VK_F11
/* 0x07b */ {kKeyF12}, // VK_F12
/* 0x07c */ {kKeyF13}, // VK_F13
/* 0x07d */ {kKeyF14}, // VK_F14
/* 0x07e */ {kKeyF15}, // VK_F15
/* 0x07f */ {kKeyF16}, // VK_F16
/* 0x080 */ {kKeyF17}, // VK_F17
/* 0x081 */ {kKeyF18}, // VK_F18
/* 0x082 */ {kKeyF19}, // VK_F19
/* 0x083 */ {kKeyF20}, // VK_F20
/* 0x084 */ {kKeyF21}, // VK_F21
/* 0x085 */ {kKeyF22}, // VK_F22
/* 0x086 */ {kKeyF23}, // VK_F23
/* 0x087 */ {kKeyF24}, // VK_F24
/* 0x088 */ {kKeyNone}, // unassigned
/* 0x089 */ {kKeyNone}, // unassigned
/* 0x08a */ {kKeyNone}, // unassigned
/* 0x08b */ {kKeyNone}, // unassigned
/* 0x08c */ {kKeyNone}, // unassigned
/* 0x08d */ {kKeyNone}, // unassigned
/* 0x08e */ {kKeyNone}, // unassigned
/* 0x08f */ {kKeyNone}, // unassigned
/* 0x090 */ {kKeyNumLock}, // VK_NUMLOCK
/* 0x091 */ {kKeyScrollLock}, // VK_SCROLL
/* 0x092 */ {kKeyNone}, // unassigned
/* 0x093 */ {kKeyNone}, // unassigned
/* 0x094 */ {kKeyNone}, // unassigned
/* 0x095 */ {kKeyNone}, // unassigned
/* 0x096 */ {kKeyNone}, // unassigned
/* 0x097 */ {kKeyNone}, // unassigned
/* 0x098 */ {kKeyNone}, // unassigned
/* 0x099 */ {kKeyNone}, // unassigned
/* 0x09a */ {kKeyNone}, // unassigned
/* 0x09b */ {kKeyNone}, // unassigned
/* 0x09c */ {kKeyNone}, // unassigned
/* 0x09d */ {kKeyNone}, // unassigned
/* 0x09e */ {kKeyNone}, // unassigned
/* 0x09f */ {kKeyNone}, // unassigned
/* 0x0a0 */ {kKeyShift_L}, // VK_LSHIFT
/* 0x0a1 */ {kKeyShift_R}, // VK_RSHIFT
/* 0x0a2 */ {kKeyControl_L}, // VK_LCONTROL
/* 0x0a3 */ {kKeyControl_R}, // VK_RCONTROL
/* 0x0a4 */ {kKeyAlt_L}, // VK_LMENU
/* 0x0a5 */ {kKeyAlt_R}, // VK_RMENU
/* 0x0a6 */ {kKeyNone}, // VK_BROWSER_BACK
/* 0x0a7 */ {kKeyNone}, // VK_BROWSER_FORWARD
/* 0x0a8 */ {kKeyNone}, // VK_BROWSER_REFRESH
/* 0x0a9 */ {kKeyNone}, // VK_BROWSER_STOP
/* 0x0aa */ {kKeyNone}, // VK_BROWSER_SEARCH
/* 0x0ab */ {kKeyNone}, // VK_BROWSER_FAVORITES
/* 0x0ac */ {kKeyNone}, // VK_BROWSER_HOME
/* 0x0ad */ {kKeyNone}, // VK_VOLUME_MUTE
/* 0x0ae */ {kKeyNone}, // VK_VOLUME_DOWN
/* 0x0af */ {kKeyNone}, // VK_VOLUME_UP
/* 0x0b0 */ {kKeyNone}, // VK_MEDIA_NEXT_TRACK
/* 0x0b1 */ {kKeyNone}, // VK_MEDIA_PREV_TRACK
/* 0x0b2 */ {kKeyNone}, // VK_MEDIA_STOP
/* 0x0b3 */ {kKeyNone}, // VK_MEDIA_PLAY_PAUSE
/* 0x0b4 */ {kKeyNone}, // VK_LAUNCH_MAIL
/* 0x0b5 */ {kKeyNone}, // VK_LAUNCH_MEDIA_SELECT
/* 0x0b6 */ {kKeyNone}, // VK_LAUNCH_APP1
/* 0x0b7 */ {kKeyNone}, // VK_LAUNCH_APP2
/* 0x0b8 */ {kKeyNone}, // unassigned
/* 0x0b9 */ {kKeyNone}, // unassigned
/* 0x0ba */ {kKeyNone}, // OEM specific
/* 0x0bb */ {kKeyNone}, // OEM specific
/* 0x0bc */ {kKeyNone}, // OEM specific
/* 0x0bd */ {kKeyNone}, // OEM specific
/* 0x0be */ {kKeyNone}, // OEM specific
/* 0x0bf */ {kKeyNone}, // OEM specific
/* 0x0c0 */ {kKeyNone}, // OEM specific
/* 0x0c1 */ {kKeyNone}, // unassigned
/* 0x0c2 */ {kKeyNone}, // unassigned
/* 0x0c3 */ {kKeyNone}, // unassigned
/* 0x0c4 */ {kKeyNone}, // unassigned
/* 0x0c5 */ {kKeyNone}, // unassigned
/* 0x0c6 */ {kKeyNone}, // unassigned
/* 0x0c7 */ {kKeyNone}, // unassigned
/* 0x0c8 */ {kKeyNone}, // unassigned
/* 0x0c9 */ {kKeyNone}, // unassigned
/* 0x0ca */ {kKeyNone}, // unassigned
/* 0x0cb */ {kKeyNone}, // unassigned
/* 0x0cc */ {kKeyNone}, // unassigned
/* 0x0cd */ {kKeyNone}, // unassigned
/* 0x0ce */ {kKeyNone}, // unassigned
/* 0x0cf */ {kKeyNone}, // unassigned
/* 0x0d0 */ {kKeyNone}, // unassigned
/* 0x0d1 */ {kKeyNone}, // unassigned
/* 0x0d2 */ {kKeyNone}, // unassigned
/* 0x0d3 */ {kKeyNone}, // unassigned
/* 0x0d4 */ {kKeyNone}, // unassigned
/* 0x0d5 */ {kKeyNone}, // unassigned
/* 0x0d6 */ {kKeyNone}, // unassigned
/* 0x0d7 */ {kKeyNone}, // unassigned
/* 0x0d8 */ {kKeyNone}, // unassigned
/* 0x0d9 */ {kKeyNone}, // unassigned
/* 0x0da */ {kKeyNone}, // unassigned
/* 0x0db */ {kKeyNone}, // OEM specific
/* 0x0dc */ {kKeyNone}, // OEM specific
/* 0x0dd */ {kKeyNone}, // OEM specific
/* 0x0de */ {kKeyNone}, // OEM specific
/* 0x0df */ {kKeyNone}, // OEM specific
/* 0x0e0 */ {kKeyNone}, // OEM specific
/* 0x0e1 */ {kKeyNone}, // OEM specific
/* 0x0e2 */ {kKeyNone}, // OEM specific
/* 0x0e3 */ {kKeyNone}, // OEM specific
/* 0x0e4 */ {kKeyNone}, // OEM specific
/* 0x0e5 */ {kKeyNone}, // unassigned
/* 0x0e6 */ {kKeyNone}, // OEM specific
/* 0x0e7 */ {kKeyNone}, // unassigned
/* 0x0e8 */ {kKeyNone}, // unassigned
/* 0x0e9 */ {kKeyNone}, // OEM specific
/* 0x0ea */ {kKeyNone}, // OEM specific
/* 0x0eb */ {kKeyNone}, // OEM specific
/* 0x0ec */ {kKeyNone}, // OEM specific
/* 0x0ed */ {kKeyNone}, // OEM specific
/* 0x0ee */ {kKeyNone}, // OEM specific
/* 0x0ef */ {kKeyNone}, // OEM specific
/* 0x0f0 */ {kKeyNone}, // OEM specific
/* 0x0f1 */ {kKeyNone}, // OEM specific
/* 0x0f2 */ {kKeyHiraganaKatakana}, // VK_OEM_COPY
/* 0x0f3 */ {kKeyZenkaku}, // VK_OEM_AUTO
/* 0x0f4 */ {kKeyZenkaku}, // VK_OEM_ENLW
/* 0x0f5 */ {kKeyNone}, // OEM specific
/* 0x0f6 */ {kKeyNone}, // VK_ATTN
/* 0x0f7 */ {kKeyNone}, // VK_CRSEL
/* 0x0f8 */ {kKeyNone}, // VK_EXSEL
/* 0x0f9 */ {kKeyNone}, // VK_EREOF
/* 0x0fa */ {kKeyNone}, // VK_PLAY
/* 0x0fb */ {kKeyNone}, // VK_ZOOM
/* 0x0fc */ {kKeyNone}, // reserved
/* 0x0fd */ {kKeyNone}, // VK_PA1
/* 0x0fe */ {kKeyNone}, // VK_OEM_CLEAR
/* 0x0ff */ {kKeyNone}, // reserved
/* 0x100 */ {kKeyNone}, // reserved
/* 0x101 */ {kKeyNone}, // VK_LBUTTON
/* 0x102 */ {kKeyNone}, // VK_RBUTTON
/* 0x103 */ {kKeyBreak}, // VK_CANCEL
/* 0x104 */ {kKeyNone}, // VK_MBUTTON
/* 0x105 */ {kKeyNone}, // VK_XBUTTON1
/* 0x106 */ {kKeyNone}, // VK_XBUTTON2
/* 0x107 */ {kKeyNone}, // undefined
/* 0x108 */ {kKeyNone}, // VK_BACK
/* 0x109 */ {kKeyNone}, // VK_TAB
/* 0x10a */ {kKeyNone}, // undefined
/* 0x10b */ {kKeyNone}, // undefined
/* 0x10c */ {kKeyClear}, // VK_CLEAR
/* 0x10d */ {kKeyKP_Enter}, // VK_RETURN
/* 0x10e */ {kKeyNone}, // undefined
/* 0x10f */ {kKeyNone}, // undefined
/* 0x110 */ {kKeyShift_R}, // VK_SHIFT
/* 0x111 */ {kKeyControl_R}, // VK_CONTROL
/* 0x112 */ {kKeyAlt_R}, // VK_MENU
/* 0x113 */ {kKeyNone}, // VK_PAUSE
/* 0x114 */ {kKeyNone}, // VK_CAPITAL
/* 0x115 */ {kKeyHangul}, // VK_HANGUL
/* 0x116 */ {kKeyNone}, // undefined
/* 0x117 */ {kKeyNone}, // VK_JUNJA
/* 0x118 */ {kKeyNone}, // VK_FINAL
/* 0x119 */ {kKeyHanja}, // VK_HANJA
/* 0x11a */ {kKeyNone}, // undefined
/* 0x11b */ {kKeyNone}, // VK_ESCAPE
/* 0x11c */ {kKeyNone}, // VK_CONVERT
/* 0x11d */ {kKeyNone}, // VK_NONCONVERT
/* 0x11e */ {kKeyNone}, // VK_ACCEPT
/* 0x11f */ {kKeyNone}, // VK_MODECHANGE
/* 0x120 */ {kKeyNone}, // VK_SPACE
/* 0x121 */ {kKeyPageUp}, // VK_PRIOR
/* 0x122 */ {kKeyPageDown}, // VK_NEXT
/* 0x123 */ {kKeyEnd}, // VK_END
/* 0x124 */ {kKeyHome}, // VK_HOME
/* 0x125 */ {kKeyLeft}, // VK_LEFT
/* 0x126 */ {kKeyUp}, // VK_UP
/* 0x127 */ {kKeyRight}, // VK_RIGHT
/* 0x128 */ {kKeyDown}, // VK_DOWN
/* 0x129 */ {kKeySelect}, // VK_SELECT
/* 0x12a */ {kKeyNone}, // VK_PRINT
/* 0x12b */ {kKeyExecute}, // VK_EXECUTE
/* 0x12c */ {kKeyPrint}, // VK_SNAPSHOT
/* 0x12d */ {kKeyInsert}, // VK_INSERT
/* 0x12e */ {kKeyDelete}, // VK_DELETE
/* 0x12f */ {kKeyHelp}, // VK_HELP
/* 0x130 */ {kKeyNone}, // VK_0
/* 0x131 */ {kKeyNone}, // VK_1
/* 0x132 */ {kKeyNone}, // VK_2
/* 0x133 */ {kKeyNone}, // VK_3
/* 0x134 */ {kKeyNone}, // VK_4
/* 0x135 */ {kKeyNone}, // VK_5
/* 0x136 */ {kKeyNone}, // VK_6
/* 0x137 */ {kKeyNone}, // VK_7
/* 0x138 */ {kKeyNone}, // VK_8
/* 0x139 */ {kKeyNone}, // VK_9
/* 0x13a */ {kKeyNone}, // undefined
/* 0x13b */ {kKeyNone}, // undefined
/* 0x13c */ {kKeyNone}, // undefined
/* 0x13d */ {kKeyNone}, // undefined
/* 0x13e */ {kKeyNone}, // undefined
/* 0x13f */ {kKeyNone}, // undefined
/* 0x140 */ {kKeyNone}, // undefined
/* 0x141 */ {kKeyNone}, // VK_A
/* 0x142 */ {kKeyNone}, // VK_B
/* 0x143 */ {kKeyNone}, // VK_C
/* 0x144 */ {kKeyNone}, // VK_D
/* 0x145 */ {kKeyNone}, // VK_E
/* 0x146 */ {kKeyNone}, // VK_F
/* 0x147 */ {kKeyNone}, // VK_G
/* 0x148 */ {kKeyNone}, // VK_H
/* 0x149 */ {kKeyNone}, // VK_I
/* 0x14a */ {kKeyNone}, // VK_J
/* 0x14b */ {kKeyNone}, // VK_K
/* 0x14c */ {kKeyNone}, // VK_L
/* 0x14d */ {kKeyNone}, // VK_M
/* 0x14e */ {kKeyNone}, // VK_N
/* 0x14f */ {kKeyNone}, // VK_O
/* 0x150 */ {kKeyNone}, // VK_P
/* 0x151 */ {kKeyNone}, // VK_Q
/* 0x152 */ {kKeyNone}, // VK_R
/* 0x153 */ {kKeyNone}, // VK_S
/* 0x154 */ {kKeyNone}, // VK_T
/* 0x155 */ {kKeyNone}, // VK_U
/* 0x156 */ {kKeyNone}, // VK_V
/* 0x157 */ {kKeyNone}, // VK_W
/* 0x158 */ {kKeyNone}, // VK_X
/* 0x159 */ {kKeyNone}, // VK_Y
/* 0x15a */ {kKeyNone}, // VK_Z
/* 0x15b */ {kKeySuper_L}, // VK_LWIN
/* 0x15c */ {kKeySuper_R}, // VK_RWIN
/* 0x15d */ {kKeyMenu}, // VK_APPS
/* 0x15e */ {kKeyNone}, // undefined
/* 0x15f */ {kKeyNone}, // VK_SLEEP
/* 0x160 */ {kKeyNone}, // VK_NUMPAD0
/* 0x161 */ {kKeyNone}, // VK_NUMPAD1
/* 0x162 */ {kKeyNone}, // VK_NUMPAD2
/* 0x163 */ {kKeyNone}, // VK_NUMPAD3
/* 0x164 */ {kKeyNone}, // VK_NUMPAD4
/* 0x165 */ {kKeyNone}, // VK_NUMPAD5
/* 0x166 */ {kKeyNone}, // VK_NUMPAD6
/* 0x167 */ {kKeyNone}, // VK_NUMPAD7
/* 0x168 */ {kKeyNone}, // VK_NUMPAD8
/* 0x169 */ {kKeyNone}, // VK_NUMPAD9
/* 0x16a */ {kKeyNone}, // VK_MULTIPLY
/* 0x16b */ {kKeyNone}, // VK_ADD
/* 0x16c */ {kKeyKP_Separator}, // VK_SEPARATOR
/* 0x16d */ {kKeyNone}, // VK_SUBTRACT
/* 0x16e */ {kKeyNone}, // VK_DECIMAL
/* 0x16f */ {kKeyKP_Divide}, // VK_DIVIDE
/* 0x170 */ {kKeyNone}, // VK_F1
/* 0x171 */ {kKeyNone}, // VK_F2
/* 0x172 */ {kKeyNone}, // VK_F3
/* 0x173 */ {kKeyNone}, // VK_F4
/* 0x174 */ {kKeyNone}, // VK_F5
/* 0x175 */ {kKeyNone}, // VK_F6
/* 0x176 */ {kKeyNone}, // VK_F7
/* 0x177 */ {kKeyNone}, // VK_F8
/* 0x178 */ {kKeyNone}, // VK_F9
/* 0x179 */ {kKeyNone}, // VK_F10
/* 0x17a */ {kKeyNone}, // VK_F11
/* 0x17b */ {kKeyNone}, // VK_F12
/* 0x17c */ {kKeyF13}, // VK_F13
/* 0x17d */ {kKeyF14}, // VK_F14
/* 0x17e */ {kKeyF15}, // VK_F15
/* 0x17f */ {kKeyF16}, // VK_F16
/* 0x180 */ {kKeyF17}, // VK_F17
/* 0x181 */ {kKeyF18}, // VK_F18
/* 0x182 */ {kKeyF19}, // VK_F19
/* 0x183 */ {kKeyF20}, // VK_F20
/* 0x184 */ {kKeyF21}, // VK_F21
/* 0x185 */ {kKeyF22}, // VK_F22
/* 0x186 */ {kKeyF23}, // VK_F23
/* 0x187 */ {kKeyF24}, // VK_F24
/* 0x188 */ {kKeyNone}, // unassigned
/* 0x189 */ {kKeyNone}, // unassigned
/* 0x18a */ {kKeyNone}, // unassigned
/* 0x18b */ {kKeyNone}, // unassigned
/* 0x18c */ {kKeyNone}, // unassigned
/* 0x18d */ {kKeyNone}, // unassigned
/* 0x18e */ {kKeyNone}, // unassigned
/* 0x18f */ {kKeyNone}, // unassigned
/* 0x190 */ {kKeyNumLock}, // VK_NUMLOCK
/* 0x191 */ {kKeyNone}, // VK_SCROLL
/* 0x192 */ {kKeyNone}, // unassigned
/* 0x193 */ {kKeyNone}, // unassigned
/* 0x194 */ {kKeyNone}, // unassigned
/* 0x195 */ {kKeyNone}, // unassigned
/* 0x196 */ {kKeyNone}, // unassigned
/* 0x197 */ {kKeyNone}, // unassigned
/* 0x198 */ {kKeyNone}, // unassigned
/* 0x199 */ {kKeyNone}, // unassigned
/* 0x19a */ {kKeyNone}, // unassigned
/* 0x19b */ {kKeyNone}, // unassigned
/* 0x19c */ {kKeyNone}, // unassigned
/* 0x19d */ {kKeyNone}, // unassigned
/* 0x19e */ {kKeyNone}, // unassigned
/* 0x19f */ {kKeyNone}, // unassigned
/* 0x1a0 */ {kKeyShift_L}, // VK_LSHIFT
/* 0x1a1 */ {kKeyShift_R}, // VK_RSHIFT
/* 0x1a2 */ {kKeyControl_L}, // VK_LCONTROL
/* 0x1a3 */ {kKeyControl_R}, // VK_RCONTROL
/* 0x1a4 */ {kKeyAlt_L}, // VK_LMENU
/* 0x1a5 */ {kKeyAlt_R}, // VK_RMENU
/* 0x1a6 */ {kKeyWWWBack}, // VK_BROWSER_BACK
/* 0x1a7 */ {kKeyWWWForward}, // VK_BROWSER_FORWARD
/* 0x1a8 */ {kKeyWWWRefresh}, // VK_BROWSER_REFRESH
/* 0x1a9 */ {kKeyWWWStop}, // VK_BROWSER_STOP
/* 0x1aa */ {kKeyWWWSearch}, // VK_BROWSER_SEARCH
/* 0x1ab */ {kKeyWWWFavorites}, // VK_BROWSER_FAVORITES
/* 0x1ac */ {kKeyWWWHome}, // VK_BROWSER_HOME
/* 0x1ad */ {kKeyAudioMute}, // VK_VOLUME_MUTE
/* 0x1ae */ {kKeyAudioDown}, // VK_VOLUME_DOWN
/* 0x1af */ {kKeyAudioUp}, // VK_VOLUME_UP
/* 0x1b0 */ {kKeyAudioNext}, // VK_MEDIA_NEXT_TRACK
/* 0x1b1 */ {kKeyAudioPrev}, // VK_MEDIA_PREV_TRACK
/* 0x1b2 */ {kKeyAudioStop}, // VK_MEDIA_STOP
/* 0x1b3 */ {kKeyAudioPlay}, // VK_MEDIA_PLAY_PAUSE
/* 0x1b4 */ {kKeyAppMail}, // VK_LAUNCH_MAIL
/* 0x1b5 */ {kKeyAppMedia}, // VK_LAUNCH_MEDIA_SELECT
/* 0x1b6 */ {kKeyAppUser1}, // VK_LAUNCH_APP1
/* 0x1b7 */ {kKeyAppUser2}, // VK_LAUNCH_APP2
/* 0x1b8 */ {kKeyNone}, // unassigned
/* 0x1b9 */ {kKeyNone}, // unassigned
/* 0x1ba */ {kKeyNone}, // OEM specific
/* 0x1bb */ {kKeyNone}, // OEM specific
/* 0x1bc */ {kKeyNone}, // OEM specific
/* 0x1bd */ {kKeyNone}, // OEM specific
/* 0x1be */ {kKeyNone}, // OEM specific
/* 0x1bf */ {kKeyNone}, // OEM specific
/* 0x1c0 */ {kKeyNone}, // OEM specific
/* 0x1c1 */ {kKeyNone}, // unassigned
/* 0x1c2 */ {kKeyNone}, // unassigned
/* 0x1c3 */ {kKeyNone}, // unassigned
/* 0x1c4 */ {kKeyNone}, // unassigned
/* 0x1c5 */ {kKeyNone}, // unassigned
/* 0x1c6 */ {kKeyNone}, // unassigned
/* 0x1c7 */ {kKeyNone}, // unassigned
/* 0x1c8 */ {kKeyNone}, // unassigned
/* 0x1c9 */ {kKeyNone}, // unassigned
/* 0x1ca */ {kKeyNone}, // unassigned
/* 0x1cb */ {kKeyNone}, // unassigned
/* 0x1cc */ {kKeyNone}, // unassigned
/* 0x1cd */ {kKeyNone}, // unassigned
/* 0x1ce */ {kKeyNone}, // unassigned
/* 0x1cf */ {kKeyNone}, // unassigned
/* 0x1d0 */ {kKeyNone}, // unassigned
/* 0x1d1 */ {kKeyNone}, // unassigned
/* 0x1d2 */ {kKeyNone}, // unassigned
/* 0x1d3 */ {kKeyNone}, // unassigned
/* 0x1d4 */ {kKeyNone}, // unassigned
/* 0x1d5 */ {kKeyNone}, // unassigned
/* 0x1d6 */ {kKeyNone}, // unassigned
/* 0x1d7 */ {kKeyNone}, // unassigned
/* 0x1d8 */ {kKeyNone}, // unassigned
/* 0x1d9 */ {kKeyNone}, // unassigned
/* 0x1da */ {kKeyNone}, // unassigned
/* 0x1db */ {kKeyNone}, // OEM specific
/* 0x1dc */ {kKeyNone}, // OEM specific
/* 0x1dd */ {kKeyNone}, // OEM specific
/* 0x1de */ {kKeyNone}, // OEM specific
/* 0x1df */ {kKeyNone}, // OEM specific
/* 0x1e0 */ {kKeyNone}, // OEM specific
/* 0x1e1 */ {kKeyNone}, // OEM specific
/* 0x1e2 */ {kKeyNone}, // OEM specific
/* 0x1e3 */ {kKeyNone}, // OEM specific
/* 0x1e4 */ {kKeyNone}, // OEM specific
/* 0x1e5 */ {kKeyNone}, // unassigned
/* 0x1e6 */ {kKeyNone}, // OEM specific
/* 0x1e7 */ {kKeyNone}, // unassigned
/* 0x1e8 */ {kKeyNone}, // unassigned
/* 0x1e9 */ {kKeyNone}, // OEM specific
/* 0x1ea */ {kKeyNone}, // OEM specific
/* 0x1eb */ {kKeyNone}, // OEM specific
/* 0x1ec */ {kKeyNone}, // OEM specific
/* 0x1ed */ {kKeyNone}, // OEM specific
/* 0x1ee */ {kKeyNone}, // OEM specific
/* 0x1ef */ {kKeyNone}, // OEM specific
/* 0x1f0 */ {kKeyNone}, // OEM specific
/* 0x1f1 */ {kKeyNone}, // OEM specific
/* 0x1f2 */ {kKeyNone}, // VK_OEM_COPY
/* 0x1f3 */ {kKeyNone}, // VK_OEM_AUTO
/* 0x1f4 */ {kKeyNone}, // VK_OEM_ENLW
/* 0x1f5 */ {kKeyNone}, // OEM specific
/* 0x1f6 */ {kKeyNone}, // VK_ATTN
/* 0x1f7 */ {kKeyNone}, // VK_CRSEL
/* 0x1f8 */ {kKeyNone}, // VK_EXSEL
/* 0x1f9 */ {kKeyNone}, // VK_EREOF
/* 0x1fa */ {kKeyNone}, // VK_PLAY
/* 0x1fb */ {kKeyNone}, // VK_ZOOM
/* 0x1fc */ {kKeyNone}, // reserved
/* 0x1fd */ {kKeyNone}, // VK_PA1
/* 0x1fe */ {kKeyNone}, // VK_OEM_CLEAR
/* 0x1ff */ {kKeyNone} // reserved
};
struct Win32Modifiers
{
public:
UINT m_vk;
KeyModifierMask m_mask;
};
static const Win32Modifiers s_modifiers[] = {{VK_SHIFT, KeyModifierShift}, {VK_LSHIFT, KeyModifierShift},
{VK_RSHIFT, KeyModifierShift}, {VK_CONTROL, KeyModifierControl},
{VK_LCONTROL, KeyModifierControl}, {VK_RCONTROL, KeyModifierControl},
{VK_MENU, KeyModifierAlt}, {VK_LMENU, KeyModifierAlt},
{VK_RMENU, KeyModifierAlt}, {VK_LWIN, KeyModifierSuper},
{VK_RWIN, KeyModifierSuper}};
MSWindowsKeyState::MSWindowsKeyState(
MSWindowsDesks *desks, void *eventTarget, IEventQueue *events, std::vector<String> layouts, bool isLangSyncEnabled
)
: KeyState(events, std::move(layouts), isLangSyncEnabled),
m_eventTarget(eventTarget),
m_desks(desks),
m_keyLayout(GetKeyboardLayout(0)),
m_fixTimer(NULL),
m_lastDown(0),
m_useSavedModifiers(false),
m_savedModifiers(0),
m_originalSavedModifiers(0),
m_events(events)
{
init();
}
MSWindowsKeyState::MSWindowsKeyState(
MSWindowsDesks *desks, void *eventTarget, IEventQueue *events, deskflow::KeyMap &keyMap,
std::vector<String> layouts, bool isLangSyncEnabled
)
: KeyState(events, keyMap, std::move(layouts), isLangSyncEnabled),
m_eventTarget(eventTarget),
m_desks(desks),
m_keyLayout(GetKeyboardLayout(0)),
m_fixTimer(NULL),
m_lastDown(0),
m_useSavedModifiers(false),
m_savedModifiers(0),
m_originalSavedModifiers(0),
m_events(events)
{
init();
}
MSWindowsKeyState::~MSWindowsKeyState()
{
disable();
}
void MSWindowsKeyState::init()
{
// look up symbol that's available on winNT family but not win95
HMODULE userModule = GetModuleHandle("user32.dll");
m_ToUnicodeEx = (ToUnicodeEx_t)GetProcAddress(userModule, "ToUnicodeEx");
}
void MSWindowsKeyState::disable()
{
if (m_fixTimer != NULL) {
m_events->removeHandler(Event::kTimer, m_fixTimer);
m_events->deleteTimer(m_fixTimer);
m_fixTimer = NULL;
}
m_lastDown = 0;
}
KeyButton MSWindowsKeyState::virtualKeyToButton(UINT virtualKey) const
{
return m_virtualKeyToButton[virtualKey & 0xffu];
}
void MSWindowsKeyState::setKeyLayout(HKL keyLayout)
{
m_keyLayout = keyLayout;
}
bool MSWindowsKeyState::testAutoRepeat(bool press, bool isRepeat, KeyButton button)
{
if (!isRepeat) {
isRepeat = (press && m_lastDown != 0 && button == m_lastDown);
}
if (press) {
m_lastDown = button;
} else {
m_lastDown = 0;
}
return isRepeat;
}
void MSWindowsKeyState::saveModifiers()
{
m_savedModifiers = getActiveModifiers();
m_originalSavedModifiers = m_savedModifiers;
}
void MSWindowsKeyState::useSavedModifiers(bool enable)
{
if (enable != m_useSavedModifiers) {
m_useSavedModifiers = enable;
if (!m_useSavedModifiers) {
// transfer any modifier state changes to KeyState's state
KeyModifierMask mask = m_originalSavedModifiers ^ m_savedModifiers;
getActiveModifiersRValue() = (getActiveModifiers() & ~mask) | (m_savedModifiers & mask);
}
}
}
KeyID MSWindowsKeyState::mapKeyFromEvent(WPARAM charAndVirtKey, LPARAM info, KeyModifierMask *maskOut) const
{
static const KeyModifierMask s_controlAlt = KeyModifierControl | KeyModifierAlt;
// extract character, virtual key, and if we didn't use AltGr
auto wc = static_cast<WCHAR>((charAndVirtKey & 0xffffu));
UINT vkCode = ((charAndVirtKey >> 16) & 0xffu);
bool noAltGr = ((charAndVirtKey & 0xff000000u) != 0);
// handle some keys via table lookup
KeyID id = getKeyID(vkCode, (KeyButton)((info >> 16) & 0x1ffu));
// check if not in table; map character to key id
if (id == kKeyNone && wc != 0) {
// UTF16
id = static_cast<KeyID>(wc) & 0xffffu;
}
// set modifier mask
if (maskOut != NULL) {
KeyModifierMask active = getActiveModifiers();
if (!noAltGr && (active & s_controlAlt) == s_controlAlt) {
// if !noAltGr then we're only interested in matching the
// key, not the AltGr. AltGr is down (i.e. control and alt
// are down) but we don't want the client to have to match
// that so we clear it.
active &= ~s_controlAlt;
}
if (id == kKeyHangul) {
// If shift-space is used to change input mode, clear shift modifier.
active &= ~KeyModifierShift;
}
*maskOut = active;
}
return id;
}
bool MSWindowsKeyState::didGroupsChange() const
{
GroupList groups;
return (getGroups(groups) && groups != m_groups);
}
UINT MSWindowsKeyState::mapKeyToVirtualKey(KeyID key) const
{
if (key == kKeyNone) {
return 0;
}
KeyToVKMap::const_iterator i = m_keyToVKMap.find(key);
if (i == m_keyToVKMap.end()) {
return 0;
} else {
return i->second;
}
}
void MSWindowsKeyState::onKey(KeyButton button, bool down, KeyModifierMask newState)
{
KeyState::onKey(button, down, newState);
}
void MSWindowsKeyState::sendKeyEvent(
void *target, bool press, bool isAutoRepeat, KeyID key, KeyModifierMask mask, SInt32 count, KeyButton button
)
{
if (press || isAutoRepeat) {
// send key
if (press && !isAutoRepeat) {
KeyState::sendKeyEvent(target, true, false, key, mask, 1, button);
if (count > 0) {
--count;
}
}
if (count >= 1) {
KeyState::sendKeyEvent(target, true, true, key, mask, count, button);
}
} else {
// do key up
KeyState::sendKeyEvent(target, false, false, key, mask, 1, button);
}
}
void MSWindowsKeyState::fakeKeyDown(KeyID id, KeyModifierMask mask, KeyButton button, const String &lang)
{
KeyState::fakeKeyDown(id, mask, button, lang);
}
bool MSWindowsKeyState::fakeKeyRepeat(
KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, const String &lang
)
{
return KeyState::fakeKeyRepeat(id, mask, count, button, lang);
}
bool MSWindowsKeyState::fakeCtrlAltDel()
{
// to fake ctrl+alt+del on the NT family we broadcast a suitable
// hotkey to all windows on the winlogon desktop. however, the
// current thread must be on that desktop to do the broadcast
// and we can't switch just any thread because some own windows
// or hooks. so start a new thread to do the real work.
HANDLE hEvtSendSas = OpenEvent(EVENT_MODIFY_STATE, FALSE, "Global\\SendSAS");
if (hEvtSendSas) {
LOG((CLOG_DEBUG "found the SendSAS event - signaling my launcher to "
"simulate ctrl+alt+del"));
SetEvent(hEvtSendSas);
CloseHandle(hEvtSendSas);
} else {
Thread cad(new FunctionJob(&MSWindowsKeyState::ctrlAltDelThread));
cad.wait();
}
return true;
}
void MSWindowsKeyState::ctrlAltDelThread(void *)
{
// get the Winlogon desktop at whatever privilege we can
HDESK desk = OpenDesktop("Winlogon", 0, FALSE, MAXIMUM_ALLOWED);
if (desk != NULL) {
if (SetThreadDesktop(desk)) {
PostMessage(HWND_BROADCAST, WM_HOTKEY, 0, MAKELPARAM(MOD_CONTROL | MOD_ALT, VK_DELETE));
} else {
LOG((CLOG_DEBUG "can't switch to Winlogon desk: %d", GetLastError()));
}
CloseDesktop(desk);
} else {
LOG((CLOG_DEBUG "can't open Winlogon desk: %d", GetLastError()));
}
}
KeyModifierMask MSWindowsKeyState::pollActiveModifiers() const
{
KeyModifierMask state = 0;
// get non-toggle modifiers from our own shadow key state
for (size_t i = 0; i < sizeof(s_modifiers) / sizeof(s_modifiers[0]); ++i) {
KeyButton button = virtualKeyToButton(s_modifiers[i].m_vk);
if (button != 0 && isKeyDown(button)) {
state |= s_modifiers[i].m_mask;
}
}
// we can get toggle modifiers from the system
if ((GetKeyState(VK_CAPITAL) & 0x01) != 0) {
state |= KeyModifierCapsLock;
}
if ((GetKeyState(VK_NUMLOCK) & 0x01) != 0) {
state |= KeyModifierNumLock;
}
if ((GetKeyState(VK_SCROLL) & 0x01) != 0) {
state |= KeyModifierScrollLock;
}
return state;
}
SInt32 MSWindowsKeyState::pollActiveGroup() const
{
// determine the thread that'll receive this event
HWND targetWindow = GetForegroundWindow();
DWORD targetThread = GetWindowThreadProcessId(targetWindow, NULL);
// get keyboard layout for the thread
HKL hkl = GetKeyboardLayout(targetThread);
if (!hkl) {
// GetKeyboardLayout failed. Maybe targetWindow is a console window.
// We're getting the keyboard layout of the desktop instead.
targetWindow = GetDesktopWindow();
targetThread = GetWindowThreadProcessId(targetWindow, NULL);
hkl = GetKeyboardLayout(targetThread);
}
// get group
GroupMap::const_iterator i = m_groupMap.find(hkl);
if (i == m_groupMap.end()) {
LOG((CLOG_DEBUG1 "can't find keyboard layout %08x", hkl));
return 0;
}
return i->second;
}
void MSWindowsKeyState::pollPressedKeys(KeyButtonSet &pressedKeys) const
{
BYTE keyState[256];
if (!GetKeyboardState(keyState)) {
LOG((CLOG_WARN "keyboard state is unexpected"));
LOG((CLOG_DEBUG "function 'GetKeyboardState' returned false on 'pollPressedKeys'"));
return;
}
for (KeyButton i = 1; i < 256; ++i) {
if ((keyState[i] & 0x80) != 0) {
KeyButton keyButton = virtualKeyToButton(i);
if (keyButton != 0) {
pressedKeys.insert(keyButton);
}
}
}
}
void MSWindowsKeyState::getKeyMap(deskflow::KeyMap &keyMap)
{
// update keyboard groups
if (getGroups(m_groups)) {
m_groupMap.clear();
SInt32 numGroups = (SInt32)m_groups.size();
for (SInt32 g = 0; g < numGroups; ++g) {
m_groupMap[m_groups[g]] = g;
}
}
HKL activeLayout = GetKeyboardLayout(0);
// clear table
memset(m_virtualKeyToButton, 0, sizeof(m_virtualKeyToButton));
m_keyToVKMap.clear();
deskflow::KeyMap::KeyItem item;
SInt32 numGroups = (SInt32)m_groups.size();
for (SInt32 g = 0; g < numGroups; ++g) {
item.m_group = g;
ActivateKeyboardLayout(m_groups[g], 0);
// clear tables
memset(m_buttonToVK, 0, sizeof(m_buttonToVK));
memset(m_buttonToNumpadVK, 0, sizeof(m_buttonToNumpadVK));
// map buttons (scancodes) to virtual keys
for (KeyButton i = 1; i < 256; ++i) {
UINT vk = MapVirtualKey(i, 1);
if (vk == 0) {
// unmapped
continue;
}
// deal with certain virtual keys specially
switch (vk) {
case VK_SHIFT:
// this is important for sending the correct modifier to the
// client, a patch from bug #242 (right shift broken for ms
// remote desktop) removed this to just use left shift, which
// caused bug #2799 (right shift broken for osx).
// we must not repeat this same mistake and must fix platform
// specific bugs in code that only affects that platform.
if (MapVirtualKey(VK_RSHIFT, 0) == i) {
vk = VK_RSHIFT;
} else {
vk = VK_LSHIFT;
}
break;
case VK_CONTROL:
vk = VK_LCONTROL;
break;
case VK_MENU:
vk = VK_LMENU;
break;
case VK_NUMLOCK:
vk = VK_PAUSE;
break;
case VK_NUMPAD0:
case VK_NUMPAD1:
case VK_NUMPAD2:
case VK_NUMPAD3:
case VK_NUMPAD4:
case VK_NUMPAD5:
case VK_NUMPAD6:
case VK_NUMPAD7:
case VK_NUMPAD8:
case VK_NUMPAD9:
case VK_DECIMAL:
// numpad keys are saved in their own table
m_buttonToNumpadVK[i] = vk;
continue;
case VK_LWIN:
case VK_RWIN:
break;
case VK_RETURN:
case VK_PRIOR:
case VK_NEXT:
case VK_END:
case VK_HOME:
case VK_LEFT:
case VK_UP:
case VK_RIGHT:
case VK_DOWN:
case VK_INSERT:
case VK_DELETE:
// also add extended key for these
m_buttonToVK[i | 0x100u] = vk;
break;
}
if (m_buttonToVK[i] == 0) {
m_buttonToVK[i] = vk;
}
}
// now map virtual keys to buttons. multiple virtual keys may map
// to a single button. if the virtual key matches the one in
// m_buttonToVK then we use the button as is. if not then it's
// either a numpad key and we use the button as is or it's an
// extended button.
for (UINT i = 1; i < 255; ++i) {
// skip virtual keys we don't want
switch (i) {
case VK_LBUTTON:
case VK_RBUTTON:
case VK_MBUTTON:
case VK_XBUTTON1:
case VK_XBUTTON2:
case VK_SHIFT:
case VK_CONTROL:
case VK_MENU:
continue;
}
// get the button
KeyButton button = static_cast<KeyButton>(MapVirtualKey(i, 0));
if (button == 0) {
continue;
}
// deal with certain virtual keys specially
switch (i) {
case VK_NUMPAD0:
case VK_NUMPAD1:
case VK_NUMPAD2:
case VK_NUMPAD3:
case VK_NUMPAD4:
case VK_NUMPAD5:
case VK_NUMPAD6:
case VK_NUMPAD7:
case VK_NUMPAD8:
case VK_NUMPAD9:
case VK_DECIMAL:
m_buttonToNumpadVK[button] = i;
break;
default:
// add extended key if virtual keys don't match
if (m_buttonToVK[button] != i) {
m_buttonToVK[button | 0x100u] = i;
}
break;
}
}
// add the extended printscreen (alt+printscreen)
// or maybe it's the non-extended printscreen?
// scancodes and keyboard inputs are complicated
if (m_buttonToVK[0x54u] == 0) {
m_buttonToVK[0x54u] = VK_SNAPSHOT;
}
// set virtual key to button table
if (activeLayout == m_groups[g]) {
for (KeyButton i = 0; i < 512; ++i) {
if (m_buttonToVK[i] != 0) {
if (m_virtualKeyToButton[m_buttonToVK[i]] == 0) {
m_virtualKeyToButton[m_buttonToVK[i]] = i;
}
}
if (m_buttonToNumpadVK[i] != 0) {
if (m_virtualKeyToButton[m_buttonToNumpadVK[i]] == 0) {
m_virtualKeyToButton[m_buttonToNumpadVK[i]] = i;
}
}
}
}
// add numpad keys
for (KeyButton i = 0; i < 512; ++i) {
if (m_buttonToNumpadVK[i] != 0) {
item.m_id = getKeyID(m_buttonToNumpadVK[i], i);
item.m_button = i;
item.m_required = KeyModifierNumLock;
item.m_sensitive = KeyModifierNumLock | KeyModifierShift;
item.m_generates = 0;
item.m_client = m_buttonToNumpadVK[i];
addKeyEntry(keyMap, item);
}
}
// add other keys
BYTE keys[256];
memset(keys, 0, sizeof(keys));
for (KeyButton i = 0; i < 512; ++i) {
if (m_buttonToVK[i] != 0) {
// initialize item
item.m_id = getKeyID(m_buttonToVK[i], i);
item.m_button = i;
item.m_required = 0;
item.m_sensitive = 0;
item.m_client = m_buttonToVK[i];
// get flags for modifier keys
deskflow::KeyMap::initModifierKey(item);
if (item.m_id == 0) {
// translate virtual key to a character with and without
// shift, caps lock, and AltGr.
struct Modifier
{
UINT m_vk1;
UINT m_vk2;
BYTE m_state;
KeyModifierMask m_mask;
};
static const Modifier modifiers[] = {
{VK_SHIFT, VK_SHIFT, 0x80u, KeyModifierShift},
{VK_CAPITAL, VK_CAPITAL, 0x01u, KeyModifierCapsLock},
{VK_CONTROL, VK_MENU, 0x80u, KeyModifierControl | KeyModifierAlt}
};
static const size_t s_numModifiers = sizeof(modifiers) / sizeof(modifiers[0]);
static const size_t s_numCombinations = 1 << s_numModifiers;
KeyID id[s_numCombinations];
bool anyFound = false;
KeyButton button = static_cast<KeyButton>(i & 0xffu);
for (size_t j = 0; j < s_numCombinations; ++j) {
for (size_t k = 0; k < s_numModifiers; ++k) {
// if ((j & (1 << k)) != 0) {
// http://msdn.microsoft.com/en-us/library/ke55d167.aspx
if ((j & (1i64 << k)) != 0) {
keys[modifiers[k].m_vk1] = modifiers[k].m_state;
keys[modifiers[k].m_vk2] = modifiers[k].m_state;
} else {
keys[modifiers[k].m_vk1] = 0;
keys[modifiers[k].m_vk2] = 0;
}
}
id[j] = getIDForKey(item, button, m_buttonToVK[i], keys, m_groups[g]);
if (id[j] != 0) {
anyFound = true;
}
}
if (anyFound) {
// determine what modifiers we're sensitive to.
// we're sensitive if the KeyID changes when the
// modifier does.
item.m_sensitive = 0;
for (size_t k = 0; k < s_numModifiers; ++k) {
for (size_t j = 0; j < s_numCombinations; ++j) {
// if (id[j] != id[j ^ (1u << k)]) {
// http://msdn.microsoft.com/en-us/library/ke55d167.aspx
if (id[j] != id[j ^ (1ui64 << k)]) {
item.m_sensitive |= modifiers[k].m_mask;
break;
}
}
}
// save each key. the map will automatically discard
// duplicates, like an unshift and shifted version of
// a key that's insensitive to shift.
for (size_t j = 0; j < s_numCombinations; ++j) {
item.m_id = id[j];
item.m_required = 0;
for (size_t k = 0; k < s_numModifiers; ++k) {
if ((j & (1i64 << k)) != 0) {
item.m_required |= modifiers[k].m_mask;
}
}
addKeyEntry(keyMap, item);
}
}
} else {
// found in table
switch (m_buttonToVK[i]) {
case VK_TAB:
// add kKeyLeftTab, too
item.m_id = kKeyLeftTab;
item.m_required |= KeyModifierShift;
item.m_sensitive |= KeyModifierShift;
addKeyEntry(keyMap, item);
item.m_id = kKeyTab;
item.m_required &= ~KeyModifierShift;
break;
case VK_CANCEL:
item.m_required |= KeyModifierControl;
item.m_sensitive |= KeyModifierControl;
break;
}
addKeyEntry(keyMap, item);
}
}
}
}
// restore keyboard layout
ActivateKeyboardLayout(activeLayout, 0);
}
void MSWindowsKeyState::fakeKey(const Keystroke &keystroke)
{
switch (keystroke.m_type) {
case Keystroke::kButton: {
LOG(
(CLOG_DEBUG1 " %03x (%08x) %s", keystroke.m_data.m_button.m_button, keystroke.m_data.m_button.m_client,
keystroke.m_data.m_button.m_press ? "down" : "up")
);
KeyButton scanCode = keystroke.m_data.m_button.m_button;
// windows doesn't send key ups for key repeats
if (keystroke.m_data.m_button.m_repeat && !keystroke.m_data.m_button.m_press) {
LOG((CLOG_DEBUG1 " discard key repeat release"));
break;
}
// get the virtual key for the button
WORD vk = (WORD)keystroke.m_data.m_button.m_client;
DWORD flags = 0;
if (keystroke.m_data.m_button.m_press == false)
flags |= KEYEVENTF_KEYUP;
// special handling of VK_SNAPSHOT
if (vk == VK_SNAPSHOT)
scanCode = (getActiveModifiers() & KeyModifierAlt) ? 0x54 : 0x137;
if (scanCode & 0x100)
flags |= KEYEVENTF_EXTENDEDKEY;
// vk,sc,flags,keystroke.m_data.m_button.m_repeat
m_desks->fakeKeyEvent(vk, scanCode, flags, keystroke.m_data.m_button.m_repeat);
// synthesize event
// m_desks->fakeKeyEvent(button, vk,
// keystroke.m_data.m_button.m_press,
// keystroke.m_data.m_button.m_repeat);
break;
}
case Keystroke::kGroup:
// we don't restore the group. we'd like to but we can't be
// sure the restoring group change will be processed after the
// key events.
if (!keystroke.m_data.m_group.m_restore) {
if (keystroke.m_data.m_group.m_absolute) {
LOG((CLOG_DEBUG1 " group %d", keystroke.m_data.m_group.m_group));
setWindowGroup(keystroke.m_data.m_group.m_group);
} else {
LOG((CLOG_DEBUG1 " group %+d", keystroke.m_data.m_group.m_group));
setWindowGroup(getEffectiveGroup(pollActiveGroup(), keystroke.m_data.m_group.m_group));
}
}
break;
}
}
KeyModifierMask &MSWindowsKeyState::getActiveModifiersRValue()
{
if (m_useSavedModifiers) {
return m_savedModifiers;
} else {
return KeyState::getActiveModifiersRValue();
}
}
bool MSWindowsKeyState::getGroups(GroupList &groups) const
{
// get keyboard layouts
UInt32 newNumLayouts = GetKeyboardLayoutList(0, NULL);
if (newNumLayouts == 0) {
LOG((CLOG_DEBUG1 "can't get keyboard layouts"));
return false;
}
HKL *newLayouts = new HKL[newNumLayouts];
newNumLayouts = GetKeyboardLayoutList(newNumLayouts, newLayouts);
if (newNumLayouts == 0) {
LOG((CLOG_DEBUG1 "can't get keyboard layouts"));
delete[] newLayouts;
return false;
}
groups.clear();
groups.insert(groups.end(), newLayouts, newLayouts + newNumLayouts);
delete[] newLayouts;
return true;
}
void MSWindowsKeyState::setWindowGroup(SInt32 group)
{
HWND targetWindow = GetForegroundWindow();
bool sysCharSet = true;
// XXX -- determine if m_groups[group] can be used with the system
// character set.
if (!PostMessage(targetWindow, WM_INPUTLANGCHANGEREQUEST, sysCharSet ? 1 : 0, (LPARAM)m_groups[group])) {
LOG((CLOG_WARN "failed to post change language message"));
}
// XXX -- use a short delay to let the target window process the message
// before it sees the keyboard events. i'm not sure why this is
// necessary since the messages should arrive in order. if we don't
// delay, though, some of our keyboard events may disappear.
Sleep(100);
}
KeyID MSWindowsKeyState::getKeyID(UINT virtualKey, KeyButton button) const
{
// Some virtual keycodes have same values.
// VK_HANGUL == VK_KANA, VK_HANJA == NK_KANJI
// which are used to change the input mode of IME.
// But they have different X11 keysym. So we should distinguish them.
if ((LOWORD(m_keyLayout) & 0xffffu) == 0x0412u) { // 0x0412 : Korean Locale ID
if (virtualKey == VK_HANGUL || virtualKey == VK_HANJA) {
// If shift-space is used to change the input mode,
// the extented bit is not set. So add it to get right key id.
button |= 0x100u;
}
}
if ((button & 0x100u) != 0) {
virtualKey += 0x100u;
}
return s_virtualKey[virtualKey];
}
UINT MSWindowsKeyState::mapButtonToVirtualKey(KeyButton button) const
{
return m_buttonToVK[button];
}
KeyID MSWindowsKeyState::getIDForKey(
deskflow::KeyMap::KeyItem &item, KeyButton button, UINT virtualKey, PBYTE keyState, HKL hkl
) const
{
WCHAR unicode[2];
int n = m_ToUnicodeEx(virtualKey, button, keyState, unicode, sizeof(unicode) / sizeof(unicode[0]), 0, hkl);
KeyID id = static_cast<KeyID>(unicode[0]);
switch (n) {
case -1: {
// dead key. add an space to the keyboard so we exit
// the dead key mode and future calls to this function
// with different modifiers are not affected.
BYTE emptyState[256] = {};
n = m_ToUnicodeEx(VK_SPACE, 0, emptyState, unicode, sizeof(unicode) / sizeof(unicode[0]), 0, hkl);
// as an alternative, we could use the returned
// buffer in unicode to look at the dead key character
// and not rely on getDeadKey to provide the mapping
return deskflow::KeyMap::getDeadKey(id);
}
default:
case 0:
// unmapped
return kKeyNone;
case 1:
return id;
case 2:
// left over dead key in buffer. this used to recurse,
// but apparently this causes a stack overflow, so just
// return no key instead.
return kKeyNone;
}
}
void MSWindowsKeyState::addKeyEntry(deskflow::KeyMap &keyMap, deskflow::KeyMap::KeyItem &item)
{
keyMap.addKeyEntry(item);
if (item.m_group == 0) {
m_keyToVKMap[item.m_id] = static_cast<UINT>(item.m_client);
}
}
| 51,386
|
C++
|
.cpp
| 1,251
| 35.505995
| 118
| 0.532976
|
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,576
|
MSWindowsDebugOutputter.cpp
|
deskflow_deskflow/src/lib/platform/MSWindowsDebugOutputter.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 "platform/MSWindowsDebugOutputter.h"
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <string>
MSWindowsDebugOutputter::MSWindowsDebugOutputter()
{
}
MSWindowsDebugOutputter::~MSWindowsDebugOutputter()
{
}
void MSWindowsDebugOutputter::open(const char *title)
{
}
void MSWindowsDebugOutputter::close()
{
}
void MSWindowsDebugOutputter::show(bool showIfEmpty)
{
}
bool MSWindowsDebugOutputter::write(ELevel level, const char *msg)
{
OutputDebugString((std::string(msg) + "\n").c_str());
return true;
}
void MSWindowsDebugOutputter::flush()
{
}
| 1,299
|
C++
|
.cpp
| 44
| 27.863636
| 72
| 0.780096
|
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,577
|
MSWindowsDesks.cpp
|
deskflow_deskflow/src/lib/platform/MSWindowsDesks.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 "platform/MSWindowsDesks.h"
#include "arch/win32/ArchMiscWindows.h"
#include "base/IEventQueue.h"
#include "base/IJob.h"
#include "base/Log.h"
#include "base/TMethodEventJob.h"
#include "base/TMethodJob.h"
#include "deskflow/IScreenSaver.h"
#include "deskflow/XScreen.h"
#include "deskflow/win32/AppUtilWindows.h"
#include "mt/Lock.h"
#include "mt/Thread.h"
#include "platform/MSWindowsScreen.h"
#include "platform/dfwhook.h"
#include <malloc.h>
// these are only defined when WINVER >= 0x0500
#if !defined(SPI_GETMOUSESPEED)
#define SPI_GETMOUSESPEED 112
#endif
#if !defined(SPI_SETMOUSESPEED)
#define SPI_SETMOUSESPEED 113
#endif
#if !defined(SPI_GETSCREENSAVERRUNNING)
#define SPI_GETSCREENSAVERRUNNING 114
#endif
// X button stuff
#if !defined(WM_XBUTTONDOWN)
#define WM_XBUTTONDOWN 0x020B
#define WM_XBUTTONUP 0x020C
#define WM_XBUTTONDBLCLK 0x020D
#define WM_NCXBUTTONDOWN 0x00AB
#define WM_NCXBUTTONUP 0x00AC
#define WM_NCXBUTTONDBLCLK 0x00AD
#define MOUSEEVENTF_XDOWN 0x0080
#define MOUSEEVENTF_XUP 0x0100
#define XBUTTON1 0x0001
#define XBUTTON2 0x0002
#endif
#if !defined(VK_XBUTTON1)
#define VK_XBUTTON1 0x05
#define VK_XBUTTON2 0x06
#endif
// <unused>; <unused>
#define DESKFLOW_MSG_SWITCH DESKFLOW_HOOK_LAST_MSG + 1
// <unused>; <unused>
#define DESKFLOW_MSG_ENTER DESKFLOW_HOOK_LAST_MSG + 2
// <unused>; <unused>
#define DESKFLOW_MSG_LEAVE DESKFLOW_HOOK_LAST_MSG + 3
// wParam = flags, HIBYTE(lParam) = virtual key, LOBYTE(lParam) = scan code
#define DESKFLOW_MSG_FAKE_KEY DESKFLOW_HOOK_LAST_MSG + 4
// flags, XBUTTON id
#define DESKFLOW_MSG_FAKE_BUTTON DESKFLOW_HOOK_LAST_MSG + 5
// x; y
#define DESKFLOW_MSG_FAKE_MOVE DESKFLOW_HOOK_LAST_MSG + 6
// xDelta; yDelta
#define DESKFLOW_MSG_FAKE_WHEEL DESKFLOW_HOOK_LAST_MSG + 7
// POINT*; <unused>
#define DESKFLOW_MSG_CURSOR_POS DESKFLOW_HOOK_LAST_MSG + 8
// IKeyState*; <unused>
#define DESKFLOW_MSG_SYNC_KEYS DESKFLOW_HOOK_LAST_MSG + 9
// install; <unused>
#define DESKFLOW_MSG_SCREENSAVER DESKFLOW_HOOK_LAST_MSG + 10
// dx; dy
#define DESKFLOW_MSG_FAKE_REL_MOVE DESKFLOW_HOOK_LAST_MSG + 11
// enable; <unused>
#define DESKFLOW_MSG_FAKE_INPUT DESKFLOW_HOOK_LAST_MSG + 12
static void send_keyboard_input(WORD wVk, WORD wScan, DWORD dwFlags)
{
INPUT inp;
inp.type = INPUT_KEYBOARD;
inp.ki.wVk = (dwFlags & KEYEVENTF_UNICODE) ? 0 : wVk; // 1..254 inclusive otherwise
inp.ki.wScan = wScan;
inp.ki.dwFlags = dwFlags & 0xF;
inp.ki.time = 0;
inp.ki.dwExtraInfo = 0;
SendInput(1, &inp, sizeof(inp));
}
static void send_mouse_input(DWORD dwFlags, DWORD dx, DWORD dy, DWORD dwData)
{
INPUT inp;
inp.type = INPUT_MOUSE;
inp.mi.dwFlags = dwFlags;
inp.mi.dx = dx;
inp.mi.dy = dy;
inp.mi.mouseData = dwData;
inp.mi.time = 0;
inp.mi.dwExtraInfo = 0;
SendInput(1, &inp, sizeof(inp));
}
//
// MSWindowsDesks
//
MSWindowsDesks::MSWindowsDesks(
bool isPrimary, bool noHooks, const IScreenSaver *screensaver, IEventQueue *events, IJob *updateKeys,
bool stopOnDeskSwitch
)
: m_isPrimary(isPrimary),
m_noHooks(noHooks),
m_isOnScreen(m_isPrimary),
m_x(0),
m_y(0),
m_w(0),
m_h(0),
m_xCenter(0),
m_yCenter(0),
m_multimon(false),
m_timer(NULL),
m_screensaver(screensaver),
m_screensaverNotify(false),
m_activeDesk(NULL),
m_activeDeskName(),
m_mutex(),
m_deskReady(&m_mutex, false),
m_updateKeys(updateKeys),
m_events(events),
m_stopOnDeskSwitch(stopOnDeskSwitch)
{
m_cursor = createBlankCursor();
m_deskClass = createDeskWindowClass(m_isPrimary);
m_keyLayout = AppUtilWindows::instance().getCurrentKeyboardLayout();
resetOptions();
}
MSWindowsDesks::~MSWindowsDesks()
{
disable();
destroyClass(m_deskClass);
destroyCursor(m_cursor);
delete m_updateKeys;
}
void MSWindowsDesks::enable()
{
m_threadID = GetCurrentThreadId();
// set the active desk and (re)install the hooks
checkDesk();
// install the desk timer. this timer periodically checks
// which desk is active and reinstalls the hooks as necessary.
// we wouldn't need this if windows notified us of a desktop
// change but as far as i can tell it doesn't.
m_timer = m_events->newTimer(0.2, NULL);
m_events->adoptHandler(
Event::kTimer, m_timer, new TMethodEventJob<MSWindowsDesks>(this, &MSWindowsDesks::handleCheckDesk)
);
updateKeys();
}
void MSWindowsDesks::disable()
{
// remove timer
if (m_timer != NULL) {
m_events->removeHandler(Event::kTimer, m_timer);
m_events->deleteTimer(m_timer);
m_timer = NULL;
}
// destroy desks
removeDesks();
m_isOnScreen = m_isPrimary;
}
void MSWindowsDesks::enter()
{
sendMessage(DESKFLOW_MSG_ENTER, 0, 0);
}
void MSWindowsDesks::leave(HKL keyLayout)
{
sendMessage(DESKFLOW_MSG_LEAVE, (WPARAM)keyLayout, 0);
}
void MSWindowsDesks::resetOptions()
{
m_leaveForegroundOption = false;
}
void MSWindowsDesks::setOptions(const OptionsList &options)
{
for (UInt32 i = 0, n = (UInt32)options.size(); i < n; i += 2) {
if (options[i] == kOptionWin32KeepForeground) {
m_leaveForegroundOption = (options[i + 1] != 0);
LOG((CLOG_DEBUG1 "%s the foreground window", m_leaveForegroundOption ? "don\'t grab" : "grab"));
}
}
}
void MSWindowsDesks::updateKeys()
{
sendMessage(DESKFLOW_MSG_SYNC_KEYS, 0, 0);
}
void MSWindowsDesks::setShape(
SInt32 x, SInt32 y, SInt32 width, SInt32 height, SInt32 xCenter, SInt32 yCenter, bool isMultimon
)
{
m_x = x;
m_y = y;
m_w = width;
m_h = height;
m_xCenter = xCenter;
m_yCenter = yCenter;
m_multimon = isMultimon;
}
void MSWindowsDesks::installScreensaverHooks(bool install)
{
if (m_isPrimary && m_screensaverNotify != install) {
m_screensaverNotify = install;
sendMessage(DESKFLOW_MSG_SCREENSAVER, install, 0);
}
}
void MSWindowsDesks::fakeInputBegin()
{
sendMessage(DESKFLOW_MSG_FAKE_INPUT, 1, 0);
}
void MSWindowsDesks::fakeInputEnd()
{
sendMessage(DESKFLOW_MSG_FAKE_INPUT, 0, 0);
}
void MSWindowsDesks::getCursorPos(SInt32 &x, SInt32 &y) const
{
POINT pos;
sendMessage(DESKFLOW_MSG_CURSOR_POS, reinterpret_cast<WPARAM>(&pos), 0);
x = pos.x;
y = pos.y;
}
void MSWindowsDesks::fakeKeyEvent(WORD virtualKey, WORD scanCode, DWORD flags, bool /*isAutoRepeat*/) const
{
sendMessage(DESKFLOW_MSG_FAKE_KEY, flags, MAKELPARAM(scanCode, virtualKey));
}
void MSWindowsDesks::fakeMouseButton(ButtonID button, bool press)
{
// the system will swap the meaning of left/right for us if
// the user has configured a left-handed mouse but we don't
// want it to swap since we want the handedness of the
// server's mouse. so pre-swap for a left-handed mouse.
if (GetSystemMetrics(SM_SWAPBUTTON)) {
switch (button) {
case kButtonLeft:
button = kButtonRight;
break;
case kButtonRight:
button = kButtonLeft;
break;
}
}
// map button id to button flag and button data
DWORD data = 0;
DWORD flags;
switch (button) {
case kButtonLeft:
flags = press ? MOUSEEVENTF_LEFTDOWN : MOUSEEVENTF_LEFTUP;
break;
case kButtonMiddle:
flags = press ? MOUSEEVENTF_MIDDLEDOWN : MOUSEEVENTF_MIDDLEUP;
break;
case kButtonRight:
flags = press ? MOUSEEVENTF_RIGHTDOWN : MOUSEEVENTF_RIGHTUP;
break;
case kButtonExtra0 + 0:
data = XBUTTON1;
flags = press ? MOUSEEVENTF_XDOWN : MOUSEEVENTF_XUP;
break;
case kButtonExtra0 + 1:
data = XBUTTON2;
flags = press ? MOUSEEVENTF_XDOWN : MOUSEEVENTF_XUP;
break;
default:
return;
}
// do it
sendMessage(DESKFLOW_MSG_FAKE_BUTTON, flags, data);
}
void MSWindowsDesks::fakeMouseMove(SInt32 x, SInt32 y) const
{
sendMessage(DESKFLOW_MSG_FAKE_MOVE, static_cast<WPARAM>(x), static_cast<LPARAM>(y));
}
void MSWindowsDesks::fakeMouseRelativeMove(SInt32 dx, SInt32 dy) const
{
sendMessage(DESKFLOW_MSG_FAKE_REL_MOVE, static_cast<WPARAM>(dx), static_cast<LPARAM>(dy));
}
void MSWindowsDesks::fakeMouseWheel(SInt32 xDelta, SInt32 yDelta) const
{
sendMessage(DESKFLOW_MSG_FAKE_WHEEL, xDelta, yDelta);
}
void MSWindowsDesks::sendMessage(UINT msg, WPARAM wParam, LPARAM lParam) const
{
if (m_activeDesk != NULL && m_activeDesk->m_window != NULL) {
PostThreadMessage(m_activeDesk->m_threadID, msg, wParam, lParam);
waitForDesk();
}
}
HCURSOR
MSWindowsDesks::createBlankCursor() const
{
// create a transparent cursor
int cw = GetSystemMetrics(SM_CXCURSOR);
int ch = GetSystemMetrics(SM_CYCURSOR);
UInt8 *cursorAND = new UInt8[ch * ((cw + 31) >> 2)];
UInt8 *cursorXOR = new UInt8[ch * ((cw + 31) >> 2)];
memset(cursorAND, 0xff, ch * ((cw + 31) >> 2));
memset(cursorXOR, 0x00, ch * ((cw + 31) >> 2));
HCURSOR c = CreateCursor(MSWindowsScreen::getWindowInstance(), 0, 0, cw, ch, cursorAND, cursorXOR);
delete[] cursorXOR;
delete[] cursorAND;
return c;
}
void MSWindowsDesks::destroyCursor(HCURSOR cursor) const
{
if (cursor != NULL) {
DestroyCursor(cursor);
}
}
ATOM MSWindowsDesks::createDeskWindowClass(bool isPrimary) const
{
WNDCLASSEX classInfo;
classInfo.cbSize = sizeof(classInfo);
classInfo.style = CS_DBLCLKS | CS_NOCLOSE;
classInfo.lpfnWndProc = isPrimary ? &MSWindowsDesks::primaryDeskProc : &MSWindowsDesks::secondaryDeskProc;
classInfo.cbClsExtra = 0;
classInfo.cbWndExtra = 0;
classInfo.hInstance = MSWindowsScreen::getWindowInstance();
classInfo.hIcon = NULL;
classInfo.hCursor = m_cursor;
classInfo.hbrBackground = NULL;
classInfo.lpszMenuName = NULL;
classInfo.lpszClassName = "DeskflowDesk";
classInfo.hIconSm = NULL;
return RegisterClassEx(&classInfo);
}
void MSWindowsDesks::destroyClass(ATOM windowClass) const
{
if (windowClass != 0) {
UnregisterClass(MAKEINTATOM(windowClass), MSWindowsScreen::getWindowInstance());
}
}
HWND MSWindowsDesks::createWindow(ATOM windowClass, const char *name) const
{
HWND window = CreateWindowEx(
WS_EX_TRANSPARENT | WS_EX_TOOLWINDOW, MAKEINTATOM(windowClass), name, WS_POPUP, 0, 0, 1, 1, NULL, NULL,
MSWindowsScreen::getWindowInstance(), NULL
);
if (window == NULL) {
LOG((CLOG_ERR "failed to create window: %d", GetLastError()));
throw XScreenOpenFailure();
}
return window;
}
void MSWindowsDesks::destroyWindow(HWND hwnd) const
{
if (hwnd != NULL) {
DestroyWindow(hwnd);
}
}
LRESULT CALLBACK MSWindowsDesks::primaryDeskProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
return DefWindowProc(hwnd, msg, wParam, lParam);
}
LRESULT CALLBACK MSWindowsDesks::secondaryDeskProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
// would like to detect any local user input and hide the hider
// window but for now we just detect mouse motion.
bool hide = false;
switch (msg) {
case WM_MOUSEMOVE:
if (LOWORD(lParam) != 0 || HIWORD(lParam) != 0) {
hide = true;
}
break;
}
if (hide && IsWindowVisible(hwnd)) {
ReleaseCapture();
SetWindowPos(hwnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_HIDEWINDOW);
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
void MSWindowsDesks::deskMouseMove(SInt32 x, SInt32 y) const
{
// when using absolute positioning with mouse_event(),
// the normalized device coordinates range over only
// the primary screen.
SInt32 w = GetSystemMetrics(SM_CXSCREEN);
SInt32 h = GetSystemMetrics(SM_CYSCREEN);
send_mouse_input(
MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE, (DWORD)((65535.0f * x) / (w - 1) + 0.5f),
(DWORD)((65535.0f * y) / (h - 1) + 0.5f), 0
);
}
void MSWindowsDesks::deskMouseRelativeMove(SInt32 dx, SInt32 dy) const
{
// relative moves are subject to cursor acceleration which we don't
// want.so we disable acceleration, do the relative move, then
// restore acceleration. there's a slight chance we'll end up in
// the wrong place if the user moves the cursor using this system's
// mouse while simultaneously moving the mouse on the server
// system. that defeats the purpose of deskflow so we'll assume
// that won't happen. even if it does, the next mouse move will
// correct the position.
// save mouse speed & acceleration
int oldSpeed[4];
bool accelChanged =
SystemParametersInfo(SPI_GETMOUSE, 0, oldSpeed, 0) && SystemParametersInfo(SPI_GETMOUSESPEED, 0, oldSpeed + 3, 0);
// use 1:1 motion
if (accelChanged) {
int newSpeed[4] = {0, 0, 0, 1};
accelChanged = SystemParametersInfo(SPI_SETMOUSE, 0, newSpeed, 0) ||
SystemParametersInfo(SPI_SETMOUSESPEED, 0, newSpeed + 3, 0);
}
// move relative to mouse position
send_mouse_input(MOUSEEVENTF_MOVE, dx, dy, 0);
// restore mouse speed & acceleration
if (accelChanged) {
SystemParametersInfo(SPI_SETMOUSE, 0, oldSpeed, 0);
SystemParametersInfo(SPI_SETMOUSESPEED, 0, oldSpeed + 3, 0);
}
}
void MSWindowsDesks::deskEnter(Desk *desk)
{
if (!m_isPrimary) {
ReleaseCapture();
}
ShowCursor(TRUE);
SetWindowPos(desk->m_window, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_HIDEWINDOW);
// restore the foreground window
// XXX -- this raises the window to the top of the Z-order. we
// want it to stay wherever it was to properly support X-mouse
// (mouse over activation) but i've no idea how to do that.
// the obvious workaround of using SetWindowPos() to move it back
// after being raised doesn't work.
DWORD thisThread = GetWindowThreadProcessId(desk->m_window, NULL);
DWORD thatThread = GetWindowThreadProcessId(desk->m_foregroundWindow, NULL);
AttachThreadInput(thatThread, thisThread, TRUE);
SetForegroundWindow(desk->m_foregroundWindow);
AttachThreadInput(thatThread, thisThread, FALSE);
EnableWindow(desk->m_window, desk->m_lowLevel ? FALSE : TRUE);
desk->m_foregroundWindow = NULL;
}
void MSWindowsDesks::deskLeave(Desk *desk, HKL keyLayout)
{
ShowCursor(FALSE);
if (m_isPrimary) {
// map a window to hide the cursor and to use whatever keyboard
// layout we choose rather than the keyboard layout of the last
// active window.
int x, y, w, h;
if (desk->m_lowLevel) {
// with a low level hook the cursor will never budge so
// just a 1x1 window is sufficient.
x = m_xCenter;
y = m_yCenter;
w = 1;
h = 1;
} else {
// with regular hooks the cursor will jitter as it's moved
// by the user then back to the center by us. to be sure
// we never lose it, cover all the monitors with the window.
x = m_x;
y = m_y;
w = m_w;
h = m_h;
}
SetWindowPos(desk->m_window, HWND_TOP, x, y, w, h, SWP_NOACTIVATE | SWP_SHOWWINDOW);
// switch to requested keyboard layout
ActivateKeyboardLayout(keyLayout, 0);
// if not using low-level hooks we have to also activate the
// window to ensure we don't lose keyboard focus.
// FIXME -- see if this can be avoided. if so then always
// disable the window (see handling of DESKFLOW_MSG_SWITCH).
if (!desk->m_lowLevel) {
SetActiveWindow(desk->m_window);
}
// if using low-level hooks then disable the foreground window
// so it can't mess up any of our keyboard events. the console
// program, for example, will cause characters to be reported as
// unshifted, regardless of the shift key state. interestingly
// we do see the shift key go down and up.
//
// note that we must enable the window to activate it and we
// need to disable the window on deskEnter.
else {
desk->m_foregroundWindow = getForegroundWindow();
if (desk->m_foregroundWindow != NULL) {
EnableWindow(desk->m_window, TRUE);
SetActiveWindow(desk->m_window);
DWORD thisThread = GetWindowThreadProcessId(desk->m_window, NULL);
DWORD thatThread = GetWindowThreadProcessId(desk->m_foregroundWindow, NULL);
AttachThreadInput(thatThread, thisThread, TRUE);
SetForegroundWindow(desk->m_window);
AttachThreadInput(thatThread, thisThread, FALSE);
}
}
} else {
// move hider window under the cursor center, raise, and show it
SetWindowPos(desk->m_window, HWND_TOP, m_xCenter, m_yCenter, 1, 1, SWP_NOACTIVATE | SWP_SHOWWINDOW);
// watch for mouse motion. if we see any then we hide the
// hider window so the user can use the physically attached
// mouse if desired. we'd rather not capture the mouse but
// we aren't notified when the mouse leaves our window.
SetCapture(desk->m_window);
// warp the mouse to the cursor center
LOG((CLOG_DEBUG2 "warping cursor to center: %+d,%+d", m_xCenter, m_yCenter));
deskMouseMove(m_xCenter, m_yCenter);
}
}
void MSWindowsDesks::deskThread(void *vdesk)
{
MSG msg;
// use given desktop for this thread
Desk *desk = static_cast<Desk *>(vdesk);
desk->m_threadID = GetCurrentThreadId();
desk->m_window = NULL;
desk->m_foregroundWindow = NULL;
if (desk->m_desk != NULL && SetThreadDesktop(desk->m_desk) != 0) {
// create a message queue
PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE);
// create a window. we use this window to hide the cursor.
try {
desk->m_window = createWindow(m_deskClass, "DeskflowDesk");
LOG((CLOG_DEBUG "desk %s window is 0x%08x", desk->m_name.c_str(), desk->m_window));
} catch (...) {
// ignore
LOG((CLOG_DEBUG "can't create desk window for %s", desk->m_name.c_str()));
}
}
// tell main thread that we're ready
{
Lock lock(&m_mutex);
m_deskReady = true;
m_deskReady.broadcast();
}
while (GetMessage(&msg, NULL, 0, 0)) {
switch (msg.message) {
default:
TranslateMessage(&msg);
DispatchMessage(&msg);
continue;
case DESKFLOW_MSG_SWITCH:
if (!m_noHooks) {
MSWindowsHook::uninstall();
if (m_screensaverNotify) {
MSWindowsHook::uninstallScreenSaver();
MSWindowsHook::installScreenSaver();
}
switch (MSWindowsHook::install()) {
case kHOOK_FAILED:
// we won't work on this desk
desk->m_lowLevel = false;
break;
case kHOOK_OKAY:
desk->m_lowLevel = false;
break;
case kHOOK_OKAY_LL:
desk->m_lowLevel = true;
break;
}
// a window on the primary screen with low-level hooks
// should never activate.
if (desk->m_window)
EnableWindow(desk->m_window, desk->m_lowLevel ? FALSE : TRUE);
}
break;
case DESKFLOW_MSG_ENTER:
m_isOnScreen = true;
deskEnter(desk);
break;
case DESKFLOW_MSG_LEAVE:
m_isOnScreen = false;
m_keyLayout = (HKL)msg.wParam;
deskLeave(desk, m_keyLayout);
break;
case DESKFLOW_MSG_FAKE_KEY:
// Note, this is intended to be HI/LOWORD and not HI/LOBYTE
send_keyboard_input(HIWORD(msg.lParam), LOWORD(msg.lParam), (DWORD)msg.wParam);
break;
case DESKFLOW_MSG_FAKE_BUTTON:
if (msg.wParam != 0) {
send_mouse_input((DWORD)msg.wParam, 0, 0, (DWORD)msg.lParam);
}
break;
case DESKFLOW_MSG_FAKE_MOVE:
deskMouseMove(static_cast<SInt32>(msg.wParam), static_cast<SInt32>(msg.lParam));
break;
case DESKFLOW_MSG_FAKE_REL_MOVE:
deskMouseRelativeMove(static_cast<SInt32>(msg.wParam), static_cast<SInt32>(msg.lParam));
break;
case DESKFLOW_MSG_FAKE_WHEEL:
// XXX -- add support for x-axis scrolling
if (msg.lParam != 0) {
send_mouse_input(MOUSEEVENTF_WHEEL, 0, 0, (DWORD)msg.lParam);
}
break;
case DESKFLOW_MSG_CURSOR_POS: {
POINT *pos = reinterpret_cast<POINT *>(msg.wParam);
if (!GetCursorPos(pos)) {
pos->x = m_xCenter;
pos->y = m_yCenter;
}
break;
}
case DESKFLOW_MSG_SYNC_KEYS:
m_updateKeys->run();
break;
case DESKFLOW_MSG_SCREENSAVER:
if (!m_noHooks) {
if (msg.wParam != 0) {
MSWindowsHook::installScreenSaver();
} else {
MSWindowsHook::uninstallScreenSaver();
}
}
break;
case DESKFLOW_MSG_FAKE_INPUT:
send_keyboard_input(
DESKFLOW_HOOK_FAKE_INPUT_VIRTUAL_KEY, DESKFLOW_HOOK_FAKE_INPUT_SCANCODE, msg.wParam ? 0 : KEYEVENTF_KEYUP
);
break;
}
// notify that message was processed
Lock lock(&m_mutex);
m_deskReady = true;
m_deskReady.broadcast();
}
// clean up
deskEnter(desk);
if (desk->m_window != NULL) {
DestroyWindow(desk->m_window);
}
if (desk->m_desk != NULL) {
closeDesktop(desk->m_desk);
}
}
MSWindowsDesks::Desk *MSWindowsDesks::addDesk(const String &name, HDESK hdesk)
{
Desk *desk = new Desk;
desk->m_name = name;
desk->m_desk = hdesk;
desk->m_targetID = GetCurrentThreadId();
desk->m_thread = new Thread(new TMethodJob<MSWindowsDesks>(this, &MSWindowsDesks::deskThread, desk));
waitForDesk();
m_desks.insert(std::make_pair(name, desk));
return desk;
}
void MSWindowsDesks::removeDesks()
{
for (Desks::iterator index = m_desks.begin(); index != m_desks.end(); ++index) {
Desk *desk = index->second;
PostThreadMessage(desk->m_threadID, WM_QUIT, 0, 0);
desk->m_thread->wait();
delete desk->m_thread;
delete desk;
}
m_desks.clear();
m_activeDesk = NULL;
m_activeDeskName = "";
}
void MSWindowsDesks::checkDesk()
{
// get current desktop. if we already know about it then return.
Desk *desk;
HDESK hdesk = openInputDesktop();
String name = getDesktopName(hdesk);
Desks::const_iterator index = m_desks.find(name);
if (index == m_desks.end()) {
desk = addDesk(name, hdesk);
// hold on to hdesk until thread exits so the desk can't
// be removed by the system
} else {
closeDesktop(hdesk);
desk = index->second;
}
// if we are told to shut down on desk switch, and this is not the
// first switch, then shut down.
if (m_stopOnDeskSwitch && m_activeDesk != NULL && name != m_activeDeskName) {
LOG((CLOG_DEBUG "shutting down because of desk switch to \"%s\"", name.c_str()));
m_events->addEvent(Event(Event::kQuit));
return;
}
// if active desktop changed then tell the old and new desk threads
// about the change. don't switch desktops when the screensaver is
// active becaue we'd most likely switch to the screensaver desktop
// which would have the side effect of forcing the screensaver to
// stop.
if (name != m_activeDeskName && !m_screensaver->isActive()) {
// show cursor on previous desk
bool wasOnScreen = m_isOnScreen;
if (!wasOnScreen) {
sendMessage(DESKFLOW_MSG_ENTER, 0, 0);
}
// check for desk accessibility change. we don't get events
// from an inaccessible desktop so when we switch from an
// inaccessible desktop to an accessible one we have to
// update the keyboard state.
LOG((CLOG_DEBUG "switched to desk \"%s\"", name.c_str()));
bool syncKeys = false;
bool isAccessible = isDeskAccessible(desk);
if (isDeskAccessible(m_activeDesk) != isAccessible) {
if (isAccessible) {
LOG((CLOG_DEBUG "desktop is now accessible"));
syncKeys = true;
} else {
LOG((CLOG_DEBUG "desktop is now inaccessible"));
}
}
// switch desk
m_activeDesk = desk;
m_activeDeskName = name;
sendMessage(DESKFLOW_MSG_SWITCH, 0, 0);
// hide cursor on new desk
if (!wasOnScreen) {
sendMessage(DESKFLOW_MSG_LEAVE, (WPARAM)m_keyLayout, 0);
}
// update keys if necessary
if (syncKeys) {
updateKeys();
}
} else if (name != m_activeDeskName) {
// screen saver might have started
PostThreadMessage(m_threadID, DESKFLOW_MSG_SCREEN_SAVER, TRUE, 0);
}
}
bool MSWindowsDesks::isDeskAccessible(const Desk *desk) const
{
return (desk != NULL && desk->m_desk != NULL);
}
void MSWindowsDesks::waitForDesk() const
{
MSWindowsDesks *self = const_cast<MSWindowsDesks *>(this);
Lock lock(&m_mutex);
while (!(bool)m_deskReady) {
m_deskReady.wait();
}
self->m_deskReady = false;
}
void MSWindowsDesks::handleCheckDesk(const Event &, void *)
{
checkDesk();
// also check if screen saver is running if on a modern OS and
// this is the primary screen.
if (m_isPrimary) {
BOOL running;
SystemParametersInfo(SPI_GETSCREENSAVERRUNNING, 0, &running, FALSE);
PostThreadMessage(m_threadID, DESKFLOW_MSG_SCREEN_SAVER, running, 0);
}
}
HDESK
MSWindowsDesks::openInputDesktop()
{
return OpenInputDesktop(DF_ALLOWOTHERACCOUNTHOOK, TRUE, DESKTOP_CREATEWINDOW | DESKTOP_HOOKCONTROL | GENERIC_WRITE);
}
void MSWindowsDesks::closeDesktop(HDESK desk)
{
if (desk != NULL) {
CloseDesktop(desk);
}
}
String MSWindowsDesks::getDesktopName(HDESK desk)
{
if (desk == NULL) {
return String();
} else {
DWORD size;
GetUserObjectInformation(desk, UOI_NAME, NULL, 0, &size);
TCHAR *name = (TCHAR *)alloca(size + sizeof(TCHAR));
GetUserObjectInformation(desk, UOI_NAME, name, size, &size);
String result(name);
return result;
}
}
HWND MSWindowsDesks::getForegroundWindow() const
{
// Ideally we'd return NULL as much as possible, only returning
// the actual foreground window when we know it's going to mess
// up our keyboard input. For now we'll just let the user
// decide.
if (m_leaveForegroundOption) {
return NULL;
}
return GetForegroundWindow();
}
| 26,060
|
C++
|
.cpp
| 785
| 29.329936
| 120
| 0.69754
|
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,578
|
XWindowsClipboardUTF8Converter.cpp
|
deskflow_deskflow/src/lib/platform/XWindowsClipboardUTF8Converter.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 "platform/XWindowsClipboardUTF8Converter.h"
#include <algorithm>
//
// XWindowsClipboardUTF8Converter
//
XWindowsClipboardUTF8Converter::XWindowsClipboardUTF8Converter(Display *display, const char *name, bool normalize)
: m_atom(XInternAtom(display, name, False)),
m_normalize(normalize)
{
// do nothing
}
XWindowsClipboardUTF8Converter::~XWindowsClipboardUTF8Converter()
{
// do nothing
}
IClipboard::EFormat XWindowsClipboardUTF8Converter::getFormat() const
{
return IClipboard::kText;
}
Atom XWindowsClipboardUTF8Converter::getAtom() const
{
return m_atom;
}
int XWindowsClipboardUTF8Converter::getDataSize() const
{
return 8;
}
static bool isCR(char ch)
{
return (ch == '\r');
}
String XWindowsClipboardUTF8Converter::fromIClipboard(const String &data) const
{
return data;
}
String XWindowsClipboardUTF8Converter::toIClipboard(const String &data) const
{
// https://bugzilla.mozilla.org/show_bug.cgi?id=1547595
// GTK normalizes the clipboard's line endings to CRLF (\r\n) internally.
// When sending the raw data to other systems, like Windows, where \n is
// converted to \r\n we end up with \r\r\n, resulting in double lines when
// pasting.
//
// This seems to happen only when the clipboard format is
// text/plain;charset=utf8 and not when it's UTF8_STRING.
// When normalize clipboard is set, any \r present in the string is removed
if (m_normalize) {
String copy = data;
copy.erase(std::remove_if(copy.begin(), copy.end(), isCR), copy.end());
return copy;
}
return data;
}
| 2,299
|
C++
|
.cpp
| 70
| 30.557143
| 114
| 0.760722
|
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,579
|
XWindowsScreenSaver.cpp
|
deskflow_deskflow/src/lib/platform/XWindowsScreenSaver.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 "platform/XWindowsScreenSaver.h"
#include "base/Event.h"
#include "base/IEventQueue.h"
#include "base/Log.h"
#include "base/TMethodEventJob.h"
#include "deskflow/IPlatformScreen.h"
#include "platform/XWindowsUtil.h"
#include <X11/Xatom.h>
#if HAVE_X11_EXTENSIONS_XTEST_H
#include <X11/extensions/XTest.h>
#else
#error The XTest extension is required to build deskflow
#endif
#if HAVE_X11_EXTENSIONS_DPMS_H
extern "C"
{
#include <X11/Xmd.h>
#include <X11/extensions/dpms.h>
#if !HAVE_DPMS_PROTOTYPES
#undef DPMSModeOn
#undef DPMSModeStandby
#undef DPMSModeSuspend
#undef DPMSModeOff
#define DPMSModeOn 0
#define DPMSModeStandby 1
#define DPMSModeSuspend 2
#define DPMSModeOff 3
extern Bool DPMSQueryExtension(Display *, int *, int *);
extern Bool DPMSCapable(Display *);
extern Status DPMSEnable(Display *);
extern Status DPMSDisable(Display *);
extern Status DPMSForceLevel(Display *, CARD16);
extern Status DPMSInfo(Display *, CARD16 *, BOOL *);
#endif
}
#endif
//
// XWindowsScreenSaver
//
XWindowsScreenSaver::XWindowsScreenSaver(Display *display, Window window, void *eventTarget, IEventQueue *events)
: m_display(display),
m_xscreensaverSink(window),
m_eventTarget(eventTarget),
m_xscreensaver(None),
m_xscreensaverActive(false),
m_dpms(false),
m_disabled(false),
m_suppressDisable(false),
m_disableTimer(NULL),
m_disablePos(0),
m_events(events)
{
// get atoms
m_atomScreenSaver = XInternAtom(m_display, "SCREENSAVER", False);
m_atomScreenSaverVersion = XInternAtom(m_display, "_SCREENSAVER_VERSION", False);
m_atomScreenSaverActivate = XInternAtom(m_display, "ACTIVATE", False);
m_atomScreenSaverDeactivate = XInternAtom(m_display, "DEACTIVATE", False);
// check for DPMS extension. this is an alternative screen saver
// that powers down the display.
#if HAVE_X11_EXTENSIONS_DPMS_H
int eventBase, errorBase;
if (DPMSQueryExtension(m_display, &eventBase, &errorBase)) {
if (DPMSCapable(m_display)) {
// we have DPMS
m_dpms = true;
}
}
#endif
// watch top-level windows for changes
bool error = false;
{
XWindowsUtil::ErrorLock lock(m_display, &error);
Window root = DefaultRootWindow(m_display);
XWindowAttributes attr;
XGetWindowAttributes(m_display, root, &attr);
m_rootEventMask = attr.your_event_mask;
XSelectInput(m_display, root, m_rootEventMask | SubstructureNotifyMask);
}
if (error) {
LOG((CLOG_DEBUG "didn't set root event mask"));
m_rootEventMask = 0;
}
// get the built-in settings
XGetScreenSaver(m_display, &m_timeout, &m_interval, &m_preferBlanking, &m_allowExposures);
// get the DPMS settings
m_dpmsEnabled = isDPMSEnabled();
// get the xscreensaver window, if any
if (!findXScreenSaver()) {
setXScreenSaver(None);
}
// install disable timer event handler
m_events->adoptHandler(
Event::kTimer, this, new TMethodEventJob<XWindowsScreenSaver>(this, &XWindowsScreenSaver::handleDisableTimer)
);
}
XWindowsScreenSaver::~XWindowsScreenSaver()
{
// done with disable job
if (m_disableTimer != NULL) {
m_events->deleteTimer(m_disableTimer);
}
m_events->removeHandler(Event::kTimer, this);
if (m_display != NULL) {
enableDPMS(m_dpmsEnabled);
XSetScreenSaver(m_display, m_timeout, m_interval, m_preferBlanking, m_allowExposures);
clearWatchForXScreenSaver();
XWindowsUtil::ErrorLock lock(m_display);
XSelectInput(m_display, DefaultRootWindow(m_display), m_rootEventMask);
}
}
void XWindowsScreenSaver::destroy()
{
m_display = NULL;
delete this;
}
bool XWindowsScreenSaver::handleXEvent(const XEvent *xevent)
{
switch (xevent->type) {
case CreateNotify:
if (m_xscreensaver == None) {
if (isXScreenSaver(xevent->xcreatewindow.window)) {
// found the xscreensaver
setXScreenSaver(xevent->xcreatewindow.window);
} else {
// another window to watch. to detect the xscreensaver
// window we look for a property but that property may
// not yet exist by the time we get this event so we
// have to watch the window for property changes.
// this would be so much easier if xscreensaver did the
// smart thing and stored its window in a property on
// the root window.
addWatchXScreenSaver(xevent->xcreatewindow.window);
}
}
break;
case DestroyNotify:
if (xevent->xdestroywindow.window == m_xscreensaver) {
// xscreensaver is gone
LOG((CLOG_DEBUG "xscreensaver died"));
setXScreenSaver(None);
return true;
}
break;
case PropertyNotify:
if (xevent->xproperty.state == PropertyNewValue) {
if (isXScreenSaver(xevent->xproperty.window)) {
// found the xscreensaver
setXScreenSaver(xevent->xcreatewindow.window);
}
}
break;
case MapNotify:
if (xevent->xmap.window == m_xscreensaver) {
// xscreensaver has activated
setXScreenSaverActive(true);
return true;
}
break;
case UnmapNotify:
if (xevent->xunmap.window == m_xscreensaver) {
// xscreensaver has deactivated
setXScreenSaverActive(false);
return true;
}
break;
}
return false;
}
void XWindowsScreenSaver::enable()
{
// for xscreensaver
m_disabled = false;
updateDisableTimer();
// for built-in X screen saver
XSetScreenSaver(m_display, m_timeout, m_interval, m_preferBlanking, m_allowExposures);
// for DPMS
enableDPMS(m_dpmsEnabled);
}
void XWindowsScreenSaver::disable()
{
// for xscreensaver
m_disabled = true;
updateDisableTimer();
// use built-in X screen saver
XGetScreenSaver(m_display, &m_timeout, &m_interval, &m_preferBlanking, &m_allowExposures);
XSetScreenSaver(m_display, 0, m_interval, m_preferBlanking, m_allowExposures);
// for DPMS
m_dpmsEnabled = isDPMSEnabled();
enableDPMS(false);
// FIXME -- now deactivate?
}
void XWindowsScreenSaver::activate()
{
// remove disable job timer
m_suppressDisable = true;
updateDisableTimer();
// enable DPMS if it was enabled
enableDPMS(m_dpmsEnabled);
// try xscreensaver
findXScreenSaver();
if (m_xscreensaver != None) {
sendXScreenSaverCommand(m_atomScreenSaverActivate);
return;
}
// try built-in X screen saver
if (m_timeout != 0) {
XForceScreenSaver(m_display, ScreenSaverActive);
}
// try DPMS
activateDPMS(true);
}
void XWindowsScreenSaver::deactivate()
{
// reinstall disable job timer
m_suppressDisable = false;
updateDisableTimer();
// try DPMS
activateDPMS(false);
// disable DPMS if screen saver is disabled
if (m_disabled) {
enableDPMS(false);
}
// try xscreensaver
findXScreenSaver();
if (m_xscreensaver != None) {
sendXScreenSaverCommand(m_atomScreenSaverDeactivate);
return;
}
// use built-in X screen saver
XForceScreenSaver(m_display, ScreenSaverReset);
}
bool XWindowsScreenSaver::isActive() const
{
// check xscreensaver
if (m_xscreensaver != None) {
return m_xscreensaverActive;
}
// check DPMS
if (isDPMSActivated()) {
return true;
}
// can't check built-in X screen saver activity
return false;
}
bool XWindowsScreenSaver::findXScreenSaver()
{
// do nothing if we've already got the xscreensaver window
if (m_xscreensaver == None) {
// find top-level window xscreensaver window
Window root = DefaultRootWindow(m_display);
Window rw, pw, *cw;
unsigned int nc;
if (XQueryTree(m_display, root, &rw, &pw, &cw, &nc)) {
for (unsigned int i = 0; i < nc; ++i) {
if (isXScreenSaver(cw[i])) {
setXScreenSaver(cw[i]);
break;
}
}
XFree(cw);
}
}
return (m_xscreensaver != None);
}
void XWindowsScreenSaver::setXScreenSaver(Window window)
{
LOG((CLOG_DEBUG "xscreensaver window: 0x%08x", window));
// save window
m_xscreensaver = window;
if (m_xscreensaver != None) {
// clear old watch list
clearWatchForXScreenSaver();
// see if xscreensaver is active
bool error = false;
XWindowAttributes attr;
{
XWindowsUtil::ErrorLock lock(m_display, &error);
XGetWindowAttributes(m_display, m_xscreensaver, &attr);
}
setXScreenSaverActive(!error && attr.map_state != IsUnmapped);
// save current DPMS state; xscreensaver may have changed it.
m_dpmsEnabled = isDPMSEnabled();
} else {
// screen saver can't be active if it doesn't exist
setXScreenSaverActive(false);
// start watching for xscreensaver
watchForXScreenSaver();
}
}
bool XWindowsScreenSaver::isXScreenSaver(Window w) const
{
// check for m_atomScreenSaverVersion string property
Atom type;
return (
XWindowsUtil::getWindowProperty(m_display, w, m_atomScreenSaverVersion, NULL, &type, NULL, False) &&
type == XA_STRING
);
}
void XWindowsScreenSaver::setXScreenSaverActive(bool activated)
{
if (m_xscreensaverActive != activated) {
LOG((CLOG_DEBUG "xscreensaver %s on window 0x%08x", activated ? "activated" : "deactivated", m_xscreensaver));
m_xscreensaverActive = activated;
// if screen saver was activated forcefully (i.e. against
// our will) then just accept it. don't try to keep it
// from activating since that'll just pop up the password
// dialog if locking is enabled.
m_suppressDisable = activated;
updateDisableTimer();
if (activated) {
m_events->addEvent(Event(m_events->forIPrimaryScreen().screensaverActivated(), m_eventTarget));
} else {
m_events->addEvent(Event(m_events->forIPrimaryScreen().screensaverDeactivated(), m_eventTarget));
}
}
}
void XWindowsScreenSaver::sendXScreenSaverCommand(Atom cmd, long arg1, long arg2)
{
XEvent event;
event.xclient.type = ClientMessage;
event.xclient.display = m_display;
event.xclient.window = m_xscreensaverSink;
event.xclient.message_type = m_atomScreenSaver;
event.xclient.format = 32;
event.xclient.data.l[0] = static_cast<long>(cmd);
event.xclient.data.l[1] = arg1;
event.xclient.data.l[2] = arg2;
event.xclient.data.l[3] = 0;
event.xclient.data.l[4] = 0;
LOG((CLOG_DEBUG "send xscreensaver command: %d %d %d", (long)cmd, arg1, arg2));
bool error = false;
{
XWindowsUtil::ErrorLock lock(m_display, &error);
XSendEvent(m_display, m_xscreensaver, False, 0, &event);
}
if (error) {
findXScreenSaver();
}
}
void XWindowsScreenSaver::watchForXScreenSaver()
{
// clear old watch list
clearWatchForXScreenSaver();
// add every child of the root to the list of windows to watch
Window root = DefaultRootWindow(m_display);
Window rw, pw, *cw;
unsigned int nc;
if (XQueryTree(m_display, root, &rw, &pw, &cw, &nc)) {
for (unsigned int i = 0; i < nc; ++i) {
addWatchXScreenSaver(cw[i]);
}
XFree(cw);
}
// now check for xscreensaver window in case it set the property
// before we could request property change events.
if (findXScreenSaver()) {
// found it so clear out our watch list
clearWatchForXScreenSaver();
}
}
void XWindowsScreenSaver::clearWatchForXScreenSaver()
{
// stop watching all windows
XWindowsUtil::ErrorLock lock(m_display);
for (WatchList::iterator index = m_watchWindows.begin(); index != m_watchWindows.end(); ++index) {
XSelectInput(m_display, index->first, index->second);
}
m_watchWindows.clear();
}
void XWindowsScreenSaver::addWatchXScreenSaver(Window window)
{
// get window attributes
bool error = false;
XWindowAttributes attr;
{
XWindowsUtil::ErrorLock lock(m_display, &error);
XGetWindowAttributes(m_display, window, &attr);
}
// if successful and window uses override_redirect (like xscreensaver
// does) then watch it for property changes.
if (!error && attr.override_redirect == True) {
error = false;
{
XWindowsUtil::ErrorLock lock(m_display, &error);
XSelectInput(m_display, window, attr.your_event_mask | PropertyChangeMask);
}
if (!error) {
// if successful then add the window to our list
m_watchWindows.insert(std::make_pair(window, attr.your_event_mask));
}
}
}
void XWindowsScreenSaver::updateDisableTimer()
{
if (m_disabled && !m_suppressDisable && m_disableTimer == NULL) {
// 5 seconds should be plenty often to suppress the screen saver
m_disableTimer = m_events->newTimer(5.0, this);
} else if ((!m_disabled || m_suppressDisable) && m_disableTimer != NULL) {
m_events->deleteTimer(m_disableTimer);
m_disableTimer = NULL;
}
}
void XWindowsScreenSaver::handleDisableTimer(const Event &, void *)
{
// send fake mouse motion directly to xscreensaver
if (m_xscreensaver != None) {
XEvent event;
event.xmotion.type = MotionNotify;
event.xmotion.display = m_display;
event.xmotion.window = m_xscreensaver;
event.xmotion.root = DefaultRootWindow(m_display);
event.xmotion.subwindow = None;
event.xmotion.time = CurrentTime;
event.xmotion.x = m_disablePos;
event.xmotion.y = 0;
event.xmotion.x_root = m_disablePos;
event.xmotion.y_root = 0;
event.xmotion.state = 0;
event.xmotion.is_hint = NotifyNormal;
event.xmotion.same_screen = True;
XWindowsUtil::ErrorLock lock(m_display);
XSendEvent(m_display, m_xscreensaver, False, 0, &event);
m_disablePos = 20 - m_disablePos;
}
}
void XWindowsScreenSaver::activateDPMS(bool activate)
{
#if HAVE_X11_EXTENSIONS_DPMS_H
if (m_dpms) {
// DPMSForceLevel will generate a BadMatch if DPMS is disabled
XWindowsUtil::ErrorLock lock(m_display);
DPMSForceLevel(m_display, activate ? DPMSModeStandby : DPMSModeOn);
}
#endif
}
void XWindowsScreenSaver::enableDPMS(bool enable)
{
#if HAVE_X11_EXTENSIONS_DPMS_H
if (m_dpms) {
if (enable) {
DPMSEnable(m_display);
} else {
DPMSDisable(m_display);
}
}
#endif
}
bool XWindowsScreenSaver::isDPMSEnabled() const
{
#if HAVE_X11_EXTENSIONS_DPMS_H
if (m_dpms) {
CARD16 level;
BOOL state;
DPMSInfo(m_display, &level, &state);
return (state != False);
} else {
return false;
}
#else
return false;
#endif
}
bool XWindowsScreenSaver::isDPMSActivated() const
{
#if HAVE_X11_EXTENSIONS_DPMS_H
if (m_dpms) {
CARD16 level;
BOOL state;
DPMSInfo(m_display, &level, &state);
return (level != DPMSModeOn);
} else {
return false;
}
#else
return false;
#endif
}
| 15,140
|
C++
|
.cpp
| 494
| 26.94332
| 115
| 0.712992
|
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,580
|
MSWindowsEventQueueBuffer.cpp
|
deskflow_deskflow/src/lib/platform/MSWindowsEventQueueBuffer.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 "platform/MSWindowsEventQueueBuffer.h"
#include "arch/win32/ArchMiscWindows.h"
#include "base/IEventQueue.h"
#include "mt/Thread.h"
//
// EventQueueTimer
//
class EventQueueTimer
{
};
//
// MSWindowsEventQueueBuffer
//
MSWindowsEventQueueBuffer::MSWindowsEventQueueBuffer(IEventQueue *events) : m_events(events)
{
// remember thread. we'll be posting messages to it.
m_thread = GetCurrentThreadId();
// create a message type for custom events
m_userEvent = RegisterWindowMessage("DESKFLOW_USER_EVENT");
// get message type for daemon quit
m_daemonQuit = ArchMiscWindows::getDaemonQuitMessage();
// make sure this thread has a message queue
MSG dummy;
PeekMessage(&dummy, NULL, WM_USER, WM_USER, PM_NOREMOVE);
}
MSWindowsEventQueueBuffer::~MSWindowsEventQueueBuffer()
{
// do nothing
}
void MSWindowsEventQueueBuffer::waitForEvent(double timeout)
{
// check if messages are available first. if we don't do this then
// MsgWaitForMultipleObjects() will block even if the queue isn't
// empty if the messages in the queue were there before the last
// call to GetMessage()/PeekMessage().
if (HIWORD(GetQueueStatus(QS_ALLPOSTMESSAGE)) != 0) {
return;
}
// convert timeout
DWORD t;
if (timeout < 0.0) {
t = INFINITE;
} else {
t = (DWORD)(1000.0 * timeout);
}
// wait for a message. we cannot be interrupted by thread
// cancellation but that's okay because we're run in the main
// thread and we never cancel that thread.
HANDLE dummy[1];
MsgWaitForMultipleObjects(0, dummy, FALSE, t, QS_ALLPOSTMESSAGE);
}
IEventQueueBuffer::Type MSWindowsEventQueueBuffer::getEvent(Event &event, UInt32 &dataID)
{
// NOTE: QS_ALLINPUT was replaced with QS_ALLPOSTMESSAGE.
//
// peek at messages first. waiting for QS_ALLINPUT will return
// if a message has been sent to our window but GetMessage will
// dispatch that message behind our backs and block. PeekMessage
// will also dispatch behind our backs but won't block.
if (!PeekMessage(&m_event, NULL, 0, 0, PM_NOREMOVE) && !PeekMessage(&m_event, (HWND)-1, 0, 0, PM_NOREMOVE)) {
return kNone;
}
// BOOL. yeah, right.
BOOL result = GetMessage(&m_event, NULL, 0, 0);
if (result == -1) {
return kNone;
} else if (result == 0) {
event = Event(Event::kQuit);
return kSystem;
} else if (m_daemonQuit != 0 && m_event.message == m_daemonQuit) {
event = Event(Event::kQuit);
return kSystem;
} else if (m_event.message == m_userEvent) {
dataID = static_cast<UInt32>(m_event.wParam);
return kUser;
} else {
event = Event(Event::kSystem, m_events->getSystemTarget(), &m_event);
return kSystem;
}
}
bool MSWindowsEventQueueBuffer::addEvent(UInt32 dataID)
{
return (PostThreadMessage(m_thread, m_userEvent, static_cast<WPARAM>(dataID), 0) != 0);
}
bool MSWindowsEventQueueBuffer::isEmpty() const
{
return (HIWORD(GetQueueStatus(QS_ALLPOSTMESSAGE)) == 0);
}
EventQueueTimer *MSWindowsEventQueueBuffer::newTimer(double, bool) const
{
return new EventQueueTimer;
}
void MSWindowsEventQueueBuffer::deleteTimer(EventQueueTimer *timer) const
{
delete timer;
}
| 3,882
|
C++
|
.cpp
| 113
| 31.769912
| 111
| 0.7368
|
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,581
|
XWindowsClipboardHTMLConverter.cpp
|
deskflow_deskflow/src/lib/platform/XWindowsClipboardHTMLConverter.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 "platform/XWindowsClipboardHTMLConverter.h"
#include "base/Unicode.h"
//
// XWindowsClipboardHTMLConverter
//
XWindowsClipboardHTMLConverter::XWindowsClipboardHTMLConverter(Display *display, const char *name)
: m_atom(XInternAtom(display, name, False))
{
// do nothing
}
XWindowsClipboardHTMLConverter::~XWindowsClipboardHTMLConverter()
{
// do nothing
}
IClipboard::EFormat XWindowsClipboardHTMLConverter::getFormat() const
{
return IClipboard::kHTML;
}
Atom XWindowsClipboardHTMLConverter::getAtom() const
{
return m_atom;
}
int XWindowsClipboardHTMLConverter::getDataSize() const
{
return 8;
}
String XWindowsClipboardHTMLConverter::fromIClipboard(const String &data) const
{
return data;
}
String XWindowsClipboardHTMLConverter::toIClipboard(const String &data) const
{
if (Unicode::isUTF8(data)) {
return data;
} else {
return Unicode::UTF16ToUTF8(data);
}
}
| 1,643
|
C++
|
.cpp
| 55
| 27.854545
| 98
| 0.784537
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.