forked from CleanroomMC/ModularUI
-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathPanelSyncManager.java
More file actions
429 lines (376 loc) · 17.4 KB
/
PanelSyncManager.java
File metadata and controls
429 lines (376 loc) · 17.4 KB
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
package com.cleanroommc.modularui.value.sync;
import com.cleanroommc.modularui.ModularUI;
import com.cleanroommc.modularui.api.IPanelHandler;
import com.cleanroommc.modularui.api.ISyncedAction;
import com.cleanroommc.modularui.network.ModularNetwork;
import com.cleanroommc.modularui.screen.ModularContainer;
import com.cleanroommc.modularui.utils.item.PlayerMainInvWrapper;
import com.cleanroommc.modularui.widgets.slot.ModularSlot;
import com.cleanroommc.modularui.widgets.slot.SlotGroup;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.network.PacketBuffer;
import io.netty.buffer.Unpooled;
import it.unimi.dsi.fastutil.objects.Object2ReferenceArrayMap;
import it.unimi.dsi.fastutil.objects.Object2ReferenceLinkedOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2ReferenceOpenHashMap;
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
import org.apache.logging.log4j.Level;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Supplier;
public class PanelSyncManager implements ISyncRegistrar<PanelSyncManager> {
private final Map<String, SyncHandler<?>> syncHandlers = new Object2ReferenceLinkedOpenHashMap<>();
private final Map<String, SlotGroup> slotGroups = new Object2ReferenceOpenHashMap<>();
private final Map<SyncHandler<?>, String> reverseSyncHandlers = new Reference2ObjectOpenHashMap<>();
private final Map<String, SyncedAction> syncedActions = new Object2ReferenceOpenHashMap<>();
private final Map<String, PanelSyncHandler> subPanels = new Object2ReferenceArrayMap<>();
private final ModularSyncManager modularSyncManager;
private String panelName;
private boolean init = true;
private boolean locked = false;
private boolean allowSyncHandlerRegistration = false;
private final boolean client;
private final List<Consumer<EntityPlayer>> openListener = new ArrayList<>();
private final List<Consumer<EntityPlayer>> closeListener = new ArrayList<>();
private final List<Runnable> tickListener = new ArrayList<>();
@ApiStatus.Internal
public PanelSyncManager(ModularSyncManager msm, boolean main) {
this.modularSyncManager = msm;
this.client = msm.isClient();
if (main) msm.setMainPSM(this);
}
@ApiStatus.Internal
public void initialize(String panelName) {
this.panelName = panelName;
var snapshotKeys = new ArrayList<>(this.syncHandlers.keySet());
for (var mapKey : snapshotKeys) {
var syncHandler = this.syncHandlers.get(mapKey);
if (syncHandler != null) {
syncHandler.init(mapKey, this);
}
}
this.locked = true;
this.init = true;
this.subPanels.forEach((s, syncHandler) -> this.modularSyncManager.getMainPSM().registerPanelSyncHandler(s, syncHandler));
}
private void registerPanelSyncHandler(String name, SyncHandler<?> syncHandler) {
// only called on main psm
SyncHandler<?> currentSh = this.syncHandlers.get(name);
if (currentSh != null && currentSh != syncHandler) {
throw new IllegalStateException("Failed to register panel sync handler during initialization. " +
"There already exists a sync handler for the name '" + name + "'.");
}
String currentName = this.reverseSyncHandlers.get(syncHandler);
if (currentName != null && !name.equals(currentName)) {
throw new IllegalStateException("Failed to register panel sync handler for name '" + name + "' during initialization. " +
"The panel sync handler is already registered under the name '" + currentName + "'.");
}
this.syncHandlers.put(name, syncHandler);
this.reverseSyncHandlers.put(syncHandler, name);
syncHandler.init(name, this);
}
void closeSubPanels() {
this.subPanels.values().forEach(syncHandler -> {
if (syncHandler.isSubPanel()) {
syncHandler.closePanel();
}
});
}
@ApiStatus.Internal
public void onOpen() {
this.openListener.forEach(listener -> listener.accept(getPlayer()));
}
@ApiStatus.Internal
public void onClose() {
this.closeListener.forEach(listener -> listener.accept(getPlayer()));
this.syncHandlers.values().forEach(SyncHandler::dispose);
// Previously panel sync handlers were removed from the main psm, however this problematic if the screen will be reopened at some
// point. We can just not remove the sync handlers since mui has proper checks for re-registering panels.
}
public boolean isInitialised() {
return this.panelName != null;
}
void detectAndSendChanges(boolean init) {
if (!isClient()) {
for (SyncHandler<?> syncHandler : this.syncHandlers.values()) {
syncHandler.detectAndSendChanges(init || this.init);
}
}
this.init = false;
}
void onUpdate() {
this.tickListener.forEach(Runnable::run);
}
@ApiStatus.Internal
public void receiveWidgetUpdate(String mapKey, boolean action, int id, PacketBuffer buf) throws IOException {
if (action) {
invokeSyncedAction(mapKey, buf);
return;
}
if (!this.syncHandlers.containsKey(mapKey)) {
ModularUI.LOGGER.warn("SyncHandler '{}' does not exist for panel '{}'! ID was {}.", mapKey, panelName, id);
return;
}
SyncHandler<?> syncHandler = this.syncHandlers.get(mapKey);
if (isClient()) {
syncHandler.readOnClient(id, buf);
} else if (syncHandler.isAllowC2S()) {
syncHandler.readOnServer(id, buf);
} else {
ModularUI.LOGGER.throwing(Level.WARN, new SecurityException("Tried to send a packet to server, but the sync handler does not accept client packets."));
}
}
private boolean invokeSyncedAction(String mapKey, PacketBuffer buf) {
SyncedAction syncedAction = this.syncedActions.get(mapKey);
if (syncedAction == null) {
ModularUI.LOGGER.warn("SyncAction '{}' does not exist for panel '{}'!.", mapKey, panelName);
return false;
}
if (!isLocked() || this.allowSyncHandlerRegistration || !syncedAction.isExecuteClient() || !syncedAction.isExecuteServer()) {
syncedAction.invoke(this.client, buf);
} else {
// only allow sync handler registration if it is executed on client and server
allowTemporarySyncHandlerRegistration(true);
syncedAction.invoke(this.client, buf);
allowTemporarySyncHandlerRegistration(false);
}
// true if the action should be executed on the other side
return syncedAction.isExecute(!this.client);
}
public ItemStack getCursorItem() {
return getModularSyncManager().getCursorItem();
}
public void setCursorItem(ItemStack stack) {
getModularSyncManager().setCursorItem(stack);
}
@Override
public boolean hasSyncHandler(SyncHandler<?> syncHandler) {
if (this.reverseSyncHandlers.containsKey(syncHandler)) return true;
return this != getHyperVisor() && getHyperVisor().hasSyncHandler(syncHandler);
}
private void putSyncValue(String name, int id, SyncHandler<?> syncHandler) {
if (isLocked()) {
// registration of sync handlers forbidden
if (this.allowSyncHandlerRegistration) {
// lock can be bypassed currently, but it wasn't used
throw new IllegalStateException("SyncHandlers must be registered during panel building. Please use getOrCreateSyncHandler() inside DynamicSyncHandler!");
} else {
throw new IllegalStateException("SyncHandlers must be registered during panel building. The only exceptions is via a DynamicSyncHandler and sync functions!");
}
}
String key = makeSyncKey(name, id);
String currentKey = this.reverseSyncHandlers.get(syncHandler);
if (currentKey != null) {
if (!currentKey.equals(key)) {
boolean auto = name.startsWith(ModularSyncManager.AUTO_SYNC_PREFIX);
if (auto != currentKey.startsWith(ModularSyncManager.AUTO_SYNC_PREFIX)) {
throw new IllegalStateException("Old and new sync handler must both be either not auto or auto!");
}
if (auto && !currentKey.startsWith(name)) {
throw new IllegalStateException("Sync Handler was previously added with a different panel!");
}
}
this.syncHandlers.remove(currentKey);
}
this.syncHandlers.put(key, syncHandler);
this.reverseSyncHandlers.put(syncHandler, key);
if (isInitialised()) {
syncHandler.init(key, this);
}
}
@Override
public PanelSyncManager syncValue(String name, int id, SyncHandler<?> syncHandler) {
Objects.requireNonNull(name, "Name must not be null");
Objects.requireNonNull(syncHandler, "Sync Handler must not be null");
putSyncValue(name, id, syncHandler);
return this;
}
/**
* @deprecated replaced by {@link #syncedPanel(String, boolean, PanelSyncHandler.IPanelBuilder)}
*/
@ApiStatus.ScheduledForRemoval(inVersion = "3.3.0")
@Deprecated
public IPanelHandler panel(String key, PanelSyncHandler.IPanelBuilder panelBuilder, boolean subPanel) {
SyncHandler<?> sh = this.subPanels.get(key);
if (sh != null) return (IPanelHandler) sh;
PanelSyncHandler syncHandler = new PanelSyncHandler(panelBuilder, subPanel);
this.subPanels.put(key, syncHandler);
return syncHandler;
}
/**
* Creates a synced panel handler. This can be used to automatically handle syncing for synced panels.
* Synced panels do not need to be synced themselves, but contain at least one widget which is synced.
* <p><b>NOTE</b></p>
* A panel sync handler is only created once. If one was already registered, that one will be returned.
* (This is only relevant for nested sub panels.) Furthermore, the panel handler has to be created on client and server with the same
* key. Like any other sync handler, the panel sync handler has to be created before the panel opened. The only exception is inside
* dynamic sync handlers.
*
* @param key the key used for syncing
* @param subPanel true if this panel should close when its parent closes (the parent is defined by <i>this</i> {@link PanelSyncManager})
* @param panelBuilder the panel builder, that will create the new panel. It must not return null or any existing panels.
* @return a synced panel handler.
* @throws NullPointerException if the build panel of the builder is null
* @throws IllegalArgumentException if the build panel of the builder is the main panel
* @throws IllegalStateException if this method was called too late
*/
@Override
public IPanelHandler syncedPanel(String key, boolean subPanel, PanelSyncHandler.IPanelBuilder panelBuilder) {
IPanelHandler ph = findPanelHandlerNullable(key);
if (ph != null) return ph;
if (isLocked() && !this.allowSyncHandlerRegistration) {
// registration of sync handlers forbidden
throw new IllegalStateException("Synced panels must be registered during panel building. The only exceptions is via a DynamicSyncHandler and sync functions!");
}
PanelSyncHandler syncHandler = new PanelSyncHandler(panelBuilder, subPanel);
this.subPanels.put(key, syncHandler);
if (isInitialised() && (this == this.modularSyncManager.getMainPSM() ||
this.modularSyncManager.getMainPSM().findSyncHandlerNullable(this.panelName, PanelSyncHandler.class) == null)) {
// current panel is open
this.modularSyncManager.getMainPSM().registerPanelSyncHandler(key, syncHandler);
}
return syncHandler;
}
@Override
public @Nullable IPanelHandler findPanelHandlerNullable(String key) {
return this.subPanels.get(key);
}
@Override
public PanelSyncManager registerSlotGroup(SlotGroup slotGroup) {
if (!slotGroup.isSingleton()) {
this.slotGroups.put(slotGroup.getName(), slotGroup);
}
return this;
}
public interface SlotFunction {
@NotNull
ModularSlot apply(@NotNull PlayerMainInvWrapper playerInv, int index);
}
/**
* @param listener The function to run whenever the gui {@link net.minecraft.inventory.Container} is open, ran on both the server and client threads.
* @return {@code this} for chaining
*/
public PanelSyncManager addOpenListener(Consumer<EntityPlayer> listener) {
this.openListener.add(listener);
return this;
}
/**
* @param listener The function to run whenever the gui {@link net.minecraft.inventory.Container} is closed, ran on both the server and client threads.
* @return {@code this} for chaining
*/
public PanelSyncManager addCloseListener(Consumer<EntityPlayer> listener) {
this.closeListener.add(listener);
return this;
}
public PanelSyncManager onClientTick(Runnable runnable) {
if (this.client) {
this.tickListener.add(runnable);
}
return this;
}
public PanelSyncManager onServerTick(Runnable runnable) {
if (!this.client) {
this.tickListener.add(runnable);
}
return this;
}
public PanelSyncManager onCommonTick(Runnable runnable) {
this.tickListener.add(runnable);
return this;
}
@Override
public PanelSyncManager registerSyncedAction(String mapKey, boolean executeClient, boolean executeServer, ISyncedAction action) {
if (executeClient || executeServer) {
this.syncedActions.put(mapKey, new SyncedAction(action, executeClient, executeServer));
}
return this;
}
public void callSyncedAction(String mapKey, PacketBuffer packet) {
if (invokeSyncedAction(mapKey, packet)) {
ModularNetwork.get(isClient()).sendActionPacket(getModularSyncManager(), this.panelName, mapKey, packet, getPlayer());
}
}
public void callSyncedAction(String mapKey, Consumer<PacketBuffer> packetBuilder) {
PacketBuffer packet = new PacketBuffer(Unpooled.buffer());
packetBuilder.accept(packet);
callSyncedAction(mapKey, packet);
}
public void callSyncedAction(String mapKey) {
callSyncedAction(mapKey, new PacketBuffer(Unpooled.buffer(0)));
}
@Override
public <T extends SyncHandler<?>> T getOrCreateSyncHandler(String name, int id, Class<T> clazz, Supplier<T> supplier) {
SyncHandler<?> syncHandler = findSyncHandlerNullable(name, id);
if (syncHandler == null) {
if (isLocked() && !this.allowSyncHandlerRegistration) {
// registration is locked, and we don't have permission to temporarily bypass lock
throw new IllegalStateException("SyncHandlers must be registered during panel building. The only exceptions is via a DynamicSyncHandler and sync functions!");
}
T t = supplier.get();
boolean l = this.locked;
this.locked = false; // bypass possible lock
putSyncValue(name, id, t);
this.locked = l;
return t;
}
if (clazz.isAssignableFrom(syncHandler.getClass())) {
return clazz.cast(syncHandler);
}
throw new IllegalStateException("SyncHandler for key " + makeSyncKey(name, id) + " is of type " + syncHandler.getClass() + ", but type " + clazz + " was expected!");
}
@Override
public SlotGroup getSlotGroup(String name) {
return this.slotGroups.get(name);
}
public Collection<SlotGroup> getSlotGroups() {
return this.slotGroups.values();
}
@ApiStatus.ScheduledForRemoval(inVersion = "3.2.0")
@Deprecated
public @Nullable SyncHandler<?> getSyncHandler(String mapKey) {
return getSyncHandlerFromMapKey(mapKey);
}
public @Nullable SyncHandler<?> getSyncHandlerFromMapKey(String mapKey) {
return this.syncHandlers.get(mapKey);
}
@Override
public @Nullable SyncHandler<?> findSyncHandlerNullable(String name, int id) {
return this.syncHandlers.get(makeSyncKey(name, id));
}
public EntityPlayer getPlayer() {
return getModularSyncManager().getPlayer();
}
public ModularSyncManager getModularSyncManager() {
return modularSyncManager;
}
public ISyncRegistrar<?> getHyperVisor() {
return this.modularSyncManager.getMainPSM();
}
public ModularContainer getContainer() {
return getModularSyncManager().getContainer();
}
public String getPanelName() {
return panelName;
}
public boolean isClient() {
return this.client;
}
public boolean isLocked() {
return locked;
}
void allowTemporarySyncHandlerRegistration(boolean allow) {
this.allowSyncHandlerRegistration = allow;
}
public static String makeSyncKey(String name, int id) {
return name + ":" + id;
}
}