Exemple #1
0
        protected virtual void TriggerEvent(SimpleTask task, EventCallback cb = null)
        {
            TaskScheduleEvent e = new TaskScheduleEvent(task);

            if (!(task.Owner is IEventEmitter owner))
            {
                return;
            }

            IEventBus eventBus = Container.Resolve <IEventBus>();

            if (eventBus == null)
            {
                InternalTasks.Add(task);
                cb?.Invoke(owner, null);
                return;
            }

            eventBus.Emit(owner, e, @event =>
            {
                task.IsCancelled = e.IsCancelled;

                if (!e.IsCancelled)
                {
                    InternalTasks.Add(task);
                }

                cb?.Invoke(owner, @event);
            });
        }
        public virtual void TriggerEvent(UnityTask task, EventCallback cb = null)
        {
            if (task.ExecutionTarget == ExecutionTargetContext.Async || task.ExecutionTarget == ExecutionTargetContext.NextAsyncFrame ||
                task.ExecutionTarget == ExecutionTargetContext.EveryAsyncFrame)
            {
                m_AsyncThreadPool.EventWaitHandle.Set();
            }

            TaskScheduleEvent e = new TaskScheduleEvent(task);

            if (m_EventBus == null)
            {
                m_Tasks.Add(task);
                cb?.Invoke(task.Owner, null);
                return;
            }

            m_EventBus.Emit(task.Owner, e, @event =>
            {
                task.IsCancelled = e.IsCancelled;

                if (!e.IsCancelled)
                {
                    m_Tasks.Add(task);
                }

                cb?.Invoke(task.Owner, @event);
            });
        }
        private void OnLoadChannelsComplete(RealmEventArgs args)
        {
            Validation.IsNotNull(args, "args");
            Validation.IsNotNull(args.Data, "args.Data");

            var data = args.Data.ToDictionaryAtom();

            if (!data.GetBool("success"))
            {
                throw new ProcedureFailureException("Load Failure", GetType());
            }

            var commandResults = data.GetAtom <ListAtom>("commandResult");
            var results        = commandResults.GetEnumerator().Current.CastAs <DictionaryAtom>().GetAtom <ListAtom>("Results");

            using (var it = results.GetEnumerator())
            {
                while (it.MoveNext())
                {
                    var result     = it.Current.CastAs <DictionaryAtom>();
                    var channelDef = (ChannelDef)_staticDataManager.GetStaticData(Globals.SystemTypes.Channel, result.GetInt("ChannelPrimitiveID").ToString());
                    var obj        = _entityManager.Create <Channel>(result.GetInt("ChannelID"), result.GetString("Name"), result, channelDef);
                    if (obj == null)
                    {
                        throw new InstantiationException("Failed to instantiate Channel {0}", result.GetInt("ChannelID"));
                    }

                    obj.OnInit(_entityManager.InitializationAtom);
                    _repository.Add(obj.ID, obj);
                }
            }

            _log.DebugFormat("Loaded {0} channels.", _repository.Count);
            _callback?.Invoke(new RealmEventArgs());
        }
        private void TriggerEvent(SimpleTask task, EventCallback cb = null)
        {
            TaskScheduleEvent e = new TaskScheduleEvent(task);

            if (!(task.Owner is IEventEmitter owner))
            {
                return;
            }

            if (!task.Owner.IsAlive)
            {
                return;
            }

            IEventManager eventManager = container.Resolve <IEventManager>();

            eventManager?.Emit(owner, e, @event =>
            {
                task.IsCancelled = e.IsCancelled;

                if (!e.IsCancelled)
                {
                    tasks.Add(task);
                }

                cb?.Invoke(owner, @event);
            });
        }
        public void LoadGameState(EventCallback <RealmEventArgs> callback)
        {
            _callback = callback;
            _log.Debug("GameStateLoader initialized");

            try
            {
                var gameState = _liveDbContext.GameStates.LastOrDefault();
                if (gameState == null)
                {
                    throw new ProcedureFailureException("Load Failure", GetType());
                }

                var obj = new GameState(new MudTime
                {
                    Year   = gameState.Year,
                    Month  = gameState.MonthId,
                    Day    = gameState.Day,
                    Hour   = gameState.Hour,
                    Minute = gameState.Minute
                });

                _log.DebugFormat("GameStateLoader loaded the new game state: {0}", obj.ToString());

                _callback?.Invoke(new RealmEventArgs(new EventTable {
                    { "GameState", obj }
                }));
            }
            catch (Exception ex)
            {
                ex.Handle(ExceptionHandlingOptions.RecordAndThrow);
            }
        }
 /// <summary>
 /// Submits the given callback with the passed data fields
 /// </summary>
 /// <param name="callback"></param>
 /// <param name="success"></param>
 /// <param name="result"></param>
 /// <param name="data"></param>
 private static void IssueCallback(EventCallback <RealmEventArgs> callback, bool success, Atom result, DictionaryAtom data)
 {
     callback?.Invoke(new RealmEventArgs(new EventTable
     {
         { "userData", data },
         { "commandResult", result },
         { "success", success }
     }));
 }
 internal void RaiseEvent()
 {
     OnEvent?.Invoke(this, EventArgs.Empty);
     EventCallback?.Invoke();
     if (_period == BlockerPeriod.Once)
     {
         Remove?.Invoke();
     }
 }
