Repository navigation
Expand file tree
/
Copy pathFrmPython.Extras.cs
More file actions
647 lines (607 loc) · 33.9 KB
/
Copy pathFrmPython.Extras.cs
File metadata and controls
647 lines (607 loc) · 33.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
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Dm42.Editor;
using Range = Dm42.Editor.TextRange;
namespace dm42editor
{
/// <summary>
/// Fenêtre Python → RPN : menu contextuel, effacement de la page, thèmes clair / sombre du code Python,
/// couleurs du listing RPN, envoi vers Free42 / Plus42. Réglages enregistrés dans
/// %LOCALAPPDATA%\dm42editor\python-vue.ini.
/// </summary>
public partial class FrmPython
{
// ==================================================================
// Réglages d'affichage
// ==================================================================
sealed class RpnColors
{
public Color Back, Text, LineNo, Label, Flow, Test, Alpha;
public RpnColors Clone() => (RpnColors)MemberwiseClone();
public static RpnColors Lcd() => new RpnColors
{
Back = Color.FromArgb(198, 205, 176), Text = Color.FromArgb(30, 36, 24), LineNo = Color.FromArgb(115, 123, 98),
Label = Color.FromArgb(140, 47, 12), Flow = Color.FromArgb(154, 82, 0), Test = Color.FromArgb(31, 76, 120), Alpha = Color.FromArgb(85, 107, 20)
};
public static RpnColors Dark() => new RpnColors
{
Back = Color.FromArgb(30, 30, 30), Text = Color.FromArgb(220, 220, 214), LineNo = Color.FromArgb(110, 110, 104),
Label = Color.FromArgb(240, 150, 70), Flow = Color.FromArgb(230, 190, 90), Test = Color.FromArgb(110, 180, 240), Alpha = Color.FromArgb(160, 210, 120)
};
public static RpnColors Paper() => new RpnColors
{
Back = Color.FromArgb(251, 250, 246), Text = Color.FromArgb(31, 30, 27), LineNo = Color.FromArgb(160, 156, 145),
Label = Color.FromArgb(170, 40, 20), Flow = Color.FromArgb(184, 86, 27), Test = Color.FromArgb(45, 94, 158), Alpha = Color.FromArgb(61, 122, 42)
};
public static RpnColors Free42() => new RpnColors
{
Back = Color.FromArgb(232, 236, 222), Text = Color.Black, LineNo = Color.FromArgb(96, 96, 96),
Label = Color.FromArgb(0, 0, 160), Flow = Color.FromArgb(160, 0, 0), Test = Color.FromArgb(0, 110, 0), Alpha = Color.FromArgb(120, 60, 0)
};
public static readonly (string Name, Func<RpnColors> Make)[] Presets =
{
(Lang.T("Écran LCD (défaut)"), Lcd), (Lang.T("Sombre"), Dark), (Lang.T("Papier"), Paper), (Lang.T("Contraste"), Free42)
};
}
bool pyDark;
RpnColors rpnColors = RpnColors.Lcd();
ToolStripMenuItem darkItem;
Color RpnFore => rpnColors.Text;
static string SettingsFile =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "dm42editor", "python-vue.ini");
void LoadViewSettings()
{
try
{
if (!File.Exists(SettingsFile)) return;
var d = File.ReadAllLines(SettingsFile)
.Select(l => l.Split(new[] { '=' }, 2)).Where(p => p.Length == 2)
.ToDictionary(p => p[0].Trim(), p => p[1].Trim());
pyDark = d.TryGetValue("PythonSombre", out var v) && v == "1";
// ancien réglage de l'émulateur : repris par le réglage commun (Paramètres)
if (d.TryGetValue("Free42", out var f) && f.Length > 0 && Emulator.ExePath.Length == 0) Emulator.ExePath = f;
Color C(string key, Color def) => d.TryGetValue(key, out var s) && TryColor(s, out var c) ? c : def;
var r = RpnColors.Lcd();
rpnColors = new RpnColors
{
Back = C("Rpn.Fond", r.Back), Text = C("Rpn.Texte", r.Text), LineNo = C("Rpn.Numeros", r.LineNo),
Label = C("Rpn.Labels", r.Label), Flow = C("Rpn.Sauts", r.Flow), Test = C("Rpn.Tests", r.Test), Alpha = C("Rpn.Textes", r.Alpha)
};
}
catch { /* réglages illisibles : valeurs par défaut */ }
}
void SaveViewSettings()
{
try
{
Directory.CreateDirectory(Path.GetDirectoryName(SettingsFile));
string H(Color c) => $"#{c.R:X2}{c.G:X2}{c.B:X2}";
File.WriteAllLines(SettingsFile, new[]
{
"PythonSombre=" + (pyDark ? "1" : "0"),
"Rpn.Fond=" + H(rpnColors.Back), "Rpn.Texte=" + H(rpnColors.Text), "Rpn.Numeros=" + H(rpnColors.LineNo),
"Rpn.Labels=" + H(rpnColors.Label), "Rpn.Sauts=" + H(rpnColors.Flow), "Rpn.Tests=" + H(rpnColors.Test), "Rpn.Textes=" + H(rpnColors.Alpha)
});
}
catch { /* dossier non accessible : tant pis */ }
}
static bool TryColor(string s, out Color c)
{
c = Color.Empty;
if (s.Length == 7 && s[0] == '#' && int.TryParse(s.Substring(1), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out int v))
{
c = Color.FromArgb(255, Color.FromArgb(v));
return true;
}
return false;
}
/// <summary>Appelé à la fin de la construction de l'interface.</summary>
void InitExtras()
{
LoadViewSettings();
pyBox.ContextMenuStrip = BuildPythonMenu();
rpnBox.ContextMenuStrip = BuildRpnMenu();
messages.ContextMenuStrip = BuildMessagesMenu();
messages.KeyDown += (s, e) =>
{
if (e.Control && e.KeyCode == Keys.C) { CopyMessages(!e.Shift); e.Handled = true; }
};
// clic droit : sélectionne le message visé avant d'ouvrir le menu
messages.MouseDown += (s, e) =>
{
if (e.Button != MouseButtons.Right) return;
int i = messages.IndexFromPoint(e.Location);
if (i >= 0 && i != messages.SelectedIndex) messages.SelectedIndex = i;
};
ApplyPythonTheme();
ApplyRpnColors();
FormClosed += (s, e) => SaveViewSettings();
}
// ==================================================================
// Menus contextuels
// ==================================================================
ContextMenuStrip DarkMenu()
{
var m = new ContextMenuStrip { Renderer = new HpRenderer(), BackColor = Color.FromArgb(44, 44, 41), ForeColor = Ink, ShowImageMargin = false };
return m;
}
static ToolStripMenuItem Item(string text, string keys, EventHandler click)
{
var it = new ToolStripMenuItem(text) { ShortcutKeyDisplayString = keys, ForeColor = Ink };
it.Click += click;
return it;
}
ContextMenuStrip BuildPythonMenu()
{
var m = DarkMenu();
var undo = Item("Annuler", "Ctrl+Z", (s, e) => pyBox.Undo());
var redo = Item("Rétablir", "Ctrl+Y", (s, e) => pyBox.Redo());
var cut = Item("Couper", "Ctrl+X", (s, e) => pyBox.Cut());
var copy = Item("Copier", "Ctrl+C", (s, e) => pyBox.Copy());
var paste = Item("Coller", "Ctrl+V", (s, e) => pyBox.Paste());
var clearSel = Item("Effacer la sélection", "Suppr", (s, e) => pyBox.ClearSelected());
var all = Item("Tout sélectionner", "Ctrl+A", (s, e) => pyBox.SelectAll());
var comment = Item("Commenter / décommenter", "Ctrl+K", (s, e) => ToggleComment());
var clearAll = Item("Effacer toute la page…", null, (s, e) => ClearPage());
m.Items.AddRange(new ToolStripItem[] { undo, redo, new ToolStripSeparator(), cut, copy, paste, clearSel, new ToolStripSeparator(),
all, comment, new ToolStripSeparator(), clearAll });
m.Opening += (s, e) =>
{
bool sel = !pyBox.Selection.IsEmpty;
undo.Enabled = pyBox.UndoEnabled;
redo.Enabled = pyBox.RedoEnabled;
cut.Enabled = copy.Enabled = clearSel.Enabled = sel;
bool clip;
try { clip = Clipboard.ContainsText(); } catch { clip = true; }
paste.Enabled = clip;
};
return m;
}
ContextMenuStrip BuildMessagesMenu()
{
var m = DarkMenu();
var one = Item("Copier le message", "Ctrl+C", (s, e) => CopyMessages(true));
var all = Item("Copier tous les messages", "Ctrl+Maj+C", (s, e) => CopyMessages(false));
m.Items.AddRange(new ToolStripItem[] { one, all });
m.Opening += (s, e) =>
{
one.Enabled = messages.SelectedItem != null;
all.Enabled = messages.Items.Count > 0;
};
return m;
}
/// <summary>Copie le message sélectionné (ou tous) dans le presse-papiers.</summary>
void CopyMessages(bool selectedOnly)
{
var items = selectedOnly
? (messages.SelectedItem != null ? new[] { messages.SelectedItem } : Array.Empty<object>())
: messages.Items.Cast<object>().ToArray();
if (items.Length == 0) { status.Text = Lang.T("Aucun message à copier."); return; }
try
{
Clipboard.SetText(string.Join(Environment.NewLine, items.Select(i => i.ToString())));
status.Text = items.Length == 1 ? Lang.T("Message copié dans le presse-papiers.") : Lang.F("{0} messages copiés dans le presse-papiers.", items.Length);
}
catch (Exception ex) { status.Text = Lang.T("Presse-papiers indisponible : ") + ex.Message; }
}
ContextMenuStrip BuildRpnMenu()
{
var m = DarkMenu();
var copy = Item("Copier", "Ctrl+C", (s, e) => rpnBox.Copy());
m.Items.AddRange(new ToolStripItem[]
{
copy,
Item("Tout sélectionner", "Ctrl+A", (s, e) => rpnBox.SelectAll()),
new ToolStripSeparator(),
Item("Copier tout le listing", null, (s, e) => CopyRpn()),
Item("Envoyer vers l'émulateur", "F7", (s, e) => SendToFree42()),
Item("Envoyer vers la R47 Android (USB)", "Maj+F7", (s, e) => SendToAndroid()),
Item("Générer le fichier .raw…", "F8", (s, e) => SaveRaw()),
Item("Logigramme du listing…", null, (s, e) => ShowFlowchart()),
new ToolStripSeparator(),
Item("Couleurs du listing…", null, (s, e) => EditRpnColors())
});
m.Opening += (s, e) => copy.Enabled = !rpnBox.Selection.IsEmpty;
return m;
}
/// <summary>Menu Fichier : nouveau, ouvrir, enregistrer, exemples, imprimer, quitter.</summary>
ToolStripDropDownButton BuildFileMenu(ToolStrip tools)
{
var file = new ToolStripDropDownButton("Fichier") { ForeColor = Ink, ShowDropDownArrow = false };
var examples = Ico("examples", new ToolStripMenuItem("Exemples DM42") { ForeColor = Ink });
for (int i = 0; i < Py42.Core.Examples.All.Count; i++)
{
int idx = i;
examples.DropDownItems.Add(Item(Py42.Core.Tr.T(Py42.Core.Examples.All[i].Title), null, (s, e) => { if (ConfirmDiscard()) LoadExample(idx); }));
}
examples.DropDown.Renderer = tools.Renderer;
examples.DropDown.BackColor = Color.FromArgb(44, 44, 41);
// exemples C47 / R47 : ils choisissent la cible C47 (récursivité, entiers longs : refusés pour la HP-42S)
var examplesC47 = Ico("examples", new ToolStripMenuItem("Exemples C47 / R47") { ForeColor = Ink });
for (int i = 0; i < Py42.Core.ExamplesC47.All.Count; i++)
{
int idx = i;
examplesC47.DropDownItems.Add(Item(Py42.Core.ExamplesC47.All[i].Title, null, (s, e) => { if (ConfirmDiscard()) LoadC47Example(idx); }));
}
// programmes de la distribution C47 (dossier PROGRAMS du simulateur) réécrits en Python
var programsC47 = new ToolStripMenuItem("Programmes de la distribution C47") { ForeColor = Ink };
for (int i = 0; i < Py42.Core.ExamplesC47.Programs.Count; i++)
{
int idx = i;
programsC47.DropDownItems.Add(Item(Py42.Core.ExamplesC47.Programs[i].Title, null, (s, e) => { if (ConfirmDiscard()) LoadC47Program(idx); }));
}
programsC47.DropDown.Renderer = tools.Renderer;
programsC47.DropDown.BackColor = Color.FromArgb(44, 44, 41);
examplesC47.DropDownItems.Add(new ToolStripSeparator());
examplesC47.DropDownItems.Add(programsC47);
examplesC47.DropDown.Renderer = tools.Renderer;
examplesC47.DropDown.BackColor = Color.FromArgb(44, 44, 41);
file.DropDownItems.AddRange(new ToolStripItem[]
{
Ico("new", Item("Nouveau", "Ctrl+N", (s, e) => { if (ConfirmDiscard()) NewProgram(); })),
Ico("open", Item("Ouvrir…", "Ctrl+O", (s, e) => OpenFileDialog())),
Ico("save", Item("Enregistrer", "Ctrl+S", (s, e) => SavePython(false))),
Ico("save", Item("Enregistrer sous…", "Ctrl+Maj+S", (s, e) => SavePython(true))),
new ToolStripSeparator(),
examples,
examplesC47,
new ToolStripSeparator(),
Ico("print", Item("Imprimer le code Python…", "Ctrl+P", (s, e) => pyBox.Print(PrintTitle()))),
Ico("print", Item("Imprimer le listing RPN…", null, (s, e) => PrintRpn())),
new ToolStripSeparator(),
Ico("quit", Item("Quitter", "Alt+F4", (s, e) => Close()))
});
// le menu déroulant ne reprend pas toujours le rendu de la barre : on le lui donne explicitement
file.DropDown.Renderer = tools.Renderer;
file.DropDown.BackColor = Color.FromArgb(44, 44, 41);
file.DropDown.ForeColor = Ink;
return file;
}
/// <summary>Logigramme du listing RPN ; double-clic sur une forme : ligne Python d'origine.</summary>
void ShowFlowchart()
{
if (last == null) { status.Text = Lang.T("Rien à représenter : corrigez d'abord les erreurs."); return; }
var f = new Flowchart.FrmFlowchart(() => rpnBox.IsDisposed ? "" : rpnBox.Text,
Path.GetFileNameWithoutExtension(PrintTitle()), line =>
{
// ligne du listing → ligne Python qui l'a produite
int i = line - HeaderLines;
if (last == null || i < 0 || i >= last.Code.Count || last.Code[i].Line <= 0 || last.Code[i].Line > pyBox.LinesCount) return;
pyBox.Selection = new Range(pyBox, 0, last.Code[i].Line - 1, 0, last.Code[i].Line - 1);
pyBox.DoSelectionVisible();
Activate();
pyBox.Focus();
});
// suit les nouvelles conversions du listing
EventHandler<Dm42.Editor.TextChangedEventArgs> follow = (s, e) => { if (!f.IsDisposed) f.Reload(); };
rpnBox.TextChangedDelayed += follow;
f.FormClosed += (s, e) => rpnBox.TextChangedDelayed -= follow;
f.Show(this);
}
/// <summary>Icône vectorielle (16 px, traits clairs) sur une entrée des menus sombres de la fenêtre.</summary>
static ToolStripMenuItem Ico(string name, ToolStripMenuItem item)
{
item.Image = ToolbarIcons.Make(name, 16, Ink, Color.FromArgb(44, 44, 41));
item.ImageScaling = ToolStripItemImageScaling.None;
return item;
}
string PrintTitle() => currentFile != null ? Path.GetFileName(currentFile)
: (progName.Text.Trim().Length > 0 ? progName.Text.Trim() : "MAIN") + ".py";
void PrintRpn()
{
if (last == null) { status.Text = Lang.T("Rien à imprimer : corrigez d'abord les erreurs."); return; }
rpnBox.Print(Path.GetFileNameWithoutExtension(PrintTitle()) + Lang.T(" — listing RPN"));
}
/// <summary>
/// Avant de remplacer le code : propose d'enregistrer les modifications.
/// Renvoie false si l'utilisateur annule (ou n'enregistre pas alors qu'il l'a demandé).
/// </summary>
bool ConfirmDiscard()
{
if (!pyBox.IsChanged) return true;
string name = currentFile != null ? Path.GetFileName(currentFile) : Lang.T("ce programme");
var r = MessageBox.Show(this, Lang.F("Enregistrer les modifications de {0} ?", name), "Python → RPN",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (r == DialogResult.Cancel) return false;
if (r == DialogResult.Yes) { SavePython(false); return !pyBox.IsChanged; }
return true;
}
ToolStripDropDownButton BuildViewMenu(ToolStrip tools)
{
var view = new ToolStripDropDownButton("Affichage") { ForeColor = Ink, ShowDropDownArrow = false };
darkItem = new ToolStripMenuItem("Code Python : thème sombre") { CheckOnClick = true, ForeColor = Ink };
darkItem.CheckedChanged += (s, e) =>
{
if (pyDark == darkItem.Checked) return;
pyDark = darkItem.Checked;
ApplyPythonTheme();
SaveViewSettings();
};
view.DropDownItems.Add(darkItem);
view.DropDownItems.Add(new ToolStripSeparator());
view.DropDownItems.Add(new ToolStripMenuItem("Couleurs du listing RPN…", null, (s, e) => EditRpnColors()) { ForeColor = Ink });
var presets = new ToolStripMenuItem("Listing RPN : modèle") { ForeColor = Ink };
foreach (var p in RpnColors.Presets)
{
var make = p.Make;
presets.DropDownItems.Add(new ToolStripMenuItem(p.Name, null, (s, e) => { rpnColors = make(); ApplyRpnColors(); SaveViewSettings(); }) { ForeColor = Ink });
}
presets.DropDown.Renderer = tools.Renderer;
presets.DropDown.BackColor = Color.FromArgb(44, 44, 41);
view.DropDownItems.Add(presets);
view.DropDown.Renderer = tools.Renderer;
view.DropDown.BackColor = Color.FromArgb(44, 44, 41);
view.DropDown.ForeColor = Ink;
return view;
}
// ==================================================================
// Édition
// ==================================================================
void ClearPage()
{
if (pyBox.TextLength == 0) return;
if (MessageBox.Show(this, Lang.T("Effacer tout le code Python de la page ?\n(Ctrl+Z permet d'annuler.)"), Lang.T("Effacer la page"),
MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK) return;
pyBox.SelectAll();
pyBox.ClearSelected(); // passe par l'historique : Ctrl+Z rétablit le code
pyBox.Focus();
}
/// <summary>Ajoute ou retire « # » au début des lignes sélectionnées.</summary>
void ToggleComment()
{
var sel = pyBox.Selection.Clone();
sel.Normalize();
int from = sel.Start.iLine, to = sel.End.iLine;
if (to > from && sel.End.iChar == 0) to--;
var lines = Enumerable.Range(from, to - from + 1).Select(i => pyBox.GetLineText(i)).ToList();
bool uncomment = lines.Where(l => l.Trim().Length > 0).All(l => l.TrimStart().StartsWith("#"));
var changed = lines.Select(l =>
{
if (l.Trim().Length == 0) return l;
int ind = l.Length - l.TrimStart().Length;
if (!uncomment) return l.Substring(0, ind) + "# " + l.Substring(ind);
string rest = l.Substring(ind + 1);
return l.Substring(0, ind) + (rest.StartsWith(" ") ? rest.Substring(1) : rest);
});
pyBox.Selection = new Range(pyBox, 0, from, pyBox.GetLineText(to).Length, to);
pyBox.InsertText(string.Join("\r\n", changed));
pyBox.Selection = new Range(pyBox, 0, from, pyBox.GetLineText(to).Length, to);
}
// ==================================================================
// Thème du code Python
// ==================================================================
void ApplyPythonTheme()
{
if (darkItem != null && darkItem.Checked != pyDark) darkItem.Checked = pyDark;
void Fore(TextStyle st, Color c) => st.ForeBrush = new SolidBrush(c);
if (pyDark)
{
pyBox.BackColor = Color.FromArgb(30, 30, 30);
pyBox.ForeColor = Color.FromArgb(220, 220, 214);
pyBox.IndentBackColor = Color.FromArgb(37, 37, 36);
pyBox.LineNumberColor = Color.FromArgb(118, 116, 108);
pyBox.CurrentLineColor = Color.FromArgb(50, 255, 255, 255);
pyBox.ServiceLinesColor = Color.FromArgb(60, 60, 58);
Fore(pyComment, Color.FromArgb(118, 150, 96));
Fore(pyDoc, Color.FromArgb(118, 150, 96));
Fore(pyString, Color.FromArgb(214, 157, 120));
Fore(pyKeyword, Color.FromArgb(240, 150, 70));
Fore(pyBuiltin, Color.FromArgb(120, 190, 240));
Fore(pyHp, Color.FromArgb(210, 140, 220));
Fore(pyNumber, Color.FromArgb(181, 206, 150));
Fore(pyDef, Color.FromArgb(235, 225, 160));
}
else
{
pyBox.BackColor = Paper;
pyBox.ForeColor = Color.FromArgb(31, 30, 27);
pyBox.IndentBackColor = Color.FromArgb(240, 238, 230);
pyBox.LineNumberColor = Color.FromArgb(163, 159, 148);
pyBox.CurrentLineColor = Color.FromArgb(60, 210, 210, 255);
pyBox.ServiceLinesColor = Color.FromArgb(220, 218, 210);
Fore(pyComment, Color.FromArgb(138, 134, 118));
Fore(pyDoc, Color.FromArgb(138, 134, 118));
Fore(pyString, Color.FromArgb(61, 122, 42));
Fore(pyKeyword, Color.FromArgb(184, 86, 27));
Fore(pyBuiltin, Color.FromArgb(45, 94, 158));
Fore(pyHp, Color.FromArgb(120, 40, 140));
Fore(pyNumber, Color.FromArgb(138, 59, 143));
Fore(pyDef, Color.Black);
}
pyBox.Invalidate();
}
// ==================================================================
// Couleurs du listing RPN
// ==================================================================
void ApplyRpnColors()
{
rpnBox.BackColor = rpnColors.Back;
rpnBox.IndentBackColor = rpnColors.Back;
rpnBox.ForeColor = last == null ? Color.FromArgb(130, rpnColors.Text) : rpnColors.Text;
rpLineNo.ForeBrush = new SolidBrush(rpnColors.LineNo);
rpLabel.ForeBrush = new SolidBrush(rpnColors.Label);
rpFlow.ForeBrush = new SolidBrush(rpnColors.Flow);
rpTest.ForeBrush = new SolidBrush(rpnColors.Test);
rpAlpha.ForeBrush = new SolidBrush(rpnColors.Alpha);
rpnBox.Invalidate();
}
void EditRpnColors()
{
var backup = rpnColors.Clone();
var work = rpnColors.Clone();
var rows = new (string Label, Func<Color> Get, Action<Color> Set)[]
{
(Lang.T("Fond de page"), () => work.Back, c => work.Back = c),
(Lang.T("Texte (instructions)"), () => work.Text, c => work.Text = c),
(Lang.T("Numéros de ligne"), () => work.LineNo, c => work.LineNo = c),
(Lang.T("LBL (labels)"), () => work.Label, c => work.Label = c),
("GTO, XEQ, RTN, END", () => work.Flow, c => work.Flow = c),
(Lang.T("Tests (X<Y?, FS?…)"), () => work.Test, c => work.Test = c),
(Lang.T("Textes \"…\""), () => work.Alpha, c => work.Alpha = c),
};
using (var f = new Form
{
Text = "Couleurs du listing RPN",
FormBorderStyle = FormBorderStyle.FixedDialog,
MaximizeBox = false, MinimizeBox = false, ShowInTaskbar = false,
StartPosition = FormStartPosition.CenterParent,
BackColor = Body, ForeColor = Ink, Font = new Font("Segoe UI", 9.5f),
AutoSize = true, AutoSizeMode = AutoSizeMode.GrowAndShrink, Padding = new Padding(12)
})
{
var grid = new TableLayoutPanel { AutoSize = true, ColumnCount = 2, Dock = DockStyle.Fill };
var swatches = new List<Button>();
void Preview() { rpnColors = work.Clone(); ApplyRpnColors(); HighlightRpn(); }
void Refresh() { for (int i = 0; i < rows.Length; i++) swatches[i].BackColor = rows[i].Get(); Preview(); }
var presetBox = new ComboBox { DropDownStyle = ComboBoxStyle.DropDownList, Width = 190 };
presetBox.Items.AddRange(RpnColors.Presets.Select(p => (object)p.Name).ToArray());
grid.Controls.Add(new Label { Text = "Modèle", AutoSize = true, Anchor = AnchorStyles.Left, ForeColor = Muted });
grid.Controls.Add(presetBox);
foreach (var row in rows)
{
var r = row;
var b = new Button { Width = 190, Height = 26, FlatStyle = FlatStyle.Flat, Text = "", Cursor = Cursors.Hand };
b.FlatAppearance.BorderColor = Color.FromArgb(110, 108, 100);
b.Click += (s, e) =>
{
using (var dlg = new ColorDialog { Color = r.Get(), FullOpen = true, AnyColor = true })
if (dlg.ShowDialog(f) == DialogResult.OK) { r.Set(dlg.Color); Refresh(); }
};
swatches.Add(b);
grid.Controls.Add(new Label { Text = r.Label, AutoSize = true, Anchor = AnchorStyles.Left, Margin = new Padding(0, 6, 16, 0) });
grid.Controls.Add(b);
}
presetBox.SelectedIndexChanged += (s, e) =>
{
var p = RpnColors.Presets[presetBox.SelectedIndex].Make();
work.Back = p.Back; work.Text = p.Text; work.LineNo = p.LineNo; work.Label = p.Label; work.Flow = p.Flow; work.Test = p.Test; work.Alpha = p.Alpha;
Refresh();
};
var ok = new Button { Text = "OK", DialogResult = DialogResult.OK, BackColor = Shift, ForeColor = Color.FromArgb(28, 27, 25), FlatStyle = FlatStyle.Flat, AutoSize = true };
var cancel = new Button { Text = "Annuler", DialogResult = DialogResult.Cancel, FlatStyle = FlatStyle.Flat, AutoSize = true };
var buttons = new FlowLayoutPanel { FlowDirection = FlowDirection.RightToLeft, AutoSize = true, Dock = DockStyle.Fill, Margin = new Padding(0, 12, 0, 0) };
buttons.Controls.Add(cancel);
buttons.Controls.Add(ok);
grid.Controls.Add(new Label { Text = "La fenêtre se met à jour en direct.", AutoSize = true, ForeColor = Muted, Anchor = AnchorStyles.Left, Margin = new Padding(0, 16, 0, 0) });
grid.Controls.Add(buttons);
f.Controls.Add(grid);
f.AcceptButton = ok;
f.CancelButton = cancel;
Refresh();
Lang.Apply(f);
if (f.ShowDialog(this) == DialogResult.OK) { rpnColors = work.Clone(); SaveViewSettings(); }
else rpnColors = backup;
ApplyRpnColors();
HighlightRpn();
}
}
// ==================================================================
// Fichier .raw direct (encodeur dm42dll, comme « Encoder et enregistrer en .raw »)
// ==================================================================
string lastRawDir;
void SaveRaw()
{
if (last == null) { status.Text = Lang.T("Rien à encoder : corrigez d'abord les erreurs."); return; }
if (TargetC47) { SaveP47(); return; }
var bytes = Py42.Raw.RawExport.Encode(last, out var errors);
if (bytes == null)
{
MessageBox.Show(this, Lang.T("Le listing n'a pas pu être encodé :\n\n") + string.Join("\n", errors.Distinct().Take(15)),
Lang.T("Générer .raw"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
string name = currentFile != null ? Path.GetFileNameWithoutExtension(currentFile)
: (progName.Text.Trim().Length > 0 ? progName.Text.Trim() : "MAIN");
string dir = lastRawDir ?? (currentFile != null ? Path.GetDirectoryName(currentFile)
: Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
using (var dlg = new SaveFileDialog
{
Title = Lang.T("Enregistrer le programme pour la DM42 / Free42"),
Filter = Lang.T("Programme HP-42S (*.raw)|*.raw"),
DefaultExt = ".raw",
FileName = name + ".raw",
InitialDirectory = dir
})
{
if (dlg.ShowDialog(this) != DialogResult.OK) return;
try
{
File.WriteAllBytes(dlg.FileName, bytes);
lastRawDir = Path.GetDirectoryName(dlg.FileName);
status.Text = Lang.F("{0} : {1} octets, {2} pas. DM42 : copiez-le sur son disque USB puis Load Program ; Free42 : File → Import Programs.", Path.GetFileName(dlg.FileName), bytes.Length, last.Code.Count);
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, Lang.T("Écriture impossible"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
// ==================================================================
// Envoi vers l'émulateur réglé dans Paramètres (presse-papiers + fenêtre au premier plan)
// ==================================================================
/// <summary>Fichier .p47 pour la C47 / R47 : la source convertie, encodée par C47.Core.</summary>
void SaveP47()
{
if (!lastC47Code.Ok)
{
MessageBox.Show(this, Lang.T("Le listing n'a pas pu être encodé :\n\n") + string.Join("\n", lastC47Code.Errors.Take(15).Select(er => Lang.F("Ligne {0} : {1}", er.Line, C47.Core.Tr.T(er.Message)))),
Lang.T("Générer .p47"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
string name = currentFile != null ? Path.GetFileNameWithoutExtension(currentFile)
: (progName.Text.Trim().Length > 0 ? progName.Text.Trim() : "MAIN");
string dir = lastRawDir ?? (currentFile != null ? Path.GetDirectoryName(currentFile)
: Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
using (var dlg = new SaveFileDialog
{
Title = Lang.T("Enregistrer le programme pour la C47"),
Filter = Lang.T("Programme C47 (*.p47)|*.p47"),
DefaultExt = ".p47",
FileName = name + ".p47",
InitialDirectory = dir
})
{
if (dlg.ShowDialog(this) != DialogResult.OK) return;
try
{
File.WriteAllBytes(dlg.FileName, C47.Core.P47File.Write(lastC47Code.Program));
lastRawDir = Path.GetDirectoryName(dlg.FileName);
status.Text = Lang.F("{0} enregistré : {1} pas, {2} octets", Path.GetFileName(dlg.FileName), lastC47Code.Steps, lastC47Code.Program.Length);
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, Lang.T("Écriture impossible"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
void SendToFree42()
{
if (last == null) { status.Text = Lang.T("Rien à envoyer : corrigez d'abord les erreurs."); return; }
if (TargetC47)
{
if (!lastC47Code.Ok) { status.Text = Lang.T("Le listing C47 contient des erreurs : voir les messages."); return; }
status.Text = Emulator.SendC47(this, C47.Core.P47File.Write(lastC47Code.Program), progName.Text.Trim().Length > 0 ? progName.Text.Trim() : "MAIN");
return;
}
status.Text = Emulator.Send(this, last.Listing(true, header: true), last.Code.Count);
}
/// <summary>Maj+F7, cible C47 / R47 : copie le .p47 dans l'application R47 / C47 du téléphone Android branché en USB.</summary>
void SendToAndroid()
{
if (!TargetC47) { status.Text = Lang.T("Choisissez d'abord la cible C47 / R47."); return; }
if (last == null) { status.Text = Lang.T("Rien à envoyer : corrigez d'abord les erreurs."); return; }
if (!lastC47Code.Ok) { status.Text = Lang.T("Le listing C47 contient des erreurs : voir les messages."); return; }
status.Text = Lang.T("Envoi vers le téléphone…");
Refresh();
status.Text = AndroidR47.Send(this, C47.Core.P47File.Write(lastC47Code.Program), progName.Text.Trim().Length > 0 ? progName.Text.Trim() : "MAIN");
}
}
}