File size: 28,162 Bytes
985c397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// SPDX-License-Identifier: LGPL-2.1-or-later

/***************************************************************************
 *   Copyright (c) 2015 Victor Titov (DeepSOIC) <vv.titov@gmail.com>       *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  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 Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/


#include <Base/Console.h>
#include <Base/Tools.h>

#include <App/Document.h>
#include <App/Datums.h>
#include <App/ObjectIdentifier.h>
#include <App/Expression.h>
#include <App/ExpressionParser.h>

#include "AttachExtension.h"
#include "AttachExtensionPy.h"


using namespace Part;
using namespace Attacher;

namespace
{
std::vector<std::string> EngineEnums = {"Engine 3D", "Engine Plane", "Engine Line", "Engine Point"};

const char* enumToClass(const char* mode)
{
    if (EngineEnums.at(0) == mode) {
        return "Attacher::AttachEngine3D";
    }
    if (EngineEnums.at(1) == mode) {
        return "Attacher::AttachEnginePlane";
    }
    if (EngineEnums.at(2) == mode) {
        return "Attacher::AttachEngineLine";
    }
    if (EngineEnums.at(3) == mode) {
        return "Attacher::AttachEnginePoint";
    }

    return "Attacher::AttachEngine3D";
}

const char* classToEnum(const char* type)
{
    if (strcmp(type, "Attacher::AttachEngine3D") == 0) {
        return EngineEnums.at(0).c_str();
    }
    if (strcmp(type, "Attacher::AttachEnginePlane") == 0) {
        return EngineEnums.at(1).c_str();
    }
    if (strcmp(type, "Attacher::AttachEngineLine") == 0) {
        return EngineEnums.at(2).c_str();
    }
    if (strcmp(type, "Attacher::AttachEnginePoint") == 0) {
        return EngineEnums.at(3).c_str();
    }

    return EngineEnums.at(0).c_str();
}

void restoreAttacherEngine(AttachExtension* self)
{
    const char* mode = enumToClass(self->AttacherEngine.getValueAsString());
    const char* type = self->AttacherType.getValue();
    if (strcmp(mode, type) != 0) {
        self->AttacherEngine.setValue(classToEnum(type));
    }
}
}  // namespace

EXTENSION_PROPERTY_SOURCE(Part::AttachExtension, App::DocumentObjectExtension)

AttachExtension::AttachExtension()
{
    EXTENSION_ADD_PROPERTY_TYPE(
        AttacherType,
        ("Attacher::AttachEngine3D"),
        "Attachment",
        (App::PropertyType)(App::Prop_ReadOnly | App::Prop_Hidden),
        "Class name of attach engine object driving the attachment."
    );

    EXTENSION_ADD_PROPERTY_TYPE(
        AttacherEngine,
        (0L),
        "Attachment",
        (App::PropertyType)(App::Prop_None),
        "Attach engine object driving the attachment."
    );
    AttacherEngine.setEnums(EngineEnums);

    EXTENSION_ADD_PROPERTY_TYPE(
        AttachmentSupport,
        (nullptr, nullptr),
        "Attachment",
        (App::PropertyType)(App::Prop_None),
        "Support of the 2D geometry"
    );
    AttachmentSupport.setScope(App::LinkScope::Global);

    EXTENSION_ADD_PROPERTY_TYPE(
        MapMode,
        (mmDeactivated),
        "Attachment",
        App::Prop_None,
        "Mode of attachment to other object"
    );
    MapMode.setEditorName("PartGui::PropertyEnumAttacherItem");
    MapMode.setEnums(AttachEngine::eMapModeStrings);
    // a rough test if mode string list in Attacher.cpp is in sync with eMapMode enum.
    assert(MapMode.getEnumVector().size() == mmDummy_NumberOfModes);

    EXTENSION_ADD_PROPERTY_TYPE(
        MapReversed,
        (false),
        "Attachment",
        App::Prop_None,
        "Reverse Z-direction (flip sketch upside down)"
    );

    EXTENSION_ADD_PROPERTY_TYPE(
        MapPathParameter,
        (0.0),
        "Attachment",
        App::Prop_None,
        "Sets point of curve to map the sketch to. 0..1 = start..end"
    );

    EXTENSION_ADD_PROPERTY_TYPE(
        AttachmentOffset,
        (Base::Placement()),
        "Attachment",
        App::Prop_None,
        "Extra placement to apply in addition to attachment (in local coordinates)"
    );

    // Only show these properties when applicable. Controlled by extensionOnChanged
    this->MapPathParameter.setStatus(App::Property::Status::Hidden, true);
    this->MapReversed.setStatus(App::Property::Status::Hidden, true);
    this->AttachmentOffset.setStatus(App::Property::Status::Hidden, true);

    _props.attacherType = &AttacherType;
    _props.attachment = &AttachmentSupport;
    _props.mapMode = &MapMode;
    _props.mapReversed = &MapReversed;
    _props.mapPathParameter = &MapPathParameter;

    setAttacher(new AttachEngine3D);  // default attacher
    _baseProps.attacher.reset(new AttachEngine3D);

    updatePropertyStatus(false);

    initExtensionType(AttachExtension::getExtensionClassTypeId());
}

AttachExtension::~AttachExtension()
{}

template<class T>
static inline bool getProp(
    bool force,
    T*& prop,
    Base::Type type,
    App::PropertyContainer* owner,
    const char* name,
    const char* doc
)
{
    prop = freecad_cast<T*>(owner->getDynamicPropertyByName(name));
    if (prop || !force) {
        return false;
    }
    prop = static_cast<T*>(owner->addDynamicProperty(type.getName(), name, "Attachment", doc));
    if (!prop) {
        FC_THROWM(Base::RuntimeError, "Failed to add property " << owner->getFullName() << name);
    }
    prop->setStatus(App::Property::Status::LockDynamic, true);
    prop->setStatus(App::Property::Status::Hidden, true);
    return true;
}

template<class T>
static inline bool getProp(
    bool force,
    T*& prop,
    App::PropertyContainer* owner,
    const char* name,
    const char* doc
)
{
    return getProp(force, prop, T::getClassTypeId(), owner, name, doc);
}

void AttachExtension::initBase(bool force)
{
    if (_baseProps.attacherType) {
        return;
    }
    auto obj = getExtendedObject();

    // Temporary holding the properties so that we only handle onChanged() event
    // when all relevant properties are ready.
    Properties props;

    if (getProp<App::PropertyString>(
            force,
            props.attacherType,
            obj,
            "BaseAttacherType",
            "Class name of attach engine object driving the attachment for base geometry."
        )) {
        props.attacherType->setValue(_baseProps.attacher->getTypeId().getName());
    }
    else if (!props.attacherType) {
        return;
    }

    getProp<App::PropertyLinkSubList>(
        force,
        props.attachment,
        App::PropertyLinkSubListHidden::getClassTypeId(),
        obj,
        "BaseAttachment",
        "Link to base geometry."
    );

    if (getProp<App::PropertyEnumeration>(
            force,
            props.mapMode,
            obj,
            "BaseMapMode",
            "Mode of attachment for the base geometry"
        )) {
        props.mapMode->setStatus(App::Property::Status::Hidden, false);
    }
    if (props.mapMode) {
        props.mapMode->setEditorName("PartGui::PropertyEnumAttacherItem");
        props.mapMode->setEnums(AttachEngine::eMapModeStrings);
    }

    getProp<App::PropertyBool>(
        force,
        props.mapReversed,
        obj,
        "BaseMapReversed",
        "Reverse Z-direction of the base geometry attachment"
    );

    getProp<App::PropertyFloat>(
        force,
        props.mapPathParameter,
        obj,
        "BaseMapPathParameter",
        "Sets point of base curve to map 0..1 = start..end"
    );

    static_cast<Properties&>(_baseProps) = props;
}

void AttachExtension::setAttacher(AttachEngine* pAttacher, bool base)
{
    auto& props = base ? _baseProps : _props;
    props.attacher.reset(pAttacher);
    if (props.attacher) {
        if (base) {
            initBase(true);
        }
        const char* typeName = props.attacher->getTypeId().getName();
        if (strcmp(props.attacherType->getValue(), typeName)
            != 0) {  // make sure we need to change, to break recursive
                     // onChange->changeAttacherType->onChange...
            props.attacherType->setValue(typeName);
        }
        updateAttacherVals(base);
    }
    else {
        if (props.attacherType
            && strlen(props.attacherType->getValue())
                != 0) {  // make sure we need to change, to break recursive
                         // onChange->changeAttacherType->onChange...
            props.attacherType->setValue("");
        }
    }
}

bool AttachExtension::changeAttacherType(const char* typeName, bool base)
{
    auto& prop = base ? _baseProps : _props;

    // check if we need to actually change anything
    if (prop.attacher) {
        if (strcmp(prop.attacher->getTypeId().getName(), typeName) == 0) {
            return false;
        }
    }
    else if (strlen(typeName) == 0) {
        return false;
    }
    if (strlen(typeName) == 0) {
        setAttacher(nullptr, base);
        return true;
    }
    Base::Type t = Base::Type::fromName(typeName);
    if (t.isDerivedFrom(AttachEngine::getClassTypeId())) {
        AttachEngine* pNewAttacher = static_cast<Attacher::AttachEngine*>(
            Base::Type::createInstanceByName(typeName)
        );
        this->setAttacher(pNewAttacher, base);
        return true;
    }

    std::stringstream errMsg;
    errMsg << "Object if this type is not derived from AttachEngine: " << typeName;
    throw AttachEngineException(errMsg.str());
}

bool AttachExtension::positionBySupport()
{
    _active = 0;
    if (!_props.attacher) {
        throw Base::RuntimeError(
            "AttachExtension: can't positionBySupport, because no AttachEngine is set."
        );
    }
    updateAttacherVals();
    Base::Placement plaOriginal = getPlacement().getValue();
    try {
        if (_props.attacher->mapMode == mmDeactivated) {
            return false;
        }
        bool subChanged = false;

        getPlacement().setValue(Base::Placement());

        Base::Placement basePlacement;
        if (_baseProps.attacher && _baseProps.attacher->mapMode != mmDeactivated) {
            basePlacement
                = _baseProps.attacher->calculateAttachedPlacement(Base::Placement(), &subChanged);
            if (subChanged) {
                _baseProps.attachment->setValues(
                    _baseProps.attachment->getValues(),
                    _baseProps.attacher->getSubValues()
                );
            }
        }

        subChanged = false;
        _props.attacher->setOffset(AttachmentOffset.getValue() * basePlacement.inverse());
        auto placement = _props.attacher->calculateAttachedPlacement(plaOriginal, &subChanged);
        if (subChanged) {
            Base::ObjectStatusLocker<App::Property::Status, App::Property> guard(
                App::Property::User3,
                &AttachmentSupport
            );
            AttachmentSupport.setValues(AttachmentSupport.getValues(), _props.attacher->getSubValues());
        }
        getPlacement().setValue(placement);
        _active = 1;
        return true;
    }
    catch (ExceptionCancel&) {
        // disabled, don't do anything
        getPlacement().setValue(plaOriginal);
        return false;
    }
    catch (Base::Exception&) {
        getPlacement().setValue(plaOriginal);
        throw;
    }
    catch (Standard_Failure&) {
        getPlacement().setValue(plaOriginal);
        throw;
    }
}

bool AttachExtension::isAttacherActive() const
{
    if (_active < 0) {
        _active = 0;
        try {
            updateAttacherVals(/*base*/ false);
            updateAttacherVals(/*base*/ true);
            _props.attacher->calculateAttachedPlacement(getPlacement().getValue());
            _active = 1;
        }
        catch (Base::Exception&) {
        }
    }
    return _active != 0;
}

