-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForm1.cs
More file actions
593 lines (492 loc) · 16.6 KB
/
Copy pathForm1.cs
File metadata and controls
593 lines (492 loc) · 16.6 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
namespace GroupDynamic;
public partial class Form1 : Form
{
private string lastSearchText = string.Empty;
private bool lastMatchCase;
private bool lastWholeWord;
private bool lastUseRegex;
private int untitledDocumentCount;
private AppSettings appSettings = new();
public Form1()
{
InitializeComponent();
appSettings = AppSettingsService.Load();
ConfigureForm();
RestoreWindowSettings();
CreateEmptyTab();
}
private void ConfigureForm()
{
saveFileDialog.Filter = FileDialogFilters.Save;
openFileDialog.Filter = FileDialogFilters.Open;
if (!string.IsNullOrWhiteSpace(appSettings.LastDirectory) && Directory.Exists(appSettings.LastDirectory))
{
openFileDialog.InitialDirectory = appSettings.LastDirectory;
saveFileDialog.InitialDirectory = appSettings.LastDirectory;
}
Text = "StudentPad";
ApplyTheme(appSettings.Theme);
UpdateStatus("Приложение готово к работе.");
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (!ConfirmCloseAllDocuments())
{
e.Cancel = true;
return;
}
SaveWindowSettings();
AppSettingsService.Save(appSettings);
base.OnFormClosing(e);
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
CreateEmptyTab();
UpdateStatus("Создан новый файл.");
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenDocument();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveDocument(false);
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveDocument(true);
}
private void closeTabToolStripMenuItem_Click(object sender, EventArgs e)
{
CloseActiveTab();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private void openButton_Click(object sender, EventArgs e)
{
OpenDocument();
}
private void saveButton_Click(object sender, EventArgs e)
{
SaveDocument(false);
}
private void findNextButton_Click(object sender, EventArgs e)
{
FindAndSelect(true);
}
private void findFromStartButton_Click(object sender, EventArgs e)
{
FindAndSelect(false);
}
private void clearSelectionButton_Click(object sender, EventArgs e)
{
RichTextBox? editor = GetActiveEditor();
if (editor is null)
{
return;
}
editor.SelectionLength = 0;
editor.Focus();
UpdateStatus("Выделение очищено.");
}
private void searchTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
FindAndSelect(true);
e.Handled = true;
e.SuppressKeyPress = true;
}
}
private void documentTabControl_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateWindowTitle();
UpdateEditorInfo();
}
private void lightThemeToolStripMenuItem_Click(object sender, EventArgs e)
{
ApplyTheme(AppTheme.Light);
}
private void darkThemeToolStripMenuItem_Click(object sender, EventArgs e)
{
ApplyTheme(AppTheme.Dark);
}
private void systemThemeToolStripMenuItem_Click(object sender, EventArgs e)
{
ApplyTheme(AppTheme.System);
}
private void OpenDocument()
{
if (openFileDialog.ShowDialog() != DialogResult.OK)
{
return;
}
string selectedPath = openFileDialog.FileName;
string extension = Path.GetExtension(selectedPath).ToLowerInvariant();
try
{
LoadedDocument document = extension == ".rtf"
? new LoadedDocument(string.Empty, false)
: DocumentLoader.Load(selectedPath);
TabPage tab = CreateDocumentTab(Path.GetFileName(selectedPath));
DocumentTabState tabState = GetTabState(tab);
tabState.IsLoading = true;
try
{
if (extension == ".rtf")
{
tabState.Editor.LoadFile(selectedPath, RichTextBoxStreamType.RichText);
tabState.IsPdfDocument = false;
}
else
{
tabState.Editor.Text = document.Text;
tabState.IsPdfDocument = document.IsPdf;
}
}
finally
{
tabState.IsLoading = false;
}
tabState.FilePath = selectedPath;
tabState.DisplayName = Path.GetFileName(selectedPath);
tabState.Editor.SelectionStart = 0;
tabState.Editor.SelectionLength = 0;
SetTabDirty(tab, false);
documentTabControl.TabPages.Add(tab);
documentTabControl.SelectedTab = tab;
RememberDirectory(selectedPath);
UpdateWindowTitle();
UpdateStatus($"Файл открыт: {selectedPath}");
}
catch (Exception ex)
{
MessageBox.Show($"Не удалось открыть файл.\n{ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
UpdateStatus("Ошибка открытия файла.");
}
}
private bool SaveDocument(bool saveAs)
{
TabPage? tab = GetActiveDocumentTab();
return tab is not null && SaveDocument(tab, saveAs);
}
private bool SaveDocument(TabPage tab, bool saveAs)
{
DocumentTabState tabState = GetTabState(tab);
string? targetPath = tabState.FilePath;
if (saveAs || string.IsNullOrWhiteSpace(targetPath) || tabState.IsPdfDocument)
{
if (tabState.IsPdfDocument)
{
saveFileDialog.FileName = "converted-from-pdf.txt";
}
else if (!string.IsNullOrWhiteSpace(tabState.FilePath))
{
saveFileDialog.FileName = Path.GetFileName(tabState.FilePath);
}
else
{
saveFileDialog.FileName = GetDefaultSaveFileName(tabState);
}
if (saveFileDialog.ShowDialog() != DialogResult.OK)
{
return false;
}
targetPath = saveFileDialog.FileName;
}
try
{
DocumentSaveService.Save(targetPath, tabState.Editor);
tabState.FilePath = targetPath;
tabState.IsPdfDocument = false;
tabState.DisplayName = Path.GetFileName(targetPath);
SetTabDirty(tab, false);
RememberDirectory(targetPath);
UpdateWindowTitle();
UpdateStatus($"Файл сохранён: {targetPath}");
return true;
}
catch (Exception ex)
{
MessageBox.Show($"Не удалось сохранить файл.\n{ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
UpdateStatus("Ошибка сохранения файла.");
return false;
}
}
private void FindAndSelect(bool searchFromCurrentPosition)
{
RichTextBox? editor = GetActiveEditor();
if (editor is null)
{
return;
}
string searchText = searchTextBox.Text;
SearchOptions options = new(
caseSensitiveCheckBox.Checked,
wholeWordCheckBox.Checked,
regexCheckBox.Checked);
if (string.IsNullOrWhiteSpace(searchText))
{
MessageBox.Show("Введите текст для поиска.", "Поиск", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
string sourceText = editor.Text;
if (string.IsNullOrEmpty(sourceText))
{
UpdateStatus("В документе нет текста для поиска.");
return;
}
int startIndex = 0;
bool optionsChanged = searchText != lastSearchText
|| options.MatchCase != lastMatchCase
|| options.WholeWord != lastWholeWord
|| options.UseRegex != lastUseRegex;
if (searchFromCurrentPosition && !optionsChanged)
{
startIndex = editor.SelectionStart + editor.SelectionLength;
}
SearchResult result = SearchService.Find(sourceText, searchText, startIndex, options);
if (!result.Found && result.ErrorMessage is null && startIndex > 0)
{
result = SearchService.Find(sourceText, searchText, 0, options);
}
lastSearchText = searchText;
lastMatchCase = options.MatchCase;
lastWholeWord = options.WholeWord;
lastUseRegex = options.UseRegex;
if (result.ErrorMessage is not null)
{
MessageBox.Show($"Ошибка в регулярном выражении.\n{result.ErrorMessage}", "Regex", MessageBoxButtons.OK, MessageBoxIcon.Warning);
UpdateStatus("Ошибка в регулярном выражении.");
return;
}
if (!result.Found)
{
UpdateStatus("Ничего не найдено.");
MessageBox.Show("Совпадение не найдено.", "Поиск", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
editor.Focus();
editor.SelectionStart = result.Start;
editor.SelectionLength = result.Length;
editor.ScrollToCaret();
UpdateStatus($"Найдено совпадение на позиции {result.Start + 1}.");
}
private void CreateEmptyTab()
{
string title = untitledDocumentCount == 0
? "Новый файл"
: $"Новый файл {untitledDocumentCount + 1}";
untitledDocumentCount++;
TabPage tab = CreateDocumentTab(title);
documentTabControl.TabPages.Add(tab);
documentTabControl.SelectedTab = tab;
UpdateWindowTitle();
UpdateEditorInfo();
}
private TabPage CreateDocumentTab(string title)
{
TabPage tab = new();
RichTextBox editor = new()
{
Dock = DockStyle.Fill,
Font = new Font("Consolas", 11F, FontStyle.Regular, GraphicsUnit.Point),
BorderStyle = BorderStyle.None
};
editor.TextChanged += Editor_TextChanged;
DocumentTabState state = new(editor)
{
DisplayName = title
};
tab.Tag = state;
tab.Controls.Add(editor);
UpdateTabTitle(tab);
ApplyThemeToControl(editor);
ApplyThemeToTab(tab);
return tab;
}
private void CloseActiveTab()
{
TabPage? tab = GetActiveDocumentTab();
if (tab is null || !ConfirmSaveTab(tab))
{
return;
}
documentTabControl.TabPages.Remove(tab);
tab.Dispose();
if (documentTabControl.TabPages.Count == 0)
{
CreateEmptyTab();
}
UpdateWindowTitle();
UpdateEditorInfo();
UpdateStatus("Вкладка закрыта.");
}
private bool ConfirmCloseAllDocuments()
{
foreach (TabPage tab in documentTabControl.TabPages.Cast<TabPage>().ToList())
{
documentTabControl.SelectedTab = tab;
if (!ConfirmSaveTab(tab))
{
return false;
}
}
return true;
}
private bool ConfirmSaveTab(TabPage tab)
{
DocumentTabState tabState = GetTabState(tab);
if (!tabState.IsDirty)
{
return true;
}
DialogResult result = MessageBox.Show(
$"Сохранить изменения в документе «{tabState.DisplayName}»?",
"Несохранённые изменения",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Warning);
return result switch
{
DialogResult.Yes => SaveDocument(tab, false),
DialogResult.No => true,
_ => false
};
}
private void Editor_TextChanged(object? sender, EventArgs e)
{
if (sender is RichTextBox editor)
{
TabPage? tab = FindTabByEditor(editor);
if (tab is not null)
{
DocumentTabState tabState = GetTabState(tab);
if (!tabState.IsLoading)
{
SetTabDirty(tab, true);
}
}
}
UpdateEditorInfo();
}
private TabPage? GetActiveDocumentTab()
{
return documentTabControl.SelectedTab;
}
private RichTextBox? GetActiveEditor()
{
TabPage? tab = GetActiveDocumentTab();
return tab is null ? null : GetTabState(tab).Editor;
}
private TabPage? FindTabByEditor(RichTextBox editor)
{
foreach (TabPage tab in documentTabControl.TabPages)
{
if (GetTabState(tab).Editor == editor)
{
return tab;
}
}
return null;
}
private void SetTabDirty(TabPage tab, bool isDirty)
{
DocumentTabState tabState = GetTabState(tab);
tabState.IsDirty = isDirty;
UpdateTabTitle(tab);
UpdateWindowTitle();
}
private void UpdateTabTitle(TabPage tab)
{
DocumentTabState tabState = GetTabState(tab);
tab.Text = tabState.IsDirty ? $"{tabState.DisplayName}*" : tabState.DisplayName;
}
private void UpdateWindowTitle()
{
TabPage? tab = GetActiveDocumentTab();
string fileName = tab?.Text ?? "StudentPad";
Text = $"StudentPad - {fileName}";
}
private void UpdateEditorInfo()
{
RichTextBox? editor = GetActiveEditor();
if (editor is null)
{
editorInfoLabel.Text = string.Empty;
return;
}
DocumentStatistics statistics = DocumentStatistics.From(editor.Text);
editorInfoLabel.Text = $"Строк: {statistics.Lines} | Символов: {statistics.Symbols} | Вкладок: {documentTabControl.TabPages.Count}";
}
private void UpdateStatus(string message)
{
statusLabel.Text = message;
UpdateEditorInfo();
}
private string GetDefaultSaveFileName(DocumentTabState tabState)
{
string fileName = tabState.DisplayName;
return Path.HasExtension(fileName) ? fileName : $"{fileName}.txt";
}
private void RememberDirectory(string path)
{
string? directory = Path.GetDirectoryName(path);
if (string.IsNullOrWhiteSpace(directory))
{
return;
}
appSettings.LastDirectory = directory;
openFileDialog.InitialDirectory = directory;
saveFileDialog.InitialDirectory = directory;
}
private void RestoreWindowSettings()
{
if (appSettings.WindowWidth >= MinimumSize.Width && appSettings.WindowHeight >= MinimumSize.Height)
{
Size = new Size(appSettings.WindowWidth, appSettings.WindowHeight);
}
if (appSettings.WindowWidth > 0 && appSettings.WindowHeight > 0)
{
Point savedLocation = new(appSettings.WindowLeft, appSettings.WindowTop);
bool visibleOnScreen = Screen.AllScreens.Any(screen => screen.WorkingArea.Contains(savedLocation));
if (visibleOnScreen)
{
StartPosition = FormStartPosition.Manual;
Location = savedLocation;
}
}
if (appSettings.IsMaximized)
{
WindowState = FormWindowState.Maximized;
}
}
private void SaveWindowSettings()
{
Rectangle bounds = WindowState == FormWindowState.Normal ? Bounds : RestoreBounds;
appSettings.Theme = currentTheme;
appSettings.WindowLeft = bounds.Left;
appSettings.WindowTop = bounds.Top;
appSettings.WindowWidth = bounds.Width;
appSettings.WindowHeight = bounds.Height;
appSettings.IsMaximized = WindowState == FormWindowState.Maximized;
}
private DocumentTabState GetTabState(TabPage tab)
{
return (DocumentTabState)tab.Tag!;
}
}
public class DocumentTabState
{
public DocumentTabState(RichTextBox editor)
{
Editor = editor;
}
public RichTextBox Editor { get; }
public string DisplayName { get; set; } = "Новый файл";
public string? FilePath { get; set; }
public bool IsPdfDocument { get; set; }
public bool IsDirty { get; set; }
public bool IsLoading { get; set; }
}