Exemplo n.º 1
0
    public static void drawUpgradeSpecs(Editor editor, UpgradeLevel.Specs specs, int[] prices = null)
    {
        EditorGUILayout.Space();
        EditorGUILayout.LabelField("Specs:");
        EditorGUILayout.Space();

        drawUpgradeInfoFloat(editor, "Magnet Radius", ref specs.magnetRadius);
        drawPriceInfo(editor, prices, UpgradeLevel.Type.Magnet);
        EditorGUILayout.Space();

        drawUpgradeInfoInt(editor, "Carrot Sprays", ref specs.carrotSprayCount);
        drawPriceInfo(editor, prices, UpgradeLevel.Type.CarrotSpray);
        EditorGUILayout.Space();

        drawUpgradeInfoInt(editor, "Bubble Gums", ref specs.bubbleGumCount);
        drawPriceInfo(editor, prices, UpgradeLevel.Type.BubbleGum);
        EditorGUILayout.Space();

        drawUpgradeInfoFloat(editor, "Fart Capacity", ref specs.fartCapacity);
        drawUpgradeInfoFloat(editor, "Fart Force", ref specs.fartForce);
        drawPriceInfo(editor, prices, UpgradeLevel.Type.PowerUpFart);
        EditorGUILayout.Space();

        drawUpgradeInfoFloat(editor, "Glide Capacity", ref specs.glideCapacity);
        drawUpgradeInfoFloat(editor, "Glide Force", ref specs.glideForce);
        drawPriceInfo(editor, prices, UpgradeLevel.Type.PowerUpGlide);

        EditorGUILayout.Space();
    }
Exemplo n.º 2
0
    protected void Bt_send_Click(object sender, EventArgs e)
    {
        if (IsValid)
        {
            Hashtable ht = new Hashtable();
            Editor ed = new Editor();
            ed.LoadInfo(Request.Cookies["userID"].Value.ToString());
            ht.Add("messageFrom", SQLString.GetQuotedString(ed.editorColumn));
            ht.Add("messageTo", SQLString.GetQuotedString(txtTo.Text));
            ht.Add("messageTime", SQLString.GetQuotedString(DateTime.Now.ToString()));
            ht.Add("messageTitle", SQLString.GetQuotedString(txtTitle.Text));
            ht.Add("messageContent", SQLString.GetQuotedString(txtContent.Text));
            ht.Add("messageState", SQLString.GetQuotedString("0"));

            Message msg = new Message();
            if (msg.NewMesg(ht))
            {
                Response.Write("<Script Language=JavaScript>alert(\"发送成功!\")</Script>");
            }
            else
            {
                Response.Write("<Script Language=JavaScript>alert(\"发送失败!\")</Script>");
            }
            txtContent.Text = "";
            txtTitle.Text = "";
            txtTo.Text = "";
        }
    }
Exemplo n.º 3
0
 public void EditorInitialize(Editor.TWorldDirector director)
 {
     this.director = director;
     editor = new Editor.TWorldObjectEditor(panel2.Handle, panel2.Width, panel2.Height, director);
     editor.GUI_Notify_ToolsChanged += OnToolsChange;
     timer1.Enabled = true;
 }
Exemplo n.º 4
0
    protected void Bt_Update_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            Editor editor = new Editor();
            editor.LoadInfo(Request.Cookies["userID"].Value.ToString());
            if (txtPwdold.Text == editor.editorPwd)
            {
                string xwhere = "where editorID=" + SQLString.GetQuotedString(Request.Cookies["userID"].Value.ToString());
                Hashtable ht = new Hashtable();
                ht.Add("editorPwd", SQLString.GetQuotedString(txtPwdnew.Text));
                if (editor.Update(ht, xwhere))
                {
                    Response.Write("<Script Language=JavaScript>alert(\"密码修改成功!\")</Script>");

                }
                else
                {
                    Response.Write("<Script Language=JavaScript>alert(\"密码修改失败!\")</Script>");
                }

            }
            else
            {
                Response.Write("<Script Language=JavaScript>alert(\"旧密码错误!\")</Script>");

            }
        }
    }
    protected void Bt_add_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            Editor ed = new Editor();
            ed.LoadInfo(Request.Cookies["userID"].Value.ToString());
            string column = ed.editorColumn;

            Hashtable ht = new Hashtable();
            ht.Add("expertID", SQLString.GetQuotedString(txtID.Text));
            ht.Add("expertPwd", SQLString.GetQuotedString(txtID.Text));//51(aspx)
            ht.Add("expertName", SQLString.GetQuotedString(txtName.Text));
            ht.Add("expertColumn", SQLString.GetQuotedString(column));
            Expert ep = new Expert();
            if (ep.Add(ht))
            {
                Response.Write("<script>alert('添加成功!');window.location=window.location;</script>");
            }
            else
            {

                Response.Write("<script>alert('添加失败!');window.location=window.location;</script>");
            }
            txtID.Text = "";
            txtName.Text = "";
        }
    }
Exemplo n.º 6
0
    public override void ShowInspectorGUI(Editor editor)
    {
        // Calls inspector code from parent class (in this case, allows user to display the default inspector for the object)
        base.ShowInspectorGUI(editor);

        // Insert inspector code here
    }
Exemplo n.º 7
0
 public void EditorInitialize(Editor.TWorldDirector director)
 {
     this.director = director;
     editor = new Editor.TLayersManager(director);
     editor.GUI_Notify_LayersManagerSceneChange += editor_LayersManagerSceneChange;
     editor.GUI_Notify_LayersChange += editor_GUI_Notify_LayersChange;
 }
Exemplo n.º 8
0
		public override void OnFlowSettingsGUI() {
			
			if (Social.settings == null) {
				
				Social.settings = this.GetSettingsFile();
				if (Social.settings == null) Social.settings = ME.EditorUtilities.GetAssetsOfType<SocialSettings>(useCache: false).FirstOrDefault();
				
			}

			var settings = Social.settings;
			if (settings == null) {
				
				EditorGUILayout.HelpBox(string.Format(FlowAddon.MODULE_HAS_ERRORS, "Settings file not found (SocialSettings)."), MessageType.Error);

			} else {
				
				GUILayout.Label(FlowAddon.MODULE_INSTALLED, EditorStyles.centeredGreyMiniLabel);

				if (this.editor == null) this.editor = Editor.CreateEditor(settings);
				if (this.editor != null) {

					this.editor.OnInspectorGUI();

				}

			}

		}
Exemplo n.º 9
0
 public AirCondTable(List<AirCondRow> condRows)
 {
     doc = Application.DocumentManager.MdiActiveDocument;
     db = doc.Database;
     ed = doc.Editor;
     this.condRows = condRows;
 }
        public EditingCodedValueDomains()
        {
            InitializeComponent();

            editor = LayoutRoot.Resources["MyEditor"] as Editor;
            featureLayer = MyMap.Layers["RecreationFacilities"] as FeatureLayer;
        }
        private void Editor_EditCompleted(object sender, Editor.EditEventArgs e)
        {
            var editor = sender as Editor;
            if (e.Action == Editor.EditAction.Select)
            {
                foreach (var edit in e.Edits)
                {
                    if (edit.Graphic != null && edit.Graphic.Selected)
                    {
                        var layer = edit.Layer as FeatureLayer;
                        if (layer != null && layer.IsGeometryUpdateAllowed(edit.Graphic))
                        {
                            // edit geometry
                            if (editor.EditVertices.CanExecute(null))
                                editor.EditVertices.Execute(null);
                        }

                        // edit attribute
                        MyFeatureDataGrid.SelectedItem = edit.Graphic;
                        break;
                    }
                }
            }
            else if (e.Action == Editor.EditAction.EditVertices)
            {
                // should never happen since feature service AllowGeometryUpdates=False
                if (editor.Select.CanExecute("new"))
                    editor.Select.Execute("new");
            }
        }
 public PointMassSubComponentEditor(Editor editor)
     : base(editor)
 {
     name = "Point Masses";
     eEdgePointMasses = editor.serializedObject.FindProperty("mEdgePointMasses");
     eInternalPointMasses = editor.serializedObject.FindProperty("mInternalPointMasses");
 }
Exemplo n.º 13
0
 //private DockPanel _DockPanel;
 //private DockState _DockState;
 public EditorContainer(Editor editor, DockPanel dock, DockState dockState = DockState.Document)
 {
     Editor = editor;
     Editor.UndoRedoStateChanged += Editor_UndoRedoStateChanged;
     Editor.TextChangedDelayed += Editor_TextChangedDelayed;
     Splitter = new Splitter() { Dock = DockStyle.Right, BackColor = SystemColors.ControlDarkDark, Width = 4 };
     DocumentMap = new DocumentMap() {
         Target = editor,
         Dock = DockStyle.Right,
         Width = DocumentMapInitialWidth,
         MinimumSize = new Size(DocumentMapMinimumWidth, 0),
         Scale = DocumentMapInitialWidth * DocumentMapScaleFactor,
         BackColor = EditorSyntax.Styles.Background,
         ForeColor = Color.FromArgb(0, 122, 204)
     };
     DocumentMap.DoubleClick += DocumentMap_DoubleClick;
     DocumentMap.MouseWheel += DocumentMap_MouseWheel;
     Splitter.SplitterMoved += Splitter_SplitterMoved;
     Name = Editor.File.FileName;
     ToolTipText = Editor.File.Path;
     Controls.Add(Editor);
     Controls.Add(Splitter);
     Controls.Add(DocumentMap);
     UpdateText(true);
     FormClosing += EditorContainer_FormClosing;
     FormClosed += EditorContainer_FormClosed;
     System.Threading.Thread.Sleep(10);
     dock.Invoke(new Action(() => { Show(dock, dockState); }));
 }
        public FeatureLayerSelection()
        {
            InitializeComponent();

            MyMap.Extent = initialExtent;
            editor = LayoutRoot.Resources["MyEditor"] as Editor;
        }
Exemplo n.º 15
0
		public frmExtract( string FlatName, string RootDir, Editor.Lib.ShaiyaData Data ) {
			InitializeComponent();

			mFlatName = FlatName;
			mRootDir = RootDir;
			mData = Data;
		}
Exemplo n.º 16
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="editor"></param>
        public Observer(Editor editor)
        {
            _editor = editor;

            _invalidateContainer = () =>
            {
                if (IsPaused)
                {
                    return;
                }
            };

            _invalidateStyles = () =>
            {
                if (IsPaused)
                {
                    return;
                }

                if (_editor.Project != null && _editor.Project.CurrentContainer != null)
                {
                    foreach (var renderer in _editor.Renderers)
                    {
                        renderer.ClearCache(isZooming: false);
                    }
                    _editor.Project.CurrentContainer.Invalidate();
                }
            };

            _invalidateLayers = () =>
            {
                if (IsPaused)
                {
                    return;
                }

                if (_editor.Project != null && _editor.Project.CurrentContainer != null)
                {
                    _editor.Project.CurrentContainer.Invalidate();
                }
            };

            _invalidateShapes = () =>
            {
                if (IsPaused)
                {
                    return;
                }

                if (_editor.Project != null && _editor.Project.CurrentContainer != null)
                {
                    _editor.Project.CurrentContainer.Invalidate();
                }
            };

            if (_editor.Project != null)
            {
                Add(_editor.Project);
            }
        }
Exemplo n.º 17
0
 protected void Bt_login_Click(object sender, EventArgs e)
 {
     string editorID = txtUserID.Text;
     string editorPwd = txtUserPwd.Text;
     Editor editor = new Editor();
     int flag = editor.Login(editorID, editorPwd);
     if (flag == 1)
     {
         editor.LoadInfo(editorID);
         Response.Cookies["userID"].Value = txtUserID.Text;
         Response.Cookies["userID"].Expires = DateTime.Now.AddDays(7);
         Response.Cookies["userName"].Value = editor.editorName;
         Response.Cookies["userName"].Expires = DateTime.Now.AddDays(7);
         Response.Cookies["editorColumn"].Value = editor.editorColumn;
         Response.Cookies["editorColumn"].Expires = DateTime.Now.AddDays(7);
         Response.Cookies["userPwd"].Value = txtUserPwd.Text;
         Response.Cookies["userPwd"].Expires = DateTime.Now.AddDays(7);
         Response.Redirect("main.htm");
     }
     else if (flag == -1)
     {
         Response.Write("<Script Language=JavaScript>alert(\"密码错误!\")</Script>");
     }
     else if (flag == 0)
     {
         Response.Write("<Script Language=JavaScript>alert(\"用户名不存在!\")</Script>");
     }
 }