short int AttachExtension::extensionMustExecute()
{
    return DocumentObjectExtension::extensionMustExecute();
}


App::DocumentObjectExecReturn* AttachExtension::extensionExecute()
{
    if (this->isTouched_Mapping()) {
        try {
            positionBySupport();
            // we let all Base::Exceptions thru, so that App:DocumentObject can take appropriate
            // action
            /*} catch (Base::Exception &e) {
                return new App::DocumentObjectExecReturn(e.what());*/
            // Convert OCC exceptions to Base::Exception
        }
        catch (Standard_Failure& e) {
            throw Base::RuntimeError(e.GetMessageString());
            //            return new App::DocumentObjectExecReturn(e.GetMessageString());
        }
    }
    return App::DocumentObjectExtension::extensionExecute();
}

void AttachExtension::extensionOnChanged(const App::Property* prop)
{
    if (!getExtendedObject()->isRestoring()) {
        // If we change anything that affects our position, update it immediately so you can see it
        // interactively.
        if ((prop == &AttachmentSupport || prop == &MapMode || prop == &MapPathParameter
             || prop == &MapReversed || prop == &AttachmentOffset)) {
            bool bAttached = false;
            try {
                bAttached = positionBySupport();
            }
            catch (Base::Exception& e) {
                getExtendedObject()->setStatus(App::Error, true);
                Base::Console().error("PositionBySupport: %s\n", e.what());
                // set error message - how?
            }
            catch (Standard_Failure& e) {
                getExtendedObject()->setStatus(App::Error, true);
                Base::Console().error("PositionBySupport: %s\n", e.GetMessageString());
            }

            updateSinglePropertyStatus(bAttached);
        }
        if (prop == &AttacherEngine) {
            AttacherType.setValue(enumToClass(AttacherEngine.getValueAsString()));
        }
        else if (_props.matchProperty(prop)) {
            _active = -1;
            updateAttacherVals(/*base*/ false);
            updatePropertyStatus(isAttacherActive());
        }
        else if (_baseProps.matchProperty(prop)) {
            _active = -1;
            updateAttacherVals(/*base*/ true);
            updatePropertyStatus(isAttacherActive(), /*base*/ true);
        }
    }
    if (prop == &(this->AttacherType)) {
        this->changeAttacherType(this->AttacherType.getValue());
    }
    else if (prop == _baseProps.attacherType) {
        this->changeAttacherType(_baseProps.attacherType->getValue());
    }

    App::DocumentObjectExtension::extensionOnChanged(prop);
}

