예제 #1
0
        // add new style
        private void BtAddNewStyle_OnClick(object sender, RoutedEventArgs e)
        {
            var selected = TvStyles.SelectedItem;

            if (selected == null)
            {
                return;
            }

            if (selected is EntityStyles entityStyles)
            {
                var newStyle = new IntellectualEntityStyle(entityStyles.EntityType, true)
                {
                    Name      = ModPlusAPI.Language.GetItem(Invariables.LangItem, "h13"),
                    StyleType = StyleType.User
                };
                entityStyles.Styles.Add(newStyle);
                StyleManager.AddStyle(newStyle);
            }
            else if (selected is IntellectualEntityStyle style)
            {
                var newStyle = new IntellectualEntityStyle(style.EntityType, true)
                {
                    Name      = ModPlusAPI.Language.GetItem(Invariables.LangItem, "h13"),
                    StyleType = StyleType.User
                };
                _styles.Single(es => es.Styles.Contains(style)).Styles.Add(newStyle);
                StyleManager.AddStyle(newStyle);
            }
        }
예제 #2
0
        private void BtCreateStyleFromEntity_OnClick(object sender, RoutedEventArgs e)
        {
            /* Созданный стиль нужно еще найти в TreeView и выбрать его, раскрыв дерево
             * для этого можно искать по гуиду, а сам поиск взять в плагине mpDwgBase
             */
            try
            {
                Hide();
                var promptEntityOptions =
                    new PromptEntityOptions($"\n{ModPlusAPI.Language.GetItem(Invariables.LangItem, "msg3")}");
                promptEntityOptions.SetRejectMessage("\nWrong entity");
                promptEntityOptions.AllowNone = false;
                promptEntityOptions.AddAllowedClass(typeof(BlockReference), true);
                promptEntityOptions.AllowObjectOnLockedLayer = true;
                var selectionResult = AcadUtils.Document.Editor.GetEntity(promptEntityOptions);
                if (selectionResult.Status == PromptStatus.OK)
                {
                    var newStyleGuid = string.Empty;
                    using (var tr = new OpenCloseTransaction())
                    {
                        var obj = tr.GetObject(selectionResult.ObjectId, OpenMode.ForRead);
                        if (obj is BlockReference blockReference)
                        {
                            var entity   = EntityReaderService.Instance.GetFromEntity(blockReference);
                            var newStyle = new IntellectualEntityStyle(entity.GetType())
                            {
                                Name      = ModPlusAPI.Language.GetItem(Invariables.LangItem, "h13"),
                                StyleType = StyleType.User,
                                Guid      = Guid.NewGuid().ToString()
                            };
                            newStyle.GetPropertiesFromEntity(entity, blockReference);
                            newStyleGuid = newStyle.Guid;
                            foreach (var entityStyles in _styles)
                            {
                                if (entityStyles.EntityType == entity.GetType())
                                {
                                    entityStyles.Styles.Add(newStyle);
                                    StyleManager.AddStyle(newStyle);
                                    break;
                                }
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(newStyleGuid))
                    {
                        SearchInTreeViewByGuid(newStyleGuid);
                    }
                }
            }
            catch (Exception exception)
            {
                ExceptionBox.Show(exception);
            }
            finally
            {
                Show();
            }
        }
예제 #3
0
        /// <summary>
        /// Возвращает значение свойства "Имя слоя" из стиля
        /// </summary>
        /// <param name="style">Стиль <see cref="IntellectualEntityStyle"/></param>
        public static string GetLayerNameProperty(this IntellectualEntityStyle style)
        {
            foreach (var property in style.Properties)
            {
                if (property.Name == "LayerName")
                {
                    return(property.Value.ToString());
                }
            }

            return(string.Empty);
        }
예제 #4
0
        /// <summary>
        /// Возвращает значение свойства "Тип линии" из стиля
        /// </summary>
        /// <param name="style">Стиль <see cref="IntellectualEntityStyle"/></param>
        /// <returns>В случае неудачи возвращает "Continuous"</returns>
        public static string GetLineTypeProperty(this IntellectualEntityStyle style)
        {
            foreach (var property in style.Properties)
            {
                if (property.Name == "LineType")
                {
                    return(property.Value.ToString());
                }
            }

            return("Continuous");
        }
예제 #5
0
        /// <summary>
        /// Возвращает значение свойства "Текстовый стиль" из стиля
        /// </summary>
        /// <param name="style">Стиль <see cref="IntellectualEntityStyle"/></param>
        /// <returns>В случае неудачи возвращает "Standard"</returns>
        public static string GetTextStyleProperty(this IntellectualEntityStyle style)
        {
            foreach (var property in style.Properties)
            {
                if (property.Name == "TextStyle")
                {
                    return(property.Value.ToString());
                }
            }

            return("Standard");
        }
예제 #6
0
        /// <summary>
        /// Сделать слой текущим
        /// </summary>
        public void SetCurrent(IntellectualEntityStyle style)
        {
            foreach (IntellectualEntityStyle entityStyle in Styles)
            {
                if (entityStyle != style)
                {
                    if (entityStyle.IsCurrent)
                    {
                        entityStyle.IsCurrent = false;
                    }
                }
            }

            style.IsCurrent = true;
        }
예제 #7
0
        /// <summary>
        /// Конвертировать стиль в XElement
        /// </summary>
        private static XElement ConvertToXElement(this IntellectualEntityStyle style)
        {
            var styleXel = new XElement("UserStyle");

            styleXel.SetAttributeValue(nameof(style.Name), style.Name);
            styleXel.SetAttributeValue(nameof(style.Description), style.Description);
            styleXel.SetAttributeValue(nameof(style.Guid), style.Guid);

            foreach (var entityProperty in style.Properties)
            {
                if (entityProperty.Name == "Scale")
                {
                    var propXel = new XElement("Property");
                    propXel.SetAttributeValue("Name", entityProperty.Name);
                    propXel.SetAttributeValue("Value", ((AnnotationScale)entityProperty.Value).Name);
                    styleXel.Add(propXel);
                }
                else
                {
                    var propXel = new XElement("Property");
                    propXel.SetAttributeValue("Name", entityProperty.Name);
                    propXel.SetAttributeValue("Value", entityProperty.Value);
                    styleXel.Add(propXel);
                }
            }

            if (LayerUtils.HasLayer(style.GetLayerNameProperty()))
            {
                styleXel.Add(LayerUtils.SetLayerXml(LayerUtils.GetLayerTableRecordByLayerName(style.GetLayerNameProperty())));
            }
            else if (style.LayerXmlData != null)
            {
                styleXel.Add(style.LayerXmlData);
            }

            // add text style
            if (TextStyleUtils.HasTextStyle(style.GetTextStyleProperty()))
            {
                styleXel.Add(TextStyleUtils.SetTextStyleTableRecordXElement(TextStyleUtils.GetTextStyleTableRecordByName(style.GetTextStyleProperty())));
            }
            else if (style.TextStyleXmlData != null)
            {
                styleXel.Add(style.TextStyleXmlData);
            }

            return(styleXel);
        }
예제 #8
0
        /// <summary>
        /// Наполнение стиля свойствами со значениями по умолчанию
        /// </summary>
        /// <param name="style">Стиль <see cref="IntellectualEntityStyle"/></param>
        /// <param name="entityType">Тип интеллектуального объекта</param>
        public static void FillStyleDefaultProperties(this IntellectualEntityStyle style, Type entityType)
        {
            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 == "Scale")
                    {
                        style.Properties.Add(new IntellectualEntityProperty(
                                                 attribute,
                                                 entityType,
                                                 AcadUtils.AnnotationScaleFromString(attribute.DefaultValue.ToString()),
                                                 ObjectId.Null));
                    }
                    else if (attribute.Name == "LayerName")
                    {
                        style.Properties.Add(new IntellectualEntityProperty(
                                                 attribute,
                                                 entityType,
                                                 AcadUtils.Layers.Contains(attribute.DefaultValue.ToString())
                                ? attribute.DefaultValue
                                : Language.GetItem(Invariables.LangItem, "defl"),
                                                 ObjectId.Null));
                    }
                    else
                    {
                        style.Properties.Add(new IntellectualEntityProperty(
                                                 attribute,
                                                 entityType,
                                                 attribute.DefaultValue,
                                                 ObjectId.Null));
                    }
                }
            }
        }