Exemplo n.º 18
0
        public void EditorInitialize(Editor.TWorldDirector director)
        {
            seek_text_changed = false;
            treeView1.Nodes.Clear();

            textBox1.Enabled = false;
            textBox2.Enabled = false;
            textBox3.Enabled = false;

            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();

            event_editor = new Editor.TEventsEditor(director);
            event_editor.Initialize();

            for(int curr_event_type = 0; curr_event_type<event_editor.GetEventTypesCount();curr_event_type++)
            {
                var curr_type_node = treeView1.Nodes.Add(event_editor.GetEventTypeName(curr_event_type));

                for (int i = 0; i < event_editor.GetEventsCount(curr_event_type); i++)
                {
                    var event_node = curr_type_node.Nodes.Add(i.ToString());
                }
            }
        }
Exemplo n.º 19
0
 private static SearchOption IncludeSubdirs(Editor ed, DirectoryInfo dir)
 {
     // Вопрос - включая подпапки?
     SearchOption recursive = SearchOption.AllDirectories;
     if (dir.GetDirectories().Length > 0)
     {
         var opt = new PromptKeywordOptions("\nВключая подпапки");
         opt.Keywords.Add("Да");
         opt.Keywords.Add("Нет");
         opt.Keywords.Default = "Да";
         var res = ed.GetKeywords(opt);
         if (res.Status == PromptStatus.OK)
         {
             if (res.StringResult == "Нет")
             {
                 recursive = SearchOption.TopDirectoryOnly;
             }
         }
     }
     ed.WriteMessage("\nПапка для переопределения блока " + dir.FullName);
     if (recursive == SearchOption.AllDirectories)
         ed.WriteMessage("\nВключая подпапки");
     else
         ed.WriteMessage("\nТолько в этой папке, без подпапок.");
     return recursive;
 }
    public void DrawWindow(int id)
    {
        if (_editor == null)
            _editor = Editor.CreateEditor (_data);

        _editor.DrawDefaultInspector ();

        // We can also display the path if necessary, commented this out as if the path is large it makes the window width excessive
        //string path = AssetDatabase.GetAssetPath (_data);
        //GUILayout.Label(path);

        GUILayout.BeginHorizontal ();
        if (GUILayout.Button ("Remove")) {
            _ownerWindow.ScriptableObjectWindows.RemoveAt (id);
        }

        if (GUILayout.Button ("Delete")) {
            if (EditorUtility.DisplayDialog("Delete Asset", "Remove " + this.Data.name + "?", "Okay", "Cancel"))
            {
                _ownerWindow.ScriptableObjectWindows.RemoveAt (id);
                AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath (Data));
                AssetDatabase.SaveAssets ();
            }
        }

        GUILayout.EndHorizontal ();
    }
Exemplo n.º 21
0
        public static void GenerateNCS()
        {
            doc = Application.DocumentManager.Add("");
            using (doc.LockDocument())
            {
                ed = doc.Editor;
                db = doc.Database;
                IdTextStylePik = db.GetTextStylePIK();

                using (var t = db.TransactionManager.StartTransaction())
                {
                    //Форма стартовых настроек
                    Options.Show();

                    // Чтение палитры NCS
                    ColorBook colorBookNcs = ColorBook.ReadFromFile(Options.Instance.NCSFile);

                    // Запрос точки начала генерации палитр цветов
                    var ptStart = ed.GetPointWCS("Точка вставки");

                    // Расположение цветов в модели
                    var cs = db.CurrentSpaceId.GetObject(OpenMode.ForWrite) as BlockTableRecord;
                    placementColors(cs, colorBookNcs, ptStart);

                    t.Commit();
                }
            }
        }
Exemplo n.º 22
0
        private void Recorder_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var recorder = new Recorder();
            Hide();

            var result = recorder.ShowDialog();

            if (result.HasValue && result.Value)
            {
                // If Close
                Environment.Exit(0);
            }
            else if (result.HasValue)
            {
                #region If Backbutton or Stop Clicked

                if (recorder.ExitArg == ExitAction.Recorded)
                {
                    var editor = new Editor { ListFrames = recorder.ListFrames };
                    GenericShowDialog(editor);
                    return;
                }

                Show();

                #endregion
            }
        }
Exemplo n.º 23
0
		public override void OnFlowSettingsGUI() {
			
			if (Heatmap.settings == null) {

				Heatmap.settings = this.GetSettingsFile();
				//if (Heatmap.settings == null) Heatmap.settings = ME.EditorUtilities.GetAssetsOfType<HeatmapSettings>(useCache: false).FirstOrDefault();

			}

			if (this.noDataTexture == null) this.noDataTexture = Resources.Load("UI.Windows/Heatmap/NoData") as Texture;

			var settings = Heatmap.settings;
			if (settings == null) {
				
				EditorGUILayout.HelpBox(string.Format(FlowAddon.MODULE_HAS_ERRORS, "Settings file not found (HeatmapSettings)."), MessageType.Error);
				
			} else {
				
				GUILayout.Label(FlowAddon.MODULE_INSTALLED, EditorStyles.centeredGreyMiniLabel);

				if (this.editor == null) this.editor = Editor.CreateEditor(settings);
				if (this.editor != null) {
					
					this.editor.OnInspectorGUI();
					
				}
				
			}

		}
Exemplo n.º 24
0
 public void Disconnect()
 {
     if (_editor == null) return;
     ClearSpellCheckErrors();
     _editor.EditBox.TextArea.TextView.BackgroundRenderers.Remove(_spellCheckRenderer);
     _editor.EditBox.TextArea.TextView.VisualLinesChanged -= TextViewVisualLinesChanged;
     _editor = null;
 }
Exemplo n.º 25
0
 public BlockPlans()
 {
     _doc = Application.DocumentManager.MdiActiveDocument;
     _ed = _doc.Editor;
     _db = _doc.Database;
     _section = string.Empty;
     setTypeBlock(BlockPlanTypeEnum.Mounting);
 }
 public AttachPointSubComponentEditor(Editor editor)
     : base(editor)
 {
     name = "Attach Point";
     handlePositions = new Vector3[4];
     handleSizes = new float[4];
     eAttachPoints = editor.serializedObject.FindProperty("mAttachPoints");
 }
Exemplo n.º 27
0
 public AutoCADIO(
     Editor ed, bool showProgress = false, string commandFile = null
     )
 {
     _suppliedCommandFile = commandFile;
       _ed = ed;
       _showProgress = showProgress;
 }
Exemplo n.º 28
0
 public AStirrups()
 {
     editor = Application.DocumentManager.MdiActiveDocument.Editor;
     db = Application.DocumentManager.MdiActiveDocument.Database;
     doc = Application.DocumentManager.MdiActiveDocument;
     acMark = new ACMark();
     adaptator = new BWCadAdaptator();
 }
Exemplo n.º 29
0
 public static void NewFile(Editor editor)
 {
     if (SaveIfModified(editor) == false) return;
     editor.Text = string.Empty;
     editor.IsModified = false;
     editor.FileName = string.Empty;
     Settings.Default.LastOpenFile = string.Empty;
 }
 private void Editor_EditCompleted(object sender, Editor.EditEventArgs e)
 {
     if (e.Action != Editor.EditAction.Cancel)
     {
         AttributeGrid.Visibility = System.Windows.Visibility.Visible;
         CoverGrid.Visibility = System.Windows.Visibility.Visible;
     }
 }
Exemplo n.º 31
0
 /// <summary>
 /// InspectorElement constructor.
 /// </summary>
 public InspectorElement(Editor editor) : this(editor, Mode.Normal)
 {
 }
