-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathProgram.cs
636 lines (544 loc) · 31 KB
/
Program.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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
using System;
using System.Collections.Generic;
using System.IO;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
namespace merginto
{
internal class Program
{
public static int Main(string[] args)
{
const string appName = "merginto";
const string appTitle = "[ mergeinto Console ] ";
Console.Clear();
Console.WindowWidth = Console.LargestWindowWidth * 9 / 10;
Console.WindowHeight = Console.LargestWindowHeight * 4 / 10;
Console.Title = appName;
Console.WriteLine(appTitle);
#region Args Parsing
string
pathComicsDir = null,
pathOutputDir = null;
bool hideTitle = false;
bool dontAskAgain = false;
int argsCount = args.Length;
if (argsCount >= 1) // Parse Args
{
for (int argIndex = 0; argIndex < argsCount; argIndex += 1)
{
switch (args[argIndex].ToUpper())
{
case "/INPUT":
case "-INPUT":
case "/I":
case "-I":
case "/IN":
case "-IN":
pathComicsDir = args[argIndex + 1];
argIndex += 1;
break;
case "/OUTPUT":
case "-OUTPUT":
case "/OUT":
case "-OUT":
case "/O":
case "-O":
pathOutputDir = args[argIndex + 1];
argIndex += 1;
break;
case "/HELP":
case "-HELP":
case "/?":
HelpPrint();
return 0;
case "/HIDETITLE":
case "-HIDETITLE":
case "/H":
case "-H":
hideTitle = true;
break;
case "/Y":
case "-Y":
case "/YES":
case "-YES":
dontAskAgain = true;
break;
default:
WriteLine("Cannot Parse Arguments!", ConsoleColor.Red);
HelpPrint();
return -1;
}
}
}
else // Receive Input
{
//WriteLine(@" _____ _____ _____ _____ _____ _____ _____ _______", ConsoleColor.Cyan);
//WriteLine(@" /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /::\ \", ConsoleColor.Cyan);
//WriteLine(@" /::\____\ /::\ \ /::\ \ /::\ \ /::\ \ /::\____\ /::\ \ /::::\ \", ConsoleColor.Cyan);
//WriteLine(@" /::::| | /::::\ \ /::::\ \ /::::\ \ \:::\ \ /::::| | \:::\ \ /::::::\ \", ConsoleColor.Cyan);
//WriteLine(@" /:::::| | /::::::\ \ /::::::\ \ /::::::\ \ \:::\ \ /:::::| | \:::\ \ /::::::::\ \", ConsoleColor.Cyan);
//WriteLine(@" /::::::| | /:::/\:::\ \ /:::/\:::\ \ /:::/\:::\ \ \:::\ \ /::::::| | \:::\ \ /:::/~~\:::\ \", ConsoleColor.Cyan);
//WriteLine(@" /:::/|::| | /:::/__\:::\ \ /:::/__\:::\ \ /:::/ \:::\ \ \:::\ \ /:::/|::| | \:::\ \ /:::/ \:::\ \", ConsoleColor.Cyan);
//WriteLine(@" /:::/ |::| | /::::\ \:::\ \ /::::\ \:::\ \ /:::/ \:::\ \ /::::\ \ /:::/ |::| | /::::\ \ /:::/ / \:::\ \", ConsoleColor.Cyan);
//WriteLine(@" /:::/ |::|___|______ /::::::\ \:::\ \ /::::::\ \:::\ \ /:::/ / \:::\ \ ____ /::::::\ \ /:::/ |::| | _____ /::::::\ \ /:::/____/ \:::\____\", ConsoleColor.Cyan);
//WriteLine(@" /:::/ |::::::::\ \ /:::/\:::\ \:::\ \ /:::/\:::\ \:::\____\ /:::/ / \:::\ ___\ /\ \ /:::/\:::\ \ /:::/ |::| |/\ \ /:::/\:::\ \ |:::| | |:::| |", ConsoleColor.Cyan);
//WriteLine(@"/:::/ |:::::::::\____\/:::/__\:::\ \:::\____\/:::/ \:::\ \:::| |/:::/____/ ___\:::| |/::\ \/:::/ \:::\____\/:: / |::| /::\____\ /:::/ \:::\____\|:::|____| |:::| |", ConsoleColor.Cyan);
//WriteLine(@"\::/ / ~~~~~/:::/ /\:::\ \:::\ \::/ /\::/ |::::\ /:::|____|\:::\ \ /\ /:::|____|\:::\ /:::/ \::/ /\::/ /|::| /:::/ / /:::/ \::/ / \:::\ \ /:::/ /", ConsoleColor.Cyan);
//WriteLine(@" \/____/ /:::/ / \:::\ \:::\ \/____/ \/____|:::::\/:::/ / \:::\ /::\ \::/ / \:::\/:::/ / \/____/ \/____/ |::| /:::/ / /:::/ / \/____/ \:::\ \ /:::/ /", ConsoleColor.Cyan);
//WriteLine(@" /:::/ / \:::\ \:::\ \ |:::::::::/ / \:::\ \:::\ \/____/ \::::::/ / |::|/:::/ / /:::/ / \:::\ /:::/ /", ConsoleColor.Cyan);
//WriteLine(@" /:::/ / \:::\ \:::\____\ |::|\::::/ / \:::\ \:::\____\ \::::/____/ |::::::/ / /:::/ / \:::\__/:::/ /", ConsoleColor.Cyan);
//WriteLine(@" /:::/ / \:::\ \::/ / |::| \::/____/ \:::\ /:::/ / \:::\ \ |:::::/ / \::/ / \::::::::/ /", ConsoleColor.Cyan);
//WriteLine(@" /:::/ / \:::\ \/____/ |::| ~| \:::\/:::/ / \:::\ \ |::::/ / \/____/ \::::::/ /", ConsoleColor.Cyan);
//WriteLine(@" /:::/ / \:::\ \ |::| | \::::::/ / \:::\ \ /:::/ / \::::/ /", ConsoleColor.Cyan);
//WriteLine(@" /:::/ / \:::\____\ \::| | \::::/ / \:::\____\ /:::/ / \::/____/", ConsoleColor.Cyan);
//WriteLine(@" \::/ / \::/ / \:| | \::/____/ \::/ / \::/ / ~~", ConsoleColor.Cyan);
//WriteLine(@" \/____/ \/____/ \|___| \/____/ \/____/", ConsoleColor.Cyan);
string[] autoFolders = Directory.GetDirectories(System.Environment.CurrentDirectory);
bool inputDefined = false, _outputDefined = false;
foreach (string folder in autoFolders)
{
switch (Path.GetFileName(folder).ToUpperInvariant())
{
case "INPUT":
case "IN":
inputDefined = true;
pathComicsDir = folder;
break;
case "OUTPUT":
case "OUT":
_outputDefined = true;
pathOutputDir = folder;
break;
}
}
//WriteLine("\n언제든 종료하고 싶으시면 Ctrl+C를 입력해 주세요.",ConsoleColor.Magenta);
//WriteLine("폴더 혹은 파일의 이름이 너무 길거나 (70문자 이상) 알 수 없는 문자가 포함된 경우 오류가 발생합니다!",ConsoleColor.Magenta);
Write("\n\n");
if (inputDefined)
{
WriteLine("작품 입력 폴더가 자동 감지되었습니다!", ConsoleColor.DarkGray);
WriteLine("Input Folder Auto-Detected!", ConsoleColor.DarkGray);
WriteLine($"IN: {pathComicsDir}", ConsoleColor.DarkGray);
}
else
{
WriteLine("입력 폴더(\"Input\")가 감지되지 않았습니다. 직접 설정해 주세요.");
WriteLine("The input folder could not be found. Please Set Manually.");
Write("\n");
WriteLine("작품 폴더들이 들어있는 폴더의 경로를 입력하거나 이 창으로 드래그하세요. (입력 후 Enter)", ConsoleColor.Yellow);
Write(
"Please Enter full path or Drag the folder containing the folders, including comic image files.\n>",
ConsoleColor.Yellow);
pathComicsDir = Console.ReadLine();
}
Write("\n\n");
if (_outputDefined)
{
WriteLine("PDF 출력 폴더가 자동 감지되었습니다!", ConsoleColor.DarkGray);
WriteLine("Output Folder Auto-Detected!", ConsoleColor.DarkGray);
WriteLine($"OUT: {pathOutputDir}", ConsoleColor.DarkGray);
}
else
{
WriteLine("출력 폴더(\"Output\")가 감지되지 않았습니다. 직접 설정해 주세요.");
WriteLine("The output folder could not be found. Please Set Manually.");
Write("\n");
WriteLine("생성된 PDF 파일들이 들어갈 폴더의 경로를 입력하거나 이 창으로 드래그하세요. (입력 후 Enter)", ConsoleColor.Yellow);
Write(
"Please Enter full path or Drag the folder in which the PDF files created will be placed.\nEx) E:\\WorkingSpace\\OutPut\n>",
ConsoleColor.Yellow);
pathOutputDir = Console.ReadLine();
}
Write("\n");
WriteLine("작업 중 이 창으로 로그를 출력할 때, 작품의 이름(폴더명)을 숨길까요? ( Y = 숨긴다, N = 숨기지 않는다 ) (입력 후 Enter)",
ConsoleColor.Yellow);
Write(
"When printing the log in progress, should this program hide the title of the cartoon? ( y = hide title, n = show title(default) )\n(Y/N) : ",
ConsoleColor.Yellow);
ConsoleKeyInfo readKey = Console.ReadKey();
hideTitle = readKey.Key == ConsoleKey.Y;
}
#endregion
#region Argument Checking
if (pathComicsDir == null || pathOutputDir == null)
{
Write("Params Error!\nInput and output folders must be defined!", ConsoleColor.Red);
return -1;
}
bool
pathComicsDirExists = Directory.Exists(pathComicsDir),
_pathOutputDirExists = Directory.Exists(pathOutputDir);
if (!(pathComicsDirExists && _pathOutputDirExists)) // Input folder or Output Folder not exists
{
Console.Beep();
WriteLine("ERROR: 작품 폴더들이 들어있는 폴더 혹은 출력 폴더가 존재하지 않습니다!", ConsoleColor.Red);
WriteLine("다른 경로를 입력하거나 폴더를 생성한 후 다시 시도해 주세요.", ConsoleColor.Red);
WriteLine("ERROR: Path not exists!", ConsoleColor.Red);
WriteLine($"Input Folder {pathComicsDir} ... {pathComicsDirExists}",
pathComicsDirExists ? ConsoleColor.Green : ConsoleColor.Red);
WriteLine($"Output Folder {pathOutputDir} ... {_pathOutputDirExists}",
_pathOutputDirExists ? ConsoleColor.Green : ConsoleColor.Red);
Environment.Exit(0);
return 0;
}
#endregion
WriteLine("\n작품 가져오는 중...", ConsoleColor.Gray);
WriteLine("Finding Comics...\n", ConsoleColor.Gray);
string[] comicFolders = Directory.GetDirectories(pathComicsDir); // Comics
if (comicFolders.Length <= 0)
{
Console.Beep();
WriteLine("ERROR: 입력 폴더 내에 작품이 발견되지 않았습니다.", ConsoleColor.Red);
Console.ReadKey();
return 0;
}
string[] failureList = new string[comicFolders.Length];
int failureCount = 0;
Array.Sort(comicFolders, new FileNameComparer());
int totalComicsCount = comicFolders.Length; // Comics Count
int totalImagesCount = 0;
for (int i = 0; i < totalComicsCount; i++)
{
string _comicFolder = comicFolders[i];
string _comicName = hideTitle ? $"Comic {i + 1:D4}" : $"{Path.GetFileName(_comicFolder)}";
int _comicImageCount = Directory.GetFiles(_comicFolder).Length;
totalImagesCount += _comicImageCount; // Images Count
Write($"[{i + 1:D4}/{totalComicsCount:D4}] ", ConsoleColor.DarkCyan);
Write($"{_comicName} ");
Write("...", ConsoleColor.DarkGray);
WriteLine($"{_comicImageCount,4} Images");
}
if (!dontAskAgain)
{
Write("\n");
WriteLine($"Output Path: {pathOutputDir}\n\tex) {pathOutputDir}\\WebToon1.pdf", ConsoleColor.Cyan);
Write("\n");
WriteLine(
$"{totalComicsCount} 개의 작품들을 (이미지 {totalImagesCount}개) {totalComicsCount}개의 PDF 파일로 변환하여 위의 경로에 생성할까요?",
ConsoleColor.Yellow);
Write("\n");
WriteLine(" - y가 입력될 시 위의 모든 작업을 시작합니다! 창을 닫지 말고 켠 채로 유지해주세요!", ConsoleColor.Gray);
WriteLine(" - 작업을 중지하고 싶으시면 창을 닫거나 Ctrl+C를 입력해 주세요!", ConsoleColor.Gray);
WriteLine(" - 이후 폴더 이름을 변경하실 경우 해당 작품이 스킵될 수 있습니다!", ConsoleColor.Gray);
WriteLine(" - 만약 위의 작품들 중 이름이 너무 길거나 (70+) 알 수 없는 문자가 포함되었을 경우 수정 후 다시 실행해 주세요!", ConsoleColor.Gray);
WriteLine(" - PNG 파일로 이루어진 작품의 경우 시간이 오래 걸릴 수 있습니다!", ConsoleColor.Gray);
WriteLine(" - 작업 진척도를 올바르게 확인하시려면 현재 콘솔 창을 충분히 넓게 늘려주세요!", ConsoleColor.Gray);
Write("\n");
WriteLine(
$"Convert {totalComicsCount} cartoon image folders ({totalImagesCount} images) in a into PDF files and create them in this folder?",
ConsoleColor.Yellow);
Write($"(Y/N) : ", ConsoleColor.Yellow);
ConsoleKey key = Console.ReadKey().Key;
if (key != ConsoleKey.Y)
{
WriteLine("\nTerminated!", ConsoleColor.Green);
WriteLine("사용자에 의해 종료됨!", ConsoleColor.Green);
WriteLine("\nPress any ket to exit", ConsoleColor.Green);
Console.ReadKey();
return 0;
}
}
Write("\n작업을 시작합니다!\n", ConsoleColor.Yellow);
Console.Clear();
Console.CursorVisible = false;
int __v = 0;
int totalImagesIndex = 1; // Total Image Index
for (int comicProcessingIndex = 1; comicProcessingIndex <= totalComicsCount; comicProcessingIndex++)
{
string
comicPath =
comicFolders
[comicProcessingIndex - 1], // Current Processing Comic Folder's Full Path "C:\Comics\WebToon1"
_comicRealName =
Path.GetFileName(comicPath), // Current Processing Comic Folder's Real Folder Name "WebToon1"
_comicNumericalName =
$"COMIC_{comicProcessingIndex:D4}", // Current Processing Comic Folder's Numerical Name "COMIC_0001"
comicName =
hideTitle
? _comicNumericalName
: _comicRealName, // Current Processing Comic's Name for Display "WebToon1" or "COMIC_0001"
pdfFullPath = Path.Combine(pathOutputDir, _comicRealName + ".pdf");
if (!(Directory.Exists(comicPath) && Directory.Exists(pathOutputDir)))
{
Console.Beep();
WriteLine($"Folder {comicPath} or {pathOutputDir} not exists!", ConsoleColor.Red);
WriteLine($"작품들 폴더 {comicPath} 혹은 출력 폴더 {pathOutputDir}가 존재하지 않습니다!", ConsoleColor.Red);
WriteLine("Skipping...", ConsoleColor.Yellow);
WriteLine("해당 작품 건너뛰는 중 ...", ConsoleColor.Yellow);
failureList[failureCount++] = comicName;
continue;
}
float comicProcess = 100f * comicProcessingIndex / totalComicsCount;
string[] images = Directory.GetFiles(comicPath);
Array.Sort(images, new FileNameComparer());
int imagesCount = images.Length;
PdfDocument pdf = new PdfDocument();
WriteLine(String.Format(
"Processing Comic [{0,-4}/{1,-4}] : {2} : {3} Images",
comicProcessingIndex.ToString("D4"), totalComicsCount.ToString("D4"),
comicName,
imagesCount
), ConsoleColor.DarkGray);
string lastStatus = "";
for (int pageIndex = 0; pageIndex < imagesCount; pageIndex += 1, totalImagesIndex++)
{
int page = pageIndex + 1;
string imagePath = images[pageIndex];
string imageName = Path.GetFileName(imagePath);
string imageExtension = Path.GetExtension(imagePath).ToUpper();
switch (imageExtension)
{
case ".PNG":
case ".JPG":
case ".JPEG":
case ".BMP":
case ".GIFF":
case ".TIFF":
break;
default:
Console.Beep();
failureList[failureCount++] =
$"\n{comicProcessingIndex}번째 작품 {comicName}의 {page}번째 파일 ({imageExtension})";
Write("\n");
WriteLine(
$"\n{comicProcessingIndex}번째 작품 {comicName}의 {page}번째 파일{(hideTitle ? string.Empty : $"({imagePath})")}을 처리할 수 없습니다!",
ConsoleColor.Red);
WriteLine($"Cannot Process {page}th file of {comicName} ({comicProcessingIndex}th comic)!",
ConsoleColor.Red);
WriteLine($"파일 확장자 {imageExtension}는 지원되지 않습니다.", ConsoleColor.Red);
Write("\n");
WriteLine("오류 페이지 건너뛰는 중...", ConsoleColor.Yellow);
Write("\n");
continue;
break;
}
PdfPage pdfPage = pdf.AddPage();
XImage ximage = XImage.FromFile(imagePath);
XGraphics gfx = XGraphics.FromPdfPage(pdfPage);
double
height = ximage.Size.Height,
width = ximage.Size.Width;
pdfPage.Height = height;
pdfPage.Width = width;
float
currentComicPageProcess = 100f * page / imagesCount,
totalImageProcess = 100f * totalImagesIndex / totalImagesCount;
char ving = vingle();
string status = String.Format(
" {13} >>> {9} ({10}x{11}) => Page {12} ... COMIC {3}% [{4}/{5}] : PAGE {6}% [{7}/{8}] / TOTAL {0}% [{1}/{2}] ",
totalImageProcess, totalImagesIndex, totalImagesCount,
comicProcess, comicProcessingIndex, totalComicsCount,
currentComicPageProcess, page, imagesCount,
imageName, width, height, page,
ving
);
lastStatus = status;
Console.Write("\r" + status);
Console.Title =
$"{ving} Merginto : Processing - [{totalImagesIndex}/{totalImagesCount}] : {totalImageProcess:F2}%";
gfx.DrawImage(ximage, 0, 0);
}
pdf.Save(pdfFullPath);
WriteLine("\r" + lastStatus + " ... Fin! \t", ConsoleColor.Green);
char vingle()
{
char[] _arr = new[] { '↗', '→', '↘', '↓', '↙', '←', '↖', '↑' };
__v++;
if (__v == 8) __v = 0;
return _arr[__v];
}
}
Console.Beep();
Write("\n");
WriteLine(string.Format(
"처리한 작업: 작품 {0}개, 이미지 {1}개\n" +
"Task Finished: {0} Comics, {1} Images\n",
totalComicsCount, totalImagesIndex
), ConsoleColor.Yellow);
WriteLine("모든 작업이 완료되었습니다!", ConsoleColor.Cyan);
WriteLine("Totally Finished!!!", ConsoleColor.Cyan);
if (failureList.Length > 0)
{
WriteLine("실패 목록:\n");
foreach (var fail in failureList)
{
WriteLine($"F: {fail}");
}
}
else
{
WriteLine("실패한 작업이 없습니다.");
WriteLine("No fails!");
}
Console.ReadKey();
return 0;
}
private static void WriteLine(object o, ConsoleColor color = ConsoleColor.White)
{
Console.ForegroundColor = color;
Console.WriteLine(o);
Console.ForegroundColor = ConsoleColor.White;
}
private static void Write(object o, ConsoleColor color = ConsoleColor.White)
{
Console.ForegroundColor = color;
Console.Write(o);
Console.ForegroundColor = ConsoleColor.White;
}
private static void HelpPrint()
{
Write("\n\nExample: ", ConsoleColor.Yellow);
WriteLine("D:\\ITP.exe /i D:\\Comics /o D:\\CreatedPdfs /hidetitle");
Write("\nAvailable Switches\n", ConsoleColor.Yellow);
WriteLine("\n\t/i <folderpath>:", ConsoleColor.Cyan);
WriteLine("\t\tSpecifies full path of the folder containing the folders, including animated image files.");
WriteLine("\t\tAliases: /i /in /input -i -in -input");
WriteLine("\t\tUsage: /i <full path of comics folder>");
WriteLine("\t\tExample: /i C:\\Comics");
WriteLine("\n\t/o <folderpath>:", ConsoleColor.Cyan);
WriteLine("\t\tSpecifies the folder in which the PDF files created will be placed.");
WriteLine("\t\tAliases: /i /in /input -i -in -input");
WriteLine("\t\tUsage: /i <full path of output folder>");
WriteLine("\t\tExample: /i C:\\PDFs");
WriteLine("\n\t/? :", ConsoleColor.Cyan);
WriteLine("\t\tShows this message");
WriteLine("\t\tAliases: /? /help -help");
WriteLine("\n\t/h :", ConsoleColor.Cyan);
WriteLine("\t\tReplace the name of comics with Numeric Name");
WriteLine("\t\tAliases: /h /hidetitle -h -hidetitle");
WriteLine("\n\t/y :", ConsoleColor.Cyan);
WriteLine("\t\tDo not ask any question and try process directly.");
WriteLine("\t\tAliases: /y /yes -Y -YES");
}
}
public class FileNameComparer : IComparer<string>
{
public FileNameComparer()
{
}
public int Compare(object x, object y)
{
if ((x is string) && (y is string))
{
return StringLogicalComparer.Compare((string)x, (string)y);
}
return -1;
}
public int Compare(string x, string y)
{
return StringLogicalComparer.Compare(x, y);
}
private class StringLogicalComparer
{
public static int Compare(string s1, string s2)
{
if ((s1 == null) && (s2 == null)) return 0;
else if (s1 == null) return -1;
else if (s2 == null) return 1;
if ((s1.Equals(string.Empty) && (s2.Equals(string.Empty)))) return 0;
else if (s1.Equals(string.Empty)) return -1;
else if (s2.Equals(string.Empty)) return -1;
bool sp1 = Char.IsLetterOrDigit(s1, 0);
bool sp2 = Char.IsLetterOrDigit(s2, 0);
if (sp1 && !sp2) return 1;
if (!sp1 && sp2) return -1;
int i1 = 0, i2 = 0;
int r = 0;
while (true)
{
bool c1 = Char.IsDigit(s1, i1);
bool c2 = Char.IsDigit(s2, i2);
if (!c1 && !c2)
{
bool letter1 = Char.IsLetter(s1, i1);
bool letter2 = Char.IsLetter(s2, i2);
if ((letter1 && letter2) || (!letter1 && !letter2))
{
if (letter1 && letter2)
{
r = Char.ToLower(s1[i1]).CompareTo(Char.ToLower(s2[i2]));
}
else
{
r = s1[i1].CompareTo(s2[i2]);
}
if (r != 0) return r;
}
else if (!letter1 && letter2) return -1;
else if (letter1 && !letter2) return 1;
}
else if (c1 && c2)
{
r = CompareNum(s1, ref i1, s2, ref i2);
if (r != 0) return r;
}
else if (c1)
{
return -1;
}
else if (c2)
{
return 1;
}
i1++;
i2++;
if ((i1 >= s1.Length) && (i2 >= s2.Length))
{
return 0;
}
else if (i1 >= s1.Length)
{
return -1;
}
else if (i2 >= s2.Length)
{
return -1;
}
}
}
private static int CompareNum(string s1, ref int i1, string s2, ref int i2)
{
int nzStart1 = i1, nzStart2 = i2; // nz = non zero
int end1 = i1, end2 = i2;
ScanNumEnd(s1, i1, ref end1, ref nzStart1);
ScanNumEnd(s2, i2, ref end2, ref nzStart2);
int start1 = i1;
i1 = end1 - 1;
int start2 = i2;
i2 = end2 - 1;
int nzLength1 = end1 - nzStart1;
int nzLength2 = end2 - nzStart2;
if (nzLength1 < nzLength2) return -1;
else if (nzLength1 > nzLength2) return 1;
for (int j1 = nzStart1, j2 = nzStart2; j1 <= i1; j1++, j2++)
{
int r = s1[j1].CompareTo(s2[j2]);
if (r != 0) return r;
}
// the nz parts are equal
int length1 = end1 - start1;
int length2 = end2 - start2;
if (length1 == length2) return 0;
if (length1 > length2) return -1;
return 1;
}
private static void ScanNumEnd(string s, int start, ref int end, ref int nzStart)
{
nzStart = start;
end = start;
bool countZeros = true;
while (Char.IsDigit(s, end))
{
if (countZeros && s[end].Equals('0'))
{
nzStart++;
}
else countZeros = false;
end++;
if (end >= s.Length) break;
}
}
}
}
}