Inheritance: MonoBehaviour
Exemplo n.º 1
0
		static Selection TryExtendSelectionToComments(IDocument document, Selection selection, IList<ISpecial> commentsBlankLines)
		{
			var extendedToComments = ExtendSelectionToComments(document, selection, commentsBlankLines);
			if (extendedToComments != null)
				return extendedToComments;
			return selection;
		}
Exemplo n.º 2
0
        // Constructor
        #region Constructor


        public ObjectsPropertiesVM()
        {
            Selection = new Selection();
            Selection.PropertyChanged += Selection_SelectionSetChanged;

            //_canSelectFirstNodes = true;
        }
Exemplo n.º 3
0
 /// <summary>
 /// Replace the current selection'sections text color with  the color specified in the argument
 /// </summary>
 /// <param Name="selection">The selection to modify</param>
 /// <param Name="argument">The argument provided to the command</param>
 public override void Execute(Selection selection, string[] arguments)
 {
     //Detect which color the user wanted
     Color? color = GetColor(arguments);
     //If there was a valid color and a valid selection, apply the color to the selection
     if (color != null && selection != null) { MergeAndApply(selection, color: color); }
 }
        public MainMenu(Rectangle windowSize, KeyboardState newKeyboardState, MouseState newMouseState)
        {
            windowWidth = windowSize.Width;
            windowHeight = windowSize.Height;
            keyboardState = newKeyboardState;
            mousestate = newMouseState;
            selection = Selection.Play;
            wallpaper = new Sprite(new Rectangle(0, 0, windowWidth, windowHeight), windowSize);
            wallpaperText = new Sprite(new Rectangle(0, 0, windowWidth, windowHeight), windowSize);
            nuages = new Sprite(new Rectangle(0, 0, windowWidth * 3, windowHeight), windowSize);
            nuages.Direction = new Vector2(-1, 0);
            nuages.Vitesse = 0.1f; // 1f = 1000 px/sec
            mouse = new ParticleEngine(windowSize, new DecimalRectangle(-200, -200, 0, 0), new Vector3(1, 10, 10),
                                new List<string>() { "particle/star"}, 10, 0.1f, 2f, -45f, 15f, 0f, 180f, -1f, 1f, 10f, 150f);
            mouse.SetColorRange(0, 100, 0, 30, 0, 30);
            relativeAmplitudeVibrationSelection = (float)amplitudeVibrationSelection / (float)(windowHeight + windowWidth);
            sprites = new List<AnimatedSprite>();

            menuItems = new Dictionary<Selection, Sprite>();
            menuItems.Add(Selection.Play, new Sprite(new Rectangle(112, 423, 124, 55), windowSize, "menu/textPlay"));
            menuItems.Add(Selection.Extra, new Sprite(new Rectangle(191, 480, 124, 55), windowSize, "menu/textExtra"));
            menuItems.Add(Selection.Options, new Sprite(new Rectangle(394, 470, 135, 55), windowSize, "menu/textOptions"));
            menuItems.Add(Selection.Credit, new Sprite(new Rectangle(562, 400, 124, 55), windowSize, "menu/textCredit"));
            menuItems.Add(Selection.Exit, new Sprite(new Rectangle(675, 480, 101, 55), windowSize, "menu/textExit"));
        }
Exemplo n.º 5
0
        internal Selection ToSelection()
        {
            Selection s = new Selection();
            if (this.Pane != PaneValues.TopLeft) s.Pane = this.Pane;

            if (this.ActiveCell.Length > 0 && !this.ActiveCell.Equals("A1", StringComparison.OrdinalIgnoreCase))
            {
                s.ActiveCell = this.ActiveCell;
            }

            if (this.ActiveCellId != 0) s.ActiveCellId = this.ActiveCellId;

            if (this.SequenceOfReferences.Count > 0)
            {
                if (this.SequenceOfReferences.Count == 1)
                {
                    // not equal to A1
                    if (this.SequenceOfReferences[0].StartRowIndex != 1
                        || this.SequenceOfReferences[0].StartColumnIndex != 1
                        || this.SequenceOfReferences[0].EndRowIndex != 1
                        || this.SequenceOfReferences[0].EndColumnIndex != 1)
                    {
                        s.SequenceOfReferences = SLTool.TranslateCellPointRangeToSeqRef(this.SequenceOfReferences);
                    }
                }
                else
                {
                    s.SequenceOfReferences = SLTool.TranslateCellPointRangeToSeqRef(this.SequenceOfReferences);
                }
            }

            return s;
        }
Exemplo n.º 6
0
        public bool Contains(Selection selection)
        {
            // single line comparison
            if (selection.StartLine == StartLine && selection.EndLine == EndLine)
            {
                return selection.StartColumn >= StartColumn && selection.EndColumn <= EndColumn;
            }

            // multiline, obvious case:
            if (selection.StartLine > StartLine && selection.EndLine < EndLine)
            {
                return true;
            }

            // starts on same line:
            if (selection.StartLine == StartLine && selection.StartColumn >= StartColumn)
            {
                return selection.EndLine < EndLine || 
                    (selection.EndLine == EndLine && selection.EndColumn <= EndColumn);
            }

            // ends on same line:
            if (selection.EndLine == EndLine && selection.EndColumn <= EndColumn + 1) // +1 for \r\n
            {
                return selection.StartLine > StartLine ||
                       (selection.StartLine == StartLine && selection.StartColumn >= StartColumn);
            }

            return false;
        }
Exemplo n.º 7
0
		protected override void Init ()
		{
			var listView = new ListView ();

			var selection = new Selection ();
			listView.SetBinding (ListView.ItemsSourceProperty, "Items");

			listView.ItemTemplate = new DataTemplate (() => {
				var cell = new SwitchCell ();
				cell.SetBinding (SwitchCell.TextProperty, "Name");
				cell.SetBinding (SwitchCell.OnProperty, "IsSelected", BindingMode.TwoWay);
				return cell;
			});

			var instructions = new Label {
				FontSize = 16,
				Text =
					"The label at the bottom should equal the number of switches which are in the 'on' position. Flip some of the switches. If the number at the bottom does not equal the number of 'on' switches, the test has failed."
			};

			var label = new Label { FontSize = 24 };
			label.SetBinding (Label.TextProperty, "SelectedCount");

			Content = new StackLayout {
				VerticalOptions = LayoutOptions.Fill,
				Children = {
					instructions,
					listView,
					label
				}
			};

			BindingContext = selection;
		}
Exemplo n.º 8
0
 public YoutubeWidget(string source, 
     Selection selection) 
     : this(source)
 {
     this.mSelection = selection;
     HttpService = new HttpService();
 }
        public Calendar()
        {
            InitializeComponent();

            ItemContextMenu = new ContextMenu();
            MenuItem Block = new MenuItem();
            Block.Header = "Block";
            Block.Click += new RoutedEventHandler(MenuBlock_Click);
            ItemContextMenu = new ContextMenu();
            MenuItem UnBlock = new MenuItem();
            UnBlock.Header = "Unblock";
            UnBlock.Click += new RoutedEventHandler(MenuUnBlock_Click);
            MenuItem Delete = new MenuItem();
            Delete.Header = "Delete";
            Delete.Click += new RoutedEventHandler(MenuDelete_Click);
            ItemContextMenu.Items.Add(Block);
            ItemContextMenu.Items.Add(UnBlock);
            ItemContextMenu.Items.Add(Delete);

            oSel = new Selection(this);
            DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
            dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
            dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
            dispatcherTimer.Start();
            oRefresh();
        }
Exemplo n.º 10
0
        public MainMenu(Rectangle windowSize, KeyboardState newKeyboardState, MouseState newMouseState)
        {
            windowWidth = windowSize.Width;
            windowHeight = windowSize.Height;
            keyboardState = newKeyboardState;
            mousestate = newMouseState;
            selection = Selection.Play;
            wallpaper = new Sprite(new Rectangle(0, 0, windowWidth, windowHeight), windowSize);
            wallpaperText = new Sprite(new Rectangle(0, 0, windowWidth, windowHeight), windowSize);
            nuages = new Sprite(new Rectangle(0, 0, windowWidth * 3, windowHeight), windowSize);
            nuages.Direction = new Vector2(-1, 0);
            nuages.Vitesse = 0.1f; // 1f = 1000 px/sec
            mouse = new AnimatedSprite(new Rectangle(-100, -100, 80, 100), windowSize, 8, 4, 40);
            relativeAmplitudeVibrationSelection = (float)amplitudeVibrationSelection / (float)(windowHeight + windowWidth);
            sprites = new List<AnimatedSprite>();

            menuItems = new Dictionary<Selection, Sprite>();
            menuItems.Add(Selection.Play, new Sprite(new Rectangle(112, 423, 124, 55), windowSize, "menu/textPlay"));
            menuItems.Add(Selection.Extra, new Sprite(new Rectangle(191, 480, 124, 55), windowSize, "menu/textExtra"));
            menuItems.Add(Selection.Options, new Sprite(new Rectangle(394, 470, 135, 55), windowSize, "menu/textOptions"));
            menuItems.Add(Selection.Credit, new Sprite(new Rectangle(562, 400, 124, 55), windowSize, "menu/textCredit"));
            menuItems.Add(Selection.Exit, new Sprite(new Rectangle(675, 480, 101, 55), windowSize, "menu/textExit"));

            Fire = new ParticleEngine(new Rectangle(0,windowSize.Height,windowSize.Width,0));
            Fire.SetSpeedRange(0.2f, 2f, 90, 40);
            Fire.SetLifeTimeRange(20, 90);
            Fire.SetScaleRange(0.2f, 1.4f);

            Cursor = new ParticleEngine(new Rectangle());
            Cursor.SetSpeedRange(0.2f, 1.6f, -45, 25);
            Cursor.SetAngularSpeedRange(0, 3);
            Cursor.SetLifeTimeRange(20, 50);
            Cursor.SetScaleRange(0.2f, 1.4f);
            Cursor.SetColorRange(0, 255, 0, 255, 0, 255, 0, 20);
        }
Exemplo n.º 11
0
 /// <summary>
 /// Replace the text of the selection with the answer to the calculation
 /// </summary>
 /// <param Name="selection">The current selection, used as input, and modified for the output</param>
 /// <param Name="argument">Anything added after the command Name, used as input</param>
 public void Execute(Selection selection, string[] arguments)
 {
     //Attempt to perform the calculation
     try { selection.Text = PerformCalculation(selection.Text); }
     //If it fails, raise an error to the user
     catch { new Error(String.Format(@"Sum'{0}' is not formatted correctly", selection.Text), Camera); }
 }