Exemplo n.º 32
0
        void SetupMauiLayout()
        {
            var verticalStack = new VerticalStackLayout()
            {
                Spacing = 5, BackgroundColor = Colors.AntiqueWhite
            };
            var horizontalStack = new HorizontalStackLayout()
            {
                Spacing = 2, BackgroundColor = Colors.CornflowerBlue
            };

            //verticalStack.Add(CreateSampleGrid());
            verticalStack.Add(CreateResizingButton());

            AddTextResizeDemo(verticalStack);

            verticalStack.Add(new Label {
                Text = " ", Padding = new Thickness(10)
            });
            var label = new Label {
                Text = "End-aligned text", BackgroundColor = Colors.Fuchsia, HorizontalTextAlignment = TextAlignment.End
            };

            label.Margin = new Thickness(15, 10, 20, 15);

            SemanticProperties.SetHint(label, "Hint Text");
            SemanticProperties.SetDescription(label, "Description Text");

            verticalStack.Add(label);
            verticalStack.Add(new Label {
                Text = "This should be BIG text!", FontSize = 24, HorizontalOptions = LayoutOptions.End
            });

            SemanticProperties.SetHeadingLevel((BindableObject)verticalStack.Children.Last(), SemanticHeadingLevel.Level1);
            verticalStack.Add(new Label {
                Text = "This should be BOLD text!", FontAttributes = FontAttributes.Bold, HorizontalOptions = LayoutOptions.Center
            });
            verticalStack.Add(new Label {
                Text = "This should have character spacing!", CharacterSpacing = 3
            });
            verticalStack.Add(new Label {
                Text = "This should be a CUSTOM font!", FontFamily = "Dokdo"
            });
            verticalStack.Add(
                new Button
            {
                Text    = "Push a Page",
                Command = new Command(async() =>
                {
                    await Navigation.PushAsync(new SemanticsPage());
                })
            }
                );

            verticalStack.Add(new Label {
                Text = "This should have padding", Padding = new Thickness(40), BackgroundColor = Colors.LightBlue
            });
            verticalStack.Add(new Label {
                Text = LoremIpsum
            });
            verticalStack.Add(new Label {
                Text = LoremIpsum, MaxLines = 2
            });
            verticalStack.Add(new Label {
                Text = LoremIpsum, LineBreakMode = LineBreakMode.TailTruncation
            });
            verticalStack.Add(new Label {
                Text = LoremIpsum, MaxLines = 2, LineBreakMode = LineBreakMode.TailTruncation
            });
            verticalStack.Add(new Label {
                Text = "This should have five times the line height! " + LoremIpsum, LineHeight = 5, MaxLines = 2
            });
            verticalStack.Add(new Label
            {
                FontSize   = 24,
                Text       = "LinearGradient Text",
                Background = new LinearGradientBrush(
                    new GradientStopCollection
                {
                    new GradientStop(Colors.Green, 0),
                    new GradientStop(Colors.Blue, 1)
                },
                    new Point(0, 0),
                    new Point(1, 0))
            });
            verticalStack.Add(new Label
            {
                Text       = "RadialGradient",
                Padding    = new Thickness(30),
                Background = new RadialGradientBrush(
                    new GradientStopCollection
                {
                    new GradientStop(Colors.DarkBlue, 0),
                    new GradientStop(Colors.Yellow, 0.6f),
                    new GradientStop(Colors.LightPink, 1)
                },
                    new Point(0.5, 0.5),
                    0.3f)
            });

            SemanticProperties.SetHeadingLevel((BindableObject)verticalStack.Children.Last(), SemanticHeadingLevel.Level2);

            var visibleClearButtonEntry = new Entry()
            {
                ClearButtonVisibility = ClearButtonVisibility.WhileEditing, Placeholder = "This Entry will show clear button if has input."
            };
            var hiddenClearButtonEntry = new Entry()
            {
                ClearButtonVisibility = ClearButtonVisibility.Never, Placeholder = "This Entry will not..."
            };

            verticalStack.Add(visibleClearButtonEntry);
            verticalStack.Add(hiddenClearButtonEntry);

            verticalStack.Add(new Editor {
                Placeholder = "This is an editor placeholder."
            });
            verticalStack.Add(new Editor {
                Placeholder = "Green Text Color.", TextColor = Colors.Green
            });
            var paddingButton = new Button
            {
                Padding         = new Thickness(40),
                Text            = "This button has a padding!!",
                BackgroundColor = Colors.Purple,
            };

            verticalStack.Add(paddingButton);

            var underlineLabel = new Label {
                Text = "underline", TextDecorations = TextDecorations.Underline
            };

            verticalStack.Add(underlineLabel);

            verticalStack.Add(new ActivityIndicator());
            verticalStack.Add(new ActivityIndicator {
                Color = Colors.Red, IsRunning = true
            });

            var button = new Button()
            {
                Text = _viewModel.Text, WidthRequest = 200
            };

            button.Clicked += async(sender, e) =>
            {
                var events = _services.GetRequiredService <ILifecycleEventService>();
                events.InvokeEvents <Action <string> >("CustomEventName", action => action("VALUE"));

                var location = await Geolocation.GetLocationAsync(new GeolocationRequest(GeolocationAccuracy.Lowest));

                Debug.WriteLine($"I tracked you down to {location.Latitude}, {location.Longitude}! You can't hide!");
            };

            var button2 = new Button()
            {
                TextColor = Colors.Green,
                Text      = "Hello I'm a button",
                //	BackgroundColor = Color.Purple,
                Margin = new Thickness(12)
            };

            horizontalStack.Add(button);
            horizontalStack.Add(button2);

            horizontalStack.Add(new Label {
                Text = "And these buttons are in a HorizontalStackLayout", VerticalOptions = LayoutOptions.Center
            });

            verticalStack.Add(horizontalStack);

            verticalStack.Add(new Button {
                Text = "CharacterSpacing"
            });
            verticalStack.Add(new Button {
                CharacterSpacing = 8, Text = "CharacterSpacing"
            });

            verticalStack.Add(new RedButton {
                Text = "Dynamically Registered"
            });

            var checkbox = new CheckBox();

            checkbox.CheckedChanged += (sender, e) =>
            {
                Debug.WriteLine($"Checked Changed to '{e.Value}'");
            };
            verticalStack.Add(checkbox);
            verticalStack.Add(new CheckBox {
                BackgroundColor = Colors.LightPink
            });
            verticalStack.Add(new CheckBox {
                IsChecked = true, Color = Colors.Aquamarine
            });

            var editor = new Editor();

            editor.Completed += (sender, args) =>
            {
                Debug.WriteLine($"Editor Completed");
            };

            verticalStack.Add(editor);
            verticalStack.Add(new Editor {
                Text = "Editor"
            });
            verticalStack.Add(new Editor {
                Text = "Lorem ipsum dolor sit amet", MaxLength = 10
            });
            verticalStack.Add(new Editor {
                Text = "Predictive Text Off", IsTextPredictionEnabled = false
            });
            verticalStack.Add(new Editor {
                Text = "Lorem ipsum dolor sit amet", FontSize = 10, FontFamily = "Dokdo"
            });
            verticalStack.Add(new Editor {
                Text = "ReadOnly Editor", IsReadOnly = true
            });


            var entry = new Entry();

            entry.TextChanged += (sender, e) =>
            {
                Debug.WriteLine($"Text Changed from '{e.OldTextValue}' to '{e.NewTextValue}'");
            };

            var entryMargin = new Thickness(10, 0);

            verticalStack.Add(entry);
            verticalStack.Add(new Entry {
                Text = "Entry", TextColor = Colors.DarkRed, FontFamily = "Dokdo", MaxLength = -1, Margin = entryMargin
            });
            verticalStack.Add(new Entry {
                IsPassword = true, TextColor = Colors.Black, Placeholder = "Pasword Entry", Margin = entryMargin
            });
            verticalStack.Add(new Entry {
                IsTextPredictionEnabled = false
            });
            verticalStack.Add(new Entry {
                Placeholder = "This should be placeholder text", Margin = entryMargin
            });
            verticalStack.Add(new Entry {
                Text = "This should be read only property", IsReadOnly = true, Margin = entryMargin
            });
            verticalStack.Add(new Entry {
                MaxLength = 5, Placeholder = "MaxLength text", Margin = entryMargin
            });
            verticalStack.Add(new Entry {
                Text = "This should be text with character spacing", CharacterSpacing = 10
            });
            verticalStack.Add(new Entry {
                Keyboard = Keyboard.Numeric, Placeholder = "Numeric Entry"
            });
            verticalStack.Add(new Entry {
                Keyboard = Keyboard.Email, Placeholder = "Email Entry"
            });
            verticalStack.Add(new Entry {
                Placeholder = "This is a blue text box", BackgroundColor = Colors.CornflowerBlue
            });

            verticalStack.Add(new ProgressBar {
                Progress = 0.5
            });
            verticalStack.Add(new ProgressBar {
                Progress = 0.5, BackgroundColor = Colors.LightCoral
            });
            verticalStack.Add(new ProgressBar {
                Progress = 0.5, ProgressColor = Colors.Purple
            });

            var searchBar = new SearchBar
            {
                CharacterSpacing = 4,
                Text             = "A search query"
            };

            verticalStack.Add(searchBar);

            var placeholderSearchBar = new SearchBar
            {
                Placeholder = "Placeholder"
            };

            verticalStack.Add(placeholderSearchBar);

            var monkeyList = new List <string>
            {
                "Baboon",
                "Capuchin Monkey",
                "Blue Monkey",
                "Squirrel Monkey",
                "Golden Lion Tamarin",
                "Howler Monkey",
                "Japanese Macaque"
            };

            var picker = new Picker {
                Title = "Select a monkey", FontFamily = "Dokdo", HorizontalTextAlignment = TextAlignment.Center
            };

            picker.ItemsSource = monkeyList;
            verticalStack.Add(picker);

            verticalStack.Add(new Slider());

            verticalStack.Add(new Stepper());
            verticalStack.Add(new Stepper {
                BackgroundColor = Colors.IndianRed
            });
            verticalStack.Add(new Stepper {
                Minimum = 0, Maximum = 10, Value = 5
            });

            verticalStack.Add(new Switch());
            verticalStack.Add(new Switch()
            {
                OnColor = Colors.Green
            });
            verticalStack.Add(new Switch()
            {
                ThumbColor = Colors.Yellow
            });
            verticalStack.Add(new Switch()
            {
                OnColor = Colors.Green, ThumbColor = Colors.Yellow
            });

            verticalStack.Add(new DatePicker());
            verticalStack.Add(new DatePicker {
                CharacterSpacing = 6
            });
            verticalStack.Add(new DatePicker {
                FontSize = 24
            });

            verticalStack.Add(new TimePicker());
            verticalStack.Add(new TimePicker {
                Time = TimeSpan.FromHours(8), CharacterSpacing = 6
            });

            verticalStack.Add(new Label {
                Text = "IMAGES (static | animated):"
            });
            verticalStack.Add(CreateImagesGrid());

            Content = new ScrollView
            {
                Content = verticalStack
            };
        }
Exemplo n.º 33
0
 public override void Trigger(EditableView.ClickPosition.Sources source, EditableView pnlView, Transaction transaction)
 {
     Editor.SimulateKey(Key);
 }
 static void Drawer_TitleDefaultFrameSettings(HDRenderPipelineUI s, SerializedHDRenderPipelineAsset d, Editor o)
 {
     GUILayout.BeginHorizontal();
     EditorGUILayout.LabelField(defaultFrameSettingsContent, EditorStyles.boldLabel);
     EditorGUI.BeginChangeCheck();
     selectedFrameSettings = (SelectedFrameSettings)EditorGUILayout.EnumPopup(selectedFrameSettings);
     if (EditorGUI.EndChangeCheck())
     {
         Init(s, d, o);
     }
     GUILayout.EndHorizontal();
 }
Exemplo n.º 35
0
 public void FocusEditor(bool bringttop)
 {
     Editor.FocusEditor(bringttop);
 }
Exemplo n.º 36
0
    // Draw the property inside the given rect
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        var e = Editor.CreateEditor(property.objectReferenceValue);

        position.height = EditorGUI.GetPropertyHeight(property);

        if (e != null)
        {
            var w = position.width;
            position.width = 20;
            if (GUI.Button(position, _folded ? "+" : "-", EditorStyles.toolbarButton))
            {
                _folded = !_folded;
            }
            position.width = w - 25;
            position.x    += 25;
            EditorGUIUtility.labelWidth -= 25;
            EditorGUI.PropertyField(position, property);
            EditorGUIUtility.labelWidth += 25;
            position.x    -= 25;
            position.width = w;
        }
        else
        {
            EditorGUI.PropertyField(position, property);
        }

        position.y += EditorGUI.GetPropertyHeight(property);

        if (_folded)
        {
            return;
        }

        if (e != null)
        {
            position.x     += 20;
            position.width -= 40;

            position = MyGUI.DrawLine(MyGUI.Gray, position);

            var so = e.serializedObject;
            so.Update();

            var prop = so.GetIterator();
            prop.NextVisible(true);
            while (prop.NextVisible(true))
            {
                position.height = EditorGUI.GetPropertyHeight(prop);
                EditorGUI.PropertyField(position, prop);
                position.y += EditorGUI.GetPropertyHeight(prop) + 4;
            }
            if (GUI.changed)
            {
                so.ApplyModifiedProperties();
            }

            position.y -= 4;
            MyGUI.DrawLine(MyGUI.Gray, position);
        }
    }
