public RootWithActionExtenderForm() { InitializeComponent(); MyRoot = Root.NewEditableRoot(); cslaActionExtender1.ResetActionBehaviors(MyRoot); }
public virtual bool Setup() { root = new Root(); bool carryOn = Configure(); if (!carryOn) return false; SetupResources(); ChooseSceneManager(); CreateCamera(); CreateViewports(); // Set default mipmap level (NB some APIs ignore this) TextureManager.Singleton.DefaultNumMipmaps = 5; // Create any resource listeners (for loading screens) CreateResourceListener(); LoadResources(); // Create the scene CreateScene(); CreateFrameListener(); CreateInput(); return true; }
private Root CreateRoot() { var root = new Root(); root.RenderSystem = root.GetRenderSystemByName("Direct3D9 Rendering Subsystem"); root.Initialise(false); return root; }
public override Root.Models.Content CopyDataTo(Root.Models.Content content, bool copyCollections = true) { var copy = (ServerControlWidget)base.CopyDataTo(content, copyCollections); copy.Url = Url; return copy; }
public void Test_List1ContainsList2() { var list1 = new List<object>(); var list2 = new List<object>(); var root = new Root(list1, list2); list1.Add(list2); var factory = new PropertyFactory(new PropertyProvider()); Property p = factory.CreateProperty("Root", root); // Always 2 properties in Root var complexProperty = p as ComplexProperty; Assert.IsNotNull(complexProperty); Assert.AreEqual(2, complexProperty.Properties.Count); Assert.AreEqual(1, complexProperty.Reference.Count); Assert.IsFalse(complexProperty.Reference.IsProcessed); // Both lists are of CollectionProperty var lp1 = complexProperty.Properties[0] as CollectionProperty; Assert.IsNotNull(lp1); var lp2 = complexProperty.Properties[1] as CollectionProperty; Assert.IsNotNull(lp2); Assert.AreEqual(1, lp1.Items.Count); var lp1i1 = lp1.Items[0] as CollectionProperty; Assert.IsNotNull(lp1i1); Assert.AreNotEqual(lp1i1, lp2); Assert.AreEqual(lp1i1.Reference, lp2.Reference); Assert.AreEqual(2, lp1i1.Reference.Count); }
public override Root.Models.Content CopyDataTo(Root.Models.Content content) { var copy = (ServerControlWidget)base.CopyDataTo(content); copy.Url = Url; return copy; }
public DropDown(Root root, string id, DropDownProperties properties, Menu menu) : base(root, id, properties, menu) { AddDisplayModes(); StateProperties[DropDownCommandProperties.Value] = ""; StateProperties[DropDownCommandProperties.SelectedItemId] = ""; }
protected override void OnLaunched(LaunchActivatedEventArgs e) { if (rootFrame == null) { rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; rootFrame.Navigated += OnNavigated; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } } if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar")) { var i = Windows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync(); } rootPage = new Root(rootFrame); Window.Current.Content = rootPage; SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested; SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = rootFrame.CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed; Window.Current.Activate(); }
public static void SaveModel(Root model, string outputPath, Exporter exporter) { exporter.Options.InputPath = null; exporter.Options.Input = model; exporter.Options.OutputPath = outputPath; exporter.Export(); }
/// <summary> /// Gets the replaced HTML. /// </summary> /// <param name="stringBuilder">The string builder.</param> /// <param name="model">The model.</param> /// <returns>HTML with replaced model values</returns> public override System.Text.StringBuilder GetReplacedHtml(System.Text.StringBuilder stringBuilder, Root.ViewModels.Cms.RenderPageViewModel model) { var image = model.GetPageSecondaryImageModel(); stringBuilder = GetReplacedHtml(stringBuilder, image != null ? image.PublicUrl : null); return stringBuilder; }
/// <summary> /// Setups this instance. /// </summary> /// <returns></returns> protected virtual bool Setup() { if (!string.IsNullOrEmpty(ConfigDirectory)) PluginsCfg = Path.Combine(ConfigDirectory, PluginsCfg); Root = new Root(PluginsCfg); if (!Configure()) return false; ChooseSceneManager(); CreateCamera(); CreateViewports(); TextureManager.Instance.DefaultNumMipmaps = 5; CreateResourceListener(); LoadResources(); CreateScene(); CreateFrameListeners(); InitializeInput(); DebugOverlay = new DebugOverlay(Window); DebugOverlay.AdditionalInfo = "Bilinear"; return true; }
/// <summary> /// Gets the replaced HTML. /// </summary> /// <param name="stringBuilder">The string builder.</param> /// <param name="model">The model.</param> /// <returns>HTML with replaced model values</returns> public override System.Text.StringBuilder GetReplacedHtml(System.Text.StringBuilder stringBuilder, Root.ViewModels.Cms.RenderPageViewModel model) { var blog = model.GetBlogPostModel(); stringBuilder = GetReplacedHtml(stringBuilder, blog != null ? blog.ActivationDate : (System.DateTime?)null); return stringBuilder; }
public object Fetch(SingleCriteria<Root, string> criteria) { var obj = new Root(); obj.Data = criteria.Value; obj.MarkAsOld(); return obj; }
public object Update3(Root obj) { obj.TransactionalType = _transactionalType; obj.Data = "Update"; obj.MarkAsOld(); return obj; }
public void Run(TestConfig config) { Debug.Assert(!config.IsTransient); IDatabase db = DatabaseFactory.CreateDatabase(); Tests.AssertDatabaseException( () => { var r = db.Root; }, DatabaseException.ErrorCode.DATABASE_NOT_OPENED); db = config.GetDatabase(); Root root = new Root(); var idx = db.CreateIndex<string, RecordFull>(IndexType.NonUnique); root.idx = idx; db.Root = root; db.Commit(); for (int i = 0; i < 10; i++) { var r = new RecordFull(i); idx.Put(r.StrVal, r); } var f = db.File; OsFile of = (OsFile)f; of.Close(); IDatabase db2 = config.GetDatabase(false); try { db.Close(); } catch { } db2.Close(); }
public object Fetch() { var obj = new Root(); obj.Data = "Fetch"; obj.MarkAsOld(); return obj; }
public void Go() { try { CreateRoot(); DefineResources(); CreateRenderSystem(); CreateRenderWindow(); InitializeResources(); ChooseSceneManager(); CreateScene(); CreateFrameListeners(); EnterRenderLoop(); DestroyData(); mRoot.Dispose(); mRoot = null; } catch (OperationCanceledException e) { Console.WriteLine(e); } }
public void Run(TestConfig config) { IDatabase db = config.GetDatabase(); Root root = new Root(); var r = new RecordFull(); root.r = r; db.Root = root; db.Commit(); // delete the object from the database r.Deallocate(); db.Commit(); db.Close(); db = config.GetDatabase(false); // r was explicitly deleted from the database but it's // still referenced by db.Root. Loading root object will // try to recursively load Record object but since it's // been deleted, we should get an exception Tests.AssertDatabaseException(() => { root = (Root)db.Root; }, DatabaseException.ErrorCode.DELETED_OBJECT); r = root.r; db.Close(); }
public InsertTable(Root root, string id, InsertTableProperties properties) : base(root, id, properties) { AddDisplayMode("Menu"); }
public static DTOBase Create(FileInfo info, Root root) { if (info == null) throw new ArgumentNullException("info"); if (root == null) throw new ArgumentNullException("root"); string ext = info.Extension.ToLower(); string parentPath = info.Directory.FullName.Substring(root.Directory.FullName.Length); FileDTO response; string hash = root.VolumeId + Helper.EncodePath(info.FullName.Substring(root.Directory.FullName.Length)); if (ext == ".png" || ext == ".jpg" || ext == ".jpeg" || info.Extension == ".gif") { response = new ImageDTO(); //((ImageDTO)response).Thumbnail = } else { response = new FileDTO(); } response.Read = 1; response.Write = root.IsReadOnly ? (byte)0 : (byte)1; response.Locked = root.IsReadOnly ? (byte)1 : (byte)0; response.Name = info.Name; response.Size = info.Length; response.UnixTimeStamp = (long)(info.LastWriteTimeUtc - _unixOrigin).TotalSeconds; response.Mime = Helper.GetMimeType(info); response.Hash = hash; response.ParentHash = root.VolumeId + Helper.EncodePath(parentPath.Length > 0 ? parentPath : info.Directory.Name); return response; }
public void SwitchTo(string name) { if (gameState.ContainsKey(name)) currentGameState = gameState[name]; else throw new KeyNotFoundException("Can't find gamestate" + name); }
/// <summary> /// Gets the replaced HTML. /// </summary> /// <param name="stringBuilder">The string builder.</param> /// <param name="model">The model.</param> /// <returns>HTML with replaced model values</returns> public override System.Text.StringBuilder GetReplacedHtml(System.Text.StringBuilder stringBuilder, Root.ViewModels.Cms.RenderPageViewModel model) { var author = model.GetBlogPostAuthorModel(); stringBuilder = GetReplacedHtml(stringBuilder, author != null ? author.Name : null); return stringBuilder; }
public Root CreateXmlDocument(SearchInputService input) { try { CrawlerHelper helper = new CrawlerHelper(); Root root = new Root(); root.Departure = input.DepartureCode; root.Arrival = input.ArrivalCode; CookieCollection cookieCollection = helper.getCookieCollection("https://ameliaweb5.intelisys.ca/VietJet/ameliapost.aspx?lang=vi", "POST", getPostdata(input)); HtmlDocument htmld = helper.getDocument("https://ameliaweb5.intelisys.ca/VietJet/ameliapost.aspx?lang=vi", "POST", getPostdata2(input), cookieCollection); root.outBound = new OutInBound(); root.inBound = new OutInBound(); root.AirLine = AirLineName.vietJetAir; HtmlNodeCollection collection; try { collection = htmld.DocumentNode.SelectNodes("//div[@id='toDepDiv']/div[@id='travOpsMain']/table[1]/tr[7]/td/table[1]/tr"); root.outBound.Items = getitems(input.DepartTime,input, collection); } catch { } //chieu ve if (input.IsRoundTrip) { collection = htmld.DocumentNode.SelectNodes("//div[@id='toRetDiv']/div[@id='travOpsMain']/table[1]/tr[7]/td/table[1]/tr"); root.inBound.Items = getitems(input.ReturnTime,input, collection); } return root; } catch { return null; } }
/// <summary> /// Gets the replaced HTML. /// </summary> /// <param name="stringBuilder">The string builder.</param> /// <param name="model">The model.</param> /// <returns>HTML with replaced model values</returns> public override System.Text.StringBuilder GetReplacedHtml(System.Text.StringBuilder stringBuilder, Root.ViewModels.Cms.RenderPageViewModel model) { var category = model.GetPageCategoryModel(); stringBuilder = GetReplacedHtml(stringBuilder, category != null ? category.Name : null); return stringBuilder; }
/// <summary> /// Creates a GalleryButton control. /// </summary> /// <param name="root">The Root that this control is in</param> /// <param name="id">The ID of this control</param> /// <param name="properties">The properties of this control</param> /// <param name="dims">The dimensions of this control</param> public GalleryButton(Root root, string id, GalleryButtonProperties properties, GalleryElementDimensions dims) : base(root, id, properties) { AddDisplayMode("Large"); AddDisplayMode("Menu"); ElementDimensions = dims; }
/// <summary> /// Initialises the render system, tells it to use directx, windowed, etc /// </summary> private static RenderSystem InitRenderSystem(Root root) { Launch.Log("[Loading] Creating RenderSystem..."); if (root.RenderSystem == null) { var renderSystem = root.GetRenderSystemByName("Direct3D9 Rendering Subsystem"); renderSystem.SetConfigOption("Full Screen", Options.Get("Full Screen")); renderSystem.SetConfigOption("Floating-point mode", Options.Get("Floating-point mode")); renderSystem.SetConfigOption("VSync", Options.Get("VSync")); renderSystem.SetConfigOption("VSync Interval", Options.Get("VSync Interval")); renderSystem.SetConfigOption("FSAA", Options.Get("FSAA")); renderSystem.SetConfigOption("Video Mode", Options.Get("Video Mode")); renderSystem.SetConfigOption("sRGB Gamma Conversion", Options.Get("sRGB Gamma Conversion")); root.RenderSystem = renderSystem; } #if DEBUG // print out the things we can support var renderList = root.GetAvailableRenderers(); foreach (var renderSystem in renderList) { Launch.Log("\n**** Available options for Render System: " + renderSystem.Name + " ****"); foreach (var option in renderSystem.GetConfigOptions()) { Launch.Log("\t" + option.Key); foreach (var p in option.Value.possibleValues) { Launch.Log("\t\t" + p); } } Launch.Log("***********************************"); } #endif return root.RenderSystem; }
static public IDbConnection CreateConnection(Root dbRoot, string database) { IDbConnection cn = PostgreSQLDatabases.CreateConnection(dbRoot.ConnectionString); cn.Open(); cn.ChangeDatabase(database); return cn; }
public static DTOBase Create(FileInfo info, Root root) { if (info == null) throw new ArgumentNullException("info"); if (root == null) throw new ArgumentNullException("root"); string parentPath = info.Directory.FullName.Substring(root.Directory.FullName.Length); string relativePath = info.FullName.Substring(root.Directory.FullName.Length); FileDTO response; if (root.CanCreateThumbnail(info)) { ImageDTO imageResponse = new ImageDTO(); imageResponse.Thumbnail = root.GetExistingThumbHash(info) ?? (object)1; var dim = root.GetImageDimension(info); imageResponse.Dimension = string.Format("{0}x{1}", dim.Width, dim.Height); response = imageResponse; } else { response = new FileDTO(); } response.Read = 1; response.Write = root.IsReadOnly ? (byte)0 : (byte)1; response.Locked = (root.LockedFolders.Any(f => f == info.Directory.Name) || root.IsLocked) ? (byte)1 : (byte)0; response.Name = info.Name; response.Size = info.Length; response.UnixTimeStamp = (long)(info.LastWriteTimeUtc - _unixOrigin).TotalSeconds; response.Mime = Helper.GetMimeType(info); response.Hash = root.VolumeId + Helper.EncodePath(relativePath); response.ParentHash = root.VolumeId + Helper.EncodePath(parentPath.Length > 0 ? parentPath : info.Directory.Name); return response; }
public static void DeSerialisoiIdSeach(string imdbID, ref Root leffat) { string url = "http://www.omdbapi.com/?i=" + imdbID + "&r=xml&plot=full"; XmlSerializer deserializer = new XmlSerializer(typeof(Root)); try { HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url); myRequest.AllowAutoRedirect = true; myRequest.Method = "GET"; myRequest.Timeout = 6000; WebResponse myResponse = myRequest.GetResponse(); XmlTextReader reader = new XmlTextReader(myResponse.GetResponseStream()); leffat = (Root)deserializer.Deserialize(reader); reader.Close(); myResponse.Close(); } catch (Exception ex) { throw ex; } finally { } }
public ToggleButton(Root root, string id, BooleanControlProperties properties) : base(root, id, properties) { _id = id; AddDisplayModes(); StateProperties[ToggleButtonCommandProperties.On] = false.ToString(); }
/// <summary> /// Remove all entities from screen. /// </summary> public void Clear() { Root.ClearChildren(); }
public void Save() => Root.Save();
internal override string GetFilterSortId(Root root) => Item.GetNameId(root);
public override (string, string) GetKindNameId(Root root) => Item.GetKindNameId(root);
/// <summary> /// Stops profiling /// </summary> /// <returns>The root profiler</returns> public static Profiler StopProfiling() { Root.Stop(); return(Root); }
/// <inheritdoc /> protected override void OnLeftMouseButtonUp() { // Skip if was controlling mouse or mouse is not over the area if (_prevInput.IsControllingMouse || !Bounds.Contains(ref _viewMousePos)) { return; } if (TransformGizmo.IsActive) { // Ensure player is not moving objects if (TransformGizmo.ActiveAxis != TransformGizmo.Axis.None) { return; } } else { // For now just pick objects in transform gizmo mode return; } // Get mouse ray and try to hit any object var ray = MouseRay; var view = new Ray(ViewPosition, ViewDirection); var hit = _window.Graph.Root.RayCast(ref ray, ref view, out _, SceneGraphNode.RayCastData.FlagTypes.SkipColliders); // Update selection if (hit != null) { // For child actor nodes (mesh, link or sth) we need to select it's owning actor node first or any other child node (but not a child actor) if (hit is ActorChildNode actorChildNode) { var parentNode = actorChildNode.ParentNode; bool canChildBeSelected = _window.Selection.Contains(parentNode); if (!canChildBeSelected) { for (int i = 0; i < parentNode.ChildNodes.Count; i++) { if (_window.Selection.Contains(parentNode.ChildNodes[i])) { canChildBeSelected = true; break; } } } if (!canChildBeSelected) { // Select parent hit = parentNode; } } bool addRemove = Root.GetKey(KeyboardKeys.Control); bool isSelected = _window.Selection.Contains(hit); if (addRemove) { if (isSelected) { _window.Deselect(hit); } else { _window.Select(hit, true); } } else { _window.Select(hit); } } else { _window.Deselect(); } // Keep focus Focus(); base.OnLeftMouseButtonUp(); }
internal static Root ParseJson(string json) { // JsonUtility sometimes creates non-null default instances of objects-type members // even though there are none in the original JSON. // This work-around makes sure not existent JSON nodes will be null in the result. #if MEASURE_TIMINGS var stopWatch = new Stopwatch(); stopWatch.Start(); #endif Root root = null; // Step one: main JSON parsing Profiler.BeginSample("JSON main"); try { root = JsonUtility.FromJson <Root>(json); } catch (System.ArgumentException) { return(null); } if (root == null) { return(null); } Profiler.EndSample(); // Step two: // detect, if a secondary null-check is necessary. Profiler.BeginSample("JSON extension check"); bool check = false; if (root.materials != null) { for (int i = 0; i < root.materials.Length; i++) { var mat = root.materials[i]; // mat.extension is always set (not null), because JsonUtility constructs a default // if any of mat.extension's members is not null, it is because there was // a legit extensions node in JSON => we have to check which ones if (mat.extensions.KHR_materials_unlit != null) { check = true; } else { // otherwise dump the wrongfully constructed MaterialExtension mat.extensions = null; } } } if (root.accessors != null) { for (int i = 0; i < root.accessors.Length; i++) { var accessor = root.accessors[i]; if (accessor.sparse.indices == null || accessor.sparse.values == null) { // If indices and values members are null, `sparse` is likely // an auto-instance by the JsonUtility and not present in JSON. // Therefore we remove it: accessor.sparse = null; } #if GLTFAST_SAFE else { // This is very likely a valid sparse accessor. // However, an empty sparse property ( "sparse": {} ) would break // glTFast, so better do a thorough follow-up check check = true; } #endif // GLTFAST_SAFE } } #if DRACO_UNITY if (!check && root.meshes != null) { foreach (var mesh in root.meshes) { if (mesh.primitives != null) { foreach (var primitive in mesh.primitives) { if (primitive.extensions?.KHR_draco_mesh_compression != null) { check = true; break; } } } } } #endif Profiler.EndSample(); // Step three: // If we have to make an explicit check, parse the JSON again with a // different, minimal Root class, where class members are serialized to // the type string. In case the string is null, there's no JSON node. // Otherwise the string would be empty (""). if (check) { Profiler.BeginSample("JSON secondary"); var fakeRoot = JsonUtility.FromJson <FakeSchema.Root>(json); if (root.materials != null) { for (var i = 0; i < root.materials.Length; i++) { var mat = root.materials[i]; if (mat.extensions == null) { continue; } Assert.AreEqual(mat.name, fakeRoot.materials[i].name); var fake = fakeRoot.materials[i].extensions; if (fake.KHR_materials_unlit == null) { mat.extensions.KHR_materials_unlit = null; } if (fake.KHR_materials_pbrSpecularGlossiness == null) { mat.extensions.KHR_materials_pbrSpecularGlossiness = null; } if (fake.KHR_materials_transmission == null) { mat.extensions.KHR_materials_transmission = null; } if (fake.KHR_materials_clearcoat == null) { mat.extensions.KHR_materials_clearcoat = null; } if (fake.KHR_materials_sheen == null) { mat.extensions.KHR_materials_sheen = null; } } } #if GLTFAST_SAFE if (root.accessors != null) { for (var i = 0; i < root.accessors.Length; i++) { var sparse = fakeRoot.accessors[i].sparse; if (sparse?.indices == null || sparse.values == null) { root.accessors[i].sparse = null; } } } #endif #if DRACO_UNITY if (root.meshes != null) { for (var i = 0; i < root.meshes.Length; i++) { var mesh = root.meshes[i]; Assert.AreEqual(mesh.name, fakeRoot.meshes[i].name); for (var j = 0; j < mesh.primitives.Length; j++) { var primitive = mesh.primitives[j]; if (primitive.extensions == null) { continue; } var fake = fakeRoot.meshes[i].primitives[j]; if (fake.extensions.KHR_draco_mesh_compression == null) { // TODO: Differentiate Primitive extensions here // since Draco is the only primitive extension, we // remove the whole extensions property. // primitive.extensions.KHR_draco_mesh_compression = null; primitive.extensions = null; } } } } #endif Profiler.EndSample(); } // Step four: // Further null checks on nodes' extensions if (root.nodes != null) { for (int i = 0; i < root.nodes.Length; i++) { var e = root.nodes[i].extensions; if (e != null) { if (e.EXT_mesh_gpu_instancing?.attributes == null && (e.KHR_lights_punctual == null || e.KHR_lights_punctual.light < 0)) { root.nodes[i].extensions = null; } } } } #if MEASURE_TIMINGS stopWatch.Stop(); var elapsedSeconds = stopWatch.ElapsedMilliseconds / 1000f; var throughput = json.Length / elapsedSeconds; Debug.Log($"JSON throughput: {throughput} bytes/sec ({json.Length} bytes in {elapsedSeconds} seconds)"); #endif return(root); }
/** * open a document in the root entry's list of entries * * @param documentName the name of the document to be opened * * @return a newly opened DocumentInputStream * * @exception IOException if the document does not exist or the * name is that of a DirectoryEntry */ public DocumentInputStream CreateDocumentInputStream( String documentName) { return(Root.CreateDocumentInputStream(documentName)); }
/// <summary> /// Add an entity to screen. /// </summary> /// <param name="entity">Entity to add.</param> public void AddEntity(Entity entity) { Root.AddChild(entity); }
// It returns whether the entity contains references to external entities. public void ScanEntityValue(ArrayList refs) { // To modify this code, beware nesting between this and EntityValue. string value = EntityValue; if (this.SystemId != null) { hasExternalReference = true; } if (recursed) { throw NotWFError("Entity recursion was found."); } recursed = true; if (scanned) { foreach (string referenced in refs) { if (this.ReferencingEntities.Contains(referenced)) { throw NotWFError(String.Format( "Nested entity was found between {0} and {1}", referenced, Name)); } } recursed = false; return; } int len = value.Length; int start = 0; for (int i = 0; i < len; i++) { switch (value [i]) { case '&': start = i + 1; break; case ';': if (start == 0) { break; } string name = value.Substring(start, i - start); if (name.Length == 0) { throw NotWFError("Entity reference name is missing."); } if (name [0] == '#') { break; // character reference } if (XmlChar.GetPredefinedEntity(name) >= 0) { break; // predefined reference } this.ReferencingEntities.Add(name); DTDEntityDeclaration decl = Root.EntityDecls [name]; if (decl != null) { if (decl.SystemId != null) { hasExternalReference = true; } refs.Add(Name); decl.ScanEntityValue(refs); foreach (string str in decl.ReferencingEntities) { ReferencingEntities.Add(str); } refs.Remove(Name); value = value.Remove(start - 1, name.Length + 2); value = value.Insert(start - 1, decl.EntityValue); i -= name.Length + 1; // not +2, because of immediate i++ . len = value.Length; } start = 0; break; } } if (start != 0) #if NET_2_1 { Root.AddError(new XmlSchemaException(this, this.BaseURI, "Invalid reference character '&' is specified.")); } #else { Root.AddError(new XmlSchemaException("Invalid reference character '&' is specified.", this.LineNumber, this.LinePosition, null, this.BaseURI, null)); } #endif scanned = true; recursed = false; }
public override void Construct() { Transaction = null; Result = TradeDialogResult.Pending; Border = "border-fancy"; var bottomRow = AddChild(new Widget { AutoLayout = AutoLayout.DockBottom, MinimumSize = new Point(0, 32) }); TotalDisplay = bottomRow.AddChild(new Widget { MinimumSize = new Point(128, 0), AutoLayout = AutoLayout.DockLeft, Font = "outline-font", TextColor = new Vector4(1, 1, 1, 1), TextVerticalAlign = VerticalAlign.Center }); SpaceDisplay = bottomRow.AddChild(new Widget { MinimumSize = new Point(128, 0), AutoLayout = AutoLayout.DockLeft, Font = "outline-font", TextColor = new Vector4(1, 1, 1, 1), TextVerticalAlign = VerticalAlign.Center }); bottomRow.AddChild(new Widget { Font = "outline-font", Border = "border-button", TextColor = new Vector4(1, 1, 1, 1), Text = "Propose Trade", AutoLayout = AutoLayout.DockRight, OnClick = (sender, args) => { if (EnvoyColumns.Valid && PlayerColumns.Valid) { Result = TradeDialogResult.Propose; Transaction = new TradeTransaction { EnvoyEntity = Envoy, EnvoyItems = EnvoyColumns.SelectedResources, EnvoyMoney = EnvoyColumns.TradeMoney, PlayerEntity = Player, PlayerItems = PlayerColumns.SelectedResources, PlayerMoney = PlayerColumns.TradeMoney }; this.Close(); } else { Root.ShowTooltip(Root.MousePosition, "Trade is invalid"); } } }); bottomRow.AddChild(new Widget { Font = "outline-font", Border = "border-button", TextColor = new Vector4(1, 1, 1, 1), Text = "Cancel", AutoLayout = AutoLayout.DockRight, Padding = new Margin(0, 0, 0, 16), OnClick = (sender, args) => { Result = TradeDialogResult.Cancel; this.Close(); } }); var mainPanel = AddChild(new TwoColumns { AutoLayout = AutoLayout.DockFill }); EnvoyColumns = mainPanel.AddChild(new ResourceColumns { TradeEntity = Envoy, ValueSourceEntity = Envoy, AutoLayout = AutoLayout.DockFill, LeftHeader = "Their Items", RightHeader = "They Offer", OnTotalSelectedChanged = (s) => UpdateBottomDisplays() }) as ResourceColumns; PlayerColumns = mainPanel.AddChild(new ResourceColumns { TradeEntity = Player, ValueSourceEntity = Envoy, AutoLayout = AutoLayout.DockFill, ReverseColumnOrder = true, LeftHeader = "Our Items", RightHeader = "We Offer", OnTotalSelectedChanged = (s) => UpdateBottomDisplays() }) as ResourceColumns; UpdateBottomDisplays(); }
/// <summary> /// Remove an entity from screen. /// </summary> /// <param name="entity">Entity to remove.</param> public void RemoveEntity(Entity entity) { Root.RemoveChild(entity); }
public void PrettyPrint() { ModulesVisited = new Dictionary <ModuleCacheKey, bool>(); Root.PrettyPrint(); }
public override void Construct() { Padding = new Margin(2, 2, 0, 0); AddChild(new Gui.Widget { Text = "Randomize", Border = "border-button", ChangeColorOnHover = true, TextColor = new Vector4(0, 0, 0, 1), Font = "font16", AutoLayout = Gui.AutoLayout.DockTop, OnClick = (sender, args) => { DwarfGame.LogSentryBreadcrumb("WorldGenerator", "User is regenerating the world."); Settings.Seed = MathFunctions.RandInt(Int32.MinValue, Int32.MaxValue); Settings.Name = Overworld.GetRandomWorldName(); RestartGeneration(); } }); AddChild(new Gui.Widget { Text = "Save World", Border = "border-button", ChangeColorOnHover = true, TextColor = new Vector4(0, 0, 0, 1), Font = "font16", AutoLayout = Gui.AutoLayout.DockTop, OnClick = (sender, args) => { DwarfGame.LogSentryBreadcrumb("WorldGenerator", "User is saving the world."); if (Generator.CurrentState != OverworldGenerator.GenerationState.Finished) { Root.ShowTooltip(Root.MousePosition, "Generator is not finished."); } else { global::System.IO.DirectoryInfo worldDirectory = global::System.IO.Directory.CreateDirectory(DwarfGame.GetWorldDirectory() + global::System.IO.Path.DirectorySeparatorChar + Settings.Name); var file = new NewOverworldFile(Game.GraphicsDevice, Settings); file.WriteFile(worldDirectory.FullName); Root.ShowModalPopup(Root.ConstructWidget(new Gui.Widgets.Popup { Text = "File saved." })); } } }); AddChild(new Gui.Widget { Text = "Advanced", Border = "border-button", ChangeColorOnHover = true, TextColor = new Vector4(0, 0, 0, 1), Font = "font16", AutoLayout = Gui.AutoLayout.DockTop, OnClick = (sender, args) => { DwarfGame.LogSentryBreadcrumb("WorldGenerator", "User is modifying advanced settings."); var advancedSettingsEditor = Root.ConstructWidget(new Gui.Widgets.WorldGenerationSettingsDialog { Settings = Settings, OnClose = (s) => { if ((s as Gui.Widgets.WorldGenerationSettingsDialog).Result == Gui.Widgets.WorldGenerationSettingsDialog.DialogResult.Okay) { RestartGeneration(); } } }); Root.ShowModalPopup(advancedSettingsEditor); } }); StartButton = AddChild(new Gui.Widget { Text = "Launch", Border = "border-button", ChangeColorOnHover = true, TextColor = new Vector4(0, 0, 0, 1), Font = "font16", AutoLayout = Gui.AutoLayout.DockBottom, OnClick = (sender, args) => { Settings.Company.Name = NameField.Text; Settings.Company.Motto = MottoField.Text; Settings.InstanceSettings.InitalEmbarkment = new Embarkment(Settings); Settings.PlayerCorporationFunds = Settings.Difficulty.StartingFunds; Settings.Natives.FirstOrDefault(n => n.Name == "Player").PrimaryColor = new Color(Settings.Company.LogoBackgroundColor); OnVerified?.Invoke(); } }); AddChild(new Gui.Widget { Text = "Difficulty", AutoLayout = Gui.AutoLayout.DockTop, Font = "font8", TextColor = new Vector4(0, 0, 0, 1) }); var difficultySelectorCombo = AddChild(new Gui.Widgets.ComboBox { AutoLayout = Gui.AutoLayout.DockTop, Items = Library.EnumerateDifficulties().Select(e => e.Name).ToList(), TextColor = new Vector4(0, 0, 0, 1), Font = "font8", OnSelectedIndexChanged = (sender) => { Settings.Difficulty = Library.GetDifficulty((sender as Gui.Widgets.ComboBox).SelectedItem); } }) as Gui.Widgets.ComboBox; AddChild(new Gui.Widget { Text = "Caves", AutoLayout = Gui.AutoLayout.DockTop, Font = "font8", TextColor = new Vector4(0, 0, 0, 1), }); var layerSetting = AddChild(new Gui.Widgets.ComboBox { AutoLayout = AutoLayout.DockTop, Items = new List <string>(new string[] { "Barely any", "Few", "Normal", "Lots", "Way too many" }), Font = "font8", TextColor = new Vector4(0, 0, 0, 1), OnSelectedIndexChanged = (sender) => { switch ((sender as Gui.Widgets.ComboBox).SelectedItem) { case "Barely any": Settings.NumCaveLayers = 2; break; case "Few": Settings.NumCaveLayers = 3; break; case "Normal": Settings.NumCaveLayers = 4; break; case "Lots": Settings.NumCaveLayers = 6; break; case "Way too many": Settings.NumCaveLayers = 9; break; } } }) as Gui.Widgets.ComboBox; AddChild(new Gui.Widget { Text = "Z Levels", AutoLayout = Gui.AutoLayout.DockTop, Font = "font8", TextColor = new Vector4(0, 0, 0, 1), }); var zLevelSetting = AddChild(new Gui.Widgets.ComboBox { AutoLayout = AutoLayout.DockTop, Items = new List <string>(new string[] { "16", "64", "128" }), Font = "font8", TextColor = new Vector4(0, 0, 0, 1), OnSelectedIndexChanged = (sender) => { switch ((sender as Gui.Widgets.ComboBox).SelectedItem) { case "16": Settings.zLevels = 1; break; case "64": Settings.zLevels = 4; break; case "128": Settings.zLevels = 8; break; } } }) as Gui.Widgets.ComboBox; zLevelSetting.SelectedIndex = 1; difficultySelectorCombo.SelectedIndex = difficultySelectorCombo.Items.IndexOf("Normal"); layerSetting.SelectedIndex = layerSetting.Items.IndexOf("Normal"); #region Name AddChild(new Gui.Widget { MinimumSize = new Point(64, 0), Text = "Company Name", Font = "font8", AutoLayout = AutoLayout.DockTop, TextHorizontalAlign = HorizontalAlign.Left, TextVerticalAlign = VerticalAlign.Center }); var nameRow = AddChild(new Widget { MinimumSize = new Point(0, 32), AutoLayout = AutoLayout.DockTop, Padding = new Margin(0, 0, 2, 2) }); nameRow.AddChild(new Gui.Widgets.Button { Text = "?", AutoLayout = AutoLayout.DockRight, Border = "border-button", OnClick = (sender, args) => { var templates = TextGenerator.GetAtoms(ContentPaths.Text.Templates.company); NameField.Text = TextGenerator.GenerateRandom(Datastructures.SelectRandom(templates).ToArray()); } }); NameField = nameRow.AddChild(new Gui.Widgets.EditableTextField { Text = Settings.Company.Name, AutoLayout = AutoLayout.DockFill }) as Gui.Widgets.EditableTextField; #endregion #region Motto AddChild(new Widget { MinimumSize = new Point(64, 0), Text = "Company Motto", Font = "font8", AutoLayout = AutoLayout.DockTop, TextHorizontalAlign = HorizontalAlign.Left, TextVerticalAlign = VerticalAlign.Center }); var mottoRow = AddChild(new Widget { MinimumSize = new Point(0, 32), AutoLayout = AutoLayout.DockTop, Padding = new Margin(0, 0, 2, 2) }); mottoRow.AddChild(new Gui.Widgets.Button { Text = "?", AutoLayout = AutoLayout.DockRight, Border = "border-button", OnClick = (sender, args) => { var templates = TextGenerator.GetAtoms(ContentPaths.Text.Templates.mottos); MottoField.Text = TextGenerator.GenerateRandom(Datastructures.SelectRandom(templates).ToArray()); // Todo: Doesn't automatically invalidate when text changed?? MottoField.Invalidate(); } }); MottoField = mottoRow.AddChild(new Gui.Widgets.EditableTextField { Text = Settings.Company.Motto, AutoLayout = AutoLayout.DockFill }) as Gui.Widgets.EditableTextField; #endregion #region Logo AddChild(new Widget { MinimumSize = new Point(64, 0), Text = "Company Logo", Font = "font8", AutoLayout = AutoLayout.DockTop, TextHorizontalAlign = HorizontalAlign.Left, TextVerticalAlign = VerticalAlign.Center }); var logoRow = AddChild(new Widget { MinimumSize = new Point(0, 64), AutoLayout = AutoLayout.DockTop, Padding = new Margin(0, 0, 2, 2) }); CompanyLogoDisplay = logoRow.AddChild(new Gui.Widgets.CompanyLogo { AutoLayout = AutoLayout.DockLeft, MinimumSize = new Point(64, 64), MaximumSize = new Point(64, 64), CompanyInformation = Settings.Company }) as Gui.Widgets.CompanyLogo; var rightBox = logoRow.AddChild(new Widget { AutoLayout = AutoLayout.DockFill }); var bgBox = rightBox.AddChild(new Widget { AutoLayout = AutoLayout.DockTop, MinimumSize = new Point(32, 32), }); bgBox.AddChild(new Widget { Text = "BG:", AutoLayout = AutoLayout.DockLeft }); bgBox.AddChild(new Widget { Background = Settings.Company.LogoBackground, MinimumSize = new Point(32, 32), MaximumSize = new Point(32, 32), AutoLayout = AutoLayout.DockLeft, OnClick = (sender, args) => { var source = Root.GetTileSheet("company-logo-background") as Gui.TileSheet; var chooser = new Gui.Widgets.GridChooser { ItemSource = Enumerable.Range(0, source.Columns * source.Rows) .Select(i => new Widget { Background = new TileReference("company-logo-background", i) }), OnClose = (s2) => { var gc = s2 as Gui.Widgets.GridChooser; if (gc.DialogResult == Gui.Widgets.GridChooser.Result.OKAY && gc.SelectedItem != null) { sender.Background = gc.SelectedItem.Background; sender.Invalidate(); Settings.Company.LogoBackground = gc.SelectedItem.Background; CompanyLogoDisplay.Invalidate(); } }, PopupDestructionType = PopupDestructionType.DestroyOnOffClick }; Root.ShowModalPopup(chooser); } }); bgBox.AddChild(new Widget { Background = new TileReference("basic", 1), BackgroundColor = Settings.Company.LogoBackgroundColor, MinimumSize = new Point(32, 32), MaximumSize = new Point(32, 32), AutoLayout = AutoLayout.DockLeft, OnClick = (sender, args) => { var chooser = new Gui.Widgets.GridChooser { ItemSize = new Point(16, 16), ItemSpacing = new Point(4, 4), ItemSource = EnumerateDefaultColors() .Select(c => new Widget { Background = new TileReference("basic", 1), BackgroundColor = new Vector4(c.ToVector3(), 1), }), OnClose = (s2) => { var gc = s2 as Gui.Widgets.GridChooser; if (gc.DialogResult == Gui.Widgets.GridChooser.Result.OKAY && gc.SelectedItem != null) { sender.BackgroundColor = gc.SelectedItem.BackgroundColor; sender.Invalidate(); Settings.Company.LogoBackgroundColor = gc.SelectedItem.BackgroundColor; CompanyLogoDisplay.Invalidate(); } }, PopupDestructionType = PopupDestructionType.DestroyOnOffClick }; Root.ShowModalPopup(chooser); } }); var fgBox = rightBox.AddChild(new Widget { AutoLayout = AutoLayout.DockFill, MinimumSize = new Point(32, 32), }); fgBox.AddChild(new Widget { Text = "FG:", AutoLayout = AutoLayout.DockLeft }); fgBox.AddChild(new Widget { Background = Settings.Company.LogoSymbol, MinimumSize = new Point(32, 32), MaximumSize = new Point(32, 32), AutoLayout = AutoLayout.DockLeft, OnClick = (sender, args) => { var source = Root.GetTileSheet("company-logo-symbol") as Gui.TileSheet; var chooser = new Gui.Widgets.GridChooser { ItemSource = Enumerable.Range(0, source.Columns * source.Rows) .Select(i => new Widget { Background = new TileReference("company-logo-symbol", i) }), OnClose = (s2) => { var gc = s2 as Gui.Widgets.GridChooser; if (gc.DialogResult == Gui.Widgets.GridChooser.Result.OKAY && gc.SelectedItem != null) { sender.Background = gc.SelectedItem.Background; sender.Invalidate(); Settings.Company.LogoSymbol = gc.SelectedItem.Background; CompanyLogoDisplay.Invalidate(); } }, PopupDestructionType = PopupDestructionType.DestroyOnOffClick }; Root.ShowModalPopup(chooser); } }); fgBox.AddChild(new Widget { Background = new TileReference("basic", 1), BackgroundColor = Settings.Company.LogoSymbolColor, MinimumSize = new Point(32, 32), MaximumSize = new Point(32, 32), AutoLayout = AutoLayout.DockLeft, OnClick = (sender, args) => { var chooser = new Gui.Widgets.GridChooser { ItemSize = new Point(16, 16), ItemSpacing = new Point(4, 4), ItemSource = EnumerateDefaultColors() .Select(c => new Widget { Background = new TileReference("basic", 1), BackgroundColor = new Vector4(c.ToVector3(), 1), }), OnClose = (s2) => { var gc = s2 as Gui.Widgets.GridChooser; if (gc.DialogResult == Gui.Widgets.GridChooser.Result.OKAY && gc.SelectedItem != null) { sender.BackgroundColor = gc.SelectedItem.BackgroundColor; sender.Invalidate(); Settings.Company.LogoSymbolColor = gc.SelectedItem.BackgroundColor; CompanyLogoDisplay.Invalidate(); } }, PopupDestructionType = PopupDestructionType.DestroyOnOffClick }; Root.ShowModalPopup(chooser); } }); #endregion base.Construct(); }
public void ResolveDependencies() { Action action = () => { if (DependenciesResolved) { return; } List <PeDependencyItem> NewDependencies = new List <PeDependencyItem>(); foreach (PeImportDll DllImport in Imports) { string ModuleFilepath = null; ModuleSearchStrategy Strategy; // Find Dll in "paths" Tuple <ModuleSearchStrategy, PE> ResolvedModule = Root.ResolveModule(DllImport.Name); Strategy = ResolvedModule.Item1; if (Strategy != ModuleSearchStrategy.NOT_FOUND) { ModuleFilepath = ResolvedModule.Item2?.Filepath; } bool IsAlreadyCached = Root.isModuleCached(DllImport.Name, ModuleFilepath); PeDependencyItem DependencyItem = Root.GetModuleItem(DllImport.Name, ModuleFilepath, Strategy, RecursionLevel + 1); // do not add twice the same imported module if (ResolvedImports.Find(ri => ri.ModuleName == DllImport.Name) == null) { ResolvedImports.Add(DependencyItem); } // Do not process twice a dependency. It will be displayed only once if (!IsAlreadyCached) { Debug.WriteLine("[{0:d}] [{1:s}] Adding dep {2:s}", RecursionLevel, ModuleName, ModuleFilepath); NewDependencies.Add(DependencyItem); } FullDependencies.Add(DependencyItem); } DependenciesResolved = true; if ((Root.MaxRecursion > 0) && ((RecursionLevel + 1) >= Root.MaxRecursion)) { return; } // Recursively resolve dependencies foreach (var Dep in NewDependencies) { Dep.LoadPe(); Dep.ResolveDependencies(); } }; SafeExecutor(action); }
/// <inheritdoc /> protected override DragDropEffect OnDragDropHeader(DragData data) { var result = DragDropEffect.None; Actor myActor = Actor; Actor newParent; int newOrder = -1; // Check if has no actor (only for Root Actor) if (myActor == null) { // Append to the last scene var scenes = SceneManager.Scenes; if (scenes == null || scenes.Length == 0) { throw new InvalidOperationException("No scene loaded."); } newParent = scenes[scenes.Length - 1]; } else { newParent = myActor; // Use drag positioning to change target parent and index if (DragOverMode == DragItemPositioning.Above) { if (myActor.HasParent) { newParent = myActor.Parent; newOrder = myActor.OrderInParent; } } else if (DragOverMode == DragItemPositioning.Below) { if (myActor.HasParent) { newParent = myActor.Parent; newOrder = myActor.OrderInParent + 1; } } } if (newParent == null) { throw new InvalidOperationException("Missing parent actor."); } // Drag actors if (_dragActors != null && _dragActors.HasValidDrag) { bool worldPositionLock = Root.GetKey(Keys.Control) == false; var singleObject = _dragActors.Objects.Count == 1; if (singleObject) { var targetActor = _dragActors.Objects[0].Actor; var customAction = targetActor.HasPrefabLink ? new ReparentAction(targetActor) : null; using (new UndoBlock(ActorNode.Root.Undo, targetActor, "Change actor parent", customAction)) { targetActor.SetParent(newParent, worldPositionLock); targetActor.OrderInParent = newOrder; } } else { var targetActors = _dragActors.Objects.ConvertAll(x => x.Actor); var customAction = targetActors.Any(x => x.HasPrefabLink) ? new ReparentAction(targetActors) : null; using (new UndoMultiBlock(ActorNode.Root.Undo, targetActors, "Change actors parent", customAction)) { for (int i = 0; i < targetActors.Count; i++) { var targetActor = targetActors[i]; targetActor.SetParent(newParent, worldPositionLock); targetActor.OrderInParent = newOrder; } } } result = DragDropEffect.Move; } // Drag assets else if (_dragAssets != null && _dragAssets.HasValidDrag) { for (int i = 0; i < _dragAssets.Objects.Count; i++) { var item = _dragAssets.Objects[i]; switch (item.ItemDomain) { case ContentDomain.Model: { if (item.TypeName == typeof(SkinnedModel).FullName) { // Create actor var model = FlaxEngine.Content.LoadAsync <SkinnedModel>(item.ID); var actor = AnimatedModel.New(); actor.StaticFlags = Actor.StaticFlags; actor.Name = item.ShortName; actor.SkinnedModel = model; actor.Transform = Actor.Transform; // Spawn ActorNode.Root.Spawn(actor, Actor); } else { // Create actor var model = FlaxEngine.Content.LoadAsync <Model>(item.ID); var actor = StaticModel.New(); actor.StaticFlags = Actor.StaticFlags; actor.Name = item.ShortName; actor.Model = model; actor.Transform = Actor.Transform; // Spawn ActorNode.Root.Spawn(actor, Actor); } break; } case ContentDomain.Other: { if (item.TypeName == typeof(CollisionData).FullName) { // Create actor var actor = MeshCollider.New(); actor.StaticFlags = Actor.StaticFlags; actor.Name = item.ShortName; actor.CollisionData = FlaxEngine.Content.LoadAsync <CollisionData>(item.ID); actor.Transform = Actor.Transform; // Spawn ActorNode.Root.Spawn(actor, Actor); } else if (item.TypeName == typeof(ParticleSystem).FullName) { // Create actor var actor = ParticleEffect.New(); actor.StaticFlags = Actor.StaticFlags; actor.Name = item.ShortName; actor.ParticleSystem = FlaxEngine.Content.LoadAsync <ParticleSystem>(item.ID); actor.Transform = Actor.Transform; // Spawn ActorNode.Root.Spawn(actor, Actor); } else if (item.TypeName == typeof(SceneAnimation).FullName) { // Create actor var actor = SceneAnimationPlayer.New(); actor.StaticFlags = Actor.StaticFlags; actor.Name = item.ShortName; actor.Animation = FlaxEngine.Content.LoadAsync <SceneAnimation>(item.ID); actor.Transform = Actor.Transform; // Spawn ActorNode.Root.Spawn(actor, Actor); } break; } case ContentDomain.Audio: { // Create actor var actor = AudioSource.New(); actor.StaticFlags = Actor.StaticFlags; actor.Name = item.ShortName; actor.Clip = FlaxEngine.Content.LoadAsync <AudioClip>(item.ID); actor.Transform = Actor.Transform; // Spawn ActorNode.Root.Spawn(actor, Actor); break; } case ContentDomain.Prefab: { // Create prefab instance var prefab = FlaxEngine.Content.LoadAsync <Prefab>(item.ID); var actor = PrefabManager.SpawnPrefab(prefab, null); actor.StaticFlags = Actor.StaticFlags; actor.Name = item.ShortName; actor.Transform = Actor.Transform; // Spawn ActorNode.Root.Spawn(actor, Actor); break; } } } result = DragDropEffect.Move; } // Drag actor type else if (_dragActorType != null && _dragActorType.HasValidDrag) { for (int i = 0; i < _dragActorType.Objects.Count; i++) { var item = _dragActorType.Objects[i]; // Create actor var actor = FlaxEngine.Object.New(item) as Actor; if (actor == null) { Editor.LogWarning("Failed to spawn actor of type " + item.FullName); continue; } actor.StaticFlags = Actor.StaticFlags; actor.Name = item.Name; actor.Transform = Actor.Transform; // Spawn ActorNode.Root.Spawn(actor, Actor); } result = DragDropEffect.Move; } // Clear cache _dragHandlers.OnDragDrop(null); // Check if scene has been modified if (result != DragDropEffect.None) { var node = SceneGraphFactory.FindNode(newParent.ID) as ActorNode; node?.TreeNode.Expand(); } return(result); }
public DVCLogIn() : base(UITableViewStyle.Grouped, null, true) { loginView = new FBLoginView(ExtendedPermissions); if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0)) { loginView.Frame = new CGRect(51, 0, 218, 46); } else { loginView.Frame = new CGRect(40, 0, 218, 46); } loginView.FetchedUserInfo += (sender, e) => { if (Root.Count < 3) { user = e.User; pictureView.ProfileID = user.GetId(); Root.Add(new Section("Hello " + user.GetName()) { new StringElement("Actions Menu", () => { var dvc = new DVCActions(user); NavigationController.PushViewController(dvc, true); }) { Alignment = UITextAlignment.Center } }); } }; loginView.ShowingLoggedOutUser += (sender, e) => { pictureView.ProfileID = null; if (Root.Count >= 3) { InvokeOnMainThread(() => { var section = Root [2]; section.Remove(0); Root.Remove(section); ReloadData(); }); } }; pictureView = new FBProfilePictureView(); if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0)) { pictureView.Frame = new CGRect(50, 0, 220, 220); } else { pictureView.Frame = new CGRect(40, 0, 220, 220); } Root = new RootElement("Facebook Sample") { new Section() { new UIViewElement("", loginView, true) { Flags = UIViewElement.CellFlags.DisableSelection | UIViewElement.CellFlags.Transparent, } }, new Section() { new UIViewElement("", pictureView, true) { Flags = UIViewElement.CellFlags.DisableSelection | UIViewElement.CellFlags.Transparent, }, } }; }
public bool IsNewModule() { return(Root.VisitModule(this.ModuleName, this.Filepath)); }
public override void Construct() { base.Construct(); ReservedKeys = new Keys[] { Keys.Up, Keys.Left, Keys.Right, Keys.Down, Keys.LeftControl, //Keys.LeftShift, //Keys.RightShift, Keys.LeftAlt, Keys.RightAlt, Keys.RightControl, Keys.Escape }.ToList(); var bindingCount = KeyManager.Buttons.Count; var insideScrollHandler = false; ScrollBar = AddChild(new VerticalScrollBar { ScrollArea = bindingCount, ScrollPosition = 0, AutoLayout = AutoLayout.DockRight, OnScrollValueChanged = (sender) => { if (insideScrollHandler) { return; } insideScrollHandler = true; LayoutRows(); insideScrollHandler = false; } }) as VerticalScrollBar; OnLayout += (sender) => { var height = sender.Rect.Height; var rowsVisible = height / 20; ScrollBar.ScrollArea = Math.Max(0, bindingCount - rowsVisible + 1); }; foreach (var binding in KeyManager.Buttons) { var lambdaBinding = binding; var row = AddChild(new Widget { MinimumSize = new Point(0, 20), AutoLayout = AutoLayout.None, }); Rows.Add(row); row.AddChild(new Widget { MinimumSize = new Point(128, 0), AutoLayout = AutoLayout.DockLeft, Text = binding.Key }); row.AddChild(new Gui.Widgets.KeyField { AssignedKey = binding.Value, BeforeKeyChange = (sender, args) => { if (KeyManager.IsMapped(args.NewKey)) { args.Cancelled = true; Root.ShowTooltip(new Point(sender.Rect.X, sender.Rect.Y + 20), String.Format("Key {0} is already assigned.", args.NewKey)); } else if (ReservedKeys.Contains(args.NewKey)) { args.Cancelled = true; Root.ShowTooltip(new Point(sender.Rect.X, sender.Rect.Y + 20), String.Format("Key {0} is reserved.", args.NewKey)); } }, OnKeyChange = (sender, newKey) => { KeyManager[lambdaBinding.Key] = newKey; KeyManager.SaveConfigSettings(); }, AutoLayout = AutoLayout.DockFill }); } LayoutRows(); }
public async Task <Attestation> NewAttestationAsync(BlsPublicKey validatorPublicKey, bool proofOfCustodyBit, Slot slot, CommitteeIndex index, CancellationToken cancellationToken) { Root head = await _store.GetHeadAsync().ConfigureAwait(false); BeaconBlock headBlock = (await _store.GetSignedBlockAsync(head).ConfigureAwait(false)).Message; BeaconState parentState = await _store.GetBlockStateAsync(head).ConfigureAwait(false); // Clone state (will mutate) and process outstanding slots BeaconState headState = BeaconState.Clone(parentState); _beaconStateTransition.ProcessSlots(headState, slot); // Set attestation_data.index = index where index is the index associated with the validator's committee. ValidatorIndex?validatorIndex = FindValidatorIndexByPublicKey(headState, validatorPublicKey); if (validatorIndex == null) { throw new Exception($"Can not find validator index for public key {validatorPublicKey}"); } // TODO: May need a more efficient way to try and find the committee and position within the committee. // Some of this may already be cached in Validator Assignments (generally stable for an epoch), // but not with the index within the committee. Easy enough to extend and use the same cache. IReadOnlyList <ValidatorIndex> committee = _beaconStateAccessor.GetBeaconCommittee(headState, headState.Slot, index); int committeeSize = committee.Count; int?committeeMemberIndexOfValidator = null; for (int committeeMemberIndex = 0; committeeMemberIndex < committee.Count; committeeMemberIndex++) { if (committee[committeeMemberIndex] == validatorIndex) { committeeMemberIndexOfValidator = committeeMemberIndex; break; } } if (committeeMemberIndexOfValidator == null) { throw new Exception($"Validator index {validatorIndex} is not a member of committee {index}"); } Root beaconBlockRoot = _cryptographyService.HashTreeRoot(headBlock); Checkpoint source = headState.CurrentJustifiedCheckpoint; Epoch currentEpoch = _beaconStateAccessor.GetCurrentEpoch(headState); Slot startSlot = _beaconChainUtility.ComputeStartSlotOfEpoch(currentEpoch); Root epochBoundaryBlockRoot; if (startSlot == headState.Slot) { epochBoundaryBlockRoot = beaconBlockRoot; } else { epochBoundaryBlockRoot = _beaconStateAccessor.GetBlockRootAtSlot(headState, startSlot); } Checkpoint target = new Checkpoint(currentEpoch, epochBoundaryBlockRoot); AttestationData attestationData = new AttestationData(slot, index, beaconBlockRoot, source, target); var aggregationBits = new BitArray(committeeSize); aggregationBits.Set(committeeMemberIndexOfValidator.Value, true); var attestation = new Attestation(aggregationBits, attestationData, BlsSignature.Zero); return(attestation); }
/// <summary> /// Add an entity to screen. /// </summary> /// <param name="entity">Entity to add.</param> public Entity AddEntity(Entity entity) { return(Root.AddChild(entity)); }
public override void Construct() { Root.RegisterForUpdate(this); Border = "border-fancy"; int w = Root.RenderData.VirtualScreen.Width; int h = Root.RenderData.VirtualScreen.Height; Rect = new Rectangle(Root.RenderData.VirtualScreen.Center.X - w / 2, Root.RenderData.VirtualScreen.Center.Y - h / 2, w, h); var playerClasses = Library.EnumerateClasses().Where(c => c.PlayerClass).ToList(); foreach (var job in playerClasses) { Applicants.Add(job.Name, new GeneratedApplicant { Applicant = GenerateApplicant(job.Name) }); } var left = AddChild(new Widget() { AutoLayout = AutoLayout.DockTop, Padding = new Margin(5, 5, 32, 32), MinimumSize = new Point(48 * 2 * playerClasses.Count, 40 * 2 + 40) }); var right = AddChild(new Widget() { AutoLayout = AutoLayout.DockFill }); var buttonRow = right.AddChild(new Widget { AutoLayout = AutoLayout.DockBottom, MinimumSize = new Point(0, 30) }); var jobDescription = right.AddChild(new Widget { MinimumSize = new Point((int)(w * 0.4f), 0), InteriorMargin = new Margin(16, 16, 16, 16), WrapWithinWords = false, WrapText = true, AutoLayout = AutoLayout.DockLeft, Font = "font10" }); var applicantInfo = right.AddChild(new ApplicantInfo { AutoLayout = AutoLayout.DockFill }) as ApplicantInfo; applicantInfo.Hidden = true; left.AddChild(new Widget { Text = "Applicants", AutoLayout = AutoLayout.DockTop, MinimumSize = new Point(0, 20), Font = "font16" }); foreach (var job in playerClasses) { var frame = left.AddChild(new Widget() { MinimumSize = new Point(48 * 2, 40 * 2 + 15), AutoLayout = AutoLayout.DockLeft }); var applicant = Applicants[job.Name]; var layers = applicant.Applicant.GetLayers(); applicant.Portrait = frame.AddChild(new EmployeePortrait() { Tooltip = "Click to review applications for " + job.Name, AutoLayout = AutoLayout.DockTop, TextHorizontalAlign = HorizontalAlign.Center, TextVerticalAlign = VerticalAlign.Bottom, OnClick = (sender, args) => { jobDescription.Text = "\n\n" + applicant.Applicant.Class.JobDescription; jobDescription.Invalidate(); applicantInfo.Hidden = false; HireButton.Hidden = false; HireButton.Invalidate(); applicantInfo.Applicant = applicant.Applicant; }, MinimumSize = new Point(48 * 2, 40 * 2), MaximumSize = new Point(48 * 2, 40 * 2), Sprite = layers, AnimationPlayer = applicant.Applicant.GetAnimationPlayer(layers, "WalkingFORWARD") }) as EmployeePortrait; frame.AddChild(new Widget() { Text = job.Name, MinimumSize = new Point(0, 15), TextColor = Color.Black.ToVector4(), Font = "font8", AutoLayout = AutoLayout.DockTop, TextHorizontalAlign = HorizontalAlign.Center }); } buttonRow.AddChild(new Widget { Text = "Back", Border = "border-button", AutoLayout = AutoLayout.DockLeft, Font = "font16", OnClick = (sender, args) => { this.Close(); }, ChangeColorOnHover = true, }); HireButton = buttonRow.AddChild(new Button { Text = "Hire", Border = "border-button", AutoLayout = AutoLayout.DockRight, OnClick = (sender, args) => { var applicant = applicantInfo.Applicant; if (applicant != null) { Settings.InstanceSettings.InitalEmbarkment.Employees.Add(applicant); applicantInfo.Hidden = true; HireButton.Hidden = true; this.Invalidate(); applicantInfo.Invalidate(); HireButton.Invalidate(); var newApplicant = GenerateApplicant(applicant.Class.Name); Applicants[applicant.Class.Name].Applicant = newApplicant; Applicants[applicant.Class.Name].Portrait.Sprite = newApplicant.GetLayers(); Applicants[applicant.Class.Name].Portrait.AnimationPlayer = newApplicant.GetAnimationPlayer(Applicants[applicant.Class.Name].Portrait.Sprite, "WalkingFORWARD"); } }, Hidden = true, Font = "font16", ChangeColorOnHover = true, }) as Button; this.Layout(); OnUpdate += (sender, time) => { foreach (var applicant in Applicants) { applicant.Value.Portrait.AnimationPlayer.Update(new DwarfTime(time), false, Timer.TimerMode.Real); applicant.Value.Portrait.Invalidate(); applicant.Value.Portrait.Sprite.Update(GameStates.GameState.Game.GraphicsDevice); } }; }
/// <summary> /// Creates a new parameter. /// </summary> /// <param name="root">Root object to which the parameter belongs.</param> /// <param name="name">Name of the effect parameter.</param> /// <param name="value">Value of the effect parameter.</param> public IntParameter(Root root, string name, int value) : base(root, name, value) { }
/// <summary> /// Get xml serializer. /// </summary> /// <returns>XML serializer instance.</returns> virtual protected XmlSerializer GetXmlSerializer() { return(new XmlSerializer(Root.GetType(), Entity._serializableTypes.ToArray())); }
public override void ViewDidLoad() { base.ViewDidLoad(); var secDetails = new Section(); var commentsSection = new Section(null, new TableFooterButton("Add Comment", () => ViewModel.AddCommentCommand.ExecuteIfCan())); var commentsElement = new HtmlElement("comments"); commentsElement.UrlRequested = ViewModel.GoToUrlCommand.ExecuteIfCan; var descriptionElement = new HtmlElement("description"); descriptionElement.UrlRequested = ViewModel.GoToUrlCommand.ExecuteIfCan; secDetails.Add(_milestoneElement); secDetails.Add(_assigneeElement); secDetails.Add(_labelsElement); var addCommentElement = new StyledStringElement("Add Comment") { Image = Images.Pencil }; this.WhenViewModel(x => x.MarkdownDescription).Subscribe(x => { if (string.IsNullOrEmpty(x)) { secDetails.Remove(descriptionElement); } else { var markdown = new DescriptionView { Model = x }; var html = markdown.GenerateString(); descriptionElement.Value = html; if (!secDetails.Contains(descriptionElement)) { secDetails.Insert(0, UITableViewRowAnimation.Fade, descriptionElement); } } }); ViewModel.Events.Changed.Subscribe(_ => { var commentModels = ViewModel.Events .Select(x => { var body = string.Empty; var comment = x as IssueCommentItemViewModel; var @event = x as IssueEventItemViewModel; if (comment != null) { body = comment.Comment; } else if (@event != null) { body = CreateEventBody(@event.EventInfo, @event.Commit); } return(new Comment(x.AvatarUrl, x.Actor, body, x.CreatedAt.LocalDateTime.Humanize())); }) .Where(x => !string.IsNullOrEmpty(x.Body)) .ToList(); if (commentModels.Count > 0) { var razorView = new CommentsView { Model = commentModels }; var html = razorView.GenerateString(); commentsElement.Value = html; if (!commentsSection.Contains(commentsElement)) { commentsSection.Insert(0, UITableViewRowAnimation.Fade, commentsElement); } } else { commentsSection.Remove(commentsElement); } }); Root.Reset(new Section(), secDetails, commentsSection); }
/// <summary> /// Creates a new parameter. /// </summary> /// <param name="root">Root object to which the parameter belongs.</param> /// <param name="name">Name of the new parameter.</param> /// <param name="value">Value of the new parameter.</param> /// <param name="effect">Effect to which the parameter belongs.</param> public IntParameter(Root root, string name, int value, Effect effect) : base(root, name, value, effect) { }
public override string GetSummaryId(Root root) => Item.GetSummaryId(root);
private void CreateTable() { var application = IoC.Resolve <IApplicationService>(); var vm = (SettingsViewModel)ViewModel; var currentAccount = application.Account; var accountSection = new Section("Account"); accountSection.Add(new BooleanElement("Save Credentials", !currentAccount.DontRemember, e => { // currentAccount.DontRemember = !e.Value; // application.Accounts.Update(currentAccount); })); var showOrganizationsInEvents = new BooleanElement("Show Organizations in Events", currentAccount.ShowOrganizationsInEvents, e => { // currentAccount.ShowOrganizationsInEvents = e.Value; // application.Accounts.Update(currentAccount); }); var showOrganizations = new BooleanElement("List Organizations in Menu", currentAccount.ExpandOrganizations, e => { // currentAccount.ExpandOrganizations = e.Value; // application.Accounts.Update(currentAccount); }); var repoDescriptions = new BooleanElement("Show Repo Descriptions", currentAccount.ShowRepositoryDescriptionInList, e => { // currentAccount.ShowRepositoryDescriptionInList = e.Value; // application.Accounts.Update(currentAccount); }); var startupView = new StyledStringElement("Startup View", vm.DefaultStartupViewName, MonoTouch.UIKit.UITableViewCellStyle.Value1) { Accessory = MonoTouch.UIKit.UITableViewCellAccessory.DisclosureIndicator, }; startupView.Tapped += () => vm.GoToDefaultStartupViewCommand.Execute(null); //var sidebarOrder = new StyledStringElement("Sidebar Order", () => vm.GoToSidebarOrderCommand.Execute(null)); var largeFonts = new BooleanElement("Large Fonts", vm.LargeFonts, x => { vm.LargeFonts = x.Value; Theme.Setup(); CreateTable(); }); accountSection.Add(new BooleanElement("Push Notifications", vm.PushNotificationsEnabled, e => vm.PushNotificationsEnabled = e.Value)); var totalCacheSizeMB = vm.CacheSize.ToString("0.##"); var deleteCache = new StyledStringElement("Delete Cache", string.Format("{0} MB", totalCacheSizeMB), MonoTouch.UIKit.UITableViewCellStyle.Value1); deleteCache.Tapped += () => { vm.DeleteAllCacheCommand.Execute(null); deleteCache.Value = string.Format("{0} MB", 0); ReloadData(); }; var usage = new BooleanElement("Send Anonymous Usage", vm.AnalyticsEnabled, e => vm.AnalyticsEnabled = e.Value); //Assign the root Root.Add(accountSection); Root.Add(new Section("Appearance") { showOrganizationsInEvents, showOrganizations, repoDescriptions, startupView, largeFonts }); Root.Add(new Section("Internal") { deleteCache, usage }); }
private string GetClassAttribute(string rangeText, Classification.Range range, bool isLargeFile = false) { string classificationType = range.ClassificationType; if (classificationType == null || classificationType == Constants.ClassificationPunctuation) { return null; } if (range.ClassificationType == Constants.ClassificationLiteral) { return classificationType; } if (range.ClassificationType != Constants.ClassificationIdentifier && range.ClassificationType != Constants.ClassificationTypeName && rangeText != "this" && rangeText != "base" && rangeText != "var" && rangeText != "New" && rangeText != "new" && rangeText != "[" && rangeText != "partial" && rangeText != "Partial") { return classificationType; } if (range.ClassificationType == Constants.ClassificationKeyword) { return classificationType; } var position = range.ClassifiedSpan.TextSpan.Start; var token = Root.FindToken(position, findInsideTrivia: true); var declaredSymbol = SemanticModel.GetDeclaredSymbol(token.Parent); if (declaredSymbol is IParameterSymbol && rangeText == "this") { return classificationType; } if (declaredSymbol != null) { return ClassFromSymbol(declaredSymbol, classificationType); } var node = GetBindableParent(token); if (token.ToString() == "[" && token.Parent is Microsoft.CodeAnalysis.CSharp.Syntax.BracketedArgumentListSyntax && token.Parent.Parent is Microsoft.CodeAnalysis.CSharp.Syntax.ElementAccessExpressionSyntax) { node = token.Parent.Parent; } if (node == null) { return classificationType; } var symbol = GetSymbol(node); if (symbol == null) { return classificationType; } return ClassFromSymbol(symbol, classificationType); }
public IssueView() { this.WhenAnyValue(x => x.ViewModel.ShowMenuCommand) .Select(x => x.ToBarButtonItem(UIBarButtonSystemItem.Action)) .Subscribe(x => NavigationItem.RightBarButtonItem = x); this.WhenAnyValue(x => x.ViewModel.GoToAssigneesCommand) .Switch() .Subscribe(_ => ShowAssigneeSelector()); this.WhenAnyValue(x => x.ViewModel.GoToMilestonesCommand) .Switch() .Subscribe(_ => ShowMilestonesSelector()); this.WhenAnyValue(x => x.ViewModel.GoToLabelsCommand) .Switch() .Subscribe(_ => ShowLabelsSelector()); this.WhenAnyValue(x => x.ViewModel.Issue) .IsNotNull() .Subscribe(x => { HeaderView.Text = x.Title; HeaderView.ImageUri = x.User.AvatarUrl; if (x.UpdatedAt.HasValue) { HeaderView.SubText = "Updated " + x.UpdatedAt.Value.UtcDateTime.Humanize(); } else { HeaderView.SubText = "Created " + x.CreatedAt.UtcDateTime.Humanize(); } }); _milestoneElement = new StyledStringElement("Milestone", string.Empty, UITableViewCellStyle.Value1) { Image = Images.Milestone, Accessory = UITableViewCellAccessory.DisclosureIndicator }; _milestoneElement.Tapped += () => ViewModel.GoToMilestonesCommand.ExecuteIfCan(); this.WhenAnyValue(x => x.ViewModel.AssignedMilestone) .Select(x => x == null ? "No Milestone" : x.Title) .Subscribe(x => { _milestoneElement.Value = x; Root.Reload(_milestoneElement); }); _assigneeElement = new StyledStringElement("Assigned", string.Empty, UITableViewCellStyle.Value1) { Image = Images.Person, Accessory = UITableViewCellAccessory.DisclosureIndicator }; _assigneeElement.Tapped += () => ViewModel.GoToAssigneesCommand.ExecuteIfCan(); this.WhenAnyValue(x => x.ViewModel.AssignedUser) .Select(x => x == null ? "Unassigned" : x.Login) .Subscribe(x => { _assigneeElement.Value = x; Root.Reload(_assigneeElement); }); _labelsElement = new StyledStringElement("Labels", string.Empty, UITableViewCellStyle.Value1) { Image = Images.Tag, Accessory = UITableViewCellAccessory.DisclosureIndicator }; _labelsElement.Tapped += () => ViewModel.GoToLabelsCommand.ExecuteIfCan(); this.WhenAnyValue(x => x.ViewModel.AssignedLabels) .Select(x => (x == null || x.Count == 0) ? "None" : string.Join(",", x)) .Subscribe(x => { _labelsElement.Value = x; Root.Reload(_labelsElement); }); }