Exemplo n.º 12
0
		public static Composite Buff(string spell, Selection<bool> reqs = null)
		{
			return
				new Decorator(
					ret => (reqs == null || reqs(ret)) && !Me.HasBuff(spell),
					Cast(spell, ret => Me, ret => true));
		}
Exemplo n.º 13
0
        /// <summary>
        /// Create a new Load/Save Screen.
        /// </summary>
        /// <param name="NextState">Depending whether the game is loading or saving.
        /// If the game is loading, then the it is the state the game will go to if the operation is cancelled.
        /// If the game is saving, this state will be reached regardless.</param>
        /// <param name="SaveMode">True for saving, false for loading.</param>
        public SaveLoadScreen(State.State NextState, bool SaveMode)
        {
            this.NextState = NextState;
            this.SaveMode = SaveMode;

            if (SaveMode)
            {
                LogsSelection = new Selection(50, 130, new string[] {
                    "1: ", "2: ", "3: ", "4: ", "5: ", "6: ", "7: ", "8: ", "Cancel"});
            }
            else
            {
                LogsSelection = new Selection(50, 130, new string[] {
                    "1: ", "2: ", "3: ", "4: ", "5: ", "6: ", "7: ", "8: ", "Autosave", "Cancel"});
            }

            for (int i = 0; i < 8; i++)
            {
                if (Properties.Settings.Default.Logs[i] == "0")
                {
                    LogsSelection.Choices[i] += "-";
                }
                else
                {
                    LogsSelection.Choices[i] += Properties.Settings.Default.Logs[i];
                }
            }
        }
Exemplo n.º 14
0
 public Point[] FillEllipse(Selection sel)
 {
     return drawShape(sel, (g, s) => {
     g.FillEllipse(new SolidBrush(CR_FORE), sel.GetTrimRect());
     g.DrawEllipse(new Pen       (CR_FORE), sel.GetTrimRect());
      });
 }
 /// <summary>
 /// Represents the Relationship Class information
 /// </summary>
 /// <param name="featureLayer"></param>
 /// <param name="selection"></param>
 public RelateInfo(FeatureLayer featureLayer, Selection selection)
 {
     _featureLayer = featureLayer;
     _selection = selection;            
     _featureClassName = _featureLayer.GetFeatureClass().GetName();
     
 }
		public Composite UseItem(Selection<bool> reqs = null)
		{
			return new Decorator(ret => reqs == null || reqs(ret),
				new Action(delegate
				{
					if (_timer.IsRunning && _timer.Elapsed.TotalSeconds < CoolDown)
						return RunStatus.Failure;

					if (!_timer.IsRunning)
						_timer.Start();

					foreach (var o in BuddyTor.Me.InventoryEquipment)
					{
						if (o.Name.Contains(ItemName))
						{
							o.Use();
							o.Interact();
							_timer.Stop();
							_timer.Reset();
							_timer.Start();
							return RunStatus.Success;
						}
					}
					return RunStatus.Failure;
				}));
		}
Exemplo n.º 17
0
        public virtual Selection PreSelection(SelectionManager sm, Selection sel)
        {
            if ( !sel.IsEmpty && !sel.Start.Node.Equals(node) )
                return new Selection(SelectionManager.CreateSelectionPoint(node, false));

            return sel;
        }
        public override void Initialize(EditingContext context)
        {
            this.context = context;
            AttachedPropertiesService propertiesService = this.context.Services.GetService<AttachedPropertiesService>();
            helpService = this.context.Services.GetService<IIntegratedHelpService>();

            oldSelection = this.context.Items.GetValue<Selection>();
            isPrimarySelectionProperty = new AttachedProperty<bool>()
                {
                    Getter = (modelItem) => (this.context.Items.GetValue<Selection>().PrimarySelection == modelItem),
                    Name = "IsPrimarySelection",
                    OwnerType = typeof(Object)
                };

            isSelectionProperty = new AttachedProperty<bool>()
            {
                Getter = (modelItem) => (((IList)this.context.Items.GetValue<Selection>().SelectedObjects).Contains(modelItem)),
                Name = "IsSelection",
                OwnerType = typeof(Object)
            };


            propertiesService.AddProperty(isPrimarySelectionProperty);
            propertiesService.AddProperty(isSelectionProperty);
            



            if (this.context.Services.GetService<ViewService>() == null)
            {
                view = new System.Activities.Presentation.View.DesignerView(this.context);
                WorkflowViewService viewService = new WorkflowViewService(context);
                WorkflowViewStateService viewStateService = new WorkflowViewStateService(context);
                this.context.Services.Publish<ViewService>(viewService);
                this.context.Services.Publish<VirtualizedContainerService>(new VirtualizedContainerService(this.context));
                this.context.Services.Publish<ViewStateService>(viewStateService);
                this.context.Services.Publish<DesignerView>(view);

                WorkflowAnnotationAdornerService annotationService = new WorkflowAnnotationAdornerService();
                annotationService.Initialize(this.context, view.scrollViewer);
                this.context.Services.Publish<AnnotationAdornerService>(annotationService);

                this.context.Services.Subscribe<ModelService>(delegate(ModelService modelService)
                {
                    this.modelService = modelService;
                    if (modelService.Root != null)
                    {
                        view.MakeRootDesigner(modelService.Root);
                    }
                    view.RestoreDesignerStates();
                    this.context.Items.Subscribe<Selection>(new SubscribeContextCallback<Selection>(OnItemSelected));
                });
            }

            if (helpService != null)
            {
                helpService.AddContextAttribute(string.Empty, KeywordForWorkflowDesignerHomePage, HelpKeywordType.F1Keyword); 
            }
        }
Exemplo n.º 19
0
		public static Composite CastOnGround(string spell, Selection<bool> reqs = null)
		{
			return
				new Decorator(
					ret =>
						(reqs == null || reqs(ret)) && Me.CurrentTarget != null,
					CastOnGround(spell, ctx => Me.CurrentTarget.Position, ctx => true));
		}
Exemplo n.º 20
0
 //public Point[] DrawClosedCurve(Selection sel) {
 //   Rectangle r = sel.GetTrimRect();
 //   r.Inflate(-5,-5);
 //   Point[] pts = new Point[] { r.Location, new Point (r.Right,r.Top), new Point (r.Right,r.Bottom), new Point (r.Left, r.Bottom) } ;
 //   return drawShape( sel, (g,s) => g.DrawClosedCurve( new Pen(CR_FORE), pts, 0.2F, System.Drawing.Drawing2D.FillMode.Alternate  ));
 //}
 private Point[] drawShape(Selection sel, Action<Graphics, Selection> f )
 {
     using (Graphics g = Graphics.FromImage(_bmp)) {
     g.Clear(CR_BACK);
     f( g, sel );
      }
      return getPixelList(sel);
 }
Exemplo n.º 21
0
 public BrushEditor(IEditorApplication application, Tilemap Tilemap, Tileset Tileset, string brushFile)
 {
     selection = new Selection();
     selection.Changed += OnSelectionChanged;
     this.application = application;
     this.Tilemap = Tilemap;
     brush = Brush.loadFromFile(brushFile, Tileset);
 }
 public ViewModelLocator()
 {
     if (DesignMode)
         _document = LoadDesignModeDocument();
     else
         _document = LoadDocument();
     _selection = new Selection();
 }
Exemplo n.º 23
0
 public TextView(ITextViewDocument document, ITextViewAppearance appearance, ITextViewAdornments adornments)
 {
     _appearance = appearance;
     _adornments = adornments;
     _document = document;
     _selection = new Selection(document.Caret);
     _document.Caret.Moved += EnsureCursorIsVisible;
 }
Exemplo n.º 24
0
 public void TestContains()
 {
     Selection<object> test = new Selection<object>();
     Assert.False(test.Contains("a"));
     test.Add("a");
     Assert.True(test.Contains("a"));
     test.Add("b");
     Assert.True(test.Contains("b"));
 }
Exemplo n.º 25
0
 public void TestIEnumerable()
 {
     Selection<object> test = new Selection<object>();
     CollectionAssert.IsEmpty(test);
     test.Add("a");
     Utilities.TestSequenceEqual(test, "a");
     test.Add("b");
     Utilities.TestSequenceEqual(test, "a", "b");
 }
Exemplo n.º 26
0
 public FillEditor(IEditorApplication application, Tilemap Tilemap, Tileset Tileset, Selection selection)
 {
     this.application = application;
     this.Tilemap = Tilemap;
     this.Tileset = Tileset;
     this.selection = selection;
     application.TilemapChanged += OnTilemapChanged;
     selection.Changed += OnSelectionChanged;
 }
Exemplo n.º 27
0
 /// <summary>
 /// Replaces the style of a given selection with a specified style
 /// </summary>
 /// <param Name="selection">The selection to change</param>
 /// <param Name="style">The style to change to</param>
 protected void ApplyStyle(Selection selection, Style style)
 {
     //This only works if the selection exists
     if (selection != null)
     {
         selection.Font = style.Font;
         selection.Color = style.Color;
     }
 }
Exemplo n.º 28
0
 public void TestCount()
 {
     Selection<object> test = new Selection<object>();
     Assert.True(test.Count == 0);
     test.Add("a");
     Assert.True(test.Count == 1);
     test.Add("b");
     Assert.True(test.Count == 2);
 }
        private Table getTable(Selection selection)
        {
            if (selection != null && selection.Tables != null && selection.Tables[1] != null)
            {
                return selection.Tables[1];
            }

            throw new ArgumentException("No table selected");
        }
Exemplo n.º 30
0
        internal void FromSelection(Selection s)
        {
            this.SetAllNull();

            if (s.Pane != null) this.Pane = s.Pane.Value;
            if (s.ActiveCell != null) this.ActiveCell = s.ActiveCell.Value;
            if (s.ActiveCellId != null) this.ActiveCellId = s.ActiveCellId.Value;
            if (s.SequenceOfReferences != null) this.SequenceOfReferences = SLTool.TranslateSeqRefToCellPointRange(s.SequenceOfReferences);
        }
