Inheritance: Node, IEnumerable
 protected void Transform(ElementNode elementNode, IList<Node> body)
 {
     foreach (IReplacement replacement in replacements)
     {
         replacement.DoReplace(elementNode, body);
     }
 }
示例#2
0
 public ConfigElements()
 {
     InitializeComponent();
     Icon = Resources.Icon_Vixen3;
     _displayedNode = null;
     _tooltip = new ToolTip();
 }
示例#3
0
        // renders the given node to the internal ElementData dictionary. If the given node is
        // not a element, will recursively descend until we render its elements.
        public static EffectIntents RenderNode(ElementNode node, Curve levelCurve, ColorGradient colorGradient, TimeSpan duration, bool isDiscrete, bool allowZeroIntensity = false)
        {
            //Collect all the points first.
            double[] allPointsTimeOrdered = _GetAllSignificantDataPoints(levelCurve, colorGradient).ToArray();
            var elementData = new EffectIntents();
            foreach (ElementNode elementNode in node.GetLeafEnumerator())
            {
                // this is probably always going to be a single element for the given node, as
                // we have iterated down to leaf nodes in RenderNode() above. May as well do
                // it this way, though, in case something changes in future.
                if (elementNode == null || elementNode.Element == null)
                    continue;

                //ElementColorType colorType = ColorModule.getColorTypeForElementNode(elementNode);

                if (isDiscrete && IsElementDiscrete(node))
                {
                    IEnumerable<Color> colors = ColorModule.getValidColorsForElementNode(elementNode, false)
                         .Intersect(colorGradient.GetColorsInGradient());
                    foreach (Color color in colors)
                    {
                        AddIntentsToElement(elementNode.Element, allPointsTimeOrdered, levelCurve, colorGradient, duration, elementData, allowZeroIntensity, color);
                    }
                }
                else
                {
                    AddIntentsToElement(elementNode.Element, allPointsTimeOrdered, levelCurve, colorGradient, duration, elementData, allowZeroIntensity);
                }
            }

            return elementData;
        }
        private static bool IsEnabled(ElementNode element)
        {
            if (element.Name != "img")
                return false;

            return element.HasAttribute("src");
        }
        public MouseWheelSupport(FrameworkElement elementToAddMouseWheelSupportTo, FrameworkElement parentElementWithMouseWheelSupport)
        {
            ElementToAddMouseWheelSupportTo = elementToAddMouseWheelSupportTo;

            //Make sure the browser listener is setup
            if (browserListener == null)
                browserListener = new BrowserMouseWheelEventListener();

            //Add an event handler to the browser listener for this particular Silverlight element
            browserListener.Moved += this.HandleBrowserMouseWheelMoved;
            
            //Setup the focus/blur handlers for the Silverlight element
            elementToAddMouseWheelSupportTo.GotFocus += new RoutedEventHandler(ElementGotFocus);
            elementToAddMouseWheelSupportTo.LostFocus += new RoutedEventHandler(ElementLostFocus);

            //Setup mouse move for the Silverlight element
            elementToAddMouseWheelSupportTo.MouseMove += new System.Windows.Input.MouseEventHandler(ElementMouseMove);

            elementToAddMouseWheelSupportTo.MouseEnter += new System.Windows.Input.MouseEventHandler(elementToAddMouseWheelSupportTo_MouseEnter);
            elementToAddMouseWheelSupportTo.MouseLeave += new System.Windows.Input.MouseEventHandler(elementToAddMouseWheelSupportTo_MouseLeave);
            elementToAddMouseWheelSupportTo.LostMouseCapture += new System.Windows.Input.MouseEventHandler(elementToAddMouseWheelSupportTo_LostMouseCapture);

            //Add a new node to our tree and save a reference to the node for this element
            elementState = elementStateTree.Add(elementToAddMouseWheelSupportTo, parentElementWithMouseWheelSupport);
        }
 internal ElementNode(string name, string prefix, string xmlns, ElementNode parent)
 {
     this.name = name;
     this.prefix = prefix;
     this.xmlns = xmlns;
     this.parent = parent;
 }
示例#7
0
        //const int InitialStringLength = 20;

		public PreviewIcicle(PreviewPoint point1, PreviewPoint point2, ElementNode selectedNode, double zoomLevel)
		{
            // If we are creating this fresh, we need to know so we can add strings, etc. as drawn.
            creating = true;
            initialNode = selectedNode;

			ZoomLevel = zoomLevel;
			AddPoint(PointToZoomPoint(point1));
			AddPoint(PointToZoomPoint(point2));

			if (selectedNode != null) {
				if (selectedNode.Children.Count() > 0 && PreviewTools.GetLeafNodes(selectedNode).Count == 0) 
				{
					StringType = StringTypes.Pixel;
                    _strings = new List<PreviewBaseShape>();
                    foreach (ElementNode child in selectedNode.Children)
                    {
                        int pixelCount = child.Children.Count();
                        PreviewLine line = new PreviewLine(new PreviewPoint(10, 10), new PreviewPoint(10, 10), pixelCount, child, ZoomLevel);
                        line.Parent = this;
                        _strings.Add(line);
                    }
                    _stringCount = _strings.Count;
                    creating = false;
				} else
                {
					StringType = StringTypes.Standard;
				}
			}
			Layout();
		}
示例#8
0
文件: VUMeter.cs 项目: jaredb7/vixen
        // renders the given node to the internal ElementData dictionary. If the given node is
        // not a element, will recursively descend until we render its elements.
        protected override void RenderNode(ElementNode node)
        {
            if (!AudioUtilities.AudioLoaded)
                return;

            foreach (ElementNode elementNode in node.GetLeafEnumerator()) {
                // this is probably always going to be a single element for the given node, as
                // we have iterated down to leaf nodes in RenderNode() above. May as well do
                // it this way, though, in case something changes in future.
                if (elementNode == null || elementNode.Element == null)
                    continue;
                bool discreteColors = ColorModule.isElementNodeDiscreteColored(elementNode);

                for(int i = 0;i<(int)((TimeSpan.TotalMilliseconds/Spacing)-1);i++)
                {

                    double gradientPosition1 = (AudioUtilities.VolumeAtTime(i * Spacing) + Data.Range)/Data.Range ;
                    double gradientPosition2 = (AudioUtilities.VolumeAtTime((i+1) * Spacing) + Data.Range)/Data.Range;
                    if (gradientPosition1 <= 0)
                        gradientPosition1 = 0;
                    if (gradientPosition1 >= 1)
                        gradientPosition1 = 1;

                    //Some odd corner cases
                    if (gradientPosition2 <= 0)
                        gradientPosition2 = 0;
                    if (gradientPosition2 >= 1)
                        gradientPosition2 = 1;
                    TimeSpan startTime = TimeSpan.FromMilliseconds(i * Spacing);
                    ElementData.Add(GenerateEffectIntents(elementNode, WorkingGradient, MeterIntensityCurve, gradientPosition1, gradientPosition2, TimeSpan.FromMilliseconds(Spacing), startTime, discreteColors));

                }

            }
        }
示例#9
0
        private void _SearchBranchForFilters(ElementNode node, IEnumerable<ISequenceFilterNode> filters,
            Stack<IEnumerable<ISequenceFilterNode>> filtersFound, SequenceFilterLookup lookup)
        {
            // Must push a single value for each level we enter.
            ISequenceFilterNode[] sequenceFilterNodes = _GetFiltersForNode(node, filters);
            if (sequenceFilterNodes.Length > 0) {
                filtersFound.Push(sequenceFilterNodes);
            }
            else {
                filtersFound.Push(null);
            }

            if (node.IsLeaf) {
                ISequenceFilterNode[] elementFilters = filtersFound.Where(x => x != null).Reverse().SelectMany(x => x).ToArray();
                if (elementFilters.Length > 0) {
                    lookup.AddElementFilters(node.Element, elementFilters);
                }
            }
            else {
                foreach (ElementNode childNode in node.Children) {
                    _SearchBranchForFilters(childNode, filters, filtersFound, lookup);
                }
            }

            // Pop a single value for every level we exit.
            filtersFound.Pop();
        }
示例#10
0
		private void PopulateGeneralNodeInfo(ElementNode node)
		{
			if (node == null) {
				labelParents.Text = string.Empty;
				_tooltip.SetToolTip(labelParents, null);
				textBoxName.Text = string.Empty;
			}
			else {
				// update the label with parent info about the node. Any good suggestions or improvements for this?
				int parentCount = GetNodeParentGroupCount(node);
				List<string> parents = GetNodeParentGroupNames(node);
				string labelString = string.Empty, tooltipString = string.Empty;
				labelString = string.Format("This element is in {0} group{1}{2}", parentCount, ((parentCount != 1) ? "s" : string.Empty),
				                            ((parentCount == 0) ? "." : ": "));
				tooltipString = labelString + "\r\n\r\n";
				foreach (string p in parents) {
					labelString = string.Format("{0}{1}, ", labelString, p);
					tooltipString = string.Format("{0}{1}\r\n", tooltipString, p);
				}
				labelParents.Text = labelString.TrimEnd(new char[] {' ', ','});
				tooltipString = tooltipString.TrimEnd(new char[] {'\r', '\n'});
				if (labelString.Length > 100) {
					_tooltip.SetToolTip(labelParents, tooltipString);
				}
				else {
					_tooltip.SetToolTip(labelParents, null);
				}

				textBoxName.Text = node.Name;
			}
		}
示例#11
0
        // renders the given node to the internal ElementData dictionary. If the given node is
        // not a element, will recursively descend until we render its elements.
        private void RenderNode(ElementNode node)
        {
            foreach(Element element in node) {
                // this is probably always going to be a single element for the given node, as
                // we have iterated down to leaf nodes in RenderNode() above. May as well do
                // it this way, though, in case something changes in future.
                if (element == null)
                    continue;

                double[] allPointsTimeOrdered = _GetAllSignificantDataPoints().ToArray();
                Debug.Assert(allPointsTimeOrdered.Length > 1);

                double lastPosition = allPointsTimeOrdered[0];
                for(int i=1; i<allPointsTimeOrdered.Length; i++) {
                    double position = allPointsTimeOrdered[i];

                    LightingValue startValue = new LightingValue(ColorGradient.GetColorAt(lastPosition), (float)LevelCurve.GetValue(lastPosition * 100) / 100);
                    LightingValue endValue = new LightingValue(ColorGradient.GetColorAt(position), (float)LevelCurve.GetValue(position * 100) / 100);

                    TimeSpan startTime = TimeSpan.FromMilliseconds(TimeSpan.TotalMilliseconds * lastPosition);
                    TimeSpan timeSpan = TimeSpan.FromMilliseconds(TimeSpan.TotalMilliseconds * (position - lastPosition));

                    IIntent intent = new LightingIntent(startValue, endValue, timeSpan);

                    _elementData.AddIntentForElement(element.Id, intent, startTime);

                    lastPosition = position;
                }
            }
        }
        private static bool IsEnabled(ElementNode element)
        {
            if (element.Name != "img")
                return false;

            return element.GetAttribute("src", true) != null;
        }
