- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNotepadCalc.cpp
More file actions
Latest commit
1137 lines (1003 loc) · 43.3 KB
/
Copy pathNotepadCalc.cpp
File metadata and controls
1137 lines (1003 loc) · 43.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
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
// NotepadCalc.cpp
// A combined Notepad + Calculator application using the standard Win32 API.
//
// Layout:
// +-------------------------------+------------------+
// | | [ display ] |
// | text editor | [C][(][)][Bksp] |
// | (Notepad area) | [7][8][9][ / ] |
// | | [4][5][6][ * ] |
// | | [1][2][3][ - ] |
// | | [0][.][%][ + ] |
// | | [ = ] |
// | | [ Insert into ]|
// | | [ Notepad ] |
// +-------------------------------+------------------+
// | status bar |
// +--------------------------------------------------+
//
// Features:
// - Multiline text editor (Notepad-style) backed by an EDIT control.
// - File menu: New, Open, Save, Save As, Exit (standard common dialogs).
// - Edit menu: Undo, Cut, Copy, Paste, Delete, Select All.
// - Calculator: a full clickable keypad docked on the right. Click digits and
// operators, press "=" to evaluate, then "Insert into Notepad" to drop the
// last calculation ("expression = answer") into the editor at the caret.
// - Calculator menu also has "Evaluate Selection / Line" (Ctrl+E) which
// evaluates the highlighted text (or current line) in the editor itself.
// - Status bar showing caret line/column and the last computed result.
//
// The expression evaluator supports + - * / %, parentheses, unary minus,
// floating point numbers, and standard operator precedence.
//
// Pure Win32 / C++ - no MFC, no .NET, no third-party libraries.
#ifndef UNICODE
#defineUNICODE
#endif
#ifndef _UNICODE
#define_UNICODE
#endif
#include<windows.h>
#include<commdlg.h>
#include<commctrl.h>
#include<richedit.h>
#include<string>
#include<cwchar>
#include<cwctype>
#include<cmath>
#include<stdexcept>
#pragma comment(lib, "comdlg32.lib")
#pragma comment(lib, "comctl32.lib")
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "gdi32.lib")
// ---------------------------------------------------------------------------
// Control / command identifiers
// ---------------------------------------------------------------------------
#defineIDC_EDIT1001// main multiline editor
#defineIDC_STATUS1002// status bar
#defineIDC_CALC_DISPLAY1003// calculator read-only display
#defineIDM_FILE_NEW2001
#defineIDM_FILE_OPEN2002
#defineIDM_FILE_SAVE2003
#defineIDM_FILE_SAVEAS2004
#defineIDM_FILE_EXIT2005
#defineIDM_EDIT_UNDO2101
#defineIDM_EDIT_REDO2107
#defineIDM_EDIT_CUT2102
#defineIDM_EDIT_COPY2103
#defineIDM_EDIT_PASTE2104
#defineIDM_EDIT_DELETE2105
#defineIDM_EDIT_SELALL2106
// "Undo Checkpoints" submenu - when a typing run is committed as an undo step.
#defineIDM_UNDO_TIME_OFF2120// radio: time interval
#defineIDM_UNDO_TIME_052121
#defineIDM_UNDO_TIME_12122
#defineIDM_UNDO_TIME_22123
#defineIDM_UNDO_TIME_52124
#defineIDM_UNDO_ON_ENTER2125// toggle: checkpoint on Enter
#defineIDM_UNDO_ON_PUNCT2126// toggle: checkpoint on . , ; : ! ?
#defineIDM_CALC_EVAL2201
#defineIDM_CALC_PANEL2202
// "Insert Result As" submenu - how Ctrl+E places the answer on the line.
#defineIDM_EVAL_NEWLINE2210
#defineIDM_EVAL_APPEND2211
#defineIDM_EVAL_REPLACE_FULL2212
#defineIDM_EVAL_REPLACE_RESULT2213
#defineIDM_HELP_ABOUT2301
// Calculator keypad buttons share a contiguous id range starting here.
#defineIDC_CALC_BTN_BASE3000
// Timer that closes the current undo group ~1 second after the last edit, so
// undo steps back in time-based chunks instead of one giant typing run.
#defineIDT_UNDO_GROUP1
#defineUNDO_GROUP_MS1000
// Button "kinds" decide what a click does.
enum CalcKind {
K_CHAR, // append a character to the expression
K_CLEAR, // clear the expression
K_BACK, // backspace
K_EQUALS, // evaluate
K_INSERT// insert last calculation into the editor
};
structCalcButton {
int id;
constwchar_t* label;
CalcKind kind;
wchar_t ch; // character to append when kind == K_CHAR
int row; // grid row (1-based; row 0 is the display)
int col; // grid column 0..3
int colspan; // how many columns this button spans
HWND hwnd; // filled in at creation time
};
// Keypad layout. Rows 1..7; the display occupies row 0 above these.
static CalcButton g_buttons[] = {
{ IDC_CALC_BTN_BASE + 0, L"C", K_CLEAR, 0, 1, 0, 1, nullptr },
{ IDC_CALC_BTN_BASE + 1, L"(", K_CHAR, L'(', 1, 1, 1, nullptr },
{ IDC_CALC_BTN_BASE + 2, L")", K_CHAR, L')', 1, 2, 1, nullptr },
{ IDC_CALC_BTN_BASE + 3, L"Bksp", K_BACK, 0, 1, 3, 1, nullptr },
{ IDC_CALC_BTN_BASE + 4, L"7", K_CHAR, L'7', 2, 0, 1, nullptr },
{ IDC_CALC_BTN_BASE + 5, L"8", K_CHAR, L'8', 2, 1, 1, nullptr },
{ IDC_CALC_BTN_BASE + 6, L"9", K_CHAR, L'9', 2, 2, 1, nullptr },
{ IDC_CALC_BTN_BASE + 7, L"/", K_CHAR, L'/', 2, 3, 1, nullptr },
{ IDC_CALC_BTN_BASE + 8, L"4", K_CHAR, L'4', 3, 0, 1, nullptr },
{ IDC_CALC_BTN_BASE + 9, L"5", K_CHAR, L'5', 3, 1, 1, nullptr },
{ IDC_CALC_BTN_BASE + 10, L"6", K_CHAR, L'6', 3, 2, 1, nullptr },
{ IDC_CALC_BTN_BASE + 11, L"*", K_CHAR, L'*', 3, 3, 1, nullptr },
{ IDC_CALC_BTN_BASE + 12, L"1", K_CHAR, L'1', 4, 0, 1, nullptr },
{ IDC_CALC_BTN_BASE + 13, L"2", K_CHAR, L'2', 4, 1, 1, nullptr },
{ IDC_CALC_BTN_BASE + 14, L"3", K_CHAR, L'3', 4, 2, 1, nullptr },
{ IDC_CALC_BTN_BASE + 15, L"-", K_CHAR, L'-', 4, 3, 1, nullptr },
{ IDC_CALC_BTN_BASE + 16, L"0", K_CHAR, L'0', 5, 0, 1, nullptr },
{ IDC_CALC_BTN_BASE + 17, L".", K_CHAR, L'.', 5, 1, 1, nullptr },
{ IDC_CALC_BTN_BASE + 18, L"%", K_CHAR, L'%', 5, 2, 1, nullptr },
{ IDC_CALC_BTN_BASE + 19, L"+", K_CHAR, L'+', 5, 3, 1, nullptr },
{ IDC_CALC_BTN_BASE + 20, L"=", K_EQUALS, 0, 6, 0, 4, nullptr },
{ IDC_CALC_BTN_BASE + 21, L"Insert into Notepad", K_INSERT, 0, 7, 0, 4, nullptr },
};
staticconstint g_buttonCount = (int)(sizeof(g_buttons) / sizeof(g_buttons[0]));
staticconstintkCalcRows = 7; // number of keypad rows (rows 1..7)
// ---------------------------------------------------------------------------
// Globals
// ---------------------------------------------------------------------------
staticconstwchar_t* kAppClass = L"NotepadCalcWindowClass";
staticconstwchar_t* kAppTitle = L"Notepad + Calculator (Win32)";
staticHWND g_hMainWnd = nullptr;
staticHWND g_hEdit = nullptr; // editor
staticHWND g_hStatus = nullptr; // status bar
staticHWND g_hCalcDisp = nullptr; // calculator display (read-only)
staticHFONT g_hFont = nullptr; // editor font
staticHFONT g_hBtnFont = nullptr; // keypad button font
staticHFONT g_hDispFont = nullptr; // calculator display font
static std::wstring g_filePath; // current document path ("" = untitled)
staticbool g_dirty = false;
staticbool g_panelOn = true; // calculator panel visible? (on by default)
staticbool g_undoTimerRunning = false; // checkpoint timer armed?
staticUINT g_undoIntervalMs = UNDO_GROUP_MS; // 0 = time checkpoints off
staticbool g_undoOnEnter = true; // checkpoint when Enter pressed
staticbool g_undoOnPunct = false; // checkpoint on . , ; : ! ?
// How "Evaluate Selection / Line" (Ctrl+E) inserts the answer.
enum EvalInsertMode {
EVAL_NEWLINE = 0, // add a new line below with "= result"
EVAL_APPEND, // append " = result" to the end of the same line
EVAL_REPLACE_FULL, // replace the evaluated text with "expr = result"
EVAL_REPLACE_RESULT// replace the evaluated text with just "result"
};
static EvalInsertMode g_evalMode = EVAL_NEWLINE;
// Calculator state.
static std::wstring g_calcExpr; // expression currently shown
static std::wstring g_lastExpr; // last successfully evaluated expression
static std::wstring g_lastResult; // last result
staticbool g_calcJustEvaluated = false; // result is showing; next input continues/restarts
// Pixel width reserved for the docked calculator panel.
staticconstintkPanelWidth = 250;
// ===========================================================================
// Expression evaluator: compact recursive-descent parser.
//
// grammar:
// expr := term (('+' | '-') term)*
// term := factor (('*' | '/' | '%') factor)*
// factor := '-' factor | '+' factor | primary
// primary:= number | '(' expr ')'
// ===========================================================================
classEvaluator {
public:
explicitEvaluator(const std::wstring& src) : s_(src), pos_(0) {}
doubleparse() {
double v = expr();
skipSpaces();
if (pos_ != s_.size())
throwstd::runtime_error("unexpected trailing characters");
return v;
}
private:
const std::wstring& s_;
size_t pos_;
voidskipSpaces() {
while (pos_ < s_.size() && iswspace(s_[pos_])) ++pos_;
}
wchar_tpeek() {
skipSpaces();
return pos_ < s_.size() ? s_[pos_] : L'\0';
}
doubleexpr() {
double v = term();
for (;;) {
wchar_t c = peek();
if (c == L'+') { ++pos_; v += term(); }
elseif (c == L'-') { ++pos_; v -= term(); }
elsebreak;
}
return v;
}
doubleterm() {
double v = factor();
for (;;) {
wchar_t c = peek();
if (c == L'*') { ++pos_; v *= factor(); }
elseif (c == L'/') {
++pos_;
double d = factor();
if (d == 0.0) throwstd::runtime_error("division by zero");
v /= d;
}
elseif (c == L'%') {
++pos_;
double d = factor();
if (d == 0.0) throwstd::runtime_error("modulo by zero");
v = std::fmod(v, d);
}
elsebreak;
}
return v;
}
doublefactor() {
wchar_t c = peek();
if (c == L'-') { ++pos_; return -factor(); }
if (c == L'+') { ++pos_; returnfactor(); }
returnprimary();
}
doubleprimary() {
wchar_t c = peek();
if (c == L'(') {
++pos_;
double v = expr();
if (peek() != L')') throwstd::runtime_error("missing ')'");
++pos_;
return v;
}
returnnumber();
}
doublenumber() {
skipSpaces();
size_t start = pos_;
bool sawDigit = false;
while (pos_ < s_.size() && iswdigit(s_[pos_])) { ++pos_; sawDigit = true; }
if (pos_ < s_.size() && s_[pos_] == L'.') {
++pos_;
while (pos_ < s_.size() && iswdigit(s_[pos_])) { ++pos_; sawDigit = true; }
}
if (sawDigit && pos_ < s_.size() && (s_[pos_] == L'e' || s_[pos_] == L'E')) {
size_t save = pos_;
++pos_;
if (pos_ < s_.size() && (s_[pos_] == L'+' || s_[pos_] == L'-')) ++pos_;
bool expDigit = false;
while (pos_ < s_.size() && iswdigit(s_[pos_])) { ++pos_; expDigit = true; }
if (!expDigit) pos_ = save;
}
if (!sawDigit) throwstd::runtime_error("expected a number");
returnstd::wcstod(s_.substr(start, pos_ - start).c_str(), nullptr);
}
};
// Try to evaluate; returns true on success and writes the formatted result.
staticboolTryEvaluate(const std::wstring& input, std::wstring& outResult) {
try {
Evaluator e(input);
double v = e.parse();
wchar_t buf[64];
if (v == std::floor(v) && std::fabs(v) < 1e15) {
swprintf(buf, 64, L"%.0f", v);
} else {
swprintf(buf, 64, L"%.10g", v);
}
outResult = buf;
returntrue;
} catch (const std::exception& ex) {
std::string msg = ex.what();
outResult.assign(msg.begin(), msg.end());
returnfalse;
}
}
// ===========================================================================
// Helpers
// ===========================================================================
staticvoidSetStatusText(int part, const std::wstring& text) {
if (g_hStatus)
SendMessageW(g_hStatus, SB_SETTEXTW, (WPARAM)part, (LPARAM)text.c_str());
}
staticvoidUpdateTitle() {
std::wstring t = kAppTitle;
t += L" - ";
t += g_filePath.empty() ? L"Untitled" : g_filePath;
if (g_dirty) t += L" *";
SetWindowTextW(g_hMainWnd, t.c_str());
}
staticvoidUpdateCaretStatus() {
DWORD selStart = 0, selEnd = 0;
SendMessageW(g_hEdit, EM_GETSEL, (WPARAM)&selStart, (LPARAM)&selEnd);
int line = (int)SendMessageW(g_hEdit, EM_LINEFROMCHAR, (WPARAM)selStart, 0);
int lineStart = (int)SendMessageW(g_hEdit, EM_LINEINDEX, (WPARAM)line, 0);
int col = (int)selStart - lineStart;
wchar_t buf[64];
swprintf(buf, 64, L"Ln %d, Col %d", line + 1, col + 1);
SetStatusText(0, buf);
}
static std::wstring GetEditText() {
int len = GetWindowTextLengthW(g_hEdit);
std::wstring s;
s.resize((size_t)len + 1);
// Use the actual number of characters copied: for Rich Edit the length
// hint can be an over-estimate, and we must not keep trailing nulls.
int copied = GetWindowTextW(g_hEdit, &s[0], len + 1);
s.resize((size_t)(copied < 0 ? 0 : copied));
return s;
}
staticvoidInsertAtCaret(const std::wstring& text) {
// Bracket the programmatic insert with EM_STOPGROUPTYPING so it forms its
// own undo step, separate from any typing before or after it.
SendMessageW(g_hEdit, EM_STOPGROUPTYPING, 0, 0);
SendMessageW(g_hEdit, EM_REPLACESEL, TRUE, (LPARAM)text.c_str());
SendMessageW(g_hEdit, EM_STOPGROUPTYPING, 0, 0);
}
// ---------------------------------------------------------------------------
// File operations
// ---------------------------------------------------------------------------
staticboolDoSaveToPath(const std::wstring& path) {
HANDLE h = CreateFileW(path.c_str(), GENERIC_WRITE, 0, nullptr,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (h == INVALID_HANDLE_VALUE) {
MessageBoxW(g_hMainWnd, L"Could not open file for writing.",
kAppTitle, MB_ICONERROR);
returnfalse;
}
std::wstring text = GetEditText();
int u8len = WideCharToMultiByte(CP_UTF8, 0, text.c_str(), (int)text.size(),
nullptr, 0, nullptr, nullptr);
std::string utf8;
utf8.resize((size_t)u8len);
WideCharToMultiByte(CP_UTF8, 0, text.c_str(), (int)text.size(),
&utf8[0], u8len, nullptr, nullptr);
DWORD written = 0;
constunsignedchar bom[3] = { 0xEF, 0xBB, 0xBF };
WriteFile(h, bom, 3, &written, nullptr);
if (!utf8.empty())
WriteFile(h, utf8.data(), (DWORD)utf8.size(), &written, nullptr);
CloseHandle(h);
g_filePath = path;
g_dirty = false;
UpdateTitle();
returntrue;
}
staticboolDoSaveAs() {
wchar_t file[MAX_PATH] = L"";
if (!g_filePath.empty())
wcsncpy_s(file, g_filePath.c_str(), _TRUNCATE);
OPENFILENAMEW ofn = {};
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = g_hMainWnd;
ofn.lpstrFilter = L"Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0";
ofn.lpstrFile = file;
ofn.nMaxFile = MAX_PATH;
ofn.lpstrDefExt = L"txt";
ofn.Flags = OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST;
if (!GetSaveFileNameW(&ofn)) returnfalse;
returnDoSaveToPath(file);
}
staticboolDoSave() {
if (g_filePath.empty()) returnDoSaveAs();
returnDoSaveToPath(g_filePath);
}
staticboolConfirmDiscard() {
if (!g_dirty) returntrue;
int r = MessageBoxW(g_hMainWnd,
L"You have unsaved changes. Save them now?",
kAppTitle, MB_YESNOCANCEL | MB_ICONWARNING);
if (r == IDCANCEL) returnfalse;
if (r == IDYES) returnDoSave();
returntrue;
}
staticvoidDoNew() {
if (!ConfirmDiscard()) return;
SetWindowTextW(g_hEdit, L"");
SendMessageW(g_hEdit, EM_EMPTYUNDOBUFFER, 0, 0);
g_filePath.clear();
g_dirty = false;
UpdateTitle();
}
staticvoidDoOpen() {
if (!ConfirmDiscard()) return;
wchar_t file[MAX_PATH] = L"";
OPENFILENAMEW ofn = {};
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = g_hMainWnd;
ofn.lpstrFilter = L"Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0";
ofn.lpstrFile = file;
ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
if (!GetOpenFileNameW(&ofn)) return;
HANDLE h = CreateFileW(file, GENERIC_READ, FILE_SHARE_READ, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (h == INVALID_HANDLE_VALUE) {
MessageBoxW(g_hMainWnd, L"Could not open file.", kAppTitle, MB_ICONERROR);
return;
}
DWORD size = GetFileSize(h, nullptr);
std::string raw;
raw.resize(size);
DWORD read = 0;
if (size > 0) ReadFile(h, &raw[0], size, &read, nullptr);
CloseHandle(h);
raw.resize(read);
constchar* data = raw.data();
int len = (int)raw.size();
if (len >= 3 && (unsignedchar)data[0] == 0xEF &&
(unsignedchar)data[1] == 0xBB && (unsignedchar)data[2] == 0xBF) {
data += 3;
len -= 3;
}
int wlen = MultiByteToWideChar(CP_UTF8, 0, data, len, nullptr, 0);
std::wstring wtext;
wtext.resize((size_t)wlen);
if (wlen > 0)
MultiByteToWideChar(CP_UTF8, 0, data, len, &wtext[0], wlen);
SetWindowTextW(g_hEdit, wtext.c_str());
SendMessageW(g_hEdit, EM_EMPTYUNDOBUFFER, 0, 0);
g_filePath = file;
g_dirty = false;
UpdateTitle();
}
// ---------------------------------------------------------------------------
// Calculator: keypad-driven
// ---------------------------------------------------------------------------
staticvoidRefreshCalcDisplay() {
SetWindowTextW(g_hCalcDisp, g_calcExpr.empty() ? L"0" : g_calcExpr.c_str());
}
// Append one character from a keypad press, with sensible behaviour right
// after a result is shown (digits/'(' start fresh; operators continue).
staticvoidCalcAppend(wchar_t c) {
bool startsNew = (iswdigit(c) || c == L'(' || c == L'.');
if (g_calcJustEvaluated) {
g_calcExpr = startsNew ? std::wstring() : g_lastResult;
g_calcJustEvaluated = false;
}
g_calcExpr.push_back(c);
RefreshCalcDisplay();
}
staticvoidCalcClear() {
g_calcExpr.clear();
g_calcJustEvaluated = false;
RefreshCalcDisplay();
}
staticvoidCalcBackspace() {
if (g_calcJustEvaluated) {
g_calcExpr.clear();
g_calcJustEvaluated = false;
} elseif (!g_calcExpr.empty()) {
g_calcExpr.pop_back();
}
RefreshCalcDisplay();
}
staticvoidCalcEquals() {
if (g_calcExpr.empty()) return;
std::wstring result;
if (TryEvaluate(g_calcExpr, result)) {
g_lastExpr = g_calcExpr; // remember the expression (the "variables")
g_lastResult = result; // ...and the answer
g_calcExpr = result; // show the answer; keep typing to continue
g_calcJustEvaluated = true;
RefreshCalcDisplay();
SetStatusText(1, g_lastExpr + L" = " + result);
} else {
MessageBeep(MB_ICONWARNING);
SetStatusText(1, L"Error: " + result);
}
}
// Insert the last completed calculation ("expression = answer") into the
// editor at the caret, replacing any selection.
staticvoidCalcInsertIntoNotepad() {
if (g_lastResult.empty()) {
MessageBeep(MB_ICONWARNING);
SetStatusText(1, L"No calculation to insert yet - press = first");
return;
}
std::wstring text = g_lastExpr + L" = " + g_lastResult;
SetFocus(g_hEdit);
InsertAtCaret(text); // marks the document dirty via EN_CHANGE
SetStatusText(1, L"Inserted: " + text);
}
// Dispatch a keypad button press by its command id.
staticboolHandleCalcButton(int id) {
for (int i = 0; i < g_buttonCount; ++i) {
if (g_buttons[i].id != id) continue;
switch (g_buttons[i].kind) {
caseK_CHAR: CalcAppend(g_buttons[i].ch); break;
caseK_CLEAR: CalcClear(); break;
caseK_BACK: CalcBackspace(); break;
caseK_EQUALS: CalcEquals(); break;
caseK_INSERT: CalcInsertIntoNotepad(); break;
}
returntrue;
}
returnfalse;
}
// Move the caret to the end of the line that contains character index `pos`.
staticvoidCaretToEndOfLine(DWORD pos) {
int line = (int)SendMessageW(g_hEdit, EM_LINEFROMCHAR, (WPARAM)pos, 0);
int lineStart = (int)SendMessageW(g_hEdit, EM_LINEINDEX, (WPARAM)line, 0);
int lineLen = (int)SendMessageW(g_hEdit, EM_LINELENGTH, (WPARAM)lineStart, 0);
DWORD eol = (DWORD)(lineStart + lineLen);
SendMessageW(g_hEdit, EM_SETSEL, eol, eol);
}
// Evaluate the editor's selection / current line (menu + Ctrl+E).
// How the answer is placed is controlled by g_evalMode (Calculator > Insert
// Result As).
staticvoidDoEvaluateSelection() {
// Work out the character range to evaluate and pull out its text. Rich
// Edit indexes a line break as one character internally, so we read the
// text through control messages (EM_GETSELTEXT / EM_GETLINE) rather than
// slicing the WM_GETTEXT string, whose "\r\n" indices would not line up.
CHARRANGE cr;
SendMessageW(g_hEdit, EM_EXGETSEL, 0, (LPARAM)&cr);
DWORD rangeStart, rangeEnd;
std::wstring src;
if (cr.cpMax > cr.cpMin) {
rangeStart = (DWORD)cr.cpMin;
rangeEnd = (DWORD)cr.cpMax;
src.resize((size_t)(cr.cpMax - cr.cpMin) + 1);
LRESULT n = SendMessageW(g_hEdit, EM_GETSELTEXT, 0, (LPARAM)&src[0]);
src.resize((size_t)(n < 0 ? 0 : n));
} else {
int line = (int)SendMessageW(g_hEdit, EM_LINEFROMCHAR, (WPARAM)cr.cpMin, 0);
int lineStart = (int)SendMessageW(g_hEdit, EM_LINEINDEX, (WPARAM)line, 0);
int lineLen = (int)SendMessageW(g_hEdit, EM_LINELENGTH, (WPARAM)lineStart, 0);
rangeStart = (DWORD)lineStart;
rangeEnd = (DWORD)(lineStart + lineLen);
if (lineLen > 0) {
src.resize((size_t)lineLen + 1);
// EM_GETLINE expects the buffer capacity (in chars) in its first WORD.
*reinterpret_cast<WORD*>(&src[0]) = (WORD)(lineLen + 1);
LRESULT n = SendMessageW(g_hEdit, EM_GETLINE, (WPARAM)line, (LPARAM)&src[0]);
src.resize((size_t)(n < 0 ? 0 : n));
}
}
size_t a = src.find_first_not_of(L"\t\r\n");
size_t b = src.find_last_not_of(L"\t\r\n");
if (a == std::wstring::npos) {
SetStatusText(1, L"Nothing to evaluate");
return;
}
std::wstring expr = src.substr(a, b - a + 1);
std::wstring result;
if (!TryEvaluate(expr, result)) {
SetStatusText(1, L"Error: " + result);
MessageBoxW(g_hMainWnd, (L"Could not evaluate expression:\n\n" +
expr + L"\n\n" + result).c_str(),
kAppTitle, MB_ICONWARNING);
return;
}
switch (g_evalMode) {
caseEVAL_NEWLINE:
// Leave the line untouched; add "= result" on the next line.
CaretToEndOfLine(rangeEnd);
InsertAtCaret(L"\r\n= " + result);
break;
caseEVAL_APPEND:
// Append " = result" to the end of the evaluated line.
CaretToEndOfLine(rangeEnd);
InsertAtCaret(L" = " + result);
break;
caseEVAL_REPLACE_FULL:
// Replace the evaluated text with "expr = result".
SendMessageW(g_hEdit, EM_SETSEL, (WPARAM)rangeStart, (LPARAM)rangeEnd);
InsertAtCaret(expr + L" = " + result);
break;
caseEVAL_REPLACE_RESULT:
// Replace the evaluated text with just the result.
SendMessageW(g_hEdit, EM_SETSEL, (WPARAM)rangeStart, (LPARAM)rangeEnd);
InsertAtCaret(result);
break;
}
SetStatusText(1, L"Result: " + result);
}
// ---------------------------------------------------------------------------
// Layout / sizing
// ---------------------------------------------------------------------------
staticvoidLayoutChildren() {
RECT rc;
GetClientRect(g_hMainWnd, &rc);
SendMessageW(g_hStatus, WM_SIZE, 0, 0);
RECT sr;
GetWindowRect(g_hStatus, &sr);
int statusH = sr.bottom - sr.top;
int bottom = rc.bottom - statusH;
int editWidth = rc.right;
if (g_panelOn) {
editWidth = rc.right - kPanelWidth;
if (editWidth < 100) editWidth = 100;
constint pad = 6;
constint gap = 4;
int panelX = editWidth;
int innerX = panelX + pad;
int innerW = rc.right - innerX - pad;
if (innerW < 40) innerW = 40;
// Display across the top of the panel.
int dispH = 46;
MoveWindow(g_hCalcDisp, innerX, pad, innerW, dispH, TRUE);
ShowWindow(g_hCalcDisp, SW_SHOW);
// Keypad grid below the display.
int buttonsTop = pad + dispH + gap;
int buttonsBottom = bottom - pad;
int rowH = (buttonsBottom - buttonsTop) / kCalcRows;
if (rowH < 24) rowH = 24;
int colW = innerW / 4;
for (int i = 0; i < g_buttonCount; ++i) {
CalcButton& btn = g_buttons[i];
int bx = innerX + btn.col * colW;
int by = buttonsTop + (btn.row - 1) * rowH;
int bw = btn.colspan * colW - gap;
int bh = rowH - gap;
MoveWindow(btn.hwnd, bx, by, bw, bh, TRUE);
ShowWindow(btn.hwnd, SW_SHOW);
}
} else {
ShowWindow(g_hCalcDisp, SW_HIDE);
for (int i = 0; i < g_buttonCount; ++i)
ShowWindow(g_buttons[i].hwnd, SW_HIDE);
}
MoveWindow(g_hEdit, 0, 0, editWidth, bottom, TRUE);
}
staticvoidTogglePanel() {
g_panelOn = !g_panelOn;
HMENU menu = GetMenu(g_hMainWnd);
CheckMenuItem(menu, IDM_CALC_PANEL,
MF_BYCOMMAND | (g_panelOn ? MF_CHECKED : MF_UNCHECKED));
LayoutChildren();
}
// Reflect the current insert mode as the checked radio item in the submenu.
staticvoidUpdateEvalModeMenu() {
HMENU menu = GetMenu(g_hMainWnd);
UINT selected = IDM_EVAL_NEWLINE;
switch (g_evalMode) {
caseEVAL_NEWLINE: selected = IDM_EVAL_NEWLINE; break;
caseEVAL_APPEND: selected = IDM_EVAL_APPEND; break;
caseEVAL_REPLACE_FULL: selected = IDM_EVAL_REPLACE_FULL; break;
caseEVAL_REPLACE_RESULT: selected = IDM_EVAL_REPLACE_RESULT; break;
}
CheckMenuRadioItem(menu, IDM_EVAL_NEWLINE, IDM_EVAL_REPLACE_RESULT,
selected, MF_BYCOMMAND);
}
// Reflect the undo-checkpoint settings in the Edit > Undo Checkpoints submenu.
staticvoidUpdateUndoMenu() {
HMENU menu = GetMenu(g_hMainWnd);
UINT sel = IDM_UNDO_TIME_1;
switch (g_undoIntervalMs) {
case0: sel = IDM_UNDO_TIME_OFF; break;
case500: sel = IDM_UNDO_TIME_05; break;
case1000: sel = IDM_UNDO_TIME_1; break;
case2000: sel = IDM_UNDO_TIME_2; break;
case5000: sel = IDM_UNDO_TIME_5; break;
}
CheckMenuRadioItem(menu, IDM_UNDO_TIME_OFF, IDM_UNDO_TIME_5, sel, MF_BYCOMMAND);
CheckMenuItem(menu, IDM_UNDO_ON_ENTER,
MF_BYCOMMAND | (g_undoOnEnter ? MF_CHECKED : MF_UNCHECKED));
CheckMenuItem(menu, IDM_UNDO_ON_PUNCT,
MF_BYCOMMAND | (g_undoOnPunct ? MF_CHECKED : MF_UNCHECKED));
}
// Change the time-based checkpoint interval (0 disables it). Any pending timer
// is cancelled so the new interval takes effect from the next edit.
staticvoidSetUndoInterval(UINT ms) {
g_undoIntervalMs = ms;
if (g_undoTimerRunning) {
KillTimer(g_hMainWnd, IDT_UNDO_GROUP);
g_undoTimerRunning = false;
}
UpdateUndoMenu();
}
// Characters that end an undo group when "On Punctuation" is enabled.
staticboolIsPunctCheckpoint(wchar_t c) {
return c == L'.' || c == L',' || c == L';' ||
c == L':' || c == L'!' || c == L'?';
}
// Subclass procedure for the editor: watches typed characters so we can close
// the undo group right after an Enter or a punctuation mark (when enabled).
staticLRESULTCALLBACKEditSubclassProc(HWND hWnd, UINT msg, WPARAM wParam,
LPARAM lParam, UINT_PTR uId, DWORD_PTR) {
if (msg == WM_CHAR) {
wchar_t ch = (wchar_t)wParam;
// Let the control insert the character first, then checkpoint.
LRESULT r = DefSubclassProc(hWnd, msg, wParam, lParam);
bool checkpoint =
(g_undoOnEnter && (ch == L'\r' || ch == L'\n')) ||
(g_undoOnPunct && IsPunctCheckpoint(ch));
if (checkpoint)
SendMessageW(hWnd, EM_STOPGROUPTYPING, 0, 0);
return r;
}
if (msg == WM_NCDESTROY)
RemoveWindowSubclass(hWnd, EditSubclassProc, uId);
returnDefSubclassProc(hWnd, msg, wParam, lParam);
}
// ---------------------------------------------------------------------------
// Menu construction
// ---------------------------------------------------------------------------
staticHMENUBuildMenu() {
HMENU menu = CreateMenu();
HMENU file = CreatePopupMenu();
AppendMenuW(file, MF_STRING, IDM_FILE_NEW, L"&New\tCtrl+N");
AppendMenuW(file, MF_STRING, IDM_FILE_OPEN, L"&Open...\tCtrl+O");
AppendMenuW(file, MF_STRING, IDM_FILE_SAVE, L"&Save\tCtrl+S");
AppendMenuW(file, MF_STRING, IDM_FILE_SAVEAS, L"Save &As...");
AppendMenuW(file, MF_SEPARATOR, 0, nullptr);
AppendMenuW(file, MF_STRING, IDM_FILE_EXIT, L"E&xit");
AppendMenuW(menu, MF_POPUP, (UINT_PTR)file, L"&File");
HMENU edit = CreatePopupMenu();
AppendMenuW(edit, MF_STRING, IDM_EDIT_UNDO, L"&Undo\tCtrl+Z");
AppendMenuW(edit, MF_STRING, IDM_EDIT_REDO, L"&Redo\tCtrl+Y");
AppendMenuW(edit, MF_SEPARATOR, 0, nullptr);
AppendMenuW(edit, MF_STRING, IDM_EDIT_CUT, L"Cu&t\tCtrl+X");
AppendMenuW(edit, MF_STRING, IDM_EDIT_COPY, L"&Copy\tCtrl+C");
AppendMenuW(edit, MF_STRING, IDM_EDIT_PASTE, L"&Paste\tCtrl+V");
AppendMenuW(edit, MF_STRING, IDM_EDIT_DELETE, L"&Delete\tDel");
AppendMenuW(edit, MF_SEPARATOR, 0, nullptr);
AppendMenuW(edit, MF_STRING, IDM_EDIT_SELALL, L"Select &All\tCtrl+A");
// Submenu: when typing runs are committed as undo checkpoints.
AppendMenuW(edit, MF_SEPARATOR, 0, nullptr);
HMENU undo = CreatePopupMenu();
AppendMenuW(undo, MF_STRING, IDM_UNDO_TIME_OFF, L"Time interval: &Off");
AppendMenuW(undo, MF_STRING, IDM_UNDO_TIME_05, L"Time interval: 0.&5 seconds");
AppendMenuW(undo, MF_STRING, IDM_UNDO_TIME_1, L"Time interval: &1 second");
AppendMenuW(undo, MF_STRING, IDM_UNDO_TIME_2, L"Time interval: &2 seconds");
AppendMenuW(undo, MF_STRING, IDM_UNDO_TIME_5, L"Time interval: 5 &seconds");
AppendMenuW(undo, MF_SEPARATOR, 0, nullptr);
AppendMenuW(undo, MF_STRING, IDM_UNDO_ON_ENTER, L"On &Enter / new line");
AppendMenuW(undo, MF_STRING, IDM_UNDO_ON_PUNCT, L"On &punctuation ( . , ; : ! ? )");
AppendMenuW(edit, MF_POPUP, (UINT_PTR)undo, L"Undo &Checkpoints");
AppendMenuW(menu, MF_POPUP, (UINT_PTR)edit, L"&Edit");
HMENU calc = CreatePopupMenu();
AppendMenuW(calc, MF_STRING, IDM_CALC_EVAL, L"&Evaluate Selection / Line\tCtrl+E");
// Submenu: how the evaluated answer is inserted.
HMENU evalAs = CreatePopupMenu();
AppendMenuW(evalAs, MF_STRING, IDM_EVAL_NEWLINE,
L"On a &new line below (\"= result\")");
AppendMenuW(evalAs, MF_STRING, IDM_EVAL_APPEND,
L"&Append to the line (\"... = result\")");
AppendMenuW(evalAs, MF_STRING, IDM_EVAL_REPLACE_FULL,
L"&Replace with \"expr = result\"");
AppendMenuW(evalAs, MF_STRING, IDM_EVAL_REPLACE_RESULT,
L"Replace with &result only");
AppendMenuW(calc, MF_POPUP, (UINT_PTR)evalAs, L"&Insert Result As");
AppendMenuW(calc, MF_SEPARATOR, 0, nullptr);
AppendMenuW(calc, MF_STRING | MF_CHECKED, IDM_CALC_PANEL,
L"Show Calculator &Panel\tCtrl+P");
AppendMenuW(menu, MF_POPUP, (UINT_PTR)calc, L"&Calculator");
HMENU help = CreatePopupMenu();
AppendMenuW(help, MF_STRING, IDM_HELP_ABOUT, L"&About");
AppendMenuW(menu, MF_POPUP, (UINT_PTR)help, L"&Help");
return menu;
}
// ---------------------------------------------------------------------------
// Keyboard accelerators
// ---------------------------------------------------------------------------
staticHACCELBuildAccelerators() {
ACCEL acc[] = {
{ FVIRTKEY | FCONTROL, 'N', IDM_FILE_NEW },
{ FVIRTKEY | FCONTROL, 'O', IDM_FILE_OPEN },
{ FVIRTKEY | FCONTROL, 'S', IDM_FILE_SAVE },
{ FVIRTKEY | FCONTROL, 'E', IDM_CALC_EVAL },
{ FVIRTKEY | FCONTROL, 'P', IDM_CALC_PANEL },
{ FVIRTKEY | FCONTROL, 'A', IDM_EDIT_SELALL },
{ FVIRTKEY | FCONTROL, 'Z', IDM_EDIT_UNDO },
{ FVIRTKEY | FCONTROL, 'Y', IDM_EDIT_REDO },
};
returnCreateAcceleratorTableW(acc, (int)(sizeof(acc) / sizeof(acc[0])));
}
// ===========================================================================
// Window procedure
// ===========================================================================
staticLRESULTCALLBACKWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
switch (msg) {
caseWM_CREATE: {
HINSTANCE hInst = ((LPCREATESTRUCT)lParam)->hInstance;
g_hFont = CreateFontW(-16, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY,
FIXED_PITCH | FF_MODERN, L"Consolas");
g_hBtnFont = CreateFontW(-18, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY,
VARIABLE_PITCH | FF_SWISS, L"Segoe UI");
g_hDispFont = CreateFontW(-24, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY,
FIXED_PITCH | FF_MODERN, L"Consolas");
// Main editor: a Rich Edit control. Unlike the plain EDIT control
// (single-level undo only), Rich Edit keeps a real undo/redo stack
// whose depth we set with EM_SETUNDOLIMIT.
g_hEdit = CreateWindowExW(
WS_EX_CLIENTEDGE, MSFTEDIT_CLASS, L"",
WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL |
ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_NOHIDESEL,
0, 0, 0, 0, hWnd, (HMENU)IDC_EDIT, hInst, nullptr);
SendMessageW(g_hEdit, WM_SETFONT, (WPARAM)g_hFont, TRUE);
SendMessageW(g_hEdit, EM_EXLIMITTEXT, 0, (LPARAM)0x7FFFFFFF); // lift the size cap
SendMessageW(g_hEdit, EM_SETUNDOLIMIT, (WPARAM)128, 0); // 128 undo/redo levels
// Rich Edit sends no notifications unless we ask: we want EN_CHANGE
// (dirty flag) and EN_SELCHANGE (caret position in the status bar).
SendMessageW(g_hEdit, EM_SETEVENTMASK, 0, ENM_CHANGE | ENM_SELCHANGE);
// Subclass the editor to watch typed Enter / punctuation for checkpoints.
SetWindowSubclass(g_hEdit, EditSubclassProc, 1, 0);
// Calculator display (read-only, right-aligned).
g_hCalcDisp = CreateWindowExW(
WS_EX_CLIENTEDGE, L"EDIT", L"0",
WS_CHILD | ES_RIGHT | ES_READONLY | ES_AUTOHSCROLL,
0, 0, 0, 0, hWnd, (HMENU)IDC_CALC_DISPLAY, hInst, nullptr);
SendMessageW(g_hCalcDisp, WM_SETFONT, (WPARAM)g_hDispFont, TRUE);
// Calculator keypad buttons.
for (int i = 0; i < g_buttonCount; ++i) {
g_buttons[i].hwnd = CreateWindowExW(
0, L"BUTTON", g_buttons[i].label,
WS_CHILD | BS_PUSHBUTTON,
0, 0, 0, 0, hWnd, (HMENU)(INT_PTR)g_buttons[i].id, hInst, nullptr);
SendMessageW(g_buttons[i].hwnd, WM_SETFONT, (WPARAM)g_hBtnFont, TRUE);
}
// Status bar with two parts.
g_hStatus = CreateWindowExW(
0, STATUSCLASSNAMEW, nullptr,
WS_CHILD | WS_VISIBLE | SBARS_SIZEGRIP,
0, 0, 0, 0, hWnd, (HMENU)IDC_STATUS, hInst, nullptr);
{
int parts[2] = { 160, -1 };
SendMessageW(g_hStatus, SB_SETPARTS, 2, (LPARAM)parts);
}
UpdateEvalModeMenu();
UpdateUndoMenu();
UpdateCaretStatus();
SetStatusText(1, L"Ready");
return0;
}
caseWM_SIZE:
LayoutChildren();
return0;
caseWM_SETFOCUS:
SetFocus(g_hEdit);
return0;
caseWM_NOTIFY: {
// Rich Edit reports caret/selection moves via EN_SELCHANGE.
NMHDR* nh = (NMHDR*)lParam;
if (nh->idFrom == IDC_EDIT && nh->code == EN_SELCHANGE)
UpdateCaretStatus();
return0;
}
caseWM_TIMER:
if (wParam == IDT_UNDO_GROUP) {
KillTimer(hWnd, IDT_UNDO_GROUP);
g_undoTimerRunning = false;
// Close the current typing run; the next keystroke starts a new
// undo action, giving ~1-second undo granularity.
SendMessageW(g_hEdit, EM_STOPGROUPTYPING, 0, 0);
}
return0;
caseWM_COMMAND: {
WORD id = LOWORD(wParam);
WORD code = HIWORD(wParam);
// Keypad button clicks.
if (code == BN_CLICKED && id >= IDC_CALC_BTN_BASE &&
id < IDC_CALC_BTN_BASE + g_buttonCount) {
HandleCalcButton(id);
return0;
}
// Editor notifications.
if (id == IDC_EDIT) {
if (code == EN_CHANGE) {
if (!g_dirty) { g_dirty = true; UpdateTitle(); }
UpdateCaretStatus();
// Arm a one-shot timer (if enabled and not already running).