1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
|
/*
* Copyright (C) 2005-2018 Team Kodi
* This file is part of Kodi - https://kodi.tv
*
* SPDX-License-Identifier: GPL-2.0-or-later
* See LICENSES/README.md for more information.
*/
#include "EventClient.h"
#include "EventPacket.h"
#include "ServiceBroker.h"
#include "dialogs/GUIDialogKaiToast.h"
#include "filesystem/File.h"
#include "guilib/LocalizeStrings.h"
#include "input/ButtonTranslator.h"
#include "input/GamepadTranslator.h"
#include "input/IRTranslator.h"
#include "input/Key.h"
#include "input/KeyboardTranslator.h"
#include "utils/StringUtils.h"
#include "utils/TimeUtils.h"
#include "utils/log.h"
#include "windowing/GraphicContext.h"
#include <map>
#include <mutex>
#include <queue>
using namespace EVENTCLIENT;
using namespace EVENTPACKET;
struct ButtonStateFinder
{
explicit ButtonStateFinder(const CEventButtonState& state)
: m_keycode(state.m_iKeyCode)
, m_map(state.m_mapName)
, m_button(state.m_buttonName)
{}
bool operator()(const CEventButtonState& state)
{
return state.m_mapName == m_map
&& state.m_iKeyCode == m_keycode
&& state.m_buttonName == m_button;
}
private:
unsigned short m_keycode;
std::string m_map;
std::string m_button;
};
/************************************************************************/
/* CEventButtonState */
/************************************************************************/
void CEventButtonState::Load()
{
if ( m_iKeyCode == 0 )
{
if ( (m_mapName.length() > 0) && (m_buttonName.length() > 0) )
{
m_iKeyCode = CButtonTranslator::TranslateString(m_mapName, m_buttonName);
if (m_iKeyCode == 0)
{
Reset();
CLog::Log(LOGERROR, "ES: Could not map {} : {} to a key", m_mapName, m_buttonName);
}
}
}
else
{
if (m_mapName.length() > 3 &&
(StringUtils::StartsWith(m_mapName, "JS")) )
{
m_joystickName = m_mapName.substr(2); // <num>:joyname
m_iControllerNumber = (unsigned char)(*(m_joystickName.c_str()))
- (unsigned char)'0'; // convert <num> to int
m_joystickName = m_joystickName.substr(2); // extract joyname
}
if (m_mapName.length() > 3 &&
(StringUtils::StartsWith(m_mapName, "CC")) ) // custom map - CC:<controllerName>
{
m_customControllerName = m_mapName.substr(3);
}
}
}
/************************************************************************/
/* CEventClient */
/************************************************************************/
bool CEventClient::AddPacket(std::unique_ptr<CEventPacket> packet)
{
if (!packet)
return false;
ResetTimeout();
if ( packet->Size() > 1 )
{
//! @todo limit payload size
if (m_seqPackets[packet->Sequence()])
{
if(!m_bSequenceError)
CLog::Log(LOGWARNING,
"CEventClient::AddPacket - received packet with same sequence number ({}) as "
"previous packet from eventclient {}",
packet->Sequence(), m_deviceName);
m_bSequenceError = true;
m_seqPackets.erase(packet->Sequence());
}
unsigned int sequence = packet->Sequence();
m_seqPackets[sequence] = std::move(packet);
if (m_seqPackets.size() == m_seqPackets[sequence]->Size())
{
unsigned int iSeqPayloadSize = 0;
for (unsigned int i = 1; i <= m_seqPackets[sequence]->Size(); i++)
{
iSeqPayloadSize += m_seqPackets[i]->PayloadSize();
}
std::vector<uint8_t> newPayload(iSeqPayloadSize);
auto newPayloadIter = newPayload.begin();
unsigned int packets = m_seqPackets[sequence]->Size(); // packet can be deleted in this loop
for (unsigned int i = 1; i <= packets; i++)
{
newPayloadIter =
std::copy(m_seqPackets[i]->Payload(),
m_seqPackets[i]->Payload() + m_seqPackets[i]->PayloadSize(), newPayloadIter);
if (i > 1)
m_seqPackets.erase(i);
}
m_seqPackets[1]->SetPayload(newPayload);
m_readyPackets.push(std::move(m_seqPackets[1]));
m_seqPackets.clear();
}
}
else
{
m_readyPackets.push(std::move(packet));
}
return true;
}
void CEventClient::ProcessEvents()
{
if (!m_readyPackets.empty())
{
while ( ! m_readyPackets.empty() )
{
ProcessPacket(m_readyPackets.front().get());
if ( ! m_readyPackets.empty() ) // in case the BYE packet cleared the queues
m_readyPackets.pop();
}
}
}
bool CEventClient::GetNextAction(CEventAction &action)
{
std::unique_lock<CCriticalSection> lock(m_critSection);
if (!m_actionQueue.empty())
{
// grab the next action in line
action = m_actionQueue.front();
m_actionQueue.pop();
return true;
}
else
{
// we got nothing
return false;
}
}
bool CEventClient::ProcessPacket(CEventPacket *packet)
{
if (!packet)
return false;
bool valid = false;
switch (packet->Type())
{
case PT_HELO:
valid = OnPacketHELO(packet);
break;
case PT_BYE:
valid = OnPacketBYE(packet);
break;
case PT_BUTTON:
valid = OnPacketBUTTON(packet);
break;
case EVENTPACKET::PT_MOUSE:
valid = OnPacketMOUSE(packet);
break;
case PT_NOTIFICATION:
valid = OnPacketNOTIFICATION(packet);
break;
case PT_PING:
valid = true;
break;
case PT_LOG:
valid = OnPacketLOG(packet);
break;
case PT_ACTION:
valid = OnPacketACTION(packet);
break;
default:
CLog::Log(LOGDEBUG, "ES: Got Unknown Packet");
break;
}
if (valid)
ResetTimeout();
return valid;
}
bool CEventClient::OnPacketHELO(CEventPacket *packet)
{
//! @todo check it last HELO packet was received less than 5 minutes back
//! if so, do not show notification of connection.
if (Greeted())
return false;
unsigned char *payload = (unsigned char *)packet->Payload();
int psize = (int)packet->PayloadSize();
// parse device name
if (!ParseString(payload, psize, m_deviceName))
return false;
CLog::Log(LOGINFO, "ES: Incoming connection from {}", m_deviceName);
// icon type
unsigned char ltype;
if (!ParseByte(payload, psize, ltype))
return false;
m_eLogoType = (LogoType)ltype;
// client's port (if any)
unsigned short dport;
if (!ParseUInt16(payload, psize, dport))
return false;
m_iRemotePort = (unsigned int)dport;
// 2 x reserved uint32 (8 bytes)
unsigned int reserved;
ParseUInt32(payload, psize, reserved);
ParseUInt32(payload, psize, reserved);
// image data if any
std::string iconfile = "special://temp/helo";
if (m_eLogoType != LT_NONE && psize>0)
{
switch (m_eLogoType)
{
case LT_JPEG:
iconfile += ".jpg";
break;
case LT_GIF:
iconfile += ".gif";
break;
default:
iconfile += ".png";
break;
}
XFILE::CFile file;
if (!file.OpenForWrite(iconfile, true) || file.Write((const void *)payload, psize) != psize)
{
CLog::Log(LOGERROR, "ES: Could not write icon file");
m_eLogoType = LT_NONE;
}
}
m_bGreeted = true;
if (m_eLogoType == LT_NONE)
{
CGUIDialogKaiToast::QueueNotification(g_localizeStrings.Get(33200), m_deviceName);
}
else
{
CGUIDialogKaiToast::QueueNotification(iconfile, g_localizeStrings.Get(33200), m_deviceName);
}
return true;
}
bool CEventClient::OnPacketBYE(CEventPacket *packet)
{
if (!Greeted())
return false;
m_bGreeted = false;
FreePacketQueues();
m_currentButton.Reset();
return true;
}
bool CEventClient::OnPacketBUTTON(CEventPacket *packet)
{
unsigned char *payload = (unsigned char *)packet->Payload();
int psize = (int)packet->PayloadSize();
std::string map, button;
unsigned short flags;
unsigned short bcode;
unsigned short amount;
// parse the button code
if (!ParseUInt16(payload, psize, bcode))
return false;
// parse flags
if (!ParseUInt16(payload, psize, flags))
return false;
// parse amount
if (!ParseUInt16(payload, psize, amount))
return false;
// parse the map to use
if (!ParseString(payload, psize, map))
return false;
// parse button name
if (flags & PTB_USE_NAME)
{
if (!ParseString(payload, psize, button))
return false;
}
unsigned int keycode;
if(flags & PTB_USE_NAME)
keycode = 0;
else if(flags & PTB_VKEY)
keycode = bcode|KEY_VKEY;
else if(flags & PTB_UNICODE)
keycode = bcode|ES_FLAG_UNICODE;
else
keycode = bcode;
float famount = 0;
bool active = (flags & PTB_DOWN) ? true : false;
if (flags & PTB_USE_NAME)
CLog::Log(LOGDEBUG, "EventClient: button name \"{}\" map \"{}\" {}", button, map,
active ? "pressed" : "released");
else
CLog::Log(LOGDEBUG, "EventClient: button code {} {}", bcode, active ? "pressed" : "released");
if(flags & PTB_USE_AMOUNT)
{
if(flags & PTB_AXIS)
famount = (float)amount/65535.0f*2.0f-1.0f;
else
famount = (float)amount/65535.0f;
}
else
famount = (active ? 1.0f : 0.0f);
if(flags & PTB_QUEUE)
{
/* find the last queued item of this type */
std::unique_lock<CCriticalSection> lock(m_critSection);
CEventButtonState state( keycode,
map,
button,
famount,
(flags & (PTB_AXIS|PTB_AXISSINGLE)) ? true : false,
(flags & PTB_NO_REPEAT) ? false : true,
(flags & PTB_USE_AMOUNT) ? true : false );
/* correct non active events so they work with rest of code */
if(!active)
{
state.m_bActive = false;
state.m_bRepeat = false;
state.m_fAmount = 0.0;
}
std::list<CEventButtonState>::reverse_iterator it;
it = find_if( m_buttonQueue.rbegin() , m_buttonQueue.rend(), ButtonStateFinder(state));
if(it == m_buttonQueue.rend())
{
if(active)
m_buttonQueue.push_back(state);
}
else
{
if(!active && it->m_bActive)
{
/* since modifying the list invalidates the reverse iterator */
std::list<CEventButtonState>::iterator it2 = (++it).base();
/* if last event had an amount, we must resend without amount */
if (it2->m_bUseAmount && it2->m_fAmount != 0.0f)
{
m_buttonQueue.push_back(state);
}
/* if the last event was waiting for a repeat interval, it has executed already.*/
if(it2->m_bRepeat)
{
if (it2->m_iNextRepeat.time_since_epoch().count() > 0)
{
m_buttonQueue.erase(it2);
}
else
{
it2->m_bRepeat = false;
it2->m_bActive = false;
}
}
}
else if(active && !it->m_bActive)
{
m_buttonQueue.push_back(state);
if (!state.m_bRepeat && state.m_bAxis && state.m_fAmount != 0.0f)
{
state.m_bActive = false;
state.m_bRepeat = false;
state.m_fAmount = 0.0;
m_buttonQueue.push_back(state);
}
}
else
it->m_fAmount = state.m_fAmount;
}
}
else
{
std::unique_lock<CCriticalSection> lock(m_critSection);
if ( flags & PTB_DOWN )
{
m_currentButton.m_iKeyCode = keycode;
m_currentButton.m_mapName = map;
m_currentButton.m_buttonName = button;
m_currentButton.m_fAmount = famount;
m_currentButton.m_bRepeat = (flags & PTB_NO_REPEAT) ? false : true;
m_currentButton.m_bAxis = (flags & PTB_AXIS) ? true : false;
m_currentButton.m_iNextRepeat = {};
m_currentButton.SetActive();
m_currentButton.Load();
}
else
{
/* when a button is released that had amount, make sure *
* to resend the keypress with an amount of 0 */
if ((flags & PTB_USE_AMOUNT) && m_currentButton.m_fAmount > 0.0f)
{
CEventButtonState state( m_currentButton.m_iKeyCode,
m_currentButton.m_mapName,
m_currentButton.m_buttonName,
0.0,
m_currentButton.m_bAxis,
false,
true );
m_buttonQueue.push_back (state);
}
m_currentButton.Reset();
}
}
return true;
}
bool CEventClient::OnPacketMOUSE(CEventPacket *packet)
{
unsigned char *payload = (unsigned char *)packet->Payload();
int psize = (int)packet->PayloadSize();
unsigned char flags;
unsigned short mx, my;
// parse flags
if (!ParseByte(payload, psize, flags))
return false;
// parse x position
if (!ParseUInt16(payload, psize, mx))
return false;
// parse x position
if (!ParseUInt16(payload, psize, my))
return false;
{
std::unique_lock<CCriticalSection> lock(m_critSection);
if ( flags & PTM_ABSOLUTE )
{
m_iMouseX = mx;
m_iMouseY = my;
m_bMouseMoved = true;
}
}
return true;
}
bool CEventClient::OnPacketNOTIFICATION(CEventPacket *packet)
{
unsigned char *payload = (unsigned char *)packet->Payload();
int psize = (int)packet->PayloadSize();
std::string title, message;
// parse caption
if (!ParseString(payload, psize, title))
return false;
// parse message
if (!ParseString(payload, psize, message))
return false;
// icon type
unsigned char ltype;
if (!ParseByte(payload, psize, ltype))
return false;
m_eLogoType = (LogoType)ltype;
// reserved uint32
unsigned int reserved;
ParseUInt32(payload, psize, reserved);
// image data if any
std::string iconfile = "special://temp/notification";
if (m_eLogoType != LT_NONE && psize>0)
{
switch (m_eLogoType)
{
case LT_JPEG:
iconfile += ".jpg";
break;
case LT_GIF:
iconfile += ".gif";
break;
default:
iconfile += ".png";
break;
}
XFILE::CFile file;
if (!file.OpenForWrite(iconfile, true) || file.Write((const void *)payload, psize) != psize)
{
CLog::Log(LOGERROR, "ES: Could not write icon file");
m_eLogoType = LT_NONE;
}
}
if (m_eLogoType == LT_NONE)
{
CGUIDialogKaiToast::QueueNotification(title, message);
}
else
{
CGUIDialogKaiToast::QueueNotification(iconfile, title, message);
}
return true;
}
bool CEventClient::OnPacketLOG(CEventPacket *packet)
{
unsigned char *payload = (unsigned char *)packet->Payload();
int psize = (int)packet->PayloadSize();
std::string logmsg;
unsigned char ltype;
if (!ParseByte(payload, psize, ltype))
return false;
if (!ParseString(payload, psize, logmsg))
return false;
CLog::Log((int)ltype, "{}", logmsg);
return true;
}
bool CEventClient::OnPacketACTION(CEventPacket *packet)
{
unsigned char *payload = (unsigned char *)packet->Payload();
int psize = (int)packet->PayloadSize();
std::string actionString;
unsigned char actionType;
if (!ParseByte(payload, psize, actionType))
return false;
if (!ParseString(payload, psize, actionString))
return false;
switch(actionType)
{
case AT_EXEC_BUILTIN:
case AT_BUTTON:
{
std::unique_lock<CCriticalSection> lock(m_critSection);
m_actionQueue.push(CEventAction(actionString.c_str(), actionType));
}
break;
default:
CLog::Log(LOGDEBUG, "ES: Failed - ActionType: {} ActionString: {}", actionType, actionString);
return false;
break;
}
return true;
}
bool CEventClient::ParseString(unsigned char* &payload, int &psize, std::string& parsedVal)
{
if (psize <= 0)
return false;
unsigned char *pos = (unsigned char *)memchr((void*)payload, (int)'\0', psize);
if (!pos)
return false;
parsedVal = (char*)payload;
psize -= ((pos - payload) + 1);
payload = pos+1;
return true;
}
bool CEventClient::ParseByte(unsigned char* &payload, int &psize, unsigned char& parsedVal)
{
if (psize <= 0)
return false;
parsedVal = *payload;
payload++;
psize--;
return true;
}
bool CEventClient::ParseUInt32(unsigned char* &payload, int &psize, unsigned int& parsedVal)
{
if (psize < 4)
return false;
parsedVal = ntohl(*((unsigned int *)payload));
payload+=4;
psize-=4;
return true;
}
bool CEventClient::ParseUInt16(unsigned char* &payload, int &psize, unsigned short& parsedVal)
{
if (psize < 2)
return false;
parsedVal = ntohs(*((unsigned short *)payload));
payload+=2;
psize-=2;
return true;
}
void CEventClient::FreePacketQueues()
{
std::unique_lock<CCriticalSection> lock(m_critSection);
while ( ! m_readyPackets.empty() )
m_readyPackets.pop();
m_seqPackets.clear();
}
unsigned int CEventClient::GetButtonCode(std::string& strMapName, bool& isAxis, float& amount, bool &isJoystick)
{
std::unique_lock<CCriticalSection> lock(m_critSection);
unsigned int bcode = 0;
if ( m_currentButton.Active() )
{
bcode = m_currentButton.KeyCode();
strMapName = m_currentButton.JoystickName();
isJoystick = true;
if (strMapName.length() == 0)
{
strMapName = m_currentButton.CustomControllerName();
isJoystick = false;
}
isAxis = m_currentButton.Axis();
amount = m_currentButton.Amount();
if ( ! m_currentButton.Repeat() )
m_currentButton.Reset();
else
{
if ( ! CheckButtonRepeat(m_currentButton.m_iNextRepeat) )
bcode = 0;
}
return bcode;
}
if(m_buttonQueue.empty())
return 0;
std::list<CEventButtonState> repeat;
std::list<CEventButtonState>::iterator it;
for(it = m_buttonQueue.begin(); bcode == 0 && it != m_buttonQueue.end(); ++it)
{
bcode = it->KeyCode();
strMapName = it->JoystickName();
isJoystick = true;
if (strMapName.length() == 0)
{
strMapName = it->CustomControllerName();
isJoystick = false;
}
isAxis = it->Axis();
amount = it->Amount();
if(it->Repeat())
{
/* MUST update m_iNextRepeat before resend */
bool skip = !it->Axis() && !CheckButtonRepeat(it->m_iNextRepeat);
repeat.push_back(*it);
if(skip)
{
bcode = 0;
continue;
}
}
}
m_buttonQueue.erase(m_buttonQueue.begin(), it);
m_buttonQueue.insert(m_buttonQueue.end(), repeat.begin(), repeat.end());
return bcode;
}
bool CEventClient::GetMousePos(float& x, float& y)
{
std::unique_lock<CCriticalSection> lock(m_critSection);
if (m_bMouseMoved)
{
x = (m_iMouseX / 65535.0f) * CServiceBroker::GetWinSystem()->GetGfxContext().GetWidth();
y = (m_iMouseY / 65535.0f) * CServiceBroker::GetWinSystem()->GetGfxContext().GetHeight();
m_bMouseMoved = false;
return true;
}
return false;
}
bool CEventClient::CheckButtonRepeat(std::chrono::time_point<std::chrono::steady_clock>& next)
{
auto now = std::chrono::steady_clock::now();
if (next.time_since_epoch().count() == 0)
{
next = now + m_iRepeatDelay;
return true;
}
else if ( now > next )
{
next = now + m_iRepeatSpeed;
return true;
}
return false;
}
bool CEventClient::Alive() const
{
// 60 seconds timeout
if ( (time(NULL) - m_lastPing) > 60 )
return false;
return true;
}
|