CommandSuggestions .java

net.minecraft.client.gui.components.CommandSuggestions (class, 682 lines): members: COMMANDS_NOT_ALLOWED_TEXT, MESSAGES_NOT_ALLOWED_TEXT, fillColor.

net.minecraft.client.gui.componentsclass682 linesclient25.4 KB

API Surface (24)

void setAllowSuggestions(final boolean allowSuggestions)
void setAllowHiding(final boolean allowHiding)
void setRestrictions(final boolean messagesAllowed, final boolean commandsAllowed)
boolean keyPressed(final KeyEvent event)
boolean mouseScrolled(final double scroll)
boolean mouseClicked(final MouseButtonEvent event)
void showSuggestions(final boolean immediateNarration)
boolean isVisible()
Component getUsageNarration()
void hide()
void updateCommandInfo()
<T> void accept(final CommandContextBuilder<ClientSuggestionProvider> context, final ArgumentCommandNode<ClientSuggestionProvider, T> argument, final @Nullable ParsedArgument<ClientSuggestionProvider, T> value)
void extractRenderState(final GuiGraphicsExtractor graphics, final int mouseX, final int mouseY)
boolean extractSuggestions(final GuiGraphicsExtractor graphics, final int mouseX, final int mouseY)
void extractUsage(final GuiGraphicsExtractor graphics)
Component getNarrationMessage()
boolean hasAllowedInput()
void extractRenderState(final GuiGraphicsExtractor graphics, final int mouseX, final int mouseY)
boolean mouseClicked(final int x, final int y)
boolean mouseScrolled(final double scroll)
boolean keyPressed(final KeyEvent event)
void cycle(final int direction)
void select(final int index)
void useSuggestion()

Fields & Constants (32)

WHITESPACE_PATTERN
UNPARSED_STYLE
LITERAL_STYLE
USAGE_FORMAT
ARGUMENT_STYLES
LINE_HEIGHT
USAGE_OFFSET_FROM_BOTTOM
COMMANDS_NOT_ALLOWED_TEXT
MESSAGES_NOT_ALLOWED_TEXT
minecraft
screen
input
font
commandsOnly
onlyShowIfCursorPastError
lineStartOffset
suggestionLineLimit
anchorToBottom
fillColor
commandUsage
commandUsagePosition
commandUsageWidth
currentParse
pendingSuggestions
suggestions
currentParseIsCommand
currentParseIsMessage
allowSuggestions
keepSuggestions
allowHiding
messagesAllowed
commandsAllowed

String literals (10)

"chat_screen.commands_not_allowed"
"chat_screen.messages_not_allowed"
"narration.suggestion.usage.cycle.hidable"
"narration.suggestion.usage.cycle.fixed"
"narration.suggestion.usage.fill.hidable"
"narration.suggestion.usage.fill.fixed"
"minecraft:"
"command.context.parse_error"
"narration.suggestion.tooltip"
"narration.suggestion"

Full Source

