RealmsMainScreen .java

com.mojang.realmsclient.RealmsMainScreen (class, 1317 lines): members: INCOMPATIBLE_RELEASE_TYPE_POPUP_MESSAGE, SERVER_EXPIRES_IN_DAY_TOOLTIP, isSnapshot.

com.mojang.realmsclientclass1,317 linescommonextends RealmsScreen53.6 KB

API Surface (48)

void init()
boolean isSnapshot()
void repositionElements()
void onClose()
void tick()
void refreshPendingInvites()
void refreshServerList()
void run()
void resetScreen()
Component getNarrationMessage()
void extractRenderState(final GuiGraphicsExtractor graphics, final int xm, final int ym, final float a)
void play(final @Nullable RealmsServer server, final Screen cancelScreen)
void play(final @Nullable RealmsServer server, final Screen cancelScreen, final boolean skipCompatibility)
Component getVersionComponent(final String version, final boolean isCompatible)
Component getVersionComponent(final String version, final int color)
Component getGameModeComponent(final int gameMode, final boolean hardcore)
void extractContent(final GuiGraphicsExtractor graphics, final int mouseX, final int mouseY, final boolean hovered, final float a)
boolean mouseClicked(final MouseButtonEvent event, final boolean doubleClick)
boolean keyPressed(final KeyEvent event)
Component getNarration()
void extractStatusLights(final RealmsServer serverData, final GuiGraphicsExtractor graphics, final int rowRight, final int rowTop, final int mouseX, final int mouseY)
void extractFirstLine(final GuiGraphicsExtractor graphics, final int rowTop, final int rowLeft, final int rowWidth, final int serverNameColor, final RealmsServer serverData)
void extractSecondLine(final GuiGraphicsExtractor graphics, final int rowTop, final int rowLeft, final int rowWidth, final RealmsServer serverData)
void extractThirdLine(final GuiGraphicsExtractor graphics, final int rowTop, final int rowLeft, final RealmsServer server)
void extractClampedString(final GuiGraphicsExtractor graphics, final @Nullable String string, final int x, final int y, final int maxX, final int color)
int versionTextX(final int rowLeft, final int rowWidth, final Component versionComponent)
int gameModeTextX(final int rowLeft, final int rowWidth, final Component versionComponent)
int extractGameMode(final RealmsServer server, final GuiGraphicsExtractor graphics, final int rowLeft, final int rowWidth, final int firstLineY)
int firstLineY(final int rowTop)
int lineHeight()
int textX(final int rowLeft)
int secondLineY(final int firstLineY)
int thirdLineY(final int firstLineY)
boolean keyPressed(final KeyEvent event)
int textWidth(final int rowWidth)
void extractContent(final GuiGraphicsExtractor graphics, final int mouseX, final int mouseY, final boolean hovered, final float a)
boolean mouseClicked(final MouseButtonEvent event, final boolean doubleClick)
Component getText()
Component getNarration()
void extractContent(final GuiGraphicsExtractor graphics, final int mouseX, final int mouseY, final boolean hovered, final float a)
Component getNarration()
void setSelected(final RealmsMainScreen.@Nullable Entry selected)
int getRowWidth()
void extractContent(final GuiGraphicsExtractor graphics, final int mouseX, final int mouseY, final boolean hovered, final float a)
boolean mouseClicked(final MouseButtonEvent event, final boolean doubleClick)
boolean keyPressed(final KeyEvent event)
Component getNarration()
RealmsServer getServer()

Fields & Constants (63)

INFO_SPRITE
NEW_REALM_SPRITE
EXPIRED_SPRITE
EXPIRES_SOON_SPRITE
OPEN_SPRITE
CLOSED_SPRITE
HARDCORE_MODE_SPRITE
LOGGER
NO_REALMS_LOCATION
TITLE
LOADING_TEXT
SERVER_UNITIALIZED_TEXT
SUBSCRIPTION_EXPIRED_TEXT
SUBSCRIPTION_RENEW_TEXT
TRIAL_EXPIRED_TEXT
PLAY_TEXT
LEAVE_SERVER_TEXT
CONFIGURE_SERVER_TEXT
SERVER_EXPIRED_TOOLTIP
SERVER_EXPIRES_SOON_TOOLTIP
SERVER_EXPIRES_IN_DAY_TOOLTIP
SERVER_OPEN_TOOLTIP
SERVER_CLOSED_TOOLTIP
UNITIALIZED_WORLD_NARRATION
NO_REALMS_TEXT
ADD_REALM_TEXT
FREE_TRIAL
INCOMPATIBLE_POPUP_TITLE
INCOMPATIBLE_RELEASE_TYPE_POPUP_MESSAGE
BUTTON_WIDTH
BUTTON_COLUMNS
BUTTON_SPACING
CONTENT_WIDTH
LOGO_PADDING
HEADER_HEIGHT
FOOTER_PADDING
NEW_REALM_SPRITE_WIDTH
NEW_REALM_SPRITE_HEIGHT
SNAPSHOT
snapshotToggle
availability
dataSubscription
handledSeenNotifications
regionsPinged
inviteNarrationLimiter
lastScreen
playButton
backButton
renewButton
configureButton
leaveButton
realmSelectionList
serverList
availableSnapshotServers
onlinePlayersPerRealm
redirectToPdpIfNoRealms
trialAvailable
notifications
header
addRealmButton
activeLayoutState
layout
message

String literals (66)

"icon/info"
"icon/new_realm"
"realm_status/expired"
"realm_status/expires_soon"
"realm_status/open"
"realm_status/closed"
"hud/heart/hardcore_full"
"textures/gui/realms/no_realms.png"
"menu.online"
"mco.selectServer.loading"
"mco.selectServer.uninitialized"
"mco.selectServer.expiredList"
"mco.selectServer.expiredRenew"
"mco.selectServer.expiredTrial"
"mco.selectServer.play"
"mco.selectServer.leave"
"mco.selectServer.configure"
"mco.selectServer.expired"
"mco.selectServer.expires.soon"
"mco.selectServer.expires.day"
"mco.selectServer.open"
"mco.selectServer.closed"
"gui.narrate.button"
"mco.selectServer.noRealms"

Code Graph: Dependencies (68)

Edges (calls / imports / inherits / references) resolved by graphify from the AST. Every chip opens the class source.

Full Source

