Skip to content

Commit

Permalink
Merge pull request #57 from Over-Run/str-template
Browse files Browse the repository at this point in the history
  • Loading branch information
squid233 authored Aug 20, 2024
2 parents e79f1b3 + 3bd946b commit 9434519
Show file tree
Hide file tree
Showing 12 changed files with 84 additions and 65 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public final class RuntimeHelper {
*/
private static final Linker LINKER = Linker.nativeLinker();
private static final Path tmpdir = Path.of(System.getProperty("java.io.tmpdir"))
.resolve(STR."overrungl\{System.getProperty("user.name")}");
.resolve("overrungl" + System.getProperty("user.name"));
private static final StackWalker STACK_WALKER = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
private static final Map<String, MemoryLayout> CANONICAL_LAYOUTS = LINKER.canonicalLayouts();
/**
Expand All @@ -65,7 +65,8 @@ private RuntimeHelper() {
* Generates a string for unknown token.
*
* @param token the token.
* @return the string formatted in {@code Unknown [0x\{toHexString(token)}]}.
* @return the string formatted in {@code Unknown [0xHex(token)]}.
* @see #unknownToken(String, int)
*/
public static String unknownToken(int token) {
return unknownToken("Unknown", token);
Expand All @@ -76,10 +77,10 @@ public static String unknownToken(int token) {
*
* @param description the description. default to {@code Unknown}
* @param token the token.
* @return the string is formatted in {@code STR."\{description} [0x\{toHexString(token)}]"}.
* @return the string is formatted in {@code description [0xHex(token)]}.
*/
public static String unknownToken(String description, int token) {
return STR."\{description} [0x\{Integer.toHexString(token)}]";
return description + " [0x" + Integer.toHexString(token) + "]";
}

/**
Expand Down Expand Up @@ -114,22 +115,22 @@ public static SymbolLookup load(String module, String basename, String version)
Files.createDirectories(tmpdir);
}
} catch (IOException e) {
throw new IllegalStateException(STR."Couldn't create directory: \{tmpdir}; try setting -Doverrungl.natives to a valid path", e);
throw new IllegalStateException("Couldn't create directory: " + tmpdir + "; try setting -Doverrungl.natives to a valid path", e);
}
var libFile = tmpdir.resolve(STR."\{basename}-\{version}\{suffix}");
var libFile = tmpdir.resolve(basename + "-" + version + suffix);
if (!Files.exists(libFile)) {
// Extract
final String fromPath = STR."\{module}/\{os.familyName()}-\{Architecture.current()}/\{path}";
final String fromPath = module + "/" + os.familyName() + "-" + Architecture.current() + "/" + path;
try (var is = STACK_WALKER.getCallerClass().getClassLoader().getResourceAsStream(fromPath)) {
Files.copy(Objects.requireNonNull(is, STR."File not found in classpath: \{fromPath}"), libFile);
Files.copy(Objects.requireNonNull(is, "File not found in classpath: " + fromPath), libFile);
} catch (Exception e) {
throw new IllegalStateException(STR."Couldn't load file: \{libFile} or \{localFile}; try setting -Doverrungl.natives to a valid path", e);
throw new IllegalStateException("Couldn't load file: " + libFile + " or " + localFile + "; try setting -Doverrungl.natives to a valid path", e);
}
}
uri = libFile;
}
if (Configurations.DEBUG.get()) {
OverrunGL.apiLog(STR."[OverrunGL] Loading native library from: \{uri}");
OverrunGL.apiLog("[OverrunGL] Loading native library from: " + uri);
}
// Load the library by the path with the global arena
return SymbolLookup.libraryLookup(uri, Arena.global());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,16 +44,15 @@ final class DebugAllocator {
for (Allocation allocation : ALLOCATIONS.keySet()) {
StringBuilder sb = new StringBuilder(512);

sb.append(STR."""
[OverrunGL] \{allocation.size} bytes leaked,\
thread \{allocation.threadId} (\{THREADS.get(allocation.threadId)}),\
address: 0x\{Long.toHexString(allocation.address).toUpperCase()}
""");
sb.append("[OverrunGL] ").append(allocation.size).append(" bytes leaked, thread ")
.append(allocation.threadId).append(" (").append(THREADS.get(allocation.threadId)).append("), address: 0x")
.append(Long.toHexString(allocation.address).toUpperCase())
.append("\n");

StackTraceElement[] stackTrace = allocation.getElements();
if (stackTrace != null) {
for (Object el : stackTrace) {
sb.append(STR."\tat \{el.toString()}\n");
sb.append(" at ").append(el.toString()).append("\n");
}
} else {
missingStacktrace = true;
Expand Down Expand Up @@ -98,22 +97,21 @@ private static void trackAbort(long address, Allocation allocationOld, Allocatio
trackAbortPrint(allocationOld, "Old", addressHex);
trackAbortPrint(allocationNew, "New", addressHex);

throw new IllegalStateException(STR."The memory address specified is already being tracked: 0x\{addressHex}");
throw new IllegalStateException("The memory address specified is already being tracked: 0x" + addressHex);
}

private static void trackAbortPrint(Allocation allocation, String name, String address) {
StringBuilder sb = new StringBuilder(512);

sb.append(STR."""
[OverrunGL] \{name} allocation with size \{allocation.size},\
thread \{allocation.threadId} (\{THREADS.get(allocation.threadId)}),\
address: 0x\{address}
""");
sb.append("[OverrunGL] ").append(name).append(" allocation with size ").append(allocation.size)
.append(", thread ").append(allocation.threadId).append(" (").append(THREADS.get(allocation.threadId)).append("), address: 0x")
.append(address)
.append("\n");

StackTraceElement[] stackTrace = allocation.getElements();
if (stackTrace != null) {
for (Object el : stackTrace) {
sb.append(STR."\tat \{el.toString()}\n");
sb.append(" at ").append(el.toString()).append("\n");
}
}

Expand All @@ -137,7 +135,7 @@ static long untrack(long address) {
private static void untrackAbort(long address) {
String addressHex = Long.toHexString(address).toUpperCase();

throw new IllegalStateException(STR."The memory address specified is not being tracked: 0x\{addressHex}");
throw new IllegalStateException("The memory address specified is not being tracked: 0x" + addressHex);
}

private record Allocation(long address, long size, long threadId, @Nullable Object[] stacktrace) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ private GLFWErrorCallback() {
*/
public static GLFWErrorFun createThrow() {
return (errorCode, description) -> {
throw new IllegalStateException(STR."GLFW error [0x\{Integer.toHexString(errorCode)}]: \{description}");
throw new IllegalStateException("GLFW error [0x" + Integer.toHexString(errorCode) + "]: " + description);
};
}

Expand All @@ -49,10 +49,10 @@ public static GLFWErrorFun createThrow() {
public static GLFWErrorFun createLog(Consumer<String> logger) {
return (errorCode, description) -> {
var sb = new StringBuilder(512);
sb.append(STR."[OverrunGL] GLFW \{GLFW.getErrorString(errorCode)} error: \{description}\n");
sb.append("[OverrunGL] GLFW ").append(GLFW.getErrorString(errorCode)).append(" error: ").append(description).append("\n");
var stack = Thread.currentThread().getStackTrace();
for (int i = 3; i < stack.length; i++) {
sb.append(STR." at \{stack[i]}\n");
sb.append(" at ").append(stack[i]).append("\n");
}
logger.accept(sb.toString());
};
Expand Down
4 changes: 2 additions & 2 deletions modules/overrungl.nfd/src/main/java/overrungl/nfd/NFD.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@
* new Pair<>("Image file", "png,jpg"));
* var result = nfd.openDialogN(outPath, filterItem, null);
* switch (result) {
* case ERROR -> System.err.println(STR."Error: \{nfd.getError()}");
* case OKAY -> System.out.println(STR."Success! \{outPath[0]}");
* case ERROR -> System.err.println("Error: " + nfd.getError());
* case OKAY -> System.out.println("Success! " + outPath[0]);
* case CANCEL -> System.out.println("User pressed cancel.");
* }
* }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ public static Tuple2<NFDResult, NFDEnumerator> fromPathSetU8(SegmentAllocator al
}

private static IllegalStateException errorIterating(NFD nfd) {
return new IllegalStateException(STR."Error iterating: \{nfd.getError()}");
return new IllegalStateException("Error iterating: " + nfd.getError());
}

@NotNull
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public static NFDResult of(int i) {
case 0 -> ERROR;
case 1 -> OKAY;
case 2 -> CANCEL;
default -> throw new IllegalArgumentException(STR."Unexpected value: \{i}");
default -> throw new IllegalArgumentException("Unexpected value: " + i);
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,14 +99,14 @@ Arena setupDebugMessageCallback(
gl.debugMessageCallback(arena, (source, type, id, severity, message, _) -> {
var sb = new StringBuilder(768);
sb.append("[OverrunGL] OpenGL debug message\n");
printDetail(sb, "ID", STR."0x\{Integer.toHexString(id).toUpperCase(Locale.ROOT)}");
printDetail(sb, "ID", "0x" + Integer.toHexString(id).toUpperCase(Locale.ROOT));
printDetail(sb, "Source", getDebugSource(source));
printDetail(sb, "Type", getDebugType(type));
printDetail(sb, "Severity", getDebugSeverity(severity));
printDetail(sb, "Message", message);
var stack = Thread.currentThread().getStackTrace();
for (int i = 3; i < stack.length; i++) {
sb.append(STR." at \{stack[i]}\n");
sb.append(" at ").append(stack[i]).append("\n");
}
logger.accept(sb.toString());
}, MemorySegment.NULL);
Expand All @@ -125,14 +125,14 @@ Arena setupDebugMessageCallback(
fallbackARB.get().glDebugMessageCallbackARB(arena, (source, type, id, severity, message, _) -> {
var sb = new StringBuilder(768);
sb.append("[OverrunGL] ARB_debug_output message\n");
printDetail(sb, "ID", STR."0x\{Integer.toHexString(id).toUpperCase(Locale.ROOT)}");
printDetail(sb, "ID", "0x" + Integer.toHexString(id).toUpperCase(Locale.ROOT));
printDetail(sb, "Source", getSourceARB(source));
printDetail(sb, "Type", getTypeARB(type));
printDetail(sb, "Severity", getSeverityARB(severity));
printDetail(sb, "Message", message);
var stack = Thread.currentThread().getStackTrace();
for (int i = 3; i < stack.length; i++) {
sb.append(STR." at \{stack[i]}\n");
sb.append(" at ").append(stack[i]).append("\n");
}
logger.accept(sb.toString());
}, MemorySegment.NULL);
Expand All @@ -145,13 +145,13 @@ Arena setupDebugMessageCallback(
fallbackAMD.get().glDebugMessageCallbackAMD(arena, (id, category, severity, message, _) -> {
var sb = new StringBuilder(768);
sb.append("[OverrunGL] AMD_debug_output message\n");
printDetail(sb, "ID", STR."0x\{Integer.toHexString(id).toUpperCase(Locale.ROOT)}");
printDetail(sb, "ID", "0x" + Integer.toHexString(id).toUpperCase(Locale.ROOT));
printDetail(sb, "Category", getCategoryAMD(category));
printDetail(sb, "Severity", getSeverityAMD(severity));
printDetail(sb, "Message", message);
var stack = Thread.currentThread().getStackTrace();
for (int i = 3; i < stack.length; i++) {
sb.append(STR." at \{stack[i]}\n");
sb.append(" at ").append(stack[i]).append("\n");
}
logger.accept(sb.toString());
}, MemorySegment.NULL);
Expand All @@ -163,7 +163,7 @@ Arena setupDebugMessageCallback(
}

private static void printDetail(StringBuilder sb, String type, String message) {
sb.append(STR." \{type}: \{message}\n");
sb.append(" ").append(type).append(": ").append(message).append("\n");
}

private static String getDebugSource(int source) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,9 @@ private void init() {
case GLFW.CONNECTED -> {
boolean isGamepad = glfw.joystickIsGamepad(jid);
var prefix = isGamepad ? "Gamepad " : "Joystick ";
System.out.println(STR."\{prefix}\{jid}: \"\{(isGamepad ? glfw.getGamepadName(jid) : glfw.getJoystickName(jid))}\" has connected");
System.out.println(prefix + jid + ": \"" + (isGamepad ? glfw.getGamepadName(jid) : glfw.getJoystickName(jid)) + "\" has connected");
}
case GLFW.DISCONNECTED -> System.out.println(STR."Joystick \{jid} has disconnected");
case GLFW.DISCONNECTED -> System.out.println("Joystick " + jid + " has disconnected");
}
});

Expand All @@ -86,14 +86,37 @@ private void loop() {
if (glfw.joystickIsGamepad(i)) {
var state = states[i];
if (glfw.getGamepadState(i, state)) {
System.out.println(STR."""
Get gamepad state for [jid=\{i},name=\{glfw.getGamepadName(i)}] successful:
Buttons: [A(Cross)=\{state.button(GLFW.GAMEPAD_BUTTON_A)}, B(Circle)=\{state.button(GLFW.GAMEPAD_BUTTON_B)}, X(Square)=\{state.button(GLFW.GAMEPAD_BUTTON_X)}, Y(Triangle)=\{state.button(GLFW.GAMEPAD_BUTTON_Y)},
Left bumper=\{state.button(GLFW.GAMEPAD_BUTTON_LEFT_BUMPER)}, Right bumper=\{state.button(GLFW.GAMEPAD_BUTTON_RIGHT_BUMPER)}, Back=\{state.button(GLFW.GAMEPAD_BUTTON_BACK)}, Start=\{state.button(GLFW.GAMEPAD_BUTTON_START)},
Guide=\{state.button(GLFW.GAMEPAD_BUTTON_GUIDE)}, Left thumb=\{state.button(GLFW.GAMEPAD_BUTTON_LEFT_THUMB)}, Right thumb=\{state.button(GLFW.GAMEPAD_BUTTON_RIGHT_THUMB)},
DPAD(up=\{state.button(GLFW.GAMEPAD_BUTTON_DPAD_UP)}, right=\{state.button(GLFW.GAMEPAD_BUTTON_DPAD_RIGHT)}, down=\{state.button(GLFW.GAMEPAD_BUTTON_DPAD_DOWN)}, left=\{state.button(GLFW.GAMEPAD_BUTTON_DPAD_LEFT)})],
Axis: [Left(x=\{state.axe(GLFW.GAMEPAD_AXIS_LEFT_X)}, y=\{state.axe(GLFW.GAMEPAD_AXIS_LEFT_Y)}), Right(x=\{state.axe(GLFW.GAMEPAD_AXIS_RIGHT_X)}, y=\{state.axe(GLFW.GAMEPAD_AXIS_RIGHT_Y)}), Trigger(left=\{state.axe(GLFW.GAMEPAD_AXIS_LEFT_TRIGGER)}, right\{state.axe(GLFW.GAMEPAD_AXIS_RIGHT_TRIGGER)})]
""");
System.out.printf("""
Get gamepad state for [jid=%d,name=%s] successful:
Buttons: [A(Cross)=%s, B(Circle)=%s, X(Square)=%s, Y(Triangle)=%s,
Left bumper=%s, Right bumper=%s, Back=%s, Start=%s,
Guide=%s, Left thumb=%s, Right thumb=%s,
DPAD(up=%s, right=%s, down=%s, left=%s)],
Axis: [Left(x=%s, y=%s), Right(x=%s, y=%s), Trigger(left=%s, right%s)]
%n""",
i,
glfw.getGamepadName(i),
state.button(GLFW.GAMEPAD_BUTTON_A),
state.button(GLFW.GAMEPAD_BUTTON_B),
state.button(GLFW.GAMEPAD_BUTTON_X),
state.button(GLFW.GAMEPAD_BUTTON_Y),
state.button(GLFW.GAMEPAD_BUTTON_LEFT_BUMPER),
state.button(GLFW.GAMEPAD_BUTTON_RIGHT_BUMPER),
state.button(GLFW.GAMEPAD_BUTTON_BACK),
state.button(GLFW.GAMEPAD_BUTTON_START),
state.button(GLFW.GAMEPAD_BUTTON_GUIDE),
state.button(GLFW.GAMEPAD_BUTTON_LEFT_THUMB),
state.button(GLFW.GAMEPAD_BUTTON_RIGHT_THUMB),
state.button(GLFW.GAMEPAD_BUTTON_DPAD_UP),
state.button(GLFW.GAMEPAD_BUTTON_DPAD_RIGHT),
state.button(GLFW.GAMEPAD_BUTTON_DPAD_DOWN),
state.button(GLFW.GAMEPAD_BUTTON_DPAD_LEFT),
state.axe(GLFW.GAMEPAD_AXIS_LEFT_X),
state.axe(GLFW.GAMEPAD_AXIS_LEFT_Y),
state.axe(GLFW.GAMEPAD_AXIS_RIGHT_X),
state.axe(GLFW.GAMEPAD_AXIS_RIGHT_Y),
state.axe(GLFW.GAMEPAD_AXIS_LEFT_TRIGGER),
state.axe(GLFW.GAMEPAD_AXIS_RIGHT_TRIGGER));
}
}
}
Expand Down
Loading

0 comments on commit 9434519

Please sign in to comment.