Repository navigation
Expand file tree
/
Copy pathMainForm.cs
More file actions
441 lines (385 loc) · 16.3 KB
/
Copy pathMainForm.cs
File metadata and controls
441 lines (385 loc) · 16.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
using System.Text;
namespace TextEditor;
/// <summary>
/// Editor di testo semplice in stile Notepad, con schede multiple.
/// </summary>
public class MainForm : Form
{
private readonly TabControl _tabs = new();
private readonly StatusStrip _status = new();
private readonly ToolStripStatusLabel _posLabel = new();
private readonly ToolStripStatusLabel _infoLabel = new();
private ToolStripMenuItem _wordWrapItem = null!;
private ToolStripMenuItem _lineNumbersItem = null!;
private Font _editorFont = new("Consolas", 11f);
private bool _wordWrap = true;
private bool _showLineNumbers = true;
private int _untitledCounter = 1;
/// <summary>Se impostato, alla comparsa la finestra si cattura in questo PNG e si chiude (solo test).</summary>
public string? ScreenshotPath { get; set; }
public MainForm(string[] args)
{
Text = "Mio Editor";
Width = 1000;
Height = 700;
StartPosition = FormStartPosition.CenterScreen;
KeyPreview = true;
AllowDrop = true;
try { Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); } catch { }
BuildTabs();
BuildStatusBar();
// L'ordine conta: il docking processa i controlli dall'ultimo aggiunto al primo.
// Aggiungendo i tab (Fill) per primi, poi la status bar (Bottom) e il menu (Top)
// per ultimi, le barre superiore/inferiore riservano il loro spazio e i tab
// riempiono il resto SENZA che il menu copra la striscia delle linguette.
Controls.Add(_tabs);
Controls.Add(_status);
BuildMenu(); // aggiunge il MenuStrip per ultimo (Dock = Top)
DragEnter += (s, e) =>
e.Effect = e.Data!.GetDataPresent(DataFormats.FileDrop) ? DragDropEffect_Copy() : DragDropEffects.None;
DragDrop += (s, e) =>
{
if (e.Data!.GetData(DataFormats.FileDrop) is string[] files)
foreach (var f in files) OpenFile(f);
};
FormClosing += (s, e) =>
{
if (!ConfirmCloseAll()) e.Cancel = true;
};
// Apri i file passati da riga di comando, altrimenti una scheda vuota.
var opened = 0;
foreach (var a in args)
if (File.Exists(a)) { OpenFile(a); opened++; }
if (opened == 0) NewTab();
}
private static DragDropEffects DragDropEffect_Copy() => DragDropEffects.Copy;
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
if (ScreenshotPath == null) return;
var t = new System.Windows.Forms.Timer { Interval = 500 };
t.Tick += (s, ev) =>
{
t.Stop();
try
{
using var bmp = new Bitmap(Width, Height);
using (var g = Graphics.FromImage(bmp))
g.CopyFromScreen(Location, Point.Empty, new Size(Width, Height));
bmp.Save(ScreenshotPath, System.Drawing.Imaging.ImageFormat.Png);
}
catch { }
Close();
};
t.Start();
}
// ---------- Costruzione UI ----------
private void BuildMenu()
{
var menu = new MenuStrip();
// File
var file = new ToolStripMenuItem("&File");
file.DropDownItems.Add(Item("&Nuovo", Keys.Control | Keys.N, (s, e) => NewTab()));
file.DropDownItems.Add(Item("&Apri...", Keys.Control | Keys.O, (s, e) => OpenDialog()));
file.DropDownItems.Add(Item("&Salva", Keys.Control | Keys.S, (s, e) => Save(Current)));
file.DropDownItems.Add(Item("Salva con &nome...", Keys.Control | Keys.Shift | Keys.S, (s, e) => SaveAs(Current)));
file.DropDownItems.Add(new ToolStripSeparator());
file.DropDownItems.Add(Item("&Chiudi scheda", Keys.Control | Keys.W, (s, e) => CloseTab(_tabs.SelectedTab)));
file.DropDownItems.Add(Item("&Esci", Keys.Alt | Keys.F4, (s, e) => Close()));
menu.Items.Add(file);
// Modifica
var edit = new ToolStripMenuItem("&Modifica");
edit.DropDownItems.Add(Item("&Annulla", Keys.Control | Keys.Z, (s, e) => Editor?.Undo()));
edit.DropDownItems.Add(Item("&Ripeti", Keys.Control | Keys.Y, (s, e) => Editor?.Redo()));
edit.DropDownItems.Add(new ToolStripSeparator());
edit.DropDownItems.Add(Item("Ta&glia", Keys.Control | Keys.X, (s, e) => Editor?.Cut()));
edit.DropDownItems.Add(Item("&Copia", Keys.Control | Keys.C, (s, e) => Editor?.Copy()));
edit.DropDownItems.Add(Item("&Incolla", Keys.Control | Keys.V, (s, e) => Editor?.Paste()));
edit.DropDownItems.Add(new ToolStripSeparator());
edit.DropDownItems.Add(Item("Seleziona &tutto", Keys.Control | Keys.A, (s, e) => Editor?.SelectAll()));
edit.DropDownItems.Add(new ToolStripSeparator());
edit.DropDownItems.Add(Item("&Trova...", Keys.Control | Keys.F, (s, e) => ShowFindReplace(false)));
edit.DropDownItems.Add(Item("&Sostituisci...", Keys.Control | Keys.H, (s, e) => ShowFindReplace(true)));
edit.DropDownItems.Add(Item("&Vai alla riga...", Keys.Control | Keys.G, (s, e) => GoToLine()));
menu.Items.Add(edit);
// Formato
var format = new ToolStripMenuItem("F&ormato");
_wordWrapItem = new ToolStripMenuItem("&A capo automatico", null, (s, e) => ToggleWordWrap()) { Checked = _wordWrap };
format.DropDownItems.Add(_wordWrapItem);
_lineNumbersItem = new ToolStripMenuItem("&Numeri di riga", null, (s, e) => ToggleLineNumbers()) { Checked = _showLineNumbers };
format.DropDownItems.Add(_lineNumbersItem);
format.DropDownItems.Add(Item("&Carattere...", Keys.None, (s, e) => ChooseFont()));
menu.Items.Add(format);
// ?
var help = new ToolStripMenuItem("&?");
help.DropDownItems.Add(Item("&Informazioni", Keys.None, (s, e) =>
MessageBox.Show("Mio Editor 1.0\nEditor di testo semplice con schede.", "Informazioni",
MessageBoxButtons.OK, MessageBoxIcon.Information)));
menu.Items.Add(help);
MainMenuStrip = menu;
Controls.Add(menu);
}
private static ToolStripMenuItem Item(string text, Keys shortcut, EventHandler handler)
{
var i = new ToolStripMenuItem(text, null, handler);
if (shortcut != Keys.None) i.ShortcutKeys = shortcut;
return i;
}
private void BuildTabs()
{
_tabs.Dock = DockStyle.Fill;
_tabs.DrawMode = TabDrawMode.OwnerDrawFixed;
_tabs.SizeMode = TabSizeMode.Normal;
_tabs.Padding = new Point(18, 4); // spazio extra a destra per la "x"
_tabs.DrawItem += Tabs_DrawItem;
_tabs.MouseDown += Tabs_MouseDown;
_tabs.SelectedIndexChanged += (s, e) => UpdateStatus();
}
private void BuildStatusBar()
{
_posLabel.Text = "Riga 1, Col 1";
_infoLabel.Spring = true;
_infoLabel.TextAlign = ContentAlignment.MiddleRight;
_infoLabel.Text = "UTF-8";
_status.Items.Add(_posLabel);
_status.Items.Add(_infoLabel);
}
// ---------- Gestione documenti ----------
private TabPage? Current => _tabs.SelectedTab;
private RichTextBox? Editor => Current?.Tag is Doc d ? d.Box : null;
private TabPage NewTab(string? path = null, string? content = null)
{
var box = new CodeBox
{
Dock = DockStyle.Fill,
BorderStyle = BorderStyle.None,
Font = _editorFont,
WordWrap = _wordWrap,
AcceptsTab = true,
DetectUrls = false,
HideSelection = false,
MaxLength = 0,
ScrollBars = RichTextBoxScrollBars.Both,
};
if (content != null) box.Text = content;
var gutter = new LineNumberGutter(box) { Font = _editorFont, Visible = _showLineNumbers };
var doc = new Doc { Box = box, Gutter = gutter, Path = path };
var page = new TabPage { Tag = doc, UseVisualStyleBackColor = true };
// Ordine: prima il box (Fill), poi il gutter (Left), così il gutter occupa
// la colonna sinistra e il testo riempie lo spazio restante.
page.Controls.Add(box);
page.Controls.Add(gutter);
box.Modified = false;
box.TextChanged += (s, e) => { doc.Dirty = box.Modified; UpdateTabTitle(page); gutter.Invalidate(); };
box.SelectionChanged += (s, e) => UpdateStatus();
box.MouseUp += (s, e) => UpdateStatus();
box.KeyUp += (s, e) => UpdateStatus();
box.ContentScrolled += (s, e) => gutter.Invalidate();
box.FontChanged += (s, e) => { gutter.Font = box.Font; gutter.Invalidate(); };
page.Text = path == null ? $"Senza nome {_untitledCounter++}" : Path.GetFileName(path);
_tabs.TabPages.Add(page);
_tabs.SelectedTab = page;
box.Select();
UpdateStatus();
return page;
}
private void OpenDialog()
{
using var dlg = new OpenFileDialog
{
Filter = "File di testo (*.txt)|*.txt|Tutti i file (*.*)|*.*",
Multiselect = true,
};
if (dlg.ShowDialog(this) == DialogResult.OK)
foreach (var f in dlg.FileNames) OpenFile(f);
}
private void OpenFile(string path)
{
// Se già aperto, porta in primo piano quella scheda.
foreach (TabPage p in _tabs.TabPages)
if (p.Tag is Doc d && string.Equals(d.Path, path, StringComparison.OrdinalIgnoreCase))
{
_tabs.SelectedTab = p;
return;
}
try
{
var text = File.ReadAllText(path);
NewTab(path, text);
}
catch (Exception ex)
{
MessageBox.Show($"Impossibile aprire il file:\n{ex.Message}", "Errore",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private bool Save(TabPage? page)
{
if (page?.Tag is not Doc doc) return false;
if (doc.Path == null) return SaveAs(page);
return WriteFile(page, doc, doc.Path);
}
private bool SaveAs(TabPage? page)
{
if (page?.Tag is not Doc doc) return false;
using var dlg = new SaveFileDialog
{
Filter = "File di testo (*.txt)|*.txt|Tutti i file (*.*)|*.*",
FileName = doc.Path != null ? Path.GetFileName(doc.Path) : page.Text.Trim('●', ' ') + ".txt",
};
if (dlg.ShowDialog(this) != DialogResult.OK) return false;
return WriteFile(page, doc, dlg.FileName);
}
private bool WriteFile(TabPage page, Doc doc, string path)
{
try
{
File.WriteAllText(path, doc.Box.Text, new UTF8Encoding(false));
doc.Path = path;
doc.Box.Modified = false;
doc.Dirty = false;
page.Text = Path.GetFileName(path);
UpdateTabTitle(page);
UpdateStatus();
return true;
}
catch (Exception ex)
{
MessageBox.Show($"Impossibile salvare il file:\n{ex.Message}", "Errore",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
private void CloseTab(TabPage? page)
{
if (page?.Tag is not Doc doc) return;
if (doc.Dirty && !ConfirmSave(page)) return;
_tabs.TabPages.Remove(page);
page.Dispose();
if (_tabs.TabPages.Count == 0) NewTab();
}
private bool ConfirmSave(TabPage page)
{
_tabs.SelectedTab = page;
var name = page.Text.TrimStart('●', ' ');
var r = MessageBox.Show($"Salvare le modifiche a \"{name}\"?", "Mio Editor",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
return r switch
{
DialogResult.Yes => Save(page),
DialogResult.No => true,
_ => false,
};
}
private bool ConfirmCloseAll()
{
foreach (TabPage p in _tabs.TabPages)
if (p.Tag is Doc { Dirty: true } && !ConfirmSave(p))
return false;
return true;
}
// ---------- Schede: disegno + click sulla "x" ----------
private void Tabs_DrawItem(object? sender, DrawItemEventArgs e)
{
var page = _tabs.TabPages[e.Index];
var rect = _tabs.GetTabRect(e.Index);
var selected = e.Index == _tabs.SelectedIndex;
using (var bg = new SolidBrush(selected ? SystemColors.Window : SystemColors.Control))
e.Graphics.FillRectangle(bg, rect);
// Testo della scheda.
var textRect = new Rectangle(rect.X + 6, rect.Y + 3, rect.Width - 26, rect.Height - 4);
TextRenderer.DrawText(e.Graphics, page.Text, _tabs.Font, textRect,
SystemColors.ControlText, TextFormatFlags.Left | TextFormatFlags.EndEllipsis);
// Pulsante "x".
var x = CloseButtonRect(rect);
TextRenderer.DrawText(e.Graphics, "✕", _tabs.Font, x, SystemColors.GrayText,
TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
}
private static Rectangle CloseButtonRect(Rectangle tab) =>
new(tab.Right - 20, tab.Y + (tab.Height - 16) / 2, 16, 16);
private void Tabs_MouseDown(object? sender, MouseEventArgs e)
{
for (int i = 0; i < _tabs.TabPages.Count; i++)
{
var rect = _tabs.GetTabRect(i);
if (!rect.Contains(e.Location)) continue;
// Click sulla "x" oppure click con rotellina = chiudi.
if (e.Button == MouseButtons.Middle || CloseButtonRect(rect).Contains(e.Location))
CloseTab(_tabs.TabPages[i]);
return;
}
}
private void UpdateTabTitle(TabPage page)
{
if (page.Tag is not Doc doc) return;
var baseName = doc.Path != null ? Path.GetFileName(doc.Path) : page.Text.TrimStart('●', ' ');
var title = doc.Dirty ? "● " + baseName : baseName;
if (page.Text != title) page.Text = title;
Text = (doc.Dirty ? "● " : "") + baseName + " - Mio Editor";
}
// ---------- Funzioni varie ----------
private void ToggleWordWrap()
{
_wordWrap = !_wordWrap;
_wordWrapItem.Checked = _wordWrap;
foreach (TabPage p in _tabs.TabPages)
if (p.Tag is Doc d) d.Box.WordWrap = _wordWrap;
}
private void ToggleLineNumbers()
{
_showLineNumbers = !_showLineNumbers;
_lineNumbersItem.Checked = _showLineNumbers;
foreach (TabPage p in _tabs.TabPages)
if (p.Tag is Doc d) { d.Gutter.Visible = _showLineNumbers; d.Gutter.Invalidate(); }
}
private void ChooseFont()
{
using var dlg = new FontDialog { Font = _editorFont };
if (dlg.ShowDialog(this) != DialogResult.OK) return;
_editorFont = dlg.Font;
foreach (TabPage p in _tabs.TabPages)
if (p.Tag is Doc d) d.Box.Font = _editorFont;
}
private void GoToLine()
{
if (Editor is not { } box) return;
var input = Microsoft.VisualBasic.Interaction.InputBox("Numero di riga:", "Vai alla riga", "1");
if (int.TryParse(input, out var line) && line >= 1)
{
line = Math.Min(line, box.Lines.Length);
var idx = box.GetFirstCharIndexFromLine(line - 1);
if (idx >= 0) { box.SelectionStart = idx; box.SelectionLength = 0; box.ScrollToCaret(); box.Focus(); }
}
}
private FindReplaceForm? _findForm;
/// <summary>Editor della scheda attiva (usato dalla finestra Trova/Sostituisci).</summary>
public RichTextBox? CurrentEditor => Editor;
private void ShowFindReplace(bool replaceMode)
{
if (Editor is null) return;
if (_findForm == null || _findForm.IsDisposed)
{
_findForm = new FindReplaceForm(this);
_findForm.FormClosed += (s, e) => _findForm = null;
}
_findForm.ShowReplace(replaceMode);
if (!_findForm.Visible) _findForm.Show(this);
_findForm.Activate();
_findForm.FocusSearch(Editor.SelectedText);
}
private void UpdateStatus()
{
if (Editor is not { } box) { _posLabel.Text = ""; _infoLabel.Text = ""; return; }
var line = box.GetLineFromCharIndex(box.SelectionStart);
var col = box.SelectionStart - box.GetFirstCharIndexFromLine(line);
_posLabel.Text = $"Riga {line + 1}, Col {col + 1}";
_infoLabel.Text = $"{box.TextLength} caratteri UTF-8";
}
private sealed class Doc
{
public required RichTextBox Box;
public required LineNumberGutter Gutter;
public string? Path;
public bool Dirty;
}
}