Exemplo n.º 31
0
        public void Controls()
        {
            wantsMouseMove = true;
            Event e = Event.current;

            switch (e.type)
            {
            case EventType.DragUpdated:
            case EventType.DragPerform:
                DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
                if (e.type == EventType.DragPerform)
                {
                    DragAndDrop.AcceptDrag();
                    graphEditor.OnDropObjects(DragAndDrop.objectReferences);
                }
                break;

            case EventType.MouseMove:
                //Keyboard commands will not get correct mouse position from Event
                lastMousePosition = e.mousePosition;
                break;

            case EventType.ScrollWheel:
                float oldZoom = zoom;
                if (e.delta.y > 0)
                {
                    zoom += 0.1f * zoom;
                }
                else
                {
                    zoom -= 0.1f * zoom;
                }
                if (NodeEditorPreferences.GetSettings().zoomToMouse)
                {
                    panOffset += (1 - oldZoom / zoom) * (WindowToGridPosition(e.mousePosition) + panOffset);
                }
                break;

            case EventType.MouseDrag:
                if (e.button == 0)
                {
                    if (IsDraggingPort)
                    {
                        // Set target even if we can't connect, so as to prevent auto-conn menu from opening erroneously
                        if (IsHoveringPort && hoveredPort.IsInput && !draggedOutput.IsConnectedTo(hoveredPort))
                        {
                            draggedOutputTarget = hoveredPort;
                        }
                        else
                        {
                            draggedOutputTarget = null;
                        }
                        Repaint();
                    }
                    else if (currentActivity == NodeActivity.HoldNode)
                    {
                        RecalculateDragOffsets(e);
                        currentActivity = NodeActivity.DragNode;
                        Repaint();
                    }
                    if (currentActivity == NodeActivity.DragNode)
                    {
                        // Holding ctrl inverts grid snap
                        bool gridSnap = NodeEditorPreferences.GetSettings().gridSnap;
                        if (e.control)
                        {
                            gridSnap = !gridSnap;
                        }

                        Vector2 mousePos = WindowToGridPosition(e.mousePosition);
                        // Move selected nodes with offset
                        for (int i = 0; i < Selection.objects.Length; i++)
                        {
                            if (Selection.objects[i] is XNode.Node)
                            {
                                XNode.Node node = Selection.objects[i] as XNode.Node;
                                Undo.RecordObject(node, "Moved Node");
                                Vector2 initial = node.position;
                                node.position = mousePos + dragOffset[i];
                                if (gridSnap)
                                {
                                    node.position.x = (Mathf.Round((node.position.x + 8) / 16) * 16) - 8;
                                    node.position.y = (Mathf.Round((node.position.y + 8) / 16) * 16) - 8;
                                }

                                // Offset portConnectionPoints instantly if a node is dragged so they aren't delayed by a frame.
                                Vector2 offset = node.position - initial;
                                if (offset.sqrMagnitude > 0)
                                {
                                    foreach (XNode.NodePort output in node.Outputs)
                                    {
                                        Rect rect;
                                        if (portConnectionPoints.TryGetValue(output, out rect))
                                        {
                                            rect.position += offset;
                                            portConnectionPoints[output] = rect;
                                        }
                                    }

                                    foreach (XNode.NodePort input in node.Inputs)
                                    {
                                        Rect rect;
                                        if (portConnectionPoints.TryGetValue(input, out rect))
                                        {
                                            rect.position += offset;
                                            portConnectionPoints[input] = rect;
                                        }
                                    }
                                }
                            }
                        }
                        // Move selected reroutes with offset
                        for (int i = 0; i < selectedReroutes.Count; i++)
                        {
                            Vector2 pos = mousePos + dragOffset[Selection.objects.Length + i];
                            if (gridSnap)
                            {
                                pos.x = (Mathf.Round(pos.x / 16) * 16);
                                pos.y = (Mathf.Round(pos.y / 16) * 16);
                            }
                            selectedReroutes[i].SetPoint(pos);
                        }
                        Repaint();
                    }
                    else if (currentActivity == NodeActivity.HoldGrid)
                    {
                        currentActivity        = NodeActivity.DragGrid;
                        preBoxSelection        = Selection.objects;
                        preBoxSelectionReroute = selectedReroutes.ToArray();
                        dragBoxStart           = WindowToGridPosition(e.mousePosition);
                        Repaint();
                    }
                    else if (currentActivity == NodeActivity.DragGrid)
                    {
                        Vector2 boxStartPos = GridToWindowPosition(dragBoxStart);
                        Vector2 boxSize     = e.mousePosition - boxStartPos;
                        if (boxSize.x < 0)
                        {
                            boxStartPos.x += boxSize.x; boxSize.x = Mathf.Abs(boxSize.x);
                        }
                        if (boxSize.y < 0)
                        {
                            boxStartPos.y += boxSize.y; boxSize.y = Mathf.Abs(boxSize.y);
                        }
                        selectionBox = new Rect(boxStartPos, boxSize);
                        Repaint();
                    }
                }
                else if (e.button == 1 || e.button == 2)
                {
                    //check drag threshold for larger screens
                    if (e.delta.magnitude > dragThreshold)
                    {
                        panOffset += e.delta * zoom;
                        isPanning  = true;
                    }
                }
                break;

            case EventType.MouseDown:
                Repaint();
                if (e.button == 0)
                {
                    draggedOutputReroutes.Clear();

                    if (IsHoveringPort)
                    {
                        if (hoveredPort.IsOutput)
                        {
                            draggedOutput     = hoveredPort;
                            autoConnectOutput = hoveredPort;
                        }
                        else
                        {
                            hoveredPort.VerifyConnections();
                            autoConnectOutput = null;
                            if (hoveredPort.IsConnected)
                            {
                                XNode.Node     node   = hoveredPort.node;
                                XNode.NodePort output = hoveredPort.Connection;
                                int            outputConnectionIndex = output.GetConnectionIndex(hoveredPort);
                                draggedOutputReroutes = output.GetReroutePoints(outputConnectionIndex);
                                hoveredPort.Disconnect(output);
                                draggedOutput       = output;
                                draggedOutputTarget = hoveredPort;
                                if (NodeEditor.onUpdateNode != null)
                                {
                                    NodeEditor.onUpdateNode(node);
                                }
                            }
                        }
                    }
                    else if (IsHoveringNode && IsHoveringTitle(hoveredNode))
                    {
                        // If mousedown on node header, select or deselect
                        if (!Selection.Contains(hoveredNode))
                        {
                            SelectNode(hoveredNode, e.control || e.shift);
                            if (!e.control && !e.shift)
                            {
                                selectedReroutes.Clear();
                            }
                        }
                        else if (e.control || e.shift)
                        {
                            DeselectNode(hoveredNode);
                        }

                        // Cache double click state, but only act on it in MouseUp - Except ClickCount only works in mouseDown.
                        isDoubleClick = (e.clickCount == 2);

                        e.Use();
                        currentActivity = NodeActivity.HoldNode;
                    }
                    else if (IsHoveringReroute)
                    {
                        // If reroute isn't selected
                        if (!selectedReroutes.Contains(hoveredReroute))
                        {
                            // Add it
                            if (e.control || e.shift)
                            {
                                selectedReroutes.Add(hoveredReroute);
                            }
                            // Select it
                            else
                            {
                                selectedReroutes = new List <RerouteReference>()
                                {
                                    hoveredReroute
                                };
                                Selection.activeObject = null;
                            }
                        }
                        // Deselect
                        else if (e.control || e.shift)
                        {
                            selectedReroutes.Remove(hoveredReroute);
                        }
                        e.Use();
                        currentActivity = NodeActivity.HoldNode;
                    }
                    // If mousedown on grid background, deselect all
                    else if (!IsHoveringNode)
                    {
                        currentActivity = NodeActivity.HoldGrid;
                        if (!e.control && !e.shift)
                        {
                            selectedReroutes.Clear();
                            Selection.activeObject = null;
                        }
                    }
                }
                break;

            case EventType.MouseUp:
                if (e.button == 0)
                {
                    //Port drag release
                    if (IsDraggingPort)
                    {
                        // If connection is valid, save it
                        if (draggedOutputTarget != null && draggedOutput.CanConnectTo(draggedOutputTarget))
                        {
                            XNode.Node node = draggedOutputTarget.node;
                            if (graph.nodes.Count != 0)
                            {
                                draggedOutput.Connect(draggedOutputTarget);
                            }

                            // ConnectionIndex can be -1 if the connection is removed instantly after creation
                            int connectionIndex = draggedOutput.GetConnectionIndex(draggedOutputTarget);
                            if (connectionIndex != -1)
                            {
                                draggedOutput.GetReroutePoints(connectionIndex).AddRange(draggedOutputReroutes);
                                if (NodeEditor.onUpdateNode != null)
                                {
                                    NodeEditor.onUpdateNode(node);
                                }
                                EditorUtility.SetDirty(graph);
                            }
                        }
                        // Open context menu for auto-connection if there is no target node
                        else if (draggedOutputTarget == null && NodeEditorPreferences.GetSettings().dragToCreate&& autoConnectOutput != null)
                        {
                            GenericMenu menu = new GenericMenu();
                            graphEditor.AddContextMenuItems(menu, draggedOutput.ValueType);
                            menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
                        }
                        //Release dragged connection
                        draggedOutput       = null;
                        draggedOutputTarget = null;
                        EditorUtility.SetDirty(graph);
                        if (NodeEditorPreferences.GetSettings().autoSave)
                        {
                            AssetDatabase.SaveAssets();
                        }
                    }
                    else if (currentActivity == NodeActivity.DragNode)
                    {
                        IEnumerable <XNode.Node> nodes = Selection.objects.Where(x => x is XNode.Node).Select(x => x as XNode.Node);
                        foreach (XNode.Node node in nodes)
                        {
                            EditorUtility.SetDirty(node);
                        }
                        if (NodeEditorPreferences.GetSettings().autoSave)
                        {
                            AssetDatabase.SaveAssets();
                        }
                    }
                    else if (!IsHoveringNode)
                    {
                        // If click outside node, release field focus
                        if (!isPanning)
                        {
                            EditorGUI.FocusTextInControl(null);
                            EditorGUIUtility.editingTextField = false;
                        }
                        if (NodeEditorPreferences.GetSettings().autoSave)
                        {
                            AssetDatabase.SaveAssets();
                        }
                    }

                    // If click node header, select it.
                    if (currentActivity == NodeActivity.HoldNode && !(e.control || e.shift))
                    {
                        selectedReroutes.Clear();
                        SelectNode(hoveredNode, false);

                        // Double click to center node
                        if (isDoubleClick)
                        {
                            Vector2 nodeDimension = nodeSizes.ContainsKey(hoveredNode) ? nodeSizes[hoveredNode] / 2 : Vector2.zero;
                            panOffset = -hoveredNode.position - nodeDimension;
                        }
                    }

                    // If click reroute, select it.
                    if (IsHoveringReroute && !(e.control || e.shift))
                    {
                        selectedReroutes = new List <RerouteReference>()
                        {
                            hoveredReroute
                        };
                        Selection.activeObject = null;
                    }

                    Repaint();
                    currentActivity = NodeActivity.Idle;
                }
                else if (e.button == 1 || e.button == 2)
                {
                    if (!isPanning)
                    {
                        if (IsDraggingPort)
                        {
                            draggedOutputReroutes.Add(WindowToGridPosition(e.mousePosition));
                        }
                        else if (currentActivity == NodeActivity.DragNode && Selection.activeObject == null && selectedReroutes.Count == 1)
                        {
                            selectedReroutes[0].InsertPoint(selectedReroutes[0].GetPoint());
                            selectedReroutes[0] = new RerouteReference(selectedReroutes[0].port, selectedReroutes[0].connectionIndex, selectedReroutes[0].pointIndex + 1);
                        }
                        else if (IsHoveringReroute)
                        {
                            ShowRerouteContextMenu(hoveredReroute);
                        }
                        else if (IsHoveringPort)
                        {
                            ShowPortContextMenu(hoveredPort);
                        }
                        else if (IsHoveringNode && IsHoveringTitle(hoveredNode))
                        {
                            if (!Selection.Contains(hoveredNode))
                            {
                                SelectNode(hoveredNode, false);
                            }
                            autoConnectOutput = null;
                            GenericMenu menu = new GenericMenu();
                            NodeEditor.GetEditor(hoveredNode, this).AddContextMenuItems(menu);
                            menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
                            e.Use();     // Fixes copy/paste context menu appearing in Unity 5.6.6f2 - doesn't occur in 2018.3.2f1 Probably needs to be used in other places.
                        }
                        else if (!IsHoveringNode)
                        {
                            autoConnectOutput = null;
                            GenericMenu menu = new GenericMenu();
                            graphEditor.AddContextMenuItems(menu);
                            menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
                        }
                    }
                    isPanning = false;
                }
                // Reset DoubleClick
                isDoubleClick = false;
                break;

            case EventType.KeyDown:
                if (EditorGUIUtility.editingTextField || GUIUtility.keyboardControl != 0)
                {
                    break;
                }
                else if (e.keyCode == KeyCode.F)
                {
                    Home();
                }
                if (NodeEditorUtilities.IsMac())
                {
                    if (e.keyCode == KeyCode.Return)
                    {
                        RenameSelectedNode();
                    }
                }
                else
                {
                    if (e.keyCode == KeyCode.F2)
                    {
                        RenameSelectedNode();
                    }
                }
                if (e.keyCode == KeyCode.A)
                {
                    if (Selection.objects.Any(x => graph.nodes.Contains(x as XNode.Node)))
                    {
                        foreach (XNode.Node node in graph.nodes)
                        {
                            DeselectNode(node);
                        }
                    }
                    else
                    {
                        foreach (XNode.Node node in graph.nodes)
                        {
                            SelectNode(node, true);
                        }
                    }
                    Repaint();
                }
                break;

            case EventType.ValidateCommand:
            case EventType.ExecuteCommand:
                if (e.commandName == "SoftDelete")
                {
                    if (e.type == EventType.ExecuteCommand)
                    {
                        RemoveSelectedNodes();
                    }
                    e.Use();
                }
                else if (NodeEditorUtilities.IsMac() && e.commandName == "Delete")
                {
                    if (e.type == EventType.ExecuteCommand)
                    {
                        RemoveSelectedNodes();
                    }
                    e.Use();
                }
                else if (e.commandName == "Duplicate")
                {
                    if (e.type == EventType.ExecuteCommand)
                    {
                        DuplicateSelectedNodes();
                    }
                    e.Use();
                }
                else if (e.commandName == "Copy")
                {
                    if (!EditorGUIUtility.editingTextField)
                    {
                        if (e.type == EventType.ExecuteCommand)
                        {
                            CopySelectedNodes();
                        }
                        e.Use();
                    }
                }
                else if (e.commandName == "Paste")
                {
                    if (!EditorGUIUtility.editingTextField)
                    {
                        if (e.type == EventType.ExecuteCommand)
                        {
                            PasteNodes(WindowToGridPosition(lastMousePosition));
                        }
                        e.Use();
                    }
                }
                Repaint();
                break;

            case EventType.Ignore:
                // If release mouse outside window
                if (e.rawType == EventType.MouseUp && currentActivity == NodeActivity.DragGrid)
                {
                    Repaint();
                    currentActivity = NodeActivity.Idle;
                }
                break;
            }
        }
