Search in sources :

Example 6 with Cancellable

use of org.spongepowered.api.event.Cancellable in project SpongeCommon by SpongePowered.

the class CancellationEventFilterDelegate method write.

@Override
public int write(String name, ClassWriter cw, MethodVisitor mv, Method method, int locals) {
    if (this.state == Tristate.UNDEFINED) {
        return locals;
    }
    if (!Cancellable.class.isAssignableFrom(method.getParameters()[0].getType())) {
        throw new IllegalStateException("Attempted to filter a non-cancellable event type by its cancellation status");
    }
    mv.visitVarInsn(ALOAD, 1);
    mv.visitTypeInsn(CHECKCAST, Type.getInternalName(Cancellable.class));
    mv.visitMethodInsn(INVOKEINTERFACE, Type.getInternalName(Cancellable.class), "isCancelled", "()Z", true);
    Label success = new Label();
    if (this.state == Tristate.TRUE) {
        mv.visitJumpInsn(IFNE, success);
    } else {
        mv.visitJumpInsn(IFEQ, success);
    }
    mv.visitInsn(ACONST_NULL);
    mv.visitInsn(ARETURN);
    mv.visitLabel(success);
    return locals;
}
Also used : Cancellable(org.spongepowered.api.event.Cancellable) Label(org.objectweb.asm.Label)

Example 7 with Cancellable

use of org.spongepowered.api.event.Cancellable in project SpongeForge by SpongePowered.

the class SpongeModEventManager method post.

// Uses SpongeForgeEventFactory (required for any events shared in SpongeCommon)
private boolean post(Event spongeEvent, Class<? extends net.minecraftforge.fml.common.eventhandler.Event> clazz, boolean useCauseStackManager) {
    RegisteredListener.Cache listenerCache = getHandlerCache(spongeEvent);
    SpongeForgeEventFactory.handlePrefireLogic(spongeEvent);
    // Fire events to plugins before modifications
    for (Order order : Order.values()) {
        post(spongeEvent, listenerCache.getListenersByOrder(order), true, false, useCauseStackManager);
    }
    boolean cancelled = false;
    if (spongeEvent instanceof Cancellable) {
        cancelled = ((Cancellable) spongeEvent).isCancelled();
    }
    if (!cancelled) {
        spongeEvent = SpongeForgeEventFactory.callForgeEvent(spongeEvent, clazz);
    }
    // Fire events to plugins after modifications (default)
    for (Order order : Order.values()) {
        post(spongeEvent, listenerCache.getListenersByOrder(order), false, false, useCauseStackManager);
    }
    return spongeEvent instanceof Cancellable && ((Cancellable) spongeEvent).isCancelled();
}
Also used : Order(org.spongepowered.api.event.Order) Cancellable(org.spongepowered.api.event.Cancellable) RegisteredListener(org.spongepowered.common.event.RegisteredListener)

Example 8 with Cancellable

use of org.spongepowered.api.event.Cancellable in project SpongeCommon by SpongePowered.

the class TransactionalCaptureSupplier method processTransactions.