CommandSuggestions.java682 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.client.gui.components;
2
3
import com.google.common.base.Strings;
4
import com.google.common.collect.ImmutableList;
5
import com.google.common.collect.Lists;
6
import com.mojang.blaze3d.platform.cursor.CursorTypes;
7
import com.mojang.brigadier.CommandDispatcher;
8
import com.mojang.brigadier.ParseResults;
9
import com.mojang.brigadier.StringReader;
10
import com.mojang.brigadier.context.CommandContextBuilder;
11
import com.mojang.brigadier.context.ParsedArgument;
12
import com.mojang.brigadier.context.SuggestionContext;
13
import com.mojang.brigadier.exceptions.CommandSyntaxException;
14
import com.mojang.brigadier.suggestion.Suggestion;
15
import com.mojang.brigadier.suggestion.Suggestions;
16
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
17
import com.mojang.brigadier.tree.ArgumentCommandNode;
18
import com.mojang.brigadier.tree.CommandNode;
19
import com.mojang.brigadier.tree.LiteralCommandNode;
20
import java.util.ArrayList;
21
import java.util.Collection;
22
import java.util.List;
23
import java.util.Locale;
24
import java.util.Map;
25
import java.util.Map.Entry;
26
import java.util.concurrent.CompletableFuture;
27
import java.util.regex.Matcher;
28
import java.util.regex.Pattern;
29
import java.util.stream.Stream;
30
import net.fabricmc.api.EnvType;
31
import net.fabricmc.api.Environment;
32
import net.minecraft.ChatFormatting;
33
import net.minecraft.client.Minecraft;
34
import net.minecraft.client.gui.Font;
35
import net.minecraft.client.gui.GuiGraphicsExtractor;
36
import net.minecraft.client.gui.screens.Screen;
37
import net.minecraft.client.input.KeyEvent;
38
import net.minecraft.client.input.MouseButtonEvent;
39
import net.minecraft.client.multiplayer.ClientSuggestionProvider;
40
import net.minecraft.client.renderer.Rect2i;
41
import net.minecraft.commands.ArgumentVisitor;
42
import net.minecraft.commands.Commands;
43
import net.minecraft.commands.SharedSuggestionProvider;
44
import net.minecraft.commands.ArgumentVisitor.Output;
45
import net.minecraft.commands.arguments.MessageArgument.Message;
46
import net.minecraft.network.chat.CommonComponents;
47
import net.minecraft.network.chat.Component;
48
import net.minecraft.network.chat.ComponentUtils;
49
import net.minecraft.network.chat.Style;
50
import net.minecraft.util.FormattedCharSequence;
51
import net.minecraft.util.Mth;
52
import net.minecraft.world.phys.Vec2;
53
import org.jspecify.annotations.Nullable;
54
55
@Environment(EnvType.CLIENT)
56
public class CommandSuggestions {
57
	private static final Pattern WHITESPACE_PATTERN = Pattern.compile("(\\s+)");
58
	private static final Style UNPARSED_STYLE = Style.EMPTY.withColor(ChatFormatting.RED);
59
	private static final Style LITERAL_STYLE = Style.EMPTY.withColor(ChatFormatting.GRAY);
60
	public static final Style USAGE_FORMAT = Style.EMPTY.withColor(ChatFormatting.GRAY);
61
	private static final List<Style> ARGUMENT_STYLES = Stream.of(
62
			ChatFormatting.AQUA, ChatFormatting.YELLOW, ChatFormatting.GREEN, ChatFormatting.LIGHT_PURPLE, ChatFormatting.GOLD
63
		)
64
		.map(Style.EMPTY::withColor)
65
		.collect(ImmutableList.toImmutableList());
66
	public static final int LINE_HEIGHT = 12;
67
	public static final int USAGE_OFFSET_FROM_BOTTOM = 27;
68
	private static final Component COMMANDS_NOT_ALLOWED_TEXT = Component.translatable("chat_screen.commands_not_allowed").withStyle(ChatFormatting.RED);
69
	private static final Component MESSAGES_NOT_ALLOWED_TEXT = Component.translatable("chat_screen.messages_not_allowed").withStyle(ChatFormatting.RED);
70
	private final Minecraft minecraft;
71
	private final Screen screen;
72
	private final EditBox input;
73
	private final Font font;
74
	private final boolean commandsOnly;
75
	private final boolean onlyShowIfCursorPastError;
76
	private final int lineStartOffset;
77
	private final int suggestionLineLimit;
78
	private final boolean anchorToBottom;
79
	private final int fillColor;
80
	private final List<FormattedCharSequence> commandUsage = Lists.newArrayList();
81
	private int commandUsagePosition;
82
	private int commandUsageWidth;
83
	private @Nullable ParseResults<ClientSuggestionProvider> currentParse;
84
	private @Nullable CompletableFuture<Suggestions> pendingSuggestions;
85
	private CommandSuggestions.@Nullable SuggestionsList suggestions;
86
	private boolean currentParseIsCommand;
87
	private boolean currentParseIsMessage;
88
	private boolean allowSuggestions;
89
	private boolean keepSuggestions;
90
	private boolean allowHiding = true;
91
	private boolean messagesAllowed = true;
92
	private boolean commandsAllowed = true;
93
94
	public CommandSuggestions(
95
		final Minecraft minecraft,
96
		final Screen screen,
97
		final EditBox input,
98
		final Font font,
99
		final boolean commandsOnly,
100
		final boolean onlyShowIfCursorPastError,
101
		final int lineStartOffset,
102
		final int suggestionLineLimit,
103
		final boolean anchorToBottom,
104
		final int fillColor
105
	) {
106
		this.minecraft = minecraft;
107
		this.screen = screen;
108
		this.input = input;
109
		this.font = font;
110
		this.commandsOnly = commandsOnly;
111
		this.onlyShowIfCursorPastError = onlyShowIfCursorPastError;
112
		this.lineStartOffset = lineStartOffset;
113
		this.suggestionLineLimit = suggestionLineLimit;
114
		this.anchorToBottom = anchorToBottom;
115
		this.fillColor = fillColor;
116
		input.addFormatter(this::formatChat);
117
	}
118
119
	public void setAllowSuggestions(final boolean allowSuggestions) {
120
		this.allowSuggestions = allowSuggestions;
121
		if (!allowSuggestions) {
122
			this.suggestions = null;
123
		}
124
	}
125
126
	public void setAllowHiding(final boolean allowHiding) {
127
		this.allowHiding = allowHiding;
128
	}
129
130
	public void setRestrictions(final boolean messagesAllowed, final boolean commandsAllowed) {
131
		this.messagesAllowed = messagesAllowed;
132
		this.commandsAllowed = commandsAllowed;
133
	}
134
135
	public boolean keyPressed(final KeyEvent event) {
136
		boolean isVisible = this.suggestions != null;
137
		if (isVisible && this.suggestions.keyPressed(event)) {
138
			return true;
139
		}
140
141
		if (this.screen.getFocused() != this.input || !event.isCycleFocus() || this.allowHiding && !isVisible) {
142
			return false;
143
		}
144
145
		this.showSuggestions(true);
146
		return true;
147
	}
148
149
	public boolean mouseScrolled(final double scroll) {
150
		return this.suggestions != null && this.suggestions.mouseScrolled(Mth.clamp(scroll, -1.0, 1.0));
151
	}
152
153
	public boolean mouseClicked(final MouseButtonEvent event) {
154
		return this.suggestions != null && this.suggestions.mouseClicked((int)event.x(), (int)event.y());
155
	}
156
157
	public void showSuggestions(final boolean immediateNarration) {
158
		if (this.pendingSuggestions != null && this.pendingSuggestions.isDone()) {
159
			Suggestions suggestions = this.pendingSuggestions.join();
160
			if (!suggestions.isEmpty()) {
161
				int maxSuggestionWidth = 0;
162
163
				for (Suggestion suggestion : suggestions.getList()) {
164
					maxSuggestionWidth = Math.max(maxSuggestionWidth, this.font.width(suggestion.getText()));
165
				}
166
167
				int x = Mth.clamp(this.input.getScreenX(suggestions.getRange().getStart()), 0, this.input.getScreenX(0) + this.input.getInnerWidth() - maxSuggestionWidth);
168
				int y = this.anchorToBottom ? this.screen.height - 12 : 72;
169
				this.suggestions = new CommandSuggestions.SuggestionsList(x, y, maxSuggestionWidth, this.sortSuggestions(suggestions), immediateNarration);
170
			}
171
		}
172
	}
173
174
	public boolean isVisible() {
175
		return this.suggestions != null;
176
	}
177
178
	public Component getUsageNarration() {
179
		if (this.suggestions != null && this.suggestions.tabCycles) {
180
			return this.allowHiding
181
				? Component.translatable("narration.suggestion.usage.cycle.hidable")
182
				: Component.translatable("narration.suggestion.usage.cycle.fixed");
183
		} else {
184
			return this.allowHiding
185
				? Component.translatable("narration.suggestion.usage.fill.hidable")
186
				: Component.translatable("narration.suggestion.usage.fill.fixed");
187
		}
188
	}
189
190
	public void hide() {
191
		this.suggestions = null;
192
	}
193
194
	private List<Suggestion> sortSuggestions(final Suggestions suggestions) {
195
		String partialCommand = this.input.getValue().substring(0, this.input.getCursorPosition());
196
		int lastWordIndex = getLastWordIndex(partialCommand);
197
		String lastWord = partialCommand.substring(lastWordIndex).toLowerCase(Locale.ROOT);
198
		List<Suggestion> suggestionList = Lists.newArrayList();
199
		List<Suggestion> partial = Lists.newArrayList();
200
201
		for (Suggestion suggestion : suggestions.getList()) {
202
			if (!suggestion.getText().startsWith(lastWord) && !suggestion.getText().startsWith("minecraft:" + lastWord)) {
203
				partial.add(suggestion);
204
			} else {
205
				suggestionList.add(suggestion);
206
			}
207
		}
208
209
		suggestionList.addAll(partial);
210
		return suggestionList;
211
	}
212
213
	public void updateCommandInfo() {
214
		String command = this.input.getValue();
215
		if (this.currentParse != null && !this.currentParse.getReader().getString().equals(command)) {
216
			this.currentParse = null;
217
			this.currentParseIsCommand = false;
218
			this.currentParseIsMessage = false;
219
		}
220
221
		if (!this.keepSuggestions) {
222
			this.input.setSuggestion(null);
223
			this.suggestions = null;
224
		}
225
226
		this.commandUsage.clear();
227
		StringReader reader = new StringReader(command);
228
		boolean startsWithSlash = reader.canRead() && reader.peek() == '/';
229
		if (startsWithSlash) {
230
			reader.skip();
231
		}
232
233
		boolean isCommand = this.commandsOnly || startsWithSlash;
234
		int cursorPosition = this.input.getCursorPosition();
235
		if (isCommand) {
236
			CommandDispatcher<ClientSuggestionProvider> commands = this.minecraft.player.connection.getCommands();
237
			if (this.currentParse == null) {
238
				this.currentParse = commands.parse(reader, this.minecraft.player.connection.getSuggestionsProvider());
239
				this.currentParseIsCommand = true;
240
				this.currentParseIsMessage = hasMessageArguments(this.currentParse);
241
			}
242
243
			int parseStart = this.onlyShowIfCursorPastError ? reader.getCursor() : 1;
244
			if (cursorPosition >= parseStart && (this.suggestions == null || !this.keepSuggestions)) {
245
				this.pendingSuggestions = commands.getCompletionSuggestions(this.currentParse, cursorPosition);
246
				this.pendingSuggestions.thenAccept(suggestionResult -> {
247
					if (this.pendingSuggestions.isDone()) {
248
						this.updateUsageInfo(this.currentParse, suggestionResult);
249
					}
250
				});
251
			}
252
		} else if (!command.isBlank()) {
253
			this.currentParseIsMessage = true;
254
			String partialCommand = command.substring(0, cursorPosition);
255
			int lastWord = getLastWordIndex(partialCommand);
256
			Collection<String> nonCommandSuggestions = this.minecraft.player.connection.getSuggestionsProvider().getCustomTabSuggestions();
257
			this.pendingSuggestions = SharedSuggestionProvider.suggest(nonCommandSuggestions, new SuggestionsBuilder(partialCommand, lastWord));
258
			if (this.currentParseIsMessage && !this.messagesAllowed) {
259
				this.commandUsage.add(MESSAGES_NOT_ALLOWED_TEXT.getVisualOrderText());
260
			}
261
262
			this.recomputeUsageBoxWidth();
263
			this.commandUsagePosition = 0;
264
		} else {
265
			this.pendingSuggestions = null;
266
		}
267
	}
268
269
	private static boolean hasMessageArguments(final ParseResults<ClientSuggestionProvider> parseResults) {
270
		@Environment(EnvType.CLIENT)
271
		class Visitor implements Output<ClientSuggestionProvider> {
272
			private boolean foundMessageArgument;
273
274
			@Override
275
			public <T> void accept(
276
				final CommandContextBuilder<ClientSuggestionProvider> context,
277
				final ArgumentCommandNode<ClientSuggestionProvider, T> argument,
278
				final @Nullable ParsedArgument<ClientSuggestionProvider, T> value
279
			) {
280
				this.foundMessageArgument = this.foundMessageArgument | (value != null && value.getResult() instanceof Message);
281
			}
282
		}
283
284
		Visitor visitor = new Visitor();
285
		ArgumentVisitor.visitArguments(parseResults, visitor, false);
286
		return visitor.foundMessageArgument;
287
	}
288
289
	private static int getLastWordIndex(final String text) {
290
		if (Strings.isNullOrEmpty(text)) {
291
			return 0;
292
		}
293
294
		int result = 0;
295
		Matcher matcher = WHITESPACE_PATTERN.matcher(text);
296
297
		while (matcher.find()) {
298
			result = matcher.end();
299
		}
300
301
		return result;
302
	}
303
304
	private static FormattedCharSequence getExceptionMessage(final CommandSyntaxException e) {
305
		Component message = ComponentUtils.fromMessage(e.getRawMessage());
306
		String context = e.getContext();
307
		return context == null
308
			? message.getVisualOrderText()
309
			: Component.translatable("command.context.parse_error", message, e.getCursor(), context).getVisualOrderText();
310
	}
311
312
	private void updateUsageInfo(final ParseResults<ClientSuggestionProvider> currentParse, final Suggestions suggestions) {
313
		boolean trailingCharacters = false;
314
		if (this.input.getCursorPosition() == this.input.getValue().length()) {
315
			if (suggestions.isEmpty() && !currentParse.getExceptions().isEmpty()) {
316
				int literals = 0;
317
318
				for (Entry<CommandNode<ClientSuggestionProvider>, CommandSyntaxException> entry : currentParse.getExceptions().entrySet()) {
319
					CommandSyntaxException exception = entry.getValue();
320
					if (exception.getType() == CommandSyntaxException.BUILT_IN_EXCEPTIONS.literalIncorrect()) {
321
						literals++;
322
					} else {
323
						this.commandUsage.add(getExceptionMessage(exception));
324
					}
325
				}
326
327
				if (literals > 0) {
328
					this.commandUsage
329
						.add(getExceptionMessage(CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownArgument().createWithContext(currentParse.getReader())));
330
				}
331
			} else if (currentParse.getReader().canRead()) {
332
				trailingCharacters = true;
333
			}
334
		}
335
336
		SuggestionContext<ClientSuggestionProvider> suggestionContextAtCursor = currentParse.getContext().findSuggestionContext(this.input.getCursorPosition());
337
		if (this.commandUsage.isEmpty()) {
338
			List<FormattedCharSequence> usageEntries = this.fillNodeUsage(suggestionContextAtCursor, USAGE_FORMAT);
339
			if (usageEntries.isEmpty() && trailingCharacters) {
340
				this.commandUsage.add(getExceptionMessage(Commands.getParseException(currentParse)));
341
			}
342
343
			this.commandUsage.addAll(usageEntries);
344
		}
345
346
		if (this.currentParseIsCommand && !this.commandsAllowed) {
347
			this.commandUsage.add(COMMANDS_NOT_ALLOWED_TEXT.getVisualOrderText());
348
		}
349
350
		if (this.currentParseIsMessage && !this.messagesAllowed) {
351
			this.commandUsage.add(MESSAGES_NOT_ALLOWED_TEXT.getVisualOrderText());
352
		}
353
354
		this.recomputeUsageBoxWidth();
355
		if (!this.commandUsage.isEmpty()) {
356
			this.commandUsagePosition = Mth.clamp(
357
				this.input.getScreenX(suggestionContextAtCursor.startPos), 0, this.input.getScreenX(0) + this.input.getInnerWidth() - this.commandUsageWidth
358
			);
359
		} else {
360
			this.commandUsagePosition = 0;
361
		}
362
363
		this.suggestions = null;
364
		if (this.allowSuggestions && this.minecraft.options.autoSuggestions().get()) {
365
			this.showSuggestions(false);
366
		}
367
	}
368
369
	private List<FormattedCharSequence> fillNodeUsage(final SuggestionContext<ClientSuggestionProvider> suggestionContext, final Style usageFormat) {
370
		Map<CommandNode<ClientSuggestionProvider>, String> usage = this.minecraft
371
			.player
372
			.connection
373
			.getCommands()
374
			.getSmartUsage(suggestionContext.parent, this.minecraft.player.connection.getSuggestionsProvider());
375
		List<FormattedCharSequence> lines = new ArrayList<>();
376
377
		for (Entry<CommandNode<ClientSuggestionProvider>, String> entry : usage.entrySet()) {
378
			if (!(entry.getKey() instanceof LiteralCommandNode)) {
379
				lines.add(FormattedCharSequence.forward(entry.getValue(), usageFormat));
380
			}
381
		}
382
383
		return lines;
384
	}
385
386
	private void recomputeUsageBoxWidth() {
387
		int longest = 0;
388
389
		for (FormattedCharSequence entry : this.commandUsage) {
390
			longest = Math.max(longest, this.font.width(entry));
391
		}
392
393
		this.commandUsageWidth = longest;
394
	}
395
396
	private @Nullable FormattedCharSequence formatChat(final String text, final int offset) {
397
		return this.currentParse != null ? formatText(this.currentParse, text, offset) : null;
398
	}
399
400
	private static @Nullable String calculateSuggestionSuffix(final String contents, final String suggestion) {
401
		return suggestion.startsWith(contents) ? suggestion.substring(contents.length()) : null;
402
	}
403
404
	private static FormattedCharSequence formatText(final ParseResults<ClientSuggestionProvider> currentParse, final String text, final int offset) {
405
		List<FormattedCharSequence> parts = Lists.newArrayList();
406
		int unformattedStart = 0;
407
		int nextColor = -1;
408
		CommandContextBuilder<ClientSuggestionProvider> context = currentParse.getContext().getLastChild();
409
410
		for (ParsedArgument<ClientSuggestionProvider, ?> argument : context.getArguments().values()) {
411
			if (++nextColor >= ARGUMENT_STYLES.size()) {
412
				nextColor = 0;
413
			}
414
415
			int start = Math.max(argument.getRange().getStart() - offset, 0);
416
			if (start >= text.length()) {
417
				break;
418
			}
419
420
			int end = Math.min(argument.getRange().getEnd() - offset, text.length());
421
			if (end > 0) {
422
				parts.add(FormattedCharSequence.forward(text.substring(unformattedStart, start), LITERAL_STYLE));
423
				parts.add(FormattedCharSequence.forward(text.substring(start, end), ARGUMENT_STYLES.get(nextColor)));
424
				unformattedStart = end;
425
			}
426
		}
427
428
		if (currentParse.getReader().canRead()) {
429
			int start = Math.max(currentParse.getReader().getCursor() - offset, 0);
430
			if (start < text.length()) {
431
				int end = Math.min(start + currentParse.getReader().getRemainingLength(), text.length());
432
				parts.add(FormattedCharSequence.forward(text.substring(unformattedStart, start), LITERAL_STYLE));
433
				parts.add(FormattedCharSequence.forward(text.substring(start, end), UNPARSED_STYLE));
434
				unformattedStart = end;
435
			}
436
		}
437
438
		parts.add(FormattedCharSequence.forward(text.substring(unformattedStart), LITERAL_STYLE));
439
		return FormattedCharSequence.composite(parts);
440
	}
441
442
	public void extractRenderState(final GuiGraphicsExtractor graphics, final int mouseX, final int mouseY) {
443
		if (!this.extractSuggestions(graphics, mouseX, mouseY)) {
444
			this.extractUsage(graphics);
445
		}
446
	}
447
448
	public boolean extractSuggestions(final GuiGraphicsExtractor graphics, final int mouseX, final int mouseY) {
449
		if (this.suggestions != null) {
450
			this.suggestions.extractRenderState(graphics, mouseX, mouseY);
451
			return true;
452
		} else {
453
			return false;
454
		}
455
	}
456
457
	public void extractUsage(final GuiGraphicsExtractor graphics) {
458
		int y = 0;
459
460
		for (FormattedCharSequence line : this.commandUsage) {
461
			int lineY = this.anchorToBottom ? this.screen.height - 27 - 12 * y : 72 + 12 * y;
462
			graphics.fill(this.commandUsagePosition - 1, lineY, this.commandUsagePosition + this.commandUsageWidth + 1, lineY + 12, this.fillColor);
463
			graphics.text(this.font, line, this.commandUsagePosition, lineY + 2, -1);
464
			y++;
465
		}
466
	}
467
468
	public Component getNarrationMessage() {
469
		return this.suggestions != null ? CommonComponents.NEW_LINE.copy().append(this.suggestions.getNarrationMessage()) : CommonComponents.EMPTY;
470
	}
471
472
	public boolean hasAllowedInput() {
473
		return this.currentParseIsMessage && !this.messagesAllowed ? false : !this.currentParseIsCommand || this.commandsAllowed;
474
	}
475
476
	@Environment(EnvType.CLIENT)
477
	public class SuggestionsList {
478
		private final Rect2i rect;
479
		private final String originalContents;
480
		private final List<Suggestion> suggestionList;
481
		private int offset;
482
		private int current;
483
		private Vec2 lastMouse = Vec2.ZERO;
484
		private boolean tabCycles;
485
		private int lastNarratedEntry;
486
487
		private SuggestionsList(final int x, final int y, final int width, final List<Suggestion> suggestionList, final boolean immediateNarration) {
488
			int listX = x - (CommandSuggestions.this.input.isBordered() ? 0 : 1);
489
			int listY = CommandSuggestions.this.anchorToBottom
490
				? y - 3 - Math.min(suggestionList.size(), CommandSuggestions.this.suggestionLineLimit) * 12
491
				: y - (CommandSuggestions.this.input.isBordered() ? 1 : 0);
492
			this.rect = new Rect2i(listX, listY, width + 1, Math.min(suggestionList.size(), CommandSuggestions.this.suggestionLineLimit) * 12);
493
			this.originalContents = CommandSuggestions.this.input.getValue();
494
			this.lastNarratedEntry = immediateNarration ? -1 : 0;
495
			this.suggestionList = suggestionList;
496
			this.select(0);
497
		}
498
499
		public void extractRenderState(final GuiGraphicsExtractor graphics, final int mouseX, final int mouseY) {
500
			int limit = Math.min(this.suggestionList.size(), CommandSuggestions.this.suggestionLineLimit);
501
			int unselectedColor = -5592406;
502
			boolean hasPrevious = this.offset > 0;
503
			boolean hasNext = this.suggestionList.size() > this.offset + limit;
504
			boolean limited = hasPrevious || hasNext;
505
			boolean mouseMoved = this.lastMouse.x != mouseX || this.lastMouse.y != mouseY;
506
			if (mouseMoved) {
507
				this.lastMouse = new Vec2(mouseX, mouseY);
508
			}
509
510
			if (limited) {
511
				graphics.fill(this.rect.getX(), this.rect.getY() - 1, this.rect.getX() + this.rect.getWidth(), this.rect.getY(), CommandSuggestions.this.fillColor);
512
				graphics.fill(
513
					this.rect.getX(),
514
					this.rect.getY() + this.rect.getHeight(),
515
					this.rect.getX() + this.rect.getWidth(),
516
					this.rect.getY() + this.rect.getHeight() + 1,
517
					CommandSuggestions.this.fillColor
518
				);
519
				if (hasPrevious) {
520
					for (int x = 0; x < this.rect.getWidth(); x++) {
521
						if (x % 2 == 0) {
522
							graphics.fill(this.rect.getX() + x, this.rect.getY() - 1, this.rect.getX() + x + 1, this.rect.getY(), -1);
523
						}
524
					}
525
				}
526
527
				if (hasNext) {
528
					for (int x = 0; x < this.rect.getWidth(); x++) {
529
						if (x % 2 == 0) {
530
							graphics.fill(this.rect.getX() + x, this.rect.getY() + this.rect.getHeight(), this.rect.getX() + x + 1, this.rect.getY() + this.rect.getHeight() + 1, -1);
531
						}
532
					}
533
				}
534
			}
535
536
			boolean hovered = false;
537
538
			for (int i = 0; i < limit; i++) {
539
				Suggestion suggestion = this.suggestionList.get(i + this.offset);
540
				graphics.fill(
541
					this.rect.getX(), this.rect.getY() + 12 * i, this.rect.getX() + this.rect.getWidth(), this.rect.getY() + 12 * i + 12, CommandSuggestions.this.fillColor
542
				);
543
				if (mouseX > this.rect.getX()
544
					&& mouseX < this.rect.getX() + this.rect.getWidth()
545
					&& mouseY > this.rect.getY() + 12 * i
546
					&& mouseY < this.rect.getY() + 12 * i + 12) {
547
					if (mouseMoved) {
548
						this.select(i + this.offset);
549
					}
550
551
					hovered = true;
552
				}
553
554
				graphics.text(
555
					CommandSuggestions.this.font, suggestion.getText(), this.rect.getX() + 1, this.rect.getY() + 2 + 12 * i, i + this.offset == this.current ? -256 : -5592406
556
				);
557
			}
558
559
			if (hovered) {
560
				com.mojang.brigadier.Message tooltip = this.suggestionList.get(this.current).getTooltip();
561
				if (tooltip != null) {
562
					graphics.setTooltipForNextFrame(CommandSuggestions.this.font, ComponentUtils.fromMessage(tooltip), mouseX, mouseY);
563
				}
564
			}
565
566
			if (this.rect.contains(mouseX, mouseY)) {
567
				graphics.requestCursor(CursorTypes.POINTING_HAND);
568
			}
569
		}
570
571
		public boolean mouseClicked(final int x, final int y) {
572
			if (!this.rect.contains(x, y)) {
573
				return false;
574
			}
575
576
			int line = (y - this.rect.getY()) / 12 + this.offset;
577
			if (line >= 0 && line < this.suggestionList.size()) {
578
				this.select(line);
579
				this.useSuggestion();
580
			}
581
582
			return true;
583
		}
584
585
		public boolean mouseScrolled(final double scroll) {
586
			int mouseX = (int)CommandSuggestions.this.minecraft.mouseHandler.getScaledXPos(CommandSuggestions.this.minecraft.getWindow());
587
			int mouseY = (int)CommandSuggestions.this.minecraft.mouseHandler.getScaledYPos(CommandSuggestions.this.minecraft.getWindow());
588
			if (this.rect.contains(mouseX, mouseY)) {
589
				this.offset = Mth.clamp((int)(this.offset - scroll), 0, Math.max(this.suggestionList.size() - CommandSuggestions.this.suggestionLineLimit, 0));
590
				return true;
591
			} else {
592
				return false;
593
			}
594
		}
595
596
		public boolean keyPressed(final KeyEvent event) {
597
			if (event.isUp()) {
598
				this.cycle(-1);
599
				this.tabCycles = false;
600
				return true;
601
			}
602
603
			if (event.isDown()) {
604
				this.cycle(1);
605
				this.tabCycles = false;
606
				return true;
607
			}
608
609
			if (event.isCycleFocus()) {
610
				if (this.tabCycles) {
611
					this.cycle(event.hasShiftDown() ? -1 : 1);
612
				}
613
614
				this.useSuggestion();
615
				return true;
616
			} else if (event.isEscape()) {
617
				CommandSuggestions.this.hide();
618
				CommandSuggestions.this.input.setSuggestion(null);
619
				return true;
620
			} else {
621
				return false;
622
			}
623
		}
624
625
		public void cycle(final int direction) {
626
			this.select(this.current + direction);
627
			int first = this.offset;
628
			int last = this.offset + CommandSuggestions.this.suggestionLineLimit - 1;
629
			if (this.current < first) {
630
				this.offset = Mth.clamp(this.current, 0, Math.max(this.suggestionList.size() - CommandSuggestions.this.suggestionLineLimit, 0));
631
			} else if (this.current > last) {
632
				this.offset = Mth.clamp(
633
					this.current + CommandSuggestions.this.lineStartOffset - CommandSuggestions.this.suggestionLineLimit,
634
					0,
635
					Math.max(this.suggestionList.size() - CommandSuggestions.this.suggestionLineLimit, 0)
636
				);
637
			}
638
		}
639
640
		public void select(final int index) {
641
			this.current = index;
642
			if (this.current < 0) {
643
				this.current = this.current + this.suggestionList.size();
644
			}
645
646
			if (this.current >= this.suggestionList.size()) {
647
				this.current = this.current - this.suggestionList.size();
648
			}
649
650
			Suggestion suggestion = this.suggestionList.get(this.current);
651
			CommandSuggestions.this.input
652
				.setSuggestion(CommandSuggestions.calculateSuggestionSuffix(CommandSuggestions.this.input.getValue(), suggestion.apply(this.originalContents)));
653
			if (this.lastNarratedEntry != this.current) {
654
				CommandSuggestions.this.minecraft.getNarrator().saySystemNow(this.getNarrationMessage());
655
			}
656
		}
657
658
		public void useSuggestion() {
659
			Suggestion suggestion = this.suggestionList.get(this.current);
660
			CommandSuggestions.this.keepSuggestions = true;
661
			CommandSuggestions.this.input.setValue(suggestion.apply(this.originalContents));
662
			int end = suggestion.getRange().getStart() + suggestion.getText().length();
663
			CommandSuggestions.this.input.setCursorPosition(end);
664
			CommandSuggestions.this.input.setHighlightPos(end);
665
			this.select(this.current);
666
			CommandSuggestions.this.keepSuggestions = false;
667
			this.tabCycles = true;
668
		}
669
670
		private Component getNarrationMessage() {
671
			this.lastNarratedEntry = this.current;
672
			Suggestion suggestion = this.suggestionList.get(this.current);
673
			com.mojang.brigadier.Message tooltip = suggestion.getTooltip();
674
			return tooltip != null
675
				? Component.translatable(
676
					"narration.suggestion.tooltip", this.current + 1, this.suggestionList.size(), suggestion.getText(), Component.translationArg(tooltip)
677
				)
678
				: Component.translatable("narration.suggestion", this.current + 1, this.suggestionList.size(), suggestion.getText());
679
		}
680
	}
681
}
682

Decompiled Minecraft 26.3 source of CommandSuggestions (net/minecraft/client/gui/components/CommandSuggestions.java) with Mojang official mappings, stored verbatim on the site.