bool AttachExtension::extensionHandleChangedPropertyName(
    Base::XMLReader& reader,
    const char* TypeName,
    const char* PropName
)
{
    Base::Type type = Base::Type::fromName(TypeName);
    // superPlacement -> AttachmentOffset
    if (strcmp(PropName, "superPlacement") == 0 && AttachmentOffset.getClassTypeId() == type) {
        AttachmentOffset.Restore(reader);
        return true;
    }
    // Support -> AttachmentSupport
    if (strcmp(PropName, "Support") == 0) {
        // At one point, the type of Support changed from PropertyLinkSub to its present type
        // of PropertyLinkSubList. Later, the property name changed to AttachmentSupport
        App::PropertyLinkSub tmp;
        if (strcmp(tmp.getTypeId().getName(), TypeName) == 0) {
            tmp.setContainer(this->getExtendedContainer());
            tmp.Restore(reader);
            AttachmentSupport.setValue(tmp.getValue(), tmp.getSubValues());
            this->MapMode.setValue(Attacher::mmFlatFace);
            return true;
        }
        if (AttachmentSupport.getClassTypeId() == type) {
            AttachmentSupport.Restore(reader);
            return true;
        }
    }
    return App::DocumentObjectExtension::extensionHandleChangedPropertyName(reader, TypeName, PropName);
}