Exemplo n.º 37
0
        Task RunUpdateTask(ITextSource input, IDocumentLine startLine, int endOffset, ITextSourceVersion textSourceVersion, CancellationToken token)
        {
            return(Task.Run(delegate {
                var matches = new List <(UrlType, Match, IDocumentLine)> ();
                var line = startLine;
                int o = 0;
                while (line != null && line.Offset <= endOffset)
                {
                    if (token.IsCancellationRequested)
                    {
                        return;
                    }
                    string lineText = input.GetTextAt(line.Offset, line.Length);
                    var match = UrlRegex.Match(lineText);
                    while (match.Success)
                    {
                        if (token.IsCancellationRequested)
                        {
                            return;
                        }
                        matches.Add((UrlType.Url, match, line));
                        o = match.Index + match.Length;
                        var len = line.Length - o;
                        if (len <= 0)
                        {
                            break;
                        }
                        match = UrlRegex.Match(lineText, o, len);
                    }

                    o = 0;
                    match = MailRegex.Match(lineText);
                    while (match.Success)
                    {
                        if (token.IsCancellationRequested)
                        {
                            return;
                        }
                        matches.Add((UrlType.Email, match, line));
                        o = match.Index + match.Length;
                        var len = line.Length - o;
                        if (len <= 0)
                        {
                            break;
                        }
                        match = MailRegex.Match(lineText, o, len);
                    }
                    line = line.NextLine;
                }

                Runtime.RunInMainThread(delegate {
                    if (token.IsCancellationRequested || Editor == null)
                    {
                        return;
                    }
                    if (textSourceVersion.CompareAge(Editor.Version) != 0)
                    {
                        return;
                    }
                    line = startLine;
                    while (line != null && line.Offset <= endOffset)
                    {
                        foreach (var u in Editor.GetLineMarkers(line).OfType <IUrlTextLineMarker> ())
                        {
                            Editor.RemoveMarker(u);
                            markers.Remove(u);
                        }
                        line = line.NextLine;
                    }

                    foreach (var m in matches)
                    {
                        var startCol = m.Item2.Index;
                        var url = m.Item2.Value;
                        var marker = Editor.TextMarkerFactory.CreateUrlTextMarker(Editor, url, m.Item1, "url", startCol, startCol + m.Item2.Length);
                        markers.Add(marker);
                        Editor.AddMarker(m.Item3, marker);
                    }
                    src.Remove(startLine.Offset);
                });
            }));
 static void Drawer_FieldShadowSize(ShadowInitParametersUI s, SerializedShadowInitParameters d, Editor o)
 {
     EditorGUILayout.LabelField(_.GetContent("Shadow Atlas Settings"), EditorStyles.boldLabel);
     ++EditorGUI.indentLevel;
     EditorGUILayout.PropertyField(d.shadowAtlasWidth, _.GetContent("Atlas Width"));
     EditorGUILayout.PropertyField(d.shadowAtlasHeight, _.GetContent("Atlas Height"));
     --EditorGUI.indentLevel;
 }
Exemplo n.º 39
0
        // When a key is pressed, and before the key is processed by the editor, this method will be invoked.
        // Return true if the key press should be processed by the editor.
        public override bool KeyPress(KeyDescriptor descriptor)
        {
            if (!IsActiveExtension())
            {
                return(base.KeyPress(descriptor));
            }
            bool res;

            if (CurrentCompletionContext != null)
            {
                if (CompletionWindowManager.PreProcessKeyEvent(descriptor))
                {
                    CompletionWindowManager.PostProcessKeyEvent(descriptor);
                    autoHideCompletionWindow = true;
                    // in named parameter case leave the parameter window open.
                    autoHideParameterWindow = descriptor.KeyChar != ':';
                    if (!autoHideParameterWindow && ParameterInformationWindowManager.IsWindowVisible)
                    {
                        ParameterInformationWindowManager.PostProcessKeyEvent(this, CompletionWidget, descriptor);
                    }

                    return(false);
                }
                autoHideCompletionWindow = autoHideParameterWindow = false;
            }

            if (ParameterInformationWindowManager.IsWindowVisible)
            {
                if (ParameterInformationWindowManager.ProcessKeyEvent(this, CompletionWidget, descriptor))
                {
                    return(false);
                }
                autoHideCompletionWindow = autoHideParameterWindow = false;
            }

            //			int oldPos = Editor.CursorPosition;
            //			int oldLen = Editor.TextLength;
            char deleteOrBackspaceTriggerChar = '\0';

            if (descriptor.SpecialKey == SpecialKey.Delete && Editor.CaretOffset < Editor.Length)
            {
                deleteOrBackspaceTriggerChar = Editor.GetCharAt(Editor.CaretOffset);
            }
            if (descriptor.SpecialKey == SpecialKey.BackSpace && Editor.CaretOffset > 0)
            {
                deleteOrBackspaceTriggerChar = Editor.GetCharAt(Editor.CaretOffset - 1);
            }

            res = base.KeyPress(descriptor);
            if (Editor.EditMode == EditMode.TextLink && Editor.TextLinkPurpose == TextLinkPurpose.Rename)
            {
                return(res);
            }
            if (descriptor.KeyChar == (char)16 || descriptor.KeyChar == (char)17)
            {
                return(res);
            }

            CompletionWindowManager.PostProcessKeyEvent(descriptor);

            var ignoreMods = ModifierKeys.Control | ModifierKeys.Alt
                             | ModifierKeys.Command;

            // Handle parameter completion
            if (ParameterInformationWindowManager.IsWindowVisible)
            {
                ParameterInformationWindowManager.PostProcessKeyEvent(this, CompletionWidget, descriptor);
            }

            if ((descriptor.ModifierKeys & ignoreMods) != 0)
            {
                return(res);
            }

            // don't complete on block selection
            if (!IdeApp.Preferences.EnableAutoCodeCompletion || Editor.SelectionMode == MonoDevelop.Ide.Editor.SelectionMode.Block)
            {
                return(res);
            }

            // Handle code completion
            if (descriptor.KeyChar != '\0' && CompletionWidget != null && !CompletionWindowManager.IsVisible)
            {
                completionTokenSrc.Cancel();
                CurrentCompletionContext = CompletionWidget.CurrentCodeCompletionContext;
                completionTokenSrc       = new CancellationTokenSource();
                var caretOffset = Editor.CaretOffset;
                var token       = completionTokenSrc.Token;
                try {
                    var task = HandleCodeCompletionAsync(CurrentCompletionContext, new CompletionTriggerInfo(CompletionTriggerReason.CharTyped, descriptor.KeyChar), token);
                    if (task != null)
                    {
                        // Show the completion window in two steps. The call to PrepareShowWindow creates the window but
                        // it doesn't show it. It is used only to process the keys while the completion data is being retrieved.
                        CompletionWindowManager.PrepareShowWindow(this, descriptor.KeyChar, CompletionWidget, CurrentCompletionContext);
                        EventHandler windowClosed = delegate(object o, EventArgs a) {
                            completionTokenSrc.Cancel();
                        };
                        CompletionWindowManager.WindowClosed += windowClosed;
                        task.ContinueWith(t => {
                            CompletionWindowManager.WindowClosed -= windowClosed;
                            if (token.IsCancellationRequested)
                            {
                                return;
                            }
                            var result = t.Result;
                            if (result != null)
                            {
                                int triggerWordLength = result.TriggerWordLength + (Editor.CaretOffset - caretOffset);
                                if (triggerWordLength > 0 && (triggerWordLength < Editor.CaretOffset ||
                                                              (triggerWordLength == 1 && Editor.CaretOffset == 1)))
                                {
                                    CurrentCompletionContext = CompletionWidget.CreateCodeCompletionContext(Editor.CaretOffset - triggerWordLength);
                                    if (result.TriggerWordStart >= 0)
                                    {
                                        CurrentCompletionContext.TriggerOffset = result.TriggerWordStart;
                                    }
                                    CurrentCompletionContext.TriggerWordLength = triggerWordLength;
                                }
                                // Now show the window for real.
                                if (!CompletionWindowManager.ShowWindow(result, CurrentCompletionContext))
                                {
                                    CurrentCompletionContext = null;
                                }
                            }
                            else
                            {
                                CompletionWindowManager.HideWindow();
                                CurrentCompletionContext = null;
                            }
                        }, Runtime.MainTaskScheduler);
                    }
                    else
                    {
                        CurrentCompletionContext = null;
                    }
                } catch (TaskCanceledException) {
                } catch (AggregateException) {
                }
            }

            if ((descriptor.SpecialKey == SpecialKey.Delete || descriptor.SpecialKey == SpecialKey.BackSpace) && CompletionWidget != null && !CompletionWindowManager.IsVisible)
            {
                if (!char.IsLetterOrDigit(deleteOrBackspaceTriggerChar) && deleteOrBackspaceTriggerChar != '_')
                {
                    return(res);
                }
                CurrentCompletionContext = CompletionWidget.CurrentCodeCompletionContext;

                int cpos, wlen;
                if (!GetCompletionCommandOffset(out cpos, out wlen))
                {
                    cpos = Editor.CaretOffset;
                    wlen = 0;
                }

                CurrentCompletionContext.TriggerOffset     = cpos;
                CurrentCompletionContext.TriggerWordLength = wlen;

                completionTokenSrc.Cancel();
                completionTokenSrc = new CancellationTokenSource();
                var caretOffset = Editor.CaretOffset;
                var token       = completionTokenSrc.Token;
                try {
                    var task = HandleCodeCompletionAsync(CurrentCompletionContext, new CompletionTriggerInfo(CompletionTriggerReason.BackspaceOrDeleteCommand, deleteOrBackspaceTriggerChar), token);
                    if (task != null)
                    {
                        // Show the completion window in two steps. The call to PrepareShowWindow creates the window but
                        // it doesn't show it. It is used only to process the keys while the completion data is being retrieved.
                        CompletionWindowManager.PrepareShowWindow(this, descriptor.KeyChar, CompletionWidget, CurrentCompletionContext);
                        EventHandler windowClosed = delegate(object o, EventArgs a) {
                            completionTokenSrc.Cancel();
                        };
                        CompletionWindowManager.WindowClosed += windowClosed;

                        task.ContinueWith(t => {
                            CompletionWindowManager.WindowClosed -= windowClosed;
                            if (token.IsCancellationRequested)
                            {
                                return;
                            }
                            var result = t.Result;
                            if (result != null)
                            {
                                int triggerWordLength = result.TriggerWordLength + (Editor.CaretOffset - caretOffset);

                                if (triggerWordLength > 0 && (triggerWordLength < Editor.CaretOffset ||
                                                              (triggerWordLength == 1 && Editor.CaretOffset == 1)))
                                {
                                    CurrentCompletionContext = CompletionWidget.CreateCodeCompletionContext(Editor.CaretOffset - triggerWordLength);
                                    if (result.TriggerWordStart >= 0)
                                    {
                                        CurrentCompletionContext.TriggerOffset = result.TriggerWordStart;
                                    }
                                    CurrentCompletionContext.TriggerWordLength = triggerWordLength;
                                }
                                // Now show the window for real.
                                if (!CompletionWindowManager.ShowWindow(result, CurrentCompletionContext))
                                {
                                    CurrentCompletionContext = null;
                                }
                                else
                                {
                                    CompletionWindowManager.Wnd.StartOffset = CurrentCompletionContext.TriggerOffset;
                                }
                            }
                            else
                            {
                                CompletionWindowManager.HideWindow();
                                CurrentCompletionContext = null;
                            }
                        }, Runtime.MainTaskScheduler);
                    }
                    else
                    {
                        CurrentCompletionContext = null;
                    }
                } catch (TaskCanceledException) {
                    CurrentCompletionContext = null;
                } catch (AggregateException) {
                    CurrentCompletionContext = null;
                }
            }

            if (CompletionWidget != null)
            {
                CodeCompletionContext ctx  = CompletionWidget.CurrentCodeCompletionContext;
                var newparameterHintingSrc = new CancellationTokenSource();
                var token = newparameterHintingSrc.Token;
                try {
                    var task = HandleParameterCompletionAsync(ctx, descriptor.KeyChar, token);
                    if (task != null)
                    {
                        parameterHintingSrc.Cancel();
                        parameterHintingSrc = newparameterHintingSrc;
                        parameterHingtingCursorPositionChanged = false;
                        task.ContinueWith(t => {
                            if (!token.IsCancellationRequested && t.Result != null)
                            {
                                ParameterInformationWindowManager.ShowWindow(this, CompletionWidget, ctx, t.Result);
                                if (parameterHingtingCursorPositionChanged)
                                {
                                    ParameterInformationWindowManager.UpdateCursorPosition(this, CompletionWidget);
                                }
                            }
                        }, token, TaskContinuationOptions.None, Runtime.MainTaskScheduler);
                    }
                    else
                    {
                        //Key was typed that was filtered out, no heavy processing will be performed(task==null)
                        //but we still want to update ParameterInfo window to avoid displaying it outside method call
                        parameterHingtingCursorPositionChanged = true;
                    }
                } catch (TaskCanceledException) {
                } catch (AggregateException) {
                }
            }
            return(res);
        }
Exemplo n.º 40
0
 private void OnEnable()
 {
     defaultEditor = Editor.CreateEditor(targets, System.Type.GetType("UnityEditor.TransformInspector, UnityEditor"));
     transform     = target as Transform;
 }
Exemplo n.º 41
0
        private VisualElement CreateIMGUIInspectorFromEditor(SerializedObject serializedObject, Editor editor,
                                                             bool reuseIMGUIContainer)
        {
            if ((mode & (Mode.IMGUICustom | Mode.IMGUIDefault)) == 0)
            {
                return(null);
            }

            if ((mode & Mode.IMGUICustom) > 0 && (mode & Mode.IMGUIDefault) == 0 && editor is GenericInspector)
            {
                return(null);
            }

            if ((mode & Mode.IMGUICustom) == 0 && (mode & Mode.IMGUIDefault) > 0 && !(editor is GenericInspector) && !(editor is AssetImporterEditor) && !(editor is GameObjectInspector))
            {
                editor           = ScriptableObject.CreateInstance <GenericInspector>();
                editor.hideFlags = HideFlags.HideAndDontSave;
                editor.InternalSetTargets(new[] { serializedObject.targetObject });
            }

            if (editor is GenericInspector)
            {
                AddToClassList(iMGUIDefaultVariantUssClassName);
                if ((mode & Mode.DebugMod) > 0)
                {
                    AddToClassList(debugVariantUssClassName);
                    editor.inspectorMode = InspectorMode.Debug;
                }
                else if ((mode & Mode.DebugInternalMod) > 0)
                {
                    AddToClassList(debugInternalVariantUssClassName);
                    editor.inspectorMode = InspectorMode.DebugInternal;
                }
            }
            else
            {
                AddToClassList(iMGUICustomVariantUssClassName);
            }

            IMGUIContainer inspector;

            // Reusing the existing IMGUIContainer allows us to re-use the existing gui state, when we are drawing the same inspector this will let us keep the same control ids
            if (reuseIMGUIContainer && m_IMGUIContainer != null)
            {
                inspector = m_IMGUIContainer;
            }
            else
            {
                inspector = new IMGUIContainer();
            }

            m_IgnoreOnInspectorGUIErrors = false;
            inspector.onGUIHandler       = () =>
            {
                // It's possible to run 2-3 frames after the tracker of this inspector window has
                // been recreated, and with it the Editor and its SerializedObject. One example of
                // when this happens is when the Preview window is detached from a *second* instance
                // of an InspectorWindow and re-attached.
                //
                // This is only a problem for the *second* (or third, forth, etc) instance of
                // the InspectorWindow because only the first instance can use the
                // ActiveEditorTracker.sharedTracker in InspectorWindow.CreateTracker(). The
                // other instances have to create a new tracker...each time.
                //
                // Not an ideal solution, but basically we temporarily hold the printing to console
                // for errors for which GUIUtility.ShouldRethrowException(e) returns false.
                // The errors that may occur during this brief "bad state" are SerializedProperty
                // errors. If the custom Editor created and remembered references to some
                // SerializedProperties during its OnEnable(), those references will be invalid
                // when the tracker is refreshed, until this GUIHandler is reassigned. This fix
                // just ignores those errors.
                //
                // We don't simply early return here because that can break some tests that
                // rely heavily on yields and timing of UI redraws. Yes..
                //
                // case 1119612
                if (editor.m_SerializedObject == null)
                {
                    editor.Repaint();
                    m_IgnoreOnInspectorGUIErrors = true;
                }

                if ((editor.target == null && !GenericInspector.ObjectIsMonoBehaviourOrScriptableObjectWithoutScript(editor.target)) ||
                    !editor.serializedObject.isValid)
                {
                    return;
                }

                EditorGUIUtility.ResetGUIState();
                using (new EditorGUI.DisabledScope(!editor.IsEnabled()))
                {
                    var genericEditor = editor as GenericInspector;
                    if (genericEditor != null)
                    {
                        switch (mode)
                        {
                        case Mode.Normal:
                            genericEditor.inspectorMode = InspectorMode.Normal;
                            break;

                        case Mode.Default:
                            genericEditor.inspectorMode = InspectorMode.Debug;
                            break;

                        case Mode.Custom:
                            genericEditor.inspectorMode = InspectorMode.DebugInternal;
                            break;

                        case Mode.IMGUI:
                            break;
                        }
                    }

                    //set the current PropertyHandlerCache to the current editor
                    ScriptAttributeUtility.propertyHandlerCache = editor.propertyHandlerCache;

                    var originalHierarchyMode = EditorGUIUtility.hierarchyMode;
                    EditorGUIUtility.hierarchyMode = true;

                    var originalWideMode = SetWideModeForWidth(inspector);

                    GUIStyle editorWrapper = (editor.UseDefaultMargins() && editor.CanBeExpandedViaAFoldoutWithoutUpdate()
                        ? EditorStyles.inspectorDefaultMargins
                        : GUIStyle.none);
                    try
                    {
                        GUI.changed = false;

                        using (new InspectorWindowUtils.LayoutGroupChecker())
                        {
                            EditorGUILayout.BeginVertical(editorWrapper);
                            {
                                // we have no guarantees regarding what happens in the try/catch block below,
                                // so we need to save state here and restore it afterwards,
                                // the natural thing to do would be using SavedGUIState,
                                // but it implicitly resets keyboards bindings and it breaks functionality.
                                // We have identified issues with layout so we just save that for the time being.
                                var layoutCacheState = GUILayoutUtility.current.State;
                                try
                                {
                                    var rebuildOptimizedGUIBlocks = GetRebuildOptimizedGUIBlocks(editor.target);
                                    rebuildOptimizedGUIBlocks |= editor.isInspectorDirty;
                                    float height;
                                    if (editor.GetOptimizedGUIBlock(rebuildOptimizedGUIBlocks, visible, out height))
                                    {
                                        var contentRect = GUILayoutUtility.GetRect(0, visible ? height : 0);

                                        // Layout events are ignored in the optimized code path
                                        // The exception is when we are drawing a GenericInspector, they always use the optimized path and must therefore run at least one layout calculation in it
                                        if (Event.current.type == EventType.Layout && !(editor is GenericInspector))
                                        {
                                            return;
                                        }

                                        InspectorWindowUtils.DrawAddedComponentBackground(contentRect, editor.targets);

                                        // Draw content
                                        if (visible)
                                        {
                                            GUI.changed = false;
                                            editor.OnOptimizedInspectorGUI(contentRect);
                                        }
                                    }
                                    else
                                    {
                                        InspectorWindowUtils.DrawAddedComponentBackground(contentRect, editor.targets);
                                        using (new EditorPerformanceTracker(trackerName))
                                            editor.OnInspectorGUI();
                                    }
                                }
                                catch (Exception e)
                                {
                                    if (GUIUtility.ShouldRethrowException(e))
                                    {
                                        throw;
                                    }

                                    if (!m_IgnoreOnInspectorGUIErrors)
                                    {
                                        Debug.LogException(e);
                                    }
                                }
                                finally
                                {
                                    GUILayoutUtility.current.CopyState(layoutCacheState);
                                }
                            }
                            EditorGUILayout.EndVertical();
                        }
                    }
                    finally
                    {
                        if (GUI.changed)
                        {
                            // This forces a relayout of all imguicontainers in this inspector window.
                            // fixes part of case 1148706
                            var element = inspector.GetFirstAncestorOfType <EditorElement>();
                            if (element != null)
                            {
                                EditorElement.InvalidateIMGUILayouts(element.parent);
                            }
                        }
                        EditorGUIUtility.wideMode      = originalWideMode;
                        EditorGUIUtility.hierarchyMode = originalHierarchyMode;
                    }
                }
            };

            inspector.style.overflow = Overflow.Visible;
            m_IMGUIContainer         = inspector;

            if (!(editor is GenericInspector))
            {
                inspector.AddToClassList(customInspectorUssClassName);
            }

            inspector.AddToClassList(iMGUIContainerUssClassName);

            AddToClassList(iMGUIInspectorVariantUssClassName);

            return(inspector);
        }
 static void Drawer_Environment_VolumeAnchorOverride(SerializedHDCamera p, Editor owner)
 {
     EditorGUILayout.PropertyField(p.volumeAnchorOverride, Styles.volumeAnchorOverride);
 }
Exemplo n.º 43
0
        public static bool HandleType(InvokeWrapper wrapper, T target, GUISkin skin)
        {
            object value      = null;
            bool   isNullable = false;
            Type   type       = wrapper.GetContainingType();

            if (type == typeof(Vector4) && wrapper.CanRead())
            {
                Vector4 valInField = wrapper.Get <Vector4>();
                value = EditorGUILayout.Vector4Field(MakeLabel(wrapper.Member).text, valInField);
            }
            else if (type == typeof(Vector3) && wrapper.CanRead())
            {
                Vector3 valInField = wrapper.Get <Vector3>();
                GUILayout.BeginHorizontal();
                {
                    GUILayout.Label(MakeLabel(wrapper.Member));
                    value = EditorGUILayout.Vector3Field("", valInField);
                }
                GUILayout.EndHorizontal();
            }
            else if (type == typeof(Vector2) && wrapper.CanRead())
            {
                Vector2 valInField = wrapper.Get <Vector2>();
                value = EditorGUILayout.Vector2Field(MakeLabel(wrapper.Member).text, valInField);
            }
            else if ((type == typeof(float) || type == typeof(double)) && wrapper.CanRead())
            {
                float valInField = type == typeof(double) ? Convert.ToSingle(wrapper.Get <double>()) : wrapper.Get <float>();
                FloatSliderInInspector slider = wrapper.GetAttribute <FloatSliderInInspector>();
                if (slider != null)
                {
                    value = EditorGUILayout.Slider(MakeLabel(wrapper.Member), valInField, slider.Min, slider.Max);
                }
                else
                {
                    value = EditorGUILayout.FloatField(MakeLabel(wrapper.Member), valInField, skin.textField);

                    // I can't remember why I tested this approach.
                    //GUILayout.BeginHorizontal();
                    //{
                    //  GUILayout.Label( MakeLabel( wrapper.Member ) );
                    //  value = EditorGUILayout.FloatField( valInField, skin.textField );
                    //}
                    //GUILayout.EndHorizontal();
                }
            }
            else if (type == typeof(int) && wrapper.CanRead())
            {
                int valInField = wrapper.Get <int>();
                value = EditorGUILayout.IntField(MakeLabel(wrapper.Member), valInField, skin.textField);
            }
            else if (type == typeof(bool) && wrapper.CanRead())
            {
                bool valInField = wrapper.Get <bool>();
                value = Utils.GUI.Toggle(MakeLabel(wrapper.Member), valInField, skin.button, skin.label);
            }
            else if (type == typeof(Color) && wrapper.CanRead())
            {
                Color valInField = wrapper.Get <Color>();
                value = EditorGUILayout.ColorField(MakeLabel(wrapper.Member), valInField);
            }
            else if (type == typeof(DefaultAndUserValueFloat) && wrapper.CanRead())
            {
                DefaultAndUserValueFloat valInField = wrapper.Get <DefaultAndUserValueFloat>();

                float newValue = Utils.GUI.HandleDefaultAndUserValue(wrapper.Member.Name, valInField, skin);
                if (wrapper.IsValid(newValue))
                {
                    if (!valInField.UseDefault)
                    {
                        valInField.Value = newValue;
                    }
                    value = valInField;
                }
            }
            else if (type == typeof(DefaultAndUserValueVector3) && wrapper.CanRead())
            {
                DefaultAndUserValueVector3 valInField = wrapper.Get <DefaultAndUserValueVector3>();

                Vector3 newValue = Utils.GUI.HandleDefaultAndUserValue(wrapper.Member.Name, valInField, skin);
                if (wrapper.IsValid(newValue))
                {
                    if (!valInField.UseDefault)
                    {
                        valInField.Value = newValue;
                    }
                    value = valInField;
                }
            }
            else if (type == typeof(RangeReal))
            {
                RangeReal valInField = wrapper.Get <RangeReal>();

                GUILayout.BeginHorizontal();
                {
                    GUILayout.Label(MakeLabel(wrapper.Member), skin.label);
                    valInField.Min = EditorGUILayout.FloatField("", (float)valInField.Min, skin.textField, GUILayout.MaxWidth(64));
                    valInField.Max = EditorGUILayout.FloatField("", (float)valInField.Max, skin.textField, GUILayout.MaxWidth(64));
                }
                GUILayout.EndHorizontal();

                if (valInField.Min > valInField.Max)
                {
                    valInField.Min = valInField.Max;
                }

                value = valInField;
            }
            else if (type == typeof(string) && wrapper.CanRead())
            {
                value = EditorGUILayout.TextField(MakeLabel(wrapper.Member), wrapper.Get <string>(), skin.textField);
            }
            else if (type.IsEnum && type.IsVisible && wrapper.CanRead())
            {
                Enum valInField = wrapper.Get <System.Enum>();
                value = EditorGUILayout.EnumPopup(MakeLabel(wrapper.Member), valInField, skin.button);
            }
            else if (type.IsArray && wrapper.CanRead())
            {
                Array array = wrapper.Get <Array>();
                if (array.Length == 0)
                {
                    GUILayout.BeginHorizontal();
                    {
                        GUILayout.Label(MakeLabel(wrapper.Member), skin.label);
                        GUILayout.Label(Utils.GUI.MakeLabel("Empty array", true), skin.label);
                    }
                    GUILayout.EndHorizontal();
                }
                else
                {
                    Utils.GUI.Separator();
                    using (new Utils.GUI.Indent(12))
                        foreach (object obj in wrapper.Get <Array>())
                        {
                            DrawMembersGUI(obj, target, skin);
                        }
                    Utils.GUI.Separator();
                }
            }
            else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List <>) && wrapper.CanRead())
            {
                HandleList(wrapper, target, skin);
            }
            else if (type == typeof(IFrame) && wrapper.CanRead())
            {
                IFrame frame = wrapper.Get <IFrame>();
                Utils.GUI.HandleFrame(frame, skin);
            }
            else if ((typeof(ScriptAsset).IsAssignableFrom(type) ||
                      type.BaseType == typeof(UnityEngine.Object) ||
                      type.BaseType == typeof(ScriptComponent)) && wrapper.CanRead())
            {
                bool allowSceneObject = type == typeof(GameObject) ||
                                        type.BaseType == typeof(ScriptComponent);
                UnityEngine.Object valInField = wrapper.Get <UnityEngine.Object>();
                bool recursiveEditing         = wrapper.HasAttribute <AllowRecursiveEditing>();
                bool createNewAssetButton     = false;

                if (recursiveEditing)
                {
                    var foldoutData = EditorData.Instance.GetData(target as UnityEngine.Object, wrapper.Member.Name);

                    GUILayout.BeginHorizontal();
                    {
                        var objFieldLabel = MakeLabel(wrapper.Member);
                        var buttonSize    = skin.label.CalcHeight(objFieldLabel, Screen.width);
                        UnityEngine.GUI.enabled = valInField != null;
                        foldoutData.Bool        = GUILayout.Button(Utils.GUI.MakeLabel(foldoutData.Bool ? "-" : "+"),
                                                                   skin.button,
                                                                   new GUILayoutOption[] { GUILayout.Width(20.0f), GUILayout.Height(buttonSize) }) ?
                                                  // Button clicked - toggle current value.
                                                  !foldoutData.Bool :
                                                  // If foldout were enabled but valInField has changed to null - foldout will become disabled.
                                                  valInField != null && foldoutData.Bool;
                        UnityEngine.GUI.enabled = true;
                        value = EditorGUILayout.ObjectField(objFieldLabel, valInField, type, allowSceneObject, new GUILayoutOption[] { });

                        if (typeof(ScriptAsset).IsAssignableFrom(type))
                        {
                            GUILayout.Space(4);
                            using (new GUI.ColorBlock(Color.Lerp(UnityEngine.GUI.color, Color.green, 0.1f)))
                                createNewAssetButton = GUILayout.Button(GUI.MakeLabel("New", false, "Create new asset"),
                                                                        GUILayout.Width(42),
                                                                        GUILayout.Height(buttonSize));
                        }
                    }
                    GUILayout.EndHorizontal();

                    if (GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition) && Event.current.type == EventType.MouseDown && Event.current.button == 0)
                    {
                        foldoutData.Bool = !foldoutData.Bool;
                        GUIUtility.ExitGUI();
                    }

                    if (foldoutData.Bool)
                    {
                        using (new Utils.GUI.Indent(12)) {
                            Utils.GUI.Separator();

                            GUILayout.Space(6);

                            GUILayout.Label(Utils.GUI.MakeLabel("Changes made to this object will affect all objects referencing this asset.",
                                                                Color.Lerp(Color.red, Color.white, 0.25f),
                                                                true),
                                            new GUIStyle(skin.textArea)
                            {
                                alignment = TextAnchor.MiddleCenter
                            });

                            GUILayout.Space(6);

                            // Executes OnInspectorGUI on a custom editor if it exist - otherwise Update.
                            Editor editor = null;
                            if (value is UnityEngine.Object && (editor = Editor.CreateEditor(value as UnityEngine.Object)) != null)
                            {
                                var updateMethod = typeof(BaseEditor <>).MakeGenericType(value.GetType()).GetMethod("OnRecursiveInspectorGUI", BindingFlags.Public | BindingFlags.Instance);
                                updateMethod.Invoke(editor, new object[] { target });
                            }
                            else
                            {
                                var updateMethod = typeof(BaseEditor <>).MakeGenericType(typeof(T)).GetMethod("Update", BindingFlags.Public | BindingFlags.Static);
                                updateMethod.Invoke(null, new object[] { value, target, skin });
                            }

                            Utils.GUI.Separator();
                        }
                    }
                }
                else
                {
                    value = EditorGUILayout.ObjectField(MakeLabel(wrapper.Member), valInField, type, allowSceneObject, new GUILayoutOption[] { });
                }

                if (createNewAssetButton)
                {
                    var assetName = type.Name.SplitCamelCase().ToLower();
                    var result    = EditorUtility.SaveFilePanel("Create new " + assetName, "Assets", "new " + assetName + ".asset", "asset");
                    if (result != string.Empty)
                    {
                        var info         = new System.IO.FileInfo(result);
                        var relativePath = IO.Utils.MakeRelative(result, Application.dataPath);
                        var newInstance  = ScriptAsset.Create(type);
                        newInstance.name = info.Name;
                        AssetDatabase.CreateAsset(newInstance, relativePath + (info.Extension == ".asset" ? "" : ".asset"));
                        AssetDatabase.SaveAssets();
                        AssetDatabase.Refresh();

                        value = newInstance;
                    }
                }

                isNullable = true;
            }
            else if (type.IsClass && wrapper.CanRead())
            {
            }

            return(UnityEngine.GUI.changed &&
                   (value != null || isNullable) &&
                   wrapper.ConditionalSet(value));
        }
