diff --git a/DefaultProject/DefaultProject.asset b/DefaultProject/DefaultProject.asset index f6c5c5ec..82888190 100644 --- a/DefaultProject/DefaultProject.asset +++ b/DefaultProject/DefaultProject.asset @@ -17,9 +17,11 @@ MonoBehaviour: - {fileID: 11400000, guid: 9b99d76b166e6624396bcea5a92e1bb6, type: 2} - {fileID: 11400000, guid: 00ff4f68c9cfe334dbfd68bd08abaf79, type: 2} - {fileID: 11400000, guid: 9b4aa3018ad9a1b46ab8a5508d3723bf, type: 2} - - {fileID: 11400000, guid: ab97cadb355a9674a800485eaba4a470, type: 2} _projectNamespace: uFrame.DefaultProject _currentTabs: - _graphIdentifier: a0009eb1-7b60-4ef2-80cb-0bf2f4f2bd63 _graphName: GameSystem _path: [] + - _graphIdentifier: 0999f5c3-e70f-4e6b-bb6e-75bb39f8b16d + _graphName: uFrameStarter + _path: [] diff --git a/DefaultProject/GameSystem.asset b/DefaultProject/GameSystem.asset index 686f289b..3fb6dfcb 100644 --- a/DefaultProject/GameSystem.asset +++ b/DefaultProject/GameSystem.asset @@ -14,7 +14,7 @@ MonoBehaviour: _jsonData: '{"Name":"GameSystem", "Version":"1.501", "Identifier":"a0009eb1-7b60-4ef2-80cb-0bf2f4f2bd63", "Type":"Invert.uFrame.MVVM.SubsystemGraph", "DocumentationMode":"false", "RootNode":{"_CLRType":"Invert.uFrame.MVVM.SubsystemNode, Assembly-CSharp-Editor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", - "Name":"GameSystem", "IsCollapsed":"false", "Identifier":"eb64a2e9-c071-49b7-9ddb-bf1992faa690", + "Name":"GameSystem", "IsCollapsed":"true", "Identifier":"eb64a2e9-c071-49b7-9ddb-bf1992faa690", "Items":[ {"_CLRType":"Invert.uFrame.MVVM.InstancesReference, Assembly-CSharp-Editor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Name":"", "Identifier":"7b1dda30-3217-4e68-aff8-3452377229e4", "Precompiled":"false", "Flags":{"_CLRType":"true"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, @@ -33,9 +33,11 @@ MonoBehaviour: "c83b5c90-7344-4496-b5d2-52f4846e1b3d":"false", "d51fd9ac-89d7-4dcb-bca6-dca6486026ea":"false", "3ead6cbe-5fb8-4527-95d5-70f0d6cb5acc":"false", "977cb470-4686-4006-bc16-462491cae37e":"false", "f436167c-e3dd-4010-b513-7b8e6579a3b3":"false", "840597e4-0e15-47e9-a8f8-26c8c9ee5a81":"false", - "43ef0e91-5327-408a-975f-10eb31681b84":"false"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, - Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, - "IsNewNode":"false"}, "Nodes":[ {"_CLRType":"Invert.uFrame.MVVM.ServiceNode, Assembly-CSharp-Editor, + "43ef0e91-5327-408a-975f-10eb31681b84":"false", "6f503222-b654-46f1-bcf6-b82f0dfab2d2":"false", + "dae0181e-8ea7-4ccb-b5de-44108aa622e1":"false", "2c27cb98-8f9e-456c-ba90-a5eef4b239a9":"false"}, + "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, Invert.Core.GraphDesigner, + Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, "IsNewNode":"false"}, + "Nodes":[ {"_CLRType":"Invert.uFrame.MVVM.ServiceNode, Assembly-CSharp-Editor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Name":"GameService", "IsCollapsed":"false", "Identifier":"53b81896-54b6-4a17-88f0-5dc5269f16d2", "Items":[ {"_CLRType":"Invert.uFrame.MVVM.HandlersReference, Assembly-CSharp-Editor, Version=0.0.0.0, @@ -60,15 +62,16 @@ MonoBehaviour: "77bf8f91-4379-4193-8d8e-75667eea0867":"false", "c83b5c90-7344-4496-b5d2-52f4846e1b3d":"false", "d51fd9ac-89d7-4dcb-bca6-dca6486026ea":"false", "3ead6cbe-5fb8-4527-95d5-70f0d6cb5acc":"false", "977cb470-4686-4006-bc16-462491cae37e":"false", "f436167c-e3dd-4010-b513-7b8e6579a3b3":"false", - "840597e4-0e15-47e9-a8f8-26c8c9ee5a81":"false", "43ef0e91-5327-408a-975f-10eb31681b84":"false"}, - "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, Invert.Core.GraphDesigner, - Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, "IsNewNode":"false"}, - {"_CLRType":"Invert.uFrame.MVVM.ElementNode, Assembly-CSharp-Editor, Version=0.0.0.0, - Culture=neutral, PublicKeyToken=null", "Name":"LoadingScreen", "IsCollapsed":"false", - "Identifier":"694a4b0b-241e-4797-848b-5ad28d5c820e", "Items":[ {"_CLRType":"Invert.uFrame.MVVM.PropertiesChildItem, - Assembly-CSharp-Editor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", - "Name":"Progress", "Identifier":"7faf0d23-c56f-4d6d-9adc-4c0a52bfefd1", "Precompiled":"false", - "Flags":{"_CLRType":"true"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, + "840597e4-0e15-47e9-a8f8-26c8c9ee5a81":"false", "43ef0e91-5327-408a-975f-10eb31681b84":"false", + "6f503222-b654-46f1-bcf6-b82f0dfab2d2":"false", "dae0181e-8ea7-4ccb-b5de-44108aa622e1":"false", + "2c27cb98-8f9e-456c-ba90-a5eef4b239a9":"false"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, + Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, + "IsNewNode":"false"}, {"_CLRType":"Invert.uFrame.MVVM.ElementNode, Assembly-CSharp-Editor, + Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Name":"LoadingScreen", + "IsCollapsed":"false", "Identifier":"694a4b0b-241e-4797-848b-5ad28d5c820e", "Items":[ + {"_CLRType":"Invert.uFrame.MVVM.PropertiesChildItem, Assembly-CSharp-Editor, Version=0.0.0.0, + Culture=neutral, PublicKeyToken=null", "Name":"Progress", "Identifier":"7faf0d23-c56f-4d6d-9adc-4c0a52bfefd1", + "Precompiled":"false", "Flags":{"_CLRType":"true"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, "ItemType":"Single"}, {"_CLRType":"Invert.uFrame.MVVM.PropertiesChildItem, Assembly-CSharp-Editor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Name":"Message", "Identifier":"6da09090-7121-4cc1-bb5c-86c1b69578e0", @@ -78,15 +81,7 @@ MonoBehaviour: Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Name":"Active", "Identifier":"63079fd4-206a-4de7-83bb-35b38129071a", "Precompiled":"false", "Flags":{"_CLRType":"true"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, - "ItemType":"Boolean"}, {"_CLRType":"Invert.uFrame.MVVM.CollectionsChildItem, Assembly-CSharp-Editor, - Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Name":"fdsasdf", "Identifier":"6f503222-b654-46f1-bcf6-b82f0dfab2d2", - "Precompiled":"false", "Flags":{"_CLRType":"true"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, - Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, - "ItemType":""}, {"_CLRType":"Invert.uFrame.MVVM.CommandsChildItem, Assembly-CSharp-Editor, - Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Name":"fddd", "Identifier":"dae0181e-8ea7-4ccb-b5de-44108aa622e1", - "Precompiled":"false", "Flags":{"_CLRType":"true"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, - Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, - "ItemType":""} ], "CollapsedValues":{"727fb927-af5d-4f64-8cab-fa757222a7f8":"false", + "ItemType":"Boolean"} ], "CollapsedValues":{"727fb927-af5d-4f64-8cab-fa757222a7f8":"false", "5df11e5b-235b-4011-ad01-2322c69eddd2":"false", "38781701-8b4d-480a-932e-953fecb2bc25":"false", "2d5b57f5-f3c5-4b8e-a9fa-2adc3432ca71":"false", "78cd50e6-e0ce-4ead-aa92-6cc0c4261db1":"false", "5c87b6f9-b488-495c-9e31-011b18000cba":"false", "7451c5f1-9202-41ac-b077-16398cd663dd":"false", @@ -100,14 +95,16 @@ MonoBehaviour: "c83b5c90-7344-4496-b5d2-52f4846e1b3d":"false", "d51fd9ac-89d7-4dcb-bca6-dca6486026ea":"false", "3ead6cbe-5fb8-4527-95d5-70f0d6cb5acc":"false", "977cb470-4686-4006-bc16-462491cae37e":"false", "f436167c-e3dd-4010-b513-7b8e6579a3b3":"false", "840597e4-0e15-47e9-a8f8-26c8c9ee5a81":"false", - "43ef0e91-5327-408a-975f-10eb31681b84":"false"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, - Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, - "IsNewNode":"false"}, {"_CLRType":"Invert.uFrame.MVVM.ViewNode, Assembly-CSharp-Editor, - Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Name":"LoadingScreenView", - "IsCollapsed":"false", "Identifier":"5df11e5b-235b-4011-ad01-2322c69eddd2", "Items":[ - {"_CLRType":"Invert.uFrame.MVVM.BindingsReference, Assembly-CSharp-Editor, Version=0.0.0.0, - Culture=neutral, PublicKeyToken=null", "Name":"MessageToText", "Identifier":"4ba00982-aac6-475d-ac2a-676b3967232e", - "Precompiled":"false", "Flags":{"_CLRType":"true"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, + "43ef0e91-5327-408a-975f-10eb31681b84":"false", "6f503222-b654-46f1-bcf6-b82f0dfab2d2":"false", + "dae0181e-8ea7-4ccb-b5de-44108aa622e1":"false", "2c27cb98-8f9e-456c-ba90-a5eef4b239a9":"false"}, + "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, Invert.Core.GraphDesigner, + Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, "IsNewNode":"false"}, + {"_CLRType":"Invert.uFrame.MVVM.ViewNode, Assembly-CSharp-Editor, Version=0.0.0.0, + Culture=neutral, PublicKeyToken=null", "Name":"LoadingScreenView", "IsCollapsed":"false", + "Identifier":"5df11e5b-235b-4011-ad01-2322c69eddd2", "Items":[ {"_CLRType":"Invert.uFrame.MVVM.BindingsReference, + Assembly-CSharp-Editor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", + "Name":"MessageToText", "Identifier":"4ba00982-aac6-475d-ac2a-676b3967232e", "Precompiled":"false", + "Flags":{"_CLRType":"true"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, "BindingName":"BindTextToProperty", "SourceIdentifier":"6da09090-7121-4cc1-bb5c-86c1b69578e0"}, {"_CLRType":"Invert.uFrame.MVVM.BindingsReference, Assembly-CSharp-Editor, Version=0.0.0.0, @@ -125,48 +122,52 @@ MonoBehaviour: "c83b5c90-7344-4496-b5d2-52f4846e1b3d":"false", "d51fd9ac-89d7-4dcb-bca6-dca6486026ea":"false", "3ead6cbe-5fb8-4527-95d5-70f0d6cb5acc":"false", "977cb470-4686-4006-bc16-462491cae37e":"false", "f436167c-e3dd-4010-b513-7b8e6579a3b3":"false", "840597e4-0e15-47e9-a8f8-26c8c9ee5a81":"false", - "43ef0e91-5327-408a-975f-10eb31681b84":"false"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, - Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, - "ScenePropertiesInputSlot":{"_CLRType":"Invert.uFrame.MVVM.SceneProperties, Assembly-CSharp-Editor, - Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Name":"SceneProperties", - "Identifier":"17f8f2b5-72bc-46d8-8f67-7f3ba4bb477c", "Precompiled":"false", "Flags":{"_CLRType":"true"}, + "43ef0e91-5327-408a-975f-10eb31681b84":"false", "6f503222-b654-46f1-bcf6-b82f0dfab2d2":"false", + "dae0181e-8ea7-4ccb-b5de-44108aa622e1":"false", "2c27cb98-8f9e-456c-ba90-a5eef4b239a9":"false"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, Invert.Core.GraphDesigner, - Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}}, "ElementInputSlot":{"_CLRType":"Invert.uFrame.MVVM.Element, + Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, "ScenePropertiesInputSlot":{"_CLRType":"Invert.uFrame.MVVM.SceneProperties, Assembly-CSharp-Editor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", - "Name":"Element", "Identifier":"f8c3390e-5637-4503-81d8-67ad8aefd9d7", "Precompiled":"false", - "Flags":{"_CLRType":"true"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, + "Name":"SceneProperties", "Identifier":"17f8f2b5-72bc-46d8-8f67-7f3ba4bb477c", + "Precompiled":"false", "Flags":{"_CLRType":"true"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, + Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}}, + "ElementInputSlot":{"_CLRType":"Invert.uFrame.MVVM.Element, Assembly-CSharp-Editor, + Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Name":"Element", "Identifier":"f8c3390e-5637-4503-81d8-67ad8aefd9d7", + "Precompiled":"false", "Flags":{"_CLRType":"true"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}}, "IsNewNode":"false"}, {"_CLRType":"Invert.uFrame.MVVM.SimpleClassNode, Assembly-CSharp-Editor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Name":"BeginGameCommand", - "IsCollapsed":"false", "Identifier":"03317d58-0095-406e-a859-b4fbe99b63e0", "Items":[ ], - "CollapsedValues":{}, "Flags":{"_CLRType":"true", "77bf8f91-4379-4193-8d8e-75667eea0867":"false", + "IsCollapsed":"false", "Identifier":"03317d58-0095-406e-a859-b4fbe99b63e0", "Items":[ + {"_CLRType":"Invert.uFrame.MVVM.PropertiesChildItem, Assembly-CSharp-Editor, Version=0.0.0.0, + Culture=neutral, PublicKeyToken=null", "Name":"Properties", "Identifier":"aebd51eb-48a0-4d3c-9372-3b0b7353e480", + "Precompiled":"false", "Flags":{"_CLRType":"true"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, + Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, + "ItemType":""} ], "CollapsedValues":{}, "Flags":{"_CLRType":"true", "77bf8f91-4379-4193-8d8e-75667eea0867":"false", "c83b5c90-7344-4496-b5d2-52f4846e1b3d":"false", "d51fd9ac-89d7-4dcb-bca6-dca6486026ea":"false", "3ead6cbe-5fb8-4527-95d5-70f0d6cb5acc":"false", "977cb470-4686-4006-bc16-462491cae37e":"false", "f436167c-e3dd-4010-b513-7b8e6579a3b3":"false", "840597e4-0e15-47e9-a8f8-26c8c9ee5a81":"false", - "43ef0e91-5327-408a-975f-10eb31681b84":"false"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, - Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, - "IsNewNode":"true"} ], "ConnectedItems":[ {"_CLRType":"ConnectionData, Invert.Core.GraphDesigner, + "43ef0e91-5327-408a-975f-10eb31681b84":"false", "6f503222-b654-46f1-bcf6-b82f0dfab2d2":"false", + "dae0181e-8ea7-4ccb-b5de-44108aa622e1":"false", "2c27cb98-8f9e-456c-ba90-a5eef4b239a9":"false"}, + "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, Invert.Core.GraphDesigner, + Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, "IsNewNode":"false"} + ], "ConnectedItems":[ {"_CLRType":"ConnectionData, Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null", "OutputIdentifier":"694a4b0b-241e-4797-848b-5ad28d5c820e", "InputIdentifier":"f8c3390e-5637-4503-81d8-67ad8aefd9d7"} ], "PositionData":{"_CLRType":"FilterPositionData, Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null", "eb64a2e9-c071-49b7-9ddb-bf1992faa690":{"eb64a2e9-c071-49b7-9ddb-bf1992faa690":{"x":"100", "y":"50"}, "53b81896-54b6-4a17-88f0-5dc5269f16d2":{"x":"100", "y":"250"}, "694a4b0b-241e-4797-848b-5ad28d5c820e":{"x":"540", - "y":"140"}, "03317d58-0095-406e-a859-b4fbe99b63e0":{"x":"300", "y":"250"}}, "53b81896-54b6-4a17-88f0-5dc5269f16d2":{"53b81896-54b6-4a17-88f0-5dc5269f16d2":{"x":"90", + "y":"140"}, "03317d58-0095-406e-a859-b4fbe99b63e0":{"x":"300", "y":"260"}}, "53b81896-54b6-4a17-88f0-5dc5269f16d2":{"53b81896-54b6-4a17-88f0-5dc5269f16d2":{"x":"90", "y":"230"}}, "694a4b0b-241e-4797-848b-5ad28d5c820e":{"694a4b0b-241e-4797-848b-5ad28d5c820e":{"x":"140", "y":"140"}, "5df11e5b-235b-4011-ad01-2322c69eddd2":{"x":"430", "y":"200"}}}, "FilterState":{"_CLRType":"FilterState, Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null", - "FilterStack":[ "694a4b0b-241e-4797-848b-5ad28d5c820e" ]}, "Settings":{"_CLRType":"ElementDiagramSettings, + "FilterStack":[ ]}, "Settings":{"_CLRType":"ElementDiagramSettings, Invert.Core.GraphDesigner, + Version=1.1.0.0, Culture=neutral, PublicKeyToken=null", "CodeGenDisabled":"false", + "SnapSize":"10", "Snap":"true", "CodePathStrategyName":"Default", "GridLinesColor":{"r":"0.271", + "g":"0.271", "b":"0.271", "a":"1"}, "GridLinesColorSecondary":{"r":"0.169", "g":"0.169", + "b":"0.169", "a":"1"}, "AssociationLinkColor":{"r":"1", "g":"1", "b":"1", "a":"1"}, + "DefinitionLinkColor":{"r":"0", "g":"1", "b":"1", "a":"1"}, "InheritanceLinkColor":{"r":"0", + "g":"1", "b":"0", "a":"1"}, "SceneManagerLinkColor":{"r":"0.5", "g":"0.5", "b":"0.5", + "a":"1"}, "SubSystemLinkColor":{"r":"0.5", "g":"0.5", "b":"0.5", "a":"1"}, "TransitionLinkColor":{"r":"1", + "g":"0.9215686", "b":"0.01568628", "a":"1"}, "ViewLinkColor":{"r":"0", "g":"0", + "b":"1", "a":"1"}, "RootNamespace":""}, "Changes":[ {"_CLRType":"Invert.Core.GraphDesigner.GraphItemAdded, Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null", - "CodeGenDisabled":"false", "SnapSize":"10", "Snap":"true", "CodePathStrategyName":"Default", - "GridLinesColor":{"r":"0.271", "g":"0.271", "b":"0.271", "a":"1"}, "GridLinesColorSecondary":{"r":"0.169", - "g":"0.169", "b":"0.169", "a":"1"}, "AssociationLinkColor":{"r":"1", "g":"1", - "b":"1", "a":"1"}, "DefinitionLinkColor":{"r":"0", "g":"1", "b":"1", "a":"1"}, - "InheritanceLinkColor":{"r":"0", "g":"1", "b":"0", "a":"1"}, "SceneManagerLinkColor":{"r":"0.5", - "g":"0.5", "b":"0.5", "a":"1"}, "SubSystemLinkColor":{"r":"0.5", "g":"0.5", "b":"0.5", - "a":"1"}, "TransitionLinkColor":{"r":"1", "g":"0.9215686", "b":"0.01568628", "a":"1"}, - "ViewLinkColor":{"r":"0", "g":"0", "b":"1", "a":"1"}, "RootNamespace":""}, "Changes":[ - {"_CLRType":"Invert.Core.GraphDesigner.GraphItemAdded, Invert.Core.GraphDesigner, - Version=1.1.0.0, Culture=neutral, PublicKeyToken=null", "ItemIdentifier":"6f503222-b654-46f1-bcf6-b82f0dfab2d2"}, - {"_CLRType":"Invert.Core.GraphDesigner.GraphItemAdded, Invert.Core.GraphDesigner, - Version=1.1.0.0, Culture=neutral, PublicKeyToken=null", "ItemIdentifier":"dae0181e-8ea7-4ccb-b5de-44108aa622e1"} - ]}' + "ItemIdentifier":"aebd51eb-48a0-4d3c-9372-3b0b7353e480"} ]}' diff --git a/DefaultProject/GameSystem/Commands.designer.cs b/DefaultProject/GameSystem/Commands.designer.cs new file mode 100644 index 00000000..c89a4d9a --- /dev/null +++ b/DefaultProject/GameSystem/Commands.designer.cs @@ -0,0 +1,22 @@ +// ------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Mono Runtime Version: 2.0.50727.1433 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +// ------------------------------------------------------------------------------ + +using uFrame.MVVM; + +namespace uFrame.DefaultProject { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + + + public partial class fdddCommand : ViewModelCommand { + } +} diff --git a/Editor/Templates/SceneManagerTemplate.cs.meta b/DefaultProject/GameSystem/Commands.designer.cs.meta similarity index 53% rename from Editor/Templates/SceneManagerTemplate.cs.meta rename to DefaultProject/GameSystem/Commands.designer.cs.meta index f2cc681f..3d484a9a 100644 --- a/Editor/Templates/SceneManagerTemplate.cs.meta +++ b/DefaultProject/GameSystem/Commands.designer.cs.meta @@ -1,8 +1,12 @@ fileFormatVersion: 2 -guid: 390e6123cf504ed41abd0fca84d849e2 +guid: daecbbb69a78eae45a56a923499d78f7 +timeCreated: 1433010056 +licenseType: Pro MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: + assetBundleName: + assetBundleVariant: diff --git a/DefaultProject/GameSystem/Controllers.designer.cs b/DefaultProject/GameSystem/Controllers.designer.cs index 8033acde..e68d9c11 100644 --- a/DefaultProject/GameSystem/Controllers.designer.cs +++ b/DefaultProject/GameSystem/Controllers.designer.cs @@ -8,6 +8,9 @@ // // ------------------------------------------------------------------------------ +using uFrame.IOC; +using uFrame.MVVM; + namespace uFrame.DefaultProject { using System; using System.Collections; @@ -20,7 +23,9 @@ public class LoadingScreenControllerBase : Controller { private IViewModelManager _LoadingScreenViewModelManager; - [InjectAttribute("LoadingScreen")] + private LoadingScreenViewModel _LoadingScreen; + + [Inject("LoadingScreen")] public IViewModelManager LoadingScreenViewModelManager { get { return _LoadingScreenViewModelManager; @@ -30,7 +35,17 @@ public IViewModelManager LoadingScreenViewModelManager { } } - public System.Collections.Generic.IEnumerable LoadingScreenViewModels { + [InjectAttribute("LoadingScreen")] + public LoadingScreenViewModel LoadingScreen { + get { + return _LoadingScreen; + } + set { + _LoadingScreen = value; + } + } + + public IEnumerable LoadingScreenViewModels { get { return LoadingScreenViewModelManager.OfType(); } diff --git a/DefaultProject/GameSystem/Services.designer.cs b/DefaultProject/GameSystem/Services.designer.cs index 9e65d0e3..39fa3898 100644 --- a/DefaultProject/GameSystem/Services.designer.cs +++ b/DefaultProject/GameSystem/Services.designer.cs @@ -8,6 +8,8 @@ // // ------------------------------------------------------------------------------ +using uFrame.Kernel; + namespace uFrame.DefaultProject { using System; using System.Collections; diff --git a/DefaultProject/GameSystem/Services/GameService.cs b/DefaultProject/GameSystem/Services/GameService.cs index f6013098..0d290a98 100644 --- a/DefaultProject/GameSystem/Services/GameService.cs +++ b/DefaultProject/GameSystem/Services/GameService.cs @@ -1,3 +1,6 @@ +using uFrame.IOC; +using uFrame.Kernel; + namespace uFrame.DefaultProject { using System; using System.Collections; diff --git a/DefaultProject/GameSystem/SystemLoaders.designer.cs b/DefaultProject/GameSystem/SystemLoaders.designer.cs index 7763f85d..867c2a0a 100644 --- a/DefaultProject/GameSystem/SystemLoaders.designer.cs +++ b/DefaultProject/GameSystem/SystemLoaders.designer.cs @@ -8,6 +8,10 @@ // // ------------------------------------------------------------------------------ +using uFrame.IOC; +using uFrame.Kernel; +using uFrame.MVVM; + namespace uFrame.DefaultProject { using System; using System.Collections; @@ -22,11 +26,11 @@ public class GameSystemLoaderBase : SystemLoader { private LoadingScreenController _LoadingScreenController; - [InjectAttribute("LoadingScreen")] + [Inject("LoadingScreen")] public virtual LoadingScreenViewModel LoadingScreen { get { if (this._LoadingScreen == null) { - this._LoadingScreen = this.CreateInstanceViewModel( "LoadingScreen"); + this._LoadingScreen = this.CreateViewModel( "LoadingScreen"); } return _LoadingScreen; } @@ -52,6 +56,5 @@ public override void Load() { Container.RegisterController(LoadingScreenController); Container.RegisterViewModel(LoadingScreen, "LoadingScreen"); } - } } diff --git a/DefaultProject/GameSystem/ViewModels.designer.cs b/DefaultProject/GameSystem/ViewModels.designer.cs index 4d2164d6..aeb9cdf4 100644 --- a/DefaultProject/GameSystem/ViewModels.designer.cs +++ b/DefaultProject/GameSystem/ViewModels.designer.cs @@ -8,6 +8,9 @@ // // ------------------------------------------------------------------------------ +using uFrame.Kernel; +using uFrame.MVVM; + namespace uFrame.DefaultProject { using System; using System.Collections; diff --git a/DefaultProject/GameSystem/Views.designer.cs b/DefaultProject/GameSystem/Views.designer.cs index 43e8387a..88ad38ae 100644 --- a/DefaultProject/GameSystem/Views.designer.cs +++ b/DefaultProject/GameSystem/Views.designer.cs @@ -8,108 +8,95 @@ // // ------------------------------------------------------------------------------ -namespace uFrame.DefaultProject { +using uFrame.MVVM; +using uFrame.MVVM.Bindings; + +namespace uFrame.DefaultProject +{ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UniRx; using UnityEngine; - - - public class LoadingScreenViewBase : ViewBase { - - [UnityEngine.SerializeField()] - [UFGroup("View Model Properties")] - [UnityEngine.HideInInspector()] - public Single _Progress; - - [UnityEngine.SerializeField()] - [UFGroup("View Model Properties")] - [UnityEngine.HideInInspector()] - public String _Message; - - [UnityEngine.SerializeField()] - [UFGroup("View Model Properties")] - [UnityEngine.HideInInspector()] - public Boolean _Active; - - [UFToggleGroup("Message")] - [UnityEngine.HideInInspector()] - public bool _BindMessage = true; - - [UFGroup("Message")] - [UnityEngine.SerializeField()] - [UnityEngine.HideInInspector()] - [UnityEngine.Serialization.FormerlySerializedAsAttribute("_Messageinput")] - protected UnityEngine.UI.Text _MessageInput; - - [UFToggleGroup("Progress")] - [UnityEngine.HideInInspector()] - public bool _BindProgress = true; - - [UFGroup("Progress")] - [UnityEngine.SerializeField()] - [UnityEngine.HideInInspector()] - [UnityEngine.Serialization.FormerlySerializedAsAttribute("_Progressslider")] - protected UnityEngine.UI.Slider _ProgressSlider; - - [UFToggleGroup("Active")] - [UnityEngine.HideInInspector()] - public bool _BindActive = true; - - [UFGroup("Active")] - [UnityEngine.SerializeField()] - [UnityEngine.HideInInspector()] - [UnityEngine.Serialization.FormerlySerializedAsAttribute("_ActiveonlyWhenChanged")] - protected bool _ActiveOnlyWhenChanged; - - public override string DefaultIdentifier { - get { - return "LoadingScreen"; + + public class LoadingScreenViewBase : ViewBase + { + + [UnityEngine.SerializeField()] [UFGroup("View Model Properties")] [UnityEngine.HideInInspector()] public + Single _Progress; + + [UnityEngine.SerializeField()] [UFGroup("View Model Properties")] [UnityEngine.HideInInspector()] public + String _Message; + + [UnityEngine.SerializeField()] [UFGroup("View Model Properties")] [UnityEngine.HideInInspector()] public + Boolean _Active; + + [UFToggleGroup("Message")] [UnityEngine.HideInInspector()] public bool _BindMessage = true; + + [UFGroup("Message")] [UnityEngine.SerializeField()] [UnityEngine.HideInInspector()] [UnityEngine.Serialization.FormerlySerializedAsAttribute("_Messageinput")] protected UnityEngine.UI.Text + _MessageInput; + + [UFToggleGroup("Progress")] [UnityEngine.HideInInspector()] public bool _BindProgress = true; + + [UFGroup("Progress")] [UnityEngine.SerializeField()] [UnityEngine.HideInInspector()] [UnityEngine.Serialization.FormerlySerializedAsAttribute("_Progressslider")] protected UnityEngine.UI.Slider + _ProgressSlider; + + [UFToggleGroup("Active")] [UnityEngine.HideInInspector()] public bool _BindActive = true; + + [UFGroup("Active")] [UnityEngine.SerializeField()] [UnityEngine.HideInInspector()] [UnityEngine.Serialization.FormerlySerializedAsAttribute("_ActiveonlyWhenChanged")] protected bool + _ActiveOnlyWhenChanged; + + public override string DefaultIdentifier + { + get { return "LoadingScreen"; } } - } - - public override System.Type ViewModelType { - get { - return typeof(LoadingScreenViewModel); + + public override System.Type ViewModelType + { + get { return typeof (LoadingScreenViewModel); } } - } - - public LoadingScreenViewModel LoadingScreen { - get { - return (LoadingScreenViewModel)ViewModelObject; + + public LoadingScreenViewModel LoadingScreen + { + get { return (LoadingScreenViewModel) ViewModelObject; } } - } - - protected override void InitializeViewModel(ViewModel model) { - base.InitializeViewModel(model); - // NOTE: this method is only invoked if the 'Initialize ViewModel' is checked in the inspector. - // var vm = model as LoadingScreenViewModel; - // This method is invoked when applying the data from the inspector to the viewmodel. Add any view-specific customizations here. - var loadingscreenview = ((LoadingScreenViewModel)model); - loadingscreenview.Progress = this._Progress; - loadingscreenview.Message = this._Message; - loadingscreenview.Active = this._Active; - } - - public override void Bind() { - base.Bind(); - // Use this.LoadingScreen to access the viewmodel. - // Use this method to subscribe to the view-model. - // Any designer bindings are created in the base implementation. - if (_BindMessage) { - this.BindTextToProperty(_MessageInput, this.LoadingScreen.MessageProperty); + + protected override void InitializeViewModel(ViewModel model) + { + base.InitializeViewModel(model); + // NOTE: this method is only invoked if the 'Initialize ViewModel' is checked in the inspector. + // var vm = model as LoadingScreenViewModel; + // This method is invoked when applying the data from the inspector to the viewmodel. Add any view-specific customizations here. + var loadingscreenview = ((LoadingScreenViewModel) model); + loadingscreenview.Progress = this._Progress; + loadingscreenview.Message = this._Message; + loadingscreenview.Active = this._Active; } - if (_BindProgress) { - this.BindSliderToProperty(_ProgressSlider, this.LoadingScreen.ProgressProperty); + + public override void Bind() + { + base.Bind(); + // Use this.LoadingScreen to access the viewmodel. + // Use this method to subscribe to the view-model. + // Any designer bindings are created in the base implementation. + if (_BindMessage) + { + this.BindTextToProperty(_MessageInput, this.LoadingScreen.MessageProperty); + } + if (_BindProgress) + { + this.BindSliderToProperty(_ProgressSlider, this.LoadingScreen.ProgressProperty); + } + if (_BindActive) + { + this.BindProperty(this.LoadingScreen.ActiveProperty, this.ActiveChanged, _ActiveOnlyWhenChanged); + } } - if (_BindActive) { - this.BindProperty(this.LoadingScreen.ActiveProperty, this.ActiveChanged, _ActiveOnlyWhenChanged); + + public virtual void ActiveChanged(Boolean arg1) + { } } - - public virtual void ActiveChanged(Boolean arg1) { - } - } -} + +} \ No newline at end of file diff --git a/DefaultProject/GameSystem/Views/LoadingScreenView.cs b/DefaultProject/GameSystem/Views/LoadingScreenView.cs index 950a4f94..335c9d43 100644 --- a/DefaultProject/GameSystem/Views/LoadingScreenView.cs +++ b/DefaultProject/GameSystem/Views/LoadingScreenView.cs @@ -1,3 +1,5 @@ +using uFrame.MVVM; + namespace uFrame.DefaultProject { using System; diff --git a/DefaultProject/MainMenuSystem/Commands.designer.cs b/DefaultProject/MainMenuSystem/Commands.designer.cs index 0163b09c..fec06fb0 100644 --- a/DefaultProject/MainMenuSystem/Commands.designer.cs +++ b/DefaultProject/MainMenuSystem/Commands.designer.cs @@ -8,6 +8,8 @@ // // ------------------------------------------------------------------------------ +using uFrame.MVVM; + namespace uFrame.DefaultProject { using System; using System.Collections; diff --git a/DefaultProject/MainMenuSystem/Controllers.designer.cs b/DefaultProject/MainMenuSystem/Controllers.designer.cs index 95cf8d52..d79acef7 100644 --- a/DefaultProject/MainMenuSystem/Controllers.designer.cs +++ b/DefaultProject/MainMenuSystem/Controllers.designer.cs @@ -8,6 +8,9 @@ // // ------------------------------------------------------------------------------ +using uFrame.IOC; +using uFrame.MVVM; + namespace uFrame.DefaultProject { using System; using System.Collections; @@ -22,7 +25,7 @@ public class MainMenuScreenControllerBase : Controller { private MainMenuScreenViewModel _MainMenuScreen; - [InjectAttribute("MainMenuScreen")] + [Inject("MainMenuScreen")] public IViewModelManager MainMenuScreenViewModelManager { get { return _MainMenuScreenViewModelManager; @@ -42,7 +45,7 @@ public MainMenuScreenViewModel MainMenuScreen { } } - public System.Collections.Generic.IEnumerable MainMenuScreenViewModels { + public IEnumerable MainMenuScreenViewModels { get { return MainMenuScreenViewModelManager.OfType(); } diff --git a/DefaultProject/MainMenuSystem/SystemLoaders.designer.cs b/DefaultProject/MainMenuSystem/SystemLoaders.designer.cs index fb081456..49539521 100644 --- a/DefaultProject/MainMenuSystem/SystemLoaders.designer.cs +++ b/DefaultProject/MainMenuSystem/SystemLoaders.designer.cs @@ -8,6 +8,10 @@ // // ------------------------------------------------------------------------------ +using uFrame.IOC; +using uFrame.Kernel; +using uFrame.MVVM; + namespace uFrame.DefaultProject { using System; using System.Collections; @@ -22,11 +26,11 @@ public class MainMenuSystemLoaderBase : SystemLoader { private MainMenuScreenController _MainMenuScreenController; - [InjectAttribute("MainMenuScreen")] + [Inject("MainMenuScreen")] public virtual MainMenuScreenViewModel MainMenuScreen { get { if (this._MainMenuScreen == null) { - this._MainMenuScreen = CreateInstanceViewModel( "MainMenuScreen"); + this._MainMenuScreen = this.CreateViewModel( "MainMenuScreen"); } return _MainMenuScreen; } diff --git a/DefaultProject/MainMenuSystem/ViewModels.designer.cs b/DefaultProject/MainMenuSystem/ViewModels.designer.cs index 02aec568..77483c9f 100644 --- a/DefaultProject/MainMenuSystem/ViewModels.designer.cs +++ b/DefaultProject/MainMenuSystem/ViewModels.designer.cs @@ -8,6 +8,9 @@ // // ------------------------------------------------------------------------------ +using uFrame.Kernel; +using uFrame.MVVM; + namespace uFrame.DefaultProject { using System; using System.Collections; diff --git a/DefaultProject/MainMenuSystem/Views.designer.cs b/DefaultProject/MainMenuSystem/Views.designer.cs index 1aec7330..e54697b9 100644 --- a/DefaultProject/MainMenuSystem/Views.designer.cs +++ b/DefaultProject/MainMenuSystem/Views.designer.cs @@ -8,6 +8,9 @@ // // ------------------------------------------------------------------------------ +using uFrame.MVVM; +using uFrame.MVVM.Bindings; + namespace uFrame.DefaultProject { using System; using System.Collections; diff --git a/DefaultProject/MainMenuSystem/Views/MainMenuScreenView.cs b/DefaultProject/MainMenuSystem/Views/MainMenuScreenView.cs index 8e33b19d..25860b06 100644 --- a/DefaultProject/MainMenuSystem/Views/MainMenuScreenView.cs +++ b/DefaultProject/MainMenuSystem/Views/MainMenuScreenView.cs @@ -1,3 +1,5 @@ +using uFrame.MVVM; + namespace uFrame.DefaultProject { using System; using System.Collections; diff --git a/DefaultProject/NewUnityGraphData 1.asset b/DefaultProject/NewUnityGraphData 1.asset deleted file mode 100644 index 03dc396c..00000000 --- a/DefaultProject/NewUnityGraphData 1.asset +++ /dev/null @@ -1,33 +0,0 @@ -%YAML 1.1 -%TAG !u! tag:unity3d.com,2011: ---- !u!114 &11400000 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_PrefabParentObject: {fileID: 0} - m_PrefabInternal: {fileID: 0} - m_GameObject: {fileID: 0} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: -1328937199, guid: 019118f6de8965947b2d943bbe59c84b, type: 3} - m_Name: NewUnityGraphData 1 - m_EditorClassIdentifier: - _jsonData: '{"Name":"NewUnityGraphData 1", "Version":"1.501", "Identifier":"ff92cba9-7f72-49db-a0f9-bc29f2472a30", - "Type":"Invert.uFrame.MVVM.SubsystemGraph", "DocumentationMode":"false", "RootNode":{"_CLRType":"Invert.uFrame.MVVM.SubsystemNode, - Assembly-CSharp-Editor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", - "Name":"", "IsCollapsed":"false", "Identifier":"", "Items":[ ], "CollapsedValues":{}, - "Flags":{"_CLRType":"Invert.Core.GraphDesigner.FlagsDictionary, Invert.Core.GraphDesigner, - Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, - Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, - "IsNewNode":"true"}, "Nodes":[ ], "ConnectedItems":[ ], "PositionData":{"_CLRType":"FilterPositionData, - Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, - "FilterState":{"_CLRType":"FilterState, Invert.Core.GraphDesigner, Version=1.1.0.0, - Culture=neutral, PublicKeyToken=null", "FilterStack":[ ]}, "Settings":{"_CLRType":"ElementDiagramSettings, - Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null", - "CodeGenDisabled":"false", "SnapSize":"10", "Snap":"true", "CodePathStrategyName":"Default", - "GridLinesColor":{"r":"0.271", "g":"0.271", "b":"0.271", "a":"1"}, "GridLinesColorSecondary":{"r":"0.169", - "g":"0.169", "b":"0.169", "a":"1"}, "AssociationLinkColor":{"r":"1", "g":"1", - "b":"1", "a":"1"}, "DefinitionLinkColor":{"r":"0", "g":"1", "b":"1", "a":"1"}, - "InheritanceLinkColor":{"r":"0", "g":"1", "b":"0", "a":"1"}, "SceneManagerLinkColor":{"r":"0.5", - "g":"0.5", "b":"0.5", "a":"1"}, "SubSystemLinkColor":{"r":"0.5", "g":"0.5", "b":"0.5", - "a":"1"}, "TransitionLinkColor":{"r":"1", "g":"0.9215686", "b":"0.01568628", "a":"1"}, - "ViewLinkColor":{"r":"0", "g":"0", "b":"1", "a":"1"}, "RootNamespace":""}, "Changes":[ ]}' diff --git a/DefaultProject/NewUnityGraphData 1.asset.meta b/DefaultProject/NewUnityGraphData 1.asset.meta deleted file mode 100644 index 658bf6d4..00000000 --- a/DefaultProject/NewUnityGraphData 1.asset.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: ab97cadb355a9674a800485eaba4a470 -timeCreated: 1432970381 -licenseType: Pro -NativeFormatImporter: - userData: - assetBundleName: - assetBundleVariant: diff --git a/DefaultProject/NewUnityGraphData 1.meta b/DefaultProject/NewUnityGraphData 1.meta new file mode 100644 index 00000000..dcb6035c --- /dev/null +++ b/DefaultProject/NewUnityGraphData 1.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: f81fec7eabb7ff547b9a992551d8edd7 +folderAsset: yes +timeCreated: 1433010055 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/DefaultProject/NewUnityGraphData 1/SystemLoaders.designer.cs b/DefaultProject/NewUnityGraphData 1/SystemLoaders.designer.cs new file mode 100644 index 00000000..1486103f --- /dev/null +++ b/DefaultProject/NewUnityGraphData 1/SystemLoaders.designer.cs @@ -0,0 +1,25 @@ +// ------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Mono Runtime Version: 2.0.50727.1433 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +// ------------------------------------------------------------------------------ + +using uFrame.Kernel; + +namespace uFrame.DefaultProject { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + + + public class NewUnityGraphData1LoaderBase : SystemLoader { + + public override void Load() { + } + } +} diff --git a/MVVM/Views/Bindings/EventBinding.cs.meta b/DefaultProject/NewUnityGraphData 1/SystemLoaders.designer.cs.meta similarity index 53% rename from MVVM/Views/Bindings/EventBinding.cs.meta rename to DefaultProject/NewUnityGraphData 1/SystemLoaders.designer.cs.meta index 40c31254..780b77ef 100644 --- a/MVVM/Views/Bindings/EventBinding.cs.meta +++ b/DefaultProject/NewUnityGraphData 1/SystemLoaders.designer.cs.meta @@ -1,8 +1,12 @@ fileFormatVersion: 2 -guid: c6702d49e06f3764896441a569980db0 +guid: 5222a730f2cd029498e5f871eb1a58e1 +timeCreated: 1433010055 +licenseType: Pro MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: + assetBundleName: + assetBundleVariant: diff --git a/DefaultProject/NewUnityGraphData 1/SystemLoaders.meta b/DefaultProject/NewUnityGraphData 1/SystemLoaders.meta new file mode 100644 index 00000000..c14c129d --- /dev/null +++ b/DefaultProject/NewUnityGraphData 1/SystemLoaders.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 95b0b6a223dccff48aa647639d1be2ba +folderAsset: yes +timeCreated: 1433010055 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/DefaultProject/NewUnityGraphData 1/SystemLoaders/NewUnityGraphData1Loader.cs b/DefaultProject/NewUnityGraphData 1/SystemLoaders/NewUnityGraphData1Loader.cs new file mode 100644 index 00000000..0b550d64 --- /dev/null +++ b/DefaultProject/NewUnityGraphData 1/SystemLoaders/NewUnityGraphData1Loader.cs @@ -0,0 +1,14 @@ +namespace uFrame.DefaultProject { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + + + public class NewUnityGraphData1Loader : NewUnityGraphData1LoaderBase { + + public override void Load() { + base.Load(); + } + } +} diff --git a/Editor/Templates/SceneManagerSettingsTemplate.cs.meta b/DefaultProject/NewUnityGraphData 1/SystemLoaders/NewUnityGraphData1Loader.cs.meta similarity index 53% rename from Editor/Templates/SceneManagerSettingsTemplate.cs.meta rename to DefaultProject/NewUnityGraphData 1/SystemLoaders/NewUnityGraphData1Loader.cs.meta index 943ed003..da4fe5d6 100644 --- a/Editor/Templates/SceneManagerSettingsTemplate.cs.meta +++ b/DefaultProject/NewUnityGraphData 1/SystemLoaders/NewUnityGraphData1Loader.cs.meta @@ -1,8 +1,12 @@ fileFormatVersion: 2 -guid: bf3ac5d468808c04196eb1a7a524a1cb +guid: 2a9efb0694d121047be2a4742fc4e076 +timeCreated: 1433010055 +licenseType: Pro MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: + assetBundleName: + assetBundleVariant: diff --git a/DefaultProject/NewUnityGraphData.asset b/DefaultProject/NewUnityGraphData.asset index 4e4fcdb0..ab3dd38c 100644 --- a/DefaultProject/NewUnityGraphData.asset +++ b/DefaultProject/NewUnityGraphData.asset @@ -15,11 +15,7 @@ MonoBehaviour: "Type":"Invert.uFrame.MVVM.SubsystemGraph", "DocumentationMode":"false", "RootNode":{"_CLRType":"Invert.uFrame.MVVM.SubsystemNode, Assembly-CSharp-Editor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Name":"", "IsCollapsed":"false", "Identifier":"6c0a3dc3-65f5-455b-94f8-c7e4469d69b6", - "Items":[ ], "CollapsedValues":{"98ff4c87-d9b4-443f-a855-95b22a3b6cf2":"false", - "19ad7308-248a-41ae-9d77-8014aa42edc7":"false", "18f7a20e-6209-46da-b942-c83c244257ee":"false", - "bf00b416-ea67-4688-97ea-97dad6cebb90":"false", "6878ac18-0030-415e-8084-afe251cf757a":"false", - "a67638bb-e3ca-46ff-940f-13c1c5987b16":"false", "d285eceb-f642-400a-8a76-0682a93a7729":"false"}, - "Flags":{"_CLRType":"true"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, + "Items":[ ], "CollapsedValues":{}, "Flags":{"_CLRType":"true"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, "IsNewNode":"true"}, "Nodes":[ {"_CLRType":"Invert.uFrame.MVVM.ElementNode, Assembly-CSharp-Editor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Name":"ElementA", "IsCollapsed":"false", @@ -40,16 +36,7 @@ MonoBehaviour: Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Name":"F", "Identifier":"855156e2-d6fc-4632-8a04-f74ec6cc1cd0", "Precompiled":"false", "Flags":{"_CLRType":"true"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, - "ItemType":""} ], "CollapsedValues":{"8d2fbda6-a01f-4b62-a3d8-57c4a5650677":"false", - "72692222-90bd-4611-b1b6-03e340b145d0":"false", "a43cfbaa-c3d0-4ded-b617-d5437d970ce1":"false", - "cadd44cc-860e-4091-8d75-54e76cfda082":"false", "abd14bc3-7668-4b8a-b6e5-9c526b0ffcde":"false", - "a89fd959-e70d-4803-b703-bc0ef1a3cae7":"false", "9765f863-4b69-4716-867a-e1a706c3fccb":"false", - "e3386d74-3640-4c3c-8448-f742a2d177cf":"false", "48e1351b-e799-4a89-b7fa-f78f64d5ceec":"false", - "df6d1ab8-6742-4e0e-8298-10927a54838c":"false", "a21403d3-8bc4-4d5f-8e78-528118e5fb3e":"false", - "d2a31d3e-299b-4409-87a6-fea255c3cc05":"false", "3f661499-75ac-4c4f-967c-14133b682554":"false", - "411d6d38-e2bc-4a04-a1e0-772225c52281":"false", "f7a84339-beb9-4f1d-b4c9-5430660bc914":"false", - "ad48bb49-162a-4b0a-b6f7-cf5ef6377fc0":"false", "110dab29-76b7-4a47-bb6a-73d65d438837":"false"}, - "Flags":{"_CLRType":"true"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, + "ItemType":""} ], "CollapsedValues":{}, "Flags":{"_CLRType":"true"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, "IsNewNode":"true"}, {"_CLRType":"Invert.uFrame.MVVM.ViewNode, Assembly-CSharp-Editor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Name":"ViewA", "IsCollapsed":"false", diff --git a/DefaultProject/Scenes/UIScene.unity b/DefaultProject/Scenes/UIScene.unity index d5938b01..6efff6de 100644 --- a/DefaultProject/Scenes/UIScene.unity +++ b/DefaultProject/Scenes/UIScene.unity @@ -185,7 +185,6 @@ MonoBehaviour: _BindOnStart: 1 _DisposeOnDestroy: 0 _overrideViewModel: 0 - _resolveName: _BindPlayGame: 1 _PlayGameButton: {fileID: 459940742} --- !u!224 &348365650 diff --git a/DefaultProject/ScreenFlow/Machines.designer.cs b/DefaultProject/ScreenFlow/Machines.designer.cs index 958c62ad..fdf8a28d 100644 --- a/DefaultProject/ScreenFlow/Machines.designer.cs +++ b/DefaultProject/ScreenFlow/Machines.designer.cs @@ -8,6 +8,8 @@ // // ------------------------------------------------------------------------------ +using uFrame.MVVM; + namespace uFrame.DefaultProject { using System; using System.Collections; diff --git a/DefaultProject/uFrameStarter.asset b/DefaultProject/uFrameStarter.asset index ec19aae7..caa51667 100644 --- a/DefaultProject/uFrameStarter.asset +++ b/DefaultProject/uFrameStarter.asset @@ -28,7 +28,10 @@ MonoBehaviour: "95420226-f8ee-470e-b4d9-40013da2301a":"false", "c93415de-6ff2-4aef-b727-acf594e8be5b":"false", "77bf8f91-4379-4193-8d8e-75667eea0867":"false", "c83b5c90-7344-4496-b5d2-52f4846e1b3d":"false", "afdecd91-8924-4849-8611-b2620947bcdb":"false", "5abe8530-8bca-41f6-ae08-396c06daa465":"false", - "16305b28-698d-4bd1-84a7-817b8b765c07":"false", "d51fd9ac-89d7-4dcb-bca6-dca6486026ea":"false"}, + "16305b28-698d-4bd1-84a7-817b8b765c07":"false", "d51fd9ac-89d7-4dcb-bca6-dca6486026ea":"false", + "3ead6cbe-5fb8-4527-95d5-70f0d6cb5acc":"false", "977cb470-4686-4006-bc16-462491cae37e":"false", + "f436167c-e3dd-4010-b513-7b8e6579a3b3":"false", "840597e4-0e15-47e9-a8f8-26c8c9ee5a81":"false", + "43ef0e91-5327-408a-975f-10eb31681b84":"false", "2c27cb98-8f9e-456c-ba90-a5eef4b239a9":"false"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, "IsNewNode":"false"}, "Nodes":[ {"_CLRType":"Invert.uFrame.MVVM.SceneTypeNode, Assembly-CSharp-Editor, @@ -41,7 +44,10 @@ MonoBehaviour: "c93415de-6ff2-4aef-b727-acf594e8be5b":"false", "77bf8f91-4379-4193-8d8e-75667eea0867":"false", "c83b5c90-7344-4496-b5d2-52f4846e1b3d":"false", "afdecd91-8924-4849-8611-b2620947bcdb":"false", "5abe8530-8bca-41f6-ae08-396c06daa465":"false", "16305b28-698d-4bd1-84a7-817b8b765c07":"false", - "d51fd9ac-89d7-4dcb-bca6-dca6486026ea":"false"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, + "d51fd9ac-89d7-4dcb-bca6-dca6486026ea":"false", "3ead6cbe-5fb8-4527-95d5-70f0d6cb5acc":"false", + "977cb470-4686-4006-bc16-462491cae37e":"false", "f436167c-e3dd-4010-b513-7b8e6579a3b3":"false", + "840597e4-0e15-47e9-a8f8-26c8c9ee5a81":"false", "43ef0e91-5327-408a-975f-10eb31681b84":"false", + "2c27cb98-8f9e-456c-ba90-a5eef4b239a9":"false"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, "IsNewNode":"false"}, {"_CLRType":"Invert.uFrame.MVVM.SceneTypeNode, Assembly-CSharp-Editor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Name":"GameScene", "IsCollapsed":"true", @@ -53,7 +59,10 @@ MonoBehaviour: "c93415de-6ff2-4aef-b727-acf594e8be5b":"false", "77bf8f91-4379-4193-8d8e-75667eea0867":"false", "c83b5c90-7344-4496-b5d2-52f4846e1b3d":"false", "afdecd91-8924-4849-8611-b2620947bcdb":"false", "5abe8530-8bca-41f6-ae08-396c06daa465":"false", "16305b28-698d-4bd1-84a7-817b8b765c07":"false", - "d51fd9ac-89d7-4dcb-bca6-dca6486026ea":"false"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, + "d51fd9ac-89d7-4dcb-bca6-dca6486026ea":"false", "3ead6cbe-5fb8-4527-95d5-70f0d6cb5acc":"false", + "977cb470-4686-4006-bc16-462491cae37e":"false", "f436167c-e3dd-4010-b513-7b8e6579a3b3":"false", + "840597e4-0e15-47e9-a8f8-26c8c9ee5a81":"false", "43ef0e91-5327-408a-975f-10eb31681b84":"false", + "2c27cb98-8f9e-456c-ba90-a5eef4b239a9":"false"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, "IsNewNode":"false"}, {"_CLRType":"Invert.Core.GraphDesigner.TypeReferenceNode, Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null", @@ -64,7 +73,10 @@ MonoBehaviour: "95420226-f8ee-470e-b4d9-40013da2301a":"false", "c93415de-6ff2-4aef-b727-acf594e8be5b":"false", "77bf8f91-4379-4193-8d8e-75667eea0867":"false", "c83b5c90-7344-4496-b5d2-52f4846e1b3d":"false", "afdecd91-8924-4849-8611-b2620947bcdb":"false", "5abe8530-8bca-41f6-ae08-396c06daa465":"false", - "16305b28-698d-4bd1-84a7-817b8b765c07":"false", "d51fd9ac-89d7-4dcb-bca6-dca6486026ea":"false"}, + "16305b28-698d-4bd1-84a7-817b8b765c07":"false", "d51fd9ac-89d7-4dcb-bca6-dca6486026ea":"false", + "3ead6cbe-5fb8-4527-95d5-70f0d6cb5acc":"false", "977cb470-4686-4006-bc16-462491cae37e":"false", + "f436167c-e3dd-4010-b513-7b8e6579a3b3":"false", "840597e4-0e15-47e9-a8f8-26c8c9ee5a81":"false", + "43ef0e91-5327-408a-975f-10eb31681b84":"false", "2c27cb98-8f9e-456c-ba90-a5eef4b239a9":"false"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, "IsNewNode":"false"}, {"_CLRType":"Invert.Core.GraphDesigner.TypeReferenceNode, Invert.Core.GraphDesigner, @@ -76,7 +88,10 @@ MonoBehaviour: "95420226-f8ee-470e-b4d9-40013da2301a":"false", "c93415de-6ff2-4aef-b727-acf594e8be5b":"false", "77bf8f91-4379-4193-8d8e-75667eea0867":"false", "c83b5c90-7344-4496-b5d2-52f4846e1b3d":"false", "afdecd91-8924-4849-8611-b2620947bcdb":"false", "5abe8530-8bca-41f6-ae08-396c06daa465":"false", - "16305b28-698d-4bd1-84a7-817b8b765c07":"false", "d51fd9ac-89d7-4dcb-bca6-dca6486026ea":"false"}, + "16305b28-698d-4bd1-84a7-817b8b765c07":"false", "d51fd9ac-89d7-4dcb-bca6-dca6486026ea":"false", + "3ead6cbe-5fb8-4527-95d5-70f0d6cb5acc":"false", "977cb470-4686-4006-bc16-462491cae37e":"false", + "f436167c-e3dd-4010-b513-7b8e6579a3b3":"false", "840597e4-0e15-47e9-a8f8-26c8c9ee5a81":"false", + "43ef0e91-5327-408a-975f-10eb31681b84":"false", "2c27cb98-8f9e-456c-ba90-a5eef4b239a9":"false"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, "IsNewNode":"false"}, {"_CLRType":"Invert.Core.GraphDesigner.TypeReferenceNode, Invert.Core.GraphDesigner, @@ -87,7 +102,10 @@ MonoBehaviour: "c93415de-6ff2-4aef-b727-acf594e8be5b":"false", "77bf8f91-4379-4193-8d8e-75667eea0867":"false", "c83b5c90-7344-4496-b5d2-52f4846e1b3d":"false", "afdecd91-8924-4849-8611-b2620947bcdb":"false", "5abe8530-8bca-41f6-ae08-396c06daa465":"false", "16305b28-698d-4bd1-84a7-817b8b765c07":"false", - "d51fd9ac-89d7-4dcb-bca6-dca6486026ea":"false"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, + "d51fd9ac-89d7-4dcb-bca6-dca6486026ea":"false", "3ead6cbe-5fb8-4527-95d5-70f0d6cb5acc":"false", + "977cb470-4686-4006-bc16-462491cae37e":"false", "f436167c-e3dd-4010-b513-7b8e6579a3b3":"false", + "840597e4-0e15-47e9-a8f8-26c8c9ee5a81":"false", "43ef0e91-5327-408a-975f-10eb31681b84":"false", + "2c27cb98-8f9e-456c-ba90-a5eef4b239a9":"false"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, "IsNewNode":"false"}, {"_CLRType":"Invert.Core.GraphDesigner.TypeReferenceNode, Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null", @@ -96,7 +114,10 @@ MonoBehaviour: "95420226-f8ee-470e-b4d9-40013da2301a":"false", "c93415de-6ff2-4aef-b727-acf594e8be5b":"false", "77bf8f91-4379-4193-8d8e-75667eea0867":"false", "c83b5c90-7344-4496-b5d2-52f4846e1b3d":"false", "afdecd91-8924-4849-8611-b2620947bcdb":"false", "5abe8530-8bca-41f6-ae08-396c06daa465":"false", - "16305b28-698d-4bd1-84a7-817b8b765c07":"false", "d51fd9ac-89d7-4dcb-bca6-dca6486026ea":"false"}, + "16305b28-698d-4bd1-84a7-817b8b765c07":"false", "d51fd9ac-89d7-4dcb-bca6-dca6486026ea":"false", + "3ead6cbe-5fb8-4527-95d5-70f0d6cb5acc":"false", "977cb470-4686-4006-bc16-462491cae37e":"false", + "f436167c-e3dd-4010-b513-7b8e6579a3b3":"false", "840597e4-0e15-47e9-a8f8-26c8c9ee5a81":"false", + "43ef0e91-5327-408a-975f-10eb31681b84":"false", "2c27cb98-8f9e-456c-ba90-a5eef4b239a9":"false"}, "DataBag":{"_CLRType":"Invert.Core.GraphDesigner.DataBag, Invert.Core.GraphDesigner, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"}, "IsNewNode":"false"} ], "ConnectedItems":[ ], "PositionData":{"_CLRType":"FilterPositionData, Invert.Core.GraphDesigner, diff --git a/DefaultProject/uFrameStarter/Scenes.designer.cs b/DefaultProject/uFrameStarter/Scenes.designer.cs index 5f25f604..7869dda3 100644 --- a/DefaultProject/uFrameStarter/Scenes.designer.cs +++ b/DefaultProject/uFrameStarter/Scenes.designer.cs @@ -8,6 +8,8 @@ // // ------------------------------------------------------------------------------ +using uFrame.Kernel; + namespace uFrame.DefaultProject { using System; using System.Collections; diff --git a/DefaultProject/uFrameStarter/ScenesSettings.designer.cs b/DefaultProject/uFrameStarter/ScenesSettings.designer.cs index f4e280b8..194cea62 100644 --- a/DefaultProject/uFrameStarter/ScenesSettings.designer.cs +++ b/DefaultProject/uFrameStarter/ScenesSettings.designer.cs @@ -8,6 +8,8 @@ // // ------------------------------------------------------------------------------ +using uFrame.Kernel; + namespace uFrame.DefaultProject { using System; using System.Collections; diff --git a/Editor/Commands/CreateSceneCommand.cs b/Editor/Commands/CreateSceneCommand.cs index ee37bc68..45ee8ad1 100644 --- a/Editor/Commands/CreateSceneCommand.cs +++ b/Editor/Commands/CreateSceneCommand.cs @@ -3,6 +3,8 @@ using Invert.Core; using Invert.Core.GraphDesigner; using Invert.uFrame.MVVM; +using uFrame.Kernel; +using uFrame.MVVM.Services; using UnityEditor; using UnityEngine; diff --git a/Editor/Pages/CollectionsPage.cs b/Editor/Pages/CollectionsPage.cs index 4c30b05e..6832f3ac 100644 --- a/Editor/Pages/CollectionsPage.cs +++ b/Editor/Pages/CollectionsPage.cs @@ -1,3 +1,5 @@ +using uFrame.MVVM.Templates; + namespace Invert.uFrame.MVVM { using System; using System.Collections; diff --git a/Editor/Pages/CommandsPage.cs b/Editor/Pages/CommandsPage.cs index c1361a5f..67e04f4e 100644 --- a/Editor/Pages/CommandsPage.cs +++ b/Editor/Pages/CommandsPage.cs @@ -1,3 +1,5 @@ +using uFrame.MVVM.Templates; + namespace Invert.uFrame.MVVM { using System; using System.Collections; diff --git a/Editor/Pages/ComputedPropertyPage.cs b/Editor/Pages/ComputedPropertyPage.cs index 6cc1c123..dd802a17 100644 --- a/Editor/Pages/ComputedPropertyPage.cs +++ b/Editor/Pages/ComputedPropertyPage.cs @@ -1,3 +1,5 @@ +using uFrame.MVVM.Templates; + namespace Invert.uFrame.MVVM { using System; using System.Collections; diff --git a/Editor/Pages/PropertiesPage.cs b/Editor/Pages/PropertiesPage.cs index 0bbe9449..a2995c03 100644 --- a/Editor/Pages/PropertiesPage.cs +++ b/Editor/Pages/PropertiesPage.cs @@ -1,3 +1,5 @@ +using uFrame.MVVM.Templates; + namespace Invert.uFrame.MVVM { using System; using System.Collections; diff --git a/Editor/Pages/ScenePropertiesPage.cs b/Editor/Pages/ScenePropertiesPage.cs index 544b353f..df268bb4 100644 --- a/Editor/Pages/ScenePropertiesPage.cs +++ b/Editor/Pages/ScenePropertiesPage.cs @@ -1,3 +1,5 @@ +using uFrame.MVVM.Templates; + namespace Invert.uFrame.MVVM { using System; using System.Collections; diff --git a/Editor/Pages/ServicePage.cs b/Editor/Pages/ServicePage.cs index 408bc22c..a414ffaf 100644 --- a/Editor/Pages/ServicePage.cs +++ b/Editor/Pages/ServicePage.cs @@ -1,4 +1,5 @@ using Invert.Core.GraphDesigner; +using uFrame.MVVM.Templates; namespace Invert.uFrame.MVVM { using System; diff --git a/Editor/Pages/SubsystemPage.cs b/Editor/Pages/SubsystemPage.cs index c02c21ae..4d9d5c52 100644 --- a/Editor/Pages/SubsystemPage.cs +++ b/Editor/Pages/SubsystemPage.cs @@ -1,4 +1,5 @@ using Invert.Core.GraphDesigner; +using uFrame.MVVM.Templates; using UnityEngine; namespace Invert.uFrame.MVVM { diff --git a/Editor/Resources/uFrameReadme.txt b/Editor/Resources/uFrameReadme.txt index f80624fb..f192aac4 100644 --- a/Editor/Resources/uFrameReadme.txt +++ b/Editor/Resources/uFrameReadme.txt @@ -1,6 +1,19 @@ [u]Frame Release Notes Be sure to subscribe to our newsletter @ invertgamestudios.com for updates, notifications, and cool info. +Note for 1.5 Users: The 1.6 Version of uFrame, only falls short of a major release due to it being mostly bug fixes and changes that will support + the idea of ECS and MVVM working together, and promises for the 1.x release. If you already have a lot of work done in 1.5 save 1.6 for your next game or application. + While upgrading is possible if you are familiar enough with it, but it will require a significant effort. + +1.6 RC1 Notes +- uFrame is now seperated into various namespaces, the uFrame.Kernel, and uFrame.MVVM are the main ones. + - If you have resharper, just got to each file and click on import 'uFrame.MVVM' or any other required namespace. http://i.imgur.com/0EPGdbO.png + - You may also want to check your kernel and ensure that all is well. + - It will help with errors if you stick strictly the the unity console and not the visual studio error list, just go down the list of errors and fix the namespace issues. + - It will look like you have a lot of errors in the designer files, but a simple namespace will fix them +- Depending on what beta version you are currently on you may need to fix some collection bindings with {Name}OnAdd, and {Name}OnRemove + + Editor and Project: 1.5.1 Lots of bug fixes diff --git a/Editor/Templates/CommandClassTemplate.cs b/Editor/Templates/CommandClassTemplate.cs new file mode 100644 index 00000000..4a07d277 --- /dev/null +++ b/Editor/Templates/CommandClassTemplate.cs @@ -0,0 +1,46 @@ +using System.Collections.Generic; +using System.Linq; +using Invert.Core; +using Invert.Core.GraphDesigner; + +namespace uFrame.MVVM.Templates +{ + [TemplateClass(TemplateLocation.DesignerFile, ClassNameFormat = "{0}Command")] + public partial class CommandClassTemplate : CommandClassTemplateBase, IClassRefactorable + { + public IEnumerable ClassNameFormats + { + get { yield return "{0}Command"; } + } + + public override string OutputPath + { + get { return Path2.Combine(Ctx.Data.Node.Graph.Name, "Commands"); } + } + + + public override void TemplateSetup() + { + base.TemplateSetup(); + this.Ctx.TryAddNamespace("uFrame.Kernel"); + this.Ctx.TryAddNamespace("uFrame.MVVM"); + this.Ctx.TryAddNamespace("uFrame.Serialization"); + foreach (var property in Ctx.Data.PersistedItems.OfType()) + { + var type = InvertApplication.FindTypeByName(property.RelatedTypeName); + if (type == null) continue; + + Ctx.TryAddNamespace(type.Namespace); + } + + Ctx.CurrentDecleration.IsPartial = true; + } + + + [ForEach("Properties"), GenerateProperty, WithField] + public _ITEMTYPE_ _Name_ { get; set; } + + [ForEach("Collections"), GenerateProperty, WithField] + public List<_ITEMTYPE_> _CollectionName_ { get; set; } + } +} \ No newline at end of file diff --git a/Editor/Templates/CommandClassTemplate.cs.meta b/Editor/Templates/CommandClassTemplate.cs.meta new file mode 100644 index 00000000..af571d3e --- /dev/null +++ b/Editor/Templates/CommandClassTemplate.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 273bb70e11dafa04cbb498c334e6300a +timeCreated: 1433229787 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Templates/CommandClassTemplateBase.cs b/Editor/Templates/CommandClassTemplateBase.cs new file mode 100644 index 00000000..b152d0ea --- /dev/null +++ b/Editor/Templates/CommandClassTemplateBase.cs @@ -0,0 +1,38 @@ +using System.CodeDom; +using Invert.Core.GraphDesigner; +using Invert.uFrame.MVVM; + +namespace uFrame.MVVM.Templates +{ + [TemplateClass(Location = TemplateLocation.DesignerFile, AutoInherit = true, ClassNameFormat = "{0}Command")] + public class CommandClassTemplateBase : IClassTemplate + { + + private Invert.Core.GraphDesigner.TemplateContext _Ctx; + + public virtual string OutputPath + { + get { return ""; } + } + + public virtual bool CanGenerate + { + get { return true; } + } + + public Invert.Core.GraphDesigner.TemplateContext Ctx + { + get { return _Ctx; } + set { _Ctx = value; } + } + + public virtual void TemplateSetup() + { + if (Ctx.IsDesignerFile) + { + Ctx.CurrentDecleration.BaseTypes.Clear(); + Ctx.CurrentDecleration.BaseTypes.Add(new CodeTypeReference("ViewModelCommand")); + } + } + } +} \ No newline at end of file diff --git a/Editor/Templates/CommandClassTemplateBase.cs.meta b/Editor/Templates/CommandClassTemplateBase.cs.meta new file mode 100644 index 00000000..165340f7 --- /dev/null +++ b/Editor/Templates/CommandClassTemplateBase.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 21247426ed3f57943b495c2149bb0cb4 +timeCreated: 1433229787 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Templates/ControllerTemplate.cs b/Editor/Templates/ControllerTemplate.cs index 96df849d..cd7565cd 100644 --- a/Editor/Templates/ControllerTemplate.cs +++ b/Editor/Templates/ControllerTemplate.cs @@ -3,283 +3,253 @@ using System.Collections; using System.Collections.Generic; using System.Linq; +using System.Reflection; using Invert.Core; using Invert.Core.GraphDesigner; using Invert.uFrame.MVVM; using uFrame.Graphs; -[TemplateClass(MemberGeneratorLocation.Both, ClassNameFormat = uFrameFormats.CONTROLLER_FORMAT)] -public partial class ControllerTemplate : Controller, IClassTemplate, IClassRefactorable, IMethodRefactorable +namespace uFrame.MVVM.Templates { - public TemplateContext Ctx { get; set; } - - public string OutputPath - { - get { return Path2.Combine(Ctx.Data.Graph.Name, "Controllers"); } - } - - public bool CanGenerate - { - get { return true; } - } - - public void TemplateSetup() + [TemplateClass(TemplateLocation.Both, ClassNameFormat = uFrameFormats.CONTROLLER_FORMAT)] + public partial class ControllerTemplate : Controller, IClassTemplate, IClassRefactorable, IMethodRefactorable { + public TemplateContext Ctx { get; set; } - Ctx.TryAddNamespace("UniRx"); - foreach (var property in Ctx.Data.PersistedItems.OfType()) + public string OutputPath { - var type = InvertApplication.FindTypeByName(property.RelatedTypeName); - if (type == null) continue; - - Ctx.TryAddNamespace(type.Namespace); + get { return Path2.Combine(Ctx.Data.Graph.Name, "Controllers"); } } - if (Ctx.IsDesignerFile) + public bool CanGenerate { - Ctx.CurrentDecleration.Attributes = MemberAttributes.Abstract; + get { return true; } } - Ctx.AddIterator("CommandMethod", _ => _.AllCommandHandlers.Where(p => string.IsNullOrEmpty(p.RelatedTypeName))); - Ctx.AddIterator("CommandMethodWithArg", _ => _.AllCommandHandlers.Where(p => !string.IsNullOrEmpty(p.RelatedTypeName))); - - - Ctx.AddIterator("OnCommandMethod", - _ => _.LocalCommands); + public void TemplateSetup() + { + Ctx.TryAddNamespace("uFrame.IOC"); + Ctx.TryAddNamespace("uFrame.Kernel"); + Ctx.TryAddNamespace("uFrame.MVVM"); + Ctx.TryAddNamespace("uFrame.Serialization"); + Ctx.TryAddNamespace("UniRx"); + foreach (var property in Ctx.Data.PersistedItems.OfType()) + { + var type = InvertApplication.FindTypeByName(property.RelatedTypeName); + if (type == null) continue; + Ctx.TryAddNamespace(type.Namespace); + } - if (Ctx.Data.BaseNode == null) + if (Ctx.IsDesignerFile) + { + Ctx.CurrentDecleration.Attributes = MemberAttributes.Abstract; + } + } + public IEnumerable CommandsWithoutArgs { - Ctx.AddIterator("InstanceProperty", - _ => _.Graph.NodeItems.OfType().SelectMany(p => p.Instances).Distinct()); + get { return Ctx.Data.AllCommandHandlers.Where(p => string.IsNullOrEmpty(p.RelatedTypeName)); } } - else + public IEnumerable CommandsWithArgs { - Ctx.AddCondition("InstanceProperty", _ => false); + get { return Ctx.Data.AllCommandHandlers.Where(p => !string.IsNullOrEmpty(p.RelatedTypeName)); } } - } - - public IEnumerable Instances - { - get + public IEnumerable Instances { - if (Ctx.Data.BaseNode == null) + get { - foreach ( - var item in Ctx.Data.Graph.NodeItems.OfType().SelectMany(p => p.Instances).Distinct() - ) + if (Ctx.Data.BaseNode == null) { - yield return item; + foreach ( + var item in Ctx.Data.Graph.NodeItems.OfType().SelectMany(p => p.Instances).Distinct() + ) + { + yield return item; + } } } } - } - public string NameAsViewModel { get { return Ctx.Data.Name.AsViewModel(); } } + public string NameAsViewModel { get { return Ctx.Data.Name.AsViewModel(); } } - //[TemplateProperty(MemberGeneratorLocation.DesignerFile, AutoFill = AutoFillType.NameAndTypeWithBackingField, NameFormat = "{0}ViewModelManager")] - [ForEach("Instances"),TemplateProperty,WithField] - public IViewModelManager _Name_ViewModelManager - { - get + //[TemplateProperty(TemplateLocation.DesignerFile, AutoFill = AutoFillType.NameAndTypeWithBackingField, NameFormat = "{0}ViewModelManager")] + [GenerateProperty, WithField] + public IViewModelManager _Name_ViewModelManager { - Ctx.SetType(typeof(IViewModelManager)); // I force this so it doesn't change it - Ctx.CurrentProperty.CustomAttributes.Add(new CodeAttributeDeclaration(typeof(InjectAttribute).ToCodeReference(), new CodeAttributeArgument(new CodePrimitiveExpression(Ctx.Data.Name)))); - return null; + get + { + Ctx.SetType(typeof(IViewModelManager)); // I force this so it doesn't change it + Ctx.CurrentProperty.CustomAttributes.Add(new CodeAttributeDeclaration(typeof(uFrame.IOC.InjectAttribute).ToCodeReference(), new CodeAttributeArgument(new CodePrimitiveExpression(Ctx.Data.Name)))); + return null; + } } - } - [TemplateProperty(MemberGeneratorLocation.DesignerFile, AutoFillType.NameAndTypeWithBackingField)] - public ViewModel InstanceProperty - { - get + [ForEach("Instances"), GenerateProperty, WithField] + public _REFNAME_VIEWMODEL _Name_ { - Ctx.CurrentProperty.CustomAttributes.Add(new CodeAttributeDeclaration( - typeof(InjectAttribute).ToCodeReference(), - new CodeAttributeArgument(new CodePrimitiveExpression(Ctx.ItemAs().Name)) - )); + get + { + + Ctx.CurrentProperty.CustomAttributes.Add(new CodeAttributeDeclaration( + typeof(uFrame.IOC.InjectAttribute).ToCodeReference(), + new CodeAttributeArgument(new CodePrimitiveExpression(Ctx.ItemAs().Name)) + )); - return null; - } - set - { + return null; + } + set + { + } } - } - [TemplateMethod(MemberGeneratorLocation.Both)] - public override void Setup() - { - base.Setup(); - Ctx._comment("This is called when the controller is created"); - if (Ctx.IsDesignerFile) + [GenerateMethod(TemplateLocation.Both)] + public override void Setup() { -// foreach (var command in Ctx.Data.AllCommandHandlers) -// { -// Ctx._("this.OnEvent<{0}Command>().Subscribe(this.{0}Handler)", command.Name); -// } - //foreach (var command in Ctx.Data.Handlers.Where(p => !(p.SourceItem is CommandsChildItem))) - //{ - // Ctx._("this.OnEvent<{0}>().Subscribe(this.{0}Handler)", command.Name); - //} - - //Ctx._("this.EventAggregator.OnViewModelCreated<{0}>().Subscribe(vm => this.Initialize{1}(vm as {0}));", Ctx.Data.Name.AsViewModel(), Ctx.Data.Name); - //Ctx._("this.EventAggregator.OnViewModelDestroyed<{0}>().Subscribe(this.DisposingViewModel);", Ctx.Data.Name.AsViewModel()); + base.Setup(); + Ctx._comment("This is called when the controller is created"); + if (Ctx.IsDesignerFile) + { + // foreach (var command in Ctx.Data.AllCommandHandlers) + // { + // Ctx._("this.OnEvent<{0}Command>().Subscribe(this.{0}Handler)", command.Name); + // } + //foreach (var command in Ctx.Data.Handlers.Where(p => !(p.SourceItem is CommandsChildItem))) + //{ + // Ctx._("this.OnEvent<{0}>().Subscribe(this.{0}Handler)", command.Name); + //} + + //Ctx._("this.EventAggregator.OnViewModelCreated<{0}>().Subscribe(vm => this.Initialize{1}(vm as {0}));", Ctx.Data.Name.AsViewModel(), Ctx.Data.Name); + //Ctx._("this.EventAggregator.OnViewModelDestroyed<{0}>().Subscribe(this.DisposingViewModel);", Ctx.Data.Name.AsViewModel()); - } + } - } + } - [TemplateProperty] - public IEnumerable _Name_ViewModels - { - get + [GenerateProperty] + public IEnumerable<_ITEMNAME_VIEWMODEL> _Name_ViewModels { - Ctx.SetTypeArgument(Ctx.Data.Name.AsViewModel()); - Ctx._("return {1}ViewModelManager.OfType<{0}>()", Ctx.Data.Name.AsViewModel(), Ctx.Data.Name); - return null; + get + { + Ctx._("return {1}ViewModelManager.OfType<{0}>()", Ctx.Data.Name.AsViewModel(), Ctx.Data.Name); + return null; + } } - } - [TemplateMethod(MemberGeneratorLocation.DesignerFile, CallBase = true)] - public override void Initialize(ViewModel viewModel) - { - Ctx._comment("This is called when a viewmodel is created"); - if (!Ctx.IsDesignerFile) return; - Ctx._("this.Initialize{0}((({1})(viewModel)))", Ctx.Data.Name, NameAsViewModel); - } + [GenerateMethod] + public override void Initialize(ViewModel viewModel) + { + Ctx._comment("This is called when a viewmodel is created"); + if (!Ctx.IsDesignerFile) return; + Ctx._("this.Initialize{0}((({1})(viewModel)))", Ctx.Data.Name, NameAsViewModel); + } - [TemplateMethod("Create{0}", MemberGeneratorLocation.DesignerFile, false)] - public ViewModel CreateElement() - { - Ctx.SetType(NameAsViewModel); - Ctx._("return (({0})(this.Create(Guid.NewGuid().ToString())))", NameAsViewModel); - return null; - } + [GenerateMethod(CallBase = false)] + public _ITEMNAME_VIEWMODEL Create_Name_() + { + Ctx._("return (({0})(this.Create(Guid.NewGuid().ToString())))", NameAsViewModel); + return null; + } - [TemplateMethod(MemberGeneratorLocation.DesignerFile, false)] - public override ViewModel CreateEmpty() - { - Ctx._("return new {0}(this.EventAggregator)", NameAsViewModel); - return null; - } + [GenerateMethod(CallBase = false)] + public override ViewModel CreateEmpty() + { + Ctx._("return new {0}(this.EventAggregator)", NameAsViewModel); + return null; + } - [TemplateMethod("Initialize{0}", MemberGeneratorLocation.Both, true)] - public virtual void InitializeElement(ViewModel viewModel) - { - Ctx._comment("This is called when a {0} is created", NameAsViewModel); - Ctx.CurrentMethod.Parameters[0].Type = new CodeTypeReference(NameAsViewModel); - if (Ctx.IsDesignerFile) + [GenerateMethod("Initialize{0}", TemplateLocation.Both, true), Inside(TemplateLocation.Both)] + public virtual void InitializeElement(ViewModel viewModel) { - foreach (var command in Ctx.Data.LocalCommands) + Ctx._comment("This is called when a {0} is created", NameAsViewModel); + Ctx.CurrentMethod.Parameters[0].Type = new CodeTypeReference(NameAsViewModel); + if (Ctx.IsDesignerFile) { - Ctx._("viewModel.{0}.Action = this.{0}Handler", command.Name); + foreach (var command in Ctx.Data.LocalCommands) + { + Ctx._("viewModel.{0}.Action = this.{0}Handler", command.Name); + } + Ctx._("{0}ViewModelManager.Add(viewModel)", Ctx.Data.Name); } - Ctx._("{0}ViewModelManager.Add(viewModel)", Ctx.Data.Name); - } - - } - - [TemplateMethod(MemberGeneratorLocation.DesignerFile, true)] - public override void DisposingViewModel(ViewModel viewModel) - { - base.DisposingViewModel(viewModel); - Ctx._("{0}ViewModelManager.Remove(viewModel)", Ctx.Data.Name); - } - [TemplateMethod("{0}", MemberGeneratorLocation.Both, true)] - public virtual void CommandMethod(ViewModel viewModel) - { - Ctx.CurrentMethod.Parameters[0].Type = new CodeTypeReference(Ctx.Item.Node.Name + "ViewModel"); - DoTransition(); - } - - [TemplateMethod("{0}", MemberGeneratorLocation.DesignerFile, true)] - public virtual void OnCommandMethod(ViewModelCommand command) - { + } - Ctx.CurrentMethod.Name = Ctx.Item.Name + "Handler"; - if (Ctx.Item is CommandsChildItem) + [GenerateMethod(TemplateLocation.DesignerFile, true)] + public override void DisposingViewModel(ViewModel viewModel) { - Ctx.CurrentMethod.Parameters[0].Type = new CodeTypeReference(Ctx.Item.Name + "Command"); + base.DisposingViewModel(viewModel); + Ctx._("{0}ViewModelManager.Remove(viewModel)", Ctx.Data.Name); } - else + + [ForEach("CommandsWithoutArgs"), GenerateMethod, InsideAll] + public virtual void _Name2_(ViewModel viewModel) { - Ctx.CurrentMethod.Parameters[0].Type = new CodeTypeReference(Ctx.Item.Name); + Ctx.CurrentMethod.Parameters[0].Type = new CodeTypeReference(Ctx.Item.Node.Name + "ViewModel"); + } - if (Ctx.IsDesignerFile) + [ForEach("LocalCommands"), GenerateMethod, WithNameFormat("{0}Handler")] + public virtual void _Name_Handler(ViewModelCommand command) { if (Ctx.Item is CommandsChildItem) { - var c = Ctx.TypedItem; - if (Ctx.ItemAs().OutputCommand != null) - { - Ctx._("this.{0}(command.Sender as {1}, command)", c.Name, c.Node.Name.AsViewModel()); - - } - else if (string.IsNullOrEmpty(c.RelatedType)) - { - Ctx._("this.{0}(command.Sender as {1})", c.Name, c.Node.Name.AsViewModel()); - } - else - { - Ctx._("this.{0}(command.Sender as {1}, command.Argument)", c.Name, c.Node.Name.AsViewModel()); - } - if (Ctx.ItemAs().Publish) + Ctx.CurrentMethod.Parameters[0].Type = new CodeTypeReference(Ctx.Item.Name + "Command"); + } + else + { + Ctx.CurrentMethod.Parameters[0].Type = new CodeTypeReference(Ctx.Item.Name); + } + + if (Ctx.IsDesignerFile) + { + if (Ctx.Item is CommandsChildItem) { - Ctx._("this.Publish(command)"); + var c = Ctx.TypedItem; + if (Ctx.ItemAs().OutputCommand != null) + { + Ctx._("this.{0}(command.Sender as {1}, command)", c.Name, c.Node.Name.AsViewModel()); + + } + else if (string.IsNullOrEmpty(c.RelatedType)) + { + Ctx._("this.{0}(command.Sender as {1})", c.Name, c.Node.Name.AsViewModel()); + } + else + { + Ctx._("this.{0}(command.Sender as {1}, command.Argument)", c.Name, c.Node.Name.AsViewModel()); + } + if (Ctx.ItemAs().Publish) + { + Ctx._("this.Publish(command)"); + } } - } + } } - } - private void DoTransition() - { - //if (Ctx.IsDesignerFile) - //{ - // var transition = Ctx.Item.OutputTo(); - // if (transition != null) - // { - - // var stateMachineProperty = - // Ctx.Data.LocalProperties.FirstOrDefault(p => p.RelatedTypeNode is StateMachineNode); - - // if (stateMachineProperty != null) - // { - // Ctx._("viewModel.{0}.Transition(\"{1}\")", stateMachineProperty.Name.AsSubscribableProperty(), - // transition.Name); - // } - // } - //} - } - - [TemplateMethod("{0}", MemberGeneratorLocation.Both, true)] - public virtual void CommandMethodWithArg(ViewModel viewModel, object arg) - { - CommandMethod(viewModel); - Ctx.CurrentMethod.Parameters[1].Type = new CodeTypeReference(Ctx.TypedItem.RelatedTypeName); - DoTransition(); + [ForEach("CommandsWithArgs"), GenerateMethod, WithNameFormat("{0}"), InsideAll] + public virtual void _CommandName_(ViewModel viewModel, object arg) + { + _Name2_(viewModel); + Ctx.CurrentMethod.Parameters[1].Type = new CodeTypeReference(Ctx.TypedItem.RelatedTypeName); - } + } - public IEnumerable ClassNameFormats - { - get + public IEnumerable ClassNameFormats { + get + { - yield return "{0}Controller"; - yield return "{0}ControllerBase"; + yield return "{0}Controller"; + yield return "{0}ControllerBase"; + } } - } - public IEnumerable MethodFormats - { - get { yield return "Initialize{0}"; } + public IEnumerable MethodFormats + { + get { yield return "Initialize{0}"; } + } } } - - diff --git a/Editor/Templates/SceneLoaderTemplate.cs b/Editor/Templates/SceneLoaderTemplate.cs new file mode 100644 index 00000000..b8cee549 --- /dev/null +++ b/Editor/Templates/SceneLoaderTemplate.cs @@ -0,0 +1,71 @@ +using System.CodeDom; +using System.Collections.Generic; +using Invert.Core.GraphDesigner; +using Invert.uFrame.MVVM; +namespace uFrame.MVVM.Templates +{ + [TemplateClass(TemplateLocation.Both, "{0}Loader")] + public partial class SceneLoaderTemplate : IClassTemplate, IClassRefactorable + { + public IEnumerable ClassNameFormats + { + get + { + yield return "{0}"; + yield return "{1}Base"; + } + } + + public void TemplateSetup() + { + this.Ctx.TryAddNamespace("uFrame.IOC"); + this.Ctx.TryAddNamespace("uFrame.Kernel"); + this.Ctx.TryAddNamespace("uFrame.MVVM"); + this.Ctx.TryAddNamespace("uFrame.Serialization"); + if (Ctx.IsDesignerFile) + { + //Ctx.SetBaseType("SceneLoader<{0}>",Ctx.Data.Name) + Ctx.CurrentDecleration.BaseTypes.Clear(); + Ctx.CurrentDecleration.BaseTypes.Add(string.Format("SceneLoader<{0}>", Ctx.Data.Name)); + } + else + { + Ctx.TryAddNamespace("UnityEngine"); + } + } + + [GenerateMethod(CallBase = false), Inside(TemplateLocation.Both)] + protected virtual void LoadScene(object scene, object progressDelegate) + { + Ctx.CurrentMethod.Parameters[0].Type = new CodeTypeReference(Ctx.Data.Name); + Ctx.CurrentMethod.Parameters[1].Type = new CodeTypeReference("Action"); + Ctx.CurrentMethod.Attributes |= MemberAttributes.Override; + Ctx.CurrentMethod.ReturnType = "IEnumerator".ToCodeReference(); + Ctx._("yield break"); + } + + [GenerateMethod(CallBase = false), Inside(TemplateLocation.Both)] + protected virtual void UnloadScene(object scene, object progressDelegate) + { + Ctx.CurrentMethod.Parameters[0].Type = new CodeTypeReference(Ctx.Data.Name); + Ctx.CurrentMethod.Parameters[1].Type = new CodeTypeReference("Action"); + Ctx.CurrentMethod.Attributes |= MemberAttributes.Override; + Ctx.CurrentMethod.ReturnType = "IEnumerator".ToCodeReference(); + + + Ctx._("yield break"); + } + + public string OutputPath + { + get { return Path2.Combine(Ctx.Data.Graph.Name, "Scenes"); } + } + + public bool CanGenerate + { + get { return true; } + } + + public TemplateContext Ctx { get; set; } + } +} \ No newline at end of file diff --git a/Editor/Templates/SceneLoaderTemplate.cs.meta b/Editor/Templates/SceneLoaderTemplate.cs.meta new file mode 100644 index 00000000..79f21e29 --- /dev/null +++ b/Editor/Templates/SceneLoaderTemplate.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 3f341823b9359d348af87d9a89e1eed7 +timeCreated: 1433174584 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Templates/SceneManagerSettingsTemplate.cs b/Editor/Templates/SceneManagerSettingsTemplate.cs deleted file mode 100644 index b33a9484..00000000 --- a/Editor/Templates/SceneManagerSettingsTemplate.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using Invert.Core.GraphDesigner; -//using uFrame.Graphs; -using System.Collections; -using Invert.uFrame.MVVM; -using uFrame.Graphs; - -[TemplateClass(MemberGeneratorLocation.Both, uFrameFormats.SCENE_MANAGER_SETTINGS_FORMAT)] -public sealed class SceneManagerSettingsTemplate : IClassTemplate -{ - - //public string[] _Scenes; - public string OutputPath - { - get { return Path2.Combine(Ctx.Data.Graph.Name, "SceneManagers"); } - } - - public bool CanGenerate - { - get { return true; } - } - - public void TemplateSetup() - { - this.Ctx.AddAttribute(typeof (SerializableAttribute)); - if (Ctx.IsDesignerFile) - Ctx.CurrentDecleration._public_(typeof (string[]), "_Scenes"); - } - - public TemplateContext Ctx { get; set; } -} \ No newline at end of file diff --git a/Editor/Templates/SceneManagerTemplate.cs b/Editor/Templates/SceneManagerTemplate.cs deleted file mode 100644 index efde2498..00000000 --- a/Editor/Templates/SceneManagerTemplate.cs +++ /dev/null @@ -1,246 +0,0 @@ -using System.CodeDom; -using System.Collections.Generic; -using System.Linq; -using Invert.Core.GraphDesigner; -using Invert.uFrame.MVVM; -using uFrame.Graphs; -using UnityEngine; - -//[TemplateClass(MemberGeneratorLocation.Both, uFrameFormats.SCENE_MANAGER_FORMAT)] -//public partial class SceneManagerTemplate : IClassTemplate, IClassRefactorable -//{ -// public IEnumerable ClassNameFormats -// { -// get -// { -// yield return "{0}"; -// yield return "{0}Base"; -// yield return "{0}Settings"; -// yield return "{0}SettingsBase"; -// } -// } -// public string OutputPath -// { -// get { return Path2.Combine(Ctx.Data.Graph.Name, "SceneManagers"); } -// } - -// public bool CanGenerate -// { -// get { return true; } -// } - -// public void TemplateSetup() -// { -// Ctx.TryAddNamespace("UniRx"); -// if (Ctx.IsDesignerFile) -// { -// Ctx.SetBaseType(typeof(SceneManager)); -// foreach (var transition in Ctx.Data.SceneTransitions) -// { -// var to = transition.OutputTo(); -// if (to == null) continue; -// Ctx._("public {0} {1}Transition = new {0}();", to.Name.AsSceneManagerSettings(), transition.Name.AsField()); -// } -// Ctx._("public {0} {1} = new {0}();", Ctx.Data.Name.AsSceneManagerSettings(), Ctx.Data.Name.AsSceneManagerSettings().AsField()); -// } -// Ctx.AddIterator("ServiceProperty", node => node.IncludedServices); -// Ctx.AddIterator("InstanceProperty", node => node.ImportedItems); -// Ctx.AddIterator("ControllerProperty", node => node.IncludedElements); -// Ctx.AddIterator("GetTransitionScenes", node => node.SceneTransitions); -// Ctx.AddIterator("TransitionMethod", node => node.SceneTransitions); -// Ctx.AddIterator("TransitionComplete", node => node.SceneTransitions); -// } - -// public TemplateContext Ctx { get; set; } - -// [TemplateProperty(uFrameFormats.SERVICE_FORMAT, AutoFillType.NameOnly)] -// public virtual ISystemService ServiceProperty -// { -// get -// { -// Ctx.SetType(Ctx.Item.Name.AsService()); -// Ctx.AddAttribute(typeof(InjectAttribute)); -// Ctx.CurrentDecleration._private_(Ctx.CurrentProperty.Type, Ctx.Item.Name.AsService().AsField()); -// Ctx.LazyGet(Ctx.Item.Name.AsService().AsField(), "Container.CreateInstance(typeof({0})) as {0};", Ctx.Item.Name.AsService()); -// return null; -// } -// set -// { -// Ctx._("{0} = value", Ctx.Item.Name.AsService().AsField()); -// } -// } - -// //[Inject("LocalPlayer")] -// [TemplateProperty("{0}", AutoFillType.NameOnly)] -// public virtual ViewModel InstanceProperty -// { -// get -// { -// var instance = Ctx.ItemAs(); -// Ctx.SetType(instance.SourceItem.Name.AsViewModel()); - -// Ctx.AddAttribute(typeof(InjectAttribute)) -// .Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(instance.Name))); - -// Ctx._if("this.{0} == null", instance.Name.AsField()) -// .TrueStatements._("this.{0} = CreateInstanceViewModel<{1}>( \"{2}\")", instance.Name.AsField(), instance.SourceItem.Name.AsViewModel(), instance.Name); - -// Ctx.CurrentDecleration._private_(Ctx.CurrentProperty.Type, instance.Name.AsField()); -// Ctx._("return {0}", instance.Name.AsField()); - -// //if ((this._LocalPlayer == null)) { -// // this._LocalPlayer = CreateInstanceViewModel(FPSPlayerController, "LocalPlayer"); -// //} -// //return this._LocalPlayer; -// return null; -// } -// set -// { -// //_LocalPlayer = value; -// } -// } - -// //[Inject()] -// [TemplateProperty(uFrameFormats.CONTROLLER_FORMAT, AutoFillType.NameOnly)] -// public virtual Controller ControllerProperty -// { -// get -// { -// Ctx.SetType(Ctx.Item.Name.AsController()); -// Ctx.AddAttribute(typeof(InjectAttribute)); -// Ctx.CurrentDecleration._private_(Ctx.CurrentProperty.Type, Ctx.Item.Name.AsController().AsField()); -// Ctx.LazyGet(Ctx.Item.Name.AsController().AsField(), "Container.CreateInstance(typeof({0})) as {0};", Ctx.Item.Name.AsController()); -// return null; -// } -// set -// { -// Ctx._("{0} = value", Ctx.Item.Name.AsController().AsField()); -// } -// } - -// // -// // This method is the first method to be invoked when the scene first loads. Anything registered here with 'Container' will effectively -// // be injected on controllers, and instances defined on a subsystem.And example of this would be Container.RegisterInstance(new CodeRepository()). Then any property with -// // the 'Inject' attribute on any controller or view-model will automatically be set by uFrame. -// // -// [TemplateMethod(MemberGeneratorLocation.DesignerFile)] -// public virtual void Setup() -// { -// Ctx.CurrentMethod.Attributes |= MemberAttributes.Override; -// foreach (var item in Ctx.Data.IncludedServices) -// { -// Ctx._("Container.RegisterService<{0}>({0})", item.Name.AsService()); -// } - -// foreach (var item in Ctx.Data.ImportedItems) -// { -// Ctx._("Container.RegisterViewModel<{0}>({1}, \"{1}\")", item.SourceItem.Name.AsViewModel(), item.Name, item.Name); -// } -// foreach (var item in Ctx.Data.IncludedElements) -// { -// Ctx._("Container.RegisterViewModelManager<{0}>(new ViewModelManager<{0}>())", item.Name.AsViewModel()); -// Ctx._("Container.RegisterController<{0}>({0})", item.Name.AsController()); -// } - -// Ctx._("Container.InjectAll()"); - - -// } - -// [TemplateMethod(MemberGeneratorLocation.Both)] -// public virtual void Initialize() -// { -// Ctx.CurrentMethod.Attributes |= MemberAttributes.Override; -// Ctx.CurrentMethodAttribute.CallBase = true; -// if (Ctx.IsDesignerFile) -// Ctx.CurrentMethod.invoke_base(); -// Ctx.CurrentMethod.Comments.Add(new CodeCommentStatement("This method is called right after setup is invoked.")); -// if (Ctx.IsDesignerFile) -// { -// foreach (var item in Ctx.Data.ImportedItems) -// { -// Ctx._("Publish(new ViewModelCreatedEvent() {{ ViewModel = {0} }});", item.Name); -// } - - -// foreach (var item in Ctx.Data.SceneTransitions) -// { -// var command = item.SourceItem as CommandsChildItem; -// if (command == null) -// { -// Debug.Log("command is null"); -// continue; -// } -// var transitionTo = item.OutputTo(); -// if (transitionTo == null) -// { -// Debug.Log("Transition is null"); -// continue; -// } -// Ctx._("this.OnEvent<{0}>().Subscribe(_=>{{ {1}(_); }}).DisposeWith(this.gameObject);", command.ClassName, command.Name); -// } - -// } - -// } - -// #region Transitions - -// [TemplateMethod("Get{0}Scenes", MemberGeneratorLocation.DesignerFile, false, AutoFill = AutoFillType.NameOnly)] -// public virtual System.Collections.Generic.IEnumerable GetTransitionScenes() -// { -// Ctx._("return {0}Transition._Scenes", Ctx.Item.Name.AsField()); -// //return this._QuitGameTransition._Scenes; -// return null; -// } - -// [TemplateMethod(AutoFill = AutoFillType.NameOnly)] -// public virtual void TransitionMethod(object command) -// { - -// var transition = Ctx.ItemAs(); -// var c = transition.SourceItem as CommandsChildItem; -// if (c == null) return; - -// this.Ctx.CurrentMethod.Parameters[0].Type = c.ClassName.ToCodeReference(); - -// // var transitionCommand = transition.SourceItem as CommandsChildItem; -// var transitionOutput = transition.OutputTo(); -// if (transitionOutput != null) -// { -// Ctx._("GameManager.TransitionLevel<{0}>((container) =>{{container.{1} = _{2}Transition; {2}TransitionComplete(container); }}, this.Get{2}Scenes().ToArray())", -// transitionOutput.Name.AsSceneManager(), transitionOutput.Name.AsSceneManagerSettings().AsField(), transition.Name); -// } - -// //GameManager.TransitionLevel((container) =>{container._FPSMainMenuManagerSettings = _QuitGameTransition; QuitGameTransitionComplete(container); }, this.GetQuitGameScenes().ToArray()); -// } - -// [TemplateMethod("{0}TransitionComplete", MemberGeneratorLocation.Both, true)] -// public virtual void TransitionComplete(object sceneManager) -// { -// //if (!Ctx.IsDesignerFile) return; -// var transition = Ctx.ItemAs(); -// var transitionOutput = transition.OutputTo(); -// if (transition == null) return; - -// Ctx.CurrentMethod.Parameters[0].Type = new CodeTypeReference(transitionOutput.Name.AsSceneManager()); -// } - -// //public override void Initialize() -// //{ -// // base.Initialize(); -// // if (Ctx.) -// // //foreach (var item in Ctx.Data.Trnasitions) -// // //{ - -// // // Ctx._("{0}.{1}.Subscribe(_=> {2}()).DisposeWith(this.gameObject)",item); -// // //} -// // // FPSGame.MainMenu.Subscribe(_=> MainMenu()).DisposeWith(this.gameObject); -// // // FPSGame.QuitGame.Subscribe(_=> QuitGame()).DisposeWith(this.gameObject); -// //} - -// #endregion - - - -//} \ No newline at end of file diff --git a/Editor/Templates/SceneSettingsTemplate.cs b/Editor/Templates/SceneSettingsTemplate.cs new file mode 100644 index 00000000..a33b9e7f --- /dev/null +++ b/Editor/Templates/SceneSettingsTemplate.cs @@ -0,0 +1,37 @@ +using Invert.Core.GraphDesigner; +using Invert.uFrame.MVVM; + +namespace uFrame.MVVM.Templates +{ + + + + [TemplateClass(TemplateLocation.Both, "{0}Settings")] + public partial class SceneSettingsTemplate : IClassTemplate + { + public void TemplateSetup() + { + this.Ctx.TryAddNamespace("uFrame.Kernel"); + this.Ctx.TryAddNamespace("uFrame.Serialization"); + if (Ctx.IsDesignerFile) + { + Ctx.CurrentDecleration.BaseTypes.Clear(); + Ctx.SetBaseType("SceneSettings<{0}>", Ctx.Data.Name); + } + } + + public string OutputPath + { + get { return Path2.Combine(Ctx.Data.Graph.Name, "ScenesSettings"); } + } + + public bool CanGenerate + { + get { return true; } + } + + + + public TemplateContext Ctx { get; set; } + } +} \ No newline at end of file diff --git a/Editor/Templates/SceneSettingsTemplate.cs.meta b/Editor/Templates/SceneSettingsTemplate.cs.meta new file mode 100644 index 00000000..0b3d95aa --- /dev/null +++ b/Editor/Templates/SceneSettingsTemplate.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 615c68626b20813429ec00c4217e1d40 +timeCreated: 1433174584 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Templates/SceneTemplate.cs b/Editor/Templates/SceneTemplate.cs index 8597abe3..060ff5f1 100644 --- a/Editor/Templates/SceneTemplate.cs +++ b/Editor/Templates/SceneTemplate.cs @@ -2,269 +2,69 @@ using UnityEngine; using System.Collections; using System.Collections.Generic; -using System.Linq; using System.Runtime.InteropServices; -using Invert.Core; using Invert.Core.GraphDesigner; using Invert.uFrame.MVVM; -using uFrame.Graphs; +using uFrame.Kernel; - -[TemplateClass(MemberGeneratorLocation.Both, "{0}")] -public partial class SceneTemplate : IClassTemplate, IClassRefactorable +namespace uFrame.MVVM.Templates { - [TemplateProperty(MemberGeneratorLocation.DesignerFile)] - public virtual string DefaultKernelScene - { - get - { - Ctx.CurrentProperty.Attributes = MemberAttributes.Override | MemberAttributes.Public; - Ctx._("return \"{0}KernelScene\"",Ctx.Data.Graph.Project.Name); - return null; - } - } - - public void TemplateSetup() - { - if (Ctx.IsDesignerFile) - { - Ctx.CurrentDecleration.BaseTypes.Add(typeof(MonoBehaviour).ToCodeReference()); - Ctx.SetBaseType(typeof(Scene)); - } - } - - public string OutputPath - { - get { return Path2.Combine(Ctx.Data.Graph.Name, "Scenes"); } - } - - public bool CanGenerate + [TemplateClass(TemplateLocation.Both, "{0}")] + public partial class SceneTemplate : IClassTemplate, IClassRefactorable { - get { return true; } - } - public TemplateContext Ctx { get; set; } - - - [TemplateProperty("Settings", AutoFillType.NameOnly)] - public virtual object InstanceProperty - { - get - { - //Ctx.SetType("{0}Settings"); - Ctx.SetType(string.Format("{0}Settings", Ctx.Data.Name).ToCodeReference()); - Ctx._(string.Format("return _SettingsObject as {0}Settings", Ctx.Data.Name)); - return null; - } - set + [GenerateProperty] + public virtual string DefaultKernelScene { - Ctx._(string.Format("_SettingsObject = value")); - } - } - - public IEnumerable ClassNameFormats - { - get - { - yield return "{0}"; - yield return "{1}Base"; + get + { + Ctx.CurrentProperty.Attributes = MemberAttributes.Override | MemberAttributes.Public; + Ctx._("return \"{0}KernelScene\"", Ctx.Data.Graph.Project.Name); + return null; + } } - } -} -[TemplateClass(MemberGeneratorLocation.Both, "{0}Loader")] -public partial class SceneLoaderTemplate : IClassTemplate, IClassRefactorable -{ - public IEnumerable ClassNameFormats - { - get + public void TemplateSetup() { - yield return "{0}"; - yield return "{1}Base"; - } - } - public void TemplateSetup() - { - if (Ctx.IsDesignerFile) - { - //Ctx.SetBaseType("SceneLoader<{0}>",Ctx.Data.Name) - Ctx.CurrentDecleration.BaseTypes.Clear(); - Ctx.CurrentDecleration.BaseTypes.Add(string.Format("SceneLoader<{0}>", Ctx.Data.Name)); - } - else - { - Ctx.TryAddNamespace("UnityEngine"); + if (Ctx.IsDesignerFile) + { + Ctx.CurrentDecleration.BaseTypes.Add(typeof (MonoBehaviour).ToCodeReference()); + Ctx.SetBaseType(typeof (Scene)); + } } - } - - [TemplateMethod( CallBase = false),Inside(TemplateLocation.Both)] - protected virtual void LoadScene(object scene, object progressDelegate) - { - Ctx.CurrentMethod.Parameters[0].Type = new CodeTypeReference(Ctx.Data.Name); - Ctx.CurrentMethod.Parameters[1].Type = new CodeTypeReference("Action"); - Ctx.CurrentMethod.Attributes |= MemberAttributes.Override; - Ctx.CurrentMethod.ReturnType = "IEnumerator".ToCodeReference(); - Ctx._("yield break"); - } - - [TemplateMethod(CallBase = false), Inside(TemplateLocation.Both)] - protected virtual void UnloadScene(object scene, object progressDelegate) - { - Ctx.CurrentMethod.Parameters[0].Type = new CodeTypeReference(Ctx.Data.Name); - Ctx.CurrentMethod.Parameters[1].Type = new CodeTypeReference("Action"); - Ctx.CurrentMethod.Attributes |= MemberAttributes.Override; - Ctx.CurrentMethod.ReturnType = "IEnumerator".ToCodeReference(); - - - Ctx._("yield break"); - } - - public string OutputPath - { - get { return Path2.Combine(Ctx.Data.Graph.Name, "Scenes"); } - } - - public bool CanGenerate - { - get { return true; } - } - public TemplateContext Ctx { get; set; } -} -[TemplateClass(MemberGeneratorLocation.Both, "{0}Settings")] -public partial class SceneSettingsTemplate : IClassTemplate -{ - public void TemplateSetup() - { - if (Ctx.IsDesignerFile) + public string OutputPath { - Ctx.CurrentDecleration.BaseTypes.Clear(); - Ctx.SetBaseType("SceneSettings<{0}>", Ctx.Data.Name); + get { return Path2.Combine(Ctx.Data.Graph.Name, "Scenes"); } } - } - - public string OutputPath - { - get { return Path2.Combine(Ctx.Data.Graph.Name, "ScenesSettings"); } - } - - public bool CanGenerate - { - get { return true; } - } - - - - public TemplateContext Ctx { get; set; } -} -[TemplateClass(MemberGeneratorLocation.Both, "{0}Loader")] -public partial class SystemLoaderTemplate : IClassTemplate -{ - public void TemplateSetup() - { - foreach (var property in Ctx.Data.PersistedItems.OfType()) + public bool CanGenerate { - var type = InvertApplication.FindTypeByName(property.RelatedTypeName); - if (type == null) continue; - - Ctx.TryAddNamespace(type.Namespace); - } - - if (Ctx.IsDesignerFile) - { - Ctx.CurrentDecleration.BaseTypes.Add(typeof(MonoBehaviour).ToCodeReference()); - Ctx.SetBaseType(typeof (SystemLoader)); + get { return true; } } - Ctx.AddIterator("InstanceProperty", node => node.Instances); - Ctx.AddIterator("ControllerProperty", node => node.GetContainingNodesInProject(Ctx.Data.Project).OfType()); - } + public TemplateContext Ctx { get; set; } - [TemplateMethod(CallBase = true), Inside(TemplateLocation.Both)] - public void Load() - { - Ctx.CurrentMethod.Attributes |= MemberAttributes.Override; - - if (!Ctx.IsDesignerFile) - Ctx.CurrentMethod.invoke_base(); - - if (Ctx.IsDesignerFile) + [GenerateProperty()] + public virtual object Settings { - - foreach (var item in Ctx.Data.GetContainingNodesInProject(Ctx.Data.Project).OfType().Distinct()) - { - Ctx._("Container.RegisterViewModelManager<{0}>(new ViewModelManager<{0}>())", item.Name.AsViewModel()); - Ctx._("Container.RegisterController<{0}>({0})", item.Name.AsController()); - } - - foreach (var item in Ctx.Data.Instances.Distinct()) + get { - Ctx._("Container.RegisterViewModel<{0}>({1}, \"{1}\")", item.SourceItem.Name.AsViewModel(), item.Name, item.Name); + //Ctx.SetType("{0}Settings"); + Ctx.SetType(string.Format("{0}Settings", Ctx.Data.Name).ToCodeReference()); + Ctx._(string.Format("return _SettingsObject as {0}Settings", Ctx.Data.Name)); + return null; } - - + set { Ctx._(string.Format("_SettingsObject = value")); } } - - } - - //[Inject("LocalPlayer")] - [TemplateProperty("{0}", AutoFillType.NameOnly)] - public virtual ViewModel InstanceProperty - { - get + public IEnumerable ClassNameFormats { - var instance = Ctx.ItemAs(); - Ctx.SetType(instance.SourceItem.Name.AsViewModel()); - - Ctx.AddAttribute(typeof(InjectAttribute)) - .Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(instance.Name))); - - Ctx._if("this.{0} == null", instance.Name.AsField()) - .TrueStatements._("this.{0} = this.CreateInstanceViewModel<{1}>( \"{2}\")", instance.Name.AsField(), instance.SourceItem.Name.AsViewModel(), instance.Name); - - Ctx.CurrentDecleration._private_(Ctx.CurrentProperty.Type, instance.Name.AsField()); - Ctx._("return {0}", instance.Name.AsField()); - - //if ((this._LocalPlayer == null)) { - // this._LocalPlayer = CreateInstanceViewModel(FPSPlayerController, "LocalPlayer"); - //} - //return this._LocalPlayer; - return null; - } - set - { - //_LocalPlayer = value; - } - } - - //[Inject()] - [TemplateProperty(uFrameFormats.CONTROLLER_FORMAT, AutoFillType.NameOnly)] - public virtual Controller ControllerProperty - { - get - { - Ctx.SetType(Ctx.Item.Name.AsController()); - Ctx.AddAttribute(typeof(InjectAttribute)); - Ctx.CurrentDecleration._private_(Ctx.CurrentProperty.Type, Ctx.Item.Name.AsController().AsField()); - Ctx.LazyGet(Ctx.Item.Name.AsController().AsField(), "Container.CreateInstance(typeof({0})) as {0};", Ctx.Item.Name.AsController()); - return null; - } - set - { - Ctx._("{0} = value", Ctx.Item.Name.AsController().AsField()); + get + { + yield return "{0}"; + yield return "{1}Base"; + } } } - - public string OutputPath - { - get { return Path2.Combine(Ctx.Data.Graph.Name, "SystemLoaders"); } - } - - public bool CanGenerate - { - get { return true; } - } - public TemplateContext Ctx { get; set; } } \ No newline at end of file diff --git a/Editor/Templates/ServiceTemplate.cs b/Editor/Templates/ServiceTemplate.cs index c4898746..aa81bf91 100644 --- a/Editor/Templates/ServiceTemplate.cs +++ b/Editor/Templates/ServiceTemplate.cs @@ -6,98 +6,110 @@ using Invert.Core.GraphDesigner; using Invert.uFrame.MVVM; using uFrame.Graphs; +using uFrame.Kernel; +using uFrame.MVVM; using UnityEngine; using UnityEngine.EventSystems; -[TemplateClass(MemberGeneratorLocation.Both)] -public class ServiceTemplate : IClassTemplate, IClassRefactorable +namespace uFrame.MVVM.Templates { - - [TemplateMethod(MemberGeneratorLocation.Both,true)] - public void Setup() + [TemplateClass(TemplateLocation.Both)] + public class ServiceTemplate : IClassTemplate, IClassRefactorable { - Ctx.CurrentMethod.Comments.Add(new CodeCommentStatement("",true)); - Ctx.CurrentMethod.Comments.Add(new CodeCommentStatement("This method is invoked whenever the kernel is loading.",true)); - Ctx.CurrentMethod.Comments.Add(new CodeCommentStatement("Since the kernel lives throughout the entire lifecycle of the game, this will only be invoked once.",true)); - Ctx.CurrentMethod.Comments.Add(new CodeCommentStatement("", true)); - Ctx.TryAddNamespace("UniRx"); Ctx.CurrentMethod.Attributes |= MemberAttributes.Override; - if (Ctx.IsDesignerFile) + + [GenerateMethod(TemplateLocation.Both, true)] + public void Setup() { + Ctx.CurrentMethod.Comments.Add(new CodeCommentStatement("", true)); + Ctx.CurrentMethod.Comments.Add(new CodeCommentStatement("This method is invoked whenever the kernel is loading.", true)); + Ctx.CurrentMethod.Comments.Add(new CodeCommentStatement("Since the kernel lives throughout the entire lifecycle of the game, this will only be invoked once.", true)); + Ctx.CurrentMethod.Comments.Add(new CodeCommentStatement("", true)); + Ctx.TryAddNamespace("UniRx"); Ctx.CurrentMethod.Attributes |= MemberAttributes.Override; + if (Ctx.IsDesignerFile) + { - foreach (var command in Ctx.Data.Handlers.Select(p => p.SourceItemObject).OfType()) + foreach (var command in Ctx.Data.Handlers.Select(p => p.SourceItemObject).OfType()) + { + Ctx._("this.OnEvent<{0}>().Subscribe(this.{1}Handler)", command.ClassName, command.Name); + } + + } + else { - Ctx._("this.OnEvent<{0}>().Subscribe(this.{1}Handler)", command.ClassName, command.Name); + Ctx.CurrentMethod.invoke_base(); + Ctx._comment("Use the line below to subscribe to events."); + Ctx._comment("this.OnEvent().Subscribe(myEventInstance=>{{ TODO }});"); } + } + public string OutputPath + { + get { return Path2.Combine(Ctx.Data.Graph.Name, "Services"); } } - else + + public bool CanGenerate { - Ctx.CurrentMethod.invoke_base(); - Ctx._comment("Use the line below to subscribe to events."); - Ctx._comment("this.OnEvent().Subscribe(myEventInstance=>{{ TODO }});"); + get { return true; } } - } - public string OutputPath - { - get { return Path2.Combine(Ctx.Data.Graph.Name, "Services"); } - } + public void TemplateSetup() + { + this.Ctx.TryAddNamespace("uFrame.IOC"); + this.Ctx.TryAddNamespace("uFrame.Kernel"); + this.Ctx.TryAddNamespace("uFrame.MVVM"); + Ctx.TryAddNamespace("UnityEngine"); + Ctx.TryAddNamespace("UniRx"); - public bool CanGenerate - { - get { return true; } - } + if (Ctx.IsDesignerFile) + { + Ctx.SetBaseType(typeof(SystemServiceMonoBehavior)); + } - public void TemplateSetup() - { - Ctx.TryAddNamespace("UnityEngine"); - Ctx.TryAddNamespace("UniRx"); + foreach (var property in Ctx.Data.PersistedItems.OfType()) + { + var type = InvertApplication.FindTypeByName(property.RelatedTypeName); + if (type == null) continue; - if (Ctx.IsDesignerFile) - { - Ctx.SetBaseType(typeof(SystemServiceMonoBehavior)); - } + Ctx.TryAddNamespace(type.Namespace); + } - foreach (var property in Ctx.Data.PersistedItems.OfType()) - { - var type = InvertApplication.FindTypeByName(property.RelatedTypeName); - if (type == null) continue; + Ctx.AddIterator("OnCommandMethod", + _ => _.Handlers.Select(p => p.SourceItemObject)); - Ctx.TryAddNamespace(type.Namespace); - } - Ctx.AddIterator("OnCommandMethod", - _ => _.Handlers.Select(p => p.SourceItemObject)); + } + public TemplateContext Ctx { get; set; } - } + public IEnumerable Handlers + { + get { return Ctx.Data.Handlers.Select(p => p.SourceItemObject); } + } - public TemplateContext Ctx { get; set; } + [ForEach("Handlers"), GenerateMethod(CallBase = true), Inside(TemplateLocation.Both)] + public virtual void _Name_Handler(ViewModelCommand data) + { + Ctx.CurrentMethod.Name = Ctx.Item.Name + "Handler"; + Ctx.CurrentMethod.Parameters[0].Type = new CodeTypeReference(Ctx.ItemAs().ClassName); + Ctx._comment("Process the commands information. Also, you can publish new events by using the line below."); + Ctx._comment("this.Publish(new AnotherEvent())"); - [TemplateMethod("{0}", MemberGeneratorLocation.Both, true)] - public virtual void OnCommandMethod(ViewModelCommand data) - { + Ctx.CurrentMethod.Comments.Add(new CodeCommentStatement("", true)); + Ctx.CurrentMethod.Comments.Add( + new CodeCommentStatement(string.Format("This method is executed when using this.Publish(new {0}())", + Ctx.ItemAs().ClassName))); + Ctx.CurrentMethod.Comments.Add(new CodeCommentStatement("", true)); - Ctx.CurrentMethod.Name = Ctx.Item.Name + "Handler"; - Ctx.CurrentMethod.Parameters[0].Type = new CodeTypeReference(Ctx.ItemAs().ClassName); - Ctx._comment("Process the commands information. Also, you can publish new events by using the line below."); - Ctx._comment("this.Publish(new AnotherEvent())"); - - Ctx.CurrentMethod.Comments.Add(new CodeCommentStatement("", true)); - Ctx.CurrentMethod.Comments.Add( - new CodeCommentStatement(string.Format("This method is executed when using this.Publish(new {0}())", - Ctx.ItemAs().ClassName))); - Ctx.CurrentMethod.Comments.Add(new CodeCommentStatement("", true)); - - } + } - public IEnumerable ClassNameFormats - { - get + public IEnumerable ClassNameFormats { - yield return "{0}"; - yield return "{0}Base"; + get + { + yield return "{0}"; + yield return "{0}Base"; + } } } -} \ No newline at end of file +} diff --git a/Editor/Templates/SimpleClassTemplate.cs b/Editor/Templates/SimpleClassTemplate.cs index 9d55d3ec..afda19a5 100644 --- a/Editor/Templates/SimpleClassTemplate.cs +++ b/Editor/Templates/SimpleClassTemplate.cs @@ -4,37 +4,49 @@ using Invert.Core.GraphDesigner; using Invert.uFrame.MVVM; -[TemplateClass(MemberGeneratorLocation.Both)] -public class SimpleClassTemplate : IClassTemplate +namespace uFrame.MVVM.Templates { - public string OutputPath - { - get { return Path2.Combine(Ctx.Data.Graph.Name, "SimplesClasses"); } - } - public bool CanGenerate { get { return true; } } - public void TemplateSetup() + [TemplateClass(TemplateLocation.Both)] + public class SimpleClassTemplate : IClassTemplate { - foreach (var property in Ctx.Data.ChildItems.OfType()) + public string OutputPath { - var type = InvertApplication.FindTypeByName(property.RelatedTypeName); - if (type == null) continue; + get { return Path2.Combine(Ctx.Data.Graph.Name, "SimplesClasses"); } + } - Ctx.TryAddNamespace(type.Namespace); + public bool CanGenerate + { + get { return true; } } - Ctx.AddIterator("Property", node => node.Properties); - Ctx.AddIterator("Collection", node => node.Collections); - } + public void TemplateSetup() + { + this.Ctx.TryAddNamespace("uFrame.Kernel"); + this.Ctx.TryAddNamespace("uFrame.MVVM"); + this.Ctx.TryAddNamespace("uFrame.MVVM.Bindings"); + this.Ctx.TryAddNamespace("uFrame.Serialization"); + foreach (var property in Ctx.Data.ChildItems.OfType()) + { + var type = InvertApplication.FindTypeByName(property.RelatedTypeName); + if (type == null) continue; + + Ctx.TryAddNamespace(type.Namespace); + } + + Ctx.AddIterator("Property", node => node.Properties); + Ctx.AddIterator("Collection", node => node.Collections); + } - public TemplateContext Ctx { get; set; } + public TemplateContext Ctx { get; set; } - [TemplateProperty(MemberGeneratorLocation.DesignerFile, AutoFillType.NameAndTypeWithBackingField)] - public string Property { get; set; } + [ForEach("Properties"), GenerateProperty, WithField] + public _ITEMTYPE_ _PropertyName_ { get; set; } - [TemplateProperty(MemberGeneratorLocation.DesignerFile, AutoFillType.NameAndTypeWithBackingField)] - public List Collection { get; set; } + [ForEach("Collections"), GenerateProperty, WithField] + public List<_ITEMTYPE_> _CollectionName_ { get; set; } + } } \ No newline at end of file diff --git a/Editor/Templates/StateMachineTemplate.cs b/Editor/Templates/StateMachineTemplate.cs index 47be440a..e305dac7 100644 --- a/Editor/Templates/StateMachineTemplate.cs +++ b/Editor/Templates/StateMachineTemplate.cs @@ -7,125 +7,117 @@ using Invert.uFrame.MVVM; using uFrame.Graphs; -[TemplateClass(MemberGeneratorLocation.DesignerFile)] -public class StateMachineTemplate : Invert.StateMachine.StateMachine, IClassTemplate +namespace uFrame.MVVM.Templates { - public string OutputPath + [TemplateClass(TemplateLocation.DesignerFile)] + public class StateMachineTemplate : Invert.StateMachine.StateMachine, IClassTemplate { - get { return Path2.Combine(Ctx.Data.Graph.Name, "Machines"); } - } + public string OutputPath + { + get { return Path2.Combine(Ctx.Data.Graph.Name, "Machines"); } + } - public bool CanGenerate - { - get { return true; } - } + public bool CanGenerate + { + get { return true; } + } - public void TemplateSetup() - { - Ctx.TryAddNamespace("Invert.StateMachine"); - Ctx.AddIterator("TriggerProperty", _ => _.Transitions.Distinct()); - Ctx.AddIterator("StateProperty", _ => _.States.Distinct()); - } + public void TemplateSetup() + { + Ctx.TryAddNamespace("Invert.StateMachine"); - public TemplateContext Ctx { get; set; } + } - [TemplateConstructor(MemberGeneratorLocation.DesignerFile,"vm","propertyName")] - public void StateMachineConstructor(ViewModel vm, string propertyName) - { + public TemplateContext Ctx { get; set; } - } + [GenerateConstructor("vm", "propertyName")] + public void StateMachineConstructor(ViewModel vm, string propertyName) + { - [TemplateConstructor(MemberGeneratorLocation.DesignerFile, "null", "string.Empty")] - public void StateMachineConstructor() - { + } - } + [GenerateConstructor("null", "string.Empty")] + public void StateMachineConstructor() + { + } - [TemplateProperty(MemberGeneratorLocation.DesignerFile)] - public override Invert.StateMachine.State StartState - { - get + + [GenerateProperty] + public override Invert.StateMachine.State StartState { - Ctx._("return this.{0}",Ctx.Data.StartStateOutputSlot.OutputTo().Name); - return null; + get + { + Ctx._("return this.{0}", Ctx.Data.StartStateOutputSlot.OutputTo().Name); + return null; + } } - } - - [TemplateProperty(MemberGeneratorLocation.DesignerFile,AutoFill = AutoFillType.NameOnlyWithBackingField)] - public virtual StateMachineTrigger TriggerProperty - { - get - { - Ctx._if("this.{0} == null", Ctx.Item.Name.AsField()) - .TrueStatements - ._("this.{0} = new StateMachineTrigger(this , \"{1}\")",Ctx.Item.Name.AsField(),Ctx.Item.Name); -// Ctx._("return this.{0}", Ctx.Item.Name.AsField()); - return null; + public IEnumerable DistinctTransitions + { + get { return Ctx.Data.Transitions.Distinct(); } } - } + public IEnumerable DistinctStates + { + get { return Ctx.Data.States.Distinct(); } + } - [TemplateProperty(MemberGeneratorLocation.DesignerFile, AutoFill = AutoFillType.NameOnlyWithBackingField)] - public virtual State StateProperty - { - get + [ForEach("DistinctTransitions"), GenerateProperty, WithField] + public virtual StateMachineTrigger _TriggerName_ { - Ctx.SetType(Ctx.Item.Name); - Ctx._if("this.{0} == null", Ctx.Item.Name.AsField()) - .TrueStatements - ._("this.{0} = new {1}()", Ctx.Item.Name.AsField(), Ctx.Item.Name); + get + { + Ctx._if("this.{0} == null", Ctx.Item.Name.AsField()) + .TrueStatements + ._("this.{0} = new StateMachineTrigger(this , \"{1}\")", Ctx.Item.Name.AsField(), Ctx.Item.Name); // Ctx._("return this.{0}", Ctx.Item.Name.AsField()); - return null; + return null; + } } - } - [TemplateMethod(MemberGeneratorLocation.DesignerFile)] - public override void Compose(List states) - { - //base.Compose(states); - foreach (var state in Ctx.Data.States) + + [ForEach("DistinctStates"), GenerateProperty, WithField] + public virtual State _StateName_ { - foreach (var transition in state.StateTransitions) + get { - var to = transition.OutputTo(); - if (to == null) continue; - - Ctx._("{0}.{1} = new StateTransition(\"{1}\", {0}, {2})",state.Name,transition.Name,to.Name); - Ctx._("Transitions.Add({0}.{1})", state.Name, transition.Name); + Ctx.SetType(Ctx.Item.Name); + Ctx._if("this.{0} == null", Ctx.Item.Name.AsField()) + .TrueStatements + ._("this.{0} = new {1}()", Ctx.Item.Name.AsField(), Ctx.Item.Name); + +// Ctx._("return this.{0}", Ctx.Item.Name.AsField()); + return null; } - foreach (var transition in state.StateTransitions) + } + + [GenerateMethod] + public override void Compose(List states) + { + //base.Compose(states); + foreach (var state in Ctx.Data.States) { - //var to = transition.OutputTo(); - Ctx._("{0}.AddTrigger({1}, {0}.{1})",state.Name,transition.Name); - } - Ctx._("{0}.StateMachine = this",state.Name); - Ctx._("states.Add({0})",state.Name); + foreach (var transition in state.StateTransitions) + { + var to = transition.OutputTo(); + if (to == null) continue; + + Ctx._("{0}.{1} = new StateTransition(\"{1}\", {0}, {2})", state.Name, transition.Name, to.Name); + Ctx._("Transitions.Add({0}.{1})", state.Name, transition.Name); + } + foreach (var transition in state.StateTransitions) + { + //var to = transition.OutputTo(); + Ctx._("{0}.AddTrigger({1}, {0}.{1})", state.Name, transition.Name); + } + Ctx._("{0}.StateMachine = this", state.Name); + Ctx._("states.Add({0})", state.Name); + } } - //this.Idle.StateMachine = this; - //Idle.BeginFiring = new StateTransition("BeginFiring", Idle, Firing); - //Idle.OnReload = new StateTransition("OnReload", Idle, Reloading); - //Idle.OnEmpty = new StateTransition("OnEmpty", Idle, Empty); - //Idle.AddTrigger(BeginFiring, Idle.BeginFiring); - //Idle.AddTrigger(OnReload, Idle.OnReload); - //Idle.AddTrigger(OnEmpty, Idle.OnEmpty); - //states.Add(Idle); - //this.Firing.StateMachine = this; - //Firing.EndFiring = new StateTransition("EndFiring", Firing, Idle); - //Firing.AddTrigger(EndFiring, Firing.EndFiring); - //states.Add(Firing); - //this.Reloading.StateMachine = this; - //Reloading.FinishedReloading = new StateTransition("FinishedReloading", Reloading, Idle); - //Reloading.AddTrigger(FinishedReloading, Reloading.FinishedReloading); - //states.Add(Reloading); - //this.Empty.StateMachine = this; - //Empty.OnReload = new StateTransition("OnReload", Empty, Reloading); - //Empty.AddTrigger(OnReload, Empty.OnReload); - //states.Add(Empty); - } - + + } } \ No newline at end of file diff --git a/Editor/Templates/StateTemplate.cs b/Editor/Templates/StateTemplate.cs index 044f7134..44aa8066 100644 --- a/Editor/Templates/StateTemplate.cs +++ b/Editor/Templates/StateTemplate.cs @@ -2,46 +2,49 @@ using Invert.StateMachine; using Invert.uFrame.MVVM; -[TemplateClass(MemberGeneratorLocation.DesignerFile)] -public class StateTemplate : Invert.StateMachine.State, IClassTemplate +namespace uFrame.MVVM.Templates { - public string OutputPath + [TemplateClass(TemplateLocation.DesignerFile)] + public class StateTemplate : Invert.StateMachine.State, IClassTemplate { - get { return Path2.Combine(Ctx.Data.Graph.Name, "Machines"); } - } + public string OutputPath + { + get { return Path2.Combine(Ctx.Data.Graph.Name, "Machines"); } + } - public bool CanGenerate - { - get { return true; } - } + public bool CanGenerate + { + get { return true; } + } - public void TemplateSetup() - { - Ctx.TryAddNamespace("Invert.StateMachine"); + public void TemplateSetup() + { + Ctx.TryAddNamespace("Invert.StateMachine"); - Ctx.AddIterator("TransitionProperty",_=>_.StateTransitions); - Ctx.AddIterator("TransitionInvoker", _ => _.StateTransitions); - } + } - public TemplateContext Ctx { get; set; } + public TemplateContext Ctx { get; set; } - [TemplateProperty(MemberGeneratorLocation.DesignerFile, AutoFill = AutoFillType.NameOnlyWithBackingField)] - public StateTransition TransitionProperty { get; set; } + //[GenerateProperty(TemplateLocation.DesignerFile, AutoFill = AutoFillType.NameOnlyWithBackingField)] + [ForEach("StateTransitions"), GenerateProperty("{0}"), WithField] + public StateTransition TransitionProperty { get; set; } - [TemplateProperty] - public override string Name - { - get + [GenerateProperty] + public override string Name { - Ctx._("return \"{0}\"",Ctx.Data.Name); - return "Idle"; + get + { + Ctx._("return \"{0}\"", Ctx.Data.Name); + return null; + } } - } - [TemplateMethod(MemberGeneratorLocation.DesignerFile, AutoFill = AutoFillType.NameOnly, NameFormat = "{0}Transition")] - public void TransitionInvoker() - { - Ctx._("this.Transition(this.{0})",Ctx.Item.Name); - } + //[GenerateMethod(TemplateLocation.DesignerFile, AutoFill = AutoFillType.NameOnly, NameFormat = "{0}Transition")] + [ForEach("StateTransitions"), GenerateMethod(CallBase = false), WithNameFormat("{0}Transition")] + public void TransitionMethod() + { + Ctx._("this.Transition(this.{0})", Ctx.Item.Name); + } -} \ No newline at end of file + } +} diff --git a/Editor/Templates/SystemLoaderTemplate.cs b/Editor/Templates/SystemLoaderTemplate.cs new file mode 100644 index 00000000..2d3d917b --- /dev/null +++ b/Editor/Templates/SystemLoaderTemplate.cs @@ -0,0 +1,125 @@ +using System.CodeDom; +using System.Linq; +using Invert.Core; +using Invert.Core.GraphDesigner; +using Invert.uFrame.MVVM; +using uFrame.Graphs; +using uFrame.Kernel; +using UnityEngine; + +namespace uFrame.MVVM.Templates +{ + [TemplateClass(TemplateLocation.Both, "{0}Loader")] + public partial class SystemLoaderTemplate : IClassTemplate + { + public void TemplateSetup() + { + this.Ctx.TryAddNamespace("uFrame.IOC"); + this.Ctx.TryAddNamespace("uFrame.Kernel"); + this.Ctx.TryAddNamespace("uFrame.MVVM"); + foreach (var property in Ctx.Data.PersistedItems.OfType()) + { + var type = InvertApplication.FindTypeByName(property.RelatedTypeName); + if (type == null) continue; + + Ctx.TryAddNamespace(type.Namespace); + } + + if (Ctx.IsDesignerFile) + { + Ctx.CurrentDecleration.BaseTypes.Add(typeof (MonoBehaviour).ToCodeReference()); + Ctx.SetBaseType(typeof (SystemLoader)); + } + + //Ctx.AddIterator("InstanceProperty", node => node.Instances); + Ctx.AddIterator("ControllerProperty", + node => node.GetContainingNodesInProject(Ctx.Data.Project).OfType()); + } + + [GenerateMethod(CallBase = true), Inside(TemplateLocation.Both)] + public void Load() + { + Ctx.CurrentMethod.Attributes |= MemberAttributes.Override; + + if (!Ctx.IsDesignerFile) + Ctx.CurrentMethod.invoke_base(); + + if (Ctx.IsDesignerFile) + { + + foreach ( + var item in Ctx.Data.GetContainingNodesInProject(Ctx.Data.Project).OfType().Distinct()) + { + Ctx._("Container.RegisterViewModelManager<{0}>(new ViewModelManager<{0}>())", + item.Name.AsViewModel()); + Ctx._("Container.RegisterController<{0}>({0})", item.Name.AsController()); + } + + foreach (var item in Ctx.Data.Instances.Distinct()) + { + Ctx._("Container.RegisterViewModel<{0}>({1}, \"{1}\")", item.SourceItem.Name.AsViewModel(), + item.Name, item.Name); + } + + + } + + } + + + //[Inject("LocalPlayer")] + [ForEach("Instances"), GenerateProperty] + public virtual ViewModel _Name_ + { + get + { + var instance = Ctx.ItemAs(); + Ctx.SetType(instance.SourceItem.Name.AsViewModel()); + + Ctx.AddAttribute(typeof (uFrame.IOC.InjectAttribute)) + .Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(instance.Name))); + + Ctx._if("this.{0} == null", instance.Name.AsField()) + .TrueStatements._("this.{0} = this.CreateViewModel<{1}>( \"{2}\")", instance.Name.AsField(), + instance.SourceItem.Name.AsViewModel(), instance.Name); + + Ctx.CurrentDecleration._private_(Ctx.CurrentProperty.Type, instance.Name.AsField()); + Ctx._("return {0}", instance.Name.AsField()); + + return null; + } + set + { + //_LocalPlayer = value; + } + } + + //[Inject()] + [GenerateProperty(uFrameFormats.CONTROLLER_FORMAT)] + public virtual Controller ControllerProperty + { + get + { + Ctx.SetType(Ctx.Item.Name.AsController()); + Ctx.AddAttribute(typeof (uFrame.IOC.InjectAttribute)); + Ctx.CurrentDecleration._private_(Ctx.CurrentProperty.Type, Ctx.Item.Name.AsController().AsField()); + Ctx.LazyGet(Ctx.Item.Name.AsController().AsField(), "Container.CreateInstance(typeof({0})) as {0};", + Ctx.Item.Name.AsController()); + return null; + } + set { Ctx._("{0} = value", Ctx.Item.Name.AsController().AsField()); } + } + + public string OutputPath + { + get { return Path2.Combine(Ctx.Data.Graph.Name, "SystemLoaders"); } + } + + public bool CanGenerate + { + get { return true; } + } + + public TemplateContext Ctx { get; set; } + } +} \ No newline at end of file diff --git a/Editor/Templates/SystemLoaderTemplate.cs.meta b/Editor/Templates/SystemLoaderTemplate.cs.meta new file mode 100644 index 00000000..c102935e --- /dev/null +++ b/Editor/Templates/SystemLoaderTemplate.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: a4d5e6668c27a1845b5590d5f14ca078 +timeCreated: 1433174592 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Templates/ViewComponentTemplate.cs b/Editor/Templates/ViewComponentTemplate.cs index 05a0c1f3..ee3d2c1b 100644 --- a/Editor/Templates/ViewComponentTemplate.cs +++ b/Editor/Templates/ViewComponentTemplate.cs @@ -7,114 +7,109 @@ using Invert.StateMachine; using Invert.uFrame.MVVM; using uFrame.Graphs; +using uFrame.MVVM; -[TemplateClass(MemberGeneratorLocation.Both)] -public partial class ViewComponentTemplate : IClassTemplate, IClassRefactorable +namespace uFrame.MVVM.Templates { - public string OutputPath + [TemplateClass(TemplateLocation.Both)] + public partial class ViewComponentTemplate : IClassTemplate, IClassRefactorable { - get { return Path2.Combine(Ctx.Data.Graph.Name, "ViewComponents"); } - } - - public bool CanGenerate - { - get { return true; } - } + public string OutputPath + { + get { return Path2.Combine(Ctx.Data.Graph.Name, "ViewComponents"); } + } - public void TemplateSetup() - { - if (Ctx.IsDesignerFile) + public bool CanGenerate { - Ctx.SetBaseType(InvertApplication.FindType(typeof (ViewComponent).FullName)); + get { return true; } } - foreach (var property in Ctx.Data.View.Element.PersistedItems.OfType()) + + public void TemplateSetup() { - var type = InvertApplication.FindTypeByName(property.RelatedTypeName); - if (type == null) continue; + this.Ctx.TryAddNamespace("uFrame.Kernel"); + this.Ctx.TryAddNamespace("uFrame.MVVM"); + this.Ctx.TryAddNamespace("uFrame.MVVM.Bindings"); + this.Ctx.TryAddNamespace("uFrame.Serialization"); + if (Ctx.IsDesignerFile) + { + Ctx.SetBaseType(typeof(ViewComponent)); + } + foreach (var property in Ctx.Data.View.Element.PersistedItems.OfType()) + { + var type = InvertApplication.FindTypeByName(property.RelatedTypeName); + if (type == null) continue; + + Ctx.TryAddNamespace(type.Namespace); + } + Ctx.AddIterator("ExecuteCommandOverload", _ => _.View.Element.LocalCommands); + //Ctx.AddIterator("ExecuteCommand", _ => _.View.Element.InheritedCommandsWithLocal.Where(p => string.IsNullOrEmpty(p.RelatedTypeName))); + ////Ctx.AddIterator("ExecuteCommandOverload", _ => _.View.Element.InheritedCommandsWithLocal); + //Ctx.AddIterator("ExecuteCommandWithArg", _ => _.View.Element.InheritedCommandsWithLocal.Where(p => !string.IsNullOrEmpty(p.RelatedTypeName) && p.OutputCommand == null)); - Ctx.TryAddNamespace(type.Namespace); } - //Ctx.AddIterator("ExecuteCommand", _ => _.View.Element.InheritedCommandsWithLocal.Where(p => string.IsNullOrEmpty(p.RelatedTypeName))); - ////Ctx.AddIterator("ExecuteCommandOverload", _ => _.View.Element.InheritedCommandsWithLocal); - //Ctx.AddIterator("ExecuteCommandWithArg", _ => _.View.Element.InheritedCommandsWithLocal.Where(p => !string.IsNullOrEmpty(p.RelatedTypeName) && p.OutputCommand == null)); - - } + public TemplateContext Ctx { get; set; } - public TemplateContext Ctx { get; set; } + public string ElementName + { + get + { + return Ctx.Data.View.Element.Name; + } + } - public string ElementName - { - get + [GenerateProperty] + public virtual object _ElementName_ { - return Ctx.Data.View.Element.Name; + get + { + Ctx.CurrentProperty.Type = Ctx.Data.View.Element.Name.AsViewModel().ToCodeReference(); + Ctx._("return ({0})this.View.ViewModelObject", Ctx.Data.View.Element.Name.AsViewModel()); + return null; + } } - } - [TemplateProperty] - public virtual object _ElementName_ - { - get + public IEnumerable CommandsWithArguments { - Ctx.CurrentProperty.Type = Ctx.Data.View.Element.Name.AsViewModel().ToCodeReference(); - Ctx._("return ({0})this.View.ViewModelObject", Ctx.Data.View.Element.Name.AsViewModel()); - return null; + get { return Ctx.Data.View.Element.InheritedCommandsWithLocal.Where(p => !string.IsNullOrEmpty(p.RelatedTypeName) && p.OutputCommand == null); } } - } - public IEnumerable CommandsWithArguments - { - get { return Ctx.Data.View.Element.InheritedCommandsWithLocal.Where(p => !string.IsNullOrEmpty(p.RelatedTypeName) && p.OutputCommand == null); } - } + public IEnumerable Commands + { + get { return Ctx.Data.View.Element.InheritedCommandsWithLocal.Where(p => string.IsNullOrEmpty(p.RelatedTypeName)); } + } - public IEnumerable Commands - { - get { return Ctx.Data.View.Element.InheritedCommandsWithLocal.Where(p => string.IsNullOrEmpty(p.RelatedTypeName)); } - } + [ForEach("Commands"), GenerateMethod] + public void Execute_Name_() + { + Ctx._("{0}.{1}.OnNext(new {1}Command() {{ Sender = {0} }})", Ctx.Data.View.Element.Name, Ctx.Item.Name); + } - [ForEach("Commands"), TemplateMethod] - public void Execute_Name_() - { - Ctx._("{0}.{1}.OnNext(new {1}Command() {{ Sender = {0} }})", Ctx.Data.View.Element.Name, Ctx.Item.Name); - } + //[TemplateMethod("Execute{0}", TemplateLocation.DesignerFile, false, AutoFill = AutoFillType.NameOnly)] + [ForEach("CommandsWithArguments"), GenerateMethod(CallBase = false)] + public void Execute_Name2_(object arg) + { + Ctx.CurrentMethod.Parameters[0].Type = new CodeTypeReference(Ctx.TypedItem.RelatedTypeName); + Ctx._("{0}.{1}.OnNext(new {1}Command() {{ Sender = {0}, Argument = arg }})", Ctx.Data.View.Element.Name, Ctx.Item.Name); + } - //[TemplateMethod("Execute{0}", MemberGeneratorLocation.DesignerFile, false, AutoFill = AutoFillType.NameOnly)] - [ForEach("CommandsWithArguments"), TemplateMethod(CallBase = false)] - public void Execute_Name2_(object arg) - { - Ctx.CurrentMethod.Parameters[0].Type = new CodeTypeReference(Ctx.TypedItem.RelatedTypeName); - Ctx._("{0}.{1}.OnNext(new {1}Command() {{ Sender = {0}, Argument = arg }})", Ctx.Data.View.Element.Name, Ctx.Item.Name); - } + [GenerateMethod("Execute{0}", TemplateLocation.DesignerFile, false)] + public void ExecuteCommandOverload(ViewModelCommand command) + { + Ctx.CurrentMethod.Parameters[0].Type = (Ctx.Item.Name + "Command").ToCodeReference(); + Ctx._("command.Sender = {0}", Ctx.Data.View.Element.Name); + Ctx._("{0}.{1}.OnNext(command)", Ctx.Data.View.Element.Name, Ctx.Item.Name); + //Ctx._("this.ExecuteCommand({0}.{1})", Ctx.Data.Element.Name, Ctx.Item.Name); + } - public IEnumerable ClassNameFormats - { - get + public IEnumerable ClassNameFormats { - yield return "{0}"; - yield return "{0}Base"; + get + { + yield return "{0}"; + yield return "{0}Base"; + } } } -} - -//public partial class ViewComponentTemplate : IClassTemplate -//{ -// public bool Nope -// { -// get { return true; } -// } - -// [ForEach("Properties"), TemplateProperty, WithField, If("Nope")] -// public _ITEMTYPE_ _Name_Property { get; set; } - - -// [ForEach("Commands"), TemplateMethod] -// public void Execute_Name_(ViewModelCommand command) -// { -// Ctx.CurrentMethod.Parameters[0].Type = (Ctx.Item.Name + "Command").ToCodeReference(); -// Ctx._("command.Sender = {0}", Ctx.Data.View.Element.Name); -// Ctx._("{0}.{1}.OnNext(command)", Ctx.Data.View.Element.Name, Ctx.Item.Name); -// } - - -//} \ No newline at end of file +} \ No newline at end of file diff --git a/Editor/Templates/ViewModelCommandClassTemplate.cs b/Editor/Templates/ViewModelCommandClassTemplate.cs new file mode 100644 index 00000000..7dd8adad --- /dev/null +++ b/Editor/Templates/ViewModelCommandClassTemplate.cs @@ -0,0 +1,58 @@ +using System.Collections.Generic; +using Invert.Core; +using Invert.Core.GraphDesigner; +using Invert.uFrame.MVVM; + +namespace uFrame.MVVM.Templates +{ + [TemplateClass(TemplateLocation.DesignerFile, ClassNameFormat = "{0}Command")] + public partial class ViewModelCommandClassTemplate : ViewModelCommand, IClassTemplate, + IClassRefactorable + { + public string OutputPath + { + get { return Path2.Combine(Ctx.Data.Node.Graph.Name, "Commands"); } + } + + public bool CanGenerate + { + get { return Ctx.Data.OutputCommand == null; } + } + + public void TemplateSetup() + { + this.Ctx.TryAddNamespace("uFrame.Kernel"); + this.Ctx.TryAddNamespace("uFrame.MVVM"); + this.Ctx.TryAddNamespace("uFrame.Serialization"); + var type = InvertApplication.FindTypeByName(Ctx.Data.RelatedTypeName); + if (type != null) + { + Ctx.TryAddNamespace(type.Namespace); + } + else + { + type = InvertApplication.FindType(Ctx.Data.RelatedTypeName); + if (type != null) + Ctx.TryAddNamespace(type.Namespace); + } + Ctx.CurrentDecleration.IsPartial = true; + Ctx.CurrentDecleration.Name = Ctx.Data.Name + "Command"; + Ctx.AddCondition("Argument", _ => !string.IsNullOrEmpty(_.RelatedType)); + } + + public TemplateContext Ctx { get; set; } + + public bool HasArgument + { + get { return !string.IsNullOrEmpty(Ctx.Data.RelatedType); } + } + + [GenerateProperty, WithField, If("HasArgument")] + public _ITEMTYPE_ Argument { get; set; } + + public IEnumerable ClassNameFormats + { + get { yield return "{0}Command"; } + } + } +} \ No newline at end of file diff --git a/Editor/Templates/ViewModelCommandClassTemplate.cs.meta b/Editor/Templates/ViewModelCommandClassTemplate.cs.meta new file mode 100644 index 00000000..cb84f208 --- /dev/null +++ b/Editor/Templates/ViewModelCommandClassTemplate.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: a29ff8caac6a46047bd752e6ca317803 +timeCreated: 1433229788 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Templates/ViewModelConstructorTemplate.cs b/Editor/Templates/ViewModelConstructorTemplate.cs new file mode 100644 index 00000000..69ba8e99 --- /dev/null +++ b/Editor/Templates/ViewModelConstructorTemplate.cs @@ -0,0 +1,41 @@ +using Invert.Core.GraphDesigner; +using Invert.uFrame.MVVM; +using uFrame.Graphs; +using uFrame.Kernel; + +namespace uFrame.MVVM.Templates +{ + [TemplateClass(TemplateLocation.DesignerFile, ClassNameFormat = uFrameFormats.VIEW_MODEL_FORMAT)] + public partial class ViewModelConstructorTemplate : IClassTemplate + { + public TemplateContext Ctx { get; set; } + + public string OutputPath + { + get { return Path2.Combine(Ctx.Data.Graph.Name, "ViewModels"); } + } + + [GenerateConstructor("aggregator")] + public void AggregatorConstructor(IEventAggregator aggregator) + { + + } + + public bool CanGenerate + { + get { return true; } + } + + public void TemplateSetup() + { + this.Ctx.TryAddNamespace("uFrame.Kernel"); + this.Ctx.TryAddNamespace("uFrame.MVVM"); + this.Ctx.TryAddNamespace("uFrame.Serialization"); + // Ensure the namespaces for each property type are property set up + Ctx.CurrentDecleration.BaseTypes.Clear(); + Ctx.CurrentDecleration.IsPartial = true; + Ctx.CurrentDecleration.Name = string.Format(uFrameFormats.VIEW_MODEL_FORMAT, Ctx.Data.Name); + } + + } +} \ No newline at end of file diff --git a/Editor/Templates/ViewModelConstructorTemplate.cs.meta b/Editor/Templates/ViewModelConstructorTemplate.cs.meta new file mode 100644 index 00000000..79773001 --- /dev/null +++ b/Editor/Templates/ViewModelConstructorTemplate.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: bea130e2942be2e4ba48fe9c53a234cb +timeCreated: 1433229788 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Templates/ViewModelTemplate.cs b/Editor/Templates/ViewModelTemplate.cs index 13511d99..c6fce925 100644 --- a/Editor/Templates/ViewModelTemplate.cs +++ b/Editor/Templates/ViewModelTemplate.cs @@ -1,5 +1,4 @@ using System; -using System.CodeDom; using System.Collections.Generic; using System.ComponentModel; using System.Linq; @@ -8,611 +7,461 @@ using Invert.StateMachine; using Invert.uFrame.MVVM; using uFrame.Graphs; +using uFrame.Kernel; using UnityEngine; -[TemplateClass(MemberGeneratorLocation.Both, ClassNameFormat = uFrameFormats.VIEW_MODEL_FORMAT)] -public partial class ViewModelTemplate : ViewModel, IClassTemplate, IClassRefactorable +namespace uFrame.MVVM.Templates { - #region Template Stuff - public TemplateContext Ctx { get; set; } - - public string OutputPath - { - get { return Path2.Combine(Ctx.Data.Graph.Name, "ViewModels"); } - } - - public bool CanGenerate - { - get { return true; } - } - - public void TemplateSetup() - { - // Ensure the namespaces for each property type are property set up - Ctx.CurrentDecleration.IsPartial = true; - Ctx.TryAddNamespace("UnityEngine"); - Ctx.TryAddNamespace("UniRx"); - - foreach (var property in Ctx.Data.PersistedItems.OfType()) - { - var type = InvertApplication.FindTypeByName(property.RelatedTypeName); - if (type == null) continue; - - Ctx.TryAddNamespace(type.Namespace); - } - - StateMachineProperties = Ctx.Data.AllProperties.Where(p => (p.RelatedNode() is StateMachineNode)).ToArray(); - ViewModelProperties = Ctx.Data.AllProperties.Where(p => !StateMachineProperties.Contains(p)).ToArray(); - - foreach (var item in Ctx.Data.ComputedProperties) - { - Ctx.CurrentDecleration._private_(typeof(IDisposable), "_{0}Disposable", item.Name); - } - } - - public ITypedItem[] ViewModelProperties { get; set; } - - public ITypedItem[] StateMachineProperties { get; set; } - - #endregion - - - [TemplateConstructor(MemberGeneratorLocation.DesignerFile, "aggregator")] - public void AggregatorConstructor(IEventAggregator aggregator) + [TemplateClass(TemplateLocation.Both, ClassNameFormat = uFrameFormats.VIEW_MODEL_FORMAT)] + public partial class ViewModelTemplate : ViewModel, IClassTemplate, IClassRefactorable { + #region Template Stuff - } + public TemplateContext Ctx { get; set; } - [TemplateMethod] - public override void Bind() - { - if (!Ctx.IsDesignerFile) return; - foreach (var command in Ctx.Data.LocalCommands) - { - Ctx._("this.{0} = new Signal<{0}Command>(this)", command.Name); - } - foreach (var property in ViewModelProperties) + public string OutputPath { - Ctx._("{0} = new P<{1}>(this, \"{2}\")", property.Name.AsSubscribableField(), property.RelatedTypeName, property.Name); - } - // No more parents so no need to bind to the collection change, this was bad anyways - foreach (var property in Ctx.Data.LocalCollections) - { - Ctx._("{0} = new ModelCollection<{1}>(this, \"{2}\")", property.Name.AsField(), property.RelatedTypeName, property.Name); - // Ctx._("{0}.CollectionChanged += {1}CollectionChanged", property.Name.AsField(), property.Name); + get { return Path2.Combine(Ctx.Data.Graph.Name, "ViewModels"); } } - foreach (var item in StateMachineProperties) - { - Ctx._("{0} = new {1}(this, \"{2}\")", item.Name.AsSubscribableField(), item.RelatedTypeName, item.Name); - } - foreach (var item in Ctx.Data.ComputedProperties) + public bool CanGenerate { - Ctx._("Reset{0}()", item.Name); + get { return true; } } - //_StateMachineProperty.B.AddComputer(IsCorrectPasswordProperty); - foreach (var item in Ctx.Data.ComputedProperties) - { - - var transition = item.OutputTo(); - if (transition == null) continue; - var stateMachineNode = transition.Node as IClassTypeNode; - var property = stateMachineNode.ReferencesOf().FirstOrDefault(p => p.Node == Ctx.Data); - if (property == null) continue; - Ctx._("{0}.{1}.AddComputer({2})", property.Name.AsSubscribableProperty(), transition.Name, item.Name.AsSubscribableProperty()); - } - foreach (var item in Ctx.Data.LocalCommands) + public void TemplateSetup() { - //Transition.Subscribe(_ => StateMachineProperty.B.OnNext(true)); - var transition = item.OutputTo(); - if (transition == null) continue; - var stateMachineNode = transition.Node as IClassTypeNode; - var property = stateMachineNode.ReferencesOf().FirstOrDefault(p => p.Node == Ctx.Data); - if (property == null) continue; - Ctx._("{0}.Subscribe(_ => {1}.{2}.OnNext(true))", item.Name, property.Name.AsSubscribableProperty(), transition.Name); - - } + // Ensure the namespaces for each property type are property set up + Ctx.CurrentDecleration.IsPartial = true; + Ctx.TryAddNamespace("uFrame.IOC"); + Ctx.TryAddNamespace("uFrame.Kernel"); + Ctx.TryAddNamespace("uFrame.MVVM"); + Ctx.TryAddNamespace("uFrame.MVVM.Bindings"); + Ctx.TryAddNamespace("uFrame.Serialization"); + Ctx.TryAddNamespace("UnityEngine"); + Ctx.TryAddNamespace("UniRx"); + - } + foreach (var property in Ctx.Data.PersistedItems.OfType()) + { + var type = InvertApplication.FindTypeByName(property.RelatedTypeName); + if (type == null) continue; + Ctx.TryAddNamespace(type.Namespace); + } - #region Properties + StateMachineProperties = Ctx.Data.AllProperties.Where(p => (p.RelatedNode() is StateMachineNode)).ToArray(); + ViewModelProperties = Ctx.Data.AllProperties.Where(p => !StateMachineProperties.Contains(p)).ToArray(); + if (Ctx.IsDesignerFile) + { + foreach (var item in Ctx.Data.ComputedProperties) + { + Ctx.CurrentDecleration._private_(typeof (IDisposable), "_{0}Disposable", item.Name); + } + } - //[TemplateProperty(uFrameFormats.SUBSCRIBABLE_PROPERTY_FORMAT, AutoFillType.NameAndTypeWithBackingField)] - [ForEach("StateMachineProperties"),TemplateProperty, WithField] - public virtual _ITEMTYPE_ _Name2_Property - { - get - { - return null; } - } - //[TemplateProperty(MemberGeneratorLocation.DesignerFile, AutoFillType.NameOnly)] - [ForEach("StateMachineProperties"),TemplateProperty] - public virtual State _Name2_ - { - get - { - Ctx._("return {0}.Value", Ctx.Item.Name.AsSubscribableProperty()); - return null; - } - set - { - Ctx._("{0}.Value = value", Ctx.Item.Name.AsSubscribableProperty()); - } - } - #endregion + public ITypedItem[] ViewModelProperties { get; set; } - #region Properties + public ITypedItem[] StateMachineProperties { get; set; } - //[TemplateProperty(uFrameFormats.SUBSCRIBABLE_PROPERTY_FORMAT, AutoFillType.NameAndTypeWithBackingField)] - [ForEach("ViewModelProperties"), TemplateProperty, WithField] - public virtual P<_ITEMTYPE_> _Name_Property - { - get { return null; } + #endregion - } - [ForEach("ViewModelProperties"), TemplateProperty] - public virtual _ITEMTYPE_ _Name_ - { - get - { - Ctx._("return {0}.Value", Ctx.Item.Name.AsSubscribableProperty()); - return null; - } - set + [GenerateConstructor(TemplateLocation.DesignerFile, "aggregator")] + public void AggregatorConstructor(IEventAggregator aggregator) { - Ctx._("{0}.Value = value", Ctx.Item.Name.AsSubscribableProperty()); - } - } - #endregion - #region Collections - //[TemplateProperty(MemberGeneratorLocation.DesignerFile, AutoFillType.NameAndTypeWithBackingField)] - [ForEach("LocalCollections"), TemplateProperty, WithField] - public virtual ModelCollection<_ITEMTYPE_> _Name4_ - { - get { return null; } - } - - #endregion - - #region Commands - // [TemplateProperty("{0}", AutoFillType.NameOnlyWithBackingField)] - [ForEach("LocalCommands"), TemplateProperty, WithField] - public virtual object _Name3_ - { - get - { - Ctx.SetType("Signal<{0}Command>", Ctx.Item.Name); - return null; } - set - { - - } - } - #endregion - #region Serialization - [TemplateMethod] - public override void Read(ISerializerStream stream) - { - foreach (var viewModelPropertyData in Ctx.Data.LocalProperties) + [GenerateMethod] + public override void Bind() { - - var relatedNode = viewModelPropertyData.RelatedTypeNode; - if (relatedNode is EnumNode) + if (!Ctx.IsDesignerFile) return; + foreach (var command in Ctx.Data.LocalCommands) { - Ctx._("this.{0} = ({1})stream.DeserializeInt(\"{0}\");", viewModelPropertyData.Name, viewModelPropertyData.RelatedTypeName); + Ctx._("this.{0} = new Signal<{0}Command>(this)", command.Name); } - else if (relatedNode is ElementNode) + foreach (var property in ViewModelProperties) { - var elementNode = relatedNode as ElementNode; - Ctx._("\t\tif (stream.DeepSerialize) this.{0} = stream.DeserializeObject<{1}>(\"{0}\");", viewModelPropertyData.Name, elementNode.Name.AsViewModel()); - + Ctx._("{0} = new P<{1}>(this, \"{2}\")", property.Name.AsSubscribableField(), property.RelatedTypeName, + property.Name); } - else if (relatedNode is StateMachineNode) + // No more parents so no need to bind to the collection change, this was bad anyways + foreach (var property in Ctx.Data.LocalCollections) { - Ctx._("this.{0}.SetState(stream.DeserializeString(\"{1}\"))", viewModelPropertyData.FieldName, viewModelPropertyData.Name); + Ctx._("{0} = new ModelCollection<{1}>(this, \"{2}\")", property.Name.AsField(), property.RelatedTypeName, + property.Name); + // Ctx._("{0}.CollectionChanged += {1}CollectionChanged", property.Name.AsField(), property.Name); } - else + + foreach (var item in StateMachineProperties) { - if (viewModelPropertyData.Type == null) continue; - if (!AcceptableTypes.ContainsKey(viewModelPropertyData.Type)) continue; - Ctx._("this.{0} = stream.Deserialize{1}(\"{0}\");", viewModelPropertyData.Name, AcceptableTypes[viewModelPropertyData.Type]); + Ctx._("{0} = new {1}(this, \"{2}\")", item.Name.AsSubscribableField(), item.RelatedTypeName, item.Name); } - } - foreach (var collection in Ctx.Data.LocalCollections) - { - var relatedNode = collection.RelatedTypeNode; - if (relatedNode is EnumNode) + foreach (var item in Ctx.Data.ComputedProperties) { - //var statement = new CodeSnippetStatement(string.Format("\t\tstream.SerializeInt(\"{0}\", (int)this.{0});", viewModelPropertyData.Name)); - //writeMethod.Statements.Add(statement); - - //var dstatement = new CodeSnippetStatement(string.Format("\t\tthis.{0} = ({1})stream.DeserializeInt(\"{0}\");", viewModelPropertyData.Name, viewModelPropertyData.RelatedTypeName)); - //readMethod.Statements.Add(dstatement); + Ctx._("Reset{0}()", item.Name); } - else if (relatedNode is ElementNode) + //_StateMachineProperty.B.AddComputer(IsCorrectPasswordProperty); + foreach (var item in Ctx.Data.ComputedProperties) { - var elementNode = relatedNode as ElementNode; - Ctx.PushStatements(Ctx._if("stream.DeepSerialize").TrueStatements); - Ctx._("this.{0}.Clear()", collection.Name); - Ctx._("this.{0}.AddRange(stream.DeserializeObjectArray<{1}>(\"{0}\"))", collection.Name, elementNode.Name.AsViewModel()); - Ctx.PopStatements(); + var transition = item.OutputTo(); + if (transition == null) continue; + var stateMachineNode = transition.Node as IClassTypeNode; + var property = + stateMachineNode.ReferencesOf().FirstOrDefault(p => p.Node == Ctx.Data); + if (property == null) continue; + Ctx._("{0}.{1}.AddComputer({2})", property.Name.AsSubscribableProperty(), transition.Name, + item.Name.AsSubscribableProperty()); + } - else + foreach (var item in Ctx.Data.LocalCommands) { - //if (collection.Type == null) continue; - //if (!AcceptableTypes.ContainsKey(viewModelPropertyData.Type)) continue; - //viewModelPropertyData.IsEnum(data.OwnerData); - //var statement = new CodeSnippetStatement(string.Format("\t\tstream.Serialize{0}(\"{1}\", this.{1});", AcceptableTypes[viewModelPropertyData.Type], viewModelPropertyData.Name)); - //writeMethod.Statements.Add(statement); - - //var dstatement = new CodeSnippetStatement(string.Format("\t\tthis.{0} = stream.Deserialize{1}(\"{0}\");", viewModelPropertyData.Name, AcceptableTypes[viewModelPropertyData.Type])); - //readMethod.Statements.Add(dstatement); + //Transition.Subscribe(_ => StateMachineProperty.B.OnNext(true)); + var transition = item.OutputTo(); + if (transition == null) continue; + var stateMachineNode = transition.Node as IClassTypeNode; + var property = + stateMachineNode.ReferencesOf().FirstOrDefault(p => p.Node == Ctx.Data); + if (property == null) continue; + Ctx._("{0}.Subscribe(_ => {1}.{2}.OnNext(true))", item.Name, property.Name.AsSubscribableProperty(), + transition.Name); + } + + } - } - [TemplateMethod] - public override void Write(ISerializerStream stream) - { - foreach (var viewModelPropertyData in Ctx.Data.LocalProperties) - { - var relatedNode = viewModelPropertyData.RelatedTypeNode; - if (relatedNode is EnumNode) - { - Ctx._("stream.SerializeInt(\"{0}\", (int)this.{0});", viewModelPropertyData.Name); + #region Properties - } - else if (relatedNode is ElementNode) - { - Ctx._("if (stream.DeepSerialize) stream.SerializeObject(\"{0}\", this.{0});", viewModelPropertyData.Name); - } - else if (relatedNode is StateMachineNode) - { + //[TemplateProperty(uFrameFormats.SUBSCRIBABLE_PROPERTY_FORMAT, AutoFillType.NameAndTypeWithBackingField)] + [ForEach("StateMachineProperties"), GenerateProperty, WithField] + public virtual _ITEMTYPE_ _Name2_Property + { + get { return null; } + } - Ctx._("stream.SerializeString(\"{0}\", this.{0}.Name);", viewModelPropertyData.Name); - } - else + //[TemplateProperty(TemplateLocation.DesignerFile, AutoFillType.NameOnly)] + [ForEach("StateMachineProperties"), GenerateProperty] + public virtual State _Name2_ + { + get { - if (viewModelPropertyData.Type == null) continue; - if (!AcceptableTypes.ContainsKey(viewModelPropertyData.Type)) continue; - Ctx._("stream.Serialize{0}(\"{1}\", this.{1})", AcceptableTypes[viewModelPropertyData.Type], viewModelPropertyData.Name); + Ctx._("return {0}.Value", Ctx.Item.Name.AsSubscribableProperty()); + return null; } + set { Ctx._("{0}.Value = value", Ctx.Item.Name.AsSubscribableProperty()); } } - foreach (var collection in Ctx.Data.LocalCollections) + + #endregion + + #region Properties + + //[TemplateProperty(uFrameFormats.SUBSCRIBABLE_PROPERTY_FORMAT, AutoFillType.NameAndTypeWithBackingField)] + [ForEach("ViewModelProperties"), GenerateProperty, WithField] + public virtual P<_ITEMTYPE_> _Name_Property { - var relatedNode = collection.RelatedTypeNode; - if (relatedNode is EnumNode) - { - //var statement = new CodeSnippetStatement(string.Format("\t\tstream.SerializeInt(\"{0}\", (int)this.{0});", viewModelPropertyData.Name)); - //writeMethod.Statements.Add(statement); + get { return null; } - //var dstatement = new CodeSnippetStatement(string.Format("\t\tthis.{0} = ({1})stream.DeserializeInt(\"{0}\");", viewModelPropertyData.Name, viewModelPropertyData.RelatedTypeName)); - //readMethod.Statements.Add(dstatement); - } - else if (relatedNode is ElementNode) - { - Ctx._("if (stream.DeepSerialize) stream.SerializeArray(\"{0}\", this.{0})", - collection.Name); - } - else + } + + [ForEach("ViewModelProperties"), GenerateProperty] + public virtual _ITEMTYPE_ _Name_ + { + get { - //if (collection.Type == null) continue; - //if (!AcceptableTypes.ContainsKey(viewModelPropertyData.Type)) continue; - //viewModelPropertyData.IsEnum(data.OwnerData); - //var statement = new CodeSnippetStatement(string.Format("\t\tstream.Serialize{0}(\"{1}\", this.{1});", AcceptableTypes[viewModelPropertyData.Type], viewModelPropertyData.Name)); - //writeMethod.Statements.Add(statement); - - //var dstatement = new CodeSnippetStatement(string.Format("\t\tthis.{0} = stream.Deserialize{1}(\"{0}\");", viewModelPropertyData.Name, AcceptableTypes[viewModelPropertyData.Type])); - //readMethod.Statements.Add(dstatement); + Ctx._("return {0}.Value", Ctx.Item.Name.AsSubscribableProperty()); + return null; } + set { Ctx._("{0}.Value = value", Ctx.Item.Name.AsSubscribableProperty()); } } - } - #endregion - #region Reflection + #endregion - [TemplateMethod] - protected override void FillCommands(List list) - { - //base.FillCommands(list); - foreach (var commandChildItem in Ctx.Data.LocalCommands) + #region Collections + + //[TemplateProperty(TemplateLocation.DesignerFile, AutoFillType.NameAndTypeWithBackingField)] + [ForEach("LocalCollections"), GenerateProperty, WithField] + public virtual ModelCollection<_ITEMTYPE_> _Name4_ { - Ctx._("list.Add(new ViewModelCommandInfo(\"{0}\", {0}) {{ ParameterType = typeof({1}) }})", - commandChildItem.Name, - string.IsNullOrEmpty(commandChildItem.RelatedTypeName) ? "void" : commandChildItem.RelatedTypeName - ); + get { return null; } } - } + #endregion + #region Commands - [TemplateMethod] - protected override void FillProperties(List list) - { - //base.FillProperties(list); - foreach (var property in Ctx.Data.AllProperties) - { - Ctx._comment(property.GetType().Name); - Ctx._("list.Add(new ViewModelPropertyInfo({0}, {1}, {2}, {3}, {4}))", - property.Name.AsSubscribableField(), - property.RelatedNode() is ElementNode ? "true" : "false", - "false", - property.RelatedNode() is EnumNode ? "true" : "false", // TODO FOR ENUMS - property is ComputedPropertyNode ? "true" : "false" - - ); - } - foreach (var property in Ctx.Data.LocalCollections) + // [TemplateProperty("{0}", AutoFillType.NameOnlyWithBackingField)] + [ForEach("LocalCommands"), GenerateProperty, WithField] + public virtual object _Name3_ { - Ctx._("list.Add(new ViewModelPropertyInfo({0}, {1}, {2}, {3}, {4}))", - property.Name.AsField(), - property.RelatedNode() is ElementNode ? "true" : "false", - "true", - property.RelatedNode() is EnumNode ? "true" : "false", // TODO FOR ENUMS - "false" - ); + get + { + Ctx.SetType("Signal<{0}Command>", Ctx.Item.Name); + return null; + } + set { } } - } - #endregion + #endregion + #region Serialization - // [TemplateMethod(MemberGeneratorLocation.DesignerFile, AutoFill = AutoFillType.NameOnly, NameFormat = "Get{0}Dependents")] - [ForEach("ComputedProperties"), TemplateMethod] - public virtual IEnumerable Get_Name_Dependents() - { - var computed = Ctx.ItemAs(); - foreach (var item in computed.InputsFrom()) + [GenerateMethod] + public override void Read(ISerializerStream stream) { + foreach (var viewModelPropertyData in Ctx.Data.LocalProperties) + { - Ctx._("yield return {0}", item.Name.AsSubscribableProperty()); - var relatedNode = item.RelatedTypeNode; - if (relatedNode != null) + var relatedNode = viewModelPropertyData.RelatedTypeNode; + if (relatedNode is EnumNode) + { + Ctx._("this.{0} = ({1})stream.DeserializeInt(\"{0}\");", viewModelPropertyData.Name, + viewModelPropertyData.RelatedTypeName); + } + else if (relatedNode is ElementNode) + { + var elementNode = relatedNode as ElementNode; + Ctx._("\t\tif (stream.DeepSerialize) this.{0} = stream.DeserializeObject<{1}>(\"{0}\");", + viewModelPropertyData.Name, elementNode.Name.AsViewModel()); + + } + else if (relatedNode is StateMachineNode) + { + Ctx._("this.{0}.SetState(stream.DeserializeString(\"{1}\"))", viewModelPropertyData.FieldName, + viewModelPropertyData.Name); + } + else + { + if (viewModelPropertyData.Type == null) continue; + if (!AcceptableTypes.ContainsKey(viewModelPropertyData.Type)) continue; + Ctx._("this.{0} = stream.Deserialize{1}(\"{0}\");", viewModelPropertyData.Name, + AcceptableTypes[viewModelPropertyData.Type]); + } + } + foreach (var collection in Ctx.Data.LocalCollections) { - var conditionStatements = Ctx._if("{0}.Value != null", item.Name.AsSubscribableProperty()) - .TrueStatements; - foreach (var p in computed.SubProperties.Where(p => p.SourceItem.Node == relatedNode)) + var relatedNode = collection.RelatedTypeNode; + if (relatedNode is EnumNode) { - conditionStatements._("yield return {0}.Value.{1}", item.Name.AsSubscribableProperty(), p.Name.AsSubscribableProperty()); + //var statement = new CodeSnippetStatement(string.Format("\t\tstream.SerializeInt(\"{0}\", (int)this.{0});", viewModelPropertyData.Name)); + //writeMethod.Statements.Add(statement); + + //var dstatement = new CodeSnippetStatement(string.Format("\t\tthis.{0} = ({1})stream.DeserializeInt(\"{0}\");", viewModelPropertyData.Name, viewModelPropertyData.RelatedTypeName)); + //readMethod.Statements.Add(dstatement); + } + else if (relatedNode is ElementNode) + { + var elementNode = relatedNode as ElementNode; + + Ctx.PushStatements(Ctx._if("stream.DeepSerialize").TrueStatements); + Ctx._("this.{0}.Clear()", collection.Name); + Ctx._("this.{0}.AddRange(stream.DeserializeObjectArray<{1}>(\"{0}\"))", collection.Name, + elementNode.Name.AsViewModel()); + Ctx.PopStatements(); + } + else + { + //if (collection.Type == null) continue; + //if (!AcceptableTypes.ContainsKey(viewModelPropertyData.Type)) continue; + //viewModelPropertyData.IsEnum(data.OwnerData); + //var statement = new CodeSnippetStatement(string.Format("\t\tstream.Serialize{0}(\"{1}\", this.{1});", AcceptableTypes[viewModelPropertyData.Type], viewModelPropertyData.Name)); + //writeMethod.Statements.Add(statement); + + //var dstatement = new CodeSnippetStatement(string.Format("\t\tthis.{0} = stream.Deserialize{1}(\"{0}\");", viewModelPropertyData.Name, AcceptableTypes[viewModelPropertyData.Type])); + //readMethod.Statements.Add(dstatement); } } } - foreach (var item in computed.InputsFrom()) - { - Ctx._("yield return {0}", item.Name.AsSubscribableField()); - } + [GenerateMethod] + public override void Write(ISerializerStream stream) + { + foreach (var viewModelPropertyData in Ctx.Data.LocalProperties) + { - Ctx._("yield break"); - - yield break; - } - - //[TemplateMethod(MemberGeneratorLocation.DesignerFile, AutoFill = AutoFillType.NameOnly, NameFormat = "Reset{0}")] - [ForEach("ComputedProperties"),TemplateMethod] - public virtual void Reset_Name_() - { - var computed = Ctx.ItemAs(); - Ctx._if("_{0}Disposable != null", computed.Name) - .TrueStatements._("_{0}Disposable.Dispose()", computed.Name); - Ctx._("_{0}Disposable = {1}.ToComputed(Compute{0}, this.Get{0}Dependents().ToArray()).DisposeWith(this)", computed.Name, computed.Name.AsSubscribableField()); + var relatedNode = viewModelPropertyData.RelatedTypeNode; + if (relatedNode is EnumNode) + { + Ctx._("stream.SerializeInt(\"{0}\", (int)this.{0});", viewModelPropertyData.Name); - } + } + else if (relatedNode is ElementNode) + { + Ctx._("if (stream.DeepSerialize) stream.SerializeObject(\"{0}\", this.{0});", + viewModelPropertyData.Name); + } + else if (relatedNode is StateMachineNode) + { - //[TemplateMethod(MemberGeneratorLocation.Both, AutoFill = AutoFillType.NameOnly, NameFormat = "Compute{0}")] - [ForEach("ComputedProperties"), TemplateMethod] - public virtual Boolean Compute_Name_() - { - var type = Ctx.ItemAs().RelatedTypeName; - Ctx.SetType(type); - Ctx._("return default({0})", type); - return false; - } + Ctx._("stream.SerializeString(\"{0}\", this.{0}.Name);", viewModelPropertyData.Name); + } + else + { + if (viewModelPropertyData.Type == null) continue; + if (!AcceptableTypes.ContainsKey(viewModelPropertyData.Type)) continue; + Ctx._("stream.Serialize{0}(\"{1}\", this.{1})", AcceptableTypes[viewModelPropertyData.Type], + viewModelPropertyData.Name); + } + } + foreach (var collection in Ctx.Data.LocalCollections) + { + var relatedNode = collection.RelatedTypeNode; + if (relatedNode is EnumNode) + { + //var statement = new CodeSnippetStatement(string.Format("\t\tstream.SerializeInt(\"{0}\", (int)this.{0});", viewModelPropertyData.Name)); + //writeMethod.Statements.Add(statement); - public static Dictionary AcceptableTypes = new Dictionary - { - {typeof(int),"Int" }, - {typeof(Vector3),"Vector3" }, - {typeof(Vector2),"Vector2" }, - {typeof(string),"String" }, - {typeof(bool),"Bool" }, - {typeof(float),"Float" }, - {typeof(double),"Double" }, - {typeof(Quaternion),"Quaternion" }, - }; - - public IEnumerable ClassNameFormats - { - get - { - yield return "{0}ViewModel"; - yield return "{0}ViewModelBase"; + //var dstatement = new CodeSnippetStatement(string.Format("\t\tthis.{0} = ({1})stream.DeserializeInt(\"{0}\");", viewModelPropertyData.Name, viewModelPropertyData.RelatedTypeName)); + //readMethod.Statements.Add(dstatement); + } + else if (relatedNode is ElementNode) + { + Ctx._("if (stream.DeepSerialize) stream.SerializeArray(\"{0}\", this.{0})", + collection.Name); + } + else + { + //if (collection.Type == null) continue; + //if (!AcceptableTypes.ContainsKey(viewModelPropertyData.Type)) continue; + //viewModelPropertyData.IsEnum(data.OwnerData); + //var statement = new CodeSnippetStatement(string.Format("\t\tstream.Serialize{0}(\"{1}\", this.{1});", AcceptableTypes[viewModelPropertyData.Type], viewModelPropertyData.Name)); + //writeMethod.Statements.Add(statement); + + //var dstatement = new CodeSnippetStatement(string.Format("\t\tthis.{0} = stream.Deserialize{1}(\"{0}\");", viewModelPropertyData.Name, AcceptableTypes[viewModelPropertyData.Type])); + //readMethod.Statements.Add(dstatement); + } + } } - } -} -[TemplateClass(MemberGeneratorLocation.DesignerFile, ClassNameFormat = uFrameFormats.VIEW_MODEL_FORMAT)] -public partial class ViewModelConstructorTemplate : IClassTemplate -{ - public TemplateContext Ctx { get; set; } + #endregion - public string OutputPath - { - get { return Path2.Combine(Ctx.Data.Graph.Name, "ViewModels"); } - } - [TemplateConstructor("aggregator")] - public void AggregatorConstructor(IEventAggregator aggregator) - { + #region Reflection - } - public bool CanGenerate - { - get { return true; } - } - - public void TemplateSetup() - { - // Ensure the namespaces for each property type are property set up - Ctx.CurrentDecleration.BaseTypes.Clear(); - Ctx.CurrentDecleration.IsPartial = true; - Ctx.CurrentDecleration.Name = string.Format(uFrameFormats.VIEW_MODEL_FORMAT, Ctx.Data.Name); - } - -} - -[TemplateClass(MemberGeneratorLocation.DesignerFile, ClassNameFormat = "{0}Command")] -public partial class ViewModelCommandClassTemplate : ViewModelCommand, IClassTemplate, IClassRefactorable -{ - public string OutputPath - { - get + [GenerateMethod] + protected override void FillCommands(List list) { - return Path2.Combine(Ctx.Data.Node.Graph.Name, "Commands"); - } - } + //base.FillCommands(list); + foreach (var commandChildItem in Ctx.Data.LocalCommands) + { + Ctx._("list.Add(new ViewModelCommandInfo(\"{0}\", {0}) {{ ParameterType = typeof({1}) }})", + commandChildItem.Name, + string.IsNullOrEmpty(commandChildItem.RelatedTypeName) ? "void" : commandChildItem.RelatedTypeName + ); + } - public bool CanGenerate - { - get { return Ctx.Data.OutputCommand == null; } - } + } - public void TemplateSetup() - { - var type = InvertApplication.FindTypeByName(Ctx.Data.RelatedTypeName); - if (type != null) + [GenerateMethod] + protected override void FillProperties(List list) { - Ctx.TryAddNamespace(type.Namespace); - } - else - { - type = InvertApplication.FindType(Ctx.Data.RelatedTypeName); - if (type != null) - Ctx.TryAddNamespace(type.Namespace); + //base.FillProperties(list); + foreach (var property in Ctx.Data.AllProperties) + { + Ctx._comment(property.GetType().Name); + Ctx._("list.Add(new ViewModelPropertyInfo({0}, {1}, {2}, {3}, {4}))", + property.Name.AsSubscribableField(), + property.RelatedNode() is ElementNode ? "true" : "false", + "false", + property.RelatedNode() is EnumNode ? "true" : "false", // TODO FOR ENUMS + property is ComputedPropertyNode ? "true" : "false" + + ); + } + foreach (var property in Ctx.Data.LocalCollections) + { + Ctx._("list.Add(new ViewModelPropertyInfo({0}, {1}, {2}, {3}, {4}))", + property.Name.AsField(), + property.RelatedNode() is ElementNode ? "true" : "false", + "true", + property.RelatedNode() is EnumNode ? "true" : "false", // TODO FOR ENUMS + "false" + ); + } } - Ctx.CurrentDecleration.IsPartial = true; - Ctx.CurrentDecleration.Name = Ctx.Data.Name + "Command"; - Ctx.AddCondition("Argument", _ => !string.IsNullOrEmpty(_.RelatedType)); - } - public TemplateContext Ctx { get; set; } + #endregion - public bool HasArgument - { - get { return !string.IsNullOrEmpty(Ctx.Data.RelatedType); } - } - [TemplateProperty, WithField, If("HasArgument")] - public _ITEMTYPE_ Argument { get; set; } + // [TemplateMethod(TemplateLocation.DesignerFile, AutoFill = AutoFillType.NameOnly, NameFormat = "Get{0}Dependents")] + [ForEach("ComputedProperties"), GenerateMethod] + public virtual IEnumerable Get_Name_Dependents() + { + var computed = Ctx.ItemAs(); + foreach (var item in computed.InputsFrom()) + { - public IEnumerable ClassNameFormats - { - get { yield return "{0}Command"; } - } -} + Ctx._("yield return {0}", item.Name.AsSubscribableProperty()); + var relatedNode = item.RelatedTypeNode; + if (relatedNode != null) + { + var conditionStatements = Ctx._if("{0}.Value != null", item.Name.AsSubscribableProperty()) + .TrueStatements; + foreach (var p in computed.SubProperties.Where(p => p.SourceItem.Node == relatedNode)) + { + conditionStatements._("yield return {0}.Value.{1}", item.Name.AsSubscribableProperty(), + p.Name.AsSubscribableProperty()); + } + } + } + foreach (var item in computed.InputsFrom()) + { + Ctx._("yield return {0}", item.Name.AsSubscribableField()); + } -[TemplateClass(Location = MemberGeneratorLocation.DesignerFile, AutoInherit = true, ClassNameFormat = "{0}Command")] -public class CommandClassTemplateBase : IClassTemplate -{ - private Invert.Core.GraphDesigner.TemplateContext _Ctx; + Ctx._("yield break"); - public virtual string OutputPath - { - get - { - return ""; + yield break; } - } - public virtual bool CanGenerate - { - get + //[TemplateMethod(TemplateLocation.DesignerFile, AutoFill = AutoFillType.NameOnly, NameFormat = "Reset{0}")] + [ForEach("ComputedProperties"), GenerateMethod] + public virtual void Reset_Name_() { - return true; - } - } + var computed = Ctx.ItemAs(); + Ctx._if("_{0}Disposable != null", computed.Name) + .TrueStatements._("_{0}Disposable.Dispose()", computed.Name); + Ctx._("_{0}Disposable = {1}.ToComputed(Compute{0}, this.Get{0}Dependents().ToArray()).DisposeWith(this)", + computed.Name, computed.Name.AsSubscribableField()); - public Invert.Core.GraphDesigner.TemplateContext Ctx - { - get - { - return _Ctx; - } - set - { - _Ctx = value; } - } - public virtual void TemplateSetup() - { - if (Ctx.IsDesignerFile) + //[TemplateMethod(TemplateLocation.Both, AutoFill = AutoFillType.NameOnly, NameFormat = "Compute{0}")] + [ForEach("ComputedProperties"), GenerateMethod] + public virtual Boolean Compute_Name_() { - Ctx.CurrentDecleration.BaseTypes.Clear(); - Ctx.CurrentDecleration.BaseTypes.Add(new CodeTypeReference("ViewModelCommand")); + var type = Ctx.ItemAs().RelatedTypeName; + Ctx.SetType(type); + Ctx._("return default({0})", type); + return false; } - } -} -[TemplateClass(MemberGeneratorLocation.DesignerFile, ClassNameFormat = "{0}Command")] -public partial class CommandClassTemplate : CommandClassTemplateBase, IClassRefactorable -{ - public IEnumerable ClassNameFormats - { - get + public static Dictionary AcceptableTypes = new Dictionary { - yield return "{0}Command"; - } - } + {typeof (int), "Int"}, + {typeof (Vector3), "Vector3"}, + {typeof (Vector2), "Vector2"}, + {typeof (string), "String"}, + {typeof (bool), "Bool"}, + {typeof (float), "Float"}, + {typeof (double), "Double"}, + {typeof (Quaternion), "Quaternion"}, + }; - public override string OutputPath - { - get + public IEnumerable ClassNameFormats { - return Path2.Combine(Ctx.Data.Node.Graph.Name, "Commands"); - } - } - - - public override void TemplateSetup() - { - base.TemplateSetup(); - foreach (var property in Ctx.Data.PersistedItems.OfType()) - { - var type = InvertApplication.FindTypeByName(property.RelatedTypeName); - if (type == null) continue; - - Ctx.TryAddNamespace(type.Namespace); + get + { + yield return "{0}ViewModel"; + yield return "{0}ViewModelBase"; + } } - - Ctx.CurrentDecleration.IsPartial = true; - } - - - [ForEach("Collections"), TemplateProperty, WithField] - public _ITEMTYPE_ _Name_ - { - get; - set; } - - [ForEach("Collections"), TemplateProperty, WithField] - public List<_ITEMTYPE_> _CollectionName_ - { - get; - set; - } -} - +} \ No newline at end of file diff --git a/Editor/Templates/ViewTemplate.cs b/Editor/Templates/ViewTemplate.cs index d3e02d05..a4d52a3c 100644 --- a/Editor/Templates/ViewTemplate.cs +++ b/Editor/Templates/ViewTemplate.cs @@ -11,354 +11,345 @@ using uFrame.Graphs; using UnityEngine; -[TemplateClass(MemberGeneratorLocation.Both)] -public partial class ViewTemplate : IClassTemplate, IClassRefactorable +namespace uFrame.MVVM.Templates { - public string OutputPath + [TemplateClass(TemplateLocation.Both)] + public partial class ViewTemplate : IClassTemplate, IClassRefactorable { - get { return Path2.Combine(Ctx.Data.Graph.Name, "Views"); } - } + public string OutputPath + { + get { return Path2.Combine(Ctx.Data.Graph.Name, "Views"); } + } - public bool CanGenerate - { - get { return true; } - } + public bool CanGenerate + { + get { return true; } + } - [TemplateProperty(MemberGeneratorLocation.DesignerFile)] - public string DefaultIdentifier - { - get + [GenerateProperty(TemplateLocation.DesignerFile)] + public string DefaultIdentifier + { + get + { + this.Ctx.CurrentProperty.Attributes = MemberAttributes.Override | MemberAttributes.Public; + var instance = Ctx.Data.Element.RegisteredInstances.FirstOrDefault(); + if (instance != null) + { + Ctx._("return \"{0}\"", instance.Name); + } + else + { + Ctx._("return base.DefaultIdentifier"); + } + + return null; + } + } + + + public virtual void TemplateSetup() { - this.Ctx.CurrentProperty.Attributes = MemberAttributes.Override | MemberAttributes.Public; - var instance = Ctx.Data.Element.RegisteredInstances.FirstOrDefault(); - if (instance != null) + this.Ctx.TryAddNamespace("uFrame.Kernel"); + this.Ctx.TryAddNamespace("uFrame.MVVM"); + this.Ctx.TryAddNamespace("uFrame.MVVM.Services"); + this.Ctx.TryAddNamespace("uFrame.MVVM.Bindings"); + this.Ctx.TryAddNamespace("uFrame.Serialization"); + + this.Ctx.TryAddNamespace("UniRx"); + this.Ctx.TryAddNamespace("UnityEngine"); + + // Let the Dll Know about uFrame Binding Specific Types + uFrameBindingType.ObservablePropertyType = typeof (IObservableProperty); + uFrameBindingType.UFGroupType = typeof (UFGroup); + uFrameBindingType.ICommandType = typeof (ISignal); + foreach (var property in Ctx.Data.Element.PersistedItems.OfType()) + { + var type = InvertApplication.FindTypeByName(property.RelatedTypeName); + if (type == null) continue; + + Ctx.TryAddNamespace(type.Namespace); + } + + if (Ctx.IsDesignerFile && Ctx.Data.BaseNode == null) + { + Ctx.SetBaseType(typeof (ViewBase)); + } + // Add namespaces based on the types used for properties + Ctx.AddIterator("ViewComponentProperty", _ => _.OutputsTo()); + // Add the iterators for template method/property + if (Ctx.Data.BaseNode == null) { - Ctx._("return \"{0}\"", instance.Name); + Ctx.AddIterator("ExecuteCommand", + _ => _.Element.InheritedCommandsWithLocal.Where(p => string.IsNullOrEmpty(p.RelatedTypeName))); + Ctx.AddIterator("ExecuteCommandOverload", _ => _.Element.InheritedCommandsWithLocal); + Ctx.AddIterator("ExecuteCommandWithArg", + _ => + _.Element.InheritedCommandsWithLocal.Where( + p => !string.IsNullOrEmpty(p.RelatedTypeName) && p.OutputCommand == null)); } else { - Ctx._("return base.DefaultIdentifier"); + Ctx.AddIterator("ExecuteCommand", + _ => _.Element.LocalCommands.Where(p => string.IsNullOrEmpty(p.RelatedTypeName))); + Ctx.AddIterator("ExecuteCommandOverload", _ => _.Element.LocalCommands); + Ctx.AddIterator("ExecuteCommandWithArg", + _ => + _.Element.LocalCommands.Where( + p => !string.IsNullOrEmpty(p.RelatedTypeName) && p.OutputCommand == null)); + } + + Ctx.AddIterator("ResetProperty", _ => _.SceneProperties); + Ctx.AddIterator("CalculateProperty", _ => _.SceneProperties); + Ctx.AddIterator("GetPropertyObservable", _ => _.SceneProperties); + Ctx.AddCondition("ViewModelProperty", _ => !_.IsDerivedOnly); + Ctx.AddCondition("DefaultIdentifier", _ => !_.IsDerivedOnly); + Ctx.AddCondition("ViewModelType", _ => !_.IsDerivedOnly); + if (!Ctx.IsDesignerFile) + { + // For each binding lets do some magic + foreach (var item in Ctx.Data.Bindings) + { + // Cast the source of our binding (ie: Property, Collection, Command..etc) + var source = item.SourceItem as ITypedItem; + if (source == null) continue; + // Grab the uFrame Binding Type + var bindingType = item.BindingType; + // Create the binding signature based on the Method Info + + bindingType.CreateBindingSignature(new CreateBindingSignatureParams( + Ctx.CurrentDecleration, _ => source.RelatedTypeName.ToCodeReference(), Ctx.Data, source) + { + Ctx = Ctx, + BindingsReference = item, + DontImplement = true + }); + } } - - return null; } - } + public TemplateContext Ctx { get; set; } - public virtual void TemplateSetup() - { - this.Ctx.TryAddNamespace("UniRx"); - this.Ctx.TryAddNamespace("UnityEngine"); - - // Let the Dll Know about uFrame Binding Specific Types - uFrameBindingType.ObservablePropertyType = typeof(IObservableProperty); - uFrameBindingType.UFGroupType = typeof(UFGroup); - uFrameBindingType.ICommandType = typeof(ISignal); - foreach (var property in Ctx.Data.Element.PersistedItems.OfType()) + #region SceneProperties + + [GenerateMethod("Reset{0}", TemplateLocation.DesignerFile, false)] + public virtual void ResetProperty() { - var type = InvertApplication.FindTypeByName(property.RelatedTypeName); - if (type == null) continue; + // Make sure the disposable is created + Ctx.CurrentDecleration._private_(typeof (System.IDisposable), "_{0}Disposable", Ctx.Item.Name); + Ctx._if("_{0}Disposable != null", Ctx.Item.Name) + .TrueStatements + ._("_{0}Disposable.Dispose()", Ctx.Item.Name); + Ctx._("_{0}Disposable = Get{0}Observable().Subscribe({1}.{2}).DisposeWith(this)", Ctx.Item.Name, + Ctx.Data.Element.Name, Ctx.Item.Name.AsSubscribableProperty()); - Ctx.TryAddNamespace(type.Namespace); } - if (Ctx.IsDesignerFile && Ctx.Data.BaseNode == null) + [GenerateMethod("Calculate{0}", TemplateLocation.Both, true)] + protected virtual String CalculateProperty() { - Ctx.SetBaseType(typeof(ViewBase)); + Ctx.SetType(Ctx.TypedItem.RelatedTypeName); + Ctx._("return default({0})", Ctx.TypedItem.RelatedTypeName); + return default(String); } - // Add namespaces based on the types used for properties - Ctx.AddIterator("ViewComponentProperty",_=>_.OutputsTo()); - // Add the iterators for template method/property - if (Ctx.Data.BaseNode == null) - { - Ctx.AddIterator("ExecuteCommand", - _ => _.Element.InheritedCommandsWithLocal.Where(p => string.IsNullOrEmpty(p.RelatedTypeName))); - Ctx.AddIterator("ExecuteCommandOverload", _ => _.Element.InheritedCommandsWithLocal); - Ctx.AddIterator("ExecuteCommandWithArg", - _ => - _.Element.InheritedCommandsWithLocal.Where( - p => !string.IsNullOrEmpty(p.RelatedTypeName) && p.OutputCommand == null)); - } - else + + [GenerateMethod("Get{0}Observable", TemplateLocation.DesignerFile, false)] + protected virtual UniRx.IObservable GetPropertyObservable() { - Ctx.AddIterator("ExecuteCommand", - _ => _.Element.LocalCommands.Where(p => string.IsNullOrEmpty(p.RelatedTypeName))); - Ctx.AddIterator("ExecuteCommandOverload", _ => _.Element.LocalCommands); - Ctx.AddIterator("ExecuteCommandWithArg", - _ => - _.Element.LocalCommands.Where( - p => !string.IsNullOrEmpty(p.RelatedTypeName) && p.OutputCommand == null)); + this.Ctx.SetTypeArgument(Ctx.TypedItem.RelatedTypeName); + Ctx._("return this.UpdateAsObservable().Select(p=>Calculate{0}())", Ctx.Item.Name); + return null; } - - Ctx.AddIterator("ResetProperty", _ => _.SceneProperties); - Ctx.AddIterator("CalculateProperty", _ => _.SceneProperties); - Ctx.AddIterator("GetPropertyObservable", _ => _.SceneProperties); - Ctx.AddCondition("ViewModelProperty", _=>!_.IsDerivedOnly); - Ctx.AddCondition("DefaultIdentifier", _=>!_.IsDerivedOnly); - Ctx.AddCondition("ViewModelType", _=>!_.IsDerivedOnly); - if (!Ctx.IsDesignerFile) + + #endregion + + [GenerateProperty] + public virtual Type ViewModelType { - // For each binding lets do some magic - foreach (var item in Ctx.Data.Bindings) + get { - // Cast the source of our binding (ie: Property, Collection, Command..etc) - var source = item.SourceItem as ITypedItem; - if (source == null) continue; - // Grab the uFrame Binding Type - var bindingType = item.BindingType; - // Create the binding signature based on the Method Info - - bindingType.CreateBindingSignature(new CreateBindingSignatureParams( - Ctx.CurrentDecleration, _ => source.RelatedTypeName.ToCodeReference(), Ctx.Data, source) - { - Ctx = Ctx, - BindingsReference = item, - DontImplement = true - }); + Ctx.CurrentProperty.Attributes |= MemberAttributes.Override; + Ctx._("return typeof({0})", Ctx.Data.Element.Name.AsViewModel()); + return null; } } - } - - public TemplateContext Ctx { get; set; } - #region SceneProperties - - [TemplateMethod("Reset{0}", MemberGeneratorLocation.DesignerFile, false)] - public virtual void ResetProperty() - { - // Make sure the disposable is created - Ctx.CurrentDecleration._private_(typeof(System.IDisposable), "_{0}Disposable", Ctx.Item.Name); - Ctx._if("_{0}Disposable != null", Ctx.Item.Name) - .TrueStatements - ._("_{0}Disposable.Dispose()", Ctx.Item.Name); - Ctx._("_{0}Disposable = Get{0}Observable().Subscribe({1}.{2}).DisposeWith(this)", Ctx.Item.Name, Ctx.Data.Element.Name, Ctx.Item.Name.AsSubscribableProperty()); - - } - - [TemplateMethod("Calculate{0}", MemberGeneratorLocation.Both, true)] - protected virtual String CalculateProperty() - { - Ctx.SetType(Ctx.TypedItem.RelatedTypeName); - Ctx._("return default({0})", Ctx.TypedItem.RelatedTypeName); - return default(String); - } - - [TemplateMethod("Get{0}Observable", MemberGeneratorLocation.DesignerFile, false)] - protected virtual UniRx.IObservable GetPropertyObservable() - { - this.Ctx.SetTypeArgument(Ctx.TypedItem.RelatedTypeName); - Ctx._("return this.UpdateAsObservable().Select(p=>Calculate{0}())", Ctx.Item.Name); - return null; - } - #endregion - - [TemplateProperty] - public virtual Type ViewModelType - { - get + public string ElementName { - Ctx.CurrentProperty.Attributes |= MemberAttributes.Override; - Ctx._("return typeof({0})", Ctx.Data.Element.Name.AsViewModel()); - return null; + get { return Ctx.Data.Element.Name; } } - } - [TemplateProperty] - - public Type ViewModelProperty - { - get + [GenerateProperty] + public Type _ElementName_ { - - Ctx.CurrentProperty.Name = Ctx.Data.Element.Name; - Ctx.CurrentProperty.Type = Ctx.Data.Element.Name.AsViewModel().ToCodeReference(); - Ctx._("return ({0})ViewModelObject", Ctx.Data.Element.Name.AsViewModel()); - return null; + get + { + Ctx.CurrentProperty.Type = Ctx.Data.Element.Name.AsViewModel().ToCodeReference(); + Ctx._("return ({0})ViewModelObject", Ctx.Data.Element.Name.AsViewModel()); + return null; + } } - } - //[TemplateMethod(CallBase = false)] - //public virtual ViewModel CreateModel() - //{ - // Ctx.CurrentMethod.Attributes |= MemberAttributes.Override; - // //var property = Context.Get(); - // Ctx._("return this.FetchViewModel(Identifier,ViewModelType)"); - // return null; - //} - - [TemplateMethod, Inside(TemplateLocation.Both)] - protected virtual void InitializeViewModel(ViewModel model) - { - Ctx._comment("NOTE: this method is only invoked if the 'Initialize ViewModel' is checked in the inspector."); - Ctx._comment("var vm = model as {0};", Ctx.Data.Element.Name.AsViewModel()); - Ctx._comment("This method is invoked when applying the data from the inspector to the viewmodel. Add any view-specific customizations here."); - - Ctx.CurrentMethod.Attributes |= MemberAttributes.Override; - if (!Ctx.IsDesignerFile) return; - Ctx.CurrentMethod.invoke_base(true); - if (!Ctx.Data.Element.LocalProperties.Any()) return; - if (Ctx.Data.IsDerivedOnly) return; - var variableName = Ctx.Data.Name.ToLower(); - Ctx._("var {0} = (({1})model)", variableName, Ctx.Data.Element.Name.AsViewModel()); - - foreach (var property in Ctx.Data.Element.LocalProperties) + //[TemplateMethod(CallBase = false)] + //public virtual ViewModel CreateModel() + //{ + // Ctx.CurrentMethod.Attributes |= MemberAttributes.Override; + // //var property = Context.Get(); + // Ctx._("return this.FetchViewModel(Identifier,ViewModelType)"); + // return null; + //} + + [GenerateMethod, Inside(TemplateLocation.Both)] + protected virtual void InitializeViewModel(ViewModel model) { - if (property.RelatedTypeNode is StateMachineNode) continue; - // Make sure derived views don't duplicate in initialize vm - - var field = Ctx.CurrentDecleration._public_(property.RelatedTypeName, property.Name.AsField()); - field.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(SerializeField)))); - field.CustomAttributes.Add( - new CodeAttributeDeclaration( - new CodeTypeReference(typeof(UFGroup)), - new CodeAttributeArgument( - new CodePrimitiveExpression("View Model Properties")))); - - field.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(HideInInspector)))); - var relatedNode = property.RelatedTypeNode; - var relatedViewModel = relatedNode as ElementNode; - - if (relatedViewModel == null) // Non ViewModel Properties + Ctx._comment("NOTE: this method is only invoked if the 'Initialize ViewModel' is checked in the inspector."); + Ctx._comment("var vm = model as {0};", Ctx.Data.Element.Name.AsViewModel()); + Ctx._comment( + "This method is invoked when applying the data from the inspector to the viewmodel. Add any view-specific customizations here."); + + Ctx.CurrentMethod.Attributes |= MemberAttributes.Override; + if (!Ctx.IsDesignerFile) return; + Ctx.CurrentMethod.invoke_base(true); + if (!Ctx.Data.Element.LocalProperties.Any()) return; + if (Ctx.Data.IsDerivedOnly) return; + var variableName = Ctx.Data.Name.ToLower(); + Ctx._("var {0} = (({1})model)", variableName, Ctx.Data.Element.Name.AsViewModel()); + + foreach (var property in Ctx.Data.Element.LocalProperties) { + if (property.RelatedTypeNode is StateMachineNode) continue; + // Make sure derived views don't duplicate in initialize vm + + var field = Ctx.CurrentDecleration._public_(property.RelatedTypeName, property.Name.AsField()); + field.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof (SerializeField)))); + field.CustomAttributes.Add( + new CodeAttributeDeclaration( + new CodeTypeReference(typeof (UFGroup)), + new CodeAttributeArgument( + new CodePrimitiveExpression("View Model Properties")))); + + field.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof (HideInInspector)))); + var relatedNode = property.RelatedTypeNode; + var relatedViewModel = relatedNode as ElementNode; + + if (relatedViewModel == null) // Non ViewModel Properties + { - Ctx._("{0}.{1} = this.{2}", variableName, property.Name, property.Name.AsField()); + Ctx._("{0}.{1} = this.{2}", variableName, property.Name, property.Name.AsField()); + } + else + { + field.Type = new CodeTypeReference(typeof (ViewBase)); + Ctx._("{0}.{1} = this.{2} == null ? null : ViewService.FetchViewModel(this.{2}) as {3}", + variableName, property.Name, property.Name.AsField(), relatedViewModel.Name.AsViewModel()); + } } - else + + + } + + [GenerateMethod, Inside(TemplateLocation.Both)] + public virtual void Bind() + { + Ctx.CurrentMethod.Attributes |= MemberAttributes.Override; + Ctx._comment("Use this.{0} to access the viewmodel.", Ctx.Data.Element.Name); + Ctx._comment("Use this method to subscribe to the view-model."); + Ctx._comment("Any designer bindings are created in the base implementation."); + + if (!Ctx.IsDesignerFile) { - field.Type = new CodeTypeReference(typeof(ViewBase)); - Ctx._("{0}.{1} = this.{2} == null ? null : ViewService.FetchViewModel(this.{2}) as {3}", variableName, property.Name, property.Name.AsField(), relatedViewModel.Name.AsViewModel()); + + return; } - } - - } + Ctx.CurrentMethod.invoke_base(true); - [TemplateMethod,Inside(TemplateLocation.Both)] - public virtual void Bind() - { - Ctx.CurrentMethod.Attributes |= MemberAttributes.Override; - Ctx._comment("Use this.{0} to access the viewmodel.",Ctx.Data.Element.Name); - Ctx._comment("Use this method to subscribe to the view-model."); - Ctx._comment("Any designer bindings are created in the base implementation."); - if (!Ctx.IsDesignerFile) - { + // For each binding lets do some magic + foreach (var item in Ctx.Data.Bindings) + { + // Cast the source of our binding (ie: Property, Collection, Command..etc) + var source = item.SourceItem as ITypedItem; + // Create a boolean field for each property that has a binding this will serve the condition + // in the bind method to turn the binding on or off. + var bindingField = Ctx.CurrentDecleration._public_(typeof (bool), "_Bind{0}", source.Name); + // Bindings should always be on by default + bindingField.InitExpression = new CodePrimitiveExpression(true); + // Add a toggle group attribute to it, this hides and shows anything within the same group + bindingField.CustomAttributes.Add( + new CodeAttributeDeclaration(new CodeTypeReference(typeof (UFToggleGroup)), + new CodeAttributeArgument(new CodePrimitiveExpression(source.Name)))); + // Hide them in the insepctor, our custom 'ViewInspector' class will handle them manually + bindingField.CustomAttributes.Add( + new CodeAttributeDeclaration(new CodeTypeReference(typeof (HideInInspector)))); + // Create the binding condition + var bindingCondition = Ctx._if("{0}", bindingField.Name); + // Grab the uFrame Binding Type + var bindingType = item.BindingType; + // Create the binding signature based on the Method Info + var bindingStatement = + bindingType.CreateBindingSignature(new CreateBindingSignatureParams( + Ctx.CurrentDecleration, _ => source.RelatedTypeName.ToCodeReference(), Ctx.Data, source) + { + Ctx = Ctx + }); - return; - } - Ctx.CurrentMethod.invoke_base(true); + // Add the binding statement to the condition + bindingCondition.TrueStatements.Add(bindingStatement); + } - - // For each binding lets do some magic - foreach (var item in Ctx.Data.Bindings) - { - // Cast the source of our binding (ie: Property, Collection, Command..etc) - var source = item.SourceItem as ITypedItem; - // Create a boolean field for each property that has a binding this will serve the condition - // in the bind method to turn the binding on or off. - var bindingField = Ctx.CurrentDecleration._public_(typeof(bool), "_Bind{0}", source.Name); - // Bindings should always be on by default - bindingField.InitExpression = new CodePrimitiveExpression(true); - // Add a toggle group attribute to it, this hides and shows anything within the same group - bindingField.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(UFToggleGroup)), - new CodeAttributeArgument(new CodePrimitiveExpression(source.Name)))); - // Hide them in the insepctor, our custom 'ViewInspector' class will handle them manually - bindingField.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(HideInInspector)))); - // Create the binding condition - var bindingCondition = Ctx._if("{0}", bindingField.Name); - // Grab the uFrame Binding Type - var bindingType = item.BindingType; - // Create the binding signature based on the Method Info - var bindingStatement = - bindingType.CreateBindingSignature(new CreateBindingSignatureParams( - Ctx.CurrentDecleration, _ => source.RelatedTypeName.ToCodeReference(), Ctx.Data, source) - { - Ctx = Ctx - }); - - - // Add the binding statement to the condition - bindingCondition.TrueStatements.Add(bindingStatement); + foreach (var property in Ctx.Data.SceneProperties) + { + Ctx._("Reset{0}()", property.Name); + } } - foreach (var property in Ctx.Data.SceneProperties) + [GenerateMethod("Execute{0}", TemplateLocation.DesignerFile, false)] + public void ExecuteCommand() { - Ctx._("Reset{0}()", property.Name); + Ctx._("{0}.{1}.OnNext(new {1}Command() {{ Sender = {0} }})", Ctx.Data.Element.Name, Ctx.Item.Name); + //Ctx._("this.ExecuteCommand({0}.{1})", Ctx.Data.Element.Name, Ctx.Item.Name); } - } - - [TemplateMethod("Execute{0}", MemberGeneratorLocation.DesignerFile, false, AutoFill = AutoFillType.NameOnly)] - public void ExecuteCommand() - { - Ctx._("{0}.{1}.OnNext(new {1}Command() {{ Sender = {0} }})", Ctx.Data.Element.Name, Ctx.Item.Name); - //Ctx._("this.ExecuteCommand({0}.{1})", Ctx.Data.Element.Name, Ctx.Item.Name); - } - [TemplateMethod("Execute{0}", MemberGeneratorLocation.DesignerFile, false, AutoFill = AutoFillType.NameOnly)] - public void ExecuteCommandOverload(ViewModelCommand command) - { - Ctx.CurrentMethod.Parameters[0].Type = (Ctx.Item.Name + "Command").ToCodeReference(); - Ctx._("command.Sender = {0}", Ctx.Data.Element.Name); - Ctx._("{0}.{1}.OnNext(command)", Ctx.Data.Element.Name, Ctx.Item.Name); - //Ctx._("this.ExecuteCommand({0}.{1})", Ctx.Data.Element.Name, Ctx.Item.Name); - } - [TemplateMethod("Execute{0}", MemberGeneratorLocation.DesignerFile, false, AutoFill = AutoFillType.NameOnly)] - public void ExecuteCommandWithArg(object arg) - { - Ctx.CurrentMethod.Parameters[0].Type = new CodeTypeReference(Ctx.TypedItem.RelatedTypeName); - Ctx._("{0}.{1}.OnNext(new {1}Command() {{ Sender = {0}, Argument = arg }})", Ctx.Data.Element.Name, Ctx.Item.Name); - } - public IEnumerable ClassNameFormats - { - get + [GenerateMethod("Execute{0}", TemplateLocation.DesignerFile, false)] + public void ExecuteCommandOverload(ViewModelCommand command) { - yield return "{0}"; - yield return "{0}Base"; + Ctx.CurrentMethod.Parameters[0].Type = (Ctx.Item.Name + "Command").ToCodeReference(); + Ctx._("command.Sender = {0}", Ctx.Data.Element.Name); + Ctx._("{0}.{1}.OnNext(command)", Ctx.Data.Element.Name, Ctx.Item.Name); + //Ctx._("this.ExecuteCommand({0}.{1})", Ctx.Data.Element.Name, Ctx.Item.Name); } - } - [TemplateProperty(MemberGeneratorLocation.DesignerFile, AutoFill = AutoFillType.NameAndType)] - public virtual object ViewComponentProperty - { - get + [GenerateMethod("Execute{0}", TemplateLocation.DesignerFile, false)] + public void ExecuteCommandWithArg(object arg) { - - var field = Ctx.CurrentDecleration._private_(Ctx.Item.Name, Ctx.Item.Name.AsField()); - field.CustomAttributes.Add(new CodeAttributeDeclaration(typeof (SerializeField).ToCodeReference())); - Ctx.CurrentProperty.Type = field.Type; - Ctx._("return {0} ?? ({0} = this.gameObject.EnsureComponent<{1}>())", field.Name, Ctx.Item.Name); - return null; + Ctx.CurrentMethod.Parameters[0].Type = new CodeTypeReference(Ctx.TypedItem.RelatedTypeName); + Ctx._("{0}.{1}.OnNext(new {1}Command() {{ Sender = {0}, Argument = arg }})", Ctx.Data.Element.Name, + Ctx.Item.Name); } - } -} - -public class ModelNode : GenericNode -{ - -} - -public partial class ModelTemplate : IClassTemplate -{ - public string OutputPath { get; private set; } - public bool CanGenerate { get; private set; } - public void TemplateSetup() - { - throw new NotImplementedException(); - } + public IEnumerable ClassNameFormats + { + get + { + yield return "{0}"; + yield return "{0}Base"; + } + } - public TemplateContext Ctx { get; set; } -} + [GenerateProperty("{0}")] + public virtual _ITEMTYPE_ ViewComponentProperty + { + get + { + var field = Ctx.CurrentDecleration._private_(Ctx.Item.Name, Ctx.Item.Name.AsField()); + field.CustomAttributes.Add(new CodeAttributeDeclaration(typeof (SerializeField).ToCodeReference())); + Ctx.CurrentProperty.Type = field.Type; + Ctx._("return {0} ?? ({0} = this.gameObject.EnsureComponent<{1}>())", field.Name, Ctx.Item.Name); + return null; + } -[TemplateClass(MemberGeneratorLocation.DesignerFile,"{0}Model")] -public partial class ModelTemplate : IClassTemplate -{ - [TemplateMethod(MemberGeneratorLocation.DesignerFile)] - [ForEach("Commands")] - public void CommandFunction() - { - Ctx._comment("This is the {0} function", Ctx.Item.Name); + } } -} +} \ No newline at end of file diff --git a/Editor/Templates/_ITEMNAME_VIEWMODEL.cs b/Editor/Templates/_ITEMNAME_VIEWMODEL.cs new file mode 100644 index 00000000..c22c40b4 --- /dev/null +++ b/Editor/Templates/_ITEMNAME_VIEWMODEL.cs @@ -0,0 +1,27 @@ +using Invert.Core.GraphDesigner; +using uFrame.Graphs; + +namespace uFrame.MVVM.Templates +{ + public class _ITEMNAME_VIEWMODEL : _TEMPLATETYPE_ + { + public override string TheType(TemplateContext context) + { + return context.Item.Name.AsViewModel(); + } + + } + public class _REFNAME_VIEWMODEL : _TEMPLATETYPE_ + { + public override string TheType(TemplateContext context) + { + var referenceItem = context.Item as GenericReferenceItem; + if (referenceItem != null) + { + return referenceItem.SourceItemObject.Name.AsViewModel(); + } + return string.Empty; + } + + } +} \ No newline at end of file diff --git a/Editor/Templates/_ITEMNAME_VIEWMODEL.cs.meta b/Editor/Templates/_ITEMNAME_VIEWMODEL.cs.meta new file mode 100644 index 00000000..596c5e30 --- /dev/null +++ b/Editor/Templates/_ITEMNAME_VIEWMODEL.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: bd6b749afed05dd4e8e827526c331798 +timeCreated: 1433229788 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Templates/uFrameTemplates.cs b/Editor/Templates/uFrameTemplates.cs index 4937af0e..fdcd3413 100644 --- a/Editor/Templates/uFrameTemplates.cs +++ b/Editor/Templates/uFrameTemplates.cs @@ -3,152 +3,169 @@ using Invert.Core; using Invert.Core.GraphDesigner; using Invert.Core.GraphDesigner.Unity.Refactoring; +using Invert.IOC; using Invert.StateMachine; using Invert.uFrame.MVVM; +using uFrame.MVVM.Bindings; +using uFrame.MVVM.Templates; using UnityEngine; -public class uFrameTemplates : DiagramPlugin +namespace uFrame.MVVM.Templates { - // Make sure this plugin loads after the framework plugin loads - public override decimal LoadPriority + public class uFrameTemplates : DiagramPlugin { - get { return 5; } - } - - private uFrameMVVM Framework { get; set; } - - public override string Title - { - get { return "uFrame MVVM Templates"; } - } - - public override void Initialize(uFrameContainer container) - { - // Grab a reference to the main framework graphs plugin - Framework = container.Resolve(); - //Framework.ElementsGraphRoot.AddCodeTemplate(); - // Register the code template - Framework.Service.AddCodeTemplate(); - Framework.SimpleClass.AddCodeTemplate(); - Framework.Element.AddCodeTemplate(); - Framework.Element.AddCodeTemplate(); - Framework.Element.AddCodeTemplate(); - RegisteredTemplateGeneratorsFactory.RegisterTemplate(); - RegisteredTemplateGeneratorsFactory.RegisterTemplate(); - //Framework.SceneManager.AddCodeTemplate(); - //Framework.SceneManager.AddCodeTemplate(); - Framework.SceneType.AddCodeTemplate(); - Framework.SceneType.AddCodeTemplate(); - Framework.Subsystem.AddCodeTemplate(); - Framework.SceneType.AddCodeTemplate(); - Framework.View.AddCodeTemplate(); - Framework.ViewComponent.AddCodeTemplate(); - Framework.State.AddCodeTemplate(); - Framework.StateMachine.AddCodeTemplate(); - - // Register our bindable methods - container.AddBindingMethod(typeof(ViewBindings), "BindProperty", _ => _ is PropertiesChildItem || _ is ComputedPropertyNode) - .SetNameFormat("{0} Changed") - .ImplementWith(args => - { - var sourceItem = args.SourceItem as ITypedItem; - - if (sourceItem.RelatedNode() is StateMachineNode) + // Make sure this plugin loads after the framework plugin loads + public override decimal LoadPriority + { + get { return 5; } + } + + private uFrameMVVM Framework { get; set; } + + public override string Title + { + get { return "uFrame MVVM Templates"; } + } + + public override void Initialize(UFrameContainer container) + { + // Grab a reference to the main framework graphs plugin + Framework = container.Resolve(); + //Framework.ElementsGraphRoot.AddCodeTemplate(); + // Register the code template + Framework.Service.AddCodeTemplate(); + Framework.SimpleClass.AddCodeTemplate(); + Framework.Element.AddCodeTemplate(); + Framework.Element.AddCodeTemplate(); + Framework.Element.AddCodeTemplate(); + RegisteredTemplateGeneratorsFactory.RegisterTemplate(); + RegisteredTemplateGeneratorsFactory.RegisterTemplate(); + //Framework.SceneManager.AddCodeTemplate(); + //Framework.SceneManager.AddCodeTemplate(); + Framework.SceneType.AddCodeTemplate(); + Framework.SceneType.AddCodeTemplate(); + Framework.Subsystem.AddCodeTemplate(); + Framework.SceneType.AddCodeTemplate(); + Framework.View.AddCodeTemplate(); + Framework.ViewComponent.AddCodeTemplate(); + Framework.State.AddCodeTemplate(); + Framework.StateMachine.AddCodeTemplate(); + + // Register our bindable methods + container.AddBindingMethod(typeof (ViewBindings), "BindProperty", + _ => _ is PropertiesChildItem || _ is ComputedPropertyNode) + .SetNameFormat("{0} Changed") + .ImplementWith(args => { - args.Method.Parameters.Clear(); - args.Method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(State), "State")); - } - }) - ; - - container.AddBindingMethod(typeof(ViewBindings), "BindStateProperty", _ => _ is PropertiesChildItem && _.RelatedNode() is StateMachineNode) - .SetNameFormat("{0} State Changed") - .SetDescription("Binding to a state property creates methods for each state, and in the designer code will property call the each state's method when it changes.") - .ImplementWith(args => - { - args.Method.Parameters[0].Type = typeof(State).ToCodeReference(); - var sourceItem = args.SourceItem as ITypedItem; - var stateMachine = sourceItem.RelatedNode() as StateMachineNode; - if (args.IsDesignerFile) + var sourceItem = args.SourceItem as ITypedItem; + + if (sourceItem.RelatedNode() is StateMachineNode) + { + args.Method.Parameters.Clear(); + args.Method.Parameters.Add(new CodeParameterDeclarationExpression(typeof (State), "State")); + } + }) + ; + + container.AddBindingMethod(typeof (ViewBindings), "BindStateProperty", + _ => _ is PropertiesChildItem && _.RelatedNode() is StateMachineNode) + .SetNameFormat("{0} State Changed") + .SetDescription( + "Binding to a state property creates methods for each state, and in the designer code will property call the each state's method when it changes.") + .ImplementWith(args => { - foreach (var state in stateMachine.States) + args.Method.Parameters[0].Type = typeof (State).ToCodeReference(); + var sourceItem = args.SourceItem as ITypedItem; + var stateMachine = sourceItem.RelatedNode() as StateMachineNode; + if (args.IsDesignerFile) { - var method = new CodeMemberMethod() + foreach (var state in stateMachine.States) { - Name = "On" + state.Name, - Attributes = MemberAttributes.Public - }; - var conditionStatement = - new CodeConditionStatement( - new CodeSnippetExpression(string.Format("arg1 is {0}", state.Name))); - conditionStatement.TrueStatements.Add( - new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), method.Name)); - - args.Method.Statements.Add(conditionStatement); - args.Decleration.Members.Add(method); + var method = new CodeMemberMethod() + { + Name = "On" + state.Name, + Attributes = MemberAttributes.Public + }; + var conditionStatement = + new CodeConditionStatement( + new CodeSnippetExpression(string.Format("arg1 is {0}", state.Name))); + conditionStatement.TrueStatements.Add( + new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), method.Name)); + + args.Method.Statements.Add(conditionStatement); + args.Decleration.Members.Add(method); + + } } - - } - - args.Method.Parameters[0].Type = "Invert.StateMachine.State".ToCodeReference(); - }); - - container.AddBindingMethod(typeof(ViewBindings), "BindCollection", _ => _ is CollectionsChildItem) - .SetNameFormat("{0} Collection Changed") - .SetDescription("Collection bindings bind to a collection giving you two methods, {CollectionName}Added, and {CollectionName}Removed, override these methods to execute something when the collection is modified.") - ; - - container.AddBindingMethod(typeof(ViewBindings), "BindToViewCollection", _ => _ is CollectionsChildItem) - .SetNameFormat("{0} View Collection Changed") - .SetDescription("The view collection changed binding automatically creates views for each element's viewmodel when created.") - .ImplementWith(args => - { - - if (args.Method.Name.EndsWith("CreateView")) + + args.Method.Parameters[0].Type = "Invert.StateMachine.State".ToCodeReference(); + }); + + container.AddBindingMethod(typeof (ViewBindings), "BindCollection", _ => _ is CollectionsChildItem) + .SetNameFormat("{0} Collection Changed") + .SetDescription( + "Collection bindings bind to a collection giving you two methods, {CollectionName}Added, and {CollectionName}Removed, override these methods to execute something when the collection is modified.") + ; + + container.AddBindingMethod(typeof (ViewBindings), "BindToViewCollection", _ => _ is CollectionsChildItem) + .SetNameFormat("{0} View Collection Changed") + .SetDescription( + "The view collection changed binding automatically creates views for each element's viewmodel when created.") + .ImplementWith(args => { - args.Method.Parameters[0].Name = "viewModel"; - args.Method._("return InstantiateView(viewModel)"); - } - else + + if (args.Method.Name.EndsWith("CreateView")) + { + args.Method.Parameters[0].Name = "viewModel"; + args.Method._("return InstantiateView(viewModel)"); + } + else + { + args.Method.Parameters[0].Name = "view"; + } + }) + ; + + container.AddBindingMethod(typeof (ViewBindings), "BindCommandExecuted", _ => _ is CommandsChildItem) + .SetNameFormat("{0} Executed") + .SetDescription( + "The executed binding is for listening to when a command is invoked on a view. It will provide you with a method in the format {CommandName}Executed({CommandClass} data)") + + .ImplementWith(args => { - args.Method.Parameters[0].Name = "view"; - } - }) - ; - - container.AddBindingMethod(typeof(ViewBindings), "BindCommandExecuted", _ => _ is CommandsChildItem) - .SetNameFormat("{0} Executed") - .SetDescription("The executed binding is for listening to when a command is invoked on a view. It will provide you with a method in the format {CommandName}Executed({CommandClass} data)") - - .ImplementWith(args => - { - - args.Method.Parameters[0].Name = "command"; - var commandItem = args.SourceItem as CommandsChildItem; - args.Method.Parameters[0].Type = commandItem.ClassName.ToCodeReference(); - }) - ; - - container.AddBindingMethod(typeof(UGUIExtensions), "BindInputFieldToProperty", // Registration - _ => _ is PropertiesChildItem && _.RelatedTypeName == typeof(string).Name) // Validation - .SetDescription("Binds a string property to an uGUI input field. A field will be created on the view for specifying the uGUI field.") - .SetNameFormat("{0} To Input Field")// Configuration - ; - - container.AddBindingMethod(typeof(UGUIExtensions), "BindButtonToCommand", _ => _ is CommandsChildItem) - .SetDescription("The ButtonToCommand binding will create a reference to a uGUI button on the view and automatically wire the click event to invoke the command.") - .SetNameFormat("{0} To Button"); - container.AddBindingMethod(typeof(UGUIExtensions), "BindToggleToProperty", _ => _ is PropertiesChildItem && _.RelatedTypeName == typeof(bool).Name) - .SetDescription("Bind toggle to property will bind a boolean property directly to a uGUI toggle box.") - .SetNameFormat("{0} To Toggle"); - container.AddBindingMethod(typeof(UGUIExtensions), "BindTextToProperty", _ => _ is PropertiesChildItem && _.RelatedTypeName == typeof(string).Name) - .SetDescription("Binds a string property to a uGUI text label.") - .SetNameFormat("{0} To Text"); - - container.AddBindingMethod(typeof(UGUIExtensions), "BindSliderToProperty", _ => _ is PropertiesChildItem && _.RelatedTypeName == typeof(float).Name) - .SetDescription("Binds a slider to a float value.") - .SetNameFormat("{0} To Slider"); + args.Method.Parameters[0].Name = "command"; + var commandItem = args.SourceItem as CommandsChildItem; + args.Method.Parameters[0].Type = commandItem.ClassName.ToCodeReference(); + }) + ; + + container.AddBindingMethod(typeof (UGUIExtensions), "BindInputFieldToProperty", // Registration + _ => _ is PropertiesChildItem && _.RelatedTypeName == typeof (string).Name) // Validation + .SetDescription( + "Binds a string property to an uGUI input field. A field will be created on the view for specifying the uGUI field.") + .SetNameFormat("{0} To Input Field") // Configuration + ; + + container.AddBindingMethod(typeof (UGUIExtensions), "BindButtonToCommand", _ => _ is CommandsChildItem) + .SetDescription( + "The ButtonToCommand binding will create a reference to a uGUI button on the view and automatically wire the click event to invoke the command.") + .SetNameFormat("{0} To Button"); + container.AddBindingMethod(typeof (UGUIExtensions), "BindToggleToProperty", + _ => _ is PropertiesChildItem && _.RelatedTypeName == typeof (bool).Name) + .SetDescription("Bind toggle to property will bind a boolean property directly to a uGUI toggle box.") + .SetNameFormat("{0} To Toggle"); + container.AddBindingMethod(typeof (UGUIExtensions), "BindTextToProperty", + _ => _ is PropertiesChildItem && _.RelatedTypeName == typeof (string).Name) + .SetDescription("Binds a string property to a uGUI text label.") + .SetNameFormat("{0} To Text"); + + container.AddBindingMethod(typeof (UGUIExtensions), "BindSliderToProperty", + _ => _ is PropertiesChildItem && _.RelatedTypeName == typeof (float).Name) + .SetDescription("Binds a slider to a float value.") + .SetNameFormat("{0} To Slider"); + + } } } \ No newline at end of file diff --git a/Editor/Tutorials/CreatingServices.cs b/Editor/Tutorials/CreatingServices.cs index 949016ec..9928384c 100644 --- a/Editor/Tutorials/CreatingServices.cs +++ b/Editor/Tutorials/CreatingServices.cs @@ -1,6 +1,7 @@ using Invert.Core.GraphDesigner; using Invert.StateMachine; using Invert.uFrame.MVVM; +using uFrame.Kernel; public class CreatingServices : uFrameMVVMTutorial { @@ -23,9 +24,12 @@ protected override void TutorialContent(IDocumentationBuilder _) var logEvent = DoNamedNodeStep(_, "LogEvent"); DoNamedItemStep(_, "Message", logEvent, "a property", b => { }); DoNamedItemStep(_, "LogEvent", debugService, "a handler", b => { }); + DoNamedItemStep(_, "Log", TheGame, "a command", null); SaveAndCompile(_); - EnsureCode(_, debugService, "Open DebugService.cs and implement the LogEventHandler method.", "http://i.imgur.com/Vrdqgx4.png", "DebugService", "Debug.Log"); EnsureKernel(_); + EnsureCode(_, debugService, "Open DebugService.cs and implement the LogEventHandler method.", "http://i.imgur.com/Vrdqgx4.png", "DebugService", "Debug.Log"); + EnsureCode(_, debugService, "Open GameController.cs and implement the Log method.", "http://i.imgur.com/Vrdqgx4.png", "DebugService", "Debug.Log"); + } protected override void Introduction(IDocumentationBuilder _) diff --git a/Editor/Tutorials/SceneTypePage.cs b/Editor/Tutorials/SceneTypePage.cs index 7bbec990..7f67769e 100644 --- a/Editor/Tutorials/SceneTypePage.cs +++ b/Editor/Tutorials/SceneTypePage.cs @@ -1,6 +1,7 @@ using System; using Invert.Core.GraphDesigner; using Invert.uFrame.MVVM; +using uFrame.MVVM.Templates; public class SceneTypePage : SceneTypePageBase { diff --git a/Editor/Tutorials/UFrameMvvmTutorial.cs b/Editor/Tutorials/UFrameMvvmTutorial.cs index c1d76031..11d74d71 100644 --- a/Editor/Tutorials/UFrameMvvmTutorial.cs +++ b/Editor/Tutorials/UFrameMvvmTutorial.cs @@ -2,6 +2,8 @@ using System.IO; using Invert.Core.GraphDesigner; using Invert.uFrame.MVVM; +using uFrame.Kernel; +using uFrame.MVVM; using UnityEditor; using UnityEngine; @@ -110,6 +112,7 @@ protected bool EnsureKernel(IDocumentationBuilder _) { Kernel = this.EnsureScaffoldKernel(_, TheProject, ExplainKernel); if (Kernel == null) return false; + return true; } diff --git a/Editor/UFrameEditorPlugin.cs b/Editor/UFrameEditorPlugin.cs index 00e7eb75..0f758a4a 100644 --- a/Editor/UFrameEditorPlugin.cs +++ b/Editor/UFrameEditorPlugin.cs @@ -5,12 +5,15 @@ using System.Text; using Invert.Core; using Invert.Core.GraphDesigner; +using Invert.IOC; using Invert.StateMachine; using Invert.uFrame.Editor; using Invert.uFrame.MVVM; +using uFrame.MVVM; using UniRx; using UnityEditor; using UnityEngine; +using ViewModel = Invert.Core.GraphDesigner.ViewModel; [InitializeOnLoad] public class UFrameEditorPlugin : DiagramPlugin @@ -27,7 +30,7 @@ static UFrameEditorPlugin() } - public override void Initialize(uFrameContainer container) + public override void Initialize(UFrameContainer container) { container.RegisterInstance(new CreateSceneCommand(), "CreateScene"); container.RegisterInstance(new AddManagerToSceneCommand(), "AddToScene"); diff --git a/Editor/uFrameEditors/SceneManagementServiceInspector.cs b/Editor/uFrameEditors/SceneManagementServiceInspector.cs index 2c9b18b1..57203804 100644 --- a/Editor/uFrameEditors/SceneManagementServiceInspector.cs +++ b/Editor/uFrameEditors/SceneManagementServiceInspector.cs @@ -2,6 +2,7 @@ using System.Linq; using Invert.Common; using Invert.Common.UI; +using uFrame.Kernel; using UnityEditor; using UnityEngine; diff --git a/Editor/uFrameEditors/SceneManagerInspector.cs b/Editor/uFrameEditors/SceneManagerInspector.cs index 54c59093..e820ec65 100644 --- a/Editor/uFrameEditors/SceneManagerInspector.cs +++ b/Editor/uFrameEditors/SceneManagerInspector.cs @@ -3,6 +3,7 @@ using System.Text; using Invert.Common; using Invert.Common.UI; +using uFrame.Serialization; using UnityEditor; using UnityEngine; [Obsolete] diff --git a/Editor/uFrameEditors/ViewInspector.cs b/Editor/uFrameEditors/ViewInspector.cs index 329682bb..d72e3101 100644 --- a/Editor/uFrameEditors/ViewInspector.cs +++ b/Editor/uFrameEditors/ViewInspector.cs @@ -7,9 +7,9 @@ using Invert.Common; using Invert.Common.UI; using Invert.Core.GraphDesigner; -using Invert.Core.GraphDesigner.Unity; using Invert.uFrame.Editor; -using Invert.uFrame.MVVM; +using uFrame.MVVM; +using ViewModel = uFrame.MVVM.ViewModel; using UnityEditor; using UnityEditorInternal; using UnityEngine; diff --git a/Editor/uFrameEditors/ViewServiceInspector.cs b/Editor/uFrameEditors/ViewServiceInspector.cs index 0f07d1ea..7eabe6be 100644 --- a/Editor/uFrameEditors/ViewServiceInspector.cs +++ b/Editor/uFrameEditors/ViewServiceInspector.cs @@ -2,6 +2,8 @@ using System.Linq; using Invert.Common; using Invert.Common.UI; +using uFrame.Kernel; +using uFrame.MVVM.Services; using UnityEditor; using UnityEngine; diff --git a/Editor/uFrameEditors/uFrameEditorSceneManager.cs b/Editor/uFrameEditors/uFrameEditorSceneManager.cs index 1c2d902a..79dc026a 100644 --- a/Editor/uFrameEditors/uFrameEditorSceneManager.cs +++ b/Editor/uFrameEditors/uFrameEditorSceneManager.cs @@ -3,6 +3,8 @@ using System.Linq; using Invert.Common; using Invert.uFrame.Editor; +using uFrame.Kernel; +using uFrame.MVVM; using UnityEditor; using UnityEngine; using Object = UnityEngine.Object; diff --git a/Editor/uFrameEditors/uFrameInspector.cs b/Editor/uFrameEditors/uFrameInspector.cs index 5ae07ba6..236bdad9 100644 --- a/Editor/uFrameEditors/uFrameInspector.cs +++ b/Editor/uFrameEditors/uFrameInspector.cs @@ -5,6 +5,7 @@ using System.Text.RegularExpressions; using Invert.Common; using Invert.Common.UI; +using uFrame.MVVM; using UnityEditor; using UnityEngine; using Object = UnityEngine.Object; diff --git a/Editor/uFrameEditors/uFrameMVVMKernelInspector.cs b/Editor/uFrameEditors/uFrameMVVMKernelInspector.cs index 8bb13fae..fe02acdc 100644 --- a/Editor/uFrameEditors/uFrameMVVMKernelInspector.cs +++ b/Editor/uFrameEditors/uFrameMVVMKernelInspector.cs @@ -2,6 +2,7 @@ using System.Linq; using Invert.Common; using Invert.Common.UI; +using uFrame.Kernel; using UnityEditor; using UnityEngine; @@ -38,6 +39,8 @@ public override void OnInspectorGUI() { Warning("Kernel is not loaded!"); } + if (uFrameMVVMKernel.Instance == null) return; + if (GUIHelpers.DoToolbarEx("Services")) { foreach (var instance in uFrameMVVMKernel.Instance.Services) @@ -52,9 +55,10 @@ public override void OnInspectorGUI() } } } - + if (GUIHelpers.DoToolbarEx("Systems")) { + foreach (var instance in uFrameMVVMKernel.Instance.SystemLoaders) { if (GUIHelpers.DoTriggerButton(new UFStyle() diff --git a/Kernel/EventAggregator.cs b/Kernel/EventAggregator.cs index 0b163ad7..ea3a79de 100644 --- a/Kernel/EventAggregator.cs +++ b/Kernel/EventAggregator.cs @@ -1,56 +1,59 @@ using System; using UniRx; -public class EventAggregator : IEventAggregator, ISubject +namespace uFrame.Kernel { - bool isDisposed; - readonly Subject eventsSubject = new Subject(); - - public IObservable GetEvent() + public class EventAggregator : IEventAggregator, ISubject { - return eventsSubject.Where(p => + bool isDisposed; + readonly Subject eventsSubject = new Subject(); + + public IObservable GetEvent() { - return p is TEvent; - }).Select(delegate(object p) + return eventsSubject.Where(p => + { + return p is TEvent; + }).Select(delegate(object p) + { + return (TEvent)p; + }); + } + + public void Publish(TEvent evt) { - return (TEvent) p; - }); - } - - public void Publish(TEvent evt) - { - eventsSubject.OnNext(evt); - } + eventsSubject.OnNext(evt); + } - public void Dispose() - { - Dispose(true); - } + public void Dispose() + { + Dispose(true); + } - protected virtual void Dispose(bool disposing) - { - if (isDisposed) return; - eventsSubject.Dispose(); - isDisposed = true; - } + protected virtual void Dispose(bool disposing) + { + if (isDisposed) return; + eventsSubject.Dispose(); + isDisposed = true; + } - public void OnCompleted() - { - eventsSubject.OnCompleted(); - } + public void OnCompleted() + { + eventsSubject.OnCompleted(); + } - public void OnError(Exception error) - { - eventsSubject.OnError(error); - } + public void OnError(Exception error) + { + eventsSubject.OnError(error); + } - public void OnNext(object value) - { - eventsSubject.OnNext(value); - } + public void OnNext(object value) + { + eventsSubject.OnNext(value); + } - public IDisposable Subscribe(IObserver observer) - { - return eventsSubject.Subscribe(observer); + public IDisposable Subscribe(IObserver observer) + { + return eventsSubject.Subscribe(observer); + } } -} \ No newline at end of file +} diff --git a/Kernel/GameContainer.cs b/Kernel/GameContainer.cs index 423ead3d..26f4097e 100644 --- a/Kernel/GameContainer.cs +++ b/Kernel/GameContainer.cs @@ -4,449 +4,443 @@ using System.Linq; using System.Reflection; - #if DLL - -namespace Invert.Core -{ -#endif - -/// -/// A ViewModel Container and a factory for Controllers and commands. -/// -#if DLL - public class uFrameContainer : IUFrameContainer +namespace Invert.IOC #else -public class GameContainer : IGameContainer +namespace uFrame.IOC #endif - { - private TypeInstanceCollection _instances; - private TypeMappingCollection _mappings; + /// + /// A ViewModel Container and a factory for Controllers and commands. + /// + public class UFrameContainer : IUFrameContainer - public TypeMappingCollection Mappings { - get { return _mappings ?? (_mappings = new TypeMappingCollection()); } - set { _mappings = value; } - } + private TypeInstanceCollection _instances; + private TypeMappingCollection _mappings; - public TypeInstanceCollection Instances - { - get { return _instances ?? (_instances = new TypeInstanceCollection()); } - set { _instances = value; } - } - public TypeRelationCollection RelationshipMappings - { - get { return _relationshipMappings; } - set { _relationshipMappings = value; } - } + public TypeMappingCollection Mappings + { + get { return _mappings ?? (_mappings = new TypeMappingCollection()); } + set { _mappings = value; } + } - public IEnumerable ResolveAll() - { - foreach (var obj in ResolveAll(typeof(TType))) + public TypeInstanceCollection Instances { - yield return (TType)obj; + get { return _instances ?? (_instances = new TypeInstanceCollection()); } + set { _instances = value; } } - } - /// - /// Resolves all instances of TType or subclasses of TType. Either named or not. - /// - /// The Type to resolve - /// List of objects. - public IEnumerable ResolveAll(Type type) - { - foreach (var instance1 in Instances.Where(p => p.Base == type && !string.IsNullOrEmpty(p.Name))) + public TypeRelationCollection RelationshipMappings { - yield return instance1.Instance; + get { return _relationshipMappings; } + set { _relationshipMappings = value; } } - foreach (var mapping in Mappings) + public IEnumerable ResolveAll() { - if (!string.IsNullOrEmpty(mapping.Name)) + foreach (var obj in ResolveAll(typeof(TType))) + { + yield return (TType)obj; + } + } + + /// + /// Resolves all instances of TType or subclasses of TType. Either named or not. + /// + /// The Type to resolve + /// List of objects. + public IEnumerable ResolveAll(Type type) + { + foreach (var instance1 in Instances.Where(p => p.Base == type && !string.IsNullOrEmpty(p.Name))) + { + yield return instance1.Instance; + } + + foreach (var mapping in Mappings) { + if (!string.IsNullOrEmpty(mapping.Name)) + { #if NETFX_CORE var condition = type.GetTypeInfo().IsSubclassOf(mapping.From); #else - var condition = type.IsAssignableFrom(mapping.From); + var condition = type.IsAssignableFrom(mapping.From); #endif - if (condition) - { - var item = Activator.CreateInstance(mapping.To); - Inject(item); - yield return item; + if (condition) + { + var item = Activator.CreateInstance(mapping.To); + Inject(item); + yield return item; + } } } } - } - /// - /// Clears all type-mappings and instances. - /// - public void Clear() - { - Instances.Clear(); - Mappings.Clear(); - RelationshipMappings.Clear(); - } + /// + /// Clears all type-mappings and instances. + /// + public void Clear() + { + Instances.Clear(); + Mappings.Clear(); + RelationshipMappings.Clear(); + } - /// - /// Injects registered types/mappings into an object - /// - /// - public void Inject(object obj) - { - if (obj == null) return; + /// + /// Injects registered types/mappings into an object + /// + /// + public void Inject(object obj) + { + if (obj == null) return; #if !NETFX_CORE - var members = obj.GetType().GetMembers(); + var members = obj.GetType().GetMembers(); #else var members = obj.GetType().GetTypeInfo().DeclaredMembers; #endif - foreach (var memberInfo in members) - { - var injectAttribute = - memberInfo.GetCustomAttributes(typeof(InjectAttribute), true).FirstOrDefault() as InjectAttribute; - if (injectAttribute != null) + foreach (var memberInfo in members) { - if (memberInfo is PropertyInfo) - { - var propertyInfo = memberInfo as PropertyInfo; - propertyInfo.SetValue(obj, Resolve(propertyInfo.PropertyType, injectAttribute.Name), null); - } - else if (memberInfo is FieldInfo) + var injectAttribute = + memberInfo.GetCustomAttributes(typeof(InjectAttribute), true).FirstOrDefault() as InjectAttribute; + if (injectAttribute != null) { - var fieldInfo = memberInfo as FieldInfo; - fieldInfo.SetValue(obj, Resolve(fieldInfo.FieldType, injectAttribute.Name)); + if (memberInfo is PropertyInfo) + { + var propertyInfo = memberInfo as PropertyInfo; + propertyInfo.SetValue(obj, Resolve(propertyInfo.PropertyType, injectAttribute.Name), null); + } + else if (memberInfo is FieldInfo) + { + var fieldInfo = memberInfo as FieldInfo; + fieldInfo.SetValue(obj, Resolve(fieldInfo.FieldType, injectAttribute.Name)); + } } } } - } - - /// - /// Register a type mapping - /// - /// The base type. - /// The concrete type - public void Register(string name = null) - { - Mappings[typeof(TSource), name] = typeof(TTarget); - } - - public void Register(Type source, Type target, string name = null) - { - Mappings[source, name] = target; - } - /// - /// Register a named instance - /// - /// The type to register the instance for. - /// The instance that will be resolved be the name - /// Perform the injection immediately - public void RegisterInstance(Type baseType, object instance = null, bool injectNow = true) - { - RegisterInstance(baseType, instance, null, injectNow); - } + /// + /// Register a type mapping + /// + /// The base type. + /// The concrete type + public void Register(string name = null) + { + Mappings[typeof(TSource), name] = typeof(TTarget); + } - /// - /// Register a named instance - /// - /// The type to register the instance for. - /// The name for the instance to be resolved. - /// The instance that will be resolved be the name - /// Perform the injection immediately - public virtual void RegisterInstance(Type baseType, object instance = null, string name = null, bool injectNow = true) - { - Instances[baseType, name] = instance; - if (injectNow) + public void Register(Type source, Type target, string name = null) { - Inject(instance); + Mappings[source, name] = target; } - } - public void RegisterInstance(TBase instance) where TBase : class - { - RegisterInstance(instance, true); - } + /// + /// Register a named instance + /// + /// The type to register the instance for. + /// The instance that will be resolved be the name + /// Perform the injection immediately + public void RegisterInstance(Type baseType, object instance = null, bool injectNow = true) + { + RegisterInstance(baseType, instance, null, injectNow); + } - public void RegisterInstance(TBase instance, bool injectNow) where TBase : class - { - RegisterInstance(instance, null, injectNow); - } + /// + /// Register a named instance + /// + /// The type to register the instance for. + /// The name for the instance to be resolved. + /// The instance that will be resolved be the name + /// Perform the injection immediately + public virtual void RegisterInstance(Type baseType, object instance = null, string name = null, bool injectNow = true) + { + Instances[baseType, name] = instance; + if (injectNow) + { + Inject(instance); + } + } - public void RegisterInstance(TBase instance, string name, bool injectNow = true) where TBase : class - { - RegisterInstance(typeof(TBase), instance, name, injectNow); - } + public void RegisterInstance(TBase instance) where TBase : class + { + RegisterInstance(instance, true); + } - /// - /// If an instance of T exist then it will return that instance otherwise it will create a new one based off mappings. - /// - /// The type of instance to resolve - /// The/An instance of 'instanceType' - public T Resolve(string name = null, bool requireInstance = false, params object[] args) where T : class - { - return (T)Resolve(typeof(T), name, requireInstance, args); - } + public void RegisterInstance(TBase instance, bool injectNow) where TBase : class + { + RegisterInstance(instance, null, injectNow); + } - /// - /// If an instance of instanceType exist then it will return that instance otherwise it will create a new one based off mappings. - /// - /// The type of instance to resolve - /// The type of instance to resolve - /// If true will return null if an instance isn't registered. - /// The arguments to pass to the constructor if any. - /// The/An instance of 'instanceType' - public object Resolve(Type baseType, string name = null, bool requireInstance = false, params object[] constructorArgs) - { - // Look for an instance first - var item = Instances[baseType, name]; - if (item != null) + public void RegisterInstance(TBase instance, string name, bool injectNow = true) where TBase : class { - return item; + RegisterInstance(typeof(TBase), instance, name, injectNow); } - if (requireInstance) - return null; - // Check if there is a mapping of the type - var namedMapping = Mappings[baseType, name]; - if (namedMapping != null) + + /// + /// If an instance of T exist then it will return that instance otherwise it will create a new one based off mappings. + /// + /// The type of instance to resolve + /// The/An instance of 'instanceType' + public T Resolve(string name = null, bool requireInstance = false, params object[] args) where T : class { - var obj = CreateInstance(namedMapping, constructorArgs); - Inject(obj); - return obj; + return (T)Resolve(typeof(T), name, requireInstance, args); } - return null; - } - public object CreateInstance(Type type, params object[] constructorArgs) - { - if (constructorArgs != null && constructorArgs.Length > 0) + /// + /// If an instance of instanceType exist then it will return that instance otherwise it will create a new one based off mappings. + /// + /// The type of instance to resolve + /// The type of instance to resolve + /// If true will return null if an instance isn't registered. + /// The arguments to pass to the constructor if any. + /// The/An instance of 'instanceType' + public object Resolve(Type baseType, string name = null, bool requireInstance = false, params object[] constructorArgs) { - //return Activator.CreateInstance(type,BindingFlags.Public | BindingFlags.Instance,Type.DefaultBinder, constructorArgs,CultureInfo.CurrentCulture); - var obj2 = Activator.CreateInstance(type, constructorArgs); - Inject(obj2); - return obj2; + // Look for an instance first + var item = Instances[baseType, name]; + if (item != null) + { + return item; + } + if (requireInstance) + return null; + // Check if there is a mapping of the type + var namedMapping = Mappings[baseType, name]; + if (namedMapping != null) + { + var obj = CreateInstance(namedMapping, constructorArgs); + Inject(obj); + return obj; + } + return null; } + + public object CreateInstance(Type type, params object[] constructorArgs) + { + if (constructorArgs != null && constructorArgs.Length > 0) + { + //return Activator.CreateInstance(type,BindingFlags.Public | BindingFlags.Instance,Type.DefaultBinder, constructorArgs,CultureInfo.CurrentCulture); + var obj2 = Activator.CreateInstance(type, constructorArgs); + Inject(obj2); + return obj2; + } #if !NETFX_CORE - ConstructorInfo[] constructor = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance); + ConstructorInfo[] constructor = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance); #else ConstructorInfo[] constructor = type.GetTypeInfo().DeclaredConstructors.ToArray(); #endif - if (constructor.Length < 1) - { - var obj2 = Activator.CreateInstance(type); - Inject(obj2); - return obj2; - } + if (constructor.Length < 1) + { + var obj2 = Activator.CreateInstance(type); + Inject(obj2); + return obj2; + } - var maxParameters = constructor.First().GetParameters(); + var maxParameters = constructor.First().GetParameters(); - foreach (var c in constructor) - { - var parameters = c.GetParameters(); - if (parameters.Length > maxParameters.Length) + foreach (var c in constructor) { - maxParameters = parameters; + var parameters = c.GetParameters(); + if (parameters.Length > maxParameters.Length) + { + maxParameters = parameters; + } + } + var args = maxParameters.Select(p => + { + if (p.ParameterType.IsArray) + { + return ResolveAll(p.ParameterType); + } + return Resolve(p.ParameterType) ?? Resolve(p.ParameterType, p.Name); + }).ToArray(); + var obj = Activator.CreateInstance(type, args); + Inject(obj); + return obj; } - var args = maxParameters.Select(p => + + public TBase ResolveRelation(Type tfor, params object[] args) { - if (p.ParameterType.IsArray) + try { - return ResolveAll(p.ParameterType); + return (TBase)ResolveRelation(tfor, typeof(TBase), args); + } + catch (InvalidCastException castIssue) + { + throw new Exception(string.Format("Resolve Relation couldn't cast to {0} from {1}", typeof(TBase).Name, tfor.Name), castIssue); } - return Resolve(p.ParameterType) ?? Resolve(p.ParameterType, p.Name); - }).ToArray(); - - var obj = Activator.CreateInstance(type, args); - Inject(obj); - return obj; - } - - public TBase ResolveRelation(Type tfor, params object[] args) - { - try - { - return (TBase)ResolveRelation(tfor, typeof(TBase), args); } - catch (InvalidCastException castIssue) + public void InjectAll() { - throw new Exception(string.Format("Resolve Relation couldn't cast to {0} from {1}", typeof(TBase).Name, tfor.Name), castIssue); - } - } - public void InjectAll() - { - foreach (var instance in Instances) - { - Inject(instance.Instance); + foreach (var instance in Instances) + { + Inject(instance.Instance); + } + foreach (var namedInstance in Instances) + { + Inject(namedInstance.Instance); + } } - foreach (var namedInstance in Instances) + private TypeRelationCollection _relationshipMappings = new TypeRelationCollection(); + public void RegisterRelation() { - Inject(namedInstance.Instance); + RelationshipMappings[typeof(TFor), typeof(TBase)] = typeof(TConcrete); } - } - private TypeRelationCollection _relationshipMappings = new TypeRelationCollection(); - public void RegisterRelation() - { - RelationshipMappings[typeof(TFor), typeof(TBase)] = typeof(TConcrete); - } - public void RegisterRelation(Type tfor, Type tbase, Type tconcrete) - { - RelationshipMappings[tfor, tbase] = tconcrete; - } - public object ResolveRelation(Type tfor, Type tbase, params object[] args) - { - var concreteType = RelationshipMappings[tfor, tbase]; - - if (concreteType == null) + public void RegisterRelation(Type tfor, Type tbase, Type tconcrete) { - return null; + RelationshipMappings[tfor, tbase] = tconcrete; } - var result = CreateInstance(concreteType, args); - Inject(result); - return result; - } - public TBase ResolveRelation(params object[] arg) - { - return (TBase)ResolveRelation(typeof(TFor), typeof(TBase), arg); - } -} - -public class TypeMappingCollection : List -{ - public Type this[Type from, string name = null] - { - get + public object ResolveRelation(Type tfor, Type tbase, params object[] args) { - var mapping = this.FirstOrDefault(p => p.From == from && p.Name == name); - if (mapping != null) + var concreteType = RelationshipMappings[tfor, tbase]; + + if (concreteType == null) { - return mapping.To; + return null; } - return null; + var result = CreateInstance(concreteType, args); + Inject(result); + return result; } - set + public TBase ResolveRelation(params object[] arg) { - var mapping = this.FirstOrDefault(p => p.From == from && p.Name == name); - if (mapping == null) - { - Add(new TypeMapping() { From = from, Name = name, To = value }); - } - else - { - mapping.To = value; - mapping.Name = name; - } + return (TBase)ResolveRelation(typeof(TFor), typeof(TBase), arg); } } -} -public class TypeInstanceCollection : List -{ - public object this[Type from, string name = null] + public class TypeMappingCollection : List { - get + public Type this[Type from, string name = null] { - var mapping = this.FirstOrDefault(p => p.Base == from && p.Name == name); - if (mapping != null) + get { - return mapping.Instance; - } - return null; - } - set - { - var mapping = this.FirstOrDefault(p => p.Base == from && p.Name == name); - if (mapping == null) - { - Add(new RegisteredInstance() { Base = from, Name = name, Instance = value }); + var mapping = this.FirstOrDefault(p => p.From == from && p.Name == name); + if (mapping != null) + { + return mapping.To; + } + return null; } - else + set { - mapping.Instance = value; - mapping.Name = name; + var mapping = this.FirstOrDefault(p => p.From == from && p.Name == name); + if (mapping == null) + { + Add(new TypeMapping() { From = from, Name = name, To = value }); + } + else + { + mapping.To = value; + mapping.Name = name; + } } } } -} -public class TypeRelationCollection : List -{ - public Type this[Type from, Type to] + public class TypeInstanceCollection : List { - get + + public object this[Type from, string name = null] { - var mapping = this.FirstOrDefault(p => p.From == from && p.To == to); - if (mapping != null) + get { - return mapping.Concrete; + var mapping = this.FirstOrDefault(p => p.Base == from && p.Name == name); + if (mapping != null) + { + return mapping.Instance; + } + return null; + } + set + { + var mapping = this.FirstOrDefault(p => p.Base == from && p.Name == name); + if (mapping == null) + { + Add(new RegisteredInstance() { Base = from, Name = name, Instance = value }); + } + else + { + mapping.Instance = value; + mapping.Name = name; + } } - return null; } - set + } + public class TypeRelationCollection : List + { + public Type this[Type from, Type to] { - var mapping = this.FirstOrDefault(p => p.From == from && p.To == to); - if (mapping == null) + get { - Add(new TypeRelation() { From = from, To = to, Concrete = value }); + var mapping = this.FirstOrDefault(p => p.From == from && p.To == to); + if (mapping != null) + { + return mapping.Concrete; + } + return null; } - else + set { - mapping.Concrete = value; + var mapping = this.FirstOrDefault(p => p.From == from && p.To == to); + if (mapping == null) + { + Add(new TypeRelation() { From = from, To = to, Concrete = value }); + } + else + { + mapping.Concrete = value; + } } } } -} -public class TypeRelation -{ - public Type From + public class TypeRelation { - get; - set; - } + public Type From + { + get; + set; + } - public Type To { get; set; } + public Type To { get; set; } - public Type Concrete { get; set; } + public Type Concrete { get; set; } - //public string Name { get; set; } -} -public class RegisteredInstance -{ - public Type Base - { - get; - set; + //public string Name { get; set; } } - - public object Instance + public class RegisteredInstance { - get; - set; - } + public Type Base + { + get; + set; + } - public string Name { get; set; } -} -public class TypeMapping -{ - public Type From - { - get; - set; - } + public object Instance + { + get; + set; + } - public Type To + public string Name { get; set; } + } + public class TypeMapping { - get; - set; + public Type From + { + get; + set; + } + + public Type To + { + get; + set; + } + public string Name { get; set; } } - public string Name { get; set; } -} -#if DLL -} -#endif \ No newline at end of file +} diff --git a/Kernel/IEventAggregator.cs b/Kernel/IEventAggregator.cs index 66f029c5..e50b4245 100644 --- a/Kernel/IEventAggregator.cs +++ b/Kernel/IEventAggregator.cs @@ -1,7 +1,11 @@ using UniRx; using System; // Required for WP8 and Store APPS -public interface IEventAggregator + +namespace uFrame.Kernel { - IObservable GetEvent(); - void Publish(TEvent evt); + public interface IEventAggregator + { + IObservable GetEvent(); + void Publish(TEvent evt); + } } \ No newline at end of file diff --git a/Kernel/IGameContainer.cs b/Kernel/IGameContainer.cs index 9668d4f7..41b1a768 100644 --- a/Kernel/IGameContainer.cs +++ b/Kernel/IGameContainer.cs @@ -1,120 +1,113 @@ using System; using System.Collections.Generic; - #if DLL - -namespace Invert.Core -{ - public interface IUFrameContainer +namespace Invert.IOC #else - -public interface IGameContainer +namespace uFrame.IOC #endif - { - /// - /// Clears all type mappings and instances. - /// - void Clear(); - - /// - /// Injects registered types/mappings into an object - /// - /// - void Inject(object obj); - - /// - /// Injects everything that is registered at once - /// - void InjectAll(); - - /// - /// Register a type mapping - /// - /// The base type. - /// The concrete type - void Register(string name = null); - - void RegisterRelation(); - - /// - /// Register an instance of a type. - /// - /// - /// - /// - /// - void RegisterInstance(TBase @default, bool injectNow) where TBase : class; - - /// - /// Register an instance of a type. - /// - /// - /// - /// - /// - void RegisterInstance(Type type, object @default, bool injectNow); - - /// - /// Register a named instance - /// - /// The type to register the instance for. - /// The name for the instance to be resolved. - /// The instance that will be resolved be the name - /// Perform the injection immediately - void RegisterInstance(Type baseType, object instance = null, string name = null, bool injectNow = true); - - void RegisterInstance(TBase instance, string name, bool injectNow = true) where TBase : class; - - void RegisterInstance(TBase instance) where TBase : class; - - /// - /// If an instance of T exist then it will return that instance otherwise it will create a new one based off mappings. - /// - /// The type of instance to resolve - /// The/An instance of 'instanceType' - T Resolve(string name = null, bool requireInstance = false, params object[] args) where T : class; - - TBase ResolveRelation(Type tfor, params object[] arg); - - TBase ResolveRelation(params object[] arg); - - /// - /// Resolves all instances of TType or subclasses of TType. Either named or not. - /// - /// The Type to resolve - /// List of objects. - IEnumerable ResolveAll(); - - //IEnumerable ResolveAll(Type type); - void Register(Type source, Type target, string name = null); - - /// - /// Resolves all instances of TType or subclasses of TType. Either named or not. - /// - /// The Type to resolve - /// List of objects. - IEnumerable ResolveAll(Type type); - - TypeMappingCollection Mappings { get; set; } - TypeInstanceCollection Instances { get; set; } - TypeRelationCollection RelationshipMappings { get; set; } - - /// - /// If an instance of instanceType exist then it will return that instance otherwise it will create a new one based off mappings. - /// - /// The type of instance to resolve - /// The type of instance to resolve - /// If true will return null if an instance isn't registered. - /// The/An instance of 'instanceType' - object Resolve(Type baseType, string name = null, bool requireInstance = false, params object[] constructorArgs); - - object ResolveRelation(Type tfor, Type tbase, params object[] arg); - void RegisterRelation(Type tfor, Type tbase, Type tconcrete); - object CreateInstance(Type type, params object[] args); -} -#if DLL + public interface IUFrameContainer + { + /// + /// Clears all type mappings and instances. + /// + void Clear(); + + /// + /// Injects registered types/mappings into an object + /// + /// + void Inject(object obj); + + /// + /// Injects everything that is registered at once + /// + void InjectAll(); + + /// + /// Register a type mapping + /// + /// The base type. + /// The concrete type + void Register(string name = null); + + void RegisterRelation(); + + /// + /// Register an instance of a type. + /// + /// + /// + /// + /// + void RegisterInstance(TBase @default, bool injectNow) where TBase : class; + + /// + /// Register an instance of a type. + /// + /// + /// + /// + /// + void RegisterInstance(Type type, object @default, bool injectNow); + + /// + /// Register a named instance + /// + /// The type to register the instance for. + /// The name for the instance to be resolved. + /// The instance that will be resolved be the name + /// Perform the injection immediately + void RegisterInstance(Type baseType, object instance = null, string name = null, bool injectNow = true); + + void RegisterInstance(TBase instance, string name, bool injectNow = true) where TBase : class; + + void RegisterInstance(TBase instance) where TBase : class; + + /// + /// If an instance of T exist then it will return that instance otherwise it will create a new one based off mappings. + /// + /// The type of instance to resolve + /// The/An instance of 'instanceType' + T Resolve(string name = null, bool requireInstance = false, params object[] args) where T : class; + + TBase ResolveRelation(Type tfor, params object[] arg); + + TBase ResolveRelation(params object[] arg); + + /// + /// Resolves all instances of TType or subclasses of TType. Either named or not. + /// + /// The Type to resolve + /// List of objects. + IEnumerable ResolveAll(); + + //IEnumerable ResolveAll(Type type); + void Register(Type source, Type target, string name = null); + + /// + /// Resolves all instances of TType or subclasses of TType. Either named or not. + /// + /// The Type to resolve + /// List of objects. + IEnumerable ResolveAll(Type type); + + TypeMappingCollection Mappings { get; set; } + TypeInstanceCollection Instances { get; set; } + TypeRelationCollection RelationshipMappings { get; set; } + + /// + /// If an instance of instanceType exist then it will return that instance otherwise it will create a new one based off mappings. + /// + /// The type of instance to resolve + /// The type of instance to resolve + /// If true will return null if an instance isn't registered. + /// The/An instance of 'instanceType' + object Resolve(Type baseType, string name = null, bool requireInstance = false, params object[] constructorArgs); + + object ResolveRelation(Type tfor, Type tbase, params object[] arg); + void RegisterRelation(Type tfor, Type tbase, Type tconcrete); + object CreateInstance(Type type, params object[] args); + } } - -#endif \ No newline at end of file diff --git a/Kernel/IScene.cs b/Kernel/IScene.cs index ca3b1763..f5913530 100644 --- a/Kernel/IScene.cs +++ b/Kernel/IScene.cs @@ -1,7 +1,10 @@ -public interface IScene +namespace uFrame.Kernel { - string Name { get; set; } + public interface IScene + { + string Name { get; set; } - ISceneSettings _SettingsObject { get; set; } + ISceneSettings _SettingsObject { get; set; } + } } \ No newline at end of file diff --git a/Kernel/ISceneLoader.cs b/Kernel/ISceneLoader.cs index 1fc782bc..70997fe0 100644 --- a/Kernel/ISceneLoader.cs +++ b/Kernel/ISceneLoader.cs @@ -1,9 +1,30 @@ using System; using System.Collections; - +/// +/// The Scene Loader is used to manage loading and unloading a scene, it is part of the kernel and is always available, +/// this makes sure that whenever you want to load a scene, you have complete control over it very easily. +/// public interface ISceneLoader { + /// + /// The type of scene that this loader is for. This is used by the kernel to link link it to the + /// scene type when the "SceneAwakeEvent" is invoked. + /// Type SceneType { get; } + + /// + /// Use this method to load the scene, this is useful to provide any additional setup that the scene may need programatically. + /// + /// + /// + /// IEnumerator Load(object scene, Action progressDelegate); + + /// + /// Whenever the sene is destroyed, Unload gives you programmatic control over how a scene is unloaded. + /// + /// + /// + /// IEnumerator Unload(object scene, Action progressDelegate); } \ No newline at end of file diff --git a/Kernel/ISystemLoader.cs b/Kernel/ISystemLoader.cs index ab6e9262..7cc5201f 100644 --- a/Kernel/ISystemLoader.cs +++ b/Kernel/ISystemLoader.cs @@ -1,43 +1,32 @@ using System; using UnityEngine; using System.Collections; +using uFrame.IOC; +using uFrame.Kernel; -public interface ISystemLoader +namespace uFrame.Kernel { - - void Load(); - - IGameContainer Container + public interface ISystemLoader { - get; - set; - } - IEventAggregator EventAggregator - { - get; - set; - } + void Load(); -} + IUFrameContainer Container { get; set; } -public partial class SystemLoader : MonoBehaviour,ISystemLoader -{ - public virtual void Load() - { - - } + IEventAggregator EventAggregator { get; set; } - public IGameContainer Container - { - get; - set; } - public IEventAggregator EventAggregator + public partial class SystemLoader : MonoBehaviour, ISystemLoader { - get; - set; + public virtual void Load() + { + + } + + public IUFrameContainer Container { get; set; } + + public IEventAggregator EventAggregator { get; set; } } -} +} \ No newline at end of file diff --git a/Kernel/ISystemService.cs b/Kernel/ISystemService.cs index abf681fc..a15b0093 100644 --- a/Kernel/ISystemService.cs +++ b/Kernel/ISystemService.cs @@ -1,15 +1,26 @@ using System.Collections; -public interface ISystemService +namespace uFrame.Kernel { - IEventAggregator EventAggregator { get; set; } + public interface ISystemService + { + /// + /// The Aggregator that must be used to setup everything. + /// + IEventAggregator EventAggregator { get; set; } - /// - /// The setup method is called when the controller is first created and has been injected. Use this - /// to subscribe to any events on the EventAggregator - /// - void Setup(); + /// + /// The setup method is called when the controller is first created and has been injected. Use this + /// to subscribe to any events on the EventAggregator + /// + void Setup(); - IEnumerator SetupAsync(); + /// + /// The SetupAsync method is called after the Setup method is invoke, if this service needs to load anything + /// async, this is the perfect place to do it. (e.g. Logging a user in, download player data..etc) + /// + /// + IEnumerator SetupAsync(); + } } \ No newline at end of file diff --git a/Kernel/InjectAttribute.cs b/Kernel/InjectAttribute.cs index b1c6c189..7e91b441 100644 --- a/Kernel/InjectAttribute.cs +++ b/Kernel/InjectAttribute.cs @@ -1,26 +1,28 @@ using System; #if DLL -namespace Invert.Core -{ +namespace Invert.IOC +#else +namespace uFrame.IOC #endif -/// -/// Used by the injection container to determine if a property or field should be injected. -/// -[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] -public class InjectAttribute : Attribute { - public InjectAttribute(string name) + + /// + /// Used by the injection container to determine if a property or field should be injected. + /// + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class InjectAttribute : Attribute { - Name = name; - } + public InjectAttribute(string name) + { + Name = name; + } - public string Name { get; set; } + public string Name { get; set; } - public InjectAttribute() - { + public InjectAttribute() + { + } } -} -#if DLL -} -#endif \ No newline at end of file + +} \ No newline at end of file diff --git a/Kernel/Scene.cs b/Kernel/Scene.cs index 48dc205a..b7f8b158 100644 --- a/Kernel/Scene.cs +++ b/Kernel/Scene.cs @@ -1,62 +1,79 @@ using System.Collections; using UnityEngine; using UniRx; -public class Scene : uFrameComponent, IScene -{ - [SerializeField] - private string _KernelScene; - - protected string KernelScene +namespace uFrame.Kernel +{ + /// + /// The scene class is used to define a scene as a class, + /// this MonoBehaviour should live on a gameobject that is at the root level of the scene it is defining. + /// When this type is loaded by unity, it will publish the SceneAwakeEvent. The SceneManagementService (part of the kernel) will + /// then find the scene loader associated with this scene and invoke its Load Co-Routine method. + /// + public class Scene : uFrameComponent, IScene { - get + [SerializeField] private string _KernelScene; + + /// + /// The kernel scene property is so that this scene can load the correct kernel if it hasn't been loaded yet. + /// + protected string KernelScene { - if (string.IsNullOrEmpty(_KernelScene)) + get { - return DefaultKernelScene; + if (string.IsNullOrEmpty(_KernelScene)) + { + return DefaultKernelScene; + } + return _KernelScene; } - return _KernelScene; } - } - public virtual string DefaultKernelScene { get; set; } - public string Name { get; set; } + /// + /// The default kernel scene is what is used if the "KernelScene" property is not set. This is really used by + /// the uFrame designer to remove the extra step of specifying the kernel scene each time a scene is created. + /// + public virtual string DefaultKernelScene { get; set; } - public ISceneSettings _SettingsObject { get; set; } + /// + /// The Name of this scene, this is set by the kernel so that it can reference back to it and destroy it when the + /// Unload Scene Command is fired. + /// + public string Name { get; set; } - public IEventAggregator Aggregator { get; set; } - public void Awake() - { - StartCoroutine(InternalAwake()); - } + /// + /// If this scene was loaded via a + /// + public ISceneSettings _SettingsObject { get; set; } - protected override IEnumerator Start() - { - if (!uFrameMVVMKernel.IsKernelLoaded) + /// + /// In this class we override the start method so that we can trigger the kernel to load if its not already. + /// + /// + protected override IEnumerator Start() { - Name = Application.loadedLevelName; - yield return StartCoroutine(uFrameMVVMKernel.InstantiateSceneAsyncAdditively(KernelScene)); + this.KernelLoading(); + if (!uFrameMVVMKernel.IsKernelLoaded) + { + Name = Application.loadedLevelName; + yield return StartCoroutine(uFrameMVVMKernel.InstantiateSceneAsyncAdditively(KernelScene)); + } + while (!uFrameMVVMKernel.IsKernelLoaded) yield return null; + this.KernelLoaded(); + this.Publish(new SceneAwakeEvent() {Scene = this}); } - while (!uFrameMVVMKernel.IsKernelLoaded) yield return null; - uFrameMVVMKernel.EventAggregator.Publish(new SceneAwakeEvent() { Scene = this }); - } - public IEnumerator InternalAwake() - { - - while (!uFrameMVVMKernel.IsKernelLoaded) - { - yield return null; - } - - - } -} -public class SceneAwakeEvent -{ - public IScene Scene { get; set; } + } + + /// + /// This class is used internally by the Scene class and the kernel to trigger scene loaders load method. + /// + public class SceneAwakeEvent + { + public IScene Scene { get; set; } + } } \ No newline at end of file diff --git a/Kernel/SceneLoader.cs b/Kernel/SceneLoader.cs index 6f9af6fd..88a89188 100644 --- a/Kernel/SceneLoader.cs +++ b/Kernel/SceneLoader.cs @@ -2,56 +2,76 @@ using System.Collections; using UnityEngine; -public abstract class SceneLoader : MonoBehaviour, ISceneLoader where T : IScene +namespace uFrame.Kernel { - - public virtual Type SceneType + public abstract class SceneLoader : uFrameComponent, ISceneLoader where T : IScene { - get { return typeof (T); } - } - - protected abstract IEnumerator LoadScene(T scene, Action progressDelegate); - protected abstract IEnumerator UnloadScene(T scene, Action progressDelegate); - public IEnumerator Load(object sceneObject, Action progressDelegate) - { - return LoadScene((T)sceneObject,progressDelegate); - } + public virtual Type SceneType + { + get { return typeof (T); } + } - public IEnumerator Unload(object sceneObject, Action progressDelegate) - { - return UnloadScene((T)sceneObject,progressDelegate); - } + /// + /// The type of scene that this loader is for. This is used by the kernel to link link it to the + /// scene type when the "SceneAwakeEvent" is invoked. + /// + /// The scene component that is at the root of the scene. + /// The progress delegate for providing user feedback on long running actions. + /// + protected abstract IEnumerator LoadScene(T scene, Action progressDelegate); -} + /// + /// + /// + /// The scene component that is at the root of the scene. + /// The progress delegate for providing user feedback on long running actions. + /// + protected abstract IEnumerator UnloadScene(T scene, Action progressDelegate); + public IEnumerator Load(object sceneObject, Action progressDelegate) + { + return LoadScene((T) sceneObject, progressDelegate); + } -public class DefaultSceneLoader : SceneLoader -{ + public IEnumerator Unload(object sceneObject, Action progressDelegate) + { + return UnloadScene((T) sceneObject, progressDelegate); + } - public override Type SceneType - { - get { return typeof(IScene); } } - protected override IEnumerator LoadScene(IScene scene, Action progressDelegate) - { - yield break; - } - protected override IEnumerator UnloadScene(IScene scene, Action progressDelegate) + /// + /// + /// + public class DefaultSceneLoader : SceneLoader { - yield break; - } - //public IEnumerator Load(object sceneObject, Action progressDelegate) - //{ - // return LoadScene((IScene)sceneObject, progressDelegate); - //} + public override Type SceneType + { + get { return typeof (IScene); } + } + + protected override IEnumerator LoadScene(IScene scene, Action progressDelegate) + { + yield break; + } - //public IEnumerator Unload(object sceneObject, object settings, Action progressDelegate) - //{ - // return UnloadScene((IScene)sceneObject, progressDelegate); - //} -} + protected override IEnumerator UnloadScene(IScene scene, Action progressDelegate) + { + yield break; + } + + //public IEnumerator Load(object sceneObject, Action progressDelegate) + //{ + // return LoadScene((IScene)sceneObject, progressDelegate); + //} + + //public IEnumerator Unload(object sceneObject, object settings, Action progressDelegate) + //{ + // return UnloadScene((IScene)sceneObject, progressDelegate); + //} + } +} \ No newline at end of file diff --git a/Kernel/SceneManagementService.cs b/Kernel/SceneManagementService.cs index 65a814fa..8ae54013 100644 --- a/Kernel/SceneManagementService.cs +++ b/Kernel/SceneManagementService.cs @@ -5,264 +5,275 @@ using UniRx; using UnityEngine; -public class SceneManagementService : SystemServiceMonoBehavior +namespace uFrame.Kernel { - - private Queue _scenesQueue; - public Queue ScenesQueue - { - get { return _scenesQueue ?? (_scenesQueue = new Queue()); } - } - public List LoadedScenes - { - get { return _loadedScenes ?? (_loadedScenes = new List()); } - } - private List _loadedScenes; - - [SerializeField] - private string[] _startupScenes = new string[] {}; - - public override void Setup() + public class SceneManagementService : SystemServiceMonoBehavior { - base.Setup(); - - this.OnEvent().Subscribe(_ => - { - - this.LoadScene(_.SceneName, _.Settings); - }); + private Queue _scenesQueue; - this.OnEvent().Subscribe(_ => + public Queue ScenesQueue { - this.UnloadScene(_.SceneName); - }); + get { return _scenesQueue ?? (_scenesQueue = new Queue()); } + } - var attachedSceneLoaders = uFrameMVVMKernel.Instance.GetComponentsInChildren(typeof(ISceneLoader)).OfType(); - foreach (var sceneLoader in attachedSceneLoaders) + public List LoadedScenes { - uFrameMVVMKernel.Container.RegisterSceneLoader(sceneLoader); - uFrameMVVMKernel.Container.Inject(sceneLoader); - SceneLoaders.Add(sceneLoader); + get { return _loadedScenes ?? (_loadedScenes = new List()); } } - _defaultSceneLoader = gameObject.GetComponent() ?? - gameObject.AddComponent(); - this.OnEvent().Subscribe(_ => StartCoroutine(SetupScene(_.Scene))); - } + private List _loadedScenes; - private List _sceneLoaders; - public List SceneLoaders - { - get - { - return _sceneLoaders ?? (_sceneLoaders = new List()); - } - } + [SerializeField] private string[] _startupScenes = new string[] {}; - public string[] StartupScenes - { - get { return _startupScenes; } - set { _startupScenes = value; } - } + public override void Setup() + { + base.Setup(); - private DefaultSceneLoader _defaultSceneLoader; + this.OnEvent().Subscribe(_ => + { - public IEnumerator LoadSceneInternal(string sceneName) - { - yield return StartCoroutine(uFrameMVVMKernel.InstantiateSceneAsyncAdditively(sceneName)); - } + this.LoadScene(_.SceneName, _.Settings); + }); - public void QueueSceneLoad(string sceneName, ISceneSettings settings) - { - ScenesQueue.Enqueue(new SceneQueueItem() - { - Loader = LoadSceneInternal(sceneName), - Name = sceneName, - Settings = settings - }); - } + this.OnEvent().Subscribe(_ => + { + this.UnloadScene(_.SceneName); + }); - public void QueueScenesLoad(params SceneQueueItem[] items) - { - foreach (var item in items) - { - if (item.Loader == null) + var attachedSceneLoaders = + uFrameMVVMKernel.Instance.GetComponentsInChildren(typeof (ISceneLoader)).OfType(); + foreach (var sceneLoader in attachedSceneLoaders) { - item.Loader = LoadSceneInternal(item.Name); + uFrameMVVMKernel.Container.RegisterSceneLoader(sceneLoader); + uFrameMVVMKernel.Container.Inject(sceneLoader); + SceneLoaders.Add(sceneLoader); } - ScenesQueue.Enqueue(item); + _defaultSceneLoader = gameObject.GetComponent() ?? + gameObject.AddComponent(); + + this.OnEvent().Subscribe(_ => StartCoroutine(SetupScene(_.Scene))); } - } - protected IEnumerator ExecuteLoadAsync() - { - foreach (var sceneQueeItem in ScenesQueue.ToArray()) + private List _sceneLoaders; + + public List SceneLoaders { - yield return StartCoroutine(sceneQueeItem.Loader); + get { return _sceneLoaders ?? (_sceneLoaders = new List()); } } - } - public void ExecuteLoad() - { - StartCoroutine(ExecuteLoadAsync()); - } - - public IEnumerator SetupScene(IScene sceneRoot) - { + public string[] StartupScenes + { + get { return _startupScenes; } + set { _startupScenes = value; } + } - this.Publish(new SceneLoaderEvent() - { - State = SceneState.Instantiated, - SceneRoot = sceneRoot - }); + private DefaultSceneLoader _defaultSceneLoader; + public IEnumerator LoadSceneInternal(string sceneName) + { + yield return StartCoroutine(uFrameMVVMKernel.InstantiateSceneAsyncAdditively(sceneName)); + } - //If the scene was loaded via the api (it was queued having some name and settings) - if (ScenesQueue.Count > 0) + public void QueueSceneLoad(string sceneName, ISceneSettings settings) { - var sceneQueueItem = ScenesQueue.Dequeue(); - sceneRoot.Name = sceneQueueItem.Name; - sceneRoot._SettingsObject = sceneQueueItem.Settings; + ScenesQueue.Enqueue(new SceneQueueItem() + { + Loader = LoadSceneInternal(sceneName), + Name = sceneName, + Settings = settings + }); } - //Else, means scene was the start scene (loaded before kernel) - else + + public void QueueScenesLoad(params SceneQueueItem[] items) { - sceneRoot.Name = Application.loadedLevelName; + foreach (var item in items) + { + if (item.Loader == null) + { + item.Loader = LoadSceneInternal(item.Name); + } + ScenesQueue.Enqueue(item); + } } + protected IEnumerator ExecuteLoadAsync() + { + foreach (var sceneQueeItem in ScenesQueue.ToArray()) + { + yield return StartCoroutine(sceneQueeItem.Loader); + } + } - this.Publish(new SceneLoaderEvent() + public void ExecuteLoad() { - State = SceneState.Instantiated, - SceneRoot = sceneRoot - }); + StartCoroutine(ExecuteLoadAsync()); + } - Action updateDelegate = (v, m) => + public IEnumerator SetupScene(IScene sceneRoot) { + this.Publish(new SceneLoaderEvent() { - State = SceneState.Update, - Progress = v, - ProgressMessage = m + State = SceneState.Instantiated, + SceneRoot = sceneRoot }); - }; - var sceneLoader = SceneLoaders.FirstOrDefault(loader => loader.SceneType == sceneRoot.GetType()) ?? _defaultSceneLoader; - yield return StartCoroutine(sceneLoader.Load(sceneRoot, updateDelegate)); - LoadedScenes.Add(sceneRoot); + //If the scene was loaded via the api (it was queued having some name and settings) + if (ScenesQueue.Count > 0) + { + var sceneQueueItem = ScenesQueue.Dequeue(); + sceneRoot.Name = sceneQueueItem.Name; + sceneRoot._SettingsObject = sceneQueueItem.Settings; + } + //Else, means scene was the start scene (loaded before kernel) + else + { + sceneRoot.Name = Application.loadedLevelName; + } - this.Publish(new SceneLoaderEvent() - { - State = SceneState.Loaded, - SceneRoot = sceneRoot - }); + this.Publish(new SceneLoaderEvent() + { + State = SceneState.Instantiated, + SceneRoot = sceneRoot + }); - } + Action updateDelegate = (v, m) => + { + this.Publish(new SceneLoaderEvent() + { + State = SceneState.Update, + Progress = v, + ProgressMessage = m + }); + }; - protected IEnumerator UnloadSceneAsync(string name) - { - var sceneRoot = LoadedScenes.FirstOrDefault(s => s.Name == name); - if (sceneRoot != null) yield return StartCoroutine(this.UnloadSceneAsync(sceneRoot)); - else yield break; - } + var sceneLoader = SceneLoaders.FirstOrDefault(loader => loader.SceneType == sceneRoot.GetType()) ?? + _defaultSceneLoader; - protected IEnumerator UnloadSceneAsync(IScene sceneRoot) - { + yield return StartCoroutine(sceneLoader.Load(sceneRoot, updateDelegate)); - var sceneLoader = SceneLoaders.FirstOrDefault(loader => loader.SceneType == sceneRoot.GetType()) ?? _defaultSceneLoader; + LoadedScenes.Add(sceneRoot); - Action updateDelegate = (v, m) => - { this.Publish(new SceneLoaderEvent() { - State = SceneState.Unloading, - Progress = v, - ProgressMessage = m + State = SceneState.Loaded, + SceneRoot = sceneRoot }); - }; - yield return StartCoroutine(sceneLoader.Unload(sceneRoot, updateDelegate)); - this.Publish(new SceneLoaderEvent() { State = SceneState.Unloaded, SceneRoot = sceneRoot }); + } - LoadedScenes.Remove(sceneRoot); - Destroy((sceneRoot as MonoBehaviour).gameObject); + protected IEnumerator UnloadSceneAsync(string name) + { + var sceneRoot = LoadedScenes.FirstOrDefault(s => s.Name == name); + if (sceneRoot != null) yield return StartCoroutine(this.UnloadSceneAsync(sceneRoot)); + else yield break; + } - this.Publish(new SceneLoaderEvent() { State = SceneState.Destructed, SceneRoot = sceneRoot }); + protected IEnumerator UnloadSceneAsync(IScene sceneRoot) + { + var sceneLoader = SceneLoaders.FirstOrDefault(loader => loader.SceneType == sceneRoot.GetType()) ?? + _defaultSceneLoader; - } + Action updateDelegate = (v, m) => + { + this.Publish(new SceneLoaderEvent() + { + State = SceneState.Unloading, + Progress = v, + ProgressMessage = m + }); + }; - public void UnloadScene(string name) - { - StartCoroutine(UnloadSceneAsync(name)); - } + yield return StartCoroutine(sceneLoader.Unload(sceneRoot, updateDelegate)); - public void UnloadScene(IScene sceneRoot) - { - StartCoroutine(UnloadSceneAsync(sceneRoot)); - } + this.Publish(new SceneLoaderEvent() {State = SceneState.Unloaded, SceneRoot = sceneRoot}); - public void UnloadScenes(string[] names) - { - foreach (var name in names) + LoadedScenes.Remove(sceneRoot); + Destroy((sceneRoot as MonoBehaviour).gameObject); + + this.Publish(new SceneLoaderEvent() {State = SceneState.Destructed, SceneRoot = sceneRoot}); + + + } + + public void UnloadScene(string name) { StartCoroutine(UnloadSceneAsync(name)); } - } - public void UnloadScenes(IScene[] sceneRoots) - { - foreach (var sceneRoot in sceneRoots) + public void UnloadScene(IScene sceneRoot) { StartCoroutine(UnloadSceneAsync(sceneRoot)); } - } - public void LoadScene(string name, ISceneSettings settings) - { - this.QueueSceneLoad(name, settings); - this.ExecuteLoad(); - } - public void LoadSceneIfNotAlready(string name, ISceneSettings settings) - { - if (LoadedScenes.Any(p => p.Name == name) || ScenesQueue.Any(p => p.Name == name) || Application.loadedLevelName == name) + public void UnloadScenes(string[] names) + { + foreach (var name in names) + { + StartCoroutine(UnloadSceneAsync(name)); + } + } + + public void UnloadScenes(IScene[] sceneRoots) { - return; + foreach (var sceneRoot in sceneRoots) + { + StartCoroutine(UnloadSceneAsync(sceneRoot)); + } } - this.QueueSceneLoad(name, settings); - this.ExecuteLoad(); - } - public void LoadScenes(params SceneQueueItem[] items) - { - this.QueueScenesLoad(items); - this.ExecuteLoad(); - } - public void QueueSceneLoadIfNotAlready(string sceneName, ISceneSettings settings) - { - if (LoadedScenes.Any(p => p.Name == sceneName) || ScenesQueue.Any(p => p.Name == sceneName) || Application.loadedLevelName == sceneName) + + public void LoadScene(string name, ISceneSettings settings) { - return; + this.QueueSceneLoad(name, settings); + this.ExecuteLoad(); } - ScenesQueue.Enqueue(new SceneQueueItem() + + public void LoadSceneIfNotAlready(string name, ISceneSettings settings) { - Loader = LoadSceneInternal(sceneName), - Name = sceneName, - Settings = settings - }); - } + if (LoadedScenes.Any(p => p.Name == name) || ScenesQueue.Any(p => p.Name == name) || + Application.loadedLevelName == name) + { + return; + } + this.QueueSceneLoad(name, settings); + this.ExecuteLoad(); + } -} + public void LoadScenes(params SceneQueueItem[] items) + { + this.QueueScenesLoad(items); + this.ExecuteLoad(); + } -public class SceneQueueItem -{ - public string Name { get; set; } - public IEnumerator Loader { get; set; } - public ISceneSettings Settings { get; set; } -} + public void QueueSceneLoadIfNotAlready(string sceneName, ISceneSettings settings) + { + if (LoadedScenes.Any(p => p.Name == sceneName) || ScenesQueue.Any(p => p.Name == sceneName) || + Application.loadedLevelName == sceneName) + { + return; + } + ScenesQueue.Enqueue(new SceneQueueItem() + { + Loader = LoadSceneInternal(sceneName), + Name = sceneName, + Settings = settings + }); + } + + } + + public class SceneQueueItem + { + public string Name { get; set; } + public IEnumerator Loader { get; set; } + public ISceneSettings Settings { get; set; } + } +} \ No newline at end of file diff --git a/Kernel/SceneSettings.cs b/Kernel/SceneSettings.cs index f86e178e..1235fa32 100644 --- a/Kernel/SceneSettings.cs +++ b/Kernel/SceneSettings.cs @@ -1,8 +1,11 @@ -public class SceneSettings : ISceneSettings where T : IScene +namespace uFrame.Kernel { + public class SceneSettings : ISceneSettings where T : IScene + { -} + } -public interface ISceneSettings -{ + public interface ISceneSettings + { + } } \ No newline at end of file diff --git a/Kernel/Serialization/ISerializerStream.cs b/Kernel/Serialization/ISerializerStream.cs index 916d9a4b..3d2f4bf0 100644 --- a/Kernel/Serialization/ISerializerStream.cs +++ b/Kernel/Serialization/ISerializerStream.cs @@ -1,9 +1,10 @@ using System.Collections.Generic; +using uFrame.IOC; using UnityEngine; public interface ISerializerStream { - IGameContainer DependencyContainer { get; set; } + IUFrameContainer DependencyContainer { get; set; } void SerializeArray(string name, IEnumerable items); diff --git a/Kernel/Serialization/JSON.cs b/Kernel/Serialization/JSON.cs index 00470be7..fc058844 100644 --- a/Kernel/Serialization/JSON.cs +++ b/Kernel/Serialization/JSON.cs @@ -50,7 +50,7 @@ #if UNITY_DLL namespace Invert.Json { #else -namespace uFrame { +namespace uFrame.Serialization { #endif public static class JSON { @@ -632,7 +632,7 @@ public virtual JSONClass AsObject return this as JSONClass; } } -#if UNITY_DLL || UNITY_4_0 || UNITY_5_0 || UNITY_3_0 +#if UNITY_DLL || UNITY_4_0 || UNITY_4_1||UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5_0 || UNITY_5_1 || UNITY_3_0 public virtual Quaternion AsQuaternion { get diff --git a/Kernel/Serialization/Json/JsonStream.cs b/Kernel/Serialization/Json/JsonStream.cs index 81307500..51cd8326 100644 --- a/Kernel/Serialization/Json/JsonStream.cs +++ b/Kernel/Serialization/Json/JsonStream.cs @@ -3,416 +3,416 @@ using System.Linq; using System.Text; using uFrame; +using uFrame.IOC; using UnityEngine; -public class JsonStream : ISerializerStream +namespace uFrame.Serialization { - private Stack _nodeStack; - private ITypeResolver _typeResolver; - private Dictionary _referenceObjects = new Dictionary(); - public JSONNode RootNode { get; set; } - - public Dictionary ReferenceObjects - { - get { return _referenceObjects; } - set { _referenceObjects = value; } - } - - public ITypeResolver TypeResolver - { - get { return _typeResolver ?? (_typeResolver = new DefaultTypeResolver()); } - set { _typeResolver = value; } - } - - public bool DeepSerialize { get; set; } - - public JsonStream(JSONNode node) - { - RootNode = node; - } - - public JsonStream() - { - RootNode = new JSONClass(); - } - - public JsonStream(string json) + public class JsonStream : ISerializerStream { - RootNode = JSON.Parse(json); - } + private Stack _nodeStack; + private ITypeResolver _typeResolver; + private Dictionary _referenceObjects = new Dictionary(); + public JSONNode RootNode { get; set; } - public JsonStream(ITypeResolver typeResolver) - { - _typeResolver = typeResolver; - RootNode = new JSONClass(); - } - - public JsonStream(ITypeResolver typeResolver,string json) - { - _typeResolver = typeResolver; - RootNode = JSON.Parse(json); - } - - public Stack NodeStack - { - get { return _nodeStack ?? (_nodeStack = new Stack()); } - set { _nodeStack = value; } - } - - public JSONNode CurrentNode - { - get + public Dictionary ReferenceObjects { - if (NodeStack.Count < 1) - return RootNode; - return NodeStack.Peek(); + get { return _referenceObjects; } + set { _referenceObjects = value; } } - } - public void Push(string name, JSONNode node) - { - NodeStack.Push(node); - } - - public void Pop() - { - NodeStack.Pop(); - } - - public void Serialize(string name, object obj) - { - //if (obj is IUFSerializable) - //{ - - //} - //else if (obj is Vector3) - //{ - // Serialize - //} - //else if (obj is Vector2) - //{ - - //} - //else if (obj is string) - //{ - - //} - //else if (obj is Vector4) - //{ - - //} - //else if (obj is Quaternion) - //{ - - //} - //else if (obj is bool) - //{ - - //} - } - - public IGameContainer DependencyContainer { get; set; } - - public void SerializeArray(string name, IEnumerable items) - { - SerializeObjectArray(name, items.Cast()); - } - - public void SerializeObjectArray(string name, IEnumerable items) - { - - var array = new JSONArray(); - if (name == null) - CurrentNode.Add(array); - else - CurrentNode.Add(name, array); - Push(name,array); - foreach (var item in items) - { - SerializeObject(null, item); - } - Pop(); - } - public bool UseReferences { get; set; } - - public void SerializeObject(string name, object value) - { - if (value is int) + public ITypeResolver TypeResolver { - SerializeInt(name,(int)value); - return; + get { return _typeResolver ?? (_typeResolver = new DefaultTypeResolver()); } + set { _typeResolver = value; } } - if (value is string) + + public bool DeepSerialize { get; set; } + + public JsonStream(JSONNode node) { - SerializeString(name,(string)value); - return; + RootNode = node; } - if (value is bool) + + public JsonStream() { - SerializeBool(name, (bool)value); - return; + RootNode = new JSONClass(); } - if (value is Vector2) + + public JsonStream(string json) { - SerializeVector2(name, (Vector2)value); - return; + RootNode = JSON.Parse(json); } - if (value is Vector3) + + public JsonStream(ITypeResolver typeResolver) { - SerializeVector3(name, (Vector3)value); - return; + _typeResolver = typeResolver; + RootNode = new JSONClass(); } - if (value is Quaternion) + + public JsonStream(ITypeResolver typeResolver, string json) { - SerializeQuaternion(name, (Quaternion)value); - return; + _typeResolver = typeResolver; + RootNode = JSON.Parse(json); } - if (value is double) + + public Stack NodeStack { - SerializeDouble(name, (double)value); - return; + get { return _nodeStack ?? (_nodeStack = new Stack()); } + set { _nodeStack = value; } } - var cls = new JSONClass(); - - if (name == null) - CurrentNode.Add(cls); - else - CurrentNode.Add(name, cls); - Push(name, cls); - var serializable = value as IUFSerializable; - if (serializable != null) + public JSONNode CurrentNode { - - SerializeString("Identifier", serializable.Identifier); - if (!UseReferences || !ReferenceObjects.ContainsKey(serializable.Identifier)) + get { - SerializeString("CLRType", TypeResolver.SetType(value.GetType())); - - if (UseReferences) - ReferenceObjects.Add(serializable.Identifier, serializable); - - serializable.Write(this); + if (NodeStack.Count < 1) + return RootNode; + return NodeStack.Peek(); } - } - Pop(); - } - - public void SerializeInt(string name, int value) - { - CurrentNode.Add(name, new JSONData(value)); - } - - public void SerializeBool(string name, bool value) - { - CurrentNode.Add(name, new JSONData(value)); - } - - public void SerializeString(string name, string value) - { - CurrentNode.Add(name, new JSONData(value)); - } - - public void SerializeVector2(string name, Vector2 value) - { - CurrentNode.Add(name, new JSONClass(){AsVector2 = value}); - } - public void SerializeVector3(string name, Vector3 value) - { - CurrentNode.Add(name, new JSONClass() { AsVector3 = value }); - } - - public void SerializeQuaternion(string name, Quaternion value) - { - CurrentNode.Add(name, new JSONClass(){AsQuaternion = value}); - } + public void Push(string name, JSONNode node) + { + NodeStack.Push(node); + } - public void SerializeDouble(string name, double value) - { - CurrentNode.Add(name, new JSONData(value)); - } + public void Pop() + { + NodeStack.Pop(); + } - public void SerializeFloat(string name, float value) - { - CurrentNode.Add(name, new JSONData(value)); - } + public void Serialize(string name, object obj) + { + //if (obj is IUFSerializable) + //{ + + //} + //else if (obj is Vector3) + //{ + // Serialize + //} + //else if (obj is Vector2) + //{ + + //} + //else if (obj is string) + //{ + + //} + //else if (obj is Vector4) + //{ + + //} + //else if (obj is Quaternion) + //{ + + //} + //else if (obj is bool) + //{ + + //} + } - public void SerializeColor(string name, Color value) - { - var node = new JSONClass(); - node.Add("r",new JSONData(value.r)); - node.Add("g", new JSONData(value.g)); - node.Add("b", new JSONData(value.b)); - node.Add("a", new JSONData(value.a)); - CurrentNode.Add(name, node.AsObject); - } + public IUFrameContainer DependencyContainer { get; set; } - public void SerializeBytes(string name, byte[] bytes) - { -// throw new NotImplementedException(); - } + public void SerializeArray(string name, IEnumerable items) + { + SerializeObjectArray(name, items.Cast()); + } - public IEnumerable DeserializeObjectArray(string name) - { - Push(name,CurrentNode[name]); - foreach (var jsonNode in CurrentNode.Childs) + public void SerializeObjectArray(string name, IEnumerable items) { - if (typeof(T) == typeof(string)) - { - yield return (T)(object)DeserializeString(name); - } + + var array = new JSONArray(); + if (name == null) + CurrentNode.Add(array); else - if (typeof (T) == typeof (int)) + CurrentNode.Add(name, array); + Push(name, array); + foreach (var item in items) { - yield return (T) (object) DeserializeInt(name); + SerializeObject(null, item); } - else - if (typeof(T) == typeof(bool)) + Pop(); + } + public bool UseReferences { get; set; } + + public void SerializeObject(string name, object value) + { + if (value is int) { - yield return (T)(object)DeserializeBool(name); + SerializeInt(name, (int)value); + return; } - else - if (typeof(T) == typeof(byte[])) + if (value is string) { - yield return (T)(object)DeserializeBytes(name); + SerializeString(name, (string)value); + return; } - else - if (typeof(T) == typeof(double)) + if (value is bool) { - yield return (T)(object)DeserializeDouble(name); + SerializeBool(name, (bool)value); + return; } - else - if (typeof(T) == typeof(float)) + if (value is Vector2) { - yield return (T)(object)DeserializeFloat(name); + SerializeVector2(name, (Vector2)value); + return; } - else - if (typeof(T) == typeof(Quaternion)) + if (value is Vector3) { - yield return (T)(object)DeserializeQuaternion(name); - } else - if (typeof(T) == typeof(Vector2)) + SerializeVector3(name, (Vector3)value); + return; + } + if (value is Quaternion) { - yield return (T)(object)DeserializeVector2(name); + SerializeQuaternion(name, (Quaternion)value); + return; } - else if (typeof (T) == typeof (Vector3)) + if (value is double) { - yield return (T) (object) DeserializeInt(name); + SerializeDouble(name, (double)value); + return; } + var cls = new JSONClass(); + + if (name == null) + CurrentNode.Add(cls); else + CurrentNode.Add(name, cls); + Push(name, cls); + + var serializable = value as IUFSerializable; + if (serializable != null) { - Push(null, jsonNode); - yield return (T)DeserializeObjectFromCurrent(); - Pop(); + + SerializeString("Identifier", serializable.Identifier); + if (!UseReferences || !ReferenceObjects.ContainsKey(serializable.Identifier)) + { + SerializeString("CLRType", TypeResolver.SetType(value.GetType())); + + if (UseReferences) + ReferenceObjects.Add(serializable.Identifier, serializable); + + serializable.Write(this); + } + } + Pop(); } - Pop(); - } - public T DeserializeObject(string name) - { - return (T)DeserializeObject(name); - } + public void SerializeInt(string name, int value) + { + CurrentNode.Add(name, new JSONData(value)); + } - public object DeserializeObject(string name) - { - Push(name, CurrentNode[name]); - var result = DeserializeObjectFromCurrent(); - Pop(); - return result; - } + public void SerializeBool(string name, bool value) + { + CurrentNode.Add(name, new JSONData(value)); + } - private object DeserializeObjectFromCurrent() - { - var identifier = CurrentNode["Identifier"].Value; + public void SerializeString(string name, string value) + { + CurrentNode.Add(name, new JSONData(value)); + } - if (UseReferences && ReferenceObjects.ContainsKey(identifier) ) + public void SerializeVector2(string name, Vector2 value) { - return ReferenceObjects[identifier]; + CurrentNode.Add(name, new JSONClass() { AsVector2 = value }); } - if (CurrentNode["CLRType"] == null) return null; - var clrType = CurrentNode["CLRType"].Value; - var instance = TypeResolver.CreateInstance(clrType,identifier); - var ufSerializable = instance as IUFSerializable; - if (ufSerializable != null) + + public void SerializeVector3(string name, Vector3 value) { - if (UseReferences) - ReferenceObjects.Add(identifier, ufSerializable); - ufSerializable.Read(this); + CurrentNode.Add(name, new JSONClass() { AsVector3 = value }); } - return instance; - } - public int DeserializeInt(string name) - { - return CurrentNode[name].AsInt; - } + public void SerializeQuaternion(string name, Quaternion value) + { + CurrentNode.Add(name, new JSONClass() { AsQuaternion = value }); + } - public bool DeserializeBool(string name) - { - return CurrentNode[name].AsBool; - } + public void SerializeDouble(string name, double value) + { + CurrentNode.Add(name, new JSONData(value)); + } - public string DeserializeString(string name) - { - return CurrentNode[name].Value; - } + public void SerializeFloat(string name, float value) + { + CurrentNode.Add(name, new JSONData(value)); + } - public Color DeserializeColor(string name) - { - return new Color( - CurrentNode[name]["r"].AsFloat, - CurrentNode[name]["g"].AsFloat, - CurrentNode[name]["b"].AsFloat, - CurrentNode[name]["a"].AsFloat - ); - } + public void SerializeColor(string name, Color value) + { + var node = new JSONClass(); + node.Add("r", new JSONData(value.r)); + node.Add("g", new JSONData(value.g)); + node.Add("b", new JSONData(value.b)); + node.Add("a", new JSONData(value.a)); + CurrentNode.Add(name, node.AsObject); + } - public Vector2 DeserializeVector2(string name) - { - return CurrentNode[name].AsVector3; - } + public void SerializeBytes(string name, byte[] bytes) + { + // throw new NotImplementedException(); + } - public Vector3 DeserializeVector3(string name) - { - return CurrentNode[name].AsVector3; - } + public IEnumerable DeserializeObjectArray(string name) + { + Push(name, CurrentNode[name]); + foreach (var jsonNode in CurrentNode.Childs) + { + if (typeof(T) == typeof(string)) + { + yield return (T)(object)DeserializeString(name); + } + else + if (typeof(T) == typeof(int)) + { + yield return (T)(object)DeserializeInt(name); + } + else + if (typeof(T) == typeof(bool)) + { + yield return (T)(object)DeserializeBool(name); + } + else + if (typeof(T) == typeof(byte[])) + { + yield return (T)(object)DeserializeBytes(name); + } + else + if (typeof(T) == typeof(double)) + { + yield return (T)(object)DeserializeDouble(name); + } + else + if (typeof(T) == typeof(float)) + { + yield return (T)(object)DeserializeFloat(name); + } + else + if (typeof(T) == typeof(Quaternion)) + { + yield return (T)(object)DeserializeQuaternion(name); + } + else + if (typeof(T) == typeof(Vector2)) + { + yield return (T)(object)DeserializeVector2(name); + } + else if (typeof(T) == typeof(Vector3)) + { + yield return (T)(object)DeserializeInt(name); + } + else + { + Push(null, jsonNode); + yield return (T)DeserializeObjectFromCurrent(); + Pop(); + } + } + Pop(); + } - public Quaternion DeserializeQuaternion(string name) - { - return CurrentNode[name].AsQuaternion; - } + public T DeserializeObject(string name) + { + return (T)DeserializeObject(name); + } - public double DeserializeDouble(string name) - { - return CurrentNode[name].AsDouble; - } + public object DeserializeObject(string name) + { + Push(name, CurrentNode[name]); + var result = DeserializeObjectFromCurrent(); + Pop(); + return result; + } - public float DeserializeFloat(string name) - { - return CurrentNode[name].AsFloat; - } + private object DeserializeObjectFromCurrent() + { + var identifier = CurrentNode["Identifier"].Value; - public byte[] DeserializeBytes(string name) - { - return null; - } + if (UseReferences && ReferenceObjects.ContainsKey(identifier)) + { + return ReferenceObjects[identifier]; + } + if (CurrentNode["CLRType"] == null) return null; + var clrType = CurrentNode["CLRType"].Value; + var instance = TypeResolver.CreateInstance(clrType, identifier); + var ufSerializable = instance as IUFSerializable; + if (ufSerializable != null) + { + if (UseReferences) + ReferenceObjects.Add(identifier, ufSerializable); + ufSerializable.Read(this); + } + return instance; + } - public void Load(byte[] readAllBytes) - { - var json = Encoding.UTF8.GetString(readAllBytes, 0, readAllBytes.Length); - RootNode = JSON.Parse(json); - } + public int DeserializeInt(string name) + { + return CurrentNode[name].AsInt; + } - public byte[] Save() - { - return System.Text.Encoding.UTF8.GetBytes(CurrentNode.ToString()); - } -} + public bool DeserializeBool(string name) + { + return CurrentNode[name].AsBool; + } + + public string DeserializeString(string name) + { + return CurrentNode[name].Value; + } + + public Color DeserializeColor(string name) + { + return new Color( + CurrentNode[name]["r"].AsFloat, + CurrentNode[name]["g"].AsFloat, + CurrentNode[name]["b"].AsFloat, + CurrentNode[name]["a"].AsFloat + ); + } + + public Vector2 DeserializeVector2(string name) + { + return CurrentNode[name].AsVector3; + } + + public Vector3 DeserializeVector3(string name) + { + return CurrentNode[name].AsVector3; + } + + public Quaternion DeserializeQuaternion(string name) + { + return CurrentNode[name].AsQuaternion; + } + + public double DeserializeDouble(string name) + { + return CurrentNode[name].AsDouble; + } -//public interface IReferenceHandler -//{ -// void IsReference() -//} \ No newline at end of file + public float DeserializeFloat(string name) + { + return CurrentNode[name].AsFloat; + } + + public byte[] DeserializeBytes(string name) + { + return null; + } + + public void Load(byte[] readAllBytes) + { + var json = Encoding.UTF8.GetString(readAllBytes, 0, readAllBytes.Length); + RootNode = JSON.Parse(json); + } + + public byte[] Save() + { + return System.Text.Encoding.UTF8.GetBytes(CurrentNode.ToString()); + } + } +} \ No newline at end of file diff --git a/Kernel/SimpleSubject.cs b/Kernel/SimpleSubject.cs index fb648d04..d97b86e6 100644 --- a/Kernel/SimpleSubject.cs +++ b/Kernel/SimpleSubject.cs @@ -2,47 +2,50 @@ using System.Collections.Generic; using UniRx; -public class SimpleSubject : ISubject +namespace uFrame.Kernel { - private List> _observers; - - public List> Observers + public class SimpleSubject : ISubject { - get { return _observers ?? (_observers = new List>()); } - set { _observers = value; } - } + private List> _observers; - public void OnCompleted() - { - foreach (var observer in Observers.ToArray()) + public List> Observers { - if (observer == null) continue; - observer.OnCompleted(); + get { return _observers ?? (_observers = new List>()); } + set { _observers = value; } } - Observers.Clear(); - } - public void OnError(Exception error) - { - foreach (var observer in Observers.ToArray()) + public void OnCompleted() { - if (observer == null) continue; - observer.OnError(error); + foreach (var observer in Observers.ToArray()) + { + if (observer == null) continue; + observer.OnCompleted(); + } + Observers.Clear(); } - } - public void OnNext(T value) - { - foreach (var observer in Observers) + public void OnError(Exception error) { - if (observer == null) continue; - observer.OnNext(value); + foreach (var observer in Observers.ToArray()) + { + if (observer == null) continue; + observer.OnError(error); + } } - } - public IDisposable Subscribe(IObserver observer) - { - Observers.Add(observer); - return Disposable.Create(() => Observers.Remove(observer)); + public void OnNext(T value) + { + foreach (var observer in Observers) + { + if (observer == null) continue; + observer.OnNext(value); + } + } + + public IDisposable Subscribe(IObserver observer) + { + Observers.Add(observer); + return Disposable.Create(() => Observers.Remove(observer)); + } } } \ No newline at end of file diff --git a/Kernel/SystemControllerExtensions.cs b/Kernel/SystemControllerExtensions.cs index 96a055fe..e1b0297c 100644 --- a/Kernel/SystemControllerExtensions.cs +++ b/Kernel/SystemControllerExtensions.cs @@ -1,23 +1,27 @@ using UniRx; -public static class SystemControllerExtensions +namespace uFrame.Kernel { - - /// - /// A wrapper for GetEvent on the EventAggregator GetEvent method. - /// - /// - /// An observable capable of subscriptions and filtering. - public static IObservable OnEvent(this ISystemService systemController) - { - return systemController.EventAggregator.GetEvent(); - } - /// - /// A wrapper for the Event Aggregator.Publish method. - /// - /// - public static void Publish(this ISystemService systemController, object eventMessage) + public static class SystemControllerExtensions { - systemController.EventAggregator.Publish(eventMessage); + + /// + /// A wrapper for GetEvent on the EventAggregator GetEvent method. + /// + /// + /// An observable capable of subscriptions and filtering. + public static IObservable OnEvent(this ISystemService systemController) + { + return systemController.EventAggregator.GetEvent(); + } + + /// + /// A wrapper for the Event Aggregator.Publish method. + /// + /// + public static void Publish(this ISystemService systemController, object eventMessage) + { + systemController.EventAggregator.Publish(eventMessage); + } } } \ No newline at end of file diff --git a/Kernel/SystemService.cs b/Kernel/SystemService.cs index c9bc367b..ace2bc1c 100644 --- a/Kernel/SystemService.cs +++ b/Kernel/SystemService.cs @@ -1,34 +1,40 @@ using System.Collections; +using uFrame.IOC; using UniRx; -/// -/// This class is a generic base class for a systemservice, your probably looking for SystemServiceMonoBehaviour. -/// -public abstract class SystemService : ISystemService -{ - [Inject] - public IEventAggregator EventAggregator { get; set; } - public virtual void Setup() +namespace uFrame.Kernel +{ + /// + /// This class is a generic base class for a systemservice, your probably looking for SystemServiceMonoBehaviour. + /// + public abstract class SystemService : ISystemService { - - } + [Inject] + public IEventAggregator EventAggregator { get; set; } - public virtual IEnumerator SetupAsync() - { - yield break; - } + public virtual void Setup() + { - public virtual void Dispose() - { - - } - public IObservable OnEvent() - { - return EventAggregator.GetEvent(); - } + } - public void Publish(object eventMessage) - { - EventAggregator.Publish(eventMessage); + public virtual IEnumerator SetupAsync() + { + yield break; + } + + public virtual void Dispose() + { + + } + + public IObservable OnEvent() + { + return EventAggregator.GetEvent(); + } + + public void Publish(object eventMessage) + { + EventAggregator.Publish(eventMessage); + } } } \ No newline at end of file diff --git a/Kernel/SystemServiceMonoBehavior.cs b/Kernel/SystemServiceMonoBehavior.cs index f5f84cc1..4942d3f5 100644 --- a/Kernel/SystemServiceMonoBehavior.cs +++ b/Kernel/SystemServiceMonoBehavior.cs @@ -1,57 +1,41 @@ using System.Collections; using UniRx; -/// -/// The base class for all services on the kernel. Services provide an easy communication layer with the use -/// of the EventAggregator. You can use this.Publish(new AnyType()). Or you can use this.OnEvent<AnyType>().Subscribe(anyTypeInstance=>{ }); -/// In services you can also inject any instances that are setup in any of the SystemLoaders. -/// -public abstract class SystemServiceMonoBehavior : UnityEngine.MonoBehaviour, ISystemService +namespace uFrame.Kernel { /// - /// The Event Aggregator used for listening and publishing commands. + /// The base class for all services on the kernel. Services provide an easy communication layer with the use + /// of the EventAggregator. You can use this.Publish(new AnyType()). Or you can use this.OnEvent<AnyType>().Subscribe(anyTypeInstance=>{ }); + /// In services you can also inject any instances that are setup in any of the SystemLoaders. /// - [Inject] - public IEventAggregator EventAggregator { get; set; } - - /// - /// This method is to setup an listeners on the EventAggregator, or other initialization requirements. - /// - public virtual void Setup() + public abstract class SystemServiceMonoBehavior : uFrameComponent, ISystemService { - - } - /// - /// This method is called by the kernel to do any setup the make take some time to complete. It is executed as - /// a co-routine by the kernel. - /// - /// - public virtual IEnumerator SetupAsync() - { - yield break; - } + IEventAggregator ISystemService.EventAggregator + { + get { return EventAggregator; } + set + { + // No need to set + } + } - public virtual void Dispose() - { - - } + /// + /// This method is to setup an listeners on the EventAggregator, or other initialization requirements. + /// + public virtual void Setup() + { - /// - /// A wrapper for GetEvent on the EventAggregator GetEvent method. - /// - /// - /// An observable capable of subscriptions and filtering. - public IObservable OnEvent() - { - return EventAggregator.GetEvent(); - } + } + + /// + /// This method is called by the kernel to do any setup the make take some time to complete. It is executed as + /// a co-routine by the kernel. + /// + /// + public virtual IEnumerator SetupAsync() + { + yield break; + } - /// - /// A wrapper for the Event Aggregator.Publish method. - /// - /// - public void Publish(object eventMessage) - { - EventAggregator.Publish(eventMessage); } } \ No newline at end of file diff --git a/Kernel/uFrameComponent.cs b/Kernel/uFrameComponent.cs index b6791957..0db892db 100644 --- a/Kernel/uFrameComponent.cs +++ b/Kernel/uFrameComponent.cs @@ -4,47 +4,73 @@ using UniRx; using UnityEngine; -/// -/// A base class for all view containers. -/// Simply just utility methods for views and events. -/// -public class uFrameComponent : MonoBehaviour +namespace uFrame.Kernel { + /// + /// The uFrameComponent is a simple class that extends from MonoBehaviour, and is directly plugged into the kernel. + /// Use this component when creating any components manually or if you need to plug existing libraries into the uFrame system. + /// + /// public class MyComponent : uFrameComponent { + /// } + /// + /// + /// public class MyComponent : uFrameComponent { + /// public override void KernelLoaded() { + /// this.Publish(new MyComponentCreatedEvent() { Instance = this }); + /// } + /// } + /// + public class uFrameComponent : MonoBehaviour + { - protected IEventAggregator EventAggregator { get { return uFrameMVVMKernel.EventAggregator; } } + protected IEventAggregator EventAggregator + { + get { return uFrameMVVMKernel.EventAggregator; } + } - public IObservable OnEvent() - { - return EventAggregator.GetEvent(); - } + /// Wait for an Event to occur on the global event aggregator. + /// + /// this.OnEvent<MyEventClass>().Subscribe(myEventClassInstance=>{ DO_SOMETHING_HERE }); + /// + public IObservable OnEvent() + { + return EventAggregator.GetEvent(); + } - public void Publish(object eventMessage) - { - EventAggregator.Publish(eventMessage); - } - protected virtual IEnumerator Start() - { - KernelLoading(); - while (!uFrameMVVMKernel.IsKernelLoaded) yield return null; - KernelLoaded(); - } - /// - /// Before we wait for the kernel to load, even if the kernel is already loaded it will still invoke this before it attempts to wait. - /// - public virtual void KernelLoading() - { - - } + /// Publishes a command to the event aggregator. Publish the class data you want, and let any "OnEvent" subscriptions handle them. + /// + /// this.Publish(new MyEventClass() { Message = "Hello World" }); + /// + public void Publish(object eventMessage) + { + EventAggregator.Publish(eventMessage); + } - /// - /// The first method to execute when we are sure the kernel has completed loading. - /// - public virtual void KernelLoaded() - { - - } - + protected virtual IEnumerator Start() + { + KernelLoading(); + while (!uFrameMVVMKernel.IsKernelLoaded) yield return null; + KernelLoaded(); + } + + /// + /// Before we wait for the kernel to load, even if the kernel is already loaded it will still invoke this before it attempts to wait. + /// + public virtual void KernelLoading() + { + } -} + /// + /// The first method to execute when we are sure the kernel has completed loading. + /// + public virtual void KernelLoaded() + { + + } + + + + } +} \ No newline at end of file diff --git a/Kernel/uFrameMVVMKernel.cs b/Kernel/uFrameMVVMKernel.cs index 30da734d..d6fef90a 100644 --- a/Kernel/uFrameMVVMKernel.cs +++ b/Kernel/uFrameMVVMKernel.cs @@ -4,256 +4,256 @@ using System.Linq; using UnityEngine; using System.Reflection; +using uFrame.IOC; using UniRx; -public class uFrameMVVMKernel : MonoBehaviour { +namespace uFrame.Kernel +{ + public class uFrameMVVMKernel : MonoBehaviour + { - private static GameContainer _container; - private static IEventAggregator _eventAggregator; + private static UFrameContainer _container; + private static IEventAggregator _eventAggregator; - private static bool _isKernelLoaded; - private List _services; - private List _systemLoaders; + private static bool _isKernelLoaded; + private List _services; + private List _systemLoaders; - public static IEnumerator InstantiateSceneAsyncAdditively(string sceneName) - { - var asyncOperation = Application.LoadLevelAdditiveAsync(sceneName); - float lastProgress = -1; - while (!asyncOperation.isDone) + public static IEnumerator InstantiateSceneAsyncAdditively(string sceneName) { - if (lastProgress != asyncOperation.progress) + var asyncOperation = Application.LoadLevelAdditiveAsync(sceneName); + float lastProgress = -1; + while (!asyncOperation.isDone) { - EventAggregator.Publish(new SceneLoaderEvent() + if (lastProgress != asyncOperation.progress) { - State = SceneState.Instantiating, - Name = sceneName, - Progress = asyncOperation.progress - }); - lastProgress = asyncOperation.progress; + EventAggregator.Publish(new SceneLoaderEvent() + { + State = SceneState.Instantiating, + Name = sceneName, + Progress = asyncOperation.progress + }); + lastProgress = asyncOperation.progress; + } + yield return new WaitForSeconds(0.1f); } - yield return new WaitForSeconds(0.1f); } - } - - public static bool IsKernelLoaded - { - get { return _isKernelLoaded; } - set { _isKernelLoaded = value; } - } - public static uFrameMVVMKernel Instance { get; set; } + public static bool IsKernelLoaded + { + get { return _isKernelLoaded; } + set { _isKernelLoaded = value; } + } - public static IGameContainer Container - { - get + public static uFrameMVVMKernel Instance { get; set; } + + public static IUFrameContainer Container { - if (_container == null) + get { - _container = new GameContainer(); - _container.RegisterInstance(_container); - _container.RegisterInstance(EventAggregator); - + if (_container == null) + { + _container = new UFrameContainer(); + _container.RegisterInstance(_container); + _container.RegisterInstance(EventAggregator); + + } + return _container; } - return _container; } - } - - public static IEventAggregator EventAggregator - { - get { return _eventAggregator ?? (_eventAggregator = new EventAggregator()); } - set { _eventAggregator = value; } - } - public List SystemLoaders - { - get + public static IEventAggregator EventAggregator { - return _systemLoaders ?? (_systemLoaders = new List()); + get { return _eventAggregator ?? (_eventAggregator = new EventAggregator()); } + set { _eventAggregator = value; } } - } - public List Services - { - get + public List SystemLoaders { - return _services ?? (_services = new List()); + get { return _systemLoaders ?? (_systemLoaders = new List()); } } - } - void Awake() - { - if (Instance != null) + public List Services { - throw new Exception("Loading Kernel twice is not a good practice!"); + get { return _services ?? (_services = new List()); } } - else + + private void Awake() { - Instance = this; - //if (this.gameObject.GetComponent() == null) - // this.gameObject.AddComponent(); - DontDestroyOnLoad(gameObject); - StartCoroutine(Startup()); + if (Instance != null) + { + throw new Exception("Loading Kernel twice is not a good practice!"); + } + else + { + Instance = this; + //if (this.gameObject.GetComponent() == null) + // this.gameObject.AddComponent(); + DontDestroyOnLoad(gameObject); + StartCoroutine(Startup()); + } } - } - - private IEnumerator Startup() - { - var attachedSystemLoaders = gameObject.GetComponentsInChildren(typeof(ISystemLoader)).OfType(); - foreach (var systemLoader in attachedSystemLoaders) + private IEnumerator Startup() { - this.Publish(new SystemLoaderEvent() { State = SystemState.Loading, Loader = systemLoader }); - systemLoader.Container = Container; - systemLoader.EventAggregator = EventAggregator; - systemLoader.Load(); - SystemLoaders.Add(systemLoader); - this.Publish(new SystemLoaderEvent() { State = SystemState.Loaded, Loader = systemLoader }); - } + var attachedSystemLoaders = + gameObject.GetComponentsInChildren(typeof (ISystemLoader)).OfType(); - var attachedServices = gameObject.GetComponentsInChildren(typeof(SystemServiceMonoBehavior)) - .OfType() - .Where(_=>_.isActiveAndEnabled) - .ToArray(); + foreach (var systemLoader in attachedSystemLoaders) + { + this.Publish(new SystemLoaderEvent() {State = SystemState.Loading, Loader = systemLoader}); + systemLoader.Container = Container; + systemLoader.EventAggregator = EventAggregator; + systemLoader.Load(); + SystemLoaders.Add(systemLoader); + this.Publish(new SystemLoaderEvent() {State = SystemState.Loaded, Loader = systemLoader}); + } - foreach (var service in attachedServices) - { - Container.RegisterService(service); - service.EventAggregator = EventAggregator; // JUST IN CASE, MAN - Services.Add(service); - } + var attachedServices = gameObject.GetComponentsInChildren(typeof (SystemServiceMonoBehavior)) + .OfType() + .Where(_ => _.isActiveAndEnabled) + .ToArray(); - Container.InjectAll(); + foreach (var service in attachedServices) + { + Container.RegisterService(service); + Services.Add(service); + } - foreach (var service in Container.ResolveAll()) - { - this.Publish(new ServiceLoaderEvent() { State = ServiceState.Loading, Service = service }); - service.Setup(); - yield return StartCoroutine(service.SetupAsync()); - this.Publish(new ServiceLoaderEvent() { State = ServiceState.Loaded, Service = service }); - } + Container.InjectAll(); + var allServices = Container.ResolveAll().ToArray(); + foreach (var service in allServices) + { + this.Publish(new ServiceLoaderEvent() {State = ServiceState.Loading, Service = service}); + service.Setup(); + yield return StartCoroutine(service.SetupAsync()); + this.Publish(new ServiceLoaderEvent() {State = ServiceState.Loaded, Service = service}); + } - this.Publish(new SystemsLoadedEvent() - { - Kernel = this - }); + this.Publish(new SystemsLoadedEvent() + { + Kernel = this + }); - _isKernelLoaded = true; - - this.Publish(new KernalLoadedEvent() - { - Kernel = this - }); - yield return new WaitForEndOfFrame(); //Ensure that everything is bound - yield return new WaitForEndOfFrame(); - this.Publish(new GameReadyEvent()); - } + _isKernelLoaded = true; -} + this.Publish(new KernalLoadedEvent() + { + Kernel = this + }); + yield return new WaitForEndOfFrame(); //Ensure that everything is bound + yield return new WaitForEndOfFrame(); + this.Publish(new GameReadyEvent()); + } -public class SystemsLoadedEvent -{ - public uFrameMVVMKernel Kernel; -} + } -public class KernalLoadedEvent -{ - public uFrameMVVMKernel Kernel; -} + public class SystemsLoadedEvent + { + public uFrameMVVMKernel Kernel; + } -public class GameReadyEvent -{ - -} + public class KernalLoadedEvent + { + public uFrameMVVMKernel Kernel; + } -public class LoadSceneCommand -{ + public class GameReadyEvent + { - public string SceneName { get; set; } - public ISceneSettings Settings { get; set; } + } -} + public class LoadSceneCommand + { -public class UnloadSceneCommand -{ - public string SceneName { get; set; } -} + public string SceneName { get; set; } + public ISceneSettings Settings { get; set; } -public class SystemLoaderEvent -{ - public SystemState State { get; set; } - public ISystemLoader Loader { get; set; } -} + } -public class ServiceLoaderEvent -{ - public ServiceState State { get; set; } - public ISystemService Service { get; set; } -} + public class UnloadSceneCommand + { + public string SceneName { get; set; } + } -public class SceneLoaderEvent -{ - public SceneState State { get; set; } - public IScene SceneRoot { get; set; } - public float Progress { get; set; } - public string ProgressMessage { get; set; } - public string Name { get; set; } -} - -public enum SceneState -{ - Loading, - Update, - Loaded, - Unloading, - Unloaded, - Instantiating, - Instantiated, - Destructed -} - -public enum ServiceState -{ - Loading, - Loaded, - Unloaded, -} -public enum SystemState -{ - Loading, - Loaded, - Unloaded, -} + public class SystemLoaderEvent + { + public SystemState State { get; set; } + public ISystemLoader Loader { get; set; } + } -public static class uFrameKernelExtensions -{ - public static void RegisterService(this IGameContainer container, ISystemService service) + public class ServiceLoaderEvent { - container.RegisterInstance(service, service.GetType().Name); - //container.RegisterInstance(typeof(TService), service, false); - container.RegisterInstance(service.GetType(), service); + public ServiceState State { get; set; } + public ISystemService Service { get; set; } } - public static void RegisterService(this IGameContainer container, ISystemService service) + public class SceneLoaderEvent { - container.RegisterInstance(service, service.GetType().Name); - container.RegisterInstance(typeof(TService), service); + public SceneState State { get; set; } + public IScene SceneRoot { get; set; } + public float Progress { get; set; } + public string ProgressMessage { get; set; } + public string Name { get; set; } } - public static void RegisterSceneLoader(this IGameContainer container, ISceneLoader sceneLoader) + public enum SceneState { - container.RegisterInstance(sceneLoader, sceneLoader.GetType().Name, false); - //container.RegisterInstance(typeof(TService), service, false); - container.RegisterInstance(sceneLoader.GetType(), sceneLoader, false); + Loading, + Update, + Loaded, + Unloading, + Unloaded, + Instantiating, + Instantiated, + Destructed } + public enum ServiceState + { + Loading, + Loaded, + Unloaded, + } - public static void Publish(this uFrameMVVMKernel mvvmKernel, object evt) + public enum SystemState { - uFrameMVVMKernel.EventAggregator.Publish(evt); + Loading, + Loaded, + Unloaded, } - - public static IObservable OnEvent(this uFrameMVVMKernel mvvmKernel) + + public static class uFrameKernelExtensions { - return uFrameMVVMKernel.EventAggregator.GetEvent(); + public static void RegisterService(this IUFrameContainer container, ISystemService service) + { + container.RegisterInstance(service, service.GetType().Name); + //container.RegisterInstance(typeof(TService), service, false); + container.RegisterInstance(service.GetType(), service); + } + + public static void RegisterService(this IUFrameContainer container, ISystemService service) + { + container.RegisterInstance(service, service.GetType().Name); + container.RegisterInstance(typeof (TService), service); + } + + public static void RegisterSceneLoader(this IUFrameContainer container, ISceneLoader sceneLoader) + { + container.RegisterInstance(sceneLoader, sceneLoader.GetType().Name, false); + //container.RegisterInstance(typeof(TService), service, false); + container.RegisterInstance(sceneLoader.GetType(), sceneLoader, false); + } + + + public static void Publish(this uFrameMVVMKernel mvvmKernel, object evt) + { + uFrameMVVMKernel.EventAggregator.Publish(evt); + } + + public static IObservable OnEvent(this uFrameMVVMKernel mvvmKernel) + { + return uFrameMVVMKernel.EventAggregator.GetEvent(); + } } } \ No newline at end of file diff --git a/MVVM/AggregatorExtensions.cs b/MVVM/AggregatorExtensions.cs index d3aa2996..48a4f7bc 100644 --- a/MVVM/AggregatorExtensions.cs +++ b/MVVM/AggregatorExtensions.cs @@ -1,13 +1,29 @@ using UniRx; -using System; // Required for WP8 and Store APPS -public static class AggregatorExtensions +using System; +using uFrame.Kernel; + +// Required for WP8 and Store APPS + +namespace uFrame.MVVM { - public static IObservable OnViewModelCreated(this IEventAggregator ea) where TViewModel : ViewModel + public static class AggregatorExtensions { - return ea.GetEvent().Where(p => p.ViewModel is TViewModel).Select(p=>(TViewModel)p.ViewModel); - } - public static IObservable OnViewModelDestroyed(this IEventAggregator ea) where TViewModel : ViewModel - { - return ea.GetEvent().Where(p => p.ViewModel is TViewModel).Select(p => (TViewModel)p.ViewModel); + public static IObservable OnViewModelCreated(this IEventAggregator ea) + where TViewModel : ViewModel + { + return + ea.GetEvent() + .Where(p => p.ViewModel is TViewModel) + .Select(p => (TViewModel) p.ViewModel); + } + + public static IObservable OnViewModelDestroyed(this IEventAggregator ea) + where TViewModel : ViewModel + { + return + ea.GetEvent() + .Where(p => p.ViewModel is TViewModel) + .Select(p => (TViewModel) p.ViewModel); + } } } \ No newline at end of file diff --git a/MVVM/Controllers/Controller.cs b/MVVM/Controllers/Controller.cs index 1618f360..e21c34bc 100644 --- a/MVVM/Controllers/Controller.cs +++ b/MVVM/Controllers/Controller.cs @@ -1,134 +1,120 @@ using System; using System.Collections.Generic; +using uFrame.IOC; +using uFrame.Kernel; -#if DLL -namespace Invert.Common.MVVM +namespace uFrame.MVVM { -#endif - - -/// -/// A controller is a group of commands usually to provide an abstract level -/// -public abstract partial class Controller : SystemService -{ - /// - /// The dependency container that this controller will use + /// A controller is ultimately a special service that acts as a factory for a view-model. It will properly initialize a view-model + /// by setting up any command signals and additionally will invoke any initial setup required (e.g. Loading Data, Additional subscriptions.. etc) /// - public IGameContainer Container { get; set; } - - protected Controller() + public abstract partial class Controller : SystemService { - //throw new Exception("Default constructor is not allowed. Please regenerate your diagram or create the controller with a SceneContext."); - } + private bool _setupInvoked = false; + private List _instanceVMs = new List(); + + /// + /// The dependency container that this controller will use + /// + public IUFrameContainer Container { get; set; } + + /// + /// Create a new ViewModel. This will generate a Unique Identifier for the VM. If this is a specific instance use the overload and pass + /// an identifier. + /// + /// + public virtual ViewModel Create() + { + return Create(Guid.NewGuid().ToString()); + ; + } - /// - /// Create a new ViewModel. This will generate a Unique Identifier for the VM. If this is a specific instance use the overload and pass - /// an identifier. - /// - /// - public virtual ViewModel Create() - { - return Create(Guid.NewGuid().ToString());; - } + /// + /// Creates a new ViewModel with a specific identifier. If it already exists in the SceneContext it will return that instead + /// + /// The identifier that will be used to check the context to see if it already exists. + /// + public virtual ViewModel Create(string identifier) + { - /// - /// Creates a new ViewModel with a specific identifier. If it already exists in the SceneContext it will return that instead - /// - /// The identifier that will be used to check the context to see if it already exists. - /// - public virtual ViewModel Create(string identifier) - { + var vm = CreateEmpty(identifier); + vm.Identifier = identifier; + if (_setupInvoked) + { + Initialize(vm); + EventAggregator.Publish(new ViewModelCreatedEvent() {ViewModel = vm}); + } + else + { + _instanceVMs.Add(vm); + } - var vm = CreateEmpty(identifier); - vm.Identifier = identifier; - if (_setupInvoked) - { - Initialize(vm); - EventAggregator.Publish(new ViewModelCreatedEvent() { ViewModel = vm }); + + return vm; } - else + + /// + /// Create an empty view-model with the specified identifer. Note: This method does not wire up the view-model to this controller. + /// + /// + /// A new View-Model or the view-model found in the context with the same identifier. + public virtual ViewModel CreateEmpty(string identifier) { - _instanceVMs.Add(vm); + var vm = CreateEmpty(); + vm.Disposer = this.DisposingViewModel; + vm.Identifier = identifier; + uFrameMVVMKernel.Container.RegisterViewModel(vm, identifier); + return vm; } - - - return vm; - } - - /// - /// Create an empty view-model with the specified identifer. Note: This method does not wire up the view-model to this controller. - /// - /// - /// A new View-Model or the view-model found in the context with the same identifier. - public virtual ViewModel CreateEmpty(string identifier) - { - var vm = CreateEmpty(); - vm.Disposer = this.DisposingViewModel; - vm.Identifier = identifier; - uFrameMVVMKernel.Container.RegisterViewModel(vm,identifier); - return vm; - } - /// - /// Create an empty view-model . Note: This method does not wire up the view-model to this controller and only instantiates an associated view-model. - /// - /// A new View-Model or the view-model found in the context with the same identifier. - public virtual ViewModel CreateEmpty() - { - throw new NotImplementedException("You propably need to resave you're diagram. Or you need to not call create on an abstract controller."); - } + /// + /// Create an empty view-model . Note: This method does not wire up the view-model to this controller and only instantiates an associated view-model. + /// + /// A new View-Model or the view-model found in the context with the same identifier. + public virtual ViewModel CreateEmpty() + { + throw new NotImplementedException( + "You propably need to resave you're diagram. Or you need to not call create on an abstract controller."); + } - [Obsolete("Game event is not longer used for transitions. Regenerate your diagram.")] - public void GameEvent(string name) { } + /// + /// The setup method is called when the controller is first created and has been injected. Use this + /// to subscribe to any events on the EventAggregator + /// + public override void Setup() + { + foreach (var item in _instanceVMs) + { + Initialize(item); + EventAggregator.Publish(new ViewModelCreatedEvent() {ViewModel = item}); + } + _instanceVMs.Clear(); + _instanceVMs = null; + _setupInvoked = true; + } - private bool _setupInvoked = false; - private List _instanceVMs = new List(); - /// - /// The setup method is called when the controller is first created and has been injected. Use this - /// to subscribe to any events on the EventAggregator - /// - public override void Setup() - { - foreach (var item in _instanceVMs) + /// + /// Override this method to initialize the view-model this controller is made for. + /// + /// When you invoke thisController.Create() it will invoke this method allowing you to give some + /// additional options. + /// + /// + public virtual void Initialize(ViewModel viewModel) { - Initialize(item); - EventAggregator.Publish(new ViewModelCreatedEvent() { ViewModel = item }); - } - _instanceVMs.Clear(); - _instanceVMs = null; - _setupInvoked = true; - } - public virtual void Initialize(ViewModel viewModel) - { - - } + } - [Obsolete("Use Publish")] - public void ExecuteCommand(ICommand command, object argument) - { - //CommandDispatcher.ExecuteCommand(command, argument); - } - [Obsolete("Use Publish")] - public virtual void ExecuteCommand(ICommand command) - { - //CommandDispatcher.ExecuteCommand(command, null); - } - [Obsolete("Use Publish")] - public void ExecuteCommand(ICommandWith command, TArgument argument) - { - //CommandDispatcher.ExecuteCommand(command, argument); - } + /// + /// This method is invoked when a view-model is disposing. + /// + /// + public virtual void DisposingViewModel(ViewModel viewModel) + { - public virtual void DisposingViewModel(ViewModel viewModel) - { - - } -}; + } + }; -#if DLL -} -#endif \ No newline at end of file +} \ No newline at end of file diff --git a/MVVM/Events/InstantiateViewCommand.cs b/MVVM/Events/InstantiateViewCommand.cs index 649ae583..28695e01 100644 --- a/MVVM/Events/InstantiateViewCommand.cs +++ b/MVVM/Events/InstantiateViewCommand.cs @@ -1,10 +1,14 @@ +using uFrame.Kernel; using UnityEngine; -public class InstantiateViewCommand +namespace uFrame.MVVM { - public string Identifier { get; set; } - public IScene Scene { get; set; } - public ViewModel ViewModelObject { get; set; } - public ViewBase Result { get; set; } - public GameObject Prefab { get; set; } + public class InstantiateViewCommand + { + public string Identifier { get; set; } + public IScene Scene { get; set; } + public ViewModel ViewModelObject { get; set; } + public ViewBase Result { get; set; } + public GameObject Prefab { get; set; } + } } \ No newline at end of file diff --git a/MVVM/Events/ViewCreatedEvent.cs b/MVVM/Events/ViewCreatedEvent.cs index 450e48ba..c3d3146c 100644 --- a/MVVM/Events/ViewCreatedEvent.cs +++ b/MVVM/Events/ViewCreatedEvent.cs @@ -1,4 +1,7 @@ -public class ViewCreatedEvent :ViewEvent +namespace uFrame.MVVM { - -} \ No newline at end of file + public class ViewCreatedEvent : ViewEvent + { + + } +} diff --git a/MVVM/Events/ViewDestroyedEvent.cs b/MVVM/Events/ViewDestroyedEvent.cs index e02fcd65..4ddfdf74 100644 --- a/MVVM/Events/ViewDestroyedEvent.cs +++ b/MVVM/Events/ViewDestroyedEvent.cs @@ -1,4 +1,7 @@ -public class ViewDestroyedEvent : ViewEvent +namespace uFrame.MVVM { - + public class ViewDestroyedEvent : ViewEvent + { + + } } \ No newline at end of file diff --git a/MVVM/Events/ViewEvent.cs b/MVVM/Events/ViewEvent.cs index 9ba49037..6300c3f4 100644 --- a/MVVM/Events/ViewEvent.cs +++ b/MVVM/Events/ViewEvent.cs @@ -1,6 +1,11 @@ -public class ViewEvent +using uFrame.Kernel; + +namespace uFrame.MVVM { - public bool IsInstantiated { get; set; } - public IScene Scene { get; set; } - public ViewBase View { get; set; } + public class ViewEvent + { + public bool IsInstantiated { get; set; } + public IScene Scene { get; set; } + public ViewBase View { get; set; } + } } \ No newline at end of file diff --git a/MVVM/MVVMKernelExtensions.cs b/MVVM/MVVMKernelExtensions.cs index 433e790b..4218c9d4 100644 --- a/MVVM/MVVMKernelExtensions.cs +++ b/MVVM/MVVMKernelExtensions.cs @@ -1,71 +1,85 @@ using System; +using uFrame.IOC; +using uFrame.Kernel; +using uFrame.MVVM; -public static class MVVMKernelExtensions +namespace uFrame.MVVM { - public static void RegisterViewModel(this IGameContainer container, TViewModel viewModel, string identifier) where TViewModel : ViewModel + public static class MVVMKernelExtensions { - container.Register(); - container.RegisterInstance(viewModel, identifier); - container.RegisterInstance(typeof(TViewModel), viewModel, identifier); - } + public static void RegisterViewModel(this IUFrameContainer container, TViewModel viewModel, + string identifier) where TViewModel : ViewModel + { + container.Register(); + container.RegisterInstance(viewModel, identifier); + container.RegisterInstance(typeof (TViewModel), viewModel, identifier); + } - public static void RegisterController(this IGameContainer container, TController controller) where TController : Controller - { - container.RegisterInstance(controller, controller.GetType().Name, false); - container.RegisterInstance(controller, controller.GetType().Name, false); - container.RegisterInstance(controller, false); - // Todo Convention hack make it prettier :) - container.RegisterInstance(controller, typeof(TController).Name.Replace("Controller", "ViewModel")); - } + public static void RegisterController(this IUFrameContainer container, TController controller) + where TController : Controller + { + container.RegisterInstance(controller, controller.GetType().Name, false); + container.RegisterInstance(controller, controller.GetType().Name, false); + container.RegisterInstance(controller, false); + // Todo Convention hack make it prettier :) + container.RegisterInstance(controller, + typeof (TController).Name.Replace("Controller", "ViewModel")); + } - public static void RegisterViewModelManager(this IGameContainer container, - IViewModelManager manager) - { - container.RegisterInstance(manager, typeof(TViewModel).Name.Replace("ViewModel", "")); - container.RegisterInstance(manager, typeof(TViewModel).Name); - container.RegisterInstance>(manager, typeof(TViewModel).Name.Replace("ViewModel", "")); - container.RegisterInstance>(manager); - } + public static void RegisterViewModelManager(this IUFrameContainer container, + IViewModelManager manager) + { + container.RegisterInstance(manager, typeof (TViewModel).Name.Replace("ViewModel", "")); + container.RegisterInstance(manager, typeof (TViewModel).Name); + container.RegisterInstance>(manager, + typeof (TViewModel).Name.Replace("ViewModel", "")); + container.RegisterInstance>(manager); + } - public static void RegisterViewModelController(this IGameContainer container, TController controller) where TController : Controller - { + public static void RegisterViewModelController(this IUFrameContainer container, + TController controller) where TController : Controller + { - } + } - public static T CreateViewModel(this ISystemService s, string identifier = null) where T : ViewModel - { - return (T)s.CreateViewModel(typeof(T), identifier); - } + public static T CreateViewModel(this ISystemService s, string identifier = null) where T : ViewModel + { + return (T) s.CreateViewModel(typeof (T), identifier); + } - public static ViewModel CreateViewModel(this ISystemService s, Type type, string identifier = null) - { - var controller = uFrameMVVMKernel.Container.Resolve(type.Name); - if (controller == null) + public static ViewModel CreateViewModel(this ISystemService s, Type type, string identifier = null) { - throw new Exception("Controller could not be found. Make sure your subsystem loader has been attached to the kernel."); + var controller = uFrameMVVMKernel.Container.Resolve(type.Name); + if (controller == null) + { + throw new Exception( + "Controller could not be found. Make sure your subsystem loader has been attached to the kernel."); + } + return controller.Create(identifier ?? Guid.NewGuid().ToString()); } - return controller.Create(identifier ?? Guid.NewGuid().ToString()); - } - public static T CreateViewModel() where T : ViewModel - { - return (T)CreateViewModel(typeof(T)); - } + public static T CreateViewModel() where T : ViewModel + { + return (T) CreateViewModel(typeof (T)); + } - public static ViewModel CreateViewModel( Type type, string identifier = null) - { - var controller = uFrameMVVMKernel.Container.Resolve(type.Name); - if (controller == null) + public static ViewModel CreateViewModel(Type type, string identifier = null) { - throw new Exception("Controller could not be found. Make sure your subsystem loader has been attached to the kernel."); + var controller = uFrameMVVMKernel.Container.Resolve(type.Name); + if (controller == null) + { + throw new Exception( + "Controller could not be found. Make sure your subsystem loader has been attached to the kernel."); + } + return controller.Create(identifier ?? Guid.NewGuid().ToString()); } - return controller.Create(identifier ?? Guid.NewGuid().ToString()); - } - public static TViewModel CreateInstanceViewModel(this ISystemLoader loader, string identifier) where TViewModel : ViewModel - { - var controller = uFrameMVVMKernel.Container.Resolve(typeof(TViewModel).Name); - return (TViewModel)controller.Create(identifier); + public static TViewModel CreateViewModel(this ISystemLoader loader, string identifier = null) + where TViewModel : ViewModel + { + var controller = uFrameMVVMKernel.Container.Resolve(typeof (TViewModel).Name); + return (TViewModel) controller.Create(identifier ?? Guid.NewGuid().ToString()); + } } } \ No newline at end of file diff --git a/MVVM/Services/ViewService.cs b/MVVM/Services/ViewService.cs index 747ff153..1df72e13 100644 --- a/MVVM/Services/ViewService.cs +++ b/MVVM/Services/ViewService.cs @@ -1,166 +1,172 @@ using System; using System.Collections.Generic; using System.Linq; +using uFrame.IOC; +using uFrame.Kernel; using UniRx; using UnityEngine; -public class ViewService : SystemServiceMonoBehavior +namespace uFrame.MVVM.Services { - private List _views; - private static IViewResolver _viewResolver; - - [Inject] - public static IViewResolver ViewResolver + public class ViewService : SystemServiceMonoBehavior { - get { return _viewResolver; } - set { _viewResolver = value; } - } + private List _views; + private static IViewResolver _viewResolver; - public override void Setup() - { - if (ViewResolver == null) + [Inject] + public static IViewResolver ViewResolver { - ViewResolver = new ViewResolver(); + get { return _viewResolver; } + set { _viewResolver = value; } } - this.OnEvent() - .Subscribe(InstantiateView); + public override void Setup() + { + if (ViewResolver == null) + { + ViewResolver = new ViewResolver(); + } - this.OnEvent() - .Subscribe(ViewCreated); + this.OnEvent() + .Subscribe(InstantiateView); - this.OnEvent() - .Subscribe(ViewDestroyed); - } + this.OnEvent() + .Subscribe(ViewCreated); - public List Views - { - get { return _views ?? (_views = new List()); } - set { _views = value; } - } - - protected virtual void InstantiateView(InstantiateViewCommand data) - { - var scene = data.Scene as Scene; - - GameObject viewPrefab = null; - - if (data.Prefab != null) - { - viewPrefab = data.Prefab; + this.OnEvent() + .Subscribe(ViewDestroyed); } - else if (data.ViewModelObject != null) + + public List Views { - viewPrefab = ViewResolver.FindView(data.ViewModelObject); + get { return _views ?? (_views = new List()); } + set { _views = value; } } - else + + protected virtual void InstantiateView(InstantiateViewCommand data) { - throw new Exception("No Prefab or Viewmodel were passed in."); - //viewPrefab = uFrameMVVMKernel.ViewResolver.FindView(data.Identifier); - } + var scene = data.Scene as Scene; - var result = Instantiate(viewPrefab) as GameObject; - var resultView = result.GetComponent(); + GameObject viewPrefab = null; - if (data.ViewModelObject != null) - { - resultView.Identifier = data.ViewModelObject.Identifier; - resultView.ViewModelObject = data.ViewModelObject; - } - else if (!string.IsNullOrEmpty(data.Identifier)) - { - resultView.Identifier = data.Identifier; - } + if (data.Prefab != null) + { + viewPrefab = data.Prefab; + } + else if (data.ViewModelObject != null) + { + viewPrefab = ViewResolver.FindView(data.ViewModelObject); + } + else + { + throw new Exception("No Prefab or Viewmodel were passed in."); + //viewPrefab = uFrameMVVMKernel.ViewResolver.FindView(data.Identifier); + } - resultView.CreateEventData = new ViewCreatedEvent() - { - IsInstantiated = true, - View = resultView, - Scene = data.Scene, - }; + var result = Instantiate(viewPrefab) as GameObject; + var resultView = result.GetComponent(); - if (scene != null) - resultView.transform.parent = scene.transform; + if (data.ViewModelObject != null) + { + resultView.Identifier = data.ViewModelObject.Identifier; + resultView.ViewModelObject = data.ViewModelObject; + } + else if (!string.IsNullOrEmpty(data.Identifier)) + { + resultView.Identifier = data.Identifier; + } - data.Result = resultView; - } + resultView.CreateEventData = new ViewCreatedEvent() + { + IsInstantiated = true, + View = resultView, + Scene = data.Scene, + }; - protected virtual void ViewCreated(ViewCreatedEvent viewCreatedEvent) - { + if (scene != null) + resultView.transform.parent = scene.transform; - var view = viewCreatedEvent.View; - if (view.ViewModelObject == null && view.BindOnStart) - { - var viewModel = FetchViewModel(viewCreatedEvent.View); - view.ViewModelObject = viewModel; + data.Result = resultView; } - Views.Add(view); - } - protected virtual void ViewDestroyed(ViewDestroyedEvent data) - { - if (data.View.DisposeOnDestroy) + protected virtual void ViewCreated(ViewCreatedEvent viewCreatedEvent) { - var vm = data.View.ViewModelObject; - vm.Dispose(); - Publish(new ViewModelDestroyedEvent() + + var view = viewCreatedEvent.View; + if (view.ViewModelObject == null && view.BindOnStart) { - ViewModel = vm, - }); + var viewModel = FetchViewModel(viewCreatedEvent.View); + view.ViewModelObject = viewModel; + } + Views.Add(view); } - } - /// - /// This is method is called by each view in order to get it's view-model as well as place it in - /// the SceneContext if the "Save & Load" option is checked in it's inspector - /// - /// The view that is requesting it's view-model. - /// A new view model or the view-model with the identifier specified found in the scene context. - public static ViewModel FetchViewModel(ViewBase viewBase) - { - if (viewBase.ViewModelObject != null) + protected virtual void ViewDestroyed(ViewDestroyedEvent data) { - return viewBase.ViewModelObject; - } - if (viewBase.InjectView) - { - uFrameMVVMKernel.Container.Inject(viewBase); + if (data.View.DisposeOnDestroy) + { + var vm = data.View.ViewModelObject; + vm.Dispose(); + Publish(new ViewModelDestroyedEvent() + { + ViewModel = vm, + }); + } } - // Attempt to resolve it by the identifier - //var contextViewModel = uFrameMVVMKernel.Container.Resolve(viewBase.Identifier); - // It now only registers under the viewmodeltype to allow multip different view-models with the same identifier - var contextViewModel = uFrameMVVMKernel.Container.Resolve(viewBase.ViewModelType, viewBase.Identifier) as ViewModel; - // If it doesn't resolve by the identifier we need to create it - if (contextViewModel == null) + /// + /// This is method is called by each view in order to get it's view-model as well as place it in + /// the SceneContext if the "Save & Load" option is checked in it's inspector + /// + /// The view that is requesting it's view-model. + /// A new view model or the view-model with the identifier specified found in the scene context. + public static ViewModel FetchViewModel(ViewBase viewBase) { - // Either use the controller to create it or create it ourselves - contextViewModel = MVVMKernelExtensions.CreateViewModel(viewBase.ViewModelType); - contextViewModel.Identifier = viewBase.Identifier; - - // Register it, this is usually when a non registered element is treated like a single-instance anways - uFrameMVVMKernel.Container.RegisterInstance(viewBase.ViewModelType, contextViewModel, + if (viewBase.ViewModelObject != null) + { + return viewBase.ViewModelObject; + } + if (viewBase.InjectView) + { + uFrameMVVMKernel.Container.Inject(viewBase); + } + // Attempt to resolve it by the identifier + //var contextViewModel = uFrameMVVMKernel.Container.Resolve(viewBase.Identifier); + // It now only registers under the viewmodeltype to allow multip different view-models with the same identifier + var contextViewModel = + uFrameMVVMKernel.Container.Resolve(viewBase.ViewModelType, viewBase.Identifier) as ViewModel; + + // If it doesn't resolve by the identifier we need to create it + if (contextViewModel == null) + { + // Either use the controller to create it or create it ourselves + contextViewModel = MVVMKernelExtensions.CreateViewModel(viewBase.ViewModelType); + contextViewModel.Identifier = viewBase.Identifier; + + // Register it, this is usually when a non registered element is treated like a single-instance anways + uFrameMVVMKernel.Container.RegisterInstance(viewBase.ViewModelType, contextViewModel, string.IsNullOrEmpty(viewBase.Identifier) ? null : viewBase.Identifier); - // Register it under the generic view-model type - //uFrameMVVMKernel.Container.RegisterInstance(contextViewModel, viewBase.Identifier); - - uFrameMVVMKernel.EventAggregator.Publish(new ViewModelCreatedEvent() - { - ViewModel = contextViewModel - }); - } - // If we found a view-model - if (contextViewModel != null) - { - // If the view needs to be overriden it will initialize with the inspector values - if (viewBase.OverrideViewModel) + // Register it under the generic view-model type + //uFrameMVVMKernel.Container.RegisterInstance(contextViewModel, viewBase.Identifier); + + uFrameMVVMKernel.EventAggregator.Publish(new ViewModelCreatedEvent() + { + ViewModel = contextViewModel + }); + } + // If we found a view-model + if (contextViewModel != null) { - viewBase.InitializeData(contextViewModel); + // If the view needs to be overriden it will initialize with the inspector values + if (viewBase.OverrideViewModel) + { + viewBase.InitializeData(contextViewModel); + } } + return contextViewModel; } - return contextViewModel; - } - + + } } \ No newline at end of file diff --git a/MVVM/StateMachines/StateMachine.cs b/MVVM/StateMachines/StateMachine.cs index 4f8431ab..4ea5fe4d 100644 --- a/MVVM/StateMachines/StateMachine.cs +++ b/MVVM/StateMachines/StateMachine.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using uFrame.MVVM; using UniRx; using UnityEngine; diff --git a/MVVM/ViewModels/IObservableProperty.cs b/MVVM/ViewModels/IObservableProperty.cs index 8ef3935b..41a7da87 100644 --- a/MVVM/ViewModels/IObservableProperty.cs +++ b/MVVM/ViewModels/IObservableProperty.cs @@ -1,22 +1,25 @@ using System; using UniRx; -public interface IObservableProperty +namespace uFrame.MVVM { - object ObjectValue { get; set; } - string PropertyName { get; } + public interface IObservableProperty + { + object ObjectValue { get; set; } + string PropertyName { get; } #if !DLL - ViewModel Owner { get; set; } + ViewModel Owner { get; set; } #endif - Type ValueType { get; } - IObservable AsUnit { get; } - IDisposable SubscribeInternal(Action propertyChanged); -} + Type ValueType { get; } + IObservable AsUnit { get; } + IDisposable SubscribeInternal(Action propertyChanged); + } -public static class ObservablePropertyExtensions -{ - public static P AsP(this IObservableProperty property) + public static class ObservablePropertyExtensions { - return property as P; + public static P AsP(this IObservableProperty property) + { + return property as P; + } } } \ No newline at end of file diff --git a/MVVM/ViewModels/IViewModelManager.cs b/MVVM/ViewModels/IViewModelManager.cs index 551b683b..8859baff 100644 --- a/MVVM/ViewModels/IViewModelManager.cs +++ b/MVVM/ViewModels/IViewModelManager.cs @@ -1,20 +1,23 @@ using System.Collections.Generic; -/// -/// The view model manager is a class that encapsulates a list of viewmodels -/// -/// -public interface IViewModelManager : IEnumerable +namespace uFrame.MVVM { - void Add(ViewModel viewModel); - void Remove(ViewModel viewModel); -} + /// + /// The view model manager is a class that encapsulates a list of viewmodels + /// + /// + public interface IViewModelManager : IEnumerable + { + void Add(ViewModel viewModel); + void Remove(ViewModel viewModel); + } -/// -/// The view model manager is a class that encapsulates a list of viewmodels -/// -/// -public interface IViewModelManager : IViewModelManager -{ - + /// + /// The view model manager is a class that encapsulates a list of viewmodels + /// + /// + public interface IViewModelManager : IViewModelManager + { + + } } \ No newline at end of file diff --git a/MVVM/ViewModels/ModelCollection.cs b/MVVM/ViewModels/ModelCollection.cs index c6cb6405..13605946 100644 --- a/MVVM/ViewModels/ModelCollection.cs +++ b/MVVM/ViewModels/ModelCollection.cs @@ -5,14 +5,18 @@ using System.Collections.Specialized; using System.ComponentModel; using System.Linq; + + #if DLL using Invert.uFrame.Editor; namespace Invert.MVVM { -#else -#endif +#else using UniRx; +namespace uFrame.MVVM { +#endif + public class ModelCollection : ObservableCollection #if !DLL @@ -393,6 +397,5 @@ public T[] OldItemsOfT } } -#if DLL + } -#endif \ No newline at end of file diff --git a/MVVM/ViewModels/ModelPropertyBase.cs b/MVVM/ViewModels/ModelPropertyBase.cs index a9b43742..1ba4da1b 100644 --- a/MVVM/ViewModels/ModelPropertyBase.cs +++ b/MVVM/ViewModels/ModelPropertyBase.cs @@ -3,172 +3,177 @@ using System.ComponentModel; using UniRx; -public class P : ISubject, IObservableProperty, INotifyPropertyChanged +namespace uFrame.MVVM { - private object _objectValue; - private object _lastValue; - - public IObservable ChangedObservable + public class P : ISubject, IObservableProperty, INotifyPropertyChanged { - get { return this.Where(p => ObjectValue != LastValue); } - } + private object _objectValue; + private object _lastValue; - public object ObjectValue - { - get + public IObservable ChangedObservable { - return _objectValue ?? default(T); + get { return this.Where(p => ObjectValue != LastValue); } } - set + + public object ObjectValue { - _lastValue = _objectValue; - _objectValue = value; - OnPropertyChanged(PropertyName); - + get { return _objectValue ?? default(T); } + set + { + _lastValue = _objectValue; + _objectValue = value; + OnPropertyChanged(PropertyName); + + } } - } - public string PropertyName { get; set; } + + public string PropertyName { get; set; } #if !DLL - public ViewModel Owner { get; set; } + public ViewModel Owner { get; set; } #endif - public IDisposable SubscribeInternal(Action propertyChanged) - { - return this.Subscribe((v) => propertyChanged(v)); - } - public P() - { - } + public IDisposable SubscribeInternal(Action propertyChanged) + { + return this.Subscribe((v) => propertyChanged(v)); + } - //public IDisposable SubscribeInternal(Action obj) - //{ - // this.Subscribe(obj); - //} + public P() + { + } - public object LastValue - { - get { return _lastValue; } - set { _lastValue = value; } - } + //public IDisposable SubscribeInternal(Action obj) + //{ + // this.Subscribe(obj); + //} - public IDisposable Subscribe(IObserver observer) - { - PropertyChangedEventHandler evt = delegate { observer.OnNext(ObjectValue); }; - PropertyChanged += evt; - var disposer = Disposable.Create(() => PropertyChanged -= evt); - if (Owner != null) + public object LastValue { - Owner.AddBinding(disposer); + get { return _lastValue; } + set { _lastValue = value; } } - return disposer; - } - public event PropertyChangedEventHandler PropertyChanged; + public IDisposable Subscribe(IObserver observer) + { + PropertyChangedEventHandler evt = delegate { observer.OnNext(ObjectValue); }; + PropertyChanged += evt; + var disposer = Disposable.Create(() => PropertyChanged -= evt); + if (Owner != null) + { + Owner.AddBinding(disposer); + } + return disposer; + } - protected virtual void OnPropertyChanged(string propertyName) - { - PropertyChangedEventHandler handler = PropertyChanged; - if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); - if (Owner != null) - Owner.OnPropertyChanged(this, PropertyName); - } + public event PropertyChangedEventHandler PropertyChanged; - public IObservable AsUnit - { - get { return this.Select(p => Unit.Default); } - } + protected virtual void OnPropertyChanged(string propertyName) + { + PropertyChangedEventHandler handler = PropertyChanged; + if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); + if (Owner != null) + Owner.OnPropertyChanged(this, PropertyName); + } - public Func Computer { get; set; } + public IObservable AsUnit + { + get { return this.Select(p => Unit.Default); } + } - public IDisposable ToComputed(Func action, params IObservableProperty[] properties) - { - Computer = action; - var disposables = new List(); - foreach (var property in properties) + public Func Computer { get; set; } + + public IDisposable ToComputed(Func action, params IObservableProperty[] properties) { - disposables.Add(property.SubscribeInternal(_ => + Computer = action; + var disposables = new List(); + foreach (var property in properties) { - OnNext(action()); - })); - } + disposables.Add(property.SubscribeInternal(_ => + { + OnNext(action()); + })); + } + + //OnNext(action()); - //OnNext(action()); + return Disposable.Create(() => + { + foreach (var d in disposables) + d.Dispose(); + }); + } - return Disposable.Create(() => + ///// + ///// Makes this property a computed variable. + ///// + ///// + ///// + ///// + //public IDisposable ToComputed(Func action, params IObservableProperty[] properties) + //{ + // var disposables = new List(); + // foreach (var property in properties) + // { + // disposables.Add(property.SubscribeInternal(_ => + // { + // OnNext(action(Owner)); + // })); + // } + // action(Owner); + + // return Disposable.Create(() => + // { + // foreach (var d in disposables) + // d.Dispose(); + // }); + //} + + public P(T value) { - foreach (var d in disposables) - d.Dispose(); - }); - } - ///// - ///// Makes this property a computed variable. - ///// - ///// - ///// - ///// - //public IDisposable ToComputed(Func action, params IObservableProperty[] properties) - //{ - // var disposables = new List(); - // foreach (var property in properties) - // { - // disposables.Add(property.SubscribeInternal(_ => - // { - // OnNext(action(Owner)); - // })); - // } - // action(Owner); - - // return Disposable.Create(() => - // { - // foreach (var d in disposables) - // d.Dispose(); - // }); - //} - - public P(T value) - { - _objectValue = value; - } + _objectValue = value; + } + #if !DLL - public P(ViewModel owner, string propertyName) - { - Owner = owner; - PropertyName = propertyName; + public P(ViewModel owner, string propertyName) + { + Owner = owner; + PropertyName = propertyName; - } + } #endif - public Type ValueType - { - get { return typeof(T); } - } - public IDisposable Subscribe(IObserver observer) - { - - PropertyChangedEventHandler evt = delegate { observer.OnNext(Value); }; - PropertyChanged += evt; - return Disposable.Create(() => PropertyChanged -= evt); - } + public Type ValueType + { + get { return typeof (T); } + } - public T Value - { - get { return (T)ObjectValue; } - set { ObjectValue = value; } - } + public IDisposable Subscribe(IObserver observer) + { - public void OnCompleted() - { - - } + PropertyChangedEventHandler evt = delegate { observer.OnNext(Value); }; + PropertyChanged += evt; + return Disposable.Create(() => PropertyChanged -= evt); + } - public void OnError(Exception error) - { - - } + public T Value + { + get { return (T) ObjectValue; } + set { ObjectValue = value; } + } - public void OnNext(T value) - { - ObjectValue = value; + public void OnCompleted() + { + + } + + public void OnError(Exception error) + { + + } + + public void OnNext(T value) + { + ObjectValue = value; + } } } \ No newline at end of file diff --git a/MVVM/ViewModels/ModelPropertyBinding.cs b/MVVM/ViewModels/ModelPropertyBinding.cs index 7c187ecb..c92c4b07 100644 --- a/MVVM/ViewModels/ModelPropertyBinding.cs +++ b/MVVM/ViewModels/ModelPropertyBinding.cs @@ -1,65 +1,63 @@ -#if DLL -namespace Invert.MVVM -{ -#endif -using System; -/// -/// A class that contains a binding from a ViewModel to a Target -/// -public class ModelPropertyBinding : Binding, ITwoWayBinding +namespace uFrame.MVVM.Bindings { - private bool _isImmediate = true; - - public bool IsImmediate - { - get { return _isImmediate; } - set { _isImmediate = value; } - } - - public override void Bind() - { - base.Bind(); - Disposer = ModelProperty.SubscribeInternal(PropertyChanged); - // ModelProperty.ValueChanged += PropertyChanged; - if (IsImmediate) - PropertyChanged(ModelProperty.ObjectValue); - } - - public IDisposable Disposer { get; set; } - - /// - /// If the value has changed apply the value to the property without reinvoking the SetTargetDelegate. - /// It's important to not reinvoke the SetTargetDelegate because it will create a stack overflow. But only - /// the SetTargetDelegate should be ignored because there may be other bindings to this property and when it changes - /// they should definately know about it. - /// - public void BindReverse() - { - - } + using System; /// - /// Unbind remove the property changed event handler and the sets the model property - /// to null so it can be refreshed if a new model is set + /// A class that contains a binding from a ViewModel to a Target /// - public override void Unbind() + public class ModelPropertyBinding : Binding, ITwoWayBinding { - Disposer.Dispose(); - base.Unbind(); - } - /// - /// - /// The property changed event handler. - /// - /// - private void PropertyChanged(object value) - { - SetTargetValueDelegate(value); + private bool _isImmediate = true; + + public bool IsImmediate + { + get { return _isImmediate; } + set { _isImmediate = value; } + } + + public override void Bind() + { + base.Bind(); + Disposer = ModelProperty.SubscribeInternal(PropertyChanged); + // ModelProperty.ValueChanged += PropertyChanged; + if (IsImmediate) + PropertyChanged(ModelProperty.ObjectValue); + } + + public IDisposable Disposer { get; set; } + + /// + /// If the value has changed apply the value to the property without reinvoking the SetTargetDelegate. + /// It's important to not reinvoke the SetTargetDelegate because it will create a stack overflow. But only + /// the SetTargetDelegate should be ignored because there may be other bindings to this property and when it changes + /// they should definately know about it. + /// + public void BindReverse() + { + + } + + /// + /// Unbind remove the property changed event handler and the sets the model property + /// to null so it can be refreshed if a new model is set + /// + public override void Unbind() + { + Disposer.Dispose(); + base.Unbind(); + } + + /// + /// + /// The property changed event handler. + /// + /// + private void PropertyChanged(object value) + { + SetTargetValueDelegate(value); + } } -} -#if DLL -} -#endif \ No newline at end of file +} \ No newline at end of file diff --git a/MVVM/ViewModels/Signal.cs b/MVVM/ViewModels/Signal.cs index f08dbb4a..99ef86ca 100644 --- a/MVVM/ViewModels/Signal.cs +++ b/MVVM/ViewModels/Signal.cs @@ -1,75 +1,81 @@ using System; +using uFrame.Kernel; using UniRx; -public class Signal : ISubject, ISignal where TClass : ViewModelCommand, new() +namespace uFrame.MVVM { + public class Signal : ISubject, ISignal where TClass : ViewModelCommand, new() + { - private readonly SimpleSubject _signalSubject = new SimpleSubject(); - private readonly ViewModel _viewModel; - private Action _action; + private readonly SimpleSubject _signalSubject = new SimpleSubject(); + private readonly ViewModel _viewModel; + private Action _action; - public Signal(ViewModel viewModel) - { - _viewModel = viewModel; - } - [Obsolete("Resave and compile")] - public Signal(ViewModel viewModel, IEventAggregator aggregator) - { - _viewModel = viewModel; - } - public Signal(ViewModel viewModel, Action action) - { - _action = action; - _viewModel = viewModel; - } + public Signal(ViewModel viewModel) + { + _viewModel = viewModel; + } - public void OnCompleted() - { - _signalSubject.OnCompleted(); - } + [Obsolete("Resave and compile")] + public Signal(ViewModel viewModel, IEventAggregator aggregator) + { + _viewModel = viewModel; + } - public void OnError(Exception error) - { - _signalSubject.OnError(error); - } + public Signal(ViewModel viewModel, Action action) + { + _action = action; + _viewModel = viewModel; + } - public void OnNext(TClass value) - { - value.Sender = _viewModel; + public void OnCompleted() + { + _signalSubject.OnCompleted(); + } + + public void OnError(Exception error) + { + _signalSubject.OnError(error); + } - if (Action != null) - Action(value); + public void OnNext(TClass value) + { + value.Sender = _viewModel; - _signalSubject.OnNext(value); + if (Action != null) + Action(value); - } + _signalSubject.OnNext(value); - public IDisposable Subscribe(IObserver observer) - { - return _signalSubject.Subscribe(observer); - } + } - public Type SignalType - { - get { return typeof(TClass); } - } + public IDisposable Subscribe(IObserver observer) + { + return _signalSubject.Subscribe(observer); + } - public Action Action - { - get { return _action; } - set { _action = value; } - } + public Type SignalType + { + get { return typeof (TClass); } + } - public void Publish(object data) - { - OnNext(data as TClass); - } + public Action Action + { + get { return _action; } + set { _action = value; } + } - public void Publish() - { - OnNext(new TClass() + public void Publish(object data) + { + OnNext(data as TClass); + } + + public void Publish() { - Sender = _viewModel - }); + OnNext(new TClass() + { + Sender = _viewModel + }); + } } } \ No newline at end of file diff --git a/MVVM/ViewModels/ViewModel.cs b/MVVM/ViewModels/ViewModel.cs index 1de99115..40865594 100644 --- a/MVVM/ViewModels/ViewModel.cs +++ b/MVVM/ViewModels/ViewModel.cs @@ -4,11 +4,16 @@ using System.ComponentModel; using System.Linq; using System.Reflection; +using uFrame.Kernel; +using uFrame.MVVM.Bindings; + #if DLL using Invert.MVVM; using Invert.uFrame.Editor; namespace Invert.MVVM { +#else +namespace uFrame.MVVM { #endif using UniRx; @@ -260,6 +265,5 @@ private void CacheReflectedModelProperties() } } -#if DLL + } -#endif \ No newline at end of file diff --git a/MVVM/ViewModels/ViewModelCommand.cs b/MVVM/ViewModels/ViewModelCommand.cs index a8cf2d76..97ef3613 100644 --- a/MVVM/ViewModels/ViewModelCommand.cs +++ b/MVVM/ViewModels/ViewModelCommand.cs @@ -1,8 +1,11 @@ using UnityEngine; using System.Collections; -public class ViewModelCommand +namespace uFrame.MVVM { - public ViewModel Sender { get; set; } + public class ViewModelCommand + { + public ViewModel Sender { get; set; } + } } \ No newline at end of file diff --git a/MVVM/ViewModels/ViewModelCommandInfo.cs b/MVVM/ViewModels/ViewModelCommandInfo.cs index 86ceac00..1c561989 100644 --- a/MVVM/ViewModels/ViewModelCommandInfo.cs +++ b/MVVM/ViewModels/ViewModelCommandInfo.cs @@ -1,32 +1,35 @@ using System; -public class ViewModelCommandInfo +namespace uFrame.MVVM { - public ISignal Signal { get; private set; } - [Obsolete] - public ICommand Command { get; set; } + public class ViewModelCommandInfo + { + public ISignal Signal { get; private set; } + [Obsolete] + public ICommand Command { get; set; } - public string Name { get; set; } + public string Name { get; set; } - public Type ParameterType { get; set; } + public Type ParameterType { get; set; } - [Obsolete] - public ViewModelCommandInfo(string name, ICommand command) - { - Name = name; - Command = command; - } + [Obsolete] + public ViewModelCommandInfo(string name, ICommand command) + { + Name = name; + Command = command; + } - public ViewModelCommandInfo(string name, ISignal signal) - { - Signal = signal; - Name = name; - } - [Obsolete] - public ViewModelCommandInfo(Type parameterType, string name, ICommand command) - { - ParameterType = parameterType; - Name = name; - Command = command; + public ViewModelCommandInfo(string name, ISignal signal) + { + Signal = signal; + Name = name; + } + [Obsolete] + public ViewModelCommandInfo(Type parameterType, string name, ICommand command) + { + ParameterType = parameterType; + Name = name; + Command = command; + } } -} \ No newline at end of file +} diff --git a/MVVM/ViewModels/ViewModelCreatedEvent.cs b/MVVM/ViewModels/ViewModelCreatedEvent.cs index 00cc7393..97ce0e4b 100644 --- a/MVVM/ViewModels/ViewModelCreatedEvent.cs +++ b/MVVM/ViewModels/ViewModelCreatedEvent.cs @@ -1,9 +1,12 @@ -public class ViewModelCreatedEvent +namespace uFrame.MVVM { - public ViewModelCreatedEvent() + public class ViewModelCreatedEvent { - } + public ViewModelCreatedEvent() + { + } + + public ViewModel ViewModel { get; set; } - public ViewModel ViewModel { get; set; } - + } } \ No newline at end of file diff --git a/MVVM/ViewModels/ViewModelDestroyedEvent.cs b/MVVM/ViewModels/ViewModelDestroyedEvent.cs index f8d546c8..78fdb27b 100644 --- a/MVVM/ViewModels/ViewModelDestroyedEvent.cs +++ b/MVVM/ViewModels/ViewModelDestroyedEvent.cs @@ -1,6 +1,9 @@ -public class ViewModelDestroyedEvent +namespace uFrame.MVVM { + public class ViewModelDestroyedEvent + { - public ViewModel ViewModel { get; set; } + public ViewModel ViewModel { get; set; } + } } \ No newline at end of file diff --git a/MVVM/ViewModels/ViewModelExtensions.cs b/MVVM/ViewModels/ViewModelExtensions.cs index f4f5319a..a8d3d76d 100644 --- a/MVVM/ViewModels/ViewModelExtensions.cs +++ b/MVVM/ViewModels/ViewModelExtensions.cs @@ -1,61 +1,69 @@ using System; using System.Text; +using uFrame.IOC; +using uFrame.Kernel; +using uFrame.Serialization; -public static class ViewModelExtensions +namespace uFrame.MVVM { - public static string SerializeToJSON(this ViewModel model) + public static class ViewModelExtensions { - ISerializerStream stream = new JsonStream(); - ISerializerStorage storage = new StringSerializerStorage(); - stream.DeepSerialize = true; - model.Write(stream); - storage.Save(stream); - return storage.ToString(); - } - public static void DeserializeFromJSON(this ViewModel model, string json) - { - ISerializerStream stream = new JsonStream(); - stream.DeepSerialize = true; - stream.DependencyContainer = uFrameMVVMKernel.Container; - stream.TypeResolver = new ViewModelResolver() {Container = uFrameMVVMKernel.Container}; - stream.Load(Encoding.UTF8.GetBytes(json)); - model.Read(stream); - } -} + public static string SerializeToJSON(this ViewModel model) + { + ISerializerStream stream = new JsonStream(); + ISerializerStorage storage = new StringSerializerStorage(); + stream.DeepSerialize = true; + model.Write(stream); + storage.Save(stream); + return storage.ToString(); + } -public class ViewModelResolver : ITypeResolver -{ - public IGameContainer Container { get; set; } - Type ITypeResolver.GetType(string name) - { - return Type.GetType(name); + public static void DeserializeFromJSON(this ViewModel model, string json) + { + ISerializerStream stream = new JsonStream(); + stream.DeepSerialize = true; + stream.DependencyContainer = uFrameMVVMKernel.Container; + stream.TypeResolver = new ViewModelResolver() {Container = uFrameMVVMKernel.Container}; + stream.Load(Encoding.UTF8.GetBytes(json)); + model.Read(stream); + } } - string ITypeResolver.SetType(Type type) + public class ViewModelResolver : ITypeResolver { - return type.AssemblyQualifiedName; - } + public IUFrameContainer Container { get; set; } - object ITypeResolver.CreateInstance(string name, string identifier) - { - var type = ((ITypeResolver)this).GetType(name); + Type ITypeResolver.GetType(string name) + { + return Type.GetType(name); + } + + string ITypeResolver.SetType(Type type) + { + return type.AssemblyQualifiedName; + } + + object ITypeResolver.CreateInstance(string name, string identifier) + { + var type = ((ITypeResolver) this).GetType(name); #if NETFX_CORE var isViewModel = type.GetTypeInfo().IsSubclassOf(typeof(ViewModel)); #else - var isViewModel = typeof(ViewModel).IsAssignableFrom(type); + var isViewModel = typeof (ViewModel).IsAssignableFrom(type); #endif - if (isViewModel) - { - var contextViewModel = Container.Resolve(type, identifier); - if (contextViewModel != null) + if (isViewModel) { - return contextViewModel; + var contextViewModel = Container.Resolve(type, identifier); + if (contextViewModel != null) + { + return contextViewModel; + } + return MVVMKernelExtensions.CreateViewModel(type, identifier); } - return MVVMKernelExtensions.CreateViewModel(type, identifier); - } - return null; + return null; + } } } \ No newline at end of file diff --git a/MVVM/ViewModels/ViewModelManager.cs b/MVVM/ViewModels/ViewModelManager.cs index 52f4fb27..895ec0ed 100644 --- a/MVVM/ViewModels/ViewModelManager.cs +++ b/MVVM/ViewModels/ViewModelManager.cs @@ -2,42 +2,45 @@ using System.Collections.Generic; using System.Linq; -/// -/// The view model manager is a class that encapsulates a list of viewmodels -/// -/// -public class ViewModelManager : IViewModelManager where T : ViewModel +namespace uFrame.MVVM { - private List _viewModels = new List(); - - public List ViewModels + /// + /// The view model manager is a class that encapsulates a list of viewmodels + /// + /// + public class ViewModelManager : IViewModelManager where T : ViewModel { - get { return _viewModels; } - set { _viewModels = value; } - } + private List _viewModels = new List(); - public IEnumerator GetEnumerator() - { - return ViewModels.Cast().GetEnumerator(); - } + public List ViewModels + { + get { return _viewModels; } + set { _viewModels = value; } + } - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } + public IEnumerator GetEnumerator() + { + return ViewModels.Cast().GetEnumerator(); + } - public void Add(ViewModel viewModel) - { - if(!ViewModels.Contains((T)viewModel)) - ViewModels.Add((T)viewModel); - - } + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } - public void Remove(ViewModel viewModel) - { - ViewModels.Remove((T)viewModel); - - } + public void Add(ViewModel viewModel) + { + if (!ViewModels.Contains((T) viewModel)) + ViewModels.Add((T) viewModel); + + } + + public void Remove(ViewModel viewModel) + { + ViewModels.Remove((T) viewModel); - + } + + + } } \ No newline at end of file diff --git a/MVVM/ViewModels/ViewModelPropertyInfo.cs b/MVVM/ViewModels/ViewModelPropertyInfo.cs index 62a146ac..81666f7a 100644 --- a/MVVM/ViewModels/ViewModelPropertyInfo.cs +++ b/MVVM/ViewModels/ViewModelPropertyInfo.cs @@ -1,20 +1,24 @@ -public class ViewModelPropertyInfo +namespace uFrame.MVVM { - public bool IsComputed { get; set; } - public bool IsCollectionProperty { get; set; } + public class ViewModelPropertyInfo + { + public bool IsComputed { get; set; } + public bool IsCollectionProperty { get; set; } - public bool IsElementProperty { get; set; } + public bool IsElementProperty { get; set; } - public bool IsEnum { get; set; } + public bool IsEnum { get; set; } - public IObservableProperty Property { get; set; } + public IObservableProperty Property { get; set; } - public ViewModelPropertyInfo(IObservableProperty property, bool isElementProperty, bool isCollectionProperty, bool isEnum, bool isComputed = false) - { - Property = property; - IsElementProperty = isElementProperty; - IsCollectionProperty = isCollectionProperty; - IsEnum = isEnum; - IsComputed = isComputed; + public ViewModelPropertyInfo(IObservableProperty property, bool isElementProperty, bool isCollectionProperty, + bool isEnum, bool isComputed = false) + { + Property = property; + IsElementProperty = isElementProperty; + IsCollectionProperty = isCollectionProperty; + IsEnum = isEnum; + IsComputed = isComputed; + } } } \ No newline at end of file diff --git a/MVVM/ViewStateResolver.cs b/MVVM/ViewStateResolver.cs index 4e92ab2d..7b1d4450 100644 --- a/MVVM/ViewStateResolver.cs +++ b/MVVM/ViewStateResolver.cs @@ -1,6 +1,7 @@ using System; using System.Diagnostics; using System.Linq; +using uFrame.MVVM; using Debug = UnityEngine.Debug; #if NETFX_CORE using System.Reflection; diff --git a/MVVM/Views/Bindings/Binding.cs b/MVVM/Views/Bindings/Binding.cs index 91236ed4..6c7681c7 100644 --- a/MVVM/Views/Bindings/Binding.cs +++ b/MVVM/Views/Bindings/Binding.cs @@ -2,140 +2,129 @@ using UniRx; using UnityEngine; -/// -/// The base class for all bindings. -/// -public abstract class Binding : IBinding, IDisposable +namespace uFrame.MVVM.Bindings { - private IObservableProperty _modelProperty; - private Func _modelPropertySelector; - /// - /// Does this instance type implement ITwoWayBinding? + /// The base class for all bindings. /// - public bool CanTwoWayBind + public abstract class Binding : IBinding, IDisposable { - get + private IObservableProperty _modelProperty; + private Func _modelPropertySelector; + + /// + /// Does this instance type implement ITwoWayBinding? + /// + public bool CanTwoWayBind { - return this is ITwoWayBinding; + get { return this is ITwoWayBinding; } } - } - /// - /// A delegate for Getting the target value and is required for a two-way binding. - /// - public Func GetTargetValueDelegate { get; set; } + /// + /// A delegate for Getting the target value and is required for a two-way binding. + /// + public Func GetTargetValueDelegate { get; set; } - public bool IsBound { get; set; } + public bool IsBound { get; set; } - /// - /// Was this loaded from a component in the Unity Inspector? - /// - public bool IsComponent { get; set; } + /// + /// Was this loaded from a component in the Unity Inspector? + /// + public bool IsComponent { get; set; } - /// - /// The source ViewModel member name that is being bound to. - /// - public string ModelMemberName { - get { return ModelProperty.PropertyName; } - set + /// + /// The source ViewModel member name that is being bound to. + /// + public string ModelMemberName { - + get { return ModelProperty.PropertyName; } + set { } } - } - /// - /// The Model Property that is being bound to. Will call the ModelPropertySelector if null. - /// - public IObservableProperty ModelProperty - { - get + /// + /// The Model Property that is being bound to. Will call the ModelPropertySelector if null. + /// + public IObservableProperty ModelProperty { - if (_modelProperty != null) - return _modelProperty; - else return _modelProperty = ModelPropertySelector(); + get + { + if (_modelProperty != null) + return _modelProperty; + else return _modelProperty = ModelPropertySelector(); + } + set { _modelProperty = value; } } - set + + /// + /// A selector that will select the model property. + /// This should be set manually if reflection shouldn't be used. + /// + public Func ModelPropertySelector { - _modelProperty = value; + get { return _modelPropertySelector; } + set { _modelPropertySelector = value; } } - } - - /// - /// A selector that will select the model property. - /// This should be set manually if reflection shouldn't be used. - /// - public Func ModelPropertySelector - { - get { return _modelPropertySelector; } - set { _modelPropertySelector = value; } - } - /// - /// A delegate to set the value of the target member(s). - /// - public Action SetTargetValueDelegate { get; set; } + /// + /// A delegate to set the value of the target member(s). + /// + public Action SetTargetValueDelegate { get; set; } - ///// - ///// The owner view that this Binding belongs to - ///// - //public ViewModel Source { get; set; } + ///// + ///// The owner view that this Binding belongs to + ///// + //public ViewModel Source { get; set; } - /// - /// The value of the ViewModel Member - /// - public object SourceValue - { - get + /// + /// The value of the ViewModel Member + /// + public object SourceValue { - return ModelProperty.ObjectValue; + get { return ModelProperty.ObjectValue; } } - } - /// - /// Is this a two-way binding. - /// - public bool TwoWay - { - get; - set; - } + /// + /// Is this a two-way binding. + /// + public bool TwoWay { get; set; } - protected Binding() - { - } + protected Binding() + { + } - ///// - ///// Constructor - ///// - ///// The View that will own this binding. - ///// The member of the ViewModel. - //protected Binding(ViewBase sourceView, string modelMemberName) - //{ - // Source = sourceView; - // ModelMemberName = modelMemberName; - //} + ///// + ///// Constructor + ///// + ///// The View that will own this binding. + ///// The member of the ViewModel. + //protected Binding(ViewBase sourceView, string modelMemberName) + //{ + // Source = sourceView; + // ModelMemberName = modelMemberName; + //} + + /// + /// Set-up the binding. This should almost always be implemented in a deriving class. + /// + public virtual void Bind() + { + IsBound = true; + _modelProperty = null; + } - /// - /// Set-up the binding. This should almost always be implemented in a deriving class. - /// - public virtual void Bind() - { - IsBound = true; - _modelProperty = null; - } + /// + /// Unbind this binding + /// + public virtual void Unbind() + { + IsBound = false; + _modelProperty = null; + } - /// - /// Unbind this binding - /// - public virtual void Unbind() - { - IsBound = false; - _modelProperty = null; + public void Dispose() + { + Unbind(); + } } - public void Dispose() - { - Unbind(); - } } \ No newline at end of file diff --git a/MVVM/Views/Bindings/CollisionEventType.cs b/MVVM/Views/Bindings/CollisionEventType.cs index fcf18d49..ce7ab73a 100644 --- a/MVVM/Views/Bindings/CollisionEventType.cs +++ b/MVVM/Views/Bindings/CollisionEventType.cs @@ -1,6 +1,9 @@ -public enum CollisionEventType +namespace uFrame.MVVM.Bindings { - Enter, - Exit, - Stay + public enum CollisionEventType + { + Enter, + Exit, + Stay + } } \ No newline at end of file diff --git a/MVVM/Views/Bindings/EventBinding.cs b/MVVM/Views/Bindings/EventBinding.cs deleted file mode 100644 index b2ce0fdf..00000000 --- a/MVVM/Views/Bindings/EventBinding.cs +++ /dev/null @@ -1,22 +0,0 @@ -///// -///// The event binding component that will add an event binding to a source view. -///// -//public class EventBinding : ComponentCommandBinding -//{ -// public string _EventName; - -// protected override IBinding GetBinding() -// { -// return new ModelEventBinding(_EventName) -// { -// EventName = _EventName, -// ModelMemberName = _ModelMemberName, -// Source = _SourceView.ViewModelObject, -// }; -// } - -// protected override void Awake() -// { -// base.Awake(); -// } -//} \ No newline at end of file diff --git a/MVVM/Views/Bindings/ExtendedCollisionBinding.cs b/MVVM/Views/Bindings/ExtendedCollisionBinding.cs index cb419863..f6e2df36 100644 --- a/MVVM/Views/Bindings/ExtendedCollisionBinding.cs +++ b/MVVM/Views/Bindings/ExtendedCollisionBinding.cs @@ -2,77 +2,108 @@ using UniRx; using UnityEngine; -public static class ExtendedCollisionBinding +namespace uFrame.MVVM.Bindings { - - //Observables + Bindings for Collision with any unity monobeh - - public static IDisposable BindComponentCollisionWith(this ViewBase t, CollisionEventType eventType, Action collision) where T : MonoBehaviour + public static class ExtendedCollisionBinding { - return t.AddBinding(OnComponentCollisionWith(t.gameObject, eventType).Subscribe(collision)); - } - public static IDisposable BindComponentCollision2DWith(this ViewBase t, CollisionEventType eventType, Action collision) where T : MonoBehaviour - { - return t.AddBinding(OnComponentCollision2DWith(t.gameObject, eventType).Subscribe(collision)); - } + //Observables + Bindings for Collision with any unity monobeh + + public static IDisposable BindComponentCollisionWith(this ViewBase t, CollisionEventType eventType, + Action collision) where T : MonoBehaviour + { + return t.AddBinding(OnComponentCollisionWith(t.gameObject, eventType).Subscribe(collision)); + } + + public static IDisposable BindComponentCollision2DWith(this ViewBase t, CollisionEventType eventType, + Action collision) where T : MonoBehaviour + { + return t.AddBinding(OnComponentCollision2DWith(t.gameObject, eventType).Subscribe(collision)); + } + + public static IObservable OnComponentCollisionWith(this GameObject t, CollisionEventType eventType) + where T : MonoBehaviour + { + return + t.OnCollisionObservable(eventType) + .Where(p => p.gameObject.GetComponent() != null) + .Select(p => p.gameObject.GetComponent()); + } + + public static IObservable OnComponentCollision2DWith(this GameObject t, CollisionEventType eventType) + where T : MonoBehaviour + { + return + t.OnCollision2DObservable(eventType) + .Where(p => p.gameObject.GetComponent() != null) + .Select(p => p.gameObject.GetComponent()); + } + + //Observables and bindings for Trigger with any View + public static IDisposable BindViewTriggerWith(this ViewBase t, CollisionEventType eventType, + Action collision) where T : ViewBase + { + return t.AddBinding(OnViewTriggerWith(t.gameObject, eventType).Subscribe(collision)); + } + + public static IDisposable BindViewTrigger2DWith(this ViewBase t, CollisionEventType eventType, + Action collision) where T : ViewBase + { + return t.AddBinding(OnViewTrigger2DWith(t.gameObject, eventType).Subscribe(collision)); + } + + public static IObservable OnViewTriggerWith(this GameObject t, CollisionEventType eventType) + where T : ViewBase + { + return t.OnTriggerObservable(eventType).Where(p => p.GetView() != null).Select(p => p.GetView()); + } + + public static IObservable OnViewTrigger2DWith(this GameObject t, CollisionEventType eventType) + where T : ViewBase + { + return + t.OnTrigger2DObservable(eventType) + .Where(p => p.gameObject.GetView() != null) + .Select(p => p.gameObject.GetView()); + } + + //Observables and bindings for Trigger with any unity monobeh + + public static IDisposable BindComponentTriggerWith(this ViewBase t, CollisionEventType eventType, + Action collision) where T : MonoBehaviour + { + return t.AddBinding(OnComponentTriggerWith(t.gameObject, eventType).Subscribe(collision)); + } + + public static IDisposable BindComponentTrigger2DWith(this ViewBase t, CollisionEventType eventType, + Action collision) where T : MonoBehaviour + { + return t.AddBinding(OnComponentTriggerWith2D(t.gameObject, eventType).Subscribe(collision)); + } + + public static IObservable OnComponentTriggerWith(this GameObject t, CollisionEventType eventType) + where T : MonoBehaviour + { + return + t.OnTriggerObservable(eventType) + .Where(p => p.gameObject.GetComponent() != null) + .Select(p => p.gameObject.GetComponent()); + } + + public static IObservable OnComponentTriggerWith2D(this GameObject t, CollisionEventType eventType) + where T : MonoBehaviour + { + return + t.OnTrigger2DObservable(eventType) + .Where(p => p.gameObject.GetComponent() != null) + .Select(p => p.gameObject.GetComponent()); + } - public static IObservable OnComponentCollisionWith(this GameObject t, CollisionEventType eventType) where T : MonoBehaviour - { - return t.OnCollisionObservable(eventType).Where(p => p.gameObject.GetComponent() != null).Select(p => p.gameObject.GetComponent()); - } - public static IObservable OnComponentCollision2DWith(this GameObject t, CollisionEventType eventType) where T : MonoBehaviour - { - return t.OnCollision2DObservable(eventType).Where(p => p.gameObject.GetComponent() != null).Select(p => p.gameObject.GetComponent()); - } - //Observables and bindings for Trigger with any View - public static IDisposable BindViewTriggerWith(this ViewBase t, CollisionEventType eventType, Action collision) where T : ViewBase - { - return t.AddBinding(OnViewTriggerWith(t.gameObject, eventType).Subscribe(collision)); - } - public static IDisposable BindViewTrigger2DWith(this ViewBase t, CollisionEventType eventType, Action collision) where T : ViewBase - { - return t.AddBinding(OnViewTrigger2DWith(t.gameObject, eventType).Subscribe(collision)); - } - - public static IObservable OnViewTriggerWith(this GameObject t, CollisionEventType eventType) where T : ViewBase - { - return t.OnTriggerObservable(eventType).Where(p => p.GetView() != null).Select(p => p.GetView()); - } - - public static IObservable OnViewTrigger2DWith(this GameObject t, CollisionEventType eventType) where T : ViewBase - { - return t.OnTrigger2DObservable(eventType).Where(p => p.gameObject.GetView() != null).Select(p => p.gameObject.GetView()); - } - - //Observables and bindings for Trigger with any unity monobeh - - public static IDisposable BindComponentTriggerWith(this ViewBase t, CollisionEventType eventType, Action collision) where T : MonoBehaviour - { - return t.AddBinding(OnComponentTriggerWith(t.gameObject, eventType).Subscribe(collision)); - } - - public static IDisposable BindComponentTrigger2DWith(this ViewBase t, CollisionEventType eventType, Action collision) where T : MonoBehaviour - { - return t.AddBinding(OnComponentTriggerWith2D(t.gameObject, eventType).Subscribe(collision)); - } - - public static IObservable OnComponentTriggerWith(this GameObject t, CollisionEventType eventType) where T : MonoBehaviour - { - return t.OnTriggerObservable(eventType).Where(p => p.gameObject.GetComponent() != null).Select(p => p.gameObject.GetComponent()); - } - - public static IObservable OnComponentTriggerWith2D(this GameObject t, CollisionEventType eventType) where T : MonoBehaviour - { - return t.OnTrigger2DObservable(eventType).Where(p => p.gameObject.GetComponent() != null).Select(p => p.gameObject.GetComponent()); - } - - - + } } \ No newline at end of file diff --git a/MVVM/Views/Bindings/IBindable.cs b/MVVM/Views/Bindings/IBindable.cs index 5cd12551..3d60de25 100644 --- a/MVVM/Views/Bindings/IBindable.cs +++ b/MVVM/Views/Bindings/IBindable.cs @@ -1,6 +1,9 @@ using System; -public interface IBindable +namespace uFrame.MVVM.Bindings { - IDisposable AddBinding(IDisposable binding); + public interface IBindable + { + IDisposable AddBinding(IDisposable binding); + } } \ No newline at end of file diff --git a/MVVM/Views/Bindings/IBinding.cs b/MVVM/Views/Bindings/IBinding.cs index 3377efa7..9d732ab8 100644 --- a/MVVM/Views/Bindings/IBinding.cs +++ b/MVVM/Views/Bindings/IBinding.cs @@ -1,60 +1,57 @@ -#if DLL -namespace Invert.MVVM -{ -#endif -using System; -/// -/// Interface for all bindings -/// -public interface IBinding +namespace uFrame.MVVM.Bindings { - bool IsComponent { get; set; } - - string ModelMemberName { get; set; } + using System; - //ViewBase Source { get; set; } + /// + /// Interface for all bindings + /// + public interface IBinding + { - bool TwoWay { get; set; } + bool IsComponent { get; set; } - void Bind(); + string ModelMemberName { get; set; } - void Unbind(); -} + //ViewBase Source { get; set; } -public class GenericBinding : IBinding -{ - public bool IsComponent { get; set; } - public string ModelMemberName { get; set; } - public bool TwoWay { get; set; } + bool TwoWay { get; set; } - public Action BindAction { get; set; } - public Action UnbindAction { get; set; } + void Bind(); - public GenericBinding(Action bindAction, Action unbindAction) - { - BindAction = bindAction; - UnbindAction = unbindAction; + void Unbind(); } - public void Bind() + public class GenericBinding : IBinding { - if (BindAction != null) + public bool IsComponent { get; set; } + public string ModelMemberName { get; set; } + public bool TwoWay { get; set; } + + public Action BindAction { get; set; } + public Action UnbindAction { get; set; } + + public GenericBinding(Action bindAction, Action unbindAction) { - BindAction(); + BindAction = bindAction; + UnbindAction = unbindAction; } - } - public void Unbind() - { - if (UnbindAction != null) + public void Bind() { - UnbindAction(); + if (BindAction != null) + { + BindAction(); + } } - } -} -#if DLL -} -#endif \ No newline at end of file + public void Unbind() + { + if (UnbindAction != null) + { + UnbindAction(); + } + } + } +} \ No newline at end of file diff --git a/MVVM/Views/Bindings/IBindingProvider.cs b/MVVM/Views/Bindings/IBindingProvider.cs index 34e1f7df..5ed66dbe 100644 --- a/MVVM/Views/Bindings/IBindingProvider.cs +++ b/MVVM/Views/Bindings/IBindingProvider.cs @@ -1,6 +1,9 @@ -public interface IBindingProvider +namespace uFrame.MVVM.Bindings { - void Bind(ViewBase view); + public interface IBindingProvider + { + void Bind(ViewBase view); - void Unbind(ViewBase viewBase); -} \ No newline at end of file + void Unbind(ViewBase viewBase); + } +} diff --git a/MVVM/Views/Bindings/ITwoWayBinding.cs b/MVVM/Views/Bindings/ITwoWayBinding.cs index b14ffb01..0cb5d30e 100644 --- a/MVVM/Views/Bindings/ITwoWayBinding.cs +++ b/MVVM/Views/Bindings/ITwoWayBinding.cs @@ -1,14 +1,10 @@ -#if DLL -namespace Invert.MVVM +namespace uFrame.MVVM.Bindings { -#endif -public interface ITwoWayBinding : IBinding -{ - /// - /// Will be called every update frame - /// - void BindReverse(); -} -#if DLL + public interface ITwoWayBinding : IBinding + { + /// + /// Will be called every update frame + /// + void BindReverse(); + } } -#endif \ No newline at end of file diff --git a/MVVM/Views/Bindings/IViewModelObserver.cs b/MVVM/Views/Bindings/IViewModelObserver.cs index 40ab98fc..8beffa39 100644 --- a/MVVM/Views/Bindings/IViewModelObserver.cs +++ b/MVVM/Views/Bindings/IViewModelObserver.cs @@ -1,16 +1,19 @@ using System.Collections.Generic; using UnityEngine; -/// -/// Potential future use. -/// -public interface IViewModelObserver +namespace uFrame.MVVM.Bindings { - //List Bindings { get; set; } + /// + /// Potential future use. + /// + public interface IViewModelObserver + { + //List Bindings { get; set; } - void AddBinding(IBinding binding); + void AddBinding(IBinding binding); - void RemoveBinding(IBinding binding); + void RemoveBinding(IBinding binding); - void Unbind(); + void Unbind(); + } } \ No newline at end of file diff --git a/MVVM/Views/Bindings/ModelViewModelCollectionBinding.cs b/MVVM/Views/Bindings/ModelViewModelCollectionBinding.cs index 302b30a4..b55ec663 100644 --- a/MVVM/Views/Bindings/ModelViewModelCollectionBinding.cs +++ b/MVVM/Views/Bindings/ModelViewModelCollectionBinding.cs @@ -4,319 +4,324 @@ using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; +using uFrame.MVVM; +using uFrame.MVVM.Services; using UnityEngine; using Object = UnityEngine.Object; -public class ModelCollectionBinding : Binding +namespace uFrame.MVVM.Bindings { - private bool _isImmediate = true; - private ModelCollection _collection; - - public ModelCollection Collection - { - get { return _collection ?? (_collection = ModelProperty as ModelCollection); } - set { _collection = value; } - } - - public bool IsImmediate + public class ModelCollectionBinding : Binding { - get { return _isImmediate; } - set { _isImmediate = value; } - } - - public Action OnAdd { get; set; } + private bool _isImmediate = true; + private ModelCollection _collection; - public Action OnRemove { get; set; } - - public override void Bind() - { - base.Bind(); - Collection.CollectionChanged += CollectionOnChanged; - if (IsImmediate) + public ModelCollection Collection { - BindNow(); + get { return _collection ?? (_collection = ModelProperty as ModelCollection); } + set { _collection = value; } } - } - public void Immediate() - { - if (IsBound) - { - IsImmediate = true; - BindNow(); - } - else + public bool IsImmediate { - IsImmediate = true; + get { return _isImmediate; } + set { _isImmediate = value; } } - } - public ModelCollectionBinding SetAddHandler(Action onAddHandler) - { - OnAdd = onAddHandler; - return this; - } - - public ModelCollectionBinding SetRemoveHandler(Action onRemoveHandler) - { - OnRemove = onRemoveHandler; - return this; - } + public Action OnAdd { get; set; } - public override void Unbind() - { - Collection.CollectionChanged -= CollectionOnChanged; - base.Unbind(); - } + public Action OnRemove { get; set; } - private void BindNow() - { - CollectionOnChanged(this, new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Add, Collection.Cast().ToArray())); - } + public override void Bind() + { + base.Bind(); + Collection.CollectionChanged += CollectionOnChanged; + if (IsImmediate) + { + BindNow(); + } + } - private void CollectionOnChanged(object sender, NotifyCollectionChangedEventArgs changeArgs) - { - if (changeArgs.NewItems != null) - foreach (var newItem in changeArgs.NewItems) + public void Immediate() + { + if (IsBound) { - if (OnAdd != null) - OnAdd((TCollectionType)newItem); + IsImmediate = true; + BindNow(); } - if (changeArgs.OldItems != null) - foreach (var oldItem in changeArgs.OldItems) + else { - if (OnRemove != null) - OnRemove((TCollectionType)oldItem); + IsImmediate = true; } - } -} + } -/// -/// Class for a view collection binding. Binds a ViewModel collection to a set of corresponding Views -/// -public class ModelViewModelCollectionBinding : Binding -{ - private bool _isImmediate = true; - private bool _viewFirst = false; - private Dictionary _gameObjectLookup = new Dictionary(); - private Dictionary _objectIdLookup; + public ModelCollectionBinding SetAddHandler(Action onAddHandler) + { + OnAdd = onAddHandler; + return this; + } - public INotifyCollectionChanged Collection - { - get - { - return ModelProperty as INotifyCollectionChanged; + public ModelCollectionBinding SetRemoveHandler(Action onRemoveHandler) + { + OnRemove = onRemoveHandler; + return this; } - } - public IList List - { - get { return Collection as IList; } + public override void Unbind() + { + Collection.CollectionChanged -= CollectionOnChanged; + base.Unbind(); + } + + private void BindNow() + { + CollectionOnChanged(this, + new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, + Collection.Cast().ToArray())); + } + + private void CollectionOnChanged(object sender, NotifyCollectionChangedEventArgs changeArgs) + { + if (changeArgs.NewItems != null) + foreach (var newItem in changeArgs.NewItems) + { + if (OnAdd != null) + OnAdd((TCollectionType) newItem); + } + if (changeArgs.OldItems != null) + foreach (var oldItem in changeArgs.OldItems) + { + if (OnRemove != null) + OnRemove((TCollectionType) oldItem); + } + } } - public bool IsImmediate + /// + /// Class for a view collection binding. Binds a ViewModel collection to a set of corresponding Views + /// + public class ModelViewModelCollectionBinding : Binding { - get { return _isImmediate; } - set { _isImmediate = value; } - } + private bool _isImmediate = true; + private bool _viewFirst = false; + private Dictionary _gameObjectLookup = new Dictionary(); + private Dictionary _objectIdLookup; - public Action OnAddView { get; set; } + public INotifyCollectionChanged Collection + { + get { return ModelProperty as INotifyCollectionChanged; } + } - public Func OnCreateView { get; set; } + public IList List + { + get { return Collection as IList; } + } - public Action OnRemoveView { get; set; } + public bool IsImmediate + { + get { return _isImmediate; } + set { _isImmediate = value; } + } - public Transform Parent { get; set; } + public Action OnAddView { get; set; } - public string ViewName { get; set; } + public Func OnCreateView { get; set; } - public ModelViewModelCollectionBinding Immediate(bool immediate = true) - { - IsImmediate = immediate; - return this; - } + public Action OnRemoveView { get; set; } - public ModelViewModelCollectionBinding SetAddHandler(Action onAdd) - { - OnAddView = onAdd; - return this; - } + public Transform Parent { get; set; } - public ModelViewModelCollectionBinding SetCreateHandler(Func onCreateView) - { - OnCreateView = onCreateView; - return this; - } + public string ViewName { get; set; } - public ModelViewModelCollectionBinding SetParent(Transform parent) - { - Parent = parent; - return this; - } + public ModelViewModelCollectionBinding Immediate(bool immediate = true) + { + IsImmediate = immediate; + return this; + } - public ModelViewModelCollectionBinding SetRemoveHandler(Action onRemove) - { - OnRemoveView = onRemove; - return this; - } + public ModelViewModelCollectionBinding SetAddHandler(Action onAdd) + { + OnAddView = onAdd; + return this; + } - public ModelViewModelCollectionBinding SetView(string viewName) - { - ViewName = viewName; - return this; - } + public ModelViewModelCollectionBinding SetCreateHandler(Func onCreateView) + { + OnCreateView = onCreateView; + return this; + } - public override void Unbind() - { - Collection.CollectionChanged -= CollectionOnChanged; - GameObjectLookup.Clear(); - base.Unbind(); - } + public ModelViewModelCollectionBinding SetParent(Transform parent) + { + Parent = parent; + return this; + } - public Dictionary GameObjectLookup - { - get { return _gameObjectLookup ?? (_gameObjectLookup = new Dictionary()); } - set { _gameObjectLookup = value; } - } + public ModelViewModelCollectionBinding SetRemoveHandler(Action onRemove) + { + OnRemoveView = onRemove; + return this; + } - public Dictionary ObjectIdLookup - { - get { return _objectIdLookup ?? (_objectIdLookup = new Dictionary()); } - set { _objectIdLookup = value; } - } + public ModelViewModelCollectionBinding SetView(string viewName) + { + ViewName = viewName; + return this; + } - protected void AddLookup(GameObject obj, ViewModel viewModel) - { - if (obj == null || viewModel == null) return; - var instanceId = obj.GetInstanceID(); - if (!GameObjectLookup.ContainsKey(instanceId)) - GameObjectLookup.Add(instanceId, obj); - if (!ObjectIdLookup.ContainsKey(viewModel)) - ObjectIdLookup.Add(viewModel, instanceId); - } + public override void Unbind() + { + Collection.CollectionChanged -= CollectionOnChanged; + GameObjectLookup.Clear(); + base.Unbind(); + } - protected void RemoveLookup(ViewModel model) - { - if (ObjectIdLookup.ContainsKey(model)) + public Dictionary GameObjectLookup { - var instanceId = ObjectIdLookup[model]; - ObjectIdLookup.Remove(model); - var go = GameObjectLookup[instanceId]; - GameObjectLookup.Remove(instanceId); - if (OnRemoveView != null) - { - OnRemoveView(go.GetView()); - } - else + get { return _gameObjectLookup ?? (_gameObjectLookup = new Dictionary()); } + set { _gameObjectLookup = value; } + } + + public Dictionary ObjectIdLookup + { + get { return _objectIdLookup ?? (_objectIdLookup = new Dictionary()); } + set { _objectIdLookup = value; } + } + + protected void AddLookup(GameObject obj, ViewModel viewModel) + { + if (obj == null || viewModel == null) return; + var instanceId = obj.GetInstanceID(); + if (!GameObjectLookup.ContainsKey(instanceId)) + GameObjectLookup.Add(instanceId, obj); + if (!ObjectIdLookup.ContainsKey(viewModel)) + ObjectIdLookup.Add(viewModel, instanceId); + } + + protected void RemoveLookup(ViewModel model) + { + if (ObjectIdLookup.ContainsKey(model)) { - Object.Destroy(go); + var instanceId = ObjectIdLookup[model]; + ObjectIdLookup.Remove(model); + var go = GameObjectLookup[instanceId]; + GameObjectLookup.Remove(instanceId); + if (OnRemoveView != null) + { + OnRemoveView(go.GetView()); + } + else + { + Object.Destroy(go); + } } } - } - public override void Bind() - { - base.Bind(); - - // If we are syncing from the collection first on not the scene - if (!_viewFirst) + public override void Bind() { - var targetTransform = Parent; - if (targetTransform != null) + base.Bind(); + + + // If we are syncing from the collection first on not the scene + if (!_viewFirst) { - for (var i = 0; i < targetTransform.childCount; i++) + var targetTransform = Parent; + if (targetTransform != null) { + for (var i = 0; i < targetTransform.childCount; i++) + { - Object.Destroy(targetTransform.GetChild(i).gameObject); + Object.Destroy(targetTransform.GetChild(i).gameObject); + } } } - } - else - { - var targetTransform = Parent ?? SourceView.transform; - if (targetTransform != null) - { - for (var i = 0; i < targetTransform.childCount; i++) + else + { + var targetTransform = Parent ?? SourceView.transform; + if (targetTransform != null) { - var view = targetTransform.GetChild(i).GetView(); - if (view != null) + for (var i = 0; i < targetTransform.childCount; i++) { - if (view.ViewModelObject == null) + var view = targetTransform.GetChild(i).GetView(); + if (view != null) { - view.ViewModelObject = ViewService.FetchViewModel(view); + if (view.ViewModelObject == null) + { + view.ViewModelObject = ViewService.FetchViewModel(view); + } + List.Add(view.ViewModelObject); + AddLookup(view.gameObject, view.ViewModelObject); + + if (OnAddView != null) + OnAddView(view); } - List.Add(view.ViewModelObject); - AddLookup(view.gameObject, view.ViewModelObject); - - if (OnAddView != null) - OnAddView(view); } } } + Collection.CollectionChanged += CollectionOnChanged; + if (!_viewFirst && IsImmediate) + { + CollectionOnChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, List)); + } } - Collection.CollectionChanged += CollectionOnChanged; - if (!_viewFirst && IsImmediate) - { - CollectionOnChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, List)); - } - } - public ViewBase SourceView { get; set; } + public ViewBase SourceView { get; set; } - private void CollectionOnChanged(object sender, NotifyCollectionChangedEventArgs changeArgs) - { - if (changeArgs.Action == NotifyCollectionChangedAction.Reset) + private void CollectionOnChanged(object sender, NotifyCollectionChangedEventArgs changeArgs) { - foreach (var item in ObjectIdLookup.Keys.ToArray()) + if (changeArgs.Action == NotifyCollectionChangedAction.Reset) { - RemoveLookup(item); - } - ObjectIdLookup.Clear(); - GameObjectLookup.Clear(); - return; - } - var targetTransform = Parent ?? SourceView.transform; - if (changeArgs.NewItems != null) - foreach (var item in changeArgs.NewItems) - { - ViewBase view = null; - if (OnCreateView != null) - { - - view = OnCreateView(item as ViewModel); - } - else + foreach (var item in ObjectIdLookup.Keys.ToArray()) { - - view = ViewName == null - ? SourceView.InstantiateView(item as ViewModel) - : SourceView.InstantiateView(ViewName, item as ViewModel) as ViewBase; + RemoveLookup(item); } - if (view != null) + ObjectIdLookup.Clear(); + GameObjectLookup.Clear(); + return; + } + var targetTransform = Parent ?? SourceView.transform; + if (changeArgs.NewItems != null) + foreach (var item in changeArgs.NewItems) { - AddLookup(view.gameObject, item as ViewModel); - view.transform.parent = targetTransform; - if (OnAddView != null) + ViewBase view = null; + if (OnCreateView != null) + { + + view = OnCreateView(item as ViewModel); + } + else + { + + view = ViewName == null + ? SourceView.InstantiateView(item as ViewModel) + : SourceView.InstantiateView(ViewName, item as ViewModel) as ViewBase; + } + if (view != null) { - OnAddView(view); + AddLookup(view.gameObject, item as ViewModel); + view.transform.parent = targetTransform; + if (OnAddView != null) + { + OnAddView(view); + } } } - } - if (changeArgs.OldItems != null && - changeArgs.OldItems.Count > 0) - { - foreach (var oldItem in changeArgs.OldItems) + if (changeArgs.OldItems != null && + changeArgs.OldItems.Count > 0) { - RemoveLookup(oldItem as ViewModel); - } + foreach (var oldItem in changeArgs.OldItems) + { + RemoveLookup(oldItem as ViewModel); + } + } } - } - public void ViewFirst() - { - _viewFirst = true; + public void ViewFirst() + { + _viewFirst = true; + } } } \ No newline at end of file diff --git a/MVVM/Views/Bindings/ModelViewPropertyBinding.cs b/MVVM/Views/Bindings/ModelViewPropertyBinding.cs index fe6eecfb..710c232a 100644 --- a/MVVM/Views/Bindings/ModelViewPropertyBinding.cs +++ b/MVVM/Views/Bindings/ModelViewPropertyBinding.cs @@ -2,79 +2,82 @@ using UniRx; using UnityEngine; -public class ModelViewPropertyBinding : Binding,IDisposable +namespace uFrame.MVVM.Bindings { - public Transform Parent { get; set; } + public class ModelViewPropertyBinding : Binding, IDisposable + { + public Transform Parent { get; set; } - public string ViewName { get; set; } + public string ViewName { get; set; } - public ViewBase SourceView { get; set; } + public ViewBase SourceView { get; set; } - public Func OnCreateView { get; set; } + public Func OnCreateView { get; set; } - public override void Bind() - { - base.Bind(); + public override void Bind() + { + base.Bind(); - Disposer = ModelProperty.SubscribeInternal(PropertyChanged); - PropertyChanged(ModelProperty.ObjectValue); - } + Disposer = ModelProperty.SubscribeInternal(PropertyChanged); + PropertyChanged(ModelProperty.ObjectValue); + } - public IDisposable Disposer { get; set; } + public IDisposable Disposer { get; set; } - private void PropertyChanged(object objectValue) - { - var target = GetTargetValueDelegate() as ViewBase; - - // If we have a previous view destroy it - if (target != null && target.ViewModelObject != objectValue) + private void PropertyChanged(object objectValue) { - UnityEngine.Object.Destroy(target.gameObject); + var target = GetTargetValueDelegate() as ViewBase; + + // If we have a previous view destroy it + if (target != null && target.ViewModelObject != objectValue) + { + UnityEngine.Object.Destroy(target.gameObject); + } + + // If the viewmodel is null + if (objectValue == null) + { + if (SetTargetValueDelegate != null) + SetTargetValueDelegate(null); + return; + } + + // If the target local variable is empty or the viewmodel doesn't match the target + if (target == null || target.ViewModelObject != objectValue) + { + // Instantiate the view + var view = string.IsNullOrEmpty(ViewName) + ? SourceView.InstantiateView(objectValue as ViewModel) + : SourceView.InstantiateView(ViewName, objectValue as ViewModel); + + // Set the local variable of the binder + if (SetTargetValueDelegate != null) + SetTargetValueDelegate(view); + + + + // Parent it defaulting to the view + view.transform.parent = Parent ?? view.transform; + } } - // If the viewmodel is null - if (objectValue == null) + public ModelViewPropertyBinding SetView(string viewName) { - if (SetTargetValueDelegate != null) - SetTargetValueDelegate(null); - return; + ViewName = viewName; + return this; } - // If the target local variable is empty or the viewmodel doesn't match the target - if (target == null || target.ViewModelObject != objectValue) + public ModelViewPropertyBinding SetParent(Transform parent) { - // Instantiate the view - var view = string.IsNullOrEmpty(ViewName) - ? SourceView.InstantiateView(objectValue as ViewModel) - : SourceView.InstantiateView(ViewName, objectValue as ViewModel); - - // Set the local variable of the binder - if (SetTargetValueDelegate != null) - SetTargetValueDelegate(view); - - - - // Parent it defaulting to the view - view.transform.parent = Parent ?? view.transform; + Parent = parent; + return this; } - } - public ModelViewPropertyBinding SetView(string viewName) - { - ViewName = viewName; - return this; - } - - public ModelViewPropertyBinding SetParent(Transform parent) - { - Parent = parent; - return this; - } + public override void Unbind() + { + Disposer.Dispose(); + base.Unbind(); + } - public override void Unbind() - { - Disposer.Dispose(); - base.Unbind(); } - } \ No newline at end of file diff --git a/MVVM/Views/Bindings/MouseEventType.cs b/MVVM/Views/Bindings/MouseEventType.cs index 8a1ac5fc..75aa9f38 100644 --- a/MVVM/Views/Bindings/MouseEventType.cs +++ b/MVVM/Views/Bindings/MouseEventType.cs @@ -1,15 +1,21 @@ -/// -/// A Unity mouse event. The comments are from the unity documentation. -/// -public enum MouseEventType +namespace uFrame.MVVM.Bindings { - OnBecameInvisible, //OnBecameInvisible is called when the renderer is no longer visible by any camera. - OnBecameVisible, //OnBecameVisible is called when the renderer became visible by any camera. - OnMouseDown, //OnMouseDown is called when the user has pressed the mouse button while over the GUIElement or Collider. - OnMouseDrag, //OnMouseDrag is called when the user has clicked on a GUIElement or Collider and is still holding down the mouse. - OnMouseEnter, //OnMouseEnter is called when the mouse entered the GUIElement or Collider. - OnMouseExit, //OnMouseExit is called when the mouse is not any longer over the GUIElement or Collider. - OnMouseOver, //OnMouseOver is called every frame while the mouse is over the GUIElement or Collider. - OnMouseUp, //OnMouseUp is called when the user has released the mouse button. - OnMouseUpAsButton, //OnMouseUpAsButton is only called when the mouse is released over the same GUIElement or Collider as it was pressed. + /// + /// A Unity mouse event. The comments are from the unity documentation. + /// + public enum MouseEventType + { + OnBecameInvisible, //OnBecameInvisible is called when the renderer is no longer visible by any camera. + OnBecameVisible, //OnBecameVisible is called when the renderer became visible by any camera. + OnMouseDown, + //OnMouseDown is called when the user has pressed the mouse button while over the GUIElement or Collider. + OnMouseDrag, + //OnMouseDrag is called when the user has clicked on a GUIElement or Collider and is still holding down the mouse. + OnMouseEnter, //OnMouseEnter is called when the mouse entered the GUIElement or Collider. + OnMouseExit, //OnMouseExit is called when the mouse is not any longer over the GUIElement or Collider. + OnMouseOver, //OnMouseOver is called every frame while the mouse is over the GUIElement or Collider. + OnMouseUp, //OnMouseUp is called when the user has released the mouse button. + OnMouseUpAsButton, + //OnMouseUpAsButton is only called when the mouse is released over the same GUIElement or Collider as it was pressed. + } } \ No newline at end of file diff --git a/MVVM/Views/Bindings/ObservableCollisionEnter2DBehaviour.cs b/MVVM/Views/Bindings/ObservableCollisionEnter2DBehaviour.cs index df431093..03ee7731 100644 --- a/MVVM/Views/Bindings/ObservableCollisionEnter2DBehaviour.cs +++ b/MVVM/Views/Bindings/ObservableCollisionEnter2DBehaviour.cs @@ -2,29 +2,32 @@ using UniRx; using UnityEngine; -public class ObservableCollisionEnter2DBehaviour : ObservableComponent +namespace uFrame.MVVM.Bindings { - private Subject onCollisionEnter2D; - - /// OnMouseEnter is called when the mouse entered the GUIElement or Collider. - public void OnCollisionEnter2D(Collision2D collision) + public class ObservableCollisionEnter2DBehaviour : ObservableComponent { - if (onCollisionEnter2D != null) onCollisionEnter2D.OnNext(collision); - } + private Subject onCollisionEnter2D; - /// OnMouseEnter is called when the mouse entered the GUIElement or Collider. - public IObservable OnCollisionEnter2DAsObservable() - { - return onCollisionEnter2D ?? (onCollisionEnter2D = new Subject()); - } + /// OnMouseEnter is called when the mouse entered the GUIElement or Collider. + public void OnCollisionEnter2D(Collision2D collision) + { + if (onCollisionEnter2D != null) onCollisionEnter2D.OnNext(collision); + } + /// OnMouseEnter is called when the mouse entered the GUIElement or Collider. + public IObservable OnCollisionEnter2DAsObservable() + { + return onCollisionEnter2D ?? (onCollisionEnter2D = new Subject()); + } -} -public class ObservableComponent : MonoBehaviour, IDisposable -{ - public void Dispose() + } + + public class ObservableComponent : MonoBehaviour, IDisposable { - Destroy(this); + public void Dispose() + { + Destroy(this); + } } } \ No newline at end of file diff --git a/MVVM/Views/Bindings/ObservableCollisionEnterBehaviour.cs b/MVVM/Views/Bindings/ObservableCollisionEnterBehaviour.cs index a9ee9f9e..0926cb7a 100644 --- a/MVVM/Views/Bindings/ObservableCollisionEnterBehaviour.cs +++ b/MVVM/Views/Bindings/ObservableCollisionEnterBehaviour.cs @@ -1,7 +1,7 @@ using UniRx; using UnityEngine; using System; - +namespace uFrame.MVVM.Bindings { public class ObservableCollisionEnterBehaviour : ObservableComponent { private Subject onCollisionEnter; @@ -19,4 +19,5 @@ public IObservable OnCollisionEnterAsObservable() } +} } \ No newline at end of file diff --git a/MVVM/Views/Bindings/ObservableCollisionExit2DBehaviour.cs b/MVVM/Views/Bindings/ObservableCollisionExit2DBehaviour.cs index 1ce2623a..857f6062 100644 --- a/MVVM/Views/Bindings/ObservableCollisionExit2DBehaviour.cs +++ b/MVVM/Views/Bindings/ObservableCollisionExit2DBehaviour.cs @@ -1,6 +1,7 @@ using UniRx; using UnityEngine; using System; +namespace uFrame.MVVM.Bindings { public class ObservableCollisionExit2DBehaviour : ObservableComponent { private Subject onCollisionExit2D; @@ -18,4 +19,5 @@ public IObservable OnCollisionExit2DAsObservable() } +} } \ No newline at end of file diff --git a/MVVM/Views/Bindings/ObservableCollisionExitBehaviour.cs b/MVVM/Views/Bindings/ObservableCollisionExitBehaviour.cs index da09fae7..08e6355a 100644 --- a/MVVM/Views/Bindings/ObservableCollisionExitBehaviour.cs +++ b/MVVM/Views/Bindings/ObservableCollisionExitBehaviour.cs @@ -1,6 +1,6 @@ using UniRx; using UnityEngine; -using System; +using System;namespace uFrame.MVVM.Bindings { public class ObservableCollisionExitBehaviour : ObservableComponent { private Subject onCollisionExit; @@ -18,4 +18,5 @@ public IObservable OnCollisionExitAsObservable() } +} } \ No newline at end of file diff --git a/MVVM/Views/Bindings/ObservableCollisionStay2DBehaviour.cs b/MVVM/Views/Bindings/ObservableCollisionStay2DBehaviour.cs index d34f614e..c333b712 100644 --- a/MVVM/Views/Bindings/ObservableCollisionStay2DBehaviour.cs +++ b/MVVM/Views/Bindings/ObservableCollisionStay2DBehaviour.cs @@ -1,6 +1,6 @@ using UniRx; using UnityEngine; -using System; +using System;namespace uFrame.MVVM.Bindings { public class ObservableCollisionStay2DBehaviour : ObservableComponent { private Subject onCollisionStay2D; @@ -18,4 +18,5 @@ public IObservable OnCollisionStay2DAsObservable() } +} } \ No newline at end of file diff --git a/MVVM/Views/Bindings/ObservableCollisionStayBehaviour.cs b/MVVM/Views/Bindings/ObservableCollisionStayBehaviour.cs index 14b8d006..e20af924 100644 --- a/MVVM/Views/Bindings/ObservableCollisionStayBehaviour.cs +++ b/MVVM/Views/Bindings/ObservableCollisionStayBehaviour.cs @@ -1,6 +1,6 @@ using UniRx; using UnityEngine; -using System; +using System;namespace uFrame.MVVM.Bindings { public class ObservableCollisionStayBehaviour : ObservableComponent { private Subject onCollisionStay; @@ -18,4 +18,5 @@ public IObservable OnCollisionStayAsObservable() } +} } \ No newline at end of file diff --git a/MVVM/Views/Bindings/ObservableFixedUpdateBehaviour.cs b/MVVM/Views/Bindings/ObservableFixedUpdateBehaviour.cs index 9e9f969f..2b87bc4f 100644 --- a/MVVM/Views/Bindings/ObservableFixedUpdateBehaviour.cs +++ b/MVVM/Views/Bindings/ObservableFixedUpdateBehaviour.cs @@ -1,6 +1,6 @@ using UniRx; using UnityEngine; -using System; +using System;namespace uFrame.MVVM.Bindings { public class ObservableFixedUpdateBehaviour : ObservableComponent { private Subject onFixedUpdate; @@ -16,4 +16,5 @@ public IObservable OnFixedUpdateAsObservable() { return onFixedUpdate ?? (onFixedUpdate = new Subject()); } +} } \ No newline at end of file diff --git a/MVVM/Views/Bindings/ObservableMouseDownBehaviour.cs b/MVVM/Views/Bindings/ObservableMouseDownBehaviour.cs index 03faba19..a38b4666 100644 --- a/MVVM/Views/Bindings/ObservableMouseDownBehaviour.cs +++ b/MVVM/Views/Bindings/ObservableMouseDownBehaviour.cs @@ -1,6 +1,6 @@ using UniRx; using UnityEngine; -using System; +using System;namespace uFrame.MVVM.Bindings { public class ObservableMouseDownBehaviour : ObservableComponent { private Subject onMouseDown; @@ -36,4 +36,5 @@ public IObservable OnDestroyAsObservable() return onDestroy ?? (onDestroy = new Subject()); } +} } \ No newline at end of file diff --git a/MVVM/Views/Bindings/ObservableMouseDragBehaviour.cs b/MVVM/Views/Bindings/ObservableMouseDragBehaviour.cs index 169fee2d..114ac000 100644 --- a/MVVM/Views/Bindings/ObservableMouseDragBehaviour.cs +++ b/MVVM/Views/Bindings/ObservableMouseDragBehaviour.cs @@ -1,6 +1,6 @@ using UniRx; using UnityEngine; -using System; +using System;namespace uFrame.MVVM.Bindings { public class ObservableMouseDragBehaviour : ObservableComponent { private Subject onMouseDrag; @@ -18,4 +18,5 @@ public IObservable OnMouseDragAsObservable() } +} } \ No newline at end of file diff --git a/MVVM/Views/Bindings/ObservableMouseEnterBehaviour.cs b/MVVM/Views/Bindings/ObservableMouseEnterBehaviour.cs index 85cefec3..33118c39 100644 --- a/MVVM/Views/Bindings/ObservableMouseEnterBehaviour.cs +++ b/MVVM/Views/Bindings/ObservableMouseEnterBehaviour.cs @@ -1,6 +1,6 @@ using UniRx; using UnityEngine; -using System; +using System;namespace uFrame.MVVM.Bindings { public class ObservableMouseEnterBehaviour : ObservableComponent { Subject onMouseEnter; @@ -16,4 +16,5 @@ public IObservable OnMouseEnterAsObservable() { return onMouseEnter ?? (onMouseEnter = new Subject()); } +} } \ No newline at end of file diff --git a/MVVM/Views/Bindings/ObservableMouseExitBehaviour.cs b/MVVM/Views/Bindings/ObservableMouseExitBehaviour.cs index 24ae12c2..aa0eeb8f 100644 --- a/MVVM/Views/Bindings/ObservableMouseExitBehaviour.cs +++ b/MVVM/Views/Bindings/ObservableMouseExitBehaviour.cs @@ -1,6 +1,6 @@ using UniRx; using UnityEngine; -using System; +using System;namespace uFrame.MVVM.Bindings { public class ObservableMouseExitBehaviour : ObservableComponent { private Subject onMouseExit; @@ -18,4 +18,5 @@ public IObservable OnMouseExitAsObservable() } +} } \ No newline at end of file diff --git a/MVVM/Views/Bindings/ObservableMouseOverBehaviour.cs b/MVVM/Views/Bindings/ObservableMouseOverBehaviour.cs index 1c7fb1bd..57669b0d 100644 --- a/MVVM/Views/Bindings/ObservableMouseOverBehaviour.cs +++ b/MVVM/Views/Bindings/ObservableMouseOverBehaviour.cs @@ -1,6 +1,6 @@ using UniRx; using UnityEngine; -using System; +using System;namespace uFrame.MVVM.Bindings { public class ObservableMouseOverBehaviour : ObservableComponent { private Subject onMouseOver; @@ -18,4 +18,5 @@ public IObservable OnMouseOverAsObservable() } +} } \ No newline at end of file diff --git a/MVVM/Views/Bindings/ObservableMouseUpAsButtonBehaviour.cs b/MVVM/Views/Bindings/ObservableMouseUpAsButtonBehaviour.cs index 905c5bf7..6ee64520 100644 --- a/MVVM/Views/Bindings/ObservableMouseUpAsButtonBehaviour.cs +++ b/MVVM/Views/Bindings/ObservableMouseUpAsButtonBehaviour.cs @@ -1,6 +1,6 @@ using UniRx; using UnityEngine; -using System; +using System;namespace uFrame.MVVM.Bindings { public class ObservableMouseUpAsButtonBehaviour : ObservableComponent { private Subject onMouseUpAsButton; @@ -18,4 +18,5 @@ public IObservable OnMouseUpAsButtonAsObservable() } +} } \ No newline at end of file diff --git a/MVVM/Views/Bindings/ObservableTriggerEnter2DBehaviour.cs b/MVVM/Views/Bindings/ObservableTriggerEnter2DBehaviour.cs index 9f50bdd9..72e8fa92 100644 --- a/MVVM/Views/Bindings/ObservableTriggerEnter2DBehaviour.cs +++ b/MVVM/Views/Bindings/ObservableTriggerEnter2DBehaviour.cs @@ -1,6 +1,6 @@ using UniRx; using UnityEngine; -using System; +using System;namespace uFrame.MVVM.Bindings { public class ObservableTriggerEnter2DBehaviour : ObservableComponent { private Subject onTriggerEnter2D; @@ -18,4 +18,5 @@ public IObservable OnTriggerEnter2DAsObservable() } +} } \ No newline at end of file diff --git a/MVVM/Views/Bindings/ObservableTriggerEnterBehaviour.cs b/MVVM/Views/Bindings/ObservableTriggerEnterBehaviour.cs index f689f855..49920aba 100644 --- a/MVVM/Views/Bindings/ObservableTriggerEnterBehaviour.cs +++ b/MVVM/Views/Bindings/ObservableTriggerEnterBehaviour.cs @@ -1,6 +1,6 @@ using UniRx; using UnityEngine; -using System; +using System;namespace uFrame.MVVM.Bindings { public class ObservableTriggerEnterBehaviour : ObservableComponent { private Subject onTriggerEnter; @@ -18,4 +18,5 @@ public IObservable OnTriggerEnterAsObservable() } +} } \ No newline at end of file diff --git a/MVVM/Views/Bindings/ObservableTriggerExit2DBehaviour.cs b/MVVM/Views/Bindings/ObservableTriggerExit2DBehaviour.cs index 73f40c90..37ae7487 100644 --- a/MVVM/Views/Bindings/ObservableTriggerExit2DBehaviour.cs +++ b/MVVM/Views/Bindings/ObservableTriggerExit2DBehaviour.cs @@ -1,6 +1,6 @@ using UniRx; using UnityEngine; -using System; +using System;namespace uFrame.MVVM.Bindings { public class ObservableTriggerExit2DBehaviour : ObservableComponent { private Subject onTriggerExit2D; @@ -18,4 +18,5 @@ public IObservable OnTriggerExit2DAsObservable() } +} } \ No newline at end of file diff --git a/MVVM/Views/Bindings/ObservableTriggerExitBehaviour.cs b/MVVM/Views/Bindings/ObservableTriggerExitBehaviour.cs index 29573185..945262d9 100644 --- a/MVVM/Views/Bindings/ObservableTriggerExitBehaviour.cs +++ b/MVVM/Views/Bindings/ObservableTriggerExitBehaviour.cs @@ -1,6 +1,6 @@ using UniRx; using UnityEngine; -using System; +using System;namespace uFrame.MVVM.Bindings { public class ObservableTriggerExitBehaviour : ObservableComponent { private Subject onTriggerExit; @@ -18,4 +18,5 @@ public IObservable OnTriggerExitAsObservable() } +} } \ No newline at end of file diff --git a/MVVM/Views/Bindings/ObservableTriggerStay2DBehaviour.cs b/MVVM/Views/Bindings/ObservableTriggerStay2DBehaviour.cs index 08402604..141c8734 100644 --- a/MVVM/Views/Bindings/ObservableTriggerStay2DBehaviour.cs +++ b/MVVM/Views/Bindings/ObservableTriggerStay2DBehaviour.cs @@ -1,6 +1,6 @@ using UniRx; using UnityEngine; -using System; +using System;namespace uFrame.MVVM.Bindings { public class ObservableTriggerStay2DBehaviour : ObservableComponent { private Subject onTriggerStay2D; @@ -16,4 +16,5 @@ public IObservable OnTriggerStay2DAsObservable() { return onTriggerStay2D ?? (onTriggerStay2D = new Subject()); } +} } \ No newline at end of file diff --git a/MVVM/Views/Bindings/ObservableTriggerStayBehaviour.cs b/MVVM/Views/Bindings/ObservableTriggerStayBehaviour.cs index c55b266a..a91d6e0e 100644 --- a/MVVM/Views/Bindings/ObservableTriggerStayBehaviour.cs +++ b/MVVM/Views/Bindings/ObservableTriggerStayBehaviour.cs @@ -1,6 +1,6 @@ using UniRx; using UnityEngine; -using System; +using System;namespace uFrame.MVVM.Bindings { public class ObservableTriggerStayBehaviour : ObservableComponent { private Subject onTriggerStay; @@ -18,4 +18,5 @@ public IObservable OnTriggerStayAsObservable() } +} } \ No newline at end of file diff --git a/MVVM/Views/Bindings/UGUIBindings.cs b/MVVM/Views/Bindings/UGUIBindings.cs index 21d4895a..015838e1 100644 --- a/MVVM/Views/Bindings/UGUIBindings.cs +++ b/MVVM/Views/Bindings/UGUIBindings.cs @@ -1,4 +1,4 @@ -#if UNITY_4_6 || UNITY_5_0 +#if UNITY_4_6 || UNITY_5_0 || UNITY_5_1 using System; using UniRx; using UnityEngine; @@ -7,7 +7,8 @@ using UnityEngine.UI; - +namespace uFrame.MVVM.Bindings +{ public static class UGUIExtensions { @@ -25,7 +26,8 @@ public static IDisposable BindButtonToHandler(this ViewBase viewBase, Button but } - public static IDisposable BindButtonToCommand(this ViewBase viewBase, Button button, Signal command) + public static IDisposable BindButtonToCommand(this ViewBase viewBase, Button button, + Signal command) where TSignalType : ViewModelCommand, new() { var d = button.AsClickObservable().Subscribe(_ => @@ -36,6 +38,7 @@ public static IDisposable BindButtonToCommand(this ViewBase viewBas }).DisposeWith(viewBase); return d; } + [Obsolete] public static IDisposable BindButtonToCommand(this ViewBase viewBase, Button button, ICommand command) { @@ -45,28 +48,34 @@ public static IDisposable BindButtonToCommand(this ViewBase viewBase, Button but }).DisposeWith(viewBase); return d; } + [Obsolete] - public static IDisposable BindButtonToCommand(this ViewBase viewBase, Button button, ViewModelCommand command, Func selector) + public static IDisposable BindButtonToCommand(this ViewBase viewBase, Button button, ViewModelCommand command, + Func selector) { throw new Exception("Must be fixed"); - + } + public static IDisposable BindTextToProperty(this ViewBase viewBase, Text input, P property) { if (input != null) { input.text = property.Value ?? string.Empty; } - + var d1 = property.Subscribe(value => - { if (input != null) input.text = value; }); + { + if (input != null) input.text = value; + }); return d1.DisposeWith(viewBase); } - - public static IDisposable BindTextToProperty(this ViewBase viewBase, Text input, P property, Func selector) + + public static IDisposable BindTextToProperty(this ViewBase viewBase, Text input, P property, + Func selector) { - + var d1 = property.Subscribe(value => { input.text = selector(value); @@ -77,11 +86,11 @@ public static IDisposable BindTextToProperty(this ViewBase viewBase, Text inp return d1.DisposeWith(viewBase); } - + public static IDisposable BindInputFieldToProperty(this ViewBase viewBase, InputField input, P property) { if (property.Value != null) - input.text = property.Value; + input.text = property.Value; var d1 = input.AsValueChangedObservable().Subscribe(value => { property.OnNext(value); @@ -99,10 +108,11 @@ public static IDisposable BindInputFieldToProperty(this ViewBase viewBase, Input }).DisposeWith(viewBase); } - public static IDisposable BindInputFieldToProperty(this ViewBase viewBase, InputField inputField, P property, Func i2pSelector, Func p2iSelector) + public static IDisposable BindInputFieldToProperty(this ViewBase viewBase, InputField inputField, + P property, Func i2pSelector, Func p2iSelector) { if (property.Value != null) - inputField.text = p2iSelector(property.Value); + inputField.text = p2iSelector(property.Value); var d1 = inputField.AsValueChangedObservable().Subscribe(value => { property.OnNext(i2pSelector(value)); @@ -119,8 +129,9 @@ public static IDisposable BindInputFieldToProperty(this ViewBase viewBase, I d2.Dispose(); }).DisposeWith(viewBase); } - - public static IDisposable BindInputFieldToHandler(this ViewBase viewBase, InputField inputField, Action handler) + + public static IDisposable BindInputFieldToHandler(this ViewBase viewBase, InputField inputField, + Action handler) { var d = inputField.AsValueChangedObservable().Subscribe(value => { @@ -129,7 +140,8 @@ public static IDisposable BindInputFieldToHandler(this ViewBase viewBase, InputF return d; } - public static IDisposable BindInputFieldToCommand(this ViewBase viewBase, InputField inputField, Signal command) where T : ViewModelCommand, new() + public static IDisposable BindInputFieldToCommand(this ViewBase viewBase, InputField inputField, + Signal command) where T : ViewModelCommand, new() { var d = inputField.AsEndEditObservable().Subscribe(_ => { @@ -138,14 +150,15 @@ public static IDisposable BindInputFieldToHandler(this ViewBase viewBase, InputF return d; } - public static IDisposable BindInputFieldToCommand(this ViewBase viewBase, InputField inputField, Signal command, Func selector) where T : ViewModelCommand, new() + public static IDisposable BindInputFieldToCommand(this ViewBase viewBase, InputField inputField, + Signal command, Func selector) where T : ViewModelCommand, new() { var d = inputField.AsEndEditObservable().Subscribe(_ => { var selected = selector(); selected.Sender = viewBase.ViewModelObject; command.OnNext(selected); - + }).DisposeWith(viewBase); return d; } @@ -159,7 +172,8 @@ public static IDisposable BindSliderToHandler(this ViewBase viewBase, Slider sli return d; } - public static IDisposable BindScrollbarToHandler(this ViewBase viewBase, Scrollbar scrollBar, Action handler) + public static IDisposable BindScrollbarToHandler(this ViewBase viewBase, Scrollbar scrollBar, + Action handler) { var d = scrollBar.AsValueChangedObservable().Subscribe(value => { @@ -168,7 +182,8 @@ public static IDisposable BindScrollbarToHandler(this ViewBase viewBase, Scrollb return d; } - public static IDisposable BindScrollbarToProperty(this ViewBase viewBase, Scrollbar scrollbar, P property, Func i2pSelector, Func p2iSelector) + public static IDisposable BindScrollbarToProperty(this ViewBase viewBase, Scrollbar scrollbar, + P property, Func i2pSelector, Func p2iSelector) { var d1 = scrollbar.AsValueChangedObservable().Subscribe(value => { @@ -205,6 +220,7 @@ public static IDisposable BindScrollbarToProperty(this ViewBase viewBase, Scroll d2.Dispose(); }).DisposeWith(viewBase); } + public static IDisposable BindSliderToProperty(this ViewBase viewBase, Slider slider, P property) { //Debug.Log("seeting slider to "+property.Value); @@ -229,7 +245,9 @@ public static IDisposable BindSliderToProperty(this ViewBase viewBase, Slider sl d2.Dispose(); }).DisposeWith(viewBase); } - public static IDisposable BindSliderToProperty(this ViewBase viewBase, Slider slider, P property, Func i2pSelector, Func p2iSelector) + + public static IDisposable BindSliderToProperty(this ViewBase viewBase, Slider slider, P property, + Func i2pSelector, Func p2iSelector) { var d1 = slider.AsValueChangedObservable().Subscribe(value => @@ -253,7 +271,7 @@ public static IDisposable BindSliderToProperty(this ViewBase viewBase, Slide } - + public static IDisposable BindToggleToHandler(this ViewBase viewBase, Toggle toggle, Action handler) { @@ -269,7 +287,7 @@ public static IDisposable BindToggleToProperty(this ViewBase viewBase, Toggle to toggle.isOn = property.Value; var d1 = toggle.AsValueChangedObservable().Subscribe(value => { - property.OnNext(value); + property.OnNext(value); }).DisposeWith(viewBase); var d2 = property.Subscribe(value => @@ -284,7 +302,8 @@ public static IDisposable BindToggleToProperty(this ViewBase viewBase, Toggle to }).DisposeWith(viewBase); } - public static IDisposable BindToggleToProperty(this ViewBase viewBase, Toggle toggle, P property, Func i2pSelector, Func p2iSelector) + public static IDisposable BindToggleToProperty(this ViewBase viewBase, Toggle toggle, P property, + Func i2pSelector, Func p2iSelector) { var d1 = toggle.AsValueChangedObservable().Subscribe(value => { @@ -343,6 +362,7 @@ public static IObservable AsValueChangedObservable(this Slider slider) return Disposable.Create(() => slider.onValueChanged.RemoveListener(unityAction)); }); } + public static IObservable AsValueChangedObservable(this Toggle toggle) { return Observable.Create(observer => @@ -352,7 +372,7 @@ public static IObservable AsValueChangedObservable(this Toggle toggle) return Disposable.Create(() => toggle.onValueChanged.RemoveListener(unityAction)); }); } - + public static IObservable AsValueChangedObservable(this Scrollbar scrollbar) { @@ -363,74 +383,93 @@ public static IObservable AsValueChangedObservable(this Scrollbar scrollb return Disposable.Create(() => scrollbar.onValueChanged.RemoveListener(unityAction)); }); } + public static IObservable AsObservableOfClick(this EventTrigger trigger) { - return trigger.AsObservableOf(EventTriggerType.PointerClick).Cast(); + return trigger.AsObservableOf(EventTriggerType.PointerClick).Cast(); } + public static IObservable AsObservableOfDrag(this EventTrigger trigger) { return trigger.AsObservableOf(EventTriggerType.Drag).Cast(); } + public static IObservable AsObservableOfBeginDrag(this EventTrigger trigger) { return trigger.AsObservableOf(EventTriggerType.BeginDrag).Cast(); } + public static IObservable AsObservableOfEndDrag(this EventTrigger trigger) { return trigger.AsObservableOf(EventTriggerType.EndDrag).Cast(); } + public static IObservable AsObservableOfMove(this EventTrigger trigger) { return trigger.AsObservableOf(EventTriggerType.Move).Cast(); } + public static IObservable AsObservableOfDrop(this EventTrigger trigger) { return trigger.AsObservableOf(EventTriggerType.Drop).Cast(); } + public static IObservable AsObservableOfPointerDown(this EventTrigger trigger) { return trigger.AsObservableOf(EventTriggerType.PointerDown).Cast(); } + public static IObservable AsObservableOfPointerUp(this EventTrigger trigger) { return trigger.AsObservableOf(EventTriggerType.PointerUp).Cast(); } + public static IObservable AsObservableOfPointerEnter(this EventTrigger trigger) { return trigger.AsObservableOf(EventTriggerType.PointerEnter).Cast(); } + public static IObservable AsObservableOfPointerExit(this EventTrigger trigger) { return trigger.AsObservableOf(EventTriggerType.PointerExit).Cast(); - } + } + public static IObservable AsObservableOfInitializePotentialDrag(this EventTrigger trigger) { - return trigger.AsObservableOf(EventTriggerType.InitializePotentialDrag).Cast(); + return + trigger.AsObservableOf(EventTriggerType.InitializePotentialDrag).Cast(); } + public static IObservable AsObservableOfScroll(this EventTrigger trigger) { return trigger.AsObservableOf(EventTriggerType.Scroll).Cast(); } + public static IObservable AsObservableOfSelect(this EventTrigger trigger) { return trigger.AsObservableOf(EventTriggerType.Select); } + public static IObservable AsObservableOfSubmit(this EventTrigger trigger) { return trigger.AsObservableOf(EventTriggerType.Submit); } + public static IObservable AsObservableOfCancel(this EventTrigger trigger) { return trigger.AsObservableOf(EventTriggerType.Cancel); } + public static IObservable AsObservableOfDeselect(this EventTrigger trigger) { return trigger.AsObservableOf(EventTriggerType.Deselect); } + public static IObservable AsObservableOfUpdateSelected(this EventTrigger trigger) { return trigger.AsObservableOf(EventTriggerType.UpdateSelected); - } + } + public static IObservable AsObservableOf(this EventTrigger trigger, EventTriggerType type) { return Observable.Create(observer => @@ -449,12 +488,13 @@ private static EventTrigger.Entry ComposeEntry(EventTriggerType type, Action(action)); return entry; } } +} #endif \ No newline at end of file diff --git a/MVVM/Views/Bindings/ViewBindings.cs b/MVVM/Views/Bindings/ViewBindings.cs index a07b80fd..02571cde 100644 --- a/MVVM/Views/Bindings/ViewBindings.cs +++ b/MVVM/Views/Bindings/ViewBindings.cs @@ -7,620 +7,670 @@ using UnityEngine.UI; using Object = UnityEngine.Object; using UniRx; -/// -/// Binding extension methods that make it easy to bind ViewModels to Views, Any method that starts with Bind{...} will properly be unbound when a view is destroyed, if not -/// it is the developers repsonsibility to properly dispose any subscriptions using the returned IDisposable. -/// -public static class ViewBindings -{ - /// - /// Bind to a ViewModel collection. - /// - /// The type that the collection contains. - /// This - /// - /// - /// - /// The binding class that allows chaining extra options. - public static ModelCollectionBinding BindCollection( - this IBindable t, ModelCollection collection, - Action onAdd, - Action onRemove - - ) - { - var binding = new ModelCollectionBinding() - { - Collection = collection, - OnAdd = onAdd, - OnRemove = onRemove, - - }; - t.AddBinding(binding); - binding.Bind(); - return binding; - } - - [Obsolete] - public static ModelCollectionBinding BindCollection( - this ViewBase t, - Func> collectionSelector) - { - var binding = new ModelCollectionBinding() - { - ModelPropertySelector = () => collectionSelector(), - }; - t.AddBinding(binding); - binding.Bind(); - return binding; - } - ///// - ///// Bind to a ViewModel collection. - ///// - ///// The type that the collection contains. - ///// This - ///// The Model Collection to bind to - ///// - ///// - ///// The binding class that allows chaining extra options. - //public static IDisposable BindCollection(this IBindable t, ObservableCollection collection, Action added, Action removed) - //{ - // NotifyCollectionChangedEventHandler collectionChanged = delegate(object sender, NotifyCollectionChangedEventArgs args) - // { - // if (args.Action == NotifyCollectionChangedAction.Reset) - // { - // if (removed != null) - // foreach (var item in collection.ToArray()) - // removed((TCollectionItemType)item); - // } - // else - // { - // if (added != null && args.NewItems != null) - // foreach (var item in args.NewItems) - // added((TCollectionItemType)item); - - // if (removed != null && args.OldItems != null) - // foreach (var item in args.OldItems) - // removed((TCollectionItemType)item); - // } - - // }; - - // collection.CollectionChanged += collectionChanged; - // collectionChanged(collection, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, collection.ToArray())); - // return t.AddBinding(Disposable.Create(() => collection.CollectionChanged -= collectionChanged)); - //} - - - - /// - /// Adds a binding to a collision, when the collusion occurs the call back will be invoked. - /// - /// - /// - /// - /// - public static IDisposable BindCollision(this ViewBase t, CollisionEventType eventType, Action action) - { - return t.AddBinding(OnCollisionObservable(t.gameObject, eventType).Subscribe(action)); - } +namespace uFrame.MVVM.Bindings +{ /// - /// Bind a Unity Collision event to a ViewModel command. + /// Binding extension methods that make it easy to bind ViewModels to Views, Any method that starts with Bind{...} will properly be unbound when a view is destroyed, if not + /// it is the developers repsonsibility to properly dispose any subscriptions using the returned IDisposable. /// - /// The view that owns the binding - /// The collision event to bind to. - /// The collision binding class that allows chaining extra options. - public static IObservable OnCollisionObservable(this GameObject t, CollisionEventType eventType) + public static class ViewBindings { - if (eventType == CollisionEventType.Enter) + /// + /// Bind to a ViewModel collection. + /// + /// The type that the collection contains. + /// This + /// + /// + /// + /// The binding class that allows chaining extra options. + public static ModelCollectionBinding BindCollection( + this IBindable t, ModelCollection collection, + Action onAdd, + Action onRemove + + ) { - return t.EnsureComponent().OnCollisionEnterAsObservable(); + var binding = new ModelCollectionBinding() + { + Collection = collection, + OnAdd = onAdd, + OnRemove = onRemove, + + }; + t.AddBinding(binding); + binding.Bind(); + return binding; } - else if (eventType == CollisionEventType.Exit) + + [Obsolete] + public static ModelCollectionBinding BindCollection( + this ViewBase t, + Func> collectionSelector) { - return t.EnsureComponent().OnCollisionExitAsObservable(); + var binding = new ModelCollectionBinding() + { + ModelPropertySelector = () => collectionSelector(), + }; + t.AddBinding(binding); + binding.Bind(); + return binding; } - else + + ///// + ///// Bind to a ViewModel collection. + ///// + ///// The type that the collection contains. + ///// This + ///// The Model Collection to bind to + ///// + ///// + ///// The binding class that allows chaining extra options. + //public static IDisposable BindCollection(this IBindable t, ObservableCollection collection, Action added, Action removed) + //{ + // NotifyCollectionChangedEventHandler collectionChanged = delegate(object sender, NotifyCollectionChangedEventArgs args) + // { + // if (args.Action == NotifyCollectionChangedAction.Reset) + // { + // if (removed != null) + // foreach (var item in collection.ToArray()) + // removed((TCollectionItemType)item); + // } + // else + // { + // if (added != null && args.NewItems != null) + // foreach (var item in args.NewItems) + // added((TCollectionItemType)item); + + // if (removed != null && args.OldItems != null) + // foreach (var item in args.OldItems) + // removed((TCollectionItemType)item); + // } + + // }; + + // collection.CollectionChanged += collectionChanged; + // collectionChanged(collection, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, collection.ToArray())); + // return t.AddBinding(Disposable.Create(() => collection.CollectionChanged -= collectionChanged)); + //} + + + + /// + /// Adds a binding to a collision, when the collusion occurs the call back will be invoked. + /// + /// + /// + /// + /// + public static IDisposable BindCollision(this ViewBase t, CollisionEventType eventType, Action action) { - return t.EnsureComponent().OnCollisionStayAsObservable(); + return t.AddBinding(OnCollisionObservable(t.gameObject, eventType).Subscribe(action)); } - } - /// - /// Bind a Unity Collision event to a ViewModel command. - /// - /// The view that owns the binding - /// The collision event to bind to. - /// The collision binding class that allows chaining extra options. - public static IObservable OnCollision2DObservable(this GameObject t, CollisionEventType eventType) - { - if (eventType == CollisionEventType.Enter) + /// + /// Bind a Unity Collision event to a ViewModel command. + /// + /// The view that owns the binding + /// The collision event to bind to. + /// The collision binding class that allows chaining extra options. + public static IObservable OnCollisionObservable(this GameObject t, CollisionEventType eventType) { - return t.EnsureComponent().OnCollisionEnter2DAsObservable(); + if (eventType == CollisionEventType.Enter) + { + return t.EnsureComponent().OnCollisionEnterAsObservable(); + } + else if (eventType == CollisionEventType.Exit) + { + return t.EnsureComponent().OnCollisionExitAsObservable(); + } + else + { + return t.EnsureComponent().OnCollisionStayAsObservable(); + } } - else if (eventType == CollisionEventType.Exit) + + /// + /// Bind a Unity Collision event to a ViewModel command. + /// + /// The view that owns the binding + /// The collision event to bind to. + /// The collision binding class that allows chaining extra options. + public static IObservable OnCollision2DObservable(this GameObject t, CollisionEventType eventType) { - return t.EnsureComponent().OnCollisionExit2DAsObservable(); + if (eventType == CollisionEventType.Enter) + { + return t.EnsureComponent().OnCollisionEnter2DAsObservable(); + } + else if (eventType == CollisionEventType.Exit) + { + return t.EnsureComponent().OnCollisionExit2DAsObservable(); + } + else + { + return t.EnsureComponent().OnCollisionStay2DAsObservable(); + } } - else + + /// + /// Bind a Unity Collision event to a ViewModel command. + /// + /// The view that owns the binding + /// The collision event to bind to. + /// The collision binding class that allows chaining extra options. + public static IObservable OnTriggerObservable(this GameObject t, CollisionEventType eventType) { - return t.EnsureComponent().OnCollisionStay2DAsObservable(); + if (eventType == CollisionEventType.Enter) + { + return t.EnsureComponent().OnTriggerEnterAsObservable(); + } + else if (eventType == CollisionEventType.Exit) + { + return t.EnsureComponent().OnTriggerExitAsObservable(); + } + else + { + return t.EnsureComponent().OnTriggerStayAsObservable(); + } } - } - /// - /// Bind a Unity Collision event to a ViewModel command. - /// - /// The view that owns the binding - /// The collision event to bind to. - /// The collision binding class that allows chaining extra options. - public static IObservable OnTriggerObservable(this GameObject t, CollisionEventType eventType) - { - if (eventType == CollisionEventType.Enter) + /// + /// Bind a Unity Collision event to a ViewModel command. + /// + /// The view that owns the binding + /// The collision event to bind to. + /// The collision binding class that allows chaining extra options. + public static IObservable OnTrigger2DObservable(this GameObject t, CollisionEventType eventType) { - return t.EnsureComponent().OnTriggerEnterAsObservable(); + if (eventType == CollisionEventType.Enter) + { + return t.EnsureComponent().OnTriggerEnter2DAsObservable(); + } + else if (eventType == CollisionEventType.Exit) + { + return t.EnsureComponent().OnTriggerExit2DAsObservable(); + } + else + { + return t.EnsureComponent().OnTriggerStay2DAsObservable(); + } } - else if (eventType == CollisionEventType.Exit) + + ///// + ///// Ensures that a component exists and returns it. + ///// + ///// + ///// + ///// + //public static T EnsureComponent(this ViewBase t) where T : Component + //{ + // return t.GetComponent() ?? t.gameObject.AddComponent(); + //} + + /// + /// Ensures that a component exists and returns it. + /// + /// + /// + /// + public static T EnsureComponent(this GameObject t) where T : MonoBehaviour { - return t.EnsureComponent().OnTriggerExitAsObservable(); + if (t.GetComponent() != null) return t.GetComponent(); + return t.AddComponent(); } - else + + /// + /// Creates a binding on collisions that filter to views only. + /// + /// + /// + /// + /// + public static IDisposable BindViewCollision(this ViewBase t, CollisionEventType eventType, + Action collision) { - return t.EnsureComponent().OnTriggerStayAsObservable(); + return t.AddBinding(OnViewCollision(t.gameObject, eventType).Subscribe(collision)); } - } - /// - /// Bind a Unity Collision event to a ViewModel command. - /// - /// The view that owns the binding - /// The collision event to bind to. - /// The collision binding class that allows chaining extra options. - public static IObservable OnTrigger2DObservable(this GameObject t, CollisionEventType eventType) - { - if (eventType == CollisionEventType.Enter) + + public static IDisposable BindViewCollisionWith(this ViewBase t, CollisionEventType eventType, + Action collision) where T : ViewBase { - return t.EnsureComponent().OnTriggerEnter2DAsObservable(); + return t.AddBinding(OnViewCollisionWith(t.gameObject, eventType).Subscribe(collision)); } - else if (eventType == CollisionEventType.Exit) + + public static IObservable OnViewCollision(this GameObject t, CollisionEventType eventType) { - return t.EnsureComponent().OnTriggerExit2DAsObservable(); + return OnCollisionObservable(t, eventType).Select(p => p.GetView()).Where(p => p != null); } - else + + public static IObservable OnViewCollisionWith(this GameObject t, CollisionEventType eventType) + where T : ViewBase { - return t.EnsureComponent().OnTriggerStay2DAsObservable(); + return OnCollisionObservable(t, eventType).Where(p => p.GetView() != null).Select(p => p.GetView()); } - } - ///// - ///// Ensures that a component exists and returns it. - ///// - ///// - ///// - ///// - //public static T EnsureComponent(this ViewBase t) where T : Component - //{ - // return t.GetComponent() ?? t.gameObject.AddComponent(); - //} - /// - /// Ensures that a component exists and returns it. - /// - /// - /// - /// - public static T EnsureComponent(this GameObject t) where T : MonoBehaviour - { - if (t.GetComponent() != null) return t.GetComponent(); - return t.AddComponent(); - } - - /// - /// Creates a binding on collisions that filter to views only. - /// - /// - /// - /// - /// - public static IDisposable BindViewCollision(this ViewBase t, CollisionEventType eventType, Action collision) - { - return t.AddBinding(OnViewCollision(t.gameObject, eventType).Subscribe(collision)); - } - - public static IDisposable BindViewCollisionWith(this ViewBase t, CollisionEventType eventType, Action collision) where T : ViewBase - { - return t.AddBinding(OnViewCollisionWith(t.gameObject, eventType).Subscribe(collision)); - } - - public static IObservable OnViewCollision(this GameObject t, CollisionEventType eventType) - { - return OnCollisionObservable(t, eventType).Select(p => p.GetView()).Where(p => p != null); - } + /// + /// Bind a input button to a ViewModel Command + /// + /// The view that owns the binding + /// The command to bind the input to + /// The name of the input button to bind to. + /// The binding class that allows chaining extra options. + [Obsolete] + public static IDisposable BindInputButton(this ViewBase t, ICommand commandSelector, string buttonName, + InputButtonEventType buttonEventType = InputButtonEventType.ButtonDown) + { + if (buttonEventType == InputButtonEventType.Button) + { + return + t.AddBinding( + t.UpdateAsObservable() + .Where(p => Input.GetButton(buttonName)) + .Subscribe(_ => t.ExecuteCommand(commandSelector))); + } + else if (buttonEventType == InputButtonEventType.ButtonDown) + { + return + t.AddBinding( + t.UpdateAsObservable() + .Where(p => Input.GetButtonDown(buttonName)) + .Subscribe(_ => t.ExecuteCommand(commandSelector))); + } - public static IObservable OnViewCollisionWith(this GameObject t, CollisionEventType eventType) where T : ViewBase - { - return OnCollisionObservable(t, eventType).Where(p => p.GetView() != null).Select(p => p.GetView()); - } + return + t.AddBinding( + t.UpdateAsObservable() + .Where(p => Input.GetButtonUp(buttonName)) + .Subscribe(_ => t.ExecuteCommand(commandSelector))); + } - /// - /// Bind a input button to a ViewModel Command - /// - /// The view that owns the binding - /// The command to bind the input to - /// The name of the input button to bind to. - /// The binding class that allows chaining extra options. - [Obsolete] - public static IDisposable BindInputButton(this ViewBase t, ICommand commandSelector, string buttonName, InputButtonEventType buttonEventType = InputButtonEventType.ButtonDown) - { - if (buttonEventType == InputButtonEventType.Button) + /// + /// Bind a key to a ViewModel Command + /// + /// The view that owns the binding + /// + /// + /// The binding class that allows chaining extra options. + public static IDisposable BindKey(this ViewBase t, Signal commandSelector, + KeyCode key, TCommandType parameter = null) where TCommandType : ViewModelCommand, new() { - return t.AddBinding(t.UpdateAsObservable().Where(p => Input.GetButton(buttonName)).Subscribe(_ => t.ExecuteCommand(commandSelector))); + return + t.AddBinding( + t.UpdateAsObservable() + .Where(p => Input.GetKey(key)) + .Subscribe( + _ => commandSelector.OnNext(parameter ?? new TCommandType() {Sender = t.ViewModelObject}))); } - else if (buttonEventType == InputButtonEventType.ButtonDown) + + /// + /// Bind a key to a ViewModel Command + /// + /// The view that owns the binding + /// + /// + /// The binding class that allows chaining extra options. + [Obsolete] + public static IDisposable BindKey(this ViewBase t, ICommand commandSelector, KeyCode key, + object parameter = null) { - return t.AddBinding(t.UpdateAsObservable().Where(p => Input.GetButtonDown(buttonName)).Subscribe(_ => t.ExecuteCommand(commandSelector))); + return + t.AddBinding( + t.UpdateAsObservable() + .Where(p => Input.GetKey(key)) + .Subscribe(_ => t.ExecuteCommand(commandSelector, parameter))); } - return t.AddBinding(t.UpdateAsObservable().Where(p => Input.GetButtonUp(buttonName)).Subscribe(_ => t.ExecuteCommand(commandSelector))); - } + /// + /// Bind a key to a ViewModel Command + /// + /// The view that owns the binding + /// The binding class that allows chaining extra options. + public static IObservable ScreenToRaycastAsObservable(this ViewBase t, Func onHit) + { + return t.UpdateAsObservable().Select(p => + { + Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); + RaycastHit hit; + if (Physics.Raycast(ray, out hit)) + { + return onHit(hit); + } + return default(T); + }); - /// - /// Bind a key to a ViewModel Command - /// - /// The view that owns the binding - /// - /// - /// The binding class that allows chaining extra options. - public static IDisposable BindKey(this ViewBase t, Signal commandSelector, KeyCode key, TCommandType parameter = null) where TCommandType : ViewModelCommand, new() - { - return t.AddBinding(t.UpdateAsObservable().Where(p => Input.GetKey(key)).Subscribe(_ => commandSelector.OnNext(parameter ?? new TCommandType() {Sender = t.ViewModelObject}))); - } - /// - /// Bind a key to a ViewModel Command - /// - /// The view that owns the binding - /// - /// - /// The binding class that allows chaining extra options. - [Obsolete] - public static IDisposable BindKey(this ViewBase t, ICommand commandSelector, KeyCode key, object parameter = null) - { - return t.AddBinding(t.UpdateAsObservable().Where(p => Input.GetKey(key)).Subscribe(_ => t.ExecuteCommand(commandSelector, parameter))); - } + } - /// - /// Bind a key to a ViewModel Command - /// - /// The view that owns the binding - /// The binding class that allows chaining extra options. - public static IObservable ScreenToRaycastAsObservable(this ViewBase t, Func onHit) - { - return t.UpdateAsObservable().Select(p => + /// + /// Binds a mouse event to a ViewModel Command. + /// + /// The view that will own the Binding. + /// The mouse event to bind to. + /// The binding class that allows chaining extra options. + public static IObservable OnMouseEvent(this ViewBase view, MouseEventType eventType) { - Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); - RaycastHit hit; - if (Physics.Raycast(ray, out hit)) + if (eventType == MouseEventType.OnMouseDown) + { + var component = view.AddComponentBinding(); + return component.OnMouseDownAsObservable(); + } + else if (eventType == MouseEventType.OnMouseDrag) { - return onHit(hit); + var component = view.AddComponentBinding(); + return component.OnMouseDragAsObservable(); } - return default(T); - }); + else if (eventType == MouseEventType.OnMouseEnter) + { + var component = view.AddComponentBinding(); + return component.OnMouseEnterAsObservable(); + } + else if (eventType == MouseEventType.OnMouseExit) + { + var component = view.AddComponentBinding(); + return component.OnMouseExitAsObservable(); - } + } + else if (eventType == MouseEventType.OnMouseOver) + { + var component = view.AddComponentBinding(); + return component.OnMouseOverAsObservable(); + } + return view.AddComponentBinding().OnMouseOverAsObservable(); + } - /// - /// Binds a mouse event to a ViewModel Command. - /// - /// The view that will own the Binding. - /// The mouse event to bind to. - /// The binding class that allows chaining extra options. - public static IObservable OnMouseEvent(this ViewBase view, MouseEventType eventType) - { - if (eventType == MouseEventType.OnMouseDown) + public static IObservable OnDestroyObservable(this GameObject gameObject) { - var component = view.AddComponentBinding(); - return component.OnMouseDownAsObservable(); + return gameObject.EnsureComponent().OnDestroyAsObservable(); } - else if (eventType == MouseEventType.OnMouseDrag) + + public static IDisposable DisposeWith(this IDisposable disposable, GameObject gameObject) { - var component = view.AddComponentBinding(); - return component.OnMouseDragAsObservable(); + return gameObject.OnDestroyObservable().First().Subscribe(p => disposable.Dispose()); } - else if (eventType == MouseEventType.OnMouseEnter) + + public static IDisposable DisposeWith(this IDisposable disposable, IBindable bindable) { - var component = view.AddComponentBinding(); - return component.OnMouseEnterAsObservable(); + return bindable.AddBinding(disposable); } - else if (eventType == MouseEventType.OnMouseExit) - { - var component = view.AddComponentBinding(); - return component.OnMouseExitAsObservable(); - } - else if (eventType == MouseEventType.OnMouseOver) + public static IDisposable DisposeWhenChanged(this IDisposable disposable, P sourceProperty, + bool onlyWhenChanged = true) { - var component = view.AddComponentBinding(); - return component.OnMouseOverAsObservable(); - } - return view.AddComponentBinding().OnMouseOverAsObservable(); - } + if (onlyWhenChanged) + { + var d = + sourceProperty.Where(p => sourceProperty.LastValue != sourceProperty.ObjectValue) + .First() + .Subscribe(_ => { disposable.Dispose(); }); + return d; + } + return sourceProperty.First().Subscribe(_ => { disposable.Dispose(); }); - public static IObservable OnDestroyObservable(this GameObject gameObject) - { - return gameObject.EnsureComponent().OnDestroyAsObservable(); - } + } - public static IDisposable DisposeWith(this IDisposable disposable, GameObject gameObject) - { - return gameObject.OnDestroyObservable().First().Subscribe(p => disposable.Dispose()); - } + /// + /// Binds a property to a view, this is the standard property binding extension method. + /// + /// + /// + /// + /// + /// + /// + public static IDisposable BindProperty(this IBindable bindable, P property, + Action changed, bool onlyWhenChanged = true) + { + changed(property.Value); + if (onlyWhenChanged) + { + return + bindable.AddBinding( + property.Where(p => property.LastValue != property.ObjectValue).Subscribe(changed)); + } - public static IDisposable DisposeWith(this IDisposable disposable, IBindable bindable) - { - return bindable.AddBinding(disposable); - } + return bindable.AddBinding(property.Subscribe(changed)); + } - public static IDisposable DisposeWhenChanged(this IDisposable disposable, P sourceProperty, bool onlyWhenChanged = true) - { - if (onlyWhenChanged) + /// + /// Binds a property to a view, this is the standard property binding extension method. + /// + /// + /// + /// + /// + /// + /// + public static IDisposable BindTwoWay(this IBindable bindable, P property, + Action changed, bool onlyWhenChanged = true) { - var d = sourceProperty.Where(p => sourceProperty.LastValue != sourceProperty.ObjectValue).First().Subscribe(_ => { disposable.Dispose(); }); - return d; - } - return sourceProperty.First().Subscribe(_ => { disposable.Dispose(); }); + changed(property.Value); + if (onlyWhenChanged) + { + return + bindable.AddBinding( + property.Where(p => property.LastValue != property.ObjectValue).Subscribe(changed)); + } - } + return bindable.AddBinding(property.Subscribe(changed)); + } - /// - /// Binds a property to a view, this is the standard property binding extension method. - /// - /// - /// - /// - /// - /// - /// - public static IDisposable BindProperty(this IBindable bindable, P property, Action changed, bool onlyWhenChanged = true) - { - changed(property.Value); - if (onlyWhenChanged) + /// + /// A wrapper of BindProperty for bindings in the diagram + /// + /// + /// + /// + /// + /// + /// + public static IDisposable BindStateProperty(this IBindable bindable, P property, + Action changed, bool onlyWhenChanged = true) { - return bindable.AddBinding(property.Where(p => property.LastValue != property.ObjectValue).Subscribe(changed)); + return BindProperty(bindable, property, changed, onlyWhenChanged); } - return bindable.AddBinding(property.Subscribe(changed)); - } - /// - /// Binds a property to a view, this is the standard property binding extension method. - /// - /// - /// - /// - /// - /// - /// - public static IDisposable BindTwoWay(this IBindable bindable, P property, Action changed, bool onlyWhenChanged = true) - { - changed(property.Value); - if (onlyWhenChanged) + public static IDisposable BindEnum(this IBindable bindable, P property, + Action enumChanged, Action enumChanged2) { - return bindable.AddBinding(property.Where(p => property.LastValue != property.ObjectValue).Subscribe(changed)); + + return null; } - return bindable.AddBinding(property.Subscribe(changed)); - } + /// + /// Binds to a commands execution and is diposed with the bindable + /// + /// + /// + /// + /// + public static IDisposable BindCommandExecuted(this ViewBase bindable, + Signal sourceCommand, Action executed) + where TCommandType : ViewModelCommand, new() + { - /// - /// A wrapper of BindProperty for bindings in the diagram - /// - /// - /// - /// - /// - /// - /// - public static IDisposable BindStateProperty(this IBindable bindable, P property, Action changed, bool onlyWhenChanged = true) - { - return BindProperty(bindable, property, changed, onlyWhenChanged); - } + return bindable.AddBinding(sourceCommand.Subscribe(executed)); + } - public static IDisposable BindEnum(this IBindable bindable, P property, - Action enumChanged, Action enumChanged2) - { + /// + /// Binds to a commands execution and is diposed with the bindable + /// + /// + /// + /// + /// + [Obsolete] + public static IDisposable BindCommandExecuted(this IBindable bindable, ICommand sourceCommand, Action onExecuted) + { + return bindable.AddBinding(sourceCommand.Subscribe(delegate { onExecuted(); })); + } - return null; - } + /// + /// The binding class that allows chaining extra options. + /// + /// The type of the model property to bind to. + /// The view that owns the binding + /// The ViewModel property to bind to. Ex. ()=>Model.MyViewModelProperty + /// Should set the value of the target. + /// The binding class that allows chaining extra options. + [Obsolete("Use other overload without function selector.")] + public static IDisposable BindProperty(this IBindable bindable, + Func> sourceProperty, Action targetSetter) + { + return bindable.AddBinding(sourceProperty().Subscribe(targetSetter)); + } - /// - /// Binds to a commands execution and is diposed with the bindable - /// - /// - /// - /// - /// - public static IDisposable BindCommandExecuted(this ViewBase bindable, Signal sourceCommand, Action executed) where TCommandType : ViewModelCommand, new() - { + ///// + ///// Bind a ViewModel Collection to a View Collection. + ///// + ///// The view that owns the binding + ///// + ///// + ///// + ///// The view collection is a list of ICollection that can be used to keep track of the Views created from the ViewModel Collection. + ///// + ///// The collection binding class that allows chaining extra options. + //[Obsolete("User other bindings, or regenerate this code.")] + //public static ModelViewModelCollectionBinding BindToViewCollection( + // this ViewBase view, + // Func> sourceViewModelCollection, + // ICollection viewCollection, bool viewFirst = false + // ) + // where TView : ViewBase + // where TViewModelType : ViewModel + //{ + // var binding = new ModelViewModelCollectionBinding() + // { + // SourceView = view, + // ModelPropertySelector = () => sourceViewModelCollection() as IObservableProperty + // } + // .SetAddHandler(v => viewCollection.Add(v as TView)) + // .SetRemoveHandler(v => viewCollection.Remove(v as TView)); + + // if (viewFirst) + // { + // binding.ViewFirst(); + // } + // view.AddBinding(binding); + // binding.Bind(); + // return binding; + //} + + ///// + ///// The binding class that allows chaining extra options. + ///// + ///// The type of the model property to bind to. + ///// The view that owns the binding + ///// Selector for the ViewModel Property + ///// Set a local variable on your view to store the bound view. + ///// Get the local variable on your view used in this binding. + ///// The binding class that allows chaining extra options. + //[Obsolete] + //public static ModelViewPropertyBinding BindToView(this ViewBase view, Func> sourceViewModelSelector, Action setLocal = null, Func getLocal = null) + //where TBindingType : ViewModel + //{ + // var binding = new ModelViewPropertyBinding() + // { + // SourceView = view, + // ModelPropertySelector = () => (IObservableProperty)sourceViewModelSelector(), + // TwoWay = false + // }; + // if (getLocal != null) + // { + // binding.GetTargetValueDelegate = () => getLocal(); + // if (setLocal == null) + // throw new Exception("When using a BindToView you must set the setLocal parameter and getLocal parameter."); + // binding.SetTargetValueDelegate = (o) => setLocal((ViewBase)o); + // } + + // view.AddBinding(binding); + // binding.Bind(); + // return binding; + //} + + public static ModelViewModelCollectionBinding BindToViewCollection(this ViewBase view, + ModelCollection viewModelCollection, Func createView, + Action added, + Action removed, + Transform parent, + bool viewFirst = false) + { + var binding = new ModelViewModelCollectionBinding() + { + SourceView = view, + ModelPropertySelector = () => viewModelCollection + }; + binding.SetParent(parent); + binding.SetAddHandler(added); + binding.SetRemoveHandler(removed); + binding.SetCreateHandler(createView); + if (viewFirst) + { + binding.ViewFirst(); + } + view.AddBinding(binding); + binding.Bind(); - return bindable.AddBinding(sourceCommand.Subscribe(executed)); - } + return binding; + } - /// - /// Binds to a commands execution and is diposed with the bindable - /// - /// - /// - /// - /// - [Obsolete] - public static IDisposable BindCommandExecuted(this IBindable bindable, ICommand sourceCommand, Action onExecuted) - { - return bindable.AddBinding(sourceCommand.Subscribe(delegate { onExecuted(); })); - } + //public static ModelViewModelCollectionBinding BindToViewCollection(this ViewBase view, + // Func> viewModelCollection, Func createView, + // Action added, + // Action removed, + // Transform parent, + // bool viewFirst = false) + //{ + // var binding = new ModelViewModelCollectionBinding() + // { + // SourceView = view, + // ModelPropertySelector = () => viewModelCollection() + // }; + // binding.SetParent(parent); + // binding.SetAddHandler(added); + // binding.SetRemoveHandler(removed); + // //binding.SetCreateHandler(createView); + // view.AddBinding(binding); + // if (viewFirst) + // { + // binding.ViewFirst(); + // } + // binding.Bind(); + + // return binding; + //} + + ///// + ///// Bind a ViewModel Collection + ///// + ///// + ///// The view that owns the binding + ///// The view collection is a list of ICollection that can be used to keep track of the Views created from the ViewModel Collection. + ///// Should the collection be initialized from the view. If false the View will be initialized to the ViewModel. + ///// The Collection Binding class that allows chaining extra options. + //[Obsolete] + //public static ModelViewModelCollectionBinding BindToViewCollection(this ViewBase view, + // Func> viewModelCollection, bool viewFirst = false) + //{ + // var binding = new ModelViewModelCollectionBinding() + // { + // SourceView = view, + // ModelPropertySelector = () => viewModelCollection() + // }; + // if (viewFirst) + // { + // binding.ViewFirst(); + // } + // view.AddBinding(binding); + // return binding; + //} - /// - /// The binding class that allows chaining extra options. - /// - /// The type of the model property to bind to. - /// The view that owns the binding - /// The ViewModel property to bind to. Ex. ()=>Model.MyViewModelProperty - /// Should set the value of the target. - /// The binding class that allows chaining extra options. - [Obsolete("Use other overload without function selector.")] - public static IDisposable BindProperty(this IBindable bindable, Func> sourceProperty, Action targetSetter) - { - return bindable.AddBinding(sourceProperty().Subscribe(targetSetter)); } - ///// - ///// Bind a ViewModel Collection to a View Collection. - ///// - ///// The view that owns the binding - ///// - ///// - ///// - ///// The view collection is a list of ICollection that can be used to keep track of the Views created from the ViewModel Collection. - ///// - ///// The collection binding class that allows chaining extra options. - //[Obsolete("User other bindings, or regenerate this code.")] - //public static ModelViewModelCollectionBinding BindToViewCollection( - // this ViewBase view, - // Func> sourceViewModelCollection, - // ICollection viewCollection, bool viewFirst = false - // ) - // where TView : ViewBase - // where TViewModelType : ViewModel - //{ - // var binding = new ModelViewModelCollectionBinding() - // { - // SourceView = view, - // ModelPropertySelector = () => sourceViewModelCollection() as IObservableProperty - // } - // .SetAddHandler(v => viewCollection.Add(v as TView)) - // .SetRemoveHandler(v => viewCollection.Remove(v as TView)); - - // if (viewFirst) - // { - // binding.ViewFirst(); - // } - // view.AddBinding(binding); - // binding.Bind(); - // return binding; - //} - - ///// - ///// The binding class that allows chaining extra options. - ///// - ///// The type of the model property to bind to. - ///// The view that owns the binding - ///// Selector for the ViewModel Property - ///// Set a local variable on your view to store the bound view. - ///// Get the local variable on your view used in this binding. - ///// The binding class that allows chaining extra options. - //[Obsolete] - //public static ModelViewPropertyBinding BindToView(this ViewBase view, Func> sourceViewModelSelector, Action setLocal = null, Func getLocal = null) - //where TBindingType : ViewModel - //{ - // var binding = new ModelViewPropertyBinding() - // { - // SourceView = view, - // ModelPropertySelector = () => (IObservableProperty)sourceViewModelSelector(), - // TwoWay = false - // }; - // if (getLocal != null) - // { - // binding.GetTargetValueDelegate = () => getLocal(); - // if (setLocal == null) - // throw new Exception("When using a BindToView you must set the setLocal parameter and getLocal parameter."); - // binding.SetTargetValueDelegate = (o) => setLocal((ViewBase)o); - // } - - // view.AddBinding(binding); - // binding.Bind(); - // return binding; - //} - - public static ModelViewModelCollectionBinding BindToViewCollection(this ViewBase view, - ModelCollection viewModelCollection, Func createView, - Action added, - Action removed, - Transform parent, - bool viewFirst = false) + public enum InputButtonEventType { - var binding = new ModelViewModelCollectionBinding() - { - SourceView = view, - ModelPropertySelector = () => viewModelCollection - }; - binding.SetParent(parent); - binding.SetAddHandler(added); - binding.SetRemoveHandler(removed); - binding.SetCreateHandler(createView); - if (viewFirst) - { - binding.ViewFirst(); - } - view.AddBinding(binding); - binding.Bind(); - - return binding; + Button, + ButtonDown, + ButtonUp } - - //public static ModelViewModelCollectionBinding BindToViewCollection(this ViewBase view, - // Func> viewModelCollection, Func createView, - // Action added, - // Action removed, - // Transform parent, - // bool viewFirst = false) - //{ - // var binding = new ModelViewModelCollectionBinding() - // { - // SourceView = view, - // ModelPropertySelector = () => viewModelCollection() - // }; - // binding.SetParent(parent); - // binding.SetAddHandler(added); - // binding.SetRemoveHandler(removed); - // //binding.SetCreateHandler(createView); - // view.AddBinding(binding); - // if (viewFirst) - // { - // binding.ViewFirst(); - // } - // binding.Bind(); - - // return binding; - //} - - ///// - ///// Bind a ViewModel Collection - ///// - ///// - ///// The view that owns the binding - ///// The view collection is a list of ICollection that can be used to keep track of the Views created from the ViewModel Collection. - ///// Should the collection be initialized from the view. If false the View will be initialized to the ViewModel. - ///// The Collection Binding class that allows chaining extra options. - //[Obsolete] - //public static ModelViewModelCollectionBinding BindToViewCollection(this ViewBase view, - // Func> viewModelCollection, bool viewFirst = false) - //{ - // var binding = new ModelViewModelCollectionBinding() - // { - // SourceView = view, - // ModelPropertySelector = () => viewModelCollection() - // }; - // if (viewFirst) - // { - // binding.ViewFirst(); - // } - // view.AddBinding(binding); - // return binding; - //} - -} - -public enum InputButtonEventType -{ - Button, - ButtonDown, - ButtonUp } \ No newline at end of file diff --git a/MVVM/Views/IView.cs b/MVVM/Views/IView.cs index 945ee257..52024cbb 100644 --- a/MVVM/Views/IView.cs +++ b/MVVM/Views/IView.cs @@ -1,26 +1,31 @@ using System; using System.Collections.Generic; +using uFrame.MVVM; +using uFrame.MVVM.Bindings; using UnityEngine; -public interface IView +namespace uFrame.MVVM +{ + public interface IView #if !UNITY_EDITOR : IViewModelObserver #endif -{ - /// - /// Gets the view model object. - /// - /// The view model object. - ViewModel ViewModelObject { get; } + { + /// + /// Gets the view model object. + /// + /// The view model object. + ViewModel ViewModelObject { get; } - /// - /// Gets the type of the view model. - /// - /// The type of the model. - Type ViewModelType { get; } + /// + /// Gets the type of the view model. + /// + /// The type of the model. + Type ViewModelType { get; } - /// - /// The name of the prefab that created this view - /// - string ViewName { get; set; } -} \ No newline at end of file + /// + /// The name of the prefab that created this view + /// + string ViewName { get; set; } + } +} diff --git a/MVVM/Views/IViewResolver.cs b/MVVM/Views/IViewResolver.cs index f7521c09..3ac39d23 100644 --- a/MVVM/Views/IViewResolver.cs +++ b/MVVM/Views/IViewResolver.cs @@ -1,18 +1,21 @@ using UnityEngine; -public interface IViewResolver +namespace uFrame.MVVM { - /// - /// Provides a prefab - /// - /// The model for the view prefab we are looking for - /// - GameObject FindView(ViewModel model); + public interface IViewResolver + { + /// + /// Provides a prefab + /// + /// The model for the view prefab we are looking for + /// + GameObject FindView(ViewModel model); - /// - /// Provides a prefab based off a viewname - /// - /// The name of the view prefab we are looking for - /// - GameObject FindView(string viewName); + /// + /// Provides a prefab based off a viewname + /// + /// The name of the view prefab we are looking for + /// + GameObject FindView(string viewName); + } } \ No newline at end of file diff --git a/MVVM/Views/View.cs b/MVVM/Views/View.cs index 25d42832..38946d60 100644 --- a/MVVM/Views/View.cs +++ b/MVVM/Views/View.cs @@ -1,45 +1,45 @@ using System; -/// -/// A View is a visual representation of a ViewModel. For example: A UI dialog, Player, Weapon, etc... -/// The ViewModel Type -/// -public abstract class View : ViewBase where TModel : ViewModel, new() +namespace uFrame.MVVM { /// - /// Gets or sets the ViewModel. Note: The setter will reinvoke the bind method. To set quietly use ViewModelObject + /// A View is a visual representation of a ViewModel. For example: A UI dialog, Player, Weapon, etc... + /// The ViewModel Type /// - public TModel Model + public abstract class View : ViewBase where TModel : ViewModel, new() { - get + /// + /// Gets or sets the ViewModel. Note: The setter will reinvoke the bind method. To set quietly use ViewModelObject + /// + public TModel Model { - return ViewModelObject as TModel; + get { return ViewModelObject as TModel; } + set + { + ViewModelObject = value; + //Bind(); + } } - set + + public override Type ViewModelType { - ViewModelObject = value; - //Bind(); + get { return typeof (TModel); } } - } - - public override Type ViewModelType - { - get { return typeof(TModel); } - } - protected sealed override void InitializeViewModel(ViewModel model) - { - InitializeViewModel(model as TModel); - } + protected override sealed void InitializeViewModel(ViewModel model) + { + InitializeViewModel(model as TModel); + } - /// - /// The method InitializeViewModel should be overriden to initialize anything from the Inspector Editor. - /// - /// - protected virtual void InitializeViewModel(TModel viewModel) - { - } + /// + /// The method InitializeViewModel should be overriden to initialize anything from the Inspector Editor. + /// + /// + protected virtual void InitializeViewModel(TModel viewModel) + { + } + } } \ No newline at end of file diff --git a/MVVM/Views/ViewBase.cs b/MVVM/Views/ViewBase.cs index 8a5bbba0..89e1c186 100644 --- a/MVVM/Views/ViewBase.cs +++ b/MVVM/Views/ViewBase.cs @@ -3,642 +3,648 @@ using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; +using uFrame.Kernel; +using uFrame.MVVM.Bindings; using UniRx; using UnityEngine; using UnityEngine.Serialization; -/// -/// The base class for a View that binds to a ViewModel -/// -public abstract partial class ViewBase : MVVMComponent, IUFSerializable, IBindable +namespace uFrame.MVVM { - - public T AddComponentBinding() where T : ObservableComponent + /// + /// The base class for a View that binds to a ViewModel + /// + public abstract partial class ViewBase : MVVMComponent, IUFSerializable, IBindable { - var component = gameObject.AddComponent(); - AddBinding(component); - return component; - } - public IDisposable AddComponentBinding(ObservableComponent component) - { - return AddBinding(component); - } + public T AddComponentBinding() where T : ObservableComponent + { + var component = gameObject.AddComponent(); + AddBinding(component); + return component; + } + + public IDisposable AddComponentBinding(ObservableComponent component) + { + return AddBinding(component); + } - #region Props - private List _bindingProviders; + #region Props + private List _bindingProviders; - private bool _bound = false; + private bool _bound = false; - [SerializeField,HideInInspector] - [FormerlySerializedAs("_resolveName")] - private string _viewModelId = ""; + [SerializeField, HideInInspector] + [FormerlySerializedAs("_resolveName")] + private string _viewModelId = ""; - [SerializeField, HideInInspector] - private bool _InjectView = false; + [SerializeField, HideInInspector] + private bool _InjectView = false; - private int _ViewId; + private int _ViewId; - [SerializeField, HideInInspector] - private bool _BindOnStart = true; - [SerializeField, HideInInspector] - private bool _DisposeOnDestroy; + [SerializeField, HideInInspector] + private bool _BindOnStart = true; + [SerializeField, HideInInspector] + private bool _DisposeOnDestroy; - [HideInInspector] - private ViewModel _Model; + [HideInInspector] + private ViewModel _Model; - [SerializeField, HideInInspector, UFGroup("View Model Properties")] - private bool _overrideViewModel; + [SerializeField, HideInInspector, UFGroup("View Model Properties")] + private bool _overrideViewModel; - #endregion + #endregion - public List BindingProviders - { - get { return _bindingProviders ?? (_bindingProviders = new List()); } - set { _bindingProviders = value; } - } + public List BindingProviders + { + get { return _bindingProviders ?? (_bindingProviders = new List()); } + set { _bindingProviders = value; } + } - /// - /// A wrapper for this view's viewmodel bindings. It is a wrapper - /// for ViewModel.Bindings[gameObject.GetInstanceId()] - /// - public List Bindings - { - get + /// + /// A wrapper for this view's viewmodel bindings. It is a wrapper + /// for ViewModel.Bindings[gameObject.GetInstanceId()] + /// + public List Bindings { - if (!ViewModelObject.Bindings.ContainsKey(ViewId)) + get { - ViewModelObject.Bindings.Add(ViewId, new List()); - } + if (!ViewModelObject.Bindings.ContainsKey(ViewId)) + { + ViewModelObject.Bindings.Add(ViewId, new List()); + } - return ViewModelObject.Bindings[ViewId]; + return ViewModelObject.Bindings[ViewId]; + } } - } - /// - /// This is the default identifier to use when "ResolveName" is not specified and it's a single instance. - /// This field is automatically overriden by the uFrame designer. - /// - public virtual string DefaultIdentifier - { - get + /// + /// This is the default identifier to use when "ResolveName" is not specified and it's a single instance. + /// This field is automatically overriden by the uFrame designer. + /// + public virtual string DefaultIdentifier { - return null; + get + { + return null; + } } - } - /// - /// The identifier used for requesting a view-model. - /// Implementation Details: - /// -If its not a multiinstance viewmodel and the "ResolveName" is empty it will use "DefaultIdentifier" property otherwise it will use - /// the resolve name. - /// - If it's a multiinstance viewmodel and the resolvename is specified it will use that. - /// - If the Use Hashcode as identifier is checked it will use this views hashcode. - /// - /// Note: If using a prefab that is placed in the Unity editor in various places around a scene and it still needs to be unique every - /// scene load (for scene loading and saving) you will want to override this property and supply a identifier that makes it unique. - /// - public virtual string Identifier - { - get + /// + /// The identifier used for requesting a view-model. + /// Implementation Details: + /// -If its not a multiinstance viewmodel and the "ResolveName" is empty it will use "DefaultIdentifier" property otherwise it will use + /// the resolve name. + /// - If it's a multiinstance viewmodel and the resolvename is specified it will use that. + /// - If the Use Hashcode as identifier is checked it will use this views hashcode. + /// + /// Note: If using a prefab that is placed in the Unity editor in various places around a scene and it still needs to be unique every + /// scene load (for scene loading and saving) you will want to override this property and supply a identifier that makes it unique. + /// + public virtual string Identifier { - if (String.IsNullOrEmpty(_viewModelId)) + get { - _viewModelId = Guid.NewGuid().ToString(); + if (String.IsNullOrEmpty(_viewModelId)) + { + _viewModelId = Guid.NewGuid().ToString(); + } + return _viewModelId; + } + set + { + if (ViewModelObject != null && ViewModelObject.Identifier == value) return; + _viewModelId = value; + //ViewModelObject = FetchViewModel(Identifier,ViewModelType); } - return _viewModelId; } - set + + public virtual void SetIdentifierSilently(string id) { - if(ViewModelObject != null && ViewModelObject.Identifier == value) return; - _viewModelId = value; - //ViewModelObject = FetchViewModel(Identifier,ViewModelType); + _viewModelId = id; } - } - public virtual void SetIdentifierSilently(string id) - { - _viewModelId = id; - } - - public bool InjectView - { - get { return _InjectView; } - set { _InjectView = value; } - } + public bool InjectView + { + get { return _InjectView; } + set { _InjectView = value; } + } - public bool BindOnStart - { - get { return _BindOnStart; } - set { _BindOnStart = value; } - } + public bool BindOnStart + { + get { return _BindOnStart; } + set { _BindOnStart = value; } + } - /// - /// A lazy loaded property for "GetInstanceId" on the game-object. - /// - public int ViewId - { - get + /// + /// A lazy loaded property for "GetInstanceId" on the game-object. + /// + public int ViewId { - if (_ViewId == 0) + get { - _ViewId = this.gameObject.GetInstanceID(); + if (_ViewId == 0) + { + _ViewId = this.gameObject.GetInstanceID(); + } + return _ViewId; } - return _ViewId; } - } - /// - /// Is this view currently bound to a view-model? - /// - public bool IsBound - { - get { return _bound; } - set { _bound = value; } - } + /// + /// Is this view currently bound to a view-model? + /// + public bool IsBound + { + get { return _bound; } + set { _bound = value; } + } - public void SetViewModelObjectSilently(ViewModel vm) - { - _Model = vm; - } - public virtual ViewModel ViewModelObject - { - get + public void SetViewModelObjectSilently(ViewModel vm) { - return _Model; + _Model = vm; } - set + public virtual ViewModel ViewModelObject { - - if (_Model == value) return; - if (value == null || IsBound) Unbind(); - - _Model = value; - - if (_Model == null) + get { - return; + return _Model; } + set + { - SetIdentifierSilently(_Model.Identifier); + if (_Model == value) return; + if (value == null || IsBound) Unbind(); - //if (OverrideViewModel) - //{ - // InitializeData(_Model); - //} + _Model = value; - SetupBindings(); //Star binding procedure + if (_Model == null) + { + return; + } - //Bind(); - } - } + SetIdentifierSilently(_Model.Identifier); - private void Reset() - { - - } + //if (OverrideViewModel) + //{ + // InitializeData(_Model); + //} - public abstract Type ViewModelType { get; } + SetupBindings(); //Star binding procedure + //Bind(); + } + } + private void Reset() + { - /// - /// The name of the prefab that created this view - /// - public string ViewName { get; set; } + } - /// - /// This method adds a binding directly onto the view-model. It will be registered with a key of this object instance id, this allows any disposable to be - /// properly disposed when this view is destroyed. - /// - /// The IDisposable that will be invoked when a view or view-model is un-bound. - /// The same disposable you pass in order to store a local destruction of the binding if needed. - /// - /// - /// this.AddBinding(MyViewModel.HealthProperty.Subscribe(HealthChanged)); - /// - public IDisposable AddBinding(IDisposable binding) - { - Bindings.Add(binding); - return binding; - } + public abstract Type ViewModelType { get; } - /// - /// This method is invoked right after the view-model has been bound. - /// - public virtual void AfterBind() - { - } - public ViewCreatedEvent CreateEventData { get; set; } + /// + /// The name of the prefab that created this view + /// + public string ViewName { get; set; } + /// + /// This method adds a binding directly onto the view-model. It will be registered with a key of this object instance id, this allows any disposable to be + /// properly disposed when this view is destroyed. + /// + /// The IDisposable that will be invoked when a view or view-model is un-bound. + /// The same disposable you pass in order to store a local destruction of the binding if needed. + /// + /// + /// this.AddBinding(MyViewModel.HealthProperty.Subscribe(HealthChanged)); + /// + public IDisposable AddBinding(IDisposable binding) + { + Bindings.Add(binding); + return binding; + } - public override void KernelLoaded() - { - base.KernelLoaded(); - this.Publish(CreateEventData ?? (CreateEventData = new ViewCreatedEvent() + /// + /// This method is invoked right after the view-model has been bound. + /// + + public virtual void AfterBind() { - IsInstantiated = false, - Scene = ParentScene, - View = this - })); - } + } + public ViewCreatedEvent CreateEventData { get; set; } - /// - /// When this view is destroy it will decrememnt the ViewModel's reference count. If the reference count reaches 0 - /// it will call "Unbind" on the viewmodel properly unbinding anything subscribed to it. - /// - protected virtual void OnDestroy() - { - if (IsBound) Unbind(); - if (!uFrameMVVMKernel.IsKernelLoaded || CreateEventData == null) return; - - this.Publish(new ViewDestroyedEvent() - { - IsInstantiated = CreateEventData.IsInstantiated, - Scene = CreateEventData.Scene, - View = this - }); - } + public override void KernelLoaded() + { + base.KernelLoaded(); + this.Publish(CreateEventData ?? (CreateEventData = new ViewCreatedEvent() + { + IsInstantiated = false, + Scene = ParentScene, + View = this + })); + } - protected virtual void OnDisable() - { - } - protected virtual void OnEnable() - { - - } - public IScene ParentScene - { - get + /// + /// When this view is destroy it will decrememnt the ViewModel's reference count. If the reference count reaches 0 + /// it will call "Unbind" on the viewmodel properly unbinding anything subscribed to it. + /// + protected virtual void OnDestroy() { + if (IsBound) Unbind(); + if (!uFrameMVVMKernel.IsKernelLoaded || CreateEventData == null) return; + this.Publish(new ViewDestroyedEvent() + { + IsInstantiated = CreateEventData.IsInstantiated, + Scene = CreateEventData.Scene, + View = this + }); + } + protected virtual void OnDisable() + { - return _parentScene ?? (_parentScene = (GetComponentInParentRecursive(this.transform, typeof(IScene)) as IScene)); } - set { _parentScene = value; } - } - private object GetComponentInParentRecursive(Transform parent, Type type) - { - if (parent== null) return null; - var theComponent = GetComponentInParent(type); - if (theComponent != null) + protected virtual void OnEnable() { - return theComponent; + } + public IScene ParentScene + { + get + { - var result = GetComponentInParentRecursive(parent.parent, type); - return result; - } - /// - /// This method is the primary method of a view. It's purpose is to provide a safe place to create subscriptions/bindings to it's view-model. When - /// this method is invoked it will allways have an instance to a view-model. - /// In this method you should subscribe to it's owned view-models properties, collections, and execute commands. - /// - /// - /// - /// var viewModel = ViewModelObject as FPSWeaponViewModel; // <-- for clarity, use property instead - /// this.BindProperty(viewModel.AmmoProperty, ammo=> { _AmmoLabel.text = ammo.ToString(); }); - /// - public virtual void Bind() - { - } - /// - /// This method is called in order to create a model for this view. In a uFrame Designer generated - /// view it will implement this method and call the "FetchViewModel" on the scene manager. - /// - [Obsolete] - public virtual ViewModel CreateModel() - { - return null; - } - /// - /// A wrapper for "InitializeViewModel" which takes the information supplied in the inspector and applies it to the view-model. - /// - /// If your viewmodel is a composite view-model containing properties of other view-models, a view can - /// be referenced, and this method will use that view's view-model. - /// - /// - /// - /// - /// - /// var myView = InstantiateView(new FPSWeaponViewModel() { Ammo=60 }); - /// myView.InitializeData(); - /// Debug.Log(myView.FPSWeapon.Ammo); - /// // output will not be 60, it will be the value specified on the views insepctor. - /// - public void InitializeData(ViewModel model) - { - InitializeViewModel(model); - - } - + return _parentScene ?? (_parentScene = (GetComponentInParentRecursive(this.transform, typeof(IScene)) as IScene)); + } + set { _parentScene = value; } + } + + private object GetComponentInParentRecursive(Transform parent, Type type) + { + if (parent == null) return null; + var theComponent = GetComponentInParent(type); + if (theComponent != null) + { + return theComponent; + } - private IScene _parentScene; + var result = GetComponentInParentRecursive(parent.parent, type); + return result; + } + /// + /// This method is the primary method of a view. It's purpose is to provide a safe place to create subscriptions/bindings to it's view-model. When + /// this method is invoked it will allways have an instance to a view-model. + /// In this method you should subscribe to it's owned view-models properties, collections, and execute commands. + /// + /// + /// + /// var viewModel = ViewModelObject as FPSWeaponViewModel; // <-- for clarity, use property instead + /// this.BindProperty(viewModel.AmmoProperty, ammo=> { _AmmoLabel.text = ammo.ToString(); }); + /// + public virtual void Bind() + { + } - - /// This method will ensure that a view-model exists and then call the bind method when it's appropriate. - public void SetupBindings() - { - if (ViewModelObject != null) + /// + /// This method is called in order to create a model for this view. In a uFrame Designer generated + /// view it will implement this method and call the "FetchViewModel" on the scene manager. + /// + [Obsolete] + public virtual ViewModel CreateModel() { - ViewModelObject.References++; + return null; } - foreach (var bindingProvider in BindingProviders) - bindingProvider.Bind(this); + /// + /// A wrapper for "InitializeViewModel" which takes the information supplied in the inspector and applies it to the view-model. + /// + /// If your viewmodel is a composite view-model containing properties of other view-models, a view can + /// be referenced, and this method will use that view's view-model. + /// + /// + /// + /// + /// + /// var myView = InstantiateView(new FPSWeaponViewModel() { Ammo=60 }); + /// myView.InitializeData(); + /// Debug.Log(myView.FPSWeapon.Ammo); + /// // output will not be 60, it will be the value specified on the views insepctor. + /// + public void InitializeData(ViewModel model) + { + InitializeViewModel(model); - PreBind(); - Bind(); - IsBound = true; - AfterBind(); - - } + } - /// Unbind any binding or disposable that has been added via the "AddBinding" method. - public virtual void Unbind() - { - DisposeBindings(); - IsBound = false; - } - public virtual void DisposeBindings() - { - if (_Model != null) + private IScene _parentScene; + + + /// This method will ensure that a view-model exists and then call the bind method when it's appropriate. + public void SetupBindings() { - _Model.References--; - foreach (var binding in Bindings) + if (ViewModelObject != null) { - binding.Dispose(); + ViewModelObject.References++; } + + foreach (var bindingProvider in BindingProviders) + bindingProvider.Bind(this); + + PreBind(); + Bind(); + IsBound = true; + AfterBind(); + } - for (int index = 0; index < BindingProviders.Count; index++) + /// Unbind any binding or disposable that has been added via the "AddBinding" method. + public virtual void Unbind() { - var bindingProvider = BindingProviders[index]; - bindingProvider.Unbind(this); + DisposeBindings(); + IsBound = false; } - } - public virtual void Write(ISerializerStream stream) - { + public virtual void DisposeBindings() + { + if (_Model != null) + { + _Model.References--; + foreach (var binding in Bindings) + { + binding.Dispose(); + } + } - //ViewModelObject.Write(stream); - stream.SerializeString("Identifier", this.Identifier); - stream.SerializeString("ViewType", this.GetType().FullName); - } + for (int index = 0; index < BindingProviders.Count; index++) + { + var bindingProvider = BindingProviders[index]; + bindingProvider.Unbind(this); + } + } - /// Will deserialize this view directly from a stream. - public virtual void Read(ISerializerStream stream) - { - this.Identifier = stream.DeserializeString("Identifier"); - } + public virtual void Write(ISerializerStream stream) + { - /// - /// This method should be overriden to Initialize the ViewModel - /// with any options specified in a unity component inspector. - /// - /// Exclude from Online - /// Exclude from Booklet - /// The model to initialize. - protected virtual void InitializeViewModel(ViewModel model) { } - - /// - /// This method is called immediately before "Bind". This method is used - /// by uFrames designer generated code to set-up defined bindings. - /// - protected virtual void PreBind() - { - } + //ViewModelObject.Write(stream); + stream.SerializeString("Identifier", this.Identifier); + stream.SerializeString("ViewType", this.GetType().FullName); + } - public bool OverrideViewModel - { - get + /// Will deserialize this view directly from a stream. + public virtual void Read(ISerializerStream stream) { - return _overrideViewModel; + this.Identifier = stream.DeserializeString("Identifier"); } - } - public bool DisposeOnDestroy - { - get { return _DisposeOnDestroy; } - set { _DisposeOnDestroy = value; } - } -} + /// + /// This method should be overriden to Initialize the ViewModel + /// with any options specified in a unity component inspector. + /// + /// Exclude from Online + /// Exclude from Booklet + /// The model to initialize. + protected virtual void InitializeViewModel(ViewModel model) { } + + /// + /// This method is called immediately before "Bind". This method is used + /// by uFrames designer generated code to set-up defined bindings. + /// + protected virtual void PreBind() + { + } + public bool OverrideViewModel + { + get + { + return _overrideViewModel; + } + } + public bool DisposeOnDestroy + { + get { return _DisposeOnDestroy; } + set { _DisposeOnDestroy = value; } + } + } -// Observable Stuff -public partial class ViewBase -{ - #region Observables - /// - /// Observable that notifies its subscribers only when the transform has changed. - /// - public Subject TransformChangedObservable - { - get { return _transformObservable ?? (_transformObservable = new Subject()); } - set { _transformObservable = value; } - } - public IObservable PositionAsObservable + // Observable Stuff + public partial class ViewBase { - get + #region Observables + + /// + /// Observable that notifies its subscribers only when the transform has changed. + /// + public Subject TransformChangedObservable { - return TransformChangedObservable.Select(p => p.transform.position).DistinctUntilChanged(); + get { return _transformObservable ?? (_transformObservable = new Subject()); } + set { _transformObservable = value; } } - } - public IObservable LocalPositionAsObservable - { - get + + public IObservable PositionAsObservable { - return TransformChangedObservable.Select(p => p.transform.localPosition).DistinctUntilChanged(); + get + { + return TransformChangedObservable.Select(p => p.transform.position).DistinctUntilChanged(); + } } - } - public IObservable LocalRotationAsObservable - { - get + public IObservable LocalPositionAsObservable { - return TransformChangedObservable.Select(p => p.transform.localRotation).DistinctUntilChanged(); + get + { + return TransformChangedObservable.Select(p => p.transform.localPosition).DistinctUntilChanged(); + } + } + public IObservable LocalRotationAsObservable + { + get + { + return TransformChangedObservable.Select(p => p.transform.localRotation).DistinctUntilChanged(); + } } - } - public IObservable RotationAsObservable - { - get + public IObservable RotationAsObservable { - return TransformChangedObservable.Select(p => p.transform.rotation).DistinctUntilChanged(); + get + { + return TransformChangedObservable.Select(p => p.transform.rotation).DistinctUntilChanged(); + } } - } - public IObservable ScaleAsObservable - { - get + public IObservable ScaleAsObservable { - return TransformChangedObservable.Select(p => p.transform.localScale).DistinctUntilChanged(); + get + { + return TransformChangedObservable.Select(p => p.transform.localScale).DistinctUntilChanged(); + } } - } - #endregion - private IObservable _positionObservable; - - private IObservable _rotationObservable; - private IObservable _scaleObservable; - private IObservable _transformChangedObservable; - private Subject _transformObservable; - Subject _updateObservable; - /// This Observable allows you to use the Update method of a monobehaviour as an observable. - /// - /// - /// this.UpdateAsObservable().Subscribe(_=>Debug.Log("Output every frame")); - /// - public IObservable UpdateAsObservable() - { - return _updateObservable ?? (_updateObservable = new Subject()); - } - - /// - /// Update is called every frame, if the MonoBehaviour is enabled. It is important to make sure that you override this method instead of just creating - /// it. uFrame uses this method as an observable, and that observable is used for all default Scene Property implementations. - /// - public virtual void Update() - { - if (_updateObservable != null) - _updateObservable.OnNext(Unit.Default); + #endregion + private IObservable _positionObservable; + + private IObservable _rotationObservable; + private IObservable _scaleObservable; + private IObservable _transformChangedObservable; + private Subject _transformObservable; + Subject _updateObservable; + /// This Observable allows you to use the Update method of a monobehaviour as an observable. + /// + /// + /// this.UpdateAsObservable().Subscribe(_=>Debug.Log("Output every frame")); + /// + public IObservable UpdateAsObservable() + { + return _updateObservable ?? (_updateObservable = new Subject()); + } - if (_transformObservable != null && transform.hasChanged) + /// + /// Update is called every frame, if the MonoBehaviour is enabled. It is important to make sure that you override this method instead of just creating + /// it. uFrame uses this method as an observable, and that observable is used for all default Scene Property implementations. + /// + public virtual void Update() { - TransformChangedObservable.OnNext(transform); - transform.hasChanged = false; + if (_updateObservable != null) + _updateObservable.OnNext(Unit.Default); + + if (_transformObservable != null && transform.hasChanged) + { + TransformChangedObservable.OnNext(transform); + transform.hasChanged = false; + } } } -} -// Obsolete Stuff -public partial class ViewBase -{ - [Obsolete] - protected ViewModel RequestViewModel(object dummy) + // Obsolete Stuff + public partial class ViewBase { - throw new NotImplementedException(); - } + [Obsolete] + protected ViewModel RequestViewModel(object dummy) + { + throw new NotImplementedException(); + } - [Obsolete] - public void ExecuteCommand(ICommand command) - { - throw new NotImplementedException(); - } + [Obsolete] + public void ExecuteCommand(ICommand command) + { + throw new NotImplementedException(); + } - [Obsolete] - public void ExecuteCommand(ICommand command, object selector) - { - throw new NotImplementedException(); + [Obsolete] + public void ExecuteCommand(ICommand command, object selector) + { + throw new NotImplementedException(); + } } -} -public class MVVMComponent : uFrameComponent -{ - public ViewBase InstantiateView(ViewModel model) + public class MVVMComponent : uFrameComponent { - return InstantiateView(model, Vector3.zero); - } + public ViewBase InstantiateView(ViewModel model) + { + return InstantiateView(model, Vector3.zero); + } - public ViewBase InstantiateView(ViewModel model, Vector3 position) - { - return InstantiateView(model, position, Quaternion.identity); - } + public ViewBase InstantiateView(ViewModel model, Vector3 position) + { + return InstantiateView(model, position, Quaternion.identity); + } - public ViewBase InstantiateView(ViewModel model, Vector3 position, Quaternion rotation) - { - return transform.InstantiateView(model, position, rotation); - } + public ViewBase InstantiateView(ViewModel model, Vector3 position, Quaternion rotation) + { + return transform.InstantiateView(model, position, rotation); + } - public ViewBase InstantiateView(GameObject prefab, ViewModel model) - { - return InstantiateView(prefab, model, Vector3.zero); - } + public ViewBase InstantiateView(GameObject prefab, ViewModel model) + { + return InstantiateView(prefab, model, Vector3.zero); + } - public ViewBase InstantiateView(GameObject prefab, ViewModel model, Vector3 position) - { - return InstantiateView(prefab, model, position, Quaternion.identity); - } + public ViewBase InstantiateView(GameObject prefab, ViewModel model, Vector3 position) + { + return InstantiateView(prefab, model, position, Quaternion.identity); + } - public ViewBase InstantiateView(string viewName, string identifier = null) - { - return InstantiateView(viewName, null, identifier); - } + public ViewBase InstantiateView(string viewName, string identifier = null) + { + return InstantiateView(viewName, null, identifier); + } - /// - /// Instantiates a view. - /// - /// The name of the prefab/view to instantiate - /// The model that will be passed to the view. - /// The instantiated view - public ViewBase InstantiateView(string viewName, ViewModel model, string identifier = null) - { - return InstantiateView(viewName, model, Vector3.zero, identifier); - } - /// - /// Instantiates a view. - /// - /// The name of the prefab/view to instantiate + /// + /// Instantiates a view. + /// + /// The name of the prefab/view to instantiate + /// The model that will be passed to the view. + /// The instantiated view + public ViewBase InstantiateView(string viewName, ViewModel model, string identifier = null) + { + return InstantiateView(viewName, model, Vector3.zero, identifier); + } + /// + /// Instantiates a view. + /// + /// The name of the prefab/view to instantiate + + /// The position to instantiate the view. + /// The instantiated view + public ViewBase InstantiateView(string viewName, Vector3 position, string identifier = null) + { + return InstantiateView(viewName, null, position, Quaternion.identity, identifier); + } - /// The position to instantiate the view. - /// The instantiated view - public ViewBase InstantiateView(string viewName, Vector3 position, string identifier = null) - { - return InstantiateView(viewName, null, position, Quaternion.identity, identifier); - } + /// + /// Instantiates a view. + /// + /// The name of the prefab/view to instantiate + /// The model that will be passed to the view. + /// The position to instantiate the view. + /// The instantiated view + public ViewBase InstantiateView(string viewName, ViewModel model, Vector3 position, string identifier = null) + { + return InstantiateView(viewName, model, position, Quaternion.identity, identifier); + } - /// - /// Instantiates a view. - /// - /// The name of the prefab/view to instantiate - /// The model that will be passed to the view. - /// The position to instantiate the view. - /// The instantiated view - public ViewBase InstantiateView(string viewName, ViewModel model, Vector3 position, string identifier = null) - { - return InstantiateView(viewName, model, position, Quaternion.identity, identifier); - } + /// + /// Instantiates a view. + /// + /// The name of the prefab/view to instantiate + /// The model that will be passed to the view. + /// The position to instantiate the view. + /// The rotation to instantiate the view with. + /// The instantiated view + public ViewBase InstantiateView(string viewName, ViewModel model, Vector3 position, + Quaternion rotation, string identifier = null) + { + return transform.InstantiateView(viewName, model, position, rotation, identifier); + } - /// - /// Instantiates a view. - /// - /// The name of the prefab/view to instantiate - /// The model that will be passed to the view. - /// The position to instantiate the view. - /// The rotation to instantiate the view with. - /// The instantiated view - public ViewBase InstantiateView(string viewName, ViewModel model, Vector3 position, - Quaternion rotation, string identifier = null) - { - return transform.InstantiateView(viewName, model, position, rotation, identifier); + /// + /// Instantiates a view. + /// + /// The prefab/view to instantiate + /// The model that will be passed to the view. + /// The position to instantiate the view. + /// The rotation to instantiate the view with. + /// The instantiated view + public ViewBase InstantiateView(GameObject prefab, ViewModel model, Vector3 position, + Quaternion rotation, string identifier = null) + { + return transform.InstantiateView(prefab, model, position, rotation, identifier); + } } - /// - /// Instantiates a view. - /// - /// The prefab/view to instantiate - /// The model that will be passed to the view. - /// The position to instantiate the view. - /// The rotation to instantiate the view with. - /// The instantiated view - public ViewBase InstantiateView(GameObject prefab, ViewModel model, Vector3 position, - Quaternion rotation, string identifier = null) - { - return transform.InstantiateView(prefab, model, position, rotation, identifier); - } -} \ No newline at end of file +} diff --git a/MVVM/Views/ViewComponent.cs b/MVVM/Views/ViewComponent.cs index 67f33f7a..0b79f0e5 100644 --- a/MVVM/Views/ViewComponent.cs +++ b/MVVM/Views/ViewComponent.cs @@ -1,36 +1,39 @@ +using uFrame.MVVM.Bindings; using UnityEngine; -public abstract class ViewComponent : MonoBehaviour, IBindingProvider +namespace uFrame.MVVM { - [SerializeField] - private ViewBase _view; - - public ViewBase View + public abstract class ViewComponent : MonoBehaviour, IBindingProvider { - get { return _view != null ? _view : (_view = this.GetView()); } - set { _view = value; } - } + [SerializeField] private ViewBase _view; - public virtual void Awake() - { - if (View == null) return; - if (View.IsBound) + public ViewBase View { - this.Bind(View); + get { return _view != null ? _view : (_view = this.GetView()); } + set { _view = value; } } - else + + public virtual void Awake() { - View.BindingProviders.Add(this); + if (View == null) return; + if (View.IsBound) + { + this.Bind(View); + } + else + { + View.BindingProviders.Add(this); + } } - } - public virtual void Bind(ViewBase view) - { + public virtual void Bind(ViewBase view) + { - } + } - public virtual void Unbind(ViewBase viewBase) - { - + public virtual void Unbind(ViewBase viewBase) + { + + } } } \ No newline at end of file diff --git a/MVVM/Views/ViewExtensions.cs b/MVVM/Views/ViewExtensions.cs index 64e2b783..01856bdf 100644 --- a/MVVM/Views/ViewExtensions.cs +++ b/MVVM/Views/ViewExtensions.cs @@ -1,127 +1,133 @@ using System; +using uFrame.Kernel; +using uFrame.MVVM.Services; using UnityEngine; using Object = UnityEngine.Object; -public static class ViewExtensions +namespace uFrame.MVVM { - public static ViewBase GetView(this GameObject go) + public static class ViewExtensions { - return go.GetComponent(); - } + public static ViewBase GetView(this GameObject go) + { + return go.GetComponent(); + } - public static T GetView(this GameObject go) where T : class - { - return GetView(go) as T; - } + public static T GetView(this GameObject go) where T : class + { + return GetView(go) as T; + } - public static ViewBase GetView(this Collision go) - { - return GetView(go.collider); - } + public static ViewBase GetView(this Collision go) + { + return GetView(go.collider); + } - public static T GetView(this Collision go) where T : class - { - return GetView(go.collider) as T; - } + public static T GetView(this Collision go) where T : class + { + return GetView(go.collider) as T; + } - public static ViewBase GetView(this Transform go) - { - return go.GetComponent(); - } + public static ViewBase GetView(this Transform go) + { + return go.GetComponent(); + } - public static T GetView(this Transform go) where T : class - { - return GetView(go) as T; - } + public static T GetView(this Transform go) where T : class + { + return GetView(go) as T; + } - public static ViewBase GetView(this Collider go) - { - return go.GetComponent(); - } + public static ViewBase GetView(this Collider go) + { + return go.GetComponent(); + } - public static T GetView(this Collider go) where T : class - { - return GetView(go) as T; - } + public static T GetView(this Collider go) where T : class + { + return GetView(go) as T; + } - public static ViewBase GetView(this MonoBehaviour go) - { - if (go == null) return null; - return go.GetComponent(); - } + public static ViewBase GetView(this MonoBehaviour go) + { + if (go == null) return null; + return go.GetComponent(); + } - public static T GetView(this MonoBehaviour go) where T : class - { - return GetView(go) as T; - } + public static T GetView(this MonoBehaviour go) where T : class + { + return GetView(go) as T; + } - public static ViewModel GetViewModel(this GameObject go) - { - var view = GetView(go); - if (view == null) - return null; - return view.ViewModelObject; - } + public static ViewModel GetViewModel(this GameObject go) + { + var view = GetView(go); + if (view == null) + return null; + return view.ViewModelObject; + } - public static T GetViewModel(this GameObject go) where T : class - { - return GetViewModel(go) as T; - } + public static T GetViewModel(this GameObject go) where T : class + { + return GetViewModel(go) as T; + } - public static T GetViewModel(this Collision go) where T : class - { - return GetViewModel(go.collider) as T; - } + public static T GetViewModel(this Collision go) where T : class + { + return GetViewModel(go.collider) as T; + } - public static ViewModel GetViewModel(this Transform go) - { - var view = GetView(go); - if (view == null) - return null; - return view.ViewModelObject; - } + public static ViewModel GetViewModel(this Transform go) + { + var view = GetView(go); + if (view == null) + return null; + return view.ViewModelObject; + } - public static T GetViewModel(this Transform go) where T : class - { - return GetViewModel(go) as T; - } + public static T GetViewModel(this Transform go) where T : class + { + return GetViewModel(go) as T; + } - public static ViewModel GetViewModel(this Collider go) - { - var view = GetView(go); - if (view == null) - return null; - return view.ViewModelObject; - } + public static ViewModel GetViewModel(this Collider go) + { + var view = GetView(go); + if (view == null) + return null; + return view.ViewModelObject; + } - public static ViewModel GetViewModel(this Collision go) - { - var view = GetView(go.collider); - if (view == null) - return null; - return view.ViewModelObject; - } + public static ViewModel GetViewModel(this Collision go) + { + var view = GetView(go.collider); + if (view == null) + return null; + return view.ViewModelObject; + } - public static T GetViewModel(this Collider go) where T : class - { - return GetViewModel(go) as T; - } + public static T GetViewModel(this Collider go) where T : class + { + return GetViewModel(go) as T; + } - public static ViewModel GetViewModel(this MonoBehaviour go) - { - var view = GetView(go); - if (view == null) - return null; - return view.ViewModelObject; - } + public static ViewModel GetViewModel(this MonoBehaviour go) + { + var view = GetView(go); + if (view == null) + return null; + return view.ViewModelObject; + } - public static T GetViewModel(this MonoBehaviour go) where T : class - { - return GetViewModel(go) as T; - } - [Obsolete] - public static ViewBase InitializeView(this Transform parent, string name, ViewModel model, GameObject viewObject,string identifier = null) - { + public static T GetViewModel(this MonoBehaviour go) where T : class + { + return GetViewModel(go) as T; + } + + [Obsolete] + public static ViewBase InitializeView(this Transform parent, string name, ViewModel model, GameObject viewObject, + string identifier = null) + { // var view = viewObject.GetComponent(); // if (view == null) @@ -160,53 +166,59 @@ public static ViewBase InitializeView(this Transform parent, string name, ViewMo // } // return view; - return null; - } - - public static ViewBase InstantiateView(this Transform parent, GameObject prefab, ViewModel model, string identifier = null) - { - return InstantiateView(parent, prefab, model, Vector3.zero,identifier); - } + return null; + } - public static ViewBase InstantiateView(this Transform parent, string viewName, ViewModel model, string identifier = null) - { - return InstantiateView(parent, viewName, model, Vector3.zero,identifier); - } + public static ViewBase InstantiateView(this Transform parent, GameObject prefab, ViewModel model, + string identifier = null) + { + return InstantiateView(parent, prefab, model, Vector3.zero, identifier); + } - public static ViewBase InstantiateView(this Transform parent, string viewName, ViewModel model, Vector3 position, string identifier = null) - { - return InstantiateView(parent, viewName, model, position, Quaternion.identity,identifier); - } + public static ViewBase InstantiateView(this Transform parent, string viewName, ViewModel model, + string identifier = null) + { + return InstantiateView(parent, viewName, model, Vector3.zero, identifier); + } - public static ViewBase InstantiateView(this Transform parent, string viewName, ViewModel model, Vector3 position, Quaternion rotation, string identifier = null) - { - return InstantiateView(parent, ViewService.ViewResolver.FindView(viewName), model, position, rotation,identifier); - } + public static ViewBase InstantiateView(this Transform parent, string viewName, ViewModel model, Vector3 position, + string identifier = null) + { + return InstantiateView(parent, viewName, model, position, Quaternion.identity, identifier); + } - public static ViewBase InstantiateView(this Transform parent, GameObject prefab, ViewModel model, Vector3 position, string identifier = null) - { - return InstantiateView(parent, prefab, model, position, Quaternion.identity,identifier); - } + public static ViewBase InstantiateView(this Transform parent, string viewName, ViewModel model, Vector3 position, + Quaternion rotation, string identifier = null) + { + return InstantiateView(parent, ViewService.ViewResolver.FindView(viewName), model, position, rotation, + identifier); + } - public static ViewBase InstantiateView(this Transform parent, - GameObject prefab, - ViewModel model, - Vector3 position, - Quaternion rotation, - string identifier = null) - { - var parentScene = parent.GetComponent(); - var command = new InstantiateViewCommand() - { - Identifier = identifier, - ViewModelObject = model, - Scene = parentScene, - Prefab = prefab - }; - uFrameMVVMKernel.EventAggregator.Publish(command); - command.Result.transform.position = position; - command.Result.transform.rotation = rotation; - return command.Result; + public static ViewBase InstantiateView(this Transform parent, GameObject prefab, ViewModel model, + Vector3 position, string identifier = null) + { + return InstantiateView(parent, prefab, model, position, Quaternion.identity, identifier); + } + + public static ViewBase InstantiateView(this Transform parent, + GameObject prefab, + ViewModel model, + Vector3 position, + Quaternion rotation, + string identifier = null) + { + var parentScene = parent.GetComponent(); + var command = new InstantiateViewCommand() + { + Identifier = identifier, + ViewModelObject = model, + Scene = parentScene, + Prefab = prefab + }; + uFrameMVVMKernel.EventAggregator.Publish(command); + command.Result.transform.position = position; + command.Result.transform.rotation = rotation; + return command.Result; // // Create the view object from the specified prefab // var prefabView = prefab.GetComponent(); @@ -220,34 +232,38 @@ public static ViewBase InstantiateView(this Transform parent, // viewObject.transform.parent = parent; //#endif // return viewObject.GetComponent(); - } + } - public static ViewBase InstantiateView(this Transform parent, ViewModel model, string identifier = null) - { - return InstantiateView(parent, model, Vector3.zero,identifier); - } + public static ViewBase InstantiateView(this Transform parent, ViewModel model, string identifier = null) + { + return InstantiateView(parent, model, Vector3.zero, identifier); + } - public static ViewBase InstantiateView(this Transform parent, ViewModel model, Vector3 position, string identifier = null) - { - return InstantiateView(parent, model, position, Quaternion.identity,identifier); - } + public static ViewBase InstantiateView(this Transform parent, ViewModel model, Vector3 position, + string identifier = null) + { + return InstantiateView(parent, model, position, Quaternion.identity, identifier); + } - public static ViewBase InstantiateView(this Transform parent, ViewModel model, Vector3 position, Quaternion rotation, string identifier = null) - { - return InstantiateView(parent, ViewService.ViewResolver.FindView(model), model, position, rotation,identifier); - } + public static ViewBase InstantiateView(this Transform parent, ViewModel model, Vector3 position, + Quaternion rotation, string identifier = null) + { + return InstantiateView(parent, ViewService.ViewResolver.FindView(model), model, position, rotation, + identifier); + } - public static bool IsView(this Transform go) where TView : ViewBase - { - if (go == null) return false; - var c = go.GetComponent(); - return c != null; - } + public static bool IsView(this Transform go) where TView : ViewBase + { + if (go == null) return false; + var c = go.GetComponent(); + return c != null; + } - public static bool IsView(this GameObject go) where TView : ViewBase - { - if (go == null) return false; - var c = go.GetComponent(); - return c != null; + public static bool IsView(this GameObject go) where TView : ViewBase + { + if (go == null) return false; + var c = go.GetComponent(); + return c != null; + } } } \ No newline at end of file diff --git a/MVVM/Views/ViewResolver.cs b/MVVM/Views/ViewResolver.cs index 9d562a2b..c0673398 100644 --- a/MVVM/Views/ViewResolver.cs +++ b/MVVM/Views/ViewResolver.cs @@ -1,37 +1,40 @@ using System; using UnityEngine; -/// -/// The View Managers responsibility is to provide prefabes based off of a view model -/// This implementation finds a prefab based off of the ViewModel's type name removing "View" from it. -/// -public class ViewResolver : IViewResolver +namespace uFrame.MVVM { /// - /// Provides a prefab + /// The View Managers responsibility is to provide prefabes based off of a view model + /// This implementation finds a prefab based off of the ViewModel's type name removing "View" from it. /// - /// The model for the view prefab we are looking for - /// - public virtual GameObject FindView(ViewModel model) + public class ViewResolver : IViewResolver { - if (model == null) + /// + /// Provides a prefab + /// + /// The model for the view prefab we are looking for + /// + public virtual GameObject FindView(ViewModel model) { - throw new ArgumentNullException("model"); + if (model == null) + { + throw new ArgumentNullException("model"); + } + return FindView(model.GetType().Name.Replace("ViewModel", "")); } - return FindView(model.GetType().Name.Replace("ViewModel", "")); - } - /// - /// Provides a prefab based off a viewname - /// - /// The name of the view prefab we are looking for - /// - public virtual GameObject FindView(string viewName) - { - var viewPrefab = (GameObject)Resources.Load(viewName); - if (viewPrefab == null) - throw new Exception(string.Format("Could not find view prefab `{0}`", viewName)); + /// + /// Provides a prefab based off a viewname + /// + /// The name of the view prefab we are looking for + /// + public virtual GameObject FindView(string viewName) + { + var viewPrefab = (GameObject) Resources.Load(viewName); + if (viewPrefab == null) + throw new Exception(string.Format("Could not find view prefab `{0}`", viewName)); - return viewPrefab; + return viewPrefab; + } } } \ No newline at end of file diff --git a/Obsolete/Computed.cs b/Obsolete/Computed.cs index 97bdf72c..2e5c02f1 100644 --- a/Obsolete/Computed.cs +++ b/Obsolete/Computed.cs @@ -1,4 +1,6 @@ using System; +using uFrame.MVVM; +using uFrame.MVVM.Bindings; #if DLL diff --git a/Obsolete/Controller.cs b/Obsolete/Controller.cs new file mode 100644 index 00000000..d531a0e3 --- /dev/null +++ b/Obsolete/Controller.cs @@ -0,0 +1,25 @@ +using System; + +namespace uFrame.MVVM +{ + + + public partial class Controller + { + [Obsolete("Use Publish")] + public void ExecuteCommand(ICommand command, object argument) + { + //CommandDispatcher.ExecuteCommand(command, argument); + } + [Obsolete("Use Publish")] + public virtual void ExecuteCommand(ICommand command) + { + //CommandDispatcher.ExecuteCommand(command, null); + } + [Obsolete("Use Publish")] + public void ExecuteCommand(ICommandWith command, TArgument argument) + { + //CommandDispatcher.ExecuteCommand(command, argument); + } + } +} \ No newline at end of file diff --git a/Obsolete/Controller.cs.meta b/Obsolete/Controller.cs.meta new file mode 100644 index 00000000..f0dd32d0 --- /dev/null +++ b/Obsolete/Controller.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: adcb104f053de62428f4831a0adb1e3c +timeCreated: 1433222996 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Obsolete/GameManager.cs b/Obsolete/GameManager.cs index 82fcb03e..be97d9cb 100644 --- a/Obsolete/GameManager.cs +++ b/Obsolete/GameManager.cs @@ -2,6 +2,9 @@ using System.Collections; using System.Collections.Generic; using System.Linq; +using uFrame.IOC; +using uFrame.Kernel; +using uFrame.MVVM; using UniRx; using UnityEngine; /// @@ -36,7 +39,7 @@ public class GameManager : MonoBehaviour public string _StartupScene; private static SceneManager _activeSceneManager; - private static IGameContainer _container; + private static IUFrameContainer _container; private static IViewResolver _viewResolver; @@ -115,13 +118,13 @@ public static SceneManager ActiveSceneManager private set { _activeSceneManager = value; } } - public static IGameContainer Container + public static IUFrameContainer Container { get { if (_container == null) { - _container = new GameContainer(); + _container = new UFrameContainer(); _container.RegisterInstance(EventAggregator); diff --git a/Obsolete/SceneContext.cs b/Obsolete/SceneContext.cs index 8a39e30c..8fc1647e 100644 --- a/Obsolete/SceneContext.cs +++ b/Obsolete/SceneContext.cs @@ -1,13 +1,16 @@ using System; using System.Collections.Generic; using System.Linq; +using uFrame.IOC; +using uFrame.MVVM; + /// /// The scene context keeps track of view-models based on their identifiers when a view has checked "Save & Load" /// [Obsolete] public class SceneContext { - private IGameContainer _container; + private IUFrameContainer _container; private Dictionary _viewModels; private Dictionary _persitantViewModels; @@ -44,7 +47,7 @@ public ViewModel this[string identifier] } } - public IGameContainer Container + public IUFrameContainer Container { get { @@ -74,7 +77,7 @@ public SceneContext() { } - public SceneContext(IGameContainer gameContainer) + public SceneContext(IUFrameContainer gameContainer) { Container = gameContainer; } diff --git a/Obsolete/SceneManager.cs b/Obsolete/SceneManager.cs index b1f0f60d..2b806d60 100644 --- a/Obsolete/SceneManager.cs +++ b/Obsolete/SceneManager.cs @@ -5,6 +5,10 @@ using UniRx; using UnityEngine; using System.Reflection; +using uFrame.IOC; +using uFrame.Kernel; +using uFrame.MVVM; +using uFrame.Serialization; /// /// The main entry point for a game that is managed and accessible via GameManager. Only one will @@ -18,29 +22,19 @@ public abstract class SceneManager : uFrameComponent, ITypeResolver [Inject] [Obsolete] - public ICommandDispatcher CommandDispatcher - { - get; - set; - } + public ICommandDispatcher CommandDispatcher { get; set; } /// /// The Dependency container for this scene. If unset then it will use "GameManager.Container". /// - public IGameContainer Container + public IUFrameContainer Container { - get - { - return GameManager.Container; - } - set - { - - } + get { return GameManager.Container; } + set { } } - /// + /// /// This method should do any set up necessary to load the controller and is invoked when you call /// GameStateManager.SwitchGame(). This should call StartCoroutine(Controller.Load) on any /// regular controller in the scene. @@ -74,6 +68,7 @@ public virtual void Reload() { GameManager.Transition(this); } + /// /// This method is called by the GameManager in order to register any dependencies. It is one of the first things /// to be invoked. This method is called before the "Load" method. @@ -117,10 +112,7 @@ protected virtual void OnDestroy() /// The settings. public static ISwitchLevelSettings Settings { - get - { - return GameManager.SwitchLevelSettings; - } + get { return GameManager.SwitchLevelSettings; } } @@ -135,10 +127,12 @@ public static ISwitchLevelSettings Settings /// The identifier of the view-model to be created or loaded (if reloading a scenes state). /// A new view model or the view-model with the identifier specified found in the scene context. [Obsolete] - public TViewModel SetupViewModel(Controller controller, string identifier) where TViewModel : ViewModel + public TViewModel SetupViewModel(Controller controller, string identifier) + where TViewModel : ViewModel { return null; } + /// /// Used by the SceneManager when creating an instance before the scene loads. This allows a view-model instance to be ready /// before a view-initializes it. This is used by the uFrame generators to initialize single isntance view-models. @@ -147,26 +141,27 @@ public TViewModel SetupViewModel(Controller controller, string ident /// The controller that the view-model should be initialized with /// The identifier of the view-model to be created or loaded (if reloading a scenes state). /// A new view model or the view-model with the identifier specified found in the scene context. - - public TViewModel SetupViewModel( string identifier) where TViewModel : ViewModel + + public TViewModel SetupViewModel(string identifier) where TViewModel : ViewModel { // Create the ViewModel - var contextViewModel = Activator.CreateInstance(typeof(TViewModel), EventAggregator) as TViewModel; + var contextViewModel = Activator.CreateInstance(typeof (TViewModel), EventAggregator) as TViewModel; contextViewModel.Identifier = identifier; // Register the instance under "ViewModel" so any single instance view-model can be accessed with ResolveAll(); Container.RegisterViewModel(contextViewModel, identifier); return contextViewModel; } - - public TViewModel CreateInstanceViewModel( string identifier) where TViewModel : ViewModel + + public TViewModel CreateInstanceViewModel(string identifier) where TViewModel : ViewModel { - var contextViewModel = Activator.CreateInstance(typeof(TViewModel), EventAggregator) as TViewModel; + var contextViewModel = Activator.CreateInstance(typeof (TViewModel), EventAggregator) as TViewModel; contextViewModel.Identifier = identifier; return contextViewModel; } [Obsolete] - public TViewModel CreateInstanceViewModel(Controller controller, string identifier) where TViewModel : ViewModel + public TViewModel CreateInstanceViewModel(Controller controller, string identifier) + where TViewModel : ViewModel { return null; } @@ -216,7 +211,11 @@ public void LoadState(ISerializerStorage storage, ISerializerStream stream) // Do something here maybe? } } - private void VoidMethod(object p) { } + + private void VoidMethod(object p) + { + } + public void SaveState(ISerializerStorage storage, ISerializerStream stream) { stream.DeepSerialize = true; @@ -249,6 +248,7 @@ public ViewModel RequestViewModel(ViewBase viewBase, Controller controller) { return null; } + /// /// This is method is called by each view in order to get it's view-model as well as place it in /// the SceneContext if the "Save & Load" option is checked in it's inspector @@ -320,7 +320,7 @@ public virtual void Initialize() { systemController.Setup(); } - + } Type ITypeResolver.GetType(string name) @@ -335,12 +335,12 @@ string ITypeResolver.SetType(Type type) object ITypeResolver.CreateInstance(string name, string identifier) { - var type = ((ITypeResolver)this).GetType(name); - + var type = ((ITypeResolver) this).GetType(name); + #if NETFX_CORE - var isViewModel = type.GetTypeInfo().IsSubclassOf(typeof(ViewModel)); + var isViewModel = type.GetTypeInfo().IsSubclassOf(typeof(ViewModel)); #else - var isViewModel = typeof(ViewModel).IsAssignableFrom(type); + var isViewModel = typeof (ViewModel).IsAssignableFrom(type); #endif // IsAssignableFrom doesn't work with winRT // typeof(ViewModel).IsAssignableFrom(type); @@ -382,6 +382,7 @@ public static void FromJson(this SceneManager sceneManager, string stateData) var stream = new JsonStream(); sceneManager.LoadState(stringStorage, stream); } + public static string ToJson(this SceneManager sceneManager) { var stringStorage = new StringSerializerStorage(); @@ -394,6 +395,7 @@ public static string ToJson(this SceneManager sceneManager) public static class ContainerExtensions { } + public class LoadedEvent { } diff --git a/Obsolete/SystemLoader.cs b/Obsolete/SystemLoader.cs index 5839f054..05a8c46c 100644 --- a/Obsolete/SystemLoader.cs +++ b/Obsolete/SystemLoader.cs @@ -1,10 +1,11 @@ using System; - -public partial class SystemLoader -{ - [Obsolete("Regenerate your diagrams or use the extension method this.CreateInstanceViewModel")] - public TViewModel CreateInstanceViewModel(string identifier) +namespace uFrame.Kernel { + public partial class SystemLoader { - throw new Exception(string.Format("{0} needs to be regenerated", this.GetType().Name)); + [Obsolete("Regenerate your diagrams or use the extension method this.CreateInstanceViewModel")] + public TViewModel CreateInstanceViewModel(string identifier) + { + throw new Exception(string.Format("{0} needs to be regenerated", this.GetType().Name)); + } } } \ No newline at end of file