public MainWindow()
        {
            InitializeComponent();

            // initialize the EyeX Engine client library.
            system = InteractionSystem.Initialize(LogTarget.Trace);

            // create a context, register event handlers, and enable the connection to the engine.
            context = new InteractionContext(false);
            context.RegisterQueryHandlerForCurrentProcess(HandleQuery);
            context.RegisterEventHandler(HandleEvent);
            context.EnableConnection();

            // enable gaze point tracking over the entire window
            InitializeGlobalInteractorSnapshot();
            context.ConnectionStateChanged += (object s, ConnectionStateChangedEventArgs ce) =>
            {
                if (ce.State == ConnectionState.Connected)
                {
                    globalInteractorSnapshot.Commit((InteractionSnapshotResult isr) => { });
                }
            };

            // enable gaze triggered buttons
            gazeAwareButtons = new Dictionary<InteractorId, Button>();
            initalizeGazeAwareButtons();
        }
Example #2
0
 public override InteractionResult Handle(InteractionContext context)
 {
     if (context.Request.CurrentStoryId.IsEmpty)
         return Error("Please select a story first");
     context.Response.SendToProject(new AddTask(context.Request.Data, context.Request.CurrentStoryId));
     return Handled();
 }
Example #3
0
 public override InteractionResult Handle(InteractionContext context)
 {
     Identity id;
     var source = context.Request.Data;
     if (string.IsNullOrEmpty(source))
     {
         id = context.Request.CurrentStoryId;
         if (id.IsEmpty)
         {
             return Error("Id was not specified and there is no focused story");
         }
     }
     else if (!context.Request.TryGetId(source, out id))
     {
         return Error("Could not find story ID '{0}'", source);
     }
     var store = context.Storage;
     if (id is StoryId)
     {
         var result = store.GetEntity<StoryView>(id);
         if (!result.HasValue)
         {
             return Error("Story id not found '{0}'", id);
         }
         var story = result.Value;
         var activities = store.GetEntity<ActivityList>(id).GetValue(new ActivityList());
         var tasks = store.GetEntity<TaskList>(id).GetValue(new TaskList());
         var notes = store.GetEntity<NoteList>(id).GetValue(new NoteList());
         var composite = new FocusComposite(story.StoryId, story.Name, activities.List, tasks.List, notes.Notes);
         context.Response.RenderView(composite);
         context.Response.FocusStory(story.StoryId, story.Name);
         return Handled();
     }
     if (id is TagId)
     {
         var result = store.GetEntity<TagView>(id);
         if (!result.HasValue)
         {
             return Error("Tag not found '{0}'", id);
         }
         var view = result.Value;
         var stories = view.Stories
             .Select(s => store.GetEntity<StoryView>(s.Story))
             .Where(o => o.HasValue)
             .Select(o => o.Value)
             .ToList();
         var activities = stories.SelectMany(s => store.GetEntity<ActivityList>(s.StoryId).Convert(al => al.List, new List<ActivityList.Item>())).ToList();
         var tasks = stories.SelectMany(s => store.GetEntity<TaskList>(s.StoryId).Convert(al => al.List, new List<TaskList.Item>())).ToList();
         var notes = stories.SelectMany(s => store.GetEntity<NoteList>(s.StoryId).Convert(al => al.Notes, new List<NoteList.Item>())).ToList();
         var composite = new FocusComposite(id, view.Name, activities, tasks, notes);
         context.Response.RenderView(composite);
         return Handled();
     }
     return Error("Can't focus");
 }
Example #4
0
 public override InteractionResult Handle(InteractionContext context)
 {
     var items = context.Request.Data.Split(' ');
     Identity itemId;
     if (!context.Request.TryGetId(items[0], out itemId))
     {
         return Error("Failed to lookup item '{0}'", items[0]);
     }
     context.Response.SendToProject(new TagItem(items[1], itemId));
     return Handled();
 }
Example #5
0
        public override InteractionResult Handle(InteractionContext context)
        {
            var title = DateTime.Now.ToString("yyyy-MM-hh HH:mm");

            var txt = context.Request.Data;
            var storyId = context.Request.CurrentStoryId;
            if (!string.IsNullOrEmpty(txt))
            {
                title = txt;

            }
            context.Response.GrabFile("", (s, s1) => context.Response.SendToProject(new AddNote(title, s, storyId)));

            return Handled();
        }
