-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathEngineMessenger.mm
More file actions
89 lines (67 loc) · 2.17 KB
/
Copy pathEngineMessenger.mm
File metadata and controls
89 lines (67 loc) · 2.17 KB
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
//
// EngineMessenger.m
// ChessKitEngine
//
#import "EngineMessenger.h"
#import "../Engines/AvailableEngines.h"
@implementation EngineMessenger : NSObject
Engine *_engine;
NSPipe *_pipe;
NSFileHandle *_pipeReadHandle;
/// Initializes a new `EngineMessenger` with default engine `Stockfish`.
- (id)init {
return [self initWithEngineType:EngineTypeStockfish];
}
- (id)initWithEngineType: (EngineType_objc) type {
self = [super init];
if (self) {
switch (type) {
case EngineTypeStockfish:
_engine = new StockfishEngine();
break;
case EngineTypeLc0:
_engine = new Lc0Engine();
break;
case EngineTypeArasan:
_engine = new ArasanEngine();
break;
}
_engine->initialize();
}
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
_engine->deinitialize();
}
- (void)start {
_pipe = [NSPipe pipe];
_pipeReadHandle = [_pipe fileHandleForReading];
dup2([[_pipe fileHandleForWriting] fileDescriptor], fileno(stdout));
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(readStdout:)
name:NSFileHandleReadCompletionNotification
object:_pipeReadHandle
];
[_pipeReadHandle readInBackgroundAndNotify];
}
- (void)stop {
[_pipeReadHandle closeFile];
_pipe = NULL;
_pipeReadHandle = NULL;
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)sendCommand: (NSString*) command {
_engine->send_command(std::string([command UTF8String]));
}
# pragma mark Private
- (void)readStdout: (NSNotification*) notification {
[_pipeReadHandle readInBackgroundAndNotify];
NSData *data = [[notification userInfo] objectForKey:NSFileHandleNotificationDataItem];
NSArray<NSString *> *output = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] componentsSeparatedByString:@"\n"];
[output enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[self responseHandler](obj);
}];
}
@end