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
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
# SPDX-License-Identifier: LGPL-2.1-or-later

# ***************************************************************************
# *   Copyright (c) 2014 Yorik van Havre <yorik@uncreated.net>              *
# *   Copyright (c) 2014 sliptonic <shopinthewoods@gmail.com>               *
# *   Copyright (c) 2015 Dan Falck <ddfalck@gmail.com>                      *
# *   Copyright (c) 2018, 2019 Gauthier Briere                              *
# *   Copyright (c) 2019, 2020 Schildkroet                                  *
# *   Copyright (c) 2022-2025 Larry Woestman <LarryWoestman2@gmail.com>     *
# *                                                                         *
# *   This file is part of the FreeCAD CAx development system.              *
# *                                                                         *
# *   This program is free software; you can redistribute it and/or modify  *
# *   it under the terms of the GNU Lesser General Public License (LGPL)    *
# *   as published by the Free Software Foundation; either version 2 of     *
# *   the License, or (at your option) any later version.                   *
# *   for detail see the LICENCE text file.                                 *
# *                                                                         *
# *   FreeCAD is distributed in the hope that it will be useful,            *
# *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
# *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
# *   GNU Lesser General Public License for more details.                   *
# *                                                                         *
# *   You should have received a copy of the GNU Library General Public     *
# *   License along with FreeCAD; if not, write to the Free Software        *
# *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
# *   USA                                                                   *
# *                                                                         *
# ***************************************************************************

"""
These are functions related to arguments and values for creating custom post processors.
"""
import argparse
import os
import shlex
from typing import Any, Callable, Dict, Tuple, Union

from FreeCAD import Units

import Path.Post.UtilsParse as PostUtilsParse

# Define some types that are used throughout this file
PathParameter = float
PathParameters = Dict[str, PathParameter]
Parser = argparse.ArgumentParser
Values = Dict[str, Any]

ParameterFunction = Callable[[Values, str, str, PathParameter, PathParameters], str]


def add_flag_type_arguments(
    argument_group,
    default_flag: bool,
    true_argument: str,
    false_argument: str,
    true_help: str,
    false_help: str,
    visible: bool = True,
) -> None:
    """Create an argument specification for an argument that is a flag."""
    if visible:
        if default_flag:
            true_help += " (default)"
        else:
            false_help += " (default)"
    else:
        true_help = false_help = argparse.SUPPRESS
    argument_group.add_argument(true_argument, action="store_true", help=true_help)
    argument_group.add_argument(false_argument, action="store_true", help=false_help)


def init_argument_defaults(argument_defaults: Dict[str, bool]) -> None:
    """Initialize which argument to show as the default in flag-type arguments."""
    argument_defaults["axis-modal"] = False
    argument_defaults["bcnc"] = False
    argument_defaults["comments"] = True
    argument_defaults["enable_coolant"] = False
    argument_defaults["enable_machine_specific_commands"] = False
    argument_defaults["header"] = True
    argument_defaults["line-numbers"] = False
    argument_defaults["list_tools_in_preamble"] = False
    argument_defaults["metric_inches"] = True
    argument_defaults["modal"] = False
    argument_defaults["output_all_arguments"] = False
    argument_defaults["output_machine_name"] = False
    argument_defaults["output_path_labels"] = False
    argument_defaults["output_visible_arguments"] = False
    argument_defaults["show-editor"] = True
    argument_defaults["split_arcs"] = False
    argument_defaults["tlo"] = True
    argument_defaults["tool_change"] = True
    argument_defaults["translate_drill"] = False


