コード例 #1
0
ファイル: CommandExec.cs プロジェクト: yekoufeng/bucket
        /// <inheritdoc />
        protected override int Execute(IInput input, IOutput output)
        {
            var    io     = GetIO();
            var    bucket = GetBucket();
            string binary = input.GetArgument("binary");

            if (input.GetOption("list") || string.IsNullOrEmpty(binary))
            {
                OutputList(bucket, io);
                return(ExitCodes.Normal);
            }

            var dispatcher = bucket.GetEventDispatcher();

            if (output.IsNormal)
            {
                output.SetVerbosity(OutputOptions.VerbosityQuiet);
            }

            var scriptEventArgs = new ScriptEventArgs("__exec_command", bucket, io, true, input.GetArgument("args"));

            dispatcher.AddListener("__exec_command", (sender, eventArgs) =>
            {
                if (dispatcher is BEventDispatcher bucketEventDispatcher)
                {
                    bucketEventDispatcher.ExecuteScript(binary, sender, (ScriptEventArgs)eventArgs);
                    return;
                }

                throw new NotSupportedException("The \"exec\" command can be used only when the event system is BucketEventSystem.");
            });

            dispatcher.Dispatch(this, scriptEventArgs);
            return(scriptEventArgs.ExitCode);
        }
コード例 #2
0
        public ScriptEventArgs CallEvent(string name, ScriptEventArgs args)
        {
            if (Globals.PrintEvents)
            {
                if (name.ToLower().Contains("update") && Globals.PrintEventUpdates)
                {
                    Log.Custom("Event called: " + name, "ATTN", ConsoleColor.DarkCyan, ConsoleColor.Cyan);
                }
                else if (!name.ToLower().Contains("update"))
                {
                    Log.Custom("Event called: " + name, "ATTN", ConsoleColor.DarkCyan, ConsoleColor.Cyan);
                }
            }

            if (!hooks.ContainsKey(name))
            {
                args.Canceled = false;
                return(args);
            }

            // ToArray because if event removes a function from this event, it'll cause an exception. (collection modified)
            foreach (object function in hooks[name].ToArray())
            {
                ScriptHandlers.ForEach(sh => sh.CallFunction(function, args));
            }

            return(args);
        }
コード例 #3
0
        private void OnPublishModelScriptError(object sender, ScriptEventArgs e)
        {
            this.CancellationToken.ThrowIfCancellationRequested();

            Logger.Write(
                TraceEventType.Verbose,
                string.Format(
                    "Sending scripting error progress event, Urn={0}, OperationId={1}, Sequence={2}, Completed={3}, Error={4}",
                    e.Urn,
                    this.OperationId,
                    this.eventSequenceNumber,
                    e.Completed,
                    e?.Error?.ToString() ?? "null"));

            // Keep scripting...it's a best effort operation.
            e.ContinueScripting = true;

            this.SendProgressNotificationEvent(new ScriptingProgressNotificationParams
            {
                ScriptingObject = e.Urn?.ToScriptingObject(),
                Status          = e.GetStatus(),
                CompletedCount  = this.scriptedObjectCount,
                TotalCount      = this.totalScriptedObjectCount,
                ErrorMessage    = e?.Error?.Message,
                ErrorDetails    = e?.Error?.ToString(),
            });
        }
コード例 #4
0
        /// <summary>
        /// Execute a command by its name
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        public void OnInputEvent(object sender, ScriptEventArgs e)
        {
            string cmd = (string)e.Data;

            if (cmd.Length > 0)
            {
                var stringArray = cmd.Split(' ');

                string command = stringArray[0].ToLower();

                Func <string[], string> func;

                if (_commands.TryGetValue(command, out func))
                {
                    string[] args = stringArray.Skip(1).ToArray();

                    string text = func?.Invoke(args);

                    if (text.Length > 0)
                    {
                        _frontendMgr.WriteLine(text);
                    }

                    else
                    {
                        _frontendMgr.WriteLine("Success");
                    }
                }
            }
        }