Exemplo n.º 44
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DebugLogWindow"/> class.
        /// </summary>
        /// <param name="editor">The editor.</param>
        public DebugLogWindow(Editor editor)
            : base(editor, true, ScrollBars.None)
        {
            Title = "Debug Log";
            Icon  = IconInfo;
            OnEditorOptionsChanged(Editor.Options.Options);

            // Toolstrip
            var toolstrip = new ToolStrip(22.0f)
            {
                Parent = this,
            };

            toolstrip.AddButton("Clear", Clear).LinkTooltip("Clears all log entries");
            _clearOnPlayButton  = (ToolStripButton)toolstrip.AddButton("Clear on Play").SetAutoCheck(true).SetChecked(true).LinkTooltip("Clears all log entries on enter playmode");
            _pauseOnErrorButton = (ToolStripButton)toolstrip.AddButton("Pause on Error").SetAutoCheck(true).LinkTooltip("Performs auto pause on error");
            toolstrip.AddSeparator();
            _groupButtons[0] = (ToolStripButton)toolstrip.AddButton(editor.Icons.Error32, () => UpdateLogTypeVisibility(LogGroup.Error, _groupButtons[0].Checked)).SetAutoCheck(true).SetChecked(true).LinkTooltip("Shows/hides error messages");
            _groupButtons[1] = (ToolStripButton)toolstrip.AddButton(editor.Icons.Warning32, () => UpdateLogTypeVisibility(LogGroup.Warning, _groupButtons[1].Checked)).SetAutoCheck(true).SetChecked(true).LinkTooltip("Shows/hides warning messages");
            _groupButtons[2] = (ToolStripButton)toolstrip.AddButton(editor.Icons.Info32, () => UpdateLogTypeVisibility(LogGroup.Info, _groupButtons[2].Checked)).SetAutoCheck(true).SetChecked(true).LinkTooltip("Shows/hides info messages");
            UpdateCount();

            // Split panel
            _split = new SplitPanel(Orientation.Vertical, ScrollBars.Vertical, ScrollBars.Both)
            {
                AnchorPreset  = AnchorPresets.StretchAll,
                Offsets       = new Margin(0, 0, toolstrip.Bottom, 0),
                SplitterValue = 0.8f,
                Parent        = this
            };

            // Info detail info
            _logInfo = new Label
            {
                Parent       = _split.Panel2,
                AutoWidth    = true,
                AutoHeight   = true,
                Margin       = new Margin(4),
                Offsets      = Margin.Zero,
                AnchorPreset = AnchorPresets.StretchAll,
            };

            // Entries panel
            _entriesPanel = new VerticalPanel
            {
                AnchorPreset = AnchorPresets.HorizontalStretchTop,
                Offsets      = Margin.Zero,
                IsScrollable = true,
                Parent       = _split.Panel1,
            };

            // Cache entries icons
            IconInfo    = Editor.Icons.Info32;
            IconWarning = Editor.Icons.Warning32;
            IconError   = Editor.Icons.Error32;

            // Bind events
            Editor.Options.OptionsChanged            += OnEditorOptionsChanged;
            Debug.Logger.LogHandler.SendLog          += LogHandlerOnSendLog;
            Debug.Logger.LogHandler.SendExceptionLog += LogHandlerOnSendExceptionLog;
        }