def init_arguments_visible(arguments_visible: Dict[str, bool]) -> None:
    """Initialize the flags for which arguments are visible in the arguments tooltip."""
    arguments_visible["axis-modal"] = True
    arguments_visible["axis-precision"] = True
    arguments_visible["bcnc"] = False
    arguments_visible["chipbreaking_amount"] = False
    arguments_visible["command_space"] = False
    arguments_visible["comments"] = True
    arguments_visible["comment_symbol"] = False
    arguments_visible["enable_coolant"] = False
    arguments_visible["enable_machine_specific_commands"] = False
    arguments_visible["end_of_line_characters"] = False
    arguments_visible["feed-precision"] = True
    arguments_visible["finish_label"] = False
    arguments_visible["header"] = True
    arguments_visible["line_number_increment"] = False
    arguments_visible["line_number_start"] = False
    arguments_visible["line-numbers"] = True
    arguments_visible["list_tools_in_preamble"] = False
    arguments_visible["metric_inches"] = True
    arguments_visible["modal"] = True
    arguments_visible["output_all_arguments"] = True
    arguments_visible["output_machine_name"] = False
    arguments_visible["output_path_labels"] = False
    arguments_visible["output_visible_arguments"] = True
    arguments_visible["postamble"] = True
    arguments_visible["post_operation"] = False
    arguments_visible["preamble"] = True
    arguments_visible["precision"] = True
    arguments_visible["return-to"] = False
    arguments_visible["show-editor"] = True
    arguments_visible["split_arcs"] = True
    arguments_visible["tlo"] = True
    arguments_visible["tool_change"] = False
    arguments_visible["translate_drill"] = False
    arguments_visible["wait-for-spindle"] = False