RealmsMainScreen.java1317 lines · Minecraft 26.3 · verbatim
1
package com.mojang.realmsclient;
2
3
import com.google.common.collect.Lists;
4
import com.google.common.util.concurrent.RateLimiter;
5
import com.mojang.blaze3d.Blaze3D;
6
import com.mojang.logging.LogUtils;
7
import com.mojang.realmsclient.client.Ping;
8
import com.mojang.realmsclient.client.RealmsClient;
9
import com.mojang.realmsclient.dto.PingResult;
10
import com.mojang.realmsclient.dto.RealmsNotification;
11
import com.mojang.realmsclient.dto.RealmsServer;
12
import com.mojang.realmsclient.dto.RealmsServerPlayerLists;
13
import com.mojang.realmsclient.dto.RegionPingResult;
14
import com.mojang.realmsclient.exception.RealmsServiceException;
15
import com.mojang.realmsclient.gui.RealmsDataFetcher;
16
import com.mojang.realmsclient.gui.RealmsHeader;
17
import com.mojang.realmsclient.gui.RealmsServerList;
18
import com.mojang.realmsclient.gui.screens.RealmsCreateRealmScreen;
19
import com.mojang.realmsclient.gui.screens.RealmsGenericErrorScreen;
20
import com.mojang.realmsclient.gui.screens.RealmsJoinRealmWithCodeScreen;
21
import com.mojang.realmsclient.gui.screens.RealmsLongRunningMcoTaskScreen;
22
import com.mojang.realmsclient.gui.screens.RealmsPdpScreen;
23
import com.mojang.realmsclient.gui.screens.RealmsPopups;
24
import com.mojang.realmsclient.gui.screens.configuration.RealmsConfigureWorldScreen;
25
import com.mojang.realmsclient.gui.task.DataFetcher;
26
import com.mojang.realmsclient.util.RealmsUtil;
27
import com.mojang.realmsclient.util.task.GetServerDetailsTask;
28
import java.net.URI;
29
import java.util.ArrayList;
30
import java.util.Collection;
31
import java.util.HashSet;
32
import java.util.List;
33
import java.util.Map;
34
import java.util.Objects;
35
import java.util.Optional;
36
import java.util.Set;
37
import java.util.UUID;
38
import java.util.concurrent.CompletableFuture;
39
import java.util.function.Consumer;
40
import java.util.function.Supplier;
41
import net.fabricmc.api.EnvType;
42
import net.fabricmc.api.Environment;
43
import net.minecraft.ChatFormatting;
44
import net.minecraft.SharedConstants;
45
import net.minecraft.client.Minecraft;
46
import net.minecraft.client.gui.GuiGraphicsExtractor;
47
import net.minecraft.client.gui.components.AbstractWidget;
48
import net.minecraft.client.gui.components.Button;
49
import net.minecraft.client.gui.components.CycleButton;
50
import net.minecraft.client.gui.components.FocusableTextWidget;
51
import net.minecraft.client.gui.components.ImageButton;
52
import net.minecraft.client.gui.components.ImageWidget;
53
import net.minecraft.client.gui.components.LoadingDotsWidget;
54
import net.minecraft.client.gui.components.MultiLineTextWidget;
55
import net.minecraft.client.gui.components.ObjectSelectionList;
56
import net.minecraft.client.gui.components.PlayerFaceExtractor;
57
import net.minecraft.client.gui.components.PopupScreen;
58
import net.minecraft.client.gui.components.RealmsButton;
59
import net.minecraft.client.gui.components.Tooltip;
60
import net.minecraft.client.gui.components.WidgetSprites;
61
import net.minecraft.client.gui.components.WidgetTooltipHolder;
62
import net.minecraft.client.gui.layouts.FrameLayout;
63
import net.minecraft.client.gui.layouts.GridLayout;
64
import net.minecraft.client.gui.layouts.HeaderAndFooterLayout;
65
import net.minecraft.client.gui.layouts.Layout;
66
import net.minecraft.client.gui.layouts.LinearLayout;
67
import net.minecraft.client.gui.layouts.SpacerElement;
68
import net.minecraft.client.gui.navigation.ScreenRectangle;
69
import net.minecraft.client.gui.screens.ConfirmLinkScreen;
70
import net.minecraft.client.gui.screens.Screen;
71
import net.minecraft.client.gui.screens.TitleScreen;
72
import net.minecraft.client.gui.screens.inventory.tooltip.ClientActivePlayersTooltip;
73
import net.minecraft.client.input.KeyEvent;
74
import net.minecraft.client.input.MouseButtonEvent;
75
import net.minecraft.client.renderer.PlayerSkinRenderCache;
76
import net.minecraft.client.renderer.RenderPipelines;
77
import net.minecraft.client.resources.sounds.SimpleSoundInstance;
78
import net.minecraft.network.chat.CommonComponents;
79
import net.minecraft.network.chat.Component;
80
import net.minecraft.realms.RealmsScreen;
81
import net.minecraft.resources.Identifier;
82
import net.minecraft.sounds.SoundEvents;
83
import net.minecraft.util.CommonLinks;
84
import net.minecraft.util.Util;
85
import net.minecraft.util.CommonLinks.ExtensionReference;
86
import net.minecraft.world.item.component.ResolvableProfile;
87
import net.minecraft.world.level.GameType;
88
import org.apache.commons.lang3.StringUtils;
89
import org.jspecify.annotations.Nullable;
90
import org.slf4j.Logger;
91
92
@Environment(EnvType.CLIENT)
93
public class RealmsMainScreen extends RealmsScreen {
94
	private static final Identifier INFO_SPRITE = Identifier.withDefaultNamespace("icon/info");
95
	private static final Identifier NEW_REALM_SPRITE = Identifier.withDefaultNamespace("icon/new_realm");
96
	private static final Identifier EXPIRED_SPRITE = Identifier.withDefaultNamespace("realm_status/expired");
97
	private static final Identifier EXPIRES_SOON_SPRITE = Identifier.withDefaultNamespace("realm_status/expires_soon");
98
	private static final Identifier OPEN_SPRITE = Identifier.withDefaultNamespace("realm_status/open");
99
	private static final Identifier CLOSED_SPRITE = Identifier.withDefaultNamespace("realm_status/closed");
100
	public static final Identifier HARDCORE_MODE_SPRITE = Identifier.withDefaultNamespace("hud/heart/hardcore_full");
101
	private static final Logger LOGGER = LogUtils.getLogger();
102
	private static final Identifier NO_REALMS_LOCATION = Identifier.withDefaultNamespace("textures/gui/realms/no_realms.png");
103
	private static final Component TITLE = Component.translatable("menu.online");
104
	private static final Component LOADING_TEXT = Component.translatable("mco.selectServer.loading");
105
	private static final Component SERVER_UNITIALIZED_TEXT = Component.translatable("mco.selectServer.uninitialized");
106
	private static final Component SUBSCRIPTION_EXPIRED_TEXT = Component.translatable("mco.selectServer.expiredList");
107
	private static final Component SUBSCRIPTION_RENEW_TEXT = Component.translatable("mco.selectServer.expiredRenew");
108
	private static final Component TRIAL_EXPIRED_TEXT = Component.translatable("mco.selectServer.expiredTrial");
109
	private static final Component PLAY_TEXT = Component.translatable("mco.selectServer.play");
110
	private static final Component LEAVE_SERVER_TEXT = Component.translatable("mco.selectServer.leave");
111
	private static final Component CONFIGURE_SERVER_TEXT = Component.translatable("mco.selectServer.configure");
112
	private static final Component SERVER_EXPIRED_TOOLTIP = Component.translatable("mco.selectServer.expired");
113
	private static final Component SERVER_EXPIRES_SOON_TOOLTIP = Component.translatable("mco.selectServer.expires.soon");
114
	private static final Component SERVER_EXPIRES_IN_DAY_TOOLTIP = Component.translatable("mco.selectServer.expires.day");
115
	private static final Component SERVER_OPEN_TOOLTIP = Component.translatable("mco.selectServer.open");
116
	private static final Component SERVER_CLOSED_TOOLTIP = Component.translatable("mco.selectServer.closed");
117
	private static final Component UNITIALIZED_WORLD_NARRATION = Component.translatable("gui.narrate.button", SERVER_UNITIALIZED_TEXT);
118
	private static final Component NO_REALMS_TEXT = Component.translatable("mco.selectServer.noRealms");
119
	private static final Component ADD_REALM_TEXT = Component.translatable("mco.selectServer.purchase");
120
	private static final Component FREE_TRIAL = Component.translatable("mco.selectServer.freeTrial");
121
	private static final Component INCOMPATIBLE_POPUP_TITLE = Component.translatable("mco.compatibility.incompatible.popup.title");
122
	private static final Component INCOMPATIBLE_RELEASE_TYPE_POPUP_MESSAGE = Component.translatable("mco.compatibility.incompatible.releaseType.popup.message");
123
	private static final int BUTTON_WIDTH = 100;
124
	private static final int BUTTON_COLUMNS = 3;
125
	private static final int BUTTON_SPACING = 4;
126
	private static final int CONTENT_WIDTH = 308;
127
	private static final int LOGO_PADDING = 5;
128
	private static final int HEADER_HEIGHT = 44;
129
	private static final int FOOTER_PADDING = 11;
130
	private static final int NEW_REALM_SPRITE_WIDTH = 40;
131
	private static final int NEW_REALM_SPRITE_HEIGHT = 20;
132
	private static final boolean SNAPSHOT = !SharedConstants.getCurrentVersion().stable();
133
	private static boolean snapshotToggle = SNAPSHOT;
134
	private final CompletableFuture<RealmsAvailability.Result> availability = RealmsAvailability.get();
135
	private DataFetcher.@Nullable Subscription dataSubscription;
136
	private final Set<UUID> handledSeenNotifications = new HashSet<>();
137
	private static boolean regionsPinged;
138
	private final RateLimiter inviteNarrationLimiter;
139
	private final Screen lastScreen;
140
	private Button playButton;
141
	private Button backButton;
142
	private Button renewButton;
143
	private Button configureButton;
144
	private Button leaveButton;
145
	private RealmsMainScreen.RealmSelectionList realmSelectionList;
146
	private RealmsServerList serverList;
147
	private List<RealmsServer> availableSnapshotServers = List.of();
148
	private RealmsServerPlayerLists onlinePlayersPerRealm = new RealmsServerPlayerLists(Map.of());
149
	private boolean redirectToPdpIfNoRealms;
150
	private boolean trialAvailable;
151
	private final List<RealmsNotification> notifications = new ArrayList<>();
152
	private final RealmsHeader header;
153
	private Button addRealmButton;
154
	private RealmsMainScreen.LayoutState activeLayoutState;
155
	private @Nullable HeaderAndFooterLayout layout;
156
157
	public RealmsMainScreen(final Screen lastScreen) {
158
		super(TITLE);
159
		this.lastScreen = lastScreen;
160
		this.redirectToPdpIfNoRealms = lastScreen instanceof TitleScreen && Minecraft.getInstance().gui.screen() == lastScreen;
161
		this.header = new RealmsHeader(this, this::openJoinRealmScreen);
162
		this.inviteNarrationLimiter = RateLimiter.create(0.016666668F);
163
	}
164
165
	@Override
166
	public void init() {
167
		this.serverList = new RealmsServerList(this.minecraft);
168
		this.realmSelectionList = new RealmsMainScreen.RealmSelectionList();
169
		this.playButton = Button.builder(PLAY_TEXT, button -> play(this.getSelectedServer(), this)).width(100).build();
170
		this.configureButton = Button.builder(CONFIGURE_SERVER_TEXT, button -> this.configureClicked(this.getSelectedServer())).width(100).build();
171
		this.renewButton = Button.builder(SUBSCRIPTION_RENEW_TEXT, button -> this.onRenew(this.getSelectedServer())).width(100).build();
172
		this.leaveButton = Button.builder(LEAVE_SERVER_TEXT, button -> this.leaveClicked(this.getSelectedServer())).width(100).build();
173
		this.addRealmButton = this.createAddRealmButton();
174
		this.backButton = Button.builder(CommonComponents.GUI_BACK, button -> this.onClose()).width(100).build();
175
		this.updateLayout(RealmsMainScreen.LayoutState.LOADING);
176
		this.updateButtonStates();
177
		this.availability.thenAcceptAsync(result -> {
178
			Screen errorScreen = result.createErrorScreen(this.lastScreen);
179
			if (errorScreen == null) {
180
				this.dataSubscription = this.initDataFetcher(this.minecraft.realmsDataFetcher());
181
			} else {
182
				this.minecraft.gui.setScreen(errorScreen);
183
			}
184
		}, this.screenExecutor);
185
	}
186
187
	public static boolean isSnapshot() {
188
		return SNAPSHOT && snapshotToggle;
189
	}
190
191
	@Override
192
	protected void repositionElements() {
193
		if (this.layout != null) {
194
			this.realmSelectionList.updateSize(this.width, this.layout);
195
			this.layout.arrangeElements();
196
		}
197
	}
198
199
	@Override
200
	public void onClose() {
201
		this.minecraft.gui.setScreen(this.lastScreen);
202
	}
203
204
	private void updateLayout() {
205
		if (this.serverList.isEmpty() && this.availableSnapshotServers.isEmpty() && this.notifications.isEmpty()) {
206
			this.updateLayout(RealmsMainScreen.LayoutState.NO_REALMS);
207
		} else {
208
			this.updateLayout(RealmsMainScreen.LayoutState.LIST);
209
		}
210
	}
211
212
	private void updateLayout(final RealmsMainScreen.LayoutState state) {
213
		this.updateLayout(state, false);
214
	}
215
216
	private void updateLayout(final RealmsMainScreen.LayoutState state, final boolean force) {
217
		if (force || this.activeLayoutState != state) {
218
			if (this.layout != null) {
219
				this.layout.visitWidgets(x$0 -> this.removeWidget(x$0));
220
			}
221
222
			this.layout = this.createLayout(state);
223
			this.activeLayoutState = state;
224
			this.layout.visitWidgets(x$0 -> this.addRenderableWidget(x$0));
225
			this.repositionElements();
226
		}
227
	}
228
229
	private HeaderAndFooterLayout createLayout(final RealmsMainScreen.LayoutState state) {
230
		HeaderAndFooterLayout layout = new HeaderAndFooterLayout(this);
231
		layout.setHeaderHeight(44);
232
		layout.addToHeader(this.createHeader());
233
		Layout footer = this.createFooter(state);
234
		footer.arrangeElements();
235
		layout.setFooterHeight(footer.getHeight() + 22);
236
		layout.addToFooter(footer);
237
		switch (state) {
238
			case LOADING:
239
				layout.addToContents(new LoadingDotsWidget(this.font, LOADING_TEXT));
240
				break;
241
			case NO_REALMS:
242
				layout.addToContents(this.createNoRealmsContent());
243
				break;
244
			case LIST:
245
				layout.addToContents(this.realmSelectionList);
246
		}
247
248
		return layout;
249
	}
250
251
	private Layout createHeader() {
252
		return this.header.createLayout(realmsLogo(), 44, 4);
253
	}
254
255
	private Button createAddRealmButton() {
256
		return this.trialAvailable
257
			? new RealmsButton(0, 0, 100, 20, FREE_TRIAL, var1 -> this.openRealmsPdp())
258
			: Button.builder(ADD_REALM_TEXT, var1 -> this.openRealmsPdp()).size(100, 20).build();
259
	}
260
261
	private Layout createFooter(final RealmsMainScreen.LayoutState state) {
262
		GridLayout footer = new GridLayout().spacing(4);
263
		GridLayout.RowHelper helper = footer.createRowHelper(3);
264
		if (RealmsClient.ENVIRONMENT == RealmsClient.Environment.STAGE) {
265
			helper.addChild(
266
				CycleButton.booleanBuilder(Component.literal("Snapshot"), Component.literal("Release"), snapshotToggle)
267
					.create(0, 0, 100, 20, Component.literal("Realm"), (button, value) -> {
268
						snapshotToggle = value;
269
						this.availableSnapshotServers = List.of();
270
						this.debugRefreshDataFetchers();
271
					}),
272
				3,
273
				helper.newCellSettings().alignHorizontallyCenter()
274
			);
275
		}
276
277
		if (state == RealmsMainScreen.LayoutState.LIST) {
278
			helper.addChild(this.playButton);
279
			helper.addChild(this.configureButton);
280
			helper.addChild(this.renewButton);
281
			helper.addChild(this.leaveButton);
282
		}
283
284
		helper.addChild(this.addRealmButton);
285
		helper.addChild(this.backButton);
286
		return footer;
287
	}
288
289
	private LinearLayout createNoRealmsContent() {
290
		LinearLayout content = LinearLayout.vertical().spacing(8);
291
		content.defaultCellSetting().alignHorizontallyCenter();
292
		content.addChild(ImageWidget.texture(130, 64, NO_REALMS_LOCATION, 130, 64));
293
		content.addChild(
294
			FocusableTextWidget.builder(NO_REALMS_TEXT, this.font)
295
				.maxWidth(308)
296
				.alwaysShowBorder(false)
297
				.backgroundFill(FocusableTextWidget.BackgroundFill.ON_FOCUS)
298
				.build()
299
		);
300
		return content;
301
	}
302
303
	private void updateButtonStates() {
304
		RealmsServer server = this.getSelectedServer();
305
		boolean serverSelected = server != null;
306
		this.addRealmButton.active = this.activeLayoutState != RealmsMainScreen.LayoutState.LOADING;
307
		this.header.setJoinRealmButtonActive(this.activeLayoutState != RealmsMainScreen.LayoutState.LOADING);
308
		this.playButton.active = serverSelected && server.shouldPlayButtonBeActive();
309
		if (!this.playButton.active && serverSelected && server.state == RealmsServer.State.CLOSED) {
310
			this.playButton.setTooltip(Tooltip.create(RealmsServer.WORLD_CLOSED_COMPONENT));
311
		}
312
313
		this.renewButton.active = serverSelected && this.shouldRenewButtonBeActive(server);
314
		this.leaveButton.active = serverSelected && this.shouldLeaveButtonBeActive(server);
315
		this.configureButton.active = serverSelected && this.shouldConfigureButtonBeActive(server);
316
	}
317
318
	private boolean shouldRenewButtonBeActive(final RealmsServer server) {
319
		return server.expired && isSelfOwnedServer(server);
320
	}
321
322
	private boolean shouldConfigureButtonBeActive(final RealmsServer server) {
323
		return isSelfOwnedServer(server) && server.state != RealmsServer.State.UNINITIALIZED;
324
	}
325
326
	private boolean shouldLeaveButtonBeActive(final RealmsServer server) {
327
		return !isSelfOwnedServer(server);
328
	}
329
330
	@Override
331
	public void tick() {
332
		super.tick();
333
		if (this.dataSubscription != null) {
334
			this.dataSubscription.tick();
335
		}
336
	}
337
338
	public static void refreshPendingInvites() {
339
		Minecraft.getInstance().realmsDataFetcher().pendingInvitesTask.reset();
340
	}
341
342
	public static void refreshServerList() {
343
		Minecraft.getInstance().realmsDataFetcher().serverListUpdateTask.reset();
344
	}
345
346
	private void debugRefreshDataFetchers() {
347
		for (DataFetcher.Task<?> task : this.minecraft.realmsDataFetcher().getTasks()) {
348
			task.reset();
349
		}
350
	}
351
352
	private DataFetcher.Subscription initDataFetcher(final RealmsDataFetcher dataSource) {
353
		DataFetcher.Subscription result = dataSource.dataFetcher.createSubscription();
354
		result.subscribe(dataSource.serverListUpdateTask, updatedServers -> {
355
			this.serverList.updateServersList(updatedServers.serverList());
356
			this.availableSnapshotServers = updatedServers.availableSnapshotServers();
357
			this.refreshListAndLayout();
358
			this.openPdpIfNoRealms();
359
			boolean ownsNonExpiredRealmServer = false;
360
361
			for (RealmsServer retrievedServer : this.serverList) {
362
				if (this.isSelfOwnedNonExpiredServer(retrievedServer)) {
363
					ownsNonExpiredRealmServer = true;
364
				}
365
			}
366
367
			if (!regionsPinged && ownsNonExpiredRealmServer) {
368
				regionsPinged = true;
369
				this.pingRegions();
370
			}
371
		});
372
		callRealmsClient(RealmsClient::getNotifications, retrievedNotifications -> {
373
			this.notifications.clear();
374
			this.notifications.addAll(retrievedNotifications);
375
376
			for (RealmsNotification notification : retrievedNotifications) {
377
				if (notification instanceof RealmsNotification.InfoPopup popup) {
378
					PopupScreen popupScreen = popup.buildScreen(this, this::dismissNotification);
379
					if (popupScreen != null) {
380
						this.minecraft.gui.setScreen(popupScreen);
381
						this.markNotificationsAsSeen(List.of(notification));
382
						break;
383
					}
384
				}
385
			}
386
387
			if (!this.notifications.isEmpty() && this.activeLayoutState != RealmsMainScreen.LayoutState.LOADING) {
388
				this.refreshListAndLayout();
389
			}
390
		});
391
		result.subscribe(dataSource.pendingInvitesTask, numberOfPendingInvites -> {
392
			this.header.setPendingInvites(numberOfPendingInvites);
393
			if (numberOfPendingInvites > 0 && this.inviteNarrationLimiter.tryAcquire(1)) {
394
				this.minecraft.getNarrator().saySystemNow(Component.translatable("mco.configure.world.invite.narration", numberOfPendingInvites));
395
			}
396
		});
397
		result.subscribe(dataSource.trialAvailabilityTask, this::setTrialAvailable);
398
		result.subscribe(dataSource.onlinePlayersTask, playerList -> this.onlinePlayersPerRealm = playerList);
399
		result.subscribe(dataSource.newsTask, news -> {
400
			dataSource.newsManager.updateUnreadNews(news);
401
			this.header.setNews(dataSource.newsManager.newsLink(), dataSource.newsManager.hasUnreadNews());
402
		});
403
		return result;
404
	}
405
406
	private void markNotificationsAsSeen(final Collection<RealmsNotification> notifications) {
407
		List<UUID> seenNotifications = new ArrayList<>(notifications.size());
408
409
		for (RealmsNotification notification : notifications) {
410
			if (!notification.seen() && !this.handledSeenNotifications.contains(notification.uuid())) {
411
				seenNotifications.add(notification.uuid());
412
			}
413
		}
414
415
		if (!seenNotifications.isEmpty()) {
416
			callRealmsClient(realmsClient -> {
417
				realmsClient.notificationsSeen(seenNotifications);
418
				return null;
419
			}, ignored -> this.handledSeenNotifications.addAll(seenNotifications));
420
		}
421
	}
422
423
	private static <T> void callRealmsClient(final RealmsMainScreen.RealmsCall<T> supplier, final Consumer<T> callback) {
424
		Minecraft minecraft = Minecraft.getInstance();
425
		CompletableFuture.<T>supplyAsync(() -> {
426
			try {
427
				return supplier.request(RealmsClient.getOrCreate(minecraft));
428
			} catch (RealmsServiceException e) {
429
				throw new RuntimeException(e);
430
			}
431
		}, Util.nonCriticalIoPool()).thenAcceptAsync(callback, minecraft).exceptionally(e -> {
432
			LOGGER.error("Failed to execute call to Realms Service", e);
433
			return null;
434
		});
435
	}
436
437
	private void refreshListAndLayout() {
438
		this.realmSelectionList.refreshEntries(this);
439
		this.updateLayout();
440
		this.updateButtonStates();
441
	}
442
443
	private void openPdpIfNoRealms() {
444
		if (this.redirectToPdpIfNoRealms) {
445
			this.redirectToPdpIfNoRealms = false;
446
			if (this.serverList.isEmpty() && this.availableSnapshotServers.isEmpty() && this.minecraft.gui.screen() == this) {
447
				this.minecraft
448
					.gui
449
					.setScreen(new RealmsPdpScreen(this.lastScreen, this.trialAvailable, this::openJoinRealmScreen, () -> this.minecraft.gui.setScreen(this)));
450
			}
451
		}
452
	}
453
454
	private void setTrialAvailable(final boolean trialAvailable) {
455
		if (this.trialAvailable != trialAvailable) {
456
			this.trialAvailable = trialAvailable;
457
			this.addRealmButton = this.createAddRealmButton();
458
			this.updateLayout(this.activeLayoutState, true);
459
			this.updateButtonStates();
460
		}
461
	}
462
463
	private void pingRegions() {
464
		Util.nonCriticalIoPool().execute(() -> {
465
			List<RegionPingResult> regionPingResultList = Ping.pingAllRegions();
466
			RealmsClient client = RealmsClient.getOrCreate();
467
			PingResult pingResult = new PingResult(regionPingResultList, this.getOwnedNonExpiredRealmIds());
468
469
			try {
470
				client.sendPingResults(pingResult);
471
			} catch (Throwable t) {
472
				LOGGER.warn("Could not send ping result to Realms: ", t);
473
			}
474
		});
475
	}
476
477
	private List<Long> getOwnedNonExpiredRealmIds() {
478
		List<Long> ids = Lists.newArrayList();
479
480
		for (RealmsServer server : this.serverList) {
481
			if (this.isSelfOwnedNonExpiredServer(server)) {
482
				ids.add(server.id);
483
			}
484
		}
485
486
		return ids;
487
	}
488
489
	private void onRenew(final @Nullable RealmsServer server) {
490
		if (server != null) {
491
			ExtensionReference reference = server.expiredTrial ? ExtensionReference.EXPIRED_TRIAL : ExtensionReference.EXPIRED_REALM;
492
			URI extensionUrl = CommonLinks.extendRealms(server.remoteSubscriptionId, this.minecraft.getUser().getProfileId(), reference);
493
			this.minecraft.gui.setScreen(new ConfirmLinkScreen(result -> {
494
				if (result) {
495
					Blaze3D.openUri(extensionUrl);
496
				} else {
497
					this.minecraft.gui.setScreen(this);
498
				}
499
			}, extensionUrl, true));
500
		}
501
	}
502
503
	private void configureClicked(final @Nullable RealmsServer selectedServer) {
504
		if (selectedServer != null && this.minecraft.isLocalPlayer(selectedServer.ownerUUID)) {
505
			this.minecraft.gui.setScreen(new RealmsConfigureWorldScreen(this, selectedServer.id));
506
		}
507
	}
508
509
	private void leaveClicked(final @Nullable RealmsServer selectedServer) {
510
		if (selectedServer != null && !this.minecraft.isLocalPlayer(selectedServer.ownerUUID)) {
511
			Component popupMessage = Component.translatable("mco.configure.world.leave.question.line1");
512
			this.minecraft.gui.setScreen(RealmsPopups.infoPopupScreen(this, popupMessage, var2x -> this.leaveServer(selectedServer)));
513
		}
514
	}
515
516
	private @Nullable RealmsServer getSelectedServer() {
517
		return this.realmSelectionList.getSelected() instanceof RealmsMainScreen.ServerEntry entry ? entry.getServer() : null;
518
	}
519
520
	private void leaveServer(final RealmsServer server) {
521
		(new Thread("Realms-leave-server") {
522
			@Override
523
			public void run() {
524
				try {
525
					RealmsClient client = RealmsClient.getOrCreate();
526
					client.uninviteMyselfFrom(server.id);
527
					RealmsMainScreen.this.minecraft.execute(RealmsMainScreen::refreshServerList);
528
				} catch (RealmsServiceException e) {
529
					RealmsMainScreen.LOGGER.error("Couldn't configure world", e);
530
					RealmsMainScreen.this.minecraft.execute(() -> RealmsMainScreen.this.minecraft.gui.setScreen(new RealmsGenericErrorScreen(e, RealmsMainScreen.this)));
531
				}
532
			}
533
		}).start();
534
		this.minecraft.gui.setScreen(this);
535
	}
536
537
	private void dismissNotification(final UUID uuid) {
538
		callRealmsClient(realmsClient -> {
539
			realmsClient.notificationsDismiss(List.of(uuid));
540
			return null;
541
		}, ignored -> {
542
			this.notifications.removeIf(notification -> notification.dismissable() && uuid.equals(notification.uuid()));
543
			this.refreshListAndLayout();
544
		});
545
	}
546
547
	public void resetScreen() {
548
		this.realmSelectionList.setSelected((RealmsMainScreen.Entry)null);
549
		refreshServerList();
550
	}
551
552
	@Override
553
	public Component getNarrationMessage() {
554
		return switch (this.activeLayoutState) {
555
			case LOADING -> CommonComponents.joinForNarration(super.getNarrationMessage(), LOADING_TEXT);
556
			case NO_REALMS -> CommonComponents.joinForNarration(super.getNarrationMessage(), NO_REALMS_TEXT);
557
			case LIST -> super.getNarrationMessage();
558
		};
559
	}
560
561
	@Override
562
	public void extractRenderState(final GuiGraphicsExtractor graphics, final int xm, final int ym, final float a) {
563
		super.extractRenderState(graphics, xm, ym, a);
564
		if (isSnapshot()) {
565
			graphics.text(this.font, "Minecraft " + SharedConstants.getCurrentVersion().name(), 2, this.height - 10, -1);
566
		}
567
568
		switch (RealmsClient.ENVIRONMENT) {
569
			case STAGE:
570
				this.extractEnvironment(graphics, "STAGE!", -256);
571
				break;
572
			case LOCAL:
573
				this.extractEnvironment(graphics, "LOCAL!", -8388737);
574
		}
575
	}
576
577
	private void openRealmsPdp() {
578
		this.minecraft.gui.setScreen(new RealmsPdpScreen(this, this.trialAvailable, this::openJoinRealmScreen));
579
	}
580
581
	private void openJoinRealmScreen() {
582
		Screen lastScreen = this.minecraft.gui.screen();
583
		if (lastScreen != null) {
584
			this.minecraft.gui.setScreen(new RealmsJoinRealmWithCodeScreen(lastScreen, () -> {
585
				this.minecraft.gui.setScreen(this);
586
				this.resetScreen();
587
			}));
588
		}
589
	}
590
591
	public static void play(final @Nullable RealmsServer server, final Screen cancelScreen) {
592
		play(server, cancelScreen, false);
593
	}
594
595
	public static void play(final @Nullable RealmsServer server, final Screen cancelScreen, final boolean skipCompatibility) {
596
		if (server != null) {
597
			if (!isSnapshot() || skipCompatibility || server.isMinigameActive()) {
598
				Minecraft.getInstance().gui.setScreen(new RealmsLongRunningMcoTaskScreen(cancelScreen, new GetServerDetailsTask(cancelScreen, server)));
599
				return;
600
			}
601
602
			switch (server.compatibility) {
603
				case COMPATIBLE:
604
					Minecraft.getInstance().gui.setScreen(new RealmsLongRunningMcoTaskScreen(cancelScreen, new GetServerDetailsTask(cancelScreen, server)));
605
					break;
606
				case UNVERIFIABLE:
607
					confirmToPlay(
608
						server,
609
						cancelScreen,
610
						Component.translatable("mco.compatibility.unverifiable.title").withColor(-171),
611
						Component.translatable("mco.compatibility.unverifiable.message"),
612
						CommonComponents.GUI_CONTINUE
613
					);
614
					break;
615
				case NEEDS_DOWNGRADE:
616
					confirmToPlay(
617
						server,
618
						cancelScreen,
619
						Component.translatable("selectWorld.backupQuestion.downgrade").withColor(-2142128),
620
						Component.translatable(
621
							"mco.compatibility.downgrade.description",
622
							Component.literal(server.activeVersion).withColor(-171),
623
							Component.literal(SharedConstants.getCurrentVersion().name()).withColor(-171)
624
						),
625
						Component.translatable("mco.compatibility.downgrade")
626
					);
627
					break;
628
				case NEEDS_UPGRADE:
629
					upgradeRealmAndPlay(server, cancelScreen);
630
					break;
631
				case INCOMPATIBLE:
632
					Minecraft.getInstance()
633
						.gui
634
						.setScreen(
635
							new PopupScreen.Builder(cancelScreen, INCOMPATIBLE_POPUP_TITLE)
636
								.addMessage(
637
									Component.translatable(
638
										"mco.compatibility.incompatible.series.popup.message",
639
										Component.literal(server.activeVersion).withColor(-171),
640
										Component.literal(SharedConstants.getCurrentVersion().name()).withColor(-171)
641
									)
642
								)
643
								.addButton(CommonComponents.GUI_BACK, PopupScreen::onClose)
644
								.build()
645
						);
646
					break;
647
				case RELEASE_TYPE_INCOMPATIBLE:
648
					Minecraft.getInstance()
649
						.gui
650
						.setScreen(
651
							new PopupScreen.Builder(cancelScreen, INCOMPATIBLE_POPUP_TITLE)
652
								.addMessage(INCOMPATIBLE_RELEASE_TYPE_POPUP_MESSAGE)
653
								.addButton(CommonComponents.GUI_BACK, PopupScreen::onClose)
654
								.build()
655
						);
656
			}
657
		}
658
	}
659
660
	private static void confirmToPlay(
661
		final RealmsServer server, final Screen lastScreen, final Component title, final Component message, final Component confirmButton
662
	) {
663
		Minecraft.getInstance().gui.setScreen(new PopupScreen.Builder(lastScreen, title).addMessage(message).addButton(confirmButton, var2 -> {
664
			Minecraft.getInstance().gui.setScreen(new RealmsLongRunningMcoTaskScreen(lastScreen, new GetServerDetailsTask(lastScreen, server)));
665
			refreshServerList();
666
		}).addButton(CommonComponents.GUI_CANCEL, PopupScreen::onClose).build());
667
	}
668
669
	private static void upgradeRealmAndPlay(final RealmsServer server, final Screen cancelScreen) {
670
		Component title = Component.translatable("mco.compatibility.upgrade.title").withColor(-171);
671
		Component confirmButton = Component.translatable("mco.compatibility.upgrade");
672
		Component serverVersion = Component.literal(server.activeVersion).withColor(-171);
673
		Component clientVersion = Component.literal(SharedConstants.getCurrentVersion().name()).withColor(-171);
674
		Component message = isSelfOwnedServer(server)
675
			? Component.translatable("mco.compatibility.upgrade.description", serverVersion, clientVersion)
676
			: Component.translatable("mco.compatibility.upgrade.friend.description", serverVersion, clientVersion);
677
		confirmToPlay(server, cancelScreen, title, message, confirmButton);
678
	}
679
680
	public static Component getVersionComponent(final String version, final boolean isCompatible) {
681
		return getVersionComponent(version, isCompatible ? -8355712 : -2142128);
682
	}
683
684
	public static Component getVersionComponent(final String version, final int color) {
685
		return StringUtils.isBlank(version) ? CommonComponents.EMPTY : Component.literal(version).withColor(color);
686
	}
687
688
	public static Component getGameModeComponent(final int gameMode, final boolean hardcore) {
689
		return hardcore ? Component.translatable("gameMode.hardcore").withColor(-65536) : GameType.byId(gameMode).getLongDisplayName();
690
	}
691
692
	private static boolean isSelfOwnedServer(final RealmsServer serverData) {
693
		return Minecraft.getInstance().isLocalPlayer(serverData.ownerUUID);
694
	}
695
696
	private boolean isSelfOwnedNonExpiredServer(final RealmsServer serverData) {
697
		return isSelfOwnedServer(serverData) && !serverData.expired;
698
	}
699
700
	private void extractEnvironment(final GuiGraphicsExtractor graphics, final String text, final int color) {
701
		graphics.pose().pushMatrix();
702
		graphics.pose().translate(this.width / 2 - 25, 20.0F);
703
		graphics.pose().rotate((float) (-Math.PI / 9));
704
		graphics.pose().scale(1.5F, 1.5F);
705
		graphics.text(this.font, text, 0, 0, color);
706
		graphics.pose().popMatrix();
707
	}
708
709
	@Environment(EnvType.CLIENT)
710
	private class AvailableSnapshotEntry extends RealmsMainScreen.Entry {
711
		private static final Component START_SNAPSHOT_REALM = Component.translatable("mco.snapshot.start");
712
		private static final int TEXT_PADDING = 5;
713
		private final WidgetTooltipHolder tooltip = new WidgetTooltipHolder();
714
		private final RealmsServer parent;
715
716
		public AvailableSnapshotEntry(final RealmsServer parent) {
717
			this.parent = parent;
718
			this.tooltip.set(Tooltip.create(Component.translatable("mco.snapshot.tooltip")));
719
		}
720
721
		@Override
722
		public void extractContent(final GuiGraphicsExtractor graphics, final int mouseX, final int mouseY, final boolean hovered, final float a) {
723
			graphics.blitSprite(RenderPipelines.GUI_TEXTURED, RealmsMainScreen.NEW_REALM_SPRITE, this.getContentX() - 5, this.getContentYMiddle() - 10, 40, 20);
724
			int textYPos = this.getContentYMiddle() - 9 / 2;
725
			graphics.text(RealmsMainScreen.this.font, START_SNAPSHOT_REALM, this.getContentX() + 40 - 2, textYPos - 5, -8388737);
726
			graphics.text(
727
				RealmsMainScreen.this.font,
728
				Component.translatable("mco.snapshot.description", Objects.requireNonNullElse(this.parent.name, "unknown server")),
729
				this.getContentX() + 40 - 2,
730
				textYPos + 5,
731
				-8355712
732
			);
733
			this.tooltip
734
				.refreshTooltipForNextRenderPass(
735
					graphics,
736
					mouseX,
737
					mouseY,
738
					hovered,
739
					this.isFocused() && RealmsMainScreen.this.minecraft.gui.screen() == RealmsMainScreen.this,
740
					new ScreenRectangle(this.getContentX(), this.getContentY(), this.getContentWidth(), this.getContentHeight())
741
				);
742
		}
743
744
		@Override
745
		public boolean mouseClicked(final MouseButtonEvent event, final boolean doubleClick) {
746
			this.addSnapshotRealm();
747
			return true;
748
		}
749
750
		@Override
751
		public boolean keyPressed(final KeyEvent event) {
752
			if (event.isSelection()) {
753
				this.addSnapshotRealm();
754
				return false;
755
			} else {
756
				return super.keyPressed(event);
757
			}
758
		}
759
760
		private void addSnapshotRealm() {
761
			RealmsMainScreen.this.minecraft.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F));
762
			RealmsMainScreen.this.minecraft
763
				.gui
764
				.setScreen(
765
					new PopupScreen.Builder(RealmsMainScreen.this, Component.translatable("mco.snapshot.createSnapshotPopup.title"))
766
						.addMessage(Component.translatable("mco.snapshot.createSnapshotPopup.text"))
767
						.addButton(
768
							Component.translatable("mco.selectServer.create"),
769
							var1 -> RealmsMainScreen.this.minecraft.gui.setScreen(new RealmsCreateRealmScreen(RealmsMainScreen.this, this.parent, true))
770
						)
771
						.addButton(CommonComponents.GUI_CANCEL, PopupScreen::onClose)
772
						.build()
773
				);
774
		}