Exemplo n.º 45
0
        public static void Scan(GameObject meshObject, float voxelSize)
        {
            Transform meshTransform = meshObject.transform;

            Mesh       mesh = null;
            MeshFilter mF   = meshObject.GetComponent <MeshFilter>();

            if (mF != null)
            {
                mesh = mF.sharedMesh;
            }
            else
            {
                SkinnedMeshRenderer sMR = meshObject.GetComponent <SkinnedMeshRenderer>();
                if (sMR != null)
                {
                    mesh = sMR.sharedMesh;
                }
            }
            if (mesh == null)
            {
                return;
            }

            // bool addedCollider = false;
            GameObject mcContainer = new GameObject("PVMCC");

            mcContainer.transform.SetParent(meshObject.transform, false);
            MeshCollider mc = mcContainer.AddComponent <MeshCollider>();

            mc.sharedMesh = mesh;

            GameObject mcContainerRev = new GameObject("PVMCCR");

            mcContainerRev.transform.SetParent(meshObject.transform, false);
            Mesh reverseMesh = (Mesh)UnityEngine.Object.Instantiate(mesh);

            reverseMesh.triangles = mesh.triangles.Reverse().ToArray();
            MeshCollider mcr = mcContainerRev.AddComponent <MeshCollider>();

            mcr.sharedMesh = reverseMesh;

            Vector3[] vertices = mesh.vertices;
            if (vertices.Length <= 0)
            {
                return;
            }

            Texture2D renderTex     = null;
            Color     materialColor = Color.white;
            Renderer  rend          = meshObject.GetComponent <Renderer>();

            if (rend != null && rend.sharedMaterial != null && rend.sharedMaterial.mainTexture != null)
            {
                renderTex = (Texture2D)rend.sharedMaterial.mainTexture;
                try
                {
                    renderTex.GetPixel(0, 0);
                }
                catch (Exception)
                {
                    string          path = AssetDatabase.GetAssetPath(rend.sharedMaterial.mainTexture);
                    TextureImporter ti   = (TextureImporter)TextureImporter.GetAtPath(path);
                    ti.isReadable = true;
                    AssetDatabase.ImportAsset(path);
                    ti.isReadable = false;

                    try
                    {
                        renderTex.GetPixel(0, 0);
                    }
                    catch (Exception)
                    {
                        renderTex = null;
                    }
                }
            }
            else if (rend != null && rend.sharedMaterial != null)
            {
                materialColor = rend.sharedMaterial.color;
            }

            Vector3 min, max;

            min = max = meshTransform.TransformPoint(vertices[0]);
            for (int i = 1; i < vertices.Length; i++)
            {
                Vector3 V = meshTransform.TransformPoint(vertices[i]);
                for (int n = 0; n < 3; n++)
                {
                    if (V[n] > max[n])
                    {
                        max[n] = V[n];
                    }
                    if (V[n] < min[n])
                    {
                        min[n] = V[n];
                    }
                }

                vertices[i] = V;
            }
            vertices[0] = meshTransform.TransformPoint(vertices[0]);
            Bounds bounds = new Bounds();

            bounds.SetMinMax(min, max);

            if (bounds.size.x <= 0f || bounds.size.y <= 0f || bounds.size.z <= 0f)
            {
                return;
            }

            var newObject = Editor.Instantiate(EditorUtility.VoxelVolumePrefab, Vector3.zero, Quaternion.identity) as GameObject;

            newObject.name = meshObject.name + " (Voxels)";
            newObject.GetComponent <Volume>().Material = EditorUtility.PicaVoxelDiffuseMaterial;
            newObject.GetComponent <Volume>().GenerateBasic(FillMode.None);
            Volume voxelVolume = newObject.GetComponent <Volume>();

            voxelVolume.XSize            = (int)(bounds.size.x / voxelSize) + 1;
            voxelVolume.YSize            = (int)(bounds.size.y / voxelSize) + 1;
            voxelVolume.ZSize            = (int)(bounds.size.z / voxelSize) + 1;
            voxelVolume.Frames[0].XSize  = voxelVolume.XSize;
            voxelVolume.Frames[0].YSize  = voxelVolume.YSize;
            voxelVolume.Frames[0].ZSize  = voxelVolume.ZSize;
            voxelVolume.Frames[0].Voxels = new Voxel[voxelVolume.XSize * voxelVolume.YSize * voxelVolume.ZSize];
            for (int i = 0; i < voxelVolume.Frames[0].Voxels.Length; i++)
            {
                voxelVolume.Frames[0].Voxels[i].Value = 128;
            }
            voxelVolume.VoxelSize = voxelSize;


            Vector3[] testDirs = { Vector3.forward, Vector3.back, Vector3.left, Vector3.right, Vector3.up, Vector3.down };

            float stepScale = 0.5f;
            int   size      = (int)((bounds.size.x) / (voxelSize * stepScale)) * (int)((bounds.size.y) / (voxelSize * stepScale)) *
                              (int)((bounds.size.z) / (voxelSize * stepScale));
            int progress = 0;

            // Outside
            for (float x = bounds.min.x; x < bounds.max.x + voxelSize; x += voxelSize * stepScale)
            {
                for (float y = bounds.min.y; y < bounds.max.y + voxelSize; y += voxelSize * stepScale)
                {
                    for (float z = bounds.min.z; z < bounds.max.z + voxelSize; z += voxelSize * stepScale)
                    {
                        Vector3 test = new Vector3(x, y, z);

                        for (int d = 0; d < 6; d++)
                        {
                            Vector3 hit;
                            Color   col;
                            if (TestRay(mc, mcContainer, renderTex, materialColor, mesh, test, testDirs[d].normalized, out hit, out col))
                            {
                                int vX = (voxelVolume.XSize - 1) - (int)((bounds.max.x - hit.x) / voxelSize);
                                int vY = (voxelVolume.YSize - 1) - (int)((bounds.max.y - hit.y) / voxelSize);
                                int vZ = (voxelVolume.ZSize - 1) - (int)((bounds.max.z - hit.z) / voxelSize);
                                if (!(vX < voxelVolume.XSize && vY < voxelVolume.YSize && vZ < voxelVolume.ZSize))
                                {
                                    continue;
                                }
                                voxelVolume.Frames[0].Voxels[vX + voxelVolume.XSize * (vY + voxelVolume.YSize * vZ)] = new Voxel()
                                {
                                    State = VoxelState.Active, Color = col, Value = 128
                                };
                            }
                        }

                        progress++;
                    }
                }


                if (UnityEditor.EditorUtility.DisplayCancelableProgressBar("Scanning Mesh", "Scanning Outside", (1f / (float)size) * (float)progress))
                {
                    UnityEditor.EditorUtility.ClearProgressBar();
                    GameObject.DestroyImmediate(voxelVolume.gameObject);
                    UnityEngine.Object.DestroyImmediate(mcContainer);
                    UnityEngine.Object.DestroyImmediate(mcContainerRev);
                    return;
                }
            }

            progress = 0;

            //Inside
            for (float x = bounds.min.x; x < bounds.max.x + voxelSize; x += voxelSize * stepScale)
            {
                for (float y = bounds.min.y; y < bounds.max.y + voxelSize; y += voxelSize * stepScale)
                {
                    for (float z = bounds.min.z; z < bounds.max.z + voxelSize; z += voxelSize * stepScale)
                    {
                        Vector3 test = new Vector3(x, y, z);

                        Vector3 hit;
                        Color   col;

                        float closestHit = Mathf.Infinity;
                        Color closestCol = Color.white;

                        int hitCount = 0;
                        for (int d = 0; d < 6; d++)
                        {
                            if (TestRay(mcr, mcContainerRev, renderTex, materialColor, reverseMesh, test, testDirs[d].normalized, out hit, out col))
                            {
                                if (Vector3.Distance(hit, test) < closestHit)
                                {
                                    closestHit = Vector3.Distance(hit, test);
                                    closestCol = col;
                                }
                                hitCount++;
                            }
                        }

                        if (hitCount == 6)
                        {
                            int vX = (voxelVolume.XSize - 1) - (int)((bounds.max.x - test.x) / voxelSize);
                            int vY = (voxelVolume.YSize - 1) - (int)((bounds.max.y - test.y) / voxelSize);
                            int vZ = (voxelVolume.ZSize - 1) - (int)((bounds.max.z - test.z) / voxelSize);
                            if (!(vX < voxelVolume.XSize && vY < voxelVolume.YSize && vZ < voxelVolume.ZSize))
                            {
                                continue;
                            }
                            voxelVolume.Frames[0].Voxels[vX + voxelVolume.XSize * (vY + voxelVolume.YSize * vZ)] = new Voxel()
                            {
                                State = VoxelState.Active, Color = closestCol, Value = 128
                            };
                        }

                        progress++;
                    }
                }

                if (UnityEditor.EditorUtility.DisplayCancelableProgressBar("Scanning Mesh", "Attempting to fill inside", (1f / (float)size) * (float)progress))
                {
                    UnityEditor.EditorUtility.ClearProgressBar();
                    GameObject.DestroyImmediate(voxelVolume.gameObject);
                    UnityEngine.Object.DestroyImmediate(mcContainer);
                    UnityEngine.Object.DestroyImmediate(mcContainerRev);
                    return;
                }
            }

            UnityEditor.EditorUtility.ClearProgressBar();



            voxelVolume.CreateChunks();
            voxelVolume.SaveForSerialize();
            voxelVolume.Frames[0].OnAfterDeserialize();
            voxelVolume.transform.position = meshObject.transform.position;

            voxelVolume.Pivot = (new Vector3(voxelVolume.XSize, voxelVolume.YSize, voxelVolume.ZSize) * voxelVolume.VoxelSize) / 2f;
            voxelVolume.UpdatePivot();

            UnityEngine.Object.DestroyImmediate(mcContainer);
            UnityEngine.Object.DestroyImmediate(mcContainerRev);

            voxelVolume.UpdateAllChunks();
        }