コード例 #5
0
        private void OnPublishModelScriptProgress(object sender, ScriptEventArgs e)
        {
            this.CancellationToken.ThrowIfCancellationRequested();

            if (e.Completed)
            {
                this.scriptedObjectCount += 1;
            }

            Logger.Write(
                LogLevel.Verbose,
                string.Format(
                    "Sending progress event, Urn={0}, OperationId={1}, Sequence={2}, Status={3}, Error={4}",
                    e.Urn,
                    this.OperationId,
                    this.eventSequenceNumber,
                    e.GetStatus(),
                    e?.Error?.ToString() ?? "null"));

            this.SendProgressNotificationEvent(new ScriptingProgressNotificationParams
            {
                ScriptingObject = e.Urn.ToScriptingObject(),
                Status          = e.GetStatus(),
                CompletedCount  = this.scriptedObjectCount,
                TotalCount      = this.totalScriptedObjectCount,
                ErrorMessage    = e?.Error?.Message,
                ErrorDetails    = e?.Error?.ToString(),
            });
        }
コード例 #6
0
        public void OnInputEvent(object sender, ScriptEventArgs e)
        {
            var cmd = (string)e.Data;

            if (cmd.Length <= 0)
            {
                return;
            }

            var stringArray = cmd.Split(' ');

            var command = stringArray[0].ToLower();

            if (!_commands.TryGetValue(command, out var func))
            {
                return;
            }

            var args = stringArray.Skip(1).ToArray();

            var text = func?.Invoke(args);

            if (!string.IsNullOrEmpty(text))
            {
                _frontendMgr.WriteLine(text);
            }
        }
コード例 #7
0
        /// <summary>
        /// Track when and how this event was invoked first time;
        /// Only for development to learn if and when events are called.
        /// </summary>
        private static void TrackInvocation(ScriptEvent eventType, ScriptEventArgs eventArgs)
        {
            var invocationLog = Environment.NewLine +
                                DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + Environment.NewLine +
                                JsonMapper.ToJson(eventArgs) + Environment.NewLine +
                                Environment.StackTrace;

            var invokedEvent = PersistentData.Instance.InvokedEvents.FirstOrDefault(ie => ie.EventName == eventType.ToString());

            if (invokedEvent == null)
            {
                invokedEvent = new PersistentData.InvokedEvent()
                {
                    EventName = eventType.ToString(),
                    LastCalls = new List <string>()
                };
                PersistentData.Instance.InvokedEvents.Add(invokedEvent);
            }

            // Rotate last 10 call logs with newest on top
            if (invokedEvent.LastCalls.Count == 10)
            {
                invokedEvent.LastCalls.RemoveAt(invokedEvent.LastCalls.Count - 1);
            }
            invokedEvent.LastCalls.Insert(0, invocationLog.Indent(10) + Environment.NewLine + new string(' ', 8));

            PersistentData.Instance.SaveLater();
        }
コード例 #8
0
        private void OnKeyDown(object sender, ScriptEventArgs e)
        {
            var keyArgs = e.Data as KeyEventArgs;

            if (keyArgs == null)
            {
                return;
            }

            if (!ScriptThread.GetVar <bool>("enableconsole"))
            {
                return;
            }

            if (keyArgs.KeyCode == Keys.CapsLock)
            {
                _capsLock = !_capsLock;
            }

            if (!_showingConsole)
            {
                if (keyArgs.KeyCode == ScriptThread.GetVar <Keys>("toggleconsole"))
                {
                    ShowConsole();
                }
            }

            else
            {
                GetConsoleInput(keyArgs);
            }
        }
コード例 #9
0
        private void _mainForm_ScriptPanelCheckedChanged(object sender, ScriptEventArgs e)
        {
            var box    = (MyCheckBox)sender;
            var script = box.Script;

            script.Enabled = box.Checked;
            _mainForm.LeSettings.ScriptStatus[script.ScriptName] = box.Checked;
            box.Refresh();
        }
コード例 #10
0
        protected virtual void OnScriptOpened(object sender, ScriptEventArgs e)
        {
            EventHandler <ScriptEventArgs> handler = ScriptOpened;

            if (handler != null)
            {
                handler(sender, e);
            }
        }
コード例 #11
0
        private void _mainForm_TrayScriptEnableClick(object sender, ScriptEventArgs e)
        {
            var menuItem = (MenuItem)sender;

            if (e.Script.Enabled)
            {
                e.Script.Enabled = false;
                menuItem.Text    = "Enable";
            }
            else
            {
                e.Script.Enabled = true;
                menuItem.Text    = "Disable";
            }
            _mainForm.LeSettings.ScriptStatus[e.Script.ScriptName] = e.Script.Enabled;
            RefreshPanel();
        }
