RealmsDownloadLatestWorldScreen .java

com.mojang.realmsclient.gui.screens.RealmsDownloadLatestWorldScreen (class): members: previousWrittenBytes, bytesPersSecond, DownloadStatus, DOWNLOAD_LOCK.

com.mojang.realmsclient.gui.screensclass275 linescommonextends RealmsScreen9.4 KB

API Surface (4)

void init()
void tick()
void onClose()
void extractRenderState(final GuiGraphicsExtractor graphics, final int xm, final int ym, final float a)

Fields & Constants (28)

LOGGER
DOWNLOAD_LOCK
BAR_WIDTH
BAR_TOP
BAR_BOTTOM
BAR_BORDER
DOTS
lastScreen
worldDownload
downloadTitle
narrationRateLimiter
cancelButton
worldName
downloadStatus
errorMessage
status
progress
cancelled
showDots
finished
extracting
previousWrittenBytes
previousTimeSnapshot
bytesPersSecond
animTick
dotIndex
checked
callback

String literals (15)

"mco.download.preparing"
"mco.download.title"
"mco.download.confirmation.oversized"
"mco.download.percent"
"mco.download.speed.narration"
"mco.download.speed"
"mco.download.failed"
"mco.download.downloading"
"mco.download.extracting"
"Failed to check Realms backup download status"
"mco.download.done"
"Could not acquire upload lock"
"Exception while downloading world"
"Realms world download monitor"
"mco.download.cancelled"

Full Source

