aboutsummaryrefslogtreecommitdiff
path: root/neoforge/src/main/java/me/shedaniel/rei/forge/AnnotationUtils.java
blob: 6486f0aba2256a6bc0880492bbf756e8cb60e069 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/*
 * This file is licensed under the MIT License, part of Roughly Enough Items.
 * Copyright (c) 2018, 2019, 2020, 2021, 2022, 2023 shedaniel
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package me.shedaniel.rei.forge;

import com.google.common.collect.Lists;
import me.shedaniel.rei.impl.init.PrimitivePlatformAdapter;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.fml.ModList;
import net.neoforged.fml.loading.FMLEnvironment;
import net.neoforged.fml.loading.modscan.ModAnnotation;
import net.neoforged.neoforgespi.language.IModInfo;
import net.neoforged.neoforgespi.language.ModFileScanData;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.apache.commons.lang3.tuple.Triple;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.util.TriConsumer;
import org.objectweb.asm.Type;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;

public class AnnotationUtils {
    public static final Logger LOGGER = LogManager.getFormatterLogger("REI");
    
    public static <A, T> void scanAnnotation(Class<A> clazz, Predicate<Class<T>> predicate, TriConsumer<List<String>, Supplier<T>, Class<T>> consumer) {
        scanAnnotation(Type.getType(clazz), predicate, consumer);
    }
    
    public static <T> void scanAnnotation(Type annotationType, Predicate<Class<T>> predicate, TriConsumer<List<String>, Supplier<T>, Class<T>> consumer) {
        List<Triple<List<String>, Supplier<T>, Class<T>>> instances = Lists.newArrayList();
        for (ModFileScanData data : ModList.get().getAllScanData()) {
            List<String> modIds = data.getIModInfoData().stream()
                    .flatMap(info -> info.getMods().stream())
                    .map(IModInfo::getModId)
                    .collect(Collectors.toList());
            out:
            for (ModFileScanData.AnnotationData annotation : data.getAnnotations()) {
                if (annotationType.equals(annotation.annotationType())) {
                    Object value = annotation.annotationData().get("value");
                    boolean enabled;
                    
                    if (value instanceof Dist[]) {
                        enabled = Arrays.asList((Dist[]) value).contains(FMLEnvironment.dist);
                    } else if (value instanceof ModAnnotation.EnumHolder) {
                        enabled = Objects.equals(((ModAnnotation.EnumHolder) value).value(), FMLEnvironment.dist.name());
                    } else if (value instanceof List) {
                        List<ModAnnotation.EnumHolder> holders = ((List<?>) value).stream().filter(o -> o instanceof ModAnnotation.EnumHolder)
                                .map(o -> (ModAnnotation.EnumHolder) o).toList();
                        if (!holders.isEmpty()) {
                            enabled = holders.stream()
                                    .anyMatch(o -> Objects.equals(o.value(), FMLEnvironment.dist.name()));
                        } else {
                            enabled = true;
                        }
                    } else {
                        enabled = true;
                    }
                    
                    if (!enabled) continue;
                    
                    try {
                        Class<T> clazz = (Class<T>) Class.forName(annotation.memberName());
                        if (predicate.test(clazz)) {
                            instances.add(new ImmutableTriple<>(modIds, () -> {
                                try {
                                    return clazz.getDeclaredConstructor().newInstance();
                                } catch (Throwable throwable) {
                                    LOGGER.error("Failed to load plugin: " + annotation.memberName(), throwable);
                                    return null;
                                }
                            }, clazz));
                        }
                    } catch (Throwable throwable) {
                        Throwable t = throwable;
                        while (t != null) {
                            if (t.getMessage() != null && t.getMessage().contains("invalid dist DEDICATED_SERVER") && !PrimitivePlatformAdapter.get().isClient()) {
                                LOGGER.warn("Plugin " + annotation.memberName() + " is attempting to load on the server, but is not compatible with the server. " +
                                            "The mod should declare the environments it is compatible with in the @" + annotationType.getClassName() + " annotation.");
                                continue out;
                            }
                            t = t.getCause();
                        }
                        LOGGER.error("Failed to load plugin: " + annotation.memberName(), throwable);
                    }
                }
            }
        }
        
        for (Triple<List<String>, Supplier<T>, Class<T>> pair : instances) {
            consumer.accept(pair.getLeft(), pair.getMiddle(), pair.getRight());
        }
    }
}