def init_shared_arguments(
    values: Values,
    argument_defaults: Dict[str, bool],
    arguments_visible: Dict[str, bool],
) -> Parser:
    """Initialize the arguments for postprocessors."""
    help_message: str
    parser: Parser
    shared: argparse._ArgumentGroup

    parser = argparse.ArgumentParser(
        prog=values["MACHINE_NAME"], usage=argparse.SUPPRESS, add_help=False
    )
    shared = parser.add_argument_group("Arguments that are commonly used")
    add_flag_type_arguments(
        shared,
        argument_defaults["metric_inches"],
        "--metric",
        "--inches",
        "Convert output for Metric mode (G21)",
        "Convert output for US imperial mode (G20)",
        arguments_visible["metric_inches"],
    )
    add_flag_type_arguments(
        shared,
        argument_defaults["axis-modal"],
        "--axis-modal",
        "--no-axis-modal",
        "Don't output axis values if they are the same as the previous line",
        "Output axis values even if they are the same as the previous line",
        arguments_visible["axis-modal"],
    )
    if arguments_visible["axis-precision"]:
        help_message = (
            f"Number of digits of precision for axis moves, "
            f'default is {str(values["DEFAULT_AXIS_PRECISION"])}'
        )
    else:
        help_message = argparse.SUPPRESS
    shared.add_argument(
        "--axis-precision",
        default=-1,
        type=int,
        help=help_message,
    )
    add_flag_type_arguments(
        shared,
        argument_defaults["bcnc"],
        "--bcnc",
        "--no-bcnc",
        (
            "Add Job operations as bCNC block headers. "
            "Consider suppressing comments by adding --no-comments"
        ),
        "Suppress bCNC block header output",
        arguments_visible["bcnc"],
    )
    if arguments_visible["chipbreaking_amount"]:
        help_message = (
            "Amount to move for chipbreaking in a translated G73 command, "
            f'default is {str(values["CHIPBREAKING_AMOUNT"])}'
        )
    else:
        help_message = argparse.SUPPRESS
    shared.add_argument(
        "--chipbreaking_amount",
        help=help_message,
    )
    if arguments_visible["command_space"]:
        help_message = (
            "The character to use between parts of a command, "
            "default is a space, may also use a null string"
        )
    else:
        help_message = argparse.SUPPRESS
    shared.add_argument(
        "--command_space",
        default=" ",
        help=help_message,
    )
    add_flag_type_arguments(
        shared,
        argument_defaults["comments"],
        "--comments",
        "--no-comments",
        "Output comments",
        "Suppress comment output",
        arguments_visible["comments"],
    )
    if arguments_visible["comment_symbol"]:
        help_message = (
            f'The character used to start a comment, default is "{values["COMMENT_SYMBOL"]}"'
        )
    else:
        help_message = argparse.SUPPRESS
    shared.add_argument(
        "--comment_symbol",
        help=help_message,
    )
    add_flag_type_arguments(
        shared,
        argument_defaults["enable_coolant"],
        "--enable_coolant",
        "--disable_coolant",
        "Enable coolant",
        "Disable coolant",
        arguments_visible["enable_coolant"],
    )
    add_flag_type_arguments(
        shared,
        argument_defaults["enable_machine_specific_commands"],
        "--enable_machine_specific_commands",
        "--disable_machine_specific_commands",
        "Enable machine specific commands of the form (MC_RUN_COMMAND: blah)",
        "Disable machine specific commands",
        arguments_visible["enable_machine_specific_commands"],
    )
    if arguments_visible["end_of_line_characters"]:
        help_message = (
            "The character(s) to use at the end of each line in the output file, "
            "default is whatever the system uses, may also use '\\n', '\\r', or '\\r\\n'"
        )
    else:
        help_message = argparse.SUPPRESS
    shared.add_argument(
        "--end_of_line_characters",
        help=help_message,
    )
    if arguments_visible["feed-precision"]:
        help_message = (
            f"Number of digits of precision for feed rate, "
            f'default is {str(values["DEFAULT_FEED_PRECISION"])}'
        )
    else:
        help_message = argparse.SUPPRESS
    shared.add_argument(
        "--feed-precision",
        default=-1,
        type=int,
        help=help_message,
    )
    if arguments_visible["finish_label"]:
        help_message = (
            "The characters to use in the 'Finish operation' comment, "
            f'default is "{values["FINISH_LABEL"]}"'
        )
    else:
        help_message = argparse.SUPPRESS
    shared.add_argument(
        "--finish_label",
        help=help_message,
    )
    add_flag_type_arguments(
        shared,
        argument_defaults["header"],
        "--header",
        "--no-header",
        "Output headers",
        "Suppress header output",
        arguments_visible["header"],
    )
    if arguments_visible["line_number_increment"]:
        help_message = (
            f'Amount to increment the line numbers, default is {str(values["LINE_INCREMENT"])}'
        )
    else:
        help_message = argparse.SUPPRESS
    shared.add_argument(
        "--line_number_increment",
        default=-1,
        type=int,
        help=help_message,
    )
    if arguments_visible["line_number_start"]:
        help_message = (
            f'The number the line numbers start at, default is {str(values["line_number"])}'
        )
    else:
        help_message = argparse.SUPPRESS
    shared.add_argument(
        "--line_number_start",
        default=-1,
        type=int,
        help=help_message,
    )
    add_flag_type_arguments(
        shared,
        argument_defaults["line-numbers"],
        "--line-numbers",
        "--no-line-numbers",
        "Prefix with line numbers",
        "Don't prefix with line numbers",
        arguments_visible["line-numbers"],
    )
    add_flag_type_arguments(
        shared,
        argument_defaults["list_tools_in_preamble"],
        "--list_tools_in_preamble",
        "--no-list_tools_in_preamble",
        "List the tools used in the operation in the preamble",
        "Don't list the tools used in the operation",
        arguments_visible["list_tools_in_preamble"],
    )
    add_flag_type_arguments(
        shared,
        argument_defaults["modal"],
        "--modal",
        "--no-modal",
        "Don't output the G-command name if it is the same as the previous line",
        "Output the G-command name even if it is the same as the previous line",
        arguments_visible["modal"],
    )
    add_flag_type_arguments(
        shared,
        argument_defaults["output_all_arguments"],
        "--output_all_arguments",
        "--no-output_all_arguments",
        "Output all of the available arguments",
        "Don't output all of the available arguments",
        arguments_visible["output_all_arguments"],
    )
    add_flag_type_arguments(
        shared,
        argument_defaults["output_machine_name"],
        "--output_machine_name",
        "--no-output_machine_name",
        "Output the machine name in the pre-operation information",
        "Don't output the machine name in the pre-operation information",
        arguments_visible["output_machine_name"],
    )
    add_flag_type_arguments(
        shared,
        argument_defaults["output_path_labels"],
        "--output_path_labels",
        "--no-output_path_labels",
        "Output Path labels at the beginning of each Path",
        "Don't output Path labels at the beginning of each Path",
        arguments_visible["output_path_labels"],
    )
    add_flag_type_arguments(
        shared,
        argument_defaults["output_visible_arguments"],
        "--output_visible_arguments",
        "--no-output_visible_arguments",
        "Output all of the visible arguments",
        "Don't output the visible arguments",
        arguments_visible["output_visible_arguments"],
    )
    if arguments_visible["postamble"]:
        help_message = (
            f"Set commands to be issued after the last command, "
            f'default is "{values["POSTAMBLE"]}"'
        )
    else:
        help_message = argparse.SUPPRESS
    shared.add_argument("--postamble", help=help_message)
    if arguments_visible["post_operation"]:
        help_message = (
            f"Set commands to be issued after every operation, "
            f'default is "{values["POST_OPERATION"]}"'
        )
    else:
        help_message = argparse.SUPPRESS
    shared.add_argument("--post_operation", help=help_message)
    if arguments_visible["preamble"]:
        help_message = (
            f"Set commands to be issued before the first command, "
            f'default is "{values["PREAMBLE"]}"'
        )
    else:
        help_message = argparse.SUPPRESS
    shared.add_argument("--preamble", help=help_message)
    # The --precision argument is included for backwards compatibility with some
    # postprocessors.  If both --axis-precision and --precision are provided, the
    # --axis-precision value "wins".  If both --feed-precision and --precision are
    # provided, the --feed-precision value "wins".
    if arguments_visible["precision"]:
        help_message = (
            f"Number of digits of precision for both feed rate and axis "
            f'moves, default is {str(values["DEFAULT_AXIS_PRECISION"])} for metric or '
            f'{str(values["DEFAULT_INCH_AXIS_PRECISION"])} for inches'
        )
    else:
        help_message = argparse.SUPPRESS
    shared.add_argument(
        "--precision",
        default=-1,
        type=int,
        help=help_message,
    )
    if arguments_visible["return-to"]:
        help_message = (
            "Move to the specified x,y,z coordinates at the end, e.g. "
            "--return-to=0,0,0 (default is do not move)"
        )
    else:
        help_message = argparse.SUPPRESS
    shared.add_argument("--return-to", default="", help=help_message)
    add_flag_type_arguments(
        shared,
        argument_defaults["show-editor"],
        "--show-editor",
        "--no-show-editor",
        "Pop up editor before writing output",
        "Don't pop up editor before writing output",
        arguments_visible["show-editor"],
    )
    add_flag_type_arguments(
        shared,
        argument_defaults["split_arcs"],
        "--split-arcs",
        "--no-split-arcs",
        "Convert G2/G3 arc commands to discrete G1 line segments",
        "Output G2/G3 arc commands as-is",
        arguments_visible["split_arcs"],
    )
    add_flag_type_arguments(
        shared,
        argument_defaults["tlo"],
        "--tlo",
        "--no-tlo",
        "Output tool length offset (G43) following tool changes",
        "Suppress tool length offset (G43) following tool changes",
        arguments_visible["tlo"],
    )
    add_flag_type_arguments(
        shared,
        argument_defaults["tool_change"],
        "--tool_change",
        "--no-tool_change",
        "Insert M6 and any other tool change G-code for all tool changes",
        "Convert M6 to a comment for all tool changes",
        arguments_visible["tool_change"],
    )
    add_flag_type_arguments(
        shared,
        argument_defaults["translate_drill"],
        "--translate_drill",
        "--no-translate_drill",
        "Translate drill cycles G73, G81, G82 & G83 into G0/G1 movements",
        "Don't translate drill cycles G73, G81, G82 & G83 into G0/G1 movements",
        arguments_visible["translate_drill"],
    )
    if arguments_visible["wait-for-spindle"]:
        help_message = "Time to wait (in seconds) after M3, M4 (default = 0.0)"
    else:
        help_message = argparse.SUPPRESS
    shared.add_argument("--wait-for-spindle", type=float, default=0.0, help=help_message)
    return parser