Example #6
0
    public InteractResult OnActInteract(InteractionContext context)
    {
        if (!this.Fallen)
        {
            return(InteractResult.NoOp);
        }

        if (context.Parameters != null && context.Parameters.ContainsKey("id"))
        {
            this.PickupLog(context.Player, context.Parameters["id"]);
            return(InteractResult.Success);
        }

        return(InteractResult.NoOp);
    }
Example #7
0
        public override InteractionResult Handle(InteractionContext context)
        {
            var title = DateTime.Now.ToString("yyyy-MM-hh HH:mm");

            var txt     = context.Request.Data;
            var storyId = context.Request.CurrentStoryId;

            if (!string.IsNullOrEmpty(txt))
            {
                title = txt;
            }
            context.Response.GrabFile("", (s, s1) => context.Response.SendToProject(new AddNote(title, s, storyId)));

            return(Handled());
        }
Example #8
0
        public async Task Docs(InteractionContext ctx,
                               [Option("name", "Function name")] string name,
                               [Option("version", "Experimental or stable game version")]
                               Versions version)
        {
            var doc = this._docs.DocsDictionary[version.GetEnumDescription()];

            if (doc is null)
            {
                throw new NullReferenceException("There was an error while trying to get docs");
            }

            var(cat, func) = FindDoc(name, doc);

            if (cat is null && func is null)
            {
                var errMsg = new DiscordInteractionResponseBuilder()
                             .WithContent($"Function `{name}` not found.");
                await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, errMsg);

                return;
            }

            var baseUrl          = doc.BaseUrl;
            var funcName         = func !.Name;
            var argsFormatted    = FormatApiInputsAndOutputs(func.Arguments);
            var returnsFormatted = FormatApiInputsAndOutputs(func.Return);
            var info             = func.Info;
            var definition       = func.Def;
            var example          = $"```lua\n{func.Example}\n```";

            var embed = new DiscordEmbedBuilder();

            embed.WithTitle($"#{funcName}");
            embed.WithUrl($"{baseUrl}#{funcName}");
            embed.WithDescription($"`{definition}`\n\n{info}");
            embed.AddField("Arguments", argsFormatted);
            embed.AddField("Returns", returnsFormatted);
            embed.AddField("Example", example);
            embed.WithFooter($"API(game) Version: {doc.Version}");
            embed.WithColor(new DiscordColor(0xf0d080));

            var msg = new DiscordInteractionResponseBuilder()
                      .WithContent($"{baseUrl}#{funcName}")
                      .AddEmbed(embed.Build());

            await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, msg);
        }
    private bool TryDamageUnfelledTree(INetObject damager, float amount, InteractionContext context)
    {
        if (this.health > 0)
        {
            List <IAtomicAction> playerActions = new List <IAtomicAction>();
            if (damager is Player)
            {
                IAtomicAction statAction = PlayerActions.Harvest.CreateAtomicAction(((Player)damager).User, this);
                playerActions.Add(statAction);

                if (!statAction.CanApplyNonDisposing().Notify((Player)damager))
                {
                    // We only want to dispose the action if it is invalid.  Othewise we want to keep it around to possibly apply later.
                    statAction.Dispose();
                    return(false);
                }
                playerActions.Add(new SimpleAtomicAction(() => (context.SelectedItem as ToolItem).AddExperience(context.Player.User, 5 * this.Species.ExperienceMultiplier, Localizer.Format("felling a {0}", this.Species.UILink()))));
            }

            MultiAtomicAction playerAction = new MultiAtomicAction(playerActions);

            // damage trunk
            this.health = Mathf.Max(0, this.health - amount);

            this.RPC("UpdateHP", this.health / this.Species.TreeHealth);

            if (this.health <= 0)
            {
                this.health = 0;
                if (!playerAction.TryApply().Success)
                {
                    throw new Exception("Killing this tree was verified to be legal a moment ago, but is not anymore.");
                }
                this.FellTree(damager);
                EcoSim.PlantSim.KillPlant(this, DeathType.Harvesting);
            }
            else
            {
                playerAction.Dispose(); // Dispose the unused action
            }
            this.Save();
            return(true);
        }
        else
        {
            return(false);
        }
    }
            public async Task ConfigureJoinlogSuppressAsync(InteractionContext ctx)
            {
                await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource, new() { IsEphemeral = true });

                GuildConfig config = await guildConfig.FindOrCreateConfigAsync(ctx.Guild.Id);

                DiscordChannel current = ctx.Guild.GetChannel(config.JoinLogChannel);

                await ctx.FollowUpAsync(new DiscordFollowupMessageBuilder()
                {
                    Content = config.SuppressJoinlogCleanRecords
                                                ? "All clean records are currently suppressed from displaying in Joinlog."
                                                : "All records are displayed in Joinlog."
                }
                                        .AddComponents(new DiscordSelectComponent("sg-joinlog-suppress-select", "Turn Autoban on/off", GetToggleOptions(), maxOptions: 1)));
            }
