Search in sources :

Example 1 with PluginContainer

use of org.spongepowered.plugin.PluginContainer in project SpongeCommon by SpongePowered.

the class FilteredPluginContainerParameter method parseValue.

@Override
public Optional<? extends PluginContainer> parseValue(final Parameter.Key<? super PluginContainer> parameterKey, final ArgumentReader.Mutable reader, final CommandContext.Builder context) throws ArgumentParseException {
    final String id = reader.parseString();
    final PluginContainer pluginContainer = this.validPluginContainers.get(id);
    if (pluginContainer != null) {
        return Optional.of(pluginContainer);
    }
    throw reader.createException(Component.text("Could not find valid plugin to refresh with ID \"" + id + "\""));
}
Also used : PluginContainer(org.spongepowered.plugin.PluginContainer) DummyPluginContainer(org.spongepowered.common.applaunch.plugin.DummyPluginContainer)

Example 2 with PluginContainer

use of org.spongepowered.plugin.PluginContainer in project SpongeCommon by SpongePowered.

the class InventoryUtil method getPluginContainer.

public static PluginContainer getPluginContainer(Object inventory) {
    // TODO maybe caching?
    final PluginContainer container;
    if (inventory instanceof CustomInventory) {
        return ((CustomInventory) inventory).getPlugin();
    }
    if (inventory instanceof CarriedInventory) {
        final Optional<?> carrier = ((CarriedInventory<?>) inventory).carrier();
        if (carrier.isPresent()) {
            inventory = carrier.get();
        }
    }
    final Object base = inventory;
    if (base instanceof BlockEntity) {
        final ResourceKey key = Sponge.game().registry(RegistryTypes.BLOCK_ENTITY_TYPE).valueKey(((BlockEntity) base).type());
        final String pluginId = key.namespace();
        container = Sponge.pluginManager().plugin(pluginId).orElseThrow(() -> new AssertionError("Missing plugin " + pluginId + " for block " + key.namespace() + ":" + key.value()));
    } else if (base instanceof Entity) {
        final ResourceKey key = (ResourceKey) (Object) EntityType.getKey((EntityType<?>) ((Entity) base).type());
        final String pluginId = key.namespace();
        container = Sponge.pluginManager().plugin(pluginId).orElseGet(() -> {
            SpongeCommon.logger().debug("Unknown plugin for [{}]", base);
            return Launch.instance().minecraftPlugin();
        });
    } else if (base instanceof SpongeUserData) {
        container = Launch.instance().minecraftPlugin();
    } else {
        container = Sponge.pluginManager().plugin(PlatformHooks.INSTANCE.getInventoryHooks().getModIdFromInventory(base.getClass())).orElseGet(() -> {
            SpongeCommon.logger().debug("Unknown plugin for [{}]", base);
            return Launch.instance().minecraftPlugin();
        });
    }
    return container;
}
Also used : EntityType(net.minecraft.world.entity.EntityType) BlockEntity(org.spongepowered.api.block.entity.BlockEntity) ChestBlockEntity(net.minecraft.world.level.block.entity.ChestBlockEntity) Entity(org.spongepowered.api.entity.Entity) PluginContainer(org.spongepowered.plugin.PluginContainer) CarriedInventory(org.spongepowered.api.item.inventory.type.CarriedInventory) SpongeUserData(org.spongepowered.common.entity.player.SpongeUserData) CustomInventory(org.spongepowered.common.inventory.custom.CustomInventory) BlockEntity(org.spongepowered.api.block.entity.BlockEntity) ChestBlockEntity(net.minecraft.world.level.block.entity.ChestBlockEntity) ResourceKey(org.spongepowered.api.ResourceKey)

Example 3 with PluginContainer

use of org.spongepowered.plugin.PluginContainer in project SpongeCommon by SpongePowered.

the class VanillaPluginManager method loadPlugins.