@SuppressWarnings("unchecked")
public boolean processTransactions(final PhaseContext<@NonNull ?> context) {
    if (this.head == null) {
        return false;
    }
    final ImmutableMultimap.Builder<TransactionType, ? extends Event> builder = ImmutableMultimap.builder();
    final ImmutableList<EventByTransaction<@NonNull ?>> batched = TransactionalCaptureSupplier.batchTransactions(this.head, null, context, builder);
    boolean cancelledAny = false;
    for (final EventByTransaction<@NonNull ?> eventWithTransactions : batched) {
        final Event event = eventWithTransactions.event;
        if (eventWithTransactions.isParentOrDeciderCancelled()) {
            cancelledAny = true;
            eventWithTransactions.markCancelled();
            continue;
        }
        Sponge.eventManager().post(event);
        if (event instanceof Cancellable && ((Cancellable) event).isCancelled()) {
            eventWithTransactions.markCancelled();
            cancelledAny = true;
        }
        if (((GameTransaction) eventWithTransactions.decider).markCancelledTransactions(event, eventWithTransactions.transactions)) {
            cancelledAny = true;
        }
        for (final GameTransaction<@NonNull ?> transaction : eventWithTransactions.transactions) {
            if (transaction.cancelled) {
                ((GameTransaction) transaction).markEventAsCancelledIfNecessary(eventWithTransactions.event);
            }
            if (!transaction.cancelled) {
                ((GameTransaction) transaction).postProcessEvent(context, event);
            }
        }
    }
    if (cancelledAny) {
        for (final EventByTransaction<@NonNull ?> eventByTransaction : batched.reverse()) {
            if (eventByTransaction.decider.cancelled) {
                ((GameTransaction) eventByTransaction.decider).markEventAsCancelledIfNecessary(eventByTransaction.event);
            }
            for (final GameTransaction<@NonNull ?> gameTransaction : eventByTransaction.transactions.reverse()) {
                if (gameTransaction.cancelled) {
                    ((GameTransaction) gameTransaction).restore(context, eventByTransaction.event);
                }
            }
        }
    }
    builder.build().asMap().forEach((transactionType, events) -> transactionType.createAndProcessPostEvents(context, events));
    return !cancelledAny;
}
Also used : TransactionType(org.spongepowered.common.event.tracking.context.transaction.type.TransactionType) Cancellable(org.spongepowered.api.event.Cancellable) NonNull(org.checkerframework.checker.nullness.qual.NonNull) MonotonicNonNull(org.checkerframework.checker.nullness.qual.MonotonicNonNull) Event(org.spongepowered.api.event.Event) ImmutableMultimap(com.google.common.collect.ImmutableMultimap)

Example 9 with Cancellable

use of org.spongepowered.api.event.Cancellable in project SpongeCommon by SpongePowered.

the class ServerGamePacketListenerImplMixin method impl$callInteractBlockPrimaryEvent.