Exemplo n.º 32
0
 public static Mock <IVBE> BuildFromSingleModule(string content, ComponentType type, out IVBComponent component, Selection selection = default(Selection), bool referenceStdLibs = false)
 {
     return(BuildFromSingleModule(content, TestModuleName, type, out component, selection, referenceStdLibs));
 }
Exemplo n.º 33
0
 public void SetSelectionForeground(Color color)
 {
     Selection.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(color));
 }
Exemplo n.º 34
0
        private void RenderSelection(RenderContext context)
        {
            var bounds = ActualBounds;

            if (string.IsNullOrEmpty(Text) || Selection == null)
            {
                return;
            }

            var selectStart = Math.Min(SelectStart, SelectEnd);
            var selectEnd   = Math.Max(SelectStart, SelectEnd);

            if (selectStart >= selectEnd)
            {
                return;
            }

            var startGlyph = _formattedText.GetGlyphInfoByIndex(selectStart);

            if (startGlyph == null)
            {
                return;
            }

            var lineIndex = startGlyph.TextChunk.LineIndex;
            var i         = selectStart;

            var lineHeight = _formattedText.Font.FontSize;

            while (true)
            {
                startGlyph = _formattedText.GetGlyphInfoByIndex(i);
                var startPosition = GetRenderPositionByIndex(i);

                var line = _formattedText.Lines[startGlyph.TextChunk.LineIndex];

                if (selectEnd < line.TextStartIndex + line.Count)
                {
                    var endPosition = GetRenderPositionByIndex(selectEnd);

                    Selection.Draw(context,
                                   new Rectangle(startPosition.X - _internalScrolling.X,
                                                 startPosition.Y - _internalScrolling.Y,
                                                 endPosition.X - startPosition.X,
                                                 lineHeight));

                    break;
                }

                Selection.Draw(context,
                               new Rectangle(startPosition.X - _internalScrolling.X,
                                             startPosition.Y - _internalScrolling.Y,
                                             bounds.Left + startGlyph.TextChunk.Size.X - startPosition.X,
                                             lineHeight));

                ++lineIndex;
                if (lineIndex >= _formattedText.Lines.Count)
                {
                    break;
                }

                i = _formattedText.Lines[lineIndex].TextStartIndex;
            }
        }
        void DrawRendererListLayout(ReorderableList list, SerializedProperty prop)
        {
            list.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) =>
            {
                rect.y += 2;
                Rect indexRect = new Rect(rect.x, rect.y, 14, EditorGUIUtility.singleLineHeight);
                EditorGUI.LabelField(indexRect, index.ToString());
                Rect objRect = new Rect(rect.x + indexRect.width, rect.y, rect.width - 134, EditorGUIUtility.singleLineHeight);

                EditorGUI.BeginChangeCheck();
                EditorGUI.ObjectField(objRect, prop.GetArrayElementAtIndex(index), GUIContent.none);
                if (EditorGUI.EndChangeCheck())
                {
                    EditorUtility.SetDirty(target);
                }

                Rect defaultButton   = new Rect(rect.width - 75, rect.y, 86, EditorGUIUtility.singleLineHeight);
                var  defaultRenderer = m_DefaultRendererProp.intValue;
                GUI.enabled = index != defaultRenderer;
                if (GUI.Button(defaultButton, !GUI.enabled ? Styles.rendererDefaultText : Styles.rendererSetDefaultText))
                {
                    m_DefaultRendererProp.intValue = index;
                    EditorUtility.SetDirty(target);
                }
                GUI.enabled = true;

                Rect selectRect = new Rect(rect.x + rect.width - 24, rect.y, 24, EditorGUIUtility.singleLineHeight);

                UniversalRenderPipelineAsset asset = target as UniversalRenderPipelineAsset;

                if (asset.ValidateRendererData(index))
                {
                    if (GUI.Button(selectRect, Styles.rendererSettingsText))
                    {
                        Selection.SetActiveObjectWithContext(prop.GetArrayElementAtIndex(index).objectReferenceValue,
                                                             null);
                    }
                }
                else // Missing ScriptableRendererData
                {
                    if (GUI.Button(selectRect, index == defaultRenderer ? Styles.rendererDefaultMissingText : Styles.rendererMissingText))
                    {
                        EditorGUIUtility.ShowObjectPicker <ScriptableRendererData>(null, false, null, index);
                    }
                }

                // If object selector chose an object, assign it to the correct ScriptableRendererData slot.
                if (Event.current.commandName == "ObjectSelectorUpdated" && EditorGUIUtility.GetObjectPickerControlID() == index)
                {
                    prop.GetArrayElementAtIndex(index).objectReferenceValue = EditorGUIUtility.GetObjectPickerObject();
                }
            };

            list.drawHeaderCallback = (Rect rect) =>
            {
                EditorGUI.LabelField(rect, Styles.rendererHeaderText);
            };

            list.onCanRemoveCallback = li => { return(li.count > 1); };

            list.onRemoveCallback = li =>
            {
                bool shouldUpdateIndex = false;
                // Checking so that the user is not deleting  the default renderer
                if (li.index != m_DefaultRendererProp.intValue)
                {
                    // Need to add the undo to the removal of our assets here, for it to work properly.
                    Undo.RecordObject(target, $"Deleting renderer at index {li.index}");

                    if (prop.GetArrayElementAtIndex(li.index).objectReferenceValue == null)
                    {
                        shouldUpdateIndex = true;
                    }
                    prop.DeleteArrayElementAtIndex(li.index);
                }
                else
                {
                    EditorUtility.DisplayDialog(Styles.rendererListDefaultMessage.text, Styles.rendererListDefaultMessage.tooltip,
                                                "Close");
                }

                if (shouldUpdateIndex)
                {
                    UpdateDefaultRendererValue(li.index);
                }

                EditorUtility.SetDirty(target);
            };

            list.onReorderCallbackWithDetails += (reorderableList, index, newIndex) =>
            {
                // Need to update the default renderer index
                UpdateDefaultRendererValue(index, newIndex);
            };
        }