Exemple #8
0
        /// <summary>
        /// 建立监听
        /// </summary>
        public void Connection()
        {
            if (token == "")
            {
                throw new Exception("请先调用登录方法");
            }
            webSocket            = new WebSocket(address);
            webSocket.OnMessage += (sender, e) =>
            {
                if (e.Data.StartsWith("error"))
                {
                    throw new Exception(e.Data);
                }
                Console.WriteLine("Get Data : " + e.Data);
                var index = e.Data.IndexOf(' ');
                if (index < 0)
                {
                    return;
                }
                var value = JsonConvert.DeserializeObject <Dictionary <string, object> >(JsonConvert.SerializeObject(e.Data.Substring(index + 1)));
                callback?.Invoke(new EventEntity(api)
                {
                    Id       = value.Keys.ToList().Contains("id") ? value["id"]?.ToString() : null,
                    Title    = value.Keys.ToList().Contains("title") ? value["title"]?.ToString() : null,
                    Cover    = value.Keys.ToList().Contains("cover") ? value["cover"]?.ToString() : null,
                    Abstract = value.Keys.ToList().Contains("abstract") ? value["abstract"]?.ToString() : null,
                });
            };

            webSocket.OnOpen += (sender, e) =>
            {
                Console.WriteLine("OnOpen ...");
            };

            webSocket.OnClose += (sender, e) =>
            {
                Console.WriteLine("Close ...");
                if (close)
                {
                    return;
                }
                webSocket.Close();
                Connection();
            };
            webSocket.OnError += (sender, e) =>
            {
                Console.WriteLine("OnError ...");
            };
            webSocket.Connect();
            Console.WriteLine("连接成功 ...");
        }
Exemple #9
0
        public void OnListChanged()
        {
            if (Parent != null)
            {
                OnResize();
            }

            if (SelectedIndex >= p_list.Count)
            {
                UnSelect();
            }

            OnListChange?.Invoke(this);
        }