@SuppressWarnings("unchecked")
public void loadPlugins(final VanillaPluginPlatform platform) {
    this.locatedResources.putAll(platform.getResources());
    final Map<PluginCandidate<PluginResource>, PluginLanguageService<PluginResource>> pluginLanguageLookup = new HashMap<>();
    final Map<PluginLanguageService<PluginResource>, PluginLoader<PluginResource, PluginContainer>> pluginLoaders = new HashMap<>();
    // Initialise the plugin language loaders.
    for (final Map.Entry<PluginLanguageService<PluginResource>, List<PluginCandidate<PluginResource>>> candidate : platform.getCandidates().entrySet()) {
        final PluginLanguageService<PluginResource> languageService = candidate.getKey();
        final String loaderClass = languageService.pluginLoader();
        try {
            pluginLoaders.put(languageService, (PluginLoader<PluginResource, PluginContainer>) Class.forName(loaderClass).getConstructor().newInstance());
        } catch (final InstantiationException | IllegalAccessException | ClassNotFoundException | NoSuchMethodException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        candidate.getValue().forEach(x -> pluginLanguageLookup.put(x, languageService));
    }
    // Priority to platform plugins that will already exist here -- meaning the resolver will act upon them first
    // and if someone decides to give a plugin an ID that is the same as a platform plugin, the resolver will effectively
    // reject it.
    final Set<PluginCandidate<PluginResource>> resources = new LinkedHashSet<>();
    pluginLanguageLookup.keySet().stream().filter(x -> this.plugins.containsKey(x.metadata().id())).forEach(resources::add);
    resources.addAll(pluginLanguageLookup.keySet());
    final ResolutionResult<PluginResource> resolutionResult = DependencyResolver.resolveAndSortCandidates(resources, platform.logger());
    final Map<PluginCandidate<PluginResource>, String> failedInstances = new HashMap<>();
    final Map<PluginCandidate<PluginResource>, String> consequentialFailedInstances = new HashMap<>();
    final ClassLoader launchClassloader = VanillaLaunch.instance().getClass().getClassLoader();
    for (final PluginCandidate<PluginResource> candidate : resolutionResult.sortedSuccesses()) {
        final PluginContainer plugin = this.plugins.get(candidate.metadata().id());
        if (plugin != null) {
            if (plugin instanceof VanillaDummyPluginContainer) {
                continue;
            }
            // If we get here, we screwed up - duplicate IDs should have been detected earlier.
            // Place it in the resolution result... it'll then get picked up in the big error message
            resolutionResult.duplicateIds().add(candidate.metadata().id());
            // but this is our screw up, let's also make a big point of it
            final PrettyPrinter prettyPrinter = new PrettyPrinter(120).add("ATTEMPTED TO CREATE PLUGIN WITH DUPLICATE PLUGIN ID").centre().hr().addWrapped("Sponge attempted to create a second plugin with ID '%s'. This is not allowed - all plugins must have a unique " + "ID. Usually, Sponge will catch this earlier -- but in this case Sponge has validated two plugins with " + "the same ID. Please report this error to Sponge.", candidate.metadata().id()).add().add("Technical Details:").add("Plugins to load:", 4);
            resolutionResult.sortedSuccesses().forEach(x -> prettyPrinter.add("*" + x.metadata().id(), 4));
            prettyPrinter.add().add("Detected Duplicate IDs:", 4);
            resolutionResult.duplicateIds().forEach(x -> prettyPrinter.add("*" + x, 4));
            prettyPrinter.log(platform.logger(), Level.ERROR);
            continue;
        }
        // This should work fine, we're sorted so all deps should be in place at this stage.
        if (this.stillValid(candidate, consequentialFailedInstances)) {
            final PluginLanguageService<PluginResource> languageService = pluginLanguageLookup.get(candidate);
            final PluginLoader<PluginResource, PluginContainer> pluginLoader = pluginLoaders.get(languageService);
            try {
                final PluginContainer container = pluginLoader.loadPlugin(platform.getStandardEnvironment(), candidate, launchClassloader);
                this.addPlugin(container);
                this.containerToResource.put(container, candidate.resource());
            } catch (final InvalidPluginException e) {
                failedInstances.put(candidate, "Failed to construct: see stacktrace(s) above this message for details.");
                e.printStackTrace();
            }
        }
    }
    resolutionResult.printErrorsIfAny(failedInstances, consequentialFailedInstances, platform.logger());
    platform.logger().info("Loaded plugin(s): {}", this.sortedPlugins.stream().map(p -> p.metadata().id()).collect(Collectors.toList()));
}
Also used : LinkedHashSet(java.util.LinkedHashSet) SpongePluginManager(org.spongepowered.common.launch.plugin.SpongePluginManager) PluginLanguageService(org.spongepowered.plugin.PluginLanguageService) PluginCandidate(org.spongepowered.plugin.PluginCandidate) Level(org.apache.logging.log4j.Level) PrettyPrinter(org.spongepowered.common.util.PrettyPrinter) HashMap(java.util.HashMap) DependencyResolver(org.spongepowered.vanilla.launch.plugin.resolver.DependencyResolver) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Object2ObjectOpenHashMap(it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap) PluginLoader(org.spongepowered.plugin.PluginLoader) Map(java.util.Map) LinkedHashSet(java.util.LinkedHashSet) IdentityHashMap(java.util.IdentityHashMap) ResolutionResult(org.spongepowered.vanilla.launch.plugin.resolver.ResolutionResult) Collection(java.util.Collection) Set(java.util.Set) InvalidPluginException(org.spongepowered.plugin.InvalidPluginException) Collectors(java.util.stream.Collectors) InvocationTargetException(java.lang.reflect.InvocationTargetException) Objects(java.util.Objects) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) PluginContainer(org.spongepowered.plugin.PluginContainer) PluginDependency(org.spongepowered.plugin.metadata.model.PluginDependency) VanillaPluginPlatform(org.spongepowered.vanilla.applaunch.plugin.VanillaPluginPlatform) Optional(java.util.Optional) PluginResource(org.spongepowered.plugin.PluginResource) Collections(java.util.Collections) Singleton(com.google.inject.Singleton) VanillaLaunch(org.spongepowered.vanilla.launch.VanillaLaunch) HashMap(java.util.HashMap) Object2ObjectOpenHashMap(it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap) IdentityHashMap(java.util.IdentityHashMap) PluginLanguageService(org.spongepowered.plugin.PluginLanguageService) PrettyPrinter(org.spongepowered.common.util.PrettyPrinter) InvalidPluginException(org.spongepowered.plugin.InvalidPluginException) PluginResource(org.spongepowered.plugin.PluginResource) ArrayList(java.util.ArrayList) List(java.util.List) PluginLoader(org.spongepowered.plugin.PluginLoader) PluginContainer(org.spongepowered.plugin.PluginContainer) PluginCandidate(org.spongepowered.plugin.PluginCandidate) InvocationTargetException(java.lang.reflect.InvocationTargetException) HashMap(java.util.HashMap) Object2ObjectOpenHashMap(it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap) Map(java.util.Map) IdentityHashMap(java.util.IdentityHashMap)