@Redirect(method = "handlePlayerAction", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/level/ServerPlayerGameMode;handleBlockBreakAction(Lnet/minecraft/core/BlockPos;Lnet/minecraft/network/protocol/game/ServerboundPlayerActionPacket$Action;Lnet/minecraft/core/Direction;I)V"))
public void impl$callInteractBlockPrimaryEvent(final ServerPlayerGameMode playerInteractionManager, final BlockPos p_225416_1_, final ServerboundPlayerActionPacket.Action p_225416_2_, final Direction p_225416_3_, final int p_225416_4_) {
    final BlockSnapshot snapshot = ((org.spongepowered.api.world.server.ServerWorld) (playerInteractionManager.level)).createSnapshot(VecHelper.toVector3i(p_225416_1_));
    final InteractBlockEvent.Primary event = SpongeCommonEventFactory.callInteractBlockEventPrimary(p_225416_2_, this.player, this.player.getItemInHand(InteractionHand.MAIN_HAND), snapshot, InteractionHand.MAIN_HAND, p_225416_3_);
    if (event instanceof Cancellable && ((Cancellable) event).isCancelled()) {
        this.player.connection.send(new ClientboundBlockBreakAckPacket(p_225416_1_, playerInteractionManager.level.getBlockState(p_225416_1_), p_225416_2_, false, "block action restricted"));
        this.impl$ignorePackets++;
    } else {
        if (p_225416_2_ == ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK) {
            if (!Objects.equals(((ServerPlayerGameModeAccessor) playerInteractionManager).accessor$destroyPos(), p_225416_1_)) {
                // prevents Mismatch in destroy block pos warning
                return;
            }
        }
        playerInteractionManager.handleBlockBreakAction(p_225416_1_, p_225416_2_, p_225416_3_, p_225416_4_);
        if (p_225416_2_ == ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK) {
            this.impl$ignorePackets++;
        }
    }
}
Also used : InteractBlockEvent(org.spongepowered.api.event.block.InteractBlockEvent) ClientboundBlockBreakAckPacket(net.minecraft.network.protocol.game.ClientboundBlockBreakAckPacket) Cancellable(org.spongepowered.api.event.Cancellable) BlockSnapshot(org.spongepowered.api.block.BlockSnapshot) ServerPlayerGameModeAccessor(org.spongepowered.common.accessor.server.level.ServerPlayerGameModeAccessor) Redirect(org.spongepowered.asm.mixin.injection.Redirect)

Example 10 with Cancellable

use of org.spongepowered.api.event.Cancellable in project TriggerReactor by wysohn.

the class TriggerReactor method createInterrupterForInv.

@Override
public ProcessInterrupter createInterrupterForInv(Object e, Interpreter interpreter, Map<UUID, Long> cooldowns, Map<IInventory, InventoryTrigger> inventoryMap) {
    return new ProcessInterrupter() {

        @Override
        public boolean onNodeProcess(Node node) {
            // is still running after the inventory is closed.
            if (e instanceof InteractInventoryEvent.Open || e instanceof InteractInventoryEvent.Close) {
                Inventory inv = ((InteractInventoryEvent) e).getTargetInventory();
                if (!(inv instanceof CarriedInventory))
                    return false;
                CarriedInventory inventory = (CarriedInventory) inv;
                Carrier carrier = (Carrier) inventory.getCarrier().orElse(null);
                if (carrier == null)
                    return false;
                // it's not GUI so stop execution
                return !inventoryMap.containsKey(new SpongeInventory(inv, carrier));
            }
            return false;
        }

        @Override
        public boolean onCommand(Object context, String command, Object[] args) {
            if ("CALL".equalsIgnoreCase(command)) {
                if (args.length < 1)
                    throw new RuntimeException("Need parameter [String] or [String, boolean]");
                if (args[0] instanceof String) {
                    Trigger trigger = getNamedTriggerManager().get((String) args[0]);
                    if (trigger == null)
                        throw new RuntimeException("No trigger found for Named Trigger " + args[0]);
                    if (args.length > 1 && args[1] instanceof Boolean) {
                        trigger.setSync((boolean) args[1]);
                    } else {
                        trigger.setSync(true);
                    }
                    if (trigger.isSync()) {
                        trigger.activate(e, interpreter.getVars());
                    } else {
                        // use snapshot to avoid concurrent modification
                        trigger.activate(e, new HashMap<>(interpreter.getVars()));
                    }
                    return true;
                } else {
                    throw new RuntimeException("Parameter type not match; it should be a String." + " Make sure to put double quotes, if you provided String literal.");
                }
            } else if ("CANCELEVENT".equalsIgnoreCase(command)) {
                if (!interpreter.isSync())
                    throw new RuntimeException("CANCELEVENT is illegal in async mode!");
                if (context instanceof Cancellable) {
                    ((Cancellable) context).setCancelled(true);
                    return true;
                } else {
                    throw new RuntimeException(context + " is not a Cancellable event!");
                }
            } else if ("COOLDOWN".equalsIgnoreCase(command)) {
                if (!(args[0] instanceof Number))
                    throw new RuntimeException(args[0] + " is not a number!");
                long mills = (long) (((Number) args[0]).doubleValue() * 1000L);
                if (e instanceof Event) {
                    ((Event) e).getCause().first(Player.class).ifPresent((player) -> {
                        UUID uuid = player.getUniqueId();
                        cooldowns.put(uuid, System.currentTimeMillis() + mills);
                    });
                }
                return true;
            }
            return false;
        }

        @Override
        public Object onPlaceholder(Object context, String placeholder, Object[] args) {
            // }
            return null;
        }
    };
}
Also used : IPlayer(io.github.wysohn.triggerreactor.core.bridge.entity.IPlayer) Player(org.spongepowered.api.entity.living.player.Player) DelegatedPlayer(io.github.wysohn.triggerreactor.sponge.tools.DelegatedPlayer) SpongePlayer(io.github.wysohn.triggerreactor.sponge.bridge.entity.SpongePlayer) CarriedInventory(org.spongepowered.api.item.inventory.type.CarriedInventory) InteractInventoryEvent(org.spongepowered.api.event.item.inventory.InteractInventoryEvent) Cancellable(org.spongepowered.api.event.Cancellable) ConfigurationNode(ninja.leaping.configurate.ConfigurationNode) Node(io.github.wysohn.triggerreactor.core.script.parser.Node) CommentedConfigurationNode(ninja.leaping.configurate.commented.CommentedConfigurationNode) ProcessInterrupter(io.github.wysohn.triggerreactor.core.script.interpreter.Interpreter.ProcessInterrupter) SpongeInventory(io.github.wysohn.triggerreactor.sponge.bridge.SpongeInventory) Trigger(io.github.wysohn.triggerreactor.core.manager.trigger.Trigger) InventoryTrigger(io.github.wysohn.triggerreactor.core.manager.trigger.inventory.InventoryTrigger) GameInitializationEvent(org.spongepowered.api.event.game.state.GameInitializationEvent) GameReloadEvent(org.spongepowered.api.event.game.GameReloadEvent) GameStartedServerEvent(org.spongepowered.api.event.game.state.GameStartedServerEvent) GameStoppingServerEvent(org.spongepowered.api.event.game.state.GameStoppingServerEvent) TriggerReactorStopEvent(io.github.wysohn.triggerreactor.sponge.manager.event.TriggerReactorStopEvent) TabCompleteEvent(org.spongepowered.api.event.command.TabCompleteEvent) Event(org.spongepowered.api.event.Event) InteractInventoryEvent(org.spongepowered.api.event.item.inventory.InteractInventoryEvent) IEvent(io.github.wysohn.triggerreactor.core.bridge.event.IEvent) TriggerReactorStartEvent(io.github.wysohn.triggerreactor.sponge.manager.event.TriggerReactorStartEvent) GameAboutToStartServerEvent(org.spongepowered.api.event.game.state.GameAboutToStartServerEvent) SendCommandEvent(org.spongepowered.api.event.command.SendCommandEvent) Carrier(org.spongepowered.api.item.inventory.Carrier) IInventory(io.github.wysohn.triggerreactor.core.bridge.IInventory) CarriedInventory(org.spongepowered.api.item.inventory.type.CarriedInventory) Inventory(org.spongepowered.api.item.inventory.Inventory) SpongeInventory(io.github.wysohn.triggerreactor.sponge.bridge.SpongeInventory)

Aggregations

Cancellable (org.spongepowered.api.event.Cancellable)10 Event (org.spongepowered.api.event.Event)4 Label (org.objectweb.asm.Label)3 ImmutableMultimap (com.google.common.collect.ImmutableMultimap)2 IPlayer (io.github.wysohn.triggerreactor.core.bridge.entity.IPlayer)2 IEvent (io.github.wysohn.triggerreactor.core.bridge.event.IEvent)2 Trigger (io.github.wysohn.triggerreactor.core.manager.trigger.Trigger)2 InventoryTrigger (io.github.wysohn.triggerreactor.core.manager.trigger.inventory.InventoryTrigger)2 ProcessInterrupter (io.github.wysohn.triggerreactor.core.script.interpreter.Interpreter.ProcessInterrupter)2 Node (io.github.wysohn.triggerreactor.core.script.parser.Node)2 SpongePlayer (io.github.wysohn.triggerreactor.sponge.bridge.entity.SpongePlayer)2 TriggerReactorStartEvent (io.github.wysohn.triggerreactor.sponge.manager.event.TriggerReactorStartEvent)2 TriggerReactorStopEvent (io.github.wysohn.triggerreactor.sponge.manager.event.TriggerReactorStopEvent)2 DelegatedPlayer (io.github.wysohn.triggerreactor.sponge.tools.DelegatedPlayer)2 ConfigurationNode (ninja.leaping.configurate.ConfigurationNode)2 CommentedConfigurationNode (ninja.leaping.configurate.commented.CommentedConfigurationNode)2 MonotonicNonNull (org.checkerframework.checker.nullness.qual.MonotonicNonNull)2 NonNull (org.checkerframework.checker.nullness.qual.NonNull)2 Player (org.spongepowered.api.entity.living.player.Player)2 CauseStackManager (org.spongepowered.api.event.CauseStackManager)2