Exemple #10
0
        protected virtual void TriggerEvent(ScheduledTask task, EventCallback cb = null)
        {
            if (task.ExecutionTarget == ExecutionTargetContext.Async ||
                task.ExecutionTarget == ExecutionTargetContext.NextAsyncFrame ||
                task.ExecutionTarget == ExecutionTargetContext.EveryAsyncFrame)
            {
                asyncTaskRunner.NotifyTaskScheduled();
            }

            TaskScheduleEvent e = new TaskScheduleEvent(task);

            if (!(task.Owner is IEventEmitter owner))
            {
                return;
            }

            IEventBus eventBus = Container.Resolve <IEventBus>();

            if (eventBus == null)
            {
                InternalTasks.Add(task);
                cb?.Invoke(owner, null);
                return;
            }

            eventBus.Emit(owner, e, async @event =>
            {
                task.IsCancelled = e.IsCancelled;

                if (!e.IsCancelled)
                {
                    InternalTasks.Add(task);
                }

                cb?.Invoke(owner, @event);
            });
        }
        public void LoadYear(EventCallback <RealmEventArgs> callback)
        {
            _callback = callback;

            try
            {
                var monthsInOrder = _dbContext.Months.OrderBy(x => x.SortOrder).Select(month => month.Id).ToList();
                _callback?.Invoke(new RealmEventArgs(new EventTable {
                    { "Months", monthsInOrder }
                }));
            }
            catch (Exception ex)
            {
                ex.Handle(ExceptionHandlingOptions.RecordAndThrow);
            }
        }
        /// <summary>
        /// Convenience Setup method. It sets the <see cref="IBindable.bindingPath"/> of the tracker, registers a callback and sets an initial value.
        /// </summary>
        /// <param name="propertyPath">Path of the property to be tracked</param>
        /// <param name="callback">Set a callback to be called when the property changes</param>
        /// <param name="initialValue">The initial value of the property. Set it to avoid triggering the callback when the element is bound.</param>
        public void SetUp(string propertyPath, EventCallback <ChangeEvent <TValue> > callback, TValue initialValue = default)
        {
            SetValueWithoutNotify(initialValue);
            bindingPath          = propertyPath;
            valueChangedCallback = callback;

            // There's a issue present at least in Unity 2020.2.7f1, maybe also in older/newer versions, where ChangeEvents are fired on every
            // binding, even if the value hasn't changed. We'll submit a bug report, but on the chance that Unity considers this an expected
            // behavior, here's a fix for us.
            this.RegisterValueChangedCallback(e =>
            {
                if (!EqualityComparer <TValue> .Default.Equals(e.previousValue, e.newValue))
                {
                    valueChangedCallback?.Invoke(e);
                }
            });
        }
        /// <summary>
        /// Called every time the list itself changes (items added / removed).
        /// </summary>
        protected void OnListChanged()
        {
            // if already placed in a parent, call the resize event to recalculate scollbar and labels
            if (_parent != null)
            {
                OnResize();
            }

            // make sure selected index is valid
            if (SelectedIndex >= _list.Count)
            {
                Unselect();
            }

            // invoke list change callback
            OnListChange?.Invoke(this);
        }
        private static int AddCallback(ComponentSystem sys, Entity uiControl, TypeManager.FieldInfo field, bool watchNegative, EventCallback callback)
        {
            if (!sys.World.EntityManager.Exists(uiControl))
            {
                return(-1);
            }

            var watchers = sys.World.GetExistingSystem <UIControlsWatchersSystem>();

            return(watchers.WatchChanged(uiControl, field, (Entity e, bool oldValue, bool value, Watcher source) =>
            {
                if (value ^ watchNegative)
                {
                    callback?.Invoke(e);
                }

                return true;
            }));
        }
        private void OnLoadComplete(RealmEventArgs args)
        {
            Validation.IsNotNull(args, "args");
            Validation.IsNotNull(args.Data, "args.Data");

            var data = args.Data.ToDictionaryAtom();

            if (!data.GetBool("success"))
            {
                _log.ErrorFormat("Failure to load data in {0}", GetType());
                return;
            }

            var commandResult = data.GetAtom <ListAtom>("commandResult").Get(0).CastAs <DictionaryAtom>();

            _callback?.Invoke(
                new RealmEventArgs(new EventTable {
                { "results", commandResult.GetAtom <ListAtom>("Results") }
            }));
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="args"></param>
        private void OnLoadComplete(RealmEventArgs args)
        {
            Validation.IsNotNull(args, "args");
            Validation.IsNotNull(args.Data, "args.Data");

            var data = args.Data.ToDictionaryAtom();

            if (!data.GetBool("success"))
            {
                _log.ErrorFormat("Failure to load data in {0}", GetType());
                return;
            }

            var commandResult = data.GetAtom <ListAtom>("commandResult").Get(0).CastAs <DictionaryAtom>();

            PopulateHashRepository(commandResult.GetAtom <ListAtom>("Results"));

            _log.DebugFormat("{0} hashes loaded.", _repository.Count);
            _callback?.Invoke(new RealmEventArgs());
        }
 public void OnPointerEnter(PointerEventData eventData)
 {
     onPointerEnter.Invoke(eventData);
 }
 public void OnPointerClick(PointerEventData eventData)
 {
     onPointerClick.Invoke(eventData);
 }
 public void OnPointerExit(PointerEventData eventData)
 {
     onPointerExit.Invoke(eventData);
 }
Exemple #20
0
        public virtual void Subscribe <TEvent>(IOpenModComponent component, EventCallback <TEvent> callback) where TEvent : IEvent
        {
            if (!component.IsComponentAlive)
            {
                return;
            }

            var attribute = GetEventListenerAttribute(callback.Method);

            m_EventSubscriptions.Add(new EventSubscription(component, (serviceProvider, sender, @event) => callback.Invoke(serviceProvider, sender, (TEvent)@event), attribute, typeof(TEvent), component.LifetimeScope.BeginLifetimeScope()));
        }
 public void OnPointerUp(PointerEventData eventData)
 {
     onPointerUp.Invoke(eventData);
 }
 public void OnDrag(PointerEventData eventData)
 {
     Debug.Log("Drag");
     onDrag.Invoke(eventData);
 }
 public void OnEndDrag(PointerEventData eventData)
 {
     onEndDrag.Invoke(eventData);
 }
Exemple #24
0
        /// <summary>
        /// Create the DropDown list.
        /// </summary>
        /// <param name="size">List size (refers to the whole size of the list + the header when dropdown list is opened).</param>
        /// <param name="anchor">Position anchor.</param>
        /// <param name="offset">Offset from anchor position.</param>
        /// <param name="skin">Panel skin to use for this DropDown list and header.</param>
        public DropDown(Vector2 size, Anchor anchor = Anchor.Auto, Vector2?offset = null, PanelSkin skin = PanelSkin.ListBackground) :
            base(size, anchor, offset)
        {
            // default padding of self is 0
            Padding = Vector2.Zero;

            // to get collision right when list is opened
            UseActualSizeForCollision = true;

            // create the panel and paragraph used to show currently selected value (what's shown when drop-down is closed)
            _selectedTextPanel     = new Panel(new Vector2(0, SelectedPanelHeight), skin, Anchor.TopLeft);
            _selectedTextParagraph = UserInterface.DefaultParagraph(string.Empty, Anchor.CenterLeft);
            _selectedTextParagraph.UseActualSizeForCollision = false;
            _selectedTextParagraph.UpdateStyle(SelectList.DefaultParagraphStyle);
            _selectedTextParagraph.UpdateStyle(DefaultParagraphStyle);
            _selectedTextParagraph.UpdateStyle(DefaultSelectedParagraphStyle);
            _selectedTextPanel.AddChild(_selectedTextParagraph, true);

            // create the arrow down icon
            _arrowDownImage = new Image(Resources.ArrowDown, new Vector2(ArrowSize, ArrowSize), ImageDrawMode.Stretch, Anchor.CenterRight, new Vector2(-10, 0));
            _selectedTextPanel.AddChild(_arrowDownImage, true);

            // create the list component
            _selectList = new SelectList(size, Anchor.TopCenter, Vector2.Zero, skin);

            // update list offset and space before
            _selectList.SetOffset(new Vector2(0, SelectedPanelHeight));
            _selectList.SpaceBefore = Vector2.Zero;

            // add the header and select list as children
            AddChild(_selectedTextPanel);
            AddChild(_selectList);

            // add callback on list value change
            _selectList.OnValueChange = (Entity entity) =>
            {
                // hide list
                ListVisible = false;

                // set selected text
                _selectedTextParagraph.Text = (SelectedValue ?? DefaultText);
            };

            // hide the list by default
            _selectList.Visible = false;

            // setup the callback to show / hide the list when clicking the dropbox
            _selectedTextPanel.OnClick = (Entity self) =>
            {
                // change visibility
                ListVisible = !ListVisible;
            };

            // set starting text
            _selectedTextParagraph.Text = (SelectedValue ?? DefaultText);

            // update styles
            _selectList.UpdateStyle(DefaultStyle);

            // make the list events trigger the dropdown events
            _selectList.OnListChange       += (Entity entity) => { OnListChange?.Invoke(this); };
            _selectList.OnMouseDown        += (Entity entity) => { OnMouseDown?.Invoke(this); };
            _selectList.OnMouseReleased    += (Entity entity) => { OnMouseReleased?.Invoke(this); };
            _selectList.WhileMouseDown     += (Entity entity) => { WhileMouseDown?.Invoke(this); };
            _selectList.WhileMouseHover    += (Entity entity) => { WhileMouseHover?.Invoke(this); };
            _selectList.OnClick            += (Entity entity) => { OnClick?.Invoke(this); };
            _selectList.OnValueChange      += (Entity entity) => { OnValueChange?.Invoke(this); };
            _selectList.OnMouseEnter       += (Entity entity) => { OnMouseEnter?.Invoke(this); };
            _selectList.OnMouseLeave       += (Entity entity) => { OnMouseLeave?.Invoke(this); };
            _selectList.OnMouseWheelScroll += (Entity entity) => { OnMouseWheelScroll?.Invoke(this); };
            _selectList.OnStartDrag        += (Entity entity) => { OnStartDrag?.Invoke(this); };
            _selectList.OnStopDrag         += (Entity entity) => { OnStopDrag?.Invoke(this); };
            _selectList.WhileDragging      += (Entity entity) => { WhileDragging?.Invoke(this); };
            _selectList.BeforeDraw         += (Entity entity) => { BeforeDraw?.Invoke(this); };
            _selectList.AfterDraw          += (Entity entity) => { AfterDraw?.Invoke(this); };
            _selectList.BeforeUpdate       += (Entity entity) => { BeforeUpdate?.Invoke(this); };
            _selectList.AfterUpdate        += (Entity entity) => { AfterUpdate?.Invoke(this); };

            // make the selected value panel trigger the dropdown events
            _selectedTextPanel.OnMouseDown        += (Entity entity) => { OnMouseDown?.Invoke(this); };
            _selectedTextPanel.OnMouseReleased    += (Entity entity) => { OnMouseReleased?.Invoke(this); };
            _selectedTextPanel.WhileMouseDown     += (Entity entity) => { WhileMouseDown?.Invoke(this); };
            _selectedTextPanel.WhileMouseHover    += (Entity entity) => { WhileMouseHover?.Invoke(this); };
            _selectedTextPanel.OnClick            += (Entity entity) => { OnClick?.Invoke(this); };
            _selectedTextPanel.OnValueChange      += (Entity entity) => { OnValueChange?.Invoke(this); };
            _selectedTextPanel.OnMouseEnter       += (Entity entity) => { OnMouseEnter?.Invoke(this); };
            _selectedTextPanel.OnMouseLeave       += (Entity entity) => { OnMouseLeave?.Invoke(this); };
            _selectedTextPanel.OnMouseWheelScroll += (Entity entity) => { OnMouseWheelScroll?.Invoke(this); };
            _selectedTextPanel.OnStartDrag        += (Entity entity) => { OnStartDrag?.Invoke(this); };
            _selectedTextPanel.OnStopDrag         += (Entity entity) => { OnStopDrag?.Invoke(this); };
            _selectedTextPanel.WhileDragging      += (Entity entity) => { WhileDragging?.Invoke(this); };
            _selectedTextPanel.BeforeDraw         += (Entity entity) => { BeforeDraw?.Invoke(this); };
            _selectedTextPanel.AfterDraw          += (Entity entity) => { AfterDraw?.Invoke(this); };
            _selectedTextPanel.BeforeUpdate       += (Entity entity) => { BeforeUpdate?.Invoke(this); };
            _selectedTextPanel.AfterUpdate        += (Entity entity) => { AfterUpdate?.Invoke(this); };
        }
 public void OnPointerDown(PointerEventData eventData)
 {
     Debug.Log("Pointer Down");
     onPointerDown.Invoke(eventData);
 }