Exemplo n.º 36
0
        public override void eventHandler(GameObject gameObject, QObjectList objectList, Event currentEvent)
        {
            if (currentEvent.isMouse && currentEvent.button == 0 && rect.Contains(currentEvent.mousePosition))
            {
                if (currentEvent.type == EventType.MouseDown)
                {
                    targetVisibilityState = ((!gameObject.activeSelf) == true ? 1 : 0);
                }
                else if (currentEvent.type == EventType.MouseDrag && targetVisibilityState != -1)
                {
                    if (targetVisibilityState == (gameObject.activeSelf == true ? 1 : 0))
                    {
                        return;
                    }
                }
                else
                {
                    targetVisibilityState = -1;
                    return;
                }

                bool showWarning = QSettings.getInstance().get <bool>(QSetting.AdditionalShowModifierWarning);

                List <GameObject> targetGameObjects = new List <GameObject>();
                if (currentEvent.control || currentEvent.command)
                {
                    if (currentEvent.shift)
                    {
                        if (!showWarning || EditorUtility.DisplayDialog("Change edit-time visibility", "Are you sure you want to turn " + (gameObject.activeSelf ? "off" : "on") + " the edit-time visibility of this GameObject and all its children? (You can disable this warning in the settings)", "Yes", "Cancel"))
                        {
                            getGameObjectListRecursive(gameObject, ref targetGameObjects);
                        }
                    }
                    else if (currentEvent.alt)
                    {
                        if (gameObject.transform.parent != null)
                        {
                            if (!showWarning || EditorUtility.DisplayDialog("Change edit-time visibility", "Are you sure you want to turn " + (gameObject.activeSelf ? "off" : "on") + " the edit-time visibility this GameObject and its siblings? (You can disable this warning in the settings)", "Yes", "Cancel"))
                            {
                                getGameObjectListRecursive(gameObject.transform.parent.gameObject, ref targetGameObjects, 1);
                                targetGameObjects.Remove(gameObject.transform.parent.gameObject);
                            }
                        }
                        else
                        {
                            Debug.Log("This action for root objects is supported for Unity3d 5.3.3 and above");
                            return;
                        }
                    }
                    else
                    {
                        getGameObjectListRecursive(gameObject, ref targetGameObjects, 0);
                    }
                }
                else if (currentEvent.shift)
                {
                    if (!showWarning || EditorUtility.DisplayDialog("Change visibility", "Are you sure you want to turn " + (gameObject.activeSelf ? "off" : "on") + " the visibility of this GameObject and all its children? (You can disable this warning in the settings)", "Yes", "Cancel"))
                    {
                        getGameObjectListRecursive(gameObject, ref targetGameObjects);
                    }
                }
                else if (currentEvent.alt)
                {
                    if (gameObject.transform.parent != null)
                    {
                        if (!showWarning || EditorUtility.DisplayDialog("Change visibility", "Are you sure you want to turn " + (gameObject.activeSelf ? "off" : "on") + " the visibility this GameObject and its siblings? (You can disable this warning in the settings)", "Yes", "Cancel"))
                        {
                            getGameObjectListRecursive(gameObject.transform.parent.gameObject, ref targetGameObjects, 1);
                            targetGameObjects.Remove(gameObject.transform.parent.gameObject);
                        }
                    }
                    else
                    {
                        Debug.Log("This action for root objects is supported for Unity3d 5.3.3 and above");
                        return;
                    }
                }
                else
                {
                    if (Selection.Contains(gameObject))
                    {
                        targetGameObjects.AddRange(Selection.gameObjects);
                    }
                    else
                    {
                        getGameObjectListRecursive(gameObject, ref targetGameObjects, 0);
                    };
                }

                setVisibility(targetGameObjects, objectList, !gameObject.activeSelf, currentEvent.control || currentEvent.command);
                currentEvent.Use();
            }
        }
Exemplo n.º 37
0
        } // OnMouseUp

        #endregion

        #region On Key Press

        protected override void OnKeyPress(KeyEventArgs e)
        {
            flashTime = 0;
            
            if (!e.Handled)
            {
                if (e.Key == Keys.Enter && mode != TextBoxMode.Multiline && !readOnly)
                {
                    initialText = Text;
                    selection = new Selection(-1, -1);
                    Focused = false;
                }
                if (e.Key == Keys.Escape)
                {
                    if (initialText != null)
                        Text = initialText;
                    selection = new Selection(-1, -1);
                    Focused = false;
                }
                if (e.Key == Keys.A && e.Control && mode != TextBoxMode.Password)
                {
                    SelectAll();
                }
                if (e.Key == Keys.Up)
                {
                    e.Handled = true;

                    if (e.Shift && selection.IsEmpty && mode != TextBoxMode.Password)
                    {
                        selection.Start = Position;
                    }
                    if (!e.Control)
                    {
                        PositionY -= 1;
                    }
                }
                else if (e.Key == Keys.Down)
                {
                    e.Handled = true;
                    if (e.Shift && selection.IsEmpty && mode != TextBoxMode.Password)
                    {
                        selection.Start = Position;
                    }
                    if (!e.Control)
                    {
                        PositionY += 1;
                    }
                }
                else if (e.Key == Keys.Back && !readOnly)
                {
                    e.Handled = true;
                    if (!selection.IsEmpty)
                    {
                        Text = Text.Remove(selection.Start, selection.Length);
                        Position = selection.Start;
                    }
                    else if (Text.Length > 0 && Position > 0)
                    {
                        Position -= 1;
                        Text = Text.Remove(Position, 1);
                    }
                    selection.Clear();
                }
                else if (e.Key == Keys.Delete && !readOnly)
                {
                    e.Handled = true;
                    if (!selection.IsEmpty)
                    {
                        Text = Text.Remove(selection.Start, selection.Length);
                        Position = selection.Start;
                    }
                    else if (Position < Text.Length)
                    {
                        Text = Text.Remove(Position, 1);
                    }
                    selection.Clear();
                }
                else if (e.Key == Keys.Left)
                {
                    e.Handled = true;
                    if (e.Shift && selection.IsEmpty && mode != TextBoxMode.Password)
                    {
                        selection.Start = Position;
                    }
                    if (!e.Control)
                    {
                        Position -= 1;
                    }
                    if (e.Control)
                    {
                        Position = FindPreviousWord(shownText);
                    }
                }
                else if (e.Key == Keys.Right)
                {
                    e.Handled = true;
                    if (e.Shift && selection.IsEmpty && mode != TextBoxMode.Password)
                    {
                        selection.Start = Position;
                    }
                    if (!e.Control)
                    {
                        Position += 1;
                    }
                    if (e.Control)
                    {
                        Position = FindNextWord(shownText);
                    }
                }
                else if (e.Key == Keys.Home)
                {
                    e.Handled = true;
                    if (e.Shift && selection.IsEmpty && mode != TextBoxMode.Password)
                    {
                        selection.Start = Position;
                    }
                    if (!e.Control)
                    {
                        PositionX = 0;
                    }
                    if (e.Control)
                    {
                        Position = 0;
                    }
                }
                else if (e.Key == Keys.End)
                {
                    e.Handled = true;
                    if (e.Shift && selection.IsEmpty && mode != TextBoxMode.Password)
                    {
                        selection.Start = Position;
                    }
                    if (!e.Control)
                    {
                        PositionX = lines[PositionY].Length;
                    }
                    if (e.Control)
                    {
                        Position = Text.Length;
                    }
                }
                else if (e.Key == Keys.PageUp)
                {
                    e.Handled = true;
                    if (e.Shift && selection.IsEmpty && mode != TextBoxMode.Password)
                    {
                        selection.Start = Position;
                    }
                    if (!e.Control)
                    {
                        PositionY -= linesDrawn;
                    }
                }
                else if (e.Key == Keys.PageDown)
                {
                    e.Handled = true;
                    if (e.Shift && selection.IsEmpty && mode != TextBoxMode.Password)
                    {
                        selection.Start = Position;
                    }
                    if (!e.Control)
                    {
                        PositionY += linesDrawn;
                    }
                }
                else if (e.Key == Keys.Enter && mode == TextBoxMode.Multiline && !readOnly)
                {
                    e.Handled = true;
                    Text = Text.Insert(Position, Separator);
                    PositionX = 0;
                    PositionY += 1;
                }
                else if (e.Key == Keys.Tab)
                {
                }
                else if (!readOnly && !e.Control)
                {
                    string c = Keyboard.KeyToString(e.Key, e.Shift, e.Caps);
                    if (selection.IsEmpty)
                    {
                        Text = Text.Insert(Position, c);
                        if (c != "") PositionX += 1;
                    }
                    else
                    {
                        if (Text.Length > 0)
                        {
                            // Avoid out of range.
                            if (selection.Start + selection.Length > Text.Length)
                                Text = Text.Remove(selection.Start, Text.Length - selection.Start);
                            else
                                Text = Text.Remove(selection.Start, selection.Length);
                            Text = Text.Insert(selection.Start, c);
                            Position = selection.Start + 1;
                        }
                        selection.Clear();
                    }
                }

                if (e.Shift && !selection.IsEmpty)
                {
                    selection.End = Position;
                }

                #region Copy Paste

                // Windows only because it uses the Clipboard class. Of course this could be implemented manually in the XBOX 360 if you want it.
                #if (WINDOWS)
                if (e.Control && e.Key == Keys.C && mode != TextBoxMode.Password)
                {
                    System.Windows.Forms.Clipboard.Clear();
                    if (mode != TextBoxMode.Password && !selection.IsEmpty)
                    {
                        System.Windows.Forms.Clipboard.SetText((Text.Substring(selection.Start, selection.Length)).Replace("\n", Environment.NewLine));
                    }
                }
                else if (e.Control && e.Key == Keys.V && !readOnly && mode != TextBoxMode.Password)
                {
                    string t = System.Windows.Forms.Clipboard.GetText().Replace(Environment.NewLine, "\n");
                    if (selection.IsEmpty)
                    {
                        Text = Text.Insert(Position, t);
                        Position = Position + t.Length;
                    }
                    else
                    {
                        Text = Text.Remove(selection.Start, selection.Length);
                        Text = Text.Insert(selection.Start, t);
                        PositionX = selection.Start + t.Length;
                        selection.Clear();
                    }
                }
                #endif

                #endregion

                if ((!e.Shift && !e.Control) || Text.Length <= 0)
                {
                    selection.Clear();
                }

                if (e.Control && e.Key == Keys.Down)
                {
                    e.Handled = true;
                    HandleGuide(PlayerIndex.One);
                }
                flashTime = 0;
                if (ClientArea != null) ClientArea.Invalidate();

                DeterminePages();
                ProcessScrolling();
            }
            base.OnKeyPress(e);
        } // OnKeyPress
