-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
4980 lines (4609 loc) · 220 KB
/
Copy pathmain.cpp
File metadata and controls
4980 lines (4609 loc) · 220 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
#define NOMINMAX
#include <windows.h>
#include <commctrl.h>
#include <commdlg.h>
#include <richedit.h>
#include <shlobj.h>
#include <shobjidl.h>
#include <shellapi.h>
#include <algorithm>
#include <chrono>
#include <climits>
#include <cmath>
#include <cmath>
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <initializer_list>
#include <iomanip>
#include <initializer_list>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <regex>
#include <set>
#include <sstream>
#include <string>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
using std::optional;
namespace fs = std::filesystem;
#include "build_info.inc"
#include "nc_lexer.h"
#include "nc_modal_state.h"
#include "nc_events.h"
using nc::MachineModalState;
using nc::parseGcodeLine;
using nc::parseXY;
using nc::normalizeTokens;
using nc::normalizeTokensForWcs;
#include "nc_lexer.h"
#include "nc_modal_state.h"
#include "nc_events.h"
using nc::MachineModalState;
using nc::parseGcodeLine;
using nc::parseXY;
using nc::normalizeTokens;
using nc::normalizeTokensForWcs;
static constexpr COLORREF C_BG = RGB(240, 240, 240);
static constexpr COLORREF C_CARD = C_BG;
static constexpr COLORREF C_PRIMARY_DARK = RGB(0, 0, 0);
static constexpr COLORREF C_TEXT = RGB(0, 0, 0);
static constexpr COLORREF C_MUTED = RGB(96, 96, 96);
static constexpr COLORREF C_ERR = RGB(160, 0, 0);
static constexpr UINT_PTR TOOLTIP_TIMER_ID = 7001;
static constexpr UINT_PTR HOVER_POLL_TIMER_ID = 7002;
static constexpr UINT WM_APP_JOB_DONE = WM_APP + 101;
static constexpr UINT WM_APP_SHOW_TOOLTIP = WM_APP + 102;
static constexpr UINT WM_APP_JOB_PROGRESS = WM_APP + 103;
enum ControlId {
ID_BTN_NORMAL = 1001,
ID_BTN_MERGE,
ID_BTN_PREVIEW,
ID_BTN_TOPMOST,
ID_BTN_ADD_FILES,
ID_BTN_ADD_FOLDER,
ID_BTN_UP,
ID_BTN_DOWN,
ID_BTN_REMOVE,
ID_BTN_CLEAR,
ID_LIST_FILES,
ID_ALLOW_HH,
ID_FILTER_TRY,
ID_STRIP,
ID_OPEN_G28,
ID_END_DUAL,
ID_HH_STRIP,
ID_H_FORCE,
ID_CROSS_G43,
ID_SORT_H,
ID_SORT_FILE,
ID_SORT_Z_GLOBAL,
ID_SORT_Z_CLUSTER,
ID_SORT_SMART,
ID_APPEND_TRY,
ID_G54G56_MODE,
ID_G56_H_PLUS10,
ID_G54G56_LIFT_OFF,
ID_G54G56_LIFT_50,
ID_G54G56_LIFT_100,
ID_MULTI_WCS_CONFIG,
ID_EXP_COMP_ENABLE,
ID_EXP_COMP_CONFIG,
ID_SIDE_COMP_ENABLE,
ID_PRE_LEGACY,
ID_M00_WAIT_OFF,
ID_M00_WAIT_ALL,
ID_M00_WAIT_DRILL,
ID_G41_RISK_TEXT,
ID_PRE_LEGACY,
ID_PRE_OFF,
ID_PRE_NEXT,
ID_PRE_RING,
ID_TRAILING,
ID_TMAP,
ID_SILENT,
ID_NOVICE,
ID_LABEL_TRAILING,
ID_LABEL_TMAP,
ID_GROUP_HEAD,
ID_GROUP_SORT,
ID_GROUP_TOOL,
ID_GROUP_PARAMS,
ID_TABS,
ID_TEXT_NORMAL,
ID_TEXT_H,
ID_TEXT_HH,
ID_TEXT_LOG,
ID_G54G56_SECOND_AUTO,
ID_G54G56_SECOND_TOGGLE,
ID_G54G56_SECOND_G54,
ID_G54G56_SECOND_G56,
ID_SAFETY_AUDIT_ENABLE,
ID_SAFETY_AUDIT_STRICT,
ID_COMP_LIMIT_ENABLE,
ID_COMP_LIMIT_VALUE,
ID_BTN_SAFETY_REPORT,
ID_GROUP_SAFETY,
ID_SHOP_PRECHECK_INPUT,
ID_SHOP_KEYWORD_PREVIEW,
ID_SHOP_COORD_DRY_RUN,
ID_SHOP_G41_ENVELOPE,
ID_SHOP_AUTO_BACKUP,
ID_SHOP_CONFIG_SNAPSHOT,
ID_GROUP_TEMPLATE,
ID_TEMPLATE_COMBO,
ID_BTN_TEMPLATE_APPLY,
};
static std::wstring widen(const std::string& s) {
if (s.empty()) return {};
int n = MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), nullptr, 0);
if (n <= 0) return L"";
std::wstring w(n, L'\0');
MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), w.data(), n);
return w;
}
static std::string narrowUtf8(const std::wstring& w) {
if (w.empty()) return {};
int n = WideCharToMultiByte(CP_UTF8, 0, w.data(), (int)w.size(), nullptr, 0, nullptr, nullptr);
std::string s(n, '\0');
WideCharToMultiByte(CP_UTF8, 0, w.data(), (int)w.size(), s.data(), n, nullptr, nullptr);
return s;
}
static std::string bytesToUtf8(const std::string& bytes, UINT cp, DWORD flags = 0) {
if (bytes.empty()) return {};
int wn = MultiByteToWideChar(cp, flags, bytes.data(), (int)bytes.size(), nullptr, 0);
if (wn <= 0) return {};
std::wstring w(wn, L'\0');
if (!MultiByteToWideChar(cp, flags, bytes.data(), (int)bytes.size(), w.data(), wn)) return {};
return narrowUtf8(w);
}
static std::string readFileBytes(const fs::path& path) {
std::ifstream in(path, std::ios::binary | std::ios::ate);
if (!in) throw std::runtime_error("open failed: " + narrowUtf8(path.wstring()));
std::streamoff n = in.tellg();
if (n < 0) throw std::runtime_error("read size failed: " + narrowUtf8(path.wstring()));
std::string bytes((size_t)n, '\0');
in.seekg(0, std::ios::beg);
if (!bytes.empty()) {
in.read(bytes.data(), (std::streamsize)bytes.size());
if (!in || in.gcount() != (std::streamsize)bytes.size()) {
throw std::runtime_error("read failed: " + narrowUtf8(path.wstring()));
}
}
return bytes;
}
static std::vector<std::string> splitLines(const std::string& text) {
std::vector<std::string> out;
out.reserve((size_t)std::count(text.begin(), text.end(), '\n') + 1);
size_t start = 0;
while (start <= text.size()) {
size_t pos = text.find('\n', start);
std::string line = text.substr(start, pos == std::string::npos ? std::string::npos : pos - start);
if (!line.empty() && line.back() == '\r') line.pop_back();
out.push_back(line);
if (pos == std::string::npos) break;
start = pos + 1;
}
if (!out.empty() && out.back().empty() && !text.empty() && text.back() == '\n') out.pop_back();
return out;
}
static std::vector<std::string> splitLinesKeepEnds(const std::string& text) {
std::vector<std::string> out;
out.reserve((size_t)std::count(text.begin(), text.end(), '\n') + 1);
size_t start = 0;
while (start < text.size()) {
size_t pos = text.find('\n', start);
if (pos == std::string::npos) {
out.push_back(text.substr(start));
break;
}
out.push_back(text.substr(start, pos - start + 1));
start = pos + 1;
}
return out;
}
static std::string utf8IgnoreInvalid(const std::string& bytes) {
std::string out;
for (size_t i = 0; i < bytes.size();) {
unsigned char c = (unsigned char)bytes[i];
size_t len = 0;
if (c < 0x80) len = 1;
else if ((c & 0xE0) == 0xC0 && c >= 0xC2) len = 2;
else if ((c & 0xF0) == 0xE0) len = 3;
else if ((c & 0xF8) == 0xF0 && c <= 0xF4) len = 4;
else { ++i; continue; }
if (i + len > bytes.size()) break;
bool ok = true;
for (size_t j = 1; j < len; ++j) {
if (((unsigned char)bytes[i + j] & 0xC0) != 0x80) { ok = false; break; }
}
if (!ok) { ++i; continue; }
out.append(bytes, i, len);
i += len;
}
return out;
}
static std::vector<std::string> readTextLines(const fs::path& path) {
const std::string bytes = readFileBytes(path);
std::string text = bytesToUtf8(bytes, CP_UTF8, MB_ERR_INVALID_CHARS);
if (text.empty() && !bytes.empty()) text = bytesToUtf8(bytes, CP_ACP, 0);
if (text.empty() && !bytes.empty()) text = bytes;
return splitLines(text);
}
static std::vector<std::string> readNormalLines(const fs::path& path) {
return splitLinesKeepEnds(utf8IgnoreInvalid(readFileBytes(path)));
}
static void writeUtf8File(const fs::path& path, const std::string& text) {
std::ofstream out(path, std::ios::binary);
if (!out) throw std::runtime_error("write failed");
out.write(text.data(), (std::streamsize)text.size());
}
static std::string trim(const std::string& s) {
size_t a = 0, b = s.size();
while (a < b && std::isspace((unsigned char)s[a])) ++a;
while (b > a && std::isspace((unsigned char)s[b - 1])) --b;
return s.substr(a, b - a);
}
static std::string upperAscii(std::string s) {
for (char& c : s) c = (char)std::toupper((unsigned char)c);
return s;
}
static bool startsWith(const std::string& s, const std::string& prefix) {
return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
}
static bool endsWithLower(const std::wstring& s, const std::wstring& suffix) {
if (s.size() < suffix.size()) return false;
for (size_t i = 0; i < suffix.size(); ++i) {
wchar_t a = towlower(s[s.size() - suffix.size() + i]);
wchar_t b = towlower(suffix[i]);
if (a != b) return false;
}
return true;
}
static std::string baseNameUtf8(const fs::path& p) {
return narrowUtf8(p.filename().wstring());
}
static std::string formatGcodeVal(double val) {
if (std::abs(val - std::round(val)) < 1e-9) {
return std::to_string((long long)std::llround(val)) + ".";
}
std::ostringstream ss;
ss << std::setprecision(12) << val;
std::string s = ss.str();
while (s.find('.') != std::string::npos && !s.empty() && s.back() == '0') s.pop_back();
return s;
}
struct Segment {
std::string src_fn;
fs::path src_path;
optional<std::string> tool_comment;
optional<std::string> dia_comment;
optional<std::string> date_comment;
optional<std::string> wcs;
optional<std::string> g0_no_wcs_etc;
optional<std::string> g0_xy_etc;
optional<std::string> g43_line;
optional<int> h_num;
std::vector<std::string> cutting_body;
optional<double> first_cut_z;
optional<std::string> machine_time;
optional<std::string> cutting_time;
std::pair<optional<double>, optional<double>> g0_xy;
bool has_drill_cycle = false; // 是否包含G81/G83/G84钻孔循环
};
bool has_drill_cycle = false; // 是否包含G81/G83/G84钻孔循环
};
static constexpr const char* SORT_H_ASC = "H_ASC";
static constexpr const char* SORT_FILE = "FILE";
static constexpr const char* SORT_Z_GLOBAL = "Z_GLOBAL";
static constexpr const char* SORT_Z_CLUSTER = "Z_CLUSTER";
static constexpr const char* SORT_SMART_AUTO = "SMART_AUTO";
static constexpr const char* PRESELECT_OFF = "OFF";
static constexpr const char* PRESELECT_LEGACY = "LEGACY";
static constexpr const char* PRESELECT_NEXT = "NEXT";
static constexpr const char* PRESELECT_RING = "RING";
// M00 wait mode
static constexpr const char* M00_WAIT_OFF = "OFF";
static constexpr const char* M00_WAIT_ALL_TOOLS = "ALL_TOOLS";
static constexpr const char* M00_WAIT_DRILL_ONLY = "DRILL_ONLY";
// G41 刀损补偿速度/安全策略:0 最危险最快,4 最安全。
static constexpr const char* G41_RISK_EXTREME = "EXTREME"; // 极限速度: 自动开 G41 后不自动关 G40
static constexpr const char* G41_RISK_FAST = "FAST"; // 偏快: 旧版兼容,段末才 G40
static constexpr const char* G41_RISK_BALANCED = "BALANCED"; // 平衡: G0/固定循环/停机前 G40
static constexpr const char* G41_RISK_SAFE = "SAFE"; // 偏安全: 再加纯 Z 前 G40
static constexpr const char* G41_RISK_SAFEST = "SAFEST"; // 安全: 当前保守策略,G0/纯Z/固定循环/G2G3前 G40
static constexpr const char* G41_CLOSE_SEGMENT = G41_RISK_FAST; // 兼容旧 CLI
static constexpr const char* G41_CLOSE_ADAPTIVE = G41_RISK_SAFEST; // 兼容旧 CLI
static constexpr const char* SECOND_WCS_AUTO = "AUTO";
static constexpr const char* SECOND_WCS_TOGGLE = "TOGGLE";
static constexpr const char* SECOND_WCS_G54 = "G54";
static constexpr const char* SECOND_WCS_G56 = "G56";
struct TipDef {
int id;
const char* key;
const char* text;
};
static const std::vector<TipDef>& tooltipDefs() {
static const std::vector<TipDef> defs = {
#include "py_tooltips.inc"
};
return defs;
}
static const char* tooltipUtf8ForId(int id) {
for (const auto& def : tooltipDefs()) {
if (def.id == id) return def.text;
}
return nullptr;
}
static void dumpTooltipsFile(const fs::path& path) {
auto esc = [](const char* s) {
std::string out;
for (const char* p = s; *p; ++p) {
if (*p == '\\') out += "\\\\";
else if (*p == '\n') out += "\\n";
else if (*p == '\t') out += "\\t";
else out.push_back(*p);
}
return out;
};
std::ostringstream ss;
for (const auto& def : tooltipDefs()) {
ss << def.id << "\t" << def.key << "\t" << esc(def.text) << "\n";
}
writeUtf8File(path, ss.str());
}
struct WorkOffsetConfig {
std::string wcs;
int h_offset = 0;
};
struct ExperimentalCompensation {
std::string wcs;
double x = 0.0;
double y = 0.0;
double z = 0.0;
};
struct MergeOptions {
std::string version = "H";
bool strip_header_g49g80 = true;
bool open_g28 = true;
bool end_dual_axis = true;
bool hh_strip_f4000 = true;
bool h_force_f4000 = true;
bool g54g56_mode = false;
bool end_zero_zero = false;
int g54g56_lift_z = 0;
std::vector<WorkOffsetConfig> work_offsets = {{"G54", 0}, {"G56", 10}};
bool experimental_compensation = false;
std::vector<ExperimentalCompensation> compensations;
bool side_compensation_g41 = false;
std::string preselect_mode = PRESELECT_LEGACY;
std::string m00_wait_mode = M00_WAIT_OFF; // M00暂停模式
std::string g41_close_strategy = G41_RISK_BALANCED; // G41刀损补偿策略,默认平衡速度和风险
std::string preselect_mode = PRESELECT_LEGACY;
std::string sort_strategy = SORT_H_ASC;
bool append_try_knife_at_end = false;
bool safety_audit_report = false;
bool safety_audit_strict = false;
bool compensation_limit_check = false;
double compensation_limit_abs = 0.10;
bool shop_precheck_input = false;
bool shop_keyword_preview = false;
bool shop_coord_dry_run = false;
bool shop_g41_envelope = false;
bool shop_auto_backup = false;
bool shop_config_snapshot = false;
std::string config_template_name;
int trailing_blank_lines = 1;
std::map<std::string, int> tool_t_map;
};
enum class JobKind { Normal, Merge, Preview, Load, Safety };
struct JobResult {
JobKind kind = JobKind::Normal;
bool ok = false;
std::wstring status;
std::wstring logMessage;
std::wstring outDir;
std::wstring errorTitle;
std::wstring errorMessage;
std::string normalText;
std::string hText;
std::string hhText;
std::string safetyText;
std::vector<fs::path> loadedFiles;
int added = 0;
int skippedHh = 0;
int skippedTry = 0;
int skippedOther = 0;
};
static bool isTryKnifeName(const std::string& fn) {
std::string low = upperAscii(fn);
return low.size() >= 7 && low.rfind("-11.PTP") == low.size() - 7;
}
static bool isFlyingKnifeSeg(const Segment& seg) {
return isTryKnifeName(seg.src_fn) && seg.h_num && *seg.h_num == 1;
}
static Segment parseSegment(const std::vector<std::string>& lines, const std::string& srcFn, const fs::path& path) {
static const std::regex g0Any(R"(^G0(?=[\sA-Z])\s*(.+)$)");
static const std::regex g43(R"(^G43\s*Z[\d\.\-]+\s*H(\d+)(\s*.*)?$)");
static const std::regex zInline(R"(^G[01](?:\s|G\d+|X[\d\.\-]+|Y[\d\.\-]+)*\s*Z([\d\.\-]+))");
static const std::regex zLead(R"(^Z([\d\.\-]+))");
Segment seg;
seg.src_fn = srcFn;
seg.src_path = path;
for (size_t j = 0; j < lines.size(); ++j) {
std::string s = trim(lines[j]);
if (s.empty()) continue;
if (s[0] == '(') {
if (!seg.tool_comment && startsWith(s, "(Tool")) seg.tool_comment = s;
else if (!seg.dia_comment && startsWith(s, "(===") && s.find("DIA") != std::string::npos) seg.dia_comment = s;
else if (!seg.date_comment && startsWith(s, "(Date")) seg.date_comment = s;
else if (s.find("MACHINE-TIME") != std::string::npos) seg.machine_time = s;
else if (s.find("CUTTING-TIME") != std::string::npos) seg.cutting_time = s;
continue;
}
if (!seg.g0_xy_etc) {
std::smatch m;
if (std::regex_match(s, m, g0Any)) {
std::vector<std::string> kept;
std::vector<std::string> noWcs;
for (const auto& t : normalizeTokens(m[1].str())) {
if (t == "G54" || t == "G55" || t == "G56" || t == "G57" || t == "G58" || t == "G59") {
if (!seg.wcs) seg.wcs = t;
if (t != "G54") kept.push_back(t);
continue;
} else {
if (t != "G90") kept.push_back(t);
if (t != "G90") noWcs.push_back(t);
}
}
if (!seg.wcs || noWcs.empty()) {
noWcs.clear();
for (const auto& t : normalizeTokensForWcs(m[1].str())) {
if (t == "G54" || t == "G55" || t == "G56" || t == "G57" || t == "G58" || t == "G59") {
if (!seg.wcs) seg.wcs = t;
continue;
}
if (t != "G90") noWcs.push_back(t);
}
}
std::ostringstream ss;
for (size_t i = 0; i < kept.size(); ++i) {
if (i) ss << ' ';
ss << kept[i];
}
seg.g0_xy_etc = ss.str();
std::ostringstream nw;
for (size_t i = 0; i < noWcs.size(); ++i) {
if (i) nw << ' ';
nw << noWcs[i];
}
seg.g0_no_wcs_etc = nw.str();
seg.g0_xy = parseXY(*seg.g0_xy_etc);
}
}
if (!seg.g43_line) {
std::smatch m;
if (std::regex_match(s, m, g43)) {
seg.g43_line = s;
try { seg.h_num = std::stoi(m[1].str()); } catch (...) { seg.h_num.reset(); }
for (size_t k = j + 1; k < lines.size(); ++k) {
if (startsWith(trim(lines[k]), "M05")) break;
seg.cutting_body.push_back(lines[k]);
}
// 修复 #25: 钻孔检测与首切 Z 提取分离,钻孔检测必须遍历整个 body
for (const auto& bl : seg.cutting_body) {
std::string bs = trim(bl);
// 检测钻孔/镗孔固定循环 G81-G89
for (const auto& t : parseGcodeLine(bs)) {
if (t.ch == 'G' && t.val >= 81.0 && t.val <= 89.0) {
seg.has_drill_cycle = true;
break;
}
}
if (seg.has_drill_cycle) break; // 已找到钻孔,可提前退出
}
// 提取第一个 Z 坐标(独立循环,不受钻孔检测影响)
}
// 修复 #25: 钻孔检测与首切 Z 提取分离,钻孔检测必须遍历整个 body
for (const auto& bl : seg.cutting_body) {
std::string bs = trim(bl);
// 检测钻孔/镗孔固定循环 G81-G89
for (const auto& t : parseGcodeLine(bs)) {
if (t.ch == 'G' && t.val >= 81.0 && t.val <= 89.0) {
seg.has_drill_cycle = true;
break;
}
}
if (seg.has_drill_cycle) break; // 已找到钻孔,可提前退出
}
// 提取第一个 Z 坐标(独立循环,不受钻孔检测影响)
for (const auto& bl : seg.cutting_body) {
std::string bs = trim(bl);
std::smatch zm;
if (std::regex_search(bs, zm, zInline) || std::regex_search(bs, zm, zLead)) {
try { seg.first_cut_z = std::stod(zm[1].str()); } catch (...) {}
break; // 只需首个 Z
}
}
}
}
return seg;
}
static std::string g0PayloadForWcs(const Segment& seg, const std::string& wcs) {
(void)wcs;
return seg.g0_no_wcs_etc.value_or(seg.g0_xy_etc.value_or(""));
}
static std::string extractToolName(const std::string& toolComment) {
static const std::regex re(R"(\(Tool\s*=\s*([^\)]+)\))");
std::smatch m;
return std::regex_match(toolComment, m, re) ? trim(m[1].str()) : "";
}
static bool isAxisBoundaryBefore(const std::string& line, size_t pos) {
if (pos == 0) return true;
unsigned char prev = (unsigned char)line[pos - 1];
return std::isspace(prev) || line[pos - 1] == ',' || line[pos - 1] == ';';
}
static std::string replaceHNumber(std::string line, int hNum) {
std::ostringstream h;
h << "H" << std::setw(2) << std::setfill('0') << hNum;
static const std::regex hRe(R"(H\s*\d+)");
return std::regex_replace(line, hRe, h.str(), std::regex_constants::format_first_only);
}
static std::string dTokenText(int dNum) {
std::ostringstream d;
d << "D" << std::setw(2) << std::setfill('0') << dNum;
return d.str();
}
static std::string replaceDNumber(std::string line, int dNum) {
if (dNum <= 0) return line;
std::string d = dTokenText(dNum);
bool inComment = false;
for (size_t i = 0; i < line.size(); ++i) {
if (line[i] == '(') { inComment = true; continue; }
if (inComment) { if (line[i] == ')') inComment = false; continue; }
if ((line[i] == 'D' || line[i] == 'd') && isAxisBoundaryBefore(line, i)) {
size_t start = i + 1;
while (start < line.size() && std::isspace((unsigned char)line[start])) ++start;
size_t end = start;
while (end < line.size() && std::isdigit((unsigned char)line[end])) ++end;
if (end > start) { line.replace(i, end - i, d); return line; }
}
}
return line;
}
static std::string ensureG41DNumber(std::string line, int dNum) {
if (dNum <= 0) return line;
bool inComment = false;
optional<size_t> g41End;
for (size_t i = 0; i < line.size(); ++i) {
if (line[i] == '(') { inComment = true; continue; }
if (inComment) { if (line[i] == ')') inComment = false; continue; }
if ((line[i] == 'D' || line[i] == 'd') && isAxisBoundaryBefore(line, i)) return replaceDNumber(std::move(line), dNum);
if ((line[i] == 'G' || line[i] == 'g') && isAxisBoundaryBefore(line, i)) {
size_t j = i + 1;
while (j < line.size() && line[j] == '0') ++j;
if (j + 1 < line.size() && line[j] == '4' && line[j + 1] == '1') {
size_t k = j + 2;
if (k >= line.size() || !std::isdigit((unsigned char)line[k])) g41End = k;
}
}
}
if (g41End) line.insert(*g41End, " " + dTokenText(dNum));
return line;
}
static std::string toolGroupKey(const Segment& seg) {
std::string name = upperAscii(extractToolName(seg.tool_comment.value_or("")));
if (name.size() > 1 && name.back() == 'X') name.pop_back();
if (name.empty()) return "H" + std::to_string(seg.h_num.value_or(0));
return name;
}
static bool shouldUsePairedCoordinates(const Segment& a, const Segment& b) {
std::string ta = upperAscii(extractToolName(a.tool_comment.value_or("")));
std::string tb = upperAscii(extractToolName(b.tool_comment.value_or("")));
return (!ta.empty() && !tb.empty() && ta != tb && toolGroupKey(a) == toolGroupKey(b));
}
static std::string formatLiftZLikeOriginal(const std::string& original, bool hasG0, int liftZ, bool hasG40) {
std::ostringstream ss;
if (hasG0) ss << "G0 ";
ss << "Z" << liftZ;
static const std::regex zRe(R"(Z[-+]?\d+(\.\d*)?)");
std::smatch m;
if (std::regex_search(original, m, zRe) && m[1].matched) ss << m[1].str();
if (hasG40) ss << "G40";
return ss.str();
}
static std::vector<std::string> cuttingBodyForG54G56(const Segment& seg, int liftZ) {
std::vector<std::string> body = seg.cutting_body;
if (liftZ <= 0) return body;
for (auto it = body.rbegin(); it != body.rend(); ++it) {
std::string s = trim(*it);
if (s.empty()) continue;
std::smatch m;
static const std::regex zOnlyRe(R"(^(G0\s*)?Z[-+]?\d+(?:\.\d*)?(G40)?$)");
if (std::regex_match(s, m, zOnlyRe)) {
bool hasG0 = m[1].matched;
bool hasG40 = m[2].matched;
*it = formatLiftZLikeOriginal(s, hasG0, liftZ, hasG40);
}
break;
}
return body;
}
static std::string adjustG0ForG54G56(std::string line, const Segment& seg, const MergeOptions& opts) {
(void)seg;
(void)opts;
return line;
}
static std::string upperWcs(std::string s) {
s = upperAscii(trim(s));
static const std::regex basic("^G5[4-9]$");
std::smatch m;
static const std::regex ext(R"(^G54\.1\s*P\s*([1-9]|[1-3][0-9]|4[0-8])$)");
if (std::regex_match(s, basic)) return s;
if (std::regex_match(s, m, ext)) return "G54.1 P" + m[1].str();
throw std::runtime_error("坐标系格式错(仅支持 G54-G59 / G54.1 P1-P48): " + s);
}
static std::vector<WorkOffsetConfig> parseWorkOffsetConfigText(const std::string& raw) {
std::vector<WorkOffsetConfig> out;
std::set<std::string> seen;
std::stringstream ss(raw);
for (std::string piece; std::getline(ss, piece, ',');) {
piece = trim(piece);
if (piece.empty()) continue;
auto pos = piece.find(':');
if (pos == std::string::npos) throw std::runtime_error("多坐标配置格式错: " + piece);
std::string wcs = upperWcs(piece.substr(0, pos));
// 修复 #31: stoi 必须完整消费,拒绝 "10.5"/"10abc"/"0x10"
std::string numStr = trim(piece.substr(pos + 1));
size_t consumed = 0;
int offset = 0;
try {
offset = std::stoi(numStr, &consumed);
} catch (const std::exception&) {
throw std::runtime_error("多坐标 offset 非法: " + piece);
}
if (consumed != numStr.size()) {
throw std::runtime_error("多坐标 offset 含非法字符(必须为纯整数): " + piece);
}
if (offset < -199 || offset > 199) throw std::runtime_error("多坐标 offset 超范围(-199..199): " + piece);
if (!seen.insert(wcs).second) throw std::runtime_error("多坐标配置重复: " + wcs);
out.push_back({wcs, offset});
if (out.size() > 48) throw std::runtime_error("多坐标配置最多支持 48 项");
}
if (out.empty()) throw std::runtime_error("多坐标配置不能为空");
return out;
}
static std::string formatWorkOffsetConfigText(const std::vector<WorkOffsetConfig>& cfg) {
std::ostringstream ss;
for (size_t i = 0; i < cfg.size(); ++i) {
if (i) ss << ',';
ss << cfg[i].wcs << ':' << cfg[i].h_offset;
}
return ss.str();
}
static double parseStrictDouble(const std::string& raw, const std::string& label);
static void enforceExperimentalCompensationHardCap(const ExperimentalCompensation& comp);
static std::vector<ExperimentalCompensation> parseCompensationConfigText(const std::string& raw) {
std::vector<ExperimentalCompensation> out;
std::set<std::string> seenWcs;
std::stringstream ss(raw);
for (std::string piece; std::getline(ss, piece, ';');) {
piece = trim(piece);
if (piece.empty()) throw std::runtime_error("坐标补偿配置存在空项");
std::stringstream fields(piece);
std::string wcsPart;
if (!std::getline(fields, wcsPart, ':')) throw std::runtime_error("实验性补偿格式错: " + piece);
ExperimentalCompensation comp;
comp.wcs = upperWcs(wcsPart);
if (!seenWcs.insert(comp.wcs).second) throw std::runtime_error("坐标补偿配置重复: " + comp.wcs);
std::set<char> seenAxis;
bool sawAxis = false;
for (std::string field; std::getline(fields, field, ':');) {
field = trim(field);
if (field.size() < 2) throw std::runtime_error("实验性补偿字段格式错: " + piece);
char axis = (char)std::toupper((unsigned char)field[0]);
if (axis != 'X' && axis != 'Y' && axis != 'Z') throw std::runtime_error("实验性补偿轴错误: " + field);
if (!seenAxis.insert(axis).second) throw std::runtime_error("坐标补偿配置重复轴: " + comp.wcs + " " + axis);
double value = parseStrictDouble(field.substr(1), "坐标补偿数值");
if (axis == 'X') comp.x = value;
else if (axis == 'Y') comp.y = value;
else comp.z = value;
sawAxis = true;
}
if (!sawAxis) throw std::runtime_error("坐标补偿配置缺少轴: " + piece);
out.push_back(comp);
}
return out;
}
static std::string formatCompensationConfigText(const std::vector<ExperimentalCompensation>& cfg) {
std::ostringstream ss;
for (size_t i = 0; i < cfg.size(); ++i) {
if (i) ss << ';';
ss << cfg[i].wcs << ":X" << cfg[i].x << ":Y" << cfg[i].y << ":Z" << cfg[i].z;
}
return ss.str();
}
static std::string normalizeTemplateKey(std::string name) {
name = upperAscii(trim(name));
for (char& c : name) if (c == ' ' || c == '-' || c == '/') c = '_';
return name;
}
static void applyConfigTemplate(MergeOptions& opts, const std::string& rawName) {
std::string key = normalizeTemplateKey(rawName);
if (key.empty() || key == "NONE" || key == "OFF") return;
opts.config_template_name = rawName;
if (key == "M70_SAFE" || rawName == "M70默认安全") {
opts.g41_close_strategy = G41_CLOSE_ADAPTIVE;
opts.side_compensation_g41 = true;
opts.safety_audit_report = true;
opts.compensation_limit_check = true;
opts.compensation_limit_abs = 0.10;
opts.shop_precheck_input = true;
opts.shop_keyword_preview = true;
opts.shop_coord_dry_run = true;
opts.shop_g41_envelope = true;
return;
}
if (key == "G54G56_H10" || key == "G54_G56_H10" || rawName == "G54/G56 H+10") {
opts.g54g56_mode = true;
opts.work_offsets = {{"G54", 0}, {"G56", 10}};
opts.g54g56_lift_z = 100;
opts.shop_keyword_preview = true;
opts.shop_coord_dry_run = true;
return;
}
if (key == "MULTI_WCS" || rawName == "多工位 G54/G56/G55") {
opts.g54g56_mode = true;
opts.work_offsets = {{"G54", 0}, {"G56", 10}, {"G55", 20}};
opts.g54g56_lift_z = 100;
opts.shop_keyword_preview = true;
opts.shop_coord_dry_run = true;
return;
}
if (key == "DRILL_PAUSE" || rawName == "钻孔刀暂停") {
opts.m00_wait_mode = M00_WAIT_DRILL_ONLY;
opts.preselect_mode = PRESELECT_NEXT;
opts.safety_audit_report = true;
opts.shop_keyword_preview = true;
opts.shop_precheck_input = true;
return;
}
if (key == "MASTER_COMPAT" || rawName == "老师傅兼容") {
opts.g54g56_mode = false;
opts.side_compensation_g41 = false;
opts.g41_close_strategy = G41_CLOSE_SEGMENT;
opts.m00_wait_mode = M00_WAIT_OFF;
opts.preselect_mode = PRESELECT_LEGACY;
opts.shop_precheck_input = true;
opts.shop_keyword_preview = true;
return;
}
throw std::runtime_error("未知配置模板: " + rawName);
}
struct CompensationLimitIssue {
std::string severity;
std::string text;
};
static std::vector<CompensationLimitIssue> scanCompensationLimitIssues(const MergeOptions& opts) {
std::vector<CompensationLimitIssue> issues;
if (!opts.compensation_limit_check) return issues;
if (!std::isfinite(opts.compensation_limit_abs) || opts.compensation_limit_abs < 0.0) {
issues.push_back({"ERROR", "坐标补偿限值配置无效,最大允许绝对值必须为非负数"});
return issues;
}
auto checkAxis = [&](const std::string& wcs, char axis, double value) {
if (std::abs(value) > opts.compensation_limit_abs + 1e-12) {
std::ostringstream ss;
ss << "坐标补偿超限: " << wcs << ' ' << axis << formatGcodeVal(value)
<< ",允许 |delta| <= " << formatGcodeVal(opts.compensation_limit_abs);
issues.push_back({opts.safety_audit_strict ? "ERROR" : "WARN", ss.str()});
}
};
for (const auto& comp : opts.compensations) {
checkAxis(comp.wcs, 'X', comp.x);
checkAxis(comp.wcs, 'Y', comp.y);
checkAxis(comp.wcs, 'Z', comp.z);
}
return issues;
}
static double parseStrictDouble(const std::string& raw, const std::string& label) {
std::string s = trim(raw);
if (s.empty()) throw std::runtime_error(label + "不能为空");
try {
size_t consumed = 0;
double v = std::stod(s, &consumed);
if (consumed != s.size() || !std::isfinite(v)) throw std::runtime_error("");
return v;
} catch (...) {
throw std::runtime_error(label + "填写无效,请输入纯数字");
}
}
static int parseStrictInt(const std::string& raw, const std::string& label, int lo, int hi) {
std::string s = trim(raw);
if (s.empty()) throw std::runtime_error(label + "不能为空");
try {
size_t consumed = 0;
long v = std::stol(s, &consumed);
if (consumed != s.size() || v < lo || v > hi) throw std::runtime_error("");
return (int)v;
} catch (...) {
throw std::runtime_error(label + "必须是 " + std::to_string(lo) + "-" + std::to_string(hi) + " 的整数");
}
}
static void writeCliWarning(const std::string& message);
static void writeCliWarning(const std::string& message);
static void enforceCompensationLimitForOutput(const MergeOptions& opts, bool writeWarnings) {
auto issues = scanCompensationLimitIssues(opts);
for (const auto& issue : issues) {
if (writeWarnings) writeCliWarning(issue.severity + ": " + issue.text + "\n");
if (issue.severity == "ERROR" || issue.severity == "FATAL") {
throw std::runtime_error(issue.text);
}
}
}
static void enforceExperimentalCompensationHardCap(const ExperimentalCompensation& comp) {
constexpr double kExperimentalCompHardCap = 5.0;
auto check = [&](char axis, double value) {
if (std::abs(value) > kExperimentalCompHardCap + 1e-12) {
std::ostringstream ss;
ss << "实验性坐标补偿幅值超硬上限: " << comp.wcs << ' ' << axis << formatGcodeVal(value)
<< ",硬上限 |delta| <= " << formatGcodeVal(kExperimentalCompHardCap);
throw std::runtime_error(ss.str());
}
};
check('X', comp.x); check('Y', comp.y); check('Z', comp.z);
}
static std::string applyAxisDelta(std::string line, char axis, double delta) {
if (std::abs(delta) < 1e-12) return line;
bool inComment = false;
for (size_t i = 0; i < line.size(); ++i) {
if (line[i] == '(') { inComment = true; continue; }
if (inComment) {
if (line[i] == ')') inComment = false;
continue;
}
if ((char)std::toupper((unsigned char)line[i]) != axis) continue;
if (!isAxisBoundaryBefore(line, i)) continue;
size_t start = i + 1;
while (start < line.size() && std::isspace((unsigned char)line[start])) ++start;
size_t end = start;
if (end < line.size() && (line[end] == '+' || line[end] == '-')) ++end;
bool hasDigit = false;
while (end < line.size() && (std::isdigit((unsigned char)line[end]) || line[end] == '.')) {
if (std::isdigit((unsigned char)line[end])) hasDigit = true;
++end;
}
if (!hasDigit) continue;
std::string tok = line.substr(start, end - start);
double v = 0.0;
try {
size_t consumed = 0;
v = std::stod(tok, &consumed);
if (consumed != tok.size()) continue;
} catch (...) {
continue;
}
line.replace(start, end - start, formatGcodeVal(v + delta));
return line;
}
return line;
}
static void applyExperimentalCompensation(std::string& line, const std::string& wcs, const MergeOptions& opts, bool forceSkipZ = false) {
if (!opts.experimental_compensation) return;
bool skipZ = forceSkipZ;
for (const auto& t : parseGcodeLine(line)) {
if (t.ch != 'G') continue;
if (std::abs(t.val - 0.0) < 1e-9 || std::abs(t.val - 43.0) < 1e-9 || (t.val >= 81.0 && t.val <= 89.0)) {
skipZ = true;
}
}
for (const auto& comp : opts.compensations) {
if (comp.wcs != wcs) continue;
line = applyAxisDelta(line, 'X', comp.x);
line = applyAxisDelta(line, 'Y', comp.y);
if (!skipZ) line = applyAxisDelta(line, 'Z', comp.z);
return;
}
}
static void applyExperimentalCompensation(std::vector<std::string>& lines, const std::string& wcs, const MergeOptions& opts) {
if (!opts.experimental_compensation) return;
int motion = -1;
for (auto& line : lines) {
for (const auto& t : parseGcodeLine(line)) {
if (t.ch == 'G' && std::abs(t.val - 0.0) < 1e-9) motion = 0;
else if (t.ch == 'G' && std::abs(t.val - 1.0) < 1e-9) motion = 1;
}
applyExperimentalCompensation(line, wcs, opts, motion == 0);
}
}
static std::string upperWcs(std::string s) {