775
776
		@Override
777
		public Component getNarration() {
778
			return Component.translatable(
779
				"gui.narrate.button",
780
				CommonComponents.joinForNarration(
781
					START_SNAPSHOT_REALM, Component.translatable("mco.snapshot.description", Objects.requireNonNullElse(this.parent.name, "unknown server"))
782
				)
783
			);
784
		}
785
	}
786
787
	@Environment(EnvType.CLIENT)
788
	private static class CrossButton extends ImageButton {
789
		private static final WidgetSprites SPRITES = new WidgetSprites(
790
			Identifier.withDefaultNamespace("widget/cross_button"), Identifier.withDefaultNamespace("widget/cross_button_highlighted")
791
		);
792
793
		protected CrossButton(final Button.OnPress onPress, final Component tooltip) {
794
			super(0, 0, 14, 14, SPRITES, onPress);
795
			this.setTooltip(Tooltip.create(tooltip));
796
		}
797
	}
798
799
	@Environment(EnvType.CLIENT)
800
	private abstract class Entry extends ObjectSelectionList.Entry<RealmsMainScreen.Entry> {
801
		protected static final int STATUS_LIGHT_WIDTH = 10;
802
		private static final int STATUS_LIGHT_HEIGHT = 28;
803
		protected static final int PADDING_X = 7;
804
		protected static final int PADDING_Y = 2;
805
806
		protected void extractStatusLights(
807
			final RealmsServer serverData, final GuiGraphicsExtractor graphics, final int rowRight, final int rowTop, final int mouseX, final int mouseY
808
		) {
809
			int x = rowRight - 10 - 7;
810
			int y = rowTop + 2;
811
			if (serverData.expired) {
812
				this.extractRealmStatus(graphics, x, y, mouseX, mouseY, RealmsMainScreen.EXPIRED_SPRITE, () -> RealmsMainScreen.SERVER_EXPIRED_TOOLTIP);
813
			} else if (serverData.state == RealmsServer.State.CLOSED) {
814
				this.extractRealmStatus(graphics, x, y, mouseX, mouseY, RealmsMainScreen.CLOSED_SPRITE, () -> RealmsMainScreen.SERVER_CLOSED_TOOLTIP);
815
			} else if (RealmsMainScreen.isSelfOwnedServer(serverData) && serverData.daysLeft < 7) {
816
				this.extractRealmStatus(
817
					graphics,
818
					x,
819
					y,
820
					mouseX,
821
					mouseY,
822
					RealmsMainScreen.EXPIRES_SOON_SPRITE,
823
					() -> {
824
						if (serverData.daysLeft <= 0) {
825
							return RealmsMainScreen.SERVER_EXPIRES_SOON_TOOLTIP;
826
						} else {
827
							return serverData.daysLeft == 1
828
								? RealmsMainScreen.SERVER_EXPIRES_IN_DAY_TOOLTIP
829
								: Component.translatable("mco.selectServer.expires.days", serverData.daysLeft);
830
						}
831
					}
832
				);
833
			} else if (serverData.state == RealmsServer.State.OPEN) {
834
				this.extractRealmStatus(graphics, x, y, mouseX, mouseY, RealmsMainScreen.OPEN_SPRITE, () -> RealmsMainScreen.SERVER_OPEN_TOOLTIP);
835
			}
836
		}
837
838
		private void extractRealmStatus(
839
			final GuiGraphicsExtractor graphics, final int x, final int y, final int xm, final int ym, final Identifier sprite, final Supplier<Component> tooltip
840
		) {
841
			graphics.blitSprite(RenderPipelines.GUI_TEXTURED, sprite, x, y, 10, 28);
842
			if (RealmsMainScreen.this.realmSelectionList.isMouseOver(xm, ym) && xm >= x && xm <= x + 10 && ym >= y && ym <= y + 28) {
843
				graphics.setTooltipForNextFrame(tooltip.get(), xm, ym);
844
			}
845
		}
846
847
		protected void extractFirstLine(
848
			final GuiGraphicsExtractor graphics, final int rowTop, final int rowLeft, final int rowWidth, final int serverNameColor, final RealmsServer serverData
849
		) {
850
			int textX = this.textX(rowLeft);
851
			int firstLineY = this.firstLineY(rowTop);
852
			Component versionComponent = RealmsMainScreen.getVersionComponent(serverData.activeVersion, serverData.isCompatible());
853
			int versionTextX = this.versionTextX(rowLeft, rowWidth, versionComponent);
854
			this.extractClampedString(graphics, serverData.getName(), textX, firstLineY, versionTextX, serverNameColor);
855
			if (versionComponent != CommonComponents.EMPTY && !serverData.isMinigameActive()) {
856
				graphics.text(RealmsMainScreen.this.font, versionComponent, versionTextX, firstLineY, -8355712);
857
			}
858
		}
859
860
		protected void extractSecondLine(final GuiGraphicsExtractor graphics, final int rowTop, final int rowLeft, final int rowWidth, final RealmsServer serverData) {
861
			int textX = this.textX(rowLeft);
862
			int firstLineY = this.firstLineY(rowTop);
863
			int secondLineY = this.secondLineY(firstLineY);
864
			String minigameName = serverData.getMinigameName();
865
			boolean minigameActive = serverData.isMinigameActive();
866
			if (minigameActive && minigameName != null) {
867
				Component minigameNameComponent = Component.literal(minigameName).withStyle(ChatFormatting.GRAY);
868
				graphics.text(
869
					RealmsMainScreen.this.font, Component.translatable("mco.selectServer.minigameName", minigameNameComponent).withColor(-171), textX, secondLineY, -1
870
				);
871
			} else {
872
				int maxX = this.extractGameMode(serverData, graphics, rowLeft, rowWidth, firstLineY);
873
				this.extractClampedString(graphics, serverData.getDescription(), textX, this.secondLineY(firstLineY), maxX, -8355712);
874
			}
875
		}
876
877
		protected void extractThirdLine(final GuiGraphicsExtractor graphics, final int rowTop, final int rowLeft, final RealmsServer server) {
878
			int textX = this.textX(rowLeft);
879
			int firstLineY = this.firstLineY(rowTop);
880
			int thirdLineY = this.thirdLineY(firstLineY);
881
			if (!RealmsMainScreen.isSelfOwnedServer(server)) {
882
				graphics.text(RealmsMainScreen.this.font, server.owner, textX, this.thirdLineY(firstLineY), -8355712);
883
			} else if (server.expired) {
884
				Component expirationText = server.expiredTrial ? RealmsMainScreen.TRIAL_EXPIRED_TEXT : RealmsMainScreen.SUBSCRIPTION_EXPIRED_TEXT;
885
				graphics.text(RealmsMainScreen.this.font, expirationText, textX, thirdLineY, -2142128);
886
			}
887
		}
888
889
		protected void extractClampedString(
890
			final GuiGraphicsExtractor graphics, final @Nullable String string, final int x, final int y, final int maxX, final int color
891
		) {
892
			if (string != null) {
893
				int availableSpace = maxX - x;
894
				if (RealmsMainScreen.this.font.width(string) > availableSpace) {
895
					String clampedName = RealmsMainScreen.this.font.plainSubstrByWidth(string, availableSpace - RealmsMainScreen.this.font.width("... "));
896
					graphics.text(RealmsMainScreen.this.font, clampedName + "...", x, y, color);
897
				} else {
898
					graphics.text(RealmsMainScreen.this.font, string, x, y, color);
899
				}
900
			}
901
		}
902
903
		protected int versionTextX(final int rowLeft, final int rowWidth, final Component versionComponent) {
904
			return rowLeft + rowWidth - RealmsMainScreen.this.font.width(versionComponent) - 20;
905
		}
906
907
		protected int gameModeTextX(final int rowLeft, final int rowWidth, final Component versionComponent) {
908
			return rowLeft + rowWidth - RealmsMainScreen.this.font.width(versionComponent) - 20;
909
		}
910
911
		protected int extractGameMode(final RealmsServer server, final GuiGraphicsExtractor graphics, final int rowLeft, final int rowWidth, final int firstLineY) {
912
			boolean hardcore = server.isHardcore;
913
			int gameMode = server.gameMode;
914
			int x = rowLeft;
915
			if (GameType.isValidId(gameMode)) {
916
				Component gameModeComponent = RealmsMainScreen.getGameModeComponent(gameMode, hardcore);
917
				x = this.gameModeTextX(rowLeft, rowWidth, gameModeComponent);
918
				graphics.text(RealmsMainScreen.this.font, gameModeComponent, x, this.secondLineY(firstLineY), -8355712);
919
			}
920
921
			if (hardcore) {
922
				x -= 10;
923
				graphics.blitSprite(RenderPipelines.GUI_TEXTURED, RealmsMainScreen.HARDCORE_MODE_SPRITE, x, this.secondLineY(firstLineY), 8, 8);
924
			}
925
926
			return x;
927
		}
928
929
		protected int firstLineY(final int rowTop) {
930
			return rowTop + 1;
931
		}
932
933
		protected int lineHeight() {
934
			return 2 + 9;
935
		}
936
937
		protected int textX(final int rowLeft) {
938
			return rowLeft + 36 + 2;
939
		}
940
941
		protected int secondLineY(final int firstLineY) {
942
			return firstLineY + this.lineHeight();
943
		}
944
945
		protected int thirdLineY(final int firstLineY) {
946
			return firstLineY + this.lineHeight() * 2;
947
		}
948
	}
