清理 org.jackhuang.hmcl.util (#2673)

* 合并 Holder 与 ReferenceHolder

* 清理代码

* 清理代码

* update

* update

* update
This commit is contained in:
Glavo
2024-01-24 03:07:56 +08:00
committed by GitHub
parent f53aed9a08
commit 1eb53b247c
30 changed files with 71 additions and 93 deletions

View File

@@ -26,7 +26,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.function.Function; import java.util.function.Function;
public class AggregatedObservableList<T> { public final class AggregatedObservableList<T> {
protected final List<ObservableList<T>> lists = new ArrayList<>(); protected final List<ObservableList<T>> lists = new ArrayList<>();
final private List<Integer> sizes = new ArrayList<>(); final private List<Integer> sizes = new ArrayList<>();
@@ -126,7 +126,7 @@ public class AggregatedObservableList<T> {
return startIndex + sizes.get(index) - 1; return startIndex + sizes.get(index) - 1;
} }
private class InternalListModificationListener implements ListChangeListener<T> { private final class InternalListModificationListener implements ListChangeListener<T> {
@NotNull @NotNull
private final ObservableList<T> list; private final ObservableList<T> list;

View File

@@ -38,7 +38,7 @@ import static org.jackhuang.hmcl.util.i18n.I18n.i18n;
/** /**
* @author huangyuhui * @author huangyuhui
*/ */
public class CrashReporter implements Thread.UncaughtExceptionHandler { public final class CrashReporter implements Thread.UncaughtExceptionHandler {
// Lazy initialization resources // Lazy initialization resources
private static final class Hole { private static final class Hole {

View File

@@ -25,7 +25,7 @@ import java.util.function.Supplier;
* *
* @param <T> value type * @param <T> value type
*/ */
public class Lazy<T> { public final class Lazy<T> {
private Supplier<T> supplier; private Supplier<T> supplier;
private T value = null; private T value = null;
@@ -40,5 +40,4 @@ public class Lazy<T> {
} }
return value; return value;
} }
} }

View File

@@ -23,7 +23,7 @@ import java.io.InputStream;
* Suppress the throwable when we make sure the resource cannot miss. * Suppress the throwable when we make sure the resource cannot miss.
* @see CrashReporter * @see CrashReporter
*/ */
public class ResourceNotFoundError extends Error { public final class ResourceNotFoundError extends Error {
public ResourceNotFoundError(String message) { public ResourceNotFoundError(String message) {
super(message); super(message);
} }

View File

@@ -21,7 +21,7 @@ import org.jackhuang.hmcl.ui.construct.TaskExecutorDialogPane;
import java.util.function.Consumer; import java.util.function.Consumer;
public class TaskCancellationAction { public final class TaskCancellationAction {
public static TaskCancellationAction NO_CANCEL = new TaskCancellationAction((Consumer<TaskExecutorDialogPane>) null); public static TaskCancellationAction NO_CANCEL = new TaskCancellationAction((Consumer<TaskExecutorDialogPane>) null);
public static TaskCancellationAction NORMAL = new TaskCancellationAction(() -> { public static TaskCancellationAction NORMAL = new TaskCancellationAction(() -> {
}); });

View File

@@ -1,10 +1,25 @@
package org.jackhuang.hmcl.util; package org.jackhuang.hmcl.util;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import java.util.Objects; import java.util.Objects;
public final class Holder<T> { public final class Holder<T> implements InvalidationListener {
public T value; public T value;
public Holder() {
}
public Holder(T value) {
this.value = value;
}
@Override
public void invalidated(Observable observable) {
// no-op
}
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hashCode(value); return Objects.hashCode(value);

View File

@@ -17,7 +17,6 @@
*/ */
package org.jackhuang.hmcl.util; package org.jackhuang.hmcl.util;
import java.util.Optional;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer; import java.util.function.Consumer;
@@ -30,7 +29,7 @@ import java.util.function.Supplier;
* *
* @author yushijinhun * @author yushijinhun
*/ */
public class InvocationDispatcher<ARG> implements Consumer<ARG> { public final class InvocationDispatcher<ARG> implements Consumer<ARG> {
public static <ARG> InvocationDispatcher<ARG> runOn(Executor executor, Consumer<ARG> action) { public static <ARG> InvocationDispatcher<ARG> runOn(Executor executor, Consumer<ARG> action) {
return new InvocationDispatcher<>(arg -> executor.execute(() -> { return new InvocationDispatcher<>(arg -> executor.execute(() -> {
@@ -40,9 +39,8 @@ public class InvocationDispatcher<ARG> implements Consumer<ARG> {
})); }));
} }
private Consumer<Supplier<ARG>> handler; private final Consumer<Supplier<ARG>> handler;
private final AtomicReference<Holder<ARG>> pendingArg = new AtomicReference<>();
private AtomicReference<Optional<ARG>> pendingArg = new AtomicReference<>();
public InvocationDispatcher(Consumer<Supplier<ARG>> handler) { public InvocationDispatcher(Consumer<Supplier<ARG>> handler) {
this.handler = handler; this.handler = handler;
@@ -50,8 +48,8 @@ public class InvocationDispatcher<ARG> implements Consumer<ARG> {
@Override @Override
public void accept(ARG arg) { public void accept(ARG arg) {
if (pendingArg.getAndSet(Optional.ofNullable(arg)) == null) { if (pendingArg.getAndSet(new Holder<>(arg)) == null) {
handler.accept(() -> pendingArg.getAndSet(null).orElse(null)); handler.accept(() -> pendingArg.getAndSet(null).value);
} }
} }
} }

View File

@@ -416,7 +416,7 @@ public final class StringUtils {
/** /**
* Class for computing the longest common subsequence between strings. * Class for computing the longest common subsequence between strings.
*/ */
public static class LongestCommonSubsequence { public static final class LongestCommonSubsequence {
// We reuse dynamic programming storage array here to reduce allocations. // We reuse dynamic programming storage array here to reduce allocations.
private final int[][] f; private final int[][] f;
private final int maxLengthA; private final int maxLengthA;

View File

@@ -17,7 +17,7 @@
*/ */
package org.jackhuang.hmcl.util; package org.jackhuang.hmcl.util;
public class ToStringBuilder { public final class ToStringBuilder {
private final StringBuilder stringBuilder; private final StringBuilder stringBuilder;
private boolean first = true; private boolean first = true;

View File

@@ -32,9 +32,9 @@ import java.util.Map;
* *
* @author yushijinhun * @author yushijinhun
*/ */
public class EnumOrdinalDeserializer<T extends Enum<T>> implements JsonDeserializer<T> { public final class EnumOrdinalDeserializer<T extends Enum<T>> implements JsonDeserializer<T> {
private Map<String, T> mapping = new HashMap<>(); private final Map<String, T> mapping = new HashMap<>();
public EnumOrdinalDeserializer(Class<T> enumClass) { public EnumOrdinalDeserializer(Class<T> enumClass) {
for (T constant : enumClass.getEnumConstants()) { for (T constant : enumClass.getEnumConstants()) {

View File

@@ -26,7 +26,7 @@ import java.util.Map;
* @param <K> * @param <K>
* @param <V> * @param <V>
*/ */
public class JsonMap<K, V> extends HashMap<K, V> { public final class JsonMap<K, V> extends HashMap<K, V> {
public JsonMap(int initialCapacity, float loadFactor) { public JsonMap(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor); super(initialCapacity, loadFactor);
} }

View File

@@ -10,7 +10,7 @@ import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class JsonTypeAdapterFactory implements TypeAdapterFactory { public final class JsonTypeAdapterFactory implements TypeAdapterFactory {
public static final JsonTypeAdapterFactory INSTANCE = new JsonTypeAdapterFactory(); public static final JsonTypeAdapterFactory INSTANCE = new JsonTypeAdapterFactory();

View File

@@ -23,7 +23,7 @@ import org.jackhuang.hmcl.util.DigestUtils;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Path; import java.nio.file.Path;
public class ChecksumMismatchException extends ArtifactMalformedException { public final class ChecksumMismatchException extends ArtifactMalformedException {
private final String algorithm; private final String algorithm;
private final String expectedChecksum; private final String expectedChecksum;

View File

@@ -26,8 +26,8 @@ import java.net.HttpURLConnection;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
public class HttpMultipartRequest implements Closeable { public final class HttpMultipartRequest implements Closeable {
private static final String endl = "\r\n"; private static final byte[] ENDL = {'\r', '\n'};
private final String boundary = "*****" + System.currentTimeMillis() + "*****"; private final String boundary = "*****" + System.currentTimeMillis() + "*****";
private final HttpURLConnection urlConnection; private final HttpURLConnection urlConnection;
@@ -44,7 +44,7 @@ public class HttpMultipartRequest implements Closeable {
private void addLine(String content) throws IOException { private void addLine(String content) throws IOException {
stream.write(content.getBytes(UTF_8)); stream.write(content.getBytes(UTF_8));
stream.write(endl.getBytes(UTF_8)); stream.write(ENDL);
} }
public HttpMultipartRequest file(String name, String filename, String contentType, InputStream inputStream) throws IOException { public HttpMultipartRequest file(String name, String filename, String contentType, InputStream inputStream) throws IOException {

View File

@@ -20,7 +20,7 @@ package org.jackhuang.hmcl.util.io;
import java.io.IOException; import java.io.IOException;
import java.net.URL; import java.net.URL;
public class ResponseCodeException extends IOException { public final class ResponseCodeException extends IOException {
private final URL url; private final URL url;
private final int responseCode; private final int responseCode;

View File

@@ -24,7 +24,7 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.*; import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.BasicFileAttributes;
public class Unzipper { public final class Unzipper {
private final Path zipFile, dest; private final Path zipFile, dest;
private boolean replaceExistentFile = false; private boolean replaceExistentFile = false;
private boolean terminateIfSubDirectoryNotExists = false; private boolean terminateIfSubDirectoryNotExists = false;

View File

@@ -25,7 +25,7 @@ import javafx.scene.control.ToggleGroup;
/** /**
* @author yushijinhun * @author yushijinhun
*/ */
public class AutomatedToggleGroup extends ToggleGroup { public final class AutomatedToggleGroup extends ToggleGroup {
private final ObservableList<? extends Toggle> toggles; private final ObservableList<? extends Toggle> toggles;
private final ListChangeListener<Toggle> listListener; private final ListChangeListener<Toggle> listListener;

View File

@@ -70,7 +70,7 @@ public abstract class BindingMapping<T, U> extends ObjectBinding<U> {
return new AsyncMappedBinding<>(this, mapper, initial); return new AsyncMappedBinding<>(this, mapper, initial);
} }
private static class SimpleBinding<T> extends BindingMapping<T, T> { private static final class SimpleBinding<T> extends BindingMapping<T, T> {
public SimpleBinding(ObservableValue<T> predecessor) { public SimpleBinding(ObservableValue<T> predecessor) {
super(predecessor); super(predecessor);
@@ -92,7 +92,7 @@ public abstract class BindingMapping<T, U> extends ObjectBinding<U> {
} }
} }
private static class MappedBinding<T, U> extends BindingMapping<T, U> { private static final class MappedBinding<T, U> extends BindingMapping<T, U> {
private final Function<? super T, ? extends U> mapper; private final Function<? super T, ? extends U> mapper;
@@ -107,7 +107,7 @@ public abstract class BindingMapping<T, U> extends ObjectBinding<U> {
} }
} }
private static class FlatMappedBinding<T extends ObservableValue<? extends U>, U> extends BindingMapping<T, U> { private static final class FlatMappedBinding<T extends ObservableValue<? extends U>, U> extends BindingMapping<T, U> {
private final Supplier<? extends U> nullAlternative; private final Supplier<? extends U> nullAlternative;
private T lastObservable = null; private T lastObservable = null;
@@ -142,7 +142,7 @@ public abstract class BindingMapping<T, U> extends ObjectBinding<U> {
} }
} }
private static class AsyncMappedBinding<T, U> extends BindingMapping<T, U> { private static final class AsyncMappedBinding<T, U> extends BindingMapping<T, U> {
private boolean initialized = false; private boolean initialized = false;
private T prev; private T prev;

View File

@@ -24,6 +24,7 @@ import javafx.beans.property.Property;
import javafx.collections.ObservableList; import javafx.collections.ObservableList;
import javafx.scene.Node; import javafx.scene.Node;
import javafx.scene.control.*; import javafx.scene.control.*;
import org.jackhuang.hmcl.util.Holder;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
@@ -116,7 +117,7 @@ public final class ExtendedProperties {
} }
}; };
toggleGroup.getToggles().addListener(new WeakInvalidationListener(onTogglesChanged)); toggleGroup.getToggles().addListener(new WeakInvalidationListener(onTogglesChanged));
property.addListener(new ReferenceHolder(onTogglesChanged)); property.addListener(new Holder<>(onTogglesChanged));
return property; return property;
} }

View File

@@ -21,6 +21,7 @@ import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener; import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList; import javafx.collections.ObservableList;
import javafx.collections.WeakListChangeListener; import javafx.collections.WeakListChangeListener;
import org.jackhuang.hmcl.util.Holder;
import java.util.*; import java.util.*;
import java.util.function.Function; import java.util.function.Function;
@@ -35,14 +36,14 @@ public final class MappedObservableList {
private MappedObservableList() { private MappedObservableList() {
} }
private static class MappedObservableListUpdater<T, U> implements ListChangeListener<T> { private static final class MappedObservableListUpdater<T, U> implements ListChangeListener<T> {
private ObservableList<T> origin; private final ObservableList<T> origin;
private ObservableList<U> target; private final ObservableList<U> target;
private Function<T, U> mapper; private final Function<T, U> mapper;
// If we directly synchronize changes to target, each operation on target will cause a event to be fired. // If we directly synchronize changes to target, each operation on target will cause a event to be fired.
// So we first write changes to buffer. After all the changes are processed, we use target.setAll to synchronize the changes. // So we first write changes to buffer. After all the changes are processed, we use target.setAll to synchronize the changes.
private List<U> buffer; private final List<U> buffer;
MappedObservableListUpdater(ObservableList<T> origin, ObservableList<U> target, Function<T, U> mapper) { MappedObservableListUpdater(ObservableList<T> origin, ObservableList<U> target, Function<T, U> mapper) {
this.origin = origin; this.origin = origin;
@@ -125,7 +126,7 @@ public final class MappedObservableList {
ListChangeListener<T> listener = new MappedObservableListUpdater<>(origin, target, mapper); ListChangeListener<T> listener = new MappedObservableListUpdater<>(origin, target, mapper);
// let target hold a reference to listener to prevent listener being garbage-collected before target is garbage-collected // let target hold a reference to listener to prevent listener being garbage-collected before target is garbage-collected
target.addListener(new ReferenceHolder(listener)); target.addListener(new Holder<>(listener));
// let origin hold a weak reference to listener, so that target can be garbage-collected when it's no longer used // let origin hold a weak reference to listener, so that target can be garbage-collected when it's no longer used
origin.addListener(new WeakListChangeListener<>(listener)); origin.addListener(new WeakListChangeListener<>(listener));

View File

@@ -28,7 +28,7 @@ import java.util.function.Function;
/** /**
* @author yushijinhun * @author yushijinhun
*/ */
public class MappedProperty<T, U> extends SimpleObjectProperty<U> { public final class MappedProperty<T, U> extends SimpleObjectProperty<U> {
private final Property<T> predecessor; private final Property<T> predecessor;
private final Function<U, T> reservedMapper; private final Function<U, T> reservedMapper;

View File

@@ -35,7 +35,7 @@ import javafx.beans.binding.ObjectBinding;
/** /**
* @author yushijinhun * @author yushijinhun
*/ */
public class ObservableCache<K, V, E extends Exception> { public final class ObservableCache<K, V, E extends Exception> {
private final ExceptionalFunction<K, V, E> source; private final ExceptionalFunction<K, V, E> source;
private final BiConsumer<K, Throwable> exceptionHandler; private final BiConsumer<K, Throwable> exceptionHandler;

View File

@@ -28,10 +28,10 @@ import java.util.concurrent.CopyOnWriteArrayList;
* *
* @author yushijinhun * @author yushijinhun
*/ */
public class ObservableHelper implements Observable, InvalidationListener { public final class ObservableHelper implements Observable, InvalidationListener {
private List<InvalidationListener> listeners = new CopyOnWriteArrayList<>(); private final List<InvalidationListener> listeners = new CopyOnWriteArrayList<>();
private Observable source; private final Observable source;
public ObservableHelper() { public ObservableHelper() {
this.source = this; this.source = this;

View File

@@ -28,7 +28,7 @@ import javafx.beans.binding.ObjectBinding;
/** /**
* @author yushijinhun * @author yushijinhun
*/ */
public class ObservableOptionalCache<K, V, E extends Exception> { public final class ObservableOptionalCache<K, V, E extends Exception> {
private final ObservableCache<K, Optional<V>, E> backed; private final ObservableCache<K, Optional<V>, E> backed;

View File

@@ -36,7 +36,7 @@ public final class PropertyUtils {
private PropertyUtils() { private PropertyUtils() {
} }
public static class PropertyHandle { public static final class PropertyHandle {
public final WritableValue<Object> accessor; public final WritableValue<Object> accessor;
public final Observable observable; public final Observable observable;
@@ -160,8 +160,6 @@ public final class PropertyUtils {
public static void attachListener(Object instance, InvalidationListener listener) { public static void attachListener(Object instance, InvalidationListener listener) {
getPropertyHandleFactories(instance.getClass()) getPropertyHandleFactories(instance.getClass())
.forEach((name, factory) -> { .forEach((name, factory) -> factory.apply(instance).observable.addListener(listener));
factory.apply(instance).observable.addListener(listener);
});
} }
} }

View File

@@ -27,12 +27,13 @@ import javafx.beans.value.WeakChangeListener;
/** /**
* @author yushijinhun * @author yushijinhun
*/ */
public class ReadWriteComposedProperty<T> extends SimpleObjectProperty<T> { public final class ReadWriteComposedProperty<T> extends SimpleObjectProperty<T> {
@SuppressWarnings("unused") @SuppressWarnings({"unused", "FieldCanBeLocal"})
private final ObservableValue<T> readSource; private final ObservableValue<T> readSource;
private final Consumer<T> writeTarget; private final Consumer<T> writeTarget;
@SuppressWarnings("FieldCanBeLocal")
private ChangeListener<T> listener; private ChangeListener<T> listener;
public ReadWriteComposedProperty(ObservableValue<T> readSource, Consumer<T> writeTarget) { public ReadWriteComposedProperty(ObservableValue<T> readSource, Consumer<T> writeTarget) {

View File

@@ -1,35 +0,0 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2020 huangyuhui <huanghongxun2008@126.com> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.util.javafx;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
class ReferenceHolder implements InvalidationListener {
@SuppressWarnings("unused")
private Object ref;
public ReferenceHolder(Object ref) {
this.ref = ref;
}
@Override
public void invalidated(Observable observable) {
// no-op
}
}

View File

@@ -30,7 +30,7 @@ import javafx.util.StringConverter;
/** /**
* @author yushijinhun * @author yushijinhun
*/ */
public class SafeStringConverter<S extends T, T> extends StringConverter<T> { public final class SafeStringConverter<S extends T, T> extends StringConverter<T> {
public static SafeStringConverter<Integer, Number> fromInteger() { public static SafeStringConverter<Integer, Number> fromInteger() {
return new SafeStringConverter<Integer, Number>(Integer::parseInt, NumberFormatException.class) return new SafeStringConverter<Integer, Number>(Integer::parseInt, NumberFormatException.class)
@@ -48,10 +48,10 @@ public class SafeStringConverter<S extends T, T> extends StringConverter<T> {
.fallbackTo(0.0); .fallbackTo(0.0);
} }
private ExceptionalFunction<String, S, ?> converter; private final ExceptionalFunction<String, S, ?> converter;
private Class<?> malformedExceptionClass; private final Class<?> malformedExceptionClass;
private S fallbackValue = null; private S fallbackValue = null;
private List<Predicate<S>> restrictions = new ArrayList<>(); private final List<Predicate<S>> restrictions = new ArrayList<>();
public <E extends Exception> SafeStringConverter(ExceptionalFunction<String, S, E> converter, Class<E> malformedExceptionClass) { public <E extends Exception> SafeStringConverter(ExceptionalFunction<String, S, E> converter, Class<E> malformedExceptionClass) {
this.converter = converter; this.converter = converter;
@@ -94,7 +94,7 @@ public class SafeStringConverter<S extends T, T> extends StringConverter<T> {
return Optional.of(converted); return Optional.of(converted);
} }
protected boolean filter(S value) { private boolean filter(S value) {
for (Predicate<S> restriction : restrictions) { for (Predicate<S> restriction : restrictions) {
if (!restriction.test(value)) { if (!restriction.test(value)) {
return false; return false;

View File

@@ -35,7 +35,7 @@ import java.util.function.Predicate;
* @see org.jackhuang.hmcl.launch.ExitWaiter * @see org.jackhuang.hmcl.launch.ExitWaiter
* @see org.jackhuang.hmcl.launch.StreamPump * @see org.jackhuang.hmcl.launch.StreamPump
*/ */
public class ManagedProcess { public final class ManagedProcess {
private final Process process; private final Process process;
private final List<String> commands; private final List<String> commands;
private final String classpath; private final String classpath;

View File

@@ -28,7 +28,7 @@ import javafx.scene.image.WritableImage;
* *
* @author yushijinhun * @author yushijinhun
*/ */
public class NormalizedSkin { public final class NormalizedSkin {
private static void copyImage(Image src, WritableImage dst, int sx, int sy, int dx, int dy, int w, int h, boolean flipHorizontal) { private static void copyImage(Image src, WritableImage dst, int sx, int sy, int dx, int dy, int w, int h, boolean flipHorizontal) {
PixelReader reader = src.getPixelReader(); PixelReader reader = src.getPixelReader();