Example #11
0
        private void HandleDeletionRequest(InteractionContext <INode, Unit> interaction)
        {
            var node      = interaction.Input;
            var connected = connections.Where(c => c.To.Node == node || c.From.Node == node);

            foreach (var connection in connected)
            {
                connection.To.ConnectedTo   = null;
                connection.From.ConnectedTo = null;
            }

            connections.RemoveAll(connected.ToArray());
            nodes.Remove(node);

            interaction.SetOutput(Unit.Default);
        }
    public override Task <bool> ExecuteChecksAsync(InteractionContext ctx)
    {
        if (ctx.Interaction.GuildId == null)
        {
            return(Task.FromResult(AllowDirectMessages));
        }
        using var dbctx = (DatabaseContext)ctx.Services.GetService(typeof(DatabaseContext));
        var guildsettings = dbctx.GetServerSettings(ctx.Guild.Id);
        var compareval    = typeof(ServerSettings).GetProperty(Variable).GetValue(guildsettings);

        if (Equals(compareval, State))
        {
            return(Task.FromResult(true));
        }
        return(Task.FromResult(false));
    }
Example #13
0
    public override InteractResult OnActRight(InteractionContext context)
    {
        var currentBlock = context.Player.User.Inventory.Carried.Stacks.First().Item as BlockItem;

        if (currentBlock != null && context.HasBlock && context.Normal != Vector3i.Zero)
        {
            var result = currentBlock.OnActRight(context);
            if (result == InteractResult.Success)
            {
                context.Player.User.Inventory.AddItem(currentBlock);
                return(result);
            }
        }

        return(InteractResult.NoOp);
    }
Example #14
0
 public override InteractResult OnActLeft(InteractionContext context)
 {
     if (context.HasTarget && context.Target is WorldObject)
     {
         BrokenComponent target = (context.Target as WorldObject).GetComponent <BrokenComponent>();
         if (target != null && target.Enabled == false)
         {
             if (context.Player.User.Inventory.TryRemoveItems(GetType(), 1))
             {
                 target.Repair();
                 return(InteractResult.Success);
             }
         }
     }
     return(InteractResult.NoOp);
 }
Example #15
0
 public override InteractResult OnActInteract(InteractionContext context)
 {
     if (context.Parameters != null && context.Parameters.ContainsKey("Down"))
     {
         var physicsEntity = this.netEntity as NetPhysicsEntity;
         physicsEntity.SetPhysicsController(context.Player);
         this.AnimatedStates["dir"] = -1f;
     }
     else if (context.Parameters != null && context.Parameters.ContainsKey("Up"))
     {
         var physicsEntity = this.netEntity as NetPhysicsEntity;
         physicsEntity.SetPhysicsController(context.Player);
         this.AnimatedStates["dir"] = 1f;
     }
     return(base.OnActInteract(context));
 }
Example #16
0
 protected override WW.Math.Point3D ProcessWcsPosition(
     InteractionContext context,
     WW.Math.Point3D p)
 {
     p = base.ProcessWcsPosition(context, p);
     if (this.ControlPointIndex == 1 && this.nullable_1.HasValue && this.nullable_1.Value > 0.0)
     {
         DxfLine entity = (DxfLine)this.Entity;
         if (p != entity.point3D_0)
         {
             Vector3D unit = (p - entity.point3D_0).GetUnit();
             p = entity.point3D_0 + unit * this.nullable_1.Value;
         }
     }
     return(p);
 }
            public async Task SetLoginAsync(InteractionContext ctx,
                                            [Option("username", "Account Username")] string username,
                                            [Option("password", "Account Password")] string password)
            {
                await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource, new() { IsEphemeral = true });

                GuildConfig config = await guildConfig.FindOrCreateConfigAsync(ctx.Guild.Id);

                config.ApiLogin = new() { Username = username, Password = encryption.Encrypt(password) };

                await guildConfig.UpdateOneAsync(
                    Builders <GuildConfig> .Filter.Eq(c => c.Id, config.Id),
                    Builders <GuildConfig> .Update.Set(c => c.ApiLogin, config.ApiLogin));

                await ctx.FollowUpAsync($"API credentials has been set.", true);
            }
