use of org.spongepowered.api.command.CommandSource in project SpongeCommon by SpongePowered.
the class CommandState method unwind.
@Override
public void unwind(CommandPhaseContext phaseContext) {
Optional<EntityPlayer> playerSource = phaseContext.getSource(EntityPlayer.class);
if (playerSource.isPresent()) {
// Post event for inventory changes
((IMixinInventoryPlayer) playerSource.get().inventory).setCapture(false);
List<SlotTransaction> list = ((IMixinInventoryPlayer) playerSource.get().inventory).getCapturedTransactions();
if (!list.isEmpty()) {
ChangeInventoryEvent event = SpongeEventFactory.createChangeInventoryEvent(Sponge.getCauseStackManager().getCurrentCause(), ((Inventory) playerSource.get().inventory), list);
SpongeImpl.postEvent(event);
PacketPhaseUtil.handleSlotRestore(playerSource.get(), null, list, event.isCancelled());
list.clear();
}
}
final CommandSource sender = phaseContext.getSource(CommandSource.class).orElseThrow(TrackingUtil.throwWithContext("Expected to be capturing a Command Sender, but none found!", phaseContext));
phaseContext.getCapturedBlockSupplier().acceptAndClearIfNotEmpty(list -> TrackingUtil.processBlockCaptures(list, this, phaseContext));
try (StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
Sponge.getCauseStackManager().pushCause(sender);
Sponge.getCauseStackManager().addContext(EventContextKeys.SPAWN_TYPE, InternalSpawnTypes.PLACEMENT);
phaseContext.getCapturedEntitySupplier().acceptAndClearIfNotEmpty(entities -> {
// TODO the entity spawn causes are not likely valid,
// need to investigate further.
final SpawnEntityEvent spawnEntityEvent = SpongeEventFactory.createSpawnEntityEvent(Sponge.getCauseStackManager().getCurrentCause(), entities);
SpongeImpl.postEvent(spawnEntityEvent);
if (!spawnEntityEvent.isCancelled()) {
final boolean isPlayer = sender instanceof Player;
final Player player = isPlayer ? (Player) sender : null;
for (Entity entity : spawnEntityEvent.getEntities()) {
if (isPlayer) {
EntityUtil.toMixin(entity).setCreator(player.getUniqueId());
}
EntityUtil.getMixinWorld(entity).forceSpawnEntity(entity);
}
}
});
}
try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
Sponge.getCauseStackManager().pushCause(sender);
Sponge.getCauseStackManager().addContext(EventContextKeys.SPAWN_TYPE, InternalSpawnTypes.DROPPED_ITEM);
phaseContext.getCapturedEntityDropSupplier().acceptIfNotEmpty(uuidItemStackMultimap -> {
for (Map.Entry<UUID, Collection<ItemDropData>> entry : uuidItemStackMultimap.asMap().entrySet()) {
final UUID key = entry.getKey();
@Nullable net.minecraft.entity.Entity foundEntity = null;
for (WorldServer worldServer : WorldManager.getWorlds()) {
final net.minecraft.entity.Entity entityFromUuid = worldServer.getEntityFromUuid(key);
if (entityFromUuid != null) {
foundEntity = entityFromUuid;
break;
}
}
final Optional<Entity> affectedEntity = Optional.ofNullable((Entity) foundEntity);
if (!affectedEntity.isPresent()) {
continue;
}
final Collection<ItemDropData> itemStacks = entry.getValue();
if (itemStacks.isEmpty()) {
return;
}
final List<ItemDropData> items = new ArrayList<>();
items.addAll(itemStacks);
itemStacks.clear();
final WorldServer minecraftWorld = EntityUtil.getMinecraftWorld(affectedEntity.get());
if (!items.isEmpty()) {
final List<Entity> itemEntities = items.stream().map(data -> data.create(minecraftWorld)).map(EntityUtil::fromNative).collect(Collectors.toList());
Sponge.getCauseStackManager().pushCause(affectedEntity.get());
final DropItemEvent.Destruct destruct = SpongeEventFactory.createDropItemEventDestruct(Sponge.getCauseStackManager().getCurrentCause(), itemEntities);
SpongeImpl.postEvent(destruct);
Sponge.getCauseStackManager().popCause();
if (!destruct.isCancelled()) {
final boolean isPlayer = sender instanceof Player;
final Player player = isPlayer ? (Player) sender : null;
for (Entity entity : destruct.getEntities()) {
if (isPlayer) {
EntityUtil.toMixin(entity).setCreator(player.getUniqueId());
}
EntityUtil.getMixinWorld(entity).forceSpawnEntity(entity);
}
}
}
}
});
}
}
use of org.spongepowered.api.command.CommandSource in project SpongeCommon by SpongePowered.
the class MixinServerCommandManager method executeCommand.
/**
* @author zml
*
* Purpose: Reroute MC command handling through Sponge
* Reasoning: All commands should go through one system -- we need none of the MC handling code
*/
@Override
public int executeCommand(ICommandSender sender, String command) {
command = command.trim();
if (command.startsWith("/")) {
command = command.substring(1);
}
CommandSource source = WrapperCommandSource.of(sender);
CommandResult result = SpongeImpl.getGame().getCommandManager().process(source, command);
updateStat(sender, CommandResultStats.Type.AFFECTED_BLOCKS, result.getAffectedBlocks());
updateStat(sender, CommandResultStats.Type.AFFECTED_ENTITIES, result.getAffectedEntities());
updateStat(sender, CommandResultStats.Type.AFFECTED_ITEMS, result.getAffectedItems());
updateStat(sender, CommandResultStats.Type.QUERY_RESULT, result.getQueryResult());
updateStat(sender, CommandResultStats.Type.SUCCESS_COUNT, result.getSuccessCount());
return result.getSuccessCount().orElse(0);
// return super.executeCommand(sender, command); // Try Vanilla instead
}
use of org.spongepowered.api.command.CommandSource in project SpongeCommon by SpongePowered.
the class SpongeCommandFactory method sendContainerMeta.
public static void sendContainerMeta(CommandSource src, CommandContext args, String argumentName) {
for (PluginContainer container : args.<PluginContainer>getAll(argumentName)) {
Text.Builder builder = Text.builder().append(title(container.getName()));
container.getVersion().ifPresent(version -> builder.append(Text.of((" v" + version))));
appendPluginMeta(builder, "ID", container.getId());
appendPluginMeta(builder, "Description", container.getDescription());
appendPluginMeta(builder, "URL", container.getUrl().map(url -> {
ClickAction.OpenUrl action = null;
try {
// make the url clickable
action = TextActions.openUrl(new URL(url));
} catch (MalformedURLException e) {
// or not
}
return Text.builder(url).onClick(action);
}));
if (!container.getAuthors().isEmpty()) {
appendPluginMeta(builder, "Authors", String.join(", ", container.getAuthors()));
}
appendPluginMeta(builder, "Main class", container.getInstance().map(instance -> instance.getClass().getCanonicalName()));
src.sendMessage(builder.build());
}
}
use of org.spongepowered.api.command.CommandSource in project SpongeCommon by SpongePowered.
the class TimingsExport method reportTimings.
/**
* Builds an XML report of the timings to be uploaded for parsing.
*
* @param sender Who to report to
*/
static void reportTimings(CommandSource sender) {
Platform platform = SpongeImpl.getGame().getPlatform();
JsonObjectBuilder builder = JSONUtil.objectBuilder().add("version", platform.getContainer(IMPLEMENTATION).getVersion().orElse(platform.getMinecraftVersion().getName() + "-DEV")).add("maxplayers", SpongeImpl.getGame().getServer().getMaxPlayers()).add("start", TimingsManager.timingStart / 1000).add("end", System.currentTimeMillis() / 1000).add("sampletime", (System.currentTimeMillis() - TimingsManager.timingStart) / 1000);
if (!TimingsManager.privacy) {
builder.add("server", getServerName()).add("motd", Sponge.getServer().getMotd().toPlain()).add("online-mode", Sponge.getServer().getOnlineMode()).add("icon", SpongeImpl.getServer().getServerStatusResponse().getFavicon());
}
final Runtime runtime = Runtime.getRuntime();
RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
builder.add("system", JSONUtil.objectBuilder().add("timingcost", getCost()).add("name", System.getProperty("os.name")).add("version", System.getProperty("os.version")).add("jvmversion", System.getProperty("java.version")).add("arch", System.getProperty("os.arch")).add("maxmem", runtime.maxMemory()).add("cpu", runtime.availableProcessors()).add("runtime", ManagementFactory.getRuntimeMXBean().getUptime()).add("flags", RUNTIME_FLAG_JOINER.join(runtimeBean.getInputArguments())).add("gc", JSONUtil.mapArrayToObject(ManagementFactory.getGarbageCollectorMXBeans(), (input) -> {
return JSONUtil.singleObjectPair(input.getName(), JSONUtil.arrayOf(input.getCollectionCount(), input.getCollectionTime()));
})));
Set<BlockType> blockTypeSet = Sets.newHashSet();
Set<EntityType> entityTypeSet = Sets.newHashSet();
int size = HISTORY.size();
TimingHistory[] history = new TimingHistory[size + 1];
int i = 0;
for (TimingHistory timingHistory : HISTORY) {
blockTypeSet.addAll(timingHistory.blockTypeSet);
entityTypeSet.addAll(timingHistory.entityTypeSet);
history[i++] = timingHistory;
}
// Current snapshot
history[i] = new TimingHistory();
blockTypeSet.addAll(history[i].blockTypeSet);
entityTypeSet.addAll(history[i].entityTypeSet);
JsonObjectBuilder handlersBuilder = JSONUtil.objectBuilder();
for (TimingIdentifier.TimingGroup group : TimingIdentifier.GROUP_MAP.values()) {
for (TimingHandler id : group.handlers) {
if (!id.timed && !id.isSpecial()) {
continue;
}
handlersBuilder.add(id.id, JSONUtil.arrayOf(group.id, id.name));
}
}
builder.add("idmap", JSONUtil.objectBuilder().add("groups", JSONUtil.mapArrayToObject(TimingIdentifier.GROUP_MAP.values(), (group) -> {
return JSONUtil.singleObjectPair(group.id, group.name);
})).add("handlers", handlersBuilder).add("worlds", JSONUtil.mapArrayToObject(TimingHistory.worldMap.entrySet(), (entry) -> {
return JSONUtil.singleObjectPair(entry.getValue(), entry.getKey());
})).add("tileentity", JSONUtil.mapArrayToObject(blockTypeSet, (blockType) -> {
return JSONUtil.singleObjectPair(Block.getIdFromBlock((Block) blockType), blockType.getId());
})).add("entity", JSONUtil.mapArrayToObject(entityTypeSet, (entityType) -> {
if (entityType == EntityTypes.UNKNOWN) {
return null;
}
return JSONUtil.singleObjectPair(TimingsPls.getEntityId(entityType), entityType.getId());
})));
// Information about loaded plugins
builder.add("plugins", JSONUtil.mapArrayToObject(SpongeImpl.getGame().getPluginManager().getPlugins(), (plugin) -> {
return JSONUtil.objectBuilder().add(plugin.getId(), JSONUtil.objectBuilder().add("version", plugin.getVersion().orElse("")).add("description", plugin.getDescription().orElse("")).add("website", plugin.getUrl().orElse("")).add("authors", AUTHOR_LIST_JOINER.join(plugin.getAuthors()))).build();
}));
// Information on the users Config
builder.add("config", JSONUtil.objectBuilder().add("sponge", serializeConfigNode(SpongeImpl.getGlobalConfig().getRootNode())));
new TimingsExport(sender, builder.build(), history).start();
}
use of org.spongepowered.api.command.CommandSource in project SpongeCommon by SpongePowered.
the class SpongeContextCalculator method accumulateContexts.
@Override
public void accumulateContexts(Subject subject, Set<Context> accumulator) {
Optional<CommandSource> subjSource = subject.getCommandSource();
if (subjSource.isPresent()) {
CommandSource source = subjSource.get();
if (source instanceof Locatable) {
World currentExt = ((Locatable) source).getWorld();
accumulator.add(currentExt.getContext());
accumulator.add((currentExt.getDimension().getContext()));
}
if (source instanceof RemoteSource) {
RemoteSource rem = (RemoteSource) source;
accumulator.addAll(this.remoteIpCache.getUnchecked(rem));
accumulator.addAll(this.localIpCache.getUnchecked(rem));
accumulator.add(new Context(Context.LOCAL_PORT_KEY, String.valueOf(rem.getConnection().getVirtualHost().getPort())));
accumulator.add(new Context(Context.LOCAL_HOST_KEY, rem.getConnection().getVirtualHost().getHostName()));
}
}
}
Aggregations