Reorganized source tree. Moved client.cpp into cmd/synergy as

synergy.cpp and server.cpp into cmd/synergyd as synergyd.cpp.
Moved and renamed related files.  Moved remaining source files
into lib/....  Modified and added makefiles as appropriate.
Result is that library files are under lib with each library
in its own directory and program files are under cmd with each
command in its own directory.
This commit is contained in:
crs
2002-07-30 16:52:46 +00:00
parent 9792d35a6b
commit fee4095624
201 changed files with 367 additions and 375 deletions

View File

@@ -0,0 +1,47 @@
#include "CClientProxy.h"
#include "IInputStream.h"
#include "IOutputStream.h"
//
// CClientProxy
//
CClientProxy::CClientProxy(IServer* server, const CString& name,
IInputStream* input, IOutputStream* output) :
m_server(server),
m_name(name),
m_input(input),
m_output(output)
{
// do nothing
}
CClientProxy::~CClientProxy()
{
delete m_output;
delete m_input;
}
IServer*
CClientProxy::getServer() const
{
return m_server;
}
IInputStream*
CClientProxy::getInputStream() const
{
return m_input;
}
IOutputStream*
CClientProxy::getOutputStream() const
{
return m_output;
}
CString
CClientProxy::getName() const
{
return m_name;
}

78
lib/server/CClientProxy.h Normal file
View File

@@ -0,0 +1,78 @@
#ifndef CCLIENTPROXY_H
#define CCLIENTPROXY_H
#include "IClient.h"
#include "CString.h"
class IInputStream;
class IOutputStream;
class IServer;
//! Generic proxy for client
class CClientProxy : public IClient {
public:
/*!
\c name is the name of the client.
*/
CClientProxy(IServer* server, const CString& name,
IInputStream* adoptedInput,
IOutputStream* adoptedOutput);
~CClientProxy();
//! @name accessors
//@{
//! Get server
/*!
Returns the server passed to the c'tor.
*/
IServer* getServer() const;
//! Get input stream
/*!
Returns the input stream passed to the c'tor.
*/
IInputStream* getInputStream() const;
//! Get output stream
/*!
Returns the output stream passed to the c'tor.
*/
IOutputStream* getOutputStream() const;
//@}
// IClient overrides
virtual bool open() = 0;
virtual void mainLoop() = 0;
virtual void close() = 0;
virtual void enter(SInt32 xAbs, SInt32 yAbs,
UInt32 seqNum, KeyModifierMask mask,
bool forScreensaver) = 0;
virtual bool leave() = 0;
virtual void setClipboard(ClipboardID, const CString&) = 0;
virtual void grabClipboard(ClipboardID) = 0;
virtual void setClipboardDirty(ClipboardID, bool) = 0;
virtual void keyDown(KeyID, KeyModifierMask) = 0;
virtual void keyRepeat(KeyID, KeyModifierMask, SInt32 count) = 0;
virtual void keyUp(KeyID, KeyModifierMask) = 0;
virtual void mouseDown(ButtonID) = 0;
virtual void mouseUp(ButtonID) = 0;
virtual void mouseMove(SInt32 xAbs, SInt32 yAbs) = 0;
virtual void mouseWheel(SInt32 delta) = 0;
virtual void screensaver(bool activate) = 0;
virtual CString getName() const;
virtual SInt32 getJumpZoneSize() const = 0;
virtual void getShape(SInt32& x, SInt32& y,
SInt32& width, SInt32& height) const = 0;
virtual void getCursorPos(SInt32& x, SInt32& y) const = 0;
virtual void getCursorCenter(SInt32& x, SInt32& y) const = 0;
private:
IServer* m_server;
CString m_name;
IInputStream* m_input;
IOutputStream* m_output;
};
#endif

View File

@@ -0,0 +1,353 @@
#include "CClientProxy1_0.h"
#include "CServer.h"
#include "CClipboard.h"
#include "CProtocolUtil.h"
#include "XSynergy.h"
#include "IInputStream.h"
#include "IOutputStream.h"
#include "CLock.h"
#include "CThread.h"
#include "CLog.h"
#include "CStopwatch.h"
#include <cstring>
//
// CClientProxy1_0
//
CClientProxy1_0::CClientProxy1_0(IServer* server, const CString& name,
IInputStream* input, IOutputStream* output) :
CClientProxy(server, name, input, output)
{
for (UInt32 i = 0; i < kClipboardEnd; ++i) {
m_clipboardDirty[i] = true;
}
}
CClientProxy1_0::~CClientProxy1_0()
{
// do nothing
}
bool
CClientProxy1_0::open()
{
// send request
log((CLOG_DEBUG1 "querying client \"%s\" info", getName().c_str()));
CProtocolUtil::writef(getOutputStream(), kMsgQInfo);
getOutputStream()->flush();
// wait for and verify reply
UInt8 code[4];
for (;;) {
UInt32 n = getInputStream()->read(code, 4, -1.0);
if (n == 4) {
if (memcmp(code, kMsgCNoop, 4) == 0) {
// discard heartbeats
continue;
}
if (memcmp(code, kMsgDInfo, 4) == 0) {
break;
}
}
throw XBadClient();
}
// handle reply
recvInfo(false);
return true;
}
void
CClientProxy1_0::mainLoop()
{
// handle messages until the client hangs up or stops sending heartbeats
CStopwatch heartTimer;
for (;;) {
CThread::testCancel();
// wait for a message
UInt8 code[4];
UInt32 n = getInputStream()->read(code, 4, kHeartRate);
CThread::testCancel();
// check if client hungup
if (n == 0) {
log((CLOG_NOTE "client \"%s\" disconnected", getName().c_str()));
return;
}
// check if client has stopped sending heartbeats
if (n == (UInt32)-1) {
/* FIXME -- disabled to avoid masking bugs
if (heartTimer.getTime() > kHeartDeath) {
log((CLOG_NOTE "client \"%s\" is dead", getName().c_str()));
return;
}
*/
continue;
}
// got a message so reset heartbeat monitor
heartTimer.reset();
// verify we got an entire code
if (n != 4) {
log((CLOG_ERR "incomplete message from \"%s\": %d bytes", getName().c_str(), n));
// client sent an incomplete message
throw XBadClient();
}
// parse message
log((CLOG_DEBUG2 "msg from \"%s\": %c%c%c%c", getName().c_str(), code[0], code[1], code[2], code[3]));
if (memcmp(code, kMsgDInfo, 4) == 0) {
recvInfo(true);
}
else if (memcmp(code, kMsgCNoop, 4) == 0) {
// discard no-ops
continue;
}
else if (memcmp(code, kMsgCClipboard, 4) == 0) {
recvGrabClipboard();
}
else if (memcmp(code, kMsgDClipboard, 4) == 0) {
recvClipboard();
}
// note -- more message handlers go here
else {
log((CLOG_ERR "invalid message from client \"%s\"", getName().c_str()));
// unknown message
throw XBadClient();
}
}
}
void
CClientProxy1_0::close()
{
log((CLOG_DEBUG1 "send close to \"%s\"", getName().c_str()));
CProtocolUtil::writef(getOutputStream(), kMsgCClose);
// force the close to be sent before we return
getOutputStream()->flush();
}
void
CClientProxy1_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));
CProtocolUtil::writef(getOutputStream(), kMsgCEnter,
xAbs, yAbs, seqNum, mask);
}
bool
CClientProxy1_0::leave()
{
log((CLOG_DEBUG1 "send leave to \"%s\"", getName().c_str()));
CProtocolUtil::writef(getOutputStream(), kMsgCLeave);
// we can never prevent the user from leaving
return true;
}
void
CClientProxy1_0::setClipboard(ClipboardID id, const CString& data)
{
// ignore if this clipboard is already clean
CLock lock(&m_mutex);
if (m_clipboardDirty[id]) {
// this clipboard is now clean
m_clipboardDirty[id] = false;
log((CLOG_DEBUG "send clipboard %d to \"%s\" size=%d", id, getName().c_str(), data.size()));
CProtocolUtil::writef(getOutputStream(), kMsgDClipboard, id, 0, &data);
}
}
void
CClientProxy1_0::grabClipboard(ClipboardID id)
{
log((CLOG_DEBUG "send grab clipboard %d to \"%s\"", id, getName().c_str()));
CProtocolUtil::writef(getOutputStream(), kMsgCClipboard, id, 0);
// this clipboard is now dirty
CLock lock(&m_mutex);
m_clipboardDirty[id] = true;
}
void
CClientProxy1_0::setClipboardDirty(ClipboardID id, bool dirty)
{
CLock lock(&m_mutex);
m_clipboardDirty[id] = dirty;
}
void
CClientProxy1_0::keyDown(KeyID key, KeyModifierMask mask)
{
log((CLOG_DEBUG1 "send key down to \"%s\" id=%d, mask=0x%04x", getName().c_str(), key, mask));
CProtocolUtil::writef(getOutputStream(), kMsgDKeyDown, key, mask);
}
void
CClientProxy1_0::keyRepeat(KeyID key, KeyModifierMask mask, SInt32 count)
{
log((CLOG_DEBUG1 "send key repeat to \"%s\" id=%d, mask=0x%04x, count=%d", getName().c_str(), key, mask, count));
CProtocolUtil::writef(getOutputStream(), kMsgDKeyRepeat, key, mask, count);
}
void
CClientProxy1_0::keyUp(KeyID key, KeyModifierMask mask)
{
log((CLOG_DEBUG1 "send key up to \"%s\" id=%d, mask=0x%04x", getName().c_str(), key, mask));
CProtocolUtil::writef(getOutputStream(), kMsgDKeyUp, key, mask);
}
void
CClientProxy1_0::mouseDown(ButtonID button)
{
log((CLOG_DEBUG1 "send mouse down to \"%s\" id=%d", getName().c_str(), button));
CProtocolUtil::writef(getOutputStream(), kMsgDMouseDown, button);
}
void
CClientProxy1_0::mouseUp(ButtonID button)
{
log((CLOG_DEBUG1 "send mouse up to \"%s\" id=%d", getName().c_str(), button));
CProtocolUtil::writef(getOutputStream(), kMsgDMouseUp, button);
}
void
CClientProxy1_0::mouseMove(SInt32 xAbs, SInt32 yAbs)
{
log((CLOG_DEBUG2 "send mouse move to \"%s\" %d,%d", getName().c_str(), xAbs, yAbs));
CProtocolUtil::writef(getOutputStream(), kMsgDMouseMove, xAbs, yAbs);
}
void
CClientProxy1_0::mouseWheel(SInt32 delta)
{
log((CLOG_DEBUG2 "send mouse wheel to \"%s\" %+d", getName().c_str(), delta));
CProtocolUtil::writef(getOutputStream(), kMsgDMouseWheel, delta);
}
void
CClientProxy1_0::screensaver(bool on)
{
log((CLOG_DEBUG1 "send screen saver to \"%s\" on=%d", getName().c_str(), on ? 1 : 0));
CProtocolUtil::writef(getOutputStream(), kMsgCScreenSaver, on ? 1 : 0);
}
SInt32
CClientProxy1_0::getJumpZoneSize() const
{
CLock lock(&m_mutex);
return m_info.m_zoneSize;
}
void
CClientProxy1_0::getShape(SInt32& x, SInt32& y, SInt32& w, SInt32& h) const
{
CLock lock(&m_mutex);
x = m_info.m_x;
y = m_info.m_y;
w = m_info.m_w;
h = m_info.m_h;
}
void
CClientProxy1_0::getCursorPos(SInt32&, SInt32&) const
{
assert(0 && "shouldn't be called");
}
void
CClientProxy1_0::getCursorCenter(SInt32& x, SInt32& y) const
{
CLock lock(&m_mutex);
x = m_info.m_mx;
y = m_info.m_my;
}
void
CClientProxy1_0::recvInfo(bool notify)
{
{
CLock lock(&m_mutex);
// parse the message
SInt16 x, y, w, h, zoneSize, mx, my;
CProtocolUtil::readf(getInputStream(), kMsgDInfo + 4,
&x, &y, &w, &h, &zoneSize, &mx, &my);
log((CLOG_DEBUG "received client \"%s\" info shape=%d,%d %dx%d, zone=%d, pos=%d,%d", getName().c_str(), x, y, w, h, zoneSize, mx, my));
// validate
if (w <= 0 || h <= 0 || zoneSize < 0) {
throw XBadClient();
}
if (mx < x || my < y || mx >= x + w || my >= y + h) {
throw XBadClient();
}
// save
m_info.m_x = x;
m_info.m_y = y;
m_info.m_w = w;
m_info.m_h = h;
m_info.m_zoneSize = zoneSize;
m_info.m_mx = mx;
m_info.m_my = my;
}
// tell server of change
if (notify) {
getServer()->onInfoChanged(getName(), m_info);
}
// acknowledge receipt
log((CLOG_DEBUG1 "send info ack to \"%s\"", getName().c_str()));
CProtocolUtil::writef(getOutputStream(), kMsgCInfoAck);
}
void
CClientProxy1_0::recvClipboard()
{
// parse message
ClipboardID id;
UInt32 seqNum;
CString data;
CProtocolUtil::readf(getInputStream(), kMsgDClipboard + 4, &id, &seqNum, &data);
log((CLOG_DEBUG "received client \"%s\" clipboard %d seqnum=%d, size=%d", getName().c_str(), id, seqNum, data.size()));
// validate
if (id >= kClipboardEnd) {
throw XBadClient();
}
// send update. this calls us back to reset our clipboard dirty flag
// so don't hold a lock during the call.
getServer()->onClipboardChanged(id, seqNum, data);
}
void
CClientProxy1_0::recvGrabClipboard()
{
// parse message
ClipboardID id;
UInt32 seqNum;
CProtocolUtil::readf(getInputStream(), kMsgCClipboard + 4, &id, &seqNum);
log((CLOG_DEBUG "received client \"%s\" grabbed clipboard %d seqnum=%d", getName().c_str(), id, seqNum));
// validate
if (id >= kClipboardEnd) {
throw XBadClient();
}
// send update. this calls us back to reset our clipboard dirty flag
// so don't hold a lock during the call.
getServer()->onGrabClipboard(getName(), id, seqNum);
}

View File

