file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
Static.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/effects/Static.java
package uk.co.bithatch.snake.lib.effects; import java.util.Arrays; public class Static extends Effect { private int[] color = new int[] { 0, 255, 0 }; public Static() { } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Static other = (Static) obj; if (!Arrays.equals(color, other.color)) return false; return true; } public int[] getColor() { return color; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(color); return result; } public void setColor(int[] color) { this.color = color; } @Override public String toString() { return "Static [color=" + Arrays.toString(color) + "]"; } }
825
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Effect.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/effects/Effect.java
package uk.co.bithatch.snake.lib.effects; public abstract class Effect implements Cloneable { @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
195
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Pulsate.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/effects/Pulsate.java
package uk.co.bithatch.snake.lib.effects; public class Pulsate extends Effect { public Pulsate() { } }
108
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Off.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/effects/Off.java
package uk.co.bithatch.snake.lib.effects; public class Off extends Effect { public Off() { } }
100
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Matrix.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/effects/Matrix.java
package uk.co.bithatch.snake.lib.effects; import java.util.Arrays; public class Matrix extends Effect { private int[][][] cells; public Matrix() { } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Matrix other = (Matrix) obj; if (!Arrays.deepEquals(cells, other.cells)) return false; return true; } public int[] getCell(int row, int col) { if (cells == null || row >= cells.length) return new int[] { 0, 0, 0 }; int[][] rowData = cells[row]; if (rowData == null || col >= rowData.length) return new int[] { 0, 0, 0 }; return rowData[col]; } public int[][][] getCells() { return cells; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.deepHashCode(cells); return result; } public void setCells(int[][][] cells) { this.cells = cells; } @Override public String toString() { return "Matrix [cells=" + Arrays.toString(cells) + "]"; } public void clear() { if (cells != null && cells.length > 0) { cells = new int[cells.length][cells[0].length][3]; } } }
1,205
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
ReleaseMapAction.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/binding/ReleaseMapAction.java
package uk.co.bithatch.snake.lib.binding; import uk.co.bithatch.linuxio.EventCode; import uk.co.bithatch.linuxio.EventCode.Ev; public interface ReleaseMapAction extends MapAction { EventCode getRelease(); void setRelease(EventCode release); default String getValue() { return String.valueOf(getRelease().code()); } @Override default Class<? extends MapAction> getActionType() { return ReleaseMapAction.class; } default void setValue(String value) { setRelease(EventCode.fromCode(Ev.EV_KEY, Integer.parseInt(value))); } }
543
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
ProfileMapAction.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/binding/ProfileMapAction.java
package uk.co.bithatch.snake.lib.binding; public interface ProfileMapAction extends MapAction { String getProfileName(); void setProfileName(String profileName); default String getValue() { return getProfileName(); } @Override default Class<? extends MapAction> getActionType() { return ProfileMapAction.class; } default void setValue(String value) { setProfileName(value); } }
401
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
KeyMapAction.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/binding/KeyMapAction.java
package uk.co.bithatch.snake.lib.binding; import uk.co.bithatch.linuxio.EventCode; public interface KeyMapAction extends MapAction { EventCode getPress(); void setPress(EventCode press); default String getValue() { return String.valueOf(getPress().code()); } @Override default Class<? extends MapAction> getActionType() { return KeyMapAction.class; } default void setValue(String value) { setPress(EventCode.fromCode(EventCode.Ev.EV_KEY, Integer.parseInt(value))); } }
491
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
ProfileMap.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/binding/ProfileMap.java
package uk.co.bithatch.snake.lib.binding; import java.util.Map; import uk.co.bithatch.linuxio.EventCode; import uk.co.bithatch.linuxio.EventCode.Type; import uk.co.bithatch.snake.lib.effects.Matrix; public interface ProfileMap { void setMatrix(Matrix matrix); Matrix getMatrix(); boolean[] getLEDs(); void setLEDs(boolean red, boolean green, boolean blue); default void setLEDs(boolean[] rgb) { setLEDs(rgb[0], rgb[1], rgb[2]); } void record(int keyCode); boolean isActive(); void activate(); Profile getProfile(); String getId(); Map<EventCode, MapSequence> getSequences(); void remove(); void stopRecording(); boolean isRecording(); int getRecordingMacroKey(); boolean isDefault(); void makeDefault(); MapSequence addSequence(EventCode key, boolean addDefault); @SuppressWarnings("resource") default EventCode getNextFreeKey() { for (EventCode code : EventCode.filteredForType(getProfile().getDevice().getSupportedInputEvents(), Type.EV_KEY)) { if (!getSequences().containsKey(code)) return code; } throw new IllegalStateException("No free supported input codes. Please remove an existing mapping."); } }
1,168
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
MapMapAction.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/binding/MapMapAction.java
package uk.co.bithatch.snake.lib.binding; public interface MapMapAction extends MapAction { String getMapName(); void setMapName(String mapName); default String getValue() { return getMapName(); } @Override default Class<? extends MapAction> getActionType() { return MapMapAction.class; } default void setValue(String value) { setMapName(value); } }
374
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
SleepMapAction.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/binding/SleepMapAction.java
package uk.co.bithatch.snake.lib.binding; public interface SleepMapAction extends MapAction { float getSeconds(); void setSeconds(float seconds); default String getValue() { return String.valueOf(getSeconds()); } @Override default Class<? extends MapAction> getActionType() { return SleepMapAction.class; } default void setValue(String value) { setSeconds(Float.parseFloat(value)); } }
408
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
MapAction.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/binding/MapAction.java
package uk.co.bithatch.snake.lib.binding; import uk.co.bithatch.snake.lib.ValidationException; public interface MapAction { void commit(); MapSequence getSequence(); ProfileMap getMap(); int getActionId(); String getValue(); void remove(); void validate() throws ValidationException; <A extends MapAction> A update(Class<A> actionType, Object value); Class<? extends MapAction> getActionType(); void setValue(String value); }
448
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
ShiftMapAction.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/binding/ShiftMapAction.java
package uk.co.bithatch.snake.lib.binding; public interface ShiftMapAction extends MapAction { String getMapName(); void setMapName(String mapName); default String getValue() { return getMapName(); } @Override default Class<? extends MapAction> getActionType() { return ShiftMapAction.class; } default void setValue(String value) { setMapName(value); } }
376
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Profile.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/binding/Profile.java
package uk.co.bithatch.snake.lib.binding; import java.util.List; import uk.co.bithatch.snake.lib.Device; public interface Profile { public interface Listener { void changed(Profile profile); void activeMapChanged(ProfileMap map); void mapAdded(ProfileMap profile); void mapRemoved(ProfileMap profile); void mapChanged(ProfileMap profile); } Device getDevice(); void addListener(Listener listener); void removeListener(Listener listener); void activate(); boolean isActive(); String getName(); ProfileMap getDefaultMap(); void setDefaultMap(ProfileMap map); ProfileMap getActiveMap(); ProfileMap getMap(String id); List<ProfileMap> getMaps(); ProfileMap addMap(String id); void remove(); }
737
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
MapSequence.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/binding/MapSequence.java
package uk.co.bithatch.snake.lib.binding; import java.util.ArrayList; import uk.co.bithatch.linuxio.EventCode; import uk.co.bithatch.snake.lib.ValidationException; @SuppressWarnings("serial") public abstract class MapSequence extends ArrayList<MapAction> { private EventCode key; private ProfileMap map; public MapSequence(ProfileMap map) { this.map = map; } public MapSequence(ProfileMap map, EventCode key) { setMacroKey(key); this.map = map; } public ProfileMap getMap() { return map; } public EventCode getMacroKey() { return key; } public void setMacroKey(EventCode key) { this.key = key; } public abstract <A extends MapAction> A addAction(Class<A> actionType, Object value); public void validate() throws ValidationException { for (MapAction m : this) m.validate(); } public abstract void remove(); public abstract void commit(); public abstract void record(); public abstract boolean isRecording(); public abstract void stopRecording(); public EventCode getLastInputCode() { int idx = size() - 1; while (idx > -1) { MapAction a = get(idx); if (a instanceof KeyMapAction) return ((KeyMapAction) a).getPress(); else if (a instanceof ReleaseMapAction) return ((ReleaseMapAction) a).getRelease(); idx--; } return EventCode.BTN_0; } }
1,322
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
ExecuteMapAction.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/binding/ExecuteMapAction.java
package uk.co.bithatch.snake.lib.binding; import java.util.ArrayList; import java.util.List; public interface ExecuteMapAction extends MapAction { List<String> getArgs(); String getCommand(); void setArgs(List<String> args); void setCommand(String script); @Override default Class<? extends MapAction> getActionType() { return ExecuteMapAction.class; } default void setValue(String value) { List<String> l = ExecuteMapAction.parseQuotedString(value); setCommand(l.isEmpty() ? "" : l.remove(0)); setArgs(l); } default String getValue() { StringBuilder v = new StringBuilder(); v.append(formatArgument(getCommand())); for (String arg : getArgs()) { v.append(" "); v.append(formatArgument(arg)); } return v.toString(); } public static String formatArgument(String arg) { if (arg.indexOf(' ') != -1 || arg.indexOf('"') != -1 || arg.indexOf('\'') != -1) { StringBuilder a = new StringBuilder("'"); for (char c : arg.toCharArray()) { if (c == '\\' || c == '\'' || c == '"') a.append("\\"); a.append(c); } a.append("'"); return a.toString(); } else return arg; } public static List<String> parseQuotedString(String command) { List<String> args = new ArrayList<String>(); boolean escaped = false; boolean quoted = false; StringBuilder word = new StringBuilder(); for (int i = 0; i < command.length(); i++) { char c = command.charAt(i); if (c == '"' && !escaped) { if (quoted) { quoted = false; } else { quoted = true; } } else if (c == '\\' && !escaped) { escaped = true; } else if ((c == ' ' || c == '\n') && !escaped && !quoted) { if (word.length() > 0) { args.add(word.toString()); word.setLength(0); ; } } else { word.append(c); } } if (word.length() > 0) args.add(word.toString()); return args; } }
1,871
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
module-info.java
/FileExtraction/Java_unseen/bithatch_snake/snake-backend-openrazer/src/main/java/module-info.java
module uk.co.bithatch.snake.lib.backend.openrazer { requires transitive uk.co.bithatch.snake.lib; requires transitive uk.co.bithatch.linuxio; requires transitive org.freedesktop.dbus; provides uk.co.bithatch.snake.lib.Backend with uk.co.bithatch.snake.lib.backend.openrazer.OpenRazerBackend; exports uk.co.bithatch.snake.lib.backend.openrazer; }
354
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
RazerDPI.java
/FileExtraction/Java_unseen/bithatch_snake/snake-backend-openrazer/src/main/java/uk/co/bithatch/snake/lib/backend/openrazer/RazerDPI.java
package uk.co.bithatch.snake.lib.backend.openrazer; import org.freedesktop.dbus.annotations.DBusInterfaceName; import org.freedesktop.dbus.interfaces.DBusInterface; @DBusInterfaceName("razer.device.dpi") public interface RazerDPI extends DBusInterface { int[] getDPI(); int maxDPI(); void setDPI(short x, short y); }
332
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
RazerRegionScroll.java
/FileExtraction/Java_unseen/bithatch_snake/snake-backend-openrazer/src/main/java/uk/co/bithatch/snake/lib/backend/openrazer/RazerRegionScroll.java
package uk.co.bithatch.snake.lib.backend.openrazer; import org.freedesktop.dbus.annotations.DBusInterfaceName; import org.freedesktop.dbus.interfaces.DBusInterface; @DBusInterfaceName("razer.device.lighting.scroll") public interface RazerRegionScroll extends DBusInterface { boolean getScrollActive(); double getScrollBrightness(); void setScrollActive(boolean active); void setScrollBreathDual(byte red1, byte green1, byte blue1, byte red2, byte green2, byte blue2); void setScrollBreathRandom(); void setScrollBreathSingle(byte red1, byte green1, byte blue1); void setScrollBrightness(double brightness); void setScrollNone(); void setScrollReactive(byte red1, byte green1, byte blue1, byte speed); void setScrollSpectrum(); void setScrollStatic(byte red1, byte green1, byte blue1); void setScrollWave(int direction); }
864
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
RazerBrightness.java
/FileExtraction/Java_unseen/bithatch_snake/snake-backend-openrazer/src/main/java/uk/co/bithatch/snake/lib/backend/openrazer/RazerBrightness.java
package uk.co.bithatch.snake.lib.backend.openrazer; import org.freedesktop.dbus.annotations.DBusInterfaceName; import org.freedesktop.dbus.interfaces.DBusInterface; @DBusInterfaceName("razer.device.lighting.brightness") public interface RazerBrightness extends DBusInterface { double getBrightness(); void setBrightness(double brightness); }
354
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
RazerRegionRight.java
/FileExtraction/Java_unseen/bithatch_snake/snake-backend-openrazer/src/main/java/uk/co/bithatch/snake/lib/backend/openrazer/RazerRegionRight.java
package uk.co.bithatch.snake.lib.backend.openrazer; import org.freedesktop.dbus.annotations.DBusInterfaceName; import org.freedesktop.dbus.interfaces.DBusInterface; @DBusInterfaceName("razer.device.lighting.right") public interface RazerRegionRight extends DBusInterface { double getRightBrightness(); void setRightBreathDual(byte red1, byte green1, byte blue1, byte red2, byte green2, byte blue2); void setRightBreathRandom(); void setRightBreathSingle(byte red1, byte green1, byte blue1); void setRightBrightness(double brightness); void setRightNone(); void setRightReactive(byte red1, byte green1, byte blue1, byte speed); void setRightSpectrum(); void setRightStatic(byte red1, byte green1, byte blue1); void setRightWave(int direction); }
781
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
NativeRazerDevice.java
/FileExtraction/Java_unseen/bithatch_snake/snake-backend-openrazer/src/main/java/uk/co/bithatch/snake/lib/backend/openrazer/NativeRazerDevice.java
package uk.co.bithatch.snake.lib.backend.openrazer; import java.io.IOException; import java.io.StringReader; import java.lang.System.Logger.Level; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.lang3.StringUtils; import org.freedesktop.dbus.annotations.DBusInterfaceName; import org.freedesktop.dbus.connections.impl.DBusConnection; import org.freedesktop.dbus.exceptions.DBusException; import org.freedesktop.dbus.exceptions.NotConnected; import org.freedesktop.dbus.interfaces.DBusInterface; import org.freedesktop.dbus.interfaces.Introspectable; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import uk.co.bithatch.linuxio.EventCode; import uk.co.bithatch.linuxio.EventCode.Ev; import uk.co.bithatch.snake.lib.BrandingImage; import uk.co.bithatch.snake.lib.Capability; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.lib.DeviceType; import uk.co.bithatch.snake.lib.Key; import uk.co.bithatch.snake.lib.Macro; import uk.co.bithatch.snake.lib.MacroKey; import uk.co.bithatch.snake.lib.MacroKey.State; import uk.co.bithatch.snake.lib.MacroScript; import uk.co.bithatch.snake.lib.MacroSequence; import uk.co.bithatch.snake.lib.MacroURL; import uk.co.bithatch.snake.lib.Region; import uk.co.bithatch.snake.lib.ValidationException; import uk.co.bithatch.snake.lib.binding.ExecuteMapAction; import uk.co.bithatch.snake.lib.binding.KeyMapAction; import uk.co.bithatch.snake.lib.binding.MapAction; import uk.co.bithatch.snake.lib.binding.MapMapAction; import uk.co.bithatch.snake.lib.binding.MapSequence; import uk.co.bithatch.snake.lib.binding.Profile; import uk.co.bithatch.snake.lib.binding.ProfileMap; import uk.co.bithatch.snake.lib.binding.ProfileMapAction; import uk.co.bithatch.snake.lib.binding.ReleaseMapAction; import uk.co.bithatch.snake.lib.binding.ShiftMapAction; import uk.co.bithatch.snake.lib.binding.SleepMapAction; import uk.co.bithatch.snake.lib.effects.Breath; import uk.co.bithatch.snake.lib.effects.Effect; import uk.co.bithatch.snake.lib.effects.Matrix; import uk.co.bithatch.snake.lib.effects.Off; import uk.co.bithatch.snake.lib.effects.On; import uk.co.bithatch.snake.lib.effects.Pulsate; import uk.co.bithatch.snake.lib.effects.Reactive; import uk.co.bithatch.snake.lib.effects.Ripple; import uk.co.bithatch.snake.lib.effects.Spectrum; import uk.co.bithatch.snake.lib.effects.Starlight; import uk.co.bithatch.snake.lib.effects.Static; import uk.co.bithatch.snake.lib.effects.Wave; public class NativeRazerDevice implements Device { abstract class AbstractRazerRegion<I extends DBusInterface> implements Region { short brightness = -1; Set<Capability> caps = new HashSet<>(); Class<I> clazz; DBusConnection conn; Effect effect = new Off(); String effectPrefix; Map<String, List<Class<?>>> methods = new HashMap<>(); Name name; Set<Class<? extends Effect>> supportedEffects = new LinkedHashSet<>(); I underlying; private Document document; AbstractRazerRegion(Class<I> clazz, Name name, DBusConnection conn, String effectPrefix) { this.effectPrefix = effectPrefix; this.clazz = clazz; this.name = name; this.conn = conn; } @Override public <E extends Effect> E createEffect(Class<E> clazz) { E effectInstance; try { effectInstance = clazz.getConstructor().newInstance(); return effectInstance; } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new IllegalStateException(String.format("Cannot create effect %s.", clazz)); } } @Override public void updateEffect(Effect effect) { throw new UnsupportedOperationException(); } @Override public final short getBrightness() { assertCap(Capability.BRIGHTNESS_PER_REGION); if (brightness == -1) { brightness = doGetBrightness(); } return brightness; } @Override public Set<Capability> getCapabilities() { return caps; } public Device getDevice() { return NativeRazerDevice.this; } @Override public final Effect getEffect() { return effect; } @Override public final Name getName() { return name; } @Override public Set<Class<? extends Effect>> getSupportedEffects() { return supportedEffects; } public final void load(String path) throws Exception { loadIntrospection(path); loadInterfaces(path); if (hasMethod("set" + effectPrefix + "None")) supportedEffects.add(Off.class); if (hasMethod("set" + effectPrefix + "Static", byte.class, byte.class, byte.class)) supportedEffects.add(Static.class); if (hasMethod("set" + effectPrefix + "BreathRandom")) supportedEffects.add(Breath.class); if (hasMethod("set" + effectPrefix + "Reactive", byte.class, byte.class, byte.class, byte.class)) supportedEffects.add(Reactive.class); if (hasMethod("set" + effectPrefix + "Spectrum")) supportedEffects.add(Spectrum.class); if (hasMethod("set" + effectPrefix + "Wave", int.class)) supportedEffects.add(Wave.class); onCaps(caps); if (supportedEffects.isEmpty()) { throw new UnsupportedOperationException(String.format("Region %s not supported.", name.name())); } caps.add(Capability.EFFECT_PER_REGION); caps.add(Capability.EFFECTS); try { brightness = doGetBrightness(); caps.add(Capability.BRIGHTNESS_PER_REGION); if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("Region %s on device %s supports separate brightness.", name.name(), NativeRazerDevice.class.getName())); } catch (Exception e) { if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("Region %s on device %s does not support separate brightness.", name.name(), NativeRazerDevice.class.getName())); } } @Override public final void setBrightness(short brightness) { assertCap(Capability.BRIGHTNESS_PER_REGION); if (brightness != this.brightness) { this.brightness = brightness; doSetBrightness(brightness); fireChange(this); fireChange(null); } } @Override public void setEffect(Effect effect) { if (!Objects.equals(effect, this.effect)) { doSetEffect(effect); fireChange(null); } } protected short doGetBrightness() { throw new UnsupportedOperationException(); } protected void doSetBreathDual(Breath breath) { throw new UnsupportedOperationException(); } protected void doSetBreathRandom() { throw new UnsupportedOperationException(); } protected void doSetBreathSingle(Breath breath) { throw new UnsupportedOperationException(); } protected void doSetBrightness(int brightness) { throw new UnsupportedOperationException(); } protected void doSetEffect(Effect effect) { doChangeEffect(effect, false); fireChange(this); } protected void doUpdateEffect(Effect effect) { doChangeEffect(effect, true); } protected void doChangeEffect(Effect effect, boolean update) { try { this.effect = effect; brightness = -1; if (effect instanceof Breath) { Breath breath = (Breath) effect; switch (breath.getMode()) { case DUAL: doSetBreathDual(breath); break; case SINGLE: doSetBreathSingle(breath); break; default: doSetBreathRandom(); break; } } else if (effect instanceof Off) { doSetOff(); } else if (effect instanceof Spectrum) { doSetSpectrum(); } else if (effect instanceof Reactive) { doSetReactive((Reactive) effect); } else if (effect instanceof Static) { doSetStatic((Static) effect); } else if (effect instanceof On) { doSetOn((On) effect); } else if (effect instanceof Wave) { doSetWave((Wave) effect); } else if (effect instanceof Matrix) { doSetMatrix((Matrix) effect, update); } else if (effect instanceof Pulsate) { doSetPulsate((Pulsate) effect); } else if (effect instanceof Starlight) { Starlight starlight = (Starlight) effect; switch (starlight.getMode()) { case DUAL: doSetStarlightDual(starlight); break; case SINGLE: doSetStarlightSingle(starlight); break; default: doSetStarlightRandom(starlight); break; } } else if (effect instanceof Ripple) { Ripple ripple = (Ripple) effect; switch (ripple.getMode()) { case SINGLE: doSetRipple(ripple); break; default: doSetRippleRandomColour(ripple); break; } } else throw new UnsupportedOperationException( String.format("Effect %s not supported by region %s", effect.getClass(), name)); } catch (NotConnected nc) { // Ignore } } protected void doSetMatrix(Matrix matrix, boolean update) { throw new UnsupportedOperationException(); } protected void doSetOff() { throw new UnsupportedOperationException(); } protected void doSetOn(On monoStaticEffect) { throw new UnsupportedOperationException(); } protected void doSetPulsate(Pulsate pulsate) { throw new UnsupportedOperationException(); } protected void doSetReactive(Reactive reactive) { throw new UnsupportedOperationException(); } protected void doSetRipple(Ripple ripple) { throw new UnsupportedOperationException(); } protected void doSetRippleRandomColour(Ripple ripple) { throw new UnsupportedOperationException(); } protected void doSetSpectrum() { throw new UnsupportedOperationException(); } protected void doSetStarlightDual(Starlight starlight) { throw new UnsupportedOperationException(); } protected void doSetStarlightRandom(Starlight starlight) { throw new UnsupportedOperationException(); } protected void doSetStarlightSingle(Starlight starlight) { throw new UnsupportedOperationException(); } protected void doSetStatic(Static staticEffect) { throw new UnsupportedOperationException(); } protected void doSetWave(Wave wave) { throw new UnsupportedOperationException(); } protected boolean hasMethod(String name, Class<?>... classes) { List<Class<?>> sig = methods.get(name); return sig != null && sig.equals(Arrays.asList(classes)); } protected void loadInterfaces(String path) throws DBusException { underlying = conn.getRemoteObject("org.razer", String.format("/org/razer/device/%s", path), clazz, true); loadMethods(clazz); } protected void loadIntrospection(String path) throws DBusException, ParserConfigurationException, SAXException, IOException { Introspectable intro = conn.getRemoteObject("org.razer", String.format("/org/razer/device/%s", path), Introspectable.class, true); InputSource source = new InputSource(new StringReader(intro.Introspect())); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); dbf.setValidating(false); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); document = db.parse(source); } protected boolean loadMethods(Class<?> clazz) { NodeList nl = document.getElementsByTagName("interface"); boolean ok = false; for (int i = 0; i < nl.getLength(); i++) { Node n = nl.item(i); Node attr = n.getAttributes().getNamedItem("name"); if (attr != null) { DBusInterfaceName dbusName = clazz.getAnnotation(DBusInterfaceName.class); if (dbusName.value().equals(attr.getNodeValue())) { NodeList ichildren = n.getChildNodes(); for (int j = 0; j < ichildren.getLength(); j++) { Node in = ichildren.item(j); if (in.getNodeName().equalsIgnoreCase("method")) { Node nattr = in.getAttributes().getNamedItem("name"); List<Class<?>> sig = new ArrayList<>(); NodeList achildren = in.getChildNodes(); for (int aj = 0; aj < achildren.getLength(); aj++) { Node ain = achildren.item(aj); if (ain.getNodeName().equalsIgnoreCase("arg")) { Node naattr = ain.getAttributes().getNamedItem("type"); if (naattr != null) { String natype = naattr.getNodeValue(); if (natype.equals("y")) sig.add(byte.class); else if (natype.equals("b")) sig.add(boolean.class); else if (natype.equals("n") || natype.equals("q")) sig.add(short.class); else if (natype.equals("i") || natype.equals("i")) sig.add(int.class); else if (natype.equals("x") || natype.equals("t")) sig.add(long.class); else if (natype.equals("d")) sig.add(double.class); else if (natype.equals("s")) sig.add(String.class); /* * TODO: Other types we don't really care about at the moment, as the * signatures are only used for capabilities, which only use the above * primitive types */ } } } methods.put(nattr.getNodeValue(), sig); } } break; } } } return ok; } protected void onCaps(Set<Capability> caps) { } void assertCap(Capability cap) { if (!caps.contains(cap)) throw new UnsupportedOperationException( String.format("The capability %s is not supported by region %s on device %s.", cap, name.name(), getDevice().getName())); } // // private Preferences regionPrefs() { // Preferences regionPrefs = prefs.node(this.name.name()); // return regionPrefs; // } } class NativeRazerRegionBacklight extends AbstractRazerRegion<RazerRegionBacklight> { public NativeRazerRegionBacklight(DBusConnection connection) { super(RazerRegionBacklight.class, Name.BACKLIGHT, connection, "Backlight"); } @Override protected void doSetOff() { underlying.setBacklightActive(false); } @Override protected void doSetOn(On on) { underlying.setBacklightActive(true); } @Override protected void onCaps(Set<Capability> caps) { if (hasMethod("setBacklightActive", boolean.class)) { supportedEffects.add(On.class); supportedEffects.add(Off.class); } } } class NativeRazerRegionChroma extends AbstractRazerRegion<RazerRegionChroma> { RazerBW2013 underlyingBw2013; RazerCustom underlyingCustom; public NativeRazerRegionChroma(DBusConnection connection) { super(RazerRegionChroma.class, Name.CHROMA, connection, ""); } @Override protected short doGetBrightness() { return (short) underlying.getBrightness(); } @Override protected void doSetBreathDual(Breath breath) { underlying.setBreathDual((byte) breath.getColor1()[0], (byte) breath.getColor1()[1], (byte) breath.getColor1()[2], (byte) breath.getColor2()[0], (byte) breath.getColor2()[1], (byte) breath.getColor2()[2]); } @Override protected void doSetBreathRandom() { underlying.setBreathRandom(); } @Override protected void doSetBreathSingle(Breath breath) { underlying.setBreathSingle((byte) breath.getColor()[0], (byte) breath.getColor()[1], (byte) breath.getColor()[2]); } @Override protected void doSetBrightness(int brightness) { underlying.setBrightness(brightness); } @Override protected void doSetMatrix(Matrix matrix, boolean update) { // https://github.com/openrazer/openrazer/wiki/Using-the-keyboard-driver int[][][] cells = matrix.getCells(); int[] dim = getDevice().getMatrixSize(); int y = dim[0]; int x = dim[1]; byte[] b = new byte[(y * 3) + (y * x * 3)]; int q = 0; if (cells != null) { for (int yy = 0; yy < y; yy++) { b[q++] = (byte) yy; b[q++] = (byte) 0; b[q++] = (byte) (x - 1); if (cells[yy] != null) for (int xx = 0; xx < x; xx++) { if (cells[yy][xx] != null) { b[q++] = (byte) (cells[yy][xx][0] & 0xff); b[q++] = (byte) (cells[yy][xx][1] & 0xff); b[q++] = (byte) (cells[yy][xx][2] & 0xff); } } } } /* TODO only need to do this once when the matrix is initially selected */ if (!update) underlying.setCustom(); underlying.setKeyRow(b); } @Override protected void doSetOff() { underlying.setNone(); } @Override protected void doSetOn(On monoStaticEffect) { underlyingBw2013.setStatic(); } @Override protected void doSetPulsate(Pulsate pulsate) { underlyingBw2013.setPulsate(); } @Override protected void doSetReactive(Reactive reactive) { underlying.setReactive((byte) reactive.getColor()[0], (byte) reactive.getColor()[1], (byte) reactive.getColor()[2], (byte) reactive.getSpeed()); } @Override protected void doSetRipple(Ripple ripple) { underlyingCustom.setRipple((byte) ripple.getColor()[0], (byte) ripple.getColor()[1], (byte) ripple.getColor()[2], (double) ripple.getRefreshRate()); } @Override protected void doSetRippleRandomColour(Ripple ripple) { underlyingCustom.setRippleRandomColour((double) ripple.getRefreshRate()); } @Override protected void doSetSpectrum() { underlying.setSpectrum(); } @Override protected void doSetStarlightDual(Starlight starlight) { underlying.setStarlightDual((byte) starlight.getColor1()[0], (byte) starlight.getColor1()[1], (byte) starlight.getColor1()[2], (byte) starlight.getColor2()[0], (byte) starlight.getColor2()[1], (byte) starlight.getColor2()[2], (byte) starlight.getSpeed()); } @Override protected void doSetStarlightRandom(Starlight starlight) { underlying.setStarlightRandom((byte) starlight.getSpeed()); } @Override protected void doSetStarlightSingle(Starlight starlight) { underlying.setStarlightSingle((byte) starlight.getColor()[0], (byte) starlight.getColor()[1], (byte) starlight.getColor()[2], (byte) starlight.getSpeed()); } @Override protected void doSetStatic(Static staticEffect) { underlying.setStatic((byte) staticEffect.getColor()[0], (byte) staticEffect.getColor()[1], (byte) staticEffect.getColor()[2]); } @Override protected void doSetWave(Wave wave) { underlying.setWave(wave.getDirection().ordinal() + 1); } @Override protected void loadInterfaces(String path) throws DBusException { super.loadInterfaces(path); try { underlyingBw2013 = conn.getRemoteObject("org.razer", String.format("/org/razer/device/%s", path), RazerBW2013.class, true); loadMethods(RazerBW2013.class); } catch (Exception e) { } try { underlyingCustom = conn.getRemoteObject("org.razer", String.format("/org/razer/device/%s", path), RazerCustom.class, true); loadMethods(RazerCustom.class); } catch (Exception e) { } } @SuppressWarnings("resource") @Override protected void onCaps(Set<Capability> caps) { if (((NativeRazerDevice) getDevice()).device.hasMatrix()) { supportedEffects.add(Matrix.class); } if (hasMethod("setStarlightDual", byte.class, byte.class, byte.class, byte.class, byte.class, byte.class, byte.class)) { caps.add(Capability.STARLIGHT_DUAL); supportedEffects.add(Starlight.class); } if (hasMethod("setStarlightRandom", byte.class)) { caps.add(Capability.STARLIGHT_RANDOM); supportedEffects.add(Starlight.class); } if (hasMethod("setStarlightSingle", byte.class, byte.class, byte.class, byte.class)) { caps.add(Capability.STARLIGHT_SINGLE); supportedEffects.add(Starlight.class); } if (hasMethod("setPulsate")) supportedEffects.add(Pulsate.class); if (hasMethod("setStatic")) supportedEffects.add(On.class); if (hasMethod("setRipple", byte.class, byte.class, byte.class, double.class)) { caps.add(Capability.RIPPLE_SINGLE); supportedEffects.add(Ripple.class); } if (hasMethod("setRippleRandomColour", double.class)) { caps.add(Capability.RIPPLE_RANDOM); supportedEffects.add(Ripple.class); } } } class NativeRazerRegionLeft extends AbstractRazerRegion<RazerRegionLeft> { public NativeRazerRegionLeft(DBusConnection connection) { super(RazerRegionLeft.class, Name.LEFT, connection, "Left"); } @Override protected short doGetBrightness() { return (short) underlying.getLeftBrightness(); } @Override protected void doSetBreathDual(Breath breath) { underlying.setLeftBreathDual((byte) breath.getColor1()[0], (byte) breath.getColor1()[1], (byte) breath.getColor1()[2], (byte) breath.getColor2()[0], (byte) breath.getColor2()[1], (byte) breath.getColor1()[2]); } @Override protected void doSetBreathRandom() { underlying.setLeftBreathRandom(); } @Override protected void doSetBreathSingle(Breath breath) { underlying.setLeftBreathSingle((byte) breath.getColor()[0], (byte) breath.getColor()[1], (byte) breath.getColor()[2]); } @Override protected void doSetBrightness(int brightness) { underlying.setLeftBrightness(brightness); } @Override protected void doSetOff() { underlying.setLeftNone(); } @Override protected void doSetReactive(Reactive reactive) { underlying.setLeftReactive((byte) reactive.getColor()[0], (byte) reactive.getColor()[1], (byte) reactive.getColor()[2], (byte) reactive.getSpeed()); } @Override protected void doSetSpectrum() { underlying.setLeftSpectrum(); } @Override protected void doSetStatic(Static staticEffect) { underlying.setLeftStatic((byte) staticEffect.getColor()[0], (byte) staticEffect.getColor()[1], (byte) staticEffect.getColor()[2]); } @Override protected void doSetWave(Wave wave) { underlying.setLeftWave(wave.getDirection().ordinal() + 1); } } class NativeRazerRegionLogo extends AbstractRazerRegion<RazerRegionLogo> { public NativeRazerRegionLogo(DBusConnection connection) { super(RazerRegionLogo.class, Name.LOGO, connection, "Logo"); } @Override protected short doGetBrightness() { return (short) underlying.getLogoBrightness(); } @Override protected void doSetBreathDual(Breath breath) { underlying.setLogoBreathDual((byte) breath.getColor1()[0], (byte) breath.getColor1()[1], (byte) breath.getColor1()[2], (byte) breath.getColor2()[0], (byte) breath.getColor2()[1], (byte) breath.getColor1()[2]); } @Override protected void doSetBreathRandom() { underlying.setLogoBreathRandom(); } @Override protected void doSetBreathSingle(Breath breath) { underlying.setLogoBreathSingle((byte) breath.getColor()[0], (byte) breath.getColor()[1], (byte) breath.getColor()[2]); } @Override protected void doSetBrightness(int brightness) { underlying.setLogoBrightness(brightness); } @Override protected void doSetOff() { if (hasMethod("setLogoActive", boolean.class)) { underlying.setLogoActive(false); } else underlying.setLogoNone(); } @Override protected void doSetOn(On on) { underlying.setLogoActive(true); } @Override protected void doSetReactive(Reactive reactive) { underlying.setLogoReactive((byte) reactive.getColor()[0], (byte) reactive.getColor()[1], (byte) reactive.getColor()[2], (byte) reactive.getSpeed()); } @Override protected void doSetSpectrum() { underlying.setLogoSpectrum(); } @Override protected void doSetStatic(Static staticEffect) { underlying.setLogoStatic((byte) staticEffect.getColor()[0], (byte) staticEffect.getColor()[1], (byte) staticEffect.getColor()[2]); } @Override protected void doSetWave(Wave wave) { underlying.setLogoWave(wave.getDirection().ordinal() + 1); } @Override protected void onCaps(Set<Capability> caps) { if (hasMethod("setLogoActive", boolean.class)) { supportedEffects.add(On.class); supportedEffects.add(Off.class); } } } class NativeRazerRegionRight extends AbstractRazerRegion<RazerRegionRight> { public NativeRazerRegionRight(DBusConnection connection) { super(RazerRegionRight.class, Name.RIGHT, connection, "Right"); } @Override protected short doGetBrightness() { return (short) underlying.getRightBrightness(); } @Override protected void doSetBreathDual(Breath breath) { underlying.setRightBreathDual((byte) breath.getColor1()[0], (byte) breath.getColor1()[1], (byte) breath.getColor1()[2], (byte) breath.getColor2()[0], (byte) breath.getColor2()[1], (byte) breath.getColor1()[2]); } @Override protected void doSetBreathRandom() { underlying.setRightBreathRandom(); } @Override protected void doSetBreathSingle(Breath breath) { underlying.setRightBreathSingle((byte) breath.getColor()[0], (byte) breath.getColor()[1], (byte) breath.getColor()[2]); } @Override protected void doSetBrightness(int brightness) { underlying.setRightBrightness(brightness); } @Override protected void doSetOff() { underlying.setRightNone(); } @Override protected void doSetReactive(Reactive reactive) { underlying.setRightReactive((byte) reactive.getColor()[0], (byte) reactive.getColor()[1], (byte) reactive.getColor()[2], (byte) reactive.getSpeed()); } @Override protected void doSetSpectrum() { underlying.setRightSpectrum(); } @Override protected void doSetStatic(Static staticEffect) { underlying.setRightStatic((byte) staticEffect.getColor()[0], (byte) staticEffect.getColor()[1], (byte) staticEffect.getColor()[2]); } @Override protected void doSetWave(Wave wave) { underlying.setRightWave(wave.getDirection().ordinal() + 1); } } class NativeRazerRegionScroll extends AbstractRazerRegion<RazerRegionScroll> { public NativeRazerRegionScroll(DBusConnection connection) { super(RazerRegionScroll.class, Name.SCROLL, connection, "Scroll"); } @Override protected short doGetBrightness() { return (short) underlying.getScrollBrightness(); } @Override protected void doSetBreathDual(Breath breath) { underlying.setScrollBreathDual((byte) breath.getColor1()[0], (byte) breath.getColor1()[1], (byte) breath.getColor1()[2], (byte) breath.getColor2()[0], (byte) breath.getColor2()[1], (byte) breath.getColor1()[2]); } @Override protected void doSetBreathRandom() { underlying.setScrollBreathRandom(); } @Override protected void doSetBreathSingle(Breath breath) { underlying.setScrollBreathSingle((byte) breath.getColor()[0], (byte) breath.getColor()[1], (byte) breath.getColor()[2]); } @Override protected void doSetBrightness(int brightness) { underlying.setScrollBrightness(brightness); } @Override protected void doSetOff() { if (hasMethod("setScrollActive", boolean.class)) { underlying.setScrollActive(false); } else underlying.setScrollNone(); } @Override protected void doSetOn(On on) { underlying.setScrollActive(true); } @Override protected void doSetReactive(Reactive reactive) { underlying.setScrollReactive((byte) reactive.getColor()[0], (byte) reactive.getColor()[1], (byte) reactive.getColor()[2], (byte) reactive.getSpeed()); } @Override protected void doSetSpectrum() { underlying.setScrollSpectrum(); } @Override protected void doSetStatic(Static staticEffect) { underlying.setScrollStatic((byte) staticEffect.getColor()[0], (byte) staticEffect.getColor()[1], (byte) staticEffect.getColor()[2]); } @Override protected void doSetWave(Wave wave) { underlying.setScrollWave(wave.getDirection().ordinal() + 1); } @Override protected void onCaps(Set<Capability> caps) { if (hasMethod("setScrollActive", boolean.class)) { supportedEffects.add(On.class); supportedEffects.add(Off.class); } } } final static System.Logger LOG = System.getLogger(NativeRazerDevice.class.getName()); final static long MAX_CACHE_AGE = TimeUnit.DAYS.toMillis(7); public static String genericHash(String input) { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(hash).replace("/", "").replace("=", ""); } catch (Exception e) { throw new RuntimeException(e); } } private RazerBattery battery; private int batteryLevel; private ScheduledFuture<?> batteryTask; private Map<BrandingImage, String> brandingImages = new HashMap<>(); private RazerBrightness brightness; private RazerRegionProfileLEDs leds; private Set<Capability> caps = new HashSet<>(); private DBusConnection conn; private RazerDevice device; private String deviceName; private RazerDPI dpi; private String driverVersion; private Effect effect; private String firmware; private RazerGameMode gameMode; private short lastBrightness = -1; private List<Listener> listeners = new ArrayList<>(); private RazerMacro macros; private int maxDpi = -1; private String path; private int pollRate = -1; // private Preferences prefs; private List<Region> regionList; private Set<Class<? extends Effect>> supportedEffects = new LinkedHashSet<>(); private boolean wasCharging; private byte lowBatteryThreshold = 5; private int idleTime = (int) TimeUnit.MINUTES.toSeconds(5); private int[] matrix; private RazerBinding binding; private List<Profile> profiles; private RazerBindingLighting bindingLighting; private Set<EventCode> supportedInputEvents = new LinkedHashSet<>(); private Set<Key> supportedLegacyKeys = new LinkedHashSet<>(); private DeviceType deviceType; private String deviceSerial; NativeRazerDevice(String path, DBusConnection conn, OpenRazerBackend backend) throws Exception { this.path = path; this.conn = conn; device = conn.getRemoteObject("org.razer", String.format("/org/razer/device/%s", path), RazerDevice.class); // TODO actual supported events will need backend support (or implement our ownt // evdev caps discovery, or dervice from layout) var keyList = new ArrayList<>(Arrays.asList(EventCode.values())); Collections.sort(keyList, (k1, k2) -> k1.name().compareTo(k2.name())); supportedInputEvents.addAll(keyList); var legacyKeyList = new ArrayList<>(Arrays.asList(Key.values())); Collections.sort(legacyKeyList, (k1, k2) -> k1.name().compareTo(k2.name())); supportedLegacyKeys.addAll(legacyKeyList); try { device.getPollRate(); caps.add(Capability.POLL_RATE); if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("Device %s supports poll rate.", NativeRazerDevice.class.getName())); } catch (Exception e) { if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("Device %s does not support separate brightness.", NativeRazerDevice.class.getName())); } try { RazerDPI dpi = conn.getRemoteObject("org.razer", String.format("/org/razer/device/%s", path), RazerDPI.class); dpi.getDPI(); this.dpi = dpi; if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("%s has DPI control.", getName())); caps.add(Capability.DPI); } catch (Exception e) { // if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("%s has no DPI control.", getName())); } try { RazerBrightness brightness = conn.getRemoteObject("org.razer", String.format("/org/razer/device/%s", path), RazerBrightness.class); brightness.getBrightness(); this.brightness = brightness; if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("%s has brightness control.", getName())); caps.add(Capability.BRIGHTNESS); } catch (Exception e) { // if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("%s has no brightness control.", getName())); } try { RazerRegionProfileLEDs leds = conn.getRemoteObject("org.razer", String.format("/org/razer/device/%s", path), RazerRegionProfileLEDs.class); leds.getBlueLED(); if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("%s has profile LEDS control.", getName())); caps.add(Capability.PROFILE_LEDS); this.leds = leds; } catch (Exception e) { // if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("%s has no profile LEDs.", getName())); } try { RazerBattery battery = conn.getRemoteObject("org.razer", String.format("/org/razer/device/%s", path), RazerBattery.class); battery.getBattery(); this.battery = battery; if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("%s has battery control.", getName())); caps.add(Capability.BATTERY); } catch (Exception e) { // if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("%s has no battery control.", getName())); } try { RazerGameMode gameMode = conn.getRemoteObject("org.razer", String.format("/org/razer/device/%s", path), RazerGameMode.class); gameMode.getGameMode(); if (!getType().equals(DeviceType.KEYBOARD)) { throw new UnsupportedOperationException( "Why do things other than keyboard have this DBus method if it doesn't work?"); } this.gameMode = gameMode; if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("%s has game mode control.", getName())); caps.add(Capability.GAME_MODE); } catch (Exception e) { // if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("%s has no game mode control.", getName())); } try { RazerBinding binding = conn.getRemoteObject("org.razer", String.format("/org/razer/device/%s", path), RazerBinding.class); this.binding = binding; if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("%s has macro profiles.", getName())); try { binding.getProfiles(); caps.add(Capability.MACRO_PROFILES); caps.add(Capability.MACROS); } catch (Exception e) { if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("%s has no legacy macros.", getName())); } try { RazerBindingLighting bindingLighting = conn.getRemoteObject("org.razer", String.format("/org/razer/device/%s", path), RazerBindingLighting.class); bindingLighting.getProfileLEDs(binding.getActiveProfile(), binding.getActiveMap()); this.bindingLighting = bindingLighting; if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("%s has binding lighting.", getName())); caps.add(Capability.MACRO_PROFILE_LEDS); } catch (Exception e) { // if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("%s has no binding lighting.", getName())); } } catch (Exception e) { // if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("%s has no macro profiles.", getName())); } try { device.getKeyboardLayout(); if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("%s has keyboard layout.", getName())); caps.add(Capability.KEYBOARD_LAYOUT); } catch (Exception e) { // if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("%s has no keyboard layout.", getName())); } try { RazerMacro macro = conn.getRemoteObject("org.razer", String.format("/org/razer/device/%s", path), RazerMacro.class); try { macro.getMacros(); if (!getType().equals(DeviceType.KEYBOARD)) { throw new UnsupportedOperationException( "Why do things other than keyboard have this DBus method if it doesn't work?"); } this.macros = macro; if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("%s has legacy macro control.", getName())); caps.add(Capability.MACROS); } catch (Exception e) { } try { macro.getMacroRecordingState(); this.macros = macro; caps.add(Capability.MACRO_RECORDING); if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("%s has no macro recording.", getName())); } catch (Exception e) { } try { macro.getModeModifier(); this.macros = macro; caps.add(Capability.MACRO_MODE_MODIFIER); if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("%s has no macro mode modifier.", getName())); } catch (Exception e) { } } catch (Exception e) { if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("%s has no macro control.", getName())); } if (device.hasDedicatedMacroKeys()) { caps.add(Capability.DEDICATED_MACRO_KEYS); } if (device.hasMatrix()) { caps.add(Capability.MATRIX); supportedEffects.add(Matrix.class); } getRegions(); for (Region r : regionList) { for (Class<? extends Effect> ec : r.getSupportedEffects()) { if (!supportedEffects.contains(ec)) supportedEffects.add(ec); } if (r.getCapabilities().contains(Capability.BRIGHTNESS_PER_REGION)) { caps.add(Capability.BRIGHTNESS); } if (r.getCapabilities().contains(Capability.EFFECT_PER_REGION)) { caps.add(Capability.EFFECTS); } caps.addAll(r.getCapabilities()); } /* * Because OpenRazer doesn't seem to provider getters for these values, we just * have to store them locally, and reset them when any Snake app starts up */ if (getCapabilities().contains(Capability.BATTERY)) { battery.setLowBatteryThreshold(getLowBatteryThreshold()); battery.setIdleTime(getIdleTime()); /* Poll for battery changes, we don't get events from openrazer */ /* TODO: Check, does it use standard battery events maybe? */ batteryTask = backend.getBatteryPoll().scheduleAtFixedRate(() -> pollBattery(), 30, 30, TimeUnit.SECONDS); } try { JsonObject jsonObject = JsonParser.parseString(device.getRazerUrls()).getAsJsonObject(); for (String key : jsonObject.keySet()) { String img = jsonObject.get(key).getAsString(); try { BrandingImage bimg = BrandingImage.valueOf(key.substring(0, key.length() - 4).toUpperCase()); brandingImages.put(bimg, img); } catch (Exception e) { LOG.log(Level.WARNING, String.format( "Unknow Razer URL image type. The image %s for %s will be ignored. Please report this to Snake developers.", key, img), e); } } } catch (Exception e) { } } @Override public void addListener(Listener listener) { listeners.add(listener); } @Override public void addMacro(MacroSequence macroSequence) { assertCap(Capability.MACROS); GsonBuilder gson = new GsonBuilder(); gson.registerTypeAdapter(MacroKey.class, new JsonSerializer<MacroKey>() { @Override public JsonElement serialize(MacroKey src, Type typeOfSrc, JsonSerializationContext context) { JsonObject root = new JsonObject(); root.addProperty("type", "MacroKey"); root.addProperty("key_id", src.getKey().nativeKeyName()); root.addProperty("pre_pause", src.getPrePause()); root.addProperty("state", src.getState().name()); return root; } }); gson.registerTypeAdapter(MacroURL.class, new JsonSerializer<MacroURL>() { @Override public JsonElement serialize(MacroURL src, Type typeOfSrc, JsonSerializationContext context) { JsonObject root = new JsonObject(); root.addProperty("type", "MacroURL"); root.addProperty("url", src.getUrl()); return root; } }); gson.registerTypeAdapter(MacroScript.class, new JsonSerializer<MacroScript>() { @Override public JsonElement serialize(MacroScript src, Type typeOfSrc, JsonSerializationContext context) { JsonObject root = new JsonObject(); root.addProperty("type", "MacroScript"); root.addProperty("script", src.getScript() == null ? "" : src.getScript()); if (src.getArgs() != null) { root.addProperty("args", String.join(" ", src.getArgs())); } return root; } }); Gson parser = gson.create(); var js = parser.toJson(macroSequence); macros.addMacro(macroSequence.getMacroKey().nativeKeyName(), js); } @Override public void close() throws Exception { if (batteryTask != null) batteryTask.cancel(false); } @Override public <E extends Effect> E createEffect(Class<E> clazz) { E effectInstance; try { effectInstance = clazz.getConstructor().newInstance(); return effectInstance; } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new IllegalStateException(String.format("Cannot create effect %s.", clazz)); } } @Override public void deleteMacro(Key key) { assertCap(Capability.MACROS); macros.deleteMacro(key.nativeKeyName()); } @Override public String exportMacros() { assertCap(Capability.MACROS); return macros.getMacros(); } @Override public int getBattery() { assertCap(Capability.BATTERY); return (int) battery.getBattery(); } @Override public short getBrightness() { assertCap(Capability.BRIGHTNESS); if (brightness == null) return Device.super.getBrightness(); else { if (lastBrightness == -1) { lastBrightness = (short) brightness.getBrightness(); } return lastBrightness; } } @Override public Set<Capability> getCapabilities() { return caps; } @Override public int[] getDPI() { assertCap(Capability.DPI); return dpi.getDPI(); } @Override public String getDriverVersion() { if (driverVersion == null) driverVersion = device.getDriverVersion(); return driverVersion; } @Override public Set<EventCode> getSupportedInputEvents() { return supportedInputEvents; } @Override public Set<Key> getSupportedLegacyKeys() { return supportedLegacyKeys; } @Override public Effect getEffect() { if (effect == null) { Class<? extends Effect> efClazz = getSupportedEffects().isEmpty() ? null : getSupportedEffects().iterator().next(); if (efClazz != null) { effect = createEffect(efClazz); } } return effect; } @Override public String getFirmware() { if (firmware == null) firmware = device.getFirmware(); return firmware; } @Override public int getIdleTime() { return idleTime; } @Override public String getImage() { try { String image = device.getDeviceImage(); if (image != null && !image.equals("") && !image.startsWith("http:") && !image.startsWith("https:")) return image; } catch (Exception e) { } Iterator<String> it = brandingImages.values().iterator(); while (it.hasNext()) { String v = it.next(); if (v != null && !v.equals("")) return v; } return null; } @Override public String getImageUrl(BrandingImage image) { return brandingImages.get(image); } @Override public String getKeyboardLayout() { return device.getKeyboardLayout(); } @Override public byte getLowBatteryThreshold() { return lowBatteryThreshold; } @Override public Map<Key, MacroSequence> getMacros() { assertCap(Capability.MACROS); String macroString = macros.getMacros(); JsonObject jsonObject = JsonParser.parseString(macroString).getAsJsonObject(); Map<Key, MacroSequence> macroSequences = new LinkedHashMap<>(); for (String key : jsonObject.keySet()) { Key keyObj = Key.values()[0]; try { keyObj = Key.fromNativeKeyName(key); } catch (IllegalArgumentException iae) { LOG.log(Level.WARNING, String.format( "Macro trigger has invalid key %s. This has been ignored and defaulted to the first available. If macros are saved now, the original key will be lost.", key)); ; } MacroSequence seq = new MacroSequence(keyObj); JsonArray arr = jsonObject.get(key).getAsJsonArray(); for (JsonElement el : arr) { JsonObject obj = el.getAsJsonObject(); String type = obj.get("type").getAsString(); Macro macro; if (type.equals("MacroKey")) { MacroKey macroKey = new MacroKey(); try { macroKey.setKey(Key.fromNativeKeyName(obj.get("key_id").getAsString())); } catch (IllegalArgumentException iae) { LOG.log(Level.WARNING, String.format( "Macro action has invalid key %s. This has been ignored and defaulted to the first available. If macros are saved now, the original key will be lost.", obj.get("key_id").getAsString())); macroKey.setKey(Key.values()[0]); ; } macroKey.setPrePause(obj.get("pre_pause").getAsLong()); macroKey.setState(State.valueOf(obj.get("state").getAsString())); macro = macroKey; } else if (type.equals("MacroURL")) { MacroURL macroURL = new MacroURL(); macroURL.setUrl(obj.get("url").getAsString()); macro = macroURL; } else if (type.equals("MacroScript")) { MacroScript macroScript = new MacroScript(); macroScript.setScript(obj.get("script").getAsString()); if (obj.has("args")) { macroScript.setArgs(Arrays.asList(obj.get("args").getAsString().split(" "))); } macro = macroScript; } else throw new UnsupportedOperationException(); seq.add(macro); } macroSequences.put(seq.getMacroKey(), seq); } return macroSequences; } @Override public int[] getMatrixSize() { assertCap(Capability.MATRIX); if (matrix == null) matrix = device.getMatrixDimensions(); return matrix; } @Override public int getMaxDPI() { assertCap(Capability.DPI); if (maxDpi == -1) maxDpi = dpi.maxDPI(); return maxDpi; } @Override public String getMode() { return device.getDeviceMode(); } @Override public String getName() { if (deviceName == null) deviceName = device.getDeviceName(); return deviceName; } @Override public int getPollRate() { if (pollRate == -1) pollRate = device.getPollRate(); return pollRate; } @Override public List<Region> getRegions() { if (regionList == null) { regionList = new ArrayList<Region>(); for (AbstractRazerRegion<?> r : Arrays.asList(new NativeRazerRegionChroma(conn), new NativeRazerRegionLeft(conn), new NativeRazerRegionRight(conn), new NativeRazerRegionLogo(conn), new NativeRazerRegionScroll(conn), new NativeRazerRegionBacklight(conn))) { try { r.load(path); regionList.add(r); } catch (Exception e) { LOG.log(Level.DEBUG, "Failed to load region.", e); } } } return regionList; } @Override public String getSerial() { if (deviceSerial == null) { deviceSerial = device.getSerial(); } return deviceSerial; } @Override public Set<Class<? extends Effect>> getSupportedEffects() { return supportedEffects; } @Override public DeviceType getType() { if (deviceType == null) { try { deviceType = DeviceType.valueOf(device.getDeviceType().toUpperCase()); } catch (Exception e) { return DeviceType.UNRECOGNISED; } } return deviceType; } @Override public void importMacros(String macros) { for (MacroSequence s : getMacros().values()) deleteMacro(s.getMacroKey()); JsonObject jsonObject = JsonParser.parseString(macros).getAsJsonObject(); for (String key : jsonObject.keySet()) { this.macros.addMacro(key, jsonObject.get(key).toString()); } } @Override public boolean isCharging() { assertCap(Capability.BATTERY); return battery.isCharging(); } @Override public boolean isGameMode() { assertCap(Capability.GAME_MODE); return this.gameMode.getGameMode(); } @Override public boolean isModeModifier() { assertCap(Capability.MACROS); return macros.getModeModifier(); } @Override public boolean isSuspended() { // TODO err return false; } @Override public void removeListener(Listener listener) { listeners.remove(listener); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void setBrightness(short brightness) { assertCap(Capability.BRIGHTNESS); if (this.brightness == null) { /* Calculated overall brightness */ if (brightness != getBrightness()) { if (caps.contains(Capability.BRIGHTNESS_PER_REGION)) { for (Region r : getRegions()) { if (r.getCapabilities().contains(Capability.BRIGHTNESS_PER_REGION)) { /* * NOTE: These are set directly so we don't fire too many events, just the * device change */ ((AbstractRazerRegion) r).brightness = brightness; ((AbstractRazerRegion) r).doSetBrightness(brightness); } } fireChange(null); } } } else { /* Driver supplied overall brightness */ if (brightness != lastBrightness) { lastBrightness = brightness; this.brightness.setBrightness(brightness); fireChange(null); } } } @Override public void setDPI(short x, short y) { assertCap(Capability.DPI); dpi.setDPI(x, y); fireChange(null); } @SuppressWarnings("rawtypes") @Override public void setEffect(Effect effect) { this.effect = effect; lastBrightness = -1; for (Region r : getRegions()) { if (r.isSupported(effect)) ((AbstractRazerRegion) r).doSetEffect(effect); } fireChange(null); } @SuppressWarnings("rawtypes") @Override public void updateEffect(Effect effect) { boolean change = false; if (this.effect == null || this.effect.getClass() != effect.getClass()) { change = true; } this.effect = effect; lastBrightness = -1; for (Region r : getRegions()) { if (r.isSupported(effect)) { if (change) ((AbstractRazerRegion) r).doSetEffect(effect); else ((AbstractRazerRegion) r).doUpdateEffect(effect); } } if (change) { fireChange(null); } } @Override public void setGameMode(boolean gameMode) { assertCap(Capability.GAME_MODE); this.gameMode.setGameMode(gameMode); fireChange(null); } @Override public void setIdleTime(int idleTime) { assertCap(Capability.BATTERY); int old = this.idleTime; if (old != idleTime) { this.idleTime = idleTime; battery.setIdleTime(idleTime); fireChange(null); } } @Override public void setLowBatteryThreshold(byte threshold) { assertCap(Capability.BATTERY); int old = lowBatteryThreshold; if (old != threshold) { this.lowBatteryThreshold = threshold; battery.setLowBatteryThreshold(threshold); fireChange(null); } } @Override public void setModeModifier(boolean modify) { assertCap(Capability.MACROS); macros.setModeModifier(modify); } @Override public void setPollRate(int pollRate) { this.pollRate = pollRate; device.setPollRate((short) pollRate); fireChange(null); } @Override public void setSuspended(boolean suspended) { if (suspended) device.suspendDevice(); else device.resumeDevice(); fireChange(null); } @Override public String toString() { return "NativeRazerDevice [deviceName=" + deviceName + ", driverVersion=" + driverVersion + ", firmware=" + firmware + ", path=" + path + "]"; } @Override public boolean[] getProfileRGB() { assertCap(Capability.PROFILE_LEDS); return new boolean[] { leds.getRedLED(), leds.getGreenLED(), leds.getBlueLED() }; } @Override public void setProfileRGB(boolean[] rgb) { assertCap(Capability.PROFILE_LEDS); leds.setRedLED(rgb[0]); leds.setGreenLED(rgb[1]); leds.setBlueLED(rgb[2]); } protected void fireMapAdded(ProfileMap map) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).mapAdded(map); } protected void fireMapRemoved(ProfileMap map) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).mapRemoved(map); } protected void fireMapChanged(ProfileMap map) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).mapChanged(map); } protected void fireChange(Region region) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).changed(this, region); } protected void fireProfileAdded(Profile profile) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).profileAdded(profile); } protected void fireProfileRemoved(Profile profile) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).profileRemoved(profile); } protected void fireActiveMapChanged(ProfileMap map) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).activeMapChanged(map); } void assertCap(Capability cap) { if (!caps.contains(cap)) throw new UnsupportedOperationException( String.format("The capability %s is not supported on device %s.", cap, getName())); } private void pollBattery() { boolean charging = battery.isCharging(); int level = (int) battery.getBattery(); if (charging != wasCharging || batteryLevel != level) { wasCharging = charging; batteryLevel = level; fireChange(null); } } @Override public List<Profile> getProfiles() { assertCap(Capability.MACRO_PROFILES); if (profiles == null) { profiles = new ArrayList<>(); for (JsonElement el : JsonParser.parseString(binding.getProfiles()).getAsJsonArray()) { profiles.add(new RazerMacroProfile(bindingLighting, this, el.getAsString())); } } return profiles; } @Override public Profile getActiveProfile() { assertCap(Capability.MACRO_PROFILES); String activeProfile = binding.getActiveProfile(); if (StringUtils.isBlank(activeProfile)) return null; else return getProfile(activeProfile); } @Override public Profile getProfile(String name) { assertCap(Capability.MACRO_PROFILES); for (Profile p : getProfiles()) { if (p.getName().equals(name)) return p; } return null; } @Override public Profile addProfile(String name) { assertCap(Capability.MACRO_PROFILES); binding.addProfile(name); Profile profile = new RazerMacroProfile(bindingLighting, this, name); if (profiles == null) profiles = new ArrayList<>(); getProfiles(); profiles.add(profile); fireProfileAdded(profile); profile.getDefaultMap().setLEDs(new boolean[3]); return profile; } static class RazerMacroProfile implements Profile { private NativeRazerDevice device; private String name; private List<uk.co.bithatch.snake.lib.binding.Profile.Listener> listeners = new ArrayList<>(); private List<ProfileMap> profileMaps; private RazerBindingLighting bindingLighting; RazerMacroProfile(RazerBindingLighting bindingLighting, NativeRazerDevice device, String name) { this.device = device; this.bindingLighting = bindingLighting; this.name = name; } @Override public void addListener(uk.co.bithatch.snake.lib.binding.Profile.Listener listener) { listeners.add(listener); } @Override public void removeListener(uk.co.bithatch.snake.lib.binding.Profile.Listener listener) { listeners.remove(listener); } @Override public void activate() { device.binding.setActiveProfile(getName()); ProfileMap map = getActiveMap(); device.fireActiveMapChanged(map); fireActiveMapChanged(map); } @Override public boolean isActive() { return getName().equals(device.binding.getActiveProfile()); } @Override public String getName() { return name; } @Override public ProfileMap getDefaultMap() { return getMap(device.binding.getDefaultMap(getName())); } @Override public ProfileMap getActiveMap() { if (isActive()) return getMap(device.binding.getActiveMap()); else return null; } @Override public ProfileMap getMap(String id) { for (ProfileMap map : getMaps()) if (map.getId().equals(id)) return map; return null; } @Override public List<ProfileMap> getMaps() { if (profileMaps == null) { profileMaps = new ArrayList<>(); for (JsonElement el : JsonParser.parseString(device.binding.getMaps(getName())).getAsJsonArray()) { profileMaps.add(new RazerMacroProfileMap(device, this, el.getAsString(), bindingLighting)); } } return profileMaps; } @Override public String toString() { return "RazerMacroProfile [name=" + name + "]"; } @Override public ProfileMap addMap(String id) { device.binding.addMap(getName(), id); ProfileMap map = new RazerMacroProfileMap(device, this, id, bindingLighting); if (profileMaps == null) profileMaps = new ArrayList<>(); profileMaps.add(map); fireMapAdded(map); device.fireMapAdded(map); return map; } @Override public void setDefaultMap(ProfileMap map) { device.binding.setDefaultMap(getName(), map.getId()); fireChanged(); } @Override public void remove() { device.binding.removeProfile(getName()); device.fireProfileRemoved(this); device.getProfiles(); device.profiles.remove(this); } protected void fireMapAdded(ProfileMap map) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).mapAdded(map); } protected void fireMapRemoved(ProfileMap map) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).mapRemoved(map); } protected void fireMapChanged(ProfileMap map) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).mapChanged(map); } protected void fireActiveMapChanged(ProfileMap map) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).activeMapChanged(map); } protected void fireChanged() { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).changed(this); } @Override public Device getDevice() { return device; } } static class RazerMacroProfileMap implements ProfileMap { private String id; private RazerMacroProfile profile; private NativeRazerDevice device; private RazerBindingLighting bindingLighting; private Map<EventCode, MapSequence> sequences; RazerMacroProfileMap(NativeRazerDevice device, RazerMacroProfile profile, String id, RazerBindingLighting bindingLighting) { this.id = id; this.profile = profile; this.device = device; this.bindingLighting = bindingLighting; } @Override public boolean[] getLEDs() { device.assertCap(Capability.MACRO_PROFILE_LEDS); ThreeTuple<Boolean, Boolean, Boolean> profileLEDs = bindingLighting.getProfileLEDs(profile.getName(), getId()); return new boolean[] { profileLEDs.a, profileLEDs.b, profileLEDs.c }; } @Override public void setLEDs(boolean red, boolean green, boolean blue) { device.assertCap(Capability.MACRO_PROFILE_LEDS); bindingLighting.setProfileLEDs(profile.getName(), getId(), red, green, blue); ((RazerMacroProfile) profile).fireMapChanged(this); device.fireMapChanged(this); } @Override public Profile getProfile() { return profile; } @Override public String getId() { return id; } @Override public boolean isActive() { return profile.isActive() && getId().equals(device.binding.getActiveMap()); } @Override public void activate() { if (!profile.isActive()) profile.activate(); device.binding.setActiveMap(getId()); device.fireActiveMapChanged(this); ((RazerMacroProfile) profile).fireActiveMapChanged(this); } @Override public Map<EventCode, MapSequence> getSequences() { if (sequences == null) { sequences = new LinkedHashMap<>(); JsonObject actions = JsonParser .parseString(device.binding.getActions(getProfile().getName(), getId(), "")).getAsJsonObject(); for (String key : actions.keySet()) { RazerMapSequence seq = new RazerMapSequence(this, EventCode.fromCode(Ev.EV_KEY, Integer.parseInt(key))); JsonArray actionsArray = actions.get(key).getAsJsonArray(); for (JsonElement actionElement : actionsArray) { JsonObject actionObject = actionElement.getAsJsonObject(); seq.add(createMapAction(seq, actionObject)); } sequences.put(seq.getMacroKey(), seq); } } return sequences; } protected RazerMapAction createMapAction(RazerMapSequence seq, JsonObject actionObject) { String type = actionObject.get("type").getAsString(); String value = actionObject.get("value").getAsString(); switch (type) { case "release": try { return new RazerReleaseMapAction(this, seq, device.binding, value); } catch (NumberFormatException nfe) { // TODO get last pressed key if available instead of next available return new RazerReleaseMapAction(this, seq, device.binding, String.valueOf(getNextFreeKey().code())); } case "execute": return new RazerExecuteMapAction(this, seq, device.binding, value); case "map": return new RazerMapMapAction(this, seq, device.binding, value); case "profile": return new RazerProfileMapAction(this, seq, device.binding, value); case "shift": return new RazerShiftMapAction(this, seq, device.binding, value); case "sleep": try { return new RazerSleepMapAction(this, seq, device.binding, value); } catch (NumberFormatException nfe) { return new RazerSleepMapAction(this, seq, device.binding, "1"); } default: try { return new RazerKeyMapAction(this, seq, device.binding, value); } catch (Exception e) { return new RazerKeyMapAction(this, seq, device.binding, String.valueOf(getNextFreeKey().code())); } } } @Override public void remove() { device.binding.removeMap(profile.getName(), getId()); ((RazerMacroProfile) profile).profileMaps.remove(this); ((RazerMacroProfile) profile).fireMapRemoved(this); device.fireMapRemoved(this); } @Override public String toString() { return "RazerMacroProfileMap [id=" + id + "]"; } @Override public void record(int keyCode) { device.assertCap(Capability.MACRO_RECORDING); device.macros.startMacroRecording(profile.getName(), getId(), keyCode); } @Override public int getRecordingMacroKey() { return device.macros.getMacroKey(); } @Override public boolean isRecording() { device.assertCap(Capability.MACRO_RECORDING); return device.macros.getMacroRecordingState(); } @Override public void stopRecording() { device.assertCap(Capability.MACRO_RECORDING); device.macros.stopMacroRecording(); } @Override public void setMatrix(Matrix matrix) { device.assertCap(Capability.MATRIX); // TODO // bindingLighting.setMatrix(profile.getName(), getId(), ""); throw new UnsupportedOperationException("TODO"); } @Override public Matrix getMatrix() { device.assertCap(Capability.MATRIX); // TODO throw new UnsupportedOperationException("TODO"); } @Override public boolean isDefault() { return device.binding.getDefaultMap(profile.getName()).equals(getId()); } @Override public void makeDefault() { device.binding.setDefaultMap(profile.getName(), getId()); ((RazerMacroProfile) profile).fireMapChanged(this); device.fireMapChanged(this); } @Override public MapSequence addSequence(EventCode key, boolean addDefaultActions) { RazerMapSequence seq = new RazerMapSequence(this, key); if (addDefaultActions) seq.addAction(KeyMapAction.class, key); synchronized (sequences) { if (sequences.containsKey(key)) throw new IllegalArgumentException(String.format("Key %s already mapped.", key)); sequences.put(key, seq); } device.fireMapChanged(this); return seq; } } static abstract class RazerMapAction implements MapAction { private RazerBinding binding; private ProfileMap map; private RazerMapSequence sequence; RazerMapAction(ProfileMap map, RazerMapSequence sequence, RazerBinding binding, String value) { this.binding = binding; this.sequence = sequence; this.map = map; setValue(value); } @Override public final ProfileMap getMap() { return map; } @Override public final int getActionId() { int idx = getSequence().indexOf(this); if (idx == -1) throw new IllegalStateException("Found not found action ID for " + getActionType() + " in " + sequence); return idx; } @Override public void remove() { doRemove(); sequence.remove(this); if (sequence.isEmpty()) sequence.remove(); } protected void doRemove() { binding.removeAction(map.getProfile().getName(), map.getId(), sequence.getMacroKey().code(), getActionId()); } @Override public MapSequence getSequence() { return sequence; } @Override public String toString() { return getClass().getSimpleName() + " [hashCode=" + hashCode() + ",actionId=" + getActionId() + ", value=" + getValue() + "]"; } @SuppressWarnings("unchecked") @Override public <A extends MapAction> A update(Class<A> actionType, Object value) { RazerMacroProfileMap razerProfileMap = (RazerMacroProfileMap) getMap(); int actionId = getActionId(); razerProfileMap.device.binding.updateAction(getMap().getProfile().getName(), getMap().getId(), getSequence().getMacroKey().code(), toNativeActionName(actionType), value == null ? "" : String.valueOf(value), actionId); JsonElement actions = JsonParser .parseString(razerProfileMap.device.binding.getActions(getMap().getProfile().getName(), getMap().getId(), String.valueOf(getSequence().getMacroKey().code()))); JsonArray actionsArray = actions.getAsJsonArray(); JsonObject actionObject = actionsArray.get(actionId).getAsJsonObject(); MapAction currentAction = sequence.get(actionId); if (currentAction.getActionType().equals(actionType)) { currentAction.setValue(value == null ? null : String.valueOf(value)); return (A) currentAction; } else { MapAction mapAction = razerProfileMap.createMapAction((RazerMapSequence) getSequence(), actionObject); /* If switching between key types, keep the key code */ if ((actionType.equals(KeyMapAction.class) && currentAction.getActionType().equals(ReleaseMapAction.class)) || (actionType.equals(ReleaseMapAction.class) && currentAction.getActionType().equals(KeyMapAction.class))) { mapAction.setValue(currentAction.getValue()); razerProfileMap.device.binding.updateAction(getMap().getProfile().getName(), getMap().getId(), getSequence().getMacroKey().code(), toNativeActionName(actionType), mapAction.getValue(), actionId); } getSequence().set(actionId, mapAction); ((RazerMacroProfile) razerProfileMap.profile).fireMapChanged(razerProfileMap); return (A) mapAction; } } @Override public void commit() { update(getActionType(), getValue()); } } @SuppressWarnings("serial") static class RazerMapSequence extends MapSequence { public RazerMapSequence(ProfileMap map, EventCode key) { super(map, key); } public RazerMapSequence(ProfileMap map) { super(map); } @Override public void remove() { for (MapAction act : this) { ((RazerMapAction) act).doRemove(); } clear(); ((RazerMacroProfileMap) getMap()).sequences.remove(getMacroKey()); } @SuppressWarnings("unchecked") @Override public <A extends MapAction> A addAction(Class<A> actionType, Object value) { RazerMacroProfileMap razerProfileMap = (RazerMacroProfileMap) getMap(); razerProfileMap.device.binding.addAction(getMap().getProfile().getName(), getMap().getId(), getMacroKey().code(), toNativeActionName(actionType), value instanceof EventCode ? String.valueOf(((EventCode) value).code()) : String.valueOf(value)); JsonElement actions = JsonParser.parseString(razerProfileMap.device.binding.getActions( getMap().getProfile().getName(), getMap().getId(), String.valueOf(getMacroKey().code()))); JsonArray actionsArray = actions.getAsJsonArray(); JsonObject actionObject = actionsArray.get(actionsArray.size() - 1).getAsJsonObject(); MapAction mapAction = razerProfileMap.createMapAction(this, actionObject); add(mapAction); ((RazerMacroProfile) razerProfileMap.profile).fireMapChanged(razerProfileMap); return (A) mapAction; } @Override public void commit() { /* * There is no DBus function to update the key for a map, so have to remove the * entire map and recreate all of the actions */ RazerMacroProfileMap razerProfileMap = (RazerMacroProfileMap) getMap(); razerProfileMap.device.binding.removeMap(getMap().getProfile().getName(), getMap().getId()); razerProfileMap.device.binding.addMap(getMap().getProfile().getName(), getMap().getId()); for (Map.Entry<EventCode, MapSequence> seqEn : razerProfileMap.sequences.entrySet()) { for (MapAction action : seqEn.getValue()) { razerProfileMap.device.binding.addAction(getMap().getProfile().getName(), getMap().getId(), seqEn.getValue().getMacroKey().code(), toNativeActionName(action.getActionType()), action.getValue()); } } } @Override public void record() { RazerMacroProfileMap razerProfileMap = (RazerMacroProfileMap) getMap(); razerProfileMap.device.macros.startMacroRecording(razerProfileMap.getProfile().getName(), razerProfileMap.getId(), getMacroKey().code()); } @Override public boolean isRecording() { return ((RazerMacroProfileMap) getMap()).device.macros.getMacroRecordingState(); } @Override public void stopRecording() { ((RazerMacroProfileMap) getMap()).device.macros.stopMacroRecording(); } } static class RazerKeyMapAction extends RazerMapAction implements KeyMapAction { private EventCode press; RazerKeyMapAction(ProfileMap map, RazerMapSequence sequence, RazerBinding binding, String press) { super(map, sequence, binding, press); } @Override public void validate() throws ValidationException { if (press == null) throw new ValidationException("keyMapAction.missingPress"); } @Override public EventCode getPress() { return press; } @Override public void setPress(EventCode press) { this.press = press; } } static class RazerReleaseMapAction extends RazerMapAction implements ReleaseMapAction { private EventCode release; RazerReleaseMapAction(ProfileMap map, RazerMapSequence sequence, RazerBinding binding, String value) { super(map, sequence, binding, value); } @Override public void validate() throws ValidationException { if (release == null) throw new ValidationException("keyReleaseAction.missingRelease"); } @Override public EventCode getRelease() { return release; } @Override public void setRelease(EventCode release) { this.release = release; } } static class RazerExecuteMapAction extends RazerMapAction implements ExecuteMapAction { private String command; private List<String> args; RazerExecuteMapAction(ProfileMap map, RazerMapSequence sequence, RazerBinding binding, String value) { super(map, sequence, binding, value); } @Override public void validate() throws ValidationException { if (command == null || command.length() == 0) throw new ValidationException("executeMapAction.missingCommand"); } @Override public List<String> getArgs() { return args; } @Override public String getCommand() { return command; } @Override public void setArgs(List<String> args) { this.args = args; } @Override public void setCommand(String script) { this.command = script; } } static class RazerMapMapAction extends RazerMapAction implements MapMapAction { private String mapName; RazerMapMapAction(ProfileMap map, RazerMapSequence sequence, RazerBinding binding, String value) { super(map, sequence, binding, value); } @Override public void validate() throws ValidationException { if (mapName == null || mapName.length() == 0) throw new ValidationException("mapMapAction.missingMapName"); } @Override public String getMapName() { return mapName; } @Override public void setMapName(String mapName) { this.mapName = mapName; } } static class RazerProfileMapAction extends RazerMapAction implements ProfileMapAction { private String profileName; RazerProfileMapAction(ProfileMap map, RazerMapSequence sequence, RazerBinding binding, String value) { super(map, sequence, binding, value); } @Override public void validate() throws ValidationException { if (profileName == null || profileName.length() == 0) throw new ValidationException("profileMapAction.missingProfileName"); } @Override public String getProfileName() { return profileName; } @Override public void setProfileName(String profileName) { this.profileName = profileName; } } static class RazerShiftMapAction extends RazerMapAction implements ShiftMapAction { private String mapName; RazerShiftMapAction(ProfileMap map, RazerMapSequence sequence, RazerBinding binding, String value) { super(map, sequence, binding, value); } @Override public void validate() throws ValidationException { if (mapName == null || mapName.length() == 0) throw new ValidationException("shiftMapAction.missingMapName"); } @Override public String getMapName() { return mapName; } @Override public void setMapName(String mapName) { this.mapName = mapName; } } static class RazerSleepMapAction extends RazerMapAction implements SleepMapAction { private float seconds; RazerSleepMapAction(ProfileMap map, RazerMapSequence sequence, RazerBinding binding, String value) { super(map, sequence, binding, value); } @Override public void validate() throws ValidationException { } @Override public float getSeconds() { return seconds; } @Override public void setSeconds(float seconds) { this.seconds = seconds; } } static String toNativeActionName(Class<? extends MapAction> actionType) { String actionTypeName = actionType.getSimpleName(); actionTypeName = actionTypeName.substring(0, actionTypeName.length() - 9).toLowerCase(); return actionTypeName; } }
74,077
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
ThreeTuple.java
/FileExtraction/Java_unseen/bithatch_snake/snake-backend-openrazer/src/main/java/uk/co/bithatch/snake/lib/backend/openrazer/ThreeTuple.java
package uk.co.bithatch.snake.lib.backend.openrazer; import org.freedesktop.dbus.Tuple; public final class ThreeTuple<A, B, C> extends Tuple { public final A a; public final B b; public final C c; public ThreeTuple(A a, B b, C c) { this.a = a; this.b = b; this.c = c; } }
284
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
RazerDevice.java
/FileExtraction/Java_unseen/bithatch_snake/snake-backend-openrazer/src/main/java/uk/co/bithatch/snake/lib/backend/openrazer/RazerDevice.java
package uk.co.bithatch.snake.lib.backend.openrazer; import org.freedesktop.dbus.annotations.DBusInterfaceName; import org.freedesktop.dbus.annotations.DBusMemberName; import org.freedesktop.dbus.exceptions.DBusException; import org.freedesktop.dbus.interfaces.DBusInterface; import org.freedesktop.dbus.messages.DBusSignal; @DBusInterfaceName("razer.device.misc") public interface RazerDevice extends DBusInterface { String getDeviceImage(); String getDeviceMode(); String getDeviceName(); String getDeviceType(); String getDriverVersion(); String getFirmware(); String getKeyboardLayout(); int[] getMatrixDimensions(); int getPollRate(); String getRazerUrls(); String getSerial(); int[] getVidPid(); boolean hasDedicatedMacroKeys(); boolean hasMatrix(); void resumeDevice(); void setDeviceMode(byte mode, byte param); void setPollRate(short rate); void suspendDevice(); }
911
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
OpenRazerBackend.java
/FileExtraction/Java_unseen/bithatch_snake/snake-backend-openrazer/src/main/java/uk/co/bithatch/snake/lib/backend/openrazer/OpenRazerBackend.java
package uk.co.bithatch.snake.lib.backend.openrazer; import java.lang.System.Logger.Level; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.prefs.Preferences; import org.freedesktop.dbus.connections.impl.DBusConnection; import org.freedesktop.dbus.errors.ServiceUnknown; import uk.co.bithatch.snake.lib.Backend; import uk.co.bithatch.snake.lib.BackendException; import uk.co.bithatch.snake.lib.Capability; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.lib.effects.Effect; public class OpenRazerBackend implements Backend { final static System.Logger LOG = System.getLogger(OpenRazerBackend.class.getName()); final static Preferences PREFS = Preferences.userNodeForPackage(OpenRazerBackend.class); final ScheduledExecutorService batteryPoll = Executors.newScheduledThreadPool(1); private DBusConnection conn; private RazerDaemon daemon; private List<Device> deviceList; private Map<String, Device> deviceMap = new HashMap<>(); private RazerDevices devices; private Object lock = new Object(); private List<BackendListener> listeners = new ArrayList<>(); private String[] currentDevices; @Override public void addListener(BackendListener listener) { listeners.add(listener); } @Override public void close() throws Exception { LOG.log(Level.DEBUG, "Closing OpenRazer backend."); try { conn.close(); } catch (Exception e) { } finally { LOG.log(Level.DEBUG, "Stopping battery poll thread."); batteryPoll.shutdown(); } } @Override public List<Device> getDevices() throws Exception { synchronized (lock) { if (deviceList == null) { deviceMap.clear(); List<Device> newDeviceList = new ArrayList<>(); try { currentDevices = devices.getDevices(); for (String d : currentDevices) { NativeRazerDevice dev = new NativeRazerDevice(d, conn, this); deviceMap.put(d, dev); newDeviceList.add(dev); } Collections.sort(newDeviceList, (c1, c2) -> c1.getSerial().compareTo(c2.getSerial())); } catch (ServiceUnknown se) { throw new BackendException("OpenRazer not available", se); } deviceList = newDeviceList; } } return deviceList; } @Override public String getName() { return "OpenRazer"; } @Override public Set<Class<? extends Effect>> getSupportedEffects() { Set<Class<? extends Effect>> l = new LinkedHashSet<>(); try { for (Device d : getDevices()) { l.addAll(d.getSupportedEffects()); } } catch (Exception e) { } return l; } @Override public String getVersion() { return daemon.version(); } @Override public void init() throws Exception { conn = DBusConnection.getConnection(DBusConnection.DBusBusType.SESSION); devices = conn.getRemoteObject("org.razer", "/org/razer", RazerDevices.class); conn.addSigHandler(RazerDevices.DeviceAdded.class, devices, (sig) -> { synchronized (lock) { List<String> was = Arrays.asList(currentDevices); try { String[] nowArr = devices.getDevices(); List<String> now = new ArrayList<>(Arrays.asList(nowArr)); now.removeAll(was); for (String newDevice : now) { NativeRazerDevice dev = new NativeRazerDevice(newDevice, conn, this); deviceMap.put(newDevice, dev); deviceList.add(dev); for (int i = listeners.size() - 1; i >= 0; i--) { listeners.get(i).deviceAdded(dev); } } currentDevices = nowArr; } catch (Exception e) { LOG.log(Level.ERROR, "Failed to get newly added device.", e); } } }); conn.addSigHandler(RazerDevices.DeviceRemoved.class, devices, (sig) -> { synchronized (lock) { List<String> was = new ArrayList<>(Arrays.asList(currentDevices)); try { String[] nowArr = devices.getDevices(); List<String> now = Arrays.asList(nowArr); was.removeAll(now); for (String removedDevice : was) { Device dev = deviceMap.get(removedDevice); if (dev != null) { deviceList.remove(dev); deviceMap.remove(removedDevice); for (int i = listeners.size() - 1; i >= 0; i--) { listeners.get(i).deviceRemoved(dev); } } } currentDevices = nowArr; } catch (Exception e) { LOG.log(Level.ERROR, "Failed to get newly remove device.", e); } } }); daemon = conn.getRemoteObject("org.razer", "/org/razer", RazerDaemon.class); getDevices(); } @Override public boolean isGameMode() { try { for (Device d : getDevices()) { if (d.getCapabilities().contains(Capability.GAME_MODE) && d.isGameMode()) return true; } } catch (Exception e) { } return false; } @Override public boolean isSync() { return devices.getSyncEffects(); } @Override public void removeListener(BackendListener listener) { listeners.add(listener); } @Override public void setGameMode(boolean gameMode) { try { for (Device d : getDevices()) { if (d.getCapabilities().contains(Capability.GAME_MODE)) d.setGameMode(gameMode); } } catch (Exception e) { } } @Override public void setSync(boolean sync) { devices.syncEffects(sync); } ScheduledExecutorService getBatteryPoll() { return batteryPoll; } }
5,410
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
RazerDevices.java
/FileExtraction/Java_unseen/bithatch_snake/snake-backend-openrazer/src/main/java/uk/co/bithatch/snake/lib/backend/openrazer/RazerDevices.java
package uk.co.bithatch.snake.lib.backend.openrazer; import org.freedesktop.dbus.annotations.DBusInterfaceName; import org.freedesktop.dbus.annotations.DBusMemberName; import org.freedesktop.dbus.exceptions.DBusException; import org.freedesktop.dbus.interfaces.DBusInterface; import org.freedesktop.dbus.messages.DBusSignal; @DBusInterfaceName("razer.devices") public interface RazerDevices extends DBusInterface { @DBusMemberName("device_added") class DeviceAdded extends DBusSignal { public DeviceAdded(String path) throws DBusException { super(path); } } @DBusMemberName("device_removed") class DeviceRemoved extends DBusSignal { public DeviceRemoved(String path) throws DBusException { super(path); } } void enableTurnOffOnScreensaver(boolean enable); String[] getDevices(); boolean getOffOnScreensaver(); boolean getSyncEffects(); String supportedDevices(); void syncEffects(boolean enabled); }
939
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
RazerGameMode.java
/FileExtraction/Java_unseen/bithatch_snake/snake-backend-openrazer/src/main/java/uk/co/bithatch/snake/lib/backend/openrazer/RazerGameMode.java
package uk.co.bithatch.snake.lib.backend.openrazer; import org.freedesktop.dbus.annotations.DBusInterfaceName; import org.freedesktop.dbus.interfaces.DBusInterface; @DBusInterfaceName("razer.device.led.gamemode") public interface RazerGameMode extends DBusInterface { boolean getGameMode(); void setGameMode(boolean gameMode); }
339
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
RazerBinding.java
/FileExtraction/Java_unseen/bithatch_snake/snake-backend-openrazer/src/main/java/uk/co/bithatch/snake/lib/backend/openrazer/RazerBinding.java
package uk.co.bithatch.snake.lib.backend.openrazer; import org.freedesktop.dbus.annotations.DBusInterfaceName; import org.freedesktop.dbus.interfaces.DBusInterface; @DBusInterfaceName("razer.device.binding") public interface RazerBinding extends DBusInterface { void addAction(String profile, String mapping, int keyCode, String actionType, String value); void addMap(String profile, String mapping); void addProfile(String profile); void clearActions(String profile, String mapping, byte keyCode); void copyMap(String profile, String mapping, String destProfile, String mapName); String getActions(String profile, String mapping, String keyCode); String getActiveMap(); String getActiveProfile(); String getDefaultMap(String profile); String getMaps(String profile); String getProfiles(); void removeAction(String profile, String mapping, int keyCode, int actionId); void removeMap(String profile, String mapping); void removeProfile(String profile); void setActiveMap(String mapping); void setActiveProfile(String profile); void setDefaultMap(String profile, String mapping); void updateAction(String profile, String mapping, int keyCode, String actionType, String value, int actionId); }
1,246
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
RazerRegionLogo.java
/FileExtraction/Java_unseen/bithatch_snake/snake-backend-openrazer/src/main/java/uk/co/bithatch/snake/lib/backend/openrazer/RazerRegionLogo.java
package uk.co.bithatch.snake.lib.backend.openrazer; import org.freedesktop.dbus.annotations.DBusInterfaceName; import org.freedesktop.dbus.interfaces.DBusInterface; @DBusInterfaceName("razer.device.lighting.logo") public interface RazerRegionLogo extends DBusInterface { boolean getLogoActive(); double getLogoBrightness(); void setLogoActive(boolean active); void setLogoBreathDual(byte red1, byte green1, byte blue1, byte red2, byte green2, byte blue2); void setLogoBreathRandom(); void setLogoBreathSingle(byte red1, byte green1, byte blue1); void setLogoBrightness(double brightness); void setLogoNone(); void setLogoReactive(byte red1, byte green1, byte blue1, byte speed); void setLogoSpectrum(); void setLogoStatic(byte red1, byte green1, byte blue1); void setLogoWave(int direction); }
832
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
RazerRegionLeft.java
/FileExtraction/Java_unseen/bithatch_snake/snake-backend-openrazer/src/main/java/uk/co/bithatch/snake/lib/backend/openrazer/RazerRegionLeft.java
package uk.co.bithatch.snake.lib.backend.openrazer; import org.freedesktop.dbus.annotations.DBusInterfaceName; import org.freedesktop.dbus.interfaces.DBusInterface; @DBusInterfaceName("razer.device.lighting.left") public interface RazerRegionLeft extends DBusInterface { double getLeftBrightness(); void setLeftBreathDual(byte red1, byte green1, byte blue1, byte red2, byte green2, byte blue2); void setLeftBreathRandom(); void setLeftBreathSingle(byte red1, byte green1, byte blue1); void setLeftBrightness(double brightness); void setLeftNone(); void setLeftReactive(byte red1, byte green1, byte blue1, byte speed); void setLeftSpectrum(); void setLeftStatic(byte red1, byte green1, byte blue1); void setLeftWave(int direction); }
769
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
RazerMacro.java
/FileExtraction/Java_unseen/bithatch_snake/snake-backend-openrazer/src/main/java/uk/co/bithatch/snake/lib/backend/openrazer/RazerMacro.java
package uk.co.bithatch.snake.lib.backend.openrazer; import org.freedesktop.dbus.annotations.DBusInterfaceName; import org.freedesktop.dbus.interfaces.DBusInterface; @DBusInterfaceName("razer.device.macro") public interface RazerMacro extends DBusInterface { @Deprecated void addMacro(String key, String json); @Deprecated void deleteMacro(String key); @Deprecated String getMacros(); @Deprecated boolean getModeModifier(); @Deprecated void setModeModifier(boolean modify); int getMacroKey(); boolean getMacroRecordingState(); void startMacroRecording(String profile, String mapping, int keyCode); void stopMacroRecording(); }
656
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
RazerBW2013.java
/FileExtraction/Java_unseen/bithatch_snake/snake-backend-openrazer/src/main/java/uk/co/bithatch/snake/lib/backend/openrazer/RazerBW2013.java
package uk.co.bithatch.snake.lib.backend.openrazer; import org.freedesktop.dbus.annotations.DBusInterfaceName; import org.freedesktop.dbus.interfaces.DBusInterface; @DBusInterfaceName("razer.device.lighting.bw2013") public interface RazerBW2013 extends DBusInterface { byte getEffect(); void setPulsate(); void setStatic(); }
336
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
RazerBattery.java
/FileExtraction/Java_unseen/bithatch_snake/snake-backend-openrazer/src/main/java/uk/co/bithatch/snake/lib/backend/openrazer/RazerBattery.java
package uk.co.bithatch.snake.lib.backend.openrazer; import org.freedesktop.dbus.annotations.DBusInterfaceName; import org.freedesktop.dbus.interfaces.DBusInterface; @DBusInterfaceName("razer.device.power") public interface RazerBattery extends DBusInterface { double getBattery(); boolean isCharging(); void setIdleTime(int idleTime); void setLowBatteryThreshold(byte lowBatteryThreshold); }
410
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
RazerBindingLighting.java
/FileExtraction/Java_unseen/bithatch_snake/snake-backend-openrazer/src/main/java/uk/co/bithatch/snake/lib/backend/openrazer/RazerBindingLighting.java
package uk.co.bithatch.snake.lib.backend.openrazer; import org.freedesktop.dbus.annotations.DBusInterfaceName; import org.freedesktop.dbus.interfaces.DBusInterface; @DBusInterfaceName("razer.device.binding.lighting") public interface RazerBindingLighting extends DBusInterface { String getMatrix(String profile, String mapping); void setMatrix(String profile, String mapping, String matrix); ThreeTuple<Boolean, Boolean, Boolean> getProfileLEDs(String profile, String mapping); void setProfileLEDs(String profile, String mapping, boolean red, boolean green, boolean blue); }
585
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
RazerRegionChroma.java
/FileExtraction/Java_unseen/bithatch_snake/snake-backend-openrazer/src/main/java/uk/co/bithatch/snake/lib/backend/openrazer/RazerRegionChroma.java
package uk.co.bithatch.snake.lib.backend.openrazer; import org.freedesktop.dbus.annotations.DBusInterfaceName; import org.freedesktop.dbus.interfaces.DBusInterface; @DBusInterfaceName("razer.device.lighting.chroma") public interface RazerRegionChroma extends DBusInterface { double getBrightness(); void setBreathDual(byte red1, byte green1, byte blue1, byte red2, byte green2, byte blue2); void setBreathRandom(); void setBreathSingle(byte red1, byte green1, byte blue1); void setBrightness(double brightness); void setCustom(); void setKeyRow(byte[] payload); void setNone(); void setReactive(byte red1, byte green1, byte blue1, byte speed); void setSpectrum(); void setStarlightDual(byte red1, byte green1, byte blue1, byte red2, byte green2, byte blue2, byte speed); void setStarlightRandom(byte speed); void setStarlightSingle(byte red, byte green, byte blue, byte speed); void setStatic(byte red1, byte green1, byte blue1); void setWave(int direction); }
994
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
RazerDaemon.java
/FileExtraction/Java_unseen/bithatch_snake/snake-backend-openrazer/src/main/java/uk/co/bithatch/snake/lib/backend/openrazer/RazerDaemon.java
package uk.co.bithatch.snake.lib.backend.openrazer; import org.freedesktop.dbus.annotations.DBusInterfaceName; import org.freedesktop.dbus.interfaces.DBusInterface; @DBusInterfaceName("razer.daemon") public interface RazerDaemon extends DBusInterface { void stop(); String version(); }
292
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
ProfileTest.java
/FileExtraction/Java_unseen/bithatch_snake/snake-backend-openrazer/src/main/java/uk/co/bithatch/snake/lib/backend/openrazer/ProfileTest.java
package uk.co.bithatch.snake.lib.backend.openrazer; import java.util.Map; import uk.co.bithatch.linuxio.EventCode; import uk.co.bithatch.snake.lib.Backend; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.lib.binding.MapSequence; import uk.co.bithatch.snake.lib.binding.Profile; import uk.co.bithatch.snake.lib.binding.ProfileMap; public class ProfileTest { public static void main(String[] args) throws Exception { try (Backend be = new OpenRazerBackend()) { be.init(); Device device = be.getDevices().get(0); for (Profile profile : device.getProfiles()) { System.out.println(profile + " " + (profile.isActive() ? "*" : "")); for (ProfileMap map : profile.getMaps()) { for (Map.Entry<EventCode, MapSequence> en : map.getSequences().entrySet()) { System.out.println(" " + en.getKey() + " : " + en.getValue()); } } } } } }
901
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
RazerRegionBacklight.java
/FileExtraction/Java_unseen/bithatch_snake/snake-backend-openrazer/src/main/java/uk/co/bithatch/snake/lib/backend/openrazer/RazerRegionBacklight.java
package uk.co.bithatch.snake.lib.backend.openrazer; import org.freedesktop.dbus.annotations.DBusInterfaceName; import org.freedesktop.dbus.interfaces.DBusInterface; @DBusInterfaceName("razer.device.lighting.backlight") public interface RazerRegionBacklight extends DBusInterface { boolean getBacklightActive(); void setBacklightActive(boolean active); }
360
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
RazerRegionProfileLEDs.java
/FileExtraction/Java_unseen/bithatch_snake/snake-backend-openrazer/src/main/java/uk/co/bithatch/snake/lib/backend/openrazer/RazerRegionProfileLEDs.java
package uk.co.bithatch.snake.lib.backend.openrazer; import org.freedesktop.dbus.annotations.DBusInterfaceName; import org.freedesktop.dbus.interfaces.DBusInterface; @DBusInterfaceName("razer.device.lighting.profile_led") public interface RazerRegionProfileLEDs extends DBusInterface { boolean getRedLED(); void setRedLED(boolean red); boolean getGreenLED(); void setGreenLED(boolean green); boolean getBlueLED(); void setBlueLED(boolean blue); }
461
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
RazerCustom.java
/FileExtraction/Java_unseen/bithatch_snake/snake-backend-openrazer/src/main/java/uk/co/bithatch/snake/lib/backend/openrazer/RazerCustom.java
package uk.co.bithatch.snake.lib.backend.openrazer; import org.freedesktop.dbus.annotations.DBusInterfaceName; import org.freedesktop.dbus.interfaces.DBusInterface; @DBusInterfaceName("razer.device.lighting.custom") public interface RazerCustom extends DBusInterface { void setRipple(byte red1, byte green1, byte blue1, double refreshRate); void setRippleRandomColour(double refreshRate); }
397
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Configuration.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/Configuration.java
package uk.co.bithatch.snake.ui; import java.util.Arrays; import java.util.Collection; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import javafx.beans.property.BooleanProperty; import javafx.beans.property.FloatProperty; import javafx.beans.property.IntegerProperty; import javafx.beans.property.Property; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleFloatProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.scene.paint.Color; import uk.co.bithatch.snake.ui.addons.Theme; public class Configuration { public enum TrayIcon { OFF, AUTO, DARK, LIGHT, COLOR } // private static final float GAIN = 1.0f; private Property<Theme> theme = new SimpleObjectProperty<>(); private BooleanProperty decorated = new SimpleBooleanProperty(); private BooleanProperty turnOffOnExit = new SimpleBooleanProperty(); private IntegerProperty x = new SimpleIntegerProperty(); private IntegerProperty y = new SimpleIntegerProperty(); private IntegerProperty w = new SimpleIntegerProperty(); private IntegerProperty h = new SimpleIntegerProperty(); private IntegerProperty audioSource = new SimpleIntegerProperty(); private IntegerProperty audioFPS = new SimpleIntegerProperty(); private BooleanProperty audioFFT = new SimpleBooleanProperty(); private FloatProperty audioGain = new SimpleFloatProperty(); private IntegerProperty transparency = new SimpleIntegerProperty(); private BooleanProperty showBattery = new SimpleBooleanProperty(); private BooleanProperty whenLow = new SimpleBooleanProperty(); private Property<TrayIcon> trayIcon = new SimpleObjectProperty<>(); private Preferences node; class ColorPreferenceUpdateChangeListener implements ChangeListener<Color> { private Preferences node; private String key; ColorPreferenceUpdateChangeListener(Preferences node, String key) { this.node = node; this.key = key; } @Override public void changed(ObservableValue<? extends Color> observable, Color oldValue, Color newValue) { putColor(key, node, newValue); } } class ThemePreferenceUpdateChangeListener implements ChangeListener<Theme> { private Preferences node; private String key; ThemePreferenceUpdateChangeListener(Preferences node, String key) { this.node = node; this.key = key; } @Override public void changed(ObservableValue<? extends Theme> observable, Theme oldValue, Theme newValue) { node.put(key, newValue.getId()); } } class BooleanPreferenceUpdateChangeListener implements ChangeListener<Boolean> { private Preferences node; private String key; BooleanPreferenceUpdateChangeListener(Preferences node, String key) { this.node = node; this.key = key; } @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { node.putBoolean(key, newValue); } } class IntegerPreferenceUpdateChangeListener implements ChangeListener<Number> { private Preferences node; private String key; IntegerPreferenceUpdateChangeListener(Preferences node, String key) { this.node = node; this.key = key; } @Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { node.putInt(key, newValue.intValue()); } } class FloatPreferenceUpdateChangeListener implements ChangeListener<Number> { private Preferences node; private String key; FloatPreferenceUpdateChangeListener(Preferences node, String key) { this.node = node; this.key = key; } @Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { node.putFloat(key, newValue.floatValue()); } } class TrayIconPreferenceUpdateChangeListener implements ChangeListener<TrayIcon> { private Preferences node; private String key; TrayIconPreferenceUpdateChangeListener(Preferences node, String key) { this.node = node; this.key = key; } @Override public void changed(ObservableValue<? extends TrayIcon> observable, TrayIcon oldValue, TrayIcon newValue) { node.put(key, newValue.name()); } } Configuration(Preferences node, App context) { this.node = node; showBattery.setValue(node.getBoolean("showBattery", true)); showBattery.addListener(new BooleanPreferenceUpdateChangeListener(node, "showBattery")); whenLow.setValue(node.getBoolean("whenLow", true)); whenLow.addListener(new BooleanPreferenceUpdateChangeListener(node, "whenLow")); trayIcon.setValue(TrayIcon.valueOf(node.get("trayIcon", TrayIcon.AUTO.name()))); trayIcon.addListener(new TrayIconPreferenceUpdateChangeListener(node, "trayIcon")); decorated.setValue(node.getBoolean("decorated", false)); decorated.addListener(new BooleanPreferenceUpdateChangeListener(node, "decorated")); decorated.addListener((e) -> { if (decorated.get()) { transparency.setValue(0); } }); turnOffOnExit.setValue(node.getBoolean("turnOffOnExit", true)); turnOffOnExit.addListener(new BooleanPreferenceUpdateChangeListener(node, "turnOffOnExit")); audioSource.setValue(node.getInt("audioSource", 0)); audioSource.addListener(new IntegerPreferenceUpdateChangeListener(node, "audioSource")); audioFPS.setValue(node.getInt("audioFPS", 10)); audioFPS.addListener(new IntegerPreferenceUpdateChangeListener(node, "audioFPS")); audioFFT.setValue(node.getBoolean("audioFFT", true)); audioFFT.addListener(new BooleanPreferenceUpdateChangeListener(node, "audioFFT")); audioGain.setValue(node.getInt("audioGain", 1)); audioGain.addListener(new FloatPreferenceUpdateChangeListener(node, "audioGain")); x.setValue(node.getInt("x", 0)); x.addListener(new IntegerPreferenceUpdateChangeListener(node, "x")); y.setValue(node.getInt("y", 0)); y.addListener(new IntegerPreferenceUpdateChangeListener(node, "y")); w.setValue(node.getInt("w", 0)); w.addListener(new IntegerPreferenceUpdateChangeListener(node, "w")); h.setValue(node.getInt("h", 0)); h.addListener(new IntegerPreferenceUpdateChangeListener(node, "h")); transparency.setValue(node.getInt("transparency", 0)); transparency.addListener(new IntegerPreferenceUpdateChangeListener(node, "transparency")); String themeName = node.get("theme", ""); Collection<Theme> themes = context.getAddOnManager().getThemes(); if (themes.isEmpty()) throw new IllegalStateException("No themes. Please add a theme module to the classpath or modulepath."); Theme firstTheme = themes.iterator().next(); if (themeName.equals("")) { themeName = firstTheme.getId(); } Theme selTheme = context.getAddOnManager().getTheme(themeName); if (selTheme == null && !themeName.equals(firstTheme.getId())) selTheme = firstTheme; theme.setValue(selTheme); theme.addListener(new ThemePreferenceUpdateChangeListener(node, "theme")); } public boolean hasBounds() { try { return Arrays.asList(node.keys()).contains("x"); } catch (BackingStoreException e) { return false; } } return audioGain; } static void putColor(String key, Preferences p, Color color) { p.putDouble(key + "_r", color.getRed()); p.putDouble(key + "_g", color.getGreen()); p.putDouble(key + "_b", color.getBlue()); p.putDouble(key + "_a", color.getOpacity()); } static Color getColor(String key, Preferences p, Color defaultColour) { return new Color(p.getDouble(key + "_r", defaultColour == null ? 1.0 : defaultColour.getRed()), p.getDouble(key + "_g", defaultColour == null ? 1.0 : defaultColour.getGreen()), p.getDouble(key + "_b", defaultColour == null ? 1.0 : defaultColour.getBlue()), p.getDouble(key + "_a", defaultColour == null ? 1.0 : defaultColour.getOpacity())); } }
7,875
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
module-info.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/module-info.java
module uk.co.bithatch.snake.ui { requires java.desktop; requires transitive javafx.controls; requires transitive javafx.graphics; requires transitive javafx.fxml; requires transitive javafx.swing; requires jdk.zipfs; requires transitive uk.co.bithatch.snake.lib; requires transitive javafx.web; requires com.goxr3plus.fxborderlessscene; requires kotlin.stdlib; requires SystemTray; requires Updates; requires transitive uk.co.bithatch.snake.widgets; exports uk.co.bithatch.snake.ui; exports uk.co.bithatch.snake.ui.addons; exports uk.co.bithatch.snake.ui.effects; exports uk.co.bithatch.snake.ui.util; exports uk.co.bithatch.snake.ui.designer; exports uk.co.bithatch.snake.ui.widgets; exports uk.co.bithatch.snake.ui.macros; exports uk.co.bithatch.snake.ui.drawing; exports uk.co.bithatch.snake.ui.audio; exports uk.co.bithatch.snake.ui.tray; opens uk.co.bithatch.snake.ui; opens uk.co.bithatch.snake.ui.icons; opens uk.co.bithatch.snake.ui.designer; opens uk.co.bithatch.snake.ui.widgets; opens uk.co.bithatch.snake.ui.tray; requires transitive com.sshtools.forker.wrapped; requires transitive org.commonmark; requires transitive com.sshtools.icongenerator.common; requires javafx.base; requires transitive org.codehaus.groovy; requires transitive uk.co.bithatch.linuxio; requires com.sshtools.twoslices; requires org.controlsfx.controls; requires transitive uk.co.bithatch.macrolib; requires uk.co.bithatch.jimpulse; requires transitive uk.co.bithatch.jdraw; requires transitive com.sshtools.jfreedesktop.javafx; requires transitive org.kordamp.ikonli.fontawesome; requires transitive org.kordamp.ikonli.javafx; requires transitive org.kordamp.ikonli.swing; uses uk.co.bithatch.snake.lib.Backend; uses uk.co.bithatch.snake.ui.PlatformService; uses uk.co.bithatch.snake.ui.EffectHandler; provides uk.co.bithatch.snake.ui.EffectHandler with uk.co.bithatch.snake.ui.effects.BreathEffectHandler, uk.co.bithatch.snake.ui.effects.OnEffectHandler, uk.co.bithatch.snake.ui.effects.OffEffectHandler, uk.co.bithatch.snake.ui.effects.PulsateEffectHandler, uk.co.bithatch.snake.ui.effects.ReactiveEffectHandler, uk.co.bithatch.snake.ui.effects.RippleEffectHandler, uk.co.bithatch.snake.ui.effects.SpectrumEffectHandler, uk.co.bithatch.snake.ui.effects.StarlightEffectHandler, uk.co.bithatch.snake.ui.effects.StaticEffectHandler, uk.co.bithatch.snake.ui.effects.WaveEffectHandler, uk.co.bithatch.snake.ui.effects.AudioEffectHandler; }
2,544
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Confirm.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/Confirm.java
package uk.co.bithatch.snake.ui; import java.text.MessageFormat; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; public class Confirm extends AbstractController implements Modal { @FXML private Label title; @FXML private Label description; @FXML private Hyperlink yes; @FXML private Hyperlink no; private Runnable onYes; private Runnable onNo; public void confirm(ResourceBundle bundle, String prefix, Runnable onYes, Object... args) { confirm(bundle, prefix, onYes, null, args); } public void confirm(ResourceBundle bundle, String prefix, Runnable onYes, Runnable onNo, Object... args) { title.textProperty().set(MessageFormat.format(bundle.getString(prefix + ".title"), (Object[]) args)); description.textProperty() .set(MessageFormat.format(bundle.getString(prefix + ".description"), (Object[]) args)); yes.textProperty().set(MessageFormat.format(bundle.getString(prefix + ".yes"), (Object[]) args)); no.textProperty().set(MessageFormat.format(bundle.getString(prefix + ".no"), (Object[]) args)); this.onYes = onYes; this.onNo = onNo; } public Label getTitle() { return title; } public Hyperlink getYes() { return yes; } public Hyperlink getNo() { return no; } @FXML void evtNo() { if (onNo != null) { onNo.run(); } context.pop(); } @FXML void evtYes() { onYes.run(); context.pop(); } }
1,452
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Options.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/Options.java
package uk.co.bithatch.snake.ui; import java.io.IOException; import java.lang.System.Logger.Level; import java.text.MessageFormat; import java.util.ResourceBundle; import java.util.prefs.PreferenceChangeEvent; import java.util.prefs.PreferenceChangeListener; import javafx.animation.FadeTransition; import javafx.application.Platform; import javafx.beans.binding.Bindings; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.ColorPicker; import javafx.scene.control.ComboBox; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.Slider; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.BorderPane; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.util.Duration; import uk.co.bithatch.snake.lib.Capability; import uk.co.bithatch.snake.ui.Configuration.TrayIcon; import uk.co.bithatch.snake.ui.addons.AddOn; import uk.co.bithatch.snake.ui.addons.AddOnManager.Listener; import uk.co.bithatch.snake.ui.addons.Theme; import uk.co.bithatch.snake.widgets.Direction; public class Options extends AbstractDeviceController implements Listener, PreferenceChangeListener { final static System.Logger LOG = System.getLogger(Options.class.getName()); final static ResourceBundle bundle = ResourceBundle.getBundle(Options.class.getName()); @FXML private ColorPicker color; @FXML private CheckBox decorated; @FXML private ComboBox<Theme> theme; @FXML private BorderPane optionsHeader; @FXML private Label transparencyLabel; @FXML private Slider transparency; @FXML private RadioButton noTrayIcon; @FXML private RadioButton autoTrayIcon; @FXML private RadioButton darkTrayIcon; @FXML private RadioButton lightTrayIcon; @FXML private RadioButton colorTrayIcon; @FXML private Label noTrayIconLabel; @FXML private Label autoTrayIconLabel; @FXML private Label darkTrayIconLabel; @FXML private Label lightTrayIconLabel; @FXML private Label colorTrayIconLabel; @FXML private CheckBox showBattery; @FXML private CheckBox whenLow; @FXML private CheckBox startOnLogin; @FXML private ToggleGroup trayIconGroup; @FXML private CheckBox betas; @FXML private CheckBox updateAutomatically; @FXML private CheckBox telemetry; @FXML private CheckBox checkForUpdates; @FXML private VBox updates; @FXML private Hyperlink startUpdate; @FXML private HBox updatesContainer; @FXML private Label availableVersion; @FXML private Label installedVersion; @FXML private FlowPane controls; public FlowPane getControls() { return controls; } @Override protected void onConfigure() throws Exception { noTrayIconLabel.setLabelFor(noTrayIcon); autoTrayIconLabel.setLabelFor(autoTrayIcon); darkTrayIconLabel.setLabelFor(darkTrayIcon); lightTrayIconLabel.setLabelFor(lightTrayIcon); colorTrayIconLabel.setLabelFor(colorTrayIcon); Configuration cfg = context.getConfiguration(); startOnLogin.selectedProperty().addListener((e) -> setStartOnLogin(cfg)); startOnLogin.visibleProperty().set(PlatformService.isPlatformSupported()); whenLow.visibleProperty().bind(showBattery.visibleProperty()); whenLow.managedProperty().bind(whenLow.visibleProperty()); showBattery.managedProperty().bind(showBattery.visibleProperty()); showBattery.visibleProperty().set(context.getBackend().getCapabilities().contains(Capability.BATTERY)); if (PlatformService.isPlatformSupported()) { PlatformService ps = PlatformService.get(); startOnLogin.selectedProperty().set(ps.isStartOnLogin()); updatesContainer.visibleProperty().set(ps.isUpdateableApp()); telemetry.selectedProperty().set(cfg.isTelemetry()); telemetry.selectedProperty() .addListener((e) -> cfg.setTelemetry(telemetry.selectedProperty().get())); updateAutomatically.selectedProperty().set(ps.isUpdateAutomatically()); updateAutomatically.selectedProperty() .addListener((e) -> ps.setUpdateAutomatically(updateAutomatically.selectedProperty().get())); checkForUpdates.selectedProperty().set(ps.isCheckForUpdates()); checkForUpdates.selectedProperty().addListener((e) -> { ps.setCheckForUpdates(checkForUpdates.selectedProperty().get()); updates.visibleProperty().set(ps.isUpdateAvailable() && ps.isCheckForUpdates()); }); betas.selectedProperty().set(ps.isBetas()); betas.selectedProperty().addListener((e) -> { ps.setBetas(betas.selectedProperty().get()); startUpdate.disableProperty().set(true); new Thread() { public void run() { try { Thread.sleep(3000); } catch (Exception e) { } System.exit(90); } }.start(); }); updates.visibleProperty().set(ps.isUpdateAvailable() && ps.isCheckForUpdates()); updates.managedProperty().bind(updates.visibleProperty()); updates.getStyleClass().add("warning"); if (ps.isUpdateAvailable()) { FadeTransition anim = new FadeTransition(Duration.seconds(5)); anim.setAutoReverse(true); anim.setCycleCount(FadeTransition.INDEFINITE); anim.setNode(updates); anim.setFromValue(0.5); anim.setToValue(1); anim.play(); availableVersion.textProperty().set(MessageFormat.format(bundle.getString("availableVersion"), PlatformService.get().getAvailableVersion())); installedVersion.textProperty().set(MessageFormat.format(bundle.getString("installedVersion"), PlatformService.get().getInstalledVersion())); } else { availableVersion.textProperty().set(""); installedVersion.textProperty().set(""); } } else { updatesContainer.visibleProperty().set(false); } betas.disableProperty().bind(Bindings.not(checkForUpdates.selectedProperty())); updateAutomatically.disableProperty().bind(Bindings.not(checkForUpdates.selectedProperty())); checkForUpdates.managedProperty().bind(checkForUpdates.visibleProperty()); startOnLogin.selectedProperty().addListener((e) -> { try { PlatformService.get().setStartOnLogin(startOnLogin.selectedProperty().get()); } catch (IOException e1) { LOG.log(Level.ERROR, "Failed to set start on login state.", e); } }); optionsHeader.setBackground(createHeaderBackground()); decorated.setSelected(cfg.isDecorated()); decorated.selectedProperty().addListener((e,o,n) -> context.getConfiguration().setDecorated(n)); theme.itemsProperty().get().addAll(context.getAddOnManager().getThemes()); theme.getSelectionModel().select(context.getConfiguration().getTheme()); transparencyLabel.setLabelFor(transparency); transparency.disableProperty().bind(decorated.selectedProperty()); transparency.setValue(cfg.getTransparency()); transparency.valueProperty().addListener((e,o,n) -> context.getConfiguration().setTransparency(n.intValue())); if (context.getWindow() != null) { context.getWindow().getOptions().visibleProperty().set(false); } trayIconGroup.selectedToggleProperty().addListener((e,o,n) -> { if (noTrayIcon.selectedProperty().get()) cfg.setTrayIcon(TrayIcon.OFF); else if (autoTrayIcon.selectedProperty().get()) cfg.setTrayIcon(TrayIcon.AUTO); else if (darkTrayIcon.selectedProperty().get()) cfg.setTrayIcon(TrayIcon.DARK); else if (lightTrayIcon.selectedProperty().get()) cfg.setTrayIcon(TrayIcon.LIGHT); else if (colorTrayIcon.selectedProperty().get()) cfg.setTrayIcon(TrayIcon.COLOR); setAvailable(cfg); setStartOnLogin(cfg); }); showBattery.setSelected(cfg.isShowBattery()); showBattery.selectedProperty().addListener((e,o,n) -> context.getConfiguration().setShowBattery(n)); whenLow.setSelected(cfg.isWhenLow()); whenLow.disableProperty().bind(Bindings.not(showBattery.selectedProperty())); whenLow.selectedProperty().addListener((e,o,n) -> context.getConfiguration().setWhenLow(n)); switch (cfg.getTrayIcon()) { case OFF: noTrayIcon.selectedProperty().set(true); break; case AUTO: autoTrayIcon.selectedProperty().set(true); break; case DARK: darkTrayIcon.selectedProperty().set(true); break; case LIGHT: lightTrayIcon.selectedProperty().set(true); break; default: colorTrayIcon.selectedProperty().set(true); break; } context.getAddOnManager().addListener(this); cfg.getNode().addPreferenceChangeListener(this); setAvailable(cfg); } @Override protected void onDeviceCleanUp() { super.onDeviceCleanUp(); context.getConfiguration().getNode().removePreferenceChangeListener(this); } private void setStartOnLogin(Configuration cfg) { try { PlatformService.get() .setStartOnLogin(cfg.getTrayIcon() != TrayIcon.OFF && startOnLogin.selectedProperty().get()); } catch (IOException e) { LOG.log(Level.ERROR, "Failed to set start on login state.", e); } } private void setAvailable(Configuration cfg) { showBattery.disableProperty().set(cfg.getTrayIcon() == TrayIcon.OFF); startOnLogin.disableProperty().set(cfg.getTrayIcon() == TrayIcon.OFF); } @FXML void evtStartUpdate() { System.exit(100); } @FXML void evtTheme() { context.getConfiguration().setTheme(theme.getSelectionModel().getSelectedItem()); } @FXML void evtOpenAddOns() { context.push(AddOns.class, Direction.FROM_BOTTOM); } @FXML void evtBack() { if (context.getWindow() != null) { context.getWindow().getOptions().visibleProperty().set(true); } context.pop(); } @Override public void addOnAdded(AddOn addOn) { if (addOn instanceof Theme) Platform.runLater(() -> theme.itemsProperty().get().add((Theme) addOn)); } @Override public void addOnRemoved(AddOn addOn) { if (addOn instanceof Theme) Platform.runLater(() -> theme.itemsProperty().get().remove((Theme) addOn)); } @Override public void preferenceChange(PreferenceChangeEvent evt) { Configuration cfg = context.getConfiguration(); if (evt.getKey().equals(Configuration.PREF_DECORATED)) decorated.setSelected(cfg.isDecorated()); else if (evt.getKey().equals(Configuration.PREF_THEME)) theme.getSelectionModel().select(cfg.getTheme()); else if (evt.getKey().equals(Configuration.PREF_TRANSPARENCY)) transparency.setValue(cfg.getTransparency()); else if (evt.getKey().equals(Configuration.PREF_SHOW_BATTERY)) showBattery.setSelected(cfg.isShowBattery()); else if (evt.getKey().equals(Configuration.PREF_WHEN_LOW)) whenLow.setSelected(cfg.isWhenLow()); } }
10,389
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
AbstractBackendEffectController.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/AbstractBackendEffectController.java
package uk.co.bithatch.snake.ui; import java.util.Objects; import uk.co.bithatch.snake.lib.effects.Effect; import uk.co.bithatch.snake.ui.effects.AbstractBackendEffectHandler; public abstract class AbstractBackendEffectController<E extends Effect, H extends AbstractBackendEffectHandler<E, ?>> extends AbstractEffectController<E, H> { private E effect; public E getEffect() { return effect; } public final void setEffect(E effect) { this.effect = effect; onSetEffect(); } protected void onSetEffect() { } @SuppressWarnings("unchecked") @Override protected void onSetEffectHandler() { Effect deviceEffect = getRegion().getEffect(); Class<?> deviceEffectClass = deviceEffect == null ? null : deviceEffect.getClass(); Class<? extends Effect> requiredEffectClass = getEffectHandler().getBackendEffectClass(); if (Objects.equals(requiredEffectClass, deviceEffectClass)) { setEffect((E) deviceEffect); } else { E newEffect = (E) getRegion().createEffect(requiredEffectClass); getEffectHandler().load(getRegion(), newEffect); setEffect(newEffect); } } }
1,099
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
PollRateControl.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/PollRateControl.java
package uk.co.bithatch.snake.ui; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.Slider; import uk.co.bithatch.snake.lib.Device; public class PollRateControl extends ControlController { @FXML private Label pollRateText; @FXML private Slider pollRate; @Override protected void onSetControlDevice() { Device dev = getDevice(); pollRate.maxProperty().set(2); setPollRateForDevice(dev); pollRate.setShowTickMarks(true); pollRate.setSnapToTicks(true); pollRate.setMajorTickUnit(1); pollRate.setMinorTickCount(0); pollRate.valueProperty().addListener((e) -> { int pr; switch ((int) pollRate.valueProperty().get()) { case 2: pr = 1000; break; case 1: pr = 500; break; default: pr = 125; break; } dev.setPollRate(pr); pollRateText.textProperty().set(String.format("%dHz", dev.getPollRate())); }); pollRateText.textProperty().set(String.format("%dHz", dev.getPollRate())); } private void setPollRateForDevice(Device dev) { switch (dev.getPollRate()) { case 1000: pollRate.valueProperty().set(2); break; case 500: pollRate.valueProperty().set(1); break; default: pollRate.valueProperty().set(0); break; } } }
1,249
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
EffectHandler.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/EffectHandler.java
package uk.co.bithatch.snake.ui; import java.net.URL; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.image.ImageView; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.lib.Lit; import uk.co.bithatch.snake.lib.effects.Effect; import uk.co.bithatch.snake.lib.effects.Matrix; public interface EffectHandler<E, C extends AbstractEffectController<E, ?>> { default String getName() { return getClass().getSimpleName(); } default boolean isMatrixBased() { return Matrix.class.equals(getBackendEffectClass()); } Class<? extends Effect> getBackendEffectClass(); Device getDevice(); default boolean isRegions() { return !isMatrixBased(); } void open(App context, Device component); Class<C> getOptionsController(); default boolean hasOptions() { return getOptionsController() != null; } default void added(Device device) { } default void removed(Device device) { } void store(Lit component, C controller); void update(Lit component); boolean isSupported(Lit component); URL getEffectImage(int size); default Node getEffectImageNode(int size, int viewSize) { URL effectImage = getEffectImage(size); if (effectImage == null) return new Label("Missing image " + getClass().getSimpleName()); else { ImageView iv = new ImageView(effectImage.toExternalForm()); iv.setFitHeight(viewSize); iv.setFitWidth(viewSize); iv.setSmooth(true); iv.setPreserveRatio(true); return iv; } } String getDisplayName(); E activate(Lit component); default void deactivate(Lit component) { } void select(Lit component); App getContext(); default boolean isReadOnly() { return true; } }
1,695
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
MacroProfileControl.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/MacroProfileControl.java
package uk.co.bithatch.snake.ui; import java.io.IOException; import java.lang.System.Logger; import java.util.Iterator; import java.util.ResourceBundle; import org.controlsfx.control.SearchableComboBox; import org.kordamp.ikonli.fontawesome.FontAwesome; import org.kordamp.ikonli.javafx.FontIcon; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.ContextMenu; import javafx.scene.control.Hyperlink; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.control.MenuItem; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.util.Callback; import uk.co.bithatch.macrolib.MacroBank; import uk.co.bithatch.macrolib.MacroDevice; import uk.co.bithatch.macrolib.MacroProfile; import uk.co.bithatch.macrolib.MacroSystem; import uk.co.bithatch.macrolib.MacroSystem.ActiveBankListener; import uk.co.bithatch.macrolib.MacroSystem.ActiveProfileListener; import uk.co.bithatch.macrolib.MacroSystem.MacroSystemListener; import uk.co.bithatch.macrolib.MacroSystem.ProfileListener; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.widgets.Direction; import uk.co.bithatch.snake.widgets.GeneratedIcon; import uk.co.bithatch.snake.widgets.JavaFX; public class MacroProfileControl extends ControlController implements ActiveBankListener, ActiveProfileListener, ProfileListener, MacroSystemListener { final static Logger LOG = System.getLogger(MacroProfileControl.class.getName()); final static ResourceBundle bundle = ResourceBundle.getBundle(MacroProfileControl.class.getName()); @FXML private SearchableComboBox<MacroProfile> profiles; @FXML private VBox banks; @FXML private Hyperlink addProfile; @FXML private Hyperlink configure; private MacroSystem macroSystem; private boolean adjusting; @Override protected void onDeviceCleanUp() { macroSystem.removeActiveBankListener(this); macroSystem.removeProfileListener(this); macroSystem.removeActiveProfileListener(this); macroSystem.removeMacroSystemListener(this); } @Override protected void onSetControlDevice() { macroSystem = context.getMacroManager().getMacroSystem(); buildProfiles(); buildBanks(); configureForProfile(); macroSystem.addActiveBankListener(this); macroSystem.addProfileListener(this); macroSystem.addActiveProfileListener(this); macroSystem.addMacroSystemListener(this); Callback<ListView<MacroProfile>, ListCell<MacroProfile>> factory = listView -> { return new ListCell<MacroProfile>() { @Override protected void updateItem(MacroProfile item, boolean empty) { super.updateItem(item, empty); if (item == null || empty) { setText(""); } else { setText(item.getName()); } } }; }; profiles.setButtonCell(factory.call(null)); profiles.setCellFactory(factory); profiles.getSelectionModel().select(macroSystem.getActiveProfile(getMacroDevice())); profiles.getSelectionModel().selectedItemProperty().addListener((e, o, n) -> { if (n != null && !adjusting) { try { n.makeActive(); } catch (IOException e1) { error(e1); } } }); } protected void buildProfiles() { MacroProfile sel = profiles.getSelectionModel().getSelectedItem(); profiles.getSelectionModel().clearSelection(); profiles.getItems().clear(); try { MacroDevice macroDevice = getMacroDevice(); for (Iterator<MacroProfile> profileIt = macroSystem.profiles(macroDevice); profileIt.hasNext();) { MacroProfile profile = profileIt.next(); profiles.getItems().add(profile); } if (profiles.getItems().contains(sel)) profiles.getSelectionModel().select(sel); } catch (Exception e) { error(e); } } protected void buildBanks() { banks.getChildren().clear(); try { MacroDevice macroDevice = getMacroDevice(); MacroProfile activeProfile = macroSystem.getActiveProfile(macroDevice); for (Iterator<MacroProfile> profileIt = macroSystem.profiles(macroDevice); profileIt.hasNext();) { MacroProfile profile = profileIt.next(); if (profile.equals(activeProfile)) { Iterator<MacroBank> macroBanks = profile.getBanks().iterator(); for (int i = 0; i < macroDevice.getBanks(); i++) { MacroBank bank = macroBanks.hasNext() ? macroBanks.next() : null; banks.getChildren().add(new BankRow(i, getDevice(), bank)); } } } } catch (Exception e) { error(e); } } protected void addBank(MacroProfile profile) { int nextFreeBankNumber; try { nextFreeBankNumber = profile.nextFreeBankNumber(); } catch (IllegalStateException ise) { error(ise); return; } Input confirm = context.push(Input.class, Direction.FADE); confirm.getConfirm().setGraphic(new FontIcon(FontAwesome.PLUS_CIRCLE)); confirm.setValidator((l) -> { String name = confirm.inputProperty().get(); boolean available = profile.getBank(name) == null; l.getStyleClass().clear(); if (available) { l.textProperty().set(""); l.visibleProperty().set(false); } else { l.visibleProperty().set(true); l.textProperty().set(bundle.getString("error.bankWithNameAlreadyExists")); l.getStyleClass().add("danger"); } return available; }); confirm.confirm(bundle, "addBank", () -> { profile.createBank(confirm.inputProperty().get()); }, String.valueOf(nextFreeBankNumber + 1)); } @FXML void evtConfigure() throws Exception { context.editMacros(this); } void configureForProfile() { MacroDevice device = getMacroDevice(); MacroBank profileBank = macroSystem.getActiveBank(device); /* Selected profile */ for (Node n : banks.getChildren()) { ((MacrosComponent) n).updateAvailability(); } configure.disableProperty().set(profileBank == null); } protected MacroDevice getMacroDevice() { return context.getMacroManager().getMacroDevice(getDevice()); } protected void remove(MacroBank bank) { Confirm confirm = context.push(Confirm.class, Direction.FADE); confirm.getYes().setGraphic(new FontIcon(FontAwesome.TRASH)); confirm.confirm(bundle, "removeBank", () -> { try { bank.remove(); } catch (IOException e) { error(e); } }, null, bank.getBank() + 1, bank.getDisplayName()); } @FXML void evtAddProfile() { Input confirm = context.push(Input.class, Direction.FADE); confirm.setValidator((l) -> { String name = confirm.inputProperty().get(); boolean available = macroSystem.getProfileWithName(getMacroDevice(), name) == null; l.getStyleClass().clear(); if (available) { l.textProperty().set(""); l.visibleProperty().set(false); } else { l.visibleProperty().set(true); l.textProperty().set(bundle.getString("error.nameAlreadyExists")); l.getStyleClass().add("danger"); } return available; }); confirm.confirm(bundle, "addProfile", () -> { macroSystem.createProfile(getMacroDevice(), confirm.inputProperty().get()); }); } interface MacrosComponent { void updateAvailability(); } class BankRow extends HBox implements MacrosComponent { MacroBank bank; Hyperlink link; Device device; GeneratedIcon icon; BankRow(int number, Device device, MacroBank bank) { this.bank = bank; this.device = device; getStyleClass().add("small"); getStyleClass().add("gapLeft"); setAlignment(Pos.CENTER_LEFT); icon = new GeneratedIcon(); icon.setPrefHeight(22); icon.setPrefWidth(22); icon.setText(String.valueOf(number + 1)); if (bank == null) { link = new Hyperlink(bundle.getString("empty")); link.setOnAction((e) -> { addBank(profiles.getSelectionModel().getSelectedItem()); }); link.getStyleClass().add("deemphasis"); icon.getStyleClass().add("deemphasis"); } else { icon.getStyleClass().add("filled"); link = new Hyperlink(bank.getDisplayName()); link.setOnAction((e) -> { try { bank.makeActive(); } catch (Exception ex) { error(ex); } }); ContextMenu bankContextMenu = new ContextMenu(); MenuItem remove = new MenuItem(bundle.getString("contextMenuRemove")); remove.onActionProperty().set((e) -> { remove(bank); }); bankContextMenu.getItems().add(remove); bankContextMenu.setOnShowing((e) -> { remove.visibleProperty().set(macroSystem.getNumberOfProfiles(getMacroDevice()) > 1 || bank.getProfile().getBanks().size() > 1); }); link.setContextMenu(bankContextMenu); } getChildren().add(icon); getChildren().add(link); updateAvailability(); } public void updateAvailability() { if (bank != null) { JavaFX.glowOrDeemphasis(this, bank.isActive()); if (bank.isDefault()) { if (!getStyleClass().contains("emphasis")) getStyleClass().add("emphasis"); } else { getStyleClass().remove("emphasis"); } } } } @Override public void profileChanged(MacroDevice device, MacroProfile profile) { macroSystemChanged(); } @Override public void activeProfileChanged(MacroDevice device, MacroProfile profile) { if (Platform.isFxApplicationThread()) { adjusting = true; try { buildBanks(); configureForProfile(); } finally { adjusting = false; } } else Platform.runLater(() -> activeProfileChanged(device, profile)); } @Override public void activeBankChanged(MacroDevice device, MacroBank bank) { if (Platform.isFxApplicationThread()) { adjusting = true; try { configureForProfile(); } finally { adjusting = false; } } else Platform.runLater(() -> activeBankChanged(device, bank)); } @Override public void macroSystemChanged() { if (Platform.isFxApplicationThread()) { adjusting = true; try { buildProfiles(); buildBanks(); configureForProfile(); } finally { adjusting = false; } } else Platform.runLater(() -> macroSystemChanged()); } }
9,882
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
BreathOptions.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/BreathOptions.java
package uk.co.bithatch.snake.ui; import javafx.beans.binding.Bindings; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import uk.co.bithatch.snake.lib.effects.Breath; import uk.co.bithatch.snake.lib.effects.Breath.Mode; import uk.co.bithatch.snake.ui.effects.BreathEffectHandler; import uk.co.bithatch.snake.widgets.ColorBar; import uk.co.bithatch.snake.widgets.Direction; import uk.co.bithatch.snake.widgets.JavaFX; public class BreathOptions extends AbstractBackendEffectController<Breath, BreathEffectHandler> { @FXML private ColorBar color; @FXML private ColorBar color1; @FXML private ColorBar color2; @FXML private Label colorLabel; @FXML private Label color1Label; @FXML private Label color2Label; @FXML private RadioButton single; @FXML private RadioButton dual; @FXML private RadioButton random; private boolean adjusting = false; public Mode getMode() { if (single.selectedProperty().get()) return Mode.SINGLE; else if (dual.selectedProperty().get()) return Mode.DUAL; else return Mode.RANDOM; } public int[] getColor() { return JavaFX.toRGB(color.getColor()); } public int[] getColor1() { return JavaFX.toRGB(color1.getColor()); } public int[] getColor2() { return JavaFX.toRGB(color2.getColor()); } @Override protected void onConfigure() throws Exception { color.disableProperty().bind(Bindings.not(single.selectedProperty())); color1.disableProperty().bind(Bindings.not(dual.selectedProperty())); color2.disableProperty().bind(Bindings.not(dual.selectedProperty())); colorLabel.setLabelFor(color); color1Label.setLabelFor(color1); color2Label.setLabelFor(color2); dual.selectedProperty().addListener((e) -> { if (dual.isSelected()) update(); }); single.selectedProperty().addListener((e) -> { if (single.isSelected()) update(); }); random.selectedProperty().addListener((e) -> { if (random.isSelected()) update(); }); color.colorProperty().addListener((e) -> update()); color1.colorProperty().addListener((e) -> update()); color2.colorProperty().addListener((e) -> update()); } protected void update() { if(!adjusting) getEffectHandler().store(getRegion(), BreathOptions.this); } @Override protected void onSetEffect() { Breath effect = getEffect(); adjusting = true; try { switch (effect.getMode()) { case DUAL: dual.selectedProperty().set(true); break; case SINGLE: single.selectedProperty().set(true); break; default: random.selectedProperty().set(true); break; } color.setColor(JavaFX.toColor(effect.getColor())); color1.setColor(JavaFX.toColor(effect.getColor1())); color2.setColor(JavaFX.toColor(effect.getColor2())); } finally { adjusting = false; } } @FXML void evtBack(ActionEvent evt) { context.pop(); } @FXML void evtOptions(ActionEvent evt) { context.push(Options.class, this, Direction.FROM_BOTTOM); } }
3,020
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
AbstractDeviceController.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/AbstractDeviceController.java
package uk.co.bithatch.snake.ui; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.Slider; import uk.co.bithatch.snake.lib.Capability; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.lib.Device.Listener; import uk.co.bithatch.snake.lib.binding.Profile; import uk.co.bithatch.snake.lib.binding.ProfileMap; import uk.co.bithatch.snake.widgets.JavaFX; public abstract class AbstractDeviceController extends AbstractController implements Listener { private Device device; @FXML private Slider brightness; @FXML private Label brightnessLabel; private boolean adjustingBrightness; @Override protected void onConfigure() throws Exception { } public Device getDevice() { return device; } public final void setDevice(Device device) { if (this.device != null) this.device.removeListener(this); this.device = device; try { if (brightness != null && brightnessLabel != null) { JavaFX.bindManagedToVisible(brightness); JavaFX.bindManagedToVisible(brightnessLabel); brightnessLabel.visibleProperty().bind(brightness.visibleProperty()); boolean supportsBrightness = device.getCapabilities().contains(Capability.BRIGHTNESS); brightness.setVisible(supportsBrightness); if (supportsBrightness) brightness.valueProperty().set(device.getBrightness()); else brightness.valueProperty().set(0); brightness.valueProperty().addListener((e, o, n) -> { if (!adjustingBrightness) { updateBrightness(); } }); } device.addListener(this); onSetDevice(); } catch (Exception e) { throw new IllegalStateException(String.format("Failed to configure UI for device %s.", device.getName()), e); } } @Override protected final void onCleanUp() { if (device != null) device.removeListener(this); onDeviceCleanUp(); } protected void onDeviceCleanUp() { } protected void onSetDevice() throws Exception { } private void updateBrightness() { adjustingBrightness = true; try { getDevice().setBrightness((short) brightness.valueProperty().get()); } finally { adjustingBrightness = false; } } @Override public final void changed(Device device, uk.co.bithatch.snake.lib.Region region) { if (!Platform.isFxApplicationThread()) Platform.runLater(() -> changed(device, region)); else { onChanged(device, region); if (!adjustingBrightness && brightness != null && device.getCapabilities().contains(Capability.BRIGHTNESS)) { adjustingBrightness = true; try { brightness.valueProperty().set(device.getBrightness()); } finally { adjustingBrightness = false; } } } } protected void onChanged(Device device, uk.co.bithatch.snake.lib.Region region) { } @Override public void activeMapChanged(ProfileMap map) { } @Override public void profileAdded(Profile profile) { } @Override public void profileRemoved(Profile profile) { } @Override public void mapAdded(ProfileMap profile) { } @Override public void mapChanged(ProfileMap profile) { } @Override public void mapRemoved(ProfileMap profile) { } }
3,167
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
SchedulerManager.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/SchedulerManager.java
package uk.co.bithatch.snake.ui; import java.io.Closeable; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; public class SchedulerManager implements Closeable { public enum Queue { DEVICE_IO, APP_IO, MACROS, TIMER, AUDIO } private Map<Queue, ScheduledExecutorService> schedulers = Collections.synchronizedMap(new HashMap<>()); public ScheduledExecutorService get(Queue queue) { synchronized (schedulers) { var s = schedulers.get(queue); if (s == null) { s = Executors.newScheduledThreadPool(1, (r) -> new Thread(r, "snake-" + queue.name())); schedulers.put(queue, s); } return s; } } public void clear(Queue queue) { synchronized (schedulers) { var s = schedulers.get(queue); if (s != null) { s.shutdown(); schedulers.remove(queue); } } } @Override public void close() throws IOException { synchronized (schedulers) { for (Map.Entry<Queue, ScheduledExecutorService> s : schedulers.entrySet()) { s.getValue().shutdownNow(); } schedulers.clear(); } } }
1,182
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Cache.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/Cache.java
package uk.co.bithatch.snake.ui; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.System.Logger.Level; import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import uk.co.bithatch.snake.ui.SchedulerManager.Queue; import uk.co.bithatch.snake.ui.util.Strings; public class Cache implements Closeable { final static System.Logger LOG = System.getLogger(Cache.class.getName()); private Properties index = new Properties(); private Set<URL> waiting = new HashSet<>(); private Map<String, String> resolved = Collections.synchronizedMap(new HashMap<>()); private App context; public Cache(App context) throws IOException { this.context = context; File cacheIndexFile = getIndexFile(); if (cacheIndexFile.exists()) { try (InputStream in = new FileInputStream(cacheIndexFile)) { index.load(in); } } } protected File getIndexFile() { return new File(getCacheDir(), "cache.index"); } public String getCachedImage(String image) { if (image == null || image.equals("")) return null; /* Was this previously resolved? */ String r = resolved.get(image); if (r != null) return r; String hash = Strings.genericHash(image); File cacheDir = getCacheDir(); try { File cacheFile = new File(cacheDir, hash); if (!cacheFile.exists()) { synchronized (index) { /* * Let the original URL be returned the first time, so as to not hold up the * current thread, and let JavaFX background image loading happen so the UI * thread is not held up either. * * In the background, we trigger the downloading of the image which may be used * the next time the URL is request. */ URL url = new URL(image); if (!waiting.contains(url)) { waiting.add(url); context.getSchedulerManager().get(Queue.APP_IO).execute(() -> { File tmpCacheFile = new File(cacheDir, hash + ".tmp"); try (InputStream in = url.openStream()) { try (OutputStream out = new FileOutputStream(tmpCacheFile)) { in.transferTo(out); } synchronized (index) { /* Index it */ index.setProperty(image, cacheFile.getName()); try (OutputStream out = new FileOutputStream(getIndexFile())) { index.store(out, "Snake Cache Index"); } catch (IOException ioe) { } resolved.put(image, cacheFile.toURI().toURL().toExternalForm()); } } catch (IOException ioe) { if(LOG.isLoggable(Level.DEBUG)) LOG.log(Level.ERROR, "Failed to cache image.", ioe); else LOG.log(Level.ERROR, "Failed to cache image. " + ioe.getMessage()); resolved.put(image, image); return; } tmpCacheFile.renameTo(cacheFile); }); } } } else { String path = cacheFile.toURI().toURL().toExternalForm(); resolved.put(image, path); return path; } } catch (MalformedURLException murle) { throw new IllegalStateException(String.format("Failed to construct image URL for %s.", image), murle); } return image; } static File getCacheDir() { File cacheDir = new File(System.getProperty("user.home") + File.separator + ".cache" + File.separator + "snake" + File.separator + "device-image-cache"); if (!cacheDir.exists() && !cacheDir.mkdirs()) { throw new IllegalStateException( String.format("Failed to create device image cache directory %s.", cacheDir)); } return cacheDir; } @Override public void close() throws IOException { } }
3,824
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
DeviceLayoutManager.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/DeviceLayoutManager.java
package uk.co.bithatch.snake.ui; import java.lang.System.Logger.Level; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import java.util.stream.Collectors; import javafx.util.Duration; import uk.co.bithatch.linuxio.EventCode; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.lib.DeviceType; import uk.co.bithatch.snake.lib.Region; import uk.co.bithatch.snake.lib.layouts.Accessory; import uk.co.bithatch.snake.lib.layouts.Accessory.AccessoryType; import uk.co.bithatch.snake.lib.layouts.Area; import uk.co.bithatch.snake.lib.layouts.ComponentType; import uk.co.bithatch.snake.lib.layouts.DeviceLayout; import uk.co.bithatch.snake.lib.layouts.DeviceLayouts; import uk.co.bithatch.snake.lib.layouts.DeviceLayouts.Listener; import uk.co.bithatch.snake.lib.layouts.DeviceView; import uk.co.bithatch.snake.lib.layouts.IO; import uk.co.bithatch.snake.lib.layouts.Key; import uk.co.bithatch.snake.lib.layouts.LED; import uk.co.bithatch.snake.lib.layouts.MatrixCell; import uk.co.bithatch.snake.lib.layouts.MatrixIO; import uk.co.bithatch.snake.lib.layouts.ViewPosition; import uk.co.bithatch.snake.ui.SchedulerManager.Queue; import uk.co.bithatch.snake.ui.util.Prefs; import uk.co.bithatch.snake.ui.util.Strings; import uk.co.bithatch.snake.ui.util.Time.Timer; public class DeviceLayoutManager implements Listener { final static System.Logger LOG = System.getLogger(DeviceLayoutManager.class.getName()); private DeviceLayouts backend; private Preferences prefs; private Timer saveTimer = new Timer(Duration.seconds(5), (e) -> queueSave()); private Set<DeviceLayout> dirty = Collections.synchronizedSet(new LinkedHashSet<>()); private App context; public DeviceLayoutManager(App context) { this.context = context; backend = new DeviceLayouts(); backend.addListener(this); prefs = context.getPreferences().node("layouts"); } public List<DeviceLayout> getLayouts() { List<DeviceLayout> l = new ArrayList<>(); for (DeviceLayout a : backend.getLayouts()) { Device device = context.getBackend().getDevice(a.getName()); if (device != null) { DeviceLayout u = getUserLayout(device); if (u != null) l.add(u); else l.add(a); } else l.add(a); } return l; } public boolean hasLayout(Device device) { return hasUserLayout(device) || backend.hasLayout(device); } public boolean hasUserLayout(Device device) { String id = Strings.toId(device.getName()); try { if (prefs.nodeExists(id)) return true; } catch (BackingStoreException e) { throw new IllegalStateException("Could not query layouts.", e); } return false; } public void addLayout(DeviceLayout layout) { backend.addLayout(layout); } public void save(DeviceLayout layout) { if (layout.isReadOnly()) { throw new IllegalArgumentException("Cannot save read only layouts."); } String id = Strings.toId(layout.getName()); Preferences layoutNode = prefs.node(id); layoutNode.put("deviceType", layout.getDeviceType().name()); layoutNode.putInt("matrixHeight", layout.getMatrixHeight()); layoutNode.putInt("matrixWidth", layout.getMatrixWidth()); layoutNode.put("viewOrder", String.join(",", layout.getViews().keySet().stream().map(ViewPosition::name).collect(Collectors.toList()))); Preferences viewsNode = layoutNode.node("views"); try { viewsNode.removeNode(); viewsNode = layoutNode.node("views"); for (DeviceView view : layout.getViews().values()) { Preferences viewNode = viewsNode.node(view.getPosition().name()); viewNode.putBoolean("desaturateImage", view.isDesaturateImage()); viewNode.putFloat("imageOpacity", view.getImageOpacity()); viewNode.putFloat("imageScale", view.getImageScale()); if (view.getImageUri() != null) viewNode.put("imageUri", view.getImageUri()); Preferences elementsNode = viewNode.node("elements"); int idx = 0; for (IO element : view.getElements()) { Preferences elementNode = elementsNode.node(String.valueOf(idx++)); elementNode.put("type", ComponentType.fromClass(element.getClass()).name()); if (element instanceof MatrixIO && ((MatrixIO) element).isMatrixLED()) { elementNode.putInt("matrixX", ((MatrixIO) element).getMatrixX()); elementNode.putInt("matrixY", ((MatrixIO) element).getMatrixY()); } else { elementNode.remove("matrixX"); elementNode.remove("matrixY"); } if (element instanceof Key && ((Key) element).getEventCode() != null) { elementNode.put("eventCode", ((Key) element).getEventCode().name()); } else { elementNode.remove("eventCode"); } if (element instanceof Key && ((Key) element).getLegacyKey() != null) { elementNode.put("legacyKey", ((Key) element).getLegacyKey().name()); } else { elementNode.remove("legacyKey"); } if (element instanceof MatrixCell) { if (((MatrixCell) element).getRegion() != null) elementNode.put("region", ((MatrixCell) element).getRegion().name()); else elementNode.remove("region"); elementNode.putBoolean("disabled", ((MatrixCell) element).isDisabled()); elementNode.putInt("width", ((MatrixCell) element).getWidth()); } if (element instanceof Area) { if (((Area) element).getRegion() != null) elementNode.put("region", ((Area) element).getRegion().name()); } if (element instanceof Accessory) { elementNode.put("accessory", ((Accessory) element).getAccessory().name()); } elementNode.putFloat("x", element.getX()); elementNode.putFloat("y", element.getY()); if (element.getLabel() != null) elementNode.put("label", element.getLabel()); } } layoutNode.flush(); } catch (BackingStoreException bse) { throw new IllegalStateException("Could not save layout.", bse); } } public DeviceLayout getLayout(Device device) { DeviceLayout layout = backend.hasLayout(device) ? backend.getLayout(device) : null; if(layout == null || layout.isReadOnly()) { /* Either a built-in or an add-on, is there a user layout to override it? */ DeviceLayout userLayout = getUserLayout(device); if (userLayout != null) { return userLayout; } } return layout; } protected DeviceLayout getUserLayout(Device device) { String id = Strings.toId(device.getName()); try { if (prefs.nodeExists(id)) { Preferences layoutNode = prefs.node(id); DeviceLayout dl = new DeviceLayout(device); dl.setDeviceType(DeviceType.valueOf(layoutNode.get("deviceType", DeviceType.UNRECOGNISED.name()))); dl.setMatrixHeight(layoutNode.getInt("matrixHeight", 1)); dl.setMatrixWidth(layoutNode.getInt("matrixWidth", 1)); List<String> viewOrder = Arrays.asList(Prefs.getStringList(layoutNode, "viewOrder")); Preferences viewsNode = layoutNode.node("views"); for (String viewPositionName : viewOrder) { Preferences viewNode = viewsNode.node(viewPositionName); DeviceView view = new DeviceView(); view.setLayout(dl); view.setDesaturateImage(viewNode.getBoolean("desaturateImage", false)); view.setImageOpacity(viewNode.getFloat("imageOpacity", 1)); view.setImageScale(viewNode.getFloat("imageScale", 1)); view.setImageUri(viewNode.get("imageUri", null)); try { view.setPosition(ViewPosition.valueOf(viewPositionName)); } catch (Exception e) { /* Let other views load, we can't really steal anothers position */ LOG.log(Level.ERROR, "Failed to load view.", e); continue; } Preferences elementsNode = viewNode.node("elements"); List<String> elementNodeNames = new ArrayList<>(Arrays.asList(elementsNode.childrenNames())); Collections.sort(elementNodeNames); for (String elementNodeName : elementNodeNames) { Preferences elementNode = elementsNode.node(elementNodeName); try { ComponentType type = ComponentType .valueOf(elementNode.get("type", ComponentType.LED.name())); IO element; switch (type) { case LED: LED led = new LED(view); setMatrixPositionFromPreferences(elementNode, led); String regionName = elementNode.get("region", null); element = led; break; case KEY: Key key = new Key(view); setMatrixPositionFromPreferences(elementNode, key); String name = elementNode.get("eventCode", ""); key.setEventCode(name.equals("") ? null : EventCode.valueOf(name)); name = elementNode.get("legacyKey", ""); key.setLegacyKey(name.equals("") ? null : uk.co.bithatch.snake.lib.Key.valueOf(name)); regionName = elementNode.get("region", null); element = key; break; case MATRIX_CELL: MatrixCell matrixCell = new MatrixCell(view); setMatrixPositionFromPreferences(elementNode, matrixCell); matrixCell.setDisabled(elementNode.getBoolean("disabled", false)); matrixCell.setWidth(elementNode.getInt("width", 0)); regionName = elementNode.get("region", null); if (regionName != null) matrixCell.setRegion(Region.Name.valueOf(regionName)); element = matrixCell; break; case AREA: Area area = new Area(view); regionName = elementNode.get("region", null); if (regionName != null) area.setRegion(Region.Name.valueOf(regionName)); element = area; break; case ACCESSORY: Accessory accessory = new Accessory(view); accessory.setAccessory(AccessoryType.valueOf(elementNode.get("accessory", null))); element = accessory; break; default: throw new UnsupportedOperationException(); } element.setLabel(elementNode.get("label", null)); element.setX(elementNode.getFloat("x", 0)); element.setY(elementNode.getFloat("y", 0)); view.addElement(element); } catch (IllegalArgumentException iae) { LOG.log(Level.WARNING, "Failed to load layout element. ", iae); } } dl.addView(view); } backend.registerLayout(dl); return dl; } } catch (BackingStoreException bse) { throw new IllegalStateException(bse); } return null; } protected void setMatrixPositionFromPreferences(Preferences elementNode, MatrixIO led) { int mx = elementNode.getInt("matrixX", -1); try { led.setMatrixX(mx); } catch (IllegalArgumentException iae) { LOG.log(Level.WARNING, String.format("Ignored based Matrix X %d, reset to zero", mx)); led.setMatrixX(0); } int my = elementNode.getInt("matrixY", -1); try { led.setMatrixY(my); } catch (IllegalArgumentException iae) { LOG.log(Level.WARNING, String.format("Ignored based Matrix Y %d, reset to zero", my)); led.setMatrixY(0); } led.setMatrixY(my); } public void addListener(Listener listener) { backend.addListener(listener); } public void removeListener(Listener listener) { backend.removeListener(listener); } public boolean hasOfficialLayout(Device device) { return backend.hasOfficialLayout(device); } public boolean hasLayout(DeviceLayout layout) { return backend.getLayouts().contains(layout); } public void remove(DeviceLayout layout) { if (!layout.isReadOnly()) { try { prefs.node(Strings.toId(layout.getName())).removeNode(); } catch (BackingStoreException e) { LOG.log(Level.ERROR, "Failed to remove layout node.", e); } } backend.remove(layout); } @Override public void viewChanged(DeviceLayout layout, DeviceView view) { changed(layout); } @Override public void viewElementAdded(DeviceLayout layout, DeviceView view, IO element) { changed(layout); } @Override public void viewElementChanged(DeviceLayout layout, DeviceView view, IO element) { changed(layout); } @Override public void viewElementRemoved(DeviceLayout layout, DeviceView view, IO element) { changed(layout); } @Override public void viewAdded(DeviceLayout layout, DeviceView view) { changed(layout); } @Override public void viewRemoved(DeviceLayout layout, DeviceView view) { changed(layout); } @Override public void layoutChanged(DeviceLayout layout) { changed(layout); } protected void changed(DeviceLayout layout) { dirty.add(layout); saveTimer.reset(); } void queueSave() { context.getSchedulerManager().get(Queue.APP_IO).execute(() -> { synchronized (dirty) { saveAll(); dirty.clear(); } }); } void saveAll() { for (DeviceLayout l : dirty) { if (!l.isReadOnly()) save(l); } } @Override public void layoutAdded(DeviceLayout layout) { layoutChanged(layout); } @Override public void layoutRemoved(DeviceLayout layout) { } }
12,854
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Window.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/Window.java
package uk.co.bithatch.snake.ui; import org.apache.commons.lang3.SystemUtils; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.geometry.Rectangle2D; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundImage; import javafx.scene.layout.BackgroundPosition; import javafx.scene.layout.BackgroundRepeat; import javafx.scene.layout.BackgroundSize; import javafx.scene.layout.BorderPane; import javafx.scene.layout.StackPane; import javafx.stage.Screen; import javafx.stage.Stage; import uk.co.bithatch.snake.widgets.Direction; public class Window extends AbstractController { // public static Font fxont; // // static { // foxnt = Font.loadFont(AwesomeIcons.class.getResource("FROSTBITE-Narrow.ttf").toExternalForm(), 12); // } @FXML private Hyperlink min; @FXML private Hyperlink max; @FXML private Hyperlink close; @FXML private Label title; @FXML private BorderPane bar; @FXML private BorderPane titleBar; @FXML private StackPane content; @FXML private Hyperlink options; @FXML private ImageView titleBarImage; private Rectangle2D bounds; @Override protected void onConfigure() throws Exception { titleBarImage.setImage( new Image(context.getConfiguration().getTheme().getResource("icons/app64.png").toExternalForm(), true)); titleBar.setBackground( new Background(new BackgroundImage( new Image(context.getConfiguration().getTheme().getResource("titleBar.png").toExternalForm(), true), BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, new BackgroundSize(100d, 100d, true, true, false, true)))); } public Hyperlink getOptions() { return options; } public BorderPane getBar() { return bar; } public StackPane getContent() { return content; } @FXML void evtMin(ActionEvent evt) { Stage stage = (Stage) ((Hyperlink) evt.getSource()).getScene().getWindow(); stage.setIconified(true); } @FXML void evtMax(ActionEvent evt) { Stage stage = (Stage) ((Hyperlink) evt.getSource()).getScene().getWindow(); if (SystemUtils.IS_OS_LINUX) { if (!stage.isMaximized()) { this.bounds = new Rectangle2D(stage.getX(), stage.getY(), stage.getWidth(), stage.getHeight()); stage.setMaximized(true); /* * Work around, maximize STIL doesn't work on Linux properly. * https://stackoverflow.com/questions/6864540/how-to-set-a-javafx-stage-frame- * to-maximized */ // Get current screen of the stage ObservableList<Screen> screens = Screen.getScreensForRectangle(this.bounds); // Change stage properties Rectangle2D newBounds = screens.get(0).getVisualBounds(); stage.setX(newBounds.getMinX()); stage.setY(newBounds.getMinY()); stage.setWidth(newBounds.getWidth()); stage.setHeight(newBounds.getHeight()); } else { stage.setMaximized(false); stage.setX(bounds.getMinX()); stage.setY(bounds.getMinY()); stage.setWidth(bounds.getWidth()); stage.setHeight(bounds.getHeight()); } } else stage.setMaximized(!stage.isMaximized()); } @FXML void evtClose(ActionEvent evt) { context.close(); } @FXML void evtAbout(ActionEvent evt) { context.push(About.class, Direction.FADE); } @FXML void evtOptions(ActionEvent evt) { context.push(Options.class, Direction.FROM_BOTTOM); } }
3,523
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
AudioOptions.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/AudioOptions.java
package uk.co.bithatch.snake.ui; import java.text.MessageFormat; import java.util.Arrays; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.control.Slider; import javafx.scene.control.Spinner; import javafx.scene.control.SpinnerValueFactory; import javafx.scene.layout.VBox; import javafx.util.Callback; import uk.co.bithatch.snake.lib.effects.Matrix; import uk.co.bithatch.snake.ui.audio.AudioManager.AudioSource; import uk.co.bithatch.snake.ui.drawing.JavaFXBacking; import uk.co.bithatch.snake.ui.effects.AudioEffectHandler; import uk.co.bithatch.snake.ui.effects.AudioEffectMode; import uk.co.bithatch.snake.ui.effects.BlobbyAudioEffectMode; import uk.co.bithatch.snake.ui.effects.BurstyAudioEffectMode; import uk.co.bithatch.snake.ui.effects.ExpandAudioEffectMode; import uk.co.bithatch.snake.ui.effects.LineyAudioEffectMode; import uk.co.bithatch.snake.ui.effects.PeaksAudioEffectMode; import uk.co.bithatch.snake.widgets.ColorBar; import uk.co.bithatch.snake.widgets.JavaFX; public class AudioOptions extends AbstractEffectController<Matrix, AudioEffectHandler> { final static ResourceBundle bundle = ResourceBundle.getBundle(AudioOptions.class.getName()); @FXML private ComboBox<AudioSource> source; @FXML private Slider gain; @FXML private Spinner<Integer> fps; @FXML private CheckBox fft; @FXML private VBox previewContainer; @FXML private ColorBar color1; @FXML private ColorBar color2; @FXML private ColorBar color3; @FXML private ComboBox<Class<? extends AudioEffectMode>> mode; private JavaFXBacking backing; @Override protected void onConfigure() throws Exception { source.getItems().addAll(context.getAudioManager().getSources()); Configuration cfg = context.getConfiguration(); /* Global stuff */ source.getSelectionModel().select(context.getAudioManager().getSource(cfg.getAudioSource())); source.valueProperty().addListener((e, o, n) -> cfg.setAudioSource(n.getName())); fps.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(1, 50)); fps.getValueFactory().setValue(cfg.getAudioFPS()); fps.getValueFactory().valueProperty().addListener((e, o, n) -> cfg.setAudioFPS(n)); fft.selectedProperty().set(cfg.isAudioFFT()); fft.selectedProperty().addListener((e, o, n) -> cfg.setAudioFFT(n)); gain.setValue(cfg.getAudioGain()); gain.valueProperty().addListener((e, o, n) -> cfg.setAudioGain(n.floatValue())); checkAudioState(context, this); } public static void checkAudioState(App context, AbstractController controller) { if (context.getAudioManager().getError() != null) { controller.notifyMessage(MessagePersistence.EVERYTIME, MessageType.DANGER, null, MessageFormat.format(bundle.getString("error.noAudioSystem"), context.getAudioManager().getError().getLocalizedMessage()), 60); } } @Override protected void onSetEffectHandler() { backing = new JavaFXBacking(getEffectHandler().getBacking().getWidth(), getEffectHandler().getBacking().getHeight()); previewContainer.getChildren().add(backing.getCanvas()); getEffectHandler().getBacking().add(backing); mode.getItems().addAll(Arrays.asList(ExpandAudioEffectMode.class, PeaksAudioEffectMode.class, BlobbyAudioEffectMode.class, BurstyAudioEffectMode.class, LineyAudioEffectMode.class)); Callback<ListView<Class<? extends AudioEffectMode>>, ListCell<Class<? extends AudioEffectMode>>> factory = listView -> { return new ListCell<Class<? extends AudioEffectMode>>() { @Override protected void updateItem(Class<? extends AudioEffectMode> item, boolean empty) { super.updateItem(item, empty); if (item == null || empty) { setText(""); } else { setText(bundle.getString("audioEffectMode." + item.getSimpleName())); } } }; }; mode.setButtonCell(factory.call(null)); mode.setCellFactory(factory); color1.setColor(JavaFX.toColor(getEffectHandler().getColor1())); color1.colorProperty().addListener((e,o,n) -> getEffectHandler().store(getDevice(), this)); color2.setColor(JavaFX.toColor(getEffectHandler().getColor2())); color2.colorProperty().addListener((e,o,n) -> getEffectHandler().store(getDevice(), this)); color3.setColor(JavaFX.toColor(getEffectHandler().getColor3())); color3.colorProperty().addListener((e,o,n) -> getEffectHandler().store(getDevice(), this)); mode.getSelectionModel().select(getEffectHandler().getMode()); } public AudioSource getSource() { return source.getSelectionModel().getSelectedItem(); } @Override protected void onDeviceCleanUp() { getEffectHandler().getBacking().remove(backing); } @FXML void evtBack() { context.pop(); } @FXML void evtColor1() { getEffectHandler().store(getDevice(), this); } @FXML void evtColor2() { getEffectHandler().store(getDevice(), this); } @FXML void evtColor3() { getEffectHandler().store(getDevice(), this); } @FXML void evtMode() { getEffectHandler().store(getDevice(), this); } public Class<? extends AudioEffectMode> getMode() { return mode.getValue(); } public int[] getColor1() { return JavaFX.toRGB(color1.getColor()); } public int[] getColor2() { return JavaFX.toRGB(color2.getColor()); } public int[] getColor3() { return JavaFX.toRGB(color3.getColor()); } }
5,424
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
AbstractEffectController.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/AbstractEffectController.java
package uk.co.bithatch.snake.ui; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import uk.co.bithatch.snake.lib.Lit; public abstract class AbstractEffectController<E, H extends EffectHandler<E, ?>> extends AbstractDeviceController { @FXML private ImageView deviceImage; @FXML private Label deviceName; private H effectHandler; @FXML private BorderPane header; private Lit region; public Lit getRegion() { return region; } public final void setEffectHandler(H effect) { this.effectHandler = effect; onSetEffectHandler(); } public final void setRegion(Lit region) { this.region = region; onSetRegion(); } protected H getEffectHandler() { return effectHandler; } protected String getHeaderTitle() { return getDevice().getName(); } @Override protected final void onSetDevice() throws Exception { header.setBackground(createHeaderBackground()); deviceImage.setImage(new Image(context.getDefaultImage(getDevice().getType(), context.getCache().getCachedImage(getDevice().getImage())), true)); deviceName.textProperty().set(getDevice().getName()); onSetEffectDevice(); } protected void onSetEffectDevice() { } protected void onSetEffectHandler() { } protected void onSetRegion() { } }
1,365
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
DeviceOverview.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/DeviceOverview.java
package uk.co.bithatch.snake.ui; import java.util.Objects; import java.util.ResourceBundle; import org.kordamp.ikonli.javafx.FontIcon; import javafx.animation.FadeTransition; import javafx.fxml.FXML; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import uk.co.bithatch.snake.lib.Capability; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.lib.Device.Listener; import uk.co.bithatch.snake.lib.Region; import uk.co.bithatch.snake.ui.effects.EffectAcquisition; import uk.co.bithatch.snake.widgets.Direction; public class DeviceOverview extends AbstractDeviceController implements Listener { final static ResourceBundle bundle = ResourceBundle.getBundle(DeviceOverview.class.getName()); @FXML private Label deviceName; @FXML private Label deviceSerial; @FXML private Label deviceFirmware; @FXML private Label deviceStatus; @FXML private ImageView deviceImage; @FXML private HBox effect; @FXML private Label charging; @FXML private Label battery; @FXML private Hyperlink macros; @FXML private Label brightnessAmount; private EffectHandler<?, ?> lastEffect; private FadeTransition chargingAnim; private FadeTransition lowAnim; @Override protected void onConfigure() throws Exception { chargingAnim = BatteryControl.createFader(charging); lowAnim = BatteryControl.createFader(battery); } protected void onSetDevice() { Device dev = getDevice(); dev.addListener(this); deviceName.textProperty().set(dev.getName()); deviceImage.setImage(new Image( context.getCache().getCachedImage(context.getDefaultImage(dev.getType(), dev.getImage())), true)); deviceSerial.textProperty().set(dev.getSerial()); deviceFirmware.textProperty().set(dev.getFirmware()); macros.managedProperty().bind(macros.visibleProperty()); macros.visibleProperty() .set(context.getMacroManager().isSupported(dev) || dev.getCapabilities().contains(Capability.MACROS)); effect.visibleProperty().set(dev.getCapabilities().contains(Capability.EFFECTS)); battery.visibleProperty().set(dev.getCapabilities().contains(Capability.BATTERY)); charging.visibleProperty().set(dev.getCapabilities().contains(Capability.BATTERY)); updateFromDevice(dev); } private void updateFromDevice(Device dev) { EffectAcquisition acq = context.getEffectManager().getRootAcquisition(dev); if (acq != null) { /* May be null at shutdown */ EffectHandler<?, ?> thisEffect = acq.getEffect(dev); if (!Objects.equals(lastEffect, thisEffect)) { lastEffect = thisEffect; effect.getChildren().clear(); if (thisEffect != null) effect.getChildren().add(thisEffect.getEffectImageNode(16, 16)); } } if (dev.getCapabilities().contains(Capability.BRIGHTNESS)) { brightnessAmount.textProperty().set(dev.getBrightness() + "%"); } if (dev.getCapabilities().contains(Capability.BATTERY)) { int level = dev.getBattery(); battery.graphicProperty().set(new FontIcon(BatteryControl.getBatteryIcon(level))); boolean c = dev.isCharging(); charging.visibleProperty().set(c); if (c) chargingAnim.play(); else chargingAnim.stop(); BatteryControl.setBatteryStatusStyle(dev.getLowBatteryThreshold(), level, battery, lowAnim); BatteryControl.setBatteryStatusStyle(dev.getLowBatteryThreshold(), level, charging, null); } } @FXML void evtSelect() { context.push(DeviceDetails.class, this, Direction.FROM_RIGHT); } @FXML void evtMacros() { try { context.editMacros(this); } catch (Exception e) { error(e); } } @Override protected void onDeviceCleanUp() { getDevice().removeListener(this); chargingAnim.stop(); lowAnim.stop(); } @Override public void onChanged(Device device, Region region) { if (region == null) updateFromDevice(device); } }
3,885
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
DeviceDetails.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/DeviceDetails.java
package uk.co.bithatch.snake.ui; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import java.util.prefs.PreferenceChangeEvent; import java.util.prefs.PreferenceChangeListener; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.geometry.Orientation; import javafx.scene.control.Hyperlink; import javafx.scene.control.ScrollPane; import javafx.scene.control.ScrollPane.ScrollBarPolicy; import javafx.scene.effect.ColorAdjust; import javafx.scene.image.Image; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundImage; import javafx.scene.layout.BackgroundPosition; import javafx.scene.layout.BackgroundRepeat; import javafx.scene.layout.BackgroundSize; import javafx.scene.layout.BorderPane; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.Region; import javafx.scene.layout.VBox; import uk.co.bithatch.snake.lib.BrandingImage; import uk.co.bithatch.snake.lib.Capability; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.lib.Lit; import uk.co.bithatch.snake.lib.layouts.Accessory; import uk.co.bithatch.snake.lib.layouts.Accessory.AccessoryType; import uk.co.bithatch.snake.lib.layouts.ComponentType; import uk.co.bithatch.snake.lib.layouts.DeviceLayout; import uk.co.bithatch.snake.lib.layouts.DeviceLayouts.Listener; import uk.co.bithatch.snake.lib.layouts.DeviceView; import uk.co.bithatch.snake.lib.layouts.IO; import uk.co.bithatch.snake.lib.layouts.ViewPosition; import uk.co.bithatch.snake.widgets.Direction; import uk.co.bithatch.snake.widgets.JavaFX; public class DeviceDetails extends AbstractDetailsController implements Listener, PreferenceChangeListener { final static ResourceBundle bundle = ResourceBundle.getBundle(DeviceDetails.class.getName()); private static final String PREF_USE_LAYOUT_VIEW = "useLayoutView"; @FXML private FlowPane controls; @FXML private BorderPane header; @FXML private Hyperlink macros; @FXML private Hyperlink design; @FXML private Region background; @FXML private HBox decoratedTools; @FXML private HBox layoutTools; @FXML private BorderPane centre; @FXML private Hyperlink layoutView; @FXML private Hyperlink standardView; private List<Controller> deviceControls = new ArrayList<>(); private boolean useLayoutView; @Override protected void onConfigure() { } public FlowPane getControls() { return controls; } @Override protected void onSetDeviceDetails() throws Exception { Device device = getDevice(); JavaFX.bindManagedToVisible(macros, design, decoratedTools, standardView, layoutView, layoutTools); decoratedTools.visibleProperty().set(context.getConfiguration().isDecorated()); context.getConfiguration().getNode().addPreferenceChangeListener(this); layoutTools.setVisible(hasLayout()); checkLayoutStatus(); /* * Show macros link if device has the capability and there is not a layout that * has a ACCESSORY of type PROFILES */ if (device.getCapabilities().contains(Capability.MACROS) || context.getMacroManager().isSupported(device)) { if (context.getLayouts().hasLayout(device)) { macros.setVisible(!hasLayoutProfileAccessory()); } else { macros.setVisible(true); } } else { macros.setVisible(false); } boolean hasLayout = hasLayout(); useLayoutView = hasLayout && context.getPreferences(getDevice().getName()).getBoolean(PREF_USE_LAYOUT_VIEW, hasLayout); createView(); context.getLayouts().addListener(this); if (!context.getMacroManager().isStarted() && !context.peek().equals(this)) { notifyMessage(MessagePersistence.ONCE_PER_RUNTIME, MessageType.WARNING, null, bundle.getString("warning.noUInput"), 60); } updateLayout(); } protected boolean hasLayoutProfileAccessory() { DeviceView view = context.getLayouts().getLayout(getDevice()).getViewThatHas(ComponentType.ACCESSORY); if (view == null) { return false; } else { List<IO> els = view.getElements(ComponentType.ACCESSORY); boolean hasProfiles = false; for (IO el : els) { Accessory acc = (Accessory) el; if (acc.getAccessory() == AccessoryType.PROFILES) { hasProfiles = true; break; } } return hasProfiles; } } protected boolean hasLayout() { return context.getLayouts().hasLayout(getDevice()) && context.getLayouts().getLayout(getDevice()).getViewThatHas(ComponentType.AREA) != null; } protected void createView() { try { cleanUpControllers(); deviceControls.clear(); Device device = getDevice(); boolean useLayout = useLayoutView; boolean hasEffects = device.getCapabilities().contains(Capability.EFFECTS) && !device.getSupportedEffects().isEmpty(); ScrollPane scroller = new ScrollPane(); scroller.getStyleClass().add("transparentBackground"); scroller.getStyleClass().add("focusless"); scroller.setHbarPolicy(ScrollBarPolicy.NEVER); scroller.setVbarPolicy(ScrollBarPolicy.AS_NEEDED); Pane controlContainer; if (hasEffects && useLayout) { /* The layout takes up the bulk of the space */ LayoutControl layoutControl = context.openScene(LayoutControl.class); layoutControl.setDevice(device); centre.setCenter(layoutControl.getScene().getRoot()); deviceControls.add(layoutControl); /* Everything else goes in a scrolled area */ controlContainer = new VBox(); controlContainer.getStyleClass().add("controls-layout"); controlContainer.getStyleClass().add("column"); centre.setRight(scroller); } else { /* No layout, so all controls are in a horizontally flowing scroll pane */ scroller.setHbarPolicy(ScrollBarPolicy.NEVER); scroller.setVbarPolicy(ScrollBarPolicy.AS_NEEDED); FlowPane flow = new FlowPane(); flow.getStyleClass().add("spaced"); flow.prefWrapLengthProperty().bind(scroller.widthProperty()); flow.setOrientation(Orientation.HORIZONTAL); centre.setCenter(scroller); centre.setRight(null); controlContainer = flow; controlContainer.getStyleClass().add("controls-nolayout"); } scroller.setContent(controlContainer); if (!useLayout) { if (hasEffects) { EffectsControl effectsControl = context.openScene(EffectsControl.class); effectsControl.setDevice(device); controlContainer.getChildren().add(effectsControl.getScene().getRoot()); deviceControls.add(effectsControl); } if (device.getCapabilities().contains(Capability.BRIGHTNESS)) { BrightnessControl brightnessControl = context.openScene(BrightnessControl.class); brightnessControl.setDevice(device); controlContainer.getChildren().add(brightnessControl.getScene().getRoot()); deviceControls.add(brightnessControl); } String imageUrl = context.getCache().getCachedImage( context.getDefaultImage(device.getType(), device.getImageUrl(BrandingImage.PERSPECTIVE))); if (imageUrl != null) { Background bg = new Background(new BackgroundImage(new Image(imageUrl, true), BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, new BackgroundSize(100d, 100d, true, true, false, true))); background.setBackground(bg); background.opacityProperty().set(0.15); ColorAdjust adjust = new ColorAdjust(); adjust.setSaturation(-1); background.setEffect(adjust); } else { background.setBackground(null); background.setEffect(null); } } else { background.setBackground(null); background.setEffect(null); } if (device.getCapabilities().contains(Capability.BATTERY)) { BatteryControl batteryControl = context.openScene(BatteryControl.class); batteryControl.setDevice(device); controlContainer.getChildren().add(batteryControl.getScene().getRoot()); deviceControls.add(batteryControl); } if (device.getCapabilities().contains(Capability.DPI)) { DPIControl dpiControl = context.openScene(DPIControl.class); dpiControl.setDevice(device); controlContainer.getChildren().add(dpiControl.getScene().getRoot()); deviceControls.add(dpiControl); } if (context.getAudioManager().hasVolume(device)) { VolumeControl volumeControl = context.openScene(VolumeControl.class); volumeControl.setDevice(device); controlContainer.getChildren().add(volumeControl.getScene().getRoot()); deviceControls.add(volumeControl); } if (!useLayout || !hasLayoutProfileAccessory()) { if (context.getMacroManager().isSupported(device)) { MacroProfileControl profileControl = context.openScene(MacroProfileControl.class); profileControl.setDevice(device); controlContainer.getChildren().add(profileControl.getScene().getRoot()); deviceControls.add(profileControl); } else if (device.getCapabilities().contains(Capability.MACRO_PROFILES)) { ProfileControl profileControl = context.openScene(ProfileControl.class); profileControl.setDevice(device); controlContainer.getChildren().add(profileControl.getScene().getRoot()); deviceControls.add(profileControl); } } if (device.getCapabilities().contains(Capability.POLL_RATE)) { PollRateControl pollRateControl = context.openScene(PollRateControl.class); pollRateControl.setDevice(device); controlContainer.getChildren().add(pollRateControl.getScene().getRoot()); deviceControls.add(pollRateControl); } if (device.getCapabilities().contains(Capability.GAME_MODE)) { GameModeControl gameModeControl = context.openScene(GameModeControl.class); gameModeControl.setDevice(device); controlContainer.getChildren().add(gameModeControl.getScene().getRoot()); deviceControls.add(gameModeControl); } } catch (RuntimeException re) { throw re; } catch (Exception e) { throw new IllegalStateException("Failed to create view.", e); } } protected void cleanUpControllers() { for (Controller c : deviceControls) c.cleanUp(); } protected void checkLayoutStatus() { Device device = getDevice(); boolean hasLayout = context.getLayouts().hasLayout(device); boolean hasUserLayout = context.getLayouts().hasUserLayout(device); boolean hasOfficial = context.getLayouts().hasOfficialLayout(device); if (!hasLayout) { notifyMessage(MessagePersistence.ONCE_PER_RUNTIME, MessageType.INFO, bundle.getString("info.missingLayout")); } else if (hasLayout && hasUserLayout && hasOfficial) { notifyMessage(MessagePersistence.ONCE_PER_RUNTIME, MessageType.INFO, bundle.getString("info.maskingOfficial")); } else { clearNotifications(MessageType.INFO, false); } layoutTools.setVisible(hasLayout()); design.visibleProperty().set(!hasLayout || (hasLayout && hasUserLayout)); } @Override protected void onDeviceCleanUp() { cleanUpControllers(); deviceControls.clear(); context.getLayouts().removeListener(this); context.getConfiguration().getNode().removePreferenceChangeListener(this); } @FXML void evtStandardView() { useLayoutView = false; updateLayout(); } @FXML void evtLayoutView() { useLayoutView = true; updateLayout(); } @FXML void evtAbout() { context.push(About.class, Direction.FADE); } @FXML void evtDesign() throws Exception { LayoutDesigner designer = context.push(LayoutDesigner.class, Direction.FROM_BOTTOM); DeviceLayoutManager layouts = context.getLayouts(); Device device = getDevice(); boolean hasLayout = layouts.hasLayout(device); DeviceLayout layout = null; if (!hasLayout) { layout = new DeviceLayout(device); DeviceView view = new DeviceView(); view.setPosition(ViewPosition.TOP); layout.addView(view); layouts.addLayout(layout); } else { layout = layouts.getLayout(device); } designer.setLayout(layout); } @FXML void evtOptions() { context.push(Options.class, Direction.FROM_BOTTOM); } @FXML void evtMacros() { try { context.editMacros(this); } catch (Exception e) { error(e); } } public void configure(Lit lit, EffectHandler<?, ?> configurable) { throw new UnsupportedOperationException("TODO: Load effect configuration"); } @Override public void layoutChanged(DeviceLayout layout) { if (Platform.isFxApplicationThread()) { checkLayoutStatus(); return; } Platform.runLater(() -> layoutChanged(layout)); } @Override public void layoutAdded(DeviceLayout layout) { layoutChanged(layout); } @Override public void layoutRemoved(DeviceLayout layout) { layoutChanged(layout); } @Override public void preferenceChange(PreferenceChangeEvent evt) { if (evt.getKey().equals(Configuration.PREF_DECORATED)) { decoratedTools.visibleProperty().set(context.getConfiguration().isDecorated()); } } void updateLayout() { standardView.setVisible(useLayoutView); layoutView.setVisible(!useLayoutView); createView(); } }
12,828
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
ListMultipleSelectionModel.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/ListMultipleSelectionModel.java
/* * Copyright (c) 2010, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package uk.co.bithatch.snake.ui; import static javafx.scene.control.SelectionMode.SINGLE; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; import java.util.stream.IntStream; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.collections.ObservableListBase; import javafx.scene.control.MultipleSelectionModel; import javafx.scene.control.SelectionMode; import uk.co.bithatch.snake.ui.util.BasicList; /** * Largely copied from <code>MultipleSelectionModelBase</code> that is package * protected (grr). * * @param <I> type of item */ public class ListMultipleSelectionModel<I> extends MultipleSelectionModel<I> { abstract class SelectedItemsReadOnlyObservableList<E> extends ObservableListBase<E> { // This is the actual observable list of selected indices used in the selection // model private final ObservableList<Integer> selectedIndices; private final Supplier<Integer> modelSizeSupplier; private final List<WeakReference<E>> itemsRefList; public SelectedItemsReadOnlyObservableList(ObservableList<Integer> selectedIndices, Supplier<Integer> modelSizeSupplier) { this.modelSizeSupplier = modelSizeSupplier; this.selectedIndices = selectedIndices; this.itemsRefList = new ArrayList<>(); selectedIndices.addListener((ListChangeListener<Integer>) c -> { beginChange(); while (c.next()) { if (c.wasReplaced()) { List<E> removed = getRemovedElements(c); List<E> added = getAddedElements(c); if (!removed.equals(added)) { nextReplace(c.getFrom(), c.getTo(), removed); } } else if (c.wasAdded()) { nextAdd(c.getFrom(), c.getTo()); } else if (c.wasRemoved()) { int removedSize = c.getRemovedSize(); if (removedSize == 1) { nextRemove(c.getFrom(), getRemovedModelItem(c.getFrom())); } else { nextRemove(c.getFrom(), getRemovedElements(c)); } } else if (c.wasPermutated()) { int[] permutation = new int[size()]; for (int i = 0; i < size(); i++) { permutation[i] = c.getPermutation(i); } nextPermutation(c.getFrom(), c.getTo(), permutation); } else if (c.wasUpdated()) { for (int i = c.getFrom(); i < c.getTo(); i++) { nextUpdate(i); } } } // regardless of the change, we recreate the itemsRefList to reflect the current // items list. // This is important for cases where items are removed (and so must their // selection, but we lose // access to the item before we can fire the event). // FIXME we could make this more efficient by only making the reported changes // to the list itemsRefList.clear(); for (int selectedIndex : selectedIndices) { itemsRefList.add(new WeakReference<>(getModelItem(selectedIndex))); } endChange(); }); } protected abstract E getModelItem(int index); @Override public E get(int index) { int pos = selectedIndices.get(index); return getModelItem(pos); } @Override public int size() { return selectedIndices.size(); } private E _getModelItem(int index) { if (index >= modelSizeSupplier.get()) { // attempt to return from the itemsRefList instead return getRemovedModelItem(index); } else { return getModelItem(index); } } private E getRemovedModelItem(int index) { // attempt to return from the itemsRefList instead return index < 0 || index >= itemsRefList.size() ? null : itemsRefList.get(index).get(); } private List<E> getRemovedElements(ListChangeListener.Change<? extends Integer> c) { List<E> removed = new ArrayList<>(c.getRemovedSize()); final int startPos = c.getFrom(); for (int i = startPos, max = startPos + c.getRemovedSize(); i < max; i++) { removed.add(getRemovedModelItem(i)); } return removed; } private List<E> getAddedElements(ListChangeListener.Change<? extends Integer> c) { List<E> added = new ArrayList<>(c.getAddedSize()); for (int index : c.getAddedSubList()) { added.add(_getModelItem(index)); } return added; } } private ObservableList<Integer> indices = new BasicList<Integer>(); private ObservableList<I> model; private boolean atomic; private int focused = -1; private ListMultipleSelectionModel<I>.SelectedItemsReadOnlyObservableList<I> selectedItems; public ListMultipleSelectionModel(ObservableList<I> model) { super(); this.model = model; selectedItems = new SelectedItemsReadOnlyObservableList<I>(indices, () -> getItemCount()) { @Override protected I getModelItem(int index) { return ListMultipleSelectionModel.this.getModelItem(index); } }; } @Override public ObservableList<Integer> getSelectedIndices() { return indices; } @Override public ObservableList<I> getSelectedItems() { return selectedItems; } @Override public void selectIndices(int row, int... rows) { if (rows == null || rows.length == 0) { select(row); return; } /* * Performance optimisation - if multiple selection is disabled, only process * the end-most row index. */ int rowCount = getItemCount(); if (getSelectionMode() == SINGLE) { quietClearSelection(); for (int i = rows.length - 1; i >= 0; i--) { int index = rows[i]; if (index >= 0 && index < rowCount) { indices.add(index); select(index); break; } } if (indices.isEmpty()) { if (row > 0 && row < rowCount) { indices.add(row); select(row); } } } else { indices.add(row); for (int i : rows) indices.add(i); IntStream.concat(IntStream.of(row), IntStream.of(rows)).filter(index -> index >= 0 && index < rowCount) .reduce((first, second) -> second).ifPresent(lastIndex -> { setSelectedIndex(lastIndex); focus(lastIndex); setSelectedItem(getModelItem(lastIndex)); }); } } public void selectAll() { if (getSelectionMode() == SINGLE) return; if (getItemCount() <= 0) return; final int rowCount = getItemCount(); final int focusedIndex = getFocusedIndex(); // set all selected indices to true clearSelection(); List<Integer> l = new ArrayList<>(); for (int i = 0; i < rowCount; i++) l.add(i); indices.addAll(l); if (focusedIndex == -1) { setSelectedIndex(rowCount - 1); focus(rowCount - 1); } else { setSelectedIndex(focusedIndex); focus(focusedIndex); } } @Override public void selectFirst() { if (getSelectionMode() == SINGLE) { quietClearSelection(); } if (getItemCount() > 0) { select(0); } } @Override public void selectLast() { if (getSelectionMode() == SINGLE) { quietClearSelection(); } int numItems = getItemCount(); if (numItems > 0 && getSelectedIndex() < numItems - 1) { select(numItems - 1); } } @Override public void clearAndSelect(int row) { if (row < 0 || row >= getItemCount()) { clearSelection(); return; } final boolean wasSelected = isSelected(row); // RT-33558 if this method has been called with a given row, and that // row is the only selected row currently, then this method becomes a no-op. if (wasSelected && getSelectedIndices().size() == 1) { // before we return, we double-check that the selected item // is equal to the item in the given index if (getSelectedItem() == getModelItem(row)) { return; } } // firstly we make a copy of the selection, so that we can send out // the correct details in the selection change event. // We remove the new selection from the list seeing as it is not removed. // BitSet selectedIndicesCopy = new BitSet(); // selectedIndicesCopy.or(selectedIndices.bitset); // selectedIndicesCopy.clear(row); // List<Integer> previousSelectedIndices = new SelectedIndicesList(selectedIndicesCopy); ObservableList<Integer> previousSelectedIndices = new BasicList<Integer>(); previousSelectedIndices.addAll(indices); // RT-32411 We used to call quietClearSelection() here, but this // resulted in the selectedItems and selectedIndices lists never // reporting that they were empty. // makeAtomic toggle added to resolve RT-32618 // then clear the current selection // TODO: SNAKE ... had to move the clear selection out of the weak // implementation of 'startAtomic'. // or selection is not cleared properly. The choice is to copy yet MORE package // protected and private code (will even require some more classes) from the // private javafx API to completely duplicate the multipl section model. // or find a different way. Why is this so hard :( clearSelection(); // and select the new row startAtomic(); // clearSelection(); select(row); stopAtomic(); // fire off a single add/remove/replace notification (rather than // individual remove and add notifications) - see RT-33324 // ListChangeListener.Change<Integer> change; /* * getFrom() documentation: If wasAdded is true, the interval contains all the * values that were added. If wasPermutated is true, the interval marks the * values that were permutated. If wasRemoved is true and wasAdded is false, * getFrom() and getTo() should return the same number - the place where the * removed elements were positioned in the list. */ // if (wasSelected) { // change = ControlUtils.buildClearAndSelectChange(selectedIndices, previousSelectedIndices, row); // } else { // int changeIndex = Math.max(0, selectedIndices.indexOf(row)); // change = new NonIterableChange.GenericAddRemoveChange<>(changeIndex, changeIndex + 1, // previousSelectedIndices, selectedIndices); // } // // selectedIndices.callObservers(change); } @Override public void select(int row) { if (row == -1) { clearSelection(); return; } if (row < 0 || row >= getItemCount()) { return; } int selectedIndex = getSelectedIndex(); boolean isSameRow = row == selectedIndex; I currentItem = getSelectedItem(); I newItem = getModelItem(row); boolean isSameItem = newItem != null && newItem.equals(currentItem); boolean fireUpdatedItemEvent = isSameRow && !isSameItem; // focus must come first so that we have the anchors set appropriately focus(row); // if (!indices.contains(row)) { if (getSelectionMode() == SINGLE) { startAtomic(); quietClearSelection(); stopAtomic(); } indices.add(row); } setSelectedIndex(row); if (fireUpdatedItemEvent) { setSelectedItem(newItem); } } protected void focus(int index) { this.focused = index; } protected int getFocusedIndex() { return focused; } protected I getModelItem(int row) { return model.get(row); } protected int getItemCount() { return model.size(); } @Override public void select(I obj) { if (obj == null && getSelectionMode() == SelectionMode.SINGLE) { clearSelection(); return; } // We have no option but to iterate through the model and select the // first occurrence of the given object. Once we find the first one, we // don't proceed to select any others. Object rowObj = null; for (int i = 0, max = getItemCount(); i < max; i++) { rowObj = getModelItem(i); if (rowObj == null) continue; if (rowObj.equals(obj)) { if (isSelected(i)) { return; } if (getSelectionMode() == SINGLE) { quietClearSelection(); } select(i); return; } } // if we are here, we did not find the item in the entire data model. // Even still, we allow for this item to be set to the give object. // We expect that in concrete subclasses of this class we observe the // data model such that we check to see if the given item exists in it, // whilst SelectedIndex == -1 && SelectedItem != null. setSelectedIndex(-1); setSelectedItem(obj); } @Override public void clearSelection(int index) { if (index < 0) return; // TODO shouldn't directly access like this // TODO might need to update focus and / or selected index/item boolean wasEmpty = indices.isEmpty(); indices.remove((Integer) index); if (!wasEmpty && indices.isEmpty()) { clearSelection(); } } @Override public void clearSelection() { quietClearSelection(); if (!isAtomic()) { setSelectedIndex(-1); focus(-1); } } @Override public boolean isSelected(int index) { if (index >= 0 && index < model.size()) { return indices.contains(index); } return false; } @Override public boolean isEmpty() { return indices.isEmpty(); } @Override public void selectPrevious() { int focusIndex = getFocusedIndex(); if (getSelectionMode() == SINGLE) { quietClearSelection(); } if (focusIndex == -1) { select(getItemCount() - 1); } else if (focusIndex > 0) { select(focusIndex - 1); } } @Override public void selectNext() { int focusIndex = getFocusedIndex(); if (getSelectionMode() == SINGLE) { quietClearSelection(); } if (focusIndex == -1) { select(0); } else if (focusIndex != getItemCount() - 1) { select(focusIndex + 1); } } void startAtomic() { atomic = true; } void stopAtomic() { atomic = false; } boolean isAtomic() { return atomic; } private void quietClearSelection() { indices.clear(); } }
14,457
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Export.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/Export.java
package uk.co.bithatch.snake.ui; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.lang.System.Logger.Level; import java.net.URL; import java.text.MessageFormat; import java.util.Arrays; import java.util.Map; import java.util.ResourceBundle; import java.util.prefs.Preferences; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.stage.FileChooser; import javafx.stage.FileChooser.ExtensionFilter; import uk.co.bithatch.snake.ui.SchedulerManager.Queue; import uk.co.bithatch.snake.ui.addons.AbstractAddOn; import uk.co.bithatch.snake.ui.addons.AbstractJsonAddOn; import uk.co.bithatch.snake.ui.addons.AddOn; import uk.co.bithatch.snake.ui.util.Strings; import uk.co.bithatch.snake.widgets.JavaFX; public class Export extends AbstractController implements Modal { public enum OutputType { METADATA_ONLY, BUNDLE } public interface Validator { boolean validate(Export export); } final static ResourceBundle bundle = ResourceBundle.getBundle(Export.class.getName()); private static final String PREF_AUTHOR = "author"; private static final String PREF_LICENSE = "license"; private static final String PREF_URL = "url"; private AddOn addOn; @FXML private TextArea addOnDescription; @FXML private Label addOnId; @FXML private TextField addOnName; @FXML private Label addOnType; @FXML private TextField author; @FXML private Hyperlink cancel; @FXML private Hyperlink confirm; @FXML private Label description; @FXML private TextField license; @FXML private TextField output; @FXML private Label title; @FXML private TextField url; @FXML private ComboBox<OutputType> outputType; private Preferences prefs; private Validator validator; private ResourceBundle exporterBundle; private String prefix; public void validationError(String key, Object... args) { String text = bundle.getString(key); if (args.length > 0) text = MessageFormat.format(text, (Object[]) args); notifyMessage(MessageType.DANGER, bundle.getString("error.validation"), text); confirm.disableProperty().set(true); } public void export(AddOn addOn, ResourceBundle exporterBundle, String prefix, String... args) { this.addOn = addOn; outputType.itemsProperty().get().addAll(Arrays.asList(OutputType.values())); if (addOn.hasResources()) { outputType.getSelectionModel().select(OutputType.BUNDLE); for (Map.Entry<String, URL> en : addOn.resolveResources(false).entrySet()) { if (en.getValue().getProtocol().equals("file")) { outputType.disableProperty().set(true); break; } } } else { outputType.disableProperty().set(true); outputType.getSelectionModel().select(OutputType.METADATA_ONLY); } title.textProperty().set(MessageFormat.format(exporterBundle.getString(prefix + ".title"), (Object[]) args)); description.textProperty() .set(MessageFormat.format(exporterBundle.getString(prefix + ".description"), (Object[]) args)); confirm.textProperty() .set(MessageFormat.format(exporterBundle.getString(prefix + ".confirm"), (Object[]) args)); cancel.textProperty().set(MessageFormat.format(exporterBundle.getString(prefix + ".cancel"), (Object[]) args)); this.prefix = prefix; this.exporterBundle = exporterBundle; addOnName.setText(addOn.getName()); addOnName.textProperty().addListener((e) -> validateInput()); addOnType.setText(AddOns.bundle.getString("addOnType." + addOn.getClass().getSimpleName())); addOnId.setText(addOn.getId()); addOnDescription.setText(addOn.getDescription()); addOnDescription.textProperty().addListener((e) -> validateInput()); license.setText(Strings.defaultIfBlank(addOn.getLicense(), prefs.get(PREF_LICENSE, "GPLv3"))); license.promptTextProperty().set("GPLv3"); license.textProperty().addListener((e) -> validateInput()); author.setText(Strings.defaultIfBlank(addOn.getAuthor(), prefs.get(PREF_AUTHOR, ""))); author.promptTextProperty().set(System.getProperty("user.name")); author.textProperty().addListener((e) -> validateInput()); String defaultOutputLocation = getDefaultOutputLocation(); String ext = Strings.extension(defaultOutputLocation); if ("zip".equalsIgnoreCase(ext) && !outputType.getSelectionModel().getSelectedItem().equals(OutputType.BUNDLE)) { defaultOutputLocation = Strings.changeExtension(defaultOutputLocation, "json"); } else if (!"zip".equalsIgnoreCase(ext) && outputType.getSelectionModel().getSelectedItem().equals(OutputType.BUNDLE)) { defaultOutputLocation = Strings.changeExtension(defaultOutputLocation, "zip"); } output.textProperty().set(defaultOutputLocation); output.textProperty().addListener((e) -> validateInput()); url.setText(Strings.defaultIfBlank(addOn.getUrl(), prefs.get(PREF_URL, ""))); url.textProperty().addListener((e) -> validateInput()); validateInput(); } public TextArea getAddOnDescription() { return addOnDescription; } public Label getAddOnId() { return addOnId; } public TextField getAddOnName() { return addOnName; } public Label getAddOnType() { return addOnType; } public TextField getAuthor() { return author; } public TextField getLicense() { return license; } public TextField getOutput() { return output; } public TextField getUrl() { return url; } public Validator getValidator() { return validator; } public void setValidator(Validator validator) { this.validator = validator; } protected void clearErrors() { clearNotifications(false); confirm.disableProperty().set(false); } protected String getDefaultOutputLocation() { String id = addOnId.textProperty().get(); var path = prefs.get(prefix + ".lastExportLocation", System.getProperty("user.dir")) + File.separator + id + (outputType.getSelectionModel().getSelectedItem().equals(OutputType.BUNDLE) ? ".zip" : ".json"); return path; } @Override protected void onConfigure() throws Exception { prefs = context.getPreferences().node("export"); } protected void validateInput() { if (addOnName.textProperty().get().equals("")) { validationError("error.noAddOnName"); } else if (addOnDescription.textProperty().get().equals("")) { validationError("error.noAddOnDescription"); } else if (output.textProperty().get().equals("")) { validationError("error.noOutput"); } else if (outputType.getSelectionModel().getSelectedItem().equals(OutputType.BUNDLE) && !output.textProperty().get().toLowerCase().endsWith(".zip") && !output.textProperty().get().toLowerCase().endsWith(".jar")) { validationError("error.notZip"); } else { boolean ok = true; if (validator != null && !validator.validate(this)) ok = false; if (ok) clearErrors(); } } void confirm() { AbstractAddOn aaddOn = (AbstractAddOn) addOn; aaddOn.setName(addOnName.textProperty().get()); aaddOn.setDescription(addOnDescription.textProperty().get()); aaddOn.setLicense(Strings.defaultIfBlank(license.textProperty().get(), "GPLv3")); aaddOn.setAuthor(Strings.defaultIfBlank(author.textProperty().get(), System.getProperty("user.name"))); aaddOn.setUrl(url.textProperty().get()); prefs.put(PREF_LICENSE, aaddOn.getLicense()); prefs.put(PREF_AUTHOR, aaddOn.getAuthor()); prefs.put(PREF_URL, aaddOn.getUrl()); String outPath = output.textProperty().get(); getScene().getRoot().disableProperty().set(true); prefs.put(prefix + ".lastExportLocation", new File(outPath).getParentFile().getAbsolutePath()); context.getSchedulerManager().get(Queue.APP_IO).execute(() -> { try (OutputStream w = new BufferedOutputStream(new FileOutputStream(outPath))) { if (outputType.getSelectionModel().getSelectedItem().equals(OutputType.BUNDLE)) { try (ZipOutputStream zos = new ZipOutputStream(w)) { for (Map.Entry<String, URL> en : aaddOn.resolveResources(true).entrySet()) { ZipEntry entry = new ZipEntry(en.getKey()); zos.putNextEntry(entry); try (InputStream in = en.getValue().openStream()) { in.transferTo(zos); } zos.closeEntry(); } ZipEntry entry = new ZipEntry(Strings.basename(Strings.changeExtension(outPath, "json"))); zos.putNextEntry(entry); ((AbstractJsonAddOn) aaddOn).export(new OutputStreamWriter(zos)); zos.closeEntry(); } } else { ((AbstractJsonAddOn) aaddOn).export(new OutputStreamWriter(w)); } Platform.runLater(() -> { context.pop(); context.peek().notifyMessage(MessageType.SUCCESS, bundle.getString("success.export"), MessageFormat.format(bundle.getString("success.export.content"), addOn.getName(), outPath)); }); } catch (IOException ioe) { LOG.log(Level.ERROR, "Failed to export.", ioe); Platform.runLater(() -> { getScene().getRoot().disableProperty().set(false); context.peek().notifyMessage(MessageType.SUCCESS, bundle.getString("error.export"), MessageFormat.format(bundle.getString("error.export.content"), addOn.getName(), outPath, ioe.getLocalizedMessage())); }); } }); } @FXML void evtBrowse() { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(exporterBundle.getString(prefix + ".selectExportFile")); String outputPath = output.textProperty().get(); var path = Strings.defaultIfBlank(outputPath, getDefaultOutputLocation()); if (outputType.getSelectionModel().getSelectedItem().equals(OutputType.BUNDLE)) { fileChooser.getExtensionFilters().add(new ExtensionFilter(bundle.getString("addOnBundle"), "*.zip")); } else { fileChooser.getExtensionFilters() .add(new ExtensionFilter(exporterBundle.getString(prefix + ".fileExtension"), "*.json")); } /* Check extension is right for type */ path = getActualPath(path); fileChooser.getExtensionFilters() .add(new ExtensionFilter(exporterBundle.getString(prefix + ".allFiles"), "*.*")); JavaFX.selectFilesDir(fileChooser, path); File file = fileChooser.showSaveDialog(getScene().getWindow()); if (file != null) { prefs.put(prefix + ".lastExportLocation", file.getParentFile().getAbsolutePath()); output.textProperty().set(file.getAbsolutePath()); } } protected String getActualPath(String path) { String ext = Strings.extension(path); boolean bundled = outputType.getSelectionModel().getSelectedItem().equals(OutputType.BUNDLE); if ("zip".equalsIgnoreCase(ext) && !bundled) { path = Strings.changeExtension(path, "json"); } else if (!"zip".equalsIgnoreCase(ext) && bundled) { path = Strings.changeExtension(path, "zip"); } return path; } @FXML void evtOutputType() { output.textProperty().set(getActualPath(output.textProperty().get())); } @FXML void evtCancel() { context.pop(); } @FXML void evtConfirm() { confirm(); } }
11,153
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
AddOns.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/AddOns.java
package uk.co.bithatch.snake.ui; import java.io.File; import java.io.IOException; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; import java.util.ResourceBundle; import java.util.prefs.Preferences; import org.apache.commons.lang3.StringUtils; import javafx.animation.FadeTransition; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.FileChooser.ExtensionFilter; import javafx.stage.Stage; import javafx.util.Duration; import uk.co.bithatch.snake.ui.addons.AddOn; import uk.co.bithatch.snake.widgets.Direction; import uk.co.bithatch.snake.widgets.JavaFX; public class AddOns extends AbstractController { final static Preferences PREFS = Preferences.userNodeForPackage(AddOns.class); final static ResourceBundle bundle = ResourceBundle.getBundle(AddOns.class.getName()); @FXML private Hyperlink add; @FXML private Hyperlink url; @FXML private Label by; @FXML private Label license; @FXML private Label addOnType; @FXML private Label addOnName; @FXML private Label description; @FXML private VBox addOnDetailsContainer; @FXML private ListView<Node> installed; @FXML private Label error; @FXML private Label systemAddOn; @FXML private Hyperlink deleteAddOn; private Map<Node, AddOn> addOnMap = new HashMap<>(); @Override protected void onCleanUp() { } @Override protected void onConfigure() throws Exception { deleteAddOn.managedProperty().bind(deleteAddOn.visibleProperty()); systemAddOn.managedProperty().bind(systemAddOn.visibleProperty()); addOnName.managedProperty().bind(addOnName.visibleProperty()); addOnType.managedProperty().bind(addOnType.visibleProperty()); by.managedProperty().bind(by.visibleProperty()); url.managedProperty().bind(url.visibleProperty()); description.managedProperty().bind(description.visibleProperty()); license.managedProperty().bind(license.visibleProperty()); addOnDetailsContainer.managedProperty().bind(addOnDetailsContainer.visibleProperty()); installed.getSelectionModel().selectedItemProperty().addListener((e) -> updateSelected()); installed.getItems().clear(); for (AddOn addOn : context.getAddOnManager().getAddOns()) { addAddOn(addOn); } if (!installed.getItems().isEmpty()) { installed.getSelectionModel().select(0); } updateSelected(); } private AddOnDetails addAddOn(AddOn addOn) throws IOException { AddOnDetails aod = context.openScene(AddOnDetails.class); aod.setAddOn(addOn); Parent node = aod.getScene().getRoot(); installed.getItems().add(node); addOnMap.put(node, addOn); return aod; } void error(String key, Object... args) { error.visibleProperty().set(key != null); if (key == null) { error.visibleProperty().set(false); error.textProperty().set(""); } else { error.visibleProperty().set(true); String txt = bundle.getString(key); if (args.length > 0) { txt = MessageFormat.format(txt, (Object[]) args); } error.textProperty().set(bundle.getString("errorIcon") + (txt == null ? "<missing key " + key + ">" : txt)); } } void updateSelected() { AddOn addOn = getSelectedAddOn(); if (addOn == null) { addOnDetailsContainer.visibleProperty().set(false); } else { systemAddOn.visibleProperty().set(addOn.isSystem()); deleteAddOn.visibleProperty().set(!addOn.isSystem()); addOnName.textProperty().set(addOn.getName()); addOnDetailsContainer.visibleProperty().set(true); addOnType.textProperty().set(bundle.getString("addOnType." + addOn.getClass().getSimpleName())); addOnDetailsContainer.visibleProperty().set(true); by.visibleProperty().set(StringUtils.isNotBlank(addOn.getAuthor())); by.textProperty().set(MessageFormat.format(bundle.getString("by"), addOn.getAuthor())); description.visibleProperty().set(StringUtils.isNotBlank(addOn.getDescription())); description.textProperty().set(addOn.getDescription()); license.visibleProperty().set(StringUtils.isNotBlank(addOn.getLicense())); license.textProperty().set(addOn.getLicense()); url.visibleProperty().set(StringUtils.isNotBlank(addOn.getUrl())); url.textProperty().set(addOn.getUrl()); } } private AddOn getSelectedAddOn() { Node addOnNode = installed.getSelectionModel().getSelectedItem(); AddOn addOn = addOnNode == null ? null : addOnMap.get(addOnNode); return addOn; } @FXML void evtDeleteAddOn() { AddOn addOn = getSelectedAddOn(); Node addOnNode = installed.getSelectionModel().getSelectedItem(); Confirm confirm = context.push(Confirm.class, Direction.FADE); confirm.confirm(bundle, "deleteAddOn", () -> { try { context.getAddOnManager().uninstall(addOn); JavaFX.zoomTo(installed, addOnNode); JavaFX.fadeHide(addOnNode, 1, (e) -> { installed.itemsProperty().get().remove(addOnNode); if (installed.itemsProperty().get().size() > 0) JavaFX.zoomTo(installed, installed.itemsProperty().get().get(0)); }); } catch (Exception e) { LOG.log(java.lang.System.Logger.Level.ERROR, "Failed to delete add-on.", e); error("failedToDeleteAddOn", e.getMessage()); } }, addOn.getName()); } @FXML void evtAdd() { error(null); FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(bundle.getString("selectAddOn")); var path = PREFS.get("lastAddOnLocation", System.getProperty("user.dir") + File.separator + "add-on.jar"); fileChooser.getExtensionFilters() .add(new ExtensionFilter(bundle.getString("addOnFileExtension"), "*.plugin.groovy", "*.jar", "*.zip", "*.json")); fileChooser.getExtensionFilters().add(new ExtensionFilter(bundle.getString("allFileExtensions"), "*.*")); JavaFX.selectFilesDir(fileChooser, path); File file = fileChooser.showOpenDialog((Stage) getScene().getWindow()); if (file != null) { PREFS.put("lastAddOnLocation", file.getAbsolutePath()); try { AddOn addOn = context.getAddOnManager().install(file); Controller c = addAddOn(addOn); Parent root = c.getScene().getRoot(); JavaFX.zoomTo(installed, root); FadeTransition anim = new FadeTransition(Duration.seconds(3)); anim.setCycleCount(1); anim.setNode(root); anim.setFromValue(0.1); anim.setToValue(1); anim.play(); LOG.log(java.lang.System.Logger.Level.INFO, String.format("Installed %s add-on", file)); } catch (Exception e) { LOG.log(java.lang.System.Logger.Level.ERROR, "Failed to add add-on.", e); error("failedToInstallAddOn", e.getMessage()); } } } @FXML void evtUrl() { error(null); AddOn addOn = getSelectedAddOn(); context.getHostServices().showDocument(addOn.getUrl()); } @FXML void evtBack() { context.pop(); } }
6,838
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
AbstractDetailsController.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/AbstractDetailsController.java
package uk.co.bithatch.snake.ui; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; public abstract class AbstractDetailsController extends AbstractDeviceController { @FXML private Label deviceName; @FXML private ImageView deviceImage; @FXML private Hyperlink back; @FXML private BorderPane header; @Override protected void onConfigure() { } @Override protected final void onSetDevice() throws Exception { header.setBackground(createHeaderBackground()); deviceImage.setImage(new Image(context.getDefaultImage(getDevice().getType(), context.getCache().getCachedImage(getDevice().getImage())), true)); deviceName.textProperty().set(getDevice().getName()); back.visibleProperty().set(context.getControllers().indexOf(this) > 0); onSetDeviceDetails(); } protected void onSetDeviceDetails() throws Exception { } @FXML void evtBack(ActionEvent evt) { context.pop(); } }
1,096
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Configuration.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/Configuration.java
package uk.co.bithatch.snake.ui; import java.util.Arrays; import java.util.Collection; import java.util.prefs.BackingStoreException; import java.util.prefs.PreferenceChangeEvent; import java.util.prefs.PreferenceChangeListener; import java.util.prefs.Preferences; import javafx.scene.paint.Color; import uk.co.bithatch.snake.ui.addons.Theme; public class Configuration implements PreferenceChangeListener { public static final String PREF_THEME = "theme"; public static final String PREF_TRANSPARENCY = "transparency"; public static final String PREF_H = "h"; public static final String PREF_W = "w"; public static final String PREF_Y = "y"; public static final String PREF_X = "x"; public static final String PREF_AUDIO_GAIN = "audioGain"; public static final String PREF_AUDIO_FFT = "audioFFT"; public static final String PREF_AUDIO_FPS = "audioFPS"; public static final String PREF_AUDIO_SOURCE = "audioSource"; public static final String PREF_TURN_OFF_ON_EXIT = "turnOffOnExit"; public static final String PREF_DECORATED = "decorated"; public static final String PREF_TRAY_ICON = "trayIcon"; public static final String PREF_WHEN_LOW = "whenLow"; public static final String PREF_SHOW_BATTERY = "showBattery"; public static final String PREF_TELEMETRY = "telemetry"; public enum TrayIcon { OFF, AUTO, DARK, LIGHT, COLOR } private Preferences node; private Theme theme; private boolean decorated; private boolean turnOffOnExit; private int x, y, w, h; private String audioSource; private int audioFPS; private boolean audioFFT; private float audioGain; private int transparency; private boolean showBattery; private boolean whenLow; private TrayIcon trayIcon; private boolean telemetry; Configuration(Preferences node, App context) { this.node = node; showBattery = node.getBoolean(PREF_SHOW_BATTERY, true); telemetry = node.getBoolean(PREF_TELEMETRY, true); whenLow = node.getBoolean(PREF_WHEN_LOW, true); trayIcon = TrayIcon.valueOf(node.get(PREF_TRAY_ICON, TrayIcon.AUTO.name())); decorated = node.getBoolean(PREF_DECORATED, false); turnOffOnExit = node.getBoolean(PREF_TURN_OFF_ON_EXIT, true); audioSource = node.get(PREF_AUDIO_SOURCE, ""); audioFPS = node.getInt(PREF_AUDIO_FPS, 10); audioFFT = node.getBoolean(PREF_AUDIO_FFT, false); audioGain = node.getFloat(PREF_AUDIO_GAIN, 1); x = node.getInt(PREF_X, 0); y = node.getInt(PREF_Y, 0); w = node.getInt(PREF_W, 0); h = node.getInt(PREF_H, 0); transparency = node.getInt(PREF_TRANSPARENCY, 0); String themeName = node.get(PREF_THEME, ""); Collection<Theme> themes = context.getAddOnManager().getThemes(); if (themes.isEmpty()) throw new IllegalStateException("No themes. Please add a theme module to the classpath or modulepath."); Theme firstTheme = themes.iterator().next(); if (themeName.equals("")) { themeName = firstTheme.getId(); } Theme selTheme = context.getAddOnManager().getTheme(themeName); if (selTheme == null && !themeName.equals(firstTheme.getId())) selTheme = firstTheme; theme = selTheme; node.addPreferenceChangeListener(this); } public boolean hasBounds() { try { return Arrays.asList(node.keys()).contains(PREF_X); } catch (BackingStoreException e) { return false; } } public Theme getTheme() { return theme; } public void setTheme(Theme theme) { this.theme = theme; node.put(PREF_THEME, theme.getId()); } public boolean isDecorated() { return decorated; } public void setDecorated(boolean decorated) { this.decorated = decorated; node.putBoolean(PREF_DECORATED, decorated); } public boolean isTurnOffOnExit() { return turnOffOnExit; } public void setTurnOffOnExit(boolean turnOffOnExit) { this.turnOffOnExit = turnOffOnExit; node.putBoolean(PREF_TURN_OFF_ON_EXIT, turnOffOnExit); } public int getX() { return x; } public void setX(int x) { this.x = x; node.putInt(PREF_X, x); } public int getY() { return y; } public void setY(int y) { this.y = y; node.putInt(PREF_Y, y); } public int getW() { return w; } public void setW(int w) { this.w = w; node.putInt(PREF_W, w); } public int getH() { return h; } public void setH(int h) { this.h = h; node.putInt(PREF_H, h); } public String getAudioSource() { return audioSource; } public void setAudioSource(String audioSource) { this.audioSource = audioSource; node.put(PREF_AUDIO_SOURCE, audioSource); } public int getAudioFPS() { return audioFPS; } public void setAudioFPS(int audioFPS) { this.audioFPS = audioFPS; node.putInt(PREF_AUDIO_FPS, audioFPS); } public boolean isAudioFFT() { return audioFFT; } public void setAudioFFT(boolean audioFFT) { this.audioFFT = audioFFT; node.putBoolean(PREF_AUDIO_FFT, audioFFT); } public float getAudioGain() { return audioGain; } public void setAudioGain(float audioGain) { this.audioGain = audioGain; node.putFloat(PREF_AUDIO_GAIN, audioGain); } public int getTransparency() { return transparency; } public void setTransparency(int transparency) { this.transparency = transparency; node.putInt(PREF_TRANSPARENCY, transparency); } public boolean isShowBattery() { return showBattery; } public void setShowBattery(boolean showBattery) { this.showBattery = showBattery; node.putBoolean(PREF_SHOW_BATTERY, showBattery); } public boolean isTelemetry() { return telemetry; } public void setTelemetry(boolean telemetry) { this.telemetry = telemetry; node.putBoolean(PREF_TELEMETRY, telemetry); } public boolean isWhenLow() { return whenLow; } public void setWhenLow(boolean whenLow) { this.whenLow = whenLow; node.putBoolean(PREF_WHEN_LOW, whenLow); } public TrayIcon getTrayIcon() { return trayIcon; } public Preferences getNode() { return node; } public void setTrayIcon(TrayIcon trayIcon) { this.trayIcon = trayIcon; node.put(PREF_TRAY_ICON, trayIcon.name()); } static void putColor(String key, Preferences p, Color color) { p.putDouble(key + "_r", color.getRed()); p.putDouble(key + "_g", color.getGreen()); p.putDouble(key + "_b", color.getBlue()); p.putDouble(key + "_a", color.getOpacity()); } static Color getColor(String key, Preferences p, Color defaultColour) { return new Color(p.getDouble(key + "_r", defaultColour == null ? 1.0 : defaultColour.getRed()), p.getDouble(key + "_g", defaultColour == null ? 1.0 : defaultColour.getGreen()), p.getDouble(key + "_b", defaultColour == null ? 1.0 : defaultColour.getBlue()), p.getDouble(key + "_a", defaultColour == null ? 1.0 : defaultColour.getOpacity())); } @Override public void preferenceChange(PreferenceChangeEvent evt) { if (evt.getKey().equals(PREF_DECORATED)) { if (evt.getNewValue().equals("true")) { node.putInt(PREF_TRANSPARENCY, 0); } } } }
6,832
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
RippleOptions.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/RippleOptions.java
package uk.co.bithatch.snake.ui; import javafx.beans.binding.Bindings; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.Slider; import uk.co.bithatch.snake.lib.Capability; import uk.co.bithatch.snake.lib.effects.Ripple; import uk.co.bithatch.snake.lib.effects.Ripple.Mode; import uk.co.bithatch.snake.ui.effects.RippleEffectHandler; import uk.co.bithatch.snake.widgets.ColorBar; import uk.co.bithatch.snake.widgets.Direction; import uk.co.bithatch.snake.widgets.JavaFX; public class RippleOptions extends AbstractBackendEffectController<Ripple, RippleEffectHandler> { @FXML private Slider refreshRate; @FXML private ColorBar color; @FXML private Label colorLabel; @FXML private RadioButton single; @FXML private RadioButton random; private boolean adjusting = false; public double getRefreshRate() { return refreshRate.valueProperty().get(); } public Mode getMode() { if (single.selectedProperty().get()) return Mode.SINGLE; else return Mode.RANDOM; } public int[] getColor() { return JavaFX.toRGB(color.getColor()); } @Override protected void onConfigure() throws Exception { color.disableProperty().bind(Bindings.not(single.selectedProperty())); colorLabel.setLabelFor(color); colorLabel.managedProperty().bind(colorLabel.visibleProperty()); colorLabel.visibleProperty().bind(color.visibleProperty()); ; color.managedProperty().bind(color.visibleProperty()); color.visibleProperty().bind(single.visibleProperty()); random.managedProperty().bind(random.visibleProperty()); single.managedProperty().bind(single.visibleProperty()); single.selectedProperty().addListener((e) -> { if (single.isSelected()) update(); }); random.selectedProperty().addListener((e) -> { if (random.isSelected()) update(); }); color.colorProperty().addListener((e) -> update()); refreshRate.valueProperty().addListener((e) -> update()); } @FXML void evtBack(ActionEvent evt) { context.pop(); } @FXML void evtOptions(ActionEvent evt) { context.push(Options.class, this, Direction.FROM_BOTTOM); } @Override protected void onSetEffect() { Ripple effect = getEffect(); adjusting = true; try { switch (effect.getMode()) { case SINGLE: single.selectedProperty().set(true); break; default: random.selectedProperty().set(true); break; } refreshRate.valueProperty().set(effect.getRefreshRate()); color.setColor(JavaFX.toColor(effect.getColor())); random.visibleProperty().set(getRegion().getCapabilities().contains(Capability.RIPPLE_RANDOM)); single.visibleProperty().set(getRegion().getCapabilities().contains(Capability.RIPPLE_SINGLE)); } finally { adjusting = false; } } protected void update() { if (!adjusting) getEffectHandler().store(getRegion(), this); } }
2,912
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Overview.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/Overview.java
package uk.co.bithatch.snake.ui; import java.lang.System.Logger.Level; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.prefs.PreferenceChangeEvent; import java.util.prefs.PreferenceChangeListener; import org.controlsfx.control.ToggleSwitch; import org.kordamp.ikonli.javafx.FontIcon; import javafx.animation.FadeTransition; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.Slider; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.util.Duration; import uk.co.bithatch.snake.lib.Backend.BackendListener; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.lib.Device.Listener; import uk.co.bithatch.snake.lib.DeviceType; import uk.co.bithatch.snake.lib.Region; import uk.co.bithatch.snake.lib.binding.Profile; import uk.co.bithatch.snake.lib.binding.ProfileMap; import uk.co.bithatch.snake.widgets.Direction; import uk.co.bithatch.snake.widgets.ImageButton; import uk.co.bithatch.snake.widgets.JavaFX; public class Overview extends AbstractController implements Listener, BackendListener, PreferenceChangeListener { final static ResourceBundle bundle = ResourceBundle.getBundle(Overview.class.getName()); private static final int MIN_ITEMS_FOR_SEARCH = 3; @FXML private Label battery; @FXML private Slider brightness; @FXML private Hyperlink clearFilter; @FXML private BorderPane content; @FXML private HBox decoratedTools; @FXML private ListView<Node> devices; @FXML private TextField filter; @FXML private BorderPane filterOptions; @FXML private BorderPane header; @FXML private BorderPane overviewContent; @FXML private ToggleSwitch sync; @FXML private HBox types; @FXML private Hyperlink update; // private BorderPane tempFilterOptions; private boolean adjustingBrightness; private List<Device> deviceList = new ArrayList<>(); private Map<Node, DeviceOverview> deviceMap = new HashMap<>(); private Map<DeviceType, List<Device>> deviceTypeMap = new HashMap<>(); private List<DeviceType> filteredTypes = new ArrayList<>(); private Timeline filterTimer; private Timeline brightnessTimer; private FadeTransition batteryFader; @Override public void activeMapChanged(ProfileMap map) { } @Override public void changed(Device device, Region region) { Platform.runLater(() -> { rebuildBattery(); if (!adjustingBrightness) { adjustingBrightness = true; try { brightness.valueProperty().set(context.getBackend().getBrightness()); } catch(Exception e) { // } finally { adjustingBrightness = false; } } }); } @Override public void deviceAdded(Device device) { Platform.runLater(() -> { devicesChanged(); }); } @Override public void deviceRemoved(Device device) { Platform.runLater(() -> { devicesChanged(); }); } @Override public void mapAdded(ProfileMap profile) { } @Override public void mapChanged(ProfileMap profile) { } @Override public void mapRemoved(ProfileMap profile) { } @Override public void profileAdded(Profile profile) { } @Override public void profileRemoved(Profile profile) { } protected void devicesChanged() { try { rebuildDevices(); rebuildFilterTypes(); rebuildBattery(); filter(); } catch (Exception e) { LOG.log(Level.ERROR, "Failed to update devices.", e); } } @Override protected void onCleanUp() { for (DeviceOverview dov : deviceMap.values()) dov.cleanUp(); deviceMap.clear(); context.getBackend().removeListener(this); context.getConfiguration().getNode().removePreferenceChangeListener(this); } @Override protected void onConfigure() throws Exception { super.onConfigure(); JavaFX.bindManagedToVisible(filterOptions); decoratedTools.visibleProperty().set(context.getConfiguration().isDecorated()); context.getConfiguration().getNode().addPreferenceChangeListener(this); filterOptions.setBackground(createHeaderBackground()); batteryFader = BatteryControl.createFader(battery); rebuildDevices(); rebuildFilterTypes(); rebuildBattery(); filter(); context.getBackend().addListener(this); brightness.valueProperty().set(context.getBackend().getBrightness()); brightness.valueProperty().addListener((e) -> { if (!adjustingBrightness) { /* * If there are more than a handfule of devices, instead put the update on a * timer, as it can get pretty slow (e.g. with all fake drivers enabled, the 70 * ish devices make the slider a bit jerky) */ if (deviceList != null && deviceList.size() > 10) { resetBrightnessTimer((ae) -> updateBrightness()); } else { updateBrightness(); } } }); devices.setOnMouseClicked((e) -> { if (e.getClickCount() == 2) { context.push(DeviceDetails.class, this, Direction.FROM_RIGHT) .setDevice(deviceMap.get(devices.getSelectionModel().getSelectedItem()).getDevice()); } }); sync.setSelected(context.getEffectManager().isSync()); filter.textProperty().addListener((e) -> resetFilterTimer()); clearFilter.onActionProperty().set((e) -> { filter.textProperty().set(""); cancelFilterTimer(); filter(); }); if (PlatformService.isPlatformSupported()) { PlatformService ps = PlatformService.get(); if (ps.isUpdateAvailable()) { update.visibleProperty().set(true); FadeTransition anim = new FadeTransition(Duration.seconds(5)); anim.setAutoReverse(true); anim.setCycleCount(FadeTransition.INDEFINITE); anim.setNode(update); anim.setFromValue(0.5); anim.setToValue(1); anim.play(); } else update.visibleProperty().set(false); } else update.visibleProperty().set(false); if (!context.getMacroManager().isStarted()) { notifyMessage(MessagePersistence.ONCE_PER_RUNTIME, MessageType.WARNING, null, bundle.getString("warning.noUInput"), 60); } } void cancelBrightnessTimer() { if (brightnessTimer != null) { brightnessTimer.stop(); brightnessTimer = null; } } void cancelFilterTimer() { if (filterTimer != null) { filterTimer.stop(); filterTimer = null; } } @FXML void evtAbout() { context.push(About.class, Direction.FADE); } @FXML void evtOptions() { context.push(Options.class, Direction.FROM_BOTTOM); } @FXML void evtSync() { sync.selectedProperty().addListener((e) -> context.getEffectManager().setSync(sync.selectedProperty().get())); } @FXML void evtToggleSync() { sync.setSelected(!sync.isSelected()); } @FXML void evtUpdate() { context.push(Options.class, Direction.FROM_BOTTOM); } void filter() { try { for (Map.Entry<Node, DeviceOverview> en : deviceMap.entrySet()) { en.getValue().cleanUp(); } deviceMap.clear(); devices.getItems().clear(); String filterText = filter.textProperty().get().toLowerCase(); for (Device device : deviceList) { if (matchesFilter(filterText, device) && matchesFilteredType(device)) { DeviceOverview overview = context.openScene(DeviceOverview.class); overview.setDevice(device); Parent node = overview.getScene().getRoot(); devices.getItems().add(node); deviceMap.put(node, overview); } } } catch (Exception e) { throw new IllegalStateException("Failed to get devices.", e); } } void resetBrightnessTimer(EventHandler<ActionEvent> cb) { if (brightnessTimer == null) { brightnessTimer = new Timeline(new KeyFrame(Duration.millis(750), cb)); } brightnessTimer.playFromStart(); } void resetFilterTimer() { if (filterTimer == null) { filterTimer = new Timeline(new KeyFrame(Duration.millis(750), ae -> filter())); } filterTimer.playFromStart(); } private boolean matchesFilter(String filterText, Device device) { return filterText.equals("") || device.getName().toLowerCase().contains(filterText) || device.getDriverVersion().toLowerCase().contains(filterText) || device.getSerial().toLowerCase().contains(filterText); } private boolean matchesFilteredType(Device device) { return deviceTypeMap.size() < 2 || filteredTypes.contains(device.getType()); } private void rebuildBattery() { int batt = context.getBackend().getBattery(); if (batt < 0) { battery.visibleProperty().set(false); batteryFader.stop(); } else { battery.graphicProperty().set(new FontIcon(BatteryControl.getBatteryIcon(batt))); BatteryControl.setBatteryStatusStyle(context.getBackend().getLowBatteryThreshold(), batt, battery, batteryFader); battery.visibleProperty().set(true); } } private void rebuildDevices() throws Exception { for (Device dev : deviceList) { dev.removeListener(this); } deviceList = context.getBackend().getDevices(); deviceTypeMap.clear(); for (Device d : deviceList) { List<Device> dl = deviceTypeMap.get(d.getType()); if (dl == null) { dl = new ArrayList<>(); deviceTypeMap.put(d.getType(), dl); } dl.add(d); d.addListener(this); } filter.setVisible(deviceList.size() > MIN_ITEMS_FOR_SEARCH); clearFilter.setVisible(deviceList.size() > MIN_ITEMS_FOR_SEARCH); updateFilterOptions(); } private void rebuildFilterTypes() { types.getChildren().clear(); filteredTypes.clear(); for (DeviceType type : DeviceType.values()) { if (type != DeviceType.UNRECOGNISED && deviceTypeMap.containsKey(type)) { URL typeImage = context.getConfiguration().getTheme().getDeviceImage(32, type); if (typeImage == null) { typeImage = context.getConfiguration().getTheme().getDeviceImage(32, DeviceType.UNRECOGNISED); } Image img = new Image(typeImage.toExternalForm(), 32, 32, true, true, true); ImageButton button = new ImageButton(img, 32, 32); button.onActionProperty().set((e) -> { if (filteredTypes.size() > 1 && filteredTypes.contains(type)) { button.opacityProperty().set(0.5); filteredTypes.remove(type); } else if (!filteredTypes.contains(type)) { button.opacityProperty().set(1); filteredTypes.add(type); } filter(); }); filteredTypes.add(type); types.getChildren().add(button); } } types.setVisible(types.getChildren().size() > 1); updateFilterOptions(); } private void updateBrightness() { adjustingBrightness = true; try { context.getBackend().setBrightness((short) brightness.valueProperty().get()); } finally { adjustingBrightness = false; } } private void updateFilterOptions() { boolean showFilter = deviceList.size() > MIN_ITEMS_FOR_SEARCH || filteredTypes.size() > 1; filterOptions.setVisible(showFilter); // if (showFilter && tempFilterOptions != null) { // content.getChildren().add(tempFilterOptions); // tempFilterOptions = null; // } else if (!showFilter && tempFilterOptions == null) { // content.getChildren().remove(filterOptions); // tempFilterOptions = filterOptions; // } content.layout(); } @Override public void preferenceChange(PreferenceChangeEvent evt) { if (evt.getKey().equals(Configuration.PREF_DECORATED)) decoratedTools.setVisible(context.getConfiguration().isDecorated()); } }
11,515
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
StaticOptions.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/StaticOptions.java
package uk.co.bithatch.snake.ui; import javafx.event.ActionEvent; import javafx.fxml.FXML; import uk.co.bithatch.snake.lib.effects.Static; import uk.co.bithatch.snake.ui.effects.StaticEffectHandler; import uk.co.bithatch.snake.widgets.ColorBar; import uk.co.bithatch.snake.widgets.JavaFX; public class StaticOptions extends AbstractBackendEffectController<Static, StaticEffectHandler> { @FXML private ColorBar color; private boolean adjusting = false; public int[] getColor() { return JavaFX.toRGB(color.getColor()); } @Override protected void onConfigure() throws Exception { color.colorProperty().addListener((e) -> { if (!adjusting) { getEffectHandler().store(getRegion(), this); } }); } @Override protected void onSetEffect() { Static effect = getEffect(); adjusting = true; try { color.setColor(JavaFX.toColor(effect.getColor())); } finally { adjusting = false; } } @FXML void evtBack(ActionEvent evt) { context.pop(); } }
984
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Record.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/Record.java
package uk.co.bithatch.snake.ui; import java.util.Iterator; import java.util.ResourceBundle; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.scene.Group; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.layout.FlowPane; import javafx.scene.layout.VBox; import uk.co.bithatch.macrolib.MacroSystem; import uk.co.bithatch.macrolib.MacroSystem.RecordingListener; import uk.co.bithatch.macrolib.RecordedEvent; import uk.co.bithatch.macrolib.RecordingSession; public class Record extends AbstractDetailsController implements RecordingListener { final static ResourceBundle bundle = ResourceBundle.getBundle(Record.class.getName()); @FXML private VBox keyContainer; @FXML private Label status; @FXML private Label empty; @FXML private Hyperlink startRecord; @FXML private Hyperlink pause; @FXML private Hyperlink stop; @FXML private FlowPane keys; @FXML private Group headerImageGroup; private RecordingSession sequence; private MacroSystem macroSystem; @Override protected void onSetDeviceDetails() throws Exception { macroSystem = context.getMacroManager().getMacroSystem(); sequence = macroSystem.getRecordingSession(); empty.managedProperty().bind(empty.visibleProperty()); macroSystem.addRecordingListener(this); // headerImageGroup.getChildren().add(MacroMap.iconForMapSequence(sequence)); updateState(); rebuildSeq(); } @Override protected void onDeviceCleanUp() { macroSystem.removeRecordingListener(this); } private void rebuildSeq() { keys.getChildren().clear(); for (Iterator<RecordedEvent> evtIt = sequence.getEvents(); evtIt.hasNext();) { RecordedEvent evt = evtIt.next(); // Label l = new Label(MacroMap.textForMapAction(m)); // l.setGraphic(MacroMap.iconForMacro(m)); // keys.getChildren().add(l); } empty.visibleProperty().set(keys.getChildren().isEmpty()); } void updateState() { switch (sequence.getRecordingState()) { case IDLE: status.textProperty().set(bundle.getString("state.IDLE")); status.getStyleClass().remove("danger"); status.getStyleClass().remove("warning"); status.getStyleClass().add("success"); startRecord.disableProperty().set(false); stop.disableProperty().set(true); pause.disableProperty().set(true); break; case WAITING_FOR_EVENTS: case WAITING_FOR_TARGET_KEY: status.textProperty().set(bundle.getString("state.RECORDING")); status.getStyleClass().add("danger"); status.getStyleClass().remove("warning"); status.getStyleClass().remove("success"); startRecord.disableProperty().set(true); stop.disableProperty().set(false); pause.disableProperty().set(false); break; case PAUSED: status.textProperty().set(bundle.getString("state.RECORDING")); status.getStyleClass().remove("danger"); status.getStyleClass().remove("warning"); status.getStyleClass().add("success"); startRecord.disableProperty().set(true); stop.disableProperty().set(true); pause.disableProperty().set(true); break; case ERROR: notifyMessage(MessageType.DANGER, context.getMacroManager().getMacroSystem().getRecordingSession() .getRecordingError().getLocalizedMessage()); break; } } @FXML void evtBack() { context.pop(); if (context.getMacroManager().getMacroSystem().isRecording()) context.getMacroManager().getMacroSystem().stopRecording(); } @FXML void evtStartRecord() { context.getMacroManager().getMacroSystem().startRecording(); } @FXML void evtPause() { context.getMacroManager().getMacroSystem().togglePauseRecording(); } @FXML void evtStop() { context.getMacroManager().getMacroSystem().stopRecording(); context.pop(); } @Override public void recordingStateChange(RecordingSession session) { Platform.runLater(() -> { updateState(); rebuildSeq(); }); } @Override public void eventRecorded() { Platform.runLater(() -> rebuildSeq()); } }
3,941
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Bank.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/Bank.java
package uk.co.bithatch.snake.ui; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.System.Logger.Level; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.ResourceBundle; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.function.UnaryOperator; import java.util.prefs.Preferences; import org.controlsfx.control.SearchableComboBox; import org.controlsfx.control.ToggleSwitch; import org.kordamp.ikonli.fontawesome.FontAwesome; import org.kordamp.ikonli.javafx.FontIcon; import com.sshtools.icongenerator.IconBuilder.TextContent; import com.sshtools.jfreedesktop.javafx.SVGIcon; import javafx.beans.binding.Bindings; import javafx.beans.property.SimpleBooleanProperty; import javafx.fxml.FXML; import javafx.geometry.Side; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.ContextMenu; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.control.MenuItem; import javafx.scene.control.MultipleSelectionModel; import javafx.scene.control.RadioButton; import javafx.scene.control.SelectionMode; import javafx.scene.control.Spinner; import javafx.scene.control.SpinnerValueFactory; import javafx.scene.control.TabPane; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.TextFormatter; import javafx.scene.control.TextFormatter.Change; import javafx.scene.control.ToggleGroup; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import javafx.scene.layout.Region; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.FileChooser.ExtensionFilter; import javafx.stage.Stage; import javafx.util.Callback; import javafx.util.converter.FloatStringConverter; import uk.co.bithatch.linuxio.EventCode; import uk.co.bithatch.linuxio.EventCode.Type; import uk.co.bithatch.macrolib.Action; import uk.co.bithatch.macrolib.ActionMacro; import uk.co.bithatch.macrolib.Application; import uk.co.bithatch.macrolib.CommandMacro; import uk.co.bithatch.macrolib.KeySequence; import uk.co.bithatch.macrolib.Macro; import uk.co.bithatch.macrolib.MacroBank; import uk.co.bithatch.macrolib.MacroProfile; import uk.co.bithatch.macrolib.NoopMacro; import uk.co.bithatch.macrolib.RepeatMode; import uk.co.bithatch.macrolib.ScriptMacro; import uk.co.bithatch.macrolib.SimpleMacro; import uk.co.bithatch.macrolib.TargetType; import uk.co.bithatch.macrolib.UInputMacro; import uk.co.bithatch.macrolib.View; import uk.co.bithatch.macrolib.Window; import uk.co.bithatch.snake.lib.Capability; import uk.co.bithatch.snake.lib.ValidationException; import uk.co.bithatch.snake.lib.layouts.ComponentType; import uk.co.bithatch.snake.lib.layouts.DeviceLayout; import uk.co.bithatch.snake.lib.layouts.DeviceView; import uk.co.bithatch.snake.lib.layouts.IO; import uk.co.bithatch.snake.lib.layouts.Key; import uk.co.bithatch.snake.ui.designer.LayoutEditor; import uk.co.bithatch.snake.ui.designer.Viewer; import uk.co.bithatch.snake.ui.util.BasicList; import uk.co.bithatch.snake.ui.util.Strings; import uk.co.bithatch.snake.ui.widgets.MacroBankLEDHelper; import uk.co.bithatch.snake.widgets.Direction; import uk.co.bithatch.snake.widgets.GeneratedIcon; import uk.co.bithatch.snake.widgets.JavaFX; import uk.co.bithatch.snake.widgets.ProfileLEDs; public class Bank extends AbstractDetailsController { public static String textForMapSequence(KeySequence seq) { return textForInputEvent(seq.get(0)); } protected static String textForInputEvent(EventCode k) { String keyName = String.valueOf(k); String txt = keyName.substring(4); if (txt.length() > 3) return Strings.toName(txt); else { if (keyName.startsWith("BTN_")) { return MessageFormat.format(bundle.getString("button.name"), txt); } else { return MessageFormat.format(bundle.getString("key.name"), txt); } } } public static GeneratedIcon iconForMapSequence(KeySequence seq) { GeneratedIcon icon = new GeneratedIcon(); icon.getStyleClass().add("mapSequence"); icon.setPrefHeight(32); icon.setPrefWidth(32); String keyName = String.valueOf(seq.get(0)); if (keyName.startsWith("BTN_")) { icon.getStyleClass().add("mapSequenceButton"); } else { icon.getStyleClass().add("mapSequenceKey"); } String txt = keyName.substring(4); icon.setText(txt); if (txt.length() > 3) icon.setTextContent(TextContent.INITIALS); else icon.setTextContent(TextContent.ORIGINAL); return icon; } private static class MacroListCell extends ListCell<KeySequence> { @Override public void updateItem(KeySequence item, boolean empty) { super.updateItem(item, empty); if (empty) { setGraphic(null); setText(null); } else { setGraphic(iconForMapSequence(item)); setText(textForMapSequence(item)); } } } private static class ActionListCell extends ListCell<Action> { @Override public void updateItem(Action item, boolean empty) { super.updateItem(item, empty); setGraphic(null); if (empty) { setText(null); } else { setText(item.getId()); } } } final static ResourceBundle bundle = ResourceBundle.getBundle(Bank.class.getName()); final static Preferences PREFS = Preferences.userNodeForPackage(Bank.class); static List<String> parseQuotedString(String command) { List<String> args = new ArrayList<String>(); boolean escaped = false; boolean quoted = false; StringBuilder word = new StringBuilder(); for (int i = 0; i < command.length(); i++) { char c = command.charAt(i); if (c == '"' && !escaped) { if (quoted) { quoted = false; } else { quoted = true; } } else if (c == '\\' && !escaped) { escaped = true; } else if ((c == ' ' || c == '\n') && !escaped && !quoted) { if (word.length() > 0) { args.add(word.toString()); word.setLength(0); ; } } else { word.append(c); } } if (word.length() > 0) args.add(word.toString()); return args; } @FXML private Hyperlink add; @FXML private Hyperlink delete; @FXML private VBox editor; @FXML private Hyperlink export; @FXML private VBox keySection; @FXML private SearchableComboBox<EventCode> macroKey; @FXML private ComboBox<TargetType> targetType; @FXML private ToggleGroup macroType; @FXML private TextField repeatDelay; @FXML private TextArea commandArgs; @FXML private TextArea script; @FXML private Button commandBrowse; @FXML private CheckBox passthrough; @FXML private Spinner<Integer> value; @FXML private TextField commandLocation; @FXML private TextField simpleMacroText; @FXML private VBox commandSection; @FXML private VBox scriptSection; @FXML private VBox repeatSection; @FXML private VBox unmappedSection; @FXML private VBox actionSection; @FXML private VBox newMacroSection; @FXML private VBox sequenceEditor; @FXML private VBox simpleMacroSection; @FXML private SearchableComboBox<EventCode> keyCode; @FXML private RadioButton uinputMacro; @FXML private RadioButton commandMacro; @FXML private RadioButton noopMacro; @FXML private RadioButton scriptMacro; @FXML private RadioButton simpleMacro; @FXML private RadioButton actionMacro; @FXML private Hyperlink recordMacro; @FXML private ComboBox<Action> targetAction; @FXML private BorderPane macrosContainer; @FXML private BorderPane viewContainer; @FXML private ComboBox<RepeatMode> repeatMode; @FXML private Label title; @FXML private ToggleSwitch defaultBank; @FXML private ToggleSwitch defaultProfile; @FXML private Label defaultBankOnText; @FXML private Label defaultBankOffText; @FXML private Label defaultProfileOnText; @FXML private Label defaultProfileOffText; @FXML private Label profileLEDLabel; @FXML private TextField bankName; @FXML private ProfileLEDs profileLED; @FXML private TextField profileName; @FXML private ComboBox<uk.co.bithatch.macrolib.Window> window; @FXML private ComboBox<Application> application; @FXML private ToggleGroup profileLEDMode; @FXML private RadioButton automatic; @FXML private RadioButton manual; @FXML private Hyperlink addApplication; @FXML private Hyperlink addWindow; @FXML private Hyperlink removeApplication; @FXML private Hyperlink removeWindow; @FXML private ListView<Application> includeApplication; @FXML private ListView<Application> excludeApplication; @FXML private ListView<uk.co.bithatch.macrolib.Window> includeWindow; @FXML private ListView<uk.co.bithatch.macrolib.Window> excludeWindow; @FXML private TabPane applicationsTabs; @FXML private TabPane windowsTabs; @FXML private TextField windowRegExp; @FXML private TextField applicationRegExp; // TODO needed? private ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); private MacroBank bank; private ScheduledFuture<?> task; private boolean adjusting = false; private MacrosView macros; private LayoutEditor layoutEditor; private Macro macro; private MacroBankLEDHelper profileLEDHelper; protected ContextMenu createContextMenu() { ContextMenu menu = new ContextMenu(); MenuItem remove = new MenuItem(bundle.getString("contextMenuRemove")); remove.onActionProperty().set((e) -> { evtDelete(); }); menu.getItems().add(remove); if (macros != null) { MenuItem add = new MenuItem(bundle.getString("contextMenuAdd")); add.onActionProperty().set((e) -> { add(macros.getSequenceSelectionModel().getSelectedItem()); }); menu.getItems().add(add); menu.setOnShowing((e) -> { remove.disableProperty().set(!bank.contains(macros.getSequenceSelectionModel().getSelectedItem())); add.disableProperty().set(bank.contains(macros.getSequenceSelectionModel().getSelectedItem())); }); } else { menu.setOnShowing((e) -> { remove.disableProperty().set(!bank.contains(macros.getSequenceSelectionModel().getSelectedItem())); }); } return menu; } protected void error(String key) { if (key == null) clearNotifications(false); else { String txt = bundle.getString(key); notifyMessage(MessageType.DANGER, txt == null ? "<missing key " + key + ">" : txt); } } @Override protected void onDeviceCleanUp() { if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, "Stopping macros scheduler."); if (profileLEDHelper != null) { try { profileLEDHelper.close(); } catch (IOException e1) { } } executor.shutdown(); if (layoutEditor != null) { try { layoutEditor.close(); } catch (Exception e) { } } } public void setBank(MacroBank bank) throws Exception { /* Set convenience instance variables */ this.bank = bank; /* Get current profile, bank etc */ var macroManager = context.getMacroManager(); var macroDevice = bank.getProfile().getDevice(); var device = macroManager.getNativeDevice(macroDevice); /* Simple bindings */ JavaFX.bindManagedToVisible(commandSection, keySection, repeatSection, editor, actionSection, actionMacro, simpleMacroSection, scriptSection, recordMacro, newMacroSection, unmappedSection, add, defaultProfileOnText, defaultProfileOffText, defaultBankOnText, defaultBankOffText, profileLEDLabel, profileLED, automatic, manual); profileLED.disableProperty().bind(automatic.selectedProperty()); profileLEDLabel.visibleProperty().bind(profileLED.visibleProperty()); automatic.visibleProperty().bind(profileLED.visibleProperty()); manual.visibleProperty().bind(profileLED.visibleProperty()); defaultProfile.setDisable(bank.getProfile().getSystem().getNumberOfProfiles(bank.getProfile().getDevice()) < 2); defaultBank.setDisable(bank.getProfile().getBanks().size() < 2); defaultProfileOffText.visibleProperty().bind(defaultProfile.selectedProperty()); defaultProfileOnText.visibleProperty().bind(Bindings.not(defaultProfile.selectedProperty())); defaultBank.selectedProperty().addListener((e, o, n) -> { try { if (n) bank.getProfile().makeActive(); else { for (Iterator<MacroProfile> profileIt = bank.getProfile().getSystem() .profiles(bank.getProfile().getDevice()); profileIt.hasNext();) { MacroProfile p = profileIt.next(); if (p != bank.getProfile()) { p.makeActive(); break; } } if (bank.getProfile().isActive()) throw new Exception("No other profilea."); } } catch (Exception ex) { error(ex); } }); defaultBankOffText.visibleProperty().bind(defaultBank.selectedProperty()); defaultBankOnText.visibleProperty().bind(Bindings.not(defaultBank.selectedProperty())); defaultBank.selectedProperty().addListener((e, o, n) -> { try { if (n) bank.makeActive(); else { for (MacroBank b : bank.getProfile().getBanks()) { if (b != bank) { b.makeActive(); break; } } if (bank.isActive()) throw new Exception("No other banks."); } } catch (Exception ex) { error(ex); } }); /* Title */ setTitle(); /* Windows and applications */ Callback<ListView<uk.co.bithatch.macrolib.Window>, ListCell<uk.co.bithatch.macrolib.Window>> cellFactory = createWindowCellFactory( true); window.setButtonCell(cellFactory.call(null)); window.setCellFactory(cellFactory); includeWindow.setCellFactory(createWindowCellFactory(false)); excludeWindow.setCellFactory(createWindowCellFactory(false)); window.getItems().addAll(macroManager.getMacroSystem().getMonitor().getWindows()); window.getSelectionModel().selectedItemProperty().addListener((c, o, n) -> { windowRegExp.textProperty().set(""); }); Callback<ListView<Application>, ListCell<Application>> applicationCellFactory = createApplicationCellFactory( true); application.setCellFactory(applicationCellFactory); application.setButtonCell(applicationCellFactory.call(null)); application.getSelectionModel().selectedItemProperty().addListener((c, o, n) -> { applicationRegExp.textProperty().set(""); }); applicationRegExp.textProperty().addListener((c, o, n) -> { if(!n.equals("")) application.getSelectionModel().clearSelection(); }); windowRegExp.textProperty().addListener((c, o, n) -> { if(!n.equals("")) window.getSelectionModel().clearSelection(); }); includeApplication.setCellFactory(createApplicationCellFactory(false)); excludeApplication.setCellFactory(createApplicationCellFactory(false)); application.getItems().addAll(macroManager.getMacroSystem().getMonitor().getApplications()); includeApplication.getSelectionModel().selectedItemProperty().addListener((c, o, n) -> updateAvailability()); excludeApplication.getSelectionModel().selectedItemProperty().addListener((c, o, n) -> updateAvailability()); includeWindow.getSelectionModel().selectedItemProperty().addListener((c, o, n) -> updateAvailability()); excludeWindow.getSelectionModel().selectedItemProperty().addListener((c, o, n) -> updateAvailability()); windowsTabs.getSelectionModel().selectedIndexProperty().addListener((c, o, n) -> updateAvailability()); applicationsTabs.getSelectionModel().selectedIndexProperty().addListener((c, o, n) -> updateAvailability()); /* * If the device has a layout with some Key's, then replace the tree view with * the layout view */ if (context.getLayouts().hasLayout(device)) { DeviceLayout layout = context.getLayouts().getLayout(device); DeviceView view = layout.getViewThatHas(ComponentType.KEY); if (view != null) { macros = new LayoutMacrosView(bank, view, context); } } if (macros == null) { macros = new ListMacrosView(bank, context); /* * Also move the macro editor container into the center of the layout so the * components stretch as expected. When in layout mode, we want the layout to * take all the space, and the editor to have a slimmer column of space on the * right. When in standard mode, we want the editor to take up the most space, * and the list of macros to be a slimmer column down the left. */ Node center = viewContainer.getCenter(); Node right = viewContainer.getRight(); viewContainer.getChildren().remove(center); viewContainer.getChildren().remove(right); viewContainer.setLeft(center); viewContainer.setCenter(right); ((Region) right).setPrefWidth(VBox.USE_COMPUTED_SIZE); } else add.setVisible(false); macros.setContextMenu(createContextMenu()); macrosContainer.setCenter(macros.getNode()); /* The components whose visibility we can easily bind to other simple state */ commandSection.visibleProperty().bind(commandMacro.selectedProperty()); scriptSection.visibleProperty().bind(scriptMacro.selectedProperty()); actionSection.visibleProperty().bind(actionMacro.selectedProperty()); keySection.visibleProperty().bind(uinputMacro.selectedProperty()); simpleMacroSection.visibleProperty().bind(simpleMacro.selectedProperty()); repeatSection.visibleProperty().bind(Bindings.not(noopMacro.selectedProperty())); value.disableProperty().bind(passthrough.selectedProperty()); targetType.disableProperty().bind(passthrough.selectedProperty()); /* Set initial state of various components */ uinputMacro.selectedProperty().set(true); macroKey.itemsProperty().get() .addAll(EventCode.filteredForType(macroDevice.getSupportedInputEvents(), Type.EV_KEY)); targetAction.getItems().addAll(macroManager.getMacroSystem().getActions().values()); repeatMode.getItems().addAll(Arrays.asList(RepeatMode.values())); targetType.getItems().addAll(Arrays.asList(TargetType.uinputTypes())); keyCode.itemsProperty().get().addAll(EventCode.values()); value.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, Short.MAX_VALUE, 0, 1)); /* Configure components rendering / input */ UnaryOperator<Change> floatFilter = change -> { String newText = change.getControlNewText(); if (newText.matches("[-+]?([0-9]*\\.[0-9]+|[0-9]+)")) { return change; } return null; }; repeatDelay.setTextFormatter(new TextFormatter<Float>(new FloatStringConverter(), 0f, floatFilter)); targetAction.setCellFactory((list) -> { return new ActionListCell(); }); bankName.setText(bank.getName()); profileName.setText(bank.getProfile().getName()); /* * Listen to various state changes and adjust other state and selection * accordingly */ bankName.textProperty().addListener((e, o, n) -> { bank.setName(n); saveBank(); setTitle(); }); profileName.textProperty().addListener((e, o, n) -> { bank.getProfile().setName(n); saveProfile(); setTitle(); }); keyCode.getSelectionModel().selectedItemProperty().addListener((e, o, n) -> { if (!adjusting && n != null) { ((UInputMacro) macro).setCode(n); save(macro); macros.refresh(); } }); commandLocation.textProperty().addListener((e, o, n) -> { if (!adjusting) { ((CommandMacro) macro).setCommand(commandLocation.textProperty().get()); save(macro); } }); simpleMacroText.textProperty().addListener((e, o, n) -> { if (!adjusting) { ((SimpleMacro) macro).setMacro(simpleMacroText.textProperty().get()); save(macro); } }); repeatDelay.textProperty().addListener((e, o, n) -> { if (!adjusting) { try { macro.setRepeatDelay(Float.parseFloat(repeatDelay.textProperty().get())); save(macro); } catch (NumberFormatException nfe) { error("invalidPause"); } } }); commandArgs.textProperty().addListener((e, o, n) -> { if (!adjusting) { ((CommandMacro) macro).setArguments(parseQuotedString(commandArgs.textProperty().get())); save(macro); } }); script.textProperty().addListener((e, o, n) -> { if (!adjusting) { ((ScriptMacro) macro).setScript(script.textProperty().get()); save(macro); } }); repeatMode.getSelectionModel().selectedItemProperty().addListener((e, o, n) -> { if (!adjusting) { if (macro != null) { macro.setRepeatMode(n); save(macro); } } }); targetType.getSelectionModel().selectedItemProperty().addListener((e, o, n) -> { if (!adjusting) { if (macro != null) { macro.setType(n); save(macro); } } }); passthrough.selectedProperty().addListener((e, o, n) -> { if (!adjusting) { if (macro != null) { if (n) ((UInputMacro) macro).setType(TargetType.forEvent(macro.getActivatedBy().get(0))); ((UInputMacro) macro).setPassthrough(n); save(macro); } } }); value.valueProperty().addListener((e, o, n) -> { if (!adjusting) { if (macro != null) { ((UInputMacro) macro).setValue(n); save(macro); } } }); targetAction.getSelectionModel().selectedItemProperty().addListener((e, o, n) -> { if (!adjusting) { if (macro != null) { ((ActionMacro) macro).setAction(n == null ? null : n.getId()); save(macro); } } }); macroKey.getSelectionModel().selectedItemProperty().addListener((e, o, n) -> { if (!adjusting) { if (macro != null && n != null) { macro.getActivatedBy().clear(); macro.getActivatedBy().add(macroKey.getSelectionModel().getSelectedItem()); save(macro); macros.refresh(); } } }); macros.getSequenceSelectionModel().selectedItemProperty().addListener((e, o, n) -> { if (!adjusting) { adjusting = true; try { KeySequence key = macros.getSequenceSelectionModel().getSelectedItem(); macro = key == null ? null : bank.getMacro(key); // if (macro == null && key != null) { // macro = createDefaultMacro(key); // } updateForMacro(macro, key != null && key.isEmpty()); } finally { adjusting = false; } } }); /* Watch for the type of macro changing and adjust accordingly */ uinputMacro.selectedProperty().addListener((e, o, n) -> { if (!adjusting && n) { bank.remove(macro); macro = new UInputMacro(macro); if (keyCode.getSelectionModel().getSelectedItem() == null) keyCode.getSelectionModel().select(macroKey.getSelectionModel().getSelectedItem()); bank.add(macro); updateForMacro(macro, false); save(macro); } }); noopMacro.selectedProperty().addListener((e, o, n) -> { if (!adjusting && n) { bank.remove(macro); macro = new NoopMacro(macro); bank.add(macro); updateForMacro(macro, false); save(macro); } }); scriptMacro.selectedProperty().addListener((e, o, n) -> { if (!adjusting && n) { bank.remove(macro); macro = new ScriptMacro(macro); bank.add(macro); updateForMacro(macro, false); save(macro); } }); commandMacro.selectedProperty().addListener((e, o, n) -> { if (!adjusting && n) { bank.remove(macro); macro = new CommandMacro(macro); bank.add(macro); updateForMacro(macro, false); save(macro); } }); actionMacro.selectedProperty().addListener((e, o, n) -> { if (!adjusting && n) { bank.remove(macro); macro = new ActionMacro(macro); ((ActionMacro) macro) .setAction(targetAction.getItems().isEmpty() ? null : targetAction.getItems().get(0).getId()); bank.add(macro); updateForMacro(macro, false); save(macro); } }); if (getDevice().getCapabilities().contains(Capability.PROFILE_LEDS)) { profileLEDHelper = new MacroBankLEDHelper(context.getMacroManager().getMacroSystem(), bank, profileLED); automatic.setSelected(profileLEDHelper.isAutomatic()); manual.setSelected(!profileLEDHelper.isAutomatic()); } else { automatic.setSelected(true); profileLED.setVisible(false); } macros.buildTree(); adjusting = true; try { updateForMacro(macro, false); } finally { adjusting = false; } updateAvailability(); } protected Callback<ListView<Application>, ListCell<Application>> createApplicationCellFactory( boolean showChooseText) { return (l) -> { return new ListCell<Application>() { @Override protected void updateItem(Application item, boolean empty) { super.updateItem(item, empty); if (item == null || empty) { setGraphic(null); if (showChooseText) setText(bundle.getString("chooseApplication")); else setText(""); } else { String icon = item.getIcon(); if (icon != null && icon.length() > 0) { setGraphic(getViewIcon(item)); } else { setGraphic(new FontIcon(FontAwesome.BARS)); } setText(item.getName()); } } }; }; } protected Callback<ListView<Window>, ListCell<Window>> createWindowCellFactory(boolean showChooseText) { return (l) -> { return new ListCell<uk.co.bithatch.macrolib.Window>() { @Override protected void updateItem(uk.co.bithatch.macrolib.Window item, boolean empty) { super.updateItem(item, empty); if (item == null || empty) { setGraphic(null); if (showChooseText) setText(bundle.getString("chooseWindow")); else setText(""); } else { String icon = item.getIcon(); if (icon != null && icon.length() > 0) { setGraphic(getViewIcon(item)); } else { setGraphic(new FontIcon(FontAwesome.WINDOW_MAXIMIZE)); } setText(item.getName()); } } }; }; } protected Node getViewIcon(View view) { try { String icon = view.getIcon(); String path; if (icon.contains("/")) { path = Paths.get(icon).toUri().toURL().toExternalForm(); } else { path = context.getMacroManager().getMacroSystem().getIconService().findIcon(icon, 24).toUri().toURL() .toExternalForm(); } if (path != null) { if (path.endsWith(".svg")) { try (InputStream in = new URL(path).openStream()) { return new SVGIcon(path, in, 22, 22); } } else { ImageView iv = new ImageView(path); iv.setFitHeight(22); iv.setFitWidth(22); return iv; } } } catch (IOException e) { } return new Label("?"); } protected void setTitle() { title.textProperty().set(MessageFormat.format(bundle.getString("title"), bank.getBank(), bank.getName(), bank.getProfile().getName())); } protected UInputMacro createDefaultMacro(KeySequence key) { UInputMacro ui = new UInputMacro(key, key.get(0)); return ui; } protected void updateForMacro(Macro macro, boolean unmapped) { macroKey.getSelectionModel().select(macro == null ? null : macro.getActivatedBy().get(0)); export.setVisible(true); if (unmapped) { unmappedSection.setVisible(true); newMacroSection.setVisible(false); sequenceEditor.setVisible(false); delete.setVisible(false); editor.visibleProperty().set(false); recordMacro.setVisible(false); } else if (macro == null) { unmappedSection.setVisible(false); newMacroSection.setVisible(true); sequenceEditor.setVisible(false); delete.setVisible(false); editor.visibleProperty().set(false); recordMacro.setVisible(false); } else { unmappedSection.setVisible(false); sequenceEditor.setVisible(true); delete.setVisible(true); editor.visibleProperty().set(true); recordMacro.setVisible(true); newMacroSection.setVisible(false); repeatDelay.textProperty().set(String.valueOf(macro.getRepeatDelay())); repeatMode.getSelectionModel().select(macro.getRepeatMode()); if (macro instanceof UInputMacro) { uinputMacro.selectedProperty().set(true); var uinputMacroObj = (UInputMacro) macro; keyCode.getSelectionModel().select(uinputMacroObj.getCode()); if (uinputMacroObj.isPassthrough()) targetType.getSelectionModel().select(TargetType.forEvent(macro.getActivatedBy().get(0))); else targetType.getSelectionModel().select(uinputMacroObj.getType()); passthrough.setSelected(uinputMacroObj.isPassthrough()); value.getValueFactory().setValue(uinputMacroObj.getValue()); } else if (macro instanceof NoopMacro) noopMacro.selectedProperty().set(true); else if (macro instanceof ScriptMacro) { scriptMacro.selectedProperty().set(true); var scriptMacroObj = (ScriptMacro) macro; script.textProperty() .set(scriptMacroObj.getScript() == null ? "" : String.join("\n", scriptMacroObj.getScript())); } else if (macro instanceof CommandMacro) { commandMacro.selectedProperty().set(true); var commandMacroObj = (CommandMacro) macro; commandLocation.textProperty().set(commandMacroObj.getCommand()); if (commandMacroObj.getArguments() == null || commandMacroObj.getArguments().length == 0) commandArgs.textProperty().set(""); else commandArgs.textProperty().set(String.join("\n", commandMacroObj.getArguments())); } else if (macro instanceof SimpleMacro) { simpleMacro.selectedProperty().set(true); var simpleMacroObj = (SimpleMacro) macro; simpleMacroText.textProperty().set(String.valueOf(simpleMacroObj.getMacro())); } else if (macro instanceof ActionMacro) { actionMacro.selectedProperty().set(true); var actionMacroObj = (ActionMacro) macro; targetAction.getSelectionModel().select(actionMacroObj.getAction() == null ? null : context.getMacroManager().getMacroSystem().getActions().get(actionMacroObj.getAction())); } else throw new UnsupportedOperationException("Unknown action type."); } } @FXML void evtAddWindow() { uk.co.bithatch.macrolib.Window sel = window.getSelectionModel().getSelectedItem(); if (sel != null) { if (windowsTabs.getSelectionModel().getSelectedIndex() == 0) { includeWindow.getItems().add(sel); } else { excludeWindow.getItems().add(sel); } } } @FXML void evtAddApplication() { Application sel = application.getSelectionModel().getSelectedItem(); if (sel != null) { if (applicationsTabs.getSelectionModel().getSelectedIndex() == 0) { includeApplication.getItems().add(sel); } else { excludeApplication.getItems().add(sel); } } } @FXML void evtRemoveWindow() { if (windowsTabs.getSelectionModel().getSelectedIndex() == 0) { includeWindow.getItems().remove(includeWindow.getSelectionModel().getSelectedItem()); } else { excludeWindow.getItems().remove(excludeWindow.getSelectionModel().getSelectedItem()); } } @FXML void evtRemoveApplication() { if (applicationsTabs.getSelectionModel().getSelectedIndex() == 0) { includeApplication.getItems().remove(includeApplication.getSelectionModel().getSelectedItem()); } else { excludeApplication.getItems().remove(excludeApplication.getSelectionModel().getSelectedItem()); } } @FXML void evtAdd() { add(bank.getNextFreeActivationSequence()); } protected void add(KeySequence seq) { try { adjusting = true; try { macro = createDefaultMacro(seq); bank.add(macro); macros.addSequence(macro); updateForMacro(macro, false); return; } finally { adjusting = false; } } catch (IllegalStateException e) { error("noKeysLeft"); } } @FXML void evtRecordMacro() { context.push(Record.class, Direction.FROM_LEFT); } @FXML void evtManual() { profileLEDHelper.setAutomatic(false); } @FXML void evtAutomatic() { profileLEDHelper.setAutomatic(true); } @FXML void evtDelete() { Confirm confirm = context.push(Confirm.class, Direction.FADE); confirm.confirm(bundle, "removeSequence", () -> { macro.remove(); try { macro.commit(); macros.deleteSelected(); updateForMacro(null, false); } catch (Exception e) { error(e); } }, null, macro.getDisplayName()); } @FXML void evtExport() { Export confirm = context.push(Export.class, Direction.FADE); // confirm.export(addOn, bundle, "exportMacroProfile", effect.getName()); // FileChooser fileChooser = new FileChooser(); // fileChooser.setTitle(bundle.getString("selectExportFile")); // var path = PREFS.get("lastExportLocation", System.getProperty("user.dir") + File.separator + "macros.json"); // fileChooser.getExtensionFilters().add(new ExtensionFilter(bundle.getString("macroFileExtension"), "*.json")); // fileChooser.getExtensionFilters().add(new ExtensionFilter(bundle.getString("allFiles"), "*.*")); // JavaFX.selectFilesDir(fileChooser, path); // File file = fileChooser.showSaveDialog((Stage) getScene().getWindow()); // if (file != null) { // PREFS.put("lastExportLocation", file.getAbsolutePath()); // try (PrintWriter pw = new PrintWriter(file)) { // pw.println(getDevice().exportMacros()); // } catch (IOException ioe) { // LOG.log(java.lang.System.Logger.Level.ERROR, "Failed to export macros.", ioe); // } // } } @FXML void evtImport() { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(bundle.getString("selectImportFile")); var path = PREFS.get("lastExportLocation", System.getProperty("user.dir") + File.separator + "macros.json"); fileChooser.getExtensionFilters().add(new ExtensionFilter(bundle.getString("macroFileExtension"), "*.json")); fileChooser.getExtensionFilters().add(new ExtensionFilter(bundle.getString("allFiles"), "*.*")); JavaFX.selectFilesDir(fileChooser, path); File file = fileChooser.showOpenDialog((Stage) getScene().getWindow()); if (file != null) { PREFS.put("lastExportLocation", file.getAbsolutePath()); try { getDevice().importMacros(String.join(" ", Files.readAllLines(file.toPath()))); macros.buildTree(); } catch (IOException ioe) { LOG.log(java.lang.System.Logger.Level.ERROR, "Failed to export macros.", ioe); } } } @FXML void evtCommandBrowse() { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(bundle.getString("selectExecutable")); var path = commandLocation.textProperty().get(); if (path == null || path.equals("")) path = System.getProperty("user.dir"); JavaFX.selectFilesDir(fileChooser, path); File file = fileChooser.showOpenDialog((Stage) getScene().getWindow()); if (file != null) { commandLocation.textProperty().set(file.getPath()); ((CommandMacro) macro).setCommand(commandLocation.textProperty().get()); save(macro); } } private void save(Macro mkey) { try { error((String) null); context.getMacroManager().validate(mkey); if (task != null) { task.cancel(false); } task = executor.schedule(() -> { if (!bank.getMacros().contains(mkey)) { bank.add(mkey); } try { bank.commit(); } catch (Exception e) { error(e); } }, 1000, TimeUnit.MILLISECONDS); } catch (ValidationException ve) { error(ve.getMessage()); } } private void saveProfile() { error((String) null); if (task != null) { task.cancel(false); } task = executor.schedule(() -> { try { bank.getProfile().commit(); } catch (Exception e) { error(e); } }, 1000, TimeUnit.MILLISECONDS); } private void saveBank() { error((String) null); if (task != null) { task.cancel(false); } task = executor.schedule(() -> { try { bank.commit(); } catch (Exception e) { error(e); } }, 1000, TimeUnit.MILLISECONDS); } Macro getMacroForKey(EventCode eventCode) { return bank.getMacro(new KeySequence(eventCode)); } interface MacrosView { void setContextMenu(ContextMenu contextMenu); void refresh(); Node getNode(); void deleteSelected(); void addSequence(Macro seq); void buildTree(); MultipleSelectionModel<KeySequence> getSequenceSelectionModel(); } private void updateAvailability() { Application asel; if (applicationsTabs.getSelectionModel().getSelectedIndex() == 0) { asel = includeApplication.getSelectionModel().getSelectedItem(); } else { asel = excludeApplication.getSelectionModel().getSelectedItem(); } uk.co.bithatch.macrolib.Window wsel; if (windowsTabs.getSelectionModel().getSelectedIndex() == 0) { wsel = includeWindow.getSelectionModel().getSelectedItem(); } else { wsel = excludeWindow.getSelectionModel().getSelectedItem(); } removeApplication.setDisable(asel == null); removeWindow.setDisable(wsel == null); } class LayoutMacrosView extends StackPane implements MacrosView, Viewer { MacroBank bank; SimpleBooleanProperty selectable = new SimpleBooleanProperty(true); SimpleBooleanProperty readOnly = new SimpleBooleanProperty(true); LayoutEditor layoutEditor; ListMultipleSelectionModel<KeySequence> sequenceSelectionModel; KeySequence lastSequence; LayoutMacrosView(MacroBank map, DeviceView view, App context) { super(); this.bank = map; layoutEditor = new LayoutEditor(context); layoutEditor.getStyleClass().add("padded"); layoutEditor.setShowElementGraphics(false); layoutEditor.setComponentType(ComponentType.AREA); layoutEditor.open(context.getMacroManager().getNativeDevice(map.getProfile().getDevice()), view, this); getChildren().add(layoutEditor); sequenceSelectionModel = new ListMultipleSelectionModel<>(new BasicList<>()); sequenceSelectionModel.setSelectionMode(SelectionMode.SINGLE); layoutEditor.getElementSelectionModel().setSelectionMode(SelectionMode.SINGLE); layoutEditor.getElementSelectionModel().selectedIndexProperty().addListener((e, oldVal, newVal) -> { checkSelectionChange(); }); } @Override public void setContextMenu(ContextMenu contextMenu) { layoutEditor.setMenuCallback((tool, evt) -> { contextMenu.show(tool, Side.BOTTOM, 0, 0); }); } protected void checkSelectionChange() { int idx = layoutEditor.getElementSelectionModel().getSelectedIndex(); IO item = idx == -1 ? null : layoutEditor.getElements().get(idx); Key key = (Key) item; KeySequence seq = null; if (key != null) { if (key.getEventCode() == null) { /* * The key exists, but is not mapped to anything (e.g. an un-mappable DPI switch * button) */ seq = new KeySequence(); } else /* An actual sequence */ seq = new KeySequence(key.getEventCode()); } if (!Objects.equals(seq, lastSequence)) { lastSequence = seq; if (lastSequence == null) sequenceSelectionModel.clearSelection(); else sequenceSelectionModel.select(lastSequence); } } @Override public void addListener(ViewerListener listener) { } @Override public void removeListener(ViewerListener listener) { } @Override public void removeSelectedElements() { } @Override public List<ComponentType> getEnabledTypes() { return Arrays.asList(ComponentType.KEY); } @Override public SimpleBooleanProperty selectableElements() { return selectable; } @Override public SimpleBooleanProperty readOnly() { return readOnly; } @Override public void deleteSelected() { lastSequence = null; layoutEditor.getElementSelectionModel().clearSelection(); } @Override public void addSequence(Macro seq) { layoutEditor.refresh(); } @Override public void buildTree() { } @Override public MultipleSelectionModel<KeySequence> getSequenceSelectionModel() { return sequenceSelectionModel; } @Override public Node getNode() { return this; } @Override public void setEnabledTypes(List<ComponentType> enabledTypes) { } @Override public void refresh() { } } class ListMacrosView extends ListView<KeySequence> implements MacrosView { MacroBank bank; App context; private MultipleSelectionModel<KeySequence> sequenceSelectionModel; private KeySequence lastSequence; ListMacrosView(MacroBank map, App context) { this.bank = map; this.context = context; getStyleClass().add("transparentBackground"); setCellFactory((list) -> { return new MacroListCell(); }); getSelectionModel().setSelectionMode(SelectionMode.SINGLE); sequenceSelectionModel = new ListMultipleSelectionModel<>(new BasicList<>()); sequenceSelectionModel.setSelectionMode(SelectionMode.SINGLE); getSelectionModel().selectedItemProperty().addListener((a) -> { checkSelectionChange(); }); } protected void checkSelectionChange() { KeySequence seqItem = getSelectionModel().getSelectedItem(); if (!Objects.equals(seqItem, lastSequence)) { lastSequence = seqItem; sequenceSelectionModel.select(lastSequence); } } public void buildTree() { getItems().clear(); for (Macro macro : bank.getMacros()) { getItems().add(macro.getActivatedBy()); } } @Override public MultipleSelectionModel<KeySequence> getSequenceSelectionModel() { return sequenceSelectionModel; } @Override public void addSequence(Macro macro) { getItems().add(macro.getActivatedBy()); getSelectionModel().select(macro.getActivatedBy()); requestFocus(); } @Override public void deleteSelected() { lastSequence = null; getSelectionModel().clearSelection(); buildTree(); } @Override public Node getNode() { return this; } } }
41,126
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
ControlController.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/ControlController.java
package uk.co.bithatch.snake.ui; public abstract class ControlController extends AbstractDeviceController { @Override protected final void onSetDevice() throws Exception { getScene().getRoot().getStyleClass().add(getControlClassName()); getScene().getRoot().getStyleClass().add(getControlClassName() + "-" + getClass().getSimpleName().toLowerCase()); onSetControlDevice(); } protected String getControlClassName() { return "control"; } protected void onSetControlDevice() throws Exception { } }
515
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
DynamicClassLoader.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/DynamicClassLoader.java
/* * Copyright 2018 Mordechai Meisels * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package uk.co.bithatch.snake.ui; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Paths; public final class DynamicClassLoader extends URLClassLoader { static { registerAsParallelCapable(); } public DynamicClassLoader(String name, ClassLoader parent) { super(name, new URL[0], parent); } /* * Required when this classloader is used as the system classloader */ public DynamicClassLoader(ClassLoader parent) { this("classpath", parent); } public DynamicClassLoader() { this(Thread.currentThread().getContextClassLoader()); } public void add(URL url) { addURL(url); } public static DynamicClassLoader findAncestor(ClassLoader cl) { do { if (cl instanceof DynamicClassLoader) return (DynamicClassLoader) cl; cl = cl.getParent(); } while (cl != null); return null; } /* * Required for Java Agents when this classloader is used as the system classloader */ @SuppressWarnings("unused") private void appendToClassPathForInstrumentation(String jarfile) throws IOException { add(Paths.get(jarfile).toRealPath().toUri().toURL()); } }
1,895
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Error.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/Error.java
package uk.co.bithatch.snake.ui; import java.text.MessageFormat; import java.util.ResourceBundle; import java.util.prefs.PreferenceChangeEvent; import java.util.prefs.PreferenceChangeListener; import javafx.animation.FadeTransition; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import javafx.util.Duration; import uk.co.bithatch.snake.lib.BackendException; import uk.co.bithatch.snake.widgets.Direction; public class Error extends AbstractDeviceController implements PreferenceChangeListener { final static ResourceBundle bundle = ResourceBundle.getBundle(Error.class.getName()); @FXML private Label errorTitle; @FXML private Label error; @FXML private Label errorDescription; @FXML private HBox decoratedTools; @Override protected void onConfigure() throws Exception { decoratedTools.visibleProperty().set(context.getConfiguration().isDecorated()); context.getConfiguration().getNode().addPreferenceChangeListener(this); } @FXML void evtRetry() { try { context.push(Overview.class, Direction.FROM_BOTTOM); context.remove(this); } catch (Exception e) { setError(e); FadeTransition anim = new FadeTransition(Duration.seconds(1)); anim.setAutoReverse(true); anim.setCycleCount(1); anim.setNode(error); anim.setFromValue(0.5); anim.setToValue(1); anim.play(); } } @Override protected void onDeviceCleanUp() { context.getConfiguration().getNode().removePreferenceChangeListener(this); } public void setError(Throwable e) { Throwable rootCause = null; while (e != null) { rootCause = e; if (rootCause instanceof BackendException) { errorTitle.textProperty().set(bundle.getString("noBackend")); errorDescription.textProperty().set(bundle.getString("noBackend.description")); return; } e = e.getCause(); } errorTitle.textProperty().set(bundle.getString("other")); errorDescription.textProperty() .set(MessageFormat.format(bundle.getString("other.description"), rootCause.getLocalizedMessage())); } @FXML void evtAbout() { context.push(About.class, Direction.FADE); } @FXML void evtOptions() { context.push(Options.class, Direction.FROM_BOTTOM); } @Override public void preferenceChange(PreferenceChangeEvent evt) { if (evt.getKey().equals(Configuration.PREF_DECORATED)) { decoratedTools.visibleProperty().set(context.getConfiguration().isDecorated()); } } }
2,433
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
DesktopNotifications.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/DesktopNotifications.java
package uk.co.bithatch.snake.ui; import java.text.MessageFormat; import java.util.ResourceBundle; import com.sshtools.twoslices.Toast; import com.sshtools.twoslices.ToastType; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.lib.Device.Listener; import uk.co.bithatch.snake.lib.Region; import uk.co.bithatch.snake.lib.binding.Profile; import uk.co.bithatch.snake.lib.binding.ProfileMap; public class DesktopNotifications implements Listener { final static ResourceBundle bundle = ResourceBundle.getBundle(DesktopNotifications.class.getName()); private App context; public DesktopNotifications(App context) throws Exception { this.context = context; for (Device d : context.getBackend().getDevices()) { d.addListener(this); } } @Override public void changed(Device device, Region region) { } @Override public void activeMapChanged(ProfileMap map) { String cpath = context.getCache() .getCachedImage(context.getDefaultImage(map.getProfile().getDevice().getType(), map.getProfile().getDevice().getImage())); if(cpath.startsWith("file:")) cpath = cpath.substring(5); Toast.toast(ToastType.INFO, cpath, MessageFormat.format(bundle.getString("profileMapChange.title"), map.getProfile().getName(), map.getId()), MessageFormat.format(bundle.getString("profileMapChange"), map.getProfile().getName(), map.getId())); } @Override public void profileAdded(Profile profile) { } @Override public void profileRemoved(Profile profile) { } @Override public void mapAdded(ProfileMap profile) { } @Override public void mapChanged(ProfileMap profile) { } @Override public void mapRemoved(ProfileMap profile) { } }
1,698
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
LayoutDesigner.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/LayoutDesigner.java
package uk.co.bithatch.snake.ui; import java.io.File; import java.net.URISyntaxException; import java.net.URL; import java.text.MessageFormat; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.ResourceBundle; import java.util.Set; import org.controlsfx.control.SearchableComboBox; import org.controlsfx.control.ToggleSwitch; import org.kordamp.ikonli.fontawesome.FontAwesome; import org.kordamp.ikonli.javafx.FontIcon; import javafx.application.Platform; import javafx.beans.binding.Bindings; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.control.RadioButton; import javafx.scene.control.SelectionMode; import javafx.scene.control.Slider; import javafx.scene.control.Spinner; import javafx.scene.control.SpinnerValueFactory; import javafx.scene.control.TabPane; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.ToggleGroup; import javafx.scene.control.Tooltip; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.stage.FileChooser; import javafx.stage.FileChooser.ExtensionFilter; import javafx.util.Callback; import javafx.util.Duration; import uk.co.bithatch.linuxio.EventCode; import uk.co.bithatch.snake.lib.BrandingImage; import uk.co.bithatch.snake.lib.Capability; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.lib.Lit; import uk.co.bithatch.snake.lib.Region; import uk.co.bithatch.snake.lib.effects.Off; import uk.co.bithatch.snake.lib.layouts.Accessory; import uk.co.bithatch.snake.lib.layouts.Accessory.AccessoryType; import uk.co.bithatch.snake.lib.layouts.Area; import uk.co.bithatch.snake.lib.layouts.Cell; import uk.co.bithatch.snake.lib.layouts.ComponentType; import uk.co.bithatch.snake.lib.layouts.DeviceLayout; import uk.co.bithatch.snake.lib.layouts.DeviceLayouts; import uk.co.bithatch.snake.lib.layouts.DeviceLayouts.Listener; import uk.co.bithatch.snake.lib.layouts.DeviceView; import uk.co.bithatch.snake.lib.layouts.IO; import uk.co.bithatch.snake.lib.layouts.Key; import uk.co.bithatch.snake.lib.layouts.MatrixCell; import uk.co.bithatch.snake.lib.layouts.MatrixIO; import uk.co.bithatch.snake.lib.layouts.RegionIO; import uk.co.bithatch.snake.lib.layouts.ViewPosition; import uk.co.bithatch.snake.ui.addons.Layout; import uk.co.bithatch.snake.ui.designer.TabbedViewer; import uk.co.bithatch.snake.ui.designer.Viewer.ViewerListener; import uk.co.bithatch.snake.ui.designer.ViewerView; import uk.co.bithatch.snake.ui.effects.BlinkEffectHandler; import uk.co.bithatch.snake.ui.effects.EffectAcquisition; import uk.co.bithatch.snake.ui.util.Strings; import uk.co.bithatch.snake.ui.util.Time.Timer; import uk.co.bithatch.snake.ui.util.Visitor; import uk.co.bithatch.snake.widgets.Direction; import uk.co.bithatch.snake.widgets.JavaFX; public class LayoutDesigner extends AbstractDetailsController implements Listener, ViewerListener { final static ResourceBundle bundle = ResourceBundle.getBundle(LayoutDesigner.class.getName()); private static final String PREF_LAST_IMAGE_BROWSE_LOCATION = "lastImageBrowseLocation"; private EffectAcquisition acq; @FXML private Hyperlink addView; @FXML private RadioButton autoImage; @FXML private Hyperlink browseImage; @FXML private CheckBox desaturate; @FXML private ToggleSwitch enabled; @FXML private Hyperlink export; @FXML private RadioButton fileImage; @FXML private Slider imageScale; @FXML private ToggleGroup imageSource; @FXML private TextField imageUri; @FXML private TextArea label; @FXML private Spinner<Integer> matrixX; @FXML private Label matrixXLabel; @FXML private Spinner<Integer> matrixY; @FXML private Label matrixYLabel; @FXML private Label labelLabel; @FXML private Slider opacity; @FXML private ComboBox<ViewPosition> position; @FXML private ComboBox<AccessoryType> accessory; @FXML private Label positionLabel; @FXML private Label regionLabel; @FXML private Label keyMappingLabel; @FXML private Label legacyKeyMappingLabel; @FXML private Label accessoryLabel; @FXML private Label matrixLabel; @FXML private Label noSelection; @FXML private ComboBox<Region.Name> region; @FXML private Hyperlink removeElement; @FXML private Hyperlink remove; @FXML private TabPane sideBar; @FXML private StackPane stack; @FXML private HBox toolBar; @FXML private RadioButton urlImage; @FXML private Spinner<Integer> width; @FXML private Label widthLabel; @FXML private SearchableComboBox<EventCode> keyMapping; @FXML private SearchableComboBox<uk.co.bithatch.snake.lib.Key> legacyKeyMapping; private DeviceLayout layout; private boolean adjusting; private Timer backgroundChangeTimer = new Timer(Duration.millis(750), (ae) -> { changeBackgroundImage(); updateBackgroundImageComponents(); }); private BlinkEffectHandler blink; private TabbedViewer deviceViewer; @Override public void layoutAdded(DeviceLayout layout) { Platform.runLater(() -> { if (layout.getName().equals(getDevice().getName())) { this.layout = layout; deviceViewer.setLayout(layout); deviceViewer.refresh(); updateTemplateStatus(); } }); } @Override public void layoutChanged(DeviceLayout layout) { Platform.runLater(() -> { configureForView(); deviceViewer.refresh(); }); } @Override public void layoutRemoved(DeviceLayout layout) { Platform.runLater(() -> { if (deviceViewer.getLayout().equals(layout)) { deviceViewer.setLayout(null); LayoutDesigner.this.layout = null; deviceViewer.refresh(); updateTemplateStatus(); } }); } @Override public void viewAdded(DeviceLayout layout, DeviceView view) { viewChanged(layout, view); } @Override public void viewChanged(DeviceLayout layout, DeviceView view) { if (Platform.isFxApplicationThread()) configureForView(); else Platform.runLater(() -> viewAdded(layout, view)); } @Override public void viewRemoved(DeviceLayout layout, DeviceView view) { viewChanged(layout, view); } @Override protected void onDeviceCleanUp() { context.getLayouts().removeListener(this); deviceViewer.removeListener(this); deviceViewer.cleanUp(); if (acq != null) { try { acq.close(); } catch (Exception e) { e.printStackTrace(); } } } public void setLayout(DeviceLayout layout) throws Exception { this.layout = layout; JavaFX.bindManagedToVisible(enabled, width, widthLabel, toolBar, sideBar, removeElement, matrixX, matrixY, matrixXLabel, matrixYLabel, position, positionLabel, region, regionLabel, legacyKeyMapping, legacyKeyMappingLabel, keyMapping, keyMappingLabel, accessory, accessoryLabel, labelLabel, label, matrixLabel, noSelection); matrixXLabel.labelForProperty().set(matrixX); matrixYLabel.labelForProperty().set(matrixY); positionLabel.labelForProperty().set(position); sideBar.visibleProperty().bind(toolBar.visibleProperty()); matrixXLabel.visibleProperty().bind(matrixX.visibleProperty()); matrixYLabel.visibleProperty().bind(matrixY.visibleProperty()); widthLabel.visibleProperty().bind(width.visibleProperty()); positionLabel.visibleProperty().bind(position.visibleProperty()); regionLabel.visibleProperty().bind(region.visibleProperty()); accessoryLabel.visibleProperty().bind(accessory.visibleProperty()); labelLabel.visibleProperty().bind(label.visibleProperty()); keyMappingLabel.visibleProperty().bind(keyMapping.visibleProperty()); legacyKeyMappingLabel.visibleProperty().bind(legacyKeyMapping.visibleProperty()); matrixLabel.visibleProperty().bind(Bindings.or(matrixX.visibleProperty(), Bindings .or(Bindings.or(keyMapping.visibleProperty(), matrixY.visibleProperty()), matrixY.visibleProperty()))); Callback<ListView<Region.Name>, ListCell<Region.Name>> factory = new Callback<ListView<Region.Name>, ListCell<Region.Name>>() { @Override public ListCell<Region.Name> call(ListView<Region.Name> l) { return new ListCell<Region.Name>() { @Override protected void updateItem(Region.Name item, boolean empty) { super.updateItem(item, empty); String imageUrl; if (item == null || empty) { imageUrl = context.getConfiguration().getTheme().getEffectImage(24, Off.class) .toExternalForm(); setText(bundle.getString("noRegion")); } else { imageUrl = context.getConfiguration().getTheme().getRegionImage(24, item).toExternalForm(); setText(bundle.getString("region." + item.name())); } ImageView iv = new ImageView(imageUrl); iv.setFitHeight(22); iv.setFitWidth(22); iv.setSmooth(true); iv.setPreserveRatio(true); iv.getStyleClass().add("cell"); setGraphic(iv); } }; } }; region.setCellFactory(factory); region.setButtonCell(factory.call(null)); Device device = getDevice(); deviceViewer = new TabbedViewer(context, device); stack.getChildren().add(deviceViewer); deviceViewer.setSelectionMode(SelectionMode.MULTIPLE); if (layout.getViews().get(ViewPosition.MATRIX) == null && device.getCapabilities().contains(Capability.MATRIX)) { layout.addView(DeviceLayouts.createMatrixView(device)); } width.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 1024, 0, 10)); deviceViewer.setLayout(layout); configureForView(); updateTemplateStatus(); accessory.getItems().addAll(Accessory.AccessoryType.values()); keyMapping.getItems().add(null); keyMapping.getItems().addAll(device.getSupportedInputEvents()); legacyKeyMapping.getItems().add(null); legacyKeyMapping.getItems().addAll(device.getSupportedLegacyKeys()); /* Setup listeners */ imageSource.selectedToggleProperty().addListener((e, o, n) -> { if (!adjusting) backgroundChangeTimer.reset(); }); imageUri.textProperty().addListener((e, o, n) -> { if (!adjusting) backgroundChangeTimer.reset(); }); imageScale.valueProperty().addListener((e, o, n) -> { if (!adjusting) deviceViewer.getSelectedView().setImageScale((float) (imageScale.valueProperty().get() / 100.0)); }); opacity.valueProperty().addListener((e, o, n) -> { if (!adjusting) deviceViewer.getSelectedView().setImageOpacity((float) (opacity.valueProperty().get() / 100.0)); }); desaturate.selectedProperty().addListener((e, o, n) -> { if (!adjusting) deviceViewer.getSelectedView().setDesaturateImage(desaturate.isSelected()); }); position.getSelectionModel().selectedItemProperty().addListener((e, oldVal, newVal) -> { if (!adjusting) { deviceViewer.getSelectedView().setPosition(position.getSelectionModel().getSelectedItem()); backgroundChangeTimer.reset(); } }); enabled.selectedProperty().addListener((e, o, n) -> { if (!adjusting) { for (IO el : deviceViewer.getSelectedElements()) { if (el instanceof MatrixCell) ((MatrixCell) el).setDisabled(!n); } } }); width.valueProperty().addListener((e, o, n) -> { if (!adjusting) { if (o == 0 && n != 0) { width.getValueFactory().setValue(178); } else { for (IO el : deviceViewer.getSelectedElements()) { if (el instanceof MatrixCell) ((MatrixCell) el).setWidth(n); } } } }); label.textProperty().addListener((e, o, n) -> { if (!adjusting) { IO el = deviceViewer.getSelectedElement(); if (el != null) { el.setLabel(n.equals("") ? null : n); } } }); matrixX.valueProperty().addListener((e, oldVal, newVal) -> { if (!adjusting) { List<IO> selectedElements = deviceViewer.getSelectedElements(); if (!selectedElements.isEmpty()) { Integer mx = matrixX.getValue(); for (IO el : selectedElements) { if (el instanceof MatrixIO) { MatrixIO m = (MatrixIO) el; m.setMatrixX(mx); MatrixCell cell = (MatrixCell) layout.getViews().get(ViewPosition.MATRIX) .getElement(ComponentType.MATRIX_CELL, m.getMatrixX(), m.getMatrixY()); if (cell != null) { cell.setMatrixX(mx); } } } } } }); matrixY.valueProperty().addListener((e, oldVal, newVal) -> { if (!adjusting) { List<IO> selectedElements = deviceViewer.getSelectedElements(); if (!selectedElements.isEmpty()) { Integer my = matrixY.getValue(); for (IO el : selectedElements) { if (el instanceof MatrixIO) { MatrixIO m = (MatrixIO) el; m.setMatrixY(my); MatrixCell cell = (MatrixCell) layout.getViews().get(ViewPosition.MATRIX) .getElement(ComponentType.MATRIX_CELL, m.getMatrixX(), m.getMatrixY()); if (cell != null) { cell.setMatrixY(my); } } } } } }); keyMapping.getSelectionModel().selectedItemProperty().addListener((e, oldVal, newVal) -> { if (!adjusting) { IO selectedElement = deviceViewer.getSelectedElement(); if (selectedElement != null) { if (selectedElement instanceof Key) { Key m = (Key) selectedElement; m.setEventCode(newVal); } } } }); legacyKeyMapping.getSelectionModel().selectedItemProperty().addListener((e, oldVal, newVal) -> { if (!adjusting) { IO selectedElement = deviceViewer.getSelectedElement(); if (selectedElement != null) { if (selectedElement instanceof Key) { Key m = (Key) selectedElement; m.setLegacyKey(newVal); } } } }); deviceViewer.getSelectionModel().selectedIndexProperty().addListener((c, o, n) -> { configureForView(); updateAvailability(); }); deviceViewer.getKeySelectionModel().selectedIndexProperty().addListener((e, oldVal, newVal) -> { configureForView(); }); region.getSelectionModel().selectedItemProperty().addListener((e, oldVal, newVal) -> { if (!adjusting) { List<IO> selectedElements = deviceViewer.getSelectedElements(); if (!selectedElements.isEmpty()) { for (IO el : selectedElements) { if (el instanceof RegionIO) { /* For element types that actually have a region, set it directly */ ((RegionIO) el).setRegion(newVal); } else if (el instanceof MatrixIO) { /* * For element types that are associated with matrix cells, set the region on * that matrix cell element it is associated with. */ MatrixIO m = (MatrixIO) el; MatrixCell cell = m.isMatrixLED() ? (MatrixCell) layout.getViews().get(ViewPosition.MATRIX) .getElement(ComponentType.MATRIX_CELL, m.getMatrixX(), m.getMatrixY()) : null; if (cell != null) { cell.setRegion(newVal); } if (newVal == null) m.setMatrixXY(null); } } } } }); context.getLayouts().addListener(this); deviceViewer.addListener(this); /* * If this is a Matrix device, acquire effects control on the device. This will * shutdown the current effect. We then highlight individual LED lights as they * are selected */ if (device.getCapabilities().contains(Capability.MATRIX)) { acq = context.getEffectManager().acquire(device); blink = new BlinkEffectHandler() { @Override public void update(Lit component) { super.update(component); deviceViewer.updateFromMatrix(getEffect().getCells()); } }; blink.open(context, device); acq.activate(device, blink); } } void visitRelatedCells(MatrixIO mio, Visitor<MatrixIO> visit) { for (Map.Entry<ViewPosition, DeviceView> en : deviceViewer.getLayout().getViews().entrySet()) { if (en.getValue() != deviceViewer.getSelectedView()) { for (IO otherEl : en.getValue().getElements()) { if (otherEl instanceof MatrixIO) { MatrixIO otherMio = (MatrixIO) otherEl; if (mio.getMatrixX() == otherMio.getMatrixX() && mio.getMatrixY() == otherMio.getMatrixY()) { visit.visit(otherMio); } } } } } } void addView(ViewPosition viewPosition) { DeviceView view = new DeviceView(); view.setPosition(viewPosition); deviceViewer.getLayout().addView(view); deviceViewer.addView(view); deviceViewer.selectView(view); updateAvailability(); } void changeBackgroundImage() { String uri = imageUri.textProperty().get(); if (autoImage.selectedProperty().get()) uri = null; else { if (uri == null || uri.equals("")) { BrandingImage bimg = deviceViewer.getSelectedView().getPosition().toBrandingImage(); if (bimg != null) { if (fileImage.selectedProperty().get()) uri = context.getCache().getCachedImage(getDevice().getImageUrl(bimg)); else uri = getDevice().getImageUrl(bimg); } } else { URL url = null; try { url = new URL(uri); } catch (Exception e) { } if (url != null) { if (fileImage.selectedProperty().get() && (url.getProtocol().equals("http") || url.getProtocol().equals("https"))) { imageUri.textProperty().set(""); uri = null; } else if (urlImage.selectedProperty().get() && url.getProtocol().equals("file")) { imageUri.textProperty().set(""); uri = null; } } } } imageUri.setTooltip(new Tooltip(uri)); deviceViewer.getSelectedView().setImageUri(uri); deviceViewer.refresh(); } void configureForView() { adjusting = true; DeviceView view = deviceViewer.getSelectedView(); try { position.getItems().clear(); if (view != null) { DeviceLayout deviceLayout = view.getLayout(); matrixX.setValueFactory( new SpinnerValueFactory.IntegerSpinnerValueFactory(0, deviceLayout.getMatrixWidth(), 1, 1)); matrixY.setValueFactory( new SpinnerValueFactory.IntegerSpinnerValueFactory(0, deviceLayout.getMatrixHeight(), 1, 1)); ViewPosition selectedPosition = view.getPosition(); position.getItems().add(selectedPosition); // XX // XX Here! Got a progblem when removing a view.addElement(The POSITION list doesnt change); // XX for (ViewPosition viewPosition : ViewPosition.values()) { if (viewPosition != ViewPosition.MATRIX && viewPosition != selectedPosition && !deviceLayout.getViews().containsKey(viewPosition)) { position.getItems().add(viewPosition); } } position.selectionModelProperty().get().select(selectedPosition); imageScale.valueProperty().set(view.getImageScale() * 100.0); opacity.valueProperty().set(view.getImageOpacity() * 100.0); desaturate.selectedProperty().set(view.isDesaturateImage()); List<IO> elements = deviceViewer.getSelectedElements(); boolean viewingMatrix = deviceViewer.getSelectedView().getPosition().equals(ViewPosition.MATRIX); region.getItems().clear(); region.getItems().addAll(getDevice().getRegionNames()); Region.Name selectedRegion = null; int cells = 0; int areas = 0; int matrixEls = 0; int noLighting = 0; int keys = 0; int accessories = 0; for (IO el : elements) { if (el instanceof MatrixIO) { matrixEls++; if (!((MatrixIO) el).isMatrixLED()) noLighting++; else { MatrixCell cell = ((MatrixIO) el).getMatrixCell(); if (cell != null) selectedRegion = cell.getRegion(); } region.getSelectionModel().select(selectedRegion); } if (el instanceof MatrixCell) cells++; if (el instanceof Area) areas++; if (el instanceof Key) keys++; if (el instanceof Accessory) { noLighting++; accessories++; } if (el instanceof RegionIO && selectedRegion == null) selectedRegion = ((RegionIO) el).getRegion(); } matrixX.setVisible(noLighting == 0 && deviceLayout.getMatrixWidth() > 1 && matrixEls == elements.size() && matrixEls > 0); matrixY.setVisible(noLighting == 0 && deviceLayout.getMatrixHeight() > 1 && matrixEls == elements.size() && matrixEls > 0); position.setVisible(!viewingMatrix); noSelection.textProperty().set(bundle.getString(viewingMatrix ? "noMatrixSelection" : "noSelection")); if (areas > 0 || keys > 0) { region.getItems().add(null); } if (elements.size() == 1) { IO element = elements.get(0); if (!Objects.equals(element.getLabel(), label.textProperty().get())) label.textProperty().set(element.getLabel()); region.setDisable(false); region.setVisible(accessories == 0 && (areas > 0 || getDevice().getCapabilities().contains(Capability.MATRIX))); removeElement.setVisible(false); enabled.setVisible(viewingMatrix); width.setVisible(viewingMatrix); label.promptTextProperty().set(element.getDefaultLabel()); /* * When dealing with an area or a matrix cell, the region is as specified in the * element itself. */ if (element instanceof RegionIO) { accessory.setVisible(false); accessory.setDisable(true); } else { /* * Otherwise it is either the override region (if there is one), or the region * the associated matix cell is in. */ if (element instanceof MatrixIO) { accessory.setVisible(false); accessory.setDisable(true); MatrixCell cell = ((MatrixIO) element).getMatrixCell(); if (cell != null) selectedRegion = cell.getRegion(); } else if (element instanceof Accessory) { accessory.setVisible(true); accessory.setDisable(false); } } if (element instanceof Key) { keyMapping.getSelectionModel().select(((Key) element).getEventCode()); legacyKeyMapping.getSelectionModel().select(((Key) element).getLegacyKey()); } else { keyMapping.getSelectionModel().clearSelection(); legacyKeyMapping.getSelectionModel().clearSelection(); } if (element instanceof MatrixIO && getDevice().getCapabilities().contains(Capability.MATRIX)) { MatrixIO m = (MatrixIO) element; matrixX.setDisable(viewingMatrix || !m.isMatrixLED()); matrixY.setDisable(viewingMatrix || !m.isMatrixLED()); matrixX.getValueFactory().setValue(m.getMatrixX()); matrixY.getValueFactory().setValue(m.getMatrixY()); if (blink != null) blink.highlight(getDevice(), m.getMatrixX(), m.getMatrixY()); } else { matrixX.setDisable(true); matrixY.setDisable(true); } enabled.selectedProperty() .set(!(element instanceof MatrixCell) || !((MatrixCell) element).isDisabled()); width.getValueFactory() .setValue(!(element instanceof MatrixCell) ? 0 : ((MatrixCell) element).getWidth()); enabled.setDisable(!viewingMatrix); width.setDisable(!viewingMatrix); keyMapping.setVisible(element instanceof Key); legacyKeyMapping.setVisible(element instanceof Key); label.setVisible(true); noSelection.setVisible(false); } else if (elements.isEmpty()) { if (blink != null) blink.clear(getDevice()); matrixX.setDisable(true); matrixY.setDisable(true); region.setDisable(true); region.setVisible(false); label.setVisible(false); enabled.setDisable(true); enabled.setVisible(false); label.promptTextProperty().set(""); width.setVisible(false); width.setDisable(true); keyMapping.setVisible(false); legacyKeyMapping.setVisible(false); accessory.setVisible(false); accessory.setDisable(true); noSelection.setVisible(true); } else { label.setVisible(true); region.setDisable(false); noSelection.setVisible(false); accessory.setDisable(true); boolean noMatrix = matrixEls != elements.size() || !getDevice().getCapabilities().contains(Capability.MATRIX); matrixX.setDisable(viewingMatrix || noMatrix || noLighting > 0); matrixY.setDisable(viewingMatrix || noMatrix || noLighting > 0); enabled.setVisible(viewingMatrix && cells == elements.size()); label.setVisible(false); width.setVisible(viewingMatrix && cells == elements.size()); region.setVisible(accessories == 0 && (areas == elements.size() || getDevice().getCapabilities().contains(Capability.MATRIX))); enabled.setDisable(cells != elements.size()); width.setDisable(cells != elements.size()); keyMapping.setVisible(false); legacyKeyMapping.setVisible(false); accessory.setVisible(false); } region.getSelectionModel().select(selectedRegion); label.setDisable(elements.size() != 1); removeElement.setVisible(!elements.isEmpty() && !viewingMatrix); if (blink != null && elements.size() > 0) { Set<Cell> highlightCells = new HashSet<>(); DeviceView matrixView = deviceLayout.getViews().get(ViewPosition.MATRIX); for (IO element : elements) { if (element instanceof MatrixIO && ((MatrixIO) element).isMatrixLED()) highlightCells.add(((MatrixIO) element).getMatrixXY()); else if (element instanceof Area) { /* Add all of the cells in this area to highlight */ Region.Name region = ((Area) element).getRegion(); for (IO mel : matrixView.getElements()) { MatrixCell mcell = (MatrixCell) mel; if (Objects.equals(region, mcell.getRegion())) { highlightCells.add(mcell.getMatrixXY()); } } } } blink.highlight(getDevice(), highlightCells.toArray(new Cell[0])); } updateBackgroundImageComponents(); updateAvailability(); } } finally { adjusting = false; } } @FXML void evtAddView() { /* Find the next free view slot */ for (ViewPosition viewPosition : ViewPosition.values()) { if (viewPosition != ViewPosition.MATRIX && !deviceViewer.getLayout().getViews().containsKey(viewPosition)) { addView(viewPosition); return; } } } @FXML void evtBrowseImage() { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(bundle.getString("browseImage.selectImageFile")); var path = Strings.defaultIfBlank(imageUri.textProperty().get(), getDefaultOutputLocation()); fileChooser.getExtensionFilters().add(new ExtensionFilter(bundle.getString("browseImage.imageFileExtensions"), "*.png", "*.jpeg", "*.jpg", "*.gif")); fileChooser.getExtensionFilters().add(new ExtensionFilter(bundle.getString("browseImage.allFiles"), "*.*")); JavaFX.selectFilesDir(fileChooser, path); File file = fileChooser.showOpenDialog(getScene().getWindow()); if (file != null) { context.getPreferences(getDevice().getName()).put(PREF_LAST_IMAGE_BROWSE_LOCATION, file.getAbsolutePath()); imageUri.textProperty().set(file.getAbsolutePath()); } } @FXML void evtExport() { Layout addOn = new Layout(Strings.toId(getDevice().getName())); DeviceLayout layout = deviceViewer.getLayout(); addOn.setName(getDevice().getName()); addOn.setDescription(MessageFormat.format(bundle.getString("addOnTemplate.description"), getDevice().getName(), getDevice().getDriverVersion(), getDevice().getFirmware(), context.getBackend().getName(), context.getBackend().getVersion(), PlatformService.get().getInstalledVersion())); addOn.setLayout(new DeviceLayout(layout)); Export confirm = context.push(Export.class, Direction.FADE); confirm.export(addOn, bundle, "exportLayout", getDevice().getName()); } @FXML void evtRemoveElement() { deviceViewer.removeSelectedElements(); } @FXML void evtRemove() { if (deviceViewer.getViews().size() < 2 || deviceViewer.getSelectedView().getPosition().equals(ViewPosition.MATRIX)) { Confirm confirm = context.push(Confirm.class, Direction.FADE); confirm.getTitle().graphicProperty().set(new FontIcon(FontAwesome.TRASH)); confirm.getYes().graphicProperty().set(new FontIcon(FontAwesome.TRASH)); confirm.confirm(bundle, "removeLayout", () -> { context.getLayouts().remove(layout); context.pop(); }, deviceViewer.getSelectedView().getPosition()); } else { Confirm confirm = context.push(Confirm.class, Direction.FADE); confirm.getTitle().graphicProperty().set(new FontIcon(FontAwesome.TRASH)); confirm.getYes().graphicProperty().set(new FontIcon(FontAwesome.TRASH)); confirm.confirm(bundle, "removeView", () -> { DeviceView view = deviceViewer.getSelectedView(); deviceViewer.getLayout().removeView(view.getPosition()); deviceViewer.removeView(view); updateAvailability(); }, deviceViewer.getSelectedView().getPosition()); } } String getDefaultOutputLocation() { return context.getPreferences(getDevice().getName()).get(PREF_LAST_IMAGE_BROWSE_LOCATION, System.getProperty("user.dir")); } void updateAvailability() { remove.setDisable(deviceViewer.getViews().size() > 1 && deviceViewer.getSelectedView().getPosition().equals(ViewPosition.MATRIX)); } void updateBackgroundImageComponents() { /* Is the background image a complete URL? */ boolean isURL = false; URL url = null; DeviceView selectedView = deviceViewer.getSelectedView(); try { url = new URL(selectedView.getImageUri()); isURL = true; } catch (Exception e) { } /* Is the background a file URL, so local */ boolean isFile = false; if (url != null && url.getProtocol().equals("file")) { isFile = true; } if (url == null) { if (fileImage.selectedProperty().get()) isFile = true; else if (urlImage.selectedProperty().get()) isFile = true; } if (url != null) { if (isFile) { try { imageUri.promptTextProperty().set(new File(url.toURI()).getAbsolutePath()); } catch (URISyntaxException e) { imageUri.promptTextProperty().set(url.toExternalForm()); } fileImage.selectedProperty().set(true); } else if (isURL) { imageUri.promptTextProperty().set(url.toExternalForm()); urlImage.selectedProperty().set(true); } else { BrandingImage bimg = selectedView.getPosition().toBrandingImage(); if (bimg != null) { imageUri.promptTextProperty().set(getDevice().getImageUrl(bimg)); } autoImage.selectedProperty().set(true); } } imageUri.setDisable(!isFile && !isURL); browseImage.setDisable(!isFile); } void updateTemplateStatus() { toolBar.setVisible(layout != null && !layout.isReadOnly()); DeviceLayoutManager layouts = context.getLayouts(); boolean hasContributedLayout = layouts.hasLayout(getDevice()) && layouts.getLayout(getDevice()).isReadOnly(); boolean hasOfficialLayout = context.getLayouts().hasOfficialLayout(getDevice()); boolean hasUserLayout = context.getLayouts().hasUserLayout(getDevice()); if (hasUserLayout) { if (hasContributedLayout || hasOfficialLayout) notifyMessage(MessagePersistence.ONCE_PER_RUNTIME, MessageType.WARNING, bundle.getString("info.masking")); else notifyMessage(MessagePersistence.ONCE_PER_RUNTIME, MessageType.INFO, bundle.getString("info.user")); } else if (!hasOfficialLayout) { if (hasContributedLayout) { notifyMessage(MessagePersistence.ONCE_PER_RUNTIME, MessageType.INFO, bundle.getString("info.contributed")); } else notifyMessage(MessagePersistence.ONCE_PER_RUNTIME, MessageType.INFO, bundle.getString("info.notOfficial")); } else { clearNotifications(false); } } @Override public void viewerSelected(ViewerView view) { configureForView(); } }
31,295
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
EffectsControl.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/EffectsControl.java
package uk.co.bithatch.snake.ui; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import org.kordamp.ikonli.fontawesome.FontAwesome; import org.kordamp.ikonli.javafx.FontIcon; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.ComboBox; import javafx.scene.control.Hyperlink; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.util.Callback; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.lib.Region; import uk.co.bithatch.snake.ui.effects.EffectAcquisition; import uk.co.bithatch.snake.ui.effects.EffectManager; import uk.co.bithatch.snake.widgets.JavaFX; public class EffectsControl extends AbstractEffectsControl { @FXML private ComboBox<EffectHandler<?, ?>> overallEffect; @FXML private VBox regions; private boolean adjustingOverall = false; private boolean adjustingSingle = false; private Set<EffectHandler<?, ?>> deviceEffects; private Map<Region, ComboBox<EffectHandler<?, ?>>> others = new LinkedHashMap<>(); final static ResourceBundle bundle = ResourceBundle.getBundle(EffectsControl.class.getName()); @Override protected void onSetEffectsControlDevice() { JavaFX.bindManagedToVisible(addCustom, removeCustom, regions); var device = getDevice(); Callback<ListView<EffectHandler<?, ?>>, ListCell<EffectHandler<?, ?>>> cellFactory = createEffectCellFactory(); overallEffect.setButtonCell(cellFactory.call(null)); overallEffect.setCellFactory(cellFactory); overallEffect.getSelectionModel().selectedItemProperty().addListener((e) -> { if (!adjustingOverall) { EffectHandler<?, ?> selected = overallEffect.getSelectionModel().getSelectedItem(); if(selected != null) { setCustomiseState(customise, device, selected); context.getEffectManager().getRootAcquisition(device).activate(device, selected); } } }); } private Callback<ListView<EffectHandler<?, ?>>, ListCell<EffectHandler<?, ?>>> createEffectCellFactory() { Callback<ListView<EffectHandler<?, ?>>, ListCell<EffectHandler<?, ?>>> cellFactory = new Callback<ListView<EffectHandler<?, ?>>, ListCell<EffectHandler<?, ?>>>() { @Override public ListCell<EffectHandler<?, ?>> call(ListView<EffectHandler<?, ?>> l) { return new ListCell<EffectHandler<?, ?>>() { @Override protected void updateItem(EffectHandler<?, ?> item, boolean empty) { super.updateItem(item, empty); if (item == null || empty) { setGraphic(null); setText(bundle.getString("emptyChoice")); } else { Node effectImageNode = item.getEffectImageNode(24, 22); effectImageNode.getStyleClass().add("cell"); setGraphic(effectImageNode); setText(item.getDisplayName()); } } }; } }; return cellFactory; } protected void rebuildRegions() { others.clear(); regions.getChildren().clear(); Device device = getDevice(); List<Region> originalRegionList = device.getRegions(); List<Region> regionList = new ArrayList<>(); EffectManager fx = context.getEffectManager(); EffectAcquisition acq = fx.getRootAcquisition(device); EffectHandler<?, ?> selectedDeviceEffect = acq.getEffect(device); for (Region r : originalRegionList) { Set<EffectHandler<?, ?>> supported = fx.getEffects(r); EffectHandler<?, ?> selectedRegionEffect = acq.getEffect(r); if (!supported.isEmpty() && supported.contains(selectedRegionEffect)) { regionList.add(r); } } if (regionList.size() > 1) { if (selectedDeviceEffect != null && selectedDeviceEffect.isRegions()) { for (Region r : regionList) { Set<EffectHandler<?, ?>> supported = fx.getEffects(r); Set<EffectHandler<?, ?>> allEffects = new LinkedHashSet<>(supported); allEffects.addAll(fx.getEffects(device)); EffectHandler<?, ?> selectedRegionEffect = acq.getEffect(r); HBox hbox = new HBox(); ImageView iv = new ImageView( context.getConfiguration().getTheme().getRegionImage(24, r.getName()).toExternalForm()); iv.setFitHeight(22); iv.setFitWidth(22); iv.setSmooth(true); iv.setPreserveRatio(true); Hyperlink customise = new Hyperlink(); customise.setGraphic(new FontIcon(FontAwesome.GEAR)); ComboBox<EffectHandler<?, ?>> br = new ComboBox<>(); Callback<ListView<EffectHandler<?, ?>>, ListCell<EffectHandler<?, ?>>> cellFactory = createEffectCellFactory(); br.setButtonCell(cellFactory.call(null)); br.setCellFactory(cellFactory); br.maxWidth(80); br.getStyleClass().add("small"); for (EffectHandler<?, ?> f : allEffects) { if (f.isRegions()) { br.itemsProperty().get().add(f); if (selectedRegionEffect != null && f == selectedRegionEffect) { br.getSelectionModel().select(f); } } } br.getSelectionModel().selectedItemProperty().addListener((e) -> { var efHandler = br.getSelectionModel().getSelectedItem(); if (!adjustingSingle && supported.contains(efHandler)) { acq.activate(r, efHandler); adjustingOverall = true; try { overallEffect.getSelectionModel().select(acq.getEffect(device)); setCustomiseState(customise, r, br.getSelectionModel().getSelectedItem()); } finally { adjustingOverall = false; } } }); others.put(r, br); customise.getStyleClass().add("smallIconButton"); customise.onActionProperty().set((e) -> { customise(r, br.getSelectionModel().getSelectedItem()); }); setCustomiseState(customise, r, br.getSelectionModel().getSelectedItem()); hbox.getChildren().add(iv); hbox.getChildren().add(br); hbox.getChildren().add(customise); regions.getChildren().add(hbox); } } else regions.setVisible(false); } else regions.setVisible(false); } protected void onRebuildOverallEffects() { overallEffect.itemsProperty().get().clear(); EffectManager fx = context.getEffectManager(); deviceEffects = fx.getEffects(getDevice()); EffectAcquisition acq = fx.getRootAcquisition(getDevice()); EffectHandler<?, ?> selectedDeviceEffect = acq.getEffect(getDevice()); for (EffectHandler<?, ?> f : deviceEffects) { overallEffect.itemsProperty().get().add(f); if (selectedDeviceEffect != null && f.equals(selectedDeviceEffect)) { overallEffect.getSelectionModel().select(f); } } } @Override protected void selectOverallEffect(EffectHandler<?, ?> effect) { overallEffect.getSelectionModel().select(effect); } @Override protected EffectHandler<?, ?> getOverallEffect() { return overallEffect.getSelectionModel().getSelectedItem(); } }
6,875
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
VolumeControl.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/VolumeControl.java
package uk.co.bithatch.snake.ui; import java.util.ResourceBundle; import org.kordamp.ikonli.fontawesome.FontAwesome; import org.kordamp.ikonli.javafx.FontIcon; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.Slider; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.ui.audio.AudioManager.VolumeListener; public class VolumeControl extends ControlController implements VolumeListener { final static ResourceBundle bundle = ResourceBundle.getBundle(VolumeControl.class.getName()); @FXML private Slider volume; @FXML private Label muteToggle; private boolean adjusting; @Override protected void onSetControlDevice() { context.getAudioManager().addVolumeListener(this); volume.valueProperty().addListener((e, o, n) -> { try { if (!adjusting) { context.getAudioManager().setVolume(getDevice(), n.intValue()); // TODO remove when events are firing setVolumeForState(); } } catch (Exception exx) { exx.printStackTrace(); } }); setVolumeForState(); } @FXML void evtMuteToggle() { } void setVolumeForState() { adjusting = true; try { if (context.getAudioManager().isMuted(getDevice()) || context.getAudioManager().getVolume(getDevice()) == 0) { volume.setValue(0); muteToggle.graphicProperty().set(new FontIcon(FontAwesome.VOLUME_OFF)); } else { volume.setValue(context.getAudioManager().getVolume(getDevice())); muteToggle.graphicProperty().set(new FontIcon(FontAwesome.VOLUME_DOWN)); } } finally { adjusting = false; } } @Override public void volumeChanged(Device device, int volume) { if (device.equals(getDevice())) Platform.runLater(() -> setVolumeForState()); } }
1,775
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
ReactiveOptions.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/ReactiveOptions.java
package uk.co.bithatch.snake.ui; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Slider; import uk.co.bithatch.snake.lib.effects.Reactive; import uk.co.bithatch.snake.ui.SchedulerManager.Queue; import uk.co.bithatch.snake.ui.effects.ReactiveEffectHandler; import uk.co.bithatch.snake.widgets.ColorBar; import uk.co.bithatch.snake.widgets.JavaFX; public class ReactiveOptions extends AbstractBackendEffectController<Reactive, ReactiveEffectHandler> { @FXML private Slider speed; @FXML private ColorBar color; private boolean adjusting = false; public int getSpeed() { return (int) speed.valueProperty().get(); } public int[] getColor() { return JavaFX.toRGB(color.getColor()); } @Override protected void onConfigure() throws Exception { color.colorProperty().addListener((e) -> { if (!adjusting) { try { Reactive effect = (Reactive) getEffect().clone(); effect.setColor(JavaFX.toRGB(color.getColor())); context.getSchedulerManager().get(Queue.DEVICE_IO).execute(() -> getRegion().setEffect(effect)); } catch (CloneNotSupportedException cnse) { throw new IllegalStateException(cnse); } } }); speed.valueProperty().addListener((e) -> { if (!adjusting) { try { Reactive reactive = (Reactive) getEffect().clone(); reactive.setSpeed((int) speed.valueProperty().get()); context.getSchedulerManager().get(Queue.DEVICE_IO).execute(() -> getRegion().setEffect(reactive)); } catch (CloneNotSupportedException cnse) { throw new IllegalStateException(cnse); } } }); } @Override protected void onSetEffect() { Reactive effect = getEffect(); adjusting = true; try { speed.valueProperty().set(effect.getSpeed()); color.setColor(JavaFX.toColor(effect.getColor())); } finally { adjusting = false; } } @FXML void evtBack(ActionEvent evt) { context.pop(); } }
1,916
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
DPIControl.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/DPIControl.java
package uk.co.bithatch.snake.ui; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.Slider; public class DPIControl extends ControlController { @FXML private Label dpiText; @FXML private Slider dpi; @Override protected void onSetControlDevice() { dpi.maxProperty().set(getDevice().getMaxDPI()); dpi.valueProperty().set(getDevice().getDPI()[0]); dpi.snapToTicksProperty().set(true); dpi.majorTickUnitProperty().set(1000); dpi.minorTickCountProperty().set(100); dpi.valueProperty().addListener((e) -> { short v = (short) ((short) ((float) dpi.valueProperty().get() / 100.0) * (short) 100); getDevice().setDPI(v, v); dpiText.textProperty().set(String.format("%d", getDevice().getDPI()[0])); }); dpiText.textProperty().set(String.format("%d", getDevice().getDPI()[0])); } }
843
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
ProfileControl.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/ProfileControl.java
package uk.co.bithatch.snake.ui; import java.io.IOException; import java.util.List; import java.util.ResourceBundle; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import uk.co.bithatch.snake.lib.Capability; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.lib.binding.Profile; import uk.co.bithatch.snake.lib.binding.ProfileMap; import uk.co.bithatch.snake.ui.widgets.MapProfileLEDHelper; import uk.co.bithatch.snake.widgets.Direction; import uk.co.bithatch.snake.widgets.JavaFX; import uk.co.bithatch.snake.widgets.ProfileLEDs; public class ProfileControl extends ControlController { final static ResourceBundle bundle = ResourceBundle.getBundle(ProfileControl.class.getName()); @FXML private VBox profiles; @FXML private Hyperlink addProfile; @FXML private Hyperlink setDefault; @FXML private Hyperlink remove; @FXML private Hyperlink configure; @FXML private ProfileLEDs rgbs; private MapProfileLEDHelper profileLEDHelper; @Override protected void onSetControlDevice() { buildProfiles(); profileLEDHelper = new MapProfileLEDHelper(rgbs); configureForProfile(); } @Override protected void onDeviceCleanUp() { super.onDeviceCleanUp(); try { profileLEDHelper.close(); } catch (IOException e) { } } protected void buildProfiles() { profiles.getChildren().clear(); for (Profile profile : getDevice().getProfiles()) { profiles.getChildren().add(new ProfileRow(getDevice(), profile)); List<ProfileMap> maps = profile.getMaps(); for (ProfileMap map : maps) { profiles.getChildren().add(new MapRow(getDevice(), map)); } } } protected void addMap(Profile profile) { Input confirm = context.push(Input.class, Direction.FADE); confirm.setValidator((l) -> { String name = confirm.inputProperty().get(); boolean available = profile.getMap(name) == null; l.getStyleClass().clear(); if (available) { l.textProperty().set(""); l.visibleProperty().set(false); } else { l.visibleProperty().set(true); l.textProperty().set(bundle.getString("error.mapWithIDAlreadyExists")); l.getStyleClass().add("danger"); } return available; }); confirm.confirm(bundle, "addMap", () -> { profile.addMap(confirm.inputProperty().get()); }); } @FXML void evtConfigure() throws Exception { MacroMap map = context.push(MacroMap.class, Direction.FROM_BOTTOM); map.setMap(getDevice().getActiveProfile().getActiveMap()); } void configureForProfile() { Profile profile = getDevice().getActiveProfile(); ProfileMap profileMap = profile.getActiveMap(); /* Selected profile */ for (Node n : profiles.getChildren()) { ((MapComponent) n).updateAvailability(); } /* RGBs */ if (getDevice().getCapabilities().contains(Capability.MACRO_PROFILE_LEDS)) { profileLEDHelper.setMap(profile.getActiveMap()); } setDefault.disableProperty().set(profileMap == null || profileMap.isDefault()); remove.disableProperty().set(getDevice().getProfiles().size() < 2 && profile.getMaps().size() < 2); configure.disableProperty().set(profileMap == null); } @FXML void evtRemove() { ProfileMap activeMap = getDevice().getActiveProfile().getActiveMap(); Confirm confirm = context.push(Confirm.class, Direction.FADE); confirm.confirm(bundle, "removeMap", () -> { /* * TODO If the profile has other maps, select one of those. If this is the last * map, select another profile. Do this before actually removing due to bug in * the backend. * * Also make the chosen profile / map the default if this map is currently the * default */ if (activeMap.getProfile().getMaps().size() == 1) { /* Last map, select another profile */ for (Profile p : getDevice().getProfiles()) { if (!p.equals(activeMap.getProfile())) { p.activate(); if (activeMap.isDefault()) { p.getActiveMap().makeDefault(); } break; } } } else { /* Other maps available */ for (ProfileMap m : activeMap.getProfile().getMaps()) { if (!m.equals(activeMap)) { if (activeMap.isDefault()) { m.makeDefault(); } m.activate(); break; } } } activeMap.remove(); }, null, activeMap.getId()); } @FXML void evtSetDefault() { getDevice().getActiveProfile().getActiveMap().makeDefault(); } @FXML void evtAddProfile() { Input confirm = context.push(Input.class, Direction.FADE); confirm.setValidator((l) -> { String name = confirm.inputProperty().get(); boolean available = getDevice().getProfile(name) == null; l.getStyleClass().clear(); if (available) { l.textProperty().set(""); l.visibleProperty().set(false); } else { l.visibleProperty().set(true); l.textProperty().set(bundle.getString("error.nameAlreadyExists")); l.getStyleClass().add("danger"); } return available; }); confirm.confirm(bundle, "addProfile", () -> { getDevice().addProfile(confirm.inputProperty().get()); }); } interface MapComponent { void updateAvailability(); } class MapRow extends HBox implements MapComponent { Label defaultMap; ProfileMap profileMap; Hyperlink link; Device device; MapRow(Device device, ProfileMap profileMap) { this.profileMap = profileMap; this.device = device; getStyleClass().add("small"); getStyleClass().add("gapLeft"); setAlignment(Pos.CENTER_LEFT); defaultMap = new Label(bundle.getString("defaultMap")); link = new Hyperlink(profileMap.getId()); link.setOnAction((e) -> { profileMap.activate(); }); getChildren().add(defaultMap); getChildren().add(link); updateAvailability(); } public void updateAvailability() { defaultMap.visibleProperty().set(profileMap.isDefault()); JavaFX.glowOrDeemphasis(this, profileMap.isActive()); if (profileMap.isDefault()) { if (!getStyleClass().contains("emphasis")) getStyleClass().add("emphasis"); } else { getStyleClass().remove("emphasis"); } } } class ProfileRow extends HBox implements MapComponent { Profile profile; Hyperlink link; Device device; Hyperlink addMap; ProfileRow(Device device, Profile profile) { this.profile = profile; this.device = device; setAlignment(Pos.CENTER_LEFT); link = new Hyperlink(profile.getName()); link.setOnAction((e) -> { profile.activate(); }); addMap = new Hyperlink(bundle.getString("addMap")); addMap.setOnAction((e) -> { addMap(profile); }); addMap.setTooltip(JavaFX.quickTooltip(bundle.getString("addMap.tooltip"))); getChildren().add(link); getChildren().add(addMap); updateAvailability(); } public void updateAvailability() { JavaFX.glowOrDeemphasis(this, profile.isActive()); } } @Override public void mapChanged(ProfileMap map) { if (Platform.isFxApplicationThread()) { configureForProfile(); } else Platform.runLater(() -> mapChanged(map)); } @Override public void activeMapChanged(ProfileMap map) { if (Platform.isFxApplicationThread()) { configureForProfile(); } else Platform.runLater(() -> activeMapChanged(map)); } @Override public void profileAdded(Profile profile) { change(profile); } @Override public void profileRemoved(Profile profile) { change(profile); } @Override public void mapAdded(ProfileMap profile) { change(profile.getProfile()); } @Override public void mapRemoved(ProfileMap profile) { change(profile.getProfile()); } void change(Profile profile) { if (Platform.isFxApplicationThread()) { buildProfiles(); configureForProfile(); } else Platform.runLater(() -> change(profile)); } }
7,837
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
KeyboardLayout.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/KeyboardLayout.java
package uk.co.bithatch.snake.ui; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javafx.beans.property.DoubleProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ObjectPropertyBase; import javafx.css.CssMetaData; import javafx.css.Styleable; import javafx.css.StyleableDoubleProperty; import javafx.css.StyleableObjectProperty; import javafx.css.StyleableProperty; import javafx.css.converter.EnumConverter; import javafx.css.converter.SizeConverter; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.geometry.VPos; import javafx.scene.Node; import javafx.scene.layout.Pane; public class KeyboardLayout extends Pane { private static final String COL_CONSTRAINT = "col"; private static final String ROW_CONSTRAINT = "row"; static void setConstraint(Node node, Object key, Object value) { if (value == null) { node.getProperties().remove(key); } else { node.getProperties().put(key, value); } if (node.getParent() != null) { node.getParent().requestLayout(); } } static Object getConstraint(Node node, Object key) { if (node.hasProperties()) { Object value = node.getProperties().get(key); if (value != null) { return value; } } return null; } public static void setRow(Node child, int value) { setConstraint(child, ROW_CONSTRAINT, value == -1 ? null : value); } public static int getRow(Node child) { return (Integer) getConstraint(child, ROW_CONSTRAINT); } public static void setCol(Node child, int value) { setConstraint(child, COL_CONSTRAINT, value == -1 ? null : value); } public static int getCol(Node child) { return (Integer) getConstraint(child, COL_CONSTRAINT); } public static void clearConstraints(Node child) { setCol(child, -1); setRow(child, -1); } public KeyboardLayout() { super(); } public KeyboardLayout(double spacing) { this(); setSpacing(spacing); } public KeyboardLayout(Node... children) { super(); getChildren().addAll(children); } public KeyboardLayout(double spacing, Node... children) { this(); setSpacing(spacing); getChildren().addAll(children); } public final ObjectProperty<Pos> alignmentProperty() { if (alignment == null) { alignment = new StyleableObjectProperty<Pos>(Pos.TOP_LEFT) { @Override public void invalidated() { requestLayout(); } @Override public CssMetaData<KeyboardLayout, Pos> getCssMetaData() { return StyleableProperties.ALIGNMENT; } @Override public Object getBean() { return KeyboardLayout.this; } @Override public String getName() { return "alignment"; } }; } return alignment; } private ObjectProperty<Pos> alignment; private ObjectProperty<Number> xProperty; private ObjectProperty<Number> yProperty; public final void setAlignment(Pos value) { alignmentProperty().set(value); } public final Pos getAlignment() { return alignment == null ? Pos.CENTER : alignment.get(); } private Pos getAlignmentInternal() { Pos localPos = getAlignment(); return localPos == null ? Pos.CENTER : localPos; } public final DoubleProperty spacingProperty() { if (spacing == null) { spacing = new StyleableDoubleProperty() { @Override public void invalidated() { requestLayout(); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public CssMetaData getCssMetaData() { return StyleableProperties.SPACING; } @Override public Object getBean() { return KeyboardLayout.this; } @Override public String getName() { return "spacing"; } }; spacing.set(7); } return spacing; } public final ObjectProperty<Number> xProperty() { if (xProperty == null) { xProperty = new ObjectPropertyBase<>() { protected void invalidated() { requestLayout(); } @Override public Object getBean() { return KeyboardLayout.this; } @Override public String getName() { return "x"; } }; } return xProperty; } public final ObjectProperty<Number> yProperty() { if (yProperty == null) { yProperty = new ObjectPropertyBase<>() { protected void invalidated() { requestLayout(); } @Override public Object getBean() { return KeyboardLayout.this; } @Override public String getName() { return "y"; } }; } return yProperty; } public final DoubleProperty keyWidthProperty() { if (keyWidth == null) { keyWidth = new StyleableDoubleProperty() { @Override public void invalidated() { requestLayout(); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public CssMetaData getCssMetaData() { return StyleableProperties.KEY_WIDTH; } @Override public Object getBean() { return KeyboardLayout.this; } @Override public String getName() { return "key-width"; } }; keyWidth.set(36); } return keyWidth; } public final DoubleProperty keyHeightProperty() { if (keyHeight == null) { keyHeight = new StyleableDoubleProperty() { @Override public void invalidated() { requestLayout(); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public CssMetaData getCssMetaData() { return StyleableProperties.KEY_HEIGHT; } @Override public Object getBean() { return KeyboardLayout.this; } @Override public String getName() { return "key-height"; } }; keyHeight.set(36); } return keyHeight; } public final DoubleProperty keyFactorProperty() { if (keyFactor == null) { keyFactor = new StyleableDoubleProperty() { @Override public void invalidated() { requestLayout(); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public CssMetaData getCssMetaData() { return StyleableProperties.KEY_FACTOR; } @Override public Object getBean() { return KeyboardLayout.this; } @Override public String getName() { return "key-factor"; } }; } return keyFactor; } private DoubleProperty spacing; public final void setSpacing(double value) { spacingProperty().set(value); } public final double getSpacing() { return spacing == null ? 0 : spacing.get(); } private DoubleProperty keyWidth; public final void setKeyWidth(double value) { keyWidthProperty().set(value); } public final double getKeyWidth() { return keyWidth == null ? 0 : keyWidth.get(); } private DoubleProperty keyHeight; public final void setKeyHeight(double value) { keyHeightProperty().set(value); } public final double getKeyHeight() { return keyHeight == null ? 0 : keyHeight.get(); } private DoubleProperty keyFactor; public final void setKeyFactor(double value) { keyFactorProperty().set(value); } public final double getKeyFactor() { return keyFactor == null ? 0 : keyFactor.get(); } @Override protected double computeMinWidth(double height) { Insets insets = getInsets(); double w = snapSpaceX(insets.getLeft()) + computeContentWidth(getManagedChildren(), height, true) + snapSpaceX(insets.getRight()); return w; } @Override protected double computeMinHeight(double width) { Insets insets = getInsets(); double h = snapSpaceY(insets.getTop()) + computeContentHeight(getManagedChildren(), width, true) + snapSpaceY(insets.getBottom()); return h; } @Override protected double computePrefWidth(double height) { return computeMinWidth(height); } @Override protected double computePrefHeight(double width) { return computeMinHeight(width); } private double computeContentWidth(List<Node> managedChildren, double height, boolean minimum) { double x = xProperty().get() == null ? 0 : xProperty().get().doubleValue(); return x * keyWidthProperty().get() + (x - 1) * snapSpaceX(getSpacing()); } private double computeContentHeight(List<Node> managedChildren, double height, boolean minimum) { double y = yProperty().get() == null ? 0 : yProperty().get().doubleValue(); return y * keyHeightProperty().get() + (y - 1) * snapSpaceY(getSpacing()); } @Override public void requestLayout() { super.requestLayout(); } @Override protected void layoutChildren() { List<Node> managed = getManagedChildren(); Insets insets = getInsets(); double width = getWidth(); double height = getHeight(); double top = snapSpaceY(insets.getTop()); double left = snapSpaceX(insets.getLeft()); double right = snapSpaceX(insets.getRight()); double bottom = snapSpaceX(insets.getBottom()); double space = snapSpaceX(spacingProperty().get()); double kwidth = keyWidthProperty().get(); double kheight = keyHeightProperty().get(); Pos align = getAlignmentInternal(); HPos alignHpos = align.getHpos(); VPos alignVpos = align.getVpos(); double xo = left + computeXOffset(width - left - right, prefWidth(height), align.getHpos()); double yo = top + computeYOffset(height - top - bottom, prefHeight(width), align.getVpos()); double x, y; for (Node cell : managed) { int j = getCol(cell); int i = getRow(cell); double pw = kwidth; x = xo + (((j * kwidth) + (j * space)) - (pw / 2) + (kwidth / 2)); y = yo + ((i * kheight) + (i * space)); layoutInArea(cell, x, y, pw, kheight, 0, null, false, false, alignHpos, alignVpos); } } static double computeXOffset(double width, double contentWidth, HPos hpos) { switch (hpos) { case LEFT: return 0; case CENTER: return (width - contentWidth) / 2; case RIGHT: return width - contentWidth; default: throw new AssertionError("Unhandled hPos"); } } static double computeYOffset(double height, double contentHeight, VPos vpos) { switch (vpos) { case BASELINE: case TOP: return 0; case CENTER: return (height - contentHeight) / 2; case BOTTOM: return height - contentHeight; default: throw new AssertionError("Unhandled vPos"); } } private static class StyleableProperties { private static final CssMetaData<KeyboardLayout, Pos> ALIGNMENT = new CssMetaData<KeyboardLayout, Pos>( "-fx-alignment", new EnumConverter<Pos>(Pos.class), Pos.TOP_LEFT) { @Override public boolean isSettable(KeyboardLayout node) { return node.alignment == null || !node.alignment.isBound(); } @SuppressWarnings("unchecked") @Override public StyleableProperty<Pos> getStyleableProperty(KeyboardLayout node) { return (StyleableProperty<Pos>) node.alignmentProperty(); } }; private static final CssMetaData<KeyboardLayout, Number> SPACING = new CssMetaData<KeyboardLayout, Number>( "-fx-spacing", SizeConverter.getInstance(), 4.0) { @Override public boolean isSettable(KeyboardLayout node) { return node.spacing == null || !node.spacing.isBound(); } @SuppressWarnings("unchecked") @Override public StyleableProperty<Number> getStyleableProperty(KeyboardLayout node) { return (StyleableProperty<Number>) node.spacingProperty(); } }; private static final CssMetaData<KeyboardLayout, Number> KEY_WIDTH = new CssMetaData<KeyboardLayout, Number>( "-fx-key-width", SizeConverter.getInstance(), 36.0) { @Override public boolean isSettable(KeyboardLayout node) { return node.spacing == null || !node.keyWidth.isBound(); } @SuppressWarnings("unchecked") @Override public StyleableProperty<Number> getStyleableProperty(KeyboardLayout node) { return (StyleableProperty<Number>) node.keyWidthProperty(); } }; private static final CssMetaData<KeyboardLayout, Number> KEY_HEIGHT = new CssMetaData<KeyboardLayout, Number>( "-fx-key-height", SizeConverter.getInstance(), 36.0) { @Override public boolean isSettable(KeyboardLayout node) { return node.spacing == null || !node.keyHeightProperty().isBound(); } @SuppressWarnings("unchecked") @Override public StyleableProperty<Number> getStyleableProperty(KeyboardLayout node) { return (StyleableProperty<Number>) node.keyHeightProperty(); } }; private static final CssMetaData<KeyboardLayout, Number> KEY_FACTOR = new CssMetaData<KeyboardLayout, Number>( "-fx-key-factor", SizeConverter.getInstance(), 0.4) { @Override public boolean isSettable(KeyboardLayout node) { return node.keyFactor == null || !node.keyFactor.isBound(); } @SuppressWarnings("unchecked") @Override public StyleableProperty<Number> getStyleableProperty(KeyboardLayout node) { return (StyleableProperty<Number>) node.keyFactorProperty(); } }; private static final List<CssMetaData<? extends Styleable, ?>> STYLEABLES; static { final List<CssMetaData<? extends Styleable, ?>> styleables = new ArrayList<CssMetaData<? extends Styleable, ?>>( Pane.getClassCssMetaData()); styleables.add(SPACING); styleables.add(KEY_WIDTH); styleables.add(KEY_HEIGHT); styleables.add(KEY_FACTOR); styleables.add(ALIGNMENT); STYLEABLES = Collections.unmodifiableList(styleables); } } public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() { return StyleableProperties.STYLEABLES; } @Override public List<CssMetaData<? extends Styleable, ?>> getCssMetaData() { return getClassCssMetaData(); } }
13,320
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
BatteryControl.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/BatteryControl.java
package uk.co.bithatch.snake.ui; import java.util.ResourceBundle; import java.util.concurrent.TimeUnit; import org.kordamp.ikonli.fontawesome.FontAwesome; import org.kordamp.ikonli.javafx.FontIcon; import javafx.animation.FadeTransition; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.control.Spinner; import javafx.scene.control.SpinnerValueFactory; import javafx.util.Duration; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.lib.Device.Listener; import uk.co.bithatch.snake.lib.Region; public class BatteryControl extends ControlController implements Listener { @FXML private Label batteryStatus; @FXML private Label percentage; @FXML private Spinner<Integer> lowThreshold; @FXML private Spinner<Integer> idleTime; @FXML private Label charging; private FadeTransition chargingAnim; private FadeTransition lowAnim; final static ResourceBundle bundle = ResourceBundle.getBundle(BatteryControl.class.getName()); @Override protected void onConfigure() throws Exception { chargingAnim = createFader(charging); lowAnim = createFader(batteryStatus); lowThreshold.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 100)); idleTime.setValueFactory( new SpinnerValueFactory.IntegerSpinnerValueFactory(0, (int) TimeUnit.MINUTES.toSeconds(5))); lowThreshold.valueProperty() .addListener((c) -> getDevice().setLowBatteryThreshold(lowThreshold.getValue().byteValue())); idleTime.valueProperty().addListener((c) -> getDevice().setIdleTime(idleTime.getValue())); } @Override protected void onSetControlDevice() { Device dev = getDevice(); setBatteryDevice(dev); getDevice().addListener(this); } public static FadeTransition createFader(Node node) { FadeTransition anim = new FadeTransition(Duration.seconds(5)); anim.setAutoReverse(true); anim.setCycleCount(FadeTransition.INDEFINITE); anim.setNode(node); anim.setFromValue(0.5); anim.setToValue(1); return anim; } public static FontAwesome getBatteryIcon(int level) { if (level < 1) { return FontAwesome.BATTERY_EMPTY; } else if (level <= 25) { return FontAwesome.BATTERY_QUARTER; } else if (level <= 50) { return FontAwesome.BATTERY_HALF; } else if (level <= 75) { return FontAwesome.BATTERY_THREE_QUARTERS; } else { return FontAwesome.BATTERY_FULL; } } public static String getBatteryStyle(int lowest, int level) { int low = (99 - lowest) / 3; int medium = low * 2; if (level < 1 || level <= lowest) { return "danger"; } else if (level <= low) { return "warning"; } else if (level <= medium) { return "success"; } else { return null; } } public static void setBatteryStatusStyle(int lowest, int level, Node node, FadeTransition fader) { node.getStyleClass().remove("danger"); node.getStyleClass().remove("warning"); node.getStyleClass().remove("success"); String style = getBatteryStyle(lowest, level); if (style == null) style = "success"; if ("danger".equals(style) && fader != null) fader.play(); node.getStyleClass().add(style); } private void setBatteryDevice(Device dev) { int level = dev.getBattery(); setBatteryStatusStyle(dev.getLowBatteryThreshold(), level, batteryStatus, lowAnim); setBatteryStatusStyle(dev.getLowBatteryThreshold(), level, charging, null); setBatteryStatusStyle(dev.getLowBatteryThreshold(), level, percentage, null); batteryStatus.graphicProperty().set(new FontIcon(getBatteryIcon(level))); percentage.textProperty().set(String.format("%d%%", level)); lowThreshold.getValueFactory().setValue((int) dev.getLowBatteryThreshold()); idleTime.getValueFactory().setValue(dev.getIdleTime()); boolean c = dev.isCharging(); charging.visibleProperty().set(c); if (c) chargingAnim.play(); else chargingAnim.stop(); } @Override protected void onDeviceCleanUp() { getDevice().removeListener(this); chargingAnim.stop(); } @Override public void onChanged(Device device, Region region) { setBatteryDevice(device); } }
4,072
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Controller.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/Controller.java
package uk.co.bithatch.snake.ui; import javafx.fxml.Initializable; import javafx.scene.Scene; public interface Controller extends Initializable { public enum MessagePersistence { EVERYTIME, ONCE_PER_RUNTIME, ONCE_PER_INSTALL } public enum MessageType { INFO, WARNING, DANGER, SUCCESS } Scene getScene(); void configure(Scene scene, App jfxhsClient); void cleanUp(); default void notifyMessage(MessageType messageType, String content) { notifyMessage(MessagePersistence.EVERYTIME, messageType, content); } default void notifyMessage(MessagePersistence persistence, MessageType messageType, String content) { notifyMessage(persistence, messageType, null, content); } default void notifyMessage(MessageType messageType, String title, String content) { notifyMessage(MessagePersistence.EVERYTIME, messageType, title, content, 10); } default void notifyMessage(MessagePersistence persistence, MessageType messageType, String title, String content) { notifyMessage(persistence, messageType, title, content, 10); } void notifyMessage(MessagePersistence persistence, MessageType messageType, String title, String content, int timeout); default void clearNotifications(boolean immediate) { clearNotifications(null, immediate); } void clearNotifications(MessageType type, boolean immediate); }
1,334
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
BrightnessControl.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/BrightnessControl.java
package uk.co.bithatch.snake.ui; import java.util.ArrayList; import java.util.List; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.Slider; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import uk.co.bithatch.snake.lib.Capability; import uk.co.bithatch.snake.lib.Region; import uk.co.bithatch.snake.widgets.JavaFX; public class BrightnessControl extends ControlController { @FXML private Label brightnessText; @FXML private Slider brightness; @FXML private VBox regions; private boolean adjustingOverall = false; private boolean adjustingSingle = false; @Override protected void onSetControlDevice() { JavaFX.bindManagedToVisible(regions); List<Slider> others = new ArrayList<>(); brightness.maxProperty().set(100); brightness.valueProperty().set(getDevice().getBrightness()); brightness.setShowTickMarks(true); brightness.setSnapToTicks(true); brightness.setMajorTickUnit(10); brightness.setMinorTickCount(1); brightness.valueProperty().addListener((e) -> { if (!adjustingOverall) { getDevice().setBrightness((short) brightness.valueProperty().get()); brightnessText.textProperty().set(String.format("%d%%", getDevice().getBrightness())); adjustingSingle = true; try { for (Slider sl : others) { sl.setValue(brightness.valueProperty().get()); } } finally { adjustingSingle = false; } } }); brightnessText.textProperty().set(String.format("%d%%", getDevice().getBrightness())); if (getDevice().getCapabilities().contains(Capability.BRIGHTNESS_PER_REGION)) { List<Region> regionList = getDevice().getRegions(); if (regionList.size() > 1) { for (Region r : regionList) { if (r.getCapabilities().contains(Capability.BRIGHTNESS_PER_REGION)) { HBox hbox = new HBox(); ImageView iv = new ImageView( context.getConfiguration().getTheme().getRegionImage(24, r.getName()).toExternalForm()); iv.setFitHeight(22); iv.setFitWidth(22); iv.setSmooth(true); iv.setPreserveRatio(true); Slider br = new Slider(0, 100, r.getBrightness()); br.maxWidth(80); Label la = new Label(String.format("%d%%", r.getBrightness())); la.getStyleClass().add("small"); br.valueProperty().addListener((e) -> { r.setBrightness((short) br.valueProperty().get()); if (!adjustingSingle) { adjustingOverall = true; try { brightness.setValue(getDevice().getBrightness()); } finally { adjustingOverall = false; } } la.textProperty().set(String.format("%d%%", r.getBrightness())); }); others.add(br); hbox.getChildren().add(iv); hbox.getChildren().add(br); hbox.getChildren().add(la); regions.getChildren().add(hbox); } } } else regions.setVisible(false); } else regions.setVisible(false); } void setBrightness(short brightness) { for (Region r : getDevice().getRegions()) { if (r.getCapabilities().contains(Capability.BRIGHTNESS_PER_REGION)) r.setBrightness(brightness); } } }
3,176
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
GameModeControl.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/GameModeControl.java
package uk.co.bithatch.snake.ui; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.Slider; public class GameModeControl extends ControlController { @FXML private Slider gameMode; @FXML private Label on; @FXML private Label off; @Override protected void onSetControlDevice() { on.onMouseClickedProperty().set((e) -> gameMode.valueProperty().set(1)); off.onMouseClickedProperty().set((e) -> gameMode.valueProperty().set(0)); gameMode.valueProperty().set(getDevice().isGameMode() ? 1 : 0); gameMode.valueProperty().addListener((e) -> getDevice().setGameMode(gameMode.valueProperty().get() > 0)); } @Override protected void onDeviceCleanUp() { } }
707
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
PlatformService.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/PlatformService.java
package uk.co.bithatch.snake.ui; import java.io.IOException; import java.util.ServiceLoader; public interface PlatformService { public static boolean isPlatformSupported() { ServiceLoader<PlatformService> ps = ServiceLoader.load(PlatformService.class); return ps.findFirst().isPresent(); } public static PlatformService get() { ServiceLoader<PlatformService> ps = ServiceLoader.load(PlatformService.class); return ps.findFirst().get(); } boolean isStartOnLogin(); void setStartOnLogin(boolean startOnLogin) throws IOException; boolean isUpdateableApp(); boolean isUpdateAvailable(); boolean isUpdateAutomatically(); boolean isCheckForUpdates(); boolean isBetas(); void setUpdateAutomatically(boolean updateAutomatically); void setCheckForUpdates(boolean checkForUpdates); void setBetas(boolean betas); String getAvailableVersion(); String getInstalledVersion(); boolean isUpdated(); }
927
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Macros.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/Macros.java
package uk.co.bithatch.snake.ui; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.lang.System.Logger.Level; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.function.UnaryOperator; import java.util.prefs.Preferences; import org.controlsfx.control.SearchableComboBox; import com.sshtools.icongenerator.AwesomeIcon; import com.sshtools.icongenerator.IconBuilder.TextContent; import javafx.beans.binding.Bindings; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.TextFormatter; import javafx.scene.control.TextFormatter.Change; import javafx.scene.control.ToggleGroup; import javafx.scene.control.TreeCell; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.FileChooser.ExtensionFilter; import javafx.stage.Stage; import javafx.util.converter.IntegerStringConverter; import uk.co.bithatch.snake.lib.Key; import uk.co.bithatch.snake.lib.Macro; import uk.co.bithatch.snake.lib.MacroKey; import uk.co.bithatch.snake.lib.MacroKey.State; import uk.co.bithatch.snake.lib.MacroScript; import uk.co.bithatch.snake.lib.MacroSequence; import uk.co.bithatch.snake.lib.MacroURL; import uk.co.bithatch.snake.lib.ValidationException; import uk.co.bithatch.snake.ui.util.Strings; import uk.co.bithatch.snake.widgets.GeneratedIcon; import uk.co.bithatch.snake.widgets.JavaFX; public class Macros extends AbstractDetailsController { public static String textForMapSequence(MacroSequence seq) { return textForInputEvent(seq.getMacroKey()); } protected static String textForMapAction(Macro action) { if (action instanceof MacroKey) return textForInputEvent(((MacroKey) action).getKey()); else if (action instanceof MacroScript) return ((MacroScript) action).getScript(); else { String url = ((MacroURL) action).getUrl(); try { String host = new URL(url).getHost(); if (host == null || host.equals("")) return " "; else return host; } catch (MalformedURLException murle) { return " "; } } } protected static String textForInputEvent(Key k) { String keyName = String.valueOf(k); if (keyName.length() > 3) return Strings.toName(keyName); else { if (keyName.startsWith("BTN_")) { return MessageFormat.format(bundle.getString("button.name"), keyName); } else { return MessageFormat.format(bundle.getString("key.name"), keyName); } } } public static GeneratedIcon iconForMapSequence(MacroSequence seq) { GeneratedIcon icon = new GeneratedIcon(); icon.getStyleClass().add("mapSequence"); icon.setPrefHeight(32); icon.setPrefWidth(32); String keyName = String.valueOf(seq.getMacroKey()); icon.getStyleClass().add("mapSequenceKey"); icon.setText(keyName); if (keyName.length() > 3) icon.setTextContent(TextContent.INITIALS); else icon.setTextContent(TextContent.ORIGINAL); return icon; } public static GeneratedIcon iconForMacro(Macro mkey) { GeneratedIcon icon = new GeneratedIcon(); icon.getStyleClass().add("mapAction"); icon.setPrefHeight(24); icon.setPrefWidth(24); if (mkey instanceof MacroScript) { icon.setIcon(AwesomeIcon.HASHTAG); } else if (mkey instanceof MacroURL) { icon.setIcon(AwesomeIcon.GLOBE); } else { if (((MacroKey) mkey).getState() == State.DOWN) icon.setIcon(AwesomeIcon.ARROW_DOWN); else icon.setIcon(AwesomeIcon.ARROW_UP); } return icon; } private static class MacroListCell extends TreeCell<Object> { @Override public void updateItem(Object item, boolean empty) { super.updateItem(item, empty); if (empty) { setGraphic(null); setText(null); } else { if (item instanceof MacroSequence) { MacroSequence seq = (MacroSequence) item; setGraphic(iconForMapSequence(seq)); setText(textForMapSequence(seq)); } else { Macro macro = (Macro) item; setGraphic(iconForMacro(macro)); if (macro == null) setText("<null>"); else setText(MessageFormat.format(bundle.getString("macroType." + macro.getClass().getSimpleName()), textForMapAction(macro))); } } } } final static ResourceBundle bundle = ResourceBundle.getBundle(Macros.class.getName()); final static Preferences PREFS = Preferences.userNodeForPackage(Macros.class); static List<String> parseQuotedString(String command) { List<String> args = new ArrayList<String>(); boolean escaped = false; boolean quoted = false; StringBuilder word = new StringBuilder(); for (int i = 0; i < command.length(); i++) { char c = command.charAt(i); if (c == '"' && !escaped) { if (quoted) { quoted = false; } else { quoted = true; } } else if (c == '\\' && !escaped) { escaped = true; } else if ((c == ' ' || c == '\n') && !escaped && !quoted) { if (word.length() > 0) { args.add(word.toString()); word.setLength(0); ; } } else { word.append(c); } } if (word.length() > 0) args.add(word.toString()); return args; } @FXML private Hyperlink add; @FXML private Hyperlink delete; @FXML private VBox editor; @FXML private Label error; @FXML private Hyperlink export; @FXML private RadioButton keyMacro; @FXML private VBox keyMacroSection; @FXML private SearchableComboBox<Key> macroKey; @FXML private TreeView<Object> macros; @FXML private ToggleGroup macroType; @FXML private TextField pause; @FXML private TextArea scriptArgs; @FXML private Button scriptBrowse; @FXML private TextField scriptLocation; @FXML private RadioButton scriptMacro; @FXML private VBox scriptMacroSection; @FXML private VBox sequenceEditor; @FXML private SearchableComboBox<Key> simulateKey; @FXML private ComboBox<State> state; @FXML private TextField urlLocation; @FXML private RadioButton urlMacro; @FXML private VBox urlMacroSection; @FXML private Button urlOpen; private ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); private ScheduledFuture<?> task; private Set<MacroSequence> sequencesToSave = new LinkedHashSet<>(); private boolean adjusting = false; protected void error(String key) { error.visibleProperty().set(key != null); if (key == null) { error.visibleProperty().set(false); error.textProperty().set(""); } else { error.visibleProperty().set(true); String txt = bundle.getString(key); error.textProperty().set(bundle.getString("errorIcon") + (txt == null ? "<missing key " + key + ">" : txt)); } } @SuppressWarnings("unchecked") protected <M extends Macro> M getSelectedMacro() { Object sel = macros.getSelectionModel().isEmpty() ? null : macros.getSelectionModel().getSelectedItem().getValue(); if (sel instanceof Macro) return (M) macros.getSelectionModel().getSelectedItem().getValue(); else return null; } protected MacroSequence getSelectedSequence() { Object sel = macros.getSelectionModel().isEmpty() ? null : macros.getSelectionModel().getSelectedItem().getValue(); if (sel instanceof MacroSequence) return (MacroSequence) sel; else if (sel instanceof Macro) return (MacroSequence) macros.getSelectionModel().getSelectedItem().getParent().getValue(); else return null; } protected TreeItem<Object> getSelectedSequenceItem() { TreeItem<Object> sel = macros.getSelectionModel().isEmpty() ? null : macros.getSelectionModel().getSelectedItem(); if (sel != null && sel.getValue() instanceof MacroSequence) return sel; else if (sel != null && sel.getParent().getValue() instanceof MacroSequence) return sel.getParent(); else return null; } @Override protected void onDeviceCleanUp() { if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, "Stopping macros scheduler."); executor.shutdown(); } @Override protected void onSetDeviceDetails() throws Exception { keyMacro.selectedProperty().set(true); urlMacroSection.managedProperty().bind(urlMacroSection.visibleProperty()); urlMacroSection.visibleProperty().bind(urlMacro.selectedProperty()); scriptMacroSection.managedProperty().bind(scriptMacroSection.visibleProperty()); scriptMacroSection.visibleProperty().bind(scriptMacro.selectedProperty()); keyMacroSection.managedProperty().bind(keyMacroSection.visibleProperty()); keyMacroSection.visibleProperty().bind(keyMacro.selectedProperty()); if (context.getLayouts().hasLayout(getDevice())) macroKey.itemsProperty().get().addAll(context.getLayouts().getLayout(getDevice()).getSupportedLegacyKeys()); else macroKey.itemsProperty().get().addAll(getDevice().getSupportedLegacyKeys()); state.itemsProperty().get().addAll(Arrays.asList(State.values())); UnaryOperator<Change> integerFilter = change -> { String newText = change.getControlNewText(); try { Integer.parseInt(newText); return change; } catch(Exception e) { } return null; }; pause.setTextFormatter(new TextFormatter<Integer>(new IntegerStringConverter(), 0, integerFilter)); // TODO this is wrong, should be 'xte' events simulateKey.itemsProperty().get().addAll(getDevice().getSupportedLegacyKeys()); editor.managedProperty().bind(editor.visibleProperty()); urlOpen.disableProperty().bind(Bindings.isEmpty(urlLocation.textProperty())); scriptLocation.textProperty().addListener((e, o, n) -> { if (!adjusting) { var macro = (MacroScript) getSelectedMacro(); macro.setScript(scriptLocation.textProperty().get()); saveMacroSequence(getSelectedSequence()); macros.refresh(); } }); state.getSelectionModel().selectedItemProperty().addListener((e, o, n) -> { if (!adjusting) { var macro = (MacroKey) getSelectedMacro(); if (macro != null) { macro.setState(state.getSelectionModel().getSelectedItem()); saveMacroSequence(getSelectedSequence()); macros.refresh(); } } }); simulateKey.getSelectionModel().selectedItemProperty().addListener((e, o, n) -> { if (!adjusting) { var macro = (MacroKey) getSelectedMacro(); if (macro != null) { macro.setKey(simulateKey.getSelectionModel().getSelectedItem()); saveMacroSequence(getSelectedSequence()); } } }); pause.textProperty().addListener((e, o, n) -> { if (!adjusting) { var macro = (MacroKey) getSelectedMacro(); try { macro.setPrePause(Long.parseLong(pause.textProperty().get())); saveMacroSequence(getSelectedSequence()); } catch (NumberFormatException nfe) { error("invalidPause"); } } }); urlLocation.textProperty().addListener((e, o, n) -> { if (!adjusting) { var macro = (MacroURL) getSelectedMacro(); macro.setUrl(urlLocation.textProperty().get()); saveMacroSequence(getSelectedSequence()); macros.refresh(); } }); scriptArgs.textProperty().addListener((e, o, n) -> { if (!adjusting) { var macro = (MacroScript) getSelectedMacro(); macro.setArgs(parseQuotedString(scriptArgs.textProperty().get())); saveMacroSequence(getSelectedSequence()); macros.refresh(); } }); macroKey.getSelectionModel().selectedItemProperty().addListener((e, o, n) -> { if (!adjusting && n != null) { var macro = getSelectedSequence(); if (macro != null) { if (o != null) getDevice().deleteMacro(o); macro.setMacroKey(n); saveMacroSequence(macro); macros.refresh(); } } }); macros.getSelectionModel().selectedItemProperty().addListener((e, o, n) -> { if (!adjusting) { adjusting = true; try { var macro = getSelectedMacro(); editor.visibleProperty().set(macro != null); if (macro == null) { delete.textProperty().set(bundle.getString("deleteSequence")); } else { delete.textProperty().set(bundle.getString("delete")); } setSequence(getSelectedSequence()); setMacro(macro); setAvailableEditors(); if (macro instanceof MacroURL) urlMacro.selectedProperty().set(true); else if (macro instanceof MacroScript) scriptMacro.selectedProperty().set(true); else keyMacro.selectedProperty().set(true); } finally { adjusting = false; } } }); delete.visibleProperty().set(getSelectedSequence() != null); sequenceEditor.visibleProperty().set(getSelectedSequence() != null); editor.visibleProperty().set(getSelectedMacro() != null); macros.setCellFactory((list) -> { return new MacroListCell(); }); TreeItem<Object> root = new TreeItem<>(); macros.rootProperty().set(root); buildTree(); macros.setShowRoot(false); urlMacro.selectedProperty().addListener((e, o, n) -> { if (!adjusting) { if (urlMacro.selectedProperty().get()) { adjusting = true; try { TreeItem<Object> seqItem = macros.getSelectionModel().getSelectedItem().getParent(); MacroSequence seq = getSelectedSequence(); Macro macro = getSelectedMacro(); MacroURL murl = new MacroURL(); var idx = seq.indexOf(macro); seq.set(idx, murl); TreeItem<Object> newMacroItem = new TreeItem<>(murl); seqItem.getChildren().set(idx, newMacroItem); saveMacroSequence(seq); macros.getSelectionModel().select(newMacroItem); } finally { adjusting = false; } } } }); scriptMacro.selectedProperty().addListener((e, o, n) -> { if (!adjusting) { if (scriptMacro.selectedProperty().get()) { adjusting = true; try { TreeItem<Object> seqItem = macros.getSelectionModel().getSelectedItem().getParent(); MacroSequence seq = getSelectedSequence(); Macro macro = getSelectedMacro(); MacroScript murl = new MacroScript(); var idx = seq.indexOf(macro); seq.set(idx, murl); TreeItem<Object> newMacroItem = new TreeItem<>(murl); seqItem.getChildren().set(idx, newMacroItem); saveMacroSequence(seq); macros.getSelectionModel().select(newMacroItem); } finally { adjusting = false; } } } }); keyMacro.selectedProperty().addListener((e, o, n) -> { if (!adjusting) { if (keyMacro.selectedProperty().get()) { adjusting = true; try { TreeItem<Object> seqItem = macros.getSelectionModel().getSelectedItem().getParent(); MacroSequence seq = getSelectedSequence(); Macro macro = getSelectedMacro(); if (macro != null) { MacroKey murl = new MacroKey(); var idx = seq.indexOf(macro); seq.set(idx, murl); TreeItem<Object> newMacroItem = new TreeItem<>(murl); seqItem.getChildren().set(idx, newMacroItem); saveMacroSequence(seq); macros.getSelectionModel().select(newMacroItem); } } finally { adjusting = false; } } } }); export.visibleProperty().bind(Bindings.isNotEmpty(macros.rootProperty().getValue().getChildren())); } private void buildTree() { var root = macros.rootProperty().get(); for (Map.Entry<Key, MacroSequence> en : getDevice().getMacros().entrySet()) { TreeItem<Object> macroSequence = new TreeItem<>(en.getValue()); for (Macro m : en.getValue()) macroSequence.getChildren().add(new TreeItem<>(m)); root.getChildren().add(macroSequence); macroSequence.setExpanded(en.getValue().size() < 3); } } @FXML void evtAdd() { Map<Key, MacroSequence> existing = getDevice().getMacros(); for (Key k : Key.values()) { if (!existing.containsKey(k)) { MacroSequence m = new MacroSequence(); m.setMacroKey(k); var item = new TreeItem<Object>(m); macros.rootProperty().get().getChildren().add(item); macros.getSelectionModel().select(item); return; } } error("noKeysLeft"); } @FXML void evtAddMacro() { var mk = new MacroKey(); var seq = getSelectedSequence(); seq.add(mk); TreeItem<Object> t = new TreeItem<>(mk); TreeItem<Object> seqItem = getSelectedSequenceItem(); seqItem.setExpanded(true); seqItem.getChildren().add(t); saveMacroSequence(seq); macros.getSelectionModel().select(t); } @FXML void evtDelete() { Macro m = getSelectedMacro(); var seq = getSelectedSequence(); if (m == null) getDevice().deleteMacro(seq.getMacroKey()); else { seq.remove(m); saveMacroSequence(seq); } macros.getSelectionModel().getSelectedItem().getParent().getChildren() .remove(macros.getSelectionModel().getSelectedItem()); setAvailableEditors(); } @FXML void evtExport() { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(bundle.getString("selectExportFile")); var path = PREFS.get("lastExportLocation", System.getProperty("user.dir") + File.separator + "macros.json"); fileChooser.getExtensionFilters().add(new ExtensionFilter(bundle.getString("macroFileExtension"), "*.json")); fileChooser.getExtensionFilters().add(new ExtensionFilter(bundle.getString("allFiles"), "*.*")); JavaFX.selectFilesDir(fileChooser, path); File file = fileChooser.showSaveDialog((Stage) getScene().getWindow()); if (file != null) { PREFS.put("lastExportLocation", file.getAbsolutePath()); try (PrintWriter pw = new PrintWriter(file)) { pw.println(getDevice().exportMacros()); } catch (IOException ioe) { LOG.log(java.lang.System.Logger.Level.ERROR, "Failed to export macros.", ioe); } } } @FXML void evtImport() { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(bundle.getString("selectImportFile")); var path = PREFS.get("lastExportLocation", System.getProperty("user.dir") + File.separator + "macros.json"); fileChooser.getExtensionFilters().add(new ExtensionFilter(bundle.getString("macroFileExtension"), "*.json")); fileChooser.getExtensionFilters().add(new ExtensionFilter(bundle.getString("allFiles"), "*.*")); JavaFX.selectFilesDir(fileChooser, path); File file = fileChooser.showOpenDialog((Stage) getScene().getWindow()); if (file != null) { PREFS.put("lastExportLocation", file.getAbsolutePath()); try { getDevice().importMacros(String.join(" ", Files.readAllLines(file.toPath()))); macros.rootProperty().get().getChildren().clear(); buildTree(); } catch (IOException ioe) { LOG.log(java.lang.System.Logger.Level.ERROR, "Failed to export macros.", ioe); } } } @FXML void evtScriptBrowse() { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(bundle.getString("selectExecutable")); var path = scriptLocation.textProperty().get(); if (path == null || path.equals("")) path = System.getProperty("user.dir"); JavaFX.selectFilesDir(fileChooser, path); File file = fileChooser.showOpenDialog((Stage) getScene().getWindow()); if (file != null) { scriptLocation.textProperty().set(file.getPath()); var macro = (MacroScript) getSelectedMacro(); macro.setScript(scriptLocation.textProperty().get()); saveMacroSequence(getSelectedSequence()); } } @FXML void evtUrlOpen() { context.getHostServices().showDocument(urlLocation.textProperty().get()); } private void saveMacroSequence(MacroSequence mkey) { try { mkey.validate(); if (task != null) { task.cancel(false); } error((String)null); synchronized (sequencesToSave) { sequencesToSave.add(mkey); } task = executor.schedule(() -> { synchronized (sequencesToSave) { try { for (MacroSequence m : sequencesToSave) { getDevice().deleteMacro(m.getMacroKey()); getDevice().addMacro(m); } } catch (Exception e) { e.printStackTrace(); } finally { sequencesToSave.clear(); context.getLegacyMacroStorage().save(); } } }, 1000, TimeUnit.MILLISECONDS); } catch (ValidationException ve) { synchronized (sequencesToSave) { sequencesToSave.remove(mkey); } error(ve.getMessage()); } } private void setAvailableEditors() { var seq = getSelectedSequence(); sequenceEditor.visibleProperty().set(seq != null); delete.visibleProperty().set(seq != null); } private void setMacro(Macro macro) { if (macro != null) { if (macro instanceof MacroKey) { MacroKey macroKey = (MacroKey) macro; simulateKey.getSelectionModel().select(macroKey.getKey()); pause.textProperty().set(String.valueOf(macroKey.getPrePause())); state.getSelectionModel().select(macroKey.getState()); } else if (macro instanceof MacroURL) { MacroURL macroURL = (MacroURL) macro; urlLocation.textProperty().set(macroURL.getUrl()); } else if (macro instanceof MacroScript) { MacroScript macroScript = (MacroScript) macro; scriptLocation.textProperty().set(macroScript.getScript()); if (macroScript.getArgs() == null || macroScript.getArgs().isEmpty()) scriptArgs.textProperty().set(""); else scriptArgs.textProperty().set(String.join("\n", macroScript.getArgs())); } } } private void setSequence(MacroSequence seq) { macroKey.getSelectionModel().select(seq == null ? null : seq.getMacroKey()); } }
21,556
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
WaveOptions.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/WaveOptions.java
package uk.co.bithatch.snake.ui; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Slider; import javafx.scene.input.MouseEvent; import uk.co.bithatch.snake.lib.effects.Wave; import uk.co.bithatch.snake.lib.effects.Wave.Direction; import uk.co.bithatch.snake.ui.effects.WaveEffectHandler; public class WaveOptions extends AbstractBackendEffectController<Wave, WaveEffectHandler> { @FXML private Slider direction; private boolean adjusting = false; @Override protected void onConfigure() throws Exception { direction.valueProperty().addListener((e) -> { if (!adjusting) { getEffectHandler().store(getRegion(), this); } }); } @Override protected void onSetEffect() { Wave effect = getEffect(); adjusting = true; try { direction.valueProperty().set(effect.getDirection().ordinal()); } finally { adjusting = false; } } @FXML void evtBack(ActionEvent evt) { context.pop(); } @FXML void evtBackward(MouseEvent evt) { direction.valueProperty().set(0.0); } @FXML void evtForward(MouseEvent evt) { direction.valueProperty().set(1.0); } public Direction getDirection() { return Direction.values()[(int) direction.getValue()]; } }
1,225
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Changes.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/Changes.java
package uk.co.bithatch.snake.ui; import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.text.MessageFormat; import java.util.Collections; import java.util.ResourceBundle; import java.util.Set; import org.commonmark.node.IndentedCodeBlock; import org.commonmark.node.Node; import org.commonmark.parser.Parser; import org.commonmark.renderer.NodeRenderer; import org.commonmark.renderer.html.HtmlNodeRendererContext; import org.commonmark.renderer.html.HtmlRenderer; import org.commonmark.renderer.html.HtmlRenderer.Builder; import org.commonmark.renderer.html.HtmlWriter; import javafx.animation.FadeTransition; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import javafx.scene.web.WebView; import javafx.util.Duration; import uk.co.bithatch.snake.widgets.JavaFX; public class Changes extends AbstractDeviceController { final static ResourceBundle bundle = ResourceBundle.getBundle(Changes.class.getName()); @FXML private WebView changes; @FXML private Label updatedIcon; @FXML private Label updated; @FXML private HBox updatesContainer; private String html; @Override protected void onConfigure() throws Exception { JavaFX.bindManagedToVisible(updatesContainer); if (html == null) { Parser parser = Parser.builder().build(); File changesFile; File dir = new File(System.getProperty("user.dir")); File pom = new File(dir, "pom.xml"); if (pom.exists()) { changesFile = new File(dir.getParentFile(), "CHANGES.md"); } else { changesFile = new File(dir, "docs" + File.separator + "CHANGES.md"); } if (changesFile.exists()) { Node document = parser.parse(Files.readString(changesFile.toPath(), StandardCharsets.UTF_8)); Builder builder = HtmlRenderer.builder(); HtmlRenderer renderer = builder.build(); html = "<html>"; html += "<head>"; html += "<link rel=\"stylesheet\" href=\"" + context.getConfiguration().getTheme().getResource("Changes.html.css") + "\">"; html += "</head>"; html += "<body>"; html += renderer.render(document); html += "</body></html>"; } else { html = "<html><body>The CHANGES file could not be found.</body></html>"; } } try { changes.getEngine().setUserStyleSheetLocation( context.getConfiguration().getTheme().getResource("Changes.html.css").toExternalForm()); changes.getEngine().loadContent(html); } catch (Exception e) { throw new RuntimeException(e); } if (PlatformService.get().isUpdated()) { FadeTransition anim = new FadeTransition(Duration.seconds(5)); anim.setAutoReverse(true); anim.setCycleCount(FadeTransition.INDEFINITE); anim.setNode(updatesContainer); anim.setFromValue(0.5); anim.setToValue(1); anim.play(); updated.textProperty().set( MessageFormat.format(bundle.getString("updated"), PlatformService.get().getInstalledVersion())); updatesContainer.visibleProperty().set(true); } else updatesContainer.visibleProperty().set(false); } @FXML void evtBack() { context.pop(); } class IndentedCodeBlockNodeRenderer implements NodeRenderer { private final HtmlWriter html; IndentedCodeBlockNodeRenderer(HtmlNodeRendererContext context) { this.html = context.getWriter(); } @Override public Set<Class<? extends Node>> getNodeTypes() { // Return the node types we want to use this renderer for. return Collections.<Class<? extends Node>>singleton(IndentedCodeBlock.class); } @Override public void render(Node node) { // We only handle one type as per getNodeTypes, so we can just cast it here. IndentedCodeBlock codeBlock = (IndentedCodeBlock) node; html.line(); html.tag("pre"); html.text(codeBlock.getLiteral()); html.tag("/pre"); html.line(); } } }
3,818
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
AbstractEffectsControl.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/AbstractEffectsControl.java
package uk.co.bithatch.snake.ui; import java.util.ResourceBundle; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Hyperlink; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.lib.Lit; import uk.co.bithatch.snake.ui.effects.CustomEffectHandler; import uk.co.bithatch.snake.ui.effects.EffectAcquisition; import uk.co.bithatch.snake.ui.effects.EffectAcquisition.EffectChangeListener; import uk.co.bithatch.snake.ui.effects.EffectManager; import uk.co.bithatch.snake.ui.effects.EffectManager.Listener; import uk.co.bithatch.snake.widgets.Direction; import uk.co.bithatch.snake.widgets.JavaFX; public abstract class AbstractEffectsControl extends ControlController implements Listener, EffectChangeListener { @FXML protected Hyperlink customise; @FXML protected Hyperlink addCustom; @FXML protected Hyperlink removeCustom; protected boolean adjustingOverall = false; protected boolean adjustingSingle = false; final static ResourceBundle bundle = ResourceBundle.getBundle(AbstractEffectsControl.class.getName()); @Override protected final void onSetControlDevice() { onBeforeSetEffectsControlDevice(); var device = getDevice(); JavaFX.bindManagedToVisible(addCustom, customise, removeCustom); EffectManager fx = context.getEffectManager(); addCustom.visibleProperty().set(fx.isSupported(getDevice(), CustomEffectHandler.class)); removeCustom.visibleProperty() .set(fx.getRootAcquisition(getDevice()).getEffect(getDevice()) instanceof CustomEffectHandler); rebuildOverallEffects(); rebuildRegions(); setCustomiseState(customise, device, getOverallEffect()); fx.addListener(this); fx.getRootAcquisition(getDevice()).addListener(this); onSetEffectsControlDevice(); } protected void onBeforeSetEffectsControlDevice() { } protected void onSetEffectsControlDevice() { } protected abstract void rebuildRegions(); protected final void rebuildOverallEffects() { adjustingOverall = true; try { onRebuildOverallEffects(); } finally { adjustingOverall = false; } } protected abstract void onRebuildOverallEffects(); @FXML protected final void evtCustomise() { customise(getDevice(), getOverallEffect()); } @FXML protected final void evtRemoveCustom() { Confirm confirm = context.push(Confirm.class, Direction.FADE); confirm.confirm(bundle, "removeCustom", () -> { context.getEffectManager().remove(getOverallEffect()); }, getOverallEffect().getName()); } @FXML protected final void evtAddCustom() { Input confirm = context.push(Input.class, Direction.FADE); confirm.setValidator((l) -> { String name = confirm.inputProperty().get(); boolean available = context.getEffectManager().getEffect(getDevice(), name) == null; l.getStyleClass().clear(); if (available) { l.textProperty().set(""); l.visibleProperty().set(false); } else { l.visibleProperty().set(true); l.textProperty().set(bundle.getString("error.nameAlreadyExists")); l.getStyleClass().add("danger"); } return available; }); confirm.confirm(bundle, "addCustom", () -> { CustomEffectHandler fx = new CustomEffectHandler(confirm.inputProperty().get()); context.getEffectManager().add(getDevice(), fx); context.getEffectManager().getRootAcquisition(getDevice()).activate(getDevice(), fx); }); } @SuppressWarnings("unchecked") protected void customise(Lit region, EffectHandler<?, ?> handler) { AbstractEffectController<?, EffectHandler<?, ?>> c = null; if (handler != null && handler.hasOptions()) { c = (AbstractEffectController<?, EffectHandler<?, ?>>) context.push(handler.getOptionsController(), this, Direction.FROM_RIGHT); try { c.setRegion(region); c.setEffectHandler(handler); } catch (Exception e) { e.printStackTrace(); } } } @Override protected final void onDeviceCleanUp() { EffectAcquisition root = context.getEffectManager().getRootAcquisition(getDevice()); if (root != null) root.removeListener(this); context.getEffectManager().removeListener(this); onEffectsControlCleanUp(); } protected void onEffectsControlCleanUp() { } protected static void setCustomiseState(Node customise, Lit region, EffectHandler<?, ?> selectedItem) { customise.visibleProperty() .set(selectedItem != null && selectedItem.isSupported(region) && selectedItem.hasOptions()); } @Override public final void effectChanged(Lit component, EffectHandler<?, ?> effect) { if (!Platform.isFxApplicationThread()) Platform.runLater(() -> effectChanged(component, effect)); else { if (component instanceof Device) { adjustingOverall = true; try { selectEffect(effect); } finally { adjustingOverall = false; } } } } protected void selectEffect(EffectHandler<?, ?> effect) { selectOverallEffect(effect); setCustomiseState(customise, getDevice(), getOverallEffect()); removeCustom.visibleProperty().set(effect instanceof CustomEffectHandler); rebuildRegions(); } @Override protected final void onChanged(Device device, uk.co.bithatch.snake.lib.Region region) { if (region != null) { /* * If the region is changing, check if the overal effect is now either null * (different effects selected), or an effect handler (all regions have same * effect) */ EffectAcquisition aq = context.getEffectManager().getRootAcquisition(getDevice()); if (aq != null) { EffectHandler<?, ?> handler = aq.getEffect(device); adjustingOverall = true; try { selectEffect(handler); } finally { adjustingOverall = false; } } } onEffectChanged(device, region); } protected void onEffectChanged(Device device, uk.co.bithatch.snake.lib.Region region) { } protected abstract void selectOverallEffect(EffectHandler<?, ?> effect); protected abstract EffectHandler<?, ?> getOverallEffect(); @Override public final void effectRemoved(Device device, EffectHandler<?, ?> effect) { if (!Platform.isFxApplicationThread()) Platform.runLater(() -> effectRemoved(device, effect)); else { rebuildOverallEffects(); rebuildRegions(); } } @Override public final void effectAdded(Device device, EffectHandler<?, ?> effect) { if (!Platform.isFxApplicationThread()) Platform.runLater(() -> effectRemoved(device, effect)); else { rebuildOverallEffects(); rebuildRegions(); } } }
6,430
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
MixerControl.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/MixerControl.java
package uk.co.bithatch.snake.ui; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Control; import javax.sound.sampled.Line; import javax.sound.sampled.Line.Info; import javax.sound.sampled.Mixer; public class MixerControl { public static void main(String[] args) { for(Mixer.Info info : AudioSystem.getMixerInfo()) { System.out.println(String.format("Name: %s, Description: %s, Vendor: %s, Version: %s ", info.getName(), info.getDescription(), info.getVendor(), info.getVersion())); Mixer mixer = AudioSystem.getMixer(info); System.out.println("Controls: "); for(Control control : mixer.getControls()) { System.out.println(" " + control); } System.out.println("Source Line Info: "); for(Info sourceInfo : mixer.getSourceLineInfo()) { System.out.println(" " + sourceInfo); } System.out.println("Target Line Info: "); for(Info targetInfo : mixer.getTargetLineInfo()) { System.out.println(" " + targetInfo); } System.out.println("Target Lines: "); for(Line targetLine : mixer.getTargetLines()) { System.out.println(" " + targetLine); } } } }
1,132
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
AbstractController.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/AbstractController.java
package uk.co.bithatch.snake.ui; import java.lang.System.Logger.Level; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.ResourceBundle; import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.prefs.Preferences; import org.kordamp.ikonli.fontawesome.FontAwesome; import org.kordamp.ikonli.javafx.FontIcon; import javafx.animation.ScaleTransition; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundImage; import javafx.scene.layout.BackgroundPosition; import javafx.scene.layout.BackgroundRepeat; import javafx.scene.layout.BackgroundSize; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import javafx.stage.Stage; import javafx.util.Duration; import uk.co.bithatch.snake.ui.SchedulerManager.Queue; import uk.co.bithatch.snake.ui.util.Strings; public abstract class AbstractController implements Controller { final static System.Logger LOG = System.getLogger(AbstractController.class.getName()); protected App context; protected ResourceBundle resources; protected URL location; protected Scene scene; private static Set<String> shownMessages = new HashSet<>(); @FXML private VBox popupMessages; { if (popupMessages != null) { popupMessages.getStyleClass().add("popupMessages"); popupMessages.getStyleClass().add("padded"); } } @Override public final void initialize(URL location, ResourceBundle resources) { this.location = location; this.resources = resources; onInitialize(); } @Override public final void cleanUp() { onCleanUp(); } @Override public final void configure(Scene scene, App jfxhsClient) { this.scene = scene; this.context = jfxhsClient; try { onConfigure(); } catch (RuntimeException re) { throw re; } catch (Exception e) { throw new IllegalStateException(e); } } public void error(Exception exception) { if (exception == null) clearNotifications(true); else { LOG.log(Level.ERROR, "Error.", exception); String msg = exception.getLocalizedMessage(); notifyMessage(MessagePersistence.EVERYTIME, MessageType.DANGER, msg); } } @Override public void notifyMessage(MessagePersistence persistence, MessageType messageType, String title, String content, int timeout) { String key = Strings.genericHash( messageType.name() + "-" + (title == null ? "none" : title) + "-" + (content == null ? "" : content)); Preferences node = context.getPreferences().node("shownMessages"); if (persistence == MessagePersistence.ONCE_PER_RUNTIME && shownMessages.contains(key)) { return; } else if (persistence == MessagePersistence.ONCE_PER_INSTALL && node.getBoolean(key, false)) { return; } shownMessages.add(key); node.putBoolean(key, true); if (Platform.isFxApplicationThread()) { if (popupMessages == null) LOG.log(Level.WARNING, String.format("%s does not support popups", getClass().getName())); else { popupMessages.getChildren().add(new Message(messageType, title, content, timeout)); } } else Platform.runLater(() -> notifyMessage(persistence, messageType, title, content, timeout)); } @Override public void clearNotifications(MessageType type, boolean immediate) { if (popupMessages == null) return; if (Platform.isFxApplicationThread()) { if (immediate) { for (Node n : new ArrayList<>(popupMessages.getChildren())) { if (type == null || ((Message) n).type == type) { popupMessages.getChildren().remove(n); } } } else { for (Node n : popupMessages.getChildren()) { if (type == null || ((Message) n).type == type) { ((Message) n).close(); } } } } else Platform.runLater(() -> clearNotifications(immediate)); } protected Stage getStage() { return (Stage) scene.getWindow(); } protected Background createHeaderBackground() { return new Background( new BackgroundImage( new Image(context.getConfiguration().getTheme().getResource("fibre.jpg").toExternalForm(), true), BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, new BackgroundSize(100d, 100d, true, true, false, true))); } protected void onConfigure() throws Exception { } protected void onCleanUp() { } protected void onInitialize() { } @Override public Scene getScene() { return scene; } class Message extends BorderPane { private ScheduledFuture<?> task; private MessageType type; Message(MessageType type, String title, String content, int timeout) { this.type = type; getStyleClass().add(type.name().toLowerCase()); getStyleClass().add("spaced"); getStyleClass().add("padded"); getStyleClass().add("popupMessages"); HBox l2 = new HBox(); l2.setAlignment(Pos.CENTER_LEFT); l2.getStyleClass().add("row"); l2.getStyleClass().add("popupMessageContent"); Label l1 = new Label(); HBox.setHgrow(l1, Priority.ALWAYS); l1.setEllipsisString(""); l1.setAlignment(Pos.CENTER); l1.getStyleClass().add("icon"); l1.getStyleClass().add("popupMessageIcon"); l1.graphicProperty().set(new FontIcon(App.BUNDLE.getString("messageType." + type.name()))); l2.getChildren().add(l1); if (title != null) { Label c1 = new Label(); HBox.setHgrow(c1, Priority.ALWAYS); c1.getStyleClass().add("emphasis"); c1.getStyleClass().add("popupMessageTitle"); c1.textProperty().set(title); c1.setAlignment(Pos.CENTER_LEFT); l2.getChildren().add(c1); } if (content != null) { Label c2 = new Label(); c2.textProperty().set(content); c2.getStyleClass().add("popupMessageContent"); c2.setAlignment(Pos.CENTER_LEFT); c2.setWrapText(true); l2.getChildren().add(c2); } Hyperlink l3 = new Hyperlink(); l3.setGraphic(new FontIcon(FontAwesome.CLOSE)); l3.getStyleClass().add("icon"); l3.getStyleClass().add("popupMessageClose"); l3.setAlignment(Pos.CENTER); l3.setOnMouseClicked((e) -> { if (task != null) task.cancel(false); close(); }); setCenter(l2); setRight(l3); if (timeout != 0) task = context.getSchedulerManager().get(Queue.TIMER).schedule(() -> { Platform.runLater(() -> close()); }, timeout, TimeUnit.SECONDS); } void close() { ScaleTransition st = new ScaleTransition(Duration.millis(250), Message.this); st.setFromY(1); st.setToY(0); st.setCycleCount(1); st.onFinishedProperty().set((e2) -> { popupMessages.getChildren().remove(Message.this); }); st.play(); } } }
6,899
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
CustomOptions.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/CustomOptions.java
package uk.co.bithatch.snake.ui; import java.text.MessageFormat; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.ResourceBundle; import java.util.Set; import java.util.prefs.Preferences; import javafx.animation.Transition; import javafx.application.Platform; import javafx.beans.binding.Bindings; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.ListChangeListener; import javafx.fxml.FXML; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.ContextMenu; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.control.MenuItem; import javafx.scene.control.ScrollPane; import javafx.scene.control.SelectionMode; import javafx.scene.control.Slider; import javafx.scene.control.Spinner; import javafx.scene.control.SpinnerValueFactory; import javafx.scene.control.SpinnerValueFactory.IntegerSpinnerValueFactory; import javafx.scene.control.SplitPane; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.effect.Glow; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; import javafx.util.Duration; import uk.co.bithatch.snake.lib.Colors; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.lib.Region; import uk.co.bithatch.snake.lib.animation.AudioDataProvider; import uk.co.bithatch.snake.lib.animation.AudioParameters; import uk.co.bithatch.snake.lib.animation.FramePlayer; import uk.co.bithatch.snake.lib.animation.FramePlayer.FrameListener; import uk.co.bithatch.snake.lib.animation.Interpolation; import uk.co.bithatch.snake.lib.animation.KeyFrame; import uk.co.bithatch.snake.lib.animation.KeyFrame.KeyFrameCellSource; import uk.co.bithatch.snake.lib.animation.KeyFrameCell; import uk.co.bithatch.snake.lib.animation.Sequence; import uk.co.bithatch.snake.lib.layouts.Area; import uk.co.bithatch.snake.lib.layouts.ComponentType; import uk.co.bithatch.snake.lib.layouts.DeviceLayout; import uk.co.bithatch.snake.lib.layouts.DeviceView; import uk.co.bithatch.snake.lib.layouts.IO; import uk.co.bithatch.snake.lib.layouts.MatrixCell; import uk.co.bithatch.snake.lib.layouts.MatrixIO; import uk.co.bithatch.snake.lib.layouts.ViewPosition; import uk.co.bithatch.snake.ui.addons.CustomEffect; import uk.co.bithatch.snake.ui.designer.MatrixView; import uk.co.bithatch.snake.ui.designer.TabbedViewer; import uk.co.bithatch.snake.ui.effects.CustomEffectHandler; import uk.co.bithatch.snake.ui.util.Strings; import uk.co.bithatch.snake.ui.util.Time; import uk.co.bithatch.snake.widgets.ColorBar; import uk.co.bithatch.snake.widgets.Direction; import uk.co.bithatch.snake.widgets.GeneratedIcon; import uk.co.bithatch.snake.widgets.JavaFX; public class CustomOptions extends AbstractEffectController<Sequence, CustomEffectHandler> implements FrameListener { final static ResourceBundle bundle = ResourceBundle.getBundle(CustomOptions.class.getName()); final static String PREF_TIMELINE_DIVIDER = "timelineDivider"; final static String PREF_TIMELINE_VISIBLE = "timelineVisible"; final static Preferences PREFS = Preferences.userNodeForPackage(CustomOptions.class); private static final double MIN_SPEED = 0.001; final static int[] getRGBAverage(DeviceLayout layout, Collection<IO> elements, KeyFrame frame, AudioDataProvider audio) { DeviceView matrixView = null; int[] rgb = new int[3]; int r = 0; for (IO element : elements) { if (element instanceof Area) { if (matrixView == null) matrixView = layout.getViews().get(ViewPosition.MATRIX); Area area = (Area) element; Region.Name region = area.getRegion(); for (IO cell : matrixView.getElements()) { MatrixCell mc = (MatrixCell) cell; if (mc.getRegion() == region) { int[] rr = frame.getCell(mc.getMatrixX(), mc.getMatrixY()).getValues(); rgb[0] += rr[0]; rgb[1] += rr[1]; rgb[2] += rr[2]; r++; } } } else if (element instanceof MatrixIO) { MatrixIO matrixIO = (MatrixIO) element; if (matrixIO.isMatrixLED()) { int[] rr = frame.getCell(matrixIO.getMatrixX(), matrixIO.getMatrixY()).getValues(); rgb[0] += rr[0]; rgb[1] += rr[1]; rgb[2] += rr[2]; r++; } } } if (r == 0) return Colors.COLOR_BLACK; else return new int[] { rgb[0] / r, rgb[1] / r, rgb[2] / r }; } @FXML private Hyperlink addFrame; @FXML private Tab animation; @FXML private ComboBox<KeyFrameCellSource> cellBrightness; @FXML private ComboBox<KeyFrameCellSource> cellHue; @FXML private ComboBox<Interpolation> cellInterpolation; @FXML private ComboBox<KeyFrameCellSource> cellSaturation; @FXML private ColorBar colorBar; @FXML private BorderPane container; @FXML private TabPane customEditorTabs; @FXML private ComboBox<Interpolation> defaultInterpolation; @FXML private Label effectName; @FXML private Hyperlink export; @FXML private Spinner<Integer> fps; @FXML private Label frames; @FXML private Spinner<Double> gain; @FXML private Hyperlink hideTimeline; @FXML private Spinner<Integer> high; @FXML private Spinner<Double> holdKeyFrameFor; @FXML private ComboBox<Interpolation> keyFrameInterpolation; @FXML private Spinner<Integer> keyFrameNumber; @FXML private Tab keyFrameOptions; @FXML private Spinner<Integer> low; @FXML private Hyperlink pause; @FXML private Hyperlink play; @FXML private Slider progress; @FXML private Tab properties; @FXML private Hyperlink removeEffect; @FXML private Hyperlink removeFrame; @FXML private CheckBox repeat; @FXML private Button shiftDown; @FXML private Button shiftLeft; @FXML private Button shiftRight; @FXML private Button shiftUp; @FXML private Hyperlink showTimeline; @FXML private Spinner<Double> speed; @FXML private SplitPane split; @FXML private Hyperlink stop; @FXML private Label time; @FXML private HBox timeline; @FXML private BorderPane timelineContainer; @FXML private ScrollPane timelineScrollPane; private TabbedViewer deviceViewer; private int deviceX; private int deviceY; private boolean keyFrameAdjusting; private IntegerSpinnerValueFactory keyFrameNumberFactory; private Map<KeyFrame, BorderPane> keyFrames = new HashMap<>(); private KeyFrame playingFrame; private boolean timelineHidden; private boolean adjusting; private boolean adjustingProgress; private ObjectProperty<KeyFrame> currentKeyFrame = new SimpleObjectProperty<>(null, "currentKeyFrame"); public ObjectProperty<KeyFrame> currentKeyFrame() { return currentKeyFrame; } @FXML public void evtReset() { KeyFrame f = getCurrentKeyFrame(); List<IO> sel = deviceViewer.getSelectedElements(); if (sel.isEmpty()) { deviceViewer.getSelectedView().getElements(); } for (IO io : sel) { if (io instanceof MatrixIO) { MatrixIO mio = (MatrixIO) io; f.setCell(mio.getMatrixX(), mio.getMatrixY(), new KeyFrameCell(Colors.COLOR_BLACK)); } } deviceViewer.deselectAll(); updateState(); } @Override public void frameUpdate(KeyFrame frame, int[][][] rgb, float fac, long frameNumber) { Platform.runLater(() -> { updateFrame(rgb); rebuildTimestats(); }); } public KeyFrame getCurrentKeyFrame() { return currentKeyFrame.get(); } @Override public void pause(boolean pause) { Platform.runLater(() -> { deviceViewer.setSelectableElements(!pause); updateAvailability(); rebuildTimestats(); }); } @Override public void started(Sequence sequence, Device device) { Platform.runLater(() -> { deviceViewer.setSelectableElements(false); updateAvailability(); rebuildTimestats(); }); } @Override public void stopped() { Platform.runLater(() -> { deviceViewer.setSelectableElements(true); updateAvailability(); rebuildTimestats(); progress.valueProperty().set(0); }); } protected void addFrame(int index) { KeyFrame f = new KeyFrame(); f.setHoldFor(5000); f.setColor(new int[] { 0xff, 0xff, 0xff }, deviceY, deviceX); Sequence seq = getEffectHandler().getSequence(); seq.add(index, f); keyFrameNumberFactory.setMax(seq.size() - 1); rebuildTimeline(); rebuildTimestats(); updateAvailability(); selectFrame(f); saveSequence(); } protected void confirmRemoveFrame(KeyFrame frame, boolean unpause) { CustomEffectHandler fx = getEffectHandler(); Confirm confirm = context.push(Confirm.class, Direction.FADE); confirm.confirm(bundle, "removeFrame", () -> { BorderPane bp = keyFrames.get(frame); JavaFX.fadeHide(bp, 1, (e) -> { timeline.getChildren().remove(bp); Sequence seq = fx.getSequence(); seq.remove(frame); keyFrameNumberFactory.setMax(Math.max(0, seq.size() - 1)); updateAvailability(); rebuildTimestats(); rebuildTimeline(); if (unpause) fx.getPlayer().setPaused(false); }); }, () -> { if (unpause) fx.getPlayer().setPaused(false); }, fx.getSequence().indexOf(frame)); } protected ContextMenu creatContextMenu(KeyFrame frame, Hyperlink button) { ContextMenu menu = new ContextMenu(); // Remove MenuItem remove = new MenuItem(bundle.getString("contextMenuRemove")); remove.onActionProperty().set((e) -> removeFrame(frame)); menu.getItems().add(remove); // Copy MenuItem copy = new MenuItem(bundle.getString("contextMenuCopy")); copy.onActionProperty().set((e) -> { }); menu.getItems().add(copy); // Cut MenuItem cut = new MenuItem(bundle.getString("contextMenuCut")); cut.onActionProperty().set((e) -> { }); menu.getItems().add(cut); // Paste After MenuItem pasteAfter = new MenuItem(bundle.getString("contextMenuPasteAfter")); pasteAfter.onActionProperty().set((e) -> { }); menu.getItems().add(pasteAfter); // Paste Before MenuItem pasteBefore = new MenuItem(bundle.getString("contextMenuPasteBefore")); pasteBefore.onActionProperty().set((e) -> { }); menu.getItems().add(pasteBefore); // Paste Over MenuItem pasteOver = new MenuItem(bundle.getString("contextMenuPasteOver")); pasteOver.onActionProperty().set((e) -> { }); menu.getItems().add(pasteOver); // Add After MenuItem addAfter = new MenuItem(bundle.getString("contextMenuAddAfter")); addAfter.onActionProperty().set((e) -> addFrame(getEffectHandler().getSequence().indexOf(frame) + 1)); menu.getItems().add(addAfter); // Add Before MenuItem addBefore = new MenuItem(bundle.getString("contextMenuAddBefore")); addBefore.onActionProperty().set((e) -> addFrame(getEffectHandler().getSequence().indexOf(frame))); menu.getItems().add(addBefore); button.setOnContextMenuRequested((e) -> { FramePlayer player = getEffectHandler().getPlayer(); remove.disableProperty().set(player.isPlaying()); addAfter.disableProperty().set(player.isPlaying()); addBefore.disableProperty().set(player.isPlaying()); pasteOver.disableProperty().set(player.isPlaying()); pasteBefore.disableProperty().set(player.isPlaying()); pasteAfter.disableProperty().set(player.isPlaying()); cut.disableProperty().set(player.isPlaying()); copy.disableProperty().set(player.isPlaying()); }); return menu; } protected Set<Integer> getSelectedMatrixRows() { Set<Integer> rows = new HashSet<>(); for (MatrixIO el : MatrixView.expandMatrixElements(deviceViewer.getLayout(), deviceViewer.getSelectedElements())) { rows.add(el.getMatrixY()); } return rows; } protected Set<Integer> getSelectedMatrixColumns() { Set<Integer> rows = new HashSet<>(); for (MatrixIO el : MatrixView.expandMatrixElements(deviceViewer.getLayout(), deviceViewer.getSelectedElements())) { rows.add(el.getMatrixX()); } return rows; } @Override protected void onDeviceCleanUp() { CustomEffectHandler fx = getEffectHandler(); FramePlayer player = fx.getPlayer(); if (context.getEffectManager().getDeviceEffectHandlers(getDevice()).containsValue(fx)) { fx.activate(getDevice()); } player.removeListener(this); deviceViewer.cleanUp(); } @Override protected void onSetEffectDevice() { int[] dim = getDevice().getMatrixSize(); deviceY = dim[0]; deviceX = dim[1]; for (Interpolation ip : Interpolation.interpolations()) { if (!ip.equals(Interpolation.sequence) && !ip.equals(Interpolation.keyframe)) defaultInterpolation.itemsProperty().get().add(ip); if (!ip.equals(Interpolation.keyframe)) keyFrameInterpolation.itemsProperty().get().add(ip); if (!ip.equals(Interpolation.sequence)) cellInterpolation.itemsProperty().get().add(ip); } deviceViewer = new TabbedViewer(context, getDevice()); container.setCenter(deviceViewer); deviceViewer.setReadOnly(true); deviceViewer.setEnabledTypes(Arrays.asList(ComponentType.LED, ComponentType.AREA)); deviceViewer.setSelectionMode(SelectionMode.MULTIPLE); deviceViewer.setSelectableElements(true); deviceViewer.setLayout(context.getLayouts().getLayout(getDevice())); deviceViewer.getKeySelectionModel().getSelectedItems().addListener(new ListChangeListener<>() { @Override public void onChanged(Change<? extends IO> c) { updateSelection(); updateAvailability(); } }); timelineContainer.managedProperty().bind(timelineContainer.visibleProperty()); hideTimeline.managedProperty().bind(hideTimeline.visibleProperty()); hideTimeline.visibleProperty().bind(timelineContainer.visibleProperty()); showTimeline.managedProperty().bind(showTimeline.visibleProperty()); showTimeline.visibleProperty().bind(Bindings.not(timelineContainer.visibleProperty())); cellHue.getItems().addAll(KeyFrameCellSource.values()); cellSaturation.getItems().addAll(KeyFrameCellSource.values()); cellBrightness.getItems().addAll(KeyFrameCellSource.values()); cellHue.getSelectionModel().selectedItemProperty().addListener((e, o, n) -> { if (!adjusting) { setSelectedTo(colorBar.getColor(), n, 0); } }); cellSaturation.getSelectionModel().selectedItemProperty().addListener((e, o, n) -> { if (!adjusting) setSelectedTo(colorBar.getColor(), n, 1); }); cellBrightness.getSelectionModel().selectedItemProperty().addListener((e, o, n) -> { if (!adjusting) setSelectedTo(colorBar.getColor(), n, 2); }); } @Override protected void onSetEffectHandler() { CustomEffectHandler effect = getEffectHandler(); FramePlayer player = effect.getPlayer(); deviceViewer.setSelectableElements(!player.isActive()); effectName.textProperty().set(effect.getDisplayName()); keyFrameNumberFactory = new SpinnerValueFactory.IntegerSpinnerValueFactory(0, Math.max(0, effect.getSequence().size() - 1), 1, 1); keyFrameNumber.setValueFactory(keyFrameNumberFactory); keyFrameNumber.valueProperty().addListener((e) -> { if (!keyFrameAdjusting) selectFrame(effect.getSequence().get(keyFrameNumber.valueProperty().get())); }); speed.setValueFactory(new SpinnerValueFactory.DoubleSpinnerValueFactory(MIN_SPEED, 500, 1, 1)); speed.valueProperty().addListener((e) -> { if (speed.valueProperty().get() < MIN_SPEED) { speed.getValueFactory().setValue(MIN_SPEED); } else { effect.getSequence().setSpeed(speed.valueProperty().get().floatValue()); rebuildTimestats(); saveSequence(); } }); fps.setValueFactory( new SpinnerValueFactory.IntegerSpinnerValueFactory(1, 50, effect.getSequence().getFps(), 1)); fps.valueProperty().addListener((e) -> { effect.getSequence().setFps(fps.valueProperty().get()); rebuildTimestats(); saveSequence(); }); low.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 255, effect.getSequence().getAudioParameters() == null ? 0 : effect.getSequence().getAudioParameters().getLow(), 1)); low.valueProperty().addListener((e, o, n) -> { if (!adjusting) setSelectedAudioLow(n); }); high.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 255, effect.getSequence().getAudioParameters() == null ? 255 : effect.getSequence().getAudioParameters().getHigh(), 1)); high.valueProperty().addListener((e, o, n) -> { if (!adjusting) setSelectedAudioHigh(n); }); gain.setValueFactory(new SpinnerValueFactory.DoubleSpinnerValueFactory(0, 20, effect.getSequence().getAudioParameters() == null ? 1.0 : effect.getSequence().getAudioParameters().getGain(), 0.1)); gain.valueProperty().addListener((e, o, n) -> { if (!adjusting) setSelectedAudioGain(n.floatValue()); }); repeat.selectedProperty().set(effect.getSequence().isRepeat()); defaultInterpolation.selectionModelProperty().get().select(effect.getSequence().getInterpolation()); keyFrameInterpolation.selectionModelProperty().addListener((e) -> { if (!keyFrameAdjusting) { getSelectedFrame().setInterpolation(keyFrameInterpolation.getSelectionModel().getSelectedItem()); saveSequence(); } }); holdKeyFrameFor.setValueFactory(new SpinnerValueFactory.DoubleSpinnerValueFactory(0, 5000, 1, 1)); holdKeyFrameFor.valueProperty().addListener((e) -> { if (!keyFrameAdjusting) { getSelectedFrame().setHoldFor((long) (holdKeyFrameFor.getValue() * 1000.0)); saveSequence(); } }); currentKeyFrame.addListener((e, o, n) -> { updateSelection(); }); colorBar.colorProperty().addListener((e, o, n) -> { if (!adjusting) setSelectedTo(n); }); cellInterpolation.getSelectionModel().selectedItemProperty() .addListener((e, o, n) -> setSelectedToInterpolation(n)); rebuildTimeline(); updateAvailability(); rebuildTimestats(); player.addListener(this); double pos = PREFS.getDouble(PREF_TIMELINE_DIVIDER, -1); boolean vis = PREFS.getBoolean(PREF_TIMELINE_VISIBLE, true); split.getDividers().get(0).positionProperty().addListener((e, o, n) -> { if (timelineContainer.visibleProperty().get()) { PREFS.putDouble(PREF_TIMELINE_DIVIDER, split.getDividerPositions()[0]); } else if (timelineHidden && n.floatValue() > 1) { evtShowTimeline(); } }); if (vis) { split.setDividerPositions(pos == -1 ? 0.75 : pos); } else { timelineHidden = true; timelineContainer.visibleProperty().set(false); split.setDividerPositions(1); } progress.valueProperty().addListener((e) -> { if (!adjustingProgress) { try { adjustingProgress = true; long t = (long) (progress.valueProperty().get() * 1000.0); if (player.isPaused()) { player.setTimeElapsed(t); } else { KeyFrame f = effect.getSequence().getFrameAt(t); if (!player.isPlaying()) updateKeyFrameConfiguration(f); updateFrame(f.getRGBFrame(context.getAudioManager())); } } finally { adjustingProgress = false; } } }); } protected void removeFrame(KeyFrame frame) { FramePlayer player = getEffectHandler().getPlayer(); boolean unpause = false; if (player.isPlaying() && !player.isPaused()) { player.setPaused(true); unpause = true; } confirmRemoveFrame(frame, unpause); } protected void saveSequence() { getEffectHandler().store(getDevice(), this); } protected void selectFrame(KeyFrame frame) { FramePlayer player = getEffectHandler().getPlayer(); if (player.isPlaying()) player.setTimeElapsed(frame.getIndex()); progress.valueProperty().set((double) frame.getIndex() / 1000.0); updateKeyFrameConfiguration(frame); rebuildTimestats(); } protected void setCurrentKeyFrame(KeyFrame selection) { this.currentKeyFrame.set(selection); } protected void setSelectedAudioGain(float gain) { Sequence seq = getEffectHandler().getSequence(); KeyFrame kf = getSelectedFrame(); AudioParameters audio = seq.getAudioParameters(); if (audio != null && audio.getLow() == 0 && audio.getHigh() == 255 && gain == 1) { /* So we don't export default parameters */ seq.setAudioParameters(null); } else if (gain != 1) { if (audio == null) { audio = new AudioParameters(); seq.setAudioParameters(audio); } audio.setGain(gain); } deviceViewer.updateFromMatrix(kf.getRGBFrame(context.getAudioManager())); updateState(); } protected void setSelectedAudioHigh(int high) { Sequence seq = getEffectHandler().getSequence(); KeyFrame kf = getSelectedFrame(); AudioParameters audio = seq.getAudioParameters(); if (audio != null && audio.getLow() == 0 && audio.getGain() == 1 && high == 255) { /* So we don't export default parameters */ seq.setAudioParameters(null); } else if (high != 255) { if (audio == null) { audio = new AudioParameters(); seq.setAudioParameters(audio); } audio.setHigh(high); } deviceViewer.updateFromMatrix(kf.getRGBFrame(context.getAudioManager())); updateState(); } protected void setSelectedAudioLow(int low) { Sequence seq = getEffectHandler().getSequence(); KeyFrame kf = getSelectedFrame(); AudioParameters audio = seq.getAudioParameters(); if (audio != null && audio.getHigh() == 255 && audio.getGain() == 1 && low == 0) { /* So we don't export default parameters */ seq.setAudioParameters(null); } else if (low != 0) { if (audio == null) { audio = new AudioParameters(); seq.setAudioParameters(audio); } audio.setLow(low); } deviceViewer.updateFromMatrix(kf.getRGBFrame(context.getAudioManager())); updateState(); } protected void setSelectedTo(Color col) { int[] rrgb = JavaFX.toRGB(col); KeyFrame kf = getSelectedFrame(); for (MatrixIO el : MatrixView.expandMatrixElements(deviceViewer.getLayout(), deviceViewer.getSelectedElements())) { kf.setRGB(el.getMatrixX(), el.getMatrixY(), rrgb); } colorBar.setColor(col); deviceViewer.updateFromMatrix(kf.getRGBFrame(context.getAudioManager())); updateState(); } protected void setSelectedTo(Color col, KeyFrameCellSource source, int index) { KeyFrame kf = getSelectedFrame(); for (MatrixIO el : MatrixView.expandMatrixElements(deviceViewer.getLayout(), deviceViewer.getSelectedElements())) { KeyFrameCell kfc = kf.getCell(el.getMatrixX(), el.getMatrixY()); kfc.getSources()[index] = source; kfc.setValues(JavaFX.toRGB(col)); } deviceViewer.updateFromMatrix(kf.getRGBFrame(context.getAudioManager())); updateState(); } protected void setSelectedToInterpolation(Interpolation n) { if (n != null) { KeyFrame kf = getSelectedFrame(); for (MatrixIO el : MatrixView.expandMatrixElements(deviceViewer.getLayout(), deviceViewer.getSelectedElements())) { kf.getCell(el.getMatrixX(), el.getMatrixY()).setInterpolation(n); } deviceViewer.updateFromMatrix(kf.getRGBFrame(context.getAudioManager())); updateState(); } } protected void updateFrame(int[][][] rgb) { deviceViewer.updateFromMatrix(rgb); } protected void updateKeyFrameConfiguration(KeyFrame frame) { keyFrameAdjusting = true; try { currentKeyFrame.set(frame); keyFrameNumber.valueFactoryProperty().get().setValue(frame.getSequence().indexOf(frame)); keyFrameInterpolation.getSelectionModel().select(frame.getInterpolation()); holdKeyFrameFor.getValueFactory().valueProperty().set((double) frame.getHoldFor() / 1000); } finally { keyFrameAdjusting = false; } } protected void updateState() { updateMatrix(); updateAvailability(); updateSelection(); } GeneratedIcon buildFrameIcon(KeyFrame frame) { GeneratedIcon gi = new GeneratedIcon(); gi.setPrefHeight(64); gi.setPrefWidth(64); int[] rgb = frame.getOverallColor(context.getAudioManager()); gi.getStyleClass().add("keyframe-button"); gi.setStyle("-icon-color: " + Colors.toHex(rgb)); gi.setText(Time.formatTime(frame.getIndex())); gi.setFontSize(10); return gi; } @FXML void evtAddFrame() { addFrame(getEffectHandler().getSequence().size()); } @FXML void evtBack() { context.pop(); } @FXML void evtDefaultInterpolation() { getEffectHandler().getSequence().setInterpolation(defaultInterpolation.getValue()); } @FXML void evtExport() { CustomEffectHandler effect = getEffectHandler(); Sequence sequence = effect.getSequence(); CustomEffect addOn = new CustomEffect(Strings.toId(effect.getName())); addOn.setName(effect.getName()); addOn.setDescription(MessageFormat.format(bundle.getString("addOnTemplate.description"), sequence.getTotalFrames(), Time.formatTime(sequence.getTotalLength()), getDevice().getName())); addOn.setSequence(effect.getSequence()); Export confirm = context.push(Export.class, Direction.FADE); confirm.export(addOn, bundle, "exportEffect", effect.getName()); } @FXML void evtHideTimeline() { PREFS.putDouble(PREF_TIMELINE_DIVIDER, split.getDividerPositions()[0]); timelineContainer.visibleProperty().set(false); PREFS.putBoolean(PREF_TIMELINE_VISIBLE, false); double pos = split.getDividerPositions()[0]; Transition slideTransition = new Transition() { { setCycleDuration(Duration.millis(200)); } @Override protected void interpolate(double frac) { split.setDividerPositions(pos + ((1f - pos) * frac)); } }; slideTransition.onFinishedProperty().set((e) -> { Platform.runLater(() -> timelineHidden = true); }); slideTransition.setAutoReverse(false); slideTransition.setCycleCount(1); slideTransition.play(); } @FXML void evtKeyFrameInterpolation() { getSelectedFrame().setInterpolation(keyFrameInterpolation.getValue()); } @FXML void evtNone() { if (!adjusting) setSelectedTo(Color.BLACK); } @FXML void evtPause() { getEffectHandler().getPlayer().setPaused(!getEffectHandler().getPlayer().isPaused()); } @FXML void evtPlay() { getEffectHandler().getPlayer().play(); } @FXML void evtRemoveEffect() { Confirm confirm = context.push(Confirm.class, Direction.FADE); confirm.confirm(bundle, "removeEffect", () -> { context.getEffectManager().remove(getEffectHandler()); context.pop(); }, getEffectHandler().getName()); } @FXML void evtRemoveFrame() { KeyFrame frame = getSelectedFrame(); removeFrame(frame); } @FXML void evtRepeat() { getEffectHandler().getSequence().setRepeat(repeat.selectedProperty().get()); rebuildTimeline(); saveSequence(); } @FXML void evtSelectAll() { deviceViewer.selectAll(); updateSelection(); updateAvailability(); } @FXML void evtShiftDown() { KeyFrame f = getCurrentKeyFrame(); for (Integer x : getSelectedMatrixRows()) { KeyFrameCell endCell = null, cell = null, otherCell = null; for (int y = deviceY - 1; y >= 0; y--) { cell = f.getCell(x, y); if (endCell == null) { endCell = new KeyFrameCell(cell); } otherCell = f.getCell(x - 1, y); cell.copyFrom(otherCell); f.setCell(x, y, cell); } cell = f.getCell(x, 0); cell.copyFrom(endCell); f.setCell(x, 0, cell); } deviceViewer.updateFromMatrix(f.getRGBFrame(context.getAudioManager())); updateState(); } @FXML void evtShiftLeft() { KeyFrame f = getCurrentKeyFrame(); for (Integer y : getSelectedMatrixRows()) { KeyFrameCell endCell = null, cell = null, otherCell = null; for (int x = 0; x < deviceX - 1; x++) { cell = f.getCell(x, y); if (endCell == null) { endCell = new KeyFrameCell(cell); } otherCell = f.getCell(x + 1, y); cell.copyFrom(otherCell); f.setCell(x, y, cell); } cell = f.getCell(deviceX - 1, y); cell.copyFrom(endCell); f.setCell(deviceX - 1, y, cell); } deviceViewer.updateFromMatrix(f.getRGBFrame(context.getAudioManager())); updateState(); } @FXML void evtShiftRight() { KeyFrame f = getCurrentKeyFrame(); for (Integer y : getSelectedMatrixRows()) { KeyFrameCell endCell = null, cell = null, otherCell = null; for (int x = deviceX - 1; x > 0; x--) { cell = f.getCell(x, y); if (endCell == null) { endCell = new KeyFrameCell(cell); } otherCell = f.getCell(x - 1, y); cell.copyFrom(otherCell); f.setCell(x, y, cell); } cell = f.getCell(0, y); cell.copyFrom(endCell); f.setCell(0, y, cell); } deviceViewer.updateFromMatrix(f.getRGBFrame(context.getAudioManager())); updateState(); } @FXML void evtShiftUp() { KeyFrame f = getCurrentKeyFrame(); for (Integer x : getSelectedMatrixRows()) { KeyFrameCell endCell = null, cell = null, otherCell = null; for (int y = 0; y < deviceY - 1; y++) { cell = f.getCell(x, y); if (endCell == null) { endCell = new KeyFrameCell(cell); } otherCell = f.getCell(x + 1, y); cell.copyFrom(otherCell); f.setCell(x, y, cell); } cell = f.getCell(x, deviceY - 1); cell.copyFrom(endCell); f.setCell(x, deviceY - 1, cell); } deviceViewer.updateFromMatrix(f.getRGBFrame(context.getAudioManager())); updateState(); } @FXML void evtShowTimeline() { timelineHidden = false; PREFS.putBoolean(PREF_TIMELINE_VISIBLE, true); double pos = PREFS.getDouble(PREF_TIMELINE_DIVIDER, 0.75); Transition slideTransition = new Transition() { { setCycleDuration(Duration.millis(200)); } @Override protected void interpolate(double frac) { double p = 1 - ((1 - pos) * frac); split.setDividerPositions(p); } }; slideTransition.onFinishedProperty().set((e) -> timelineContainer.visibleProperty().set(true)); slideTransition.setAutoReverse(false); slideTransition.setCycleCount(1); slideTransition.play(); } @FXML void evtStop() { FramePlayer player = getEffectHandler().getPlayer(); if (player.isPlaying()) { player.stop(); } } BorderPane frameButton(KeyFrame frame, boolean last) { Node icon = buildFrameIcon(frame); Hyperlink button = new Hyperlink(); button.onActionProperty().set((e) -> { selectFrame(frame); }); button.setAlignment(Pos.CENTER); button.setGraphic(icon); ContextMenu menu = creatContextMenu(frame, button); button.contextMenuProperty().set(menu); Spinner<Double> holdFor = new Spinner<>(0, 9999, (double) frame.getHoldFor() / 1000.0, 1); holdFor.promptTextProperty().set(null); holdFor.getStyleClass().add("small"); holdFor.editableProperty().set(true); holdFor.prefWidth(100); holdFor.valueProperty().addListener((e) -> { frame.setHoldFor((long) ((double) holdFor.valueProperty().get() * 1000.0)); rebuildTimestats(); }); Label arrow = new Label(last ? (getEffectHandler().getSequence().isRepeat() ? "\uf01e" : "\uf28d") : "\uf061"); arrow.getStyleClass().add("icon"); BorderPane.setAlignment(arrow, Pos.CENTER); BorderPane h = new BorderPane(); h.setCenter(button); // h.setBottom(holdFor); h.setRight(arrow); return h; } KeyFrame getSelectedFrame() { return getEffectHandler().getSequence().getFrameAt((long) (progress.valueProperty().doubleValue() * 1000.0)); } void rebuildTimeline() { timeline.getChildren().clear(); keyFrames.clear(); Sequence seq = getEffectHandler().getSequence(); for (int i = 0; i < seq.size(); i++) { KeyFrame keyFrame = seq.get(i); BorderPane fb = frameButton(keyFrame, i == seq.size() - 1); keyFrames.put(keyFrame, fb); timeline.getChildren().add(fb); } rebuildTimestats(); timeline.getChildren().get(0).requestFocus(); } void rebuildTimestats() { CustomEffectHandler fx = getEffectHandler(); Sequence seq = fx.getSequence(); FramePlayer player = fx.getPlayer(); long totalLength = seq.getTotalLength(); long totalFrames = seq.getTotalFrames(); long frameNumber; long frameTime; if (player.isActive()) { frameNumber = player.getFrameNumber(); frameTime = player.getTimeElapsed(); if (!adjustingProgress) { try { adjustingProgress = true; progress.valueProperty().set((double) player.getTimeElapsed() / 1000.0); } finally { adjustingProgress = false; } } KeyFrame f = player.getFrame(); if (!Objects.equals(playingFrame, f)) { playingFrame = f; updateKeyFrameConfiguration(playingFrame); for (Map.Entry<KeyFrame, BorderPane> bp : keyFrames.entrySet()) { if (bp.getKey().equals(playingFrame)) { double x = bp.getValue().layoutXProperty().get(); double scrollWidth = Math.max(timelineScrollPane.getViewportBounds().getWidth(), timeline.prefWidth(100) - timelineScrollPane.getViewportBounds().getWidth()); double newPos = x / scrollWidth; timelineScrollPane.setHvalue(newPos); bp.getValue().setEffect(new Glow(0.8)); } else bp.getValue().setEffect(null); } } } else { if (playingFrame != null) { timelineScrollPane.setHvalue(0); for (BorderPane bp : keyFrames.values()) bp.setEffect(null); playingFrame = null; } frameTime = (long) (progress.valueProperty().doubleValue() * 1000.0); KeyFrame frameAt = seq.getFrameAt(frameTime); frameNumber = frameAt.getStartFrame(); } frames.textProperty().set(MessageFormat.format(bundle.getString("frames"), frameNumber, totalFrames)); time.textProperty().set(MessageFormat.format(bundle.getString("time"), Time.formatTime(frameTime), Time.formatTime(totalLength))); progress.maxProperty().set((double) totalLength / 1000.0); } void updateFrameInTimeline() { KeyFrame f = getSelectedFrame(); BorderPane bp = keyFrames.get(f); Hyperlink c = (Hyperlink) bp.getCenter(); c.setGraphic(buildFrameIcon(f)); } void updateMatrix() { updateFrameInTimeline(); saveSequence(); getEffectHandler().update(getDevice()); } void updateSelection() { adjusting = true; try { List<IO> sel = deviceViewer.getSelectedElements(); if (sel.isEmpty()) { cellInterpolation.setDisable(true); cellHue.setDisable(true); cellSaturation.setDisable(true); cellBrightness.setDisable(true); colorBar.disableProperty().set(true); } else { cellInterpolation.setDisable(false); cellHue.setDisable(false); cellSaturation.setDisable(false); cellBrightness.setDisable(false); KeyFrame frame = getSelectedFrame(); Color col = JavaFX .toColor(getRGBAverage(deviceViewer.getLayout(), sel, frame, context.getAudioManager())); KeyFrameCellSource thisHueSrc = null; KeyFrameCellSource thisSaturationSrc = null; KeyFrameCellSource thisBrightnessSrc = null; Interpolation thisInterpol = null; for (IO io : sel) { MatrixIO mio = (MatrixIO) io; KeyFrameCell keyFrameCell = frame.getCell(mio.getMatrixX(), mio.getMatrixY()); if (thisHueSrc == null || thisHueSrc != keyFrameCell.getSources()[0]) thisHueSrc = keyFrameCell.getSources()[0]; if (thisSaturationSrc == null || thisSaturationSrc != keyFrameCell.getSources()[1]) thisSaturationSrc = keyFrameCell.getSources()[1]; if (thisBrightnessSrc == null || thisBrightnessSrc != keyFrameCell.getSources()[2]) thisBrightnessSrc = keyFrameCell.getSources()[2]; if (thisInterpol == null || thisInterpol != keyFrameCell.getInterpolation()) thisInterpol = keyFrameCell.getInterpolation(); } colorBar.disableProperty() .set(thisHueSrc != KeyFrameCellSource.COLOR && thisSaturationSrc != KeyFrameCellSource.COLOR && thisBrightnessSrc != KeyFrameCellSource.COLOR); cellHue.getSelectionModel().select(thisHueSrc); cellSaturation.getSelectionModel().select(thisSaturationSrc); cellBrightness.getSelectionModel().select(thisBrightnessSrc); cellInterpolation.getSelectionModel().select(thisInterpol); colorBar.setColor(col); } } finally { adjusting = false; } } private void updateAvailability() { FramePlayer player = getEffectHandler().getPlayer(); play.disableProperty().set(player.isPlaying()); stop.disableProperty().set(!player.isPlaying()); pause.disableProperty().set(!player.isPlaying()); progress.disableProperty().set(player.isPlaying() && !player.isPaused()); progress.onMouseReleasedProperty().set((e) -> { if (!player.isPlaying()) { KeyFrame frame = getEffectHandler().getSequence() .getFrameAt((long) (progress.valueProperty().get() * 1000.0)); progress.valueProperty().set((double) frame.getIndex() / 1000.0); } }); addFrame.disableProperty().set(player.isPlaying()); removeFrame.disableProperty().set(player.isPlaying() || player.getSequence().size() < 2); keyFrameInterpolation.disableProperty().set(player.isPlaying()); holdKeyFrameFor.disableProperty().set(player.isPlaying()); removeEffect.disableProperty().set(player.isPlaying()); List<IO> sel = deviceViewer.getSelectedElements(); shiftLeft.disableProperty().set(player.isPlaying() || sel.size() == 0 || deviceX < 2); shiftRight.disableProperty().set(player.isPlaying() || sel.size() == 0 || deviceX < 2); shiftUp.disableProperty().set(player.isPlaying() || sel.size() == 0 || deviceY < 2); shiftDown.disableProperty().set(player.isPlaying() || sel.size() == 0 || deviceY < 2); } }
36,821
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Input.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/Input.java
package uk.co.bithatch.snake.ui; import java.text.MessageFormat; import java.util.ResourceBundle; import javafx.beans.property.StringProperty; import javafx.fxml.FXML; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.control.TextField; public class Input extends AbstractController implements Modal { public interface Validator { boolean validate(Label errorLabel); } @FXML private Hyperlink cancel; @FXML private Hyperlink confirm; @FXML private Label description; @FXML private Label error; @FXML private TextField input; private Runnable onCancel; private Runnable onConfirm; @FXML private Label title; private Validator validator; public void confirm(ResourceBundle bundle, String prefix, Runnable onConfirm, Runnable onCancel, String... args) { title.textProperty().set(MessageFormat.format(bundle.getString(prefix + ".title"), (Object[]) args)); description.textProperty() .set(MessageFormat.format(bundle.getString(prefix + ".description"), (Object[]) args)); confirm.textProperty().set(MessageFormat.format(bundle.getString(prefix + ".confirm"), (Object[]) args)); cancel.textProperty().set(MessageFormat.format(bundle.getString(prefix + ".cancel"), (Object[]) args)); this.onConfirm = onConfirm; this.onCancel = onCancel; input.requestFocus(); input.textProperty().addListener((e) -> validate()); input.onActionProperty().set((e) -> { if (!confirm.disabledProperty().get()) confirm(); }); } public Hyperlink getCancel() { return cancel; } public Hyperlink getConfirm() { return confirm; } public void confirm(ResourceBundle bundle, String prefix, Runnable onConfirm, String... args) { confirm(bundle, prefix, onConfirm, null, args); } public Validator getValidator() { return validator; } public StringProperty inputProperty() { return input.textProperty(); } public void setValidator(Validator validator) { this.validator = validator; } protected void validate() { if (validator != null) { confirm.disableProperty().set(!validator.validate(error)); } } void confirm() { context.pop(); onConfirm.run(); } @FXML void evtCancel() { context.pop(); if (onCancel != null) onCancel.run(); } @FXML void evtConfirm() { confirm(); } }
2,310
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
StarlightOptions.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/StarlightOptions.java
package uk.co.bithatch.snake.ui; import javafx.beans.binding.Bindings; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.Slider; import javafx.scene.control.ToggleGroup; import uk.co.bithatch.snake.lib.Capability; import uk.co.bithatch.snake.lib.effects.Starlight; import uk.co.bithatch.snake.lib.effects.Starlight.Mode; import uk.co.bithatch.snake.ui.effects.StarlightEffectHandler; import uk.co.bithatch.snake.widgets.ColorBar; import uk.co.bithatch.snake.widgets.Direction; import uk.co.bithatch.snake.widgets.JavaFX; public class StarlightOptions extends AbstractBackendEffectController<Starlight, StarlightEffectHandler> { @FXML private ColorBar color; @FXML private ColorBar color1; @FXML private ColorBar color2; @FXML private Label colorLabel; @FXML private Label color1Label; @FXML private Label color2Label; @FXML private RadioButton single; @FXML private RadioButton dual; @FXML private RadioButton random; @FXML private Slider speed; @FXML private ToggleGroup mode; private boolean adjusting = false; public int getSpeed() { return (int) speed.valueProperty().get(); } public Mode getMode() { if (single.selectedProperty().get()) return Mode.SINGLE; else if (dual.selectedProperty().get()) return Mode.DUAL; else return Mode.RANDOM; } public int[] getColor() { return JavaFX.toRGB(color.getColor()); } public int[] getColor1() { return JavaFX.toRGB(color1.getColor()); } public int[] getColor2() { return JavaFX.toRGB(color2.getColor()); } protected void update() { if (!adjusting) getEffectHandler().store(getRegion(), this); } @Override protected void onConfigure() throws Exception { colorLabel.managedProperty().bind(colorLabel.visibleProperty()); color1Label.managedProperty().bind(color1Label.visibleProperty()); color2Label.managedProperty().bind(color2Label.visibleProperty()); random.managedProperty().bind(random.visibleProperty()); single.managedProperty().bind(single.visibleProperty()); dual.managedProperty().bind(dual.visibleProperty()); color.managedProperty().bind(color.visibleProperty()); colorLabel.visibleProperty().bind(single.visibleProperty()); color1Label.visibleProperty().bind(color1.visibleProperty()); color2Label.visibleProperty().bind(color2.visibleProperty()); colorLabel.setLabelFor(color); color1Label.setLabelFor(color1); color2Label.setLabelFor(color2); color.disableProperty().bind(Bindings.not(single.selectedProperty())); color1.disableProperty().bind(Bindings.not(dual.selectedProperty())); color2.disableProperty().bind(Bindings.not(dual.selectedProperty())); color.visibleProperty().bind(single.visibleProperty()); color1.visibleProperty().bind(dual.visibleProperty()); color2.visibleProperty().bind(dual.visibleProperty()); dual.selectedProperty().addListener((e) -> { if (dual.isSelected()) update(); }); single.selectedProperty().addListener((e) -> { if (single.isSelected()) update(); }); random.selectedProperty().addListener((e) -> { if (random.isSelected()) update(); }); color.colorProperty().addListener((e) -> update()); color1.colorProperty().addListener((e) -> update()); color2.colorProperty().addListener((e) -> update()); speed.valueProperty().addListener((e) -> { update(); }); } @Override protected void onSetEffect() { Starlight effect = getEffect(); adjusting = true; try { switch (effect.getMode()) { case DUAL: dual.selectedProperty().set(true); break; case SINGLE: single.selectedProperty().set(true); break; default: random.selectedProperty().set(true); break; } color.setColor(JavaFX.toColor(effect.getColor())); color1.setColor(JavaFX.toColor(effect.getColor1())); color2.setColor(JavaFX.toColor(effect.getColor2())); speed.valueProperty().set(effect.getSpeed()); random.visibleProperty().set(getRegion().getCapabilities().contains(Capability.STARLIGHT_RANDOM)); single.visibleProperty().set(getRegion().getCapabilities().contains(Capability.STARLIGHT_SINGLE)); dual.visibleProperty().set(getRegion().getCapabilities().contains(Capability.STARLIGHT_DUAL)); } finally { adjusting = false; } } @FXML void evtOptions(ActionEvent evt) { context.push(Options.class, this, Direction.FROM_BOTTOM); } @FXML void evtBack(ActionEvent evt) { context.pop(); } }
4,505
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
About.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/About.java
package uk.co.bithatch.snake.ui; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Label; import uk.co.bithatch.snake.widgets.Direction; public class About extends AbstractDeviceController { @FXML private Label backend; @FXML private Label backendVersion; @FXML private Label version; @Override protected void onConfigure() throws Exception { backend.textProperty().set(context.getBackend().getName()); try { backendVersion.textProperty().set(context.getBackend().getVersion()); } catch (Exception e) { backendVersion.textProperty().set("Unknown"); } version.textProperty().set(PlatformService.get().getInstalledVersion()); } @FXML void evtBack(ActionEvent evt) { context.pop(); } @FXML void evtChanges(ActionEvent evt) { context.push(Changes.class, Direction.FADE); } }
850
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
AddOnDetails.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/AddOnDetails.java
package uk.co.bithatch.snake.ui; import java.net.URL; import com.sshtools.icongenerator.IconBuilder; import com.sshtools.icongenerator.IconBuilder.AwesomeIconMode; import com.sshtools.icongenerator.IconBuilder.TextContent; import javafx.fxml.FXML; import javafx.scene.canvas.Canvas; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import uk.co.bithatch.snake.ui.addons.AddOn; public class AddOnDetails extends AbstractDeviceController { @FXML private Label author; @FXML private Label addOnType; @FXML private Label addOnName; @FXML private Label screenshot; @Override protected void onConfigure() throws Exception { } public void setAddOn(AddOn addOn) { author.textProperty().set(addOn.getAuthor()); addOnType.textProperty().set(AddOns.bundle.getString("addOnType." + addOn.getClass().getSimpleName())); addOnName.textProperty().set(addOn.getName()); URL ss = addOn.getScreenshot(); if (ss == null) { IconBuilder builder = new IconBuilder(); builder.width(96); builder.height(96); builder.text(addOn.getName()); builder.autoShape(); builder.autoColor(); builder.textContent(TextContent.INITIALS); builder.autoTextColor(); builder.awesomeIconMode(AwesomeIconMode.AUTO_MATCH); screenshot.setGraphic(builder.build(Canvas.class)); } else { ImageView iv = new ImageView(new Image(ss.toExternalForm(), true)); iv.setFitHeight(96); iv.setFitWidth(96); screenshot.setGraphic(iv); } } @FXML void evtSelect() { // context.push(DeviceDetails.class, this, Direction.FROM_RIGHT); } }
1,612
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
MacroMap.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/MacroMap.java
package uk.co.bithatch.snake.ui; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.lang.System.Logger.Level; import java.nio.file.Files; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.ResourceBundle; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.function.UnaryOperator; import java.util.prefs.Preferences; import org.apache.commons.lang3.StringUtils; import com.sshtools.icongenerator.AwesomeIcon; import com.sshtools.icongenerator.IconBuilder.TextContent; import javafx.beans.binding.Bindings; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.value.ChangeListener; import javafx.collections.ObservableListBase; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.control.MultipleSelectionModel; import javafx.scene.control.RadioButton; import javafx.scene.control.SelectionMode; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.TextFormatter; import javafx.scene.control.TextFormatter.Change; import javafx.scene.control.ToggleGroup; import javafx.scene.control.TreeCell; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; import javafx.scene.layout.BorderPane; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.FileChooser.ExtensionFilter; import javafx.stage.Stage; import javafx.util.converter.FloatStringConverter; import uk.co.bithatch.linuxio.EventCode; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.lib.ValidationException; import uk.co.bithatch.snake.lib.binding.ExecuteMapAction; import uk.co.bithatch.snake.lib.binding.KeyMapAction; import uk.co.bithatch.snake.lib.binding.MapAction; import uk.co.bithatch.snake.lib.binding.MapMapAction; import uk.co.bithatch.snake.lib.binding.MapSequence; import uk.co.bithatch.snake.lib.binding.Profile; import uk.co.bithatch.snake.lib.binding.ProfileMap; import uk.co.bithatch.snake.lib.binding.ProfileMapAction; import uk.co.bithatch.snake.lib.binding.ReleaseMapAction; import uk.co.bithatch.snake.lib.binding.ShiftMapAction; import uk.co.bithatch.snake.lib.binding.SleepMapAction; import uk.co.bithatch.snake.lib.layouts.ComponentType; import uk.co.bithatch.snake.lib.layouts.DeviceLayout; import uk.co.bithatch.snake.lib.layouts.DeviceView; import uk.co.bithatch.snake.lib.layouts.IO; import uk.co.bithatch.snake.lib.layouts.Key; import uk.co.bithatch.snake.ui.designer.LayoutEditor; import uk.co.bithatch.snake.ui.designer.Viewer; import uk.co.bithatch.snake.ui.util.BasicList; import uk.co.bithatch.snake.ui.util.Strings; import uk.co.bithatch.snake.widgets.Direction; import uk.co.bithatch.snake.widgets.GeneratedIcon; import uk.co.bithatch.snake.widgets.JavaFX; public class MacroMap extends AbstractDetailsController { public static String textForMapSequence(MapSequence seq) { return textForInputEvent(seq.getMacroKey()); } protected static String textForMapAction(MapAction action) { if (action instanceof KeyMapAction) return textForInputEvent(((KeyMapAction) action).getPress()); else if (action instanceof ReleaseMapAction) return textForInputEvent(((ReleaseMapAction) action).getRelease()); else { return action.getValue(); } } protected static String textForInputEvent(EventCode k) { String keyName = String.valueOf(k); String txt = keyName.substring(4); if (txt.length() > 3) return Strings.toName(txt); else { if (keyName.startsWith("BTN_")) { return MessageFormat.format(bundle.getString("button.name"), txt); } else { return MessageFormat.format(bundle.getString("key.name"), txt); } } } public static GeneratedIcon iconForMapSequence(MapSequence seq) { GeneratedIcon icon = new GeneratedIcon(); icon.getStyleClass().add("mapSequence"); icon.setPrefHeight(32); icon.setPrefWidth(32); String keyName = String.valueOf(seq.getMacroKey()); if (keyName.startsWith("BTN_")) { icon.getStyleClass().add("mapSequenceButton"); } else { icon.getStyleClass().add("mapSequenceKey"); } String txt = keyName.substring(4); icon.setText(txt); if (txt.length() > 3) icon.setTextContent(TextContent.INITIALS); else icon.setTextContent(TextContent.ORIGINAL); return icon; } public static GeneratedIcon iconForMacro(MapAction mkey) { GeneratedIcon icon = new GeneratedIcon(); icon.getStyleClass().add("mapAction"); icon.setPrefHeight(24); icon.setPrefWidth(24); if (mkey instanceof SleepMapAction) { icon.setIcon(AwesomeIcon.CLOCK_O); } else if (mkey instanceof ExecuteMapAction) { icon.setIcon(AwesomeIcon.HASHTAG); } else if (mkey instanceof ShiftMapAction) { icon.setIcon(AwesomeIcon.LONG_ARROW_UP); } else if (mkey instanceof MapMapAction) { icon.setIcon(AwesomeIcon.GLOBE); } else if (mkey instanceof ProfileMapAction) { icon.setIcon(AwesomeIcon.ADDRESS_BOOK); } else if (mkey instanceof KeyMapAction) { icon.setIcon(AwesomeIcon.ARROW_DOWN); } else { icon.setIcon(AwesomeIcon.ARROW_UP); } return icon; } private static class MacroListCell extends TreeCell<Object> { @Override public void updateItem(Object item, boolean empty) { super.updateItem(item, empty); if (empty) { setGraphic(null); setText(null); } else { if (item instanceof MapSequence) { MapSequence seq = (MapSequence) item; setGraphic(iconForMapSequence(seq)); setText(textForMapSequence(seq)); } else { MapAction macro = (MapAction) item; setGraphic(iconForMacro(macro)); if (macro == null) setText("<null>"); else setText(MessageFormat.format( bundle.getString("mapAction." + macro.getActionType().getSimpleName()), textForMapAction(macro))); } } } } final static ResourceBundle bundle = ResourceBundle.getBundle(MacroMap.class.getName()); final static Preferences PREFS = Preferences.userNodeForPackage(MacroMap.class); static List<String> parseQuotedString(String command) { List<String> args = new ArrayList<String>(); boolean escaped = false; boolean quoted = false; StringBuilder word = new StringBuilder(); for (int i = 0; i < command.length(); i++) { char c = command.charAt(i); if (c == '"' && !escaped) { if (quoted) { quoted = false; } else { quoted = true; } } else if (c == '\\' && !escaped) { escaped = true; } else if ((c == ' ' || c == '\n') && !escaped && !quoted) { if (word.length() > 0) { args.add(word.toString()); word.setLength(0); ; } } else { word.append(c); } } if (word.length() > 0) args.add(word.toString()); return args; } @FXML private Hyperlink add; @FXML private Hyperlink delete; @FXML private VBox editor; @FXML private Hyperlink export; @FXML private VBox keySection; @FXML private ComboBox<EventCode> macroKey; @FXML private ToggleGroup macroType; @FXML private TextField seconds; @FXML private TextArea commandArgs; @FXML private Button commandBrowse; @FXML private TextField commandLocation; @FXML private VBox commandSection; @FXML private VBox sleepSection; @FXML private VBox mapSection; @FXML private VBox profileSection; @FXML private VBox sequenceEditor; @FXML private ComboBox<EventCode> keyCode; @FXML private RadioButton keyMapAction; @FXML private RadioButton executeMapAction; @FXML private RadioButton releaseMapAction; @FXML private RadioButton sleepMapAction; @FXML private RadioButton shiftMapAction; @FXML private RadioButton profileMapAction; @FXML private RadioButton mapMapAction; @FXML private Hyperlink recordMacro; @FXML private Hyperlink addMapAction; @FXML private ComboBox<String> targetMap; @FXML private ComboBox<String> targetProfile; @FXML private Label shiftMapActionLabel; @FXML private Label profileMapActionLabel; @FXML private Label mapMapActionLabel; @FXML private BorderPane macrosContainer; private Set<MapAction> macrosToSave = new LinkedHashSet<>(); private Set<MapSequence> sequencesToSave = new LinkedHashSet<>(); private ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); private ProfileMap map; private ScheduledFuture<?> task; private boolean adjusting = false; private MacrosView macros; private LayoutEditor layoutEditor; protected void error(String key) { if (key == null) clearNotifications(false); else { String txt = bundle.getString(key); notifyMessage(MessageType.DANGER, txt == null ? "<missing key " + key + ">" : txt); } } @SuppressWarnings("unchecked") protected <M extends MapAction> M getSelectedMapAction() { return (M) macros.getActionSelectionModel().getSelectedItem(); } protected MapSequence getSelectedSequence() { return macros.getSequenceSelectionModel().getSelectedItem(); } @Override protected void onDeviceCleanUp() { if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, "Stopping macros scheduler."); executor.shutdown(); if (layoutEditor != null) { try { layoutEditor.close(); } catch (Exception e) { } } } public void setMap(ProfileMap map) throws Exception { this.map = map; Device device = map.getProfile().getDevice(); /* * If the device has a layout with some Key's, then replace the tree view with * the layout view */ if (context.getLayouts().hasLayout(device)) { DeviceLayout layout = context.getLayouts().getLayout(device); DeviceView view = layout.getViewThatHas(ComponentType.KEY); if (view != null) { macros = new LayoutMacrosView(map, view, context); } keyCode.itemsProperty().get().addAll(layout.getSupportedInputEvents()); } else { /* No layout, so we must present all possible evdev input codes */ keyCode.itemsProperty().get().addAll(getDevice().getSupportedInputEvents()); } if (macros == null) { macros = new TreeMacrosView(map, context); } macrosContainer.setCenter(macros.getNode()); JavaFX.bindManagedToVisible(commandSection, keySection, sleepSection, editor, mapSection, profileSection, mapMapAction, profileMapAction, shiftMapAction, profileMapActionLabel, mapMapActionLabel, shiftMapActionLabel, addMapAction, recordMacro); keyMapAction.selectedProperty().set(true); profileMapActionLabel.visibleProperty().bind(profileMapAction.visibleProperty()); mapMapActionLabel.visibleProperty().bind(mapMapAction.visibleProperty()); shiftMapActionLabel.visibleProperty().bind(shiftMapAction.visibleProperty()); commandSection.visibleProperty().bind(executeMapAction.selectedProperty()); sleepSection.visibleProperty().bind(sleepMapAction.selectedProperty()); mapSection.visibleProperty() .bind(Bindings.or(mapMapAction.selectedProperty(), shiftMapAction.selectedProperty())); profileSection.visibleProperty().bind(profileMapAction.selectedProperty()); keySection.visibleProperty() .bind(Bindings.or(keyMapAction.selectedProperty(), releaseMapAction.selectedProperty())); /* Populate maps and profiles */ for (Profile profile : getDevice().getProfiles()) { if (profile.equals(map.getProfile())) { for (ProfileMap profileMap : profile.getMaps()) { if (!profileMap.equals(map)) targetMap.getItems().add(map.getId()); } } else targetProfile.getItems().add(profile.getName()); } shiftMapAction.visibleProperty().set(!targetMap.getItems().isEmpty()); mapMapAction.visibleProperty().set(!targetMap.getItems().isEmpty()); profileMapAction.visibleProperty().set(!targetProfile.getItems().isEmpty()); // TODO just show the input event codes supported macroKey.itemsProperty().get().addAll(getDevice().getSupportedInputEvents()); UnaryOperator<Change> floatFilter = change -> { String newText = change.getControlNewText(); if (newText.matches("[-+]?([0-9]*\\.[0-9]+|[0-9]+)")) { return change; } return null; }; seconds.setTextFormatter(new TextFormatter<Float>(new FloatStringConverter(), 0f, floatFilter)); keyCode.getSelectionModel().selectedItemProperty().addListener((e, o, n) -> { if (!adjusting) { var macro = getSelectedMapAction(); if (macro instanceof KeyMapAction) { ((KeyMapAction) macro).setPress(n); } else if (macro instanceof ReleaseMapAction) { ((ReleaseMapAction) macro).setRelease(n); } saveMacroKey(macro); macros.refresh(); } }); commandLocation.textProperty().addListener((e, o, n) -> { if (!adjusting) { var macro = (ExecuteMapAction) getSelectedMapAction(); macro.setCommand(commandLocation.textProperty().get()); saveMacroKey(macro); } }); seconds.textProperty().addListener((e, o, n) -> { if (!adjusting) { var macro = (SleepMapAction) getSelectedMapAction(); try { macro.setSeconds(Float.parseFloat(seconds.textProperty().get())); saveMacroKey(macro); } catch (NumberFormatException nfe) { error("invalidPause"); } } }); commandArgs.textProperty().addListener((e, o, n) -> { if (!adjusting) { var macro = (ExecuteMapAction) getSelectedMapAction(); macro.setArgs(parseQuotedString(commandArgs.textProperty().get())); saveMacroKey(macro); } }); macroKey.getSelectionModel().selectedItemProperty().addListener((e, o, n) -> { if (!adjusting) { var seq = getSelectedSequence(); if (seq != null) { seq.setMacroKey(macroKey.getSelectionModel().getSelectedItem()); saveMacroSequence(seq); macros.refresh(); } } }); macros.getSequenceSelectionModel().selectedItemProperty().addListener((e, o, n) -> { if (!adjusting) { adjusting = true; try { updateForSequence(getSelectedSequence()); updateForAction(getSelectedMapAction()); } finally { adjusting = false; } } }); macros.getActionSelectionModel().selectedItemProperty().addListener((e, o, n) -> { if (!adjusting) { adjusting = true; try { updateForAction(getSelectedMapAction()); } finally { adjusting = false; } } }); delete.visibleProperty().set(getSelectedSequence() != null); sequenceEditor.visibleProperty().set(getSelectedSequence() != null); editor.visibleProperty().set(getSelectedMapAction() != null); macros.buildTree(); executeMapAction.selectedProperty().addListener(createMapActionListener(ExecuteMapAction.class, () -> "")); keyMapAction.selectedProperty().addListener(createMapActionListener(KeyMapAction.class, () -> { if (getSelectedMapAction() instanceof ReleaseMapAction) { return ((ReleaseMapAction) getSelectedMapAction()).getRelease(); } return EventCode.KEY_1; })); releaseMapAction.selectedProperty().addListener(createMapActionListener(ReleaseMapAction.class, () -> { if (getSelectedMapAction() instanceof KeyMapAction) { return ((KeyMapAction) getSelectedMapAction()).getPress(); } return EventCode.KEY_1; })); shiftMapAction.selectedProperty().addListener(createMapActionListener(ShiftMapAction.class, () -> { if (getSelectedMapAction() instanceof KeyMapAction) { return ((KeyMapAction) getSelectedMapAction()).getPress(); } else if (getSelectedMapAction() instanceof ReleaseMapAction) { return ((ReleaseMapAction) getSelectedMapAction()).getRelease(); } return EventCode.KEY_1; })); mapMapAction.selectedProperty().addListener( createMapActionListener(MapMapAction.class, () -> targetMap.getSelectionModel().getSelectedItem())); profileMapAction.selectedProperty().addListener(createMapActionListener(ProfileMapAction.class, () -> targetProfile.getSelectionModel().getSelectedItem())); sleepMapAction.selectedProperty().addListener( createMapActionListener(SleepMapAction.class, () -> targetMap.getSelectionModel().getSelectedItem())); updateState(); updateForSequence(getSelectedSequence()); updateForAction(getSelectedMapAction()); } protected void updateForAction(MapAction macro) { updateAction(macro); updateState(); if (macro instanceof KeyMapAction) keyMapAction.selectedProperty().set(true); else if (macro instanceof ReleaseMapAction) releaseMapAction.selectedProperty().set(true); else if (macro instanceof SleepMapAction) sleepMapAction.selectedProperty().set(true); else if (macro instanceof ExecuteMapAction) executeMapAction.selectedProperty().set(true); else if (macro instanceof ShiftMapAction) shiftMapAction.selectedProperty().set(true); else if (macro instanceof MapMapAction) mapMapAction.selectedProperty().set(true); else if (macro instanceof ProfileMapAction) profileMapAction.selectedProperty().set(true); else if (macro != null) throw new UnsupportedOperationException("Unknown action type."); } protected <A extends MapAction> ChangeListener<? super Boolean> createMapActionListener(Class<A> clazz, Callable<Object> defaultValue) { return (e, o, n) -> { if (!adjusting && n) { adjusting = true; try { MapSequence seq = getSelectedSequence(); MapAction macro = getSelectedMapAction(); macros.add(seq, macro, clazz, defaultValue); } catch (Exception e1) { throw new IllegalStateException("Failed to change action type.", e1); } finally { adjusting = false; } } }; } @FXML void evtAdd() { try { EventCode k = map.getNextFreeKey(); adjusting = true; try { MapSequence seq = map.addSequence(k, true); macros.addSequence(seq); updateForSequence(seq); updateForAction(seq.get(0)); return; } finally { adjusting = false; } } catch (IllegalStateException e) { error("noKeysLeft"); } } @FXML void evtAddMapAction() { var seq = getSelectedSequence(); var action = getSelectedMapAction(); MapAction mk; if (action instanceof KeyMapAction) { KeyMapAction currentKeyMapAction = (KeyMapAction) action; mk = seq.addAction(ReleaseMapAction.class, currentKeyMapAction.getPress()); } else mk = seq.addAction(KeyMapAction.class, seq.getLastInputCode()); macros.addAction(mk); } @FXML void evtDelete() { macros.deleteSelected(); } @FXML void evtExport() { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(bundle.getString("selectExportFile")); var path = PREFS.get("lastExportLocation", System.getProperty("user.dir") + File.separator + "macros.json"); fileChooser.getExtensionFilters().add(new ExtensionFilter(bundle.getString("macroFileExtension"), "*.json")); fileChooser.getExtensionFilters().add(new ExtensionFilter(bundle.getString("allFiles"), "*.*")); JavaFX.selectFilesDir(fileChooser, path); File file = fileChooser.showSaveDialog((Stage) getScene().getWindow()); if (file != null) { PREFS.put("lastExportLocation", file.getAbsolutePath()); try (PrintWriter pw = new PrintWriter(file)) { pw.println(getDevice().exportMacros()); } catch (IOException ioe) { LOG.log(java.lang.System.Logger.Level.ERROR, "Failed to export macros.", ioe); } } } @FXML void evtImport() { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(bundle.getString("selectImportFile")); var path = PREFS.get("lastExportLocation", System.getProperty("user.dir") + File.separator + "macros.json"); fileChooser.getExtensionFilters().add(new ExtensionFilter(bundle.getString("macroFileExtension"), "*.json")); fileChooser.getExtensionFilters().add(new ExtensionFilter(bundle.getString("allFiles"), "*.*")); JavaFX.selectFilesDir(fileChooser, path); File file = fileChooser.showOpenDialog((Stage) getScene().getWindow()); if (file != null) { PREFS.put("lastExportLocation", file.getAbsolutePath()); try { getDevice().importMacros(String.join(" ", Files.readAllLines(file.toPath()))); macros.buildTree(); } catch (IOException ioe) { LOG.log(java.lang.System.Logger.Level.ERROR, "Failed to export macros.", ioe); } } } @FXML void evtCommandBrowse() { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(bundle.getString("selectExecutable")); var path = commandLocation.textProperty().get(); if (path == null || path.equals("")) path = System.getProperty("user.dir"); JavaFX.selectFilesDir(fileChooser, path); File file = fileChooser.showOpenDialog((Stage) getScene().getWindow()); if (file != null) { commandLocation.textProperty().set(file.getPath()); var macro = (ExecuteMapAction) getSelectedMapAction(); macro.setCommand(commandLocation.textProperty().get()); saveMacroKey(macro); } } private void saveMacroSequence(MapSequence sequence) { try { sequence.validate(); if (task != null) { task.cancel(false); } error((String)null); synchronized (sequencesToSave) { sequencesToSave.add(sequence); } task = executor.schedule(() -> { synchronized (macrosToSave) { try { for (MapSequence m : sequencesToSave) { m.commit(); } } finally { sequencesToSave.clear(); } } }, 1000, TimeUnit.MILLISECONDS); } catch (ValidationException ve) { synchronized (sequencesToSave) { sequencesToSave.remove(sequence); } error(ve.getMessage()); } } private void saveMacroKey(MapAction mkey) { try { mkey.validate(); if (task != null) { task.cancel(false); } error((String)null); synchronized (macrosToSave) { macrosToSave.add(mkey); } task = executor.schedule(() -> { synchronized (macrosToSave) { try { for (MapAction m : macrosToSave) { m.commit(); } } finally { macrosToSave.clear(); } } }, 1000, TimeUnit.MILLISECONDS); } catch (ValidationException ve) { synchronized (macrosToSave) { macrosToSave.remove(mkey); } error(ve.getMessage()); } } private void updateState() { var seq = getSelectedSequence(); var macro = getSelectedMapAction(); export.setVisible(!map.getSequences().isEmpty()); sequenceEditor.setVisible(seq != null); addMapAction.setVisible(seq != null); delete.setVisible(seq != null); editor.visibleProperty().set(macro != null); recordMacro.setVisible(seq != null && macro == null); if (macro == null) { delete.textProperty().set(bundle.getString("deleteSequence")); } else { delete.textProperty().set(bundle.getString("delete")); } } private void updateAction(MapAction macro) { if (macro != null) { if (macro instanceof KeyMapAction) { KeyMapAction macroKey = (KeyMapAction) macro; keyCode.getSelectionModel().select(macroKey.getPress()); } else if (macro instanceof ReleaseMapAction) { ReleaseMapAction macroKey = (ReleaseMapAction) macro; keyCode.getSelectionModel().select(macroKey.getRelease()); } else if (macro instanceof SleepMapAction) { SleepMapAction macroKey = (SleepMapAction) macro; seconds.textProperty().set(String.valueOf(macroKey.getSeconds())); } else if (macro instanceof MapMapAction) { MapMapAction macroKey = (MapMapAction) macro; if (!targetMap.getItems().isEmpty()) { if (StringUtils.isBlank(macroKey.getMapName()) || !targetMap.getItems().contains(macroKey.getMapName())) { targetMap.getSelectionModel().select(0); macroKey.setValue(targetMap.getSelectionModel().getSelectedItem()); saveMacroKey(macroKey); } else targetMap.getSelectionModel().select(macroKey.getMapName()); } } else if (macro instanceof ShiftMapAction) { ShiftMapAction macroKey = (ShiftMapAction) macro; if (!targetMap.getItems().isEmpty()) { if (StringUtils.isBlank(macroKey.getMapName()) || !targetMap.getItems().contains(macroKey.getMapName())) { targetMap.getSelectionModel().select(0); macroKey.setValue(targetMap.getSelectionModel().getSelectedItem()); saveMacroKey(macroKey); } else targetMap.getSelectionModel().select(macroKey.getMapName()); } } else if (macro instanceof ProfileMapAction) { ProfileMapAction macroKey = (ProfileMapAction) macro; if (!targetProfile.getItems().isEmpty()) { if (StringUtils.isBlank(macroKey.getProfileName()) || !targetProfile.getItems().contains(macroKey.getProfileName())) { targetProfile.getSelectionModel().select(0); macroKey.setValue(targetProfile.getSelectionModel().getSelectedItem()); saveMacroKey(macroKey); } else targetProfile.getSelectionModel().select(macroKey.getProfileName()); } } else if (macro instanceof ExecuteMapAction) { ExecuteMapAction macroScript = (ExecuteMapAction) macro; commandLocation.textProperty().set(macroScript.getCommand()); if (macroScript.getArgs() == null || macroScript.getArgs().isEmpty()) commandArgs.textProperty().set(""); else commandArgs.textProperty().set(String.join("\n", macroScript.getArgs())); } else throw new UnsupportedOperationException(); } } private void updateForSequence(MapSequence seq) { macroKey.getSelectionModel().select(seq == null ? null : seq.getMacroKey()); } interface MacrosView { void refresh(); Node getNode(); void deleteSelected(); void addAction(MapAction mk); void addSequence(MapSequence seq); <A extends MapAction> void add(MapSequence sequemce, MapAction action, Class<A> clazz, Callable<Object> defaultValue) throws Exception; void buildTree(); // ArrayList<MapAction> getSelectionModel(); MultipleSelectionModel<MapSequence> getSequenceSelectionModel(); MultipleSelectionModel<MapAction> getActionSelectionModel(); } static class LayoutMacrosView extends StackPane implements MacrosView, Viewer { ProfileMap map; SimpleBooleanProperty selectable = new SimpleBooleanProperty(true); SimpleBooleanProperty readOnly = new SimpleBooleanProperty(true); LayoutEditor layoutEditor; ListMultipleSelectionModel<MapSequence> sequenceSelectionModel; ListMultipleSelectionModel<MapAction> actionSelectionModel; MapSequence lastSequence; LayoutMacrosView(ProfileMap map, DeviceView view, App context) { super(); this.map = map; setPrefWidth(500); layoutEditor = new LayoutEditor(context); layoutEditor.getStyleClass().add("padded"); layoutEditor.setShowElementGraphics(false); layoutEditor.setComponentType(ComponentType.AREA); // layoutEditor.setLabelFactory((el) -> { // if (el instanceof Area) { // Area area = (Area) el; // Region.Name regionName = area.getRegion(); // return regions.get(regionName); // } // return null; // }); layoutEditor.open(map.getProfile().getDevice(), view, this); getChildren().add(layoutEditor); sequenceSelectionModel = new ListMultipleSelectionModel<>(new ObservableListBase<>() { @Override public MapSequence get(int index) { try { List<IO> els = layoutEditor.getElements(); return getSequenceForKey((Key) els.get(index)); } catch(Exception e) { e.printStackTrace(); return null; } } @Override public int size() { return layoutEditor.getElements().size(); } }); sequenceSelectionModel.setSelectionMode(SelectionMode.SINGLE); actionSelectionModel = new ListMultipleSelectionModel<>(new ObservableListBase<>() { @Override public MapAction get(int index) { // TODO return null; } @Override public int size() { // TODO return 0; } }); actionSelectionModel.setSelectionMode(SelectionMode.SINGLE); layoutEditor.getElementSelectionModel().setSelectionMode(SelectionMode.SINGLE); layoutEditor.getElementSelectionModel().selectedIndexProperty().addListener((e, oldVal, newVal) -> { checkSelectionChange(); }); } protected MapSequence getSequenceForKey(Key key) { if (key == null) return null; EventCode code = key.getEventCode(); if (code != null) { return map.getSequences().get(code); } return null; } protected void checkSelectionChange() { int idx = layoutEditor.getElementSelectionModel().getSelectedIndex(); IO item = idx == -1 ? null : layoutEditor.getElements().get(idx); Key key = (Key) item; MapSequence seq = getSequenceForKey(key); if (seq == null && key != null && key.getEventCode() != null) { seq = map.addSequence(key.getEventCode(), false); } if (!Objects.equals(seq, lastSequence)) { lastSequence = seq; sequenceSelectionModel.select(lastSequence); } // TreeItem<Object> seqItem = getSelectedSequenceItem(); // TreeItem<Object> actionItem = getSelectedActionItem(); // if (!Objects.equals(sequence.getValue(), lastSequence)) { // lastSequence = (MapSequence) seqItem.getValue(); // sequenceSelectionModel.select(lastSequence); // } // if (!Objects.equals(seqItem.getValue(), lastAction)) { // lastAction = (MapAction) actionItem.getValue(); // actionSelectionModel.select(lastAction); // } } @Override public void addListener(ViewerListener listener) { } @Override public void removeListener(ViewerListener listener) { } @Override public void removeSelectedElements() { } @Override public List<ComponentType> getEnabledTypes() { return Arrays.asList(ComponentType.KEY); } @Override public SimpleBooleanProperty selectableElements() { return selectable; } @Override public SimpleBooleanProperty readOnly() { return readOnly; } @Override public void deleteSelected() { throw new UnsupportedOperationException(); } @Override public void addAction(MapAction mk) { layoutEditor.refresh(); } @Override public void addSequence(MapSequence seq) { layoutEditor.refresh(); } @Override public <A extends MapAction> void add(MapSequence sequemce, MapAction action, Class<A> clazz, Callable<Object> defaultValue) throws Exception { throw new UnsupportedOperationException(); } @Override public void buildTree() { } @Override public MultipleSelectionModel<MapSequence> getSequenceSelectionModel() { return sequenceSelectionModel; } @Override public MultipleSelectionModel<MapAction> getActionSelectionModel() { return actionSelectionModel; } @Override public Node getNode() { return this; } @Override public void setEnabledTypes(List<ComponentType> enabledTypes) { } @Override public void refresh() { } } static class TreeMacrosView extends TreeView<Object> implements MacrosView { ProfileMap map; App context; private MultipleSelectionModel<MapSequence> sequenceSelectionModel; private MultipleSelectionModel<MapAction> actionSelectionModel; private MapSequence lastSequence; private MapAction lastAction; TreeMacrosView(ProfileMap map, App context) { this.map = map; this.context = context; setCellFactory((list) -> { return new MacroListCell(); }); TreeItem<Object> root = new TreeItem<>(); rootProperty().set(root); setShowRoot(false); getSelectionModel().setSelectionMode(SelectionMode.SINGLE); sequenceSelectionModel = new ListMultipleSelectionModel<>(new BasicList<>()); sequenceSelectionModel.setSelectionMode(SelectionMode.SINGLE); actionSelectionModel = new ListMultipleSelectionModel<>(new BasicList<>()); actionSelectionModel.setSelectionMode(SelectionMode.SINGLE); getSelectionModel().selectedItemProperty().addListener((a) -> { checkSelectionChange(); }); } protected void checkSelectionChange() { TreeItem<Object> seqItem = getSelectedSequenceItem(); TreeItem<Object> actionItem = getSelectedActionItem(); if (!Objects.equals(seqItem.getValue(), lastSequence)) { lastSequence = (MapSequence) seqItem.getValue(); sequenceSelectionModel.select(lastSequence); } if (!Objects.equals(seqItem.getValue(), lastAction)) { lastAction = (MapAction) actionItem.getValue(); actionSelectionModel.select(lastAction); } } protected TreeItem<Object> getSelectedSequenceItem() { TreeItem<Object> sel = getSelectionModel().isEmpty() ? null : getSelectionModel().getSelectedItem(); if (sel != null && sel.getValue() instanceof MapSequence) return sel; else if (sel != null && sel.getParent().getValue() instanceof MapSequence) return sel.getParent(); else return null; } protected TreeItem<Object> getSelectedActionItem() { TreeItem<Object> sel = getSelectionModel().isEmpty() ? null : getSelectionModel().getSelectedItem(); if (sel != null && sel.getValue() instanceof MapAction) return sel; else return null; } public void buildTree() { getRoot().getChildren().clear(); var root = rootProperty().get(); for (Map.Entry<EventCode, MapSequence> en : map.getSequences().entrySet()) { MapSequence seq = en.getValue(); TreeItem<Object> macroSequence = addSequenceNode(seq); if (root.getChildren().size() == 1) { macroSequence.setExpanded(true); getSelectionModel().select(macroSequence); } } } private TreeItem<Object> addSequenceNode(MapSequence seq) { TreeItem<Object> macroSequence = new TreeItem<>(seq); for (MapAction m : seq) macroSequence.getChildren().add(new TreeItem<>(m)); getRoot().getChildren().add(macroSequence); return macroSequence; } @Override public <A extends MapAction> void add(MapSequence sequemce, MapAction action, Class<A> clazz, Callable<Object> defaultValue) throws Exception { TreeItem<Object> seqItem = getSelectionModel().getSelectedItem().getParent(); var idx = sequemce.indexOf(action); MapAction murl = action.update(clazz, defaultValue.call()); TreeItem<Object> newMacroItem = new TreeItem<>(murl); seqItem.getChildren().set(idx, newMacroItem); getSelectionModel().select(newMacroItem); } @Override public MultipleSelectionModel<MapSequence> getSequenceSelectionModel() { return sequenceSelectionModel; } @Override public MultipleSelectionModel<MapAction> getActionSelectionModel() { return actionSelectionModel; } @Override public void addSequence(MapSequence seq) { TreeItem<Object> treeItem = addSequenceNode(seq); treeItem.setExpanded(true); getSelectionModel().select(treeItem.getChildren().get(0)); requestFocus(); } @Override public void addAction(MapAction mk) { TreeItem<Object> t = new TreeItem<>(mk); TreeItem<Object> seqItem = getSelectedSequenceItem(); seqItem.setExpanded(true); seqItem.getChildren().add(t); getSelectionModel().select(t); requestFocus(); } @Override public void deleteSelected() { TreeItem<Object> selectedItem = getSelectionModel().getSelectedItem(); MapAction m = getActionSelectionModel().getSelectedItem(); var seq = getSequenceSelectionModel().getSelectedItem(); if (m == null) { Confirm confirm = context.push(Confirm.class, Direction.FADE); confirm.confirm(bundle, "removeSequence", () -> { getSelectionModel().clearSelection(); seq.remove(); selectedItem.getParent().getChildren().remove(selectedItem); // TODO // updateState(); }, null, seq.getMacroKey().name()); } else { m.remove(); selectedItem.getParent().getChildren().remove(selectedItem); // TODO // updateState(); } } @Override public Node getNode() { return this; } } }
35,602
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
LayoutControl.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/LayoutControl.java
package uk.co.bithatch.snake.ui; import java.io.IOException; import java.lang.System.Logger.Level; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.ResourceBundle; import java.util.Set; import org.kordamp.ikonli.fontawesome.FontAwesome; import org.kordamp.ikonli.javafx.FontIcon; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.fxml.FXML; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.control.Slider; import javafx.scene.control.Tooltip; import javafx.scene.effect.Glow; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.util.Duration; import uk.co.bithatch.snake.lib.Capability; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.lib.Lit; import uk.co.bithatch.snake.lib.Region; import uk.co.bithatch.snake.lib.animation.KeyFrame; import uk.co.bithatch.snake.lib.animation.Sequence; import uk.co.bithatch.snake.lib.animation.FramePlayer.FrameListener; import uk.co.bithatch.snake.lib.layouts.Accessory; import uk.co.bithatch.snake.lib.layouts.Accessory.AccessoryType; import uk.co.bithatch.snake.lib.layouts.Area; import uk.co.bithatch.snake.lib.layouts.ComponentType; import uk.co.bithatch.snake.lib.layouts.DeviceLayout; import uk.co.bithatch.snake.lib.layouts.DeviceLayout.Listener; import uk.co.bithatch.snake.lib.layouts.DeviceView; import uk.co.bithatch.snake.lib.layouts.IO; import uk.co.bithatch.snake.ui.designer.LayoutEditor; import uk.co.bithatch.snake.ui.designer.Viewer; import uk.co.bithatch.snake.ui.designer.ViewerView; import uk.co.bithatch.snake.ui.effects.CustomEffectHandler; import uk.co.bithatch.snake.ui.effects.EffectAcquisition; import uk.co.bithatch.snake.ui.effects.EffectManager; import uk.co.bithatch.snake.ui.util.BasicList; import uk.co.bithatch.snake.widgets.AnimPane; import uk.co.bithatch.snake.widgets.Direction; import uk.co.bithatch.snake.widgets.JavaFX; import uk.co.bithatch.snake.widgets.SlideyStack; public class LayoutControl extends AbstractEffectsControl implements Viewer, FrameListener, Listener { final static ResourceBundle bundle = ResourceBundle.getBundle(LayoutControl.class.getName()); private static final double SELECTED_GLOW_AMOUNT = 1; private static final int OVERALL_EFFECT_ICON_SIZE = 32; private static final int REGION_EFFECT_ICON_SIZE = 24; @FXML private BorderPane layout; @FXML private BorderPane top; @FXML private StackPane layoutContainer; @FXML private Hyperlink pageLeft; @FXML private Hyperlink pageRight; private DeviceLayout deviceLayout; private EffectBar overallEffect; private List<ViewerListener> listeners = new ArrayList<>(); private SimpleBooleanProperty readOnly = new SimpleBooleanProperty(true); private SimpleBooleanProperty selectableElements = new SimpleBooleanProperty(false); private ObjectProperty<List<ComponentType>> enabledTypes = new SimpleObjectProperty<>(this, "enabledTypes"); private Map<Region.Name, Node> regions = new HashMap<>(); private AnimPane stack; private CustomEffectHandler currentEffect; private List<DeviceView> views = new ArrayList<>(); private VBox legacyProfileAccessory; private AbstractDeviceController profileAccessory; private LayoutEditor viewer; @Override protected String getControlClassName() { return "layoutControl"; } @Override protected void onSetEffectsControlDevice() { enabledTypes.set(new BasicList<>()); enabledTypes.get().add(ComponentType.AREA); enabledTypes.get().add(ComponentType.ACCESSORY); viewer = createEditor(views.get(0)); stack.setContent(Direction.FADE, viewer); layoutContainer.getChildren().add(stack); overallEffect.effect.addListener((e, o, n) -> { if (!adjustingOverall) { setCustomiseState(customise, getDevice(), getOverallEffect()); rebuildRegions(); } }); checkForCustomEffect(); rebuildRegions(); } protected LayoutEditor createEditor(DeviceView view) { LayoutEditor layoutEditor = new LayoutEditor(context); layoutEditor.setShowElementGraphics(false); layoutEditor.setSelectableComponentType(false); layoutEditor.setComponentType(ComponentType.AREA); layoutEditor.setLabelFactory((el) -> { if (el instanceof Area) { Area area = (Area) el; Region.Name regionName = area.getRegion(); return regions.get(regionName); } else if (el instanceof Accessory) { Accessory accessory = (Accessory) el; if (accessory.getAccessory() == AccessoryType.PROFILES) { if (context.getMacroManager().isSupported(getDevice())) { return createMacrolibAccessory(accessory); } else if (getDevice().getCapabilities().contains(Capability.MACROS)) { if (getDevice().getCapabilities().contains(Capability.MACRO_PROFILES)) return createProfileAccessory(accessory); else return createLegacyProfileAccessory(accessory); } } } return null; }); layoutEditor.open(getDevice(), view, this); return layoutEditor; } protected Node createMacrolibAccessory(Accessory accessory) { if (profileAccessory == null) { try { profileAccessory = context.openScene(MacroProfileControl.class); profileAccessory.setDevice(getDevice()); } catch (IOException e) { throw new IllegalStateException("Failed to load control.", e); } } return profileAccessory.getScene().getRoot(); } protected Node createProfileAccessory(Accessory accessory) { if (profileAccessory == null) { try { profileAccessory = context.openScene(ProfileControl.class); profileAccessory.setDevice(getDevice()); } catch (IOException e) { throw new IllegalStateException("Failed to load control.", e); } } return profileAccessory.getScene().getRoot(); } protected VBox createLegacyProfileAccessory(Accessory accessory) { if (legacyProfileAccessory == null) { legacyProfileAccessory = new VBox(); Label l = new Label(accessory.getDisplayLabel()); l.getStyleClass().add("subtitle"); Hyperlink link = new Hyperlink(bundle.getString("macros")); link.setOnAction((e) -> { try { context.editMacros(LayoutControl.this); } catch (Exception e2) { error(e2); } }); legacyProfileAccessory.getChildren().add(l); legacyProfileAccessory.getChildren().add(link); } return legacyProfileAccessory; } @Override protected void onBeforeSetEffectsControlDevice() { stack = new SlideyStack(); JavaFX.clipChildren(stack, 0); deviceLayout = context.getLayouts().getLayout(getDevice()); deviceLayout.addListener(this); views = deviceLayout.getViewsThatHave(ComponentType.AREA); overallEffect = new EffectBar(OVERALL_EFFECT_ICON_SIZE, getDevice(), context); overallEffect.setAlignment(Pos.CENTER); top.setCenter(overallEffect); } @Override public void removeSelectedElements() { throw new UnsupportedOperationException(); } @Override public List<ComponentType> getEnabledTypes() { return enabledTypes.get(); } @Override public void setEnabledTypes(List<ComponentType> enabledTypes) { this.enabledTypes.set(enabledTypes); } @Override public SimpleBooleanProperty selectableElements() { return selectableElements; } @Override public SimpleBooleanProperty readOnly() { return readOnly; } @FXML void evtPageLeft() { DeviceView view = views.get(getCurrentEditorIndex() - 1); cleanUpViewer(); viewer = createEditor(view); stack.setContent(Direction.FROM_LEFT, viewer); fireViewChanged(viewer); rebuildRegions(); } @FXML void evtPageRight() { DeviceView view = views.get(getCurrentEditorIndex() + 1); cleanUpViewer(); viewer = createEditor(view); stack.setContent(Direction.FROM_RIGHT, viewer); fireViewChanged(viewer); rebuildRegions(); } protected void fireViewChanged(ViewerView view) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).viewerSelected(view); } @Override protected void onEffectChanged(Device device, uk.co.bithatch.snake.lib.Region region) { for (Node other : regions.values()) { if (other instanceof RegionControl) ((RegionControl) other).update(); } getCurrentEditor().reset(); removeCustomEffectListener(); checkForCustomEffect(); } @Override protected void onEffectsControlCleanUp() { cleanUpViewer(); if (profileAccessory != null) profileAccessory.cleanUp(); deviceLayout.removeListener(this); removeCustomEffectListener(); } protected void cleanUpViewer() { if (viewer != null) { try { viewer.close(); } catch (Exception e) { LOG.log(Level.ERROR, "Failed to close viewer.", e); } viewer = null; } } protected void removeCustomEffectListener() { if (currentEffect != null) { currentEffect.getPlayer().removeListener(this); currentEffect = null; } } protected void checkForCustomEffect() { EffectAcquisition acq = context.getEffectManager().getRootAcquisition(getDevice()); EffectHandler<?, ?> mainEffect = acq == null ? null : acq.getEffect(getDevice()); if (mainEffect instanceof CustomEffectHandler) { currentEffect = (CustomEffectHandler) mainEffect; currentEffect.getPlayer().addListener(this); } } static class RegionControl extends VBox { private EffectBar effectBar; private Slider brightnessSlider; private Region region; private App context; RegionControl(DeviceView view, Region r, App context, EffectAcquisition acq, LayoutControl layoutControl) { this.region = r; this.context = context; Label l = new Label(LayoutEditor.getBestRegionName(view, r.getName())); l.getStyleClass().add("subtitle"); HBox t = new HBox(); t.getChildren().add(l); getChildren().add(t); EffectManager fx = context.getEffectManager(); Set<EffectHandler<?, ?>> supported = fx.getEffects(r); Set<EffectHandler<?, ?>> allEffects = new LinkedHashSet<>(supported); Device device = r.getDevice(); allEffects.addAll(fx.getEffects(r)); EffectHandler<?, ?> selectedRegionEffect = acq.getEffect(r); if (!supported.isEmpty() && supported.contains(selectedRegionEffect)) { effectBar = new EffectBar(REGION_EFFECT_ICON_SIZE, 20, r, context); effectBar.maxWidth(80); effectBar.getStyleClass().add("small"); for (EffectHandler<?, ?> f : allEffects) { if (f.isRegions()) { effectBar.addEffect(f); if (selectedRegionEffect != null && f == selectedRegionEffect) { effectBar.effect.set(f); } } } Hyperlink customise = new Hyperlink(); customise.setGraphic(new FontIcon(FontAwesome.GEAR)); customise.setOnMouseClicked((e) -> layoutControl.customise(r, effectBar.effect.get())); customise.getStyleClass().add("small"); setCustomiseState(customise, r, effectBar.effect.get()); t.getChildren().add(customise); getChildren().add(effectBar); if (device.getCapabilities().contains(Capability.BRIGHTNESS_PER_REGION)) { if (r.getCapabilities().contains(Capability.BRIGHTNESS_PER_REGION)) { HBox hbox = new HBox(); brightnessSlider = new Slider(0, 100, r.getBrightness()); brightnessSlider.setUserData(r); brightnessSlider.maxWidth(80); Label la = new Label(String.format("%d%%", r.getBrightness())); la.getStyleClass().add("small"); brightnessSlider.valueProperty().addListener((e) -> { r.setBrightness((short) brightnessSlider.valueProperty().get()); la.textProperty().set(String.format("%d%%", r.getBrightness())); }); hbox.getChildren().add(brightnessSlider); hbox.getChildren().add(la); getChildren().add(hbox); } } } } public void update() { if (brightnessSlider != null) brightnessSlider.valueProperty().set(region.getBrightness()); if (effectBar != null) effectBar.effect .set(context.getEffectManager().getRootAcquisition(region.getDevice()).getEffect(region)); } } @Override protected void rebuildRegions() { Device device = getDevice(); List<Region> regionList = device.getRegions(); EffectManager fx = context.getEffectManager(); EffectAcquisition acq = fx.getRootAcquisition(device); regions.clear(); LayoutEditor layoutEditor = getCurrentEditor(); if (layoutEditor != null) { if (regionList.size() > 1) { EffectHandler<?, ?> selectedDeviceEffect = acq.getEffect(device); if (selectedDeviceEffect == null || (selectedDeviceEffect != null && selectedDeviceEffect.isRegions())) { for (Region r : regionList) { regions.put(r.getName(), new RegionControl(layoutEditor.getView(), r, context, acq, LayoutControl.this)); } } } layoutEditor.refresh(); } int idx = getCurrentEditorIndex(); pageLeft.visibleProperty().set(idx > 0); pageRight.visibleProperty().set(idx < views.size() - 1); } protected int getCurrentEditorIndex() { LayoutEditor le = getCurrentEditor(); return le == null ? -1 : views.indexOf(le.getView()); } protected LayoutEditor getCurrentEditor() { return (LayoutEditor) stack.getContent(); } protected void setSelectedOverallEffect() { selectOverallEffect(currentEffect); } @Override protected void onRebuildOverallEffects() { overallEffect.getChildren().clear(); EffectManager fx = context.getEffectManager(); var deviceEffects = fx.getEffects(getDevice()); EffectAcquisition acq = fx.getRootAcquisition(getDevice()); EffectHandler<?, ?> selectedDeviceEffect = acq.getEffect(getDevice()); overallEffect.effect.set(selectedDeviceEffect); for (EffectHandler<?, ?> effectHandler : deviceEffects) { overallEffect.addEffect(effectHandler); } } static class EffectBar extends HBox { private int iconSize; private SimpleObjectProperty<EffectHandler<?, ?>> effect = new SimpleObjectProperty<>(this, "effect"); private Lit region; private App context; private int iconDisplaySize; EffectBar(int iconSize, Lit region, App context) { this(iconSize, iconSize, region, context); } EffectBar(int iconSize, int iconDisplaySize, Lit region, App context) { this.region = region; this.iconDisplaySize = iconDisplaySize; this.context = context; this.iconSize = iconSize; effect.addListener((e, o, n) -> { for (Node node : getChildren()) { EffectHandler<?, ?> effect = (EffectHandler<?, ?>) node.getUserData(); if (Objects.equals(n, effect)) { select((Hyperlink) node); } else { deselect((Hyperlink) node); } } }); } void addEffect(EffectHandler<?, ?> effect) { Hyperlink button = createButton(effect); getChildren().add(button); } Hyperlink createButton(EffectHandler<?, ?> effectHandler) { Hyperlink activate = new Hyperlink(); activate.getStyleClass().add("deemphasis"); Tooltip tt = new Tooltip(effectHandler.getDisplayName()); tt.setShowDelay(Duration.millis(200)); activate.setTooltip(tt); Node icon = effectHandler.getEffectImageNode(iconSize, iconDisplaySize); activate.setGraphic(icon); activate.setOnMouseClicked((e) -> { context.getEffectManager().getRootAcquisition(Lit.getDevice(region)).activate(region, effectHandler); }); activate.setUserData(effectHandler); EffectHandler<?, ?> selectedDeviceEffect = effect.get(); if (selectedDeviceEffect != null && effectHandler.equals(selectedDeviceEffect)) { select(activate); } return activate; } protected void select(Hyperlink activate) { activate.getStyleClass().remove("deemphasis"); activate.setEffect(new Glow(SELECTED_GLOW_AMOUNT)); } protected void deselect(Hyperlink activate) { if (!activate.getStyleClass().contains("deemphasis")) activate.getStyleClass().add("deemphasis"); activate.setEffect(null); } } @Override protected void selectOverallEffect(EffectHandler<?, ?> effect) { overallEffect.effect.set(effect); } @Override protected EffectHandler<?, ?> getOverallEffect() { return overallEffect.effect.get(); } @Override public void frameUpdate(KeyFrame frame, int[][][] rgb, float fac, long frameNumber) { getCurrentEditor().updateFromMatrix(rgb); } @Override public void pause(boolean pause) { } @Override public void started(Sequence sequence, Device device) { } @Override public void stopped() { } @Override public void addListener(ViewerListener listener) { listeners.add(listener); } @Override public void removeListener(ViewerListener listener) { listeners.remove(listener); } @Override public void layoutChanged(DeviceLayout layout, DeviceView view) { viewChanged(); } @Override public void viewRemoved(DeviceLayout layout, DeviceView view) { viewChanged(); } @Override public void viewChanged(DeviceLayout layout, DeviceView view) { viewChanged(); } protected void viewChanged() { views = deviceLayout.getViewsThatHave(ComponentType.AREA); stack.getChildren().clear(); if (views.isEmpty()) { fireViewChanged(null); } else { DeviceView view = views.get(0); cleanUpViewer(); viewer = createEditor(view); stack.setContent(Direction.FADE, viewer); fireViewChanged(viewer); } rebuildRegions(); } @Override public void viewElementAdded(DeviceLayout layout, DeviceView view, IO element) { } @Override public void viewElementChanged(DeviceLayout layout, DeviceView view, IO element) { } @Override public void viewElementRemoved(DeviceLayout layout, DeviceView view, IO element) { } @Override public void viewAdded(DeviceLayout layout, DeviceView view) { } }
17,697
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
App.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/App.java
package uk.co.bithatch.snake.ui; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.lang.System.Logger.Level; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.ServiceLoader; import java.util.Stack; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import com.goxr3plus.fxborderlessscene.borderless.BorderlessScene; import com.sshtools.forker.wrapped.Wrapped; import javafx.application.Application; import javafx.application.Platform; import javafx.collections.ObservableList; import javafx.fxml.FXMLLoader; import javafx.geometry.Insets; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.effect.DropShadow; import javafx.scene.image.Image; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Region; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.stage.StageStyle; import uk.co.bithatch.snake.lib.Backend; import uk.co.bithatch.snake.lib.Backend.BackendListener; import uk.co.bithatch.snake.lib.Capability; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.lib.DeviceType; import uk.co.bithatch.snake.ui.Configuration.TrayIcon; import uk.co.bithatch.snake.ui.SchedulerManager.Queue; import uk.co.bithatch.snake.ui.addons.AddOnManager; import uk.co.bithatch.snake.ui.addons.Theme; import uk.co.bithatch.snake.ui.audio.AudioManager; import uk.co.bithatch.snake.ui.effects.EffectManager; import uk.co.bithatch.snake.ui.macros.LegacyMacroStorage; import uk.co.bithatch.snake.ui.macros.MacroManager; import uk.co.bithatch.snake.ui.tray.Tray; import uk.co.bithatch.snake.ui.util.Strings; import uk.co.bithatch.snake.widgets.Direction; import uk.co.bithatch.snake.widgets.JavaFX; import uk.co.bithatch.snake.widgets.SlideyStack; public class App extends Application implements BackendListener { static { /* For transparent SVG icons (because sadly Swing has to be used to achieve this */ System.setProperty("swing.jlf.contentPaneTransparent", "true"); } public static int DROP_SHADOW_SIZE = 11; public final static Preferences PREFS = Preferences.userNodeForPackage(App.class); static ResourceBundle BUNDLE = ResourceBundle.getBundle(App.class.getName()); final static System.Logger LOG = System.getLogger(App.class.getName()); private static List<String> argsList; public static void boot(Stage stage) throws Exception { App app = new App(); app.start(stage); } public static File getCustomCSSFile() { File tmpFile = new File(new File(System.getProperty("java.io.tmpdir")), System.getProperty("user.name") + "-snake-jfx.css"); return tmpFile; } public static String getCustomCSSResource(Configuration configuration) { StringBuilder bui = new StringBuilder(); // Get the base colour. All other colours are derived from this Color backgroundColour = new Color(0, 0, 0, 1.0 - ((double) configuration.getTransparency() / 100.0)); if (backgroundColour.getOpacity() == 0) { // Prevent total opacity, as mouse events won't be received backgroundColour = new Color(backgroundColour.getRed(), backgroundColour.getGreen(), backgroundColour.getBlue(), 1f / 255f); } bui.append("* {\n"); bui.append("-fx-background: "); bui.append(JavaFX.toHex(backgroundColour, true)); bui.append(";\n"); bui.append("}\n"); return bui.toString(); } public static void main(String[] args) throws Exception { argsList = Arrays.asList(args); launch(args); } void setColors(Class<? extends Controller> controller, Scene scene) { scene.setFill(new Color(0, 0, 0, 0)); addStylesheets(controller, configuration.getTheme(), scene.getRoot()); } static void writeCSS(Configuration configuration) { try { File tmpFile = getCustomCSSFile(); String url = toUri(tmpFile).toExternalForm(); if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, String.format("Writing user style sheet to %s", url)); PrintWriter pw = new PrintWriter(new FileOutputStream(tmpFile)); try { pw.println(getCustomCSSResource(configuration)); } finally { pw.close(); } } catch (IOException e) { throw new RuntimeException("Could not create custom CSS resource."); } } private static URL toUri(File tmpFile) { try { return tmpFile.toURI().toURL(); } catch (MalformedURLException e) { throw new RuntimeException(e); } } private Backend backend; private Stack<Controller> controllers = new Stack<>(); private Scene primaryScene; private Stage primaryStage; private SlideyStack stackPane; private Tray tray; private boolean waitingForExitChoice; private Window window; private List<Backend> backends = new ArrayList<>(); private AddOnManager addOnManager; private Configuration configuration; private DeviceLayoutManager layouts; private Cache cache; private boolean backendInited; private LegacyMacroStorage legacyMacroStorage; private EffectManager effectManager; private MacroManager macroManager; private AudioManager audioManager; private SchedulerManager schedulerManager; public DeviceLayoutManager getLayouts() { return layouts; } public Configuration getConfiguration() { return configuration; } public Cache getCache() { return cache; } public void close() { close(configuration.getTrayIcon() == TrayIcon.OFF); } public void close(boolean shutdown) { if (shutdown) { try { macroManager.close(); } catch (Exception e) { } try { effectManager.close(); } catch (Exception e) { } layouts.saveAll(); try { getPreferences().flush(); } catch (BackingStoreException bse) { LOG.log(Level.ERROR, "Failed to flush configuration.", bse); } Platform.runLater(() -> clearControllers()); if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, "Shutting down app."); try { cache.close(); } catch (Exception e) { } try { tray.close(); } catch (Exception e) { } try { backend.close(); } catch (Exception e) { } try { schedulerManager.close(); } catch (Exception e) { } try { audioManager.close(); } catch (Exception e) { } if(Wrapped.isWrapped()) Wrapped.get().close(); Platform.exit(); } else { if (LOG.isLoggable(Level.DEBUG)) LOG.log(Level.DEBUG, "Hiding app."); Platform.runLater(() -> primaryStage.hide()); } } public void editMacros(AbstractDeviceController from) throws Exception { Device device = from.getDevice(); if (macroManager.isSupported(device)) { Bank bank = push(Bank.class, from, Direction.FROM_BOTTOM); bank.setBank(macroManager.getMacroSystem().getActiveBank(macroManager.getMacroDevice(device))); } else if (device.getCapabilities().contains(Capability.MACRO_PROFILES)) { MacroMap map = push(MacroMap.class, from, Direction.FROM_BOTTOM); map.setMap(device.getActiveProfile().getActiveMap()); } else if (device.getCapabilities().contains(Capability.MACROS)) { /* Legacy method */ push(Macros.class, from, Direction.FROM_BOTTOM); } else throw new IllegalStateException("Does not support macros."); } public EffectManager getEffectManager() { return effectManager; } public LegacyMacroStorage getLegacyMacroStorage() { return legacyMacroStorage; } public Backend getBackend() { return backend; } public Window getWindow() { return window; } public boolean isWaitingForExitChoice() { return waitingForExitChoice; } public void open() { if (!Platform.isFxApplicationThread()) Platform.runLater(() -> open()); else { primaryStage.show(); primaryStage.toFront(); } } public AddOnManager getAddOnManager() { return addOnManager; } public void openDevice(Device device) throws Exception { controllers.clear(); stackPane.getChildren().clear(); if (backend.getDevices().size() != 1) { push(Overview.class, Direction.FADE); } push(DeviceDetails.class, Direction.FADE).setDevice(device); } public <C extends Controller> C openScene(Class<C> controller) throws IOException { return openScene(controller, null); } @SuppressWarnings("unchecked") public <C extends Controller> C openScene(Class<C> controller, String fxmlSuffix) throws IOException { URL resource = controller .getResource(controller.getSimpleName() + (fxmlSuffix == null ? "" : fxmlSuffix) + ".fxml"); FXMLLoader loader = new FXMLLoader(); try { loader.setResources(ResourceBundle.getBundle(controller.getName())); } catch (MissingResourceException mre) { // Don't care } Theme theme = configuration.getTheme(); // loader.setLocation(resource); loader.setLocation(theme.getResource("App.css")); Parent root = loader.load(resource.openStream()); Controller controllerInst = (Controller) loader.getController(); if (controllerInst == null) { throw new IOException("Controller not found. Check controller in FXML"); } addStylesheets(controller, theme, root); Scene scene = new Scene(root); controllerInst.configure(scene, this); scene.getRoot().getStyleClass().add("rootPane"); return (C) controllerInst; } <C extends Controller> void addStylesheets(Class<C> controller, Theme theme, Parent root) { ObservableList<String> ss = root.getStylesheets(); if (theme.getParent() != null && theme.getParent().length() > 0) { Theme parentTheme = addOnManager.getTheme(theme.getParent()); if (parentTheme == null) throw new IllegalStateException(String.format("Parent theme %s does not exist for theme %s.", theme.getParent(), theme.getId())); ss.add(parentTheme.getResource(App.class.getSimpleName() + ".css").toExternalForm()); } Strings.addIfNotAdded(ss, theme.getResource(App.class.getSimpleName() + ".css").toExternalForm()); URL controllerCssUrl = controller.getResource(controller.getSimpleName() + ".css"); if (controllerCssUrl != null) Strings.addIfNotAdded(ss, controllerCssUrl.toExternalForm()); File tmpFile = getCustomCSSFile(); String url = toUri(tmpFile).toExternalForm(); ss.remove(url); ss.add(url); } public Controller pop() { if (!controllers.isEmpty()) { addOnManager.pop(controllers.peek()); stackPane.pop(); Controller c = controllers.pop(); c.cleanUp(); return c; } return null; } @SuppressWarnings("unchecked") public <C extends Controller> C push(Class<C> controller, Controller from, Direction direction) { if (controllers.size() > 0) { Controller c = controllers.peek(); if (c instanceof Modal) { throw new IllegalStateException("Already modal."); } if (c.getClass().equals(controller)) { /* Already on same type, on same device? */ if (c instanceof AbstractDeviceController && from instanceof AbstractDeviceController) { ((AbstractDeviceController) c).setDevice(((AbstractDeviceController) from).getDevice()); } if (primaryScene instanceof BorderlessScene) { /* TODO: Not totally sure why ... */ setColors(c.getClass(), primaryScene); } return (C) c; } } try { if (primaryScene instanceof BorderlessScene) { /* TODO: Not totally sure why ... */ setColors(controller, primaryScene); } C fc = openScene(controller, null); controllers.push(fc); stackPane.push(direction, fc.getScene().getRoot()); if (fc instanceof AbstractDeviceController && from instanceof AbstractDeviceController) { var device = ((AbstractDeviceController) from).getDevice(); if (device != null) ((AbstractDeviceController) fc).setDevice(device); } addOnManager.push(fc); return fc; } catch (Exception e) { throw new IllegalStateException("Failed to push controller.", e); } } public <C extends Controller> C push(Class<C> controller, Direction direction) { return push(controller, controllers.isEmpty() ? null : controllers.peek(), direction); } public void remove(Controller c) { controllers.remove(c); stackPane.remove(c.getScene().getRoot()); } public SchedulerManager getSchedulerManager() { return schedulerManager; } @Override public void start(Stage primaryStage) throws Exception { if (Wrapped.isWrapped()) { Wrapped.get().addLaunchListener((args) -> { open(); return 0; }); } schedulerManager = new SchedulerManager(); cache = new Cache(this); legacyMacroStorage = new LegacyMacroStorage(this); layouts = new DeviceLayoutManager(this); effectManager = new EffectManager(this); addOnManager = new AddOnManager(this); configuration = new Configuration(PREFS, this); macroManager = new MacroManager(this); audioManager = new AudioManager(this); setUserAgentStylesheet(STYLESHEET_MODENA); writeCSS(configuration); Platform.setImplicitExit(configuration.getTrayIcon() == TrayIcon.OFF); configuration.getNode().addPreferenceChangeListener((evt) -> { Platform.runLater(() -> { if (evt.getKey().equals(Configuration.PREF_THEME)) recreateScene(); else if (evt.getKey().equals(Configuration.PREF_TRAY_ICON)) Platform.setImplicitExit(configuration.getTrayIcon() == TrayIcon.OFF); else if (evt.getKey().equals(Configuration.PREF_TRANSPARENCY)) { writeCSS(configuration); setColors(peek().getClass(), primaryScene); } else if (evt.getKey().equals(Configuration.PREF_DECORATED)) recreateScene(); }); }); String activeBackend = PREFS.get("backend", ""); for (Backend possibleBackend : ServiceLoader.load(Backend.class)) { if (activeBackend.equals("") || activeBackend.equals(possibleBackend.getClass().getName())) { LOG.log(Level.DEBUG, String.format("Backend %s* available.", possibleBackend.getName())); backend = possibleBackend; } else LOG.log(Level.DEBUG, String.format("Backend %s available.", possibleBackend.getName())); backends.add(possibleBackend); } if (backend == null && !backends.isEmpty()) backend = backends.get(0); // Setup the window this.primaryStage = primaryStage; createMainScene(); /* Final configuration of the primary stage (i.e. the desktop window itself) */ configureStage(primaryStage); /* Show! */ if (!argsList.contains("--no-open")) primaryStage.show(); if (PlatformService.get().isUpdated()) push(Changes.class, Direction.FROM_TOP); /* Autostart by default */ if (!PREFS.getBoolean("installed", false)) { PlatformService.get().setStartOnLogin(true); PREFS.putBoolean("installed", true); } if(Wrapped.isWrapped()) Wrapped.get().ready(); } private void clearControllers() { for (Controller c : controllers) c.cleanUp(); controllers.clear(); } private void configureStage(Stage primaryStage) { if (configuration.hasBounds()) { primaryStage.setX(configuration.getX()); primaryStage.setY(configuration.getY()); primaryStage.setWidth(configuration.getW()); primaryStage.setHeight(configuration.getH()); } primaryStage.xProperty().addListener((e) -> configuration.setX((int) primaryStage.getX())); primaryStage.yProperty().addListener((e) -> configuration.setY((int) primaryStage.getY())); primaryStage.widthProperty().addListener((e) -> configuration.setW((int) primaryStage.getWidth())); primaryStage.heightProperty().addListener((e) -> configuration.setH((int) primaryStage.getHeight())); primaryStage.setTitle(BUNDLE.getString("title")); primaryStage.getIcons() .add(new Image(configuration.getTheme().getResource("icons/app32.png").toExternalForm())); primaryStage.getIcons() .add(new Image(configuration.getTheme().getResource("icons/app64.png").toExternalForm())); primaryStage.getIcons() .add(new Image(configuration.getTheme().getResource("icons/app96.png").toExternalForm())); primaryStage.getIcons() .add(new Image(configuration.getTheme().getResource("icons/app128.png").toExternalForm())); primaryStage.getIcons() .add(new Image(configuration.getTheme().getResource("icons/app256.png").toExternalForm())); primaryStage.getIcons() .add(new Image(configuration.getTheme().getResource("icons/app512.png").toExternalForm())); primaryStage.onCloseRequestProperty().set(we -> { we.consume(); close(); }); } private void createMainScene() throws IOException { stackPane = new SlideyStack(); var anchorPane = new AnchorPane(stackPane); anchorPane.setPrefSize(700, 500); AnchorPane.setTopAnchor(stackPane, 0.0); AnchorPane.setBottomAnchor(stackPane, 0.0); AnchorPane.setLeftAnchor(stackPane, 0.0); AnchorPane.setRightAnchor(stackPane, 0.0); /* The main view */ try { if (!backendInited) { initBackend(); addOnManager.start(); effectManager.open(); new DesktopNotifications(this); } if (!macroManager.isStarted()) macroManager.start(); controllers.clear(); if (backend.getDevices().size() == 1) { push(DeviceDetails.class, Direction.FADE).setDevice(backend.getDevices().get(0)); } else { push(Overview.class, Direction.FADE); } } catch (Exception e) { LOG.log(Level.ERROR, "Failed to initialize.", e); Error fc = openScene(Error.class, null); fc.setError(e); stackPane.getChildren().add(fc.getScene().getRoot()); controllers.clear(); controllers.push(fc); } if (configuration.isDecorated()) { if (primaryStage == null) { primaryStage = new Stage(StageStyle.DECORATED); configureStage(primaryStage); } else primaryStage.initStyle(StageStyle.DECORATED); primaryScene = new Scene(anchorPane); setColors(peek().getClass(), primaryScene); primaryStage.setScene(primaryScene); window = null; } else { if (primaryStage == null) { primaryStage = new Stage(StageStyle.TRANSPARENT); configureStage(primaryStage); } else primaryStage.initStyle(StageStyle.TRANSPARENT); window = openScene(Window.class, null); window.getContent().setPrefSize(700, 500); window.getContent().getChildren().add(anchorPane); /* * Create the borderless scene (3rd party library the handles moving and * resizing when UNDECORATED */ primaryScene = new BorderlessScene(primaryStage, StageStyle.TRANSPARENT, window.getScene().getRoot(), 250, 250); ((BorderlessScene) primaryScene).setMoveControl(window.getBar()); ((BorderlessScene) primaryScene).setSnapEnabled(false); ((BorderlessScene) primaryScene).removeDefaultCSS(); primaryScene.getRoot().setEffect(new DropShadow()); ((Region) primaryScene.getRoot()).setPadding(new Insets(10, 10, 10, 10)); primaryScene.setFill(Color.TRANSPARENT); setColors(peek().getClass(), primaryScene); primaryStage.setScene(primaryScene); } } protected void initBackend() throws Exception { if (backend == null) throw new IllegalStateException( "No backend modules available on the classpath or module path. You need at least one backend. For example, snake-backend-openrazer is the default backend."); backend.init(); backend.addListener(this); backendInited = true; /* The tray */ tray = new Tray(this); /* Activate the selected effect on all devices */ try { for (Device dev : backend.getDevices()) { try { if (dev.getCapabilities().contains(Capability.MACROS) && !dev.getCapabilities().contains(Capability.MACRO_PROFILES)) legacyMacroStorage.addDevice(dev); effectManager.addDevice(dev); } catch (Exception e) { LOG.log(Level.ERROR, String.format("Failed to set initial effects fot %s. ", dev.getSerial()), e); } } } catch (Exception e) { LOG.log(Level.ERROR, "Failed to set initial effects. Failed to enumerate devices.", e); } } private void recreateScene() { try { clearControllers(); primaryStage.close(); primaryStage = null; createMainScene(); primaryStage.show(); } catch (Exception e) { LOG.log(Level.ERROR, "Failed to create scene.", e); } } public Controller peek() { return controllers.peek(); } public Stack<Controller> getControllers() { return controllers; } public Preferences getPreferences() { return PREFS; } public Preferences getPreferences(Device device) { return getPreferences().node("devices").node(device.getSerial()); } public Preferences getPreferences(String deviceType) { return getPreferences().node("deviceTypes").node(deviceType); } public String getDefaultImage(DeviceType type, String uri) { if (uri == null || uri.equals("")) { uri = configuration.getTheme().getResource("devices/" + type.name().toLowerCase() + "512.png") .toExternalForm(); } return uri; } public MacroManager getMacroManager() { return macroManager; } @Override public void deviceAdded(Device device) { } @Override public void deviceRemoved(Device device) { Platform.runLater(() -> { boolean haveDevice = false; for (Controller c : controllers) { if (c instanceof AbstractDeviceController) { if (((AbstractDeviceController) c).getDevice().equals(device)) { haveDevice = true; } } } if (haveDevice) { while (controllers.size() > 1) pop(); Controller peek = controllers.peek(); if (peek instanceof AbstractDeviceController && ((AbstractDeviceController) peek).getDevice().equals(device)) { /* TODO */ LOG.log(Level.WARNING, "TODO! This device is gone."); } } }); } public AudioManager getAudioManager() { return audioManager; } public static void hideyMessage(App context, Node message) { message.visibleProperty().set(true); ScheduledFuture<?> task = context.getSchedulerManager().get(Queue.TIMER).schedule( () -> Platform .runLater(() -> JavaFX.fadeHide(message, 5, (ev) -> message.visibleProperty().set(false))), 1, TimeUnit.MINUTES); message.onMouseClickedProperty().set((e) -> { task.cancel(false); JavaFX.fadeHide(message, 5, (ev) -> message.visibleProperty().set(false)); }); } }
22,042
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
LegacyMacroStorage.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/macros/LegacyMacroStorage.java
package uk.co.bithatch.snake.ui.macros; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.lib.Key; import uk.co.bithatch.snake.lib.Macro; import uk.co.bithatch.snake.lib.MacroKey; import uk.co.bithatch.snake.lib.MacroKey.State; import uk.co.bithatch.snake.lib.MacroScript; import uk.co.bithatch.snake.lib.MacroSequence; import uk.co.bithatch.snake.lib.MacroURL; import uk.co.bithatch.snake.ui.App; import uk.co.bithatch.snake.ui.util.Prefs; /** * This class is thrown together as a temporary solution for macro storage * before the new system is fully implemented. */ public class LegacyMacroStorage { private App context; private List<Device> devices = new ArrayList<>(); public LegacyMacroStorage(App context) { this.context = context; } public void addDevice(Device device) { devices.add(device); if (device.getMacros().isEmpty()) { Preferences prefs = context.getPreferences(device).node("legacyMacros"); int seqs = prefs.getInt("sequences", 0); for (int i = 0; i < seqs; i++) { MacroSequence seq = getSequence(prefs.node(String.valueOf(i))); if (seq != null) device.addMacro(seq); } } } public synchronized void save() { try { for (Device device : devices) { Preferences prefs = context.getPreferences(device).node("legacyMacros"); int currentSeqs = prefs.getInt("sequences", 0); for (int i = 0; i < currentSeqs; i++) { prefs.node(String.valueOf(i)).removeNode(); } Collection<MacroSequence> sequences = device.getMacros().values(); prefs.putInt("sequences", sequences.size()); Iterator<MacroSequence> seqIt = sequences.iterator(); for (int i = 0; i < sequences.size(); i++) { saveSequence(seqIt.next(), prefs.node(String.valueOf(i))); } } } catch (BackingStoreException bse) { throw new IllegalStateException("Failed to store macros.", bse); } } private void saveSequence(MacroSequence macroSequence, Preferences node) { node.putInt("actions", macroSequence.size()); node.put("key", macroSequence.getMacroKey().nativeKeyName()); for (int i = 0; i < macroSequence.size(); i++) { saveAction(macroSequence.get(i), node.node(String.valueOf(i))); } } private void saveAction(Macro macro, Preferences node) { if (macro instanceof MacroKey) { MacroKey mk = (MacroKey) macro; node.put("type", "key"); node.put("state", mk.getState().name()); node.putLong("pause", mk.getPrePause()); node.put("key", mk.getKey().name()); } else if (macro instanceof MacroURL) { MacroURL mk = (MacroURL) macro; node.put("type", "url"); node.put("url", mk.getUrl()); } else if (macro instanceof MacroScript) { MacroScript mk = (MacroScript) macro; node.put("type", "script"); node.put("script", mk.getScript()); Prefs.setStringCollection(node, "args", mk.getArgs()); } else throw new UnsupportedOperationException(); } private MacroSequence getSequence(Preferences node) { int actions = node.getInt("actions", 0); MacroSequence seq = new MacroSequence(); try { seq.setMacroKey(Key.fromNativeKeyName(node.get("key", ""))); } catch (IllegalArgumentException iae) { return null; } for (int i = 0; i < actions; i++) { seq.add(getMacro(node.node(String.valueOf(i)))); } return seq; } private Macro getMacro(Preferences node) { String type = node.get("type", ""); if (type.equals("key")) { MacroKey mk = new MacroKey(); mk.setKey(Key.valueOf(node.get("key", ""))); mk.setPrePause(node.getLong("pause", 0)); mk.setState(State.valueOf(node.get("state", State.DOWN.name()))); return mk; } else if (type.equals("url")) { MacroURL mk = new MacroURL(); mk.setUrl(node.get("url", "")); return mk; } else if (type.equals("script")) { MacroScript mk = new MacroScript(); mk.setScript(node.get("script", "")); mk.setArgs(Arrays.asList(Prefs.getStringList(node, "args"))); return mk; } else throw new UnsupportedOperationException(); } }
4,189
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
MacrolibStorage.java
/FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/macros/MacrolibStorage.java
package uk.co.bithatch.snake.ui.macros; import java.io.IOException; import java.util.Iterator; import java.util.UUID; import uk.co.bithatch.macrolib.JsonMacroStorage; import uk.co.bithatch.macrolib.MacroDevice; import uk.co.bithatch.macrolib.MacroProfile; import uk.co.bithatch.snake.ui.App; import uk.co.bithatch.snake.ui.addons.Macros; import uk.co.bithatch.snake.ui.util.CompoundIterator; /** * Augment user profiles with read-only profiles shared by others and installed * as add-ons. */ public class MacrolibStorage extends JsonMacroStorage { private App context; public MacrolibStorage(App context) { this.context = context; } @SuppressWarnings("unchecked") @Override public Iterator<MacroProfile> profiles(MacroDevice device) throws IOException { return new CompoundIterator<>(super.profiles(device), iterateAddOnProfiles(device)); } @Override public MacroProfile loadProfile(MacroDevice device, UUID id) throws IOException { for (Macros macros : context.getAddOnManager().getAddOns(Macros.class)) { if (macros.getProfile().getId().equals(id)) { return macros.getProfile(); } } return super.loadProfile(device, id); } private Iterator<MacroProfile> iterateAddOnProfiles(MacroDevice device) throws IOException { Iterator<Macros> macrosIt = context.getAddOnManager().getAddOns(Macros.class).iterator(); return new Iterator<MacroProfile>() { @Override public boolean hasNext() { return macrosIt.hasNext(); } @Override public MacroProfile next() { return macrosIt.next().getProfile(); } }; } }
1,575
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z