/
Agth.cs
438 lines (405 loc) · 14 KB
/
Agth.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Pipes;
using System.Threading;
using System.Diagnostics;
namespace ChiiTrans
{
class AgthMessage
{
private static int idCtr = 0;
public string agthThread;
public int id;
public uint pid;
public uint time;
public string text;
public AgthMessage(string agthThread, uint pid, uint time, string text)
{
this.id = ++idCtr;
this.agthThread = agthThread;
this.pid = pid;
this.time = time;
this.text = text;
}
}
class AgthMessageList : List<AgthMessage>
{
private Mutex mutex;
public AgthMessageList() : base()
{
mutex = new Mutex();
}
public void Lock()
{
mutex.WaitOne();
}
public void Unlock()
{
mutex.ReleaseMutex();
}
}
class BlockList : LinkedList<string>
{
public bool IsMonitored { get; set; }
public BlockList()
: base()
{
IsMonitored = false;
}
}
class Agth
{
public bool is_on {get; private set;}
public bool isConnected { get; private set; }
private const string pipeName = "agth";
private NamedPipeServerStream pipe;
private Thread readingThread;
private Thread parsingThread;
private AutoResetEvent newMessages;
private AgthMessageList messages;
public Dictionary<string, BlockList> blocks;
public bool manualMonitoring;
public string CurrentApp { get; private set; }
private string CurrentAppKeys;
private Dictionary<uint, string> pidToApp;
public JsObject appProfiles;
public Agth()
{
is_on = false;
isConnected = false;
lastGoodName = false;
messages = new AgthMessageList();
blocks = new Dictionary<string, BlockList>();
newMessages = new AutoResetEvent(false);
manualMonitoring = false;
CurrentApp = null;
pidToApp = new Dictionary<uint, string>();
oldPid = 0;
}
public bool TryConnectPipe()
{
if (isConnected)
return true;
else
{
try
{
pipe = new NamedPipeServerStream(pipeName, PipeDirection.In);
isConnected = true;
StartReadingThread();
if (parsingThread == null)
StartParsingThread();
return true;
}
catch (Exception)
{
return false;
}
}
}
public void Disconnect()
{
if (isConnected)
{
isConnected = false;
TurnOff();
pipe.Close();
pipe.Dispose();
}
}
public bool TurnOn()
{
if (TryConnectPipe())
{
is_on = true;
Form1.thisForm.UpdateButtonOnOff(true);
return true;
}
else
{
return false;
}
}
public void TurnOff()
{
is_on = false;
Form1.thisForm.UpdateButtonOnOff(false);
}
private void StartReadingThread()
{
readingThread = new Thread(ReadingThreadProc);
readingThread.IsBackground = true;
readingThread.Start();
}
private void ReadingThreadProc()
{
try
{
byte[] buf = new byte[100];
messages.Lock();
messages.Clear();
messages.Unlock();
while (isConnected)
{
if (!pipe.IsConnected)
{
pipe.WaitForConnection();
}
pipe.Read(buf, 0, 20);
uint seg = BitConverter.ToUInt32(buf, 0);
uint ofs = BitConverter.ToUInt32(buf, 4);
uint pid = BitConverter.ToUInt32(buf, 8);
uint time = BitConverter.ToUInt32(buf, 12);
int size = BitConverter.ToInt32(buf, 16);
if (time == 0)
break;
size = size * 2;
pipe.Read(buf, 0, 48);
int len = 0;
while (len < 48 && (buf[len] != 0 || buf[len + 1] != 0))
len += 2;
if (len == 0 || len > 48)
break;
string funcName = Encoding.Unicode.GetString(buf, 0, len);
string text;
if (size <= buf.Length)
{
pipe.Read(buf, 0, size);
text = Encoding.Unicode.GetString(buf, 0, size);
}
else
{
byte[] buf2 = new byte[size];
pipe.Read(buf2, 0, size);
text = Encoding.Unicode.GetString(buf2, 0, size);
}
if (isConnected)
AddMessage(funcName, seg, ofs, pid, time, text);
}
}
catch (Exception)
{
}
finally
{
isConnected = false;
TurnOff();
try
{
pipe.Close();
}
catch (Exception) { }
if (Global.fullscreen)
Global.FullscreenOff();
}
}
private void StartParsingThread()
{
parsingThread = new Thread(ParsingThreadProc);
parsingThread.IsBackground = true;
parsingThread.Start();
}
private bool isGoodName(string agthThread)
{
string threadName = agthThread.Substring(agthThread.LastIndexOf(' ') + 1);
return threadName == "KiriKiri" || threadName == "System40" || threadName == "RealLive" || threadName.StartsWith("TextOut") || threadName.StartsWith("UserHook");
}
uint oldPid;
private void ParsingThreadProc()
{
Dictionary<string, StringBuilder> parsed = new Dictionary<string, StringBuilder>();
while (true)
{
newMessages.WaitOne();
parsed.Clear();
Thread.Sleep(0);
int old = messages.Count;
for (int i = 0; i < 50; ++i) //to prevent infinite flood cycle
{
Thread.Sleep(Global.options.messageDelay);
if (messages.Count <= old || Global.options.checkRepeatingPhrasesAdv) //no wait for flood games
break;
old = messages.Count;
}
messages.Lock();
string lastThreadName = "";
try
{
if (messages.Count > 0)
{
foreach (AgthMessage msg in messages)
{
if (msg.pid != oldPid)
{
oldPid = msg.pid;
SetCurrentApp(msg.pid);
}
StringBuilder s;
if (!parsed.TryGetValue(msg.agthThread, out s))
{
s = new StringBuilder();
parsed[msg.agthThread] = s;
}
//if (s.Length + msg.text.Length <= Global.options.maxSourceLength)
s.Append(msg.text);
}
lastThreadName = messages[messages.Count - 1].agthThread;
messages.Clear();
}
}
finally
{
messages.Unlock();
}
alreadyAdded = false;
bool good = false;
if (!manualMonitoring)
{
foreach (string name in parsed.Keys)
{
if (isGoodName(name))
{
good = true;
break;
}
}
}
foreach (KeyValuePair<string, StringBuilder> pair in parsed)
{
AddBlock(pair.Key, pair.Value.ToString(), good);
}
}
}
private void AddMessage(string funcName, uint seg, uint ofs, uint pid, uint time, string text)
{
string agthThread = string.Format("0x{0:X8}:{1:X8} {2}", seg, ofs, funcName);
messages.Lock();
messages.Add(new AgthMessage(agthThread, pid, time, text));
messages.Unlock();
newMessages.Set();
}
bool lastGoodName;
bool alreadyAdded;
private void AddBlock(string agthThread, string text, bool haveGood)
{
if (!blocks.ContainsKey(agthThread))
{
blocks.Add(agthThread, new BlockList());
if (Global.options.monitorNewThreads || !manualMonitoring && !alreadyAdded)
{
bool good = isGoodName(agthThread);
if (good || !lastGoodName && !haveGood)
{
if (!manualMonitoring)
{
foreach (BlockList bl in blocks.Values)
{
bl.IsMonitored = false;
}
}
blocks[agthThread].IsMonitored = true;
lastGoodName = good;
alreadyAdded = true;
}
}
if (FormMonitor.instance.Visible)
FormMonitor.instance.UpdateThreadList();
}
blocks[agthThread].AddLast(text);
if (blocks[agthThread].Count > 100)
{
blocks[agthThread].RemoveFirst();
}
if (FormMonitor.instance.Visible)
FormMonitor.instance.AddThreadBlock(agthThread, text);
if (is_on && blocks[agthThread].IsMonitored)
{
Translation.Translate(text, null, true);
}
}
public void SetCurrentApp(string app)
{
if (app != null && app != CurrentApp)
{
if (CurrentApp != null)
SaveAppProfile(CurrentApp);
CurrentApp = app;
CurrentAppKeys = "";
blocks.Clear();
Global.ResetGameWindow();
LoadAppProfile(CurrentApp);
SaveAppProfile(CurrentApp);
}
}
public void SetCurrentApp(uint pid)
{
if (!pidToApp.ContainsKey(pid))
{
pidToApp[pid] = Global.AppNameFromPid(pid);
}
SetCurrentApp(pidToApp[pid]);
}
private void SaveAppProfile(string app)
{
JsObject data = appProfiles["profiles"][app];
data.str["keys"] = CurrentAppKeys;
JsArray mon = new JsArray();
foreach (KeyValuePair<string, BlockList> kvp in blocks)
{
if (kvp.Value.IsMonitored)
mon.Add(new JsAtom(kvp.Key));
}
data["monitor"] = mon;
data.num["manual"] = manualMonitoring ? 1 : 0;
}
private void LoadAppProfile(string app)
{
if (appProfiles["profiles"].dict.ContainsKey(app))
{
JsObject data = appProfiles["profiles"][app];
foreach (string threadName in data["monitor"].str)
{
if (!blocks.ContainsKey(threadName))
{
blocks.Add(threadName, new BlockList());
blocks[threadName].IsMonitored = true;
}
}
manualMonitoring = data.num["manual"] != 0;
CurrentAppKeys = data.str["keys"];
}
}
public void SaveAppProfiles()
{
if (CurrentApp != null)
SaveAppProfile(CurrentApp);
try
{
string filename = Path.Combine(Global.cfgdir, "apps.txt");
File.WriteAllText(filename, appProfiles.Serialize());
}
catch (Exception)
{ }
}
public void LoadAppProfiles()
{
try
{
string filename = Path.Combine(Global.cfgdir, "apps.txt");
appProfiles = Json.Parse(File.ReadAllText(filename));
}
catch (Exception)
{
appProfiles = new JsObject();
appProfiles.str["last_run"] = "";
}
}
public void SetCurrentAppKeys(string keys)
{
CurrentAppKeys = keys;
}
}
}