示例#13
0
 public PreviewMultiString(PreviewPoint point1, PreviewPoint point2, ElementNode selectedNode, double zoomLevel)
 {
     ZoomLevel = zoomLevel;
     AddPoint(PointToZoomPoint(point1));
     _strings = new List<PreviewBaseShape>();
     Creating = true;
     inputElements = selectedNode;
 }
 protected static void AddAttribute(ElementNode elementNode, string attributeName, Node childNode)
 {
     elementNode.RemoveAttributesByName(attributeName);
     elementNode.Attributes.Add(
         new AttributeNode(
             attributeName,
             new List<Node> { childNode }));
 }
        public IHtmlSmartTag TryCreateSmartTag(ITextView textView, ITextBuffer textBuffer, ElementNode element, AttributeNode attribute, int caretPosition, HtmlPositionType positionType)
        {
            if (element.InnerRange == null || element.GetText(element.InnerRange).Trim().Length == 0)
                return null;

            string displayText = element.Children.Count == 0 ? "Remove HTML tag" : "Remove and keep children";

            return new HtmlRemoveParentSmartTag(textView, textBuffer, element, displayText);
        }
 private static IEnumerable<IReplacement> GetMiscReplacements(ElementNode node)
 {
     IEnumerable<IReplacement> result =
         TextAreaSpecs.Where(x => x.IsMatch(node)).Select(x => new TextAreaValueReplacement(x)).Cast<IReplacement>();
     result =
         result.Union(
             SelectSpecs.Where(x => x.IsMatch(node)).Select(x => new SelectSelectedValueReplacement(x)).Cast<IReplacement>());
     return result;
 }
        private ElementNode ChildNode(ElementNode deepChild, ElementNode parent)
        {
            if (deepChild.Parent != null && deepChild.Parent != parent)
            {
                return ChildNode(deepChild.Parent, parent);
            }

            return deepChild;
        }
示例#18
0
 private void BuildNode(TreeNode parentNode, ElementNode node)
 {
     foreach(ElementNode childNode in node.Children)
     {
         TreeNode newNode = new TreeNode(childNode.Name);
         BuildNode(newNode, childNode);
         parentNode.Nodes.Add(newNode);
     }
 }
示例#19
0
        protected IIntent CreateIntent(ElementNode node, Color color, double intensity, TimeSpan duration)
        {
            if (HasDiscreteColors && IsElementDiscrete(node))
            {
                return CreateDiscreteIntent(color, intensity, duration);
            }

            return CreateIntent(color, intensity, duration);
        }
        public IHtmlSmartTag TryCreateSmartTag(ITextView textView, ITextBuffer textBuffer, ElementNode element, AttributeNode attribute, int caretPosition, HtmlPositionType positionType)
        {
            if (element.Children.Count > 0)
            {
                return new HtmlRemoveParentSmartTag(textView, textBuffer, element);
            }

            return null;
        }
        public IHtmlSmartTag TryCreateSmartTag(ITextView textView, ITextBuffer textBuffer, ElementNode element, AttributeNode attribute, int caretPosition, HtmlPositionType positionType)
        {
            if (element.IsStyleBlock() || element.IsJavaScriptBlock())
            {
                return new HtmlMinifySmartTag(textView, textBuffer, element);
            }

            return null;
        }
示例#22
0
        protected IIntent CreateIntent(ElementNode node, Color startColor, Color endColor, double startIntensity, double endIntensity, TimeSpan duration)
        {
            if (HasDiscreteColors && IsElementDiscrete(node))
            {
                return CreateDiscreteIntent(startColor, startIntensity, endIntensity, duration);
            }

            return CreateIntent(startColor, endColor, startIntensity, endIntensity, duration);
        }
 private static IEnumerable<IReplacement> GetApplicableReplacements(ElementNode node)
 {
     var result = new List<IReplacement>();
     
     result.AddRange(UriReplacementSpecifications.GetMatching(node));
     result.AddRange(FormReplacementSpecifications.GetMatching(node));
     
     return result;
 }
示例#24
0
        public IHtmlSmartTag TryCreateSmartTag(ITextView textView, ITextBuffer textBuffer, ElementNode element, AttributeNode attribute, int caretPosition, HtmlPositionType positionType)
        {
            if (element.GetAttribute("class") == null)
            {
                return new $safeitemname$SmartTag(textView, textBuffer, element);
            }

            return null;
        }
        public IHtmlSmartTag TryCreateSmartTag(ITextView textView, ITextBuffer textBuffer, ElementNode element, AttributeNode attribute, int caretPosition, HtmlPositionType positionType)
        {
            if ((element.IsStyleBlock() || element.IsJavaScriptBlock()) && element.InnerRange.Length > 5)
            {
                return new ExtractToFileSmartTag(textView, textBuffer, element);
            }

            return null;
        }
示例#26
0
        public ElementNode ImportTemplateOnce(string templateFileName, ElementNode parentNode)
        {
            ElementNodeTemplate elementNodeTemplate = FileService.Instance.LoadElementNodeTemplateFile(templateFileName);
            if (elementNodeTemplate == null) return null;

            VixenSystem.Nodes.AddChildToParent(elementNodeTemplate.ElementNode, parentNode);

            return elementNodeTemplate.ElementNode;
        }
        public IHtmlSmartTag TryCreateSmartTag(ITextView textView, ITextBuffer textBuffer, ElementNode element, AttributeNode attribute, int caretPosition, HtmlPositionType positionType)
        {
            if (element.GetAttribute("ng-controller") != null)
            {
                return new HtmlAngularControllerSmartTag(textView, textBuffer, element);
            }

            return null;
        }
        public IHtmlSmartTag TryCreateSmartTag(ITextView textView, ITextBuffer textBuffer, ElementNode element, AttributeNode attribute, int caretPosition, HtmlPositionType positionType)
        {
            if (IsEnabled(element))
            {
                return new OptimizeImageSmartTag(textView, textBuffer, element);
            }

            return null;
        }
示例#29
0
		public PreviewTriangle(PreviewPoint point1, ElementNode selectedNode, double zoomLevel)
		{
			ZoomLevel = zoomLevel;
			_bottomRightPoint = PointToZoomPoint(point1);
			_point1 = new PreviewPoint(_bottomRightPoint);
			_point2 = new PreviewPoint(_bottomRightPoint);
			_point3 = new PreviewPoint(_bottomRightPoint);

			_strings = new List<PreviewBaseShape>();

			if (selectedNode != null) {
				List<ElementNode> children = PreviewTools.GetLeafNodes(selectedNode);
				if (children.Count >= 6)
                    //
				{
					int increment = children.Count/3;
					int pixelsLeft = children.Count;

					StringType = StringTypes.Pixel;

					// Just add lines, they will be layed out in Layout()
					for (int i = 0; i < 3; i++) {
						PreviewLine line;
						if (pixelsLeft >= increment) {
							line = new PreviewLine(new PreviewPoint(10, 10), new PreviewPoint(20, 20), increment, null, ZoomLevel);
						}
						else {
							line = new PreviewLine(new PreviewPoint(10, 10), new PreviewPoint(20, 20), pixelsLeft, null, ZoomLevel);
						}
						line.PixelColor = Color.White;
						_strings.Add(line);

						pixelsLeft -= increment;
					}

					int pixelNum = 0;
					foreach (PreviewPixel pixel in Pixels) {
						pixel.Node = children[pixelNum];
						pixel.NodeId = children[pixelNum].Id;
						pixelNum++;
					}
				}
			}

			if (_strings.Count == 0) {
				// Just add lines, they will be layed out in Layout()
				for (int i = 0; i < 3; i++) {
					PreviewLine line;
					line = new PreviewLine(new PreviewPoint(10, 10), new PreviewPoint(20, 20), 10, selectedNode, ZoomLevel);
					line.PixelColor = Color.White;
					_strings.Add(line);
				}
			}

			Layout();
		}
        public bool Visit(ElementNode element, object parameter)
        {
            if (element.Name.Equals("datalist", StringComparison.OrdinalIgnoreCase))
            {
                var list = (HashSet<string>)parameter;
                list.Add(element.Id);
            }

            return true;
        }
示例#31
0
        // gets a enumerable of valid colors for the given element node. If the element is full color, an empty enumeration
        // will be returned; otherwise one of more colors will be returned (for single or multiple discrete colors).
        // wIt will recurse the children to collect from all parts of the element
        public static IEnumerable <System.Drawing.Color> getValidColorsForElementNode(ElementNode element, bool includeChildren)
        {
            HashSet <System.Drawing.Color> result = new HashSet <System.Drawing.Color>();
            ColorModule colorModule = element.Properties.Get(ColorDescriptor.ModuleId) as ColorModule;

            if (colorModule != null)
            {
                switch (colorModule.ColorType)
                {
                case ElementColorType.FullColor:
                    break;

                case ElementColorType.MultipleDiscreteColors:
                    colorModule.Colors.ForEach(x => result.Add(x));
                    break;

                case ElementColorType.SingleColor:
                    result.Add(colorModule.SingleColor);
                    break;
                }
            }

            //recurse the children
            if (includeChildren)
            {
                if (element.Children.Any())
                {
                    result.AddRange(element.Children.SelectMany(x => getValidColorsForElementNode(x, true)));
                }
            }


            return(result);
        }
示例#32
0
 private void RemoveReplacedAttribute(ElementNode elementNode)
 {
     elementNode.RemoveAttributesByName(ReplacementSpecification.NewAttributeName);
 }
        public IEnumerable <ISuggestedAction> GetSuggestedActions(ITextView textView, ITextBuffer textBuffer, int caretPosition, ElementNode element, AttributeNode attribute, HtmlPositionType positionType)
        {
            AttributeNode src = element.GetAttribute("src");

            return(new ISuggestedAction[] {
                new HtmlBase64DecodeLightBulbAction(textView, textBuffer, element, src)
            });
        }
