Exemplo n.º 1
0
        bool GetEnabledForSelectedPanel()
        {
            //!!!!slowly

            bool enable = false;

            if (SelectedPanel != null && SelectedPanel.selectedObjects != null && SelectedPanel.selectedObjects.Length != 0)
            {
                var objs = SelectedPanel.selectedObjects;

                enable = true;

                foreach (object obj in objs)
                {
                    Component c = obj as Component;
                    if (c != null)
                    {
                        if (c.ParentRoot.HierarchyController != null)
                        {
                            var ins = c.ParentRoot.HierarchyController.CreatedByResource;
                            if (ins != null)
                            {
                                if (EditorAPI.GetDocumentByResource(ins) == null)
                                {
                                    enable = false;
                                }
                            }
                        }
                        if (c.EditorReadOnlyInHierarchy)
                        {
                            enable = false;
                        }
                    }
                }
            }

            return(enable);
        }
Exemplo n.º 2
0
        internal bool?ShowDialogAndSaveDocument(DockWindow window)
        {
            var documentWindow = window as DocumentWindow;

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

            // If the page is dirty then we need to ask if it should be saved
            if (documentWindow.IsMainWindowInWorkspace && !documentWindow.IsDocumentSaved())
            {
                var text = EditorLocalization.Translate("General", "Save changes to the following files?") + "\n";
                text += "\n" + documentWindow.Document.Name;

                switch (EditorMessageBox.ShowQuestion(text, MessageBoxButtons.YesNoCancel))
                {
                case DialogResult.Cancel:

                    //!!!!тут?
                    EditorAPI.SetRestartApplication(false);

                    return(null);

                case DialogResult.Yes:
                    //!!!!check error, return null
                    documentWindow.SaveDocument();
                    return(true);

                case DialogResult.No:
                    return(false);
                }
            }

            return(false);
        }
Exemplo n.º 3
0
 void QATButtonsUpdateProperties(ref bool needRepaint)
 {
     foreach (KryptonRibbonQATButton button in kryptonRibbon.QATButtons)
     {
         if (button.Visible)
         {
             var action = button.Tag as EditorAction;
             if (action != null)
             {
                 var state = EditorAPI.EditorActionGetState(EditorAction.HolderEnum.RibbonQAT, action);
                 if (button.Enabled != state.Enabled)
                 {
                     button.Enabled = state.Enabled;
                     needRepaint    = true;
                 }
                 if (button.Checked != state.Checked)
                 {
                     button.Checked = state.Checked;
                     needRepaint    = true;
                 }
             }
         }
     }
 }
Exemplo n.º 4
0
        void SelectCreateResource()
        {
            var initData = new NewObjectWindow.CreationDataClass();

            EditorAPI.OpenNewObjectWindow(initData);
        }
Exemplo n.º 5
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (!IsHandleCreated || WinFormsUtility.IsDesignerHosted(this) || EditorAPI.ClosingApplication)
            {
                return;
            }
            if (!loaded)
            {
                return;
            }

            //!!!!!slowly?

            //!!!!!!

            //if( needSelectResource != null )
            //{
            //	var selectResource = needSelectResource;
            //	needSelectResource = null;
            //	//ContentObjectSettings.Instance.SelectResource( selectResource );
            //}

            //UpdatePagesVisibility();

            //!!!!!
            //!!!!где еще вызывать?
            if (EngineApp.Instance != null)
            {
                EngineApp.DoTick();
            }

            if (EngineApp.GetSystemTime() - lastSlowUpdatingTime > 0.2 && !firstTick)
            {
                QATButtonsUpdate();
                RibbonUpdate();
                UpdateText();

                lastSlowUpdatingTime = EngineApp.GetSystemTime();
            }

            //save editor settings
            EditorSettingsSerialization.Dump();

            ScreenNotifications.Update();

            if (!needClose)
            {
                EditorAPI.SelectedDocumentWindowChangedUpdate();
            }

            if (!needClose)
            {
                foreach (var document in EditorAPI.Documents)
                {
                    document.EditorUpdateWhenDocumentModified_Tick();
                }
            }

            //if( !needClose )
            //	PreviewImagesManager.Update();

            ////!!!!temp
            //CheckRestartApplicationToApplyChanged();

            if (!needClose)
            {
                UpdateSoundSystem();
            }

            //save editor settings
            if (!needClose)
            {
                KryptonAutoHiddenSlidePanel.Animate = ProjectSettings.Get.AnimateWindowsAutoHiding;
            }

            //if( !needClose )
            //	ScriptEditorEngine.Instance.UpdateSettings();

            UpdateVisibilityOfFloatingWindows();

            if (needClose)
            {
                needClose = false;
                Close();
            }

            //open file at startup
            if (firstTick && !needClose)
            {
                var realFileName = EditorSettingsSerialization.OpenFileAtStartup;
                EditorSettingsSerialization.OpenFileAtStartup = "";

                if (File.Exists(realFileName))
                {
                    //select new file in Resources window
                    EditorAPI.SelectFilesOrDirectoriesInMainResourcesWindow(new string[] { realFileName });

                    //open file
                    EditorAPI.OpenFileAsDocument(realFileName, true, true);
                }
            }

            if (firstTick)
            {
                firstTick = false;

                if (SplashForm.Instance != null)
                {
                    SplashForm.Instance.AllowClose = true;
                }

                // hide cover show ribbon.
                kryptonRibbon.Visible = true;

                if (coverControl != null)
                {
                    Controls.Remove(coverControl);
                }
                //coverControl.Visible = false;

                Invalidate(true);

                if (EditorSettingsSerialization.ShowTipsAsStartup)
                {
                    EditorAPI.ShowTips();
                }
            }

            if (unlockFormUpdateInTimer.HasValue && (DateTime.Now - unlockFormUpdateInTimer.Value).TotalSeconds > 0)
            {
                KryptonWinFormsUtility.LockFormUpdate(null);
                unlockFormUpdateInTimer = null;
            }

            if (!needClose)
            {
                EngineToolTipManager.Update();
            }

            canSaveConfig = true;
        }
Exemplo n.º 6
0
        public static void Print(string text)
        {
            var window = EditorAPI.FindWindow <OutputWindow>();

            window?.PrintInstance(text);
        }
Exemplo n.º 7
0
        void AddHandlerToSharpClass(Component subscribeTo, string csharpFileName, string className)
        {
            GetMethodInfo(subscribeTo, out var parameters, out var parametersSignature);

            //get unique method name
            string methodName;
            string methodSignature;
            {
                var methodNameNotUnique = subscribeTo.Name.Replace(" ", "") + "_" + _event.Name;

                for (int n = 1; ; n++)
                {
                    methodName = methodNameNotUnique;
                    if (n != 1)
                    {
                        methodName += n.ToString();
                    }
                    methodSignature = $"method:{methodName}({parametersSignature})";

                    if (subscribeTo.ParentRoot.MetadataGetMemberBySignature(methodSignature) == null)
                    {
                        break;
                    }
                }
            }

            var newObjects = new List <Component>();

            //create handler
            var handler = subscribeTo.CreateComponent <Component_EventHandler>(enabled: false);

            handler.Name  = handler.BaseType.GetUserFriendlyNameForInstance() + " " + _event.Name;
            handler.Event = ReferenceUtility.MakeReference <ReferenceValueType_Event>(null,
                                                                                      ReferenceUtility.CalculateThisReference(handler, subscribeTo, _event.Signature));
            handler.HandlerMethod = ReferenceUtility.MakeReference <ReferenceValueType_Method>(null,
                                                                                               ReferenceUtility.CalculateThisReference(handler, subscribeTo.ParentRoot, methodSignature));
            handler.Enabled = true;
            newObjects.Add(handler);

            //undo for handler
            var document = Owner.DocumentWindow.Document;
            var action   = new UndoActionComponentCreateDelete(document, newObjects, true);

            document.UndoSystem.CommitAction(action);
            document.Modified = true;

            Owner.DocumentWindow.SelectObjects(newObjects.ToArray());

            //open cs file and add method
            var documentWindow = EditorAPI.OpenFileAsDocument(csharpFileName, true, true) as CSharpDocumentWindow;

            if (documentWindow != null)
            {
                if (!documentWindow.ScriptEditorControl.AddMethod(methodName, parameters, out var error))
                {
                    Log.Warning("Unable to add a code of the method. " + error);
                    //!!!!
                }
            }
            else
            {
                Log.Warning("Unable to add a code of the method. Document file is not opened.");
                //!!!!
            }
        }