RealmsDownloadLatestWorldScreen.java275 lines · Minecraft 26.3 · verbatim
1
package com.mojang.realmsclient.gui.screens;
2
3
import com.google.common.collect.Lists;
4
import com.google.common.util.concurrent.RateLimiter;
5
import com.mojang.logging.LogUtils;
6
import com.mojang.realmsclient.Unit;
7
import com.mojang.realmsclient.client.FileDownload;
8
import com.mojang.realmsclient.dto.WorldDownload;
9
import it.unimi.dsi.fastutil.booleans.BooleanConsumer;
10
import java.util.List;
11
import java.util.Locale;
12
import java.util.concurrent.TimeUnit;
13
import java.util.concurrent.locks.ReentrantLock;
14
import net.fabricmc.api.EnvType;
15
import net.fabricmc.api.Environment;
16
import net.minecraft.client.GameNarrator;
17
import net.minecraft.client.gui.GuiGraphicsExtractor;
18
import net.minecraft.client.gui.components.Button;
19
import net.minecraft.client.gui.screens.Screen;
20
import net.minecraft.network.chat.CommonComponents;
21
import net.minecraft.network.chat.Component;
22
import net.minecraft.realms.RealmsScreen;
23
import net.minecraft.util.Util;
24
import org.jspecify.annotations.Nullable;
25
import org.slf4j.Logger;
26
27
@Environment(EnvType.CLIENT)
28
public class RealmsDownloadLatestWorldScreen extends RealmsScreen {
29
	private static final Logger LOGGER = LogUtils.getLogger();
30
	private static final ReentrantLock DOWNLOAD_LOCK = new ReentrantLock();
31
	private static final int BAR_WIDTH = 200;
32
	private static final int BAR_TOP = 80;
33
	private static final int BAR_BOTTOM = 95;
34
	private static final int BAR_BORDER = 1;
35
	private final Screen lastScreen;
36
	private final WorldDownload worldDownload;
37
	private final Component downloadTitle;
38
	private final RateLimiter narrationRateLimiter;
39
	private Button cancelButton;
40
	private final String worldName;
41
	private final RealmsDownloadLatestWorldScreen.DownloadStatus downloadStatus;
42
	private volatile @Nullable Component errorMessage;
43
	private volatile Component status = Component.translatable("mco.download.preparing");
44
	private volatile @Nullable String progress;
45
	private volatile boolean cancelled;
46
	private volatile boolean showDots = true;
47
	private volatile boolean finished;
48
	private volatile boolean extracting;
49
	private @Nullable Long previousWrittenBytes;
50
	private @Nullable Long previousTimeSnapshot;
51
	private long bytesPersSecond;
52
	private int animTick;
53
	private static final String[] DOTS = new String[]{"", ".", ". .", ". . ."};
54
	private int dotIndex;
55
	private boolean checked;
56
	private final BooleanConsumer callback;
57
58
	public RealmsDownloadLatestWorldScreen(final Screen lastScreen, final WorldDownload worldDownload, final String worldName, final BooleanConsumer callback) {
59
		super(GameNarrator.NO_TITLE);
60
		this.callback = callback;
61
		this.lastScreen = lastScreen;
62
		this.worldName = worldName;
63
		this.worldDownload = worldDownload;
64
		this.downloadStatus = new RealmsDownloadLatestWorldScreen.DownloadStatus();
65
		this.downloadTitle = Component.translatable("mco.download.title");
66
		this.narrationRateLimiter = RateLimiter.create(0.1F);
67
	}
68
69
	@Override
70
	public void init() {
71
		this.cancelButton = this.addRenderableWidget(
72
			Button.builder(CommonComponents.GUI_CANCEL, button -> this.onClose()).bounds((this.width - 200) / 2, this.height - 42, 200, 20).build()
73
		);
74
		this.checkDownloadSize();
75
	}
76
77
	private void checkDownloadSize() {
78
		if (!this.finished && !this.checked) {
79
			this.checked = true;
80
			if (this.getContentLength(this.worldDownload.downloadLink()) >= 5368709120L) {
81
				Component popupMessage = Component.translatable("mco.download.confirmation.oversized", Unit.humanReadable(5368709120L));
82
				this.minecraft.gui.setScreen(RealmsPopups.warningAcknowledgePopupScreen(this, popupMessage, var1x -> {
83
					this.minecraft.gui.setScreen(this);
84
					this.downloadSave();
85
				}));
86
			} else {
87
				this.downloadSave();
88
			}
89
		}
90
	}
91
92
	private long getContentLength(final String downloadLink) {
93
		return FileDownload.contentLength(downloadLink).orElse(0L);
94
	}
95
96
	@Override
97
	public void tick() {
98
		super.tick();
99
		this.animTick++;
100
		if (this.status != null && this.narrationRateLimiter.tryAcquire(1)) {
101
			Component message = this.createProgressNarrationMessage();
102
			this.minecraft.getNarrator().saySystemNow(message);
103
		}
104
	}
105
106
	private Component createProgressNarrationMessage() {
107
		List<Component> elements = Lists.newArrayList();
108
		elements.add(this.downloadTitle);
109
		elements.add(this.status);
110
		if (this.progress != null) {
111
			elements.add(Component.translatable("mco.download.percent", this.progress));
112
			elements.add(Component.translatable("mco.download.speed.narration", Unit.humanReadable(this.bytesPersSecond)));
113
		}
114
115
		if (this.errorMessage != null) {
116
			elements.add(this.errorMessage);
117
		}
118
119
		return CommonComponents.joinLines(elements);
120
	}
121
122
	@Override
123
	public void onClose() {
124
		this.cancelled = true;
125
		if (this.finished && this.callback != null && this.errorMessage == null) {
126
			this.callback.accept(true);
127
		}
128
129
		this.minecraft.gui.setScreen(this.lastScreen);
130
	}
131
132
	@Override
133
	public void extractRenderState(final GuiGraphicsExtractor graphics, final int xm, final int ym, final float a) {
134
		super.extractRenderState(graphics, xm, ym, a);
135
		graphics.centeredText(this.font, this.downloadTitle, this.width / 2, 20, -1);
136
		graphics.centeredText(this.font, this.status, this.width / 2, 50, -1);
137
		if (this.showDots) {
138
			this.extractDots(graphics);
139
		}
140
141
		if (this.downloadStatus.bytesWritten != 0L && !this.cancelled) {
142
			this.extractProgressBar(graphics);
143
			this.extractDownloadSpeed(graphics);
144
		}
145
146
		if (this.errorMessage != null) {
147
			graphics.centeredText(this.font, this.errorMessage, this.width / 2, 110, -65536);
148
		}
149
	}
150
151
	private void extractDots(final GuiGraphicsExtractor graphics) {
152
		int statusWidth = this.font.width(this.status);
153
		if (this.animTick != 0 && this.animTick % 10 == 0) {
154
			this.dotIndex++;
155
		}
156
157
		graphics.text(this.font, DOTS[this.dotIndex % DOTS.length], this.width / 2 + statusWidth / 2 + 5, 50, -1);
158
	}
159
160
	private void extractProgressBar(final GuiGraphicsExtractor graphics) {
161
		double percentage = Math.min((double)this.downloadStatus.bytesWritten / this.downloadStatus.totalBytes, 1.0);
162
		this.progress = String.format(Locale.ROOT, "%.1f", percentage * 100.0);
163
		int left = (this.width - 200) / 2;
164
		int right = left + (int)Math.round(200.0 * percentage);
165
		graphics.fill(left - 1, 79, right + 1, 96, -1);
166
		graphics.fill(left, 80, right, 95, -8355712);
167
		graphics.centeredText(this.font, Component.translatable("mco.download.percent", this.progress), this.width / 2, 84, -1);
168
	}
169
170
	private void extractDownloadSpeed(final GuiGraphicsExtractor graphics) {
171
		if (this.animTick % 20 == 0) {
172
			if (this.previousWrittenBytes != null) {
173
				long timeElapsed = Util.getMillis() - this.previousTimeSnapshot;
174
				if (timeElapsed == 0L) {
175
					timeElapsed = 1L;
176
				}
177
178
				this.bytesPersSecond = 1000L * (this.downloadStatus.bytesWritten - this.previousWrittenBytes) / timeElapsed;
179
				this.extractDownloadSpeed0(graphics, this.bytesPersSecond);
180
			}
181
182
			this.previousWrittenBytes = this.downloadStatus.bytesWritten;
183
			this.previousTimeSnapshot = Util.getMillis();
184
		} else {
185
			this.extractDownloadSpeed0(graphics, this.bytesPersSecond);
186
		}
187
	}
188
189
	private void extractDownloadSpeed0(final GuiGraphicsExtractor graphics, final long bytesPerSecond) {
190
		if (bytesPerSecond > 0L) {
191
			int progressLength = this.font.width(this.progress);
192
			graphics.text(this.font, Component.translatable("mco.download.speed", Unit.humanReadable(bytesPerSecond)), this.width / 2 + progressLength / 2 + 15, 84, -1);
193
		}
194
	}
195
196
	private void downloadSave() {
197
		new Thread(() -> {
198
			try {
199
				try {
200
					if (!DOWNLOAD_LOCK.tryLock(1L, TimeUnit.SECONDS)) {
201
						this.status = Component.translatable("mco.download.failed");
202
						return;
203
					}
204
205
					if (this.cancelled) {
206
						this.downloadCancelled();
207
						return;
208
					}
209
210
					this.status = Component.translatable("mco.download.downloading", this.worldName);
211
					FileDownload fileDownload = new FileDownload();
212
					fileDownload.download(this.worldDownload, this.worldName, this.downloadStatus, this.minecraft.getLevelSource());
213
214
					while (!fileDownload.isFinished()) {
215
						if (fileDownload.isError()) {
216
							fileDownload.cancel();
217
							this.errorMessage = Component.translatable("mco.download.failed");
218
							this.cancelButton.setMessage(CommonComponents.GUI_DONE);
219
							return;
220
						}
221
222
						if (fileDownload.isExtracting()) {
223
							if (!this.extracting) {
224
								this.status = Component.translatable("mco.download.extracting");
225
							}
226
227
							this.extracting = true;
228
						}
229
230
						if (this.cancelled) {
231
							fileDownload.cancel();
232
							this.downloadCancelled();
233
							return;
234
						}
235
236
						try {
237
							Thread.sleep(500L);
238
						} catch (InterruptedException ignored) {
239
							LOGGER.error("Failed to check Realms backup download status");
240
						}
241
					}
242
243
					this.finished = true;
244
					this.status = Component.translatable("mco.download.done");
245
					this.cancelButton.setMessage(CommonComponents.GUI_DONE);
246
					return;
247
				} catch (InterruptedException ignored) {
248
					LOGGER.error("Could not acquire upload lock");
249
				} catch (Exception e) {
250
					this.errorMessage = Component.translatable("mco.download.failed");
251
					LOGGER.info("Exception while downloading world", e);
252
				}
253
			} finally {
254
				if (!DOWNLOAD_LOCK.isHeldByCurrentThread()) {
255
					return;
256
				}
257
258
				DOWNLOAD_LOCK.unlock();
259
				this.showDots = false;
260
				this.finished = true;
261
			}
262
		}, "Realms world download monitor").start();
263
	}
264
265
	private void downloadCancelled() {
266
		this.status = Component.translatable("mco.download.cancelled");
267
	}
268
269
	@Environment(EnvType.CLIENT)
270
	public static class DownloadStatus {
271
		public volatile long bytesWritten;
272
		public volatile long totalBytes;
273
	}
274
}
275

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