-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
415 lines (396 loc) · 17.9 KB
/
Program.cs
File metadata and controls
415 lines (396 loc) · 17.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
// ncode-cli — thin C# console wrapper around NeoLABNcodeSDK.dll.
//
// The Go side (internal/ncode/pattern/neolab) shells out to this binary
// once per page because the official Ncode algorithm is shipped only as
// a .NET Framework 4.5 managed DLL. This file keeps parity with the
// reference flow in Ncode-SDK2.0/cs/sampleApp(Ncode)/Program.cs, but
// exposes a single "generate" command with CLI flags and prints a JSON
// summary on stdout so the caller can locate the generated PNG.
//
// Build (Windows, Developer Command Prompt):
// msbuild NcodeCli.csproj /p:Configuration=Release /p:Platform=x64
//
// Build (non-Windows, not supported by NeoLAB SDK itself — but the
// resulting .exe runs on Linux/macOS via Mono 6.8+):
// mono-csc -r:NeoLABNcodeSDK.dll -target:exe -out:ncode-cli.exe Program.cs
// (DLL calls still require network to api.neolab.net with a valid key)
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web.Script.Serialization;
using NeoLABNcodeSDK;
namespace NcodeCli
{
internal static class Program
{
private static int Main(string[] args)
{
try
{
if (args.Length == 0)
{
Console.Error.WriteLine("usage: ncode-cli <generate|tickets|postscript> [flags]");
return 2;
}
if (args[0] == "tickets")
{
return RunTickets(args);
}
if (args[0] == "generate")
{
return RunGenerate(ParseFlags(args));
}
if (args[0] == "postscript")
{
return RunPostscript(ParseFlags(args));
}
Console.Error.WriteLine("unknown command: " + args[0]);
return 2;
}
catch (Exception ex)
{
Console.Error.WriteLine("fatal: " + ex.Message);
return 1;
}
}
// RunTickets prints the appKey's ticket list as JSON, so callers
// can discover which (section, owner, book, page) ranges are
// usable before invoking generate.
private static int RunTickets(string[] args)
{
string appKey = null;
for (int i = 1; i < args.Length - 1; i++)
{
if (args[i] == "--app-key") { appKey = args[i + 1]; break; }
}
if (string.IsNullOrEmpty(appKey))
{
Console.Error.WriteLine("tickets: --app-key is required");
return 2;
}
var sdk = new CNcodeSDK();
string tmp = Path.Combine(Path.GetTempPath(), "ncode-cli-cache");
Directory.CreateDirectory(tmp);
sdk.Init(appKey, tmp, tmp);
var tickets = sdk.GetTickets();
if (tickets == null)
{
Console.Error.WriteLine("GetTickets failed: " + sdk.GetLastError());
return 3;
}
var list = new List<Dictionary<string, object>>();
foreach (var t in tickets)
{
list.Add(new Dictionary<string, object> {
{"ncodeType", t.ncodeType.ToString()},
{"section", t.section},
{"ownerStart", t.ownerStart}, {"ownerSize", t.ownerSize},
{"bookStart", t.bookStart}, {"bookSize", t.bookSize},
{"pageStart", t.pageStart}, {"pageSize", t.pageSize},
{"period", t.period},
{"extraInfo", t.extraInfo},
});
}
Console.Out.Write(new JavaScriptSerializer().Serialize(list));
return 0;
}
// RunPostscript drives the SDK's GetPostscript path. The SDK
// manual §6 (Class summary) limits PostScript output to
// S1C6/P1C6 ticket types and dot-mode only — passing N3C6 or
// line-mode through this command will fail at the SDK call.
// dotScale (0.2 ~ 2.0) maps to GetPostscript's third argument
// and is the SDK-native way to sweep dot size for moiré
// tuning, replacing the PDF-side Type 3 glyph workaround.
//
// The PS file is written to f.OutPs verbatim, with one PS page
// per Ncode page (count = f.PageCount). RIPs that consume the
// PS directly print the dot pattern as native vector output —
// the route §8 "Caution" of the SDK manual recommends to
// bypass the printer's own dithering, which is the root cause
// of the polygonal moiré observed on the raster path.
//
// Ticket discovery is intentionally skipped here (manual §7-6b
// / sample app's commented "GenerateNcode direct" path). The
// caller passes (--type, --section, --owner, --book, --page)
// verbatim and the SDK validates against the app key's
// entitlements server-side. This works around app keys whose
// GetTickets() only surfaces a subset of the granted ranges.
private static int RunPostscript(Flags f)
{
if (string.IsNullOrEmpty(f.OutPs))
{
Console.Error.WriteLine("postscript: --out-ps is required");
return 2;
}
if (f.PageCount <= 0)
{
Console.Error.WriteLine("postscript: --page-count must be positive");
return 2;
}
if (f.DotScale < 0.2 || f.DotScale > 2.0)
{
Console.Error.WriteLine("postscript: --dot-scale must be in 0.2 .. 2.0 (SDK manual §6 GetPostscript)");
return 2;
}
NCODE_TYPE ncodeType;
try { ncodeType = ParseNcodeType(f.TypeStr); }
catch (Exception ex)
{
Console.Error.WriteLine("postscript: " + ex.Message);
return 2;
}
if (ncodeType != NCODE_TYPE.S1C6 && ncodeType != NCODE_TYPE.P1C6)
{
Console.Error.WriteLine("postscript: --type must be S1C6 or P1C6 (SDK manual §6 GetPostscript notes)");
return 2;
}
// PostScript is dot-only per SDK manual §6 (SetDotType notes
// "S1C6, P1C6 and postscript output use just only dot type
// code"). Reject --line-mode here so callers see the
// restriction immediately rather than after the SDK call.
if (f.LineMode)
{
Console.Error.WriteLine("postscript: line mode not supported (SDK manual §6)");
return 2;
}
var sdk = new CNcodeSDK();
string tmp = Path.Combine(Path.GetTempPath(), "ncode-cli-cache");
Directory.CreateDirectory(tmp);
sdk.Init(f.AppKey, tmp, tmp);
sdk.SetDotType(true);
// Ticket-less GenerateNcode overload (matches the commented
// "direct call" sample at cs/sampleApp(Ncode)/Program.cs:133
// and cpp/sampleApp(Ncode_cpp)/main.cpp:114).
List<NcodePage> pages;
int gen = sdk.GenerateNcode(out pages, ncodeType,
f.Section, f.Owner, f.Book, f.Page,
f.WidthInch, f.HeightInch, f.PageCount);
if (gen != 0 || pages == null || pages.Count == 0)
{
Console.Error.WriteLine("GenerateNcode failed (" + gen + "): " + sdk.GetLastError());
return 6;
}
// GetPostscript wants a basename for the same backslash
// workaround GetImage needs; relocate after the call (see
// MONO_PATH_WORKAROUND.md). One basename per ticket is
// fine — the SDK writes a single multi-page PS file.
string basename = Path.GetFileName(f.OutPs);
int ps = sdk.GetPostscript(pages, basename, f.DotScale);
if (ps != 0)
{
Console.Error.WriteLine("GetPostscript failed (" + ps + "): " + sdk.GetLastError());
return 7;
}
string produced = null;
foreach (var cand in new[] {
Path.Combine(tmp, basename),
tmp + "\\" + basename,
})
{
if (File.Exists(cand)) { produced = cand; break; }
}
if (produced == null)
{
Console.Error.WriteLine("SDK reported success but no PS file was found next to cache dir");
return 8;
}
if (produced != f.OutPs)
{
if (File.Exists(f.OutPs)) File.Delete(f.OutPs);
File.Move(produced, f.OutPs);
}
var pageList = new List<Dictionary<string, object>>();
foreach (var p in pages)
{
pageList.Add(new Dictionary<string, object> {
{"section", p.section}, {"owner", p.owner},
{"book", p.book}, {"page", p.page},
});
}
var resp = new Dictionary<string, object>
{
{"psPath", f.OutPs},
{"pageCount", pages.Count},
{"dotScale", f.DotScale},
{"widthInch", f.WidthInch},
{"heightInch", f.HeightInch},
{"pages", pageList},
};
Console.Out.Write(new JavaScriptSerializer().Serialize(resp));
return 0;
}
private static int RunGenerate(Flags f)
{
if (string.IsNullOrEmpty(f.OutPng))
{
Console.Error.WriteLine("generate: --out-png is required");
return 2;
}
var sdk = new CNcodeSDK();
// Point workingFolder / cacheFolder at a writable temp path;
// the SDK's Windows-style default (profile + backslash path)
// breaks on Linux/macOS under Mono.
string tmp = Path.Combine(Path.GetTempPath(), "ncode-cli-cache");
Directory.CreateDirectory(tmp);
sdk.Init(f.AppKey, tmp, tmp);
var tickets = sdk.GetTickets();
if (tickets == null || tickets.Count == 0)
{
Console.Error.WriteLine("GetTickets returned no tickets: " + sdk.GetLastError());
return 3;
}
if (f.TicketIdx < 0 || f.TicketIdx >= tickets.Count)
{
Console.Error.WriteLine("ticket index " + f.TicketIdx + " out of range (0.." + (tickets.Count - 1) + ")");
return 4;
}
// Translate the requested page coordinates into offsets within
// the chosen ticket. Caller supplies absolute section/owner/
// book/page; we subtract the ticket's starts.
var t = tickets[f.TicketIdx];
int ownerOffset = f.Owner - t.ownerStart;
int bookOffset = f.Book - t.bookStart;
int pageOffset = f.Page - t.pageStart;
if (ownerOffset < 0 || bookOffset < 0 || pageOffset < 0)
{
Console.Error.WriteLine("requested page is below ticket start range");
return 5;
}
if (ownerOffset >= t.ownerSize || bookOffset >= t.bookSize || pageOffset >= t.pageSize)
{
Console.Error.WriteLine(
"requested page is above ticket end range: "
+ "owner=" + f.Owner + " (ticket " + t.ownerStart + ".." + (t.ownerStart + t.ownerSize - 1) + ") "
+ "book=" + f.Book + " (ticket " + t.bookStart + ".." + (t.bookStart + t.bookSize - 1) + ") "
+ "page=" + f.Page + " (ticket " + t.pageStart + ".." + (t.pageStart + t.pageSize - 1) + ")");
return 5;
}
var info = sdk.SetStartPageFromTicket(t, ownerOffset, bookOffset, pageOffset);
sdk.SetDotType(!f.LineMode); // SetDotType(true) = dot pattern
List<NcodePage> pages;
int gen = sdk.GenerateNcode(out pages, info, f.WidthInch, f.HeightInch, 1);
if (gen != 0 || pages == null || pages.Count == 0)
{
Console.Error.WriteLine("GenerateNcode failed (" + gen + "): " + sdk.GetLastError());
return 6;
}
// SDK's GetImage concatenates paths with a hard-coded "\\"
// (see ncode-generation.md §2.3 / disassembly IL_030a). On
// Windows that yields workingFolder\filename as expected;
// on Linux/macOS the backslash ends up as a literal char in
// the filename. Pass only the basename and then relocate
// the produced file to the caller's --out-png so both
// platforms behave the same.
string basename = Path.GetFileName(f.OutPng);
int img = sdk.GetImage(pages[0], f.DPI, basename, f.Bold);
if (img != 0)
{
Console.Error.WriteLine("GetImage failed (" + img + "): " + sdk.GetLastError());
return 7;
}
string produced = null;
foreach (var cand in new[] {
Path.Combine(tmp, basename), // Windows / Mono happy path
tmp + "\\" + basename, // Linux literal-backslash
})
{
if (File.Exists(cand)) { produced = cand; break; }
}
if (produced == null)
{
Console.Error.WriteLine("SDK reported success but no PNG was found next to cache dir");
return 8;
}
if (produced != f.OutPng)
{
if (File.Exists(f.OutPng)) File.Delete(f.OutPng);
File.Move(produced, f.OutPng);
}
var resp = new Dictionary<string, object>
{
{"pageId", pages[0].section + "." + pages[0].owner + "." + pages[0].book + "." + pages[0].page},
{"pngPath", f.OutPng},
{"dpi", f.DPI},
{"widthInch", f.WidthInch},
{"heightInch", f.HeightInch},
};
Console.Out.Write(new JavaScriptSerializer().Serialize(resp));
return 0;
}
// ParseNcodeType maps the wire string ("N3C6"/"G3C6"/"S1C6"/
// "P1C6") to the SDK's nested enum. Kept private so the CLI
// is the single place that knows how to bridge the names.
private static NCODE_TYPE ParseNcodeType(string s)
{
if (s == null) throw new ArgumentException("ncode type is empty");
switch (s.ToUpperInvariant())
{
case "N3C6": return NCODE_TYPE.N3C6;
case "G3C6": return NCODE_TYPE.G3C6;
case "S1C6": return NCODE_TYPE.S1C6;
case "P1C6": return NCODE_TYPE.P1C6;
}
throw new ArgumentException("unknown ncode type: " + s);
}
private sealed class Flags
{
public string AppKey;
public int TicketIdx;
public string TypeStr = "N3C6";
public int Section, Owner, Book, Page;
public double WidthInch, HeightInch;
public int DPI = 600;
public bool Bold, LineMode;
public string OutPng;
// PostScript-only fields. PageCount is the number of
// sequential Ncode pages to emit (each occupies one PS page);
// OutPs is the destination .ps path; DotScale is the SDK's
// 0.2..2.0 dot-size multiplier (= dotScale parameter on
// GetPostscript).
public int PageCount = 1;
public string OutPs;
public double DotScale = 1.0;
}
private static Flags ParseFlags(string[] args)
{
var f = new Flags();
var inv = System.Globalization.CultureInfo.InvariantCulture;
// args[0] == "generate"
for (int i = 1; i < args.Length; i++)
{
string a = args[i];
if (a == "--bold") { f.Bold = true; continue; }
if (a == "--line-mode") { f.LineMode = true; continue; }
// value-taking flags: advance i and read args[i]
if (i + 1 >= args.Length)
throw new ArgumentException("flag " + a + " needs a value");
string v = args[++i];
switch (a)
{
case "--app-key": f.AppKey = v; break;
case "--ticket-idx": f.TicketIdx = int.Parse(v, inv); break;
case "--type": f.TypeStr = v; break;
case "--section": f.Section = int.Parse(v, inv); break;
case "--owner": f.Owner = int.Parse(v, inv); break;
case "--book": f.Book = int.Parse(v, inv); break;
case "--page": f.Page = int.Parse(v, inv); break;
case "--width-inch": f.WidthInch = double.Parse(v, inv); break;
case "--height-inch": f.HeightInch = double.Parse(v, inv); break;
case "--dpi": f.DPI = int.Parse(v, inv); break;
case "--out-png": f.OutPng = v; break;
case "--out-ps": f.OutPs = v; break;
case "--page-count": f.PageCount = int.Parse(v, inv); break;
case "--dot-scale": f.DotScale = double.Parse(v, inv); break;
default: throw new ArgumentException("unknown flag: " + a);
}
}
if (string.IsNullOrEmpty(f.AppKey)) throw new ArgumentException("--app-key is required");
// OutPng is required only for the generate command; OutPs
// is required only for postscript. Validate per-command in
// the run helpers so a missing flag prints the right hint.
if (f.WidthInch <= 0 || f.HeightInch <= 0) throw new ArgumentException("page dimensions must be positive");
return f;
}
}
}