Repository navigation
Expand file tree
/
Copy pathScriptRpc.cs
More file actions
417 lines (371 loc) · 16.9 KB
/
Copy pathScriptRpc.cs
File metadata and controls
417 lines (371 loc) · 16.9 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
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
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static SharpTagManager.ScriptRunner;
namespace SharpTagManager
{
static class ScriptRpc
{
// Result of a "process" RPC call. All fields are optional on the wire — a script only
// fills in what it actually did (add/replace tags, and/or rewrote the image in place).
public class ScriptProcessResult
{
public List<TagItemOrdered> Tags;
// "add" (default) just merges Tags in; "replace_layer" additionally prunes stale tags
// out of DefaultLayer (generalizes the old img2tag behavior); "replace_all" prunes
// every tag not returned (generalizes the old tag2tag behavior).
public string TagsMode = "add";
public string DefaultLayer;
public bool ImageModified;
}
public static ScriptProcessResult Process(ScriptInstance script, ImageItem item, string arguments = null)
{
ScriptProcessResult result = null;
if (script.AccessMutex.Wait(Timeout.Infinite))
{
// finally releases even on a failed/aborted call, so a killed script doesn't wedge future runs.
try
{
if (script.Rpc == null)
return null; // Script never made it past launch (e.g. venv prep failed)
// Expand paths if needed
string imagePath = item.PathSourceImage;
string path = item.PathSourceImage;
if (item.Project != null)
{
imagePath = item.Project.ToFullPath(imagePath);
path = item.Project.ToFullPath(path);
}
path = Path.ChangeExtension(path, ".json");
// Assemble arguments - always send everything a script might want, since it now
// decides for itself what to do with image/tags/layers.
Dictionary<string, object> args = new Dictionary<string, object>();
if (arguments != null)
args["args"] = arguments;
args["image_path"] = imagePath;
args["item"] = item.Name;
args["path"] = path;
if (item.Tags != null)
args["tags"] = PackTags(item.Tags);
if (item.Project?.Layers?.Items != null)
args["layers"] = PackLayers(item.Project.Layers.Items);
// Perform the RPC call
var response = script.Rpc.Call("process", args);
// Parse results
result = ParseProcessResult(response);
}
finally
{
script.AccessMutex.Release();
}
}
return result;
}
public static TaskItem Task_process(ScriptInstance script, ImageItem item, string arguments = null, TaskItem.TaskComplete callback = null)
{
TaskItem taskNew = new TaskItem();
taskNew.Name = "process " + item.Name;
taskNew.Script = script;
taskNew.Target = item;
taskNew.Tag = item;
taskNew.Arguments = arguments;
taskNew.TaskCallback = callback;
taskNew.TaskToExecute = TaskWork_process;
return taskNew;
}
static void TaskWork_process(TaskItem task)
{
task.Results = ScriptRpc.Process(task.Script, task.Target as ImageItem, task.Arguments);
}
private static ScriptProcessResult ParseProcessResult(JsonRpc.RpcResponse response)
{
Dictionary<string, object> dict = response?.Result as Dictionary<string, object>;
if (dict == null)
return null;
ScriptProcessResult result = new ScriptProcessResult();
if (dict.TryGetValue("tags", out object tagsObj) && tagsObj is ArrayList tagsList)
result.Tags = ParseTags(tagsList);
if (dict.TryGetValue("tags_mode", out object modeObj) && modeObj is string modeStr)
result.TagsMode = modeStr;
if (dict.TryGetValue("default_layer", out object layerObj) && layerObj is string layerStr)
result.DefaultLayer = layerStr;
if (dict.TryGetValue("image_modified", out object imgObj))
result.ImageModified = Convert.ToBoolean(imgObj);
return result;
}
private static ArrayList PackTags(TagCollection tags)
{
ArrayList results = new ArrayList();
foreach (TagItem item in tags.Items)
{
Dictionary<string, object> itemDict = new Dictionary<string, object>();
itemDict["name"] = item.Name;
itemDict["layer"] = item.Layer.Name;
itemDict["weight"] = tags.GetWeight(item);
BoundArea area = tags.GetBoundArea(item);
if (area != null)
itemDict["bound_area"] = PackBoundArea(area);
results.Add(itemDict);
}
return results;
}
private static ArrayList PackLayers(List<TagLayer> layers)
{
ArrayList results = new ArrayList();
foreach (TagLayer layer in layers)
{
// Don't hand scripts a layer the user has turned off or locked from editing -
// it's not meaningfully in play, so there's nothing useful for a script to do
// with it (e.g. suggest tagging into it, or read it as "current" context).
if (!layer.Options.Enabled || layer.Options.Locked)
continue;
// Global layer tags apply to every image in the project - the only sanctioned
// way to add to this layer is the layer editor UI (see TagLayer_GlobalTags.
// IntroduceTag), so don't suggest it to scripts as somewhere to tag into.
if (layer is TagLayer_GlobalTags)
continue;
var options = layer.Options;
Dictionary<string, object> dict = new Dictionary<string, object>();
dict["name"] = layer.Name;
dict["type"] = layer.TypeName;
dict["description"] = layer.Description;
dict["tags_are_editable"] = layer.TagsAreEditable;
dict["tint_color"] = ColorTranslator.ToHtml(layer.TintColor);
dict["visible"] = options.Visible;
dict["locked"] = options.Locked;
dict["enabled"] = options.Enabled;
dict["exportable"] = options.Exportable;
dict["autogenerated"] = options.Autogenerated;
results.Add(dict);
}
return results;
}
private static Dictionary<string, object> PackBoundArea(BoundArea area)
{
var dict = new Dictionary<string, object>();
dict["box"] = new Dictionary<string, object>
{
["x"] = area.BoundingBox.X,
["y"] = area.BoundingBox.Y,
["width"] = area.BoundingBox.Width,
["height"] = area.BoundingBox.Height,
};
if (!area.IsAABB)
{
var sizes = new ArrayList();
var points = new ArrayList();
foreach (var poly in area.Polygons)
{
sizes.Add(poly.Count);
foreach (var pt in poly)
points.Add(new Dictionary<string, object> { ["x"] = pt.X, ["y"] = pt.Y });
}
dict["polygon_sizes"] = sizes;
dict["points"] = points;
}
return dict;
}
private static BoundArea ParseBoundArea(Dictionary<string, object> areaDict)
{
// Parse the bounding box
RectangleF box = default;
if (areaDict.TryGetValue("box", out object boxObj) && boxObj is Dictionary<string, object> boxDict)
{
float x = 0, y = 0, w = 0, h = 0;
if (boxDict.TryGetValue("x", out object v)) x = Convert.ToSingle(v);
if (boxDict.TryGetValue("y", out object v2)) y = Convert.ToSingle(v2);
if (boxDict.TryGetValue("width", out object v3)) w = Convert.ToSingle(v3);
if (boxDict.TryGetValue("height", out object v4)) h = Convert.ToSingle(v4);
box = new System.Drawing.RectangleF(x, y, w, h);
}
else
{
return null;
}
// Parse optional polygon data
if (areaDict.TryGetValue("polygon_sizes", out object sizesObj) && sizesObj is ArrayList sizesList
&& areaDict.TryGetValue("points", out object ptsObj) && ptsObj is ArrayList ptsList
&& sizesList.Count > 0)
{
var polygons = new List<List<System.Drawing.PointF>>();
int offset = 0;
foreach (object sizeObj in sizesList)
{
int count = Convert.ToInt32(sizeObj);
var poly = new List<System.Drawing.PointF>();
for (int i = 0; i < count && offset + i < ptsList.Count; i++)
{
var ptDict = ptsList[offset + i] as Dictionary<string, object>;
if (ptDict != null)
{
float px = ptDict.TryGetValue("x", out object px_) ? Convert.ToSingle(px_) : 0;
float py = ptDict.TryGetValue("y", out object py_) ? Convert.ToSingle(py_) : 0;
poly.Add(new System.Drawing.PointF(px, py));
}
}
offset += count;
if (poly.Count > 0)
polygons.Add(poly);
}
if (polygons.Count > 0)
return new BoundArea(polygons);
}
return new BoundArea(box);
}
private static List<TagItemOrdered> ParseTags(ArrayList rawData)
{
List<TagItemOrdered> tags = new List<TagItemOrdered>();
foreach (var result in rawData)
{
if (result is string)
{
// Simple format of getting a list of tag names (strings)
TagItem tagI = new TagItem(result as string);
TagItemOrdered tag = new TagItemOrdered(tagI);
tag.NewName = result as string;
tags.Add(tag);
}
if (result is Dictionary<string, object>)
{
// Advanced format returning extra info as a Dict (containing name, layer, weight...)
Dictionary<string, object> resultD = result as Dictionary<string, object>;
object objTemp = null;
string name = "New";
if (resultD.TryGetValue("name", out objTemp))
name = (objTemp as string) ?? objTemp?.ToString() ?? "New";
TagItem tagI = new TagItem(name);
TagItemOrdered tag = new TagItemOrdered(tagI);
if (resultD.TryGetValue("layer", out objTemp))
tag.Layer = new TagLayer_Tags(objTemp as string);
if (resultD.TryGetValue("weight", out objTemp))
tag.Weight = Convert.ToDouble(objTemp, System.Globalization.CultureInfo.InvariantCulture);
if (resultD.TryGetValue("bound_area", out objTemp) && objTemp is Dictionary<string, object> areaDict)
tag.BoundArea = ParseBoundArea(areaDict);
tags.Add(tag);
}
}
return tags;
}
}
class JsonRpc
{
public class RpcResponse
{
public int Id = -1;
public object Result = null;
public string Error = null;
public string Json = null;
}
BlockingCollection<string> StreamIn = new BlockingCollection<string>();
int msgCnt = 0;
ScriptInstance Script;
public JsonRpc(ScriptInstance script)
{
Script = script;
StreamIn = new BlockingCollection<string>();
}
public void StdioReceive(DataReceivedEventArgs e, bool isError=false)
{
// Only queue lines that look like JSON - plain stdout chatter goes to the console instead.
if ((e.Data != null) && (isError == false) && e.Data.TrimStart().StartsWith("{"))
{
// Add() can race with Abort() completing the collection - just drop the line.
try { StreamIn.Add(e.Data); } catch (InvalidOperationException) { }
}
}
// Unblocks a GetResponse() still waiting after the process was killed/exited unanswered.
public void Abort()
{
if (!StreamIn.IsAddingCompleted)
StreamIn.CompleteAdding();
}
public RpcResponse Call(string method, Dictionary<string, object> args = null)
{
Script.FormOutput?.Process_RpcEvent(method);
int id = Request(method, args);
RpcResponse response = GetResponse(id);
Script.FormOutput?.Process_RpcSuccess(response.Json);
return response;
}
public int Request(string method, Dictionary<string, object> args=null)
{
JsonMapper serializer = new JsonMapper();
// Assemble RPC request
int id = msgCnt++;
Dictionary<string, object> rpcRequest = new Dictionary<string, object>();
rpcRequest["id"] = id;
rpcRequest["method"] = method;
rpcRequest["params"] = args;
// Send it as json
string requestJson = serializer.Serialize(rpcRequest);
Script.ProcessObj?.StandardInput.WriteLine(requestJson);
return id;
}
public void Notify(string method, Dictionary<string, object> args = null)
{
JsonMapper serializer = new JsonMapper();
// Assemble RPC request
Dictionary<string, object> rpcRequest = new Dictionary<string, object>();
rpcRequest["method"] = method;
rpcRequest["params"] = args;
// Send it as json
string requestJson = serializer.Serialize(rpcRequest);
Script.ProcessObj?.StandardInput.WriteLine(requestJson);
}
public RpcResponse GetResponse(int expectedId = -1)
{
JsonMapper serializer = new JsonMapper();
while (true)
{
// Get the response
Dictionary<string, object> rpcResponse;
string responseJson;
try
{
responseJson = StreamIn.Take();
}
catch (InvalidOperationException)
{
// Abort() was called (process killed/exited) before a response ever arrived.
throw new IOException("Script process ended before sending a response.");
}
try
{
rpcResponse = serializer.Deserialize<Dictionary<string, object>>(responseJson);
}
catch (Exception)
{
continue; // Not valid JSON, skip it
}
if (rpcResponse == null)
continue;
// Skip stale responses left over from an earlier, abandoned request
if ((expectedId >= 0) && rpcResponse.TryGetValue("id", out object idCheck)
&& (idCheck is int idInt) && (idInt != expectedId))
continue;
// Check for error
if (rpcResponse.ContainsKey("error") && (rpcResponse["error"] != null))
throw new IOException($"JSON-RPC Error response: {rpcResponse["error"].ToString()}");
// Pack up the response
RpcResponse response = new RpcResponse();
object ErrorObj = null;
object IdObj = null;
rpcResponse.TryGetValue("id", out IdObj);
if (IdObj is int)
response.Id = (int)IdObj;
rpcResponse.TryGetValue("result", out response.Result);
rpcResponse.TryGetValue("error", out ErrorObj);
response.Error = ErrorObj?.ToString();
response.Json = responseJson;
return response;
}
}
}
}