Skip to content

Commit

Permalink
fix scrolling issues and keybind issue, debug printouts, change event…
Browse files Browse the repository at this point in the history
…Handler on kotlin to register automatically
  • Loading branch information
nextdayy committed Jan 28, 2025
1 parent 34df51f commit c5409f9
Show file tree
Hide file tree
Showing 24 changed files with 182 additions and 100 deletions.
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name=OneConfig
mod_id=oneconfig
version_major=1
version_minor=0
version_patch=0-alpha.58
version_patch=0-alpha.59

polyfrost.defaults.loom=3

Expand Down
2 changes: 1 addition & 1 deletion gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ kotlin = "2.0.20"
kotlinx-coroutines = "1.8.1"
kotlinx-atomicfu = "0.24.0"
fabric-language-kotlin = "1.12.2+kotlin.2.0.20"
polyui = "1.7.33"
polyui = "1.7.36"
annotations = "24.1.0"
hypixel-modapi = "1.0"
hypixel-data = "0.1.2" # Dep of hypixel-modapi
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ protected FileSerializer<String> getSerializer(Path p) {
String path = p.toString();
int i = path.lastIndexOf('.');
if (i == -1) {
LOGGER.warn("no serializer set for file {}, using YAML", path);
//LOGGER.warn("no serializer set for file {}, using YAML", path);
return serializers.get(".yml");
}
return serializers.get(path.substring(i));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,15 @@

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import org.polyfrost.oneconfig.api.event.v1.events.Event;
import org.polyfrost.oneconfig.api.event.v1.events.InitializationEvent;
import org.polyfrost.oneconfig.api.event.v1.invoke.EventCollector;
import org.polyfrost.oneconfig.api.event.v1.invoke.EventHandler;
import org.polyfrost.oneconfig.api.event.v1.invoke.impl.AnnotationEventMapper;
import org.polyfrost.oneconfig.api.platform.v1.Platform;
import org.polyfrost.oneconfig.utils.v1.TableHelper;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
Expand All @@ -49,10 +54,40 @@ public final class EventManager {
private final Deque<EventCollector> collectors = new ArrayDeque<>(2);
private final Map<Object, List<EventHandler<?>>> cache = new WeakHashMap<>(5);
private final Map<Class<? extends Event>, List<EventHandler<?>>> handlers = new HashMap<>(8);

@ApiStatus.Internal
@Nullable
public static final List<EventHandler<?>> devUnregistered;

static {
if (Platform.loader().isDevelopment()) {
devUnregistered = new ArrayList<>(5);
} else devUnregistered = null;
}

private EventManager() {
registerCollector(new AnnotationEventMapper());
if (Platform.loader().isDevelopment()) {
register(EventHandler.of(InitializationEvent.class, () -> {
if (devUnregistered != null && !devUnregistered.isEmpty()) {
LOGGER.warn("Found {} handlers that were created but not registered: ", devUnregistered.size());
for (EventHandler<?> handler : devUnregistered) {
LOGGER.warn(handler);
}
}
if (!handlers.isEmpty()) {
String[] classes = new String[handlers.size() + 1];
String[] handles = new String[handlers.size() + 1];
classes[0] = "Event Class";
handles[0] = "Handlers";
int i = 1;
for (Map.Entry<Class<? extends Event>, List<EventHandler<?>>> entry : handlers.entrySet()) {
handles[i] = String.valueOf(entry.getValue().size());
classes[i++] = entry.getKey().getName().replace("org.polyfrost.oneconfig.api.event.v1.events.", "builtin.");
}
LOGGER.info(TableHelper.makeTableFromColumns("Registered Event Handlers:", classes, handles));
}
}));
}
}

/**
Expand Down Expand Up @@ -113,6 +148,10 @@ public final void register(EventHandler<? extends Event>... handlers) {
* @param handler The handler to register.
*/
public void register(EventHandler<?> handler) {
if (devUnregistered != null) {
devUnregistered.remove(handler);
}

List<EventHandler<?>> handles = handlers.computeIfAbsent(handler.getEventClass(), k -> new CopyOnWriteArrayList<>());
if (handles.isEmpty()) {
handles.add(handler);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@ public abstract class EventHandler<E extends Event> implements Comparable<EventH
public static final byte ERROR_THRESHOLD = 10;
private byte errors = 0;

public EventHandler() {
if (EventManager.devUnregistered != null) {
EventManager.devUnregistered.add(this);
}
}

/**
* Create an event handler from a consumer, in a fabric-style way.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ import kotlin.experimental.ExperimentalTypeInference
* ```
* eventHandler { event: KeyInputEvent ->
* println("Key event: $event")
* }.register()
* }
* ```
*/
@OverloadResolutionByLambdaReturnType
Expand All @@ -49,15 +49,15 @@ inline fun <reified E : Event> eventHandler(crossinline handler: (E) -> Boolean)
override fun handle(event: E) = handler(event)

override fun getEventClass() = E::class.java
}
}.register()

/**
* Kotlin specific API for registering of event handlers. Intended usage:
*
* ```
* eventHandler { event: KeyInputEvent ->
* println("Key event: $event")
* }.register()
* }
* ```
*/
@OverloadResolutionByLambdaReturnType
Expand All @@ -69,7 +69,7 @@ inline fun <reified E : Event> eventHandler(crossinline handler: (E) -> Unit) =
}

override fun getEventClass() = E::class.java
}
}.register()