@@ -0,0 +1,52 @@
#ifndef CCLIENTPROXY1_0_H
#define CCLIENTPROXY1_0_H
#include "CClientProxy.h"
#include "ProtocolTypes.h"
#include "CMutex.h"
//! Proxy for client implementing protocol version 1.0
class CClientProxy1_0 : public CClientProxy {
public:
CClientProxy1_0(IServer* server, const CString& name,
IInputStream* adoptedInput,
IOutputStream* adoptedOutput);
~CClientProxy1_0();
// IClient overrides
virtual bool open();
virtual void mainLoop();
virtual void close();
virtual void enter(SInt32 xAbs, SInt32 yAbs,
UInt32 seqNum, KeyModifierMask mask,
bool forScreensaver);
virtual bool leave();
virtual void setClipboard(ClipboardID, const CString&);
virtual void grabClipboard(ClipboardID);
virtual void setClipboardDirty(ClipboardID, bool);
virtual void keyDown(KeyID, KeyModifierMask);
virtual void keyRepeat(KeyID, KeyModifierMask, SInt32 count);
virtual void keyUp(KeyID, KeyModifierMask);
virtual void mouseDown(ButtonID);
virtual void mouseUp(ButtonID);
virtual void mouseMove(SInt32 xAbs, SInt32 yAbs);
virtual void mouseWheel(SInt32 delta);
virtual void screensaver(bool activate);
virtual SInt32 getJumpZoneSize() const;
virtual void getShape(SInt32& x, SInt32& y,
SInt32& width, SInt32& height) const;
virtual void getCursorPos(SInt32& x, SInt32& y) const;
virtual void getCursorCenter(SInt32& x, SInt32& y) const;
private:
void recvInfo(bool notify);
void recvClipboard();
void recvGrabClipboard();
private:
CMutex m_mutex;
CClientInfo m_info;
bool m_clipboardDirty[kClipboardEnd];
};
#endif

699
lib/server/CConfig.cpp Normal file
View File