Exemplo n.º 8
0
        public override void Register()
        {
            //Add Constraint
            {
                var a = new EditorAction();
                //!!!!"New Constraint"?
                a.Name = "Add Constraint";
                //a.imageSmall = Properties.Resources.Save_16;
                //a.imageBig = Properties.Resources.Save_32;

                //!!!!выключить где-то?
                a.QatSupport = true;
                //a.qatAddByDefault = true;
                a.ContextMenuSupport = EditorContextMenuWinForms.MenuTypeEnum.Document;

                Component_PhysicalBody GetBody(object obj)
                {
                    if (obj is Component_PhysicalBody body)
                    {
                        return(body);
                    }

                    var c = obj as Component;

                    if (c != null)
                    {
                        var body2 = c.GetComponent <Component_PhysicalBody>();
                        if (body2 != null)
                        {
                            return(body2);
                        }
                    }

                    return(null);
                }

                a.GetState += delegate(EditorAction.GetStateContext context)
                {
                    if (context.ObjectsInFocus.DocumentWindow != null)
                    {
                        object[] selectedObjects = context.ObjectsInFocus.Objects;
                        if (selectedObjects.Length == 2)
                        {
                            var bodyA = GetBody(selectedObjects[0]);
                            var bodyB = GetBody(selectedObjects[1]);

                            if (bodyA != null && bodyB != null)
                            {
                                context.Enabled = true;
                            }
                            //if( selectedObjects[ 0 ] is Component_PhysicalBody && selectedObjects[ 1 ] is Component_PhysicalBody )
                            //	context.Enabled = true;
                        }
                    }
                };

                a.Click += delegate(EditorAction.ClickContext context)
                {
                    object[] selectedObjects = context.ObjectsInFocus.Objects;
                    if (selectedObjects.Length == 2)
                    {
                        var bodyA = GetBody(selectedObjects[0]);
                        var bodyB = GetBody(selectedObjects[1]);
                        //var bodyA = (Component_PhysicalBody)context.ObjectsInFocus.Objects[ 0 ];
                        //var bodyB = (Component_PhysicalBody)context.ObjectsInFocus.Objects[ 1 ];

                        var parent = ComponentUtility.FindNearestCommonParent(new Component[] { bodyA, bodyB });
                        if (parent != null)
                        {
                            var data = new NewObjectWindow.CreationDataClass();

                            data.initDocumentWindow = context.ObjectsInFocus.DocumentWindow;
                            data.initParentObjects  = new List <object>();
                            data.initParentObjects.Add(parent);
                            data.initLockType = MetadataManager.GetTypeOfNetType(typeof(Component_Constraint));
                            //data.initDemandedTypeDisableChange = true;

                            data.additionActionBeforeEnabled = delegate(NewObjectWindow window)
                            {
                                var constraint = (Component_Constraint)data.createdComponentsOnTopLevel[0];

                                constraint.BodyA = ReferenceUtility.MakeReference <Component_PhysicalBody>(
                                    null, ReferenceUtility.CalculateThisReference(constraint, bodyA));
                                constraint.BodyB = ReferenceUtility.MakeReference <Component_PhysicalBody>(
                                    null, ReferenceUtility.CalculateThisReference(constraint, bodyB));

                                var pos = (bodyA.Transform.Value.Position + bodyB.Transform.Value.Position) * 0.5;
                                constraint.Transform = new Transform(pos, Quaternion.Identity);
                            };

                            EditorAPI.OpenNewObjectWindow(data);
                        }
                    }
                };

                EditorActions.Register(a);
            }
        }
Exemplo n.º 9
0
        void DeleteObjects()
        {
            ContentBrowserUtility.AllContentBrowsers_SuspendChildrenChangedEvent();
            ESet <ComponentHierarchyController> controllersToProcessDelayedOperations = new ESet <ComponentHierarchyController>();

            List <Component> deleted = new List <Component>();

            try
            {
                foreach (var obj in Objects)
                {
                    var parent = obj.Parent;
                    if (parent != null)
                    {
                        RestoreData data = new RestoreData();
                        data.parent      = parent;
                        data.insertIndex = parent.Components.IndexOf(obj);

                        dataToRestore[obj] = data;

                        obj.RemoveFromParent(true);

                        deleted.Add(obj);

                        if (obj.ParentRoot?.HierarchyController != null)
                        {
                            controllersToProcessDelayedOperations.AddWithCheckAlreadyContained(obj.ParentRoot?.HierarchyController);
                        }
                    }
                }
            }
            finally
            {
                foreach (var c in controllersToProcessDelayedOperations)
                {
                    c.ProcessDelayedOperations();
                }
                ContentBrowserUtility.AllContentBrowsers_ResumeChildrenChangedEvent();
            }

            //update selected objects for document windows
            if (document != null)
            {
                foreach (var window in EditorAPI.GetAllDocumentWindowsOfDocument(document))
                {
                    var  selectedObjects = new ESet <object>(window.SelectedObjectsSet);
                    bool updated         = false;

                    foreach (var obj in deleted)
                    {
                        if (selectedObjects.Remove(obj))
                        {
                            updated = true;
                        }
                    }

                    if (updated)
                    {
                        window.SelectObjects(selectedObjects);
                    }
                }
            }
            //!!!!так?
            //!!!!!!как-то слишком низкоуровнего из-за documentWindow?
            //if( SettingsWindow.Instance != null )
            //{
            //	SettingsWindow.PanelData panel = SettingsWindow.Instance.SelectedPanel;
            //	if( panel != null )
            //	{
            //		var selectedObjects = new ESet<object>( SettingsWindow.Instance.SelectedObjectsSet );

            //		foreach( var obj in deleted )
            //			selectedObjects.Remove( obj );

            //		if( !ESet<object>.IsEqual( selectedObjects, SettingsWindow.Instance.SelectedObjectsSet ) )
            //			SettingsWindow.Instance.SelectObjects( panel.documentWindow, selectedObjects );
            //	}
            //}
        }
Exemplo n.º 10
0
        private void kryptonButtonInstall_Click(object sender, EventArgs e)
        {
            var info = PackageManager.ReadPackageArchiveInfo(selectedPackage.FullFilePath, out var error);

            if (info == null)
            {
                return;
            }

            var filesToCopy = new List <string>();

            foreach (var file in info.Files)
            {
                var fullName = Path.Combine(VirtualFileSystem.Directories.Project, file);
                filesToCopy.Add(fullName);
            }

            var text = string.Format(Translate("Install {0}?\n\n{1} files will created."), selectedPackage.GetDisplayName(), filesToCopy.Count);

            //var text = string.Format( Translate( "Install {0}?\r\n\r\n{1} files will created." ), selectedPackage.Name, filesToCopy.Count );
            //var text = $"Install {selectedPackage.Name}?\r\n\r\n{filesToCopy.Count} files will created.";

            if (EditorMessageBox.ShowQuestion(text, EMessageBoxButtons.YesNo) != EDialogResult.Yes)
            {
                return;
            }

            var notification = ScreenNotifications.ShowSticky("Installing the package...");

            try
            {
                using (var archive = ZipFile.OpenRead(selectedPackage.FullFilePath))
                {
                    foreach (var entry in archive.Entries)
                    {
                        var  fileName  = entry.FullName;
                        bool directory = fileName[fileName.Length - 1] == '/';
                        if (fileName != "Package.info" && !directory)
                        {
                            var fullPath = Path.Combine(VirtualFileSystem.Directories.Project, fileName);

                            var directoryName = Path.GetDirectoryName(fullPath);
                            if (!Directory.Exists(directoryName))
                            {
                                Directory.CreateDirectory(directoryName);
                            }

                            entry.ExtractToFile(fullPath, true);
                        }
                    }
                }

                PackageManager.ChangeInstalledState(selectedPackage.Name, true);
            }
            catch (Exception e2)
            {
                EditorMessageBox.ShowWarning(e2.Message);
                return;
            }
            finally
            {
                notification.Close();
            }

            if (!string.IsNullOrEmpty(info.AddCSharpFilesToProject))
            {
                var toAdd = new ESet <string>();

                var path = Path.Combine(VirtualFileSystem.Directories.Assets, info.AddCSharpFilesToProject);
                if (Directory.Exists(path))
                {
                    var fullPaths = CSharpProjectFileUtility.GetProjectFileCSFiles(false, true);
                    var files     = Directory.GetFiles(path, "*.cs", SearchOption.AllDirectories);
                    foreach (var file in files)
                    {
                        if (!fullPaths.Contains(file))
                        {
                            toAdd.AddWithCheckAlreadyContained(file);
                        }
                    }
                }

                //	if( !fileItem.IsDirectory && Path.GetExtension( fileItem.FullPath ).ToLower() == ".cs" )
                //	{
                //		bool added = CSharpProjectFileUtility.GetProjectFileCSFiles( false, true ).Contains( fileItem.FullPath );
                //		if( !added )
                //			toAdd.Add( fileItem.FullPath );
                //	}

                if (toAdd.Count != 0)
                {
                    if (CSharpProjectFileUtility.UpdateProjectFile(toAdd, null, out var error2))
                    {
                        if (toAdd.Count > 1)
                        {
                            Log.Info(EditorLocalization.Translate("General", "Items have been added to the Project.csproj."));
                        }
                        else
                        {
                            Log.Info(EditorLocalization.Translate("General", "The item has been added to the Project.csproj."));
                        }
                    }
                    else
                    {
                        Log.Warning(error2);
                    }
                }
            }

            needUpdateList = true;

            if (info.MustRestart)
            {
                ShowRestartLabel();
            }

            if (!string.IsNullOrEmpty(info.OpenAfterInstall))
            {
                var realFileName = VirtualPathUtility.GetRealPathByVirtual(info.OpenAfterInstall);

                if (info.MustRestart)
                {
                    EditorSettingsSerialization.OpenFileAtStartup = realFileName;
                }
                else
                {
                    EditorAPI.SelectFilesOrDirectoriesInMainResourcesWindow(new string[] { realFileName }, Directory.Exists(realFileName));
                    EditorAPI.OpenFileAsDocument(realFileName, true, true);
                }
            }

            ScreenNotifications.Show(EditorLocalization.Translate("General", "The package has been successfully installed."));

            //restart application
            if (info.MustRestart)
            {
                var text2 = EditorLocalization.Translate("General", "To apply changes need restart the editor. Restart?");
                if (EditorMessageBox.ShowQuestion(text2, EMessageBoxButtons.YesNo) == EDialogResult.Yes)
                {
                    EditorAPI.BeginRestartApplication();
                }
            }
        }