Example #18
0
        void Window_PreselectionChanged(object sender, EventArgs e)
        {
            //if (IsDragging)
            //    return;

            // preselection can change without the mouse moving (e.g. just created a profile)
            Rendering = null;

            InteractionContext context = InteractionContext;
            Line cursorRay             = context.CursorRay;

            if (cursorRay != null)
            {
                OnMouseMove(context.Window.CursorPosition, cursorRay, Control.MouseButtons);
            }
        }
Example #19
0
        public override InteractionResult Handle(InteractionContext context)
        {
            var      splice = context.Request.Data.Split(new[] { ' ' }, 2);
            Identity guid;

            if (!context.Request.TryGetId(splice[0], out guid))
            {
                return(Error("Failed to look up ID for '{0}'", splice[0]));
            }
            if (splice.Length < 2)
            {
                return(Error("Did you miss a new name?"));
            }
            context.Response.SendToProject(new RenameItem(guid, splice[1]));
            return(Handled());
        }
        public virtual string Invalidates(InteractionContext ic)
        {
            INakedObject proposedArgument = ic.ProposedArgument;

            if (OutOfRange(proposedArgument) == 0)
            {
                return(null);
            }

            if (IsDateTime(proposedArgument.Object))
            {
                string minDate = DateTime.Today.AddDays(Min.ToDouble(null)).ToShortDateString();
                string maxDate = DateTime.Today.AddDays(Max.ToDouble(null)).ToShortDateString();
                return(string.Format(Resources.NakedObjects.RangeMismatch, minDate, maxDate));
            }
            return(string.Format(Resources.NakedObjects.RangeMismatch, Min, Max));
        }
Example #21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="KinkWizardInteractions"/> class.
 /// </summary>
 /// <param name="kinks">The kink service.</param>
 /// <param name="dataService">The in-memory data service.</param>
 /// <param name="feedback">The user feedback service.</param>
 /// <param name="channelAPI">The channel API.</param>
 /// <param name="interactionAPI">The interaction API.</param>
 /// <param name="context">The interaction context.</param>
 public KinkWizardInteractions
 (
     KinkService kinks,
     InMemoryDataService <Snowflake, KinkWizard> dataService,
     FeedbackService feedback,
     IDiscordRestChannelAPI channelAPI,
     IDiscordRestInteractionAPI interactionAPI,
     InteractionContext context
 )
 {
     _kinks          = kinks;
     _feedback       = feedback;
     _interactionAPI = interactionAPI;
     _context        = context;
     _dataService    = dataService;
     _channelAPI     = channelAPI;
 }
Example #22
0
        public ProspectData GetProspectData(InteractionContext context)
        {
            // On errors, or plant entities we have zero normal, that will broke dig results,
            // we need to replace dir with offset of 1 to start prospect from next block downside
            var rawDirection = context.Normal ?? Vector3i.Zero;
            var direction    = rawDirection == Vector3i.Zero ? Vector3i.Up : rawDirection;

            // Apply offset for starting pos by 1 in case we have unusual normal values
            var startingPos = context.BlockPosition.Value;

            if (rawDirection == Vector3i.Zero)
            {
                startingPos -= direction;
            }

            var result = new ProspectData(this, direction, this.DrillDepth);

            for (var i = 0; i < this.DrillDepth; i++)
            {
                if (this.CanProspect(context.Player, i + 1))
                {
                    var data = this.ProspectBlock(startingPos - (direction * i));
                    result.Items.Add(data);

                    // if we hit core, no need to drill further, exit
                    if (data.ItemTypeId == -2)
                    {
                        result.MaxBlocksCanProspect = i + 1;
                        break;
                    }
                }
                else
                {
                    // Clamp max blocks on failed cycle iteration for client-side checks (errors sync)
                    result.MaxBlocksCanProspect = i;
                    break;
                }
            }

            if (result.MaxBlocksCanProspect < 0)
            {
                result.MaxBlocksCanProspect = this.DrillDepth;
            }

            return(result);
        }
