/
VT100StateMachine.m
71 lines (57 loc) · 1.72 KB
/
VT100StateMachine.m
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
#import "VT100StateMachine.h"
#import "DebugLogging.h"
#import "VT100State.h"
@implementation VT100StateMachine {
NSMutableArray *_states;
}
- (instancetype)init {
self = [super init];
if (self) {
_states = [[NSMutableArray alloc] init];
}
return self;
}
- (void)addState:(VT100State *)state {
[_states addObject:state];
}
- (void)setGroundState:(VT100State *)groundState {
_groundState = groundState;
if (!_currentState) {
_currentState = _groundState;
}
}
- (void)handleCharacter:(unsigned char)character {
VT100StateTransition *transition = [_currentState stateTransitionForCharacter:character];
DLog(@"Handle %c (0x%02x): transition from %@ to %@",
character, character, _currentState, transition.toState);
if (transition) {
VT100State *toState = transition.toState;
BOOL changingState = (toState != _currentState);
if (changingState && _currentState.exitAction) {
_currentState.exitAction(character);
}
if (transition.action) {
transition.action(character);
}
if (changingState && toState.entryAction) {
toState.entryAction(character);
}
_currentState = toState;
}
}
- (id)copyWithZone:(NSZone *)zone {
VT100StateMachine *theCopy = [[VT100StateMachine alloc] init];
[theCopy.states addObjectsFromArray:self.states];
theCopy.currentState = self.currentState;
theCopy.groundState = self.groundState;
return theCopy;
}
- (VT100State *)stateWithIdentifier:(NSObject *)identifier {
for (VT100State *state in _states) {
if ([state.identifier isEqual:identifier]) {
return state;
}
}
return nil;
}
@end