949
950
	@Environment(EnvType.CLIENT)
951
	private enum LayoutState {
952
		LOADING,
953
		NO_REALMS,
954
		LIST;
955
	}
956
957
	@Environment(EnvType.CLIENT)
958
	private class NotificationMessageEntry extends RealmsMainScreen.Entry {
959
		private static final int SIDE_MARGINS = 40;
960
		public static final int PADDING = 7;
961
		public static final int HEIGHT_WITHOUT_TEXT = 38;
962
		private final Component text;
963
		private final List<AbstractWidget> children = new ArrayList<>();
964
		private final RealmsMainScreen.@Nullable CrossButton dismissButton;
965
		private final MultiLineTextWidget textWidget;
966
		private final GridLayout gridLayout;
967
		private final FrameLayout textFrame;
968
		private final Button button;
969
		private int lastEntryWidth = -1;
970
971
		public NotificationMessageEntry(
972
			final RealmsMainScreen realmsMainScreen, final int messageHeight, final Component text, final RealmsNotification.VisitUrl notification
973
		) {
974
			this.text = text;
975
			this.gridLayout = new GridLayout();
976
			this.gridLayout.addChild(ImageWidget.sprite(20, 20, RealmsMainScreen.INFO_SPRITE), 0, 0, this.gridLayout.newCellSettings().padding(7, 7, 0, 0));
977
			this.gridLayout.addChild(SpacerElement.width(40), 0, 0);
978
			this.textFrame = this.gridLayout.addChild(new FrameLayout(0, messageHeight), 0, 1, this.gridLayout.newCellSettings().paddingTop(7));
979
			this.textWidget = this.textFrame
980
				.addChild(
981
					new MultiLineTextWidget(text, RealmsMainScreen.this.font).setCentered(true),
982
					this.textFrame.newChildLayoutSettings().alignHorizontallyCenter().alignVerticallyTop()
983
				);
984
			this.gridLayout.addChild(SpacerElement.width(40), 0, 2);
985
			if (notification.dismissable()) {
986
				this.dismissButton = this.gridLayout
987
					.addChild(
988
						new RealmsMainScreen.CrossButton(b -> RealmsMainScreen.this.dismissNotification(notification.uuid()), Component.translatable("mco.notification.dismiss")),
989
						0,
990
						2,
991
						this.gridLayout.newCellSettings().alignHorizontallyRight().padding(0, 7, 7, 0)
992
					);
993
			} else {
994
				this.dismissButton = null;
995
			}
996
997
			this.button = this.gridLayout
998
				.addChild(notification.buildOpenLinkButton(realmsMainScreen), 1, 1, this.gridLayout.newCellSettings().alignHorizontallyCenter().padding(4));
999
			RealmsMainScreen.NotificationMessageEntry var6 = this;
1000
			this.button.setOverrideRenderHighlightedSprite(() -> var6.isFocused());
1001
			this.gridLayout.visitWidgets(this.children::add);
1002
		}
1003
1004
		@Override
1005
		public boolean keyPressed(final KeyEvent event) {
1006
			if (this.button.keyPressed(event)) {
1007
				return true;
1008
			} else {
1009
				return this.dismissButton != null && this.dismissButton.keyPressed(event) ? true : super.keyPressed(event);
1010
			}
1011
		}
1012
1013
		private void updateEntryWidth() {
1014
			int entryWidth = this.getWidth();
1015
			if (this.lastEntryWidth != entryWidth) {
1016
				this.refreshLayout(entryWidth);
1017
				this.lastEntryWidth = entryWidth;
1018
			}
1019
		}
1020
1021
		private void refreshLayout(final int entryWidth) {
1022
			int width = textWidth(entryWidth);
1023
			this.textFrame.setMinWidth(width);
1024
			this.textWidget.setMaxWidth(width);
1025
			this.gridLayout.arrangeElements();
1026
		}
1027
1028
		public static int textWidth(final int rowWidth) {
1029
			return rowWidth - 80;
1030
		}
1031
1032
		@Override
1033
		public void extractContent(final GuiGraphicsExtractor graphics, final int mouseX, final int mouseY, final boolean hovered, final float a) {
1034
			this.gridLayout.setPosition(this.getContentX(), this.getContentY());
1035
			this.updateEntryWidth();
1036
			this.children.forEach(child -> child.extractRenderState(graphics, mouseX, mouseY, a));
1037
		}
1038
1039
		@Override
1040
		public boolean mouseClicked(final MouseButtonEvent event, final boolean doubleClick) {
1041
			if (this.dismissButton != null && this.dismissButton.mouseClicked(event, doubleClick)) {
1042
				return true;
1043
			} else {
1044
				return this.button.mouseClicked(event, doubleClick) ? true : super.mouseClicked(event, doubleClick);
1045
			}
1046
		}
1047
1048
		public Component getText() {
1049
			return this.text;
1050
		}
1051
1052
		@Override
1053
		public Component getNarration() {
1054
			return this.getText();
1055
		}
1056
	}