Example #23
0
        public virtual string Invalidates(InteractionContext ic)
        {
            INakedObject proposedArgument = ic.ProposedArgument;

            if (proposedArgument == null)
            {
                return(null);
            }
            string titleString = proposedArgument.TitleString();

            if (!DoesNotMatch(titleString))
            {
                return(null);
            }

            return(failureMessage ?? Resources.NakedObjects.InvalidEntry);
        }
Example #24
0
            private int method_1(InteractionContext context, WW.Math.Point2D mousePosition)
            {
                double tolerance = 0.5 * context.EditHandleSize;
                int    num       = -1;
                IControlPointCollection interactionControlPoints = this.Entity.InteractionControlPoints;
                Matrix4D matrix4D = context.ProjectionTransform * this.Entity.Transform;

                for (int index = 0; index < interactionControlPoints.Count; ++index)
                {
                    if (WW.Math.Point2D.AreApproxEqual((WW.Math.Point2D)matrix4D.Transform(interactionControlPoints.Get(index)), mousePosition, tolerance))
                    {
                        num = index;
                        break;
                    }
                }
                return(num);
            }
Example #25
0
        public override InteractResult OnActLeft(InteractionContext context)
        {
            // if I target a pipe with the wrench, I transform it to a connector set to input
            if (context.HasBlock && context.Block is BaseTransportPipeBlock && Utils.SearchForConnectedInventory(context.BlockPosition.Value) != null)
            {
                //Removing the block and add the connector
                World.DeleteBlock(context.BlockPosition.Value);
                ConnectorObject connector = WorldObjectManager.TryToAdd <ConnectorObject>(context.Player.User, context.BlockPosition.Value, Quaternion.Identity);
                // If the conenctor can't be added just reset the action
                if (connector == null)
                {
                    World.SetBlock(context.Block.GetType(), context.BlockPosition.Value);
                    return(InteractResult.NoOp);
                }
                // I instanciate the connector info with the info from the pipe
                TransportPipeInfo info = null;
                if (TransportPipeManager.pipesInfo.TryGetValue(context.BlockPosition.Value, out info))
                {
                    connector.info = info;
                    context.Player.SendTemporaryMessage($"Set to input");
                    connector.mode = CONNECTOR_MODE.Input;

                    BurnCalories(context.Player);
                    UseDurability(1.0f, context.Player);

                    return(InteractResult.Success);
                }
                else
                {
                    // If the pipe don't contains any info I recreate the linker from the pipe and reset the action
                    connector.Destroy();
                    World.SetBlock(context.Block.GetType(), context.BlockPosition.Value);
                    Utils.RecreateLinker(context.BlockPosition.Value, new TransportPipeLinker());
                }
            }
            // If I use the wrench on a connector
            if (context.HasTarget && context.Target is ConnectorObject)
            {
                // I process the config inside the connector class
                (context.Target as ConnectorObject).ProcessConfig(context);
                BurnCalories(context.Player);
                UseDurability(1.0f, context.Player);
                return(InteractResult.Success);
            }
            return(InteractResult.NoOp);
        }
Example #26
0
        public override InteractResult OnActLeft(InteractionContext context)
        {
            // Try harvest.
            if (context.HasBlock && context.Block.Is <Reapable>())
            {
                return((InteractResult)AtomicActions.HarvestPlantNow(this.CreateMultiblockContext(context), context.Player?.User.Inventory));
            }

            // Try interact with a world object.
            if (context.Target is WorldObject)
            {
                return(this.BasicToolOnWorldObjectCheck(context));
            }

            // Fallback.
            return(base.OnActLeft(context));
        }
Example #27
0
        protected override void OnPaint(PaintEventArgs e)
        {
            Graphics gr = e.Graphics;

            gdiGraphics3D.Draw(e.Graphics, ClientRectangle);
            if (currentInteractorDrawable != null)
            {
                InteractionContext context =
                    new InteractionContext(
                        GetClientRectangle2D(),
                        transformationProvider.CompleteTransform,
                        true,
                        new ArgbColor(BackColor.ToArgb())
                        );
                currentInteractorDrawable.Draw(e, graphicsHelper, context);
            }
        }