Exemplo n.º 46
0
        public MainPage()
        {
            InitializeComponent();

            CurvedStackLayout curvedStackLayout = new CurvedStackLayout()
            {
                BackgroundColor = Color.White
                , Padding       = 15, Margin = 15
            };



            RoundedRectangle rr = new RoundedRectangle {
                WidthRequest = 100, HeightRequest = 50, Radius = 1, Color = Color.BlueViolet
            };



            curvedStackLayout.Children.Add(new CustomFontLabel
            {
                FontSize = 25,
                FontName = "agencyr",
                Text     = "This is a label with a custom Font"
            });


            CustomDatePicker customDatePicker = new CustomDatePicker {
                Text = "Pick a day"
            };


            CustomTimePicker ctp = new CustomTimePicker(DateTime.Now)
            {
                Text = "Pick a time"
            };



            Editor editor = new Editor
            {
                Text          = "regular editor",
                HeightRequest = 100,
                WidthRequest  = 200
            };


            CustomEditor customEditor = new CustomEditor
            {
                HeightRequest     = 200,
                HorizontalOptions = LayoutOptions.CenterAndExpand,
                FontSize          = 25,
                FontName          = "agencyr",
                Text = "This is a custom editor with a custom Font"
            };

            //   curvedStackLayout.Children.Add(editor);

            curvedStackLayout.Children.Add(customEditor);
            curvedStackLayout.Children.Add(new Circle
            {
                Radius            = 20,
                Color             = Color.Black,
                HeightRequest     = 100,
                HorizontalOptions = LayoutOptions.CenterAndExpand
            });



            curvedStackLayout.Children.Add(rr);
            curvedStackLayout.Children.Add(customDatePicker);
            curvedStackLayout.Children.Add(ctp);

            curvedStackLayout.Children.Add(new Calendar {
                HorizontalOptions = LayoutOptions.FillAndExpand, HeightRequest = 200
            });


            Label label = new Label {
                Text = "This is an image from a database"
            };

            curvedStackLayout.Children.Add(label);
            ResourceImage ri = new ResourceImage
            {
                SourceType    = ResourceImage.SourceTypes.Database,
                ResourceName  = "2",
                HeightRequest = 300,
                WidthRequest  = 300
            };

            curvedStackLayout.Children.Add(ri);

            scrollyScroll.Content = curvedStackLayout;
        }
Exemplo n.º 47
0
 /// <inheritdoc />
 public override EditorWindow Open(Editor editor, ContentItem item)
 {
     return(new AudioClipWindow(editor, (AssetItem)item));
 }
Exemplo n.º 48
0
        public override void OnInspectorGUI()
        {
            serializedObject.UpdateIfRequiredOrScript();

            GUI.enabled = cloth.Initialized;
            EditorGUI.BeginChangeCheck();
            editMode = GUILayout.Toggle(editMode, new GUIContent("Edit particles", Resources.Load <Texture2D>("EditParticles")), "LargeButton");
            if (EditorGUI.EndChangeCheck())
            {
                SceneView.RepaintAll();
            }
            GUI.enabled = true;

            EditorGUILayout.LabelField("Status: " + (cloth.Initialized ? "Initialized":"Not initialized"));

            GUI.enabled = (cloth.SharedTopology != null);
            if (GUILayout.Button("Initialize"))
            {
                if (!cloth.Initialized)
                {
                    EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
                    CoroutineJob job = new CoroutineJob();
                    routine = job.Start(cloth.GeneratePhysicRepresentationForMesh());
                    EditorCoroutine.ShowCoroutineProgressBar("Generating physical representation...", ref routine);
                    EditorGUIUtility.ExitGUI();
                }
                else
                {
                    if (EditorUtility.DisplayDialog("Actor initialization", "Are you sure you want to re-initialize this actor?", "Ok", "Cancel"))
                    {
                        EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
                        CoroutineJob job = new CoroutineJob();
                        routine = job.Start(cloth.GeneratePhysicRepresentationForMesh());
                        EditorCoroutine.ShowCoroutineProgressBar("Generating physical representation...", ref routine);
                        EditorGUIUtility.ExitGUI();
                    }
                }
            }
            GUI.enabled = true;

            if (cloth.SharedTopology == null)
            {
                EditorGUILayout.HelpBox("No ObiMeshTopology asset present.", MessageType.Info);
            }

            GUI.enabled = cloth.Initialized;
            if (GUILayout.Button("Set Rest State"))
            {
                Undo.RecordObject(cloth, "Set rest state");
                cloth.PullDataFromSolver(ParticleData.POSITIONS | ParticleData.VELOCITIES);
            }
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Optimize"))
            {
                Undo.RecordObject(cloth, "Optimize");
                cloth.Optimize();
            }
            if (GUILayout.Button("Unoptimize"))
            {
                Undo.RecordObject(cloth, "Unoptimize");
                cloth.Unoptimize();
            }
            GUILayout.EndHorizontal();

            GUI.enabled = true;

            Editor.DrawPropertiesExcluding(serializedObject, "m_Script");

            // Apply changes to the serializedProperty
            if (GUI.changed)
            {
                serializedObject.ApplyModifiedProperties();
            }
        }
Exemplo n.º 49
0
 private void WinEventHooker_EvTextChanged(object sender, WinEventHooker.WinEventHookEventArgs e)
 {
     Editor.ClearCachedText();
 }
Exemplo n.º 50
0
 public FindIslandPolygonHandler(Editor editor)
     : base(editor)
 {
 }
        static void Drawer_SectionPrimarySettings(HDRenderPipelineUI s, SerializedHDRenderPipelineAsset d, Editor o)
        {
            EditorGUILayout.PropertyField(d.renderPipelineResources, renderPipelineResourcesContent);

            HDRenderPipelineAsset hdrpAsset = d.serializedObject.targetObject as HDRenderPipelineAsset;

            hdrpAsset.renderPipelineEditorResources = EditorGUILayout.ObjectField(renderPipelineEditorResourcesContent, hdrpAsset.renderPipelineEditorResources, typeof(HDRenderPipelineEditorResources), allowSceneObjects: false) as HDRenderPipelineEditorResources;

            EditorGUILayout.PropertyField(d.diffusionProfileSettings, diffusionProfileSettingsContent);
            // EditorGUILayout.PropertyField(d.allowShaderVariantStripping, enableShaderVariantStrippingContent);
            EditorGUILayout.PropertyField(d.enableSRPBatcher, enableSRPBatcher);
            EditorGUILayout.PropertyField(d.enableVariantStrippingLog, enableVariantStrippingLog);
        }