1057
1058
	@Environment(EnvType.CLIENT)
1059
	private class ParentEntry extends RealmsMainScreen.Entry {
1060
		private final RealmsServer server;
1061
		private final WidgetTooltipHolder tooltip = new WidgetTooltipHolder();
1062
1063
		public ParentEntry(final RealmsServer server) {
1064
			this.server = server;
1065
			if (!server.expired) {
1066
				this.tooltip.set(Tooltip.create(Component.translatable("mco.snapshot.parent.tooltip")));
1067
			}
1068
		}
1069
1070
		@Override
1071
		public void extractContent(final GuiGraphicsExtractor graphics, final int mouseX, final int mouseY, final boolean hovered, final float a) {
1072
			this.extractStatusLights(this.server, graphics, this.getContentRight(), this.getContentY(), mouseX, mouseY);
1073
			RealmsUtil.extractPlayerFace(graphics, this.getContentX(), this.getContentY(), 32, this.server.ownerUUID);
1074
			this.extractFirstLine(graphics, this.getContentY(), this.getContentX(), this.getContentWidth(), -8355712, this.server);
1075
			this.extractSecondLine(graphics, this.getContentY(), this.getContentX(), this.getContentWidth(), this.server);
1076
			this.extractThirdLine(graphics, this.getContentY(), this.getContentX(), this.server);
1077
			this.tooltip
1078
				.refreshTooltipForNextRenderPass(
1079
					graphics,
1080
					mouseX,
1081
					mouseY,
1082
					hovered,
1083
					this.isFocused(),
1084
					new ScreenRectangle(this.getContentX(), this.getContentY(), this.getContentWidth(), this.getContentHeight())
1085
				);
1086
		}
1087
1088
		@Override
1089
		public Component getNarration() {
1090
			return Component.literal(Objects.requireNonNullElse(this.server.name, "unknown server"));
1091
		}
1092
	}