Example #28
0
        private void GetDirectoryHandler(InteractionContext <string, string?> interaction)
        {
            using var folderDialog = new FolderBrowserDialog
                  {
                      RootFolder = System.Environment.SpecialFolder.ProgramFilesX86
                  };
            switch (folderDialog.ShowDialog())
            {
            case DialogResult.OK:
                interaction.SetOutput(folderDialog.SelectedPath);
                break;

            default:
                interaction.SetOutput(null);
                break;
            }
        }
Example #29
0
    public override InteractResult OnActRight(InteractionContext context)
    {
        User owner;
        User creator;
        var  currentBlock = context.Player.User.Inventory.Carried.Stacks.First().Item as BlockItem;

        if (currentBlock != null && context.HasBlock && context.Normal != Vector3i.Zero)
        {
            var result = currentBlock.OnActRight(context);
            if (result == InteractResult.Success)
            {
                context.Player.User.Inventory.AddItem(currentBlock);
                return(result);
            }
        }
        else if (context.HasTarget)
        {
            if (context.Target != null)
            {
                if (context.Target is WorldObject)
                {
                    owner = (context.Target as WorldObject).OwnerUser;
                    if (owner != null)
                    {
                        ChatUtils.SendMessage(context.Player, "Owner: " + owner.Name);
                    }
                    else
                    {
                        ChatUtils.SendMessage(context.Player, "Object is unowned");
                    }
                    creator = (context.Target as WorldObject).Creator.User;
                    if (creator != null)
                    {
                        ChatUtils.SendMessage(context.Player, "Creator: " + creator.Name);
                    }
                    else
                    {
                        ChatUtils.SendMessage(context.Player, "No creator");
                    }
                }
            }
            return(InteractResult.Success);
        }

        return(InteractResult.NoOp);
    }
Example #30
0
    public override InteractResult OnActLeft(InteractionContext context)
    {
        // Try plow the block (and maybe its surroundings).
        if (context.HasBlock && context.Block !.Is <Tillable>())
        {
            return((InteractResult)AtomicActions.ChangeBlockNow(this.CreateMultiblockContext(context, () => new PlowField()), typeof(TilledDirtBlock)));
        }

        // Try interact with a world object.
        if (context.Target is WorldObject)
        {
            return(this.BasicToolOnWorldObjectCheck(context));
        }

        // Fallback.
        return(base.OnActLeft(context));
    }
Example #31
0
    public override InteractResult OnActLeft(InteractionContext context)
    {
        if (context.HasBlock && !context.Block.Is <Impenetrable>())
        {
            World.DeleteBlock(context.BlockPosition.Value);
            var plant = EcoSim.PlantSim.GetPlant(context.BlockPosition.Value + Vector3i.Up);
            if (plant != null)
            {
                EcoSim.PlantSim.DestroyPlant(plant, DeathType.Harvesting);
            }

            RoomData.QueueRoomTest(context.BlockPosition.Value);
            return(InteractResult.Success);
        }
        else if (context.HasTarget)
        {
            if (context.Target != null)
            {
                if (context.Target is WorldObject)
                {
                    (context.Target as WorldObject).Destroy();
                }
                if (context.Target is PickupableBlock)
                {
                    World.DeleteBlock(context.BlockPosition.Value);
                }
                else if (context.Target is RubbleObject)
                {
                    (context.Target as RubbleObject).Destroy();
                }
                else if (context.Target is TreeEntity)
                {
                    (context.Target as TreeEntity).Destroy();
                }
                else if (context.Target is Animal)
                {
                    (context.Target as Animal).Destroy();
                }
            }
            return(InteractResult.Success);
        }
        else
        {
            return(InteractResult.NoOp);
        }
    }
        public override InteractResult OnActLeft(InteractionContext context)
        {
            if (context.HasBlock && context.Block.Is <Minable>())
            {
                Result result;
                if (context.Block is IRepresentsItem)
                {
                    Item          item      = Item.Get((IRepresentsItem)context.Block);
                    IAtomicAction lawAction = PlayerActions.PickUp.CreateAtomicAction(context.Player, item, context.BlockPosition.Value);
                    result = this.PlayerDeleteBlock(context.BlockPosition.Value, context.Player, false, 1, null, lawAction);
                }
                else
                {
                    result = this.PlayerDeleteBlock(context.BlockPosition.Value, context.Player, false, 1);
                }

                if (result.Success)
                {
                    if (RubbleObject.TrySpawnFromBlock(context.Block.GetType(), context.BlockPosition.Value))
                    {
                        context.Player.User.UserUI.OnCreateRubble.Invoke();
                    }
                }

                return((InteractResult)result);
            }
            else if (context.Target is RubbleObject)
            {
                var rubble = (RubbleObject)context.Target;
                if (rubble.IsBreakable)
                {
                    rubble.Breakup();
                    BurnCalories(context.Player);
                    return(InteractResult.Success);
                }
                else
                {
                    return(InteractResult.NoOp);
                }
            }
            else
            {
                return(InteractResult.NoOp);
            }
        }