Exemplo n.º 38
0
        // ---------------------------- //
        // Update display list
        // ---------------------------- //
        void UpdateDisplayList()
        {
            // Maintain selected textures
            // and sprites in output atlas
            if (mSpriteList != null && mSelectedTextures != null) {
                mSpriteList.Clear();
                mSelectedTextures.Clear();
                if (ValidateSelection()) {
                    // Update selected items
                    Object[] selectedTextureObjects = Selection.GetFiltered(typeof(Texture2D), SelectionMode.Assets);
                    foreach (Texture2D t in selectedTextureObjects) {
                        if (t != mOutputTexture) {
                            mSelectedTextures.Add(t, TEXTURE_OP_ADD);
                        }
                    }
                }

                // Update sprites in output atlas
                if (mOutputTexture != null) {
                    mOutputFilePath = AssetDatabase.GetAssetPath(mOutputTexture);
                    Object[] objs = AssetDatabase.LoadAllAssetsAtPath(mOutputFilePath);
                    if (objs != null && objs.Length > 1) {
                        // Get all sprite references
                        Sprite spriteToAdd = null;
                        mSpriteList.Clear();
                        for (int i = 1; i < objs.Length; i++) {
                            spriteToAdd = objs[i] as Sprite;
                            if (spriteToAdd != null) {
                                mSpriteList.Add(spriteToAdd);
                            } else {
                                Debug.LogError("Sprite conversion failed.");
                                break;
                            }
                        }
                    } else {
                        mOutputTexture = null;
                        Debug.LogError("Output texture is not a multiple sprite");
                    }
                }

                // Remove selected texture from output atlas
                Sprite spriteToRemove = null;
                List<Texture2D> texturesToUpdate = new List<Texture2D>();
                foreach (KeyValuePair<Texture2D, string> keyValue in mSelectedTextures) {
                    foreach (Sprite sp in mSpriteList) {
                        if (sp.name == keyValue.Key.name) {
                            spriteToRemove = sp;
                            texturesToUpdate.Add(keyValue.Key);
                            break;
                        }
                    }

                    if (spriteToRemove != null) {
                        mSpriteList.Remove(spriteToRemove);
                        spriteToRemove = null;
                    }
                }

                // Update texture display status
                foreach (Texture2D t in texturesToUpdate) {
                    mSelectedTextures[t] = TEXTURE_OP_UPDATE;
                }
            }
        }
Exemplo n.º 39
0
        private void SetTableCellAttributes(XElement tableCell, int widthIndex, int curNumCol, List <decimal> cellWidthPercentages, Selection selection)
        {
            tableCell.SetAttributeValue("colspan", curNumCol);
            tableCell.SetAttributeValue("rowspan", GetRowspan(selection));

            decimal cellWidth1 = 0;

            for (int i = widthIndex; i >= widthIndex - curNumCol + 1; i--)
            {
                cellWidth1 += cellWidthPercentages[i];
            }
            decimal cellWidth = cellWidth1;

            tableCell.SetAttributeValue("width", cellWidth + "%");
        }
Exemplo n.º 40
0
 private int GetRowspan(Selection selection)
 {
     return((int)selection.Information[WdInformation.wdEndOfRangeRowNumber] -
            (int)selection.Information[WdInformation.wdStartOfRangeRowNumber] + 1);
 }
Exemplo n.º 41
0
 private Task AddToSearch()
 {
     _searchService.AddCriterion(Selection.GetText());
     return(Task.FromResult <object>(null));
 }
Exemplo n.º 42
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public virtual Result Execute(ExternalCommandData commandData
                                      , ref string message, ElementSet elements)
        {
            try
            {
                Document doc = commandData.Application.ActiveUIDocument.Document;
                if (doc == null)
                {
                    return(Result.Failed);
                }

                //Fetch a RebarBarType element to be used in Rebar creation.
                FilteredElementCollector fec = new FilteredElementCollector(doc).OfClass(typeof(RebarBarType));
                if (fec.GetElementCount() <= 0)
                {
                    return(Result.Failed);
                }
                RebarBarType barType   = fec.FirstElement() as RebarBarType;
                Rebar        rebar     = null;
                CurveElement curveElem = null;
                using (Transaction tran = new Transaction(doc, "Create Rebar"))
                {
                    Element   host = null;
                    Selection sel  = commandData.Application.ActiveUIDocument.Selection;
                    try
                    {
                        //Select structural Host.
                        Reference hostRef = sel.PickObject(ObjectType.Element, "Select Host");
                        host = doc.GetElement(hostRef.ElementId);
                        if (host == null)
                        {
                            return(Result.Failed);
                        }
                    }
                    catch (Exception e)
                    {
                        message = e.Message;
                        return(Result.Failed);
                    }

                    try
                    {
                        //Select curve element
                        Reference lineRef = sel.PickObject(ObjectType.Element, "Select Model curve");
                        curveElem = doc.GetElement(lineRef.ElementId) as CurveElement;
                    }
                    catch (Exception)
                    {
                        curveElem = null;
                    }
                    tran.Start();
                    //create Rebar Free Form by specifying the GUID defining the custom external server
                    // the Rebar element returned needs to receive constraints,
                    // so that regeneration can call the custom geometry calculations and create the bars
                    rebar = Rebar.CreateFreeForm(doc, RebarUpdateServer.SampleGuid, barType, host);
                    // Get all bar handles to set constraints to them, so that the bar can generate it's geometry
                    RebarConstraintsManager        rManager = rebar.GetRebarConstraintsManager();
                    IList <RebarConstrainedHandle> handles  = rManager.GetAllHandles();

                    // if bar has no handles then the server can't generate rebar geometry
                    if (handles.Count <= 0)
                    {
                        tran.RollBack();
                        return(Result.Failed);
                    }

                    // iterate through the rebar handles and prompt for face selection for each of them, to get user input
                    foreach (RebarConstrainedHandle handle in handles)
                    {
                        if (handle.GetHandleType() == RebarHandleType.StartOfBar ||
                            handle.GetHandleType() == RebarHandleType.EndOfBar)
                        {
                            continue;// Start handle and end handle will receive constraints from the custom external server execution
                        }
                        try
                        {
                            Reference reference = sel.PickObject(ObjectType.Face, "Select face for " + handle.GetHandleName());
                            if (reference == null)
                            {
                                continue;
                            }
                            // create constraint using the picked faces and set it to the associated handle
                            List <Reference> refs = new List <Reference>();
                            refs.Add(reference);
                            RebarConstraint constraint = RebarConstraint.Create(handle, refs, true, 0.0);
                            rManager.SetPreferredConstraintForHandle(handle, constraint);
                        }
                        catch (Exception e)
                        {
                            message = e.Message;
                            tran.RollBack();
                            return(Result.Cancelled);
                        }
                    }

                    try
                    {
                        //here we add a value to the shared parameter and add it to the regeneration dependencies
                        Parameter newSharedParam  = rebar.LookupParameter(AddSharedParams.m_paramName);
                        Parameter newSharedParam2 = rebar.LookupParameter(AddSharedParams.m_CurveIdName);
                        newSharedParam.Set(0);
                        newSharedParam2.Set(curveElem == null ? -1 : curveElem.Id.IntegerValue);

                        RebarFreeFormAccessor accesRebar = rebar.GetFreeFormAccessor();
                        accesRebar.AddUpdatingSharedParameter(newSharedParam.Id);
                        accesRebar.AddUpdatingSharedParameter(newSharedParam2.Id);
                    }
                    catch (Exception ex)
                    {
                        message = ex.Message;
                        tran.RollBack();
                        return(Result.Cancelled);
                    }
                    tran.Commit();
                    return(Result.Succeeded);
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }
        }
Exemplo n.º 43
0
        protected bool TargetsForAbilityExist(Func <GenericShip, bool> filter)
        {
            Selection.ChangeActiveShip("ShipId:" + HostShip.ShipId);

            return(Roster.AllShips.Values.FirstOrDefault(n => filter(n)) != null);
        }
Exemplo n.º 44
0
        /// <summary>
        /// Pastes an image from the clipboard.
        /// </summary>
        /// <param name="toNewLayer">Set to TRUE to paste into a
        /// new layer.  Otherwise, will paste to the current layer.</param>
        /// <param name="x">Optional. Location within image to paste to.
        /// Position will be adjusted if pasted image would hang
        /// over right or bottom edges of canvas.</param>
        /// <param name="y">Optional. Location within image to paste to.
        /// Position will be adjusted if pasted image would hang
        /// over right or bottom edges of canvas.</param>
        public void Paste(bool toNewLayer, int x = 0, int y = 0)
        {
            // Create a compound history item for recording several
            // operations so that they can all be undone/redone together.
            CompoundHistoryItem paste_action;

            if (toNewLayer)
            {
                paste_action = new CompoundHistoryItem(Stock.Paste, Catalog.GetString("Paste Into New Layer"));
            }
            else
            {
                paste_action = new CompoundHistoryItem(Stock.Paste, Catalog.GetString("Paste"));
            }

            Gtk.Clipboard cb = Gtk.Clipboard.Get(Gdk.Atom.Intern("CLIPBOARD", false));

            // See if the current tool wants to handle the paste
            // operation (e.g., the text tool could paste text)
            if (!toNewLayer)
            {
                if (PintaCore.Tools.CurrentTool.TryHandlePaste(cb))
                {
                    return;
                }
            }

            PintaCore.Tools.Commit();

            // Don't dispose this, as we're going to give it to the history
            Gdk.Pixbuf cbImage = null;

            if (cb.WaitIsImageAvailable())
            {
                cbImage = cb.WaitForImage();
            }

            if (cbImage == null)
            {
                ShowClipboardEmptyDialog();
                return;
            }

            Gdk.Size canvas_size = PintaCore.Workspace.ImageSize;

            // If the image being pasted is larger than the canvas size, allow the user to optionally resize the canvas
            if (cbImage.Width > canvas_size.Width || cbImage.Height > canvas_size.Height)
            {
                ResponseType response = ShowExpandCanvasDialog();

                if (response == ResponseType.Accept)
                {
                    var new_width  = Math.Max(canvas_size.Width, cbImage.Width);
                    var new_height = Math.Max(canvas_size.Height, cbImage.Height);
                    PintaCore.Workspace.ResizeCanvas(new_width, new_height, Pinta.Core.Anchor.Center, paste_action);
                    PintaCore.Actions.View.UpdateCanvasScale();
                }
                else if (response == ResponseType.Cancel || response == ResponseType.DeleteEvent)
                {
                    return;
                }
            }

            // If the pasted image would fall off bottom- or right-
            // side of image, adjust paste position
            x = Math.Max(0, Math.Min(x, canvas_size.Width - cbImage.Width));
            y = Math.Max(0, Math.Min(y, canvas_size.Height - cbImage.Height));

            // If requested, create a new layer, make it the current
            // layer and record it's creation in the history
            if (toNewLayer)
            {
                UserLayer l = AddNewLayer(string.Empty);
                SetCurrentUserLayer(l);
                paste_action.Push(new AddLayerHistoryItem("Menu.Layers.AddNewLayer.png", Catalog.GetString("Add New Layer"), UserLayers.IndexOf(l)));
            }

            // Copy the paste to the temp layer, which should be at least the size of this document.
            CreateSelectionLayer(Math.Max(ImageSize.Width, cbImage.Width),
                                 Math.Max(ImageSize.Height, cbImage.Height));
            ShowSelectionLayer = true;

            using (Cairo.Context g = new Cairo.Context(SelectionLayer.Surface))
            {
                g.DrawPixbuf(cbImage, new Cairo.Point(0, 0));
            }

            SelectionLayer.Transform.InitIdentity();
            SelectionLayer.Transform.Translate(x, y);

            PintaCore.Tools.SetCurrentTool(Catalog.GetString("Move Selected Pixels"));

            DocumentSelection old_selection = Selection.Clone();

            Selection.CreateRectangleSelection(new Cairo.Rectangle(x, y, cbImage.Width, cbImage.Height));
            selection.Visible = true;

            Workspace.Invalidate();

            paste_action.Push(new PasteHistoryItem(cbImage, old_selection));
            History.PushNewItem(paste_action);
        }
Exemplo n.º 45
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;
            View          view  = doc.ActiveView;

            Autodesk.Revit.Creation.Document creDoc
                = doc.Create;

            #region Check for pre-selected wall element
            Selection sel = uidoc.Selection;
            ICollection <ElementId> ids = sel.GetElementIds();

            if (1 == ids.Count)
            {
                Element e = doc.GetElement(ids.First <ElementId>());
                if (e is Wall)
                {
                    LocationCurve lc    = e.Location as LocationCurve;
                    Curve         curve = lc.Curve;

                    using (Transaction tx = new Transaction(doc))
                    {
                        tx.Start("Create Detail Line in Wall Centre");
                        creDoc.NewDetailCurve(view, curve);
                        tx.Commit();
                    }
                    return(Result.Succeeded);
                }
            }
            #endregion // Check for pre-selected wall element

            // Create a geometry line

            XYZ startPoint = new XYZ(0, 0, 0);
            XYZ endPoint   = new XYZ(10, 10, 0);

            //Line geomLine = creApp.NewLine( startPoint, endPoint, true ); // 2013

            Line geomLine = Line.CreateBound(startPoint, endPoint); // 2014

            // Create a geometry arc

            XYZ end0         = new XYZ(0, 0, 0);
            XYZ end1         = new XYZ(10, 0, 0);
            XYZ pointOnCurve = new XYZ(5, 5, 0);

            //Arc geomArc = creApp.NewArc( end0, end1, pointOnCurve ); // 2013

            Arc geomArc = Arc.Create(end0, end1, pointOnCurve); // 2014

#if NEED_PLANE
            // Create a geometry plane

            XYZ origin = new XYZ(0, 0, 0);
            XYZ normal = new XYZ(1, 1, 0);

            Plane geomPlane = creApp.NewPlane(
                normal, origin);

            // Create a sketch plane in current document

            SketchPlane sketch = creDoc.NewSketchPlane(
                geomPlane);
#endif // NEED_PLANE

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("Create Detail Line and Arc");

                // Create a DetailLine element using the
                // newly created geometry line and sketch plane

                DetailLine line = creDoc.NewDetailCurve(
                    view, geomLine) as DetailLine;

                // Create a DetailArc element using the
                // newly created geometry arc and sketch plane

                DetailArc arc = creDoc.NewDetailCurve(
                    view, geomArc) as DetailArc;

                // Change detail curve colour.
                // Initially, this only affects the newly
                // created curves. However, when the view
                // is refreshed, all detail curves will
                // be updated.

                GraphicsStyle gs = arc.LineStyle as GraphicsStyle;

                gs.GraphicsStyleCategory.LineColor
                    = new Color(250, 10, 10);

                tx.Commit();
            }
            return(Result.Succeeded);
        }