예제 #9
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));
                    }
                }
            }
        }
예제 #10
0
        /// <summary>
        /// Создание стандартных системных стилей
        /// </summary>
        private static void CreateSystemStyles()
        {
            var entityTypes = TypeFactory.Instance.GetEntityTypes();

            entityTypes.ForEach(et =>
            {
                var systemStyle = new IntellectualEntityStyle(et)
                {
                    Name =
                        $"{LocalizationUtils.GetEntityLocalizationName(et)} [{Language.GetItem(Invariables.LangItem, "h12")}]",
                    Description = TypeFactory.Instance.GetSystemStyleLocalizedDescription(et),
                    Guid        = "00000000-0000-0000-0000-000000000000",
                    StyleType   = StyleType.System
                };
                if (!HasStyle(systemStyle))
                {
                    FillStyleDefaultProperties(systemStyle, et);

                    EntityStyles.Add(systemStyle);
                }
            });
        }
예제 #11
0
        /// <summary>
        /// Проверка стиля на наличие отсутствующих свойств. Свойства могут отсутствовать в случае,
        /// если стиль уже был сохранен, но позже вышло обновление с добавлением нового свойства
        /// </summary>
        /// <param name="style">Проверяемый стиль</param>
        /// <param name="entityType">Тип примитива</param>
        private static void CheckMissedProperties(this IntellectualEntityStyle style, Type entityType)
        {
            foreach (var propertyInfo in entityType.GetProperties())
            {
                var attribute = propertyInfo.GetCustomAttribute <EntityPropertyAttribute>();
                if (attribute != null && attribute.Name != "Style")
                {
                    if (attribute.PropertyScope != PropertyScope.PaletteAndStyleEditor)
                    {
                        continue;
                    }

                    // ReSharper disable once SimplifyLinqExpression
                    if (!style.Properties.Any(p => p.Name == attribute.Name))
                    {
                        style.Properties.Add(new IntellectualEntityProperty(
                                                 attribute,
                                                 entityType,
                                                 attribute.DefaultValue,
                                                 ObjectId.Null));
                    }
                }
            }
        }