@@ -0,0 +1,699 @@
#include "CConfig.h"
#include "ProtocolTypes.h"
#include "XSocket.h"
#include "stdistream.h"
#include "stdostream.h"
//
// CConfig
//
CConfig::CConfig()
{
// do nothing
}
CConfig::~CConfig()
{
// do nothing
}
bool
CConfig::addScreen(const CString& 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, CCell()));
// add name
m_nameToCanonicalName.insert(std::make_pair(name, name));
return true;
}
void
CConfig::removeScreen(const CString& name)
{
// get canonical name and find cell
CString canonical = getCanonicalName(name);
CCellMap::iterator index = m_map.find(canonical);
if (index == m_map.end()) {
return;
}
// remove from map
m_map.erase(index);
// disconnect
for (index = m_map.begin(); index != m_map.end(); ++index) {
CCell& cell = index->second;
for (SInt32 i = 0; i <= kLastDirection - kFirstDirection; ++i)
if (getCanonicalName(cell.m_neighbor[i]) == canonical) {
cell.m_neighbor[i].erase();
}
}
// remove aliases (and canonical name)
for (CNameMap::iterator index = m_nameToCanonicalName.begin();
index != m_nameToCanonicalName.end(); ) {
if (index->second == canonical) {
m_nameToCanonicalName.erase(index++);
}
else {
++index;
}
}
}
void
CConfig::removeAllScreens()
{
m_map.clear();
m_nameToCanonicalName.clear();
}
bool
CConfig::addAlias(const CString& canonical, const CString& alias)
{
// alias name must not exist
if (m_nameToCanonicalName.find(alias) != m_nameToCanonicalName.end()) {
return false;
}
// canonical name must be known
if (m_nameToCanonicalName.find(canonical) == m_nameToCanonicalName.end()) {
return false;
}
// insert alias
m_nameToCanonicalName.insert(std::make_pair(alias, canonical));
return true;
}
bool
CConfig::removeAlias(const CString& alias)
{
// must not be a canonical name
if (m_map.find(alias) != m_map.end()) {
return false;
}
// find alias
CNameMap::iterator index = m_nameToCanonicalName.find(alias);
if (index == m_nameToCanonicalName.end()) {
return false;
}
// remove alias
m_nameToCanonicalName.erase(index);
return true;
}
void
CConfig::removeAllAliases()
{
// remove all names
m_nameToCanonicalName.clear();
// put the canonical names back in
for (CCellMap::iterator index = m_map.begin();
index != m_map.end(); ++index) {
m_nameToCanonicalName.insert(
std::make_pair(index->first, index->first));
}
}
bool
CConfig::connect(const CString& srcName,
EDirection srcSide, const CString& dstName)
{
// find source cell
CCellMap::iterator index = m_map.find(getCanonicalName(srcName));
if (index == m_map.end()) {
return false;
}
// connect side (overriding any previous connection). we
// canonicalize in getNeighbor() instead of here because the
// destination name doesn't have to exist yet.
index->second.m_neighbor[srcSide - kFirstDirection] = dstName;
return true;
}
bool
CConfig::disconnect(const CString& srcName, EDirection srcSide)
{
// find source cell
CCellMap::iterator index = m_map.find(srcName);
if (index == m_map.end()) {
return false;
}
// disconnect side
index->second.m_neighbor[srcSide - kFirstDirection].erase();
return true;
}
void
CConfig::setSynergyAddress(const CNetworkAddress& addr)
{
m_synergyAddress = addr;
}
void
CConfig::setHTTPAddress(const CNetworkAddress& addr)
{
m_httpAddress = addr;
}
bool
CConfig::isValidScreenName(const CString& 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*
// check each dot separated part
CString::size_type b = 0;
for (;;) {
// find end of part
CString::size_type e = name.find('.', b);
if (e == CString::npos) {
e = name.size();
}
// part may not be empty
if (e - b < 1) {
return false;
}
// check first and last characters
if (!isalnum(name[b]) || !isalnum(name[e - 1])) {
return false;
}
// check interior characters
for (CString::size_type i = b; i < e; ++i) {
if (!isalnum(name[i]) && name[i] != '-') {
return false;
}
}
// next part
if (e == name.size()) {
// no more parts
break;
}
b = e + 1;
}
return true;
}
CConfig::const_iterator
CConfig::begin() const
{
return const_iterator(m_map.begin());
}
CConfig::const_iterator
CConfig::end() const
{
return const_iterator(m_map.end());
}
bool
CConfig::isScreen(const CString& name) const
{
return (m_nameToCanonicalName.count(name) > 0);
}
bool
CConfig::isCanonicalName(const CString& name) const
{
return CStringUtil::CaselessCmp::equal(getCanonicalName(name), name);
}
CString
CConfig::getCanonicalName(const CString& name) const
{
CNameMap::const_iterator index = m_nameToCanonicalName.find(name);
if (index == m_nameToCanonicalName.end()) {
return CString();
}
else {
return index->second;
}
}
CString
CConfig::getNeighbor(const CString& srcName, EDirection srcSide) const
{
// find source cell
CCellMap::const_iterator index = m_map.find(getCanonicalName(srcName));
if (index == m_map.end()) {
return CString();
}
// return connection
return getCanonicalName(index->second.m_neighbor[
srcSide - kFirstDirection]);
}
const CNetworkAddress&
CConfig::getSynergyAddress() const
{
return m_synergyAddress;
}
const CNetworkAddress&
CConfig::getHTTPAddress() const
{
return m_httpAddress;
}
const char*
CConfig::dirName(EDirection dir)
{
static const char* s_name[] = { "left", "right", "top", "bottom" };
return s_name[dir - kFirstDirection];
}
bool
CConfig::readLine(std::istream& s, CString& line)
{
s >> std::ws;
while (std::getline(s, line)) {
// strip comments and then trailing whitespace
CString::size_type i = line.find('#');
if (i != CString::npos) {
line.erase(i);
}
i = line.find_last_not_of(" \t");
if (i != CString::npos) {
line.erase(i + 1);
}
// return non empty line
if (!line.empty()) {
return true;
}
s >> std::ws;
}
return false;
}
void
CConfig::readSection(std::istream& s)
{
static const char s_section[] = "section:";
static const char s_network[] = "network";
static const char s_screens[] = "screens";
static const char s_links[] = "links";
static const char s_aliases[] = "aliases";
CString line;
if (!readLine(s, line)) {
// no more sections
return;
}
// should be a section header
if (line.find(s_section) != 0) {
throw XConfigRead("found data outside section");
}
// get section name
CString::size_type i = line.find_first_not_of(" \t", sizeof(s_section) - 1);
if (i == CString::npos) {
throw XConfigRead("section name is missing");
}
CString name = line.substr(i);
i = name.find_first_of(" \t");
if (i != CString::npos) {
throw XConfigRead("unexpected data after section name");
}
// read section
if (name == s_network) {
readSectionNetwork(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("unknown section name");
}
}
void
CConfig::readSectionNetwork(std::istream& s)
{
CString line;
CString name;
while (readLine(s, line)) {
// check for end of section
if (line == "end") {
return;
}
// parse argument: `<name>=<value>'
CString::size_type i = line.find_first_of(" \t=");
if (i == 0) {
throw XConfigRead("missing argument name");
}
if (i == CString::npos) {
throw XConfigRead("missing = in argument");
}
CString name = line.substr(0, i);
i = line.find_first_not_of(" \t", i);
if (i == CString::npos || line[i] != '=') {
throw XConfigRead("missing = in argument");
}
i = line.find_first_not_of(" \t", i + 1);
CString value;
if (i != CString::npos) {
value = line.substr(i);
}
if (value.empty()) {
throw XConfigRead("missing value after =");
}
if (name == "address") {
try {
m_synergyAddress = CNetworkAddress(value, kDefaultPort);
}
catch (XSocketAddress&) {
throw XConfigRead("invalid address argument");
}
}
else if (name == "http") {
try {
m_httpAddress = CNetworkAddress(value, kDefaultPort + 1);
}
catch (XSocketAddress&) {
throw XConfigRead("invalid http argument");
}
}
else {
throw XConfigRead("unknown argument");
}
}
throw XConfigRead("unexpected end of screens section");
}
void
CConfig::readSectionScreens(std::istream& s)
{
CString line;
CString name;
while (readLine(s, line)) {
// check for end of section
if (line == "end") {
return;
}
// see if it's the next screen
if (line[line.size() - 1] == ':') {
// strip :
name = line.substr(0, line.size() - 1);
// verify validity of screen name
if (!isValidScreenName(name)) {
throw XConfigRead("invalid screen name");
}
// add the screen to the configuration
if (!addScreen(name)) {
throw XConfigRead("duplicate screen name");
}
}
else if (name.empty()) {
throw XConfigRead("argument before first screen");
}
else {
throw XConfigRead("unknown argument");
}
}
throw XConfigRead("unexpected end of screens section");
}
void
CConfig::readSectionLinks(std::istream& s)
{
CString line;
CString screen;
while (readLine(s, 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("unknown screen name");
}
if (!isCanonicalName(screen)) {
throw XConfigRead("cannot use screen name alias here");
}
}
else if (screen.empty()) {
throw XConfigRead("argument before first screen");
}
else {
// parse argument: `<name>=<value>'
CString::size_type i = line.find_first_of(" \t=");
if (i == 0) {
throw XConfigRead("missing argument name");
}
if (i == CString::npos) {
throw XConfigRead("missing = in argument");
}
CString name = line.substr(0, i);
i = line.find_first_not_of(" \t", i);
if (i == CString::npos || line[i] != '=') {
throw XConfigRead("missing = in argument");
}
i = line.find_first_not_of(" \t", i + 1);
CString value;
if (i != CString::npos) {
value = line.substr(i);
}
// handle argument
if (name == "left") {
if (!isScreen(value)) {
throw XConfigRead("unknown screen");
}
connect(screen, kLeft, value);
}
else if (name == "right") {
if (!isScreen(value)) {
throw XConfigRead("unknown screen");
}
connect(screen, kRight, value);
}
else if (name == "up") {
if (!isScreen(value)) {
throw XConfigRead("unknown screen");
}
connect(screen, kTop, value);
}
else if (name == "down") {
if (!isScreen(value)) {
throw XConfigRead("unknown screen");
}
connect(screen, kBottom, value);
}
else {
// unknown argument
throw XConfigRead("unknown argument");
}
}
}
throw XConfigRead("unexpected end of links section");
}
void
CConfig::readSectionAliases(std::istream& s)
{
CString line;
CString screen;
while (readLine(s, 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("unknown screen name");
}
if (!isCanonicalName(screen)) {
throw XConfigRead("cannot use screen name alias here");
}
}
else if (screen.empty()) {
throw XConfigRead("argument before first screen");
}
else {
// verify validity of screen name
if (!isValidScreenName(line)) {
throw XConfigRead("invalid screen alias");
}
// add alias
if (!addAlias(screen, line)) {
throw XConfigRead("alias is duplicate screen name");
}
}
}
throw XConfigRead("unexpected end of aliases section");
}
//
// CConfig I/O
//
std::istream&
operator>>(std::istream& s, CConfig& config)
{
// FIXME -- should track line and column to improve error reporting
CConfig tmp;
while (s) {
tmp.readSection(s);
}
config = tmp;
return s;
}
std::ostream&
operator<<(std::ostream& s, const CConfig& config)
{
// network section
s << "section: network" << std::endl;
if (config.m_synergyAddress.isValid()) {
s << "\taddress=" << config.m_synergyAddress.getHostname().c_str() <<
std::endl;
}
if (config.m_httpAddress.isValid()) {
s << "\thttp=" << config.m_httpAddress.getHostname().c_str() <<
std::endl;
}
s << "end" << std::endl;
// screens section
s << "section: screens" << std::endl;
for (CConfig::const_iterator screen = config.begin();
screen != config.end(); ++screen) {
s << "\t" << screen->c_str() << ":" << std::endl;
}
s << "end" << std::endl;
// links section
CString neighbor;
s << "section: links" << std::endl;
for (CConfig::const_iterator screen = config.begin();
screen != config.end(); ++screen) {
s << "\t" << screen->c_str() << ":" << std::endl;
neighbor = config.getNeighbor(*screen, kLeft);
if (!neighbor.empty()) {
s << "\t\tleft=" << neighbor.c_str() << std::endl;
}
neighbor = config.getNeighbor(*screen, kRight);
if (!neighbor.empty()) {
s << "\t\tright=" << neighbor.c_str() << std::endl;
}
neighbor = config.getNeighbor(*screen, kTop);
if (!neighbor.empty()) {
s << "\t\tup=" << neighbor.c_str() << std::endl;
}
neighbor = config.getNeighbor(*screen, kBottom);
if (!neighbor.empty()) {
s << "\t\tdown=" << neighbor.c_str() << 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
CConfig::CNameMap aliases;
for (CConfig::CNameMap::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
CString screen;
s << "section: aliases" << std::endl;
for (CConfig::CNameMap::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;
}
return s;
}
//
// CConfig I/O exceptions
//
XConfigRead::XConfigRead(const CString& error) :
m_error(error)
{
// do nothing
}
XConfigRead::~XConfigRead()
{
// do nothing
}
CString
XConfigRead::getWhat() const throw()
{
return format("XConfigRead", "read error: %s", m_error.c_str());
}

255
lib/server/CConfig.h Normal file
View File

@@ -0,0 +1,255 @@
#ifndef CCONFIG_H
#define CCONFIG_H
#include "ProtocolTypes.h"
#include "CNetworkAddress.h"
#include "XBase.h"
#include "stdmap.h"
#include "stdset.h"
#include <iosfwd>
class CConfig;
namespace std {
struct iterator_traits<CConfig> {
typedef CString value_type;
typedef ptrdiff_t difference_type;
typedef bidirectional_iterator_tag iterator_category;
typedef CString* pointer;
typedef CString& reference;
};
};
//! Server configuration
/*!
This class holds server configuration information. That includes
the names of screens and their aliases, the links between them,
and network addresses.
Note that case is preserved in screen names but is ignored when
comparing names. Screen names and their aliases share a
namespace and must be unique.
*/
class CConfig {
private:
class CCell {
public:
CString m_neighbor[kLastDirection - kFirstDirection + 1];
};
typedef std::map<CString, CCell, CStringUtil::CaselessCmp> CCellMap;
public:
typedef CCellMap::const_iterator internal_const_iterator;
class const_iterator : std::iterator_traits<CConfig> {
public:
explicit const_iterator() : m_i() { }
explicit const_iterator(const internal_const_iterator& i) : m_i(i) { }
const_iterator& operator=(const const_iterator& i) {
m_i = i.m_i;
return *this;
}
CString operator*() { return m_i->first; }
const CString* operator->() { return &(m_i->first); }
const_iterator& operator++() { ++m_i; return *this; }
const_iterator operator++(int) { return const_iterator(m_i++); }
const_iterator& operator--() { --m_i; return *this; }
const_iterator operator--(int) { return const_iterator(m_i--); }
bool operator==(const const_iterator& i) const {
return (m_i == i.m_i);
}
bool operator!=(const const_iterator& i) const {
return (m_i != i.m_i);
}
private:
internal_const_iterator m_i;
};
CConfig();
virtual ~CConfig();
//! @name manipulators
//@{
//! Add screen
/*!
Adds a screen, returning true iff successful. If a screen or
alias with the given name exists then it fails.
*/
bool addScreen(const CString& name);
//! Remove screen
/*!
Removes a screen. This also removes aliases for the screen and
disconnects any connections to the screen. \c name may be an
alias.
*/
void removeScreen(const CString& name);
//! Remove all screens
/*!
Removes all screens, aliases, and connections.
*/
void removeAllScreens();
//! Add alias
/*!
Adds an alias for a screen name. An alias can be used
any place the canonical screen name can (except addScreen()).
Returns false if the alias name already exists or the canonical
name is unknown, otherwise returns true.
*/
bool addAlias(const CString& canonical,
const CString& alias);
//! Remove alias
/*!
Removes an alias for a screen name. It returns false if the
alias is unknown or a canonical name, otherwise returns true.
*/
bool removeAlias(const CString& alias);
//! Remove all aliases
/*!
This removes all aliases but not the screens.
*/
void removeAllAliases();
//! Connect screens
/*!
Establishes a one-way connection between opposite edges of two
screens. The user will be able to jump from the \c srcSide of
screen \c srcName to the opposite side of screen \c dstName
when both screens are connected to the server and the user
isn't locked to a screen. Returns false if \c srcName is
unknown.
*/
bool connect(const CString& srcName,
EDirection srcSide,
const CString& dstName);
//! Disconnect screens
/*!
Removes a connection created by connect(). Returns false if
\c srcName is unknown.
*/
bool disconnect(const CString& srcName,
EDirection srcSide);
//! Set server address
/*!
Set the synergy listen addresses. There is no default address so
this must be called to run a server using this configuration.
*/
void setSynergyAddress(const CNetworkAddress&);
//! Set HTTP server address
/*!
Set the HTTP listen addresses. There is no default address so
this must be called to run an HTTP server using this configuration.
*/
void setHTTPAddress(const CNetworkAddress&);
//@}
//! @name accessors
//@{
//! Test screen name validity
/*!
Returns true iff \c name is a valid screen name.
*/
bool isValidScreenName(const CString& name) const;
//! Get beginning (canonical) screen name iterator
const_iterator begin() const;
//! Get ending (canonical) screen name iterator
const_iterator end() const;
//! Test for screen name
/*!
Returns true iff \c name names a screen.
*/
bool isScreen(const CString& name) const;
//! Test for canonical screen name
/*!
Returns true iff \c name is the canonical name of a screen.
*/
bool isCanonicalName(const CString& name) const;
//! Get canonical name
/*!
Returns the canonical name of a screen or the empty string if
the name is unknown. Returns the canonical name if one is given.
*/
CString getCanonicalName(const CString& name) const;
//! Get neighbor
/*!
Returns the canonical screen name of the neighbor in the given
direction (set through connect()). Returns the empty string
if there is no neighbor in that direction.
*/
CString getNeighbor(const CString&, EDirection) const;
//! Get the server address
const CNetworkAddress& getSynergyAddress() const;
//! Get the HTTP server address
const CNetworkAddress& getHTTPAddress() const;
//! Read configuration
/*!
Reads a configuration from a stream. Throws XConfigRead on error.
*/
friend std::istream& operator>>(std::istream&, CConfig&);
//! Write configuration
/*!
Writes a configuration to a stream.
*/
friend std::ostream& operator<<(std::ostream&, const CConfig&);
//! Get direction name
/*!
Returns the name of a direction (for debugging).
*/
static const char* dirName(EDirection);
//@}
private:
static bool readLine(std::istream&, CString&);
void readSection(std::istream&);
void readSectionNetwork(std::istream&);
void readSectionScreens(std::istream&);
void readSectionLinks(std::istream&);
void readSectionAliases(std::istream&);
private:
typedef std::map<CString, CString, CStringUtil::CaselessCmp> CNameMap;
CCellMap m_map;
CNameMap m_nameToCanonicalName;
CNetworkAddress m_synergyAddress;
CNetworkAddress m_httpAddress;
};
//! Configuration stream read exception
/*!
Thrown when a configuration stream cannot be parsed.
*/
class XConfigRead : public XBase {
public:
XConfigRead(const CString&);
~XConfigRead();
protected:
// XBase overrides
virtual CString getWhat() const throw();
private:
CString m_error;
};
#endif

785
lib/server/CHTTPServer.cpp Normal file
View File

@@ -0,0 +1,785 @@
#include "CHTTPServer.h"
#include "CConfig.h"
#include "CHTTPProtocol.h"
#include "CServer.h"
#include "XHTTP.h"
#include "IDataSocket.h"
#include "XThread.h"
#include "CLog.h"
#include "stdset.h"
#include "stdsstream.h"
//
// CHTTPServer
//
// maximum size of an HTTP request. this should be large enough to
// handle any reasonable request but small enough to prevent a
// malicious client from causing us to use too much memory.
const UInt32 CHTTPServer::s_maxRequestSize = 32768;
CHTTPServer::CHTTPServer(
CServer* server) :
m_server(server)
{
// do nothing
}
CHTTPServer::~CHTTPServer()
{
// do nothing
}
void
CHTTPServer::processRequest(IDataSocket* socket)
{
assert(socket != NULL);
CHTTPRequest* request = NULL;
try {
// parse request
request = CHTTPProtocol::readRequest(
socket->getInputStream(), s_maxRequestSize);
if (request == NULL) {
throw XHTTP(400);
}
// if absolute uri then strip off scheme and host
if (request->m_uri[0] != '/') {
CString::size_type n = request->m_uri.find('/');
if (n == CString::npos) {
throw XHTTP(404);
}
request->m_uri = request->m_uri.substr(n);
}
// prepare reply
CHTTPReply reply;
reply.m_majorVersion = request->m_majorVersion;
reply.m_minorVersion = request->m_minorVersion;
reply.m_status = 200;
reply.m_reason = "OK";
reply.m_method = request->m_method;
// process
doProcessRequest(*request, reply);
// send reply
CHTTPProtocol::reply(socket->getOutputStream(), reply);
log((CLOG_INFO "HTTP reply %d for %s %s", reply.m_status, request->m_method.c_str(), request->m_uri.c_str()));
// clean up
delete request;
}
catch (XHTTP& e) {
log((CLOG_WARN "returning HTTP error %d %s for %s", e.getStatus(), e.getReason().c_str(), (request != NULL) ? request->m_uri.c_str() : "<unknown>"));
// clean up
delete request;
// return error
CHTTPReply reply;
reply.m_majorVersion = 1;
reply.m_minorVersion = 0;
reply.m_status = e.getStatus();
reply.m_reason = e.getReason();
reply.m_method = "GET";
// FIXME -- use a nicer error page
reply.m_headers.push_back(std::make_pair(CString("Content-Type"),
CString("text/plain")));
reply.m_body = e.getReason();
e.addHeaders(reply);
CHTTPProtocol::reply(socket->getOutputStream(), reply);
}
catch (...) {
// ignore other exceptions
RETHROW_XTHREAD
}
}
void
CHTTPServer::doProcessRequest(CHTTPRequest& request, CHTTPReply& reply)
{
// switch based on uri
if (request.m_uri == "/editmap") {
if (request.m_method == "GET" || request.m_method == "HEAD") {
doProcessGetEditMap(request, reply);
reply.m_headers.push_back(std::make_pair(
CString("Content-Type"),
CString("text/html")));
}
else if (request.m_method == "POST") {
doProcessPostEditMap(request, reply);
reply.m_headers.push_back(std::make_pair(
CString("Content-Type"),
CString("text/html")));
}
else {
throw XHTTPAllow("GET, HEAD, POST");
}
}
else {
// unknown page
throw XHTTP(404);
}
}
void
CHTTPServer::doProcessGetEditMap(CHTTPRequest& /*request*/, CHTTPReply& reply)
{
static const char* s_editMapProlog1 =
"<html>\r\n"
"<head>\r\n"
" <title>Synergy -- Edit Screens</title>\r\n"
"</head>\r\n"
"<body>\r\n"
" <form method=\"POST\" action=\"editmap\" "
"enctype=\"multipart/form-data\">\r\n"
" <input type=hidden name=\"size\" value=\"";
static const char* s_editMapProlog2 =
"\">\r\n";
static const char* s_editMapEpilog =
" <input type=submit name=\"submit\">\r\n"
" <input type=reset>\r\n"
" <br>\r\n"
" </form>\r\n"
"</body>\r\n"
"</html>\r\n";
static const char* s_editMapTableProlog =
"<table border=\"1\" cellspacing=\"0\" cellpadding=\"0\"><tr><td>"
" <table border=\"0\" cellspacing=\"2\" cellpadding=\"6\">\r\n";
static const char* s_editMapTableEpilog =
" </table>"
"</td></tr></table>\r\n";
static const char* s_editMapRowProlog =
"<tr align=\"center\" valign=\"top\">\r\n";
static const char* s_editMapRowEpilog =
"</tr>\r\n";
static const char* s_editMapScreenDummy =
"<td>";
static const char* s_editMapScreenPrimary =
"<td bgcolor=\"#2222288\"><input type=\"text\" readonly value=\"";
static const char* s_editMapScreenLive =
"<td bgcolor=\"#cccccc\"><input type=\"text\" value=\"";
static const char* s_editMapScreenDead =
"<td><input type=\"text\" value=\"";
static const char* s_editMapScreenLiveDead1 =
"\" size=\"16\" maxlength=\"64\" name=\"";
static const char* s_editMapScreenLiveDead2 =
"\">";
static const char* s_editMapScreenEnd =
"</td>\r\n";
std::ostringstream s;
// convert screen map into a temporary screen map
CScreenArray screens;
{
CConfig config;
m_server->getConfig(&config);
screens.convertFrom(config);
// FIXME -- note to user if config couldn't be exactly represented
}
// insert blank columns and rows around array (to allow the user
// to insert new screens)
screens.insertColumn(0);
screens.insertColumn(screens.getWidth());
screens.insertRow(0);
screens.insertRow(screens.getHeight());
// get array size
const SInt32 w = screens.getWidth();
const SInt32 h = screens.getHeight();
// construct reply
reply.m_body += s_editMapProlog1;
s << w << "x" << h;
reply.m_body += s.str();
reply.m_body += s_editMapProlog2;
// add screen map for editing
const CString primaryName = m_server->getPrimaryScreenName();
reply.m_body += s_editMapTableProlog;
for (SInt32 y = 0; y < h; ++y) {
reply.m_body += s_editMapRowProlog;
for (SInt32 x = 0; x < w; ++x) {
s.str("");
if (!screens.isAllowed(x, y) && screens.get(x, y) != primaryName) {
s << s_editMapScreenDummy;
}
else {
if (!screens.isSet(x, y)) {
s << s_editMapScreenDead;
}
else if (screens.get(x, y) == primaryName) {
s << s_editMapScreenPrimary;
}
else {
s << s_editMapScreenLive;
}
s << screens.get(x, y) <<
s_editMapScreenLiveDead1 <<
"n" << x << "x" << y <<
s_editMapScreenLiveDead2;
}
s << s_editMapScreenEnd;
reply.m_body += s.str();
}
reply.m_body += s_editMapRowEpilog;
}
reply.m_body += s_editMapTableEpilog;
reply.m_body += s_editMapEpilog;
}
void
CHTTPServer::doProcessPostEditMap(CHTTPRequest& request, CHTTPReply& reply)
{
typedef std::vector<CString> ScreenArray;
typedef std::set<CString> ScreenSet;
// parse the result
CHTTPProtocol::CFormParts parts;
if (!CHTTPProtocol::parseFormData(request, parts)) {
log((CLOG_WARN "editmap: cannot parse form data"));
throw XHTTP(400);
}
try {
std::ostringstream s;
// convert post data into a temporary screen map. also check
// that no screen name is invalid or used more than once.
SInt32 w, h;
CHTTPProtocol::CFormParts::iterator index = parts.find("size");
if (index == parts.end() ||
!parseXY(index->second, w, h) ||
w <= 0 || h <= 0) {
log((CLOG_WARN "editmap: cannot parse size or size is invalid"));
throw XHTTP(400);
}
ScreenSet screenNames;
CScreenArray screens;
screens.resize(w, h);
for (SInt32 y = 0; y < h; ++y) {
for (SInt32 x = 0; x < w; ++x) {
// find part
s.str("");
s << "n" << x << "x" << y;
index = parts.find(s.str());
if (index == parts.end()) {
// FIXME -- screen is missing. error?
continue;
}
// skip blank names
const CString& name = index->second;
if (name.empty()) {
continue;
}
// check name. name must be legal and must not have
// already been seen.
if (screenNames.count(name)) {
// FIXME -- better error message
log((CLOG_WARN "editmap: duplicate name %s", name.c_str()));
throw XHTTP(400);
}
// FIXME -- check that name is legal
// save name. if we've already seen the name then
// report an error.
screens.set(x, y, name);
screenNames.insert(name);
}
}
// if new map is invalid then return error. map is invalid if:
// there are no screens, or
// the screens are not 4-connected.
if (screenNames.empty()) {
// no screens
// FIXME -- need better no screens
log((CLOG_WARN "editmap: no screens"));
throw XHTTP(400);
}
if (!screens.isValid()) {
// FIXME -- need better unconnected screens error
log((CLOG_WARN "editmap: unconnected screens"));
throw XHTTP(400);
}
// convert temporary screen map into a regular map
CConfig config;
m_server->getConfig(&config);
screens.convertTo(config);
// set new screen map on server
m_server->setConfig(config);
// now reply with current map
doProcessGetEditMap(request, reply);
}
catch (XHTTP&) {
// FIXME -- construct a more meaningful error?
throw;
}
}
bool
CHTTPServer::parseXY(const CString& xy, SInt32& x, SInt32& y)
{
std::istringstream s(xy);
char delimiter;
s >> x;
s.get(delimiter);
s >> y;
return (!!s && delimiter == 'x');
}
//
// CHTTPServer::CScreenArray
//
CHTTPServer::CScreenArray::CScreenArray() :
m_w(0),
m_h(0)
{
// do nothing
}
CHTTPServer::CScreenArray::~CScreenArray()
{
// do nothing
}
void
CHTTPServer::CScreenArray::resize(SInt32 w, SInt32 h)
{
m_screens.clear();
m_screens.resize(w * h);
m_w = w;
m_h = h;
}
void
CHTTPServer::CScreenArray::insertRow(SInt32 i)
{
assert(i >= 0 && i <= m_h);
CNames newScreens;
newScreens.resize(m_w * (m_h + 1));
for (SInt32 y = 0; y < i; ++y) {
for (SInt32 x = 0; x < m_w; ++x) {
newScreens[x + y * m_w] = m_screens[x + y * m_w];
}
}
for (SInt32 y = i; y < m_h; ++y) {
for (SInt32 x = 0; x < m_w; ++x) {
newScreens[x + (y + 1) * m_w] = m_screens[x + y * m_w];
}
}
m_screens.swap(newScreens);
++m_h;
}
void
CHTTPServer::CScreenArray::insertColumn(SInt32 i)
{
assert(i >= 0 && i <= m_w);
CNames newScreens;
newScreens.resize((m_w + 1) * m_h);
for (SInt32 y = 0; y < m_h; ++y) {
for (SInt32 x = 0; x < i; ++x) {
newScreens[x + y * (m_w + 1)] = m_screens[x + y * m_w];
}
for (SInt32 x = i; x < m_w; ++x) {
newScreens[(x + 1) + y * (m_w + 1)] = m_screens[x + y * m_w];
}
}
m_screens.swap(newScreens);
++m_w;
}
void
CHTTPServer::CScreenArray::eraseRow(SInt32 i)
{
assert(i >= 0 && i < m_h);
CNames newScreens;
newScreens.resize(m_w * (m_h - 1));
for (SInt32 y = 0; y < i; ++y) {
for (SInt32 x = 0; x < m_w; ++x) {
newScreens[x + y * m_w] = m_screens[x + y * m_w];
}
}
for (SInt32 y = i + 1; y < m_h; ++y) {
for (SInt32 x = 0; x < m_w; ++x) {
newScreens[x + (y - 1) * m_w] = m_screens[x + y * m_w];
}
}
m_screens.swap(newScreens);
--m_h;
}
void
CHTTPServer::CScreenArray::eraseColumn(SInt32 i)
{
assert(i >= 0 && i < m_w);
CNames newScreens;
newScreens.resize((m_w - 1) * m_h);
for (SInt32 y = 0; y < m_h; ++y) {
for (SInt32 x = 0; x < m_w; ++x) {
newScreens[x + y * (m_w - 1)] = m_screens[x + y * m_w];
}
for (SInt32 x = i + 1; x < m_w; ++x) {
newScreens[(x - 1) + y * (m_w - 1)] = m_screens[x + y * m_w];
}
}
m_screens.swap(newScreens);
--m_w;
}
void
CHTTPServer::CScreenArray::rotateRows(SInt32 i)
{
// nothing to do if no rows
if (m_h == 0) {
return;
}
// convert to canonical form
if (i < 0) {
i = m_h - ((-i) % m_h);
}
else {
i %= m_h;
}
if (i == 0 || i == m_h) {
return;
}
while (i > 0) {
// rotate one row
for (SInt32 x = 0; x < m_w; ++x) {
CString tmp = m_screens[x];
for (SInt32 y = 1; y < m_h; ++y) {
m_screens[x + (y - 1) * m_w] = m_screens[x + y * m_w];
}
m_screens[x + (m_h - 1) * m_w] = tmp;
}
}
}
void
CHTTPServer::CScreenArray::rotateColumns(SInt32 i)
{
// nothing to do if no columns
if (m_h == 0) {
return;
}
// convert to canonical form
if (i < 0) {
i = m_w - ((-i) % m_w);
}
else {
i %= m_w;
}
if (i == 0 || i == m_w) {
return;
}
while (i > 0) {
// rotate one column
for (SInt32 y = 0; y < m_h; ++y) {
CString tmp = m_screens[0 + y * m_w];
for (SInt32 x = 1; x < m_w; ++x) {
m_screens[x - 1 + y * m_w] = m_screens[x + y * m_w];
}
m_screens[m_w - 1 + y * m_w] = tmp;
}
}
}
void
CHTTPServer::CScreenArray::remove(SInt32 x, SInt32 y)
{
set(x, y, CString());
}
void
CHTTPServer::CScreenArray::set(SInt32 x, SInt32 y, const CString& name)
{
assert(x >= 0 && x < m_w);
assert(y >= 0 && y < m_h);
m_screens[x + y * m_w] = name;
}
bool
CHTTPServer::CScreenArray::isAllowed(SInt32 x, SInt32 y) const
{
assert(x >= 0 && x < m_w);
assert(y >= 0 && y < m_h);
if (x > 0 && !m_screens[(x - 1) + y * m_w].empty()) {
return true;
}
if (x < m_w - 1 && !m_screens[(x + 1) + y * m_w].empty()) {
return true;
}
if (y > 0 && !m_screens[x + (y - 1) * m_w].empty()) {
return true;
}
if (y < m_h - 1 && !m_screens[x + (y + 1) * m_w].empty()) {
return true;
}
return false;
}
bool
CHTTPServer::CScreenArray::isSet(SInt32 x, SInt32 y) const
{
assert(x >= 0 && x < m_w);
assert(y >= 0 && y < m_h);
return !m_screens[x + y * m_w].empty();
}
CString
CHTTPServer::CScreenArray::get(SInt32 x, SInt32 y) const
{
assert(x >= 0 && x < m_w);
assert(y >= 0 && y < m_h);
return m_screens[x + y * m_w];
}
bool
CHTTPServer::CScreenArray::find(const CString& name,
SInt32& xOut, SInt32& yOut) const
{
for (SInt32 y = 0; y < m_h; ++y) {
for (SInt32 x = 0; x < m_w; ++x) {
if (m_screens[x + y * m_w] == name) {
xOut = x;
yOut = y;
return true;
}
}
}
return false;
}
bool
CHTTPServer::CScreenArray::isValid() const
{
SInt32 count = 0, isolated = 0;
for (SInt32 y = 0; y < m_h; ++y) {
for (SInt32 x = 0; x < m_w; ++x) {
if (isSet(x, y)) {
++count;
if (!isAllowed(x, y)) {
++isolated;
}
}
}
}
return (count <= 1 || isolated == 0);
}
bool
CHTTPServer::CScreenArray::convertFrom(const CConfig& config)
{
typedef std::set<CString> ScreenSet;
// insert the first screen
CConfig::const_iterator index = config.begin();
if (index == config.end()) {
// no screens
resize(0, 0);
return true;
}
CString name = *index;
resize(1, 1);
set(0, 0, name);
// flood fill state
CNames screenStack;
ScreenSet doneSet;
// put all but the first screen on the stack
// note -- if all screens are 4-connected then we can skip this
while (++index != config.end()) {
screenStack.push_back(*index);
}
// put the first screen on the stack last so we process it first
screenStack.push_back(name);
// perform a flood fill using the stack as the seeds
while (!screenStack.empty()) {
// get next screen from stack
CString name = screenStack.back();
screenStack.pop_back();
// skip screen if we've seen it before
if (doneSet.count(name) > 0) {
continue;
}
// add this screen to doneSet so we don't process it again
doneSet.insert(name);
// find the screen. if it's not found then not all of the
// screens are 4-connected. discard disconnected screens.
SInt32 x, y;
if (!find(name, x, y)) {
continue;
}
// insert the screen's neighbors
// FIXME -- handle edge wrapping
CString neighbor;
neighbor = config.getNeighbor(name, kLeft);
if (!neighbor.empty() && doneSet.count(neighbor) == 0) {
// insert left neighbor, adding a column if necessary
if (x == 0 || get(x - 1, y) != neighbor) {
++x;
insertColumn(x - 1);
set(x - 1, y, neighbor);
}
screenStack.push_back(neighbor);
}
neighbor = config.getNeighbor(name, kRight);
if (!neighbor.empty() && doneSet.count(neighbor) == 0) {
// insert right neighbor, adding a column if necessary
if (x == m_w - 1 || get(x + 1, y) != neighbor) {
insertColumn(x + 1);
set(x + 1, y, neighbor);
}
screenStack.push_back(neighbor);
}
neighbor = config.getNeighbor(name, kTop);
if (!neighbor.empty() && doneSet.count(neighbor) == 0) {
// insert top neighbor, adding a row if necessary
if (y == 0 || get(x, y - 1) != neighbor) {
++y;
insertRow(y - 1);
set(x, y - 1, neighbor);
}
screenStack.push_back(neighbor);
}
neighbor = config.getNeighbor(name, kBottom);
if (!neighbor.empty() && doneSet.count(neighbor) == 0) {
// insert bottom neighbor, adding a row if necessary
if (y == m_h - 1 || get(x, y + 1) != neighbor) {
insertRow(y + 1);
set(x, y + 1, neighbor);
}
screenStack.push_back(neighbor);
}
}
// check symmetry
// FIXME -- handle edge wrapping
for (index = config.begin(); index != config.end(); ++index) {
const CString& name = *index;
SInt32 x, y;
if (!find(name, x, y)) {
return false;
}
CString neighbor;
neighbor = config.getNeighbor(name, kLeft);
if ((x == 0 && !neighbor.empty()) ||
(x > 0 && get(x - 1, y) != neighbor)) {
return false;
}
neighbor = config.getNeighbor(name, kRight);
if ((x == m_w - 1 && !neighbor.empty()) ||
(x < m_w - 1 && get(x + 1, y) != neighbor)) {
return false;
}
neighbor = config.getNeighbor(name, kTop);
if ((y == 0 && !neighbor.empty()) ||
(y > 0 && get(x, y - 1) != neighbor)) {
return false;
}
neighbor = config.getNeighbor(name, kBottom);
if ((y == m_h - 1 && !neighbor.empty()) ||
(y < m_h - 1 && get(x, y + 1) != neighbor)) {
return false;
}
}
return true;
}
void
CHTTPServer::CScreenArray::convertTo(CConfig& config) const
{
config.removeAllScreens();
// add screens and find smallest box containing all screens
SInt32 x0 = m_w, x1 = 0, y0 = m_h, y1 = 0;
for (SInt32 y = 0; y < m_h; ++y) {
for (SInt32 x = 0; x < m_w; ++x) {
if (isSet(x, y)) {
config.addScreen(get(x, y));
if (x < x0) {
x0 = x;
}
if (x > x1) {
x1 = x;
}
if (y < y0) {
y0 = y;
}
if (y > y1) {
y1 = y;
}
}
}
}
// make connections between screens
// FIXME -- add support for wrapping
// FIXME -- mark topmost and leftmost screens
for (SInt32 y = 0; y < m_h; ++y) {
for (SInt32 x = 0; x < m_w; ++x) {
if (!isSet(x, y)) {
continue;
}
if (x > x0 && isSet(x - 1, y)) {
config.connect(get(x, y), kLeft, get(x - 1, y));
}
if (x < x1 && isSet(x + 1, y)) {
config.connect(get(x, y), kRight, get(x + 1, y));
}
if (y > y0 && isSet(x, y - 1)) {
config.connect(get(x, y), kTop, get(x, y - 1));
}
if (y < y1 && isSet(x, y + 1)) {
config.connect(get(x, y), kBottom, get(x, y + 1));
}
}
}
}

128
lib/server/CHTTPServer.h Normal file
View File

@@ -0,0 +1,128 @@
#ifndef CHTTPSERVER_H
#define CHTTPSERVER_H
#include "CString.h"
#include "BasicTypes.h"
#include "stdvector.h"
class CServer;
class CConfig;
class CHTTPRequest;
class CHTTPReply;
class IDataSocket;
//! Simple HTTP server
/*!
This class implements a simple HTTP server for interacting with the
synergy server.
*/
class CHTTPServer {
public:
CHTTPServer(CServer*);
virtual ~CHTTPServer();
//! @name manipulators
//@{
//! Process HTTP request
/*!
Synchronously processes an HTTP request on the given socket.
*/
void processRequest(IDataSocket*);
//@}
protected:
//! Process HTTP request
/*!
Processes a successfully read HTTP request. The reply is partially
filled in (version, method, status (200) and reason (OK)). This
method checks the URI and handles the request, filling in the rest
of the reply. If the request cannot be satisfied it throws an
appropriate XHTTP exception.
*/
virtual void doProcessRequest(CHTTPRequest&, CHTTPReply&);
//! Process request for map
virtual void doProcessGetEditMap(CHTTPRequest&, CHTTPReply&);
//! Process request for changing map
virtual void doProcessPostEditMap(CHTTPRequest&, CHTTPReply&);
//! Parse coordinate string
static bool parseXY(const CString&, SInt32& x, SInt32& y);
//! Screen map helper
/*!
This class represents the screen map as a resizable array. It's
used to handle map requests.
*/
class CScreenArray {
public:
CScreenArray();
~CScreenArray();
// resize the array. this also clears all the elements.
void resize(SInt32 w, SInt32 h);
// insert/remove a row/column. all elements in a new row/column
// are unset.
void insertRow(SInt32 insertedBeforeRow);
void insertColumn(SInt32 insertedBeforeColumn);
void eraseRow(SInt32 row);
void eraseColumn(SInt32 column);
// rotate rows or columns
void rotateRows(SInt32 rowsDown);
void rotateColumns(SInt32 columnsDown);
// remove/set a screen name. setting an empty name is the
// same as removing a name. names are not checked for
// validity.
void remove(SInt32 x, SInt32 y);
void set(SInt32 x, SInt32 y, const CString&);
// convert a CConfig to a CScreenArray. returns true iff
// all connections are symmetric and therefore exactly
// representable by a CScreenArray.
bool convertFrom(const CConfig&);
// accessors
// get the array size
SInt32 getWidth() const { return m_w; }
SInt32 getHeight() const { return m_h; }
// returns true iff the cell has a 4-connected neighbor
bool isAllowed(SInt32 x, SInt32 y) const;
// returns true iff the cell has a (non-empty) name
bool isSet(SInt32 x, SInt32 y) const;
// get a screen name
CString get(SInt32 x, SInt32 y) const;
// find a screen by name. returns true iff found.
bool find(const CString&, SInt32& x, SInt32& y) const;
// return true iff the overall array is valid. that means
// just zero or one screen or all screens are 4-connected
// to other screens.
bool isValid() const;
// convert this to a CConfig
void convertTo(CConfig&) const;
private:
typedef std::vector<CString> CNames;
SInt32 m_w, m_h;
CNames m_screens;
};
private:
CServer* m_server;
static const UInt32 s_maxRequestSize;
};
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,117 @@
#ifndef CMSWINDOWSPRIMARYSCREEN_H
#define CMSWINDOWSPRIMARYSCREEN_H
#include "CPrimaryScreen.h"
#include "IMSWindowsScreenEventHandler.h"
#include "CSynergyHook.h"
#include "MouseTypes.h"
#include "CString.h"
class CMSWindowsScreen;
class IScreenReceiver;
class IPrimaryScreenReceiver;
//! Microsoft windows primary screen implementation
class CMSWindowsPrimaryScreen :
public CPrimaryScreen, public IMSWindowsScreenEventHandler {
public:
typedef bool (CMSWindowsPrimaryScreen::*HookMethod)(int, WPARAM, LPARAM);
CMSWindowsPrimaryScreen(IScreenReceiver*, IPrimaryScreenReceiver*);
virtual ~CMSWindowsPrimaryScreen();
// CPrimaryScreen overrides
virtual void reconfigure(UInt32 activeSides);
virtual void warpCursor(SInt32 x, SInt32 y);
virtual KeyModifierMask getToggleMask() const;
virtual bool isLockedToScreen() const;
virtual IScreen* getScreen() const;
// IMSWindowsScreenEventHandler overrides
virtual void onScreensaver(bool activated);
virtual bool onPreDispatch(const CEvent* event);
virtual bool onEvent(CEvent* event);
virtual SInt32 getJumpZoneSize() const;
virtual void postCreateWindow(HWND);
virtual void preDestroyWindow(HWND);
protected:
// CPrimaryScreen overrides
virtual void onPreMainLoop();
virtual void onPreOpen();
virtual void onPostOpen();
virtual void onPostClose();
virtual void onPreEnter();
virtual void onPostEnter();
virtual void onPreLeave();
virtual void onPostLeave(bool);
virtual void createWindow();
virtual void destroyWindow();
virtual bool showWindow();
virtual void hideWindow();
virtual void warpCursorToCenter();
virtual void updateKeys();
private:
void enterNoWarp();
// warp cursor without discarding queued events
void warpCursorNoFlush(SInt32 x, SInt32 y);
// discard posted messages
void nextMark();
// test if event should be ignored
bool ignore() const;
// key and button queries
KeyID mapKey(WPARAM keycode, LPARAM info,
KeyModifierMask* maskOut);
ButtonID mapButton(WPARAM button) const;
void updateKey(UINT vkCode, bool press);
private:
IPrimaryScreenReceiver* m_receiver;
CMSWindowsScreen* m_screen;
// true if windows 95/98/me
bool m_is95Family;
// the main loop's thread id
DWORD m_threadID;
// our window
HWND m_window;
// used to discard queued messages that are no longer needed
UInt32 m_mark;
UInt32 m_markReceived;
// map of key state
BYTE m_keys[256];
// last mouse position
SInt32 m_x, m_y;
// position of center pixel of screen
SInt32 m_xCenter, m_yCenter;
// hook library stuff
HINSTANCE m_hookLibrary;
InitFunc m_init;
CleanupFunc m_cleanup;
InstallFunc m_install;
UninstallFunc m_uninstall;
SetSidesFunc m_setSides;
SetZoneFunc m_setZone;
SetRelayFunc m_setRelay;
// stuff for restoring active window
HWND m_lastForegroundWindow;
HWND m_lastActiveWindow;
DWORD m_lastActiveThread;
};
#endif

View File

@@ -0,0 +1,267 @@
#include "CPrimaryClient.h"
#include "IServer.h"
#include "XSynergy.h"
#include "CPrimaryScreen.h"
#include "CClipboard.h"
#include "CLog.h"
// FIXME -- use factory to create screen
#if WINDOWS_LIKE
#include "CMSWindowsPrimaryScreen.h"
#elif UNIX_LIKE
#include "CXWindowsPrimaryScreen.h"
#endif
//
// CPrimaryClient
//
CPrimaryClient::CPrimaryClient(IServer* server,
IPrimaryScreenReceiver* receiver, const CString& name) :
m_server(server),
m_name(name),
m_seqNum(0)
{
assert(m_server != NULL);
// create screen
log((CLOG_DEBUG1 "creating primary screen"));
#if WINDOWS_LIKE
m_screen = new CMSWindowsPrimaryScreen(this, receiver);
#elif UNIX_LIKE
m_screen = new CXWindowsPrimaryScreen(this, receiver);
#endif
}
CPrimaryClient::~CPrimaryClient()
{
log((CLOG_DEBUG1 "destroying primary screen"));
delete m_screen;
}
void
CPrimaryClient::exitMainLoop()
{
m_screen->exitMainLoop();
}
void
CPrimaryClient::reconfigure(UInt32 activeSides)
{
m_screen->reconfigure(activeSides);
}
void
CPrimaryClient::getClipboard(ClipboardID id, CString& data) const
{
CClipboard clipboard;
m_screen->getClipboard(id, &clipboard);
data = clipboard.marshall();
}
bool
CPrimaryClient::isLockedToScreen() const
{
return m_screen->isLockedToScreen();
}
KeyModifierMask
CPrimaryClient::getToggleMask() const
{
return m_screen->getToggleMask();
}
void
CPrimaryClient::onError()
{
// forward to server
m_server->onError();
}
void
CPrimaryClient::onInfoChanged(const CClientInfo& info)
{
m_info = info;
try {
m_server->onInfoChanged(getName(), m_info);
}
catch (XBadClient&) {
// ignore
}
}
bool
CPrimaryClient::onGrabClipboard(ClipboardID id)
{
try {
return m_server->onGrabClipboard(getName(), id, m_seqNum);
}
catch (XBadClient&) {
return false;
}
}
void
CPrimaryClient::onClipboardChanged(ClipboardID id, const CString& data)
{
m_server->onClipboardChanged(id, m_seqNum, data);
}
bool
CPrimaryClient::open()
{
// all clipboards are clean
for (UInt32 i = 0; i < kClipboardEnd; ++i) {
m_clipboardDirty[i] = false;
}
// now open the screen
m_screen->open();
return true;
}
void
CPrimaryClient::mainLoop()
{
m_screen->mainLoop();
}
void
CPrimaryClient::close()
{
m_screen->close();
}
void
CPrimaryClient::enter(SInt32 xAbs, SInt32 yAbs,
UInt32 seqNum, KeyModifierMask, bool screensaver)
{
// note -- we must not call any server methods except onError().
m_seqNum = seqNum;
m_screen->enter(xAbs, yAbs, screensaver);
}
bool
CPrimaryClient::leave()
{
// note -- we must not call any server methods except onError().
return m_screen->leave();
}
void
CPrimaryClient::setClipboard(ClipboardID id, const CString& data)
{
// note -- we must not call any server methods except onError().
// ignore if this clipboard is already clean
if (m_clipboardDirty[id]) {
// this clipboard is now clean
m_clipboardDirty[id] = false;
// unmarshall data
CClipboard clipboard;
clipboard.unmarshall(data, 0);
// set clipboard
m_screen->setClipboard(id, &clipboard);
}
}
void
CPrimaryClient::grabClipboard(ClipboardID id)
{
// grab clipboard
m_screen->grabClipboard(id);
// clipboard is dirty (because someone else owns it now)
m_clipboardDirty[id] = true;
}
void
CPrimaryClient::setClipboardDirty(ClipboardID id, bool dirty)
{
m_clipboardDirty[id] = dirty;
}
void
CPrimaryClient::keyDown(KeyID, KeyModifierMask)
{
// ignore
}
void
CPrimaryClient::keyRepeat(KeyID, KeyModifierMask, SInt32)
{
// ignore
}
void
CPrimaryClient::keyUp(KeyID, KeyModifierMask)
{
// ignore
}
void
CPrimaryClient::mouseDown(ButtonID)
{
// ignore
}
void
CPrimaryClient::mouseUp(ButtonID)
{
// ignore
}
void
CPrimaryClient::mouseMove(SInt32 x, SInt32 y)
{
m_screen->warpCursor(x, y);
}
void
CPrimaryClient::mouseWheel(SInt32)
{
// ignore
}
void
CPrimaryClient::screensaver(bool)
{
// ignore
}
CString
CPrimaryClient::getName() const
{
return m_name;
}
SInt32
CPrimaryClient::getJumpZoneSize() const
{
return m_info.m_zoneSize;
}
void
CPrimaryClient::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
CPrimaryClient::getCursorPos(SInt32&, SInt32&) const
{
assert(0 && "shouldn't be called");
}
void
CPrimaryClient::getCursorCenter(SInt32& x, SInt32& y) const
{
x = m_info.m_mx;
y = m_info.m_my;
}

109
lib/server/CPrimaryClient.h Normal file
View File

@@ -0,0 +1,109 @@
#ifndef CPRIMARYCLIENT_H
#define CPRIMARYCLIENT_H
#include "IClient.h"
#include "IScreenReceiver.h"
#include "ProtocolTypes.h"
class IClipboard;
class CPrimaryScreen;
class IPrimaryScreenReceiver;
class IServer;
//! Primary screen as pseudo-client
/*!
The primary screen does not have a client associated with it. This
class provides a pseudo-client to allow the primary screen to be
treated as if it was on a client.
*/
class CPrimaryClient : public IScreenReceiver, public IClient {
public:
/*!
\c name is the name of the server.
*/
CPrimaryClient(IServer*, IPrimaryScreenReceiver*, const CString& name);
~CPrimaryClient();
//! @name manipulators
//@{
//! Exit event loop
/*!
Force mainLoop() to return. This call can return before
mainLoop() does (i.e. asynchronously). This may only be
called between a successful open() and close().
*/
void exitMainLoop();
//! Update configuration
/*!
Handles reconfiguration of jump zones.
*/
void reconfigure(UInt32 activeSides);
//@}
//! @name accessors
//@{
//! Get clipboard
/*!
Save the marshalled contents of the clipboard indicated by \c id.
*/
void getClipboard(ClipboardID, CString&) const;
//! Get toggle key state
/*!
Returns the primary screen's current toggle modifier key state.
*/
KeyModifierMask getToggleMask() const;
//! Get screen lock state
/*!
Returns true if the user is locked to the screen.
*/
bool isLockedToScreen() const;
//@}
// IScreenReceiver overrides
virtual void onError();
virtual void onInfoChanged(const CClientInfo&);
virtual bool onGrabClipboard(ClipboardID);
virtual void onClipboardChanged(ClipboardID, const CString&);
// IClient overrides
virtual bool open();
virtual void mainLoop();
virtual void close();
virtual void enter(SInt32 xAbs, SInt32 yAbs,
UInt32 seqNum, KeyModifierMask mask,
bool forScreensaver);
virtual bool leave();
virtual void setClipboard(ClipboardID, const CString&);
virtual void grabClipboard(ClipboardID);
virtual void setClipboardDirty(ClipboardID, bool);
virtual void keyDown(KeyID, KeyModifierMask);
virtual void keyRepeat(KeyID, KeyModifierMask, SInt32 count);
virtual void keyUp(KeyID, KeyModifierMask);
virtual void mouseDown(ButtonID);
virtual void mouseUp(ButtonID);
virtual void mouseMove(SInt32 xAbs, SInt32 yAbs);
virtual void mouseWheel(SInt32 delta);
virtual void screensaver(bool activate);
virtual CString getName() const;
virtual SInt32 getJumpZoneSize() const;
virtual void getShape(SInt32& x, SInt32& y,
SInt32& width, SInt32& height) const;
virtual void getCursorPos(SInt32& x, SInt32& y) const;
virtual void getCursorCenter(SInt32& x, SInt32& y) const;
private:
IServer* m_server;
CPrimaryScreen* m_screen;
CString m_name;
UInt32 m_seqNum;
CClientInfo m_info;
bool m_clipboardDirty[kClipboardEnd];
};
#endif

View File

@@ -0,0 +1,264 @@
#include "CPrimaryScreen.h"
#include "IScreen.h"
#include "IScreenReceiver.h"
#include "ProtocolTypes.h"
#include "CLock.h"
#include "CThread.h"
#include "CLog.h"
//
// CPrimaryScreen
//
CPrimaryScreen::CPrimaryScreen(IScreenReceiver* receiver) :
m_receiver(receiver),
m_active(false)
{
// do nothing
}
CPrimaryScreen::~CPrimaryScreen()
{
// do nothing
}
void
CPrimaryScreen::mainLoop()
{
// change our priority
CThread::getCurrentThread().setPriority(-3);
// run event loop
try {
log((CLOG_DEBUG "entering event loop"));
onPreMainLoop();
getScreen()->mainLoop();
onPostMainLoop();
log((CLOG_DEBUG "exiting event loop"));
}
catch (...) {
onPostMainLoop();
log((CLOG_DEBUG "exiting event loop"));
throw;
}
}
void
CPrimaryScreen::exitMainLoop()
{
getScreen()->exitMainLoop();
}
void
CPrimaryScreen::open()
{
CClientInfo info;
try {
// subclass hook
onPreOpen();
// open the screen
getScreen()->open();
// create and prepare our window
createWindow();
// collect screen info
getScreen()->getShape(info.m_x, info.m_y, info.m_w, info.m_h);
getScreen()->getCursorPos(info.m_mx, info.m_my);
info.m_zoneSize = getJumpZoneSize();
// update keyboard state
updateKeys();
// get notified of screen saver activation/deactivation
getScreen()->openScreensaver(true);
// subclass hook
onPostOpen();
}
catch (...) {
close();
throw;
}
// enter the screen
{
CLock lock(&m_mutex);
enterNoWarp();
}
// send screen info
m_receiver->onInfoChanged(info);
}
void
CPrimaryScreen::close()
{
onPreClose();
getScreen()->closeScreensaver();
destroyWindow();
getScreen()->close();
onPostClose();
}
void
CPrimaryScreen::enter(SInt32 x, SInt32 y, bool forScreensaver)
{
log((CLOG_INFO "entering primary at %d,%d%s", x, y, forScreensaver ? " for screen saver" : ""));
CLock lock(&m_mutex);
assert(m_active == true);
if (!forScreensaver) {
warpCursor(x, y);
}
else {
onEnterScreensaver();
}
enterNoWarp();
}
void
CPrimaryScreen::enterNoWarp()
{
// note -- must be locked on entry
// not active anymore
m_active = false;
// subclass hook
onPreEnter();
// restore active window and hide our window
hideWindow();
// subclass hook
onPostEnter();
}
bool
CPrimaryScreen::leave()
{
log((CLOG_INFO "leaving primary"));
CLock lock(&m_mutex);
assert(m_active == false);
// subclass hook
onPreLeave();
// show our window
if (!showWindow()) {
onPostLeave(false);
return false;
}
// get keyboard state as we leave
updateKeys();
// subclass hook
onPostLeave(true);
// warp mouse to center
warpCursorToCenter();
// local client now active
m_active = true;
// make sure our idea of clipboard ownership is correct
getScreen()->checkClipboards();
return true;
}
void
CPrimaryScreen::setClipboard(ClipboardID id,
const IClipboard* clipboard)
{
getScreen()->setClipboard(id, clipboard);
}
void
CPrimaryScreen::grabClipboard(ClipboardID id)
{
getScreen()->setClipboard(id, NULL);
}
bool
CPrimaryScreen::isActive() const
{
CLock lock(&m_mutex);
return m_active;
}
void
CPrimaryScreen::getClipboard(ClipboardID id,
IClipboard* clipboard) const
{
getScreen()->getClipboard(id, clipboard);
}
void
CPrimaryScreen::onPreMainLoop()
{
// do nothing
}
void
CPrimaryScreen::onPostMainLoop()
{
// do nothing
}
void
CPrimaryScreen::onPreOpen()
{
// do nothing
}
void
CPrimaryScreen::onPostOpen()
{
// do nothing
}
void
CPrimaryScreen::onPreClose()
{
// do nothing
}
void
CPrimaryScreen::onPostClose()
{
// do nothing
}
void
CPrimaryScreen::onPreEnter()
{
// do nothing
}
void
CPrimaryScreen::onPostEnter()
{
// do nothing
}
void
CPrimaryScreen::onEnterScreensaver()
{
// do nothing
}
void
CPrimaryScreen::onPreLeave()
{
// do nothing
}
void
CPrimaryScreen::onPostLeave(bool)
{
// do nothing
}

312
lib/server/CPrimaryScreen.h Normal file
View File

@@ -0,0 +1,312 @@
#ifndef CPRIMARYSCREEN_H
#define CPRIMARYSCREEN_H
#include "ClipboardTypes.h"
#include "KeyTypes.h"
#include "CMutex.h"
class IClipboard;
class IScreen;
class IScreenReceiver;
//! Generic server-side screen
/*!
This is a platform independent base class for primary screen
implementations. A primary screen is a server-side screen.
Each platform will derive a class from CPrimaryScreen to handle
platform dependent operations.
*/
class CPrimaryScreen {
public:
CPrimaryScreen(IScreenReceiver*);
virtual ~CPrimaryScreen();
//! @name manipulators
//@{
//! Open screen
/*!
Opens the screen. This includes initializing the screen, opening
the screen saver, synchronizing keyboard state, and causing events
to be reported to an IPrimaryScreenReceiver (set through another
interface). Calls close() before returning (rethrowing) if it
fails for any reason.
*/
void open();
//! Run event loop
/*!
Run the screen's event loop. This returns when it detects
the application should terminate or when exitMainLoop() is called.
mainLoop() may only be called between open() and close().
*/
void mainLoop();
//! Exit event loop
/*!
Force mainLoop() to return. This call can return before
mainLoop() does (i.e. asynchronously).
*/
void exitMainLoop();
//! Close screen
/*!
Closes the screen. This close the screen saver and the screen.
*/
void close();
//! Enter screen
/*!
Called when the user navigates to the primary screen. Warps
the cursor to the absolute coordinates \c x,y and unhides
it. If \c forScreensaver is true then we're entering because
the screen saver started and the cursor is not warped.
*/
void enter(SInt32 x, SInt32 y, bool forScreensaver);
//! Leave screen
/*!
Called when the user navigates off the primary screen. Returns
true iff successful.
*/
bool leave();
//! Update configuration
/*!
This is called when the configuration has changed. \c activeSides
is a bitmask of EDirectionMask indicating which sides of the
primary screen are linked to clients. Override to handle the
possible change in jump zones.
*/
virtual void reconfigure(UInt32 activeSides) = 0;
//! Warp cursor
/*!
Warp the cursor to the absolute coordinates \c x,y. Also
discard input events up to and including the warp before
returning.
*/
virtual void warpCursor(SInt32 x, SInt32 y) = 0;
//! Set clipboard
/*!
Sets the system's clipboard contents. This is usually called
soon after an enter().
*/
void setClipboard(ClipboardID, const IClipboard*);
//! Grab clipboard
/*!
Grabs (i.e. take ownership of) the system clipboard.
*/
void grabClipboard(ClipboardID);
//@}
//! @name accessors
//@{
//! Test if active
/*!
Returns true iff the screen is active (i.e. the user has left
the screen). Note this is the reverse of a secdonary screen.
*/
bool isActive() const;
//! Get clipboard
/*!
Saves the contents of the system clipboard indicated by \c id.
*/
void getClipboard(ClipboardID, IClipboard*) const;
//! Get jump zone size
/*!
Return the jump zone size, the size of the regions on the edges of
the screen that cause the cursor to jump to another screen.
*/
virtual SInt32 getJumpZoneSize() const = 0;
//! Get toggle key state
/*!
Return the primary screen's current toggle modifier key state.
The returned mask should have the corresponding bit set for
each toggle key that is active. For example, if caps lock is
on then the returned mask should have \c KeyModifierCapsLock set.
*/
virtual KeyModifierMask getToggleMask() const = 0;
//! Get screen lock state
/*!
Return true if any key or button is being pressed or if there's
any other reason that the user should not be allowed to switch
screens. Active toggle keys (including the scroll lock key)
should not be counted as reasons to lock to the screen.
*/
virtual bool isLockedToScreen() const = 0;
//! Get screen
/*!
Return the platform dependent screen.
*/
virtual IScreen* getScreen() const = 0;
//@}
protected:
//! Pre-mainLoop() hook
/*!
Called on entry to mainLoop(). Override to perform platform specific
operations. Default does nothing. May throw.
*/
virtual void onPreMainLoop();
//! Post-mainLoop() hook
/*!
Called on exit from mainLoop(). Override to perform platform specific
operations. Default does nothing. May \b not throw.
*/
virtual void onPostMainLoop();
//! Pre-open() hook
/*!
Called on entry to open(). Override to perform platform specific
operations. Default does nothing. May throw.
*/
virtual void onPreOpen();
//! Post-open() hook
/*!
Called on exit from open() iff the open was successful. Default
does nothing. May throw.
*/
virtual void onPostOpen();
//! Pre-close() hook
/*!
Called on entry to close(). Override to perform platform specific
operations. Default does nothing. May \b not throw.
*/
virtual void onPreClose();
//! Post-close() hook
/*!
Called on exit from close(). Override to perform platform specific
operations. Default does nothing. May \b not throw.
*/
virtual void onPostClose();
//! Pre-enter() hook
/*!
Called from enter() after the cursor has been warped or, if
\c forScreensaver is true, onEnterScreensaver() was called. Override
to perform platform specific operations. Default does nothing. May
\b not throw.
*/
virtual void onPreEnter();
//! Post-enter() hook
/*!
Called on exit from enter(). Override to perform platform specific
operations. Default does nothing. May \b not throw.
*/
virtual void onPostEnter();
//! Pre-enter() for screen saver hook
/*!
Called on entry to enter() if the \c forScreensaver passed to it was
true. Override to perform platform specific operations. Default
does nothing. May \b not throw.
*/
virtual void onEnterScreensaver();
//! Pre-leave() hook
/*!
Called on entry to leave() after desktop synchronization. Override
to perform platform specific operations. Default does nothing. May
\b not throw.
*/
virtual void onPreLeave();
//! Post-leave() hook
/*!
Called on exit from leave(). \c success is the value returned by
showWindow(). Override to perform platform specific operations.
Default does nothing. May \b not throw.
*/
virtual void onPostLeave(bool success);
//! Create window
/*!
Called to create the window. This window is generally used to
receive events, hide the cursor, and to capture keyboard and mouse
input.
*/
virtual void createWindow() = 0;
//! Destroy window
/*!
Called to destroy the window created by createWindow().
*/
virtual void destroyWindow() = 0;
//! Show window
/*!
Called when the user navigates off the primary screen. Hide the
cursor and grab exclusive access to the input devices. Every call
to showWindow() has a matching call to hideWindow() which preceeds
it. Return true iff successful (in particular, iff the input
devices were grabbed).
After a successful showWindow(), user input events and
screensaver activation/deactivation should be reported to an
IPrimaryScreenReceiver (set through another interface) until
hideWindow() is called. Report mouse motion to its
onMouseMoveSecondary(). User input should not be delivered to
any application except this one.
*/
virtual bool showWindow() = 0;
//! Hide window
/*!
Called when the user navigates back to the primary screen. Show
the cursor and ungrab the input devices.
After hideWindow(), user input events should be delivered normally
to other applications. Mouse motion over (at least) the jump zones
must be reported to an IPrimaryScreenReceiver's onMouseMovePrimary().
*/
virtual void hideWindow() = 0;
//! Warp cursor for relative motion
/*!
Prepare the cursor to report relative motion. When the user has
navigated to another screen, synergy requires the cursor motion
deltas, not the absolute coordinates. Typically this is done by
warping the cursor to the center of the primary screen and then
every time it moves compute the motion and warp back to the
center (but without reporting that warp as motion). This is
only called after a successful showWindow().
*/
virtual void warpCursorToCenter() = 0;
//! Synchronize key state
/*!
Check the current keyboard state. Normally a screen will save
the keyboard state in this method and use this shadow state
when handling user input and in methods like isLockedToScreen().
*/
virtual void updateKeys() = 0;
private:
void enterNoWarp();
private:
CMutex m_mutex;
// object to notify of changes
IScreenReceiver* m_receiver;
// m_active is true if this screen has been left
bool m_active;
};
#endif

1662
lib/server/CServer.cpp Normal file

File diff suppressed because it is too large Load Diff

256
lib/server/CServer.h Normal file
View File

@@ -0,0 +1,256 @@
#ifndef CSERVER_H
#define CSERVER_H
#include "IServer.h"
#include "IPrimaryScreenReceiver.h"
#include "CConfig.h"
#include "CClipboard.h"
#include "CCondVar.h"
#include "CMutex.h"
#include "CThread.h"
#include "stdlist.h"
#include "stdmap.h"
class CClientProxy;
class CHTTPServer;
class CPrimaryClient;
class IClient;
class IDataSocket;
class IServerProtocol;
class ISocketFactory;
class ISecurityFactory;
//! Synergy server
/*!
This class implements the top-level server algorithms for synergy.
*/
class CServer : public IServer, public IPrimaryScreenReceiver {
public:
/*!
The server will look itself up in the configuration using \c serverName
as its name.
*/
CServer(const CString& serverName);
~CServer();
//! @name manipulators
//@{
//! Open server
/*!
Open the server and return true iff successful.
*/
bool open();
//! Server main loop
/*!
Run server's event loop and return when exitMainLoop() is called.
This must be called between a successful open() and close().
(cancellation point)
*/
void mainLoop();
//! Exit event loop
/*!
Force mainLoop() to return. This call can return before
mainLoop() does (i.e. asynchronously). This may only be
called between a successful open() and close().
*/
void exitMainLoop();
//! Close server
/*!
Close the server.
*/
void close();
//! Set configuration
/*!
Change the server's configuration. Returns true iff the new
configuration was accepted (it must include the server's name).
This will disconnect any clients no longer in the configuration.
*/
bool setConfig(const CConfig&);
//@}
//! @name accessors
//@{
//! Get configuration
/*!
Returns the current configuration.
*/
void getConfig(CConfig*) const;
//! Get name
/*!
Returns the server's name passed to the c'tor
*/
CString getPrimaryScreenName() const;
//@}
// IServer overrides
virtual void onError();
virtual void onInfoChanged(const CString&, const CClientInfo&);
virtual bool onGrabClipboard(const CString&, ClipboardID, UInt32);
virtual void onClipboardChanged(ClipboardID, UInt32, const CString&);
// IPrimaryScreenReceiver overrides
virtual void onScreensaver(bool activated);
virtual void onKeyDown(KeyID, KeyModifierMask);
virtual void onKeyUp(KeyID, KeyModifierMask);
virtual void onKeyRepeat(KeyID, KeyModifierMask, SInt32 count);
virtual void onMouseDown(ButtonID);
virtual void onMouseUp(ButtonID);
virtual bool onMouseMovePrimary(SInt32 x, SInt32 y);
virtual void onMouseMoveSecondary(SInt32 dx, SInt32 dy);
virtual void onMouseWheel(SInt32 delta);
protected:
//! Handle special keys
/*!
Handles keys with special meaning.
*/
bool onCommandKey(KeyID, KeyModifierMask, bool down);
private:
typedef std::list<CThread> CThreadList;
// get the sides of the primary screen that have neighbors
UInt32 getActivePrimarySides() const;
// handle mouse motion
bool onMouseMovePrimaryNoLock(SInt32 x, SInt32 y);
void onMouseMoveSecondaryNoLock(SInt32 dx, SInt32 dy);
// set the clipboard
void onClipboardChangedNoLock(ClipboardID,
UInt32 seqNum, const CString& data);
// returns true iff mouse should be locked to the current screen
bool isLockedToScreenNoLock() const;
// change the active screen
void switchScreen(IClient*,
SInt32 x, SInt32 y, bool forScreenSaver);
// lookup neighboring screen
IClient* getNeighbor(IClient*, EDirection) const;
// lookup neighboring screen. given a position relative to the
// source screen, find the screen we should move onto and where.
// if the position is sufficiently far from the source then we
// cross multiple screens. if there is no suitable screen then
// return NULL and x,y are not modified.
IClient* getNeighbor(IClient*, EDirection,
SInt32& x, SInt32& y) const;
// open/close the primary screen
void openPrimaryScreen();
void closePrimaryScreen();
// update the clipboard if owned by the primary screen
void updatePrimaryClipboard(ClipboardID);
// close all clients that are *not* in config, not including the
// primary client.
void closeClients(const CConfig& config);
// start a thread, adding it to the list of threads
CThread startThread(IJob* adopted);
// cancel running threads, waiting at most timeout seconds for
// them to finish.
void stopThreads(double timeout = -1.0);
// reap threads, clearing finished threads from the thread list.
// doReapThreads does the work on the given thread list.
void reapThreads();
void doReapThreads(CThreadList&);
// thread method to accept incoming client connections
void acceptClients(void*);
// thread method to do client interaction
void runClient(void*);
CClientProxy* handshakeClient(IDataSocket*);
// thread method to accept incoming HTTP connections
void acceptHTTPClients(void*);
// thread method to process HTTP requests
void processHTTPRequest(void*);
// connection list maintenance
void addConnection(IClient*);
void removeConnection(const CString& name);
private:
class CClipboardInfo {
public:
CClipboardInfo();
public:
CClipboard m_clipboard;
CString m_clipboardData;
CString m_clipboardOwner;
UInt32 m_clipboardSeqNum;
};
CMutex m_mutex;
// the name of the primary screen
CString m_name;
// how long to wait to bind our socket until we give up
double m_bindTimeout;
ISocketFactory* m_socketFactory;
ISecurityFactory* m_securityFactory;
// running threads
CThreadList m_threads;
CThread* m_acceptClientThread;
// the screens
typedef std::map<CString, IClient*> CClientList;
typedef std::map<CString, CThread> CClientThreadList;
// all clients indexed by name
CClientList m_clients;
// run thread of all secondary screen clients. does not include the
// primary screen's run thread.
CClientThreadList m_clientThreads;
// the primary screen client
CPrimaryClient* m_primaryClient;
// the client with focus
IClient* m_active;
// the sequence number of enter messages
UInt32 m_seqNum;
// current mouse position (in absolute secondary screen coordinates)
SInt32 m_x, m_y;
// current configuration
CConfig m_config;
// clipboard cache
CClipboardInfo m_clipboards[kClipboardEnd];
// state saved when screen saver activates
IClient* m_activeSaver;
SInt32 m_xSaver, m_ySaver;
// HTTP request processing stuff
CHTTPServer* m_httpServer;
CCondVar<SInt32> m_httpAvailable;
static const SInt32 s_httpMaxSimultaneousRequests;
};
#endif

View File

@@ -0,0 +1,713 @@
#include "CXWindowsPrimaryScreen.h"
#include "CXWindowsScreen.h"
#include "CXWindowsUtil.h"
#include "IPrimaryScreenReceiver.h"
#include "XScreen.h"
#include "CThread.h"
#include "CLog.h"
#include "CStopwatch.h"
#if defined(X_DISPLAY_MISSING)
# error X11 is required to build synergy
#else
# include <X11/X.h>
# include <X11/Xutil.h>
# define XK_MISCELLANY
# define XK_XKB_KEYS
# include <X11/keysymdef.h>
#endif
//
// CXWindowsPrimaryScreen
//
CXWindowsPrimaryScreen::CXWindowsPrimaryScreen(
IScreenReceiver* receiver,
IPrimaryScreenReceiver* primaryReceiver) :
CPrimaryScreen(receiver),
m_receiver(primaryReceiver),
m_window(None)
{
m_screen = new CXWindowsScreen(receiver, this);
}
CXWindowsPrimaryScreen::~CXWindowsPrimaryScreen()
{
assert(m_window == None);
delete m_screen;
}
void
CXWindowsPrimaryScreen::reconfigure(UInt32)
{
// do nothing
}
void
CXWindowsPrimaryScreen::warpCursor(SInt32 x, SInt32 y)
{
CDisplayLock display(m_screen);
// warp mouse
warpCursorNoFlush(display, x, y);
// remove all input events before and including warp
XEvent event;
while (XCheckMaskEvent(display, PointerMotionMask |
ButtonPressMask | ButtonReleaseMask |
KeyPressMask | KeyReleaseMask |
KeymapStateMask,
&event)) {
// do nothing
}
// save position as last position
m_x = x;
m_y = y;
}
KeyModifierMask
CXWindowsPrimaryScreen::getToggleMask() const
{
CDisplayLock display(m_screen);
// query the pointer to get the keyboard state
Window root, window;
int xRoot, yRoot, xWindow, yWindow;
unsigned int state;
if (!XQueryPointer(display, m_window, &root, &window,
&xRoot, &yRoot, &xWindow, &yWindow, &state)) {
return 0;
}
// convert to KeyModifierMask
KeyModifierMask mask = 0;
if (state & m_numLockMask) {
mask |= KeyModifierNumLock;
}
if (state & m_capsLockMask) {
mask |= KeyModifierCapsLock;
}
if (state & m_scrollLockMask) {
mask |= KeyModifierScrollLock;
}
return mask;
}
bool
CXWindowsPrimaryScreen::isLockedToScreen() const
{
CDisplayLock display(m_screen);
// query the pointer to get the button state
Window root, window;
int xRoot, yRoot, xWindow, yWindow;
unsigned int state;
if (XQueryPointer(display, m_window, &root, &window,
&xRoot, &yRoot, &xWindow, &yWindow, &state)) {
if ((state & (Button1Mask | Button2Mask | Button3Mask |
Button4Mask | Button5Mask)) != 0) {
return true;
}
}
// get logical keyboard state
char keyMap[32];
memset(keyMap, 0, sizeof(keyMap));
XQueryKeymap(display, keyMap);
// locked if any key is down
for (unsigned int i = 0; i < sizeof(keyMap); ++i) {
if (keyMap[i] != 0) {
return true;
}
}
// not locked
return false;
}
IScreen*
CXWindowsPrimaryScreen::getScreen() const
{
return m_screen;
}
void
CXWindowsPrimaryScreen::onScreensaver(bool activated)
{
m_receiver->onScreensaver(activated);
}
bool
CXWindowsPrimaryScreen::onPreDispatch(const CEvent*)
{
return false;
}
bool
CXWindowsPrimaryScreen::onEvent(CEvent* event)
{
assert(event != NULL);
XEvent& xevent = event->m_event;
// handle event
switch (xevent.type) {
case CreateNotify:
{
// select events on new window
CDisplayLock display(m_screen);
selectEvents(display, xevent.xcreatewindow.window);
}
return true;
case MappingNotify:
// keyboard mapping changed
updateKeys();
return true;
case KeyPress:
{
log((CLOG_DEBUG1 "event: KeyPress code=%d, state=0x%04x", xevent.xkey.keycode, xevent.xkey.state));
const KeyModifierMask mask = mapModifier(xevent.xkey.state);
const KeyID key = mapKey(&xevent.xkey);
if (key != kKeyNone) {
m_receiver->onKeyDown(key, mask);
if (key == kKeyCapsLock && m_capsLockHalfDuplex) {
m_receiver->onKeyUp(key, mask | KeyModifierCapsLock);
}
else if (key == kKeyNumLock && m_numLockHalfDuplex) {
m_receiver->onKeyUp(key, mask | KeyModifierNumLock);
}
}
}
return true;
case KeyRelease:
{
const KeyModifierMask mask = mapModifier(xevent.xkey.state);
const KeyID key = mapKey(&xevent.xkey);
if (key != kKeyNone) {
// check if this is a key repeat by getting the next
// KeyPress event that has the same key and time as
// this release event, if any. first prepare the
// filter info.
CKeyEventInfo filter;
filter.m_event = KeyPress;
filter.m_window = xevent.xkey.window;
filter.m_time = xevent.xkey.time;
filter.m_keycode = xevent.xkey.keycode;
// now check for event
bool hasPress;
{
XEvent xevent2;
CDisplayLock display(m_screen);
hasPress = (XCheckIfEvent(display, &xevent2,
&CXWindowsPrimaryScreen::findKeyEvent,
(XPointer)&filter) == True);
}
if (!hasPress) {
// no press event follows so it's a plain release
log((CLOG_DEBUG1 "event: KeyRelease code=%d, state=0x%04x", xevent.xkey.keycode, xevent.xkey.state));
if (key == kKeyCapsLock && m_capsLockHalfDuplex) {
m_receiver->onKeyDown(key, mask);
}
else if (key == kKeyNumLock && m_numLockHalfDuplex) {
m_receiver->onKeyDown(key, mask);
}
m_receiver->onKeyUp(key, mask);
}
else {
// found a press event following so it's a repeat.
// we could attempt to count the already queued
// repeats but we'll just send a repeat of 1.
// note that we discard the press event.
log((CLOG_DEBUG1 "event: repeat code=%d, state=0x%04x", xevent.xkey.keycode, xevent.xkey.state));
m_receiver->onKeyRepeat(key, mask, 1);
}
}
}
return true;
case ButtonPress:
{
log((CLOG_DEBUG1 "event: ButtonPress button=%d", xevent.xbutton.button));
const ButtonID button = mapButton(xevent.xbutton.button);
if (button != kButtonNone) {
m_receiver->onMouseDown(button);
}
}
return true;
case ButtonRelease:
{
log((CLOG_DEBUG1 "event: ButtonRelease button=%d", xevent.xbutton.button));
const ButtonID button = mapButton(xevent.xbutton.button);
if (button != kButtonNone) {
m_receiver->onMouseUp(button);
}
else if (xevent.xbutton.button == 4) {
// wheel forward (away from user)
m_receiver->onMouseWheel(120);
}
else if (xevent.xbutton.button == 5) {
// wheel backward (toward user)
m_receiver->onMouseWheel(-120);
}
}
return true;
case MotionNotify:
{
log((CLOG_DEBUG2 "event: MotionNotify %d,%d", xevent.xmotion.x_root, xevent.xmotion.y_root));
// compute motion delta (relative to the last known
// mouse position)
SInt32 x = xevent.xmotion.x_root - m_x;
SInt32 y = xevent.xmotion.y_root - m_y;
// save position to compute delta of next motion
m_x = xevent.xmotion.x_root;
m_y = xevent.xmotion.y_root;
if (xevent.xmotion.send_event) {
// we warped the mouse. discard events until we
// find the matching sent event. see
// warpCursorNoFlush() for where the events are
// sent. we discard the matching sent event and
// can be sure we've skipped the warp event.
CDisplayLock display(m_screen);
do {
XMaskEvent(display, PointerMotionMask, &xevent);
} while (!xevent.xmotion.send_event);
}
else if (!isActive()) {
// motion on primary screen
m_receiver->onMouseMovePrimary(m_x, m_y);
}
else {
// motion on secondary screen. warp mouse back to
// center.
//
// my lombard (powerbook g3) running linux and
// using the adbmouse driver has two problems:
// first, the driver only sends motions of +/-2
// pixels and, second, it seems to discard some
// physical input after a warp. the former isn't a
// big deal (we're just limited to every other
// pixel) but the latter is a PITA. to work around
// it we only warp when the mouse has moved more
// than s_size pixels from the center.
static const SInt32 s_size = 32;
if (xevent.xmotion.x_root - m_xCenter < -s_size ||
xevent.xmotion.x_root - m_xCenter > s_size ||
xevent.xmotion.y_root - m_yCenter < -s_size ||
xevent.xmotion.y_root - m_yCenter > s_size) {
CDisplayLock display(m_screen);
warpCursorNoFlush(display, m_xCenter, m_yCenter);
}
// send event if mouse moved. do this after warping
// back to center in case the motion takes us onto
// the primary screen. if we sent the event first
// in that case then the warp would happen after
// warping to the primary screen's enter position,
// effectively overriding it.
if (x != 0 || y != 0) {
m_receiver->onMouseMoveSecondary(x, y);
}
}
}
return true;
}
return false;
}
SInt32
CXWindowsPrimaryScreen::getJumpZoneSize() const
{
return 1;
}
void
CXWindowsPrimaryScreen::onPreMainLoop()
{
assert(m_window != None);
}
void
CXWindowsPrimaryScreen::onPreOpen()
{
assert(m_window == None);
}
void
CXWindowsPrimaryScreen::onPostOpen()
{
// get cursor info
m_screen->getCursorPos(m_x, m_y);
m_screen->getCursorCenter(m_xCenter, m_yCenter);
// check for peculiarities
// FIXME -- may have to get these from some database
m_numLockHalfDuplex = false;
m_capsLockHalfDuplex = false;
// m_numLockHalfDuplex = true;
// m_capsLockHalfDuplex = true;
}
void
CXWindowsPrimaryScreen::onPreEnter()
{
assert(m_window != None);
}
void
CXWindowsPrimaryScreen::onPreLeave()
{
assert(m_window != None);
}
void
CXWindowsPrimaryScreen::onEnterScreenSaver()
{
CDisplayLock display(m_screen);
// set keyboard focus to root window. the screensaver should then
// pick up key events for when the user enters a password to unlock.
XSetInputFocus(display, PointerRoot, PointerRoot, CurrentTime);
}
void
CXWindowsPrimaryScreen::createWindow()
{
assert(m_window == None);
// get size of screen
SInt32 x, y, w, h;
m_screen->getShape(x, y, w, h);
// grab window attributes. this window is used to capture user
// input when the user is focused on another client. don't let
// the window manager mess with it.
XSetWindowAttributes attr;
attr.event_mask = PointerMotionMask |
ButtonPressMask | ButtonReleaseMask |
KeyPressMask | KeyReleaseMask |
KeymapStateMask | PropertyChangeMask;
attr.do_not_propagate_mask = 0;
attr.override_redirect = True;
attr.cursor = m_screen->getBlankCursor();
{
// create the grab window
CDisplayLock display(m_screen);
m_window = XCreateWindow(display, m_screen->getRoot(),
x, y, w, h, 0, 0,
InputOnly, CopyFromParent,
CWDontPropagate | CWEventMask |
CWOverrideRedirect | CWCursor,
&attr);
if (m_window == None) {
throw XScreenOpenFailure();
}
log((CLOG_DEBUG "window is 0x%08x", m_window));
// start watching for events on other windows
selectEvents(display, m_screen->getRoot());
}
// tell generic screen about the window
m_screen->setWindow(m_window);
}
void
CXWindowsPrimaryScreen::destroyWindow()
{
// display can be NULL if the server unexpectedly disconnected
if (m_window != None) {
m_screen->setWindow(None);
CDisplayLock display(m_screen);
if (display != NULL) {
XDestroyWindow(display, m_window);
}
m_window = None;
}
}
bool
CXWindowsPrimaryScreen::showWindow()
{
assert(m_window != None);
CDisplayLock display(m_screen);
// raise and show the input window
XMapRaised(display, m_window);
// grab the mouse and keyboard. keep trying until we get them.
// if we can't grab one after grabbing the other then ungrab
// and wait before retrying. give up after s_timeout seconds.
static const double s_timeout = 1.0;
int result;
CStopwatch timer;
do {
// keyboard first
do {
result = XGrabKeyboard(display, m_window, True,
GrabModeAsync, GrabModeAsync, CurrentTime);
assert(result != GrabNotViewable);
if (result != GrabSuccess) {
log((CLOG_DEBUG2 "waiting to grab keyboard"));
CThread::sleep(0.05);
if (timer.getTime() >= s_timeout) {
log((CLOG_DEBUG2 "grab keyboard timed out"));
XUnmapWindow(display, m_window);
return false;
}
}
} while (result != GrabSuccess);
log((CLOG_DEBUG2 "grabbed keyboard"));
// now the mouse
result = XGrabPointer(display, m_window, True, 0,
GrabModeAsync, GrabModeAsync,
m_window, None, CurrentTime);
assert(result != GrabNotViewable);
if (result != GrabSuccess) {
// back off to avoid grab deadlock
XUngrabKeyboard(display, CurrentTime);
log((CLOG_DEBUG2 "ungrabbed keyboard, waiting to grab pointer"));
CThread::sleep(0.05);
if (timer.getTime() >= s_timeout) {
log((CLOG_DEBUG2 "grab pointer timed out"));
XUnmapWindow(display, m_window);
return false;
}
}
} while (result != GrabSuccess);
log((CLOG_DEBUG1 "grabbed pointer and keyboard"));
return true;
}
void
CXWindowsPrimaryScreen::hideWindow()
{
CDisplayLock display(m_screen);
// unmap the grab window. this also ungrabs the mouse and keyboard.
XUnmapWindow(display, m_window);
}
void
CXWindowsPrimaryScreen::warpCursorToCenter()
{
warpCursor(m_xCenter, m_yCenter);
}
void
CXWindowsPrimaryScreen::warpCursorNoFlush(
Display* display, SInt32 x, SInt32 y)
{
assert(display != NULL);
assert(m_window != None);
// send an event that we can recognize before the mouse warp
XEvent eventBefore;
eventBefore.type = MotionNotify;
eventBefore.xmotion.display = display;
eventBefore.xmotion.window = m_window;
eventBefore.xmotion.root = m_screen->getRoot();
eventBefore.xmotion.subwindow = m_window;
eventBefore.xmotion.time = CurrentTime;
eventBefore.xmotion.x = x;
eventBefore.xmotion.y = y;
eventBefore.xmotion.x_root = x;
eventBefore.xmotion.y_root = y;
eventBefore.xmotion.state = 0;
eventBefore.xmotion.is_hint = False;
eventBefore.xmotion.same_screen = True;
XEvent eventAfter = eventBefore;
XSendEvent(display, m_window, False, 0, &eventBefore);
// warp mouse
XWarpPointer(display, None, m_screen->getRoot(), 0, 0, 0, 0, x, y);
// send an event that we can recognize after the mouse warp
XSendEvent(display, m_window, False, 0, &eventAfter);
XSync(display, False);
log((CLOG_DEBUG2 "warped to %d,%d", x, y));
}
void
CXWindowsPrimaryScreen::selectEvents(Display* display, Window w) const
{
// ignore errors while we adjust event masks. windows could be
// destroyed at any time after the XQueryTree() in doSelectEvents()
// so we must ignore BadWindow errors.
CXWindowsUtil::CErrorLock lock(display);
// adjust event masks
doSelectEvents(display, w);
}
void
CXWindowsPrimaryScreen::doSelectEvents(Display* display, Window w) const
{
// we want to track the mouse everywhere on the display. to achieve
// that we select PointerMotionMask on every window. we also select
// SubstructureNotifyMask in order to get CreateNotify events so we
// select events on new windows too.
//
// note that this can break certain clients due a design flaw of X.
// X will deliver a PointerMotion event to the deepest window in the
// hierarchy that contains the pointer and has PointerMotionMask
// selected by *any* client. if another client doesn't select
// motion events in a subwindow so the parent window will get them
// then by selecting for motion events on the subwindow we break
// that client because the parent will no longer get the events.
// FIXME -- should provide some workaround for event selection
// design flaw. perhaps only select for motion events on windows
// that already do or are top-level windows or don't propagate
// pointer events. or maybe an option to simply poll the mouse.
// we don't want to adjust our grab window
if (w == m_window) {
return;
}
// select events of interest. do this before querying the tree so
// we'll get notifications of children created after the XQueryTree()
// so we won't miss them.
XSelectInput(display, w, PointerMotionMask | SubstructureNotifyMask);
// recurse on child windows
Window rw, pw, *cw;
unsigned int nc;
if (XQueryTree(display, w, &rw, &pw, &cw, &nc)) {
for (unsigned int i = 0; i < nc; ++i) {
doSelectEvents(display, cw[i]);
}
XFree(cw);
}
}
KeyModifierMask
CXWindowsPrimaryScreen::mapModifier(unsigned int state) const
{
// FIXME -- should be configurable
KeyModifierMask mask = 0;
if (state & ShiftMask)
mask |= KeyModifierShift;
if (state & LockMask)
mask |= KeyModifierCapsLock;
if (state & ControlMask)
mask |= KeyModifierControl;
if (state & Mod1Mask)
mask |= KeyModifierAlt;
if (state & Mod2Mask)
mask |= KeyModifierNumLock;
if (state & Mod4Mask)
mask |= KeyModifierMeta;
if (state & Mod5Mask)
mask |= KeyModifierScrollLock;
return mask;
}
KeyID
CXWindowsPrimaryScreen::mapKey(XKeyEvent* event) const
{
CDisplayLock display(m_screen);
// convert to a keysym
// FIXME -- we're not properly handling unicode
KeySym keysym;
char dummy[1];
XLookupString(event, dummy, 0, &keysym, NULL);
// convert key
switch (keysym & 0xffffff00) {
case 0x0000:
// Latin-1
return static_cast<KeyID>(keysym);
case 0xfe00:
// ISO 9995 Function and Modifier Keys
if (keysym == XK_ISO_Left_Tab) {
return kKeyLeftTab;
}
return kKeyNone;
case 0xff00:
// MISCELLANY
return static_cast<KeyID>(keysym - 0xff00 + 0xef00);
default:
// FIXME -- support unicode characters
return kKeyNone;
}
}
ButtonID
CXWindowsPrimaryScreen::mapButton(unsigned int button) const
{
// FIXME -- should use button mapping?
if (button >= 1 && button <= 3) {
return static_cast<ButtonID>(button);
}
else {
return kButtonNone;
}
}
void
CXWindowsPrimaryScreen::updateKeys()
{
CDisplayLock display(m_screen);
// get modifier map from server
XModifierKeymap* keymap = XGetModifierMapping(display);
// initialize
m_numLockMask = 0;
m_capsLockMask = 0;
m_scrollLockMask = 0;
// set keycodes and masks
for (unsigned int i = 0; i < 8; ++i) {
const unsigned int bit = (1 << i);
for (int j = 0; j < keymap->max_keypermod; ++j) {
KeyCode keycode = keymap->modifiermap[i *
keymap->max_keypermod + j];
// note toggle modifier bits
const KeySym keysym = XKeycodeToKeysym(display, keycode, 0);
if (keysym == XK_Num_Lock) {
m_numLockMask |= bit;
}
else if (keysym == XK_Caps_Lock) {
m_capsLockMask |= bit;
}
else if (keysym == XK_Scroll_Lock) {
m_scrollLockMask |= bit;
}
}
}
XFreeModifiermap(keymap);
}
Bool
CXWindowsPrimaryScreen::findKeyEvent(Display*, XEvent* xevent, XPointer arg)
{
CKeyEventInfo* filter = reinterpret_cast<CKeyEventInfo*>(arg);
return (xevent->type == filter->m_event &&
xevent->xkey.window == filter->m_window &&
xevent->xkey.time == filter->m_time &&
xevent->xkey.keycode == filter->m_keycode) ? True : False;
}

View File

@@ -0,0 +1,98 @@
#ifndef CXWINDOWSPRIMARYSCREEN_H
#define CXWINDOWSPRIMARYSCREEN_H
#include "CPrimaryScreen.h"
#include "IScreenEventHandler.h"
#include "MouseTypes.h"
#if defined(X_DISPLAY_MISSING)
# error X11 is required to build synergy
#else
# include <X11/Xlib.h>
#endif
class CXWindowsScreen;
class IScreenReceiver;
class IPrimaryScreenReceiver;
//! X11 primary screen implementation
class CXWindowsPrimaryScreen :
public CPrimaryScreen, public IScreenEventHandler {
public:
CXWindowsPrimaryScreen(IScreenReceiver*, IPrimaryScreenReceiver*);
virtual ~CXWindowsPrimaryScreen();
// CPrimaryScreen overrides
virtual void reconfigure(UInt32 activeSides);
virtual void warpCursor(SInt32 x, SInt32 y);
virtual KeyModifierMask getToggleMask() const;
virtual bool isLockedToScreen() const;
virtual IScreen* getScreen() const;
// IScreenEventHandler overrides
virtual void onScreensaver(bool activated);
virtual bool onPreDispatch(const CEvent* event);
virtual bool onEvent(CEvent* event);
virtual SInt32 getJumpZoneSize() const;
protected:
// CPrimaryScreen overrides
virtual void onPreMainLoop();
virtual void onPreOpen();
virtual void onPostOpen();
virtual void onPreEnter();
virtual void onPreLeave();
virtual void onEnterScreenSaver();
virtual void createWindow();
virtual void destroyWindow();
virtual bool showWindow();
virtual void hideWindow();
virtual void warpCursorToCenter();
virtual void updateKeys();
private:
void warpCursorNoFlush(Display*,
SInt32 xAbsolute, SInt32 yAbsolute);
void selectEvents(Display*, Window) const;
void doSelectEvents(Display*, Window) const;
KeyModifierMask mapModifier(unsigned int state) const;
KeyID mapKey(XKeyEvent*) const;
ButtonID mapButton(unsigned int button) const;
class CKeyEventInfo {
public:
int m_event;
Window m_window;
Time m_time;
KeyCode m_keycode;
};
static Bool findKeyEvent(Display*, XEvent* xevent, XPointer arg);
private:
CXWindowsScreen* m_screen;
IPrimaryScreenReceiver* m_receiver;
// our window
Window m_window;
// note toggle keys that toggle on up/down (false) or on
// transition (true)
bool m_numLockHalfDuplex;
bool m_capsLockHalfDuplex;
// masks that indicate which modifier bits are for toggle keys
unsigned int m_numLockMask;
unsigned int m_capsLockMask;
unsigned int m_scrollLockMask;
// last mouse position
SInt32 m_x, m_y;
// position of center pixel of screen
SInt32 m_xCenter, m_yCenter;
};
#endif

32
lib/server/Makefile.am Normal file
View File

@@ -0,0 +1,32 @@
## Process this file with automake to produce Makefile.in
NULL =
DEPTH = ../..
noinst_LIBRARIES = libserver.a
libserver_a_SOURCES = \
CClientProxy.cpp \
CClientProxy1_0.cpp \
CConfig.cpp \
CHTTPServer.cpp \
CPrimaryClient.cpp \
CPrimaryScreen.cpp \
CServer.cpp \
CXWindowsPrimaryScreen.cpp \
CClientProxy.h \
CClientProxy1_0.h \
CConfig.h \
CHTTPServer.h \
CPrimaryClient.h \
CPrimaryScreen.h \
CServer.h \
CXWindowsPrimaryScreen.h \
$(NULL)
INCLUDES = \
-I$(DEPTH)/lib/base \
-I$(DEPTH)/lib/mt \
-I$(DEPTH)/lib/io \
-I$(DEPTH)/lib/http \
-I$(DEPTH)/lib/net \
-I$(DEPTH)/lib/synergy \
-I$(DEPTH)/lib/platform \
$(NULL)