コード例 #12
0
        protected override void HandleEvent(object source, ScriptEventArgs data)
        {
            var playerShip = GameObj?.ParentScene?.FindComponent <PlayerShipController>()?.GameObj?.GetComponent <Ship>();

            switch (data.Script)
            {
            case "GetPlayerShipName":
                if (data.TargetElement != null && playerShip != null)
                {
                    data.TargetElement.InnerRml = playerShip.GivenName;
                }
                break;

            case "ShowInventory":
                GameObj.GetComponent <InventoryScreen>()?.Show();
                break;
            }
        }
コード例 #13
0
ファイル: CommandRunScript.cs プロジェクト: yekoufeng/bucket
        /// <inheritdoc />
        protected override int Execute(IInput input, IOutput output)
        {
            if (input.GetOption("list"))
            {
                return(ListScripts(output));
            }

            string script = input.GetArgument("script");

            if (string.IsNullOrEmpty(script))
            {
                throw new RuntimeException("Missing required argument \"script\"");
            }

            var defiendEvents  = new HashSet <string>(ScriptEvents.GetEvents());
            var disabledScript = script.ToUpper().Replace("-", "_");

            if (!defiendEvents.Contains(script) && defiendEvents.Contains(disabledScript))
            {
                throw new RuntimeException($"Script \"{script}\" cannot be run with this command");
            }

            var bucket          = GetBucket();
            var devMode         = input.GetOption("dev") || !input.GetOption("no-dev");
            var eventDispatcher = bucket.GetEventDispatcher();

            if (!eventDispatcher.HasListener(script))
            {
                throw new RuntimeException($"Script \"{script}\" is not defined in this package");
            }

            string[] args    = input.GetArgument("args");
            string   timeout = input.GetOption("timeout");

            if (timeout != null)
            {
                BucketProcessExecutor.SetDefaultTimeout(int.Parse(timeout));
            }

            var eventArgs = new ScriptEventArgs(script, bucket, GetIO(), devMode, args);

            eventDispatcher.Dispatch(this, eventArgs);
            return(eventArgs.ExitCode);
        }
コード例 #14
0
ファイル: EventMgr.cs プロジェクト: zhxhxlzt/UnityPublic
 /// <summary>
 /// 发送事件
 /// </summary>
 /// <param name="args"></param>
 public void SendEvent(string eventName, ScriptEventArgs args, EventRcvMode mode = EventRcvMode.Sync)
 {
     if (args == null)
     {
         args = ScriptEventArgs.Empty;
     }
     args.EventName = eventName;
     if (mode == EventRcvMode.Async)
     {
         m_eventQueue.Enqueue(args);
     }
     else
     {
         if (m_registers.TryGetValue(eventName, out var registers))
         {
             registers.Invoke(args);
         }
     }
 }
コード例 #15
0
        /// <summary>
        /// Invokes all subscribed actions (scripts, logging, etc.) for the event with the given type.
        /// </summary>
        /// <param name="eventType">The type of the event that is being invoked</param>
        /// <param name="eventArgsCallback">
        /// Event args passed as delegate to defer object creation to when/if it is actually needed.
        /// The callback is only called once at most, and all actions are performed with the same resulting ScriptEventArgs
        /// </param>
        public static void InvokeScriptEvents(ScriptEvent eventType, Func <ScriptEventArgs> eventArgsCallback)
        {
            try
            {
                // ReSharper disable once RedundantAssignment
                ScriptEventArgs eventArgs = null;

#if DEBUG
                eventArgs = eventArgsCallback();
                TrackInvocation(eventType, eventArgs);
#endif

                if (PersistentData.Instance.LogEvents.Contains(eventType))
                {
                    // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                    if (eventArgs == null)
                    {
                        eventArgs = eventArgsCallback();
                    }
                    Log.Out("[EVENT] [" + eventType + "] " + JsonMapper.ToJson(eventArgs));
                }

                if (_events[(int)eventType] != null)
                {
                    // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                    if (eventArgs == null)
                    {
                        eventArgs = eventArgsCallback();
                    }
                    foreach (var filePath in _events[(int)eventType])
                    {
                        var scriptEngine = ScriptEngine.GetInstance(Path.GetExtension(filePath));
                        scriptEngine.ExecuteEvent(filePath, eventType, eventArgs);
                    }
                }
            }
            catch (Exception ex)
            {
                CommandTools.HandleEventException(ex);
            }
        }