示例#34
0
        private void SearchAttributes(object theObject, Type theObjectType, bool isObjectList)
        {
            #region root and MainElement Tag Name Setting
            foreach (object attribute in theObjectType.GetCustomAttributes(true))
            {
                if (attribute.GetType() == typeof(XMLConvertorRootAttribute))
                {
                    xmlRootName = ((XMLConvertorRootAttribute)attribute).RootName;
                }
            }
            if (xmlRootName.Length == 0 || xmlRootName.Equals(theObjectType.Name))
            {
                xmlRootName = theObjectType.Name + "List";
            }


            #endregion

            Guid guid = new Guid();
            if (!isObjectList)
            {
                CustomeXMLConvertor.XMLConvertor.XMLElement xmlElement = new CustomeXMLConvertor.XMLConvertor.XMLElement();
                xmlElement.TagName = theObjectType.Name;

                #region FieldSearch
                foreach (FieldInfo fInfo in theObjectType.GetFields())
                {
                    foreach (Attribute attr in Attribute.GetCustomAttributes(fInfo))
                    {
                        if (attr.GetType() == typeof(XMLConvertorElementAttribute))
                        {
                            if (((XMLConvertorElementAttribute)attr).Category.Equals(xmlCategory))
                            {
                                object      fValue = fInfo.GetValue(obj);
                                ElementNode node   = new ElementNode(((XMLConvertorElementAttribute)attr).NodeName, fValue);
                            }
                        }
                    }
                }
                #endregion

                #region Property Search
                foreach (PropertyInfo pInfo in theObjectType.GetProperties())
                {
                    foreach (Attribute attr in Attribute.GetCustomAttributes(pInfo))
                    {
                        if (attr.GetType() == typeof(XMLConvertorElementAttribute))
                        {
                            if (((XMLConvertorElementAttribute)attr).Category.Equals(xmlCategory))
                            {
                                object      pValue = pInfo.GetValue(obj, null);
                                ElementNode node   = new ElementNode(((XMLConvertorElementAttribute)attr).NodeName, pValue);
                                xmlElement.Nodes.Add(node);
                            }
                        }
                    }
                }
                #endregion

                xmlElements.Add(Guid.NewGuid().ToString(), xmlElement);
            }
            else
            {
                IList myList = (IList)theObject;
                foreach (object item in myList)
                {
                    Type itemType = item.GetType();
                    CustomeXMLConvertor.XMLConvertor.XMLElement xmlElement = new CustomeXMLConvertor.XMLConvertor.XMLElement();
                    xmlElement.TagName = itemType.Name;

                    #region FieldSearch
                    foreach (FieldInfo fInfo in theObjectType.GetFields())
                    {
                        foreach (Attribute attr in Attribute.GetCustomAttributes(fInfo))
                        {
                            if (attr.GetType() == typeof(XMLConvertorElementAttribute))
                            {
                                if (((XMLConvertorElementAttribute)attr).Category.Equals(xmlCategory))
                                {
                                    object      fValue = fInfo.GetValue(item);
                                    ElementNode node   = new ElementNode(((XMLConvertorElementAttribute)attr).NodeName, fValue);
                                }
                            }
                        }
                    }
                    #endregion

                    #region Property Search
                    foreach (PropertyInfo pInfo in theObjectType.GetProperties())
                    {
                        foreach (Attribute attr in Attribute.GetCustomAttributes(pInfo))
                        {
                            if (attr.GetType() == typeof(XMLConvertorElementAttribute))
                            {
                                if (((XMLConvertorElementAttribute)attr).Category.Equals(xmlCategory))
                                {
                                    object      pValue = pInfo.GetValue(item, null);
                                    ElementNode node   = new ElementNode(((XMLConvertorElementAttribute)attr).NodeName, pValue);
                                    xmlElement.Nodes.Add(node);
                                }
                            }
                        }
                    }
                    #endregion

                    xmlElements.Add(Guid.NewGuid().ToString(), xmlElement);
                }
            }
        }
示例#35
0
 public override void MoveToRoot()
 {
     _current = _root;
     _state   = XPathNodeType.Element;
     _root.Reset();
 }
示例#36
0
 // renders the given node to the internal ElementData dictionary. If the given node is
 // not a element, will recursively descend until we render its elements.
 private EffectIntents RenderNode(ElementNode node)
 {
     return(PulseRenderer.RenderNode(node, LevelCurve, ColorGradient, TimeSpan, HasDiscreteColors));
 }
        public IHtmlSmartTag TryCreateSmartTag(ITextView textView, ITextBuffer textBuffer, ElementNode element, AttributeNode attribute, int caretPosition, HtmlPositionType positionType)
        {
            AttributeNode attr = element.GetAttribute("src") ?? element.GetAttribute("href");

            if (attr == null)
            {
                return(null);
            }

            Uri url = NormalizeUrl(attr);

            if (url == null || (!attr.Value.StartsWith("//", StringComparison.Ordinal) && !attr.Value.Contains("://")))
            {
                return(null);
            }

            return(new RemoteDownloaderSmartTag(textView, textBuffer, element, attr));
        }
示例#38
0
        private void DoRendering(CancellationTokenSource tokenSource = null)
        {
            //TODO: get a better increment time. doing it every X ms is..... shitty at best.
            TimeSpan increment = TimeSpan.FromMilliseconds(10);

            List <ElementNode> renderNodes = GetNodesToRenderOn();
            int targetNodeCount            = renderNodes.Count;

            //If there are no nodes to render on Exit!
            if (targetNodeCount == 0)
            {
                return;
            }

            ElementNode lastTargetedNode = null;

            Pulse.Pulse   pulse;
            EffectIntents pulseData;

            // apply the 'background' values to all targets if nonzero
            if (DefaultLevel > 0)
            {
                int i = 0;
                foreach (ElementNode target in renderNodes)
                {
                    if (tokenSource != null && tokenSource.IsCancellationRequested)
                    {
                        return;
                    }

                    bool discreteColors = ColorModule.isElementNodeDiscreteColored(target);

                    if (target == null || target.Element == null)
                    {
                        continue;
                    }

                    if (target != null)
                    {
                        pulse             = new Pulse.Pulse();
                        pulse.TargetNodes = new ElementNode[] { target };
                        pulse.TimeSpan    = TimeSpan;
                        double level = DefaultLevel * 100.0;

                        // figure out what color gradient to use for the pulse
                        switch (ColorHandling)
                        {
                        case SpinColorHandling.GradientForEachPulse:
                            pulse.ColorGradient = StaticColorGradient;
                            pulse.LevelCurve    = new Curve(new PointPairList(new double[] { 0, 100 }, new double[] { level, level }));
                            pulseData           = pulse.Render();
                            _elementData.Add(pulseData);
                            break;

                        case SpinColorHandling.GradientThroughWholeEffect:
                            pulse.ColorGradient = ColorGradient;
                            pulse.LevelCurve    = new Curve(new PointPairList(new double[] { 0, 100 }, new double[] { level, level }));
                            pulseData           = pulse.Render();
                            _elementData.Add(pulseData);
                            break;

                        case SpinColorHandling.StaticColor:
                            pulse.ColorGradient = StaticColorGradient;
                            pulse.LevelCurve    = new Curve(new PointPairList(new double[] { 0, 100 }, new double[] { level, level }));
                            pulseData           = pulse.Render();
                            _elementData.Add(pulseData);
                            break;

                        case SpinColorHandling.ColorAcrossItems:
                            double positionWithinGroup = i / (double)targetNodeCount;
                            if (discreteColors)
                            {
                                List <Tuple <Color, float> > colorsAtPosition =
                                    ColorGradient.GetDiscreteColorsAndProportionsAt(positionWithinGroup);
                                foreach (Tuple <Color, float> colorProportion in colorsAtPosition)
                                {
                                    double value = level * colorProportion.Item2;
                                    pulse.LevelCurve    = new Curve(new PointPairList(new double[] { 0, 100 }, new double[] { value, value }));
                                    pulse.ColorGradient = new ColorGradient(colorProportion.Item1);
                                    pulseData           = pulse.Render();
                                    _elementData.Add(pulseData);
                                }
                            }
                            else
                            {
                                pulse.ColorGradient = new ColorGradient(ColorGradient.GetColorAt(positionWithinGroup));
                                pulse.LevelCurve    = new Curve(new PointPairList(new double[] { 0, 100 }, new double[] { level, level }));
                                pulseData           = pulse.Render();
                                _elementData.Add(pulseData);
                            }
                            break;
                        }

                        i++;
                    }
                }
            }

            // calculate the pulse time and revolution time exactly (based on the parameters from the data)
            double revTimeMs = 0;             // single revolution time (ms)

            // figure out the relative length of a individual pulse
            double pulseConstant   = 0;           // how much of each pulse is a constant time
            double pulseFractional = 0;           // how much of each pulse is a fraction of a single spin

            if (PulseLengthFormat == SpinPulseLengthFormat.FixedTime)
            {
                pulseConstant = PulseTime;
            }
            else if (PulseLengthFormat == SpinPulseLengthFormat.PercentageOfRevolution)
            {
                pulseFractional = PulsePercentage / 100.0;
            }
            else if (PulseLengthFormat == SpinPulseLengthFormat.EvenlyDistributedAcrossSegments)
            {
                pulseFractional = 1.0 / (double)targetNodeCount;
            }

            // magic number. (the inaccuracy of interpolating the curve into a position. eg. if we have 5 'positions', then
            // the curve should really be from 0-80% for the last spin, to make sure the last pulse finishes accurately.)
            double pulseInterpolationOffset = 1.0 / (double)targetNodeCount;

            // figure out either the revolution count or time, based on what data we have
            if (SpeedFormat == SpinSpeedFormat.RevolutionCount)
            {
                revTimeMs = (TimeSpan.TotalMilliseconds - pulseConstant) /
                            (RevolutionCount + pulseFractional - pulseInterpolationOffset);
            }
            else if (SpeedFormat == SpinSpeedFormat.RevolutionFrequency)
            {
                revTimeMs = (1.0 / RevolutionFrequency) * 1000.0;             // convert Hz to period ms
            }
            else if (SpeedFormat == SpinSpeedFormat.FixedTime)
            {
                revTimeMs = RevolutionTime;
            }

            double pulTimeMs = pulseConstant + (revTimeMs * pulseFractional);

            TimeSpan revTimeSpan   = TimeSpan.FromMilliseconds(revTimeMs);
            TimeSpan pulseTimeSpan = TimeSpan.FromMilliseconds(pulTimeMs);

            // figure out which way we're moving through the elements
            Curve movement;

            if (ReverseSpin)
            {
                movement = new Curve(new PointPairList(new double[] { 0, 100 }, new double[] { 100, 0 }));
            }
            else
            {
                movement = new Curve(new PointPairList(new double[] { 0, 100 }, new double[] { 0, 100 }));
            }

            // iterate up to and including the last pulse generated
            // a bit iffy, but stops 'carry over' spins past the end (when there's overlapping spins). But we need to go past
            // (total - pulse) as the last pulse can often be a bit inaccurate due to the rounding of the increment
            for (TimeSpan current = TimeSpan.Zero; current <= TimeSpan - pulseTimeSpan + increment; current += increment)
            {
                if (tokenSource != null && tokenSource.IsCancellationRequested)
                {
                    return;
                }

                double currentPercentageIntoSpin = ((double)(current.Ticks % revTimeSpan.Ticks) / (double)revTimeSpan.Ticks) * 100.0;

                double targetElementPosition = movement.GetValue(currentPercentageIntoSpin);
                int    currentNodeIndex      = (int)((targetElementPosition / 100.0) * targetNodeCount);

                // on the off chance we hit the 100% mark *exactly*...
                if (currentNodeIndex == targetNodeCount)
                {
                    currentNodeIndex--;
                }

                if (currentNodeIndex >= targetNodeCount)
                {
                    Logging.Warn(
                        "Spin effect: rendering, but the current node index is higher or equal to the total target nodes.");
                    continue;
                }

                ElementNode currentNode = renderNodes[currentNodeIndex];
                if (currentNode == lastTargetedNode)
                {
                    continue;
                }

                bool discreteColors = ColorModule.isElementNodeDiscreteColored(currentNode);

                // make a pulse for it
                pulse             = new Pulse.Pulse();
                pulse.TargetNodes = new ElementNode[] { currentNode };
                pulse.TimeSpan    = pulseTimeSpan;
                pulse.LevelCurve  = new Curve(PulseCurve);

                // figure out what color gradient to use for the pulse
                switch (ColorHandling)
                {
                case SpinColorHandling.GradientForEachPulse:
                    pulse.ColorGradient = ColorGradient;
                    pulseData           = pulse.Render();
                    pulseData.OffsetAllCommandsByTime(current);
                    _elementData.Add(pulseData);
                    break;

                case SpinColorHandling.GradientThroughWholeEffect:
                    double startPos = ((double)current.Ticks / (double)TimeSpan.Ticks);
                    double endPos   = 1.0;
                    if (TimeSpan - current >= pulseTimeSpan)
                    {
                        endPos = ((double)(current + pulseTimeSpan).Ticks / (double)TimeSpan.Ticks);
                    }

                    if (discreteColors)
                    {
                        double range = endPos - startPos;
                        if (range <= 0.0)
                        {
                            Logging.Error("Spin: bad range: " + range + " (SP=" + startPos + ", EP=" + endPos + ")");
                            break;
                        }

                        ColorGradient cg = ColorGradient.GetSubGradientWithDiscreteColors(startPos, endPos);

                        foreach (Color color in cg.GetColorsInGradient())
                        {
                            if (tokenSource != null && tokenSource.IsCancellationRequested)
                            {
                                return;
                            }

                            Curve newCurve = new Curve(pulse.LevelCurve.Points);
                            foreach (PointPair point in newCurve.Points)
                            {
                                double effectRelativePosition = startPos + ((point.X / 100.0) * range);
                                double proportion             = ColorGradient.GetProportionOfColorAt(effectRelativePosition, color);
                                point.Y *= proportion;
                            }
                            pulse.LevelCurve    = newCurve;
                            pulse.ColorGradient = new ColorGradient(color);
                            pulseData           = pulse.Render();
                            pulseData.OffsetAllCommandsByTime(current);
                            _elementData.Add(pulseData);
                        }
                    }
                    else
                    {
                        pulse.ColorGradient = ColorGradient.GetSubGradient(startPos, endPos);
                        pulseData           = pulse.Render();
                        pulseData.OffsetAllCommandsByTime(current);
                        _elementData.Add(pulseData);
                    }
                    break;

                case SpinColorHandling.StaticColor:
                    pulse.ColorGradient = StaticColorGradient;
                    pulseData           = pulse.Render();
                    pulseData.OffsetAllCommandsByTime(current);
                    _elementData.Add(pulseData);
                    break;

                case SpinColorHandling.ColorAcrossItems:
                    if (discreteColors)
                    {
                        List <Tuple <Color, float> > colorsAtPosition = ColorGradient.GetDiscreteColorsAndProportionsAt(targetElementPosition / 100.0);
                        foreach (Tuple <Color, float> colorProportion in colorsAtPosition)
                        {
                            if (tokenSource != null && tokenSource.IsCancellationRequested)
                            {
                                return;
                            }

                            float proportion = colorProportion.Item2;
                            // scale all levels of the pulse curve by the proportion that is applicable to this color
                            Curve newCurve = new Curve(pulse.LevelCurve.Points);
                            foreach (PointPair pointPair in newCurve.Points)
                            {
                                pointPair.Y *= proportion;
                            }
                            pulse.LevelCurve    = newCurve;
                            pulse.ColorGradient = new ColorGradient(colorProportion.Item1);
                            pulseData           = pulse.Render();
                            pulseData.OffsetAllCommandsByTime(current);
                            _elementData.Add(pulseData);
                        }
                    }
                    else
                    {
                        pulse.ColorGradient = new ColorGradient(ColorGradient.GetColorAt(targetElementPosition / 100.0));
                        pulseData           = pulse.Render();
                        pulseData.OffsetAllCommandsByTime(current);
                        _elementData.Add(pulseData);
                    }
                    break;
                }

                lastTargetedNode = currentNode;
            }

            _elementData = EffectIntents.Restrict(_elementData, TimeSpan.Zero, TimeSpan);
        }