def init_shared_values(values: Values) -> None:
    """Initialize the default values in postprocessors."""
    #
    # The starting axis precision is 3 digits after the decimal point.
    #
    values["AXIS_PRECISION"] = 3
    #
    # How far to move up (in millimeters) in the Z axis when chipbreaking
    # with a G73 command.
    #
    values["CHIPBREAKING_AMOUNT"] = Units.Quantity(0.25, Units.Length)

    #
    # If this is set to "", all spaces are removed from between commands and parameters.
    #
    values["COMMAND_SPACE"] = " "
    #
    # The character that indicates a comment.  While "(" is the most common,
    # ";" is also used.
    #
    values["COMMENT_SYMBOL"] = "("
    #
    # Default axis precision for metric is 3 digits after the decimal point.
    # (see http://linuxcnc.org/docs/2.7/html/gcode/overview.html#_g_code_best_practices)
    #
    values["DEFAULT_AXIS_PRECISION"] = 3
    #
    # The default precision for feed is also set to 3 for metric.
    #
    values["DEFAULT_FEED_PRECISION"] = 3
    #
    # Default axis precision for inch/imperial is 4 digits after the decimal point.
    #
    values["DEFAULT_INCH_AXIS_PRECISION"] = 4
    #
    # The default precision for feed is also set to 4 for inch/imperial.
    #
    values["DEFAULT_INCH_FEED_PRECISION"] = 4
    #
    # If TRANSLATE_DRILL_CYCLES is True, these are the drill cycles
    # that get translated to G0 and G1 commands.
    #
    values["DRILL_CYCLES_TO_TRANSLATE"] = ["G73", "G81", "G82", "G83"]
    #
    # If this is set to True, then M7, M8, and M9 commands
    # to enable/disable coolant will be output.
    #
    values["ENABLE_COOLANT"] = False
    #
    # If this is set to True, then commands that are placed in
    # comments that look like (MC_RUN_COMMAND: blah) will be output.
    #
    values["ENABLE_MACHINE_SPECIFIC_COMMANDS"] = False
    #
    # By default the line ending characters of the output file(s)
    # are written to match the system that the postprocessor runs on.
    # This is indicated by a value of "\n".  If you need to force the line ending
    # characters to a specific value, set this variable to "\n\n" (meaning "use \n"),
    # "\r" or "\r\n" instead.
    #
    values["END_OF_LINE_CHARACTERS"] = "\n"
    #
    # The starting precision for feed is also set to 3 digits after the decimal point.
    #
    values["FEED_PRECISION"] = 3
    #
    # This value shows up in the post_op comment as "Finish operation:".
    # At least one postprocessor changes it to "End" to produce "End operation:".
    #
    values["FINISH_LABEL"] = "Finish"
    #
    # The line number increment value
    #
    values["LINE_INCREMENT"] = 10
    #
    # The line number starting value
    #
    values["line_number"] = 100
    #
    # If this value is True, then a list of tool numbers
    # with their labels are output just before the preamble.
    #
    values["LIST_TOOLS_IN_PREAMBLE"] = False
    #
    # The name of the machine the postprocessor is for
    #
    values["MACHINE_NAME"] = "unknown machine"
    #
    # If this value is true G-code commands are suppressed if they are
    # the same as the previous line.
    #
    values["MODAL"] = False
    #
    # This defines the motion commands that might change the X, Y, and Z position.
    #
    values["MOTION_COMMANDS"] = [
        "G0",
        "G00",
        "G1",
        "G01",
        "G2",
        "G02",
        "G3",
        "G03",
    ]
    #
    # Keeps track of the motion mode currently in use.
    # G90 for absolute moves, G91 for relative
    #
    values["MOTION_MODE"] = "G90"
    #
    # If True enables special processing for operations with "Adaptive" in the name
    #
    values["OUTPUT_ADAPTIVE"] = False
    #
    # If True adds bCNC operation block headers to the output G-code file.
    #
    values["OUTPUT_BCNC"] = False
    #
    # If True output comments.  If False comments are suppressed.
    #
    values["OUTPUT_COMMENTS"] = True
    #
    # If True output blank lines.  If False blank lines are suppressed.
    #
    values["OUTPUT_BLANK_LINES"] = True
    #
    # if False duplicate axis values or feeds are suppressed
    # if they are the same as the previous line.
    #
    values["OUTPUT_DOUBLES"] = True
    #
    # If True output the machine name in the pre_op
    #
    values["OUTPUT_MACHINE_NAME"] = False
    #
    # If True output a header at the front of the G-code file.
    # The header contains comments similar to:
    #   (Exported by FreeCAD)
    #   (Post Processor: centroid_post)
    #   (Cam File: box.fcstd)
    #   (Output Time:2020-01-01 01:02:03.123456)
    #
    values["OUTPUT_HEADER"] = True
    #
    # If True output line numbers at the front of each line.
    # If False do not output line numbers.
    #
    values["OUTPUT_LINE_NUMBERS"] = False
    #
    # If True output Path labels at the beginning of each Path.
    #
    values["OUTPUT_PATH_LABELS"] = False
    #
    # If True output tool change G-code for M6 commands followed
    # by any commands in the "TOOL_CHANGE" value.
    # If False output the M6 command as a comment and do not output
    # any commands in the "TOOL_CHANGE" value.
    #
    values["OUTPUT_TOOL_CHANGE"] = True
    #
    # This dictionary/hash holds the functions that are used
    # to process the G-code parameter values
    #
    values["PARAMETER_FUNCTIONS"] = {}
    PostUtilsParse.init_parameter_functions(values["PARAMETER_FUNCTIONS"])
    #
    # This list controls the order of parameters in a line during output.
    #
    values["PARAMETER_ORDER"] = [
        "D",
        "H",
        "L",
        "X",
        "Y",
        "Z",
        "A",
        "B",
        "C",
        "U",
        "V",
        "W",
        "I",
        "J",
        "K",
        "R",
        "P",
        "E",
        "Q",
        "F",
        "S",
        "T",
    ]
    #
    # Any commands in this value will be output as the last commands
    # in the G-code file.
    #
    values["POSTAMBLE"] = """"""
    #
    # Any commands in this value will be output after the operation(s).
    #
    values["POST_OPERATION"] = """"""
    #
    # Any commands in this value will be output after the header and
    # safety block at the beginning of the G-code file.
    #
    values["PREAMBLE"] = """"""
    #
    # Any commands in this value will be output before the operation(s).
    #
    values["PRE_OPERATION"] = """"""
    #
    # Defines which G-code commands are considered "rapid" moves.
    #
    values["RAPID_MOVES"] = ["G0", "G00"]
    #
    # Any commands in this value are output after the operation(s)
    # and post_operation commands are output but before the
    # TOOLRETURN, SAFETYBLOCK, and POSTAMBLE.
    #
    values["RETURN_TO"] = None
    #
    # Any commands in this value are output after the header but before the preamble,
    # then again after the TOOLRETURN but before the POSTAMBLE.
    #
    values["SAFETYBLOCK"] = """"""
    #
    # If True then the G-code editor widget is shown before writing
    # the G-code to the file.
    #
    values["SHOW_EDITOR"] = True
    #
    # If True then G2/G3 arc commands will be converted to discrete G1 line segments.
    #
    values["SPLIT_ARCS"] = False
    #
    # If True then the current machine units are output just before the PRE_OPERATION.
    #
    values["SHOW_MACHINE_UNITS"] = True
    #
    # If True then the current operation label is output just before the PRE_OPERATION
    # and just before the POST_OPERATION.
    #
    values["SHOW_OPERATION_LABELS"] = True
    #
    # The number of decimal places to use when outputting the speed (S) parameter.
    #
    values["SPINDLE_DECIMALS"] = 0
    #
    # The amount of time (in seconds) to wait after turning on the spindle
    # using an M3 or M4 command (a floating point number).
    #
    values["SPINDLE_WAIT"] = 0.0
    #
    # If true then then an M5 command to stop the spindle is output
    # after the M6 tool change command and before the TOOL_CHANGE commands.
    #
    values["STOP_SPINDLE_FOR_TOOL_CHANGE"] = True
    #
    # These commands are ignored by commenting them out.
    # Used when replacing the drill commands by G0 and G1 commands, for example.
    #
    values["SUPPRESS_COMMANDS"] = []
    #
    # Any commands in this value are output after the M6 command
    # when changing at tool (if OUTPUT_TOOL_CHANGE is True).
    #
    values["TOOL_CHANGE"] = """"""
    #
    # Any commands in this value are output after the POST_OPERATION,
    # RETURN_TO, and OUTPUT_BCNC and before the SAFETYBLOCK and POSTAMBLE.
    #
    values["TOOLRETURN"] = """"""
    #
    # If true, G81, G82 & G83 drill moves are translated into G0/G1 moves.
    #
    values["TRANSLATE_DRILL_CYCLES"] = False
    #
    # These values keep track of whether we are in Metric mode (G21)
    # or inches/imperial mode (G20).
    #
    values["UNITS"] = "G21"
    values["UNIT_FORMAT"] = "mm"
    values["UNIT_SPEED_FORMAT"] = "mm/min"
    #
    # If true a tool length command (G43) will be output following tool changes.
    #
    values["USE_TLO"] = True


