Skip to content

Commit

Permalink
Use Optionals instead of null return values
Browse files Browse the repository at this point in the history
  • Loading branch information
bwRavencl committed Oct 10, 2024
1 parent 54d7c01 commit a70f403
Show file tree
Hide file tree
Showing 12 changed files with 140 additions and 147 deletions.
36 changes: 20 additions & 16 deletions src/main/java/de/bwravencl/controllerbuddy/gui/GuiUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.Optional;
import java.util.prefs.Preferences;
import java.util.stream.Collectors;
import javax.swing.AbstractAction;
Expand Down Expand Up @@ -91,10 +92,10 @@ static Rectangle getAndStoreTotalDisplayBounds(final Main main) {
return totalDisplayBounds;
}

private static String getFrameLocationPreferencesKey(final JFrame frame) {
private static Optional<String> getFrameLocationPreferencesKey(final JFrame frame) {
final var title = frame.getTitle();
if (title == null || title.isBlank()) {
return null;
return Optional.empty();
}

var underscoreTitle = title.codePoints().mapToObj(c -> {
Expand All @@ -105,7 +106,7 @@ private static String getFrameLocationPreferencesKey(final JFrame frame) {
}).collect(Collectors.joining());
underscoreTitle = underscoreTitle.startsWith("_") ? underscoreTitle.substring(1) : underscoreTitle;

return underscoreTitle + "_location";
return Optional.of(underscoreTitle + "_location");
}

static Rectangle getTotalDisplayBounds() {
Expand All @@ -124,19 +125,21 @@ static void loadFrameLocation(final Preferences preferences, final JFrame frame,
final Rectangle totalDisplayBounds) {
final var location = new Point(defaultLocation);

final var locationString = preferences.get(getFrameLocationPreferencesKey(frame), null);
if (locationString != null) {
final var parts = locationString.split(",", -1);

if (parts.length == 2) {
try {
location.x = Math.round(Float.parseFloat(parts[0]) * totalDisplayBounds.width);
location.y = Math.round(Float.parseFloat(parts[1]) * totalDisplayBounds.height);
} catch (final NumberFormatException _) {
// ignore an invalid location string that does not contain numeric values
getFrameLocationPreferencesKey(frame).ifPresent(preferencesKey -> {
final var locationString = preferences.get(preferencesKey, null);
if (locationString != null) {
final var parts = locationString.split(",", -1);

if (parts.length == 2) {
try {
location.x = Math.round(Float.parseFloat(parts[0]) * totalDisplayBounds.width);
location.y = Math.round(Float.parseFloat(parts[1]) * totalDisplayBounds.height);
} catch (final NumberFormatException _) {
// ignore an invalid location string that does not contain numeric values
}
}
}
}
});

setFrameLocationRespectingBounds(frame, location, totalDisplayBounds);
}
Expand Down Expand Up @@ -233,9 +236,10 @@ public void mouseReleased(final MouseEvent e) {

final var frameLocation = frame.getLocation();
final var totalDisplayBounds = getAndStoreTotalDisplayBounds(main);
main.getPreferences().put(getFrameLocationPreferencesKey(frame),

getFrameLocationPreferencesKey(frame).ifPresent(preferencesKey -> main.getPreferences().put(preferencesKey,
frameLocation.x / (float) totalDisplayBounds.width + ","
+ frameLocation.y / (float) totalDisplayBounds.height);
+ frameLocation.y / (float) totalDisplayBounds.height));
}
}
}
83 changes: 43 additions & 40 deletions src/main/java/de/bwravencl/controllerbuddy/gui/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.Scanner;
import java.util.Set;
Expand Down Expand Up @@ -957,8 +958,8 @@ public void windowOpened(final WindowEvent e) {
Configuration.GLFW_LIBRARY_NAME.set("glfw_async");
}

final var glfwInitialized = taskRunner.run(GLFW::glfwInit);
if (Boolean.FALSE.equals(glfwInitialized)) {
final var glfwInitialized = (boolean) taskRunner.run(GLFW::glfwInit).orElse(false);
if (!glfwInitialized) {
log.log(Level.SEVERE, "Could not initialize GLFW");

if (isWindows || isLinux) {
Expand Down Expand Up @@ -1003,41 +1004,41 @@ public void windowOpened(final WindowEvent e) {
strings.getString("ERROR_DIALOG_TITLE"), JOptionPane.ERROR_MESSAGE);
}

final var presentControllers = taskRunner.run(Main::getPresentControllers);
if (presentControllers != null && !presentControllers.isEmpty()) {
log.log(Level.INFO,
"Present controllers:" + presentControllers.stream()
.map(controllerInfo -> assembleControllerLoggingMessage("\n\t", controllerInfo))
.collect(Collectors.joining()));

final var lastControllerGuid = preferences.get(PREFERENCES_LAST_CONTROLLER, null);
if (lastControllerGuid != null) {
presentControllers.stream().filter(controller -> lastControllerGuid.equals(controller.guid)).findFirst()
.ifPresentOrElse(controller -> {
log.log(Level.INFO,
assembleControllerLoggingMessage("Found previously used controller ", controller));
setSelectedController(controller);
}, () -> {
log.log(Level.INFO, "Previously used controller is not present");
setSelectedController(presentControllers.getFirst());
});
final var optionalPresentControllers = taskRunner.run(Main::getPresentControllers);

optionalPresentControllers.ifPresent(presentControllers -> {
if (!presentControllers.isEmpty()) {
log.log(Level.INFO,
"Present controllers:" + presentControllers.stream()
.map(controllerInfo -> assembleControllerLoggingMessage("\n\t", controllerInfo))
.collect(Collectors.joining()));

final var lastControllerGuid = preferences.get(PREFERENCES_LAST_CONTROLLER, null);
if (lastControllerGuid != null) {
presentControllers.stream().filter(controller -> lastControllerGuid.equals(controller.guid))
.findFirst().ifPresentOrElse(controller -> {
log.log(Level.INFO, assembleControllerLoggingMessage(
"Found previously used controller ", controller));
setSelectedController(controller);
}, () -> {
log.log(Level.INFO, "Previously used controller is not present");
setSelectedController(presentControllers.getFirst());
});
}
}
}
});

newProfile(false);

updateTheme();

if (presentControllers != null) {
onControllersChanged(presentControllers, true);
}
optionalPresentControllers.ifPresent(presentControllers -> onControllersChanged(presentControllers, true));

// noinspection resource
taskRunner.run(() -> GLFW.glfwSetJoystickCallback((jid, event) -> {
final var disconnected = event == GLFW.GLFW_DISCONNECTED;
if (disconnected || GLFW.glfwJoystickIsGamepad(jid)) {
if (disconnected && presentControllers != null
&& presentControllers.stream().anyMatch(controller -> controller.jid == jid)) {
if (disconnected && optionalPresentControllers.isPresent()
&& optionalPresentControllers.get().stream().anyMatch(controller -> controller.jid == jid)) {
log.log(Level.INFO,
assembleControllerLoggingMessage("Disconnected controller ", new ControllerInfo(jid)));

Expand All @@ -1056,8 +1057,8 @@ public void windowOpened(final WindowEvent e) {
}
}));

final var noControllerConnected = Boolean.TRUE.equals(glfwInitialized)
&& (presentControllers == null || presentControllers.isEmpty());
final var noControllerConnected = glfwInitialized
&& (optionalPresentControllers.isEmpty() || optionalPresentControllers.get().isEmpty());

if (noControllerConnected && !isSkipControllerDialogs()) {
if (isWindows || isLinux) {
Expand Down Expand Up @@ -1466,6 +1467,14 @@ public <T> T executeWhileVisible(final Callable<T> callable) {
}
}

private void executeWhileVisible(final Runnable runnable) {
executeWhileVisible(() -> {
runnable.run();

return null;
});
}

public void exportVisualization(final File file) {
if (templateSvgDocument == null) {
return;
Expand Down Expand Up @@ -1814,7 +1823,7 @@ private void initOpenVrOverlay() {
}

try {
openVrOverlay = OpenVrOverlay.start(this);
openVrOverlay = OpenVrOverlay.start(this).orElse(null);
} catch (final Throwable t) {
log.log(Level.WARNING, t.getMessage(), t);

Expand Down Expand Up @@ -2806,7 +2815,7 @@ private boolean updateGameControllerMappings(final InputStream is) {

final var content = sb.toString().getBytes(defaultCharset);
final var byteBuffer = ByteBuffer.allocateDirect(content.length).put(content).flip();
mappingsUpdated = Boolean.TRUE.equals(taskRunner.run(() -> GLFW.glfwUpdateGamepadMappings(byteBuffer)));
mappingsUpdated = taskRunner.run(() -> GLFW.glfwUpdateGamepadMappings(byteBuffer)).orElse(false);
} catch (final IOException e) {
log.log(Level.SEVERE, e.getMessage(), e);
}
Expand Down Expand Up @@ -3717,7 +3726,7 @@ private boolean isTaskOfTypeRunning(final Class<?> clazz) {
}

@SuppressWarnings("unchecked")
private <V> V run(final Callable<V> callable) {
private <V> Optional<V> run(final Callable<V> callable) {
waitForTask();

task = callable;
Expand All @@ -3733,12 +3742,12 @@ private <V> V run(final Callable<V> callable) {
throw new RuntimeException(throwable);
}

return (V) result;
return Optional.ofNullable((V) result);
} catch (final InterruptedException _) {
Thread.currentThread().interrupt();
}

return null;
return Optional.empty();
}

private void run(final Runnable runnable) {
Expand Down Expand Up @@ -4027,8 +4036,6 @@ protected void doAction() {
if (profileFileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
loadProfile(profileFileChooser.getSelectedFile(), false, true);
}

return null;
});
}
}
Expand Down Expand Up @@ -4382,8 +4389,6 @@ private void showConnectDialog() {
showConnectDialog();
}
}

return null;
});
}
}
Expand Down Expand Up @@ -4425,8 +4430,6 @@ public void actionPerformed(final ActionEvent e) {
connectionSettingsPanel.saveSettings();
startServer();
}

return null;
});
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import java.io.ObjectOutputStream;
import java.io.Serial;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
Expand Down Expand Up @@ -249,26 +250,22 @@ private static String multilineDisplayName(final String displayName) {
return "<html><center>" + displayName.replaceFirst(" ", "<br>") + "</center></html>";
}

private AbstractKeyboardButton deselectButton() {
final var selectedButton = getSelectedButton();
private Optional<AbstractKeyboardButton> deselectButton() {
final var optionalSelectedButton = getSelectedButton();

if (selectedButton != null) {
optionalSelectedButton.ifPresent(selectedButton -> {
if (selectedButton.pressed) {
selectedButton.release();
}

selectedButton.setFocus(false);
}
});

return selectedButton;
return optionalSelectedButton;
}

private void focusSelectedButton() {
final var selectedButton = getSelectedButton();

if (selectedButton != null) {
selectedButton.setFocus(true);
}
getSelectedButton().ifPresent(selectedButton -> selectedButton.setFocus(true));
}

public void forceRepoll() {
Expand All @@ -281,12 +278,12 @@ public void forceRepoll() {
}
}

private AbstractKeyboardButton getSelectedButton() {
private Optional<AbstractKeyboardButton> getSelectedButton() {
if (keyboardButtons == null) {
return null;
return Optional.empty();
}

return keyboardButtons[selectedRow][selectedColumn];
return Optional.of(keyboardButtons[selectedRow][selectedColumn]);
}

private boolean isKeyboardShifted() {
Expand All @@ -295,7 +292,7 @@ private boolean isKeyboardShifted() {

public void moveSelector(final Direction direction) {
EventQueue.invokeLater(() -> {
final var previousButton = deselectButton();
final var optionalPreviousButton = deselectButton();

switch (direction) {
case UP -> {
Expand All @@ -305,7 +302,7 @@ public void moveSelector(final Direction direction) {
selectedRow = keyboardButtons.length - 1;
}

updateSelectedColumn(previousButton);
optionalPreviousButton.ifPresent(this::updateSelectedColumn);
}
case DOWN -> {
if (selectedRow < keyboardButtons.length - 1) {
Expand All @@ -314,7 +311,7 @@ public void moveSelector(final Direction direction) {
selectedRow = 0;
}

updateSelectedColumn(previousButton);
optionalPreviousButton.ifPresent(this::updateSelectedColumn);
}
case LEFT -> {
if (selectedColumn > 0) {
Expand Down Expand Up @@ -351,11 +348,7 @@ public void poll(@SuppressWarnings("exports") final Input input) {
}

public void pressSelectedButton() {
final var selectedButton = getSelectedButton();

if (selectedButton != null) {
selectedButton.press(false);
}
getSelectedButton().ifPresent(selectedButton -> selectedButton.press(false));
}

@Serial
Expand All @@ -372,11 +365,7 @@ public void releaseAllButtons() {
}

public void releaseSelectedButton() {
final var selectedButton = getSelectedButton();

if (selectedButton != null) {
selectedButton.release();
}
getSelectedButton().ifPresent(AbstractKeyboardButton::release);
}

@Override
Expand All @@ -394,11 +383,7 @@ public void setVisible(final boolean b) {
}

public void toggleLock() {
final var selectedButton = getSelectedButton();

if (selectedButton != null) {
selectedButton.toggleLock();
}
getSelectedButton().ifPresent(AbstractKeyboardButton::toggleLock);
}

void updateLocation() {
Expand Down Expand Up @@ -549,7 +534,7 @@ private void updateTheme() {
BorderFactory.createLineBorder(Color.RED,
Math.round(FOCUSED_BUTTON_BORDER_THICKNESS * main.getOverlayScaling())));

if (this == getSelectedButton()) {
if (this == getSelectedButton().orElse(null)) {
setFocus(true);
}
}
Expand Down
Loading

0 comments on commit a70f403

Please sign in to comment.