示例#39
0
 protected abstract SpecialNode CreateWrappingNode(AttributeNode attr, ElementNode node);
示例#40
0
 protected abstract bool IsSpecialAttribute(ElementNode element, AttributeNode attribute);
示例#41
0
 protected override void Visit(ElementNode node)
 {
     Nodes.Add(node);
 }
示例#42
0
        protected EffectIntents RenderNodeByStrings(ElementNode node)
        {
            EffectIntents effectIntents = new EffectIntents();
            int           nFrames       = GetNumberFrames();

            if (nFrames <= 0 | BufferWi == 0 || BufferHt == 0)
            {
                return(effectIntents);
            }
            var buffer = new PixelFrameBuffer(BufferWi, BufferHt, UseBaseColor?BaseColor:Color.Transparent);

            int bufferSize = StringPixelCounts.Sum();

            TimeSpan startTime = TimeSpan.Zero;

            // set up arrays to hold the generated colors
            var pixels = new RGBValue[bufferSize][];

            for (int eidx = 0; eidx < bufferSize; eidx++)
            {
                pixels[eidx] = new RGBValue[nFrames];
            }

            // generate all the pixels
            for (int frameNum = 0; frameNum < nFrames; frameNum++)
            {
                if (UseBaseColor)
                {
                    var level = BaseLevelCurve.GetValue(GetEffectTimeIntervalPosition(frameNum) * 100) / 100;
                    buffer.ClearBuffer(level);
                }
                else
                {
                    buffer.ClearBuffer();
                }

                RenderEffect(frameNum, buffer);
                // peel off this frames pixels...
                if (StringOrientation == StringOrientation.Horizontal)
                {
                    int i = 0;
                    for (int y = 0; y < BufferHt; y++)
                    {
                        for (int x = 0; x < StringPixelCounts[y]; x++)
                        {
                            if (i >= pixels.Length)
                            {
                                break;
                            }
                            pixels[i][frameNum] = new RGBValue(buffer.GetColorAt(x, y));
                            i++;
                        }
                    }
                }
                else
                {
                    int i = 0;
                    for (int x = 0; x < BufferWi; x++)
                    {
                        for (int y = 0; y < StringPixelCounts[x]; y++)
                        {
                            if (i >= pixels.Length)
                            {
                                break;
                            }
                            pixels[i][frameNum] = new RGBValue(buffer.GetColorAt(x, y));
                            i++;
                        }
                    }
                }
            }

            // create the intents
            var            frameTs     = new TimeSpan(0, 0, 0, 0, FrameTime);
            List <Element> elements    = node.Distinct().ToList();
            int            numElements = elements.Count();

            for (int eidx = 0; eidx < numElements; eidx++)
            {
                IIntent intent = new StaticArrayIntent <RGBValue>(frameTs, pixels[eidx], TimeSpan);
                effectIntents.AddIntentForElement(elements[eidx].Id, intent, startTime);
            }

            return(effectIntents);
        }
示例#43
0
        private EffectIntents RenderElement(ElementNode node, double positionWithinGroup, List <IndividualTwinkleDetails> twinkles = null)
        {
            if (node == null)
            {
                return(null);
            }

            if (twinkles == null)
            {
                twinkles = GenerateTwinkleData();
            }

            EffectIntents result = new EffectIntents();

            // render the flat 'minimum value' across the entire effect
            Pulse.Pulse pulse = new Pulse.Pulse();
            pulse.TargetNodes = new ElementNode[] { node };
            pulse.TimeSpan    = TimeSpan;
            pulse.LevelCurve  = new Curve(new PointPairList(new double[] { 0, 100 }, new double[] { MinimumLevel * 100.0, MinimumLevel * 100.0 }));

            // figure out what color gradient to use for the pulse
            switch (ColorHandling)
            {
            case TwinkleColorHandling.GradientForEachPulse:
                pulse.ColorGradient = new ColorGradient(ColorGradient.GetColorAt(0));
                break;

            case TwinkleColorHandling.GradientThroughWholeEffect:
                pulse.ColorGradient = ColorGradient;
                break;

            case TwinkleColorHandling.StaticColor:
                pulse.ColorGradient = new ColorGradient(StaticColor);
                break;

            case TwinkleColorHandling.ColorAcrossItems:
                pulse.ColorGradient = new ColorGradient(ColorGradient.GetColorAt(positionWithinGroup));
                break;
            }

            EffectIntents pulseData = pulse.Render();

            result.Add(pulseData);

            // render all the individual twinkles
            foreach (IndividualTwinkleDetails twinkle in twinkles)
            {
                {
                    // make a pulse for it
                    pulse             = new Pulse.Pulse();
                    pulse.TargetNodes = new ElementNode[] { node };
                    pulse.TimeSpan    = twinkle.Duration;
                    pulse.LevelCurve  = twinkle.TwinkleCurve;

                    // figure out what color gradient to use for the pulse
                    switch (ColorHandling)
                    {
                    case TwinkleColorHandling.GradientForEachPulse:
                        pulse.ColorGradient = ColorGradient;
                        break;

                    case TwinkleColorHandling.GradientThroughWholeEffect:
                        double startPos = ((double)twinkle.StartTime.Ticks / (double)TimeSpan.Ticks);
                        double endPos   = ((double)(twinkle.StartTime + twinkle.Duration).Ticks / (double)TimeSpan.Ticks);
                        pulse.ColorGradient = ColorGradient.GetSubGradient(startPos, endPos);
                        break;

                    case TwinkleColorHandling.StaticColor:
                        pulse.ColorGradient = new ColorGradient(StaticColor);
                        break;

                    case TwinkleColorHandling.ColorAcrossItems:
                        pulse.ColorGradient = new ColorGradient(ColorGradient.GetColorAt(positionWithinGroup));
                        break;
                    }

                    pulseData = pulse.Render();
                    pulseData.OffsetAllCommandsByTime(twinkle.StartTime);
                    result.Add(pulseData);
                }
            }

            return(result);
        }