/** makes code colored!! */
@DslMarker
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ object HudManager {
val size = Vec2(if (sizeFile.exists()) sizeFile.readText().toLongOrNull() ?: 0L else 0L)
val prevSize: Vec2
if (size.isPositive) {
LOGGER.info("Size to restore: $size")
LOGGER.info("Found a size to restore: $size")
prevSize = polyUI.size
polyUI.resize(size.x, size.y)
} else {
Expand All @@ -138,6 +138,7 @@ object HudManager {
// }
val loader = HudManager::class.java.classLoader
val used = HashSet<Class<Hud<*>>>(hudProviders.size)
val failed = HashMap<String, Int>(8)
var i = 0
ConfigManager.active().gatherAll("huds").forEach { data ->
try {
Expand All @@ -156,13 +157,18 @@ object HudManager {
theHud.y = y - (hud.get().y - theHud.y)
i++
} catch (e: ClassNotFoundException) {
LOGGER.warn("Didn't load HUD from ${data.id} as it's provider (${e.message?.substringAfter(':')}) wasn't found, was the mod removed?")
val cls = e.message?.substringAfter(':') ?: "unknown"
failed[cls] = failed.getOrDefault(cls, 0) + 1
} catch (e: Exception) {
LOGGER.error("Failed to load HUD from ${data.id}", e)
}
}
if (failed.isNotEmpty()) {
LOGGER.warn("Failed to load HUDs from ${failed.size} providers as they weren't found: (maybe the mods were removed?)")
failed.forEach { (cls, amount) -> LOGGER.warn(" $cls: $amount HUDs") }
}
if (prevSize.isPositive) polyUI.resize(prevSize.x, prevSize.y)
LOGGER.info("successfully loaded {} HUDs from {} providers", i, hudProviders.size)
LOGGER.info("successfully loaded {} HUDs from {} providers (total {} registered providers)", i, used.size, hudProviders.size)
hudProviders.forEach { (cls, h) ->
if (cls in used) return@forEach
val default = h.defaultPosition()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,10 @@ object OneConfigUI {
size = Vec2(54f, 18f),
).setPalette { brand.fg }

fun invalidateCache() {
window = null
}


private val sidebarBtnAlign = Align(pad = Vec2(16f, 6f))

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ private OCPolyUIBuilder() {
Settings s = getSettings();
s.enableInitCleanup(false);
s.enableForceSettingInitialSize(true);
s.enableDebugMode(Platform.loader().isDevelopmentEnvironment());
s.enableDebugMode(Platform.loader().isDevelopment());
}

public OCPolyUIBuilder onClose(Consumer<PolyUI> onClose) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,16 @@ object KeybindManager {
eventHandler { (key, char, state): KeyInputEvent ->
if (state == 2) return@eventHandler
translateKey(inputManager, key, char, state == 1)
}.register()
}
eventHandler { _: TickEvent.End ->
keyBinder.update(50_000L, inputManager.mods, true)
}.register()
}

// asm: this is an old fix which will be kept so that in the (rare) event that the keybind system fails for whatever reason,
// the user can try to fix it by opening a screen and trying again, and it should fix the issue.
eventHandler { (screen): ScreenOpenEvent ->
if (screen == null) keyBinder.release()
}.register()
}

val m = Int2IntMap(8)
m[UKeyboard.KEY_LSHIFT] = KeyModifiers.LSHIFT.value.toInt()
Expand Down Expand Up @@ -117,8 +120,8 @@ object KeybindManager {
if (character != '\u0000' && !character.isISOControl() && character.isDefined()) {
if (state) {
inputManager.keyTyped(character)
inputManager.keyDown(character.code)
} else inputManager.keyUp(character.code)
inputManager.keyDown(character.lowercaseChar().code)
} else inputManager.keyUp(character.lowercaseChar().code)
return
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,10 @@ default String getLoaderString() {
return sb.toString();
}

boolean isDevelopmentEnvironment();
/**
* @return true if the current instance is in development mode.
*/
boolean isDevelopment();

Loaders getLoader();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ public static Set<LoaderPlatform.ActiveMod> identifyFromClass(Class<?> clazz) {
String s = uri.toString();
uri = new URL(s.substring(4, s.lastIndexOf("!"))).toURI();
}
if (uri.toString().endsWith(".class") && Platform.loader().isDevelopmentEnvironment()) {
if (uri.toString().endsWith(".class") && Platform.loader().isDevelopment()) {
LOGGER.error("The mod you are currently developing caused this issue, or another class file. Returning 'this'.");
LOGGER.error("Class: {}", clazz.getName());
return Collections.singleton(new LoaderPlatform.ActiveMod("this", "this", "Unknown", null));
Expand All @@ -208,7 +208,7 @@ public static Set<LoaderPlatform.ActiveMod> identifyFromClass(Class<?> clazz) {
private static Set<LoaderPlatform.ActiveMod> getModsAt(Path path, List<LoaderPlatform.ActiveMod> modMap) {
Set<LoaderPlatform.ActiveMod> mods = modMap.stream().filter(m -> m.source.equals(path)).collect(Collectors.toSet());
if (!mods.isEmpty()) return mods;
else if (Platform.loader().isDevelopmentEnvironment()) {
else if (Platform.loader().isDevelopment()) {
// For some reason, in dev, the mod being tested has the 'resources' folder as the origin instead of the 'classes' folder.
String resourcesPathString = path.toString().replace("\\", "/")
// Make it work with Architectury as well
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package org.polyfrost.oneconfig.utils.v1;

public final class TableHelper {
public static String makeTableFromRows(String message, String[]... rows) {
int[] widths = new int[rows[0].length];
for (String[] row : rows) {
for (int i = 0; i < row.length; i++) {
widths[i] = Math.max(widths[i], row[i].length());
}
}
int maxSize = 1;
for (int width : widths) {
maxSize += width + 3;
}
int cap = message.length() + maxSize * (rows.length + 4);
StringBuilder sb = new StringBuilder(cap);
sb.append(message).append('\n');

for (int i = 0; i < maxSize; i++) {
sb.append('-');
}
sb.append('\n');
boolean first = true;
for (String[] row : rows) {
sb.append("| ");
for (int i = 0; i < row.length; i++) {
sb.append(row[i]);
for (int j = 0; j < widths[i] - row[i].length(); j++) {
sb.append(' ');
}
sb.append(" | ");
}
sb.append('\n');
if (first) {
for (int i = 0; i < maxSize; i++) {
sb.append('-');
}
sb.append('\n');
first = false;
}
}
for (int i = 0; i < maxSize; i++) {
sb.append('-');
}

return sb.toString();
}

public static String makeTableFromColumns(String message, String[]... columns) {
String[][] rows = new String[columns[0].length][columns.length];
for (int i = 0; i < columns.length; i++) {
for (int j = 0; j < columns[i].length; j++) {
rows[j][i] = columns[i][j];
}
}
return makeTableFromRows(message, rows);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
* Various utilities for wrapping and unboxing of arrays, lists, etc.
* see {@link ArrayCastUtils} for some more info.
*/
public class WrappingUtils {
public final class WrappingUtils {
private static final Map<Class<?>, Class<?>> prim2Wrapper;
private static final Map<Class<?>, Class<?>> wrapper2Prim;

Expand Down
2 changes: 1 addition & 1 deletion settings.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ rootProject.name = name
if (rootDir.name != name) {
logger.error("""
Root directory name (${rootDir.absolutePath}) does not match project name ($name)!
This may cause issues with indexing and other tools (see https://youtrack.jetbrains.com/issue/IDEA-317606/Changing-only-the-case-of-the-Gradle-root-project-name-causes-exception-while-importing-project-java.lang.IllegalStateException#focus=Comments-27-7257761.0-0 and https://stackoverflow.com/questions/77878944/what-to-do-when-the-java-lang-illegalsateexception-module-entity-with-name ).
This may cause issues with indexing and other tools (see https://youtrack.jetbrains.com/issue/IDEA-317606#focus=Comments-27-7257761.0-0 and https://stackoverflow.com/questions/77878944 ).
If you are experiencing issues, please rename the root directory to match the project name, re-import the project, and invalidate caches if you are on IntelliJ.
""".trimIndent())
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,24 +24,22 @@
* <https://polyfrost.org/legal/oneconfig/additional-terms>
*/

package org.polyfrost.oneconfig.internal.mixin;
package org.polyfrost.oneconfig.internal.mixin.commands;

//#if MC <= 1.13 && FABRIC
//$$ import net.minecraft.client.gui.screen.Screen;
//$$ import org.spongepowered.asm.mixin.Mixin;
//$$ import org.spongepowered.asm.mixin.injection.At;
//$$ import org.spongepowered.asm.mixin.injection.Inject;
//$$ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
//$$
//$$ @Mixin(Screen.class)
//$$ public abstract class Mixin_ExecuteCommandsFromScreen {
//$$
//$$ @Inject(method = "sendMessage(Ljava/lang/String;Z)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/player/ClientPlayerEntity;sendChatMessage(Ljava/lang/String;)V"), cancellable = true)
//$$ private void commands$execute(String text, boolean toHud, CallbackInfo ci) {
//$$ if (org.polyfrost.oneconfig.api.commands.v1.internal.ClientCommandHandler.instance.execute(net.minecraft.client.MinecraftClient.getInstance().player, text) != 0) {
//$$ ci.cancel();
//$$ }
//$$ }
//$$
//$$ }
//#endif
import net.minecraft.client.gui.screen.Screen;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

@Mixin(Screen.class)
public abstract class Mixin_ExecuteCommandsFromScreen {

@Inject(method = "sendMessage(Ljava/lang/String;Z)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/player/ClientPlayerEntity;sendChatMessage(Ljava/lang/String;)V"), cancellable = true)
private void commands$execute(String text, boolean toHud, CallbackInfo ci) {
if (org.polyfrost.oneconfig.api.commands.v1.internal.ClientCommandHandler.instance.execute(net.minecraft.client.MinecraftClient.getInstance().player, text) != 0) {
ci.cancel();
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public int getMinecraftVersion() {
//#endif

@Override
public boolean isDevelopmentEnvironment() {
public boolean isDevelopment() {
//#if FORGE && MC<11300
return isDev;
//#elseif FABRIC
Expand Down
Loading

0 comments on commit c5409f9

Please sign in to comment.