예제 #12
0
 private static bool HasStyle(IntellectualEntityStyle style)
 {
     return(EntityStyles.Any(s => s.EntityType == style.EntityType &&
                             s.StyleType == style.StyleType &&
                             s.Guid == style.Guid));
 }
예제 #13
0
        private void ShowStyleProperties(IntellectualEntityStyle style)
        {
            var topGrid = new Grid();

            topGrid.RowDefinitions.Add(new RowDefinition {
                Height = GridLength.Auto
            });
            topGrid.RowDefinitions.Add(new RowDefinition {
                Height = GridLength.Auto
            });
            topGrid.RowDefinitions.Add(new RowDefinition {
                Height = GridLength.Auto
            });
            topGrid.RowDefinitions.Add(new RowDefinition {
                Height = GridLength.Auto
            });
            topGrid.RowDefinitions.Add(new RowDefinition());

            #region Set main data

            var headerName = new TextBlock
            {
                Margin = (Thickness)FindResource("ModPlusDefaultMargin"),
                Text   = ModPlusAPI.Language.GetItem(Invariables.LangItem, "h54")
            };
            Grid.SetRow(headerName, 0);
            topGrid.Children.Add(headerName);

            var tbName = new TextBox {
                IsEnabled = style.StyleType == StyleType.User
            };
            Grid.SetRow(tbName, 1);
            var binding = new Binding
            {
                Mode = BindingMode.TwoWay,
                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
                Source = style,
                Path   = new PropertyPath("Name")
            };
            BindingOperations.SetBinding(tbName, TextBox.TextProperty, binding);
            topGrid.Children.Add(tbName);

            var headerDescription = new TextBlock
            {
                Margin = (Thickness)FindResource("ModPlusDefaultMargin"),
                Text   = ModPlusAPI.Language.GetItem(Invariables.LangItem, "h55")
            };
            Grid.SetRow(headerDescription, 2);
            topGrid.Children.Add(headerDescription);

            var tbDescription = new TextBox {
                IsEnabled = style.StyleType == StyleType.User
            };
            Grid.SetRow(tbDescription, 3);
            binding = new Binding
            {
                Mode = BindingMode.TwoWay,
                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
                Source = style,
                Path   = new PropertyPath("Description")
            };
            BindingOperations.SetBinding(tbDescription, TextBox.TextProperty, binding);
            topGrid.Children.Add(tbDescription);

            #endregion

            var propertiesGrid = new Grid();
            propertiesGrid.ColumnDefinitions.Add(new ColumnDefinition());
            propertiesGrid.ColumnDefinitions.Add(new ColumnDefinition {
                Width = GridLength.Auto
            });
            propertiesGrid.ColumnDefinitions.Add(new ColumnDefinition());
            Grid.SetRow(propertiesGrid, 4);

            var groupsByCategory = style.Properties.GroupBy(p => p.Category).ToList();
            groupsByCategory.Sort((g1, g2) => g1.Key.CompareTo(g2.Key));
            var rowIndex = 0;
            foreach (var categoryGroup in groupsByCategory)
            {
                propertiesGrid.RowDefinitions.Add(new RowDefinition {
                    Height = GridLength.Auto
                });

                var categoryHeader = new TextBox {
                    Text = LocalizationUtils.GetCategoryLocalizationName(categoryGroup.Key)
                };
                Grid.SetRow(categoryHeader, rowIndex);
                Grid.SetColumn(categoryHeader, 0);
                Grid.SetColumnSpan(categoryHeader, 3);
                categoryHeader.Style = Resources["HeaderTextBoxForStyleEditor"] as Style;
                propertiesGrid.Children.Add(categoryHeader);
                rowIndex++;
                var gridSplitterStartIndex = rowIndex;
                foreach (var property in categoryGroup.OrderBy(p => p.OrderIndex))
                {
                    propertiesGrid.RowDefinitions.Add(new RowDefinition {
                        Height = GridLength.Auto
                    });

                    // property name
                    var propertyDescription = GetPropertyDescription(property);
                    var propertyHeader      = new TextBox
                    {
                        Text  = GetPropertyDisplayName(property),
                        Style = Resources["PropertyHeaderInStyleEditor"] as Style
                    };
                    SetDescription(propertyHeader, propertyDescription);
                    Grid.SetColumn(propertyHeader, 0);
                    Grid.SetRow(propertyHeader, rowIndex);
                    propertiesGrid.Children.Add(propertyHeader);

                    if (property.Name == "LayerName")
                    {
                        try
                        {
                            var cb = new ComboBox {
                                IsEnabled = style.StyleType == StyleType.User
                            };
                            Grid.SetColumn(cb, 2);
                            Grid.SetRow(cb, rowIndex);
                            var layers = AcadUtils.Layers;
                            layers.Insert(0, ModPlusAPI.Language.GetItem(Invariables.LangItem, "defl")); // "По умолчанию"
                            if (!layers.Contains(style.GetLayerNameProperty()))
                            {
                                layers.Insert(1, style.GetLayerNameProperty());
                            }

                            cb.ItemsSource = layers;
                            cb.Style       = Resources["PropertyValueComboBoxForStyleEditor"] as Style;
                            SetDescription(cb, propertyDescription);
                            BindingOperations.SetBinding(cb, Selector.SelectedItemProperty, CreateTwoWayBindingForProperty(property));
                            propertiesGrid.Children.Add(cb);
                        }
                        catch (Exception exception)
                        {
                            ExceptionBox.Show(exception);
                        }
                    }
                    else if (property.Name == "Scale")
                    {
                        try
                        {
                            var cb = new ComboBox {
                                IsEnabled = style.StyleType == StyleType.User
                            };
                            Grid.SetColumn(cb, 2);
                            Grid.SetRow(cb, rowIndex);
                            cb.ItemsSource = AcadUtils.Scales;
                            cb.Style       = Resources["PropertyValueComboBoxForStyleEditor"] as Style;
                            SetDescription(cb, propertyDescription);
                            BindingOperations.SetBinding(cb, ComboBox.TextProperty, CreateTwoWayBindingForProperty(property, new AnnotationScaleValueConverter()));
                            propertiesGrid.Children.Add(cb);
                        }
                        catch (Exception exception)
                        {
                            ExceptionBox.Show(exception);
                        }
                    }
                    else if (property.Name == "LineType")
                    {
                        try
                        {
                            var tb = new TextBox {
                                IsEnabled = style.StyleType == StyleType.User
                            };
                            Grid.SetColumn(tb, 2);
                            Grid.SetRow(tb, rowIndex);
                            tb.Cursor            = Cursors.Hand;
                            tb.Style             = Resources["PropertyValueTextBoxForStyleEditor"] as Style;
                            tb.PreviewMouseDown += LineType_OnPreviewMouseDown;
                            SetDescription(tb, propertyDescription);
                            BindingOperations.SetBinding(tb, TextBox.TextProperty, CreateTwoWayBindingForProperty(property));
                            propertiesGrid.Children.Add(tb);
                        }
                        catch (Exception exception)
                        {
                            ExceptionBox.Show(exception);
                        }
                    }
                    else if (property.Name.Contains("TextStyle"))
                    {
                        try
                        {
                            var cb = new ComboBox {
                                IsEnabled = style.StyleType == StyleType.User
                            };
                            Grid.SetColumn(cb, 2);
                            Grid.SetRow(cb, rowIndex);
                            cb.ItemsSource = AcadUtils.TextStyles;
                            cb.Style       = Resources["PropertyValueComboBoxForStyleEditor"] as Style;
                            SetDescription(cb, propertyDescription);
                            BindingOperations.SetBinding(cb, Selector.SelectedItemProperty, CreateTwoWayBindingForProperty(property));
                            propertiesGrid.Children.Add(cb);
                        }
                        catch (Exception exception)
                        {
                            ExceptionBox.Show(exception);
                        }
                    }
                    else if (property.Value is Enum)
                    {
                        try
                        {
                            var cb = new ComboBox {
                                IsEnabled = style.StyleType == StyleType.User
                            };
                            Grid.SetColumn(cb, 2);
                            Grid.SetRow(cb, rowIndex);
                            cb.Style = Resources["PropertyValueComboBoxForStyleEditor"] as Style;
                            var type = property.Value.GetType();
                            SetDescription(cb, propertyDescription);
                            cb.ItemsSource = LocalizationUtils.GetEnumPropertyLocalizationFields(type);

                            BindingOperations.SetBinding(cb, ComboBox.TextProperty,
                                                         CreateTwoWayBindingForProperty(property, new EnumPropertyValueConverter()));

                            propertiesGrid.Children.Add(cb);
                        }
                        catch (Exception exception)
                        {
                            ExceptionBox.Show(exception);
                        }
                    }
                    else if (property.Value is int)
                    {
                        try
                        {
                            var tb = new NumericBox
                            {
                                IsEnabled = style.StyleType == StyleType.User
                            };
                            Grid.SetColumn(tb, 2);
                            Grid.SetRow(tb, rowIndex);
                            tb.Minimum = Convert.ToInt32(property.Minimum);
                            tb.Maximum = Convert.ToInt32(property.Maximum);
                            tb.Style   = Resources["PropertyValueIntTextBoxForStyleEditor"] as Style;
                            SetDescription(tb, propertyDescription);
                            BindingOperations.SetBinding(tb, NumericBox.ValueProperty, CreateTwoWayBindingForPropertyForNumericValue(property, true));
                            propertiesGrid.Children.Add(tb);
                        }
                        catch (Exception exception)
                        {
                            ExceptionBox.Show(exception);
                        }
                    }
                    else if (property.Value is double)
                    {
                        try
                        {
                            var tb = new NumericBox
                            {
                                IsEnabled = style.StyleType == StyleType.User
                            };
                            Grid.SetColumn(tb, 2);
                            Grid.SetRow(tb, rowIndex);
                            tb.Minimum = Convert.ToDouble(property.Minimum);
                            tb.Maximum = Convert.ToDouble(property.Maximum);
                            tb.Style   = Resources["PropertyValueDoubleTextBoxForStyleEditor"] as Style;
                            SetDescription(tb, propertyDescription);
                            BindingOperations.SetBinding(tb, NumericBox.ValueProperty, CreateTwoWayBindingForPropertyForNumericValue(property, false));

                            propertiesGrid.Children.Add(tb);
                        }
                        catch (Exception exception)
                        {
                            ExceptionBox.Show(exception);
                        }
                    }
                    else if (property.Value is bool)
                    {
                        try
                        {
                            var chb = new CheckBox {
                                IsEnabled = style.StyleType == StyleType.User
                            };
                            SetDescription(chb, propertyDescription);
                            BindingOperations.SetBinding(chb, ToggleButton.IsCheckedProperty, CreateTwoWayBindingForProperty(property));

                            var outerBorder = new Border();
                            outerBorder.Style = Resources["PropertyBorderForCheckBoxForStyleEditor"] as Style;
                            Grid.SetColumn(outerBorder, 2);
                            Grid.SetRow(outerBorder, rowIndex);

                            outerBorder.Child = chb;
                            propertiesGrid.Children.Add(outerBorder);
                        }
                        catch (Exception exception)
                        {
                            ExceptionBox.Show(exception);
                        }
                    }
                    else if (property.Value is string)
                    {
                        try
                        {
                            var tb = new TextBox {
                                IsEnabled = style.StyleType == StyleType.User
                            };
                            Grid.SetColumn(tb, 2);
                            Grid.SetRow(tb, rowIndex);
                            tb.Style = Resources["PropertyValueTextBoxForStyleEditor"] as Style;
                            SetDescription(tb, propertyDescription);
                            BindingOperations.SetBinding(tb, TextBox.TextProperty, CreateTwoWayBindingForProperty(property));

                            propertiesGrid.Children.Add(tb);
                        }
                        catch (Exception exception)
                        {
                            ExceptionBox.Show(exception);
                        }
                    }

                    rowIndex++;
                }

                propertiesGrid.Children.Add(CreateGridSplitter(gridSplitterStartIndex, rowIndex - gridSplitterStartIndex));
            }

            topGrid.Children.Add(propertiesGrid);
            BorderProperties.Child = topGrid;
        }