示例#44
0
文件: Chase.cs 项目: starry-au/vixen
        private void DoRendering(CancellationTokenSource tokenSource = null)
        {
            List <ElementNode> renderNodes = GetNodesToRenderOn();

            int targetNodeCount = renderNodes.Count;

            // apply the 'background' values to all targets if the level is supposed to be enabled
            if (EnableDefaultLevel)
            {
                int i = 0;
                foreach (ElementNode target in renderNodes)
                {
                    if (tokenSource != null && tokenSource.IsCancellationRequested)
                    {
                        return;
                    }

                    if (target != null)
                    {
                        bool discreteColors = ColorModule.isElementNodeDiscreteColored(target);

                        double level = DefaultLevel * 100.0;

                        // figure out what color gradient to use for the pulse
                        EffectIntents pulseData;
                        switch (ColorHandling)
                        {
                        case ChaseColorHandling.GradientForEachPulse:
                            pulseData = PulseRenderer.RenderNode(target,
                                                                 new Curve(new PointPairList(new double[] { 0, 100 }, new[] { level, level })), StaticColorGradient, TimeSpan, HasDiscreteColors, true);
                            _elementData.Add(pulseData);
                            break;

                        case ChaseColorHandling.GradientThroughWholeEffect:
                            pulseData = PulseRenderer.RenderNode(target,
                                                                 new Curve(new PointPairList(new double[] { 0, 100 }, new[] { level, level })), ColorGradient, TimeSpan, HasDiscreteColors, true);
                            _elementData.Add(pulseData);
                            break;

                        case ChaseColorHandling.StaticColor:
                            pulseData = PulseRenderer.RenderNode(target,
                                                                 new Curve(new PointPairList(new double[] { 0, 100 }, new[] { level, level })), StaticColorGradient, TimeSpan, HasDiscreteColors, true);
                            _elementData.Add(pulseData);
                            break;

                        case ChaseColorHandling.ColorAcrossItems:
                            double positionWithinGroup = i / (double)targetNodeCount;
                            if (discreteColors)
                            {
                                List <Tuple <Color, float> > colorsAtPosition =
                                    ColorGradient.GetDiscreteColorsAndProportionsAt(positionWithinGroup);
                                foreach (Tuple <Color, float> colorProportion in colorsAtPosition)
                                {
                                    if (tokenSource != null && tokenSource.IsCancellationRequested)
                                    {
                                        return;
                                    }
                                    double value = level * colorProportion.Item2;
                                    pulseData = PulseRenderer.RenderNode(target,
                                                                         new Curve(new PointPairList(new double[] { 0, 100 }, new[] { value, value })), new ColorGradient(colorProportion.Item1), TimeSpan, HasDiscreteColors, true);
                                    _elementData.Add(pulseData);
                                }
                            }
                            else
                            {
                                pulseData = PulseRenderer.RenderNode(target,
                                                                     new Curve(new PointPairList(new double[] { 0, 100 }, new [] { level, level })), new ColorGradient(ColorGradient.GetColorAt(positionWithinGroup)), TimeSpan, HasDiscreteColors, true);
                                _elementData.Add(pulseData);
                            }
                            break;
                        }

                        i++;
                    }
                }
            }



            // the total chase time
            TimeSpan chaseTime = TimeSpan.FromMilliseconds(TimeSpan.TotalMilliseconds - PulseOverlap);

            if (chaseTime.TotalMilliseconds <= 0)
            {
                chaseTime = TimeSpan.FromMilliseconds(1);
            }

            //TODO: get a better increment time. doing it every X ms is..... shitty at best.
            //Less crappy is try to make some adjustment if there are a lot of nodes in a shorter time to sample more often.
            //A hard and fast 2ms was leaving gaps in larger node counts
            var sampleMs = chaseTime.TotalMilliseconds / targetNodeCount / 2.0;

            if (sampleMs < .25)
            {
                sampleMs = .25;
            }
            else if (sampleMs > 2)
            {
                sampleMs = 2;
            }
            TimeSpan increment = TimeSpan.FromTicks((long)(sampleMs * TimeSpan.TicksPerMillisecond));


            // we need to keep track of the element that is 'under' the curve at a given time, to see if it changes,
            // and when it does, we make the effect for it then (since it's a variable time pulse).
            ElementNode lastTargetedNode  = null;
            TimeSpan    lastNodeStartTime = TimeSpan.Zero;

            // iterate up to and including the last pulse generated
            for (TimeSpan current = TimeSpan.Zero; current <= TimeSpan; current += increment)
            {
                if (tokenSource != null && tokenSource.IsCancellationRequested)
                {
                    return;
                }
                double currentPercentageIntoChase = (current.Ticks / (double)chaseTime.Ticks) * 100.0;

                double currentMovementPosition = ChaseMovement.GetValue(currentPercentageIntoChase);
                int    currentNodeIndex        = (int)((currentMovementPosition / 100.0) * targetNodeCount);

                // on the off chance we hit the 100% mark *exactly*...
                if (currentNodeIndex == targetNodeCount && currentNodeIndex > 0)
                {
                    currentNodeIndex--;
                }

                if (currentNodeIndex >= targetNodeCount)
                {
                    Logging.Warn(
                        "Chase effect: rendering, but the current node index is higher or equal to the total target nodes.");
                    continue;
                }

                if (currentNodeIndex < 0)
                {
                    continue;
                }

                ElementNode currentNode = renderNodes[currentNodeIndex];
                if (currentNode == lastTargetedNode)
                {
                    continue;
                }

                // if the last node targeted wasn't null, we need to make a pulse for it
                if (lastTargetedNode != null)
                {
                    TimeSpan duration = current - lastNodeStartTime + TimeSpan.FromMilliseconds(PulseOverlap);
                    GeneratePulse(lastTargetedNode, lastNodeStartTime, duration
                                  , currentMovementPosition);
                }

                lastTargetedNode  = currentNode;
                lastNodeStartTime = current;

                // if we've hit the 100% mark of the chase curve, bail (the last one gets generated after)
                if (currentPercentageIntoChase >= 100.0)
                {
                    break;
                }
            }

            // generate the last pulse
            if (lastTargetedNode != null)
            {
                GeneratePulse(lastTargetedNode, lastNodeStartTime, TimeSpan - lastNodeStartTime, ChaseMovement.GetValue(100));
            }

            _elementData = EffectIntents.Restrict(_elementData, TimeSpan.Zero, TimeSpan);
        }
 public RemoteDownloaderSmartTag(ITextView textView, ITextBuffer textBuffer, ElementNode element, AttributeNode attribute)
     : base(textView, textBuffer, element, HtmlSmartTagPosition.StartTag)
 {
     _attribute = attribute;
 }
 public ProcessResult Process(ElementNode node, ProcessContext context = null, Dictionary <string, object> settings = null)
 {
     throw new NotImplementedException();
 }
示例#47
0
        public PreviewCane(PreviewPoint point, ElementNode selectedNode)
        {
            _topLeftPoint     = point;
            _bottomRightPoint = new PreviewPoint(point.X, point.Y);
            _archLeftPoint    = new PreviewPoint(point.X, point.Y);

            _archPixelCount = 8;
            _linePixelCount = 8;

            int lightCount = _archPixelCount + _linePixelCount;

            if (selectedNode != null)
            {
                //List<ElementNode> children = selectedNode.Children.ToList();
                List <ElementNode> children = PreviewTools.GetLeafNodes(selectedNode);
                // is this a single node?
                if (children.Count >= 8)
                {
                    StringType      = StringTypes.Pixel;
                    _archPixelCount = children.Count / 2;
                    _linePixelCount = children.Count / 2;
                    if (_archPixelCount + _linePixelCount > children.Count)
                    {
                        _archPixelCount -= 1;
                    }
                    else if (_archPixelCount + _linePixelCount < children.Count)
                    {
                        _linePixelCount -= 1;
                    }
                    lightCount = children.Count;
                    // Just add the pixels, they will get layed out next
                    foreach (ElementNode child in children)
                    {
                        PreviewPixel pixel = AddPixel(10, 10);
                        pixel.Node = child;
                        //pixel.NodeId = child.Id;
                        pixel.PixelColor = Color.White;
                    }
                }
            }

            if (_pixels.Count == 0)
            {
                // Just add the pixels, they will get layed out next
                for (int lightNum = 0; lightNum < lightCount; lightNum++)
                {
                    PreviewPixel pixel = AddPixel(10, 10);
                    pixel.PixelColor = Color.White;
                    if (selectedNode != null && selectedNode.IsLeaf)
                    {
                        pixel.Node = selectedNode;
                        //pixel.NodeId = selectedNode.Id;
                    }
                }
            }

            // Lay out the pixels
            Layout();

            //DoResize += new ResizeEvent(OnResize);
        }
示例#48
0
 public void Visit(ElementNode node, INode parentNode)
 {
 }