1093
1094
	@Environment(EnvType.CLIENT)
1095
	private class RealmSelectionList extends ObjectSelectionList<RealmsMainScreen.Entry> {
1096
		public RealmSelectionList() {
1097
			super(Minecraft.getInstance(), RealmsMainScreen.this.width, RealmsMainScreen.this.height, 0, 36);
1098
		}
1099
1100
		public void setSelected(final RealmsMainScreen.@Nullable Entry selected) {
1101
			super.setSelected(selected);
1102
			RealmsMainScreen.this.updateButtonStates();
1103
		}
1104
1105
		@Override
1106
		public int getRowWidth() {
1107
			return 300;
1108
		}
1109
1110
		private void refreshEntries(final RealmsMainScreen realmsMainScreen) {
1111
			RealmsMainScreen.Entry previouslySelected = this.getSelected();
1112
			this.clearEntries();
1113
1114
			for (RealmsNotification notification : RealmsMainScreen.this.notifications) {
1115
				if (notification instanceof RealmsNotification.VisitUrl visitUrl) {
1116
					this.addEntriesForNotification(visitUrl, realmsMainScreen, previouslySelected);
1117
					RealmsMainScreen.this.markNotificationsAsSeen(List.of(notification));
1118
					break;
1119
				}
1120
			}
1121
1122
			this.refreshServerEntries(previouslySelected);
1123
		}
1124
1125
		private void addEntriesForNotification(
1126
			final RealmsNotification.VisitUrl visitUrl, final RealmsMainScreen realmsMainScreen, final RealmsMainScreen.@Nullable Entry previouslySelected
1127
		) {
1128
			Component message = visitUrl.getMessage();
1129
			int messageHeight = RealmsMainScreen.this.font.wordWrapHeight(message, RealmsMainScreen.NotificationMessageEntry.textWidth(this.getRowWidth()));
1130
			RealmsMainScreen.NotificationMessageEntry entry = RealmsMainScreen.this.new NotificationMessageEntry(realmsMainScreen, messageHeight, message, visitUrl);
1131
			this.addEntry(entry, 38 + messageHeight);
1132
			if (previouslySelected instanceof RealmsMainScreen.NotificationMessageEntry notificationMessageEntry && notificationMessageEntry.getText().equals(message)) {
1133
				this.setSelected(entry);
1134
			}
1135
		}
1136
1137
		private void refreshServerEntries(final RealmsMainScreen.@Nullable Entry previouslySelected) {
1138
			for (RealmsServer eligibleForSnapshotServer : RealmsMainScreen.this.availableSnapshotServers) {
1139
				this.addEntry(RealmsMainScreen.this.new AvailableSnapshotEntry(eligibleForSnapshotServer));
1140
			}
1141
1142
			for (RealmsServer server : RealmsMainScreen.this.serverList) {
1143
				RealmsMainScreen.Entry entry;
1144
				if (RealmsMainScreen.isSnapshot() && !server.isSnapshotRealm()) {
1145
					if (server.state == RealmsServer.State.UNINITIALIZED) {
1146
						continue;
1147
					}
1148
1149
					entry = RealmsMainScreen.this.new ParentEntry(server);
1150
				} else {
1151
					entry = RealmsMainScreen.this.new ServerEntry(server);
1152
				}
1153
1154
				this.addEntry(entry);
1155
				if (previouslySelected instanceof RealmsMainScreen.ServerEntry serverEntry && serverEntry.serverData.id == server.id) {
1156
					this.setSelected(entry);
1157
				}
1158
			}
1159
		}
1160
	}