예제 #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);
                    }
                }
            }
        }
예제 #15
0
 /// <summary>
 /// Удаление стиля из списка
 /// </summary>
 /// <param name="style">Стиль <see cref="IntellectualEntityStyle"/></param>
 public static void RemoveStyle(IntellectualEntityStyle style)
 {
     EntityStyles.Remove(style);
 }
예제 #16
0
 /// <summary>
 /// Добавить стиль в список
 /// </summary>
 /// <param name="style">Стиль <see cref="IntellectualEntityStyle"/></param>
 public static void AddStyle(IntellectualEntityStyle style)
 {
     EntityStyles.Add(style);
 }
예제 #17
0
 /// <summary>
 /// Сохранить стиль как Текущий в настройки пользователя
 /// </summary>
 /// <param name="style">Сохраняемый стиль</param>
 public static void SaveCurrentStyleToSettings(IntellectualEntityStyle style)
 {
     UserConfigFile.SetValue($"mp{style.EntityType.Name}", "CurrentStyleGuid", style.Guid, true);
 }
예제 #18
0
        /// <summary>
        /// Загрузка пользовательских стилей из xml-файла для указанного типа примитива
        /// </summary>
        /// <param name="entityType">Тип примитива</param>
        private static void LoadStylesFromXmlFile(Type entityType)
        {
            var stylesFile = Path.Combine(MainFunction.StylesPath, $"{entityType.Name}Styles.xml");

            if (File.Exists(stylesFile))
            {
                for (var i = EntityStyles.Count - 1; i >= 0; i--)
                {
                    var style = EntityStyles[i];
                    if (style.StyleType == StyleType.System)
                    {
                        continue;
                    }

                    if (style.EntityType != entityType)
                    {
                        continue;
                    }

                    EntityStyles.RemoveAt(i);
                }

                var fXel = XElement.Load(stylesFile);
                foreach (var styleXel in fXel.Elements("UserStyle"))
                {
                    var style = new IntellectualEntityStyle(entityType)
                    {
                        StyleType = StyleType.User
                    };
                    style.Name        = styleXel.Attribute(nameof(style.Name))?.Value;
                    style.Description = styleXel.Attribute(nameof(style.Description))?.Value;

                    // Guid беру, если есть атрибут. Иначе создаю новый
                    var guidAttr = styleXel.Attribute(nameof(style.Guid));
                    style.Guid = guidAttr?.Value ?? Guid.NewGuid().ToString();

                    if (HasStyle(style))
                    {
                        continue;
                    }

                    // get layer xml data
                    var layerData = styleXel.Element("LayerTableRecord");
                    style.LayerXmlData = layerData ?? null;

                    // get text style xml data
                    var textStyleData = styleXel.Element("TextStyleTableRecord");
                    style.TextStyleXmlData = textStyleData ?? null;

                    // get properties from file
                    foreach (var propertyInfo in entityType.GetProperties())
                    {
                        var attribute = propertyInfo.GetCustomAttribute <EntityPropertyAttribute>();
                        if (attribute != null)
                        {
                            var xmlProperty = styleXel.Elements("Property").FirstOrDefault(e => e.Attribute("Name")?.Value == attribute.Name);
                            if (xmlProperty != null)
                            {
                                var xmlValue  = xmlProperty.Attribute("Value")?.Value;
                                var valueType = attribute.DefaultValue.GetType();
                                if (attribute.Name == "Scale")
                                {
                                    style.Properties.Add(new IntellectualEntityProperty(
                                                             attribute,
                                                             entityType,
                                                             AcadUtils.AnnotationScaleFromString(xmlValue),
                                                             ObjectId.Null));
                                }
                                else
                                {
                                    if (valueType == typeof(string))
                                    {
                                        style.Properties.Add(new IntellectualEntityProperty(
                                                                 attribute,
                                                                 entityType,
                                                                 xmlProperty.Attribute("Value").Value,
                                                                 ObjectId.Null));
                                    }
                                    else if (valueType == typeof(int))
                                    {
                                        style.Properties.Add(new IntellectualEntityProperty(
                                                                 attribute,
                                                                 entityType,
                                                                 int.TryParse(xmlValue, out var i) ? i : attribute.DefaultValue,
                                                                 ObjectId.Null));
                                    }
                                    else if (valueType == typeof(double))
                                    {
                                        style.Properties.Add(new IntellectualEntityProperty(
                                                                 attribute,
                                                                 entityType,
                                                                 double.TryParse(xmlValue, out var d) ? d : attribute.DefaultValue,
                                                                 ObjectId.Null));
                                    }
                                    else if (valueType == typeof(bool))
                                    {
                                        style.Properties.Add(new IntellectualEntityProperty(
                                                                 attribute,
                                                                 entityType,
                                                                 bool.TryParse(xmlValue, out var b) ? b : attribute.DefaultValue,
                                                                 ObjectId.Null));
                                    }
                                    else if (valueType.IsEnum)
                                    {
                                        try
                                        {
                                            style.Properties.Add(new IntellectualEntityProperty(
                                                                     attribute,
                                                                     entityType,
                                                                     Enum.Parse(attribute.DefaultValue.GetType(), xmlValue),
                                                                     ObjectId.Null));
                                        }
                                        catch
                                        {
                                            style.Properties.Add(new IntellectualEntityProperty(
                                                                     attribute,
                                                                     entityType,
                                                                     attribute.DefaultValue,
                                                                     ObjectId.Null));
                                        }
                                    }
                                }
                            }
                        }
                    }

                    style.CheckMissedProperties(entityType);

                    // add style
                    EntityStyles.Add(style);
                }
            }
        }