示例#49
0
 public void profile_serialize_xml()
 {
     _xmlNode = Bender.Serializer.Create().SerializeNodes(_object, (n, o) =>
                                                          ElementNode.Create(n.Name, Metadata.Empty, Options.Create()), XmlNodeBase.NodeFormat);
 }
        IEnumerable <Instruction> PushValueFromLanguagePrimitive(TypeDefinition typedef, ElementNode node)
        {
            var hasValue = node.CollectionItems.Count == 1 && node.CollectionItems[0] is ValueNode &&
                           ((ValueNode)node.CollectionItems[0]).Value is string;
            var valueString = hasValue ? ((ValueNode)node.CollectionItems[0]).Value as string : string.Empty;

            switch (typedef.FullName)
            {
            case "System.SByte":
                sbyte outsbyte;
                if (hasValue && sbyte.TryParse(valueString, NumberStyles.Number, CultureInfo.InvariantCulture, out outsbyte))
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I4, (int)outsbyte));
                }
                else
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I4, 0x00));
                }
                break;

            case "System.Int16":
                short outshort;
                if (hasValue && short.TryParse(valueString, NumberStyles.Number, CultureInfo.InvariantCulture, out outshort))
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I4, outshort));
                }
                else
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I4, 0x00));
                }
                break;

            case "System.Int32":
                int outint;
                if (hasValue && int.TryParse(valueString, NumberStyles.Number, CultureInfo.InvariantCulture, out outint))
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I4, outint));
                }
                else
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I4, 0x00));
                }
                break;

            case "System.Int64":
                long outlong;
                if (hasValue && long.TryParse(valueString, NumberStyles.Number, CultureInfo.InvariantCulture, out outlong))
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I8, outlong));
                }
                else
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I8, 0L));
                }
                break;

            case "System.Byte":
                byte outbyte;
                if (hasValue && byte.TryParse(valueString, NumberStyles.Number, CultureInfo.InvariantCulture, out outbyte))
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I4, (int)outbyte));
                }
                else
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I4, 0x00));
                }
                break;

            case "System.UInt16":
                short outushort;
                if (hasValue && short.TryParse(valueString, NumberStyles.Number, CultureInfo.InvariantCulture, out outushort))
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I4, outushort));
                }
                else
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I4, 0x00));
                }
                break;

            case "System.UInt32":
                int outuint;
                if (hasValue && int.TryParse(valueString, NumberStyles.Number, CultureInfo.InvariantCulture, out outuint))
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I4, outuint));
                }
                else
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I4, 0x00));
                }
                break;

            case "System.UInt64":
                long outulong;
                if (hasValue && long.TryParse(valueString, NumberStyles.Number, CultureInfo.InvariantCulture, out outulong))
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I8, outulong));
                }
                else
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I8, 0L));
                }
                break;

            case "System.Boolean":
                bool outbool;
                if (hasValue && bool.TryParse(valueString, out outbool))
                {
                    yield return(Instruction.Create(outbool ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0));
                }
                else
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I4_0));
                }
                break;

            case "System.String":
                yield return(Instruction.Create(OpCodes.Ldstr, valueString));

                break;

            case "System.Object":
                var ctorinfo =
                    Context.Body.Method.Module.TypeSystem.Object.Resolve()
                    .Methods.FirstOrDefault(md => md.IsConstructor && !md.HasParameters);
                var ctor = Context.Body.Method.Module.ImportReference(ctorinfo);
                yield return(Instruction.Create(OpCodes.Newobj, ctor));

                break;

            case "System.Char":
                char outchar;
                if (hasValue && char.TryParse(valueString, out outchar))
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I4, outchar));
                }
                else
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I4, 0x00));
                }
                break;

            case "System.Decimal":
                decimal outdecimal;
                if (hasValue && decimal.TryParse(valueString, NumberStyles.Number, CultureInfo.InvariantCulture, out outdecimal))
                {
                    var vardef = new VariableDefinition(Context.Body.Method.Module.ImportReference(typeof(decimal)));
                    Context.Body.Variables.Add(vardef);
                    //Use an extra temp var so we can push the value to the stack, just like other cases
                    //					IL_0003:  ldstr "adecimal"
                    //					IL_0008:  ldc.i4.s 0x6f
                    //					IL_000a:  call class [mscorlib]System.Globalization.CultureInfo class [mscorlib]System.Globalization.CultureInfo::get_InvariantCulture()
                    //					IL_000f:  ldloca.s 0
                    //					IL_0011:  call bool valuetype [mscorlib]System.Decimal::TryParse(string, valuetype [mscorlib]System.Globalization.NumberStyles, class [mscorlib]System.IFormatProvider, [out] valuetype [mscorlib]System.Decimal&)
                    //					IL_0016:  pop
                    yield return(Instruction.Create(OpCodes.Ldstr, valueString));

                    yield return(Instruction.Create(OpCodes.Ldc_I4, 0x6f));                    //NumberStyles.Number

                    var getInvariantInfo =
                        Context.Body.Method.Module.ImportReference(typeof(CultureInfo))
                        .Resolve()
                        .Properties.FirstOrDefault(pd => pd.Name == "InvariantCulture")
                        .GetMethod;
                    var getInvariant = Context.Body.Method.Module.ImportReference(getInvariantInfo);
                    yield return(Instruction.Create(OpCodes.Call, getInvariant));

                    yield return(Instruction.Create(OpCodes.Ldloca, vardef));

                    var tryParseInfo =
                        Context.Body.Method.Module.ImportReference(typeof(decimal))
                        .Resolve()
                        .Methods.FirstOrDefault(md => md.Name == "TryParse" && md.Parameters.Count == 4);
                    var tryParse = Context.Body.Method.Module.ImportReference(tryParseInfo);
                    yield return(Instruction.Create(OpCodes.Call, tryParse));

                    yield return(Instruction.Create(OpCodes.Pop));

                    yield return(Instruction.Create(OpCodes.Ldloc, vardef));
                }
                else
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I4_0));

                    var decimalctorinfo =
                        Context.Body.Method.Module.ImportReference(typeof(decimal))
                        .Resolve()
                        .Methods.FirstOrDefault(
                            md => md.IsConstructor && md.Parameters.Count == 1 && md.Parameters [0].ParameterType.FullName == "System.Int32");
                    var decimalctor = Context.Body.Method.Module.ImportReference(decimalctorinfo);
                    yield return(Instruction.Create(OpCodes.Newobj, decimalctor));
                }
                break;

            case "System.Single":
                float outfloat;
                if (hasValue && float.TryParse(valueString, NumberStyles.Number, CultureInfo.InvariantCulture, out outfloat))
                {
                    yield return(Instruction.Create(OpCodes.Ldc_R4, outfloat));
                }
                else
                {
                    yield return(Instruction.Create(OpCodes.Ldc_R4, 0f));
                }
                break;

            case "System.Double":
                double outdouble;
                if (hasValue && double.TryParse(valueString, NumberStyles.Number, CultureInfo.InvariantCulture, out outdouble))
                {
                    yield return(Instruction.Create(OpCodes.Ldc_R8, outdouble));
                }
                else
                {
                    yield return(Instruction.Create(OpCodes.Ldc_R8, 0d));
                }
                break;

            case "System.TimeSpan":
                TimeSpan outspan;
                if (hasValue && TimeSpan.TryParse(valueString, CultureInfo.InvariantCulture, out outspan))
                {
                    var vardef = new VariableDefinition(Context.Body.Method.Module.ImportReference(typeof(TimeSpan)));
                    Context.Body.Variables.Add(vardef);
                    //Use an extra temp var so we can push the value to the stack, just like other cases
                    yield return(Instruction.Create(OpCodes.Ldstr, valueString));

                    var getInvariantInfo =
                        Context.Body.Method.Module.ImportReference(typeof(CultureInfo))
                        .Resolve()
                        .Properties.FirstOrDefault(pd => pd.Name == "InvariantCulture")
                        .GetMethod;
                    var getInvariant = Context.Body.Method.Module.ImportReference(getInvariantInfo);
                    yield return(Instruction.Create(OpCodes.Call, getInvariant));

                    yield return(Instruction.Create(OpCodes.Ldloca, vardef));

                    var tryParseInfo =
                        Context.Body.Method.Module.ImportReference(typeof(TimeSpan))
                        .Resolve()
                        .Methods.FirstOrDefault(md => md.Name == "TryParse" && md.Parameters.Count == 3);
                    var tryParse = Context.Body.Method.Module.ImportReference(tryParseInfo);
                    yield return(Instruction.Create(OpCodes.Call, tryParse));

                    yield return(Instruction.Create(OpCodes.Pop));

                    yield return(Instruction.Create(OpCodes.Ldloc, vardef));
                }
                else
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I8, 0L));

                    var timespanctorinfo =
                        Context.Body.Method.Module.ImportReference(typeof(TimeSpan))
                        .Resolve()
                        .Methods.FirstOrDefault(
                            md => md.IsConstructor && md.Parameters.Count == 1 && md.Parameters [0].ParameterType.FullName == "System.Int64");
                    var timespanctor = Context.Body.Method.Module.ImportReference(timespanctorinfo);
                    yield return(Instruction.Create(OpCodes.Newobj, timespanctor));
                }
                break;

            case "System.Uri":
                Uri outuri;
                if (hasValue && Uri.TryCreate(valueString, UriKind.RelativeOrAbsolute, out outuri))
                {
                    var vardef = new VariableDefinition(Context.Body.Method.Module.ImportReference(typeof(Uri)));
                    Context.Body.Variables.Add(vardef);
                    //Use an extra temp var so we can push the value to the stack, just like other cases
                    yield return(Instruction.Create(OpCodes.Ldstr, valueString));

                    yield return(Instruction.Create(OpCodes.Ldc_I4, (int)UriKind.RelativeOrAbsolute));

                    yield return(Instruction.Create(OpCodes.Ldloca, vardef));

                    var tryCreateInfo =
                        Context.Body.Method.Module.ImportReference(typeof(Uri))
                        .Resolve()
                        .Methods.FirstOrDefault(md => md.Name == "TryCreate" && md.Parameters.Count == 3);
                    var tryCreate = Context.Body.Method.Module.ImportReference(tryCreateInfo);
                    yield return(Instruction.Create(OpCodes.Call, tryCreate));

                    yield return(Instruction.Create(OpCodes.Pop));

                    yield return(Instruction.Create(OpCodes.Ldloc, vardef));
                }
                else
                {
                    yield return(Instruction.Create(OpCodes.Ldnull));
                }
                break;

            default:
                var defaultctorinfo = typedef.Methods.FirstOrDefault(md => md.IsConstructor && !md.HasParameters);
                if (defaultctorinfo != null)
                {
                    var defaultctor = Context.Body.Method.Module.ImportReference(defaultctorinfo);
                    yield return(Instruction.Create(OpCodes.Newobj, defaultctor));
                }
                else
                {
                    //should never happen. but if it does, this prevents corrupting the IL stack
                    yield return(Instruction.Create(OpCodes.Ldnull));
                }
                break;
            }
        }