コード例 #16
0
        /// <summary>
        /// Gets the status of a scripting operation for the passed scripting event.
        /// </summary>
        /// <param name="e">The scripting event.</param>
        /// <returns>The status.</returns>
        public static string GetStatus(this ScriptEventArgs e)
        {
            Validate.IsNotNull("e", e);

            string status = null;

            if (e.Error != null)
            {
                status = "Error";
            }
            else if (e.Completed)
            {
                status = "Completed";
            }
            else
            {
                status = "Progress";
            }

            return(status);
        }
コード例 #17
0
 void Instance_PlayVideo(object sender, ScriptEventArgs <string> e)
 {
     Player.PlayVideo(e.Result);
 }
コード例 #18
0
 /// <summary>
 /// Raise an event with the specified name and arguments.
 /// </summary>
 /// <param name="name">The name of the event.</param>
 /// <param name="args">Event specific arguments.</param>
 public void NotifyEvent(string name, ScriptEventArgs args)
 {
     Events[name]?.Invoke(this, args);
 }
コード例 #19
0
 private void _mainForm_ScriptPanelActionClick(object sender, ScriptEventArgs e)
 {
     e.Script.Enabled = false;
     e.Script.Action();
     RefreshPanel();
 }
コード例 #20
0
 public T CallEvent <T>(string name, ScriptEventArgs args) where T : ScriptEventArgs
 {
     return((T)CallEvent(name, args));
 }
コード例 #21
0
ファイル: ShipRefitScene.cs プロジェクト: raycrasher/Fell-Sky
 public void HandleScriptEvent(object sender, ScriptEventArgs args)
 {
     switch (args.Script)
     {
         case "Refit_ChangeMode_Weapons":
             SetMode(EditorMode.Weapons);
             break;
         case "Refit_ChangeMode_Armor":
             SetMode(EditorMode.Armor);
             break;
         case "Refit_ChangeMode_Modules":
             SetMode(EditorMode.Modules);
             break;
         case "Refit_ChangeMode_Build":
             SetMode(EditorMode.Build);
             break;
         case "Refit_ChangeMode_RunSim":
             SetMode(EditorMode.Simulator);
             break;
         case "Refit_CloseScene":
             if (PreviousState != null)
             {
                 GameEngine.Instance.CurrentScene = PreviousState;
                 foreach(var item in Fleet)
                 {
                     item.Variant.ApplyVariant(OrigWorld, item.OrigEntity);
                 }
                 return;
             }
             break;
     }
     if (args.Script.StartsWith("Refit_ChangeMode"))
     {
         Document.GetElementById("availablePartsList").SetProperty("display", "none");
         foreach (var element in Document.GetElementById("navigation").Children)
         {
             element.SetClass("selectedmode", false);
         }
         args.TargetElement.SetClass("selectedmode", true);
     }
 }
 void Instance_PlayVideo(object sender, ScriptEventArgs<string> e)
 {
     Player.PlayVideo(e.Result);
 }
コード例 #23
0
ファイル: MainMenuScene.cs プロジェクト: raycrasher/Fell-Sky
 private void OnScriptEvent(object sender, ScriptEventArgs e)
 {
     switch (e.Script)
     {
         case "MainMenu_Show":
             document.GetElementById("options")?.SetProperty("display", "none");
             break;
         case "MainMenu_Continue":
             document.GetElementById("options")?.SetProperty("display", "none");
             GameEngine.Instance.CurrentScene = GameEngine.Instance.SystemMapScene;
             break;
         case "MainMenu_Options":
             document.GetElementById("options")?.SetProperty("display", "block");
             break;
         case "MainMenu_Editor":
             document.GetElementById("options")?.SetProperty("display", "none");
             GameEngine.Instance.CurrentScene = GameEngine.Instance.ShipRefitScene;
             break;
         case "MainMenu_Exit":
             GameEngine.Instance.Exit();
             break;
     }
 }
コード例 #24
0
 private void Proc_AfterInvoke(object sender, ScriptEventArgs e)
 {
     WARN(FormatArguments(e.Arguments));
 }
コード例 #25
0
 private void OnScriptEvent(object sender, ScriptEventArgs e)
 {
     Scene.FireEvent(this, e);
 }
コード例 #26
0
 private void OnKeyDown(object sender, ScriptEventArgs e)
 {