Esempio n. 1
0
        /// <summary>
        /// Создание блока для интеллектуального объекта
        /// </summary>
        /// <param name="intellectualEntity">Интеллектуальный объект</param>
        public static BlockReference CreateBlock(IntellectualEntity intellectualEntity)
        {
            BlockReference blockReference;

            using (AcadUtils.Document.LockDocument())
            {
                ObjectId objectId;
                using (var transaction = AcadUtils.Document.TransactionManager.StartTransaction())
                {
                    using (var blockTable = AcadUtils.Database.BlockTableId.Write <BlockTable>())
                    {
                        var blockTableRecordObjectId = blockTable.Add(intellectualEntity.BlockRecord);
                        blockReference = new BlockReference(intellectualEntity.InsertionPoint, blockTableRecordObjectId);
                        using (var blockTableRecord = AcadUtils.Database.CurrentSpaceId.Write <BlockTableRecord>())
                        {
                            blockTableRecord.BlockScaling = BlockScaling.Uniform;
                            objectId = blockTableRecord.AppendEntity(blockReference);
                        }

                        transaction.AddNewlyCreatedDBObject(blockReference, true);
                        transaction.AddNewlyCreatedDBObject(intellectualEntity.BlockRecord, true);
                    }

                    transaction.Commit();
                }

                intellectualEntity.BlockId = objectId;
            }

            return(blockReference);
        }
        /// <inheritdoc />
        public void CreateAnalog(IntellectualEntity sourceEntity, bool copyLayer)
        {
#if !DEBUG
            Statistic.SendCommandStarting(GroundLineDescriptor.Instance.Name, ModPlusConnector.Instance.AvailProductExternalVersion);
#endif

            try
            {
                Overrule.Overruling = false;

                /* Регистрация ЕСКД приложения должна запускаться при запуске
                 * функции, т.к. регистрация происходит в текущем документе
                 * При инициализации плагина регистрации нет!
                 */
                ExtendedDataUtils.AddRegAppTableRecord(GroundLineDescriptor.Instance.Name);

                var groundLine     = new GroundLine();
                var blockReference = MainFunction.CreateBlock(groundLine);

                groundLine.SetPropertiesFromIntellectualEntity(sourceEntity, copyLayer);

                InsertGroundLineWithJig(groundLine, blockReference);
            }
            catch (System.Exception exception)
            {
                ExceptionBox.Show(exception);
            }
            finally
            {
                Overrule.Overruling = true;
            }
        }
        /// <inheritdoc />
        public override void OnGripStatusChanged(ObjectId entityId, Status newStatus)
        {
            try
            {
                // При начале перемещения запоминаем первоначальное положение ручки
                // Запоминаем начальные значения
                if (newStatus == Status.GripStart)
                {
                    _gripTmp = GripPoint;
                }

                // При удачном перемещении ручки записываем новые значения в расширенные данные
                // По этим данным я потом получаю экземпляр класса groundLine
                if (newStatus == Status.GripEnd)
                {
                    using (var tr = AcadUtils.Database.TransactionManager.StartOpenCloseTransaction())
                    {
                        var blkRef = tr.GetObject(IntellectualEntity.BlockId, OpenMode.ForWrite, true, true);
                        using (var resBuf = IntellectualEntity.GetDataForXData())
                        {
                            blkRef.XData = resBuf;
                        }

                        tr.Commit();
                    }

                    IntellectualEntity.Dispose();
                }

                // При отмене перемещения возвращаем временные значения
                if (newStatus == Status.GripAbort)
                {
                    if (_gripTmp != null)
                    {
                        if (GripIndex == 0)
                        {
                            IntellectualEntity.InsertionPoint = _gripTmp;
                        }
                        else if (GripIndex == ((ILinearEntity)IntellectualEntity).MiddlePoints.Count + 1)
                        {
                            IntellectualEntity.EndPoint = _gripTmp;
                        }
                        else
                        {
                            ((ILinearEntity)IntellectualEntity).MiddlePoints[GripIndex - 1] = _gripTmp;
                        }
                    }
                }

                base.OnGripStatusChanged(entityId, newStatus);
            }
            catch (Exception exception)
            {
                if (exception.ErrorStatus != ErrorStatus.NotAllowedForThisProxy)
                {
                    ExceptionBox.Show(exception);
                }
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Обработка события изменения примитива.
        /// Так как изменения свойства в палитре тоже вызывает изменение примитива, то в этом
        /// методе происходит зацикливание. Чтобы это исправить вводим дополнительную переменную
        /// <see cref="_isModifiedFromAutocad"/> чтобы не вызывать обработку события изменения
        /// свойства <see cref="Property_PropertyChanged"/>
        /// </summary>
        private void Update(BlockReference blockReference)
        {
            _isModifiedFromAutocad = true;
            try
            {
                if (blockReference == null)
                {
                    _blkRefObjectId = ObjectId.Null;
                    return;
                }

                var intellectualEntity = EntityReaderService.Instance.GetFromEntity(blockReference);
                if (intellectualEntity != null)
                {
                    _intellectualEntity = intellectualEntity;

                    Debug.Print($"Style name: {_intellectualEntity.Style}");
                    Debug.Print($"Style guid: {_intellectualEntity.StyleGuid}");

                    var entityType = intellectualEntity.GetType();

                    foreach (var propertyInfo in entityType.GetProperties().Where(x => x.GetCustomAttribute <EntityPropertyAttribute>() != null))
                    {
                        var attribute = propertyInfo.GetCustomAttribute <EntityPropertyAttribute>();
                        if (attribute != null)
                        {
                            foreach (var property in Properties)
                            {
                                if (property.Name == attribute.Name)
                                {
                                    if (attribute.Name == "Style")
                                    {
                                        property.Value = StyleManager.GetStyleNameByGuid(entityType, _intellectualEntity.StyleGuid);
                                    }
                                    else if (attribute.Name == "LayerName")
                                    {
                                        property.Value = blockReference.Layer;
                                    }
                                    else if (attribute.Name == "LineType")
                                    {
                                        property.Value = blockReference.Linetype;
                                    }
                                    else
                                    {
                                        property.Value = propertyInfo.GetValue(intellectualEntity);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
                // ignore
            }

            _isModifiedFromAutocad = false;
        }
Esempio n. 5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AxisValueEditor"/> class.
        /// </summary>
        /// <param name="intellectualEntity">Редактируемый экземпляр интеллектуального объекта</param>
        public AxisValueEditor(IntellectualEntity intellectualEntity)
        {
            _intellectualEntity = (Axis)intellectualEntity;
            InitializeComponent();
            Title = ModPlusAPI.Language.GetItem(Invariables.LangItem, "h41");

            SetValues();
        }
Esempio n. 6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LinearEntityAddVertexGrip"/> class.
 /// </summary>
 /// <param name="intellectualEntity">Instance of <see cref="Base.IntellectualEntity"/> that implement <see cref="ILinearEntity"/></param>
 /// <param name="leftPoint">Точка слева</param>
 /// <param name="rightPoint">Точка справа</param>
 public LinearEntityAddVertexGrip(IntellectualEntity intellectualEntity, Point3d?leftPoint, Point3d?rightPoint)
 {
     IntellectualEntity     = intellectualEntity;
     GripLeftPoint          = leftPoint;
     GripRightPoint         = rightPoint;
     GripType               = GripType.Plus;
     RubberBandLineDisabled = true;
 }
Esempio n. 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="LevelMarkValueEditor"/> class.
        /// </summary>
        /// <param name="intellectualEntity">Редактируемый экземпляр интеллектуального объекта</param>
        public LevelMarkValueEditor(IntellectualEntity intellectualEntity)
        {
            _levelMark = (LevelMark)intellectualEntity;
            InitializeComponent();
            Title = ModPlusAPI.Language.GetItem(Invariables.LangItem, "h105");

            SetValues();
        }
        /// <inheritdoc />
        public override ReturnValue OnHotGrip(ObjectId entityId, Context contextFlags)
        {
            using (IntellectualEntity)
            {
                Point3d?newInsertionPoint = null;

                var linearEntity = (ILinearEntity)IntellectualEntity;

                if (GripIndex == 0)
                {
                    IntellectualEntity.InsertionPoint = linearEntity.MiddlePoints[0];
                    newInsertionPoint = linearEntity.MiddlePoints[0];
                    linearEntity.MiddlePoints.RemoveAt(0);
                }
                else if (GripIndex == linearEntity.MiddlePoints.Count + 1)
                {
                    IntellectualEntity.EndPoint = linearEntity.MiddlePoints.Last();
                    linearEntity.MiddlePoints.RemoveAt(linearEntity.MiddlePoints.Count - 1);
                }
                else
                {
                    linearEntity.MiddlePoints.RemoveAt(GripIndex - 1);
                }

                IntellectualEntity.UpdateEntities();
                IntellectualEntity.BlockRecord.UpdateAnonymousBlocks();
                using (var tr = AcadUtils.Database.TransactionManager.StartOpenCloseTransaction())
                {
                    var blkRef = tr.GetObject(IntellectualEntity.BlockId, OpenMode.ForWrite, true, true);
                    if (newInsertionPoint.HasValue)
                    {
                        ((BlockReference)blkRef).Position = newInsertionPoint.Value;
                    }

                    using (var resBuf = IntellectualEntity.GetDataForXData())
                    {
                        blkRef.XData = resBuf;
                    }

                    tr.Commit();
                }
            }

            return(ReturnValue.GetNewGripPoints);
        }
Esempio n. 9
0
        /// <inheritdoc />
        public void CreateAnalog(IntellectualEntity sourceEntity, bool copyLayer)
        {
            // send statistic
            Statistic.SendCommandStarting(AxisDescriptor.Instance.Name, ModPlusConnector.Instance.AvailProductExternalVersion);
            try
            {
                Overrule.Overruling = false;

                /* Регистрация ЕСКД приложения должна запускаться при запуске
                 * функции, т.к. регистрация происходит в текущем документе
                 * При инициализации плагина регистрации нет!
                 */
                ExtendedDataUtils.AddRegAppTableRecord(AxisDescriptor.Instance.Name);

                var axisLastHorizontalValue = string.Empty;
                var axisLastVerticalValue   = string.Empty;
                FindLastAxisValues(ref axisLastHorizontalValue, ref axisLastVerticalValue);
                var axis = new Axis(axisLastHorizontalValue, axisLastVerticalValue);

                var blockReference = MainFunction.CreateBlock(axis);

                axis.SetPropertiesFromIntellectualEntity(sourceEntity, copyLayer);

                // Отключаю видимость кружков направления
                axis.TopOrientMarkerVisible    = false;
                axis.BottomOrientMarkerVisible = false;

                InsertAxisWithJig(axis, blockReference);
            }
            catch (Exception exception)
            {
                ExceptionBox.Show(exception);
            }
            finally
            {
                Overrule.Overruling = true;
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="LinearEntityReverseGrip"/> class.
 /// </summary>
 /// <param name="intellectualEntity">Instance of <see cref="IntellectualEntity"/> that implement <see cref="ILinearEntity"/></param>
 public LinearEntityReverseGrip(IntellectualEntity intellectualEntity)
 {
     IntellectualEntity = intellectualEntity;
     GripType           = GripType.Mirror;
 }
Esempio n. 11
0
        /// <summary>
        /// Чтение свойств из примитива и запись их в стиль примитива
        /// </summary>
        /// <param name="style">Стиль примитива</param>
        /// <param name="entity">Интеллектуальный примитив</param>
        /// <param name="blockReference">Вставка блока, представляющая интеллектуальный примитив в AutoCAD</param>
        public static void GetPropertiesFromEntity(this IntellectualEntityStyle style, IntellectualEntity entity, BlockReference blockReference)
        {
            var entityType = entity.GetType();

            foreach (var propertyInfo in entityType.GetProperties())
            {
                var attribute = propertyInfo.GetCustomAttribute <EntityPropertyAttribute>();
                if (attribute != null && attribute.Name != "Style")
                {
                    if (attribute.PropertyScope != PropertyScope.PaletteAndStyleEditor)
                    {
                        continue;
                    }

                    if (attribute.Name == "LayerName")
                    {
                        style.Properties.Add(new IntellectualEntityProperty(
                                                 attribute,
                                                 entityType,
                                                 blockReference.Layer,
                                                 ObjectId.Null));
                    }
                    else if (attribute.Name == "LineType")
                    {
                        style.Properties.Add(new IntellectualEntityProperty(
                                                 attribute,
                                                 entityType,
                                                 blockReference.Linetype,
                                                 ObjectId.Null));
                    }
                    else
                    {
                        style.Properties.Add(new IntellectualEntityProperty(
                                                 attribute,
                                                 entityType,
                                                 propertyInfo.GetValue(entity),
                                                 ObjectId.Null));
                    }
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="LinearEntityRemoveVertexGrip"/> class.
 /// </summary>
 /// <param name="intellectualEntity">Instance of <see cref="Base.IntellectualEntity"/> that implement <see cref="ILinearEntity"/></param>
 /// <param name="index">Grip index</param>
 public LinearEntityRemoveVertexGrip(IntellectualEntity intellectualEntity, int index)
 {
     IntellectualEntity = intellectualEntity;
     GripIndex          = index;
     GripType           = GripType.Minus;
 }
Esempio n. 13
0
        private void Create(BlockReference blockReference)
        {
            if (blockReference == null)
            {
                _blkRefObjectId = ObjectId.Null;
                return;
            }

            var intellectualEntity = EntityReaderService.Instance.GetFromEntity(blockReference);

            if (intellectualEntity != null)
            {
                _intellectualEntity = intellectualEntity;

                var entityType = intellectualEntity.GetType();
                EntityType = entityType;
                foreach (var propertyInfo in entityType.GetProperties().Where(x => x.GetCustomAttribute <EntityPropertyAttribute>() != null))
                {
                    var attribute = propertyInfo.GetCustomAttribute <EntityPropertyAttribute>();
                    if (attribute != null)
                    {
                        if (attribute.Name == "Style")
                        {
                            var property = new IntellectualEntityProperty(
                                attribute,
                                entityType,
                                StyleManager.GetStyleNameByGuid(entityType, _intellectualEntity.StyleGuid),
                                _blkRefObjectId);
                            property.PropertyChanged += Property_PropertyChanged;
                            Properties.Add(property);
                        }
                        else if (attribute.Name == "LayerName")
                        {
                            var property = new IntellectualEntityProperty(
                                attribute,
                                entityType,
                                blockReference.Layer,
                                _blkRefObjectId);
                            property.PropertyChanged += Property_PropertyChanged;
                            Properties.Add(property);
                        }
                        else if (attribute.Name == "LineType")
                        {
                            var property = new IntellectualEntityProperty(
                                attribute,
                                entityType,
                                blockReference.Linetype,
                                _blkRefObjectId);
                            property.PropertyChanged += Property_PropertyChanged;
                            Properties.Add(property);
                        }
                        else
                        {
                            var value = propertyInfo.GetValue(intellectualEntity);
                            if (value != null)
                            {
                                var property = new IntellectualEntityProperty(
                                    attribute,
                                    entityType,
                                    value,
                                    _blkRefObjectId);
                                property.PropertyChanged += Property_PropertyChanged;
                                Properties.Add(property);
                            }
                        }
                    }
                }
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Применить к указанному интеллектуальному примитиву свойства из стиля
        /// </summary>
        /// <param name="entity">Экземпляр примитива</param>
        /// <param name="style">Стиль</param>
        /// <param name="isOnEntityCreation">True - применение стиля происходит при создании примитива.
        /// False - применение стиля происходит при выборе стиля в палитре</param>
        public static void ApplyStyle(this IntellectualEntity entity, IntellectualEntityStyle style, bool isOnEntityCreation)
        {
            var type = entity.GetType();

            foreach (var propertyInfo in type.GetProperties())
            {
                var attribute = propertyInfo.GetCustomAttribute <EntityPropertyAttribute>();
                if (attribute != null)
                {
                    var propertyFromStyle = style.Properties.FirstOrDefault(sp => sp.Name == attribute.Name);
                    if (propertyFromStyle != null)
                    {
                        if (attribute.Name == "Scale")
                        {
                            if (isOnEntityCreation)
                            {
                                if (MainSettings.Instance.UseScaleFromStyle)
                                {
                                    propertyInfo.SetValue(entity, propertyFromStyle.Value);
                                }
                                else
                                {
                                    entity.Scale = AcadUtils.GetCurrentScale();
                                }
                            }
                            else
                            {
                                propertyInfo.SetValue(entity, propertyFromStyle.Value);
                            }
                        }
                        else if (attribute.Name == "LayerName")
                        {
                            var layerName = propertyFromStyle.Value.ToString();
                            if (string.IsNullOrEmpty(layerName))
                            {
                                layerName = Language.GetItem(Invariables.LangItem, "defl");
                            }

                            if (isOnEntityCreation)
                            {
                                if (MainSettings.Instance.UseLayerFromStyle)
                                {
                                    propertyInfo.SetValue(entity, layerName);
                                    AcadUtils.SetLayerByName(entity.BlockId, layerName, style.LayerXmlData);
                                }
                            }
                            else
                            {
                                propertyInfo.SetValue(entity, layerName);
                                AcadUtils.SetLayerByName(entity.BlockId, layerName, style.LayerXmlData);
                            }
                        }
                        else if (attribute.Name == "LineType")
                        {
                            var lineType = propertyFromStyle.Value.ToString();
                            AcadUtils.SetLineType(entity.BlockId, lineType);
                        }
                        else if (attribute.Name == "TextStyle")
                        {
                            var apply = false;
                            if (isOnEntityCreation)
                            {
                                if (MainSettings.Instance.UseTextStyleFromStyle)
                                {
                                    apply = true;
                                }
                            }
                            else
                            {
                                apply = true;
                            }

                            if (apply)
                            {
                                var textStyleName = propertyFromStyle.Value.ToString();
                                if (TextStyleUtils.HasTextStyle(textStyleName))
                                {
                                    propertyInfo.SetValue(entity, textStyleName);
                                }
                                else
                                {
                                    if (MainSettings.Instance.IfNoTextStyle == 1 &&
                                        TextStyleUtils.CreateTextStyle(style.TextStyleXmlData))
                                    {
                                        propertyInfo.SetValue(entity, textStyleName);
                                    }
                                }
                            }
                        }
                        else
                        {
                            propertyInfo.SetValue(entity, propertyFromStyle.Value);
                        }
                    }
                }
                else
                {
                    if (propertyInfo.Name == "StyleGuid")
                    {
                        propertyInfo.SetValue(entity, style.Guid);
                    }
                }
            }
        }
Esempio n. 15
0
        /// <inheritdoc />
        public override void OnGripStatusChanged(ObjectId entityId, Status newStatus)
        {
            if (newStatus == Status.GripStart)
            {
                AcadUtils.Editor.TurnForcedPickOn();
                AcadUtils.Editor.PointMonitor += AddNewVertex_EdOnPointMonitor;
            }

            if (newStatus == Status.GripEnd)
            {
                AcadUtils.Editor.TurnForcedPickOff();
                AcadUtils.Editor.PointMonitor -= AddNewVertex_EdOnPointMonitor;
                using (IntellectualEntity)
                {
                    Point3d?newInsertionPoint = null;

                    var linearEntity = (ILinearEntity)IntellectualEntity;

                    if (GripLeftPoint == IntellectualEntity.InsertionPoint)
                    {
                        linearEntity.MiddlePoints.Insert(0, NewPoint);
                    }
                    else if (GripLeftPoint == null)
                    {
                        linearEntity.MiddlePoints.Insert(0, IntellectualEntity.InsertionPoint);
                        IntellectualEntity.InsertionPoint = NewPoint;
                        newInsertionPoint = NewPoint;
                    }
                    else if (GripRightPoint == null)
                    {
                        linearEntity.MiddlePoints.Add(IntellectualEntity.EndPoint);
                        IntellectualEntity.EndPoint = NewPoint;
                    }
                    else
                    {
                        linearEntity.MiddlePoints.Insert(
                            linearEntity.MiddlePoints.IndexOf(GripLeftPoint.Value) + 1, NewPoint);
                    }

                    IntellectualEntity.UpdateEntities();
                    IntellectualEntity.BlockRecord.UpdateAnonymousBlocks();
                    using (var tr = AcadUtils.Database.TransactionManager.StartOpenCloseTransaction())
                    {
                        var blkRef = tr.GetObject(IntellectualEntity.BlockId, OpenMode.ForWrite, true, true);
                        if (newInsertionPoint.HasValue)
                        {
                            ((BlockReference)blkRef).Position = newInsertionPoint.Value;
                        }

                        using (var resBuf = IntellectualEntity.GetDataForXData())
                        {
                            blkRef.XData = resBuf;
                        }

                        tr.Commit();
                    }
                }
            }

            if (newStatus == Status.GripAbort)
            {
                AcadUtils.Editor.TurnForcedPickOff();
                AcadUtils.Editor.PointMonitor -= AddNewVertex_EdOnPointMonitor;
            }

            base.OnGripStatusChanged(entityId, newStatus);
        }
Esempio n. 16
0
        public void CreateAnalogCommand()
        {
            var psr = AcadUtils.Editor.SelectImplied();

            if (psr.Value == null || psr.Value.Count != 1)
            {
                return;
            }

            IntellectualEntity intellectualEntity = null;

            using (AcadUtils.Document.LockDocument())
            {
                using (var tr = new OpenCloseTransaction())
                {
                    foreach (SelectedObject selectedObject in psr.Value)
                    {
                        if (selectedObject.ObjectId == ObjectId.Null)
                        {
                            continue;
                        }

                        var obj = tr.GetObject(selectedObject.ObjectId, OpenMode.ForRead);
                        if (obj is BlockReference blockReference)
                        {
                            intellectualEntity = EntityReaderService.Instance.GetFromEntity(blockReference);
                        }
                    }

                    tr.Commit();
                }
            }

            if (intellectualEntity == null)
            {
                return;
            }

            var copyLayer = true;
            var layerActionOnCreateAnalog = MainSettings.Instance.LayerActionOnCreateAnalog;

            if (layerActionOnCreateAnalog == LayerActionOnCreateAnalog.NotCopy)
            {
                copyLayer = false;
            }
            else if (layerActionOnCreateAnalog == LayerActionOnCreateAnalog.Ask)
            {
                var promptKeywordOptions =
                    new PromptKeywordOptions($"\n{Language.GetItem(Invariables.LangItem, "msg8")}", "Yes No");
                var promptResult = AcadUtils.Editor.GetKeywords(promptKeywordOptions);
                if (promptResult.Status == PromptStatus.OK)
                {
                    if (promptResult.StringResult == "No")
                    {
                        copyLayer = false;
                    }
                }
                else
                {
                    copyLayer = false;
                }
            }

            var function = TypeFactory.Instance.GetEntityFunctionTypes().FirstOrDefault(f =>
            {
                var functionName = $"{intellectualEntity.GetType().Name}Function";
                var fName        = f.GetType().Name;
                return(fName == functionName);
            });

            function?.CreateAnalog(intellectualEntity, copyLayer);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="LinearEntityVertexGrip"/> class.
 /// </summary>
 /// <param name="intellectualEntity">Instance of <see cref="Base.IntellectualEntity"/> that implement <see cref="ILinearEntity"/></param>
 /// <param name="index">Grip index</param>
 public LinearEntityVertexGrip(IntellectualEntity intellectualEntity, int index)
 {
     IntellectualEntity = intellectualEntity;
     GripIndex          = index;
     GripType           = GripType.Point;
 }