示例#51
0
        protected override bool IsSpecialAttribute(ElementNode element, AttributeNode attr)
        {
            var name = AttrName(attr);

            return(name == "cache" || name == "cache.key" || name == "cache.expires" || name == "cache.signal");
        }
        public void Visit(ElementNode node, INode parentNode)
        {
            var            typeref = Module.ImportReference(node.XmlType.GetTypeReference(Module, node));
            TypeDefinition typedef = typeref.Resolve();

            if (IsXaml2009LanguagePrimitive(node))
            {
                var vardef = new VariableDefinition(typeref);
                Context.Variables [node] = vardef;
                Context.Body.Variables.Add(vardef);

                Context.IL.Append(PushValueFromLanguagePrimitive(typedef, node));
                Context.IL.Emit(OpCodes.Stloc, vardef);
                return;
            }

            if (typeref.FullName == "Xamarin.Forms.Xaml.StaticExtension")
            {
                var markupProvider = new StaticExtension();

                var il = markupProvider.ProvideValue(node, Module, Context, out typeref);
                typeref = Module.ImportReference(typeref);

                var vardef = new VariableDefinition(typeref);
                Context.Variables [node] = vardef;
                Context.Body.Variables.Add(vardef);

                Context.IL.Append(il);
                Context.IL.Emit(OpCodes.Stloc, vardef);

                //clean the node as it has been fully exhausted
                node.Properties.Clear();
                node.CollectionItems.Clear();
                return;
            }

            MethodDefinition factoryCtorInfo       = null;
            MethodDefinition factoryMethodInfo     = null;
            MethodDefinition parameterizedCtorInfo = null;
            MethodDefinition ctorInfo = null;

            if (node.Properties.ContainsKey(XmlName.xArguments) && !node.Properties.ContainsKey(XmlName.xFactoryMethod))
            {
                factoryCtorInfo = typedef.AllMethods().FirstOrDefault(md => md.IsConstructor &&
                                                                      !md.IsStatic &&
                                                                      md.HasParameters &&
                                                                      md.MatchXArguments(node, Module, Context));
                if (factoryCtorInfo == null)
                {
                    throw new XamlParseException(
                              string.Format("No constructors found for {0} with matching x:Arguments", typedef.FullName), node);
                }
                ctorInfo = factoryCtorInfo;
                if (!typedef.IsValueType)                 //for ctor'ing typedefs, we first have to ldloca before the params
                {
                    Context.IL.Append(PushCtorXArguments(factoryCtorInfo, node));
                }
            }
            else if (node.Properties.ContainsKey(XmlName.xFactoryMethod))
            {
                var factoryMethod = (string)(node.Properties [XmlName.xFactoryMethod] as ValueNode).Value;
                factoryMethodInfo = typedef.AllMethods().FirstOrDefault(md => !md.IsConstructor &&
                                                                        md.Name == factoryMethod &&
                                                                        md.IsStatic &&
                                                                        md.MatchXArguments(node, Module, Context));
                if (factoryMethodInfo == null)
                {
                    throw new XamlParseException(
                              String.Format("No static method found for {0}::{1} ({2})", typedef.FullName, factoryMethod, null), node);
                }
                Context.IL.Append(PushCtorXArguments(factoryMethodInfo, node));
            }
            if (ctorInfo == null && factoryMethodInfo == null)
            {
                parameterizedCtorInfo = typedef.Methods.FirstOrDefault(md => md.IsConstructor &&
                                                                       !md.IsStatic &&
                                                                       md.HasParameters &&
                                                                       md.Parameters.All(
                                                                           pd =>
                                                                           pd.CustomAttributes.Any(
                                                                               ca =>
                                                                               ca.AttributeType.FullName ==
                                                                               "Xamarin.Forms.ParameterAttribute")));
            }
            if (parameterizedCtorInfo != null && ValidateCtorArguments(parameterizedCtorInfo, node))
            {
                ctorInfo = parameterizedCtorInfo;
//				IL_0000:  ldstr "foo"
                Context.IL.Append(PushCtorArguments(parameterizedCtorInfo, node));
            }
            ctorInfo = ctorInfo ?? typedef.Methods.FirstOrDefault(md => md.IsConstructor && !md.HasParameters && !md.IsStatic);

            var ctorinforef          = ctorInfo?.ResolveGenericParameters(typeref, Module);
            var factorymethodinforef = factoryMethodInfo?.ResolveGenericParameters(typeref, Module);
            var implicitOperatorref  = typedef.Methods.FirstOrDefault(md =>
                                                                      md.IsPublic &&
                                                                      md.IsStatic &&
                                                                      md.IsSpecialName &&
                                                                      md.Name == "op_Implicit" && md.Parameters [0].ParameterType.FullName == "System.String");

            if (ctorinforef != null || factorymethodinforef != null || typedef.IsValueType)
            {
                VariableDefinition vardef = new VariableDefinition(typeref);
                Context.Variables [node] = vardef;
                Context.Body.Variables.Add(vardef);

                ValueNode vnode = null;
                if (node.CollectionItems.Count == 1 && (vnode = node.CollectionItems.First() as ValueNode) != null &&
                    vardef.VariableType.IsValueType)
                {
                    //<Color>Purple</Color>
                    Context.IL.Append(vnode.PushConvertedValue(Context, typeref, new ICustomAttributeProvider [] { typedef },
                                                               node.PushServiceProvider(Context), false, true));
                    Context.IL.Emit(OpCodes.Stloc, vardef);
                }
                else if (node.CollectionItems.Count == 1 && (vnode = node.CollectionItems.First() as ValueNode) != null &&
                         implicitOperatorref != null)
                {
                    //<FileImageSource>path.png</FileImageSource>
                    var implicitOperator = Module.ImportReference(implicitOperatorref);
                    Context.IL.Emit(OpCodes.Ldstr, ((ValueNode)(node.CollectionItems.First())).Value as string);
                    Context.IL.Emit(OpCodes.Call, implicitOperator);
                    Context.IL.Emit(OpCodes.Stloc, vardef);
                }
                else if (factorymethodinforef != null)
                {
                    Context.IL.Emit(OpCodes.Call, Module.ImportReference(factorymethodinforef));
                    Context.IL.Emit(OpCodes.Stloc, vardef);
                }
                else if (!typedef.IsValueType)
                {
                    var ctor = Module.ImportReference(ctorinforef);
//					IL_0001:  newobj instance void class [Xamarin.Forms.Core]Xamarin.Forms.Button::'.ctor'()
//					IL_0006:  stloc.0
                    Context.IL.Emit(OpCodes.Newobj, ctor);
                    Context.IL.Emit(OpCodes.Stloc, vardef);
                }
                else if (ctorInfo != null && node.Properties.ContainsKey(XmlName.xArguments) &&
                         !node.Properties.ContainsKey(XmlName.xFactoryMethod) && ctorInfo.MatchXArguments(node, Module, Context))
                {
//					IL_0008:  ldloca.s 1
//					IL_000a:  ldc.i4.1
//					IL_000b:  call instance void valuetype Test/Foo::'.ctor'(bool)

                    var ctor = Module.ImportReference(ctorinforef);
                    Context.IL.Emit(OpCodes.Ldloca, vardef);
                    Context.IL.Append(PushCtorXArguments(factoryCtorInfo, node));
                    Context.IL.Emit(OpCodes.Call, ctor);
                }
                else
                {
//					IL_0000:  ldloca.s 0
//					IL_0002:  initobj Test/Foo
                    Context.IL.Emit(OpCodes.Ldloca, vardef);
                    Context.IL.Emit(OpCodes.Initobj, Module.ImportReference(typedef));
                }

                if (typeref.FullName == "Xamarin.Forms.Xaml.TypeExtension")
                {
                    var visitor = new SetPropertiesVisitor(Context);
                    foreach (var cnode in node.Properties.Values.ToList())
                    {
                        cnode.Accept(visitor, node);
                    }
                    foreach (var cnode in node.CollectionItems)
                    {
                        cnode.Accept(visitor, node);
                    }

                    //As we're stripping the TypeExtension bare, keep the type if we need it later (hint: we do need it)
                    INode ntype;
                    if (!node.Properties.TryGetValue(new XmlName("", "TypeName"), out ntype))
                    {
                        ntype = node.CollectionItems [0];
                    }

                    var type   = ((ValueNode)ntype).Value as string;
                    var prefix = "";
                    if (type.Contains(":"))
                    {
                        prefix = type.Split(':') [0].Trim();
                        type   = type.Split(':') [1].Trim();
                    }
                    var namespaceuri = node.NamespaceResolver.LookupNamespace(prefix);
                    Context.TypeExtensions [node] = new XmlType(namespaceuri, type, null).GetTypeReference(Module, node);

                    if (!node.SkipProperties.Contains(new XmlName("", "TypeName")))
                    {
                        node.SkipProperties.Add(new XmlName("", "TypeName"));
                    }

                    var vardefref = new VariableDefinitionReference(vardef);
                    Context.IL.Append(SetPropertiesVisitor.ProvideValue(vardefref, Context, Module, node));
                    if (vardef != vardefref.VariableDefinition)
                    {
                        Context.Variables [node] = vardefref.VariableDefinition;
                        Context.Body.Variables.Add(vardefref.VariableDefinition);
                    }
                }

                if (typeref.FullName == "Xamarin.Forms.Xaml.ArrayExtension")
                {
                    var visitor = new SetPropertiesVisitor(Context);
                    foreach (var cnode in node.Properties.Values.ToList())
                    {
                        cnode.Accept(visitor, node);
                    }
                    foreach (var cnode in node.CollectionItems)
                    {
                        cnode.Accept(visitor, node);
                    }

                    var markupProvider = new ArrayExtension();

                    var il = markupProvider.ProvideValue(node, Module, Context, out typeref);

                    vardef = new VariableDefinition(typeref);
                    Context.Variables[node] = vardef;
                    Context.Body.Variables.Add(vardef);

                    Context.IL.Append(il);
                    Context.IL.Emit(OpCodes.Stloc, vardef);

                    //clean the node as it has been fully exhausted
                    node.Properties.Remove(new XmlName("", "Type"));
                    node.CollectionItems.Clear();
                }
            }
        }
        public bool HasSuggestedActions(ITextView textView, ITextBuffer textBuffer, int caretPosition, ElementNode element, AttributeNode attribute, HtmlPositionType positionType)
        {
            if (!element.IsElement("img"))
            {
                return(false);
            }

            AttributeNode src = element.GetAttribute("src");

            if (src == null)
            {
                return(false);
            }

            return(src.Value.StartsWith("data:image/", StringComparison.Ordinal));
        }
        IEnumerable <Instruction> PushCtorXArguments(MethodDefinition factoryCtorInfo, ElementNode enode)
        {
            if (!enode.Properties.ContainsKey(XmlName.xArguments))
            {
                yield break;
            }

            var arguments = new List <INode>();
            var node      = enode.Properties[XmlName.xArguments] as ElementNode;

            if (node != null)
            {
                arguments.Add(node);
            }
            var list = enode.Properties[XmlName.xArguments] as ListNode;

            if (list != null)
            {
                foreach (var n in list.CollectionItems)
                {
                    arguments.Add(n);
                }
            }

            for (var i = 0; i < factoryCtorInfo.Parameters.Count; i++)
            {
                var parameter = factoryCtorInfo.Parameters[i];
                var arg       = arguments[i];
                VariableDefinition vardef;
                ValueNode          vnode = null;

                if (arg is IElementNode && (vardef = Context.Variables[arg as IElementNode]) != null)
                {
                    yield return(Instruction.Create(OpCodes.Ldloc, vardef));
                }
                else if ((vnode = arg as ValueNode) != null)
                {
                    foreach (var instruction in vnode.PushConvertedValue(Context,
                                                                         parameter.ParameterType,
                                                                         new ICustomAttributeProvider[] { parameter, parameter.ParameterType.Resolve() },
                                                                         enode.PushServiceProvider(Context), false, true))
                    {
                        yield return(instruction);
                    }
                }
            }
        }
