-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainForm.cs
More file actions
839 lines (770 loc) · 38.3 KB
/
MainForm.cs
File metadata and controls
839 lines (770 loc) · 38.3 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
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
using RimLangKit.Checks;
using RimLangKit.Modules.AutoTranslation;
using RimLangKit.Modules.GameLocalization;
using RimLangKit.Processors;
using RimLangKit.Properties;
using RimLangKit.Services;
using RimLangKit.Utilities;
using System.Diagnostics;
using System.Reflection;
namespace RimLangKit
{
public partial class MainForm : Form
{
private static string DirectoryPath = string.Empty;
private static string GamePath = string.Empty;
private static string AdditionalFolder = string.Empty;
private static string SelectedDBPath = string.Empty;
private static string TranslationFolder = string.Empty;
private static string AutoTranslateModFolder = string.Empty;
private readonly Color goodColor = Color.FromArgb(0, 130, 0);
private readonly Color badColor = Color.FromArgb(130, 0, 0);
public MainForm()
{
InitializeComponent();
FolderTextBox.Text = DirectoryPath;
// Обновление настроек при первом запуске
if (Settings.Default.firstLaunch)
{
Settings.Default.Upgrade();
Settings.Default.firstLaunch = false;
Settings.Default.Save();
SendToInfoTextBox("Первый запуск. Обновление настроек завершено");
}
// Инициализация меню "О программе"
ToolStripMenuItemVersion.Text += Assembly.GetEntryAssembly()?.GetName().Version?.ToString()[..^2];
// Инициализация меню "Автор"
ToolStripMenuItemCreator.Text += " OliveWizard";
// Автоматическая проверка обновлений
if (Settings.Default.isAutoUpdateActive)
{
ToolStripMenuItemAutoUpdateCheck.Checked = true;
var oldCheckDate = Settings.Default.lastCheckDate;
var newCheckDate = DateTime.Now;
if (oldCheckDate.Month != newCheckDate.Month)
{
bool result = CheckVersion();
if (result)
{
Settings.Default.lastCheckDate = newCheckDate;
Settings.Default.Save();
}
}
}
// Восстановление последней вкладки
MainTabs.SelectTab(Settings.Default.lastTab);
// Установка размера вкладок
MainTabs.SizeMode = TabSizeMode.Fixed;
MainTabs.ItemSize = new Size((MainTabs.Width / MainTabs.TabPages.Count) - 2, MainTabs.ItemSize.Height);
// Восстановление пути к папке игры
GamePath = Settings.Default.savedDirectory;
if (!Directory.Exists(GamePath))
GamePath = string.Empty;
FolderTextBox2.Text = GamePath;
LanguageInput.Text = Settings.Default.language;
RepoInput.Text = Settings.Default.repo;
}
// Выбор папки
private void FolderButton_Click(object sender, EventArgs e)
{
using FolderBrowserDialog ofd = new();
DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
{
DirectoryPath = ofd.SelectedPath;
FolderTextBox.Text = DirectoryPath;
}
}
// Обработка изменения адреса папки
private void FolderTextBox_TextChanged(object sender, EventArgs e)
{
DirectoryPath = FolderTextBox.Text;
// Кнопки доступны только тогда, когда директория существует
if (Directory.Exists(FolderTextBox.Text) && !FolderTextBox.Text.Contains("294100"))
{
LabelCheck.ForeColor = goodColor;
LabelCheck.Text = "ОК";
CommentInserterButton.Enabled = true;
FileRenamerButton.Enabled = true;
NamesTranslatorButton.Enabled = true;
CaseCreatorButton.Enabled = true;
EncodingFixerButton.Enabled = true;
TagCollectorButton.Enabled = true;
FileFixerButton.Enabled = true;
FindChangesButton.Enabled = true;
PreTranslatorButton.Enabled = true;
AdditionalFolderButton.Enabled = true;
}
else
{
LabelCheck.ForeColor = badColor;
LabelCheck.Text = "Ошибка: некорректная папка";
CommentInserterButton.Enabled = false;
FileRenamerButton.Enabled = false;
NamesTranslatorButton.Enabled = false;
CaseCreatorButton.Enabled = false;
EncodingFixerButton.Enabled = false;
TagCollectorButton.Enabled = false;
FileFixerButton.Enabled = false;
FindChangesButton.Enabled = false;
PreTranslatorButton.Enabled = false;
AdditionalFolderButton.Enabled = false;
}
}
#region прочие объекты
private void AdditionalFolderButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog ofd = new();
DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
{
AdditionalFolder = ofd.SelectedPath;
}
AdditionalFolderButton.BackColor = goodColor;
}
// Выбор текстового поля в зависимости от выбранной вкладки
private void SendToInfoTextBox(string text)
{
if (Settings.Default.lastTab == 0)
{
if (InfoTextBox.Text == string.Empty)
InfoTextBox.AppendText($"{text}");
else
InfoTextBox.AppendText($"{Environment.NewLine}{text}");
}
else
{
if (InfoTextBox2.Text == string.Empty)
InfoTextBox2.AppendText($"{text}");
else
InfoTextBox2.AppendText($"{Environment.NewLine}{text}");
}
}
private void SendToInfoTextBox(string text, int id)
{
if (id == 0)
{
if (InfoTextBox.Text == string.Empty)
InfoTextBox.AppendText($"{text}");
else
InfoTextBox.AppendText($"{Environment.NewLine}{text}");
}
else
{
if (InfoTextBox2.Text == string.Empty)
InfoTextBox2.AppendText($"{text}");
else
InfoTextBox2.AppendText($"{Environment.NewLine}{text}");
}
}
private void MainTabs_IndexChange(object sender, EventArgs e)
{
Settings.Default.lastTab = MainTabs.SelectedIndex;
Settings.Default.Save();
}
#endregion
#region кнопки функций
// Обработчик нажатий кнопок
private void ActionHandler(string name, string mask, string code)
{
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}Запуск: {name}");
// Получение списка всех файлов в заданой папке и во всех вложенных подпапках за счёт SearchOption
string[] allFiles = Directory.GetFiles(DirectoryPath, mask, SearchOption.AllDirectories);
int count = 0;
int errCount = 0;
(bool, string) result = (false, string.Empty);
string message;
foreach (string currentFile in allFiles)
{
switch (code)
{
case "FileRenamer":
result = FileRenamer.FileRenamerActivity(currentFile);
break;
case "NamesTranslator":
result = NamesTranslator.NamesTranslatorActivity(currentFile);
break;
case "TagCollector":
result = TagCollector.TagCollectorActivity(currentFile);
break;
case "FileFixer":
result = FileFixer.FileFixerActivity(currentFile);
break;
case "EncodingFixer":
result = EncodingFixer.EncodingFixerActivity(currentFile);
break;
case "CommentInserter":
result = CommentInserter.InsertComments(currentFile);
break;
default:
break;
}
if (result.Item1)
count++;
else
{
errCount++;
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}{result.Item2} ({currentFile})");
}
}
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}Завершено. Обработано файлов - {count}");
if (errCount != 0)
{
InfoTextBox.AppendText($"{Environment.NewLine}Пропущено файлов - {errCount}");
}
// Постобработка
switch (code)
{
case "TagCollector":
message = TagCollector.TagWriterActivity();
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}{message}");
message = TagCollector.DefsClassGeneratorActivity();
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}{message}");
TagCollector.DataCleanerActivity();
break;
case "FileFixer":
message = FileFixer.BrokenFilesWriterActivity();
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}{message}");
break;
default:
break;
}
}
// Работа без обработчика
private void FindChangesButton_Click(object sender, EventArgs e)
{
if (AdditionalFolder == string.Empty)
{
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}Ошибка. Не выбран источник данных");
return;
}
InfoTextBox.AppendText($"{Environment.NewLine}Файлы перевода - {DirectoryPath}.{Environment.NewLine}Исходные файлы мода - {AdditionalFolder}");
InfoTextBox.AppendText($"{TimeSetter.PlaceTime()}Поиск изменений в переводе");
string[] allFiles = Directory.GetFiles(DirectoryPath, "*.xml", SearchOption.AllDirectories);
int count = 0;
int errCount = 0;
(bool, string) result;
foreach (string tempFile in allFiles)
{
result = ChangesFinder.GetTranslationData(tempFile);
if (result.Item1)
{
count++;
}
else
{
errCount++;
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}{result.Item2} ({tempFile})");
}
}
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}Собраны данные перевода. Обработано файлов - {count}.{Environment.NewLine}Пропущено файлов - {errCount}.");
allFiles = Directory.GetFiles(AdditionalFolder, "*.xml", SearchOption.AllDirectories);
count = 0;
errCount = 0;
foreach (string tempFile in allFiles)
{
result = ChangesFinder.GetModData(tempFile);
if (result.Item1)
{
count++;
}
else
{
errCount++;
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}{result.Item2} ({tempFile})");
}
}
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}Собраны исходные данные. Обработано файлов - {count}.{Environment.NewLine}Пропущено файлов - {errCount}.");
ChangesFinder.FindChangesInFiles();
string writeResult = ChangesFinder.WriteChanges();
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}{writeResult}");
}
private void CaseCreatorButton_Click(object sender, EventArgs e)
{
InfoTextBox.AppendText($"{TimeSetter.PlaceTime()}Создание вспомогательных файлов");
string[] defTypeList = ["AbilityDef", "BodyDef", "BodyPartDef", "BodyPartGroupDef", "ChemicalDef", "FactionDef", "HediffDef", "MemeDef", "MentalBreakDef", "MentalFitDef", "MentalStateDef", "OrderedTakeGroupDef", "PawnCapacityDef", "PawnKindDef", "ScenarioDef", "SitePartDef", "SkillDef", "StyleCategoryDef", "ThingDef", "ToolCapacityDef", "WorldObjectDef", "XenotypeDef"];
//Получение списка всех файлов в заданой директории и во всех вложенных подпапках за счёт SearchOption
string[] allFiles = Directory.GetFiles(DirectoryPath, "*.xml", SearchOption.AllDirectories);
Dictionary<string, string> words = [];
// Поиск подходящей директории
string directory = Directory.Exists(DirectoryPath + "\\Common") ? DirectoryPath + "\\Common" : DirectoryPath;
int typeCount = 0;
// Проверяется каждый подходящий DefType из списка
foreach (string defType in defTypeList)
{
int count = 0;
foreach (string tempFile in allFiles)
{
// Каждый файл проверяется на соотвествие этому типу. Если не соотвествует, возвращает пустой список
List<string> tempWords = CaseCreator.FindWordsProcessing(tempFile, defType);
foreach (string word in tempWords)
{
bool result = words.TryAdd(word, defType);
if (result) { count++; }
}
}
// Если нашлись слова в данном DefType, то создаются файлы
if (count > 0)
{
int? limit = MorpherService.GetMorpherRequestLimit();
if (!limit.HasValue)
{
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}Ошибка получения лимита слов для {defType}. Проблемы с интернетом?");
continue;
}
else if (limit < words.Count)
{
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}Превышен лимит. Доступно сегодня {limit}, требуется для {defType} - {words.Count}. Стоит убрать уже обработанные папки и попробовать завтра. Или сменить IP.");
continue;
}
else
{
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}Доступно запросов - {limit}");
}
CaseCreator.CreateCase(directory, words, defType);
CaseCreator.CreateGender(directory, words, defType);
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}Обработано {count} объектов типа {defType}");
typeCount++;
}
}
if (typeCount > 0)
{
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}Созданы файлы по адресу {directory}\\Languages\\Russian\\WordInfo");
}
else
{
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}Файлы не созданы");
}
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}Завершено");
}
private void PreTranslatorButton_Click(object sender, EventArgs e)
{
if (AdditionalFolder == string.Empty)
{
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}Ошибка. Не выбран источник данных");
return;
}
InfoTextBox.AppendText($"{Environment.NewLine}Переводимые файлы - {DirectoryPath}.{Environment.NewLine}Исходные файлы для предварительного перевода - {AdditionalFolder}");
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}Сбор данных для перевода");
string[] allFiles = Directory.GetFiles(AdditionalFolder, "*.xml", SearchOption.AllDirectories);
int count = 0;
int errCount = 0;
(bool, string) result = (false, string.Empty);
foreach (string tempFile in allFiles)
{
if (tempFile.StartsWith(DirectoryPath, StringComparison.OrdinalIgnoreCase))
{
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}Включать переводимый мод в исходные файлы - плохая идея.");
return;
}
result = PreTranslator.BuildDatabase(tempFile);
if (result.Item1)
{
count++;
}
else
{
errCount++;
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}{result.Item2} ({tempFile})");
}
}
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}Собрано {result.Item2} пар перевода. Обработано файлов - {count}. Пропущено файлов - {errCount}.");
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}Начат предварительный перевод");
allFiles = Directory.GetFiles(DirectoryPath, "*.xml", SearchOption.AllDirectories);
count = 0;
errCount = 0;
foreach (string tempFile in allFiles)
{
result = PreTranslator.Translation(tempFile);
if (result.Item1)
{
count++;
}
else
{
errCount++;
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}{result.Item2} ({tempFile})");
}
}
InfoTextBox.AppendText($"{Environment.NewLine}{TimeSetter.PlaceTime()}Обработано файлов - {count}. Пропущено файлов - {errCount}.");
}
// Вызов обработчика из кнопок
private void FileRenamerButton_Click(object sender, EventArgs e)
{
ActionHandler("Переименование файлов", "*.xml", "FileRenamer");
}
private void NamesTranslatorButton_Click(object sender, EventArgs e)
{
ActionHandler("Транскрипция имён", "*.txt", "NamesTranslator");
}
private void TagCollectorButton_Click(object sender, EventArgs e)
{
ActionHandler("Сбор статистики тегов", "*.xml", "TagCollector");
}
private void FileFixerButton_Click(object sender, EventArgs e)
{
ActionHandler("Поиск сломанных файлов", "*.xml", "FileFixer");
}
private void EncodingFixerButton_Click(object sender, EventArgs e)
{
ActionHandler("Исправление кодировки", "*.xml", "EncodingFixer");
}
private void CommentInserterButton_Click(object sender, EventArgs e)
{
ActionHandler("Добавление комментариев", "*.xml", "CommentInserter");
}
#endregion
#region LanguageUpdate
// Обновление локализации
private void ButtonLanguageUpdate_Click(object sender, EventArgs e)
{
(bool, string) result;
SendToInfoTextBox("Проверка обновления");
result = LanguageUpdater.TranslationVersionCheckActivity(Settings.Default.sha, Settings.Default.repo);
if (result.Item1 == false)
{
SendToInfoTextBox(result.Item2);
return;
}
SendToInfoTextBox("Найдена новая версия");
var dr = MessageBox.Show($"{result.Item2}.\nОбновить?", "Обновление", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dr != DialogResult.Yes)
{
return;
}
SendToInfoTextBox("Загрузка обновления");
result = LanguageUpdater.LanguageUpdateDownload(Settings.Default.repo);
if (result.Item1 == false)
{
SendToInfoTextBox(result.Item2);
return;
}
SendToInfoTextBox("Обновление загружено");
SendToInfoTextBox("Установка обновления");
result = LanguageUpdater.LanguageUpdateActivity(Settings.Default.savedDirectory, Settings.Default.language);
if (result.Item1 == false)
{
SendToInfoTextBox(result.Item2);
return;
}
SendToInfoTextBox(result.Item2);
Settings.Default.sha = LanguageUpdater.GetSha();
Settings.Default.Save();
}
// Удаление скачанного перевода
private void ResetButton_Click(object sender, EventArgs e)
{
// Получение списка дополнений
if (Directory.Exists($"{Settings.Default.savedDirectory}\\Data"))
{
string[] modules = Directory.GetDirectories($"{Settings.Default.savedDirectory}\\Data");
if (modules.Length == 0)
{
MessageBox.Show("В указанной папке нет дополнений", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
string modulesList = string.Empty;
List<string> languagePathList = [];
foreach (var module in modules)
{
string moduleName = module[module.LastIndexOf('\\')..];
moduleName = moduleName[1..];
string languagePath = $"{module}\\Languages\\{Settings.Default.language}";
if (Directory.Exists(languagePath))
{
modulesList += $"- {moduleName}: {languagePath}\n";
languagePathList.Add(languagePath);
}
}
if (languagePathList.Count == 0)
{
MessageBox.Show("Перевод модулей не найден", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
var dr = MessageBox.Show($"Вы собираетесь удалить перевод, созданный в этой программе. Другие переводы затронуты не будут.\nБудут удалены следующие папки:\n\n{modulesList}", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dr == DialogResult.Yes)
{
Settings.Default.sha = "00000000";
Settings.Default.Save();
foreach (var path in languagePathList)
{
Directory.Delete(path, true);
}
MessageBox.Show("Удаление завершено", "Удаление", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
else
{
MessageBox.Show("В указанной папке нет перевода", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// Сброс настроек к значеним по умолчанию
private void DefaultButton_Click(object sender, EventArgs e)
{
var dr = MessageBox.Show("Вы действительно хотите вернуть все параметры в этом окне к изначальным?", "Сброс настроек", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dr == DialogResult.Yes)
{
Settings.Default.sha = "00000000";
Settings.Default.repo = "Ludeon/RimWorld-ru";
Settings.Default.language = "Russian (GitHub)";
Settings.Default.savedDirectory = string.Empty;
Settings.Default.Save();
LanguageInput.Text = "Russian (GitHub)";
RepoInput.Text = "Ludeon/RimWorld-ru";
FolderTextBox2.Text = string.Empty;
MessageBox.Show("Параметры сброшены", "Сброс настроек", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void RepoInput_TextChanged(object sender, EventArgs e)
{
Settings.Default.repo = RepoInput.Text;
Settings.Default.Save();
CheckTextBoxes();
}
private void LanguageInput_TextChanged(object sender, EventArgs e)
{
Settings.Default.language = LanguageInput.Text;
Settings.Default.Save();
CheckTextBoxes();
}
// Доступ к обновлению, когда введены данные
private void CheckTextBoxes()
{
if ((FolderButton2.BackColor == goodColor) && (RepoInput.Text != string.Empty) && (LanguageInput.Text != string.Empty))
{
ButtonLanguageUpdate.Enabled = true;
ResetButton.Enabled = true;
}
else
{
ButtonLanguageUpdate.Enabled = false;
ResetButton.Enabled = false;
}
}
// Выбор папки игры
private void FolderButton2_Click(object sender, EventArgs e)
{
FolderBrowserDialog ofd = new();
DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
{
GamePath = ofd.SelectedPath;
FolderTextBox2.Text = GamePath;
}
}
private void FolderTextBox2_TextChanged(object sender, EventArgs e)
{
string tempPath = FolderTextBox2.Text;
FolderButton2.BackColor = badColor;
if (Directory.Exists(tempPath))
{
FolderButton2.BackColor = goodColor;
if (Directory.Exists($"{tempPath}\\Data"))
{
string[] modules = Directory.GetDirectories($"{tempPath}\\Data");
if (modules.Length == 0)
{
SendToInfoTextBox("Нет модулей", 1);
FolderButton2.BackColor = Color.MediumBlue;
}
else
{
SendToInfoTextBox("Найдены модули:", 1);
foreach (var module in modules)
{
string moduleName = module[module.LastIndexOf('\\')..];
moduleName = moduleName[1..];
SendToInfoTextBox(moduleName, 1);
}
GamePath = tempPath;
Settings.Default.savedDirectory = tempPath;
Settings.Default.Save();
}
}
else
{
SendToInfoTextBox("Нет модулей", 1);
FolderButton2.BackColor = Color.MediumBlue;
}
}
CheckTextBoxes();
}
#endregion
#region Верхнее меню
// Переключение состояния автообновления
private void ToolStripMenuItemAutoUpdateCheck_Click(object sender, EventArgs e)
{
// Я уже не помню, почему инвертирую, но именно так работает
ToolStripMenuItemAutoUpdateCheck.Checked = !ToolStripMenuItemAutoUpdateCheck.Checked;
Settings.Default.isAutoUpdateActive = ToolStripMenuItemAutoUpdateCheck.Checked;
Settings.Default.Save();
}
// Ручная проверка обновлений
private void ToolStripMenuItemCheckUpdate_Click(object sender, EventArgs e)
{
CheckVersion();
}
private static bool CheckVersion()
{
var json = GitHubService.GetGithubJson();
if (json is null)
{
MessageBox.Show("Не удалось проверить обновления. Проверьте подключение к интернету.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
var newVersion = json?.TagName?.ToString()[1..];
var oldVersion = Assembly.GetEntryAssembly()?.GetName().Version?.ToString()[..^2];
if (oldVersion == newVersion)
{
MessageBox.Show("Обновление не требуется", "Обновление", MessageBoxButtons.OK, MessageBoxIcon.Information);
return true;
}
else
{
var dr = MessageBox.Show($"Доступно обновление до версии {newVersion}!\nПерейти на страницу загрузки?\n\nВ новой версии:\n{json?.Body}", "Обновление", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dr == DialogResult.Yes)
{
Process.Start(new ProcessStartInfo { FileName = json?.HtmlUrl?.ToString(), UseShellExecute = true });
}
return true;
}
}
// Вывод информации об авторе
private void ToolStripMenuItemCreator_Click(object sender, EventArgs e)
{
MessageBox.Show("Это полностью бесплатная программа от великого OliveWizard для сообщества RimWorld.\n\n", "Автор", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
// Переход на страницу с руководством
private void ToolStripMenuItemGuide_Click(object sender, EventArgs e)
{
Process.Start(new ProcessStartInfo { FileName = @"https://github.com/OneCodeUnit/RimLangKit/blob/master/README.md", UseShellExecute = true });
}
#endregion
#region Загрузка базы данных
// Выбор базы данных для загрузки
private void SelectDatabaseButton_Click(object sender, EventArgs e)
{
FileDialog fileDialog = new OpenFileDialog
{
Filter = "База данных (*.db)|*.db|All files (*.*)|*.*",
};
DialogResult dr = fileDialog.ShowDialog();
if (dr == DialogResult.OK)
{
SelectedDBPath = fileDialog.FileName;
SelectDatabaseTextBox.Text = SelectedDBPath;
}
}
// Обработка изменения пути к базе данных
private void SelectDatabaseTextBox_TextChanged(object sender, EventArgs e)
{
string path = SelectDatabaseTextBox.Text;
SelectedDBPath = path;
if (File.Exists(path) && path.EndsWith(".db", StringComparison.OrdinalIgnoreCase))
{
// Загрузка базы данных (проверка её содержимого)
var result = AutoTranslator.LoadDatabase(SelectedDBPath);
CheckDatabaseLabel.Text = $"Сейчас в базе: {result.Message}";
}
else
{
}
}
#endregion
// Создание новой базы данных
private void CreateDatabaseButton_Click(object sender, EventArgs e)
{
string executableDirectory;
if (SelectedDBPath == string.Empty)
executableDirectory = AppContext.BaseDirectory + "RimLang.db";
else
executableDirectory = SelectedDBPath;
var dr = MessageBox.Show($"База данных будет создана по адресу {executableDirectory}.\nСоздать?", "Создание базы данных", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dr == DialogResult.Yes)
{
AutoTranslator.NewDatabase(executableDirectory);
MessageBox.Show("База данных создана", "Создание базы данных", MessageBoxButtons.OK, MessageBoxIcon.Information);
SelectedDBPath = executableDirectory;
SelectDatabaseTextBox.Text = SelectedDBPath;
// Загрузка базы данных (проверка её содержимого)
var result = AutoTranslator.LoadDatabase(SelectedDBPath);
CheckDatabaseLabel.Text = $"Сейчас в базе: {result.Message}";
}
}
// Добавление файлов из папки в базу данных
private void UpdateDatabaseButton_Click(object sender, EventArgs e)
{
bool rewrite = false;
if (RewriteRadioButtonTrue.Checked)
rewrite = true;
if (RewriteRadioButtonFalse.Checked)
rewrite = false;
string[] allFiles = Directory.GetFiles(TranslationFolder, "*.xml", SearchOption.AllDirectories);
List<XmlError> results = [];
foreach (string currentFile in allFiles)
{
var result = AutoTranslator.CreateDatabase(SelectedDBPath, currentFile, "translated_tags", rewrite);
results.Add(new XmlError(result.IsValid, $"{currentFile}: {result.Message}"));
}
MessageBox.Show("Данные добавлены", "Обновление базы данных", MessageBoxButtons.OK, MessageBoxIcon.Information);
// Загрузка базы данных (проверка её содержимого)
var checkResult = AutoTranslator.LoadDatabase(SelectedDBPath);
CheckDatabaseLabel.Text = $"Сейчас в базе: {checkResult.Message}";
}
// Выбор папки с переводами
private void SelectForUpdateDatabaseButton_Click(object sender, EventArgs e)
{
using FolderBrowserDialog ofd = new();
DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
{
TranslationFolder = ofd.SelectedPath;
UpdateDatabaseTextBox.Text = TranslationFolder;
}
}
// Обработка изменения адреса папки с переводами
private void UpdateDatabaseTextBox_TextChanged(object sender, EventArgs e)
{
string path = UpdateDatabaseTextBox.Text;
if (Directory.Exists(path))
{
TranslationFolder = path;
}
}
// Автоперевод файлов из папки
private void AutoTranslateButton_Click(object sender, EventArgs e)
{
string[] allFiles = Directory.GetFiles(AutoTranslateModFolder, "*.xml", SearchOption.AllDirectories);
List<XmlError> results = [];
foreach (string currentFile in allFiles)
{
var result = AutoTranslator.TranslateFile(SelectedDBPath, currentFile, "translated_tags");
results.Add(new XmlError(result.IsValid, $"{currentFile}: {result.Message}"));
}
MessageBox.Show("Файлы переведы", "Автоперевод", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
// Выбор папки с модом для автоперевода
private void SelectModButton_Click(object sender, EventArgs e)
{
using FolderBrowserDialog ofd = new();
DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
{
AutoTranslateModFolder = ofd.SelectedPath;
SelectModTextBox.Text = AutoTranslateModFolder;
}
}
private void SelectModTextBox_TextChanged(object sender, EventArgs e)
{
string path = SelectModTextBox.Text;
if (Directory.Exists(path))
{
AutoTranslateModFolder = path;
}
}
}
}