Example 4 with PluginContainer

use of org.spongepowered.plugin.PluginContainer in project SpongeCommon by SpongePowered.

the class CrashReportMixin_Vanilla method vanilla$addPluginsToEnvironment.

@Inject(method = "initDetails", at = @At("RETURN"))
private void vanilla$addPluginsToEnvironment(final CallbackInfo ci) {
    this.systemDetails.setDetail("Plugins", () -> {
        final StringBuilder result = new StringBuilder(64);
        for (final PluginContainer container : Sponge.pluginManager().plugins()) {
            final PluginMetadata metadata = container.metadata();
            final String name = metadata.name().orElse(metadata.id());
            result.append("\n\t\t").append(name).append(" (").append(metadata.id()).append(") ").append(metadata.version());
        }
        return result.toString();
    });
}
Also used : PluginContainer(org.spongepowered.plugin.PluginContainer) PluginMetadata(org.spongepowered.plugin.metadata.PluginMetadata) Inject(org.spongepowered.asm.mixin.injection.Inject)

Example 5 with PluginContainer

use of org.spongepowered.plugin.PluginContainer in project SpongeCommon by SpongePowered.

the class PluginRepositorySource method loadPacks.

@Override
public void loadPacks(final Consumer<Pack> callback, final Pack.PackConstructor constructor) {
    final VanillaPluginManager pluginManager = (VanillaPluginManager) Launch.instance().pluginManager();
    // For each plugin, we create a pack. That pack might be empty.
    for (final PluginContainer pluginContainer : pluginManager.plugins()) {
        // The pack ID is prepended with "plugin-", as this will be the namespace we have to use a valid
        // character as a separator
        final String id = "plugin-" + pluginContainer.metadata().id();
        final PluginResource resource = pluginManager.resource(pluginContainer);
        // TODO: provide hook in the resource to return the file system for all resource types?
        // Also -- can we fake a FileSystem for a non-Jar (needs thinking about)....
        @Nullable Supplier<FileSystem> fileSystemSupplier = null;
        if (resource instanceof JVMPluginResource) {
            final String extension = FilenameUtils.getExtension(resource.path().getFileName().toString());
            if ("jar".equals(extension)) {
                fileSystemSupplier = ((JVMPluginResource) resource)::fileSystem;
            }
        }
        final PluginPackResources packResources = new PluginPackResources(id, pluginContainer, fileSystemSupplier);
        final Pack pack = Pack.create(id, true, () -> packResources, constructor, Pack.Position.BOTTOM, PackSource.DEFAULT);
        ((PackRepositoryBridge_Vanilla) this.repository).bridge$registerResourcePack(pluginContainer, pack);
        callback.accept(pack);
    }
}
Also used : PluginContainer(org.spongepowered.plugin.PluginContainer) JVMPluginResource(org.spongepowered.plugin.builtin.jvm.locator.JVMPluginResource) JVMPluginResource(org.spongepowered.plugin.builtin.jvm.locator.JVMPluginResource) PluginResource(org.spongepowered.plugin.PluginResource) PackRepositoryBridge_Vanilla(org.spongepowered.vanilla.bridge.server.packs.repository.PackRepositoryBridge_Vanilla) FileSystem(java.nio.file.FileSystem) VanillaPluginManager(org.spongepowered.vanilla.launch.plugin.VanillaPluginManager) Pack(net.minecraft.server.packs.repository.Pack) Nullable(org.checkerframework.checker.nullness.qual.Nullable)

Aggregations

PluginContainer (org.spongepowered.plugin.PluginContainer)22 NonNull (org.checkerframework.checker.nullness.qual.NonNull)6 Collection (java.util.Collection)4 List (java.util.List)4 Collectors (java.util.stream.Collectors)4 Component (net.kyori.adventure.text.Component)4 EventManager (org.spongepowered.api.event.EventManager)4 PluginMetadata (org.spongepowered.plugin.metadata.PluginMetadata)4 ArrayList (java.util.ArrayList)3 Optional (java.util.Optional)3 Identity (net.kyori.adventure.identity.Identity)3 TextComponent (net.kyori.adventure.text.TextComponent)3 Nullable (org.checkerframework.checker.nullness.qual.Nullable)3 Test (org.junit.jupiter.api.Test)3 Sponge (org.spongepowered.api.Sponge)3 Command (org.spongepowered.api.command.Command)3 CommandResult (org.spongepowered.api.command.CommandResult)3 Parameter (org.spongepowered.api.command.parameter.Parameter)3 RefreshGameEvent (org.spongepowered.api.event.lifecycle.RefreshGameEvent)3 SpongeEventManager (org.spongepowered.common.event.manager.SpongeEventManager)3