Exemplo n.º 46
0
 void DisplayText(Selection selection)
 {
     //   textDisplay.text = selection.intro_msg;
 }
 private static bool TextureArrayItemValidation()
 {
     return(Selection.GetFiltered <Texture2D>(SelectionMode.TopLevel).Length > 0);
 }
 private void moveTo(Selection to)
 {
     this.transform.SetParent(GameObject.Find(SelectionToString(to)).transform, false);
 }
        ///// <summary>
        ///// Allow selection of curve elements only.
        ///// </summary>
        //class CurveElementSelectionFilter : ISelectionFilter
        //{
        //  public bool AllowElement( Element e )
        //  {
        //    return e is CurveElement;
        //  }

        //  public bool AllowReference( Reference r, XYZ p )
        //  {
        //    return true;
        //  }
        //}

        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            // Select all model curves in the entire model.

            List <CurveElement> curves = new List <CurveElement>(
                new FilteredElementCollector(doc)
                .OfClass(typeof(CurveElement))
                .ToElements()
                .Cast <CurveElement>());

            int n = curves.Count;

            // If there are less than two,
            // there is nothing we can do.

            if (2 > n)
            {
                message = _prompt;
                return(Result.Failed);
            }

            // If there are exactly two, pick those.

            if (2 < n)
            {
                // Else, check for a pre-selection.

                curves.Clear();

                Selection sel = uidoc.Selection;

                n = sel.GetElementIds().Count;

                Debug.Print("{0} pre-selected elements.",
                            n);

                // If two or more model curves were pre-
                // selected, use the first two encountered.

                if (1 < n)
                {
                    foreach (Element e in sel.Elements)
                    {
                        CurveElement c = e as CurveElement;

                        if (null != c)
                        {
                            curves.Add(c);

                            if (2 == curves.Count)
                            {
                                Debug.Print("Found two model curves, "
                                            + "ignoring everything else.");

                                break;
                            }
                        }
                    }
                }

                // Else, prompt for an
                // interactive post-selection.

                if (2 != curves.Count)
                {
                    curves.Clear();

                    ISelectionFilter f
                        = new JtElementsOfClassSelectionFilter <CurveElement>();

                    try
                    {
                        Reference r = sel.PickObject(
                            ObjectType.Element, f,
                            "Please pick first model curve.");

                        curves.Add(doc.GetElement(r.ElementId)
                                   as CurveElement);
                    }
                    catch (Autodesk.Revit.Exceptions
                           .OperationCanceledException)
                    {
                        return(Result.Cancelled);
                    }

                    try
                    {
                        Reference r = sel.PickObject(
                            ObjectType.Element, f,
                            "Please pick second model curve.");

                        curves.Add(doc.GetElement(r.ElementId)
                                   as CurveElement);
                    }
                    catch (Autodesk.Revit.Exceptions
                           .OperationCanceledException)
                    {
                        return(Result.Cancelled);
                    }
                }
            }

            // Extract data from the two selected curves.

            Curve c0 = curves[0].GeometryCurve;
            Curve c1 = curves[1].GeometryCurve;

            double sp0   = c0.GetEndParameter(0);
            double ep0   = c0.GetEndParameter(1);
            double step0 = (ep0 - sp0) / _nSegments;

            double sp1   = c1.GetEndParameter(0);
            double ep1   = c1.GetEndParameter(1);
            double step1 = (ep1 - sp1) / _nSegments;

            Debug.Print("Two curves' step size [start, end]:"
                        + " {0} [{1},{2}] -- {3} [{4},{5}]",
                        Util.RealString(step0),
                        Util.RealString(sp0),
                        Util.RealString(ep0),
                        Util.RealString(step1),
                        Util.RealString(sp1),
                        Util.RealString(ep1));

            // Modify document within a transaction.

            using (Transaction tx = new Transaction(doc))
            {
                Creator creator = new Creator(doc);

                tx.Start("MidCurve");

                // Current segment start points.

                double t0 = sp0;
                double t1 = sp1;

                XYZ p0 = c0.GetEndPoint(0);
                XYZ p1 = c1.GetEndPoint(0);
                XYZ p  = Util.Midpoint(p0, p1);

                Debug.Assert(
                    p0.IsAlmostEqualTo(c0.Evaluate(t0, false)),
                    "expected equal start points");

                Debug.Assert(
                    p1.IsAlmostEqualTo(c1.Evaluate(t1, false)),
                    "expected equal start points");

                // Current segment end points.

                t0 += step0;
                t1 += step1;

                XYZ  q0, q1, q;
                Line line;

                for (int i = 0; i < _nSegments; ++i, t0 += step0, t1 += step1)
                {
                    q0 = c0.Evaluate(t0, false);
                    q1 = c1.Evaluate(t1, false);
                    q  = Util.Midpoint(q0, q1);

                    Debug.Print(
                        "{0} {1} {2} {3}-{4} {5}-{6} {7}-{8}",
                        i,
                        Util.RealString(t0),
                        Util.RealString(t1),
                        Util.PointString(p0),
                        Util.PointString(q0),
                        Util.PointString(p1),
                        Util.PointString(q1),
                        Util.PointString(p),
                        Util.PointString(q));

                    // Create approximating curve segment.

                    line = Line.CreateBound(p, q);
                    creator.CreateModelCurve(line);

                    p0 = q0;
                    p1 = q1;
                    p  = q;
                }
                tx.Commit();
            }
            return(Result.Succeeded);
        }
