| 1 | package net.minecraft.client;
|
| 2 |
|
| 3 | import com.google.common.collect.ImmutableMap;
|
| 4 | import com.google.common.math.LongMath;
|
| 5 | import com.mojang.logging.LogUtils;
|
| 6 | import com.mojang.serialization.Codec;
|
| 7 | import com.mojang.serialization.JsonOps;
|
| 8 | import com.mojang.serialization.codecs.RecordCodecBuilder;
|
| 9 | import it.unimi.dsi.fastutil.objects.Object2BooleanFunction;
|
| 10 | import java.io.Reader;
|
| 11 | import java.util.Collection;
|
| 12 | import java.util.List;
|
| 13 | import java.util.Map;
|
| 14 | import java.util.Timer;
|
| 15 | import java.util.TimerTask;
|
| 16 | import java.util.Map.Entry;
|
| 17 | import java.util.concurrent.TimeUnit;
|
| 18 | import java.util.concurrent.atomic.AtomicLong;
|
| 19 | import java.util.stream.Collectors;
|
| 20 | import net.fabricmc.api.EnvType;
|
| 21 | import net.fabricmc.api.Environment;
|
| 22 | import net.minecraft.client.gui.components.toasts.SystemToast;
|
| 23 | import net.minecraft.network.chat.Component;
|
| 24 | import net.minecraft.resources.Identifier;
|
| 25 | import net.minecraft.server.packs.resources.ResourceManager;
|
| 26 | import net.minecraft.server.packs.resources.SimplePreparableReloadListener;
|
| 27 | import net.minecraft.util.StrictJsonParser;
|
| 28 | import net.minecraft.util.Util;
|
| 29 | import net.minecraft.util.profiling.ProfilerFiller;
|
| 30 | import org.jspecify.annotations.Nullable;
|
| 31 | import org.slf4j.Logger;
|
| 32 |
|
| 33 | @Environment(EnvType.CLIENT)
|
| 34 | public class PeriodicNotificationManager
|
| 35 | extends SimplePreparableReloadListener<Map<String, List<PeriodicNotificationManager.Notification>>>
|
| 36 | implements AutoCloseable {
|
| 37 | private static final Codec<Map<String, List<PeriodicNotificationManager.Notification>>> CODEC = Codec.unboundedMap(
|
| 38 | Codec.STRING,
|
| 39 | RecordCodecBuilder.<PeriodicNotificationManager.Notification>create(
|
| 40 | i -> i.group(
|
| 41 | Codec.LONG.optionalFieldOf("delay", 0L).forGetter(PeriodicNotificationManager.Notification::delay),
|
| 42 | Codec.LONG.fieldOf("period").forGetter(PeriodicNotificationManager.Notification::period),
|
| 43 | Codec.STRING.fieldOf("title").forGetter(PeriodicNotificationManager.Notification::title),
|
| 44 | Codec.STRING.fieldOf("message").forGetter(PeriodicNotificationManager.Notification::message)
|
| 45 | )
|
| 46 | .apply(i, PeriodicNotificationManager.Notification::new)
|
| 47 | )
|
| 48 | .listOf()
|
| 49 | );
|
| 50 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 51 | private final Identifier notifications;
|
| 52 | private final Object2BooleanFunction<String> selector;
|
| 53 | private @Nullable Timer timer;
|
| 54 | private PeriodicNotificationManager.@Nullable NotificationTask notificationTask;
|
| 55 |
|
| 56 | public PeriodicNotificationManager(final Identifier notifications, final Object2BooleanFunction<String> selector) {
|
| 57 | this.notifications = notifications;
|
| 58 | this.selector = selector;
|
| 59 | }
|
| 60 |
|
| 61 | protected Map<String, List<PeriodicNotificationManager.Notification>> prepare(final ResourceManager manager, final ProfilerFiller profiler) {
|
| 62 | try (Reader reader = manager.openAsReader(this.notifications)) {
|
| 63 | return CODEC.parse(JsonOps.INSTANCE, StrictJsonParser.parse(reader)).result().orElseThrow();
|
| 64 | } catch (Exception e) {
|
| 65 | LOGGER.warn("Failed to load {}", this.notifications, e);
|
| 66 | return ImmutableMap.of();
|
| 67 | }
|
| 68 | }
|
| 69 |
|
| 70 | protected void apply(
|
| 71 | final Map<String, List<PeriodicNotificationManager.Notification>> preparations, final ResourceManager manager, final ProfilerFiller profiler
|
| 72 | ) {
|
| 73 | List<PeriodicNotificationManager.Notification> notifications = preparations.entrySet()
|
| 74 | .stream()
|
| 75 | .filter(e -> this.selector.apply(e.getKey()))
|
| 76 | .map(Entry::getValue)
|
| 77 | .flatMap(Collection::stream)
|
| 78 | .collect(Collectors.toList());
|
| 79 | if (notifications.isEmpty()) {
|
| 80 | this.stopTimer();
|
| 81 | } else if (notifications.stream().anyMatch(n -> n.period == 0L)) {
|
| 82 | Util.logAndPauseIfInIde("A periodic notification in " + this.notifications + " has a period of zero minutes");
|
| 83 | this.stopTimer();
|
| 84 | } else {
|
| 85 | long delay = this.calculateInitialDelay(notifications);
|
| 86 | long period = this.calculateOptimalPeriod(notifications, delay);
|
| 87 | if (this.timer == null) {
|
| 88 | this.timer = new Timer();
|
| 89 | }
|
| 90 |
|
| 91 | if (this.notificationTask == null) {
|
| 92 | this.notificationTask = new PeriodicNotificationManager.NotificationTask(notifications, delay, period);
|
| 93 | } else {
|
| 94 | this.notificationTask = this.notificationTask.reset(notifications, period);
|
| 95 | }
|
| 96 |
|
| 97 | this.timer.scheduleAtFixedRate(this.notificationTask, TimeUnit.MINUTES.toMillis(delay), TimeUnit.MINUTES.toMillis(period));
|
| 98 | }
|
| 99 | }
|
| 100 |
|
| 101 | @Override
|
| 102 | public void close() {
|
| 103 | this.stopTimer();
|
| 104 | }
|
| 105 |
|
| 106 | private void stopTimer() {
|
| 107 | if (this.timer != null) {
|
| 108 | this.timer.cancel();
|
| 109 | }
|
| 110 | }
|
| 111 |
|
| 112 | private long calculateOptimalPeriod(final List<PeriodicNotificationManager.Notification> notifications, final long initialDelay) {
|
| 113 | return notifications.stream().mapToLong(c -> {
|
| 114 | long delayPeriods = c.delay - initialDelay;
|
| 115 | return LongMath.gcd(delayPeriods, c.period);
|
| 116 | }).reduce(LongMath::gcd).orElseThrow(() -> new IllegalStateException("Empty notifications from: " + this.notifications));
|
| 117 | }
|
| 118 |
|
| 119 | private long calculateInitialDelay(final List<PeriodicNotificationManager.Notification> notifications) {
|
| 120 | return notifications.stream().mapToLong(c -> c.delay).min().orElse(0L);
|
| 121 | }
|
| 122 |
|
| 123 | @Environment(EnvType.CLIENT)
|
| 124 | public record Notification(long delay, long period, String title, String message) {
|
| 125 | }
|
| 126 |
|
| 127 | @Environment(EnvType.CLIENT)
|
| 128 | private static class NotificationTask extends TimerTask {
|
| 129 | private final Minecraft minecraft = Minecraft.getInstance();
|
| 130 | private final List<PeriodicNotificationManager.Notification> notifications;
|
| 131 | private final long period;
|
| 132 | private final AtomicLong elapsed;
|
| 133 |
|
| 134 | public NotificationTask(final List<PeriodicNotificationManager.Notification> notifications, final long elapsed, final long period) {
|
| 135 | this.notifications = notifications;
|
| 136 | this.period = period;
|
| 137 | this.elapsed = new AtomicLong(elapsed);
|
| 138 | }
|
| 139 |
|
| 140 | public PeriodicNotificationManager.NotificationTask reset(final List<PeriodicNotificationManager.Notification> notifications, final long period) {
|
| 141 | this.cancel();
|
| 142 | return new PeriodicNotificationManager.NotificationTask(notifications, this.elapsed.get(), period);
|
| 143 | }
|
| 144 |
|
| 145 | @Override
|
| 146 | public void run() {
|
| 147 | long currentMinute = this.elapsed.getAndAdd(this.period);
|
| 148 | long nextMinute = this.elapsed.get();
|
| 149 |
|
| 150 | for (PeriodicNotificationManager.Notification notification : this.notifications) {
|
| 151 | if (currentMinute >= notification.delay) {
|
| 152 | long elapsedPeriods = currentMinute / notification.period;
|
| 153 | long currentPeriods = nextMinute / notification.period;
|
| 154 | if (elapsedPeriods != currentPeriods) {
|
| 155 | this.minecraft
|
| 156 | .execute(
|
| 157 | () -> SystemToast.add(
|
| 158 | Minecraft.getInstance().gui.toastManager(),
|
| 159 | SystemToast.SystemToastId.PERIODIC_NOTIFICATION,
|
| 160 | Component.translatable(notification.title, elapsedPeriods),
|
| 161 | Component.translatable(notification.message, elapsedPeriods)
|
| 162 | )
|
| 163 | );
|
| 164 | return;
|
| 165 | }
|
| 166 | }
|
| 167 | }
|
| 168 | }
|
| 169 | }
|
| 170 | }
|
| 171 |
|