1161
1162
	@Environment(EnvType.CLIENT)
1163
	private interface RealmsCall<T> {
1164
		T request(RealmsClient realmsClient) throws RealmsServiceException;
1165
	}
1166
1167
	@Environment(EnvType.CLIENT)
1168
	private class ServerEntry extends RealmsMainScreen.Entry {
1169
		private static final Component ONLINE_PLAYERS_TOOLTIP_HEADER = Component.translatable("mco.onlinePlayers");
1170
		private static final int PLAYERS_ONLINE_SPRITE_SIZE = 9;
1171
		private static final int PLAYERS_ONLINE_SPRITE_SEPARATION = 3;
1172
		private static final int SKIN_HEAD_LARGE_WIDTH = 36;
1173
		private final RealmsServer serverData;
1174
		private final WidgetTooltipHolder tooltip = new WidgetTooltipHolder();
1175
1176
		public ServerEntry(final RealmsServer serverData) {
1177
			this.serverData = serverData;
1178
			boolean selfOwnedServer = RealmsMainScreen.isSelfOwnedServer(serverData);
1179
			if (RealmsMainScreen.isSnapshot() && selfOwnedServer && serverData.isSnapshotRealm()) {
1180
				this.tooltip.set(Tooltip.create(Component.translatable("mco.snapshot.paired", serverData.parentWorldName)));
1181
			} else if (!selfOwnedServer && serverData.needsDowngrade()) {
1182
				this.tooltip.set(Tooltip.create(Component.translatable("mco.snapshot.friendsRealm.downgrade", serverData.activeVersion)));
1183
			}
1184
		}
1185
1186
		@Override
1187
		public void extractContent(final GuiGraphicsExtractor graphics, final int mouseX, final int mouseY, final boolean hovered, final float a) {
1188
			if (this.serverData.state == RealmsServer.State.UNINITIALIZED) {
1189
				graphics.blitSprite(RenderPipelines.GUI_TEXTURED, RealmsMainScreen.NEW_REALM_SPRITE, this.getContentX() - 5, this.getContentYMiddle() - 10, 40, 20);
1190
				int textYPos = this.getContentYMiddle() - 9 / 2;
1191
				graphics.text(RealmsMainScreen.this.font, RealmsMainScreen.SERVER_UNITIALIZED_TEXT, this.getContentX() + 40 - 2, textYPos, -8388737);
1192
			} else {
1193
				RealmsUtil.extractPlayerFace(graphics, this.getContentX(), this.getContentY(), 32, this.serverData.ownerUUID);
1194
				this.extractFirstLine(graphics, this.getContentY(), this.getContentX(), this.getContentWidth(), -1, this.serverData);
1195
				this.extractSecondLine(graphics, this.getContentY(), this.getContentX(), this.getContentWidth(), this.serverData);
1196
				this.extractThirdLine(graphics, this.getContentY(), this.getContentX(), this.serverData);
1197
				this.extractStatusLights(this.serverData, graphics, this.getContentRight(), this.getContentY(), mouseX, mouseY);
1198
				boolean hasTooltip = this.extractOnlinePlayers(
1199
					graphics, this.getContentY(), this.getContentX(), this.getContentWidth(), this.getContentHeight(), mouseX, mouseY, a
1200
				);
1201
				if (!hasTooltip) {
1202
					this.tooltip
1203
						.refreshTooltipForNextRenderPass(
1204
							graphics,
1205
							mouseX,
1206
							mouseY,
1207
							hovered,
1208
							this.isFocused(),
1209
							new ScreenRectangle(this.getContentX(), this.getContentY(), this.getContentWidth(), this.getContentHeight())
1210
						);
1211
				}
1212
			}
1213
		}
1214
1215
		private boolean extractOnlinePlayers(
1216
			final GuiGraphicsExtractor graphics,
1217
			final int rowTop,
1218
			final int rowLeft,
1219
			final int rowWidth,
1220
			final int rowHeight,
1221
			final int mouseX,
1222
			final int mouseY,
1223
			final float a
1224
		) {
1225
			List<ResolvableProfile> profileResults = RealmsMainScreen.this.onlinePlayersPerRealm.getProfileResultsFor(this.serverData.id);
1226
			int playerCount = profileResults.size();
1227
			if (playerCount > 0) {
1228
				int playersOnlineXEnd = rowLeft + rowWidth - 21;
1229
				int playersOnlineY = rowTop + rowHeight - 9 - 2;
1230
				int playerOnlineWidth = 9 * playerCount + 3 * (playerCount - 1);
1231
				int playersOnlineXStart = playersOnlineXEnd - playerOnlineWidth;
1232
				List<PlayerSkinRenderCache.RenderInfo> tooltipEntries;
1233
				if (mouseX >= playersOnlineXStart && mouseX <= playersOnlineXEnd && mouseY >= playersOnlineY && mouseY <= playersOnlineY + 9) {
1234
					tooltipEntries = new ArrayList<>(playerCount);
1235
				} else {
1236
					tooltipEntries = null;
1237
				}
1238
1239
				PlayerSkinRenderCache skinCache = RealmsMainScreen.this.minecraft.playerSkinRenderCache();
1240
1241
				for (int i = 0; i < profileResults.size(); i++) {
1242
					ResolvableProfile profile = profileResults.get(i);
1243
					PlayerSkinRenderCache.RenderInfo profileRenderInfo = skinCache.getOrDefault(profile);
1244
					int xPos = playersOnlineXStart + 12 * i;
1245
					PlayerFaceExtractor.extractRenderState(graphics, profileRenderInfo.playerSkin(), xPos, playersOnlineY, 9);
1246
					if (tooltipEntries != null) {
1247
						tooltipEntries.add(profileRenderInfo);
1248
					}
1249
				}
1250
1251
				if (tooltipEntries != null) {
1252
					graphics.setTooltipForNextFrame(
1253
						RealmsMainScreen.this.font,
1254
						List.of(ONLINE_PLAYERS_TOOLTIP_HEADER),
1255
						Optional.of(new ClientActivePlayersTooltip.ActivePlayersTooltip(tooltipEntries)),
1256
						mouseX,
1257
						mouseY
1258
					);
1259
					return true;
1260
				}
1261
			}
1262
1263
			return false;
1264
		}
1265
1266
		private void playRealm() {
1267
			RealmsMainScreen.this.minecraft.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F));