Exemplo n.º 50
0
    static void InitDefaults()
    {
        foreach (var kv in animLayerToDefaultFile)
        {
            if (kv.Value == null)
            {
                LyumaAv3Runtime.animLayerToDefaultController[kv.Key] = null;
            }
            else
            {
                AnimatorController ac = AssetDatabase.LoadAssetAtPath <AnimatorController>("Assets/VRCSDK/Examples3/Animation/Controllers/" + kv.Value + ".controller");
                if (ac == null)
                {
                    Debug.LogWarning("Failed to resolve animator controller " + kv.Value + " for " + kv.Key);
                    ac = null;
                }
                LyumaAv3Runtime.animLayerToDefaultController[kv.Key] = ac;
            }
        }
        foreach (var kv in animLayerToDefaultAvaMaskFile)
        {
            if (kv.Value == null)
            {
                LyumaAv3Runtime.animLayerToDefaultAvaMask[kv.Key] = null;
            }
            else
            {
                AvatarMask mask = null;
                foreach (var guid in AssetDatabase.FindAssets(kv.Value))
                {
                    string path = AssetDatabase.GUIDToAssetPath(guid);
                    mask = AssetDatabase.LoadAssetAtPath <AvatarMask>(path);
                }
                if (mask == null)
                {
                    Debug.LogWarning("Failed to resolve avatar mask " + kv.Value + " for " + kv.Key);
                    mask = new AvatarMask();
                }
                LyumaAv3Runtime.animLayerToDefaultAvaMask[kv.Key] = mask;
            }
        }
        foreach (string guid in AssetDatabase.FindAssets("EmptyController"))
        {
            LyumaAv3Emulator.EmptyController = AssetDatabase.LoadAssetAtPath <RuntimeAnimatorController>(AssetDatabase.GUIDToAssetPath(guid));
        }

        LyumaAv3Runtime.updateSelectionDelegate = (go) => {
            if (go == null && LyumaAv3Emulator.emulatorInstance != null)
            {
                Debug.Log("Resetting selected object: " + LyumaAv3Emulator.emulatorInstance);
                go = LyumaAv3Emulator.emulatorInstance.gameObject;
            }
            Debug.Log("Setting selected object: " + go);
            Selection.SetActiveObjectWithContext(go, go);
            // Highlighter.Highlight("Inspector", "Animator To Debug");
        };

        LyumaAv3Runtime.addRuntimeDelegate = (runtime) => {
            GameObject go = runtime.gameObject;
            try {
                if (PrefabUtility.IsPartOfAnyPrefab(go))
                {
                    PrefabUtility.UnpackPrefabInstance(go, PrefabUnpackMode.Completely, InteractionMode.AutomatedAction);
                }
            } catch (System.Exception) {}
            int moveUpCalls = go.GetComponents <Component>().Length - 2;
            if (!PrefabUtility.IsPartOfAnyPrefab(go.GetComponents <Component>()[1]))
            {
                for (int i = 0; i < moveUpCalls; i++)
                {
                    UnityEditorInternal.ComponentUtility.MoveComponentUp(runtime);
                }
            }
        };
        LyumaAv3Menu.addRuntimeDelegate = (menu) => {
            GameObject go = menu.gameObject;
            try {
                if (PrefabUtility.IsPartOfAnyPrefab(go))
                {
                    PrefabUtility.UnpackPrefabInstance(go, PrefabUnpackMode.Completely, InteractionMode.AutomatedAction);
                }
            } catch (System.Exception) {}
            int moveUpCalls = go.GetComponents <Component>().Length - 2;
            if (!PrefabUtility.IsPartOfAnyPrefab(go.GetComponents <Component>()[1]))
            {
                for (int i = 0; i < moveUpCalls; i++)
                {
                    UnityEditorInternal.ComponentUtility.MoveComponentUp(menu);
                }
            }
        };
    }
Exemplo n.º 51
0
 /// <summary>
 /// Selects the parents.
 /// </summary>
 /// <returns>The parents.</returns>
 private IList <IChromosome> SelectParents()
 {
     return(Selection.SelectChromosomes(Population.MinSize, Population.CurrentGeneration));
 }
Exemplo n.º 52
0
 public void ClearSelectionFormatting()
 {
     Selection.ClearAllProperties();
     UpdateProperties();
 }
Exemplo n.º 53
0
        public static Mock <IVBE> BuildFromSingleModule(string content, string name, ComponentType type, out IVBComponent component, Selection selection = default(Selection), bool referenceStdLibs = false)
        {
            var vbeBuilder = new MockVbeBuilder();

            var builder = vbeBuilder.ProjectBuilder(TestProjectName, ProjectProtection.Unprotected);

            builder.AddComponent(name, type, content, selection);

            if (referenceStdLibs)
            {
                builder.AddReference("VBA", LibraryPathVBA, 4, 1, true);
            }

            var project = builder.Build();
            var vbe     = vbeBuilder.AddProject(project).Build();

            component = project.Object.VBComponents[0];

            vbe.Object.ActiveVBProject = project.Object;
            vbe.Object.ActiveCodePane  = component.CodeModule.CodePane;

            return(vbe);
        }
Exemplo n.º 54
0
 public void HighlightSelection()
 {
     Selection.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Yellow);
 }
Exemplo n.º 55
0
    public override IEnumerator CardEffect(Player player, int target, Selection selection, int cardIndex)
    {
        yield return(base.CardEffect(player, target, selection, cardIndex));

        yield return(player.DrawFromCard(numberToDraw));
    }
        public static void DoSelectionClick()
        {
            GameObject gameobject;

            SceneQueryUtility.FindClickWorldIntersection(Event.current.mousePosition, out gameobject);

            gameobject = SceneQueryUtility.FindSelectionBase(gameobject);

            var  selectedObjectsOnClick = new List <int>(Selection.instanceIDs);
            bool addedSelection         = false;

            if (EditorGUI.actionKey)
            {
                if (gameobject != null)
                {
                    var instanceID = gameobject.GetInstanceID();
                    if (selectedObjectsOnClick.Contains(instanceID))
                    {
                        selectedObjectsOnClick.Remove(instanceID);
                    }
                    else
                    {
                        selectedObjectsOnClick.Add(instanceID);
                        addedSelection = true;
                    }

                    if (selectedObjectsOnClick.Count == 0)
                    {
                        Selection.activeTransform = null;
                    }
                    else
                    {
                        Selection.instanceIDs = selectedObjectsOnClick.ToArray();
                    }
                }
            }
            else
            if (Event.current.shift)
            {
                if (gameobject != null)
                {
                    var instanceID = gameobject.GetInstanceID();
                    selectedObjectsOnClick.Add(instanceID);
                    Selection.instanceIDs = selectedObjectsOnClick.ToArray();
                    addedSelection        = true;
                }
            }
            else
            if (Event.current.alt)
            {
                if (gameobject != null)
                {
                    var instanceID = gameobject.GetInstanceID();
                    selectedObjectsOnClick.Remove(instanceID);
                    Selection.instanceIDs = selectedObjectsOnClick.ToArray();
                    return;
                }
            }
            else
            {
                Selection.activeGameObject = gameobject;
                addedSelection             = true;
            }

            if (!addedSelection)
            {
                foreach (var item in Selection.GetFiltered(typeof(CSGBrush), SelectionMode.Deep))
                {
                    var brush = item as CSGBrush;
                    if (brush.ChildData == null ||
                        !ModelTraits.IsModelEditable(brush.ChildData.Model))
                    {
                        continue;
                    }
                    SelectionUtility.LastUsedModel = brush.ChildData.Model;
                    break;
                }
            }
            else
            if (gameobject != null)
            {
                var brush = gameobject.GetComponent <CSGBrush>();
                if (brush != null)
                {
                    if (brush.ChildData == null ||
                        !ModelTraits.IsModelEditable(brush.ChildData.Model))
                    {
                        return;
                    }
                    SelectionUtility.LastUsedModel = brush.ChildData.Model;
                }
            }
        }
Exemplo n.º 57
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            revitDoc = commandData.Application.ActiveUIDocument.Document;
            uidoc    = commandData.Application.ActiveUIDocument;

            ElementId ele = null;


            Selection selection             = uidoc.Selection;
            ICollection <ElementId> element = selection.GetElementIds();

            foreach (ElementId eleID in element)
            {
                ele = eleID;
                break;
            }


            FloorType FT = new FilteredElementCollector(revitDoc)
                           .OfClass(typeof(FloorType))
                           .First <Element>(
                e => e.Name.Equals("樹 150mm 2"))
                           as FloorType;


            Transaction            transaction            = new Transaction(revitDoc);
            FailureHandlingOptions failureHandlingOptions = transaction.GetFailureHandlingOptions();
            FailureHandler         failureHandler         = new FailureHandler();

            failureHandlingOptions.SetFailuresPreprocessor(failureHandler);
            failureHandlingOptions.SetClearAfterRollback(false);
            transaction.SetFailureHandlingOptions(failureHandlingOptions);
            transaction.Start("Transaction Name");
            // Do something here that causes the error

            List <string> Height = new List <string>();
            List <XYZ>    Data   = LoadTest(ref Height, @"D:\Users\95074\Desktop\CADAPI\CombineTreeAndCircle\CombineTreeAndCircle\bin\Debug\final.txt");

            int kk = 0;

            foreach (var xyz in Data)
            {
                CreateFloor(xyz.X, xyz.Y, double.Parse(Height[kk]), xyz.Z, FT, ele);
                kk = kk + 1;
            }
            transaction.Commit();



            // The following is just illustrative.
            // In reality we would collect the errors
            // to show later.

            //if (failureHandler.ErrorMessage != "")
            //{
            //    System.Windows.Forms.MessageBox.Show(
            //      failureHandler.ErrorSeverity + " || "
            //      + failureHandler.ErrorMessage);
            //}

            return(Result.Succeeded);
        }
 public Selection RewriteSelection(
     SelectionOptimizerContext context,
     Selection selection)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 59
0
        /// <summary>
        /// tmp
        /// </summary>
        /// <param name="commandData"></param>
        void changeSlop(ExternalCommandData commandData)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;
            Selection  sel   = uidoc.Selection;

            Reference ref1 = sel.PickObject(
                ObjectType.Element, "Please pick a floor.");

            Floor f = doc.GetElement(ref1.ElementId) as Floor;

            if (f != null)
            {
                // Retrieve floor edge model line elements.

                ICollection <ElementId> deleted_ids;

                using (Transaction tx = new Transaction(doc))
                {
                    tx.Start("Temporarily Delete Floor");

                    deleted_ids = doc.Delete(f.Id);

                    tx.RollBack();
                }

                // Grab the first floor edge model line.

                ModelLine ml = null;

                foreach (ElementId id in deleted_ids)
                {
                    ml = doc.GetElement(id) as ModelLine;

                    if (null != ml)
                    {
                        break;
                    }
                }

                if (null != ml)
                {
                    using (Transaction tx = new Transaction(doc))
                    {
                        tx.Start("Change Slope Angle");

                        // This parameter is read only. Therefore,
                        // the change does not work and we cannot
                        // change the floor slope angle after the
                        // floor is created.
                        ml.get_Parameter(
                            BuiltInParameter.CURVE_IS_SLOPE_DEFINING)
                        .Set(1);

                        ml.get_Parameter(
                            BuiltInParameter.ROOF_SLOPE)
                        .Set(1.2);

                        tx.Commit();
                    }
                }
            }
        }
Exemplo n.º 60
0
 private static ShapeRange GetShapeRangeFromSelection(Selection selection)
 {
     return(selection.ShapeRange);
 }