void AttachExtension::handleLegacyTangentPlaneOrientation()
{
    // check attachment mode
    if (_props.attacher->mapMode != mmTangentPlane) {
        return;
    }

    // check stored document program version (applies to v1.0 and earlier only)
    int major, minor;
    if (sscanf(getExtendedObject()->getDocument()->getProgramVersion(), "%d.%d", &major, &minor)
        != 2) {
        return;
    }
    if (major > 1 || (major == 1 && minor > 0)) {
        return;
    }

    // check for an App::Plane support object exists
    App::GeoFeature* geof = nullptr;
    for (auto obj : this->AttachmentSupport.linkedObjects()) {
        if (obj->isDerivedFrom<App::Plane>()) {
            geof = freecad_cast<App::GeoFeature*>(obj);
            break;
        }
    }
    if (!geof) {
        return;
    }

    /*
     * determine which global axis (X/Y/Z) is closest to the plane normal
     */

    // extract the plane normal
    Base::Vector3d norm;
    geof->Placement.getValue().getRotation().multVec(Base::Vector3d(0.0, 0.0, 1.0), norm);
    gp_Dir normal(norm.x, norm.y, norm.z);

    // determine the dominant global axis
    std::array<double, 3> cosXYZ = {
        fabs(normal.Dot(gp_Dir(1, 0, 0))),  // normal dot global X axis
        fabs(normal.Dot(gp_Dir(0, 1, 0))),  // normal dot global Y axis
        fabs(normal.Dot(gp_Dir(0, 0, 1)))   // normal dot global Z axis
    };
    std::size_t axis = std::distance(cosXYZ.begin(), std::ranges::max_element(cosXYZ));

    // if Z is dominant, no changes needed
    if (axis == 2) {
        return;
    }

    /*
     * correct attachment offset position and rotation based on dominant axis
     */

    App::DocumentObject* owner = getExtendedObject();
    Base::Console().message("Converting attachment offset of %s\n", owner->getNameInDocument());

    try {
        // extract current attachment offset values
        Base::Placement placement = this->AttachmentOffset.getValue();
        Base::Vector3d position = placement.getPosition();
        Base::Rotation rotation = placement.getRotation();
        double yaw, pitch, roll;
        rotation.getYawPitchRoll(yaw, pitch, roll);

        // extract existing expressions
        auto buildOID = [owner](const std::vector<std::string>& path) {
            App::ObjectIdentifier oid(owner, true);
            for (const auto& name : path) {
                oid.addComponent(App::ObjectIdentifier::SimpleComponent(name));
            }
            return oid;
        };
        App::ObjectIdentifier oidX = buildOID({"AttachmentOffset", "Base", "x"});
        App::ObjectIdentifier oidY = buildOID({"AttachmentOffset", "Base", "y"});
        App::ObjectIdentifier oidYaw = buildOID({"AttachmentOffset", "Rotation", "Yaw"});
        const App::Expression* exprX = nullptr;
        const App::Expression* exprY = nullptr;
        const App::Expression* exprYaw = nullptr;
        for (const auto& [oid, expr] : owner->ExpressionEngine.getExpressions()) {
            if (oid == oidX) {
                exprX = expr;
            }
            else if (oid == oidY) {
                exprY = expr;
            }
            else if (oid == oidYaw) {
                exprYaw = expr;
            }
        }

        // convert placement and expressions according to the dominant axis
        auto makeRotatedExpression =
            [owner](const App::Expression* expr, double angle) -> App::Expression* {
            if (!expr) {
                return nullptr;
            }

            std::string unitSafeExprStr = "(" + expr->toString() + ")";
            if (angle >= 0) {
                unitSafeExprStr += " + " + std::to_string(angle);
            }
            else {
                unitSafeExprStr += " - " + std::to_string(-angle);
            }

            if (const App::Expression* simple = expr->eval()) {
                if (auto ue = dynamic_cast<const App::UnitExpression*>(simple)) {
                    const auto& q = ue->getQuantity();
                    if (q.getUnit() == Base::Unit::Angle) {
                        unitSafeExprStr += " deg";
                    }
                }
            }

            return App::ExpressionParser::parse(owner, unitSafeExprStr.c_str());
        };
        App::Expression* newExprX = nullptr;
        App::Expression* newExprY = nullptr;
        App::Expression* newExprYaw = nullptr;
        if (axis == 0) {  // normal mostly X
            // values
            std::swap(position.x, position.y);
            position.x = -position.x;
            rotation.setYawPitchRoll(yaw + 90, pitch, roll);

            // expressions
            if (exprX) {
                newExprY = App::ExpressionParser::parse(owner, exprX->toString().c_str());
            }
            if (exprY) {
                std::string expr = "-1 * (" + exprY->toString() + ")";
                newExprX = App::ExpressionParser::parse(owner, expr.c_str());
            }
            if (exprYaw) {
                if (yaw > 90) {
                    newExprYaw = makeRotatedExpression(exprYaw, -270);
                }
                else {
                    newExprYaw = makeRotatedExpression(exprYaw, 90);
                }
            }
        }
        else if (axis == 1) {  // normal mostly Y
            // values
            std::swap(position.x, position.y);
            position.y = -position.y;
            rotation.setYawPitchRoll(yaw - 90, pitch, roll);

            // expressions
            if (exprX) {
                std::string expr = "-1 * (" + exprX->toString() + ")";
                newExprY = App::ExpressionParser::parse(owner, expr.c_str());
            }
            if (exprY) {
                newExprX = App::ExpressionParser::parse(owner, exprY->toString().c_str());
            }
            if (exprYaw) {
                if (yaw < -90) {
                    newExprYaw = makeRotatedExpression(exprYaw, 270);
                }
                else {
                    newExprYaw = makeRotatedExpression(exprYaw, -90);
                }
            }
        }
        else {
            // should not happen
            return;
        }

        // store updated placement and expressions back to the document object

        // expressions
        owner->ExpressionEngine.setValue(oidX, App::ExpressionPtr(newExprX));
        owner->ExpressionEngine.setValue(oidY, App::ExpressionPtr(newExprY));
        owner->ExpressionEngine.setValue(oidYaw, App::ExpressionPtr(newExprYaw));

        // values
        placement.setPosition(position);
        placement.setRotation(rotation);
        this->AttachmentOffset.setValue(placement);
    }
    catch (const Base::Exception& e) {
        Base::Console().error(
            "Error converting legacy attachment offset of %s: %s\n",
            owner->getNameInDocument(),
            e.what()
        );
    }
}