def process_shared_arguments(
    values: Values,
    parser: Parser,
    argstring: str,
    all_visible: Parser,
    filename: str,
) -> Tuple[bool, Union[None, str, argparse.Namespace]]:
    """Process the arguments to the postprocessor."""
    args: argparse.Namespace
    argument_text: str
    v: str

    try:
        args = parser.parse_args(shlex.split(argstring))
        if args.output_all_arguments:
            argument_text = all_visible.format_help()
            if not filename == "-":
                with open(
                    filename,
                    "w",
                    encoding="utf-8",
                ) as f:
                    f.write(argument_text)
            return (False, argument_text)
        if args.output_visible_arguments:
            argument_text = parser.format_help()
            if not filename == "-":
                with open(
                    filename,
                    "w",
                    encoding="utf-8",
                ) as f:
                    f.write(argument_text)
            return (False, argument_text)
        # Default to metric unless an argument overrides it
        values["UNITS"] = "G21"
        if args.metric:
            values["UNITS"] = "G21"
        if args.inches:
            values["UNITS"] = "G20"
        if values["UNITS"] == "G21":
            values["UNIT_FORMAT"] = "mm"
            values["UNIT_SPEED_FORMAT"] = "mm/min"
        elif values["UNITS"] == "G20":
            values["UNIT_FORMAT"] = "in"
            values["UNIT_SPEED_FORMAT"] = "in/min"
        # The precision-related arguments need to be processed
        # after the metric/inches arguments are processed.
        # If both --axis-precision and --precision are given,
        # the --axis-precision argument "wins".
        if args.axis_precision != -1:
            values["AXIS_PRECISION"] = args.axis_precision
        elif args.precision != -1:
            values["AXIS_PRECISION"] = args.precision
        else:
            if values["UNITS"] == "G21":
                values["AXIS_PRECISION"] = values["DEFAULT_AXIS_PRECISION"]
            if values["UNITS"] == "G20":
                values["AXIS_PRECISION"] = values["DEFAULT_INCH_AXIS_PRECISION"]
        # If both --feed-precision and --precision are given,
        # the --feed-precision argument "wins".
        if args.feed_precision != -1:
            values["FEED_PRECISION"] = args.feed_precision
        elif args.precision != -1:
            values["FEED_PRECISION"] = args.precision
        else:
            if values["UNITS"] == "G21":
                values["FEED_PRECISION"] = values["DEFAULT_FEED_PRECISION"]
            elif values["UNITS"] == "G20":
                values["FEED_PRECISION"] = values["DEFAULT_INCH_FEED_PRECISION"]
        if args.axis_modal:
            values["OUTPUT_DOUBLES"] = False
        if args.no_axis_modal:
            values["OUTPUT_DOUBLES"] = True
        if args.bcnc:
            values["OUTPUT_BCNC"] = True
        if args.no_bcnc:
            values["OUTPUT_BCNC"] = False
        if args.chipbreaking_amount:
            values["CHIPBREAKING_AMOUNT"] = Units.parseQuantity(args.chipbreaking_amount)
        values["COMMAND_SPACE"] = args.command_space
        if args.comments:
            values["OUTPUT_COMMENTS"] = True
        if args.no_comments:
            values["OUTPUT_COMMENTS"] = False
        if args.comment_symbol:
            values["COMMENT_SYMBOL"] = args.comment_symbol
        if args.enable_coolant:
            values["ENABLE_COOLANT"] = True
        if args.disable_coolant:
            values["ENABLE_COOLANT"] = False
        if args.enable_machine_specific_commands:
            values["ENABLE_MACHINE_SPECIFIC_COMMANDS"] = True
        if args.disable_machine_specific_commands:
            values["ENABLE_MACHINE_SPECIFIC_COMMANDS"] = False
        if args.end_of_line_characters:
            if args.end_of_line_characters == "\\n" or args.end_of_line_characters == "\n":
                values["END_OF_LINE_CHARACTERS"] = "\n\n"
            elif args.end_of_line_characters == "\\r" or args.end_of_line_characters == "\r":
                values["END_OF_LINE_CHARACTERS"] = "\r"
            elif args.end_of_line_characters == "\\r\\n" or args.end_of_line_characters == "\r\n":
                values["END_OF_LINE_CHARACTERS"] = "\r\n"
            else:
                print("invalid end_of_line_characters, ignoring")
        if args.finish_label:
            values["FINISH_LABEL"] = args.finish_label
        if args.header:
            values["OUTPUT_HEADER"] = True
        if args.no_header:
            values["OUTPUT_HEADER"] = False
        if args.line_number_increment != -1:
            values["LINE_INCREMENT"] = args.line_number_increment
        if args.line_number_start != -1:
            values["line_number"] = args.line_number_start
        if args.line_numbers:
            values["OUTPUT_LINE_NUMBERS"] = True
        if args.no_line_numbers:
            values["OUTPUT_LINE_NUMBERS"] = False
        if args.list_tools_in_preamble:
            values["LIST_TOOLS_IN_PREAMBLE"] = True
        if args.no_list_tools_in_preamble:
            values["LIST_TOOLS_IN_PREAMBLE"] = False
        if args.modal:
            values["MODAL"] = True
        if args.no_modal:
            values["MODAL"] = False
        if args.output_machine_name:
            values["OUTPUT_MACHINE_NAME"] = True
        if args.no_output_machine_name:
            values["OUTPUT_MACHINE_NAME"] = False
        if args.output_path_labels:
            values["OUTPUT_PATH_LABELS"] = True
        if args.no_output_path_labels:
            values["OUTPUT_PATH_LABELS"] = False
        if args.postamble is not None:
            values["POSTAMBLE"] = args.postamble.replace("\\n", "\n")
        if args.post_operation is not None:
            values["POST_OPERATION"] = args.post_operation.replace("\\n", "\n")
        if args.preamble is not None:
            values["PREAMBLE"] = args.preamble.replace("\\n", "\n")
        if args.return_to != "":
            values["RETURN_TO"] = [int(v) for v in args.return_to.split(",")]
            if len(values["RETURN_TO"]) != 3:
                values["RETURN_TO"] = None
                print("--return-to coordinates must be specified as <x>,<y>,<z>, ignoring")
        if args.show_editor:
            values["SHOW_EDITOR"] = True
        if args.no_show_editor:
            values["SHOW_EDITOR"] = False
        if args.split_arcs:
            values["SPLIT_ARCS"] = True
        if args.no_split_arcs:
            values["SPLIT_ARCS"] = False
        if args.tlo:
            values["USE_TLO"] = True
        if args.no_tlo:
            values["USE_TLO"] = False
        if args.tool_change:
            values["OUTPUT_TOOL_CHANGE"] = True
        if args.no_tool_change:
            values["OUTPUT_TOOL_CHANGE"] = False
        if args.translate_drill:
            values["TRANSLATE_DRILL_CYCLES"] = True
        if args.no_translate_drill:
            values["TRANSLATE_DRILL_CYCLES"] = False
        if args.wait_for_spindle > 0.0:
            values["SPINDLE_WAIT"] = args.wait_for_spindle

    except (ArithmeticError, LookupError):
        return (False, None)

    return (True, args)


