blob: 9eb6981df0266298b5cacb5ec1e5d52a72a8125e (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
package com.keuin.kbackupfabric.backup.suggestion;
import com.mojang.brigadier.suggestion.SuggestionProvider;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import net.minecraft.server.command.ServerCommandSource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
public class BackupNameSuggestionProvider {
private static final List<String> candidateCacheList = new ArrayList<>();
private static final Object syncSetDirectory = new Object();
private static final Object syncCache = new Object();
private static final long CACHE_TTL = 8000;
private static String backupSaveDirectory;
private static long cacheUpdateTime = 0;
public static void setBackupSaveDirectory(String backupSaveDirectory) {
synchronized (syncSetDirectory) {
BackupNameSuggestionProvider.backupSaveDirectory = backupSaveDirectory;
}
// Immediately perform an update
updateCandidateList();
}
public static void updateCandidateList() {
synchronized (syncCache) {
try {
File file = new File(backupSaveDirectory);
candidateCacheList.clear();
File[] files = file.listFiles();
if (files == null)
return;
for (File f : files)
candidateCacheList.add(f.getName());
cacheUpdateTime = System.currentTimeMillis();
} catch (NullPointerException ignored) {
}
}
}
// private static void updateCandidateList(Collection<String> stringCollection) {
// candidateList.clear();
// candidateList.addAll(stringCollection);
// }
public static SuggestionProvider<ServerCommandSource> getProvider() {
return (context, builder) -> getCompletableFuture(builder);
}
private static CompletableFuture<Suggestions> getCompletableFuture(SuggestionsBuilder builder) {
if (isCacheExpired())
updateCandidateList();
String remaining = builder.getRemaining().toLowerCase(Locale.ROOT);
synchronized (syncCache) {
if (candidateCacheList.isEmpty()) { // If the list is empty then return no suggestions
return Suggestions.empty(); // No suggestions
}
for (String string : candidateCacheList) { // Iterate through the supplied list
if (string.toLowerCase(Locale.ROOT).startsWith(remaining)) {
builder.suggest(string); // Add every single entry to suggestions list.
}
}
}
return builder.buildFuture(); // Create the CompletableFuture containing all the suggestions
}
private static boolean isCacheExpired() {
return System.currentTimeMillis() - cacheUpdateTime > CACHE_TTL || cacheUpdateTime == 0;
}
}
|