void AttachExtension::onExtendedDocumentRestored()
{
    try {
        initBase(false);
        if (_baseProps.attachment) {
            _baseProps.attachment->setScope(App::LinkScope::Hidden);
        }
        if (_baseProps.attacherType) {
            changeAttacherType(_baseProps.attacherType->getValue(), true);
        }
        _active = -1;
        updatePropertyStatus(isAttacherActive());

        restoreAttacherEngine(this);

        if (_props.attacher->mapMode == mmTangentPlane) {
            handleLegacyTangentPlaneOrientation();
        }

        bool bAttached = positionBySupport();

        updateSinglePropertyStatus(bAttached);
    }
    catch (Base::Exception&) {
    }
    catch (Standard_Failure&) {
    }
}

void AttachExtension::updateSinglePropertyStatus(bool bAttached, bool base)
{
    auto& props = base ? this->_baseProps : this->_props;
    if (!props.mapMode) {
        return;
    }

    // Hide properties when not applicable to reduce user confusion
    eMapMode mmode = eMapMode(props.mapMode->getValue());
    bool modeIsPointOnCurve
        = (mmode == mmNormalToPath || mmode == mmFrenetNB || mmode == mmFrenetTN
           || mmode == mmFrenetTB || mmode == mmRevolutionSection || mmode == mmConcentric);

    // MapPathParameter is only used if there is a reference to one edge and not edge + vertex
    bool hasOneRef = props.attacher && props.attacher->subnames.size() == 1;

    props.mapPathParameter->setStatus(
        App::Property::Status::Hidden,
        !bAttached || !(modeIsPointOnCurve && hasOneRef)
    );
    props.mapReversed->setStatus(App::Property::Status::Hidden, !bAttached);

    if (base) {
        props.attachment->setStatus(App::Property::Status::Hidden, !bAttached);
    }
    else {
        this->AttachmentOffset.setStatus(App::Property::Status::Hidden, !bAttached);
        if (getExtendedContainer()) {
            // for mmTranslate, orientation should remain editable even when attached.
            getPlacement().setReadOnly(bAttached && mmode != mmTranslate);
        }
    }
}