Exemplo n.º 52
0
 /// <inheritdoc />
 public override bool Import()
 {
     // Use engine backend
     return(Editor.Import(SourceUrl, ResultUrl));
 }
        static public void Init(HDRenderPipelineUI s, SerializedHDRenderPipelineAsset d, Editor o)
        {
            s.isSectionExpandedCamera.value = false;
            s.isSectionExpandedBakedOrCustomReflection.value = false;
            s.isSectionExpandedRealtimeReflection.value      = false;
            switch (selectedFrameSettings)
            {
            case SelectedFrameSettings.Camera:
                s.isSectionExpandedCamera.value = true;
                break;

            case SelectedFrameSettings.BakedOrCustomReflection:
                s.isSectionExpandedBakedOrCustomReflection.value = true;
                break;

            case SelectedFrameSettings.RealtimeReflection:
                s.isSectionExpandedRealtimeReflection.value = true;
                break;
            }
        }
Exemplo n.º 54
0
 public SelectGridAction(Editor context, int row, int col, EditorState previousState) : base(context)
 {
     _row = row;
     _col = col;
     _previousState = previousState;
 }
Exemplo n.º 55
0
Arquivo: xRef2.cs Projeto: 15831944/EM
        getNestedEntityAndHighlight(Point3d pnt3d, BlockReference br, out FullSubentityPath path, out bool isClosed)
        {
            Entity ent = null;

            isClosed = false;
            path     = new FullSubentityPath();

            Editor ed = BaseObjs._editor;

            PromptNestedEntityOptions pneo = new PromptNestedEntityOptions("");

            pneo.NonInteractivePickPoint    = pnt3d;
            pneo.UseNonInteractivePickPoint = true;
            PromptNestedEntityResult pner = ed.GetNestedEntity(pneo);

            try
            {
                using (Transaction tr = BaseObjs.startTransactionDb())
                {
                    if (pner.Status == PromptStatus.OK)
                    {
                        ObjectId[] idsContainers = pner.GetContainers();
                        ObjectId   idSel         = pner.ObjectId;
                        int        len           = idsContainers.Length;

                        ObjectId[] idsRev = new ObjectId[len + 1];
                        //Reverse the "containers" list
                        for (int i = 0; i < len; i++)
                        {
                            ObjectId id = (ObjectId)idsContainers.GetValue(len - i - 1);
                            idsRev.SetValue(id, i);
                        }
                        //Now add the selected entity to the end of the array
                        idsRev.SetValue(idSel, len);

                        //Retrieve the sub-entity path for this entity
                        SubentityId idSubEnt = new SubentityId(SubentityType.Null, (IntPtr)0);
                        path = new FullSubentityPath(idsRev, idSubEnt);

                        ObjectId idX = (ObjectId)idsRev.GetValue(0);
                        ent = (Entity)tr.GetObject(idX, OpenMode.ForRead);

                        DBObject obj = idSel.GetObject(OpenMode.ForRead);

                        ObjectId idOwner   = ObjectId.Null;
                        DBObject objParent = null;

                        if (obj is PolylineVertex3d)
                        {
                            idOwner   = obj.OwnerId;
                            objParent = (Polyline3d)idOwner.GetObject(OpenMode.ForRead);
                            Polyline3d poly3d = (Polyline3d)obj;
                            poly3d.Highlight(path, false);
                            isClosed = poly3d.Closed;
                        }
                        else if (obj is Vertex2d)
                        {
                            idOwner   = obj.OwnerId;
                            objParent = (Polyline)idOwner.GetObject(OpenMode.ForRead);
                            Polyline poly = (Polyline)obj;
                            poly.Highlight(path, false);
                            isClosed = poly.Closed;
                        }
                        else if (obj is Polyline3d)
                        {
                            objParent = obj;
                            Polyline3d poly3d = (Polyline3d)obj;
                            poly3d.Highlight(path, false);
                            isClosed = poly3d.Closed;
                        }
                        else if (obj is Polyline)
                        {
                            objParent = obj;
                            Polyline poly = (Polyline)obj;
                            poly.Highlight(path, false);
                            isClosed = poly.Closed;
                        }
                        else if (obj is Arc)
                        {
                            objParent = obj;
                            Arc arc = (Arc)obj;
                            arc.Highlight(path, false);
                            isClosed = false;
                        }
                        else if (obj is MText || obj is DBText)
                        {
                            return(null);
                        }

                        ent = (Entity)objParent;
                    }
                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                BaseObjs.writeDebug(ex.Message + " xRef2.cs: line: 108");
            }
            return(ent);
        }
Exemplo n.º 56
0
 public static List <BasicTableItem> Build(Editor editor)
 {
     return(new List <BasicTableItem>
     {
         new BasicTableItem
         {
             Name = Localization.Editor_BasicTable_Reputation_ParagonPoints,
             Control = new NumericUpDown
             {
                 Minimum = int.MinValue,
                 Maximum = int.MaxValue,
                 Increment = 1,
                 Dock = DockStyle.Fill
             },
             Binding =
                 new Binding("Value",
                             editor._rootSaveFileBindingSource,
                             "Plot.Helpers.ParagonPoints",
                             true,
                             DataSourceUpdateMode.OnPropertyChanged)
         },
         new BasicTableItem
         {
             Name = Localization.Editor_BasicTable_Reputation_RenegadePoints,
             Control = new NumericUpDown
             {
                 Minimum = int.MinValue,
                 Maximum = int.MaxValue,
                 Increment = 1,
                 Dock = DockStyle.Fill
             },
             Binding =
                 new Binding("Value",
                             editor._rootSaveFileBindingSource,
                             "Plot.Helpers.RenegadePoints",
                             true,
                             DataSourceUpdateMode.OnPropertyChanged)
         },
         new BasicTableItem
         {
             Name = Localization.Editor_BasicTable_Reputation_Reputation,
             Control = new NumericUpDown
             {
                 Minimum = int.MinValue,
                 Maximum = int.MaxValue,
                 Increment = 1,
                 Dock = DockStyle.Fill
             },
             Binding =
                 new Binding("Value",
                             editor._rootSaveFileBindingSource,
                             "Plot.Helpers.Reputation",
                             true,
                             DataSourceUpdateMode.OnPropertyChanged)
         },
         new BasicTableItem
         {
             Name = Localization.Editor_BasicTable_Reputation_ReputationPoints,
             Control = new NumericUpDown
             {
                 Minimum = int.MinValue,
                 Maximum = int.MaxValue,
                 Increment = 1,
                 Dock = DockStyle.Fill
             },
             Binding =
                 new Binding("Value",
                             editor._rootSaveFileBindingSource,
                             "Plot.Helpers.ReputationPoints",
                             true,
                             DataSourceUpdateMode.OnPropertyChanged)
         }
     });
 }
Exemplo n.º 57
0
        static void Drawer_FieldShadowSize(ShadowInitParametersUI s, SerializedShadowInitParameters d, Editor o)
        {
            EditorGUILayout.LabelField(_.GetContent("Shadow"), EditorStyles.boldLabel);

            ++EditorGUI.indentLevel;
            EditorGUILayout.LabelField(_.GetContent("Shadow Atlas"), EditorStyles.boldLabel);
            ++EditorGUI.indentLevel;
            EditorGUILayout.PropertyField(d.shadowAtlasWidth, _.GetContent("Atlas Width"));
            EditorGUILayout.PropertyField(d.shadowAtlasHeight, _.GetContent("Atlas Height"));
//forest-begin: 16-bit shadows option
            EditorGUILayout.PropertyField(d.shadowMap16Bit, _.GetContent("16-bit Shadow Maps"));
//forest-end:
            --EditorGUI.indentLevel;

            EditorGUILayout.Space();

            EditorGUILayout.LabelField(_.GetContent("Shadow Map Budget"), EditorStyles.boldLabel);
            ++EditorGUI.indentLevel;
            EditorGUILayout.PropertyField(d.maxPointLightShadows, _.GetContent("Max Point Light Shadows"));
            EditorGUILayout.PropertyField(d.maxSpotLightShadows, _.GetContent("Max Spot Light Shadows"));
            EditorGUILayout.PropertyField(d.maxDirectionalLightShadows, _.GetContent("Max Directional Light Shadows"));
            --EditorGUI.indentLevel;

            // Clamp negative values
            d.shadowAtlasHeight.intValue          = Mathf.Max(0, d.shadowAtlasHeight.intValue);
            d.shadowAtlasWidth.intValue           = Mathf.Max(0, d.shadowAtlasWidth.intValue);
            d.maxPointLightShadows.intValue       = Mathf.Max(0, d.maxPointLightShadows.intValue);
            d.maxSpotLightShadows.intValue        = Mathf.Max(0, d.maxSpotLightShadows.intValue);
            d.maxDirectionalLightShadows.intValue = Mathf.Max(0, d.maxDirectionalLightShadows.intValue);

            --EditorGUI.indentLevel;
        }
 static void Drawer_Environment_ProbeLayerMask(SerializedHDCamera p, Editor owner)
 {
     EditorGUILayout.PropertyField(p.probeLayerMask, Styles.probeLayerMask);
 }
Exemplo n.º 59
0
        /// <summary>
        /// Adds default inspector property fields under a container VisualElement
        /// </summary>
        /// <param name="container">The parent VisualElement</param>
        /// <param name="serializedObject">The SerializedObject to inspect</param>
        /// <param name="editor">The editor currently used</param>
        public static void FillDefaultInspector(VisualElement container, SerializedObject serializedObject, Editor editor)
        {
            if (serializedObject == null)
            {
                return;
            }

            bool isPartOfPrefabInstance = editor != null && GenericInspector.IsAnyMonoBehaviourTargetPartOfPrefabInstance(editor);

            SerializedProperty property = serializedObject.GetIterator();

            if (property.NextVisible(true)) // Expand first child.
            {
                do
                {
                    var field = new PropertyField(property);
                    field.name = "PropertyField:" + property.propertyPath;

                    if (property.propertyPath == "m_Script")
                    {
                        if ((serializedObject.targetObject != null) || isPartOfPrefabInstance)
                        {
                            field.SetEnabled(false);
                        }
                    }

                    container.Add(field);
                }while (property.NextVisible(false));
            }

            if (serializedObject.targetObject == null)
            {
                AddMissingScriptLabel(container, serializedObject, isPartOfPrefabInstance);
            }
        }
Exemplo n.º 60
0
        public PageDConfirmationCS()
        {
            Title = "Ts Item";

            var datePicker = new DatePicker();

            datePicker.SetBinding(DatePicker.DateProperty, "Date");

            var workedhEntry = new Entry();

            workedhEntry.SetBinding(Entry.TextProperty, "Hours");

            var notesEditor = new Editor();

            notesEditor.SetBinding(Editor.TextProperty, "Description");

            var conSwitch = new Switch();

            conSwitch.SetBinding(Switch.IsToggledProperty, "ConfirmedStatus");

            var refSwitch = new Switch();

            refSwitch.SetBinding(Switch.IsToggledProperty, "RefusedStatus");

            var saveButton = new Button {
                Text = "Save"
            };

            saveButton.Clicked += async(sender, e) =>
            {
                var tsItem = (TsItems)BindingContext;
                await App.Database.SaveItemAsync(tsItem);

                await Navigation.PopAsync();
            };

            var deleteButton = new Button {
                Text = "Delete"
            };

            deleteButton.Clicked += async(sender, e) =>
            {
                var tsItem = (TsItems)BindingContext;
                await App.Database.DeleteItemAsync(tsItem);

                await Navigation.PopAsync();
            };

            var cancelButton = new Button {
                Text = "Cancel"
            };

            cancelButton.Clicked += async(sender, e) =>
            {
                await Navigation.PopAsync();
            };

            var speakButton = new Button {
                Text = "Speak"
            };

            speakButton.Clicked += (sender, e) =>
            {
                var tsItem = (TsItems)BindingContext;
                DependencyService.Get <ITextToSpeech>().Speak(tsItem.Hours + " " + tsItem.Description);
            };

            Content = new StackLayout
            {
                Margin          = new Thickness(20),
                VerticalOptions = LayoutOptions.StartAndExpand,
                Children        =
                {
                    new Label {
                        Text = "Date"
                    },

                    new Label {
                        Text = "Hours"
                    },
                    workedhEntry,
                    new Label {
                        Text = "Description"
                    },
                    notesEditor,
                    new StackLayout(),
                    new Label {
                        Text = "Confirm"
                    },
                    conSwitch,
                    new Label {
                        Text = "Refuse"
                    },
                    refSwitch,
                    saveButton,
                    deleteButton,
                    cancelButton,
                    speakButton
                }
            };
        }