-
Notifications
You must be signed in to change notification settings - Fork 7
/
djl_kslog.hxx
106 lines (87 loc) · 3.02 KB
/
djl_kslog.hxx
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
// writes and reads keystrokes to and from a file
#pragma once
class CKeyStrokes
{
public:
enum KeystrokeMode { ksm_None, ksm_Write, ksm_Read };
CKeyStrokes() : ksmode( ksm_None ) {}
~CKeyStrokes()
{
if ( ksm_Write == ksmode )
Persist();
} //~CKeyStrokes
void SetMode( KeystrokeMode ksm )
{
ksmode = ksm;
if ( ksm_Read == ksm )
Restore();
} //SetMode
bool KeystrokeAvailable() { return ( ( ksm_Read == ksmode ) && keys.size() ); }
bool InReadMode() { return ( ksm_Read == ksmode ); }
uint16_t Peek()
{
assert( KeystrokeAvailable() );
tracer.Trace( "peeked keystroke %04x\n", keys[ 0 ] );
return keys[ 0 ];
} //Peek
uint16_t ConsumeNext()
{
assert( KeystrokeAvailable() );
tracer.Trace( "keystrokes in read buffer available: %zd\n", keys.size() );
uint16_t x = keys[ 0 ];
keys.erase( keys.begin() ); // expensive, but not very frequent
return x;
} //ConsumeNext
void Append( uint16_t x )
{
if ( ksm_Write == ksmode )
{
tracer.Trace( "pushing char %04x onto the keystroke log\n", x );
keys.push_back( x );
}
} //Append
bool Persist()
{
// save what's in the vector to kslog.txt
tracer.Trace( "persisting %zd keystrokes\n", keys.size() );
FILE * fp = fopen( "kslog.txt", "w" );
if ( 0 != fp )
{
for ( size_t i = 0; i < keys.size(); i++ )
fprintf( fp, "%04x", keys[ i ] );
fclose( fp );
return true;
}
tracer.Trace( "error: can't create file kslog.txt\n" );
return false;
} //Persist
bool Restore()
{
// read what's in kslog.txt to the vector
tracer.Trace( "restoring kslog.txt\n" );
FILE * fp = fopen( "kslog.txt", "r" );
if ( 0 != fp )
{
long l = portable_filelen( fp );
size_t count = l / 4;
tracer.Trace( "keystroke file length: %ld, count %zd\n", l, count );
for ( size_t i = 0; i < count; i++ )
{
char ac[ 5 ] = {0};
if ( fread( ac, 1, 4, fp ) )
{
uint16_t x = (uint16_t) strtoull( ac, 0, 16 );
tracer.Trace( "read key %04x\n", x );
keys.push_back( x );
}
}
fclose( fp );
return true;
}
tracer.Trace( "error: can't find kslog.txt to read it\n" );
return false;
} //Restore
private:
vector<uint16_t> keys; // high part = scancode, lowpart = ascii char
KeystrokeMode ksmode;
};