示例#55
0
        public void TestDynaBinding()
        {
            var input = (ElementNode.Node("root",
                                          ElementNode.Valued("child", "Hello world!", "string"), ElementNode.Valued("child", 4L, "integer"))).ToNavigator();

            Assert.Equal("ello", input.Scalar(@"$this.child[0].substring(1,%context.child[1])"));
        }
示例#56
0
        private IEnumerable <IOutputFilterModuleInstance> _findFiltersThatDescendFromElement(ElementNode element)
        {
            if (element == null || element.Element == null)
            {
                return(Enumerable.Empty <IOutputFilterModuleInstance>());
            }

            return(_findComponentsOfTypeInTreeFromComponent(
                       VixenSystem.DataFlow.GetComponent(element.Element.Id),
                       typeof(IOutputFilterModuleInstance))
                   .Cast <IOutputFilterModuleInstance>());
        }
示例#57
0
        public PreviewTriangle(PreviewPoint point1, ElementNode selectedNode, double zoomLevel)
        {
            ZoomLevel         = zoomLevel;
            _bottomRightPoint = PointToZoomPoint(point1);
            _point1           = new PreviewPoint(_bottomRightPoint);
            _point2           = new PreviewPoint(_bottomRightPoint);
            _point3           = new PreviewPoint(_bottomRightPoint);

            _strings = new List <PreviewBaseShape>();

            if (selectedNode != null)
            {
                List <ElementNode> children = PreviewTools.GetLeafNodes(selectedNode);
                if (children.Count >= 6)
                //
                {
                    int increment  = children.Count / 3;
                    int pixelsLeft = children.Count;

                    StringType = StringTypes.Pixel;

                    // Just add lines, they will be layed out in Layout()
                    for (int i = 0; i < 3; i++)
                    {
                        PreviewLine line;
                        if (pixelsLeft >= increment)
                        {
                            line = new PreviewLine(new PreviewPoint(10, 10), new PreviewPoint(20, 20), increment, null, ZoomLevel);
                        }
                        else
                        {
                            line = new PreviewLine(new PreviewPoint(10, 10), new PreviewPoint(20, 20), pixelsLeft, null, ZoomLevel);
                        }
                        line.PixelColor = Color.White;
                        _strings.Add(line);

                        pixelsLeft -= increment;
                    }

                    int pixelNum = 0;
                    foreach (PreviewPixel pixel in Pixels)
                    {
                        pixel.Node   = children[pixelNum];
                        pixel.NodeId = children[pixelNum].Id;
                        pixelNum++;
                    }
                }
            }

            if (_strings.Count == 0)
            {
                // Just add lines, they will be layed out in Layout()
                for (int i = 0; i < 3; i++)
                {
                    PreviewLine line;
                    line            = new PreviewLine(new PreviewPoint(10, 10), new PreviewPoint(20, 20), 10, selectedNode, ZoomLevel);
                    line.PixelColor = Color.White;
                    _strings.Add(line);
                }
            }

            Layout();
        }
示例#58
0
 public static bool HasAttribute(this ElementNode element, string attributeName, bool ignoreCase = true)
 {
     return(element.GetAttribute(attributeName, ignoreCase) != null);
 }
示例#59
0
文件: Chase.cs 项目: starry-au/vixen
        private void GeneratePulse(ElementNode target, TimeSpan startTime, TimeSpan duration, double currentMovementPosition)
        {
            EffectIntents result = null;

            //bool discreteColors = ColorModule.isElementNodeDiscreteColored(target);
            IIntentNode intent;

            // figure out what color gradient to use for the pulse
            switch (ColorHandling)
            {
            case ChaseColorHandling.GradientForEachPulse:
                result = PulseRenderer.RenderNode(target, PulseCurve, ColorGradient, duration, HasDiscreteColors);
                result.OffsetAllCommandsByTime(startTime);
                if (ExtendPulseToStart && result.Count > 0)
                {
                    foreach (var effectIntent in result)
                    {
                        var iintentNode = effectIntent.Value.FirstOrDefault();
                        GenerateStartingStaticPulse(target, iintentNode);
                    }
                }
                _elementData.Add(result);
                if (ExtendPulseToEnd && result.Count > 0)
                {
                    foreach (var effectIntent in result)
                    {
                        var iintentNode = effectIntent.Value.FirstOrDefault();
                        GenerateExtendedStaticPulse(target, iintentNode);
                    }
                }
                break;

            case ChaseColorHandling.GradientThroughWholeEffect:
                double startPos = (startTime.Ticks / (double)TimeSpan.Ticks);
                double endPos   = ((startTime + duration).Ticks / (double)TimeSpan.Ticks);
                if (startPos < 0.0)
                {
                    startPos = 0.0;
                }
                if (endPos > 1.0)
                {
                    endPos = 1.0;
                }

                if (HasDiscreteColors)
                {
                    double range = endPos - startPos;
                    if (range <= 0.0)
                    {
                        Logging.Error("Chase: bad range: " + range + " (SP=" + startPos + ", EP=" + endPos + ")");
                        break;
                    }

                    ColorGradient cg = ColorGradient.GetSubGradientWithDiscreteColors(startPos, endPos);

                    foreach (Color color in cg.GetColorsInGradient())
                    {
                        Curve newCurve = new Curve(PulseCurve.Points);
                        foreach (PointPair point in newCurve.Points)
                        {
                            double effectRelativePosition = startPos + ((point.X / 100.0) * range);
                            double proportion             = ColorGradient.GetProportionOfColorAt(effectRelativePosition, color);
                            point.Y *= proportion;
                        }
                        result = PulseRenderer.RenderNode(target, newCurve, new ColorGradient(color), duration, HasDiscreteColors);
                        result.OffsetAllCommandsByTime(startTime);
                        if (ExtendPulseToStart && result.Count > 0)
                        {
                            intent = result.FirstOrDefault().Value.FirstOrDefault();
                            GenerateStartingStaticPulse(target, intent, new ColorGradient(color));
                        }
                        if (result.Count > 0)
                        {
                            _elementData.Add(result);
                        }
                        if (ExtendPulseToEnd && result.Count > 0)
                        {
                            intent = result.FirstOrDefault().Value.LastOrDefault();
                            GenerateExtendedStaticPulse(target, intent, new ColorGradient(color));
                        }
                    }
                }
                else
                {
                    result = PulseRenderer.RenderNode(target, PulseCurve, ColorGradient.GetSubGradient(startPos, endPos), duration, HasDiscreteColors);
                    result.OffsetAllCommandsByTime(startTime);
                    if (ExtendPulseToStart && result.Count > 0)
                    {
                        intent = result.FirstOrDefault().Value.FirstOrDefault();
                        GenerateStartingStaticPulse(target, intent, ColorGradient.GetSubGradient(0, startPos));
                    }
                    _elementData.Add(result);
                    if (ExtendPulseToEnd && result.Count > 0)
                    {
                        intent = result.FirstOrDefault().Value.LastOrDefault();
                        GenerateExtendedStaticPulse(target, intent, ColorGradient.GetSubGradient(endPos, 1));
                    }
                }

                break;

            case ChaseColorHandling.StaticColor:
                result = PulseRenderer.RenderNode(target, PulseCurve, StaticColorGradient, duration, HasDiscreteColors);
                result.OffsetAllCommandsByTime(startTime);
                if (ExtendPulseToStart && result.Count > 0)
                {
                    intent = result.FirstOrDefault().Value.FirstOrDefault();
                    GenerateStartingStaticPulse(target, intent);
                }
                _elementData.Add(result);
                if (ExtendPulseToEnd && result.Count > 0)
                {
                    intent = result.FirstOrDefault().Value.LastOrDefault();
                    GenerateExtendedStaticPulse(target, intent);
                }
                break;

            case ChaseColorHandling.ColorAcrossItems:
                if (HasDiscreteColors)
                {
                    List <Tuple <Color, float> > colorsAtPosition = ColorGradient.GetDiscreteColorsAndProportionsAt(currentMovementPosition / 100.0);
                    foreach (Tuple <Color, float> colorProportion in colorsAtPosition)
                    {
                        float proportion = colorProportion.Item2;
                        // scale all levels of the pulse curve by the proportion that is applicable to this color
                        Curve newCurve = new Curve(PulseCurve.Points);
                        foreach (PointPair pointPair in newCurve.Points)
                        {
                            pointPair.Y *= proportion;
                        }
                        result = PulseRenderer.RenderNode(target, newCurve, new ColorGradient(colorProportion.Item1), duration, HasDiscreteColors);
                        result.OffsetAllCommandsByTime(startTime);
                        if (ExtendPulseToStart && result.Count > 0)
                        {
                            intent = result.FirstOrDefault().Value.FirstOrDefault();
                            GenerateStartingStaticPulse(target, intent, new ColorGradient(colorProportion.Item1));
                        }
                        if (result.Count > 0)
                        {
                            _elementData.Add(result);
                        }
                        if (ExtendPulseToEnd && result.Count > 0)
                        {
                            intent = result.FirstOrDefault().Value.LastOrDefault();
                            GenerateExtendedStaticPulse(target, intent, new ColorGradient(colorProportion.Item1));
                        }
                    }
                }
                else
                {
                    result = PulseRenderer.RenderNode(target, PulseCurve, new ColorGradient(ColorGradient.GetColorAt(currentMovementPosition / 100.0)), duration, HasDiscreteColors);
                    result.OffsetAllCommandsByTime(startTime);
                    if (ExtendPulseToStart && result.Count > 0)
                    {
                        intent = result.FirstOrDefault().Value.FirstOrDefault();
                        GenerateStartingStaticPulse(target, intent);
                    }
                    _elementData.Add(result);
                    if (ExtendPulseToEnd && result.Count > 0)
                    {
                        intent = result.FirstOrDefault().Value.LastOrDefault();
                        GenerateExtendedStaticPulse(target, intent);
                    }
                }
                break;
            }
        }
示例#60
0
文件: Chase.cs 项目: starry-au/vixen
        private void GenerateStartingStaticPulse(ElementNode target, Curve newCurve, ColorGradient gradient, TimeSpan time)
        {
            var result = PulseRenderer.RenderNode(target, newCurve, gradient, time, HasDiscreteColors);

            _elementData.Add(result);
        }