Repository navigation
Expand file tree
/
Copy pathFrmPython.cs
More file actions
1323 lines (1234 loc) · 76.1 KB
/
Copy pathFrmPython.cs
File metadata and controls
1323 lines (1234 loc) · 76.1 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
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Dm42.Editor;
using Py = Py42.Core;
using Range = Dm42.Editor.TextRange;
namespace dm42editor
{
/// <summary>
/// Éditeur Python → RPN : éditeur coloré, listing RPN synchronisé, messages et simulateur.
/// Fenêtre construite en code (pas de fichier Designer) pour rester indépendante de Form1.
/// </summary>
public partial class FrmPython : Form
{
// ------------------------------------------------------------------
// Palette : boîtier HP-42S (anthracite, touche shift orange), écran LCD gris-vert
// ------------------------------------------------------------------
static readonly Color Body = Color.FromArgb(38, 38, 36);
static readonly Color Bar = Color.FromArgb(28, 28, 26);
static readonly Color Ink = Color.FromArgb(236, 234, 228);
static readonly Color Muted = Color.FromArgb(156, 154, 146);
static readonly Color Shift = Color.FromArgb(224, 137, 47);
static readonly Color Paper = Color.FromArgb(251, 250, 246);
static readonly Color Lcd = Color.FromArgb(198, 205, 176);
static readonly Color LcdInk = Color.FromArgb(30, 36, 24);
// Styles Python
readonly TextStyle pyComment = new TextStyle(new SolidBrush(Color.FromArgb(138, 134, 118)), null, FontStyle.Italic);
// commentaire multiligne """ … """ : même couleur, enregistré avant les autres styles pour l'emporter sur eux
readonly TextStyle pyDoc = new TextStyle(new SolidBrush(Color.FromArgb(138, 134, 118)), null, FontStyle.Italic);
static readonly Regex DocRegex = new Regex(@"(""""""|''')[\s\S]*?(\1|\z)", RegexOptions.Compiled);
readonly TextStyle pyString = new TextStyle(new SolidBrush(Color.FromArgb(61, 122, 42)), null, FontStyle.Regular);
readonly TextStyle pyKeyword = new TextStyle(new SolidBrush(Color.FromArgb(184, 86, 27)), null, FontStyle.Bold);
readonly TextStyle pyBuiltin = new TextStyle(new SolidBrush(Color.FromArgb(45, 94, 158)), null, FontStyle.Regular);
readonly TextStyle pyHp = new TextStyle(new SolidBrush(Color.FromArgb(120, 40, 140)), null, FontStyle.Bold);
readonly TextStyle pyNumber = new TextStyle(new SolidBrush(Color.FromArgb(138, 59, 143)), null, FontStyle.Regular);
readonly TextStyle pyDef = new TextStyle(Brushes.Black, null, FontStyle.Bold);
// Styles RPN
readonly TextStyle rpLineNo = new TextStyle(new SolidBrush(Color.FromArgb(115, 123, 98)), null, FontStyle.Regular);
readonly TextStyle rpLabel = new TextStyle(new SolidBrush(Color.FromArgb(140, 47, 12)), null, FontStyle.Bold);
readonly TextStyle rpFlow = new TextStyle(new SolidBrush(Color.FromArgb(154, 82, 0)), null, FontStyle.Bold);
readonly TextStyle rpTest = new TextStyle(new SolidBrush(Color.FromArgb(31, 76, 120)), null, FontStyle.Bold);
/// <summary>
/// Tests HP-42S (X<Y?, X=0?, X≤Y?, FS? 01, FC?C 12, BIT?…) et leur argument : partagé avec l'éditeur RPN.
/// </summary>
internal const string RpnTestPattern =
@"(?<!\S)(X(<>|<=|>=|!=|=|≠|<|>|≤|≥|#)(0|Y)\?|F[SC]\?C?|BIT\?|MAT\?|CPX\?|REAL\?|STR\?)(?!\S)([ \t]+(IND[ \t]+)?(ST[ \t]+[XYZTL]|\d+|""[^""]*""))?"; // argument sur la même ligne seulement
static readonly Regex RpnTestRegex = new Regex(RpnTestPattern, RegexOptions.Compiled);
readonly TextStyle rpAlpha = new TextStyle(new SolidBrush(Color.FromArgb(85, 107, 20)), null, FontStyle.Regular);
// Marques de lignes
readonly TextStyle errorMark = new TextStyle(null, new SolidBrush(Color.FromArgb(90, 214, 64, 40)), FontStyle.Regular);
readonly TextStyle syncMark = new TextStyle(null, new SolidBrush(Color.FromArgb(110, 224, 137, 47)), FontStyle.Regular);
readonly Action<string, string, string> sendToEditor;
CodeEditor pyBox, rpnBox;
ListBox messages;
ToolStripTextBox progName;
ToolStripButton radButton, upperButton, numButton, sendButton, rawButton;
/// <summary>Cible du listing : HP-42S / DM42, ou C47 / R47 (conversion par C47.Core.Hp42Converter).</summary>
ToolStripComboBox targetBox;
C47.Core.Hp42Converter.Result lastC47;
C47.Core.EncodeResult lastC47Code;
bool TargetC47 => targetBox != null && targetBox.SelectedIndex == 1;
ToolStripStatusLabel status;
ComboBox entryBox;
TextBox stackBox, inputsBox, simOut;
/// <summary>Écran de la C47 à la fin de F5 (capture SNAP du simulateur), masqué pour la DM42.</summary>
PictureBox lcdBox;
SplitContainer mainSplit, leftSplit, rightSplit;
Py.CompileResult last;
string currentFile;
string preferredEntry = "MAIN";
bool syncing;
const int HeaderLines = 1; // ligne « 00 { Prgm } » en tête du listing
sealed class Msg
{
public string Text;
public int Line;
public override string ToString() => Text;
}
public FrmPython(Action<string, string, string> sendToEditor)
{
this.sendToEditor = sendToEditor;
BuildUi();
Lang.Apply(this);
UpdateTarget(); // libellés .raw / .p47 selon la cible de départ
NewProgram();
}
// ==================================================================
// Construction de l'interface
// ==================================================================
void BuildUi()
{
Text = "Python → RPN DM42";
Size = new Size(1320, 860);
MinimumSize = new Size(900, 600);
StartPosition = FormStartPosition.CenterScreen;
BackColor = Body;
ForeColor = Ink;
KeyPreview = true;
KeyDown += OnKeyDown;
Icon = Owner?.Icon;
// ---- barre d'outils
var tools = new ToolStrip { GripStyle = ToolStripGripStyle.Hidden, BackColor = Bar, ForeColor = Ink, Padding = new Padding(6, 4, 6, 4) };
tools.Renderer = new HpRenderer(); // survol et menus sombres : le texte blanc reste lisible
tools.Items.Add(BuildFileMenu(tools));
tools.Items.Add(BuildViewMenu(tools));
tools.Items.Add(new ToolStripSeparator());
tools.Items.Add(Button("Effacer", (s, e) => ClearPage(), "Efface toute la page Python (Ctrl+Z pour annuler)"));
tools.Items.Add(new ToolStripSeparator());
tools.Items.Add(new ToolStripLabel("Programme") { ForeColor = Muted });
progName = new ToolStripTextBox { Text = "MAIN", MaxLength = 7, Width = 70, ToolTipText = "Label global du programme principal (7 caractères max)" };
progName.TextChanged += (s, e) => Recompile();
tools.Items.Add(progName);
radButton = Toggle("RAD auto", true, "Ajoute RAD au début si le programme utilise la trigonométrie (Python calcule en radians)");
upperButton = Toggle("MAJ", true, "Noms de variables et de labels en majuscules");
numButton = Toggle("N° ligne", true, "Numéros de ligne dans le listing");
tools.Items.AddRange(new ToolStripItem[] { radButton, upperButton, numButton, new ToolStripSeparator() });
tools.Items.Add(new ToolStripLabel("Cible") { ForeColor = Muted });
targetBox = new ToolStripComboBox { DropDownStyle = ComboBoxStyle.DropDownList, Width = 110, ToolTipText = "Calculatrice visée : DM42 (HP-42S, Free42, Plus42), ou C47 / R47" };
targetBox.Items.AddRange(new object[] { "DM42", "C47 / R47" });
targetBox.SelectedIndex = Emulator.DefaultC47 ? 1 : 0; // calculatrice par défaut (Paramètres)
targetBox.SelectedIndexChanged += (s, e) => { UpdateTarget(); Recompile(); };
tools.Items.Add(targetBox);
tools.Items.Add(new ToolStripSeparator());
var send = sendButton = new ToolStripButton("→ Éditeur F6") { BackColor = Shift, ForeColor = Color.FromArgb(28, 27, 25), Font = new Font(Font, FontStyle.Bold), Tag = HpRenderer.ShiftKey, ToolTipText = "Ouvre le RPN dans un onglet de DM42 Editor, prêt pour « Encoder et enregistrer en .raw »" };
send.Click += (s, e) => SendToEditor();
tools.Items.Add(send);
var rawBtn = rawButton = new ToolStripButton("Générer .raw F8") { BackColor = Shift, ForeColor = Color.FromArgb(28, 27, 25), Font = new Font(Font, FontStyle.Bold), Tag = HpRenderer.ShiftKey, ToolTipText = "Encode directement le programme en fichier .raw pour la DM42 / Free42" };
rawBtn.Click += (s, e) => SaveRaw();
tools.Items.Add(rawBtn);
tools.Items.Add(Button("Émulateur F7", (s, e) => SendToFree42(), "Copie le listing et affiche l'émulateur réglé dans Paramètres (Free42, Plus42…), lancé si besoin : mode PRGM puis Ctrl+V"));
tools.Items.Add(new ToolStripSeparator());
tools.Items.Add(Button("Aide", (s, e) => ShowHelp(this, TargetC47), "Aide de la cible choisie (DM42 ou C47) : Python accepté et commandes"));
// ---- barre d'état
var statusStrip = new StatusStrip { BackColor = Bar, SizingGrip = true };
status = new ToolStripStatusLabel { ForeColor = Muted, Spring = true, TextAlign = ContentAlignment.MiddleLeft };
statusStrip.Items.Add(status);
// ---- éditeur Python
pyBox = NewEditor(Paper, Color.FromArgb(31, 30, 27), false);
pyBox.ShowLineNumbers = true;
pyBox.LineNumberColor = Color.FromArgb(163, 159, 148);
pyBox.IndentBackColor = Color.FromArgb(240, 238, 230);
pyBox.TabLength = 4;
pyBox.AutoIndent = false; // l'auto-indentation de FCTB réindente les lignes existantes : géré à la main
pyBox.CurrentLineColor = Color.FromArgb(60, 210, 210, 255);
pyBox.DelayedTextChangedInterval = 400;
pyBox.DelayedEventsInterval = 150;
pyBox.TextChanged += (s, e) => HighlightPython(e.ChangedRange);
pyBox.TextChangedDelayed += (s, e) => Recompile();
pyBox.SelectionChangedDelayed += (s, e) => SyncFromPython();
pyBox.KeyPressed += PythonNewLine;
BuildAutocomplete();
// ---- listing RPN
rpnBox = NewEditor(Lcd, LcdInk, true);
rpnBox.ShowLineNumbers = false;
rpnBox.IndentBackColor = Lcd;
rpnBox.LeftPadding = 8;
rpnBox.DelayedEventsInterval = 150;
rpnBox.SelectionChangedDelayed += (s, e) => SyncFromRpn();
// ---- messages
messages = new ListBox
{
Dock = DockStyle.Fill,
BackColor = Color.FromArgb(31, 31, 29),
ForeColor = Ink,
BorderStyle = BorderStyle.None,
Font = new Font("Segoe UI", 9.5f),
IntegralHeight = false,
HorizontalScrollbar = true
};
messages.SelectedIndexChanged += (s, e) => GotoMessage();
// ---- simulation
var sim = BuildSimulationPanel();
// ---- assemblage
leftSplit = new SplitContainer { Dock = DockStyle.Fill, Orientation = Orientation.Horizontal, BackColor = Body, SplitterWidth = 6 };
leftSplit.Panel1.Controls.Add(Framed("PYTHON", pyBox));
leftSplit.Panel2.Controls.Add(Framed("MESSAGES", messages));
rightSplit = new SplitContainer { Dock = DockStyle.Fill, Orientation = Orientation.Horizontal, BackColor = Body, SplitterWidth = 6 };
rightSplit.Panel1.Controls.Add(Framed("RPN DM42 · HP-42S · Free42", rpnBox));
rightSplit.Panel2.Controls.Add(Framed("SIMULATION", sim));
mainSplit = new SplitContainer { Dock = DockStyle.Fill, Orientation = Orientation.Vertical, BackColor = Body, SplitterWidth = 6, Padding = new Padding(8) };
mainSplit.Panel1.Controls.Add(leftSplit);
mainSplit.Panel2.Controls.Add(rightSplit);
Controls.Add(mainSplit);
Controls.Add(tools);
Controls.Add(statusStrip);
InitExtras();
Load += (s, e) =>
{
try
{
mainSplit.SplitterDistance = (int)(mainSplit.Width * 0.56);
leftSplit.SplitterDistance = (int)(leftSplit.Height * 0.74);
rightSplit.SplitterDistance = (int)(rightSplit.Height * 0.60);
}
catch (InvalidOperationException) { /* fenêtre trop petite : on garde les valeurs par défaut */ }
};
}
ToolStripButton Button(string text, EventHandler click, string tip)
{
var b = new ToolStripButton(text) { ForeColor = Ink, ToolTipText = tip };
b.Click += click;
return b;
}
ToolStripButton Toggle(string text, bool on, string tip)
{
var b = new ToolStripButton(text) { CheckOnClick = true, Checked = on, ForeColor = Ink, ToolTipText = tip };
b.CheckedChanged += (s, e) => Recompile();
return b;
}
static CodeEditor NewEditor(Color back, Color fore, bool readOnly)
{
return new CodeEditor
{
Dock = DockStyle.Fill,
Font = new Font("Consolas", 11.5f),
BackColor = back,
ForeColor = fore,
ReadOnly = readOnly,
BorderStyle = BorderStyle.None,
CaretColor = Shift,
SelectionColor = Color.FromArgb(70, 224, 137, 47)
};
}
static Control Framed(string caption, Control content)
{
var panel = new Panel { Dock = DockStyle.Fill, Padding = new Padding(0, 22, 0, 0), BackColor = Body };
var label = new Label
{
Text = caption,
ForeColor = Muted,
Font = new Font("Segoe UI", 8.5f, FontStyle.Bold),
AutoSize = false,
Height = 20,
Dock = DockStyle.Top,
TextAlign = ContentAlignment.BottomLeft
};
var border = new Panel { Dock = DockStyle.Fill, Padding = new Padding(1), BackColor = Color.FromArgb(69, 68, 63) };
border.Controls.Add(content);
panel.Controls.Add(border);
panel.Controls.Add(label);
label.Location = new Point(0, 0);
return panel;
}
Control BuildSimulationPanel()
{
var grid = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 3, RowCount = 4, BackColor = Body, Padding = new Padding(4) };
grid.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
grid.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));
grid.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
grid.RowStyles.Add(new RowStyle(SizeType.AutoSize));
grid.RowStyles.Add(new RowStyle(SizeType.AutoSize));
grid.RowStyles.Add(new RowStyle(SizeType.AutoSize));
grid.RowStyles.Add(new RowStyle(SizeType.Percent, 100));
Label L(string t) => new Label { Text = t, ForeColor = Muted, AutoSize = true, Anchor = AnchorStyles.Left, Margin = new Padding(0, 6, 8, 0) };
entryBox = new ComboBox { DropDownStyle = ComboBoxStyle.DropDownList, Dock = DockStyle.Fill };
var run = new Button
{
Text = "R/S (F5)",
BackColor = Shift,
ForeColor = Color.FromArgb(28, 27, 25),
FlatStyle = FlatStyle.Flat,
Font = new Font("Segoe UI", 9f, FontStyle.Bold),
AutoSize = true,
Margin = new Padding(6, 2, 0, 2)
};
run.FlatAppearance.BorderColor = Color.FromArgb(181, 102, 28);
run.Click += (s, e) => RunSimulation();
stackBox = new TextBox { Dock = DockStyle.Fill, BackColor = Color.FromArgb(51, 50, 47), ForeColor = Ink, BorderStyle = BorderStyle.FixedSingle, Font = new Font("Consolas", 10f) };
inputsBox = new TextBox { Dock = DockStyle.Fill, BackColor = Color.FromArgb(51, 50, 47), ForeColor = Ink, BorderStyle = BorderStyle.FixedSingle, Font = new Font("Consolas", 10f) };
var tip = new ToolTip();
tip.SetToolTip(stackBox, Lang.T("Valeurs mises sur la pile avant l'appel, la dernière va dans X (ex. : 12 18)"));
tip.SetToolTip(inputsBox, Lang.T("Réponses dans l'ordre : INPUT, prompt(), VARMENU (une par variable), menu() (n° de touche, 0 = EXIT), GETKEY"));
simOut = new TextBox
{
Dock = DockStyle.Fill,
Multiline = true,
ReadOnly = true,
ScrollBars = ScrollBars.Vertical,
BackColor = Lcd,
ForeColor = LcdInk,
BorderStyle = BorderStyle.None,
Font = new Font("Consolas", 10.5f),
Margin = new Padding(0, 6, 0, 0)
};
grid.Controls.Add(L("Lancer"), 0, 0);
grid.Controls.Add(entryBox, 1, 0);
grid.Controls.Add(run, 2, 0);
grid.Controls.Add(L("Pile"), 0, 1);
grid.Controls.Add(stackBox, 1, 1);
grid.SetColumnSpan(stackBox, 2);
grid.Controls.Add(L("INPUT"), 0, 2);
grid.Controls.Add(inputsBox, 1, 2);
grid.SetColumnSpan(inputsBox, 2);
lcdBox = new PictureBox { Dock = DockStyle.Left, SizeMode = PictureBoxSizeMode.Zoom, BackColor = Body, Visible = false, Cursor = Cursors.Hand };
new ToolTip().SetToolTip(lcdBox, Lang.T("Écran de la C47 à la fin du programme : cliquez pour l'agrandir"));
lcdBox.Click += (s, e) => ZoomLcd();
var output = new Panel { Dock = DockStyle.Fill, Margin = new Padding(0, 6, 0, 0) };
// l'écran (400 × 240) : à gauche du texte si le panneau est large et bas, au-dessus sinon
void PlaceLcd()
{
var c = output.ClientSize;
if (c.Width > c.Height * 2)
{
lcdBox.Dock = DockStyle.Left;
lcdBox.Width = Math.Min(c.Height * 400 / 240, c.Width / 2);
}
else
{
lcdBox.Dock = DockStyle.Top;
lcdBox.Height = Math.Min(c.Width * 240 / 400, c.Height / 2);
}
}
output.Resize += (s, e) => PlaceLcd();
output.Controls.Add(simOut);
output.Controls.Add(SimLayout.Gap(lcdBox, 10)); // espace entre l'écran C47 et le texte
output.Controls.Add(lcdBox);
SimLayout.LeftMargin(simOut, 8);
grid.Controls.Add(output, 0, 3);
grid.SetColumnSpan(output, 3);
return grid;
}
void BuildAutocomplete()
{
var menu = new AutocompleteMenu(pyBox) { MinFragmentLength = 2, SearchPattern = @"[\w\.]", AppearInterval = 300 };
var items = new List<AutocompleteItem>();
foreach (var kw in new[] { "def", "return", "if", "elif", "else", "while", "for", "range", "break", "continue",
"pass", "and", "or", "not", "True", "False", "import math", "import cmath", "import numpy as np", "global", "assert" })
items.Add(new AutocompleteItem(kw));
foreach (var f in new[] { "print", "input", "prompt", "menu", "varmenu", "int", "float", "abs", "max", "min", "pow",
"math.sqrt", "math.sin", "math.cos", "math.tan", "math.asin", "math.acos", "math.atan",
"math.atan2", "math.exp", "math.log", "math.log10", "math.hypot", "math.pi", "math.e",
"math.radians", "math.degrees", "math.factorial", "math.gamma", "math.floor", "math.ceil", "round",
"np.array", "np.zeros", "np.linalg.solve", "np.linalg.inv", "np.linalg.det", "np.linalg.norm",
"np.dot", "np.cross", "np.transpose", "zeros", "solve", "inv", "det", "transpose", "norm",
"rows", "cols", "len", "dot", "cross", "copy",
"complex", "cmath.sqrt", "cmath.exp", "cmath.log", "cmath.phase", "cmath.rect", "cmath.pi",
"conjugate", "real", "imag" })
items.Add(new AutocompleteItem(f));
foreach (var h in Py.Hp42.AllHelp().OrderBy(k => k.Name, StringComparer.OrdinalIgnoreCase))
items.Add(new AutocompleteItem(h.Name) { ToolTipTitle = h.Name, ToolTipText = h.Help });
menu.SetItems(items);
}
// ==================================================================
// Coloration
// ==================================================================
static readonly string HpRegex =
@"\b(" + string.Join("|", Py.Hp42.AllHelp().Select(h => h.Name).Distinct(StringComparer.OrdinalIgnoreCase).OrderByDescending(n => n.Length).Select(Regex.Escape)) + @")\b(?=\s*\()";
/// <summary>Chaîne "…" / '…' (fermée ou non, sur une seule ligne) ou commentaire # jusqu'en fin de ligne.</summary>
static readonly Regex StringOrComment = new Regex(@"""(?:\\.|[^""\\\n])*""?|'(?:\\.|[^'\\\n])*'?|#[^\n]*", RegexOptions.Compiled);
void HighlightPython(Range r)
{
// un bloc """ peut couvrir des lignes non modifiées : il est recalculé sur tout le texte
var all = pyBox.Range;
all.ClearStyle(pyDoc);
all.SetStyle(pyDoc, DocRegex);
r.ClearStyle(pyComment, pyString, pyKeyword, pyBuiltin, pyHp, pyNumber, pyDef);
// chaînes et commentaires lus ensemble, de gauche à droite et sans passer à la ligne :
// l'apostrophe de « # l'angle » ne commence pas une chaîne, le # de "N#1" n'est pas un commentaire
var none = new Range(pyBox, 0, 0, 0, 0);
none.SetStyle(pyComment); // ordre des styles : commentaire et chaîne l'emportent sur les mots-clés
none.SetStyle(pyString);
foreach (var m in r.GetRanges(StringOrComment))
m.SetStyle(m.Text.StartsWith("#") ? pyComment : pyString);
r.SetStyle(pyKeyword, @"\b(def|return|if|elif|else|while|for|in|break|continue|pass|and|or|not|True|False|import|from|global|assert)\b");
r.SetStyle(pyDef, @"(?<=\bdef\s+)\w+");
r.SetStyle(pyHp, HpRegex, RegexOptions.IgnoreCase);
r.SetStyle(pyBuiltin, @"\b(print|input|prompt|menu|varmenu|range|int|float|abs|max|min|pow|math|sqrt|sin|cos|tan|asin|acos|atan|atan2|sinh|cosh|tanh|asinh|acosh|atanh|exp|expm1|log|log1p|log10|hypot|pi|e|factorial|gamma|radians|degrees|fabs|trunc|floor|ceil|round|cmath|np|numpy|linalg|array|zeros|solve|inv|det|transpose|norm|rows|cols|len|dot|cross|copy|complex|conjugate|conj|phase|rect|real|imag)\b");
r.SetStyle(pyNumber, @"\b\d+(\.\d*)?([eE][+-]?\d+)?j\b");
r.SetStyle(pyNumber, @"\b\d+(\.\d*)?([eE][+-]?\d+)?\b|\.\d+");
}
void HighlightRpn()
{
var r = rpnBox.Range;
r.ClearStyle(rpLineNo, rpLabel, rpFlow, rpTest, rpAlpha);
r.SetStyle(rpLineNo, @"^\d{2,3}(?=\s)", RegexOptions.Multiline);
// guillemets HP-42S "…" ou C47 ‘…’ (cible C47)
r.SetStyle(rpLabel, @"\bLBL\s+(""[^""]*""|‘[^’]*’|\d+)");
r.SetStyle(rpFlow, @"\b(GTO|XEQ)\s+(""[^""]*""|‘[^’]*’|\d+)|\b(RTN|END|STOP|(42)?KEY \d GTO \d+)\b|^\s*(IF|ELSE|ENDIF|DO|WHILE|ENDDO|FORᵀᴼᴾ|NEXT)\b.*$", RegexOptions.Multiline);
r.SetStyle(rpAlpha, @"⊢?""[^""\n]*""|(42α|42⊢) ‘[^’\n]*’");
r.SetStyle(rpTest, RpnTestRegex);
}
/// <summary>Entrée : reprend l'indentation, +4 après « : », -4 après return / break / continue / pass.</summary>
void PythonNewLine(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != '\r' && e.KeyChar != '\n') return;
int line = pyBox.Selection.Start.iLine;
if (line < 1) return;
string prev = pyBox.GetLineText(line - 1);
int indent = prev.Length - prev.TrimStart(' ').Length;
string code = Regex.Replace(prev, @"#.*$", "").TrimEnd();
if (code.EndsWith(":")) indent += 4;
else if (Regex.IsMatch(code, @"^\s*(return|break|continue|pass)\b")) indent = Math.Max(0, indent - 4);
string current = pyBox.GetLineText(line);
int already = current.Length - current.TrimStart(' ').Length;
if (indent > already) pyBox.InsertText(new string(' ', indent - already));
}
// ==================================================================
// Conversion
// ==================================================================
void Recompile()
{
if (pyBox == null) return;
var opts = new Py.CompileOptions
{
ProgramName = progName.Text,
Radians = radButton.Checked,
UpperCase = upperButton.Checked,
// C47 : structures IF / DO / FOR, registres locaux ; les noms HP-42S restants passent ensuite par Hp42Converter
Target = TargetC47 ? Py.Target.C47 : Py.Target.Hp42
};
messages.BeginUpdate();
messages.Items.Clear();
pyBox.Range.ClearStyle(errorMark);
try
{
last = Py.Compiler.Compile(pyBox.Text, opts);
rpnBox.Text = last.Listing(numButton.Checked, header: true);
if (TargetC47)
{
// même listing, en source C47 : une ligne par ligne, la synchronisation avec le Python est gardée
lastC47 = C47.Core.Hp42Converter.Convert(rpnBox.Text);
lastC47Code = C47.Core.Encoder.Encode(lastC47.Source);
rpnBox.Text = lastC47.Source;
}
rpnBox.ForeColor = RpnFore;
HighlightRpn();
foreach (var w in last.Warnings) messages.Items.Add(new Msg { Text = "⚠ " + w, Line = LineIn(w) });
if (TargetC47)
{
foreach (var w in lastC47.Warnings) messages.Items.Add(new Msg { Text = "⚠ C47 : " + C47.Core.Tr.T(w) });
foreach (var er in lastC47Code.Errors.Take(10)) messages.Items.Add(new Msg { Text = "✗ C47 : " + Lang.F("Ligne {0} : {1}", er.Line, C47.Core.Tr.T(er.Message)) });
}
if (last.Warnings.Count == 0) messages.Items.Add(new Msg { Text = Lang.T("✓ Conversion réussie") });
status.Text = Lang.F("{0} pas · {1}/99 labels locaux · pile max {2}/4 · {3} variable(s) : {4}", last.Code.Count, last.LocalLabels, last.MaxStack, last.Variables.Count, string.Join(" ", last.Variables));
string keep = entryBox.SelectedItem as string ?? preferredEntry;
entryBox.Items.Clear();
foreach (var e in last.Entries) entryBox.Items.Add(e);
if (last.Entries.Contains(keep)) entryBox.SelectedItem = keep;
else if (entryBox.Items.Count > 0) entryBox.SelectedIndex = 0;
}
catch (Py.CompileError ex)
{
last = null;
messages.Items.Add(new Msg { Text = ex.Line > 0 ? Lang.F("✖ Ligne {0} : {1}", ex.Line, ex.Message) : "✖ " + ex.Message, Line = ex.Line });
if (ex.Line > 0 && ex.Line <= pyBox.LinesCount) new Range(pyBox, ex.Line - 1).SetStyle(errorMark);
rpnBox.ForeColor = Color.FromArgb(130, RpnFore);
status.Text = Lang.T("Erreur : le listing grisé est celui de la dernière conversion réussie.");
}
messages.EndUpdate();
pyBox.Invalidate();
SyncFromPython();
}
static int LineIn(string text)
{
var m = Regex.Match(text, @"Ligne (\d+)");
return m.Success ? int.Parse(m.Groups[1].Value) : 0;
}
// ==================================================================
// Synchronisation Python ↔ RPN
// ==================================================================
void SyncFromPython()
{
if (syncing || last == null || rpnBox.Focused) return;
syncing = true;
try
{
pyBox.Range.ClearStyle(syncMark);
rpnBox.Range.ClearStyle(syncMark);
int src = pyBox.Selection.Start.iLine + 1;
Range first = null;
for (int i = 0; i < last.Code.Count; i++)
{
if (last.Code[i].Line != src) continue;
int line = i + HeaderLines;
if (line >= rpnBox.LinesCount) break;
var r = new Range(rpnBox, line);
r.SetStyle(syncMark);
if (first == null) first = r;
}
if (first != null) rpnBox.DoRangeVisible(first);
rpnBox.Invalidate();
pyBox.Invalidate();
}
finally { syncing = false; }
}
void SyncFromRpn()
{
if (syncing || last == null || !rpnBox.Focused) return;
syncing = true;
try
{
pyBox.Range.ClearStyle(syncMark);
rpnBox.Range.ClearStyle(syncMark);
int i = rpnBox.Selection.Start.iLine - HeaderLines;
if (i >= 0 && i < last.Code.Count && last.Code[i].Line > 0)
{
int src = last.Code[i].Line;
if (src <= pyBox.LinesCount)
{
var r = new Range(pyBox, src - 1);
r.SetStyle(syncMark);
pyBox.DoRangeVisible(r);
}
for (int j = 0; j < last.Code.Count; j++)
if (last.Code[j].Line == src && j + HeaderLines < rpnBox.LinesCount)
new Range(rpnBox, j + HeaderLines).SetStyle(syncMark);
}
rpnBox.Invalidate();
pyBox.Invalidate();
}
finally { syncing = false; }
}
void GotoMessage()
{
if (!(messages.SelectedItem is Msg m) || m.Line <= 0 || m.Line > pyBox.LinesCount) return;
pyBox.Selection = new Range(pyBox, 0, m.Line - 1, 0, m.Line - 1);
pyBox.DoSelectionVisible();
pyBox.Focus();
}
// ==================================================================
// Simulation
// ==================================================================
static double[] Nums(string s) => s
.Split(new[] { ' ', ';', '\t' }, StringSplitOptions.RemoveEmptyEntries)
.Select(v => double.Parse(v.Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture))
.ToArray();
void RunSimulation()
{
if (Emulator.C47Busy) { Emulator.C47Cancel = true; return; } // F5 pendant une simulation C47 : l'interrompt
if (last == null) { simOut.Text = Lang.T("Corrigez d'abord les erreurs signalées dans les messages."); return; }
if (!(entryBox.SelectedItem is string entry)) { simOut.Text = Lang.T("Aucun label à lancer."); return; }
double[] stack, inputs;
try { stack = Nums(stackBox.Text); inputs = Nums(inputsBox.Text); }
catch (FormatException) { simOut.Text = Lang.T("Valeur invalide : séparez les nombres par des espaces ou des points-virgules."); return; }
ShowLcd(null);
if (TargetC47) { RunC47Simulation(entry, stack, inputs); return; }
var r = Py.Simulator.Run(last.Code, entry, stack, inputs);
var sb = new StringBuilder();
foreach (var d in r.Display) sb.AppendLine(d);
if (r.Error != null)
{
sb.AppendLine().AppendLine($"ERREUR au pas {r.ErrorPc + 1} : {r.Error}");
if (r.ErrorPc >= 0 && r.ErrorPc < last.Code.Count)
{
syncing = true;
pyBox.Range.ClearStyle(syncMark);
rpnBox.Range.ClearStyle(syncMark);
var rr = new Range(rpnBox, r.ErrorPc + HeaderLines);
rr.SetStyle(errorMark);
rpnBox.DoRangeVisible(rr);
int src = last.Code[r.ErrorPc].Line;
if (src > 0 && src <= pyBox.LinesCount)
{
var pr = new Range(pyBox, src - 1);
pr.SetStyle(syncMark);
pyBox.DoRangeVisible(pr);
}
syncing = false;
rpnBox.Invalidate();
pyBox.Invalidate();
}
}
if (sb.Length > 0) sb.AppendLine();
sb.AppendLine($"T: {Py.Simulator.Fmt(r.T)}");
sb.AppendLine($"Z: {Py.Simulator.Fmt(r.Z)}");
sb.AppendLine($"Y: {Py.Simulator.Fmt(r.Y)}");
sb.AppendLine($"X: {Py.Simulator.Fmt(r.X)}");
sb.AppendLine();
sb.Append(Lang.F("{0} pas exécutés", r.Steps));
if (r.MaxCallDepth > 0) sb.Append(Lang.F(", {0} niveau(x) d'appel XEQ", r.MaxCallDepth));
if (r.MaxCallDepth > 8) sb.Append(Lang.T(" (attention : la HP-42S d'origine n'a que 8 niveaux de retour)"));
simOut.Text = sb.ToString().Replace("\n", Environment.NewLine).Replace("\r\r", "\r");
}
/// <summary>Écran de la C47 en taille double, dans une fenêtre à part (Échap ou clic pour fermer).</summary>
void ZoomLcd()
{
if (lcdBox.Image == null) return;
var pic = new PictureBox { Dock = DockStyle.Fill, SizeMode = PictureBoxSizeMode.Zoom, Image = new Bitmap(lcdBox.Image) };
var f = new Form
{
Text = Lang.T("Écran C47"), ClientSize = new Size(800, 480), StartPosition = FormStartPosition.CenterParent,
FormBorderStyle = FormBorderStyle.SizableToolWindow, KeyPreview = true, ShowInTaskbar = false
};
f.Controls.Add(pic);
pic.Click += (s, e) => f.Close();
f.KeyDown += (s, e) => { if (e.KeyCode == Keys.Escape) f.Close(); };
f.FormClosed += (s, e) => pic.Image.Dispose();
f.Show(this);
}
void ShowLcd(Image screen)
{
var old = lcdBox.Image;
lcdBox.Image = screen;
lcdBox.Visible = screen != null;
old?.Dispose();
}
/// <summary>Texte rendu par le simulateur, en codes de la police C47 : exposants lisibles (×⑽ⅫⅣ → ×10⁻³).</summary>
static string Readable47(string s) => C47.Core.C47Text.Display(s).Replace("⑽", "10");
/// <summary>Cible C47 : le programme encodé tourne dans le vrai simulateur C47 (sans fenêtre), qui rend la pile et ALPHA.</summary>
void RunC47Simulation(string entry, double[] stack, double[] inputs)
{
if (lastC47Code == null || !lastC47Code.Ok) { simOut.Text = Lang.T("Le listing C47 contient des erreurs : voir les messages."); return; }
simOut.Text = Lang.T("Simulateur C47 en cours… (F5 pour l'interrompre)");
simOut.Refresh();
Cursor = Cursors.WaitCursor;
Emulator.C47Run r;
// copie instrumentée : chaque message affiché est ajouté au journal PYLOG, relu à la fin
var sim = C47.Core.Encoder.Encode(C47.Core.SimCopy.Build(lastC47.Source, entry, out bool pauseSnap));
bool logged = sim.Ok;
try { r = Emulator.RunC47(this, C47.Core.P47File.Write((logged ? sim : lastC47Code).Program), logged ? C47.Core.SimCopy.Entry : entry, stack, inputs, logged ? C47.Core.SimCopy.LogVar : null, logged && pauseSnap); }
finally { Cursor = Cursors.Default; }
ShowLcd(r.Screen);
var sb = new StringBuilder();
sb.AppendLine(Lang.T("Simulateur C47 (calcul sur 34 chiffres)"));
var messages = r.Log.Split(C47.Core.SimCopy.LogSep, StringSplitOptions.RemoveEmptyEntries);
if (messages.Length > 0)
{
sb.AppendLine();
foreach (var m in messages) sb.AppendLine(Readable47(m));
}
else if (r.Alpha.Length > 0) sb.AppendLine().AppendLine(Lang.T("Dernier message : ") + Readable47(r.Alpha));
if (r.Error.Length > 0) sb.AppendLine().AppendLine(r.Error);
sb.AppendLine();
sb.AppendLine(Lang.T(r.Stack8 ? "Pile de 8 niveaux (SSIZE8, réglage d'usine de la C47)" : "Pile de 4 niveaux (SSIZE4)"));
if (r.Stack8)
{
sb.AppendLine($"D: {r.D}");
sb.AppendLine($"C: {r.C}");
sb.AppendLine($"B: {r.B}");
sb.AppendLine($"A: {r.A}");
}
sb.AppendLine($"T: {r.T}");
sb.AppendLine($"Z: {r.Z}");
sb.AppendLine($"Y: {r.Y}");
sb.AppendLine($"X: {r.X}");
simOut.Text = sb.ToString().Replace("\n", Environment.NewLine).Replace("\r\r", "\r");
}
// ==================================================================
// Fichiers, exemples, envoi
// ==================================================================
public void NewProgram()
{
currentFile = null;
pyBox.Text = "# Programme Python pour HP-42S / DM42\r\nimport math\r\n\r\ndef carre(x):\r\n return x * x\r\n\r\nn = float(input(\"N ?\"))\r\nprint(\"CARRE\", carre(n))\r\n";
pyBox.ClearUndo();
pyBox.IsChanged = false;
preferredEntry = "MAIN";
stackBox.Text = "";
inputsBox.Text = "5";
simOut.Text = "";
UpdateTitle();
Recompile();
}
public void LoadExample(int index) => LoadExample(Py.Examples.All[index]);
/// <summary>Exemple propre à la C47 (récursivité, entiers longs, textes longs) : la cible passe à C47 / R47.</summary>
public void LoadC47Example(int index)
{
targetBox.SelectedIndex = 1;
LoadExample(Py.ExamplesC47.All[index]);
}
/// <summary>Programme de la distribution C47 réécrit en Python : cible C47 / R47.</summary>
public void LoadC47Program(int index)
{
targetBox.SelectedIndex = 1;
LoadExample(Py.ExamplesC47.Programs[index]);
}
void LoadExample(Py.Examples.Example ex)
{
currentFile = null;
preferredEntry = ex.Entry;
entryBox.Items.Clear();
pyBox.Text = ex.Source.TrimStart('\n').Replace("\r\n", "\n").Replace("\n", "\r\n");
pyBox.ClearUndo();
pyBox.IsChanged = false;
stackBox.Text = ex.Stack;
inputsBox.Text = ex.Inputs;
simOut.Text = "";
UpdateTitle();
Recompile();
if (last != null && last.Entries.Contains(ex.Entry)) entryBox.SelectedItem = ex.Entry;
}
void OpenFileDialog()
{
if (!ConfirmDiscard()) return;
using (var dlg = new OpenFileDialog { Filter = "Python (*.py)|*.py|Tous les fichiers (*.*)|*.*" })
if (dlg.ShowDialog(this) == DialogResult.OK) OpenFile(dlg.FileName);
}
public void OpenFile(string path)
{
try
{
pyBox.Text = File.ReadAllText(path);
pyBox.ClearUndo();
pyBox.IsChanged = false;
currentFile = path;
UpdateTitle();
Recompile();
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, Lang.T("Ouverture impossible"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
void SavePython(bool saveAs)
{
if (currentFile == null || saveAs)
{
using (var dlg = new SaveFileDialog { Filter = "Python (*.py)|*.py", FileName = (progName.Text.Trim().Length > 0 ? progName.Text.Trim() : "programme") + ".py" })
{
if (dlg.ShowDialog(this) != DialogResult.OK) return;
currentFile = dlg.FileName;
}
}
try
{
File.WriteAllText(currentFile, pyBox.Text, new UTF8Encoding(false));
pyBox.IsChanged = false;
status.Text = Lang.T("Enregistré : ") + currentFile;
UpdateTitle();
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, Lang.T("Enregistrement impossible"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
void SendToEditor()
{
if (last == null) { status.Text = Lang.T("Rien à envoyer : corrigez d'abord les erreurs."); return; }
string baseName = currentFile != null ? Path.GetFileNameWithoutExtension(currentFile)
: (progName.Text.Trim().Length > 0 ? progName.Text.Trim() : "MAIN");
if (TargetC47)
{
// onglet C47 (titre en .p47u), prêt pour « Encoder et enregistrer en .p47 »
sendToEditor?.Invoke(lastC47.Source, baseName + ".p47u", currentFile != null ? Path.ChangeExtension(currentFile, ".p47u") : null);
status.Text = Lang.F("Source C47 envoyée dans l'onglet « {0}.p47u ». Utilisez « Encoder et enregistrer en .p47 » pour la C47.", baseName);
return;
}
string path = currentFile != null ? Path.ChangeExtension(currentFile, ".free42") : null;
sendToEditor?.Invoke(last.Listing(numButton.Checked, header: true), baseName + ".free42", path);
status.Text = Lang.F("RPN envoyé dans l'onglet « {0}.free42 ». Utilisez « Encoder et enregistrer en .raw » pour la DM42.", baseName);
}
void CopyRpn()
{
if (last == null) { status.Text = Lang.T("Rien à copier : corrigez d'abord les erreurs."); return; }
try
{
Clipboard.SetText(last.Listing(numButton.Checked, header: true));
status.Text = Lang.T("Listing copié. Dans Free42 : Edit → Paste Program.");
}
catch (Exception ex) { status.Text = Lang.T("Presse-papiers indisponible : ") + ex.Message; }
}
void UpdateTitle() =>
Text = currentFile == null ? (TargetC47 ? "Python → RPN C47 / R47" : "Python → RPN DM42") : "Python → RPN — " + Path.GetFileName(currentFile);
/// <summary>Libellés des boutons selon la cible : .raw pour la DM42, .p47 pour la C47.</summary>
void UpdateTarget()
{
rawButton.Text = Lang.T(TargetC47 ? "Générer .p47 F8" : "Générer .raw F8");
rawButton.ToolTipText = Lang.T(TargetC47 ? "Encode directement le programme en fichier .p47 pour la C47 / R47" : "Encode directement le programme en fichier .raw pour la DM42 / Free42");
// titre du cadre du listing (Framed : bordure dans le panneau, libellé à côté)
if (rpnBox.Parent?.Parent?.Controls.OfType<Label>().FirstOrDefault() is Label caption)
caption.Text = TargetC47 ? "RPN C47 · R47" : "RPN DM42 · HP-42S · Free42";
sendButton.ToolTipText = Lang.T(TargetC47 ? "Ouvre la source C47 dans un onglet C47 de l'éditeur, prêt pour « Encoder et enregistrer en .p47 »" : "Ouvre le RPN dans un onglet de DM42 Editor, prêt pour « Encoder et enregistrer en .raw »");
UpdateTitle();
}
void OnKeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.F5) { RunSimulation(); e.Handled = true; }
else if (e.KeyCode == Keys.F6) { SendToEditor(); e.Handled = true; }
else if (e.KeyCode == Keys.F7 && e.Shift) { SendToAndroid(); e.Handled = true; }
else if (e.KeyCode == Keys.F7) { SendToFree42(); e.Handled = true; }
else if (e.KeyCode == Keys.F8) { SaveRaw(); e.Handled = true; }
else if (e.Control && e.KeyCode == Keys.K && pyBox.Focused) { ToggleComment(); e.Handled = true; }
else if (e.Control && e.Shift && e.KeyCode == Keys.S) { SavePython(true); e.Handled = true; }
else if (e.Control && e.KeyCode == Keys.S) { SavePython(false); e.Handled = true; }
else if (e.Control && e.KeyCode == Keys.O) { OpenFileDialog(); e.Handled = true; }
else if (e.Control && e.KeyCode == Keys.N) { if (ConfirmDiscard()) NewProgram(); e.Handled = true; }
else if (e.Control && e.KeyCode == Keys.P) { pyBox.Print(PrintTitle()); e.Handled = true; }
if (e.Handled) e.SuppressKeyPress = true;
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing && !ConfirmDiscard()) { e.Cancel = true; return; }
base.OnFormClosing(e);
}
// ==================================================================
// Couleurs de la barre d'outils et des menus
// ==================================================================
/// <summary>
/// Rendu sombre : le rendu Windows standard surligne en bleu ciel, sur lequel le texte blanc
/// de la barre d'outils devient illisible.
/// </summary>
internal sealed class HpRenderer : ToolStripProfessionalRenderer
{
public const string ShiftKey = "shift";
public HpRenderer() : base(new HpColors()) { RoundedEdges = false; }
protected override void OnRenderButtonBackground(ToolStripItemRenderEventArgs e)
{
if (e.Item.Tag as string == ShiftKey)
{
// bouton orange « Envoyer » : reste orange, plus clair au survol
var c = e.Item.Pressed ? Color.FromArgb(196, 112, 34) : e.Item.Selected ? Color.FromArgb(238, 156, 71) : Shift;
using (var b = new SolidBrush(c)) e.Graphics.FillRectangle(b, new Rectangle(Point.Empty, e.Item.Size));
return;
}
base.OnRenderButtonBackground(e);
}
protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e)
{
if (e.Item.Tag as string != ShiftKey && !(e.Item is ToolStripTextBox))
e.TextColor = e.Item.Enabled ? Ink : Muted;
base.OnRenderItemText(e);
}
protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e)
{
e.ArrowColor = Ink;
base.OnRenderArrow(e);
}
}
sealed class HpColors : ProfessionalColorTable
{
static readonly Color Hover = Color.FromArgb(74, 73, 69);
static readonly Color Press = Color.FromArgb(96, 94, 88);
static readonly Color Check = Color.FromArgb(102, 74, 42);
static readonly Color Edge = Color.FromArgb(110, 108, 100);
static readonly Color Menu = Color.FromArgb(44, 44, 41);
static readonly Color MenuSel = Color.FromArgb(150, 86, 26);
public override Color ToolStripGradientBegin => Bar;
public override Color ToolStripGradientMiddle => Bar;
public override Color ToolStripGradientEnd => Bar;
public override Color ToolStripBorder => Bar;
public override Color StatusStripGradientBegin => Bar;
public override Color StatusStripGradientEnd => Bar;
public override Color SeparatorDark => Edge;
public override Color SeparatorLight => Bar;
public override Color ButtonSelectedHighlight => Hover;
public override Color ButtonSelectedGradientBegin => Hover;
public override Color ButtonSelectedGradientMiddle => Hover;
public override Color ButtonSelectedGradientEnd => Hover;
public override Color ButtonSelectedBorder => Edge;
public override Color ButtonSelectedHighlightBorder => Edge;
public override Color ButtonPressedHighlight => Press;
public override Color ButtonPressedGradientBegin => Press;
public override Color ButtonPressedGradientMiddle => Press;
public override Color ButtonPressedGradientEnd => Press;
public override Color ButtonPressedBorder => Edge;
public override Color ButtonPressedHighlightBorder => Edge;
public override Color ButtonCheckedHighlight => Check;
public override Color ButtonCheckedGradientBegin => Check;
public override Color ButtonCheckedGradientMiddle => Check;
public override Color ButtonCheckedGradientEnd => Check;
public override Color ButtonCheckedHighlightBorder => Shift;
public override Color CheckBackground => Check;
public override Color CheckSelectedBackground => MenuSel;
public override Color CheckPressedBackground => MenuSel;
public override Color ToolStripDropDownBackground => Menu;
public override Color ImageMarginGradientBegin => Menu;
public override Color ImageMarginGradientMiddle => Menu;
public override Color ImageMarginGradientEnd => Menu;
public override Color MenuBorder => Edge;
public override Color MenuItemBorder => MenuSel;
public override Color MenuItemSelected => MenuSel;
public override Color MenuItemSelectedGradientBegin => MenuSel;
public override Color MenuItemSelectedGradientEnd => MenuSel;
public override Color MenuItemPressedGradientBegin => Press;
public override Color MenuItemPressedGradientMiddle => Press;
public override Color MenuItemPressedGradientEnd => Press;
public override Color OverflowButtonGradientBegin => Bar;
public override Color OverflowButtonGradientMiddle => Bar;
public override Color OverflowButtonGradientEnd => Bar;
}
// ==================================================================
// Aide
// ==================================================================
/// <summary>Texte à insérer pour une ligne d'aide « SIN(x) : sinus » ou « if FS(n): ... test ».</summary>
static string HelpSnippet(string help)
{
int i = help.IndexOf(" : ", StringComparison.Ordinal);
string s = i > 0 ? help.Substring(0, i) : help;
int j = s.IndexOf(": ...", StringComparison.Ordinal);
return j > 0 ? s.Substring(0, j + 1) : s;
}
/// <summary>Insère un appel choisi dans l'aide à l'emplacement du curseur.</summary>
void InsertFromHelp(string text)
{
pyBox.InsertText(text);
pyBox.Invalidate();
}
/// <summary>Instruction produite (après « → ») sous son nom C47, pour l'aide de la cible C47.</summary>
static readonly (string Hp42, string C47)[] HelpC47Names =
{
("→ SQRT", "→ √x"), ("→ E↑X", "→ ⅇˣ"), ("→ Y↑X", "→ yˣ"), ("→ ABS", "→ |x|"), ("→ N!", "→ x!"), ("→ GAMMA", "→ Γ(x)"),
("→ →RAD", "→ deg→rad"), ("→ →DEG", "→ rad→deg"), ("→ NEWMAT", "→ M.NEW"), ("→ MVAR + VARMENU", "→ MVAR + 42VRMNU"),
("→ ALPHA + AVIEW", "→ 42α + 42ARCL + 42AVIEW"), ("→ INPUT", "→ INPUT"),
};
/// <summary>Aide de la fenêtre Python : cible DM42 (HP-42S, Free42) ou C47 / R47.</summary>
public static void ShowHelp(IWin32Window owner, bool c47 = false)
{
var sb = new StringBuilder();
var snippets = new Dictionary<string, string>(); // ligne affichée -> texte inséré au double-clic
void Fn(string help, string suffix = "")
{
// C47 : la ligne est traduite ici, puis l'instruction prend son nom C47 (√x, x!…)
string line = help;
if (c47)
{
line = Lang.T(help);
foreach (var (hp, n) in HelpC47Names) line = line.Replace(hp, n);
line += suffix;
}
sb.AppendLine(" " + line);