Skip to content

Commit

Permalink
Merge pull request #527 from CoderKuo/dev/6.2.0
Browse files Browse the repository at this point in the history
FileWatcher#修复多文件监听问题、兼容Mohist
  • Loading branch information
Bkm016 authored Jan 6, 2025
2 parents 0a151d7 + 76ca951 commit 771bcf3
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 26 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@ public class RuntimeEnvDependency {
} catch (ClassNotFoundException e) {
isAetherFound = false;
}
// Mohist 直接不用 Aether
try {
Class.forName("com.mohistmc.MohistMC");
isAetherFound = false;
}catch (ClassNotFoundException ignored){
}
}

public List<ParsedDependency> getDependency(@NotNull ReflexClass clazz) {
Expand Down
58 changes: 32 additions & 26 deletions common-legacy-api/src/main/java/taboolib/common5/FileWatcher.java
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,24 @@ public class FileWatcher {
public FileWatcher(int interval) {
try {
this.watchService = FileSystems.getDefault().newWatchService();
this.executorService.scheduleAtFixedRate(() -> fileListenerMap.forEach((file, listener) -> {
try {
listener.poll();
} catch (Throwable ex) {
ex.printStackTrace();
this.executorService.scheduleAtFixedRate(() -> {
WatchKey key;
while ((key = watchService.poll()) != null) {
key.pollEvents().forEach(event -> {
if (event.context() instanceof Path) {
Path changedPath = (Path) event.context();
fileListenerMap.forEach((file, listener) -> {
try {
listener.handleEvent(changedPath);
} catch (Throwable ex) {
ex.printStackTrace();
}
});
}
});
key.reset();
}
}), 1000, interval, TimeUnit.MILLISECONDS);
}, 1000, interval, TimeUnit.MILLISECONDS);
// 注册关闭回调
TabooLib.registerLifeCycleTask(LifeCycle.DISABLE, 0, this::release);
} catch (IOException e) {
Expand Down Expand Up @@ -142,27 +153,22 @@ static class FileListener {
);
}

public void poll() {
watchKey.pollEvents().forEach(event -> {
if (event.context() instanceof Path) {
Path path = (Path) event.context();
Path fullPath = file.getParentFile().toPath().resolve(path);
// 监听目录
if (file.isDirectory()) {
try {
// 使用 relativize 检查路径关系,更加准确
file.toPath().relativize(fullPath);
callback.accept(fullPath.toFile());
} catch (IllegalArgumentException ignored) {
// 如果不是子路径,会抛出异常,直接忽略
}
}
// 监听文件
else if (isSameFile(fullPath, file.toPath())) {
callback.accept(fullPath.toFile()); // 使用完整路径
}
public void handleEvent(Path changedPath) {
Path fullPath = file.getParentFile().toPath().resolve(changedPath);
// 监听目录
if (file.isDirectory()) {
try {
// 使用 relativize 检查路径关系,更加准确
file.toPath().relativize(fullPath);
callback.accept(fullPath.toFile());
} catch (IllegalArgumentException ignored) {
// 如果不是子路径,会抛出异常,直接忽略
}
});
}
// 监听文件
else if (isSameFile(fullPath, file.toPath())) {
callback.accept(fullPath.toFile());
}
}

public boolean isSameFile(Path path1, Path path2) {
Expand Down

0 comments on commit 771bcf3

Please sign in to comment.