void AttachExtension::updatePropertyStatus(bool bAttached, bool base)
{
    updateSinglePropertyStatus(bAttached, base);

    if (!base) {
        updateSinglePropertyStatus(bAttached, true);
    }
}

void AttachExtension::updateAttacherVals(bool base) const
{
    auto& props = base ? this->_baseProps : this->_props;
    if (!props.attachment) {
        return;
    }
    attacher(base).setUp(
        *props.attachment,
        eMapMode(props.mapMode->getValue()),
        props.mapReversed->getValue(),
        props.mapPathParameter->getValue(),
        0.0,
        0.0
    );
}

AttachExtension::Properties AttachExtension::getProperties(bool base) const
{
    return base ? _baseProps : _props;
}

AttachExtension::Properties AttachExtension::getInitedProperties(bool base)
{
    if (base) {
        initBase(true);
        return _baseProps;
    }
    return _props;
}

App::PropertyPlacement& AttachExtension::getPlacement() const
{
    auto pla = freecad_cast<App::PropertyPlacement*>(
        getExtendedObject()->getPropertyByName("Placement")
    );
    if (!pla) {
        throw Base::RuntimeError("AttachExtension cannot find placement property");
    }
    return *pla;
}

PyObject* AttachExtension::getExtensionPyObject()
{

    if (ExtensionPythonObject.is(Py::_None())) {
        // ref counter is set to 1
        ExtensionPythonObject = Py::Object(new AttachExtensionPy(this), true);
    }
    return Py::new_reference_to(ExtensionPythonObject);
}


Attacher::AttachEngine& AttachExtension::attacher(bool base) const
{
    auto& props = base ? _baseProps : _props;
    if (!props.attacher) {
        throw AttachEngineException("AttachableObject: no attacher is set.");
    }
    return *props.attacher;
}

// ------------------------------------------------

AttachEngineException::AttachEngineException()
    : Base::Exception()
{}

AttachEngineException::AttachEngineException(const char* sMessage)
    : Base::Exception(sMessage)
{}

AttachEngineException::AttachEngineException(const std::string& sMessage)
    : Base::Exception(sMessage)
{}

namespace App
{
/// @cond DOXERR
EXTENSION_PROPERTY_SOURCE_TEMPLATE(Part::AttachExtensionPython, Part::AttachExtension)
/// @endcond

// explicit template instantiation
template class PartExport ExtensionPythonT<Part::AttachExtension>;
}  // namespace App