1268
			RealmsMainScreen.play(this.serverData, RealmsMainScreen.this);
1269
		}
1270
1271
		private void createUnitializedRealm() {
1272
			RealmsMainScreen.this.minecraft.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F));
1273
			RealmsCreateRealmScreen createScreen = new RealmsCreateRealmScreen(RealmsMainScreen.this, this.serverData, this.serverData.isSnapshotRealm());
1274
			RealmsMainScreen.this.minecraft.gui.setScreen(createScreen);
1275
		}
1276
1277
		@Override
1278
		public boolean mouseClicked(final MouseButtonEvent event, final boolean doubleClick) {
1279
			if (this.serverData.state == RealmsServer.State.UNINITIALIZED) {
1280
				this.createUnitializedRealm();
1281
			} else if (this.serverData.shouldPlayButtonBeActive() && doubleClick && this.isFocused()) {
1282
				this.playRealm();
1283
			}
1284
1285
			return true;
1286
		}
1287
1288
		@Override
1289
		public boolean keyPressed(final KeyEvent event) {
1290
			if (event.isSelection()) {
1291
				if (this.serverData.state == RealmsServer.State.UNINITIALIZED) {
1292
					this.createUnitializedRealm();
1293
					return true;
1294
				}
1295
1296
				if (this.serverData.shouldPlayButtonBeActive()) {
1297
					this.playRealm();
1298
					return true;
1299
				}
1300
			}
1301
1302
			return super.keyPressed(event);
1303
		}
1304
1305
		@Override
1306
		public Component getNarration() {
1307
			return this.serverData.state == RealmsServer.State.UNINITIALIZED
1308
				? RealmsMainScreen.UNITIALIZED_WORLD_NARRATION
1309
				: Component.translatable("narrator.select", Objects.requireNonNullElse(this.serverData.name, "unknown server"));
1310
		}
1311
1312
		public RealmsServer getServer() {
1313
			return this.serverData;
1314
		}
1315
	}
1316
}
1317

Decompiled Minecraft 26.3 source of RealmsMainScreen (com/mojang/realmsclient/RealmsMainScreen.java) with Mojang official mappings, stored verbatim on the site.