Exemplo n.º 11
0
        void RibbonButtonsUpdateProperties()
        {
            //update tabs visibility
            {
                Metadata.TypeInfo selectedType = null;
                {
                    var obj = workspaceController.SelectedDocumentWindow?.ObjectOfWindow;
                    if (obj != null)
                    {
                        selectedType = MetadataManager.MetadataGetType(obj);
                    }
                }
                foreach (var ribbonTab in kryptonRibbon.RibbonTabs)
                {
                    var tab = ribbonTab.Tag as EditorRibbonDefaultConfiguration.Tab;
                    if (tab != null)
                    {
                        bool visible = true;
                        if (tab.VisibleOnlyForType != null && visible)
                        {
                            visible = selectedType != null && tab.VisibleOnlyForType.IsAssignableFrom(selectedType);
                        }
                        if (tab.VisibleCondition != null && visible)
                        {
                            visible = tab.VisibleCondition();
                        }
                        if (visible && !EditorUtility.PerformRibbonTabVisibleFilter(tab))
                        {
                            visible = false;
                        }

                        if (ribbonTab.Visible != visible)
                        {
                            ribbonLastSelectedTabTypeByUser_DisableUpdate = true;
                            ribbonTab.Visible = visible;
                            ribbonLastSelectedTabTypeByUser_DisableUpdate = false;
                        }

                        if (ribbonTab.Visible && ribbonLastSelectedTabTypeByUser != "" && ribbonLastSelectedTabTypeByUser == tab.Type)
                        {
                            ribbonLastSelectedTabTypeByUser_DisableUpdate = true;
                            kryptonRibbon.SelectedTab = ribbonTab;
                            ribbonLastSelectedTabTypeByUser_DisableUpdate = false;
                        }
                    }
                }
            }

            //update controls
            foreach (var ribbonTab in kryptonRibbon.RibbonTabs)
            {
                foreach (var ribbonGroup in ribbonTab.Groups)
                {
                    foreach (var groupItem in ribbonGroup.Items)
                    {
                        var tripple = groupItem as KryptonRibbonGroupTriple;
                        if (tripple != null)
                        {
                            foreach (var trippleItem in tripple.Items)
                            {
                                //Button, DropDown
                                var button = trippleItem as KryptonRibbonGroupButton;
                                if (button != null)
                                {
                                    //sub group
                                    if (button.Tag as string == "SubGroup" && button.KryptonContextMenu != null)
                                    {
                                        RibbonSubGroupUpdateItemsRecursive(button.KryptonContextMenu.Items, out var existsEnabled);

                                        //disable group when all items are disabled
                                        button.Enabled = existsEnabled;
                                    }

                                    //action
                                    var action = button.Tag as EditorAction;
                                    if (action != null)
                                    {
                                        var state = EditorAPI.EditorActionGetState(EditorAction.HolderEnum.RibbonQAT, action);

                                        button.Enabled = state.Enabled;

                                        //кнопка меняет тип, т.к. в действиях не указывается может ли она быть Checked.
                                        //сделано так, что меняет при первом изменении isChecked.
                                        if (state.Checked && action.ActionType == EditorAction.ActionTypeEnum.Button)
                                        {
                                            button.ButtonType = GroupButtonType.Check;
                                        }

                                        button.Checked = state.Checked;

                                        if (!EditorUtility.PerformEditorActionVisibleFilter(action))
                                        {
                                            button.Visible = false;
                                        }
                                    }
                                }

                                //Slider
                                var slider = trippleItem as KryptonRibbonGroupSlider;
                                if (slider != null)
                                {
                                    var action = slider.Tag as EditorAction;
                                    if (action != null)
                                    {
                                        var lastValue = action.Slider.Value;

                                        var state = EditorAPI.EditorActionGetState(EditorAction.HolderEnum.RibbonQAT, action);

                                        slider.Enabled = state.Enabled;
                                        if (lastValue != action.Slider.Value)
                                        {
                                            slider.Control.SetValue(action.Slider.Value);
                                            //trackBar.Value = action.Slider.Value;
                                        }

                                        if (!EditorUtility.PerformEditorActionVisibleFilter(action))
                                        {
                                            slider.Visible = false;
                                        }
                                    }
                                }

                                ////ComboBox
                                //var comboBox = trippleItem as KryptonRibbonGroupComboBox;
                                //if( comboBox != null )
                                //{
                                //	var action = comboBox.Tag as EditorAction;
                                //	if( action != null )
                                //	{
                                //		var lastItems = action.ComboBox.Items;
                                //		var lastSelectedIndex = action.ComboBox.SelectedIndex;

                                //		var state = EditorAPI.GetEditorActionState( EditorAction.HolderEnum.RibbonQAT, action );

                                //		comboBox.Enabled = state.Enabled;

                                //		if( !action.ComboBox.Items.SequenceEqual( lastItems ) )
                                //		{
                                //			var oldSelectedIndex = comboBox.SelectedIndex;

                                //			comboBox.Items.Clear();
                                //			foreach( var item in action.ComboBox.Items )
                                //				comboBox.Items.Add( item );

                                //			if( oldSelectedIndex >= 0 && oldSelectedIndex < comboBox.Items.Count )
                                //				comboBox.SelectedIndex = oldSelectedIndex;
                                //			else if( comboBox.Items.Count != 0 )
                                //				comboBox.SelectedIndex = 0;
                                //		}
                                //		if( lastSelectedIndex != action.ComboBox.SelectedIndex )
                                //			comboBox.SelectedIndex = action.ComboBox.SelectedIndex;
                                //	}
                                //}

                                //ListBox
                                var listBox = trippleItem as KryptonRibbonGroupListBox;
                                if (listBox != null)
                                {
                                    var action = listBox.Tag as EditorAction;
                                    if (action != null)
                                    {
                                        var lastItems         = action.ListBox.Items;
                                        var lastSelectedIndex = action.ListBox.SelectedIndex;

                                        var state = EditorAPI.EditorActionGetState(EditorAction.HolderEnum.RibbonQAT, action);

                                        //!!!!не listBox2?
                                        listBox.Enabled = state.Enabled;

                                        var browser = listBox.Control.contentBrowser1;

                                        //update items
                                        if (!action.ListBox.Items.SequenceEqual(lastItems))
                                        {
                                            listBox.SetItems(action.ListBox.Items);
                                        }

                                        //update selected item
                                        if (action.ListBox.SelectIndex != null)
                                        {
                                            int selectIndex = action.ListBox.SelectIndex.Value;

                                            var itemToSelect = browser.Items.FirstOrDefault(i => (int)i.Tag == selectIndex);
                                            if (itemToSelect != null)
                                            {
                                                var toSelect = new ContentBrowser.Item[] { itemToSelect };
                                                if (!toSelect.SequenceEqual(browser.SelectedItems))
                                                {
                                                    browser.SelectItems(toSelect);
                                                }
                                            }
                                            else
                                            {
                                                if (browser.SelectedItems.Length != 0)
                                                {
                                                    browser.SelectItems(null);
                                                }
                                            }

                                            action.ListBox.SelectIndex = null;
                                        }

                                        if (!EditorUtility.PerformEditorActionVisibleFilter(action))
                                        {
                                            listBox.Visible = false;
                                        }

                                        //{
                                        //	int selectIndex = action.ListBox.SelectedIndex;
                                        //	int currentSelectedIndex = -1;
                                        //	if( browser.SelectedItems.Length == 1 )
                                        //		currentSelectedIndex = (int)browser.SelectedItems[ 0 ].Tag;
                                        //	//if( browser.SelectedItems.Length == 1 )
                                        //	//	currentSelectedIndex = browser.RootItems.IndexOf( browser.SelectedItems[ 0 ] );

                                        //	if( selectIndex != currentSelectedIndex )
                                        //	{
                                        //		var itemToSelect = browser.Items.FirstOrDefault( i => (int)i.Tag == selectIndex );
                                        //		if( itemToSelect != null )
                                        //			browser.SelectItems( new ContentBrowser.Item[] { itemToSelect } );
                                        //		else
                                        //			browser.SelectItems( null );
                                        //	}
                                        //}

                                        //!!!!?
                                        //if( lastSelectedIndex != action.ListBox.SelectedIndex )
                                        //{
                                        //	if(browser.Items
                                        //	browser.SelectItems( new ContentBrowser.Item[] { items[ 0 ] } );

                                        //	//browser.SelectedIndex = action.ListBox.SelectedIndex;
                                        //}
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 12
0
        void RibbonSubGroupAddItemsRecursive(EditorRibbonDefaultConfiguration.Group subGroup, KryptonContextMenuCollection contextMenuItems)
        {
            var items = new List <KryptonContextMenuItemBase>();

            foreach (var child in subGroup.Children)
            {
                //!!!!impl
                ////sub group
                //var subGroup = child as EditorRibbonDefaultConfiguration.Group;
                //if( subGroup != null )
                //{
                //	var tripple = new KryptonRibbonGroupTriple();
                //	ribbonGroup.Items.Add( tripple );

                //	var button = new KryptonRibbonGroupButton();
                //	//button.Tag = action;
                //	button.TextLine1 = subGroup.DropDownGroupText.Item1;
                //	button.TextLine2 = subGroup.DropDownGroupText.Item2;
                //	//button.ImageSmall = action.imageSmall;
                //	button.ImageLarge = subGroup.DropDownGroupImage;
                //	button.ToolTipBody = subGroup.Name;
                //	button.ButtonType = GroupButtonType.DropDown;

                //	button.KryptonContextMenu = new KryptonContextMenu();
                //	RibbonSubGroupAddItemsRecursive( subGroup, button.KryptonContextMenu.Items );

                //	tripple.Items.Add( button );
                //}

                //action
                var action = child as EditorAction;
                if (action == null)
                {
                    var actionName = child as string;
                    if (actionName != null)
                    {
                        action = EditorActions.GetByName(actionName);
                    }
                }
                if (action != null)
                {
                    if (!action.CompletelyDisabled)
                    {
                        EventHandler clickHandler = delegate(object s, EventArgs e2)
                        {
                            var item2 = (KryptonContextMenuItem)s;

                            var action2 = item2.Tag as EditorAction;
                            if (action2 != null)
                            {
                                EditorAPI.EditorActionClick(EditorAction.HolderEnum.RibbonQAT, action2.Name);
                            }
                        };

                        var item = new KryptonContextMenuItem(action.GetContextMenuText(), null, clickHandler);
                        //var item = new KryptonContextMenuItem( action.GetContextMenuText(), action.imageSmall, clickHandler );
                        item.Tag = action;
                        items.Add(item);
                    }
                }
                //separator
                else if (child == null)
                {
                    items.Add(new KryptonContextMenuSeparator());
                }
            }

            if (items.Count != 0)
            {
                contextMenuItems.Add(new KryptonContextMenuItems(items.ToArray()));
            }
        }
Exemplo n.º 13
0
        public virtual bool Creation(NewObjectCell.ObjectCreationContext context)
        {
            if (Window.IsFileCreation() && CreateCSharpClass)
            {
                context.disableFileCreation = true;

                GetCreateCSharpClassInfo(out var csharpRealFileName, out var csharpClassName, out var csharpClassNameWithoutNamespace);

                try
                {
                    //main file
                    {
                        string className = csharpClassName;
                        //string className = CreateCSharpClass ? csharpClassName : Window.SelectedType.Name;
                        var text = ".component " + className + "\r\n{\r\n}";

                        File.WriteAllText(context.fileCreationRealFileName, text);
                    }

                    //cs file
                    //if( CreateCSharpClass )
                    {
                        string code = @"using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using NeoAxis;

namespace Project
{
	public class {Name} : {Base}
	{
	}
}";

                        code = code.Replace("{Name}", csharpClassNameWithoutNamespace);
                        code = code.Replace("{Base}", Window.SelectedType.Name);

                        File.WriteAllText(csharpRealFileName, code);
                    }
                }
                catch (Exception e)
                {
                    EditorMessageBox.ShowWarning(e.Message);
                    //Log.Warning( e.Message );
                    return(false);
                }

                //if( CreateCSharpClass )
                {
                    //add to Project.csproj
                    {
                        var toAdd = new List <string>();

                        var fileName = Path.Combine("Assets", VirtualPathUtility.GetVirtualPathByReal(csharpRealFileName));
                        toAdd.Add(fileName);

                        if (CSharpProjectFileUtility.UpdateProjectFile(toAdd, null, out var error))
                        {
                            if (toAdd.Count > 1)
                            {
                                Log.Info(EditorLocalization.Translate("General", "Items have been added to the Project.csproj."));
                            }
                            else
                            {
                                Log.Info(EditorLocalization.Translate("General", "The item has been added to the Project.csproj."));
                            }
                        }
                        else
                        {
                            EditorMessageBox.ShowWarning(error);
                            //Log.Warning( error );
                            return(false);
                        }
                    }

                    Window.DisableUnableToCreateReason = true;

                    //restart application
                    var text = EditorLocalization.Translate("General", "To apply changes need restart the editor. Restart?\r\n\r\nThe editor must be restarted to compile and enable a new created C# class.");
                    if (EditorMessageBox.ShowQuestion(text, EMessageBoxButtons.YesNo) == EDialogResult.Yes)
                    {
                        EditorAPI.BeginRestartApplication();
                    }

                    Window.DisableUnableToCreateReason = false;
                }
            }

            return(true);
        }
Exemplo n.º 14
0
        public override void Register()
        {
            var types = new List <Metadata.TypeInfo>();

            types.Add(MetadataManager.GetTypeOfNetType(typeof(Component_Constraint2D_Revolute)));
            types.Add(MetadataManager.GetTypeOfNetType(typeof(Component_Constraint2D_Prismatic)));
            types.Add(MetadataManager.GetTypeOfNetType(typeof(Component_Constraint2D_Distance)));
            types.Add(MetadataManager.GetTypeOfNetType(typeof(Component_Constraint2D_Weld)));
            types.Add(MetadataManager.GetTypeOfNetType(typeof(Component_Constraint2D_Fixed)));

            foreach (var type in types)
            {
                var displayName = TypeUtility.GetUserFriendlyNameForInstanceOfType(type.GetNetType());

                var a = new EditorAction();
                a.Name = "Add " + displayName;
                //a.ImageSmall = Properties.Resources.New_16;
                //a.ImageBig = Properties.Resources.New_32;

                a.QatSupport = true;
                //a.qatAddByDefault = true;
                a.ContextMenuSupport = EditorContextMenu.MenuTypeEnum.Document;

                Component_PhysicalBody2D GetBody(object obj)
                {
                    if (obj is Component_PhysicalBody2D body)
                    {
                        return(body);
                    }

                    var c = obj as Component;

                    if (c != null)
                    {
                        var body2 = c.GetComponent <Component_PhysicalBody2D>();
                        if (body2 != null)
                        {
                            return(body2);
                        }
                    }

                    return(null);
                }

                a.GetState += delegate(EditorAction.GetStateContext context)
                {
                    if (context.ObjectsInFocus.DocumentWindow != null)
                    {
                        object[] selectedObjects = context.ObjectsInFocus.Objects;
                        if (selectedObjects.Length == 2)
                        {
                            var bodyA = GetBody(selectedObjects[0]);
                            var bodyB = GetBody(selectedObjects[1]);

                            if (bodyA != null && bodyB != null)
                            {
                                context.Enabled = true;
                            }
                            //if( selectedObjects[ 0 ] is Component_PhysicalBody2D && selectedObjects[ 1 ] is Component_PhysicalBody2D )
                            //	context.Enabled = true;
                        }
                    }
                };

                a.Click += delegate(EditorAction.ClickContext context)
                {
                    object[] selectedObjects = context.ObjectsInFocus.Objects;
                    if (selectedObjects.Length == 2)
                    {
                        var bodyA = GetBody(selectedObjects[0]);
                        var bodyB = GetBody(selectedObjects[1]);
                        //var bodyA = (Component_PhysicalBody2D)context.ObjectsInFocus.Objects[ 0 ];
                        //var bodyB = (Component_PhysicalBody2D)context.ObjectsInFocus.Objects[ 1 ];

                        var parent = ComponentUtility.FindNearestCommonParent(new Component[] { bodyA, bodyB });
                        if (parent != null)
                        {
                            var data = new NewObjectWindow.CreationDataClass();

                            data.initDocumentWindow = context.ObjectsInFocus.DocumentWindow;
                            data.initParentObjects  = new List <object>();
                            data.initParentObjects.Add(parent);
                            data.initLockType = type;

                            data.additionActionBeforeEnabled = delegate(NewObjectWindow window)
                            {
                                var constraint = (Component_Constraint2D)data.createdComponentsOnTopLevel[0];

                                constraint.BodyA = ReferenceUtility.MakeReference <Component_PhysicalBody2D>(
                                    null, ReferenceUtility.CalculateThisReference(constraint, bodyA));
                                constraint.BodyB = ReferenceUtility.MakeReference <Component_PhysicalBody2D>(
                                    null, ReferenceUtility.CalculateThisReference(constraint, bodyB));

                                if (constraint is Component_Constraint2D_Distance)
                                {
                                    var pos  = bodyA.Transform.Value.Position;
                                    var posB = bodyB.Transform.Value.Position;

                                    var distance = (posB - pos).Length();

                                    var rot = Quaternion.FromDirectionZAxisUp((posB - pos).GetNormalize());
                                    var scl = new Vector3(distance, distance, distance);

                                    constraint.Transform = new Transform(pos, rot, scl);
                                }
                                else
                                {
                                    var pos = (bodyA.Transform.Value.Position + bodyB.Transform.Value.Position) * 0.5;
                                    constraint.Transform = new Transform(pos, Quaternion.Identity);
                                }
                            };

                            EditorAPI.OpenNewObjectWindow(data);
                        }
                    }
                };

                EditorActions.Register(a);
            }
        }
Exemplo n.º 15
0
        public static void Clear()
        {
            var window = EditorAPI.FindWindow <OutputWindow>();

            window?.ClearInstance();
        }
Exemplo n.º 16
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (EditorUtility.IsDesignerHosted(this))
            {
                return;
            }
            if (!loaded)
            {
                return;
            }

            //!!!!!slowly?

            //!!!!!!

            //if( needSelectResource != null )
            //{
            //	var selectResource = needSelectResource;
            //	needSelectResource = null;
            //	//ContentObjectSettings.Instance.SelectResource( selectResource );
            //}

            //UpdatePagesVisibility();

            //!!!!!
            //!!!!где еще вызывать?
            if (EngineApp.Instance != null)
            {
                EngineApp.DoTick();
            }

            if (EngineApp.GetSystemTime() - lastSlowUpdatingTime > 0.2 && !firstTick)
            {
                QATButtonsUpdate();
                RibbonUpdate();
                UpdateText();

                lastSlowUpdatingTime = EngineApp.GetSystemTime();
            }

            //save editor settings
            EditorSettingsSerialization.Dump();

            ScreenNotifications.Update();

            if (!needClose)
            {
                EditorAPI.SelectedDocumentWindowChangedUpdate();
            }

            if (!needClose)
            {
                foreach (var document in EditorAPI.Documents)
                {
                    document.EditorUpdateWhenDocumentModified_Tick();
                }
            }

            if (!needClose)
            {
                PreviewIconsManager.Update();
            }

            ////!!!!temp
            //CheckRestartApplicationToApplyChanged();

            if (!needClose)
            {
                UpdateSoundSystem();
            }

            //save editor settings
            if (!needClose)
            {
                KryptonAutoHiddenSlidePanel.Animate = ProjectSettings.Get.AnimateWindowsAutoHiding;
            }

            //if( !needClose )
            //	ScriptEditorEngine.Instance.UpdateSettings();

            UpdateVisibilityOfFloatingWindows();

            if (needClose)
            {
                needClose = false;
                Close();
            }

            if (firstTick)
            {
                //!!!!new
                firstTick = false;

                if (SplashForm.Instance != null)
                {
                    SplashForm.Instance.AllowClose = true;
                }

                // hide cover show ribbon.
                kryptonRibbon.Visible = true;

                if (coverControl != null)
                {
                    Controls.Remove(coverControl);
                }
                //coverControl.Visible = false;

                if (EditorSettingsSerialization.ShowTipsAsStartup)
                {
                    EditorAPI.ShowTips();
                }
            }

            canSaveConfig = true;
            firstTick     = false;
        }
Exemplo n.º 17
0
 private void kryptonButtonOpenStore_Click(object sender, EventArgs e)
 {
     EditorAPI.OpenStore();
 }
Exemplo n.º 18
0
        public virtual void EditorActionClick(EditorAction.ClickContext context)
        {
            switch (context.Action.Name)
            {
            case "Save":
                Save(null);
                break;

            case "Save As":
            {
#if !PROJECT_DEPLOY
                var dialog = new CommonSaveFileDialog();
                dialog.InitialDirectory = Path.GetDirectoryName(RealFileName);
                dialog.DefaultFileName  = Path.GetFileName(RealFileName);
                dialog.Filters.Add(new CommonFileDialogFilter("All Files", ".*"));
                if (dialog.ShowDialog() != CommonFileDialogResult.Ok)
                {
                    return;
                }

                var saveAsFileName = dialog.FileName;

                //if( File.Exists( saveAsFileName ) )
                //{
                //	var text = string.Format( EditorLocalization.Translate( "General", "A file with the name \'{0}\' already exists. Overwrite?" ), saveAsFileName );
                //	if( EditorMessageBox.ShowQuestion( text, MessageBoxButtons.OKCancel ) != DialogResult.OK )
                //		return;
                //}

                if (string.Compare(RealFileName, saveAsFileName, true) == 0)
                {
                    Save();
                }
                else
                {
                    Save(saveAsFileName, false);
                    EditorAPI.OpenFileAsDocument(saveAsFileName, true, true);
                }
#endif
            }
            break;

            case "Undo":
                if (undoSystem != null)
                {
                    if (undoSystem.DoUndo())
                    {
                        Modified = true;
                    }
                }
                break;

            case "Redo":
                if (undoSystem != null)
                {
                    if (undoSystem.DoRedo())
                    {
                        Modified = true;
                    }
                }
                break;

            case "Play":
            {
                var component = LoadedResource?.ResultComponent;
                if (component != null && RunSimulation.CheckTypeSupportedByPlayer(component.BaseType))
                {
                    if (!EditorAPI.SaveDocuments())
                    {
                        return;
                    }
                    //if( Modified )
                    //{
                    //	if( !Save( null ) )
                    //		return;
                    //}

                    //!!!!не только standalone
                    var realFileName = VirtualPathUtility.GetRealPathByVirtual(LoadedResource.Owner.Name);
                    RunSimulation.Run(realFileName, RunSimulation.RunMethod.Player);
                }
            }
            break;

            case "Find Resource":
                if (!string.IsNullOrEmpty(RealFileName))
                {
                    EditorAPI.SelectFilesOrDirectoriesInMainResourcesWindow(new string[] { RealFileName });
                }
                break;
            }
        }
Exemplo n.º 19
0
        bool CreateObject()
        {
            creationData.ClearCreatedObjects();

            //!!!!в окнах/окне делать активным после создания

            //creationData.selectedType = SelectedType;
            //creationData.replaceSelectedTypeFunction?.Invoke( this );

            //!!!!
            //create objects
            {
                creationData.beforeCreateObjectsFunction?.Invoke(this, SelectedType);

                //default creation behaviour
                if (creationData.createdObjects == null)
                {
                    creationData.createdObjects = new List <object>();

                    if (creationData.initParentObjects != null)
                    {
                        foreach (var parentObject in creationData.initParentObjects)
                        {
                            var parentComponent = parentObject as Component;

                            object obj;
                            if (parentComponent != null)
                            {
                                var insertIndex = EditorUtility.GetNewObjectInsertIndex(parentComponent, SelectedType);
                                obj = parentComponent.CreateComponent(SelectedType, insertIndex, false);
                            }
                            else
                            {
                                obj = SelectedType.InvokeInstance(null);
                            }

                            creationData.createdObjects.Add(obj);
                            creationData.createdObjectsToApplySettings.Add(obj);
                            var c = obj as Component;
                            if (c != null)
                            {
                                creationData.createdComponentsOnTopLevel.Add(c);
                            }
                        }
                    }
                    else
                    {
                        var obj = SelectedType.InvokeInstance(null);

                        creationData.createdObjects.Add(obj);
                        creationData.createdObjectsToApplySettings.Add(obj);
                        var c = obj as Component;
                        if (c != null)
                        {
                            creationData.createdComponentsOnTopLevel.Add(c);
                        }
                    }
                }
            }

            //!!!!
            //no created objects
            if (creationData.createdObjects.Count == 0)
            {
                //!!!!
                return(false);
            }

            string realFileName = "";

            if (IsFileCreation())
            {
                realFileName = VirtualPathUtility.GetRealPathByVirtual(textBoxName.Text);
            }

            //create folder for file creation
            if (IsFileCreation())
            {
                var directoryName = Path.GetDirectoryName(realFileName);
                if (!Directory.Exists(directoryName))
                {
                    try
                    {
                        Directory.CreateDirectory(directoryName);
                    }
                    catch (Exception e)
                    {
                        Log.Warning(e.Message);
                        return(false);
                    }
                }
            }

            //init settings of objects
            bool disableFileCreation = false;

            foreach (var createdObject in creationData.createdObjectsToApplySettings)
            {
                if (!ApplyCreationSettingsToObject(createdObject, ref disableFileCreation))
                {
                    return(false);
                }
            }

            //action before enabled
            creationData.additionActionBeforeEnabled?.Invoke(this);

            //finalization of creation
            foreach (var component in creationData.createdComponentsOnTopLevel)
            {
                component.Enabled = true;
            }

            creationData.additionActionAfterEnabled?.Invoke(this);
            //foreach( var obj in createdObjects )
            //	creationData.additionActionAfterEnabled?.Invoke( this, obj, newObjectsFromAdditionActions );

            //file creation. save to file
            if (IsFileCreation())
            {
                //!!!!проверки
                //!!!!!!!overwrite

                if (creationData.createdComponentsOnTopLevel.Count == 1 && !disableFileCreation)
                {
                    var createdComponent = creationData.createdComponentsOnTopLevel[0];
                    if (!ComponentUtility.SaveComponentToFile(createdComponent, realFileName, null, out string error))
                    {
                        if (!string.IsNullOrEmpty(error))
                        {
                            //!!!!
                            Log.Warning(error);
                            return(false);
                        }
                    }
                }

                //Dispose created objects for file creation mode
                foreach (var obj in creationData.createdObjects)
                {
                    var d = obj as IDisposable;
                    if (d != null)
                    {
                        d.Dispose();
                    }
                }
            }

            //update document
            if (!IsFileCreation())
            {
                //update document
                //!!!!!
                var document = creationData.initDocumentWindow.Document;
                if (document != null)
                {
                    //!!!!только компоненты?

                    var action = new UndoActionComponentCreateDelete(document, creationData.createdComponentsOnTopLevel, true);

                    //List<Component> created = new List<Component>();
                    //created.AddRange( createdComponents );
                    //foreach( var obj in newObjectsFromAdditionActions )
                    //{
                    //	var component = obj as Component;
                    //	if( component != null )
                    //		created.Add( component );
                    //}
                    //var action = new UndoActionComponentCreateDelete( created, true );
                    document.UndoSystem.CommitAction(action);

                    document.Modified = true;
                }
                else
                {
                    //!!!!надо ли?
                    Log.Warning("impl");
                }
            }

            //select and open
            if (IsFileCreation())
            {
                //!!!!не обязательно основное окно

                EditorAPI.GetRestartApplication(out var needRestart, out _);
                if (needRestart)
                {
                    EditorSettingsSerialization.OpenFileAtStartup = realFileName;
                }
                else
                {
                    //select new file in Resources window
                    EditorAPI.SelectFilesOrDirectoriesInMainResourcesWindow(new string[] { realFileName });

                    //open file
                    EditorAPI.OpenFileAsDocument(realFileName, true, true);
                }
            }
            else
            {
                //select created components
                if (creationData.createdFromContentBrowser != null)
                {
                    var creator = creationData.createdFromContentBrowser;
                    if (creator.IsHandleCreated && !creator.IsDisposed)
                    {
                        ContentBrowserUtility.SelectComponentItems(creator, creationData.createdComponentsOnTopLevel.ToArray());
                    }
                }
                else
                {
                    EditorAPI.SelectComponentsInMainObjectsWindow(creationData.initDocumentWindow, creationData.createdComponentsOnTopLevel.ToArray());
                }

                //open editor
                if (creationData.createdComponentsOnTopLevel.Count == 1)
                {
                    var component = creationData.createdComponentsOnTopLevel[0];

                    if (!component.EditorReadOnlyInHierarchy)
                    {
                        //!!!!пока так
                        if (component is Component_FlowGraph || component is Component_CSharpScript)
                        {
                            EditorAPI.OpenDocumentWindowForObject(creationData.initDocumentWindow.Document, component);
                        }
                    }
                    //if( EditorAPI.IsDocumentObjectSupport( component ) && !component.EditorReadOnlyInHierarchy )
                    //	EditorAPI.OpenDocumentWindowForObject( creationData.initDocumentWindow.Document, component );
                }
            }

            //finish creation
            creationData.ClearCreatedObjects();

            return(true);
        }
Exemplo n.º 20
0
        void ShowContextMenu()
        {
            var items = new List <KryptonContextMenuItemBase>();

            Component oneSelectedComponent = ObjectOfWindow as Component;

            //Editor
            {
                var item = new KryptonContextMenuItem(TranslateContextMenu("Editor"), EditorResourcesCache.Edit, delegate(object s, EventArgs e2)
                {
                    EditorAPI.OpenDocumentWindowForObject(Document, oneSelectedComponent);
                });
                item.Enabled = oneSelectedComponent != null && EditorAPI.IsDocumentObjectSupport(oneSelectedComponent);
                items.Add(item);
            }

            //Settings
            {
                var item = new KryptonContextMenuItem(TranslateContextMenu("Settings"), EditorResourcesCache.Settings, delegate(object s, EventArgs e2)
                {
                    bool canUseAlreadyOpened = !ModifierKeys.HasFlag(Keys.Shift);
                    EditorAPI.ShowObjectSettingsWindow(Document, oneSelectedComponent, canUseAlreadyOpened);
                });
                item.Enabled = oneSelectedComponent != null;
                items.Add(item);
            }

            items.Add(new KryptonContextMenuSeparator());

            //New object
            {
                EditorContextMenuWinForms.AddNewObjectItem(items, CanNewObject(out _), delegate(Metadata.TypeInfo type)
                {
                    TryNewObject(type);
                });
            }

            //separator
            items.Add(new KryptonContextMenuSeparator());

            //Cut
            {
                var item = new KryptonContextMenuItem(TranslateContextMenu("Cut"), EditorResourcesCache.Cut,
                                                      delegate(object s, EventArgs e2)
                {
                    //Cut();
                });
                item.ShortcutKeyDisplayString = EditorActions.GetFirstShortcutKeyString("Cut");
                item.Enabled = false;                // CanCut();
                items.Add(item);
            }

            //Copy
            {
                var item = new KryptonContextMenuItem(TranslateContextMenu("Copy"), EditorResourcesCache.Copy,
                                                      delegate(object s, EventArgs e2)
                {
                    Copy();
                });
                item.ShortcutKeyDisplayString = EditorActions.GetFirstShortcutKeyString("Copy");
                item.Enabled = CanCopy();
                items.Add(item);
            }

            //Paste
            {
                var item = new KryptonContextMenuItem(TranslateContextMenu("Paste"), EditorResourcesCache.Paste,
                                                      delegate(object s, EventArgs e2)
                {
                    Paste();
                });
                item.ShortcutKeyDisplayString = EditorActions.GetFirstShortcutKeyString("Paste");
                item.Enabled = CanPaste(out _);
                items.Add(item);
            }

            //Clone
            {
                var item = new KryptonContextMenuItem(TranslateContextMenu("Duplicate"), EditorResourcesCache.Clone,
                                                      delegate(object s, EventArgs e2)
                {
                    //TryCloneObjects();
                });
                item.ShortcutKeyDisplayString = EditorActions.GetFirstShortcutKeyString("Duplicate");
                item.Enabled = false;                // CanCloneObjects( out List<Component> dummy );
                items.Add(item);
            }

            //separator
            items.Add(new KryptonContextMenuSeparator());

            //Delete
            {
                var item = new KryptonContextMenuItem(TranslateContextMenu("Delete"), EditorResourcesCache.Delete,
                                                      delegate(object s, EventArgs e2)
                {
                    //TryDeleteObjects();
                });
                item.Enabled = false;                // CanDeleteObjects( out List<Component> dummy );
                items.Add(item);
            }

            //Rename
            {
                var item = new KryptonContextMenuItem(TranslateContextMenu("Rename"), null, delegate(object s, EventArgs e2)
                {
                    EditorUtility.ShowRenameComponentDialog(oneSelectedComponent);
                });
                item.ShortcutKeyDisplayString = EditorActions.GetFirstShortcutKeyString("Rename");
                //!!!!!
                item.Enabled = oneSelectedComponent != null;
                items.Add(item);
            }

            EditorContextMenuWinForms.AddActionsToMenu(EditorContextMenuWinForms.MenuTypeEnum.Document, items);              //, this );

            EditorContextMenuWinForms.Show(items, this);
        }
Exemplo n.º 21
0
        public static void AddActionsToMenu(MenuTypeEnum menuType, ICollection <KryptonContextMenuItemBase> items)         //, DocumentWindow documentWindow )
        {
            bool firstItem = true;

            foreach (var action in EditorActions.Actions)
            {
                if (action.ContextMenuSupport != MenuTypeEnum.None && action.ContextMenuSupport == menuType)
                {
                    var state = EditorAPI.EditorActionGetState(EditorAction.HolderEnum.ContextMenu, action);
                    //bool enabled = false;
                    //action.PerformUpdateContextMenuEvent( documentWindow, ref enabled );

                    if (state.Enabled)
                    {
                        if (firstItem)
                        {
                            if (items.Count != 0)
                            {
                                items.Add(new KryptonContextMenuSeparator());
                            }

                            firstItem = false;
                        }

                        var image = EditorAPI.GetImageForDispalyScale(action.GetImageSmall(), action.GetImageBig());
                        var item  = new KryptonContextMenuItem(Translate(action.GetContextMenuText()), image, delegate(object s, EventArgs e2)
                        {
                            ////var a = (EditorAction)item.Tag;

                            ////!!!!так?
                            var state2 = EditorAPI.EditorActionGetState(EditorAction.HolderEnum.ContextMenu, action);
                            //check still enabled
                            if (state2.Enabled)
                            {
                                EditorAPI.EditorActionClick(EditorAction.HolderEnum.ContextMenu, action.Name);
                            }

                            //action.PerformClickContextMenuEvent( documentWindow );
                        });

                        if (action.ActionType == EditorAction.ActionTypeEnum.DropDown)
                        {
                            var args = new CancelEventArgs();
                            action.DropDownContextMenu.PerformOpening(args);
                            //!!!!?
                            //if( !args.Cancel)
                            //{

                            foreach (var child in action.DropDownContextMenu.Items)
                            {
                                item.Items.Add(child);
                            }
                        }

                        //!!!!
                        //item.Enabled = !rootNodeSelected;
                        item.Tag = action;
                        item.ShortcutKeyDisplayString = EditorActions.GetFirstShortcutKeyString(action.Name);
                        items.Add(item);
                    }
                }
            }
        }
Exemplo n.º 22
0
        public static void Import(string[] fileNames, string destRealFolder)          //Initial )
        {
            try
            {
                if (!Directory.Exists(destRealFolder))
                {
                    Directory.CreateDirectory(destRealFolder);
                }
            }
            catch (Exception e)
            {
                EditorMessageBox.ShowWarning(e.Message);
                return;
            }

            ////check files inside project Data folder
            //{
            //	foreach( var fileName in fileNames )
            //	{
            //		var virtualPath = VirtualPathUtils.GetVirtualPathByReal( fileName );
            //		if( !string.IsNullOrEmpty( virtualPath ) )
            //		{
            //			Log.Warning( "Unable to import from project \'Data\' folder. The file already inside the project." );
            //			return;
            //		}
            //	}
            //}

            //processing

            //!!!!пока просто копирование
            //нужно зависимые скопировать
            //также может какую-то обработку делать

            ////select folder if exists files outside Assets folder
            //string destRealFolder = "";
            //{
            //	var existsOutside = fileNames.Any( fileName => string.IsNullOrEmpty( VirtualPathUtility.GetVirtualPathByReal( fileName ) ) );
            //	if( existsOutside )
            //	{
            //		if( string.IsNullOrEmpty( destRealFolderInitial ) )
            //		{
            //			again:;
            //			destRealFolder = VirtualPathUtility.GetRealPathByVirtual( "Import" );
            //			if( !Directory.Exists( destRealFolder ) )
            //				destRealFolder = VirtualPathUtility.GetRealPathByVirtual( "" );

            //			CommonOpenFileDialog dialog = new CommonOpenFileDialog();
            //			dialog.InitialDirectory = destRealFolder;
            //			dialog.IsFolderPicker = true;
            //			if( dialog.ShowDialog() == CommonFileDialogResult.Ok )
            //			{
            //				destRealFolder = dialog.FileName;

            //				if( !VirtualPathUtility.GetVirtualPathByReal( destRealFolder, out _ ) )
            //				{
            //					EditorMessageBox.ShowWarning( "Need select folder inside Assets folder." );
            //					//Log.Warning( "Need select folder inside Data folder." );
            //					goto again;
            //				}
            //			}
            //		}
            //		else
            //			destRealFolder = destRealFolderInitial;
            //	}
            //}

            List <string> fileNamesToSelect = new List <string>();

            foreach (var fileName in fileNames)
            {
                var virtualPath = VirtualPathUtility.GetVirtualPathByReal(fileName);
                if (!string.IsNullOrEmpty(virtualPath))
                {
                    //already inside Data folder
                    fileNamesToSelect.Add(fileName);
                }
                else
                {
                    //copy to Data folder

                    string destinationFileName;
                    try
                    {
                        destinationFileName = Path.Combine(destRealFolder, Path.GetFileName(fileName));

                        if (Directory.Exists(fileName))
                        {
                            IOUtility.CopyDirectory(fileName, destinationFileName);
                        }
                        else
                        {
                            File.Copy(fileName, destinationFileName);
                        }
                    }
                    catch (Exception e)
                    {
                        EditorMessageBox.ShowWarning(e.Message);
                        //Log.Warning( e.Message );
                        return;
                    }

                    fileNamesToSelect.Add(destinationFileName);
                }
            }

            //select new files
            EditorAPI.SelectFilesOrDirectoriesInMainResourcesWindow(fileNamesToSelect.ToArray());
            EditorAPI.SelectDockWindow(EditorAPI.FindWindow <ResourcesWindow>());
        }
Exemplo n.º 23
0
        private void ButtonAddEventHandler_Click(object sender, EventArgs e)
        {
            var items = new List <KryptonContextMenuItemBase>();

            var subscribeTo = GetOneControlledObject <Component>();

            if (subscribeTo == null)
            {
                return;
            }

            //add handler to C# class
            {
                bool   enable         = false;
                string className      = null;
                string csharpFileName = null;

                var fileName = subscribeTo.ParentRoot.HierarchyController?.CreatedByResource?.Owner.Name;
                if (!string.IsNullOrEmpty(fileName))
                {
                    className = subscribeTo.ParentRoot.GetType().Name;

                    try
                    {
                        //find by same class name
                        if (string.Compare(Path.GetFileNameWithoutExtension(fileName), className, true) == 0)
                        //if( Path.GetFileNameWithoutExtension( fileName ) == className )
                        {
                            csharpFileName = VirtualPathUtility.GetRealPathByVirtual(Path.ChangeExtension(fileName, "cs"));
                            if (File.Exists(csharpFileName))
                            {
                                enable = true;
                            }
                        }

                        //find by same file name
                        if (!enable)
                        {
                            csharpFileName = VirtualPathUtility.GetRealPathByVirtual(Path.Combine(Path.GetDirectoryName(fileName), className + ".cs"));
                            if (File.Exists(csharpFileName))
                            {
                                enable = true;
                            }
                        }
                    }
                    catch { }
                }

                var item = new KryptonContextMenuItem(Translate("Add Handler to C# File"), null, delegate(object s, EventArgs e2)
                {
                    AddHandlerToSharpClass(subscribeTo, csharpFileName, className);
                });
                item.Enabled = enable;
                items.Add(item);
            }

            //add handler to C# script
            {
                var groupItem  = new KryptonContextMenuItem(Translate("Add Handler to C# Script"), null);
                var childItems = new List <KryptonContextMenuItemBase>();

                //create new C# script
                {
                    var itemsData = new List <(string, Component)>();
                    itemsData.Add((Translate("Add C# Script in This Component"), subscribeTo));
                    if (subscribeTo != subscribeTo.ParentRoot)
                    {
                        itemsData.Add((Translate("Add C# Script in the Root Component"), subscribeTo.ParentRoot));
                    }

                    foreach (var itemData in itemsData)
                    {
                        var childItem = new KryptonContextMenuItem(itemData.Item1, null, delegate(object s, EventArgs e2)
                        {
                            var parent   = (Component)((KryptonContextMenuItem)s).Tag;
                            var document = Owner.DocumentWindow.Document;

                            //create script
                            var script     = parent.CreateComponent <Component_CSharpScript>(enabled: false);
                            script.Name    = script.BaseType.GetUserFriendlyNameForInstance();
                            script.Code    = "class _Temp{\r\n}";
                            script.Enabled = true;

                            //activate flow graph window
                            var scriptDocumentWindow = EditorAPI.OpenDocumentWindowForObject(document, script) as Component_CSharpScript_DocumentWindow;

                            Owner.DocumentWindow.SelectObjects(new object[] { script });

                            GetMethodInfo(subscribeTo, out var parameters, out var parametersSignature);
                            var methodNameNotUnique = subscribeTo.Name.Replace(" ", "") + "_" + _event.Name;
                            var methodName          = methodNameNotUnique;
                            var methodSignature     = $"method:{methodName}({parametersSignature})";

                            if (!scriptDocumentWindow.ScriptEditorControl.AddMethod(methodName, parameters, out var error))
                            {
                                Log.Warning("Unable to add a code of the method. " + error);
                                //!!!!
                            }

                            //fix code
                            try
                            {
                                scriptDocumentWindow.ScriptEditorControl.GetCode(out var code);

                                code = code.Replace("class _Temp{", "");

                                var index = code.LastIndexOf('}');
                                code      = code.Substring(0, index);

                                string newCode = "";
                                var lines      = code.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                                foreach (var line in lines)
                                {
                                    newCode += line.Trim() + "\r\n";
                                }

                                script.Code = newCode;
                            }
                            catch (Exception e3)
                            {
                                Log.Warning("Unable to fix code of the method. " + e3.Message);
                                //!!!!
                            }

                            //create event handler
                            {
                                var handler   = script.CreateComponent <Component_EventHandler>(enabled: false);
                                handler.Name  = handler.BaseType.GetUserFriendlyNameForInstance() + " " + _event.Name;
                                handler.Event = ReferenceUtility.MakeReference <ReferenceValueType_Event>(null,
                                                                                                          ReferenceUtility.CalculateThisReference(handler, subscribeTo, _event.Signature));
                                handler.HandlerMethod = ReferenceUtility.MakeReference <ReferenceValueType_Method>(null,
                                                                                                                   ReferenceUtility.CalculateThisReference(handler, script, methodSignature));
                                handler.Enabled = true;
                            }

                            //undo
                            var action = new UndoActionComponentCreateDelete(document, new Component[] { script }, true);
                            document.UndoSystem.CommitAction(action);
                            document.Modified = true;
                        });
                        childItem.Tag = itemData.Item2;
                        childItems.Add(childItem);
                    }
                }

                //add handler to one of already created C# scripts
                foreach (var script in subscribeTo.ParentRoot.GetComponents <Component_CSharpScript>(false, true))
                {
                    if (script.TypeSettingsIsPublic())
                    {
                        var text = string.Format(Translate("Add Handler to \'{0}\'"), script.GetPathFromRoot(true));
                        var item = new KryptonContextMenuItem(text, null, delegate(object s, EventArgs e2)
                        {
                            var script2  = (Component_CSharpScript)((KryptonContextMenuItem)s).Tag;
                            var document = Owner.DocumentWindow.Document;

                            var oldCode = script2.Code;

                            script2.Code = "class _Temp{\r\n}";

                            //activate flow graph window
                            var scriptDocumentWindow = EditorAPI.OpenDocumentWindowForObject(document, script2) as Component_CSharpScript_DocumentWindow;

                            Owner.DocumentWindow.SelectObjects(new object[] { script2 });

                            GetMethodInfo(subscribeTo, out var parameters, out var parametersSignature);

                            //get unique method name
                            string methodName;
                            string methodSignature;
                            {
                                var methodNameNotUnique = subscribeTo.Name.Replace(" ", "") + "_" + _event.Name;

                                for (int n = 1; ; n++)
                                {
                                    methodName = methodNameNotUnique;
                                    if (n != 1)
                                    {
                                        methodName += n.ToString();
                                    }
                                    methodSignature = $"method:{methodName}({parametersSignature})";

                                    bool found = false;
                                    if (script2.CompiledScript != null)
                                    {
                                        foreach (var m in script2.CompiledScript.Methods)
                                        {
                                            if (m.Name == methodName)
                                            {
                                                found = true;
                                            }
                                        }
                                    }
                                    if (!found)
                                    {
                                        break;
                                    }
                                    //if( subscribeTo.ParentRoot.MetadataGetMemberBySignature( methodSignature ) == null )
                                    //	break;
                                }
                            }

                            //GetMethodInfo( subscribeTo, out var parameters, out var methodName, out var methodSignature );

                            if (!scriptDocumentWindow.ScriptEditorControl.AddMethod(methodName, parameters, out var error))
                            {
                                Log.Warning("Unable to add a code of the method. " + error);
                                //!!!!
                            }

                            //set Code
                            try
                            {
                                scriptDocumentWindow.ScriptEditorControl.GetCode(out var code);

                                code = code.Replace("class _Temp{", "");

                                var index = code.LastIndexOf('}');
                                code      = code.Substring(0, index);

                                string newCode = "";
                                var lines      = code.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                                foreach (var line in lines)
                                {
                                    newCode += line.Trim() + "\r\n";
                                }

                                script2.Code = oldCode + "\r\n" + newCode;
                            }
                            catch (Exception e3)
                            {
                                Log.Warning("Unable to fix code of the method. " + e3.Message);
                                //!!!!
                            }

                            //create event handler
                            Component_EventHandler handler;
                            {
                                handler       = script2.CreateComponent <Component_EventHandler>(enabled: false);
                                handler.Name  = handler.BaseType.GetUserFriendlyNameForInstance() + " " + _event.Name;
                                handler.Event = ReferenceUtility.MakeReference <ReferenceValueType_Event>(null,
                                                                                                          ReferenceUtility.CalculateThisReference(handler, subscribeTo, _event.Signature));
                                handler.HandlerMethod = ReferenceUtility.MakeReference <ReferenceValueType_Method>(null,
                                                                                                                   ReferenceUtility.CalculateThisReference(handler, script2, methodSignature));
                                handler.Enabled = true;
                            }

                            //undo
                            {
                                var property = (Metadata.Property)script2.MetadataGetMemberBySignature("property:Code");
                                var undoItem = new UndoActionPropertiesChange.Item(script2, property, oldCode, new object[0]);
                                var action1  = new UndoActionPropertiesChange(new UndoActionPropertiesChange.Item[] { undoItem });

                                var action2 = new UndoActionComponentCreateDelete(document, new Component[] { handler }, true);

                                document.UndoSystem.CommitAction(new UndoMultiAction(new UndoSystem.Action[] { action1, action2 }));
                                document.Modified = true;
                            }
                        });
                        item.Tag = script;
                        childItems.Add(item);
                    }
                }

                groupItem.Items.Add(new KryptonContextMenuItems(childItems.ToArray()));
                items.Add(groupItem);
            }

            //Add Handler to Flow Graph
            {
                var groupItem  = new KryptonContextMenuItem(Translate("Add Handler to Flow Graph"), null);
                var childItems = new List <KryptonContextMenuItemBase>();

                //create new flow graph
                {
                    var itemsData = new List <(string, Component)>();
                    itemsData.Add((Translate("Add Flow Graph in This Component"), subscribeTo));
                    if (subscribeTo != subscribeTo.ParentRoot)
                    {
                        itemsData.Add((Translate("Add Flow Graph in the Root Component"), subscribeTo.ParentRoot));
                    }

                    foreach (var itemData in itemsData)
                    {
                        var childItem = new KryptonContextMenuItem(itemData.Item1, null, delegate(object s, EventArgs e2)
                        {
                            var parent = (Component)((KryptonContextMenuItem)s).Tag;

                            //create flow graph
                            var graph     = parent.CreateComponent <Component_FlowGraph>(enabled: false);
                            graph.Name    = graph.BaseType.GetUserFriendlyNameForInstance();
                            graph.Enabled = true;

                            //create node with handler
                            var node      = AddFlowGraphNode(graph, subscribeTo);
                            node.Position = new Vector2I(-20, -10);

                            //undo
                            var document = Owner.DocumentWindow.Document;
                            var action   = new UndoActionComponentCreateDelete(document, new Component[] { graph }, true);
                            document.UndoSystem.CommitAction(action);
                            document.Modified = true;

                            //activate flow graph window
                            EditorAPI.OpenDocumentWindowForObject(document, graph);
                        });
                        childItem.Tag = itemData.Item2;
                        childItems.Add(childItem);
                    }
                }

                //add handler to one of already created flow graph
                foreach (var graph in subscribeTo.ParentRoot.GetComponents <Component_FlowGraph>(false, true))
                {
                    if (graph.TypeSettingsIsPublic())
                    {
                        var text = string.Format(Translate("Add Handler to \'{0}\'"), graph.GetPathFromRoot(true));
                        var item = new KryptonContextMenuItem(text, null, delegate(object s, EventArgs e2)
                        {
                            var graph2 = (Component_FlowGraph)((KryptonContextMenuItem)s).Tag;

                            //create node with handler
                            var node = AddFlowGraphNode(graph2, subscribeTo);

                            //undo
                            var document = Owner.DocumentWindow.Document;
                            var action   = new UndoActionComponentCreateDelete(document, new Component[] { node }, true);
                            document.UndoSystem.CommitAction(action);
                            document.Modified = true;

                            //activate flow graph window
                            EditorAPI.OpenDocumentWindowForObject(document, graph2);
                        });
                        item.Tag = graph;
                        childItems.Add(item);
                    }
                }

                groupItem.Items.Add(new KryptonContextMenuItems(childItems.ToArray()));
                items.Add(groupItem);
            }

            ////add handler (component only)
            //{
            //	var item = new KryptonContextMenuItem( Translate( "Add handler (component only)" ), null, delegate ( object s, EventArgs e2 )
            //	{
            //		var newObjects = new List<Component>();

            //		var handler = subscribeTo.CreateComponent<Component_EventHandler>( enable: false );
            //		handler.Name = handler.BaseType.GetUserFriendlyNameForInstance() + " " + _event.Name;
            //		handler.Event = ReferenceUtility.MakeReference<ReferenceValueType_Event>( null,
            //			ReferenceUtility.CalculateThisReference( handler, subscribeTo, _event.Signature ) );
            //		handler.Enabled = true;
            //		newObjects.Add( handler );

            //		var document = Owner.DocumentWindow.Document;
            //		var action = new UndoActionComponentCreateDelete( document, newObjects, true );
            //		document.UndoSystem.CommitAction( action );
            //		document.Modified = true;

            //		Owner.DocumentWindow.SelectObjects( newObjects.ToArray() );
            //	} );
            //	item.Enabled = GetOneControlledObject<Component>() != null;
            //	items.Add( item );
            //}

            EditorContextMenu.Show(items, Owner);
        }
        public static void AddTransformToolToMenu(ICollection <KryptonContextMenuItemBase> items, TransformTool transformTool)
        //public static void AddTransformToolToMenu( ICollection<KryptonContextMenuItemBase> items, string workareaModeName )// TransformTool transformTool )
        {
            KryptonContextMenuItem item;
            string text;

            //Select
            text = Translate("Select");
            item = new KryptonContextMenuItem(text, null, delegate(object sender, EventArgs e)
            {
                EditorAPI.EditorActionClick(EditorAction.HolderEnum.ContextMenu, "Select");
            });
            item.Checked = transformTool.Mode == TransformTool.ModeEnum.None;
            //item.Checked = workareaModeName == "Transform Select";
            item.Image = EditorResourcesCache.Select;
            item.ShortcutKeyDisplayString = EditorActions.GetFirstShortcutKeyString("Select");
            items.Add(item);

            //Move & Rotate
            text = Translate("Move && Rotate");
            item = new KryptonContextMenuItem(text, null, delegate(object sender, EventArgs e)
            {
                EditorAPI.EditorActionClick(EditorAction.HolderEnum.ContextMenu, "Move & Rotate");
            });
            item.Checked = transformTool.Mode == TransformTool.ModeEnum.PositionRotation;
            //item.Checked = workareaModeName == "Transform Move";
            item.Image = EditorResourcesCache.MoveRotate;
            item.ShortcutKeyDisplayString = EditorActions.GetFirstShortcutKeyString("Move & Rotate");
            items.Add(item);

            //Move
            text = Translate("Move");
            item = new KryptonContextMenuItem(text, null, delegate(object sender, EventArgs e)
            {
                EditorAPI.EditorActionClick(EditorAction.HolderEnum.ContextMenu, "Move");
            });
            item.Checked = transformTool.Mode == TransformTool.ModeEnum.Position;
            //item.Checked = workareaModeName == "Transform Move";
            item.Image = EditorResourcesCache.Move;
            item.ShortcutKeyDisplayString = EditorActions.GetFirstShortcutKeyString("Move");
            items.Add(item);

            //Rotate
            text = Translate("Rotate");
            item = new KryptonContextMenuItem(text, null, delegate(object sender, EventArgs e)
            {
                EditorAPI.EditorActionClick(EditorAction.HolderEnum.ContextMenu, "Rotate");
            });
            item.Checked = transformTool.Mode == TransformTool.ModeEnum.Rotation;
            //item.Checked = workareaModeName == "Transform Rotate";
            item.Image = EditorResourcesCache.Rotate;
            item.ShortcutKeyDisplayString = EditorActions.GetFirstShortcutKeyString("Rotate");
            items.Add(item);

            //Scale
            text = Translate("Scale");
            item = new KryptonContextMenuItem(text, null, delegate(object sender, EventArgs e)
            {
                EditorAPI.EditorActionClick(EditorAction.HolderEnum.ContextMenu, "Scale");
            });
            item.Checked = transformTool.Mode == TransformTool.ModeEnum.Scale;
            //item.Checked = workareaModeName == "Transform Scale";
            item.Image = EditorResourcesCache.Scale;
            item.ShortcutKeyDisplayString = EditorActions.GetFirstShortcutKeyString("Scale");
            items.Add(item);
        }