#
# LinuxCNC (and GRBL) G-Code Parameter/word Patterns
# __________________________________________________
#
# LinuxCNC words (called parameters in this code in many places) may be
# reordered in any way without changing the meaning of the line.
# However, the documentation shows the examples with the parameters/words
# in a certain order that people might be used to and want to see.
#
#   axes    one or more of "X Y Z A B C U V W", usually in that order
#
# default parameter order     D H L axes I J K R P E Q F S T $
#
# G10                         L P axes R I J Q
#
# G33.1                       X Y Z K I $
#
# G53 G00|G01 or G00|G01 G53  X Y Z
#
# G73, G74, G81 to G86, G89   "X Y Z" | "U V W" R Q L P F K $
#
# G76                         P Z I J R K Q H E L $
#
# M19                         R Q P $
#
# M66                         P|E L Q
#
# M98                         P Q L
#
# N and O are associated with line numbers
#
#
#
# Tormach PathPilot (based on LinuxCNC, mostly) G-Code Patterns
# _____________________________________________________________
#
# (Just the exceptions to the LinuxCNC patterns shown above)
#
# G47                         Z R X Y P Q D
#
#
# Mach4 G-Code Patterns
# _____________________
#
# (Just the exceptions to the LinuxCNC patterns shown above)
#
# G10                        L1 P Z W D R X U Y V Q
#
# G30                        P axes
#
# G41, G42                   D|P X Y F
#
# G65, G66                   P A B C
#
# G73, G74, G76, G81-9       X Y Z Q R I J P L F
#
# G84.2, G84.3               X Y Z R P L F J
#
#
#
# Centroid G-Code Patterns
# ________________________
#
# (Just the exceptions to the LinuxCNC patterns shown above)
#
# E1-E6 are equivalent to G54-G59
#
# G10                       P D H R
#
# G65                       P L args (args are A-Z excluding G, L, N, O, and P)
# G65                       "program.cnc" L args
#
# G117, G118, G119          P X Y Z I J K P Q
#