Example #33
0
        public async Task AvatarSlashCommand(InteractionContext ctx,
                                             [Option("user", "The person you want to see the avatar of")] DiscordUser target,
                                             [Choice("default", "default")]
                                             [Choice("jpg", "jpg")]
                                             [Choice("png", "png")]
                                             [Choice("gif", "gif")]
                                             [Choice("webp", "webp")]
                                             [Option("format", "The format of image you want to see.")] string format = "default",
                                             [Option("showGuildAvatar", "Whether to show the Guild avatar. Default is true.")] bool showGuildAvatar = true
                                             )
        {
            string avatarUrl = "";

            try
            {
                if (showGuildAvatar)
                {
                    avatarUrl = await UserOrMemberAvatarURL(target, ctx.Guild, format);
                }
                else
                {
                    avatarUrl = UserAvatarURL(target, format);
                }
            } catch (ArgumentException e)
            {
                await ctx.RespondAsync($"{Program.cfgjson.Emoji.Xmark} {e.Message}", ephemeral : true);

                return;
            }

            DiscordEmbedBuilder embed = new DiscordEmbedBuilder()
                                        .WithColor(new DiscordColor(0xC63B68))
                                        .WithTimestamp(DateTime.UtcNow)
                                        .WithFooter(
                $"Called by {ctx.User.Username}#{ctx.User.Discriminator} ({ctx.User.Id})",
                ctx.User.AvatarUrl
                )
                                        .WithImageUrl(avatarUrl)
                                        .WithAuthor(
                $"Avatar for {target.Username} (Click to open in browser)",
                avatarUrl
                );

            await ctx.RespondAsync(null, embed);
        }
Example #34
0
            public async Task ListWarnings(InteractionContext ctx,
                                           [Option("user", "The user to warn")] DiscordUser user = null !)
            {
                await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);


                if (user == null)
                {
                    user = ctx.User;
                }
                else
                {
                    var usr = await ctx.Guild.GetMemberAsync(ctx.User.Id);

                    var perms = (usr.PermissionsIn(ctx.Channel) & Permissions.KickMembers) != 0;

                    if (!perms)
                    {
                        await ctx.Client.SendMessageAsync(ctx.Guild.GetChannel(607392574235344928),
                                                          $"{ctx.User.Mention} tried to list warnings for {user.Mention} but was denied\n(►˛◄’!)");

                        await ctx.DeleteResponseAsync();

                        return;
                    }
                }


                using var db = new LiteDatabase(@$ "{ctx.Guild.Id}.db");
                var col = db.GetCollection <Warning>("warnings");

                var warnings = col.Find(x => x.UserId == user.Id);

                if (warnings.Any())
                {
                    var warningsDesc = string.Join("\n", warnings.Select(x => $"{x.Id}: {x.Reason} - {x.Date:g}"));

                    var username = user.Username ?? user.Id.ToString();

                    var embed = new DiscordEmbedBuilder
                    {
                        Title       = $"Warnings for {username}",
                        Description = warningsDesc,
                        Url         = null,
                        Color       = default,
Example #35
0
    private bool TryDamageBranch(INetObject damager, float amount, InteractionContext context)
    {
        int        branchID = context.Parameters["branch"];
        TreeBranch branch   = this.branches[branchID];

        if (context.Parameters.ContainsKey("leaf"))
        {
            int leafID = context.Parameters["leaf"];

            // damage leaf
            LeafBunch leaf = branch.Leaves[leafID];

            if (leaf.Health > 0)
            {
                leaf.Health = Mathf.Max(0, leaf.Health - amount);

                if (leaf.Health <= 0)
                {
                    leaf.Health = 0;

                    if (RandomUtil.Value < this.Species.SeedDropChance)
                    {
                        var    numSeeds      = (int)this.Species.SeedRange.Max;
                        int    numBonusSeeds = 0;
                        Item[] newSeeds      = new Item[] { };
                        if (numSeeds > 0 && this.Species.SeedItem != null)
                        {
                            var yield = ItemAttribute.Get <YieldAttribute>(this.Species.SeedItem.Type);
                            numBonusSeeds = yield != null?yield.Yield.GetCurrentValueInt(context.Player.User) : 0;

                            context.Player.User.Inventory.TryAddItems(this.Species.SeedItem.Type, numSeeds + numBonusSeeds);
                        }
                    }
                    this.RPC("DestroyLeaves", branchID, leafID);
                }
            }

            this.Save();
            return(true);
        }
        else
        {
            return(this.TryDamageBranch(branch, branchID, amount));
        }
    }
 public abstract InteractionResult Handle(InteractionContext context);
Example #37
0
        public override InteractionResult Handle(InteractionContext context)
        {
            NoteId id;
            if (!context.Request.TryGetId(context.Request.Data, out id))
            {
                return Error("Unknown note id");
            }

            var optional = context.Storage.GetEntity<NoteView>(id);
            if (!optional.HasValue)
            {
                return Error("Note {0} does not exist", id);
            }
            var note = optional.Value;
            context.Response.GrabFile(note.Text, (s, s1) => context.Response.SendToProject(new EditNote(id, s, s1)));
            return Handled();
        }
Example #38
0
 public override InteractionResult Handle(InteractionContext context)
 {
     var tags = context.Storage.GetSingletonOrNew<TagList>();
     context.Response.RenderView(tags);
     return Handled();
 }
 public DisabledException(InteractionContext ic)
     : this(ic, Resources.NakedObjects.Disabled) {}
 public DisabledException(InteractionContext ic, string message)
     : base(ic, message) {}
 public HiddenException(InteractionContext ic)
     : this(ic, Resources.NakedObjects.Hidden) {}
        public void Dispose()
        {
            if (context != null)
            {
                context.Dispose();
                context = null;
            }

            system.Dispose();
        }
 public InvalidException(InteractionContext ic, string message)
     : base(ic, message) {}
 public InvalidException(InteractionContext ic)
     : this(ic, Resources.NakedObjects.Invalid) {}
Example #45
0
    private void ShutdownEyeX()
    {
        try
        {
            if (_context != null)
            {
                _context.Dispose();
                _context = null;
            }

            if (_system != null)
            {
                _system.Dispose();
                _system = null;
            }

            print("EyeX shutdown finished.");
        }
        catch (InteractionApiException ex)
        {
            print("EyeX shutdown failed: " + ex.Message);
        }
    }
Example #46
0
    private void InitializeContext()
    {
        try
        {
            _context = new InteractionContext(false);
            _context.RegisterQueryHandlerForCurrentProcess(HandleQuery);
            _context.RegisterEventHandler(HandleEvent);
            _context.ConnectionStateChanged += OnConnectionStateChanged;
            _context.EnableConnection();

            print("EyeX context initialization succeeded.");
        }
        catch (InteractionApiException ex)
        {
            print("EyeX context initialization failed: " + ex.Message);
        }
    }
Example #47
0
 public override InteractionResult Handle(InteractionContext context)
 {
     TaskId id;
     if (!context.Request.TryGetId(context.Request.Data, out id))
     {
         return Error("Couldn't locate task '{0}'", id);
     }
     context.Response.SendToProject(new CompleteTask(id));
     return Handled();
 }
Example #48
0
 public override InteractionResult Handle(InteractionContext context)
 {
     return new InteractionResult(null, InteractionResultStatus.Terminate);
 }
 public HiddenException(InteractionContext ic, string message)
     : base(ic, message) {}
Example #50
0
 public override InteractionResult Handle(InteractionContext context)
 {
     var splice = context.Request.Data.Split(new[] {' '}, 2);
     Identity guid;
     if (!context.Request.TryGetId(splice[0], out guid))
     {
         return Error("Failed to look up ID for '{0}'", splice[0]);
     }
     if (splice.Length<2)
     {
         return Error("Did you miss a new name?");
     }
     context.Response.SendToProject(new RenameItem(guid, splice[1]));
     return Handled();
 }
Example #51
0
 public override InteractionResult Handle(InteractionContext context)
 {
     context.Response.SendToProject(new StartSimpleStory(context.Request.Data));
     return Handled();
 }