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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
MacroManager.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/macros/MacroManager.java | package uk.co.bithatch.snake.ui.macros;
import java.io.IOException;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.regex.Pattern;
import com.sshtools.twoslices.Toast;
import com.sshtools.twoslices.ToastType;
import uk.co.bithatch.linuxio.EventCode;
import uk.co.bithatch.macrolib.AbstractUInputMacroDevice;
import uk.co.bithatch.macrolib.ActionBinding;
import uk.co.bithatch.macrolib.ActionMacro;
import uk.co.bithatch.macrolib.CommandMacro;
import uk.co.bithatch.macrolib.Macro;
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.ProfileListener;
import uk.co.bithatch.macrolib.MacroSystem.RecordingListener;
import uk.co.bithatch.macrolib.RecordingSession;
import uk.co.bithatch.macrolib.RecordingState;
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.snake.lib.Backend.BackendListener;
import uk.co.bithatch.snake.lib.Capability;
import uk.co.bithatch.snake.lib.Device;
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.App;
import uk.co.bithatch.snake.ui.util.Language;
/**
* This is the bridge between Snake and Macrolib. It converts between native
* Snakelib devices and Macrolib Macro devices, and provides other convenience
* methods.
* <p>
* It is hoped this will be kept light, as most of the logic is in
* {@link MacroSytem}.
*/
public class MacroManager implements AutoCloseable, ActiveBankListener, ActiveProfileListener, ProfileListener,
BackendListener, RecordingListener {
final static Logger LOG = System.getLogger(MacroManager.class.getName());
final static ResourceBundle bundle = ResourceBundle.getBundle(MacroManager.class.getName());
public static final String CLIENT_PROP_INCLUDE_INPUT_EVENT_DEVICES = "includeInputEventDevices";
public static final String CLIENT_PROP_EXCLUDE_INPUT_EVENT_DEVICES = "excludeInputEventDevices";
private MacroSystem macroSystem;
private App context;
private Map<MacroDevice, Device> macroDevices = new HashMap<>();
private Map<Device, MacroDevice> reverseMacroDevices = new HashMap<>();
private Map<String, List<Pattern>> includeDevicePatterns = new HashMap<>();
private Map<String, List<Pattern>> excludeDevicePatterns = new HashMap<>();
private boolean started;
public MacroManager(App context) {
super();
this.context = context;
macroSystem = new MacroSystem(new MacrolibStorage(context));
}
public void start() throws Exception {
if ("false".equals(System.getProperty("snake.macrolib", "true"))) {
LOG.log(Level.WARNING, "Macrolib disabled by system property snake.macrolib.");
return;
}
for (Device device : context.getBackend().getDevices()) {
DeviceLayout deviceLayout = context.getLayouts().getLayout(device);
if (deviceLayout != null) {
addPatternsForDevice(deviceLayout, device);
}
}
/*
* Need to match the OpenRazer device to the input device file. Unfortunately,
* OpenRazer doesnt give us this information so we must get it ourselves.
*
* We do this by matching the end of the device name as OpenRazer provides it
* with the device name as reported by the linux input system. The latter
* appears the be the former, prefixed with 'Razer '.
*/
// var devPaths = new HashMap<String, Path>();
// for (InputDevice dev : InputDevice.getAvailableDevices()) {
// if (dev.getName().startsWith("Razer ")) {
// var name = dev.getName().substring(6);
// var file = dev.getFile();
// devPaths.put(name, file);
// LOG.log(Level.INFO, String.format("Found Razer input device %s at %s.", name, file));
// }
// }
/*
* Check /dev/uinput now. If we grab the devies without being able to retarget
* the events, effectively the mouse and/or keyboard could stop working entirely
* until Snake is stopped.
*/
Path uinputPath = Paths.get("/dev/uinput");
if (!Files.isWritable(uinputPath) || !Files.isReadable(uinputPath)) {
LOG.log(Level.WARNING,
String.format("%s is not readable and writable. Macrolib cannot initialise.", uinputPath));
} else {
for (Device device : context.getBackend().getDevices()) {
addMacroDevice(device);
}
macroSystem.open();
macroSystem.addActiveBankListener(this);
macroSystem.addActiveProfileListener(this);
macroSystem.addProfileListener(this);
macroSystem.addRecordingListener(this);
started = true;
}
context.getBackend().addListener(this);
}
protected void addMacroDevice(Device device) throws IOException {
// var path = devPaths.get(device.getName());
var paths = findDeviceInputPaths(device.getName());
if (paths == null)
LOG.log(Level.WARNING, String.format("No input device path found for razer device %s.", device.getName()));
else {
for (Path path : paths) {
LOG.log(Level.INFO,
String.format("Open input device file %s for Razer device %s.", device.getName(), path));
try {
AbstractUInputMacroDevice macroDevice = new AbstractUInputMacroDevice(path) {
@Override
public String getUID() {
return device.getSerial();
}
@Override
public TargetType getJoystickMode() {
return TargetType.DIGITAL_JOYSTICK;
}
@Override
public int getJoystickCalibration() {
return 0;
}
@Override
public String getId() {
return device.getName();
}
@Override
public int getBanks() {
if (device.getCapabilities().contains(Capability.DEDICATED_MACRO_KEYS))
return 7;
else
return 3;
}
@Override
public Map<String, ActionBinding> getActionKeys() {
return Collections.emptyMap();
}
@Override
public Collection<EventCode> getSupportedInputEvents() {
if (context.getLayouts().hasLayout(device)) {
DeviceLayout layout = context.getLayouts().getLayout(device);
List<DeviceView> views = layout.getViewsThatHave(ComponentType.KEY);
Set<EventCode> codes = new HashSet<>();
for (DeviceView v : views) {
for (IO io : v.getElements(ComponentType.KEY)) {
Key key = (Key) io;
if (key.getEventCode() != null)
codes.add(key.getEventCode());
}
}
if (!codes.isEmpty())
return codes;
}
return super.getSupportedInputEvents();
}
};
macroSystem.addDevice(macroDevice);
macroDevices.put(macroDevice, device);
reverseMacroDevices.put(device, macroDevice);
setLEDsForDevice(macroDevice);
} catch (Exception e) {
if (LOG.isLoggable(Level.DEBUG))
LOG.log(Level.ERROR, String.format("Failed to add device %s to macro system.", path), e);
else
LOG.log(Level.WARNING, String.format("Failed to add device to macro system %s.", path), e);
}
}
}
}
protected void addPatternsForDevice(DeviceLayout deviceLayout, Device device) {
addPatternsForDevice(includeDevicePatterns, CLIENT_PROP_INCLUDE_INPUT_EVENT_DEVICES, deviceLayout, device,
true);
addPatternsForDevice(excludeDevicePatterns, CLIENT_PROP_EXCLUDE_INPUT_EVENT_DEVICES, deviceLayout, device,
false);
}
protected void addPatternsForDevice(Map<String, List<Pattern>> map, String key, DeviceLayout deviceLayout,
Device device, boolean warnEmpty) {
List<String> patterns = deviceLayout.getClientProperty(key, Collections.emptyList());
if (patterns.isEmpty()) {
if (warnEmpty && !deviceLayout.getViewsThatHave(ComponentType.KEY).isEmpty())
LOG.log(Level.WARNING, String.format(
"Device %s has a layout, but the layout does not contain a client property of '%s'. This means input devices cannot be determined. Please report this to the Snake project.",
device.getName(), key));
} else {
for (String pattern : patterns) {
addDevicePattern(map, Pattern.compile(pattern), device.getName());
}
}
}
protected void addDevicePattern(Map<String, List<Pattern>> map, Pattern pattern, String key) {
List<Pattern> l = map.get(key);
if (l == null) {
l = new ArrayList<>();
map.put(key, l);
}
l.add(pattern);
}
@Override
public void close() throws Exception {
context.getBackend().removeListener(this);
macroSystem.removeActiveBankListener(this);
macroSystem.removeActiveProfileListener(this);
macroSystem.removeProfileListener(this);
try {
macroSystem.close();
} finally {
started = false;
}
}
/**
* Get a native device given the macro system device.
*
* @param device macro system device
* @return native device
*/
public Device getNativeDevice(MacroDevice device) {
return macroDevices.get(device);
}
/**
* Get a macro system device given a native device.
*
* @param device native device
* @return macro system device
*/
public MacroDevice getMacroDevice(Device device) {
return reverseMacroDevices.get(device);
}
/**
* Get the underlying macro system instance provided by macrolib.
*
* @return macro system
*/
public MacroSystem getMacroSystem() {
return macroSystem;
}
/**
* Get if this device supports macros.
*
* @param device device
*/
public boolean isSupported(Device device) {
return getMacroDevice(device) != null;
}
public boolean isStarted() {
return started;
}
public void validate(Macro mkey) throws ValidationException {
/* TODO: perform validation similar to other macro implmentations */
if (mkey instanceof UInputMacro) {
UInputMacro uinput = (UInputMacro) mkey;
if (uinput.getCode() == null)
throw new ValidationException("error.missingUInputCode");
} else if (mkey instanceof SimpleMacro) {
SimpleMacro simple = (SimpleMacro) mkey;
if (simple.getMacro() == null || simple.getMacro().length() == 0)
throw new ValidationException("error.missingSimpleMacro");
} else if (mkey instanceof ScriptMacro) {
ScriptMacro script = (ScriptMacro) mkey;
if (script.getScript() == null || script.getScript().isEmpty())
throw new ValidationException("error.missingScript");
} else if (mkey instanceof CommandMacro) {
CommandMacro command = (CommandMacro) mkey;
if (command.getCommand() == null || command.getCommand().length() == 0)
throw new ValidationException("error.missingCommand");
} else if (mkey instanceof ActionMacro) {
ActionMacro script = (ActionMacro) mkey;
if (script.getAction() == null || script.getAction().length() == 0)
throw new ValidationException("error.missingAction");
}
}
@Override
public void activeBankChanged(MacroDevice device, MacroBank bank) {
String cpath = getDeviceImagePath(device);
Toast.toast(ToastType.INFO, cpath,
MessageFormat.format(bundle.getString("bankChange.title"), bank.getDisplayName(),
bank.getProfile().getName()),
MessageFormat.format(bundle.getString("bankChange"), bank.getDisplayName(),
bank.getProfile().getName()));
setLEDsForDevice(device);
}
protected String getDeviceImagePath(MacroDevice device) {
Device nativeDevice = getNativeDevice(device);
String cpath = context.getCache()
.getCachedImage(context.getDefaultImage(nativeDevice.getType(), nativeDevice.getImage()));
if (cpath.startsWith("file:"))
cpath = cpath.substring(5);
return cpath;
}
@Override
public void activeProfileChanged(MacroDevice device, MacroProfile profile) {
String cpath = getDeviceImagePath(device);
MacroBank activeBank = macroSystem.getActiveBank(device);
Toast.toast(ToastType.INFO, cpath,
MessageFormat.format(bundle.getString("profileChange.title"), profile.getName(),
activeBank.getDisplayName()),
MessageFormat.format(bundle.getString("profileChange"), profile.getName(),
activeBank.getDisplayName()));
setLEDsForDevice(device);
}
@Override
public void profileChanged(MacroDevice device, MacroProfile profile) {
if (profile.isActive()) {
setLEDsForDevice(device);
}
}
protected Collection<Path> findDeviceInputPaths(String name) throws IOException {
List<Pattern> includePatterns = includeDevicePatterns.get(name);
if (includePatterns == null)
return null;
List<Pattern> excludePatterns = excludeDevicePatterns.get(name);
List<Path> paths = new ArrayList<>();
for (Path p : Files.newDirectoryStream(Paths.get("/dev/input/by-id"), (f) -> matches(includePatterns, f)
&& (excludePatterns == null || excludePatterns.isEmpty() || !matches(excludePatterns, f))))
paths.add(p);
return paths;
}
protected boolean matches(List<Pattern> patterns, Path f) {
for (Pattern pattern : patterns) {
if (pattern.matcher(f.getFileName().toString()).matches())
return true;
}
return false;
}
protected void setLEDsForDevice(MacroDevice device) {
Device nativeDevice = getNativeDevice(device);
if (nativeDevice.getCapabilities().contains(Capability.PROFILE_LEDS)) {
MacroBank bank = macroSystem.getActiveBank(device);
@SuppressWarnings("unchecked")
List<Boolean> l = (List<Boolean>) bank.getProperties().getOrDefault("leds", null);
if (l == null)
nativeDevice.setProfileRGB(Language.toBinaryArray(bank.getBank() + 1, 3));
else
nativeDevice.setProfileRGB(new boolean[] { l.get(0), l.get(1), l.get(2) });
}
}
@Override
public void deviceAdded(Device device) {
DeviceLayout deviceLayout = context.getLayouts().getLayout(device);
if (deviceLayout != null) {
addPatternsForDevice(deviceLayout, device);
try {
addMacroDevice(device);
} catch (IOException e) {
LOG.log(Level.ERROR, "Failed to add macro device.", e);
}
}
}
@Override
public void deviceRemoved(Device device) {
MacroDevice macroDevice = reverseMacroDevices.get(device);
if (macroDevice != null) {
LOG.log(Level.INFO, String.format("Removing macro handling for %s", device.getName()));
try {
macroSystem.removeDevice(macroDevice);
} catch (IOException e) {
LOG.log(Level.ERROR, String.format("Failed to remove macro handling for %s", device.getName()), e);
}
reverseMacroDevices.remove(device);
macroDevices.remove(macroDevice);
}
includeDevicePatterns.remove(device.getName());
excludeDevicePatterns.remove(device.getName());
}
@Override
public void recordingStateChange(RecordingSession session) {
if (session.getRecordingState() == RecordingState.WAITING_FOR_TARGET_KEY) {
Toast.toast(ToastType.INFO, bundle.getString("recording.waitingForTarget.title"),
bundle.getString("recording.waitingForTarget"));
} else if (session.getRecordingState() == RecordingState.WAITING_FOR_EVENTS) {
Toast.toast(ToastType.INFO, bundle.getString("recording.waitingForEvents.title"),
bundle.getString("recording.waitingForEvents"));
}
}
@Override
public void eventRecorded() {
}
} | 15,632 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
MapProfileLEDHelper.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/widgets/MapProfileLEDHelper.java | package uk.co.bithatch.snake.ui.widgets;
import java.io.Closeable;
import java.io.IOException;
import java.util.Objects;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import uk.co.bithatch.snake.lib.binding.ProfileMap;
import uk.co.bithatch.snake.widgets.ProfileLEDs;
public class MapProfileLEDHelper implements Closeable, ChangeListener<boolean[]> {
private ProfileMap map;
private ProfileLEDs profileLEDs;
public MapProfileLEDHelper(ProfileLEDs profileLEDs) {
this.profileLEDs = profileLEDs;
}
public void setMap(ProfileMap map) {
if (!Objects.equals(map, this.map)) {
this.map = map;
updateState();
}
}
@Override
public void close() throws IOException {
}
@Override
public void changed(ObservableValue<? extends boolean[]> observable, boolean[] oldValue, boolean[] newValue) {
if (map != null) {
map.setLEDs(newValue);
}
}
protected void updateState() {
profileLEDs.setRgbs(map.getLEDs());
}
}
| 980 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
MacroBankLEDHelper.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/widgets/MacroBankLEDHelper.java | package uk.co.bithatch.snake.ui.widgets;
import java.io.Closeable;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
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.ProfileListener;
import uk.co.bithatch.snake.widgets.ProfileLEDs;
public class MacroBankLEDHelper implements Closeable, ProfileListener, ChangeListener<boolean[]> {
private ProfileLEDs profileLEDs;
private MacroBank bank;
private MacroSystem macroSystem;
private boolean adjusting;
private boolean automatic;
public MacroBankLEDHelper(MacroSystem macroSystem, ProfileLEDs profileLEDs) {
this(macroSystem, null, profileLEDs);
}
public MacroBankLEDHelper(MacroSystem macroSystem, MacroBank bank, ProfileLEDs profileLEDs) {
this.profileLEDs = profileLEDs;
this.macroSystem = macroSystem;
macroSystem.addProfileListener(this);
profileLEDs.rgbs().addListener(this);
setBank(bank);
}
public MacroBank getBank() {
return bank;
}
public void setBank(MacroBank bank) {
if (!Objects.equals(bank, this.bank)) {
this.bank = bank;
updateState();
}
}
@Override
public void close() throws IOException {
macroSystem.removeProfileListener(this);
profileLEDs.rgbs().removeListener(this);
}
@Override
public void profileChanged(MacroDevice device, MacroProfile profile) {
if (bank != null && bank.getProfile().equals(profile)) {
updateState();
}
}
public boolean isAutomatic() {
return automatic;
}
public void setAutomatic(boolean automatic) {
if (this.automatic != automatic) {
this.automatic = automatic;
if (automatic)
bank.getProperties().remove("leds");
else
bank.getProperties().put("leds", Arrays.asList(true, true, true));
bank.commit();
}
}
@Override
public void changed(ObservableValue<? extends boolean[]> observable, boolean[] oldValue, boolean[] newValue) {
if (bank != null && !adjusting) {
if (automatic) {
bank.getProperties().remove("leds");
} else {
bank.getProperties().put("leds", Arrays.asList(newValue[0], newValue[1], newValue[2]));
}
bank.commit();
}
}
protected void updateState() {
adjusting = true;
try {
@SuppressWarnings("unchecked")
List<Boolean> l = (List<Boolean>) bank.getProperties().getOrDefault("leds", null);
if (l == null) {
automatic = true;
profileLEDs.setRgbs(new boolean[] { false, false, false });
} else {
automatic = false;
profileLEDs.setRgbs(new boolean[] { l.get(0), l.get(1), l.get(2) });
}
} finally {
adjusting = false;
}
}
}
| 2,802 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
LayoutEditor.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/designer/LayoutEditor.java | package uk.co.bithatch.snake.ui.designer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.css.CssMetaData;
import javafx.css.SimpleStyleableObjectProperty;
import javafx.css.Styleable;
import javafx.css.StyleableDoubleProperty;
import javafx.css.StyleableProperty;
import javafx.css.StyleablePropertyFactory;
import javafx.css.converter.SizeConverter;
import javafx.geometry.Insets;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.MultipleSelectionModel;
import javafx.scene.control.RadioButton;
import javafx.scene.control.Slider;
import javafx.scene.control.ToggleGroup;
import javafx.scene.effect.ColorAdjust;
import javafx.scene.image.Image;
import javafx.scene.input.ContextMenuEvent;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import uk.co.bithatch.snake.lib.BrandingImage;
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.Region.Name;
import uk.co.bithatch.snake.lib.binding.Profile;
import uk.co.bithatch.snake.lib.binding.ProfileMap;
import uk.co.bithatch.snake.lib.layouts.Accessory;
import uk.co.bithatch.snake.lib.layouts.Area;
import uk.co.bithatch.snake.lib.layouts.ComponentType;
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.App;
import uk.co.bithatch.snake.ui.ListMultipleSelectionModel;
import uk.co.bithatch.snake.ui.util.BasicList;
import uk.co.bithatch.snake.ui.util.ListWrapper;
import uk.co.bithatch.snake.ui.util.Strings;
import uk.co.bithatch.snake.widgets.JavaFX;
import uk.co.bithatch.snake.widgets.SelectableArea;
public class LayoutEditor extends SelectableArea
implements ViewerView, Listener, uk.co.bithatch.snake.lib.layouts.DeviceView.Listener {
public interface LabelFactory {
Node createLabel(IO element);
}
public interface ContextMenuCallback {
void openContextMenu(Tool tool, ContextMenuEvent e);
}
class DeviceCanvas extends Canvas {
DeviceCanvas() {
super(512, 512);
draw();
widthProperty().addListener((e, o, n) -> draw());
heightProperty().addListener((e, o, n) -> draw());
}
protected Point2D calcImageOffset() {
double canvasWidth = boundsInLocalProperty().get().getWidth();
double canvasHeight = boundsInLocalProperty().get().getHeight();
Point2D imgSize = calcImageSize();
double imgX = (canvasWidth - imgSize.getX()) / 2;
double imgY = (canvasHeight - imgSize.getY()) / 2;
return new Point2D(imgX, imgY);
}
protected Point2D calcImageSize() {
double canvasWidth = boundsInLocalProperty().get().getWidth();
double canvasHeight = boundsInLocalProperty().get().getHeight();
if (img == null)
return new Point2D(canvasWidth, canvasHeight);
/*
* Get how much we would have to scale the width by for it cover the entire area
*/
double widthScale = canvasWidth / img.getWidth();
/*
* Get how much we would have to scale the height by for it cover the entire
* area
*/
double heightScale = canvasHeight / img.getHeight();
/*
* Scale the image so it fits the height (preserving ratio). If the width then
* exceeds available space, then scale the height back until it fits
*/
double imgHeight = img.getHeight() * heightScale;
double imgWidth = img.getWidth() * heightScale;
if (imgWidth > canvasWidth) {
imgHeight = img.getHeight() * widthScale;
imgWidth = img.getWidth() * widthScale;
}
return new Point2D(imgWidth * view.getImageScale(), imgHeight * view.getImageScale());
}
protected void draw() {
GraphicsContext ctx = getGraphicsContext2D();
double canvasWidth = boundsInLocalProperty().get().getWidth();
double canvasHeight = boundsInLocalProperty().get().getHeight();
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
Point2D imgSize = calcImageSize();
Point2D imgOff = calcImageOffset();
if (!isLayoutReadOnly()) {
ctx.setGlobalAlpha(0.2f);
double gw = Math.max(1, gridSizeSlider.valueProperty().get() * imgSize.getX());
double gh = Math.max(1, gridSizeSlider.valueProperty().get() * imgSize.getY());
ctx.setStroke(getLineColor());
ctx.beginPath();
ctx.setLineWidth(0.5);
for (double y = imgOff.getY() % gh; y < canvasHeight; y += gh) {
ctx.moveTo(0, y);
ctx.lineTo(canvasWidth, y);
}
for (double x = imgOff.getX() % gw; x < canvasWidth; x += gw) {
ctx.moveTo(x, 0);
ctx.lineTo(x, canvasHeight);
}
ctx.stroke();
ctx.closePath();
ctx.setGlobalAlpha(1);
}
ctx.setGlobalAlpha(view.getImageOpacity());
if (view.isDesaturateImage()) {
ColorAdjust adjust = new ColorAdjust();
adjust.setSaturation(-1);
ctx.setEffect(adjust);
}
ctx.drawImage(img, imgOff.getX(), imgOff.getY(), imgSize.getX(), imgSize.getY());
ctx.setGlobalAlpha(1);
if (view.isDesaturateImage()) {
ctx.setEffect(null);
}
List<ElementView> left = new ArrayList<>();
List<ElementView> top = new ArrayList<>();
List<ElementView> bottom = new ArrayList<>();
List<ElementView> right = new ArrayList<>();
separateElements(left, top, bottom, right);
double totalHeight = getTotalHeight(left);
double y = ((canvasHeight - (totalHeight)) / 2f);
/* Left */
for (ElementView elementView : left) {
IO element = elementView.getElement();
double lineWidth = elementView.getLabel().getBoundsInLocal().getWidth();
double rowHeight = elementView.getLabel().getBoundsInLocal().getHeight();
ctx.setFont(font);
double elementX = elementXToLocalX(element.getX());
double elementY = elementYToLocalY(element.getY());
double xToElement = elementX - lineWidth - (getGraphicTextGap() * 2);
ctx.setStroke(getLineColor());
ctx.beginPath();
ctx.setLineWidth(getLineWidth());
ctx.moveTo(lineWidth + getGraphicTextGap(), y + (rowHeight / 2f));
ctx.lineTo(lineWidth + getGraphicTextGap() + Math.max(1, (xToElement * 0.1)), y + (rowHeight / 2f));
ctx.lineTo(elementX - Math.max(1, (xToElement * 0.1)) - getGraphicTextGap(), elementY);
ctx.lineTo(elementX - getGraphicTextGap(), elementY);
ctx.stroke();
ctx.closePath();
y += rowHeight;
}
/* Right */
totalHeight = getTotalHeight(right);
y = ((canvasHeight - (totalHeight)) / 2f);
for (ElementView elementView : right) {
IO element = elementView.getElement();
double lineWidth = elementView.getLabel().getBoundsInLocal().getWidth();
double rowHeight = elementView.getLabel().getBoundsInLocal().getHeight();
double elementX = elementXToLocalX(element.getX());
double elementY = elementYToLocalY(element.getY());
double xToElement = canvasWidth - elementX - lineWidth - (getGraphicTextGap() * 2);
ctx.setStroke(getLineColor());
ctx.beginPath();
ctx.setLineWidth(getLineWidth());
ctx.moveTo(canvasWidth - lineWidth - getGraphicTextGap(), y + (rowHeight / 2f));
ctx.lineTo(canvasWidth - lineWidth - Math.max(1, (xToElement * 0.1)) - getGraphicTextGap(),
y + (rowHeight / 2f));
ctx.lineTo(elementX + Math.max(1, (xToElement * 0.1)) + getGraphicTextGap(), elementY);
ctx.lineTo(elementX + getGraphicTextGap(), elementY);
ctx.stroke();
ctx.closePath();
y += rowHeight;
}
/* Top */
double totalTextWidth = getTotalWidth(top);
double x = ((canvasWidth - totalTextWidth) / 2f);
for (ElementView elementView : top) {
IO element = elementView.getElement();
double lineWidth = elementView.getLabel().getBoundsInLocal().getWidth();
double rowHeight = elementView.getLabel().getBoundsInLocal().getHeight();
double elementX = elementXToLocalX(element.getX());
double elementY = elementYToLocalY(element.getY());
double yToElement = canvasHeight - elementY - rowHeight - (getGraphicTextGap() * 2);
ctx.setStroke(getLineColor());
ctx.beginPath();
ctx.setLineWidth(getLineWidth());
ctx.moveTo(x + (lineWidth / 2f), rowHeight + getGraphicTextGap());
ctx.lineTo(x + (lineWidth / 2f), rowHeight + Math.max(1, (yToElement * 0.1)) + getGraphicTextGap());
ctx.lineTo(elementX, elementY - Math.max(1, (yToElement * 0.1)) - getGraphicTextGap());
ctx.lineTo(elementX, elementY - getGraphicTextGap());
ctx.stroke();
ctx.closePath();
x += lineWidth + getGraphicTextGap();
}
/* Bottom */
totalTextWidth = getTotalWidth(bottom);
x = ((canvasWidth - totalTextWidth) / 2f);
for (ElementView elementView : bottom) {
IO element = elementView.getElement();
double lineWidth = elementView.getLabel().getBoundsInLocal().getWidth();
double rowHeight = elementView.getLabel().getBoundsInLocal().getHeight();
double elementX = elementXToLocalX(element.getX());
double elementY = elementYToLocalY(element.getY());
double yToElement = canvasHeight - elementY - rowHeight - (getGraphicTextGap() * 2);
ctx.setStroke(getLineColor());
ctx.beginPath();
ctx.setLineWidth(getLineWidth());
ctx.moveTo(elementX, elementY + getGraphicTextGap());
ctx.lineTo(elementX, elementY + getGraphicTextGap() + Math.max(1, (yToElement * 0.1)));
ctx.lineTo(x + (lineWidth / 2f),
canvasHeight - rowHeight - Math.max(1, (yToElement * 0.1)) - getGraphicTextGap());
ctx.lineTo(x + (lineWidth / 2f), canvasHeight - rowHeight - getGraphicTextGap());
ctx.stroke();
ctx.closePath();
x += lineWidth + getGraphicTextGap();
}
}
protected double elementXToLocalX(double x) {
Point2D imgSize = calcImageSize();
Point2D imgOff = calcImageOffset();
return (x * imgSize.getX()) + imgOff.getX();
}
protected double elementYToLocalY(double y) {
Point2D imgSize = calcImageSize();
Point2D imgOff = calcImageOffset();
return (y * imgSize.getY()) + imgOff.getY();
}
protected void updateElement(ElementView element, double toolX, double toolY) {
Point2D pc = getElementPosition(toolX, toolY);
element.getElement().setX((float) pc.getX());
element.getElement().setY((float) pc.getY());
}
protected Point2D getElementPosition(double toolX, double toolY) {
float pcX, pcY;
if (img != null) {
Point2D imgSize = calcImageSize();
Point2D imgOff = calcImageOffset();
double scale = imgSize.getX() / img.getWidth();
double pixelX = (toolX - imgOff.getX()) * scale;
double pixelY = (toolY - imgOff.getY()) * scale;
pcX = (float) ((pixelX / (imgSize.getX() * scale)));
pcY = (float) ((pixelY / (imgSize.getY() * scale)));
} else {
pcX = (float) ((toolX / (boundsInLocalProperty().get().getWidth())));
pcY = (float) ((toolY / (boundsInLocalProperty().get().getHeight())));
}
if (snapToGridCheckBox.selectedProperty().get()) {
pcX = (float) (pcX - (pcX % gridSizeSlider.getValue()) + (gridSizeSlider.getValue() / 2.0));
pcY = (float) (pcY - (pcY % gridSizeSlider.getValue()) + (gridSizeSlider.getValue() / 2.0));
}
return new Point2D(pcX, pcY);
}
}
private static class StyleableProperties {
private static final CssMetaData<LayoutEditor, Number> GRAPHIC_TEXT_GAP = new CssMetaData<LayoutEditor, Number>(
"-fx-graphic-text-gap", SizeConverter.getInstance(), 4.0) {
@SuppressWarnings("unchecked")
@Override
public StyleableProperty<Number> getStyleableProperty(LayoutEditor n) {
return (StyleableProperty<Number>) n.graphicTextGapProperty();
}
@Override
public boolean isSettable(LayoutEditor n) {
return n.graphicTextGap == null || !n.graphicTextGap.isBound();
}
};
private static final CssMetaData<LayoutEditor, Number> LINE_WIDTH = new CssMetaData<LayoutEditor, Number>(
"-snake-line-width", SizeConverter.getInstance(), DEFAULT_LINE_WIDTH) {
@SuppressWarnings("unchecked")
@Override
public StyleableProperty<Number> getStyleableProperty(LayoutEditor n) {
return (StyleableProperty<Number>) n.lineWidthProperty();
}
@Override
public boolean isSettable(LayoutEditor n) {
return n.graphicTextGap == null || !n.graphicTextGap.isBound();
}
};
}
final static Insets DEFAULT_INSETS = new Insets(20);
private static final double DEFAULT_GRAPHICS_TEXT_GAP = 8;
private static final double DEFAULT_LINE_WIDTH = 1;
private static final StyleablePropertyFactory<LayoutEditor> FACTORY = new StyleablePropertyFactory<>(
SelectableArea.getClassCssMetaData());
private static final CssMetaData<LayoutEditor, Color> LINE_COLOR = FACTORY
.createColorCssMetaData("-snake-line-color", s -> s.lineColorProperty, Color.GRAY, true);
public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() {
return FACTORY.getCssMetaData();
}
private final BooleanProperty showElementGraphics = new SimpleBooleanProperty(this, "showElementGraphics", true);
private final BooleanProperty selectableComponentType = new SimpleBooleanProperty(this, "selectableComponentType",
true);
private final ObjectProperty<ComponentType> componentType = new SimpleObjectProperty<>(this, "componentType");
private final ObjectProperty<LabelFactory> labelFactory = new SimpleObjectProperty<>(this, "labelFactory");
private final ObjectProperty<List<ComponentType>> enabledTypes = new SimpleObjectProperty<>(this, "enabledTypes");
private final Slider gridSizeSlider = new Slider(0.01, 0.1, 0.025);
private final ObjectProperty<MultipleSelectionModel<IO>> elementSelectionModel = new SimpleObjectProperty<MultipleSelectionModel<IO>>(
this, "elementSelectionModel");
private final StyleableProperty<Color> lineColorProperty = new SimpleStyleableObjectProperty<>(LINE_COLOR, this,
"lineColor");
private final CheckBox snapToGridCheckBox = new CheckBox();
private Image img;
private ListWrapper<ElementView, IO> items;
private DoubleProperty lineWidth;
private String loadedImage;
private Font font;
private DoubleProperty graphicTextGap;
private ContextMenuCallback menuCallback;
private App context;
private DeviceCanvas canvas;
private ObjectProperty<ObservableList<ElementView>> elementViews = new SimpleObjectProperty<>(this, "elements");
private List<Node> componentTypes = new ArrayList<>();
private Device device;
private DeviceView view;
private Pane pane;
private Viewer viewer;
private ChangeListener<? super Boolean> readOnlyListener;
public LayoutEditor(App context) {
this.context = context;
font = Font.getDefault();
enabledTypes.set(new BasicList<>());
enabledTypes.addListener((c, o, n) -> {
List<ComponentType> list = enabledTypes.get();
if (!list.contains(componentType.get())) {
if (list.isEmpty())
componentType.set(null);
else
componentType.set(list.get(0));
} else if (componentType.get() == null && !list.isEmpty())
componentType.set(list.get(0));
if (pane != null)
rebuildComponentTypesPanel();
});
elementViews.set(new BasicList<ElementView>());
elementViews.get().addListener(new ListChangeListener<>() {
@Override
public void onChanged(Change<? extends ElementView> c) {
rebuildComponentTypesPanel();
}
});
items = new ListWrapper<ElementView, IO>(elementViews.get()) {
@Override
protected IO doConvertToWrapped(ElementView in) {
return in.getElement();
}
};
setElementSelectionModel(new ListMultipleSelectionModel<>(items));
setFocusTraversable(true);
setOnKeyReleased((e) -> {
if (e.isControlDown() && e.getCode() == KeyCode.A) {
getElementSelectionModel().selectAll();
e.consume();
}
if (e.getCode() == KeyCode.DELETE) {
viewer.removeSelectedElements();
e.consume();
}
});
setOnKeyPressed((e) -> {
if (e.getCode() == KeyCode.UP) {
moveSelection(0, -(e.isShiftDown() ? 10 : 1));
e.consume();
} else if (e.getCode() == KeyCode.DOWN) {
moveSelection(0, e.isShiftDown() ? 10 : 1);
e.consume();
} else if (e.getCode() == KeyCode.LEFT) {
moveSelection(-(e.isShiftDown() ? 10 : 1), 0);
e.consume();
} else if (e.getCode() == KeyCode.RIGHT) {
moveSelection(e.isShiftDown() ? 10 : 1, 0);
e.consume();
}
});
selectableComponentType.addListener((e, o, n) -> {
if (pane != null) {
rebuildComponentTypesPanel();
rebuildElements();
}
});
showElementGraphics.addListener((e, o, n) -> {
if (pane != null) {
rebuildElements();
}
});
snapToGridCheckBox.selectedProperty().addListener((e, o, n) -> {
if (n)
resnap();
});
gridSizeSlider.valueProperty().addListener((e, o, n) -> {
if (snapToGridCheckBox.selectedProperty().get())
resnap();
});
snapToGridCheckBox.textProperty().set(TabbedViewer.bundle.getString("snapToGrid"));
selectableArea().addListener((e, o, n) -> {
if (o == null && n != null) {
clearSelection();
}
if (n != null) {
for (ElementView b : elementViews.get()) {
if (n.intersects(b.getElementTool().getBoundsInParent())) {
addToSelection(b.getElement());
}
}
}
});
elementSelectionModel().get().getSelectedItems().addListener(new ListChangeListener<IO>() {
@Override
public void onChanged(Change<? extends IO> c) {
while (c.next()) {
if (c.wasAdded()) {
for (IO io : c.getAddedSubList()) {
ElementView ev = forElement(io);
ev.getElementTool().setSelected(true);
}
}
if (c.wasRemoved()) {
for (IO io : c.getRemoved()) {
ElementView ev = forElement(io);
if (ev != null)
ev.getElementTool().setSelected(false);
}
}
}
layoutLabels();
canvas.draw();
}
});
}
public BooleanProperty showElementGraphics() {
return showElementGraphics;
}
public void setShowElementGraphics(boolean showElementGraphics) {
this.showElementGraphics.set(showElementGraphics);
}
public boolean isShowElementGraphics() {
return showElementGraphics.get();
}
public BooleanProperty selectableComponentType() {
return selectableComponentType;
}
public void setSelectableComponentType(boolean selectableComponentType) {
this.selectableComponentType.set(selectableComponentType);
}
public boolean isSelectableComponentType() {
return selectableComponentType.get();
}
public void setEnabledTypes(List<ComponentType> enabledTypes) {
this.enabledTypes.set(enabledTypes);
}
@Override
public void changed(Device device, Region region) {
}
@Override
public void close() throws Exception {
view.removeListener(this);
device.removeListener(this);
snapToGridCheckBox.visibleProperty().unbind();
gridSizeSlider.visibleProperty().unbind();
selectableProperty().unbind();
viewer.readOnly().removeListener(readOnlyListener);
}
public ObjectProperty<ComponentType> componentType() {
return componentType;
}
public ComponentType getComponentType() {
return componentType.get();
}
public ObjectProperty<LabelFactory> labelFactory() {
return labelFactory;
}
public LabelFactory getLabelFactory() {
return labelFactory.get();
}
@Override
public List<CssMetaData<? extends Styleable, ?>> getCssMetaData() {
return FACTORY.getCssMetaData();
}
@Override
public List<IO> getElements() {
return items;
}
public List<ComponentType> getEnabledTypes() {
return enabledTypes.get();
}
public final double getGraphicTextGap() {
return graphicTextGap == null ? DEFAULT_GRAPHICS_TEXT_GAP : graphicTextGap.getValue();
}
@Override
public final MultipleSelectionModel<IO> getElementSelectionModel() {
return elementSelectionModel == null ? null : elementSelectionModel.get();
}
public final Color getLineColor() {
return lineColorProperty.getValue();
}
public final double getLineWidth() {
return lineWidth == null ? DEFAULT_LINE_WIDTH : lineWidth.getValue();
}
@Override
public Node getRoot() {
return this;
}
public final DoubleProperty graphicTextGapProperty() {
if (graphicTextGap == null) {
graphicTextGap = new StyleableDoubleProperty(4) {
@Override
public Object getBean() {
return LayoutEditor.this;
}
@Override
public CssMetaData<LayoutEditor, Number> getCssMetaData() {
return StyleableProperties.GRAPHIC_TEXT_GAP;
}
@Override
public String getName() {
return "graphicTextGap";
}
};
}
return graphicTextGap;
}
public final ObjectProperty<MultipleSelectionModel<IO>> elementSelectionModel() {
return elementSelectionModel;
}
@SuppressWarnings("unchecked")
public ObservableValue<Color> lineColorProperty() {
return (ObservableValue<Color>) lineColorProperty;
}
public final DoubleProperty lineWidthProperty() {
if (lineWidth == null) {
lineWidth = new StyleableDoubleProperty(DEFAULT_LINE_WIDTH) {
@Override
public Object getBean() {
return LayoutEditor.this;
}
@Override
public CssMetaData<LayoutEditor, Number> getCssMetaData() {
return StyleableProperties.LINE_WIDTH;
}
@Override
public String getName() {
return "lineWidth";
}
};
}
return lineWidth;
}
@Override
public void open(Device device, DeviceView view, Viewer viewer) {
this.view = view;
this.device = device;
this.viewer = viewer;
setEnabledTypes(viewer.getEnabledTypes());
gridSizeSlider.visibleProperty().set(!viewer.isReadOnly());
snapToGridCheckBox.visibleProperty().set(!viewer.isReadOnly());
JavaFX.bindManagedToVisible(snapToGridCheckBox);
JavaFX.bindManagedToVisible(gridSizeSlider);
snapToGridCheckBox.visibleProperty().bind(Bindings.not(viewer.readOnly()));
gridSizeSlider.visibleProperty().bind(Bindings.not(viewer.readOnly()));
setSelectable(viewer.isSelectableElements());
selectableProperty().bind(viewer.selectableElements());
readOnlyListener = (e, o, n) -> {
rebuildElements();
};
viewer.readOnly().addListener(readOnlyListener);
reloadImage();
canvas = new DeviceCanvas();
canvas.setPickOnBounds(false);
canvas.setMouseTransparent(true);
setDefaultClickHandler((e) -> {
requestFocus();
if (isLayoutSelectableElements())
clearSelection();
});
pane = new Pane();
pane.getStyleClass().add("layout");
pane.getStyleClass().add("padded");
pane.setPickOnBounds(false);
setContent(pane);
pane.getChildren().add(snapToGridCheckBox);
pane.getChildren().add(gridSizeSlider);
pane.getChildren().add(canvas);
widthProperty().addListener((e, o, n) -> layoutDiagram());
heightProperty().addListener((e, o, n) -> layoutDiagram());
view.addListener(this);
componentType.addListener((e, o, n) -> rebuildElements());
snapToGridCheckBox.selectedProperty().addListener((e, o, n) -> layoutDiagram());
gridSizeSlider.valueProperty().addListener((e, o, n) -> layoutDiagram());
rebuildComponentTypesPanel();
rebuildElements();
device.addListener(this);
}
@Override
public void refresh() {
if (Platform.isFxApplicationThread()) {
layoutDiagram();
if (isNeedImageChange())
reloadImage();
rebuildElements();
} else
Platform.runLater(() -> refresh());
}
public void setComponentType(ComponentType componentType) {
this.componentType.set(componentType);
}
public void setLabelFactory(LabelFactory labelFactory) {
this.labelFactory.set(labelFactory);
}
public final void setGraphicTextGap(double value) {
graphicTextGapProperty().setValue(value);
}
public final void setElementSelectionModel(MultipleSelectionModel<IO> value) {
elementSelectionModel().set(value);
}
public final void setLineColor(Color lineColor) {
lineColorProperty.setValue(lineColor);
}
public final void setLineWidth(double value) {
lineWidthProperty().setValue(value);
}
public final void setSelectionModel(MultipleSelectionModel<IO> value) {
elementSelectionModel().set(value);
}
@Override
public void updateFromMatrix(int[][][] frame) {
if (Platform.isFxApplicationThread()) {
DeviceView matrixView = null;
for (ElementView elementView : elementViews.get()) {
if (elementView.getElement() instanceof Area) {
if (matrixView == null) {
matrixView = view.getLayout().getViews().get(ViewPosition.MATRIX);
if (matrixView == null)
return;
}
Area area = (Area) elementView.getElement();
int[] rgb = new int[3];
int r = 0;
Region.Name region = area.getRegion();
for (IO cell : matrixView.getElements()) {
MatrixCell mc = (MatrixCell) cell;
if (mc.getRegion() == region) {
int[] rgbe = frame[mc.getMatrixY()][mc.getMatrixX()];
if (rgbe != null) {
rgb[0] += rgbe[0];
rgb[1] += rgbe[1];
rgb[2] += rgbe[2];
}
r++;
}
}
if (r > 0) {
elementView.getElementTool().setRGB(new int[] { rgb[0] / r, rgb[1] / r, rgb[2] / r });
}
} else if (elementView.getElement() instanceof MatrixIO) {
MatrixIO matrixIO = (MatrixIO) elementView.getElement();
if (matrixIO.isMatrixLED()) {
int[] rgb = frame[matrixIO.getMatrixY()][matrixIO.getMatrixX()];
if (rgb != null) {
elementView.getElementTool().setRGB(rgb);
}
}
}
}
} else
Platform.runLater(() -> updateFromMatrix(frame));
}
@Override
public void activeMapChanged(ProfileMap map) {
}
@Override
public void profileAdded(Profile profile) {
}
@Override
public void profileRemoved(Profile profile) {
}
protected void moveSelection(double mx, double my) {
Point2D imgSize = canvas.calcImageSize();
if (snapToGridCheckBox.isSelected()) {
double gw = Math.max(1, gridSizeSlider.valueProperty().get() * imgSize.getX());
double gh = Math.max(1, gridSizeSlider.valueProperty().get() * imgSize.getY());
mx *= gw;
my *= gh;
}
for (IO el : getElementSelectionModel().getSelectedItems()) {
el.setX((float) (el.getX() + ((1 / imgSize.getX()) * mx)));
el.setY((float) (el.getY() + ((1 / imgSize.getY()) * my)));
}
layoutElements();
layoutLabels();
canvas.draw();
}
protected void addToSelection(IO led) {
setFocused(true);
int idx = items.indexOf(led);
MultipleSelectionModel<IO> model = elementSelectionModel().get();
if (!model.getSelectedIndices().contains(idx)) {
model.select(idx);
}
}
protected void clearSelection() {
getElementSelectionModel().clearSelection();
}
protected ElementView createElementView(ComponentType type) {
ElementView elementView = new ElementView(type);
Tool elementTool = new Tool(elementView, this);
elementView.setElementTool(elementTool);
return elementView;
}
protected Node createLabel(IO el) {
LabelFactory factory = labelFactory.get();
if (factory != null) {
Node node = factory.createLabel(el);
if (node != null)
return node;
}
Label label = new Label(el.getDisplayLabel());
label.setOnMouseClicked((e) -> {
if (e.isControlDown())
addToSelection(el);
else
selectSingle(el);
e.consume();
});
label.getStyleClass().add("layout-label");
return label;
}
protected String findBestDefaultLabelText(ComponentType type) {
int highest = 0;
for (ElementView element : elementViews.get()) {
if (element.getType() == type) {
int number = -1;
try {
number = Integer.parseInt(element.getElement().getLabel());
} catch (Exception nfe) {
}
highest = Math.max(highest, number);
}
}
return String.valueOf(highest + 1);
}
protected ElementView forElement(IO element) {
for (ElementView e : elementViews.get()) {
if (e.getElement().equals(element))
return e;
}
return null;
}
protected String getFinalImageUrl() {
if (view.getImageUri() == null) {
BrandingImage bimg = view.getPosition().toBrandingImage();
if (bimg != null) {
return device.getImageUrl(bimg);
} else
return null;
} else {
return view.getResolvedImageUri(view.getLayout().getBase());
}
}
protected double getTotalHeight(List<ElementView> top) {
double totalTextHeight = 0;
for (ElementView el : top) {
if (totalTextHeight > 0)
totalTextHeight += getGraphicTextGap();
totalTextHeight += el.getLabel().getBoundsInLocal().getHeight();
}
return totalTextHeight;
}
protected double getTotalWidth(List<ElementView> top) {
double totalTextWidth = 0;
for (ElementView el : top) {
if (totalTextWidth > 0)
totalTextWidth += getGraphicTextGap();
totalTextWidth += el.getLabel().getBoundsInLocal().getWidth();
}
return totalTextWidth;
}
protected boolean isLayoutReadOnly() {
return view.getLayout().isReadOnly() || viewer.isReadOnly();
}
protected boolean isLayoutSelectableElements() {
return viewer.isSelectableElements();
}
protected boolean isNeedImageChange() {
return !Objects.equals(getFinalImageUrl(), loadedImage);
}
protected void layoutComponentTypes() {
Insets insets = pane.getInsets();
double y = insets.getTop();
/* Find max best width and height of the radio buttons and icons */
double w = 0;
double h = 0;
double rh = 0;
double ih = 0;
for (int i = 0; i < componentTypes.size(); i += 2) {
Node n = componentTypes.get(i);
w = Math.max(n.getLayoutBounds().getWidth() + getGraphicTextGap(), w);
rh = Math.max(n.getLayoutBounds().getHeight() + getGraphicTextGap(), rh);
n = componentTypes.get(i + 1);
ih = Math.max(n.getLayoutBounds().getHeight() + getGraphicTextGap(), i);
}
h = Math.max(rh, h);
/* Layout */
for (int i = 0; i < componentTypes.size(); i++) {
Node n = componentTypes.get(i);
if (i % 2 == 1) {
n.setLayoutY(y - ((ih - rh) / 2.0));
n.setLayoutX(insets.getLeft() + w);
y += h;
} else {
n.setLayoutY(y);
n.setLayoutX(insets.getLeft());
}
}
/* Redraw all of the graphics */
for (Node node : componentTypes) {
if (node instanceof Tool) {
((Tool) node).redraw();
}
}
/* Grid stuff */
snapToGridCheckBox.setLayoutX(insets.getLeft());
snapToGridCheckBox.setLayoutY(y);
y += snapToGridCheckBox.getLayoutBounds().getHeight() + getGraphicTextGap();
gridSizeSlider.setLayoutX(insets.getLeft());
gridSizeSlider.setLayoutY(y);
}
protected void layoutDiagram() {
/* Need this to make sure elements their preferred sizes */
applyCss();
layout();
/*
* Layout actual nodes first. Then draw connecting lines and other decoration
*/
/* Elements are place exactly where specified */
layoutElements();
/* Need this to make sure labels have their preferred sizes */
applyCss();
layout();
/* Arrange labels */
layoutLabels();
/* Arrange component types */
layoutComponentTypes();
/* Now draw background image, lines etc */
canvas.draw();
}
protected void layoutElements() {
Insets insets = pane.getInsets();
double canvasWidth = widthProperty().get() - insets.getLeft() - insets.getRight();
double canvasHeight = heightProperty().get() - insets.getTop() - insets.getBottom();
canvas.widthProperty().set(canvasWidth);
canvas.heightProperty().set(canvasHeight);
canvas.layoutXProperty().set(insets.getLeft());
canvas.layoutYProperty().set(insets.getTop());
Point2D imgSize = canvas.calcImageSize();
Point2D imgOff = canvas.calcImageOffset();
for (ElementView elementView : elementViews.get()) {
positionElement(imgSize, imgOff, elementView);
}
}
protected void layoutLabels() {
double canvasWidth = canvas.widthProperty().get();
double canvasHeight = canvas.heightProperty().get();
Insets insets = pane.getInsets();
List<ElementView> left = new ArrayList<>();
List<ElementView> top = new ArrayList<>();
List<ElementView> bottom = new ArrayList<>();
List<ElementView> right = new ArrayList<>();
for (ElementView remain : separateElements(left, top, bottom, right)) {
remain.getLabel().setVisible(false);
}
// double y = ((canvasHeight - (rowHeight * left.size())) / 2f);
double totalHeight = getTotalHeight(left);
double y = ((canvasHeight - (totalHeight)) / 2f);
/* Left */
for (ElementView elementView : left) {
elementView.getLabel().setVisible(true);
double rowHeight = elementView.getLabel().getLayoutBounds().getHeight();
positionLabelForElement(insets.getLeft(), y + insets.getTop(), elementView);
y += rowHeight;
}
/* Right */
// y = ((canvasHeight - (rowHeight * right.size())) / 2f);
totalHeight = getTotalHeight(right);
y = ((canvasHeight - (totalHeight)) / 2f);
for (ElementView elementView : right) {
elementView.getLabel().setVisible(true);
double rowHeight = elementView.getLabel().getLayoutBounds().getHeight();
positionLabelForElement(
insets.getLeft() + canvasWidth - elementView.getLabel().getBoundsInLocal().getWidth(),
y + insets.getTop(), elementView);
y += rowHeight;
}
/* Top */
double totalTextWidth = getTotalWidth(top);
double x = ((canvasWidth - totalTextWidth) / 2f);
for (ElementView elementView : top) {
elementView.getLabel().setVisible(true);
positionLabelForElement(x + insets.getLeft(), insets.getTop(), elementView);
x += elementView.getLabel().getBoundsInLocal().getWidth() + getGraphicTextGap();
}
/* Bottom */
totalTextWidth = getTotalWidth(bottom);
x = ((canvasWidth - totalTextWidth) / 2f);
for (ElementView elementView : bottom) {
elementView.getLabel().setVisible(true);
double rowHeight = elementView.getLabel().getLayoutBounds().getHeight();
positionLabelForElement(x + insets.getLeft(), insets.getTop() + canvasHeight - rowHeight, elementView);
x += elementView.getLabel().getBoundsInLocal().getWidth() + getGraphicTextGap();
}
}
protected void positionElement(ElementView elementView) {
positionElement(canvas.calcImageSize(), canvas.calcImageOffset(), elementView);
}
protected void positionElement(Point2D imgSize, Point2D imgOff, ElementView elementView) {
Insets insets = pane.getInsets();
Node node = elementView.getElementTool();
double x = insets.getLeft() + imgOff.getX() + (imgSize.getX() * elementView.getElement().getX())
- (node.layoutBoundsProperty().get().getWidth() / 2f);
node.layoutXProperty().set(x);
double y = insets.getTop() + imgOff.getY() + (imgSize.getY() * elementView.getElement().getY())
- (node.layoutBoundsProperty().get().getHeight() / 2f);
node.layoutYProperty().set(y);
elementView.redraw();
}
protected void positionLabelForElement(double x, double y, ElementView element) {
Node node = element.getLabel();
node.layoutXProperty().set(x);
node.layoutYProperty().set(y);
}
protected void reloadImage() {
String requiredImage = getFinalImageUrl();
img = requiredImage == null || requiredImage.equals("") ? null
: new Image(context.getCache().getCachedImage(requiredImage), 0, 0, true, true);
loadedImage = requiredImage;
}
protected void resnap() {
for (ElementView e : elementViews.get()) {
IO el = e.getElement();
el.setX((float) (el.getX() - (el.getX() % gridSizeSlider.getValue()) + (gridSizeSlider.getValue() / 2.0)));
el.setY((float) (el.getY() - (el.getY() % gridSizeSlider.getValue()) + (gridSizeSlider.getValue() / 2.0)));
}
layoutElements();
}
protected void retextLabels() {
for (ElementView elementView : elementViews.get()) {
if (elementView.getLabel() != null)
if (elementView.getLabel() instanceof Label)
((Label) elementView.getLabel()).textProperty().set(elementView.getElement().getDisplayLabel());
else
/* Recreate entirely if its not a label */
/*
* TODO: Might need some kind of clean up here in here the added component adds
* listeners etc
*/
elementView.setLabel(createLabel(elementView.getElement()));
}
pane.applyCss();
pane.layout();
}
protected void selectSingle(IO led) {
MultipleSelectionModel<IO> model = elementSelectionModel.get();
model.clearAndSelect(items.indexOf(led));
}
protected List<ElementView> separateElements(List<ElementView> left, List<ElementView> top,
List<ElementView> bottom, List<ElementView> right) {
List<ElementView> r = new ArrayList<ElementView>();
for (ElementView elementView : elementViews.get()) {
if (getComponentType().isShowByDefault()
&& !elementSelectionModel.get().getSelectedItems().contains(elementView.getElement())) {
r.add(elementView);
continue;
}
IO el = elementView.getElement();
if (el.getY() < 0.4 && el.getX() >= 0.4 && el.getX() < 0.6) {
top.add(elementView);
} else if (el.getY() > 0.6 && el.getX() >= 0.4 && el.getX() < 0.6) {
bottom.add(elementView);
} else if (el.getX() <= 0.5) {
left.add(elementView);
} else {
right.add(elementView);
}
}
Collections.sort(left, (el1, el2) -> {
return Float.valueOf(el1.getElement().getY()).compareTo(el2.getElement().getY());
});
Collections.sort(right, (el1, el2) -> {
return Float.valueOf(el1.getElement().getY()).compareTo(el2.getElement().getY());
});
Collections.sort(top, (el1, el2) -> {
return Float.valueOf(el1.getElement().getX()).compareTo(el2.getElement().getX());
});
Collections.sort(bottom, (el1, el2) -> {
return Float.valueOf(el1.getElement().getX()).compareTo(el2.getElement().getX());
});
Collections.sort(r, (el1, el2) -> {
return Float.valueOf(el1.getElement().getX()).compareTo(el2.getElement().getX());
});
return r;
}
void rebuildComponentTypesPanel() {
for (Node c : componentTypes) {
pane.getChildren().remove(c);
}
componentTypes.clear();
ToggleGroup group = new ToggleGroup();
Map<ComponentType, Tool> types = new HashMap<>();
List<ComponentType> typesToShow = enabledTypes.get();
if (isSelectableComponentType() && (typesToShow.size() > 1 || !isLayoutReadOnly())) {
for (ComponentType type : typesToShow) {
ElementView elementView = createElementView(type);
RadioButton r = new RadioButton(TabbedViewer.bundle.getString("componentTypeMenu." + type.name()));
r.getStyleClass().add("layout-selector-" + type.name());
r.setToggleGroup(group);
componentTypes.add(r);
componentTypes.add(elementView.getElementTool());
if (type == getComponentType()) {
r.selectedProperty().set(true);
}
if (type != getComponentType() || isLayoutReadOnly()) {
elementView.getElementTool().disableProperty().set(true);
}
r.selectedProperty().addListener((e) -> {
setComponentType(type);
for (Map.Entry<ComponentType, Tool> en : types.entrySet()) {
if (!isLayoutReadOnly() && en.getKey() == type && !isLayoutReadOnly())
en.getValue().disableProperty().set(false);
else
en.getValue().disableProperty().set(true);
}
});
types.put(type, elementView.getElementTool());
}
}
for (Node c : componentTypes) {
pane.getChildren().add(c);
}
applyCss();
layout();
layoutComponentTypes();
}
private void rebuildElements() {
/* Remove all existing labels and elements */
for (ElementView e : elementViews.get()) {
pane.getChildren().remove(e.getElementTool());
if (e.getLabel() != null)
pane.getChildren().remove(e.getLabel());
}
getElementSelectionModel().clearSelection();
elementViews.get().clear();
applyCss();
layout();
if (view != null) {
for (IO io : view.getElements()) {
ElementView ev = null;
if (io instanceof LED && isTypeToShow(ComponentType.LED)) {
ev = createElementView(ComponentType.LED);
} else if (io instanceof Key && isTypeToShow(ComponentType.KEY)) {
ev = createElementView(ComponentType.KEY);
} else if (io instanceof Area && isTypeToShow(ComponentType.AREA)) {
ev = createElementView(ComponentType.AREA);
} else if (io instanceof Accessory && isTypeToShow(ComponentType.ACCESSORY)) {
ev = createElementView(ComponentType.ACCESSORY);
}
if (ev != null) {
ev.setElement(io);
ev.setLabel(createLabel(io));
elementViews.get().add(ev);
pane.getChildren().add(ev.getLabel());
pane.getChildren().add(ev.getElementTool());
}
}
layoutDiagram();
}
}
protected boolean isTypeToShow(ComponentType type) {
boolean c = isSelectableComponentType();
return (!c && getEnabledTypes().contains(type)) || (c && getComponentType() == type);
}
@Override
public DeviceView getView() {
return view;
}
public ContextMenuCallback getMenuCallback() {
return menuCallback;
}
public void setMenuCallback(ContextMenuCallback menuCallback) {
this.menuCallback = menuCallback;
}
public static String getBestRegionName(DeviceView view, Name name) {
IO regionEl = view.getAreaElement(name);
if (regionEl != null && regionEl.getLabel() != null)
return regionEl.getLabel();
return name == null ? null : Strings.toName(name.toString());
}
public void reset() {
for (ElementView element : elementViews.get()) {
element.reset();
}
}
@Override
public void mapAdded(ProfileMap profile) {
}
@Override
public void mapChanged(ProfileMap profile) {
}
@Override
public void mapRemoved(ProfileMap profile) {
}
public void contextMenu(Tool tool, ContextMenuEvent e) {
if (menuCallback != null)
menuCallback.openContextMenu(tool, e);
}
@Override
public void elementRemoved(DeviceView view, IO element) {
if (Platform.isFxApplicationThread()) {
ElementView ev = forElement(element);
if (ev != null) {
int indexOf = elementViews.get().indexOf(ev);
getElementSelectionModel().clearSelection(indexOf);
elementViews.get().remove(ev);
JavaFX.fadeHide(ev.getElementTool(), 0.25f, (e) -> {
pane.getChildren().remove(ev.getElementTool());
layoutDiagram();
});
if (ev.getLabel() != null) {
JavaFX.fadeHide(ev.getLabel(), 0.25f, (e) -> {
pane.getChildren().remove(ev.getLabel());
layoutDiagram();
});
}
}
} else
Platform.runLater(() -> elementRemoved(view, element));
}
@Override
public void elementAdded(DeviceView view, IO element) {
elementChanged(view, element);
}
@Override
public void elementChanged(DeviceView view, IO element) {
if (Platform.isFxApplicationThread()) {
retextLabels();
layoutLabels();
} else
Platform.runLater(() -> elementChanged(view, element));
}
@Override
public void viewChanged(DeviceView view) {
if (Platform.isFxApplicationThread()) {
retextLabels();
layoutDiagram();
} else
Platform.runLater(() -> viewChanged(view));
}
List<Node> getComponentTypes() {
return componentTypes;
}
DeviceCanvas getCanvas() {
return canvas;
}
Pane getPane() {
return pane;
}
List<ElementView> getElementViews() {
return elementViews.get();
}
} | 43,340 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
ViewerView.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/designer/ViewerView.java | package uk.co.bithatch.snake.ui.designer;
import java.util.List;
import javafx.scene.Node;
import javafx.scene.control.MultipleSelectionModel;
import uk.co.bithatch.snake.lib.Device;
import uk.co.bithatch.snake.lib.layouts.DeviceView;
import uk.co.bithatch.snake.lib.layouts.IO;
public interface ViewerView extends AutoCloseable {
DeviceView getView();
void open(Device device, DeviceView view, Viewer viewer);
Node getRoot();
void refresh();
MultipleSelectionModel<IO> getElementSelectionModel();
default void updateFromMatrix(int[][][] frame) {
}
List<IO> getElements();
}
| 596 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
Tool.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/designer/Tool.java | package uk.co.bithatch.snake.ui.designer;
import java.util.HashMap;
import java.util.Map;
import org.kordamp.ikonli.fontawesome.FontAwesome;
import org.kordamp.ikonli.javafx.FontIcon;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Point2D;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import uk.co.bithatch.snake.lib.layouts.ComponentType;
import uk.co.bithatch.snake.lib.layouts.IO;
import uk.co.bithatch.snake.lib.layouts.MatrixIO;
import uk.co.bithatch.snake.ui.util.Delta;
import uk.co.bithatch.snake.ui.util.Maths;
import uk.co.bithatch.snake.widgets.AbstractGraphic;
import uk.co.bithatch.snake.widgets.AccessoryGraphic;
import uk.co.bithatch.snake.widgets.AreaGraphic;
import uk.co.bithatch.snake.widgets.JavaFX;
import uk.co.bithatch.snake.widgets.KeyGraphic;
import uk.co.bithatch.snake.widgets.LEDGraphic;
public class Tool extends StackPane {
private final Delta dragDelta = new Delta();
private double startX = -1, startY = -1;
private Map<ElementView, Point2D> selectedAtDragStart = new HashMap<>();
private ElementView elementView;
private LayoutEditor deviceViewerPane;
private Node graphic;
public Tool(ElementView elementView, LayoutEditor deviceViewerPane) {
super();
this.elementView = elementView;
this.deviceViewerPane = deviceViewerPane;
if (deviceViewerPane.isShowElementGraphics()) {
if (elementView.getType() == ComponentType.LED)
graphic = new LEDGraphic();
else if (elementView.getType() == ComponentType.KEY)
graphic = new KeyGraphic();
else if (elementView.getType() == ComponentType.AREA)
graphic = new AreaGraphic();
else if (elementView.getType() == ComponentType.ACCESSORY)
graphic = new AccessoryGraphic();
else
throw new UnsupportedOperationException();
} else {
graphic = new Label();
((Label)graphic).setGraphic(new FontIcon(FontAwesome.DOT_CIRCLE_O));
graphic.getStyleClass().add("smallIcon");
}
getChildren().add(graphic);
ComponentType type = elementView.getType();
getStyleClass().add("layout-tool");
getStyleClass().add("layout-tool-" + type.name().toLowerCase());
setOnMousePressed((e) -> startDrag(e));
setOnMouseReleased((e) -> endDrag(e));
setOnMouseDragged((e) -> dragMovement(e));
setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
if (!deviceViewerPane.isLayoutReadOnly()) {
setCursor(Cursor.HAND);
}
}
});
setOnContextMenuRequested((e) -> deviceViewerPane.contextMenu(this, e));
}
public void setRGB(int[] rgb) {
if (graphic instanceof AbstractGraphic)
((AbstractGraphic) graphic).setLedColor(JavaFX.toColor(rgb));
else
graphic.setStyle("-fx-text-fill: " + JavaFX.toHex(rgb));
}
void startDrag(MouseEvent mouseEvent) {
if (deviceViewerPane.isLayoutSelectableElements()) {
selectedAtDragStart.clear();
for (ElementView ev : deviceViewerPane.getElementViews()) {
if (deviceViewerPane.getElementSelectionModel().getSelectedItems().contains(ev.getElement())) {
selectedAtDragStart.put(ev,
new Point2D(ev.getElementTool().getLayoutX(), ev.getElementTool().getLayoutY()));
}
}
startX = getLayoutX();
startY = getLayoutY();
dragDelta.setX(startX - mouseEvent.getSceneX());
dragDelta.setY(startY - mouseEvent.getSceneY());
setCursor(Cursor.MOVE);
deviceViewerPane.requestFocus();
/*
* If this is different from the current selection, and not a mulitple selection
* (i.e. shift or ctrl modifier), then select the new element now
*/
if (deviceViewerPane.isLayoutSelectableElements() && !mouseEvent.isControlDown()
&& !mouseEvent.isShiftDown() && !deviceViewerPane.getElementSelectionModel().getSelectedItems()
.contains(elementView.getElement())) {
selectedAtDragStart.clear();
deviceViewerPane.selectSingle(elementView.getElement());
}
mouseEvent.consume();
}
}
void dragMovement(MouseEvent mouseEvent) {
if (startX > -1 && startY > -1) {
int idx = deviceViewerPane.getComponentTypes().indexOf(Tool.this);
if (idx != -1) {
/*
* Creating a new element. Remove this tool from the list so it doesnt get
* removed from the scene
*/
deviceViewerPane.getComponentTypes().remove(idx);
deviceViewerPane.getChildren().remove(deviceViewerPane.getComponentTypes().remove(idx - 1));
deviceViewerPane.rebuildComponentTypesPanel();
/*
* Attach a label to this element view. Look for a label and region from the
* matrix view if there is one.
*/
// String label = deviceViewerPane.findBestDefaultLabelText(elementView.getType());
//
// if (elementView.getElement() instanceof Area) {
// Area area = (Area) elementView.getElement();
// Set<Region.Name> available = new LinkedHashSet<>(deviceViewerPane.device.getRegionNames());
// for (IO el : deviceViewerPane.view.getElements()) {
// if (el instanceof Area) {
// Area a = (Area) el;
// if (a.getRegion() != null)
// available.remove(a.getRegion());
// }
// }
// if (!available.isEmpty()) {
// Name a = available.iterator().next();
// area.setRegion(a);
// label = Strings.toName(a.name());
// }
// }
if (elementView.getElement() instanceof MatrixIO) {
MatrixIO mio = (MatrixIO) elementView.getElement();
try {
((MatrixIO) mio).setMatrixXY(
deviceViewerPane.getView().getNextFreeCell(deviceViewerPane.componentType().get()));
} catch (IllegalStateException ise) {
}
// DeviceView matrixView = deviceViewerPane.view.getLayout().getViews().get(ViewPosition.MATRIX);
// if (matrixView != null) {
// MatrixCell otherElement = matrixView.getElement(ComponentType.MATRIX_CELL, mio.getMatrixX(),
// mio.getMatrixY());
// if (otherElement != null && otherElement.getLabel() != null) {
// label = otherElement.getLabel();
// }
// }
}
// elementView.getElement().setLabel(label);
elementView.setLabel(deviceViewerPane.createLabel(elementView.getElement()));
deviceViewerPane.getPane().getChildren().add(elementView.getLabel());
deviceViewerPane.getElementViews().add(elementView);
/*
* Needed to make sure the above label has proper sizes to be able to calculate
* line positions on first paint.
*/
applyCss();
layout();
} else if (deviceViewerPane.isLayoutReadOnly())
return;
setLayoutX(mouseEvent.getSceneX() + dragDelta.getX());
setLayoutY(mouseEvent.getSceneY() + dragDelta.getY());
double mx = getLayoutX() - startX;
double my = getLayoutY() - startY;
for (Map.Entry<ElementView, Point2D> en : selectedAtDragStart.entrySet()) {
if (en.getKey() != elementView) {
deviceViewerPane.getCanvas().updateElement(en.getKey(), en.getValue().getX() + mx,
en.getValue().getY() + my);
deviceViewerPane.positionElement(en.getKey());
}
}
Insets insets = deviceViewerPane.getPane().getInsets();
double toolX = layoutXProperty().get() + (layoutBoundsProperty().get().getWidth() / 2f);
double toolY = layoutYProperty().get() + (layoutBoundsProperty().get().getHeight() / 2f);
deviceViewerPane.getCanvas().updateElement(elementView, toolX - insets.getLeft(), toolY - insets.getTop());
deviceViewerPane.layoutLabels();
deviceViewerPane.getCanvas().draw();
}
}
void endDrag(MouseEvent mouseEvent) {
if (startX > -1 && startY > -1) {
double endX = layoutXProperty().get();
double endY = layoutYProperty().get();
double dist = Maths.distance(startX, startY, endX, endY);
IO element = elementView.getElement();
if (dist < 30) {
if (!deviceViewerPane.getView().getElements().contains(element)) {
if (deviceViewerPane.isLayoutSelectableElements())
deviceViewerPane.clearSelection();
deviceViewerPane.getElementViews().remove(elementView);
deviceViewerPane.getChildren().remove(elementView.getElementTool());
deviceViewerPane.getChildren().remove(elementView.getLabel());
deviceViewerPane.rebuildComponentTypesPanel();
deviceViewerPane.layoutDiagram();
} else {
if (deviceViewerPane.isLayoutSelectableElements() && mouseEvent.isControlDown()) {
deviceViewerPane.addToSelection(elementView.getElement());
}
}
} else {
Insets insets = deviceViewerPane.getPane().getInsets();
double toolX = endX + (layoutBoundsProperty().get().getWidth() / 2f);
double toolY = endY + (layoutBoundsProperty().get().getHeight() / 2f);
deviceViewerPane.getCanvas().updateElement(elementView, toolX - insets.getLeft(),
toolY - insets.getTop());
if (!deviceViewerPane.getView().getElements().contains(element)) {
deviceViewerPane.getView().addElement(element);
deviceViewerPane.addToSelection(element);
}
deviceViewerPane.layoutLabels();
deviceViewerPane.getCanvas().draw();
}
setCursor(Cursor.HAND);
startX = startY = -1;
}
mouseEvent.consume();
}
public void redraw() {
if (graphic instanceof AbstractGraphic)
((AbstractGraphic) graphic).draw();
}
public void setSelected(boolean selected) {
if (graphic instanceof AbstractGraphic)
((AbstractGraphic) graphic).setSelected(selected);
}
public void reset() {
if (graphic instanceof AbstractGraphic) {
((AbstractGraphic) graphic).setLedColor(null);
} else
graphic.setStyle(null);
}
} | 9,525 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
Viewer.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/designer/Viewer.java | package uk.co.bithatch.snake.ui.designer;
import java.util.List;
import javafx.beans.property.SimpleBooleanProperty;
import uk.co.bithatch.snake.lib.layouts.ComponentType;
public interface Viewer {
public interface ViewerListener {
void viewerSelected(ViewerView view);
}
void addListener(ViewerListener listener);
void removeListener(ViewerListener listener);
void removeSelectedElements();
List<ComponentType> getEnabledTypes();
void setEnabledTypes(List<ComponentType> enabledTypes);
SimpleBooleanProperty selectableElements();
SimpleBooleanProperty readOnly();
default void setReadOnly(boolean readOnly) {
readOnly().set(readOnly);
}
default boolean isReadOnly() {
return readOnly().get();
}
default void setSelectableElements(boolean selectableElements) {
selectableElements().set(selectableElements);
}
default boolean isSelectableElements() {
return selectableElements().get();
}
}
| 931 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
MatrixView.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/designer/MatrixView.java | package uk.co.bithatch.snake.ui.designer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javafx.application.Platform;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.MultipleSelectionModel;
import javafx.scene.control.OverrunStyle;
import javafx.scene.control.ToggleButton;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.Pane;
import uk.co.bithatch.snake.lib.Colors;
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;
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.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.KeyboardLayout;
import uk.co.bithatch.snake.ui.ListMultipleSelectionModel;
import uk.co.bithatch.snake.ui.util.BasicList;
import uk.co.bithatch.snake.ui.util.ListWrapper;
import uk.co.bithatch.snake.widgets.JavaFX;
import uk.co.bithatch.snake.widgets.SelectableArea;
public class MatrixView extends SelectableArea implements ViewerView, Listener {
static class MatrixCellButton extends ToggleButton {
private MatrixCell element;
private boolean partialDisable;
private int[] rgb;
public MatrixCellButton(MatrixView view, MatrixCell element) {
super();
this.element = element;
managedProperty().bind(visibleProperty());
Label butLabel = new Label(
element == null || element.getDisplayLabel() == null ? "" : element.getDisplayLabel());
butLabel.textOverrunProperty().set(OverrunStyle.CLIP);
graphicProperty().set(butLabel);
if (element != null && element.getWidth() > 0) {
minWidthProperty().set(element.getWidth() * 0.30);
}
if (element.isDisabled() || element.getDisplayLabel() == null) {
if (view.isLayoutReadOnly())
setVisible(false);
else
setPartialDisable(true);
}
getStyleClass().add("key");
var cell = element.getMatrixXY();
setRgb(Colors.COLOR_BLACK);
setOnMouseReleased((e) -> {
int deviceX = Integer.valueOf(view.view.getLayout().getMatrixWidth());
if (e.isShiftDown()) {
if (view.lastButton != null) {
int start = (deviceX * cell.getY()) + cell.getX();
int end = (deviceX * view.lastCell.getY()) + view.lastCell.getX();
if (start > end) {
int o = end;
end = start;
start = o;
}
for (int ii = start; ii <= end; ii++) {
int r = ii / deviceX;
Cell c = new Cell(ii - (r * deviceX), r);
MatrixCellButton b = view.buttons.get(c);
if (b != null) {
if (ii == start)
view.select(b.getElement());
else
view.toggleSelection(b.getElement());
}
}
}
} else if (e.isControlDown())
view.toggleSelection(element);
else {
view.select(element);
}
view.updateAvailability();
view.lastButton = this;
view.lastCell = cell;
e.consume();
});
}
public MatrixCellButton(String text) {
super(text);
}
public MatrixCellButton(String text, Node graphic) {
super(text, graphic);
}
public MatrixCell getElement() {
return element;
}
public int[] getRgb() {
return rgb;
}
public boolean isPartialDisable() {
return partialDisable;
}
public void setPartialDisable(boolean partialDisable) {
this.partialDisable = partialDisable;
setOpacity(partialDisable ? 0.5 : 1);
}
public void setRgb(int[] rgb) {
this.rgb = rgb;
getGraphic().setStyle(String.format("-fx-text-fill: %s", JavaFX.toHex(rgb)));
}
}
private Map<Cell, MatrixCellButton> buttons = new HashMap<>();
private Device device;
private Integer deviceX;
private Integer deviceY;
private ObjectProperty<ObservableList<MatrixCellButton>> elements = new SimpleObjectProperty<>(this, "elements");
private ListWrapper<MatrixCellButton, IO> items;
private Pane keyContainer;
private ObjectProperty<MultipleSelectionModel<IO>> keySelectionModel = new SimpleObjectProperty<MultipleSelectionModel<IO>>(
this, "keySelectionModel");
private MatrixCellButton lastButton;
private Cell lastCell;
private DeviceView view;
// private ScrollPane scroll;
private Viewer viewer;
{
// TODO will need when add back support for keyboard matrixes
// scroll = new ScrollPane();
// scroll.getStyleClass().add("focusless");
// scroll.getStyleClass().add("transparentBackground");
// scroll.setPickOnBounds(true);
// setContent(scroll);
elements.set(new BasicList<MatrixCellButton>());
items = new ListWrapper<MatrixCellButton, IO>(elements.get()) {
@Override
protected IO doConvertToWrapped(MatrixCellButton in) {
return in.getElement();
}
};
setDefaultClickHandler((e) -> clearSelection());
setKeySelectionModel(new ListMultipleSelectionModel<>(items));
setOnMouseClicked((e) -> {
requestFocus();
setFocused(true);
});
setFocusTraversable(true);
setOnKeyReleased((e) -> {
if (e.isControlDown() && e.getCode() == KeyCode.A) {
getElementSelectionModel().selectAll();
}
});
getElementSelectionModel().getSelectedIndices().addListener(new ListChangeListener<Integer>() {
@Override
public void onChanged(Change<? extends Integer> c) {
while (c.next()) {
if (c.wasRemoved()) {
for (Integer i : c.getRemoved()) {
MatrixCellButton button = elements.get().get(i);
button.selectedProperty().set(false);
}
}
if (c.wasAdded()) {
for (Integer i : c.getAddedSubList()) {
MatrixCellButton button = elements.get().get(i);
button.selectedProperty().set(true);
}
}
}
}
});
selectableArea().addListener((e, o, n) -> {
if (o == null && n != null) {
clearSelection();
}
if (n != null) {
for (MatrixCellButton b : elements.get()) {
if (n.intersects(b.getBoundsInParent())) {
addToSelection(b.getElement());
}
}
}
});
}
@Override
public void changed(Device device, Region region) {
}
@Override
public void close() throws Exception {
device.removeListener(this);
}
public void deselectAll() {
for (MatrixCellButton b : buttons.values())
b.selectedProperty().set(false);
updateAvailability();
}
@Override
public List<IO> getElements() {
return items;
}
public final MultipleSelectionModel<IO> getElementSelectionModel() {
return keySelectionModel == null ? null : keySelectionModel.get();
}
@Override
public Node getRoot() {
return this;
}
public final ObjectProperty<MultipleSelectionModel<IO>> keySelectionModel() {
return keySelectionModel;
}
@Override
public void open(Device device, DeviceView view, Viewer viewer) {
this.view = view;
this.device = device;
this.viewer = viewer;
deviceX = Integer.valueOf(view.getLayout().getMatrixWidth());
deviceY = Integer.valueOf(view.getLayout().getMatrixHeight());
if (deviceY == 1) {
/*
* If a single row matrix, then wrap in flow pane so we can show everything
* without any scrolling
*/
FlowPane flow = new FlowPane();
flow.getStyleClass().add("spaced");
getStyleClass().add("single-row-matrix");
flow.setAlignment(Pos.CENTER);
// scroll.setFitToHeight(true);
// scroll.setFitToWidth(true);
keyContainer = flow;
// scroll.setHbarPolicy(ScrollBarPolicy.AS_NEEDED);
// scroll.setVbarPolicy(ScrollBarPolicy.NEVER);
} else {
KeyboardLayout layout = new KeyboardLayout();
getStyleClass().add("multi-row-matrix");
layout.xProperty().set(deviceX);
layout.yProperty().set(deviceY);
// scroll.setHbarPolicy(ScrollBarPolicy.AS_NEEDED);
// scroll.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);
keyContainer = layout;
}
rebuildElements();
// scroll.setContent(keyContainer);
keyContainer.setPickOnBounds(false);
// scroll.setPickOnBounds(false);
setContent(keyContainer);
device.addListener(this);
view.addListener(new DeviceView.Listener() {
@Override
public void viewChanged(DeviceView view) {
if (Platform.isFxApplicationThread())
retextLabels();
else
Platform.runLater(() -> viewChanged(view));
}
@Override
public void elementAdded(DeviceView view, IO element) {
viewChanged(view);
}
@Override
public void elementChanged(DeviceView view, IO element) {
viewChanged(view);
}
@Override
public void elementRemoved(DeviceView view, IO element) {
viewChanged(view);
}
});
}
@Override
public void refresh() {
if (Platform.isFxApplicationThread()) {
rebuildElements();
} else
Platform.runLater(() -> refresh());
}
public final void setKeySelectionModel(MultipleSelectionModel<IO> value) {
keySelectionModel().set(value);
}
@Override
public void updateFromMatrix(int[][][] frame) {
if (Platform.isFxApplicationThread()) {
for (MatrixCellButton elementView : elements.get()) {
if (elementView.getElement() instanceof MatrixIO) {
MatrixIO matrixIO = (MatrixIO) elementView.getElement();
int[] rgb = frame[matrixIO.getMatrixY()][matrixIO.getMatrixX()];
if (rgb == null)
rgb = Colors.COLOR_BLACK;
elementView.setRgb(rgb);
}
}
} else
Platform.runLater(() -> updateFromMatrix(frame));
}
protected void addToSelection(IO element) {
keySelectionModel().get().select(items.indexOf(element));
}
protected void clearSelection() {
keySelectionModel().get().clearSelection();
}
protected void clearSelection(IO element) {
keySelectionModel().get().clearSelection(items.indexOf(element));
}
protected boolean isLayoutReadOnly() {
return view.getLayout().isReadOnly() || viewer.isReadOnly();
}
protected void retextLabels() {
for (MatrixCellButton elementView : elements.get()) {
((Label) elementView.getGraphic()).textProperty().set(elementView.getElement().getLabel());
if (elementView.getElement().getWidth() > 0) {
elementView.minWidthProperty().set(elementView.getElement().getWidth() * 0.30);
elementView.prefWidthProperty().set(elementView.getElement().getWidth() * 0.30);
} else {
elementView.minWidthProperty().set(USE_PREF_SIZE);
}
if (isLayoutReadOnly())
elementView.visibleProperty().set(!elementView.getElement().isDisabled());
else
elementView.setPartialDisable(elementView.getElement().isDisabled());
}
layout();
}
protected void select(IO element) {
int idx = items.indexOf(element);
keySelectionModel().get().clearAndSelect(idx);
}
protected void toggleSelection(IO element) {
int idx = items.indexOf(element);
if (keySelectionModel().get().isSelected(idx)) {
keySelectionModel().get().clearSelection(idx);
} else {
keySelectionModel().get().select(idx);
}
}
private MatrixCellButton createKeyButton(MatrixCell key) {
MatrixCellButton but = new MatrixCellButton(this, key);
KeyboardLayout.setCol(but, key.getMatrixX());
KeyboardLayout.setRow(but, key.getMatrixY());
buttons.put(but.getElement().getMatrixXY(), but);
return but;
}
private void rebuildElements() {
keyContainer.getChildren().clear();
elements.get().clear();
for (int i = 0; i < deviceY; i++) {
for (int j = 0; j < deviceX; j++) {
MatrixCellButton but;
MatrixCell key = view.getElement(ComponentType.MATRIX_CELL, j, i);
if (key != null) {
but = createKeyButton(key);
keyContainer.getChildren().add(but);
elements.get().add(but);
}
}
}
}
private void updateAvailability() {
}
public final static List<MatrixIO> expandMatrixElements(DeviceLayout layout, Collection<IO> elements) {
List<MatrixIO> expanded = new ArrayList<>();
DeviceView matrixView = null;
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) {
expanded.add(mc);
}
}
} else if (element instanceof MatrixIO) {
if (((MatrixIO) element).isMatrixLED())
expanded.add((MatrixIO) element);
}
}
return expanded;
}
@Override
public DeviceView getView() {
return view;
}
@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) {
}
}
| 13,284 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
TabbedViewer.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/designer/TabbedViewer.java | package uk.co.bithatch.snake.ui.designer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableListBase;
import javafx.scene.control.MultipleSelectionModel;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import uk.co.bithatch.snake.lib.Device;
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.ViewPosition;
import uk.co.bithatch.snake.ui.App;
import uk.co.bithatch.snake.ui.Confirm;
import uk.co.bithatch.snake.ui.ListMultipleSelectionModel;
import uk.co.bithatch.snake.ui.util.BasicList;
import uk.co.bithatch.snake.widgets.Direction;
public class TabbedViewer extends TabPane implements Viewer {
final static ResourceBundle bundle = ResourceBundle.getBundle(TabbedViewer.class.getName());
private List<DeviceView> views = new ArrayList<>();
private List<ViewerView> viewerViews = new ArrayList<>();
private Map<Tab, ViewerView> tabMap = new HashMap<>();
private List<ViewPosition> exclude = new ArrayList<>();
private List<ViewPosition> include = new ArrayList<>();
private ObjectProperty<List<ComponentType>> enabledTypes = new SimpleObjectProperty<>(this, "enabledTypes");
private App context;
private Device device;
private boolean needRefresh;
private boolean adjusting;
private List<ViewerListener> listeners = new ArrayList<>();
private SimpleBooleanProperty readOnly = new SimpleBooleanProperty();
private SimpleBooleanProperty selectableElements = new SimpleBooleanProperty(true);
public TabbedViewer(App context, Device device) {
super();
this.context = context;
this.device = device;
enabledTypes.set(new BasicList<>());
Set<ComponentType> types = device.getSupportedComponentTypes();
if(context.getMacroManager().isSupported(device)) {
types.add(ComponentType.KEY);
}
setEnabledTypes(new ArrayList<>(types));
setKeySelectionModel(new ListMultipleSelectionModel<>(new ObservableListBase<>() {
@Override
public IO get(int index) {
return getSelectedView().getElements().get(index);
}
@Override
public int size() {
return getSelectedView().getElements().size();
}
}));
getSelectionModel().selectedIndexProperty().addListener((e, o, n) -> {
/*
* When tab changes, clear OUR current key selection and transfer from the newly
* selected view
*/
MultipleSelectionModel<IO> newKsv = viewerViews.get(n.intValue()).getElementSelectionModel();
MultipleSelectionModel<IO> parentKsv = getKeySelectionModel();
parentKsv.clearSelection();
ViewerView selectedViewerView = getSelectedViewerView();
for (int idx : newKsv.getSelectedIndices()) {
parentKsv.select(selectedViewerView.getElements().get(idx));
}
for (int i = listeners.size() - 1; i >= 0; i--)
listeners.get(i).viewerSelected(selectedViewerView);
refresh();
});
tabDragPolicyProperty().set(TabDragPolicy.REORDER);
getTabs().addListener(new ListChangeListener<>() {
@Override
public void onChanged(Change<? extends Tab> c) {
if (!adjusting) {
List<DeviceView> newViews = new ArrayList<>();
for (Tab tab : getTabs()) {
ViewerView view = tabMap.get(tab);
newViews.add(view.getView());
}
/* TODO: make this better. What if views are being hidden? */
TabbedViewer.this.views.clear();
TabbedViewer.this.views.addAll(newViews);
layout.setViews(newViews);
}
}
});
}
public void addListener(ViewerListener listener) {
this.listeners.add(listener);
}
public void removeListener(ViewerListener listener) {
this.listeners.remove(listener);
}
@Override
public List<ComponentType> getEnabledTypes() {
return enabledTypes.get();
}
@Override
public void setEnabledTypes(List<ComponentType> enabledTypes) {
this.enabledTypes.set(enabledTypes);
}
public ObjectProperty<List<ComponentType>> enabledTypes() {
return enabledTypes;
}
public SimpleBooleanProperty readOnly() {
return readOnly;
}
public SimpleBooleanProperty selectableElements() {
return selectableElements;
}
@Override
protected void layoutChildren() {
super.layoutChildren();
if (needRefresh) {
/*
* NOTE: Workaround. Because the LayoutEditor added to this component is a tab,
* and at the time of adding it, the parent hierarchy is not fully known (tab
* not visible), the first render is wrong as font metrics and other styling
* cannot be determined.
*
* To fix this we do a full layout once the first time this is called after that
* tab has been added
*/
needRefresh = false;
refresh();
}
}
public final void setKeySelectionModel(MultipleSelectionModel<IO> value) {
keySelectionModel().set(value);
}
public List<ViewPosition> getExclude() {
return exclude;
}
public List<ViewPosition> getInclude() {
return include;
}
private ObjectProperty<MultipleSelectionModel<IO>> keySelectionModel = new SimpleObjectProperty<MultipleSelectionModel<IO>>(
this, "keySelectionModel");
private DeviceLayout layout;
public void setSelectionMode(SelectionMode selectionMode) {
getKeySelectionModel().setSelectionMode(selectionMode);
for (ViewerView viewerView : viewerViews) {
viewerView.getElementSelectionModel().setSelectionMode(selectionMode);
}
}
public IO getSelectedElement() {
int selIdx = getSelectedViewerView().getElementSelectionModel().getSelectedIndex();
return selIdx == -1 ? null : getSelectedViewerView().getElements().get(selIdx);
}
public List<IO> getSelectedElements() {
List<IO> sel = new ArrayList<>();
List<IO> elements = getSelectedViewerView().getElements();
for (int idx : getSelectedViewerView().getElementSelectionModel().getSelectedIndices()) {
sel.add(elements.get(idx));
}
return sel;
}
public final void setSelectionModel(MultipleSelectionModel<IO> value) {
keySelectionModel().set(value);
}
public final MultipleSelectionModel<IO> getKeySelectionModel() {
return keySelectionModel == null ? null : keySelectionModel.get();
}
public final ObjectProperty<MultipleSelectionModel<IO>> keySelectionModel() {
return keySelectionModel;
}
public void setLayout(DeviceLayout layout) {
this.layout = layout;
getTabs().clear();
if (this.layout != null) {
for (DeviceView view : layout.getViews().values()) {
addView(view);
}
}
}
public void addView(DeviceView view) {
boolean inc = include.isEmpty() || include.contains(view.getPosition());
if (inc)
inc = exclude.isEmpty() || !exclude.contains(view.getPosition());
if (inc) {
ViewerView viewerView = createViewerView(view);
viewerView.getElementSelectionModel().selectionModeProperty().set(keySelectionModel.get().getSelectionMode());
addTab(viewerView, view);
onAddView(view, viewerView);
}
}
public void refresh() {
for (ViewerView view : viewerViews) {
view.refresh();
}
}
public boolean isLayoutReadOnly() {
return layout.isReadOnly() || isReadOnly();
}
public void selectView(DeviceView view) {
int idx = views.indexOf(view);
if (idx != -1) {
getSelectionModel().select(idx);
}
}
public void removeView(DeviceView view) {
int idx = views.indexOf(view);
if (idx != -1) {
views.remove(idx);
getTabs().remove(idx);
}
}
ViewerView createViewerView(DeviceView view) {
switch (view.getPosition()) {
case MATRIX:
return new MatrixView();
default:
return new LayoutEditor(context);
}
}
void addTab(ViewerView viewerView, DeviceView view) {
adjusting = true;
try {
views.add(view);
viewerViews.add(viewerView);
Tab tab = new Tab(bundle.getString("viewPosition." + view.getPosition().name()));
tab.setContent(viewerView.getRoot());
tab.setClosable(false);
tabMap.put(tab, viewerView);
needRefresh = true;
viewerView.open(device, view, this);
view.addListener((e) -> {
tab.setText(bundle.getString("viewPosition." + view.getPosition().name()));
});
MultipleSelectionModel<IO> ksv = viewerView.getElementSelectionModel();
MultipleSelectionModel<IO> parentKsv = getKeySelectionModel();
ksv.selectedIndexProperty().addListener((e, oldVal, newVal) -> {
if (ksv.getSelectedIndex() == -1) {
parentKsv.clearSelection();
} else {
List<Integer> sel = new ArrayList<>(ksv.getSelectedIndices());
for (Integer idx : sel) {
IO io = viewerView.getElements().get(idx);
parentKsv.select(io);
}
}
});
getTabs().add(tab);
} finally {
adjusting = false;
}
}
public void deselectAll() {
getSelectedViewerView().getElementSelectionModel().clearSelection();
}
public void selectAll() {
getSelectedViewerView().getElementSelectionModel().selectAll();
}
public ViewerView getSelectedViewerView() {
int idx = selectionModelProperty().get().getSelectedIndex();
return idx == -1 ? null : viewerViews.get(idx);
}
public DeviceView getSelectedView() {
int idx = selectionModelProperty().get().getSelectedIndex();
return idx == -1 ? null : views.get(idx);
}
public DeviceLayout getLayout() {
return layout;
}
public List<DeviceView> getViews() {
return views;
}
public void cleanUp() {
for (ViewerView view : viewerViews) {
try {
view.close();
} catch (Exception e) {
}
}
}
public void updateFromMatrix(int[][][] frame) {
for (ViewerView view : viewerViews) {
try {
view.updateFromMatrix(frame);
} catch (Exception e) {
}
}
}
public void removeSelectedElements() {
List<IO> els = getSelectedElements();
if (els.size() == 1)
getSelectedView().removeElement(getSelectedElement());
else if (!els.isEmpty()) {
Confirm confirm = context.push(Confirm.class, Direction.FADE);
confirm.confirm(bundle, "removeMultipleElements", () -> {
for (int i = els.size() - 1; i >= 0; i--)
getSelectedView().removeElement(els.get(i));
}, els.size());
}
}
protected void updateTabOrder() {
}
protected void onAddView(DeviceView view, ViewerView viewerView) {
}
}
| 10,459 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
ElementView.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/designer/ElementView.java | package uk.co.bithatch.snake.ui.designer;
import javafx.scene.Node;
import uk.co.bithatch.snake.lib.layouts.ComponentType;
import uk.co.bithatch.snake.lib.layouts.IO;
public class ElementView {
private ComponentType type;
private Tool elementTool;
private Node label;
private IO element;
public ElementView(ComponentType type) {
super();
this.type = type;
element = type.createElement();
}
public ComponentType getType() {
return type;
}
public void setType(ComponentType type) {
this.type = type;
}
public Tool getElementTool() {
return elementTool;
}
public void setElementTool(Tool elementTool) {
this.elementTool = elementTool;
}
public Node getLabel() {
return label;
}
public void setLabel(Node label) {
this.label = label;
}
public IO getElement() {
return element;
}
public void setElement(IO element) {
this.element = element;
}
@Override
public String toString() {
return "ElementView [type=" + type + ", elementTool=" + elementTool + ", label=" + label + ", element="
+ element + "]";
}
public void redraw() {
elementTool.redraw();
}
public void reset() {
elementTool.reset();
}
} | 1,167 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
JImpulseAudioBackend.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/audio/JImpulseAudioBackend.java | package uk.co.bithatch.snake.ui.audio;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import uk.co.bithatch.jimpulse.Impulse;
import uk.co.bithatch.snake.ui.audio.AudioManager.AudioSink;
import uk.co.bithatch.snake.ui.audio.AudioManager.AudioSource;
/**
* Deprecated. This will be replaced with proper Java pulse bindings,
*/
@Deprecated
public class JImpulseAudioBackend implements AudioBackend {
private Impulse impulse;
private AudioManager manager;
public JImpulseAudioBackend(AudioManager manager) {
impulse = new Impulse();
this.manager = manager;
}
@Override
public void setSourceIndex(int index) {
impulse.setSourceIndex(index);
}
@Override
public void init() {
impulse.initImpulse();
}
@Override
public void stop() {
impulse.stop();
}
@Override
public double[] getSnapshot(boolean fft) {
return impulse.getSnapshot(fft);
}
@Override
public List<AudioSource> getSources() {
/* TODO add this to jimpulse so we can get a list of devices more generally? */
/* TODO or make more efficient and not load so much */
ProcessBuilder pb = new ProcessBuilder("pacmd", "list-sources");
pb.redirectErrorStream(true);
try {
Process p = pb.start();
List<AudioSource> l = new ArrayList<>();
String name = null;
int index = -1;
try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line;
while ((line = r.readLine()) != null) {
line = line.trim();
if(line.startsWith("*")) {
/* Don't care if active or not */
line = line.substring(2);
}
if (line.startsWith("index: ")) {
if (name != null && index != -1) {
l.add(new AudioSource(index, name));
name = null;
}
index = Integer.parseInt(line.substring(7));
}
if (index != -1 && line.startsWith("name: ")) {
name = line.substring(6);
}
if (index != -1 && line.startsWith("device.description = \"")) {
name = line.substring(22, line.length() - 1);
}
}
}
if (name != null && index != -1) {
l.add(new AudioSource(index, name));
}
try {
int ret = p.waitFor();
if (ret != 0)
throw new IOException(String.format("Could not list sources. Exited with value %d.", ret));
} catch (InterruptedException ie) {
}
return l;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Failed to get sources.");
}
}
@Override
public List<AudioSink> getSinks() {
/* TODO add this to jimpulse so we can get a list of devices more generally? */
/* TODO or make more efficient and not load so much */
ProcessBuilder pb = new ProcessBuilder("pacmd", "list-sinks");
pb.redirectErrorStream(true);
try {
Process p = pb.start();
List<AudioSink> l = new ArrayList<>();
String name = null;
int index = -1;
try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line;
while ((line = r.readLine()) != null) {
line = line.trim();
if(line.startsWith("*")) {
/* Don't care if active or not */
line = line.substring(2);
}
if (line.startsWith("index: ")) {
if (name != null && index != -1) {
l.add(new AudioSink(index, name));
name = null;
}
index = Integer.parseInt(line.substring(7));
}
if (index != -1 && line.startsWith("name: ")) {
name = line.substring(6);
}
if (index != -1 && line.startsWith("device.description = \"")) {
name = line.substring(22, line.length() - 1);
}
}
}
if (name != null && index != -1) {
l.add(new AudioSink(index, name));
}
try {
int ret = p.waitFor();
if (ret != 0)
throw new IOException(String.format("Could not list sources. Exited with value %d.", ret));
} catch (InterruptedException ie) {
}
return l;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Failed to get sources.");
}
}
@Override
public int getVolume(AudioSink sink) {
ProcessBuilder pb = new ProcessBuilder("pacmd", "list-sinks");
pb.redirectErrorStream(true);
try {
Process p = pb.start();
boolean read = false;
try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line;
while ((line = r.readLine()) != null) {
line = line.trim();
if (line.startsWith("index: ")) {
if (read)
break;
int index = Integer.parseInt(line.substring(7));
if (index == sink.getIndex()) {
read = true;
}
}
if (read) {
if (line.startsWith("volume: ")) {
String[] parts = line.split("\\s+");
int ch = 0;
int t = 0;
for (String pa : parts) {
if (pa.endsWith("%")) {
ch++;
t += Integer.parseInt(pa.substring(0, pa.length() - 1));
}
}
System.out.println("tv " + t + " of " + ch + " for " + sink.getName() + " : "
+ sink.getIndex() + " " + line);
return t / ch;
}
}
}
} finally {
try {
int ret = p.waitFor();
if (ret != 0)
throw new IOException(String.format("Could not get volume. Exited with value %d.", ret));
} catch (InterruptedException ie) {
}
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Failed to get volume.");
}
return 0;
}
@Override
public void setVolume(AudioSink sink, int volume) {
int volVal = (int) ((float) 65536 * ((float) volume / 100.0));
System.out.println("set vol " + sink.getIndex() + " to " + volVal);
ProcessBuilder pb = new ProcessBuilder("pacmd", "set-sink-volume", String.valueOf(sink.getName()),
String.valueOf(volVal));
pb.redirectErrorStream(true);
try {
Process p = pb.start();
try {
p.getInputStream().transferTo(System.out);
int ret = p.waitFor();
if (ret != 0)
throw new IOException(String.format("Could not set volume. Exited with value %d.", ret));
manager.fireVolumeChange(sink);
} catch (InterruptedException ie) {
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Failed to set volume.");
}
}
@Override
public boolean isMuted(AudioSink sink) {
ProcessBuilder pb = new ProcessBuilder("pacmd", "list-sinks");
pb.redirectErrorStream(true);
try {
Process p = pb.start();
boolean read = false;
try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line;
while ((line = r.readLine()) != null) {
line = line.trim();
if (line.startsWith("index: ")) {
if (read)
break;
int index = Integer.parseInt(line.substring(7));
if (index == sink.getIndex()) {
read = true;
}
}
if (read) {
if (line.startsWith("muted: ")) {
return line.substring(7).equals("yes");
}
}
}
} finally {
try {
int ret = p.waitFor();
if (ret != 0)
throw new IOException(String.format("Could not list sources. Exited with value %d.", ret));
} catch (InterruptedException ie) {
}
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Failed to get sources.");
}
return false;
}
@Override
public void setMuted(AudioSink sink, boolean muted) {
ProcessBuilder pb = new ProcessBuilder("pacmd", "set-sink-mute", String.valueOf(sink.getIndex()),
String.valueOf(muted));
pb.redirectErrorStream(true);
try {
Process p = pb.start();
try {
p.getInputStream().transferTo(System.out);
int ret = p.waitFor();
if (ret != 0)
throw new IOException(String.format("Could not mute. Exited with value %d.", ret));
manager.fireVolumeChange(sink);
} catch (InterruptedException ie) {
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Failed to set volume.");
}
}
}
| 8,112 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
AudioManager.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/audio/AudioManager.java | package uk.co.bithatch.snake.ui.audio;
import java.io.Closeable;
import java.io.IOException;
import java.lang.System.Logger.Level;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import uk.co.bithatch.snake.lib.Device;
import uk.co.bithatch.snake.lib.animation.AudioDataProvider;
import uk.co.bithatch.snake.ui.App;
import uk.co.bithatch.snake.ui.Configuration;
import uk.co.bithatch.snake.ui.SchedulerManager.Queue;
public class AudioManager implements Closeable, PreferenceChangeListener, AudioDataProvider {
final static System.Logger LOG = System.getLogger(AudioManager.class.getName());
public interface Listener {
void snapshot(double[] snapshot);
}
public interface VolumeListener {
void volumeChanged(Device sink, int volume);
}
public static class AudioSource {
private int index;
private String name;
public AudioSource(int index, String name) {
super();
this.index = index;
this.name = name;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
public static class AudioSink {
private int index;
private String name;
public AudioSink(int index, String name) {
super();
this.index = index;
this.name = name;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
private App context;
private double[] snapshot = new double[256];
private List<Listener> listeners = Collections.synchronizedList(new ArrayList<>());
private List<VolumeListener> volumeListeners = Collections.synchronizedList(new ArrayList<>());
private AudioBackend backend;
private ScheduledFuture<?> grabTask;
private Configuration cfg;
private ScheduledExecutorService queue;
private Throwable error;
public AudioManager(App context) {
this.context = context;
cfg = context.getConfiguration();
queue = context.getSchedulerManager().get(Queue.AUDIO);
cfg.getNode().addPreferenceChangeListener(this);
backend = createBackend();
}
public boolean hasVolume(Device device) {
for (AudioSink sink : getSinks()) {
if (sink.getName().startsWith(device.getName())) {
return true;
}
}
return false;
}
public boolean isMuted(Device device) {
for (AudioSink sink : getSinks()) {
if (sink.getName().startsWith(device.getName())) {
return backend.isMuted(sink);
}
}
return false;
}
public void setMuted(Device device, boolean muted) {
for (AudioSink sink : getSinks()) {
if (sink.getName().startsWith(device.getName())) {
backend.setMuted(sink, muted);
return;
}
}
}
public int getVolume(Device device) {
for (AudioSink sink : getSinks()) {
if (sink.getName().startsWith(device.getName())) {
return backend.getVolume(sink);
}
}
return 0;
}
public void setVolume(Device device, int volume) {
for (AudioSink sink : getSinks()) {
if (sink.getName().startsWith(device.getName())) {
System.out.println();
backend.setVolume(sink, volume);
return;
}
}
}
public List<AudioSource> getSources() {
return backend == null ? Collections.emptyList() : backend.getSources();
}
public List<AudioSink> getSinks() {
return backend == null ? Collections.emptyList() : backend.getSinks();
}
public Throwable getError() {
return error;
}
public void removeListener(Listener listener) {
listeners.remove(listener);
}
public void addListener(Listener listener) {
synchronized (listeners) {
checkMonitoring();
listeners.add(listener);
}
}
public void removeVolumeListener(VolumeListener listener) {
volumeListeners.remove(listener);
}
public void addVolumeListener(VolumeListener listener) {
synchronized (listeners) {
volumeListeners.add(listener);
}
}
protected void checkMonitoring() {
if (grabTask == null) {
try {
AudioSource source = getSource();
if (source != null)
backend.setSourceIndex(source.getIndex());
ScheduledExecutorService queue = context.getSchedulerManager().get(Queue.AUDIO);
queue.submit(() -> backend.init());
scheduleGrabbing(queue);
} catch (Exception e) {
LOG.log(Level.ERROR, "Failed to initialise audio system backend. No audio features will be available.");
error = e;
}
}
}
public void setSource(AudioSource source) {
context.getConfiguration().setAudioSource(source.getName());
}
public AudioSource getSource() {
AudioSource source = getSource(context.getConfiguration().getAudioSource());
if (source == null) {
List<AudioSource> sources = getSources();
return sources.isEmpty() ? null : sources.get(0);
}
return source;
}
public AudioSource getSource(int index) {
for (AudioSource s : getSources()) {
if (s.getIndex() == index)
return s;
}
return null;
}
public AudioSource getSource(String name) {
for (AudioSource s : getSources()) {
if (name.equals(s.getName()))
return s;
}
return null;
}
protected void scheduleGrabbing(ScheduledExecutorService queue) {
int delay = 1000 / Math.max(1, cfg.getAudioFPS());
grabTask = queue.scheduleAtFixedRate(() -> grab(), 0, delay, TimeUnit.MILLISECONDS);
}
public double[] getSnapshot() {
synchronized (listeners) {
checkMonitoring();
return snapshot;
}
}
@Override
public void close() throws IOException {
if (grabTask != null) {
grabTask.cancel(false);
}
queue.shutdown();
try {
queue.awaitTermination(3, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
if (backend != null) {
backend.stop();
backend = null;
}
}
void grab() {
synchronized (listeners) {
snapshot = backend.getSnapshot(cfg.isAudioFFT());
float gain = cfg.getAudioGain();
if (gain != 1) {
for (int i = 0; i < snapshot.length; i++)
snapshot[i] = Math.min(1, snapshot[i] * gain);
}
for (int i = listeners.size() - 1; i >= 0; i--)
listeners.get(i).snapshot(snapshot);
}
}
@Override
public void preferenceChange(PreferenceChangeEvent evt) {
if (evt.getKey().equals(Configuration.PREF_AUDIO_SOURCE)) {
if (backend != null) {
queue.submit(() -> backend.setSourceIndex(getSource().getIndex()));
}
} else if (evt.getKey().equals(Configuration.PREF_AUDIO_FPS)) {
if (grabTask != null)
grabTask.cancel(false);
scheduleGrabbing(queue);
}
}
protected AudioBackend createBackend() {
try {
if(Boolean.getBoolean("snake.noJimpulse"))
throw new Exception("Disable by user.");
else
return new JImpulseAudioBackend(this);
} catch (UnsatisfiedLinkError | Exception e) {
error = e;
if (LOG.isLoggable(Level.DEBUG))
LOG.log(Level.ERROR, "Failed to setup audio backend. Do you have libfftw-3 installed?", e);
else
LOG.log(Level.ERROR,
"Failed to setup audio backend. Do you have libfftw-3 installed? " + e.getLocalizedMessage());
return new AudioBackend() {
@Override
public void setSourceIndex(int index) {
}
@Override
public void init() {
}
@Override
public void stop() {
}
@Override
public double[] getSnapshot(boolean audioFFT) {
return null;
}
@Override
public List<AudioSource> getSources() {
return Collections.emptyList();
}
@Override
public List<AudioSink> getSinks() {
return Collections.emptyList();
}
@Override
public int getVolume(AudioSink sink) {
return 0;
}
@Override
public void setVolume(AudioSink sink, int volume) {
}
@Override
public boolean isMuted(AudioSink sink) {
return false;
}
@Override
public void setMuted(AudioSink sink, boolean muted) {
}
};
}
}
@SuppressWarnings("resource")
void fireVolumeChange(AudioSink sink) {
int vol = backend.getVolume(sink);
try {
for (Device device : context.getBackend().getDevices()) {
if (sink.getName().startsWith(device.getName())) {
for (int i = 0; i < volumeListeners.size(); i++)
volumeListeners.get(i).volumeChanged(device, vol);
return;
}
}
} catch (Exception e) {
LOG.log(Level.ERROR, "Failed to get devices.");
}
}
}
| 8,670 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
AudioBackend.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/audio/AudioBackend.java | package uk.co.bithatch.snake.ui.audio;
import java.util.List;
import uk.co.bithatch.snake.ui.audio.AudioManager.AudioSink;
import uk.co.bithatch.snake.ui.audio.AudioManager.AudioSource;
public interface AudioBackend {
public interface Listener {
void volumeChanged(int volume);
}
void setSourceIndex(int index);
void init();
void stop();
double[] getSnapshot(boolean audioFFT);
List<AudioSource> getSources();
List<AudioSink> getSinks();
int getVolume(AudioSink sink);
void setVolume(AudioSink sink, int volume);
boolean isMuted(AudioSink sink);
void setMuted(AudioSink sink, boolean muted);
}
| 623 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
AbstractJsonAddOn.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/addons/AbstractJsonAddOn.java | package uk.co.bithatch.snake.ui.addons;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.URL;
import java.nio.file.Path;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import uk.co.bithatch.snake.lib.Json;
import uk.co.bithatch.snake.ui.App;
public abstract class AbstractJsonAddOn extends AbstractAddOn {
final static System.Logger LOG = System.getLogger(AbstractJsonAddOn.class.getName());
protected App context;
protected AbstractJsonAddOn(String id) {
this.id = id;
}
protected AbstractJsonAddOn(Path path, App context) throws IOException {
this(Json.toJson(path).getAsJsonObject(), context);
archive = path.getParent();
}
protected AbstractJsonAddOn(JsonObject addOnJson, App context) throws IOException {
this.context = context;
/* Add-on */
id = addOnJson.get("id").getAsString();
name = addOnJson.get("name").getAsString();
description = addOnJson.has("description") ? addOnJson.get("description").getAsString() : null;
author = addOnJson.has("author") ? addOnJson.get("author").getAsString() : null;
url = addOnJson.has("url") ? addOnJson.get("url").getAsString() : null;
license = addOnJson.has("license") ? addOnJson.get("license").getAsString() : null;
supportedModels = addOnJson.has("supportedModels")
? Json.toStringArray(addOnJson.get("supportedModels").getAsJsonArray())
: new String[0];
unsupportedModels = addOnJson.has("unsupportedModels")
? Json.toStringArray(addOnJson.get("unsupportedModels").getAsJsonArray())
: new String[0];
supportedLayouts = addOnJson.has("supportedLayouts")
? Json.toStringArray(addOnJson.get("supportedLayouts").getAsJsonArray())
: new String[0];
unsupportedLayouts = addOnJson.has("unsupportedLayouts")
? Json.toStringArray(addOnJson.get("unsupportedLayouts").getAsJsonArray())
: new String[0];
String thisAddOn = getClass().getSimpleName().toUpperCase();
if (!thisAddOn.equals(addOnJson.get("addOnType").getAsString())) {
throw new IOException(String.format("This add-on instance is a %s, not a %s as specified by the JSON.",
getClass().getSimpleName(), addOnJson.get("addOnType").getAsString()));
}
construct(addOnJson);
}
protected abstract void construct(JsonObject addOnJson);
protected abstract void store(JsonObject addOnJson);
@SuppressWarnings("resource")
public final void export(Writer out) {
JsonObject addOnInfo = new JsonObject();
addOnInfo.addProperty("id", id);
addOnInfo.addProperty("name", name);
addOnInfo.addProperty("addOnType", getClass().getSimpleName().toUpperCase());
if (description != null && !description.equals(""))
addOnInfo.addProperty("description", description);
if (author != null && !author.equals(""))
addOnInfo.addProperty("author", author);
if (url != null && !url.equals(""))
addOnInfo.addProperty("author", url);
if (license != null && !license.equals(""))
addOnInfo.addProperty("license", license);
if (supportedModels.length > 0)
addOnInfo.add("supportedModels", Json.toStringJsonArray(supportedModels));
if (unsupportedModels.length > 0)
addOnInfo.add("unsupportedModels", Json.toStringJsonArray(unsupportedModels));
if (supportedLayouts.length > 0)
addOnInfo.add("supportedLayouts", Json.toStringJsonArray(supportedLayouts));
if (unsupportedLayouts.length > 0)
addOnInfo.add("unsupportedLayouts", Json.toStringJsonArray(unsupportedLayouts));
store(addOnInfo);
GsonBuilder b = new GsonBuilder();
b.setPrettyPrinting();
Gson gson = b.create();
PrintWriter pw = new PrintWriter(out, true);
pw.println(gson.toJson(addOnInfo));
}
@Override
public String toString() {
return name;
}
@Override
public URL getScreenshot() {
return null;
}
}
| 3,807 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
Layout.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/addons/Layout.java | package uk.co.bithatch.snake.ui.addons;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.JsonObject;
import uk.co.bithatch.snake.lib.layouts.DeviceLayout;
import uk.co.bithatch.snake.lib.layouts.DeviceView;
import uk.co.bithatch.snake.ui.App;
import uk.co.bithatch.snake.ui.util.Strings;
public class Layout extends AbstractJsonAddOn {
final static System.Logger LOG = System.getLogger(Layout.class.getName());
private DeviceLayout layout;
Layout(Path path, App context) throws IOException {
super(path, context);
}
Layout(JsonObject object, App context) throws IOException {
super(object, context);
}
public Layout(String id) {
super(id);
}
public DeviceLayout getLayout() {
return layout;
}
public void setLayout(DeviceLayout layout) {
this.layout = layout;
}
@Override
public String toString() {
return name;
}
@Override
public URL getScreenshot() {
Collection<DeviceView> views = layout.getViews().values();
String imageUrl = null;
for (DeviceView view : views) {
if (view.getImageUri() != null) {
imageUrl = view.getImageUri();
break;
}
}
try {
return imageUrl == null ? null : new URL(imageUrl);
} catch (MalformedURLException e) {
if (archive != null) {
try {
return archive.resolve(imageUrl).toUri().toURL();
} catch (MalformedURLException e1) {
}
}
}
return null;
}
@Override
public Map<String, URL> resolveResources(boolean commit) {
Map<String, URL> res = new HashMap<>();
for (DeviceView view : layout.getViews().values()) {
if (view.getImageUri() != null) {
try {
URL url = new URL(view.getImageUri());
String key = Strings.basename(url.toExternalForm());
if (key == null) {
key = "image";
}
int idx = 2;
String okey = key;
while (res.containsKey(key)) {
key = okey + idx;
idx++;
}
res.put(key, url);
if (commit)
view.setImageUri(key);
} catch (Exception e) {
}
}
}
return res;
}
@Override
public void setArchive(Path archive) {
super.setArchive(archive);
if (layout != null)
try {
layout.setBase(archive.toUri().toURL());
} catch (MalformedURLException e) {
throw new IllegalStateException("Failed to set base.", e);
}
}
@Override
public void close() throws Exception {
context.getLayouts().remove(layout);
}
@Override
protected void construct(JsonObject addOnJson) {
/* Layout */
JsonObject sequenceJson = addOnJson.get("layout").getAsJsonObject();
layout = new DeviceLayout(null, sequenceJson);
if (layout.getName() == null)
layout.setName(getName());
}
@Override
protected void store(JsonObject addOnJson) {
JsonObject layoutObject = new JsonObject();
layout.store(layoutObject);
addOnJson.add("layout", layoutObject);
}
}
| 2,967 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
AddOn.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/addons/AddOn.java | package uk.co.bithatch.snake.ui.addons;
import java.net.URL;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Map;
public interface AddOn extends AutoCloseable {
default boolean hasResources() {
return !resolveResources(false).isEmpty();
}
default Map<String, URL> resolveResources(boolean commit) {
return Collections.emptyMap();
}
URL getLocation();
String getId();
String getName();
String getUrl();
String getLicense();
String getDescription();
String getAuthor();
URL getScreenshot();
String[] getSupportedLayouts();
String[] getUnsupportedLayouts();
String[] getSupportedModels();
String[] getUnsupportedModels();
Path getArchive();
default boolean isSystem() {
return getArchive() == null;
}
default void uninstall() {
}
void setArchive(Path archive);
} | 834 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
Theme.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/addons/Theme.java | package uk.co.bithatch.snake.ui.addons;
import java.io.IOException;
import java.io.InputStream;
import java.lang.System.Logger.Level;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import uk.co.bithatch.snake.lib.DeviceType;
import uk.co.bithatch.snake.lib.Region.Name;
public class Theme extends AbstractAddOn {
final static System.Logger LOG = System.getLogger(Theme.class.getName());
private String parent;
private AddOnManager manager;
Theme(AddOnManager manager, String id, Properties properties, URL location) {
this.manager = manager;
this.id = id;
this.location = location;
this.name = properties.getProperty("name", id);
this.url = properties.getProperty("url", "");
this.license = properties.getProperty("license", "");
this.description = properties.getProperty("description", "");
this.author = properties.getProperty("author", "");
this.parent = properties.getProperty("parent", "");
this.parent = properties.getProperty("parent", "");
}
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
@Override
public String toString() {
return name;
}
public URL getResource(String resource) {
String l = location.toExternalForm();
try {
if (LOG.isLoggable(Level.DEBUG))
LOG.log(Level.DEBUG,
String.format("Trying to get resource %s as URL in theme %s (%s).", resource, id, l));
URL r = new URL(l + "/" + resource);
InputStream in = null;
try {
in = r.openStream();
if (LOG.isLoggable(Level.DEBUG))
LOG.log(Level.DEBUG, String.format("Found resource %s in theme %s at %s.", resource, id, r));
return r;
} catch (IOException e) {
if (parent != null && parent.length() > 0) {
if (LOG.isLoggable(Level.DEBUG))
LOG.log(Level.DEBUG,
String.format("%s Doesn't exist in theme %s, trying parent %s.", resource, id, parent));
return manager.getTheme(parent).getResource(resource);
}
} finally {
try {
if (in != null)
in.close();
} catch (IOException e) {
}
}
if (LOG.isLoggable(Level.DEBUG))
LOG.log(Level.DEBUG, String.format("%s Doesn't exist.", resource));
return null;
} catch (MalformedURLException murle) {
throw new IllegalArgumentException(String.format("Failed to get resource %s.", resource), murle);
}
}
public InputStream getResourceAsStream(String resource) {
if (LOG.isLoggable(Level.DEBUG))
LOG.log(Level.DEBUG,
String.format("Trying to get resource %s as stream in theme %s (%s).", resource, id, location));
try {
InputStream in = new URL(location.toExternalForm() + "/" + resource).openStream();
if (in == null && parent != null && parent.length() > 0) {
if (LOG.isLoggable(Level.DEBUG))
LOG.log(Level.DEBUG, String.format("Doesn't exist, trying parent %s.", parent));
in = manager.getTheme(parent).getResourceAsStream(location.toExternalForm() + "/" + resource);
}
return in;
} catch (IOException ioe) {
throw new IllegalStateException(String.format("Failed to load theme resource %s.", resource), ioe);
}
}
@Override
public URL getScreenshot() {
return getResource("screenshot.png");
}
@Override
public void close() throws Exception {
}
public URL getEffectImage(int size, Class<?> effect) {
return getEffectImage(size, effect.getSimpleName().toLowerCase());
}
public URL getEffectImage(int size, String effect) {
return checkResource(effect, getResource("effects/" + effect + size + ".png"));
}
public URL getDeviceImage(int size, DeviceType type) {
return checkResource(type, getResource("devices/" + type.name().toLowerCase() + size + ".png"));
}
public URL getRegionImage(int size, Name region) {
return checkResource(region, getResource("regions/" + region.name().toLowerCase() + size + ".png"));
}
static URL checkResource(Object ctx, URL url) {
if (url == null)
throw new IllegalArgumentException(String.format("Image for %s does not exist.", String.valueOf(ctx)));
return url;
}
}
| 4,065 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
AddOnManager.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/addons/AddOnManager.java | package uk.co.bithatch.snake.ui.addons;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.System.Logger.Level;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.file.DirectoryStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import com.google.gson.JsonObject;
import groovy.util.GroovyScriptEngine;
import uk.co.bithatch.macrolib.MacroProfile;
import uk.co.bithatch.snake.lib.Backend.BackendListener;
import uk.co.bithatch.snake.lib.animation.Sequence;
import uk.co.bithatch.snake.lib.Device;
import uk.co.bithatch.snake.lib.Json;
import uk.co.bithatch.snake.lib.layouts.DeviceLayout;
import uk.co.bithatch.snake.ui.App;
import uk.co.bithatch.snake.ui.Controller;
import uk.co.bithatch.snake.ui.DynamicClassLoader;
import uk.co.bithatch.snake.ui.effects.CustomEffectHandler;
import uk.co.bithatch.snake.ui.util.Filing;
public class AddOnManager implements BackendListener {
public interface Listener {
void addOnAdded(AddOn addOn);
void addOnRemoved(AddOn addOn);
}
static class AddOnKey {
Class<? extends AddOn> clazz;
String id;
public AddOnKey(Class<? extends AddOn> clazz, String id) {
super();
this.clazz = clazz;
this.id = id;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AddOnKey other = (AddOnKey) obj;
if (clazz == null) {
if (other.clazz != null)
return false;
} else if (!clazz.equals(other.clazz))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((clazz == null) ? 0 : clazz.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
}
final static System.Logger LOG = System.getLogger(AddOnManager.class.getName());
protected static Path getAddOnsDirectory() throws IOException {
Path addons = Paths.get("addons");
if (!Files.exists(addons))
Files.createDirectories(addons);
return addons;
}
private Map<AddOnKey, AddOn> addOns;
private App context;
private GroovyScriptEngine groovy;
private final List<Listener> listeners = new ArrayList<>();
public AddOnManager(App context) {
this.context = context;
addOns = new LinkedHashMap<>();
try {
Path scriptsDirectory = getScriptsDirectory();
groovy = new GroovyScriptEngine(new URL[] { scriptsDirectory.toUri().toURL() });
addOns = new LinkedHashMap<>();
for (File scriptFile : scriptsDirectory.toFile()
.listFiles((p) -> p.isDirectory() && new File(p, p.getName() + ".plugin.groovy").exists())) {
try {
Script script = new Script(scriptFile.toPath(), context, groovy);
addOns.put(new AddOnKey(Script.class, script.getId()), script);
} catch (Exception e) {
LOG.log(Level.ERROR, String.format("Failed to load script %s", scriptFile), e);
}
}
} catch (Exception e) {
LOG.log(Level.ERROR, "Failed to load scripts", e);
}
try {
Path effectsDirectory = getEffectsDirectory();
for (File effectFile : effectsDirectory.toFile()
.listFiles((p) -> p.isDirectory() && new File(p, p.getName() + ".json").exists())) {
try {
AddOn addOn = new CustomEffect(effectFile.toPath().resolve(effectFile.getName() + ".json"),
context);
addOns.put(new AddOnKey(addOn.getClass(), addOn.getId()), addOn);
} catch (Exception e) {
LOG.log(Level.ERROR, String.format("Failed to load effect %s", effectFile), e);
}
}
} catch (Exception e) {
LOG.log(Level.ERROR, "Failed to load scripts", e);
}
try {
Path layoutsDirectory = getLayoutsDirectory();
for (File layoutFile : layoutsDirectory.toFile()
.listFiles((p) -> p.isDirectory() && new File(p, p.getName() + ".json").exists())) {
try {
Layout addOn = new Layout(layoutFile.toPath().resolve(layoutFile.getName() + ".json"), context);
addOns.put(new AddOnKey(addOn.getClass(), addOn.getId()), addOn);
DeviceLayout layout = addOn.getLayout();
layout.setBase(addOn.getArchive().toUri().toURL());
layout.setReadOnly(true);
context.getLayouts().addLayout(layout);
} catch (Exception e) {
LOG.log(Level.ERROR, String.format("Failed to load layout%s", layoutFile), e);
}
}
} catch (Exception e) {
LOG.log(Level.ERROR, "Failed to load scripts", e);
}
try {
Path macrosDirectory = getMacrosDirectory();
for (File layoutFile : macrosDirectory.toFile()
.listFiles((p) -> p.isDirectory() && new File(p, p.getName() + ".json").exists())) {
try {
Macros addOn = new Macros(layoutFile.toPath().resolve(layoutFile.getName() + ".json"), context);
addOns.put(new AddOnKey(addOn.getClass(), addOn.getId()), addOn);
MacroProfile macroProfile = addOn.getProfile();
// macroProfile.setBase(addOn.getArchive().toUri().toURL());
// addOn.setReadOnly(true);
// context.getLayouts().addLayout(macroProfile);
} catch (Exception e) {
LOG.log(Level.ERROR, String.format("Failed to load layout%s", layoutFile), e);
}
}
} catch (Exception e) {
LOG.log(Level.ERROR, "Failed to load scripts", e);
}
try {
if (ClassLoader.getSystemClassLoader() instanceof DynamicClassLoader) {
DynamicClassLoader dlc = (DynamicClassLoader) ClassLoader.getSystemClassLoader();
for (File themeFile : getThemesDirectory().toFile().listFiles()) {
dlc.add(themeFile.toURI().toURL());
}
}
// for (File themeFile : getThemesDirectory().listFiles()) {
// try {
// // Curent ModuleLayer is usually boot layer. but it can be different if you are
// // using multiple layers
// //ModuleLayer currentModuleLayer = Theme.class.getModule().getLayer();
// ModuleLayer currentModuleLayer = ModuleLayer.boot();
// final Set<Path> modulePathSet = Set.of(themeFile.toPath());
// // ModuleFinder to find modules
// final ModuleFinder moduleFinder = ModuleFinder.of(modulePatThemehSet.toArray(new Path[0]));
// // I really dont know why does it requires empty finder.
// final ModuleFinder emptyFinder = ModuleFinder.of(new Path[0]);
// // ModuleNames to be loaded
// final Set<String> moduleNames = moduleFinder.findAll().stream()
// .map(moduleRef -> moduleRef.descriptor().name()).collect(Collectors.toSet());
// // Unless you want to use URLClassloader for tomcat like situation, use Current
// // Class Loader
// final ClassLoader loader = Theme.class.getClassLoader();
// // Derive new configuration from current module layer configuration
// final java.lang.module.Configuration configuration = currentModuleLayer.configuration()
// .resolveAndBind(moduleFinder, emptyFinder, moduleNames);
// // New Module layer derived from current modulee layer
// final ModuleLayer moduleLayer = currentModuleLayer.defineModulesWithOneLoader(configuration,
// loader);
// // find module and load class Load class
// final Class<?> controllerClass = moduleLayer.findModule("org.util.npci.coreconnect").get()
// .getClassLoader().loadClass("org.util.npci.coreconnect.CoreController");
//
// } catch (Exception e) {
// LOG.log(Level.ERROR, String.format("Failed to load theme add-on %s.", themeFile), e);
// }
// }
for (Enumeration<URL> u = ClassLoader.getSystemResources("META-INF/theme"); u.hasMoreElements();) {
URL url = u.nextElement();
InputStream themeIn = url.openStream();
for (String t : readThemeNames(themeIn)) {
Theme theme = loadTheme(t);
if (url.toExternalForm().startsWith("jar:file")) {
/* Is this theme in a jar file (not directly on classpath) */
String fileUri = url.toExternalForm().substring(4);
int idx = fileUri.indexOf("!");
if (idx != -1)
fileUri = fileUri.substring(0, idx);
/* And is it's path a child of the addOns directory? */
if (fileUri.startsWith(getAddOnsDirectory().toUri().toURL().toExternalForm())) {
Path path = Path.of(new URI(fileUri));
theme.setArchive(path);
}
}
}
}
} catch (Exception ioe) {
throw new IllegalStateException("Failed to load themes.", ioe);
}
}
public void addListener(Listener listener) {
listeners.add(listener);
}
@SuppressWarnings("unchecked")
public <A extends AddOn> A getAddOn(Class<? extends AddOn> clazz, String id) {
return (A) addOns.get(new AddOnKey(clazz, id));
}
public Collection<AddOn> getAddOns() {
return addOns.values();
}
public Collection<Script> getScripts() {
return getAddOns(Script.class);
}
public Collection<CustomEffect> getCustomEffects() {
return getAddOns(CustomEffect.class);
}
public Collection<Theme> getThemes() {
return getAddOns(Theme.class);
}
public Collection<Layout> getLayouts() {
return getAddOns(Layout.class);
}
@SuppressWarnings("unchecked")
public <A extends AddOn> Collection<A> getAddOns(Class<A> clazz) {
List<A> l = new ArrayList<>();
for (Map.Entry<AddOnKey, AddOn> men : addOns.entrySet()) {
if (men.getKey().clazz.equals(clazz)) {
l.add((A) men.getValue());
}
}
return l;
}
public Theme getTheme(String id) {
return getAddOn(Theme.class, id);
}
public Script getScript(String id) {
return getAddOn(Script.class, id);
}
public Layout getLayout(String id) {
return getAddOn(Script.class, id);
}
public CustomEffect getCustomEffect(String id) {
return getAddOn(CustomEffect.class, id);
}
@SuppressWarnings("unchecked")
public <T extends AddOn> T install(File file) throws Exception {
ZipEntry themeEntry = null;
String addOnName = null;
String fileName = file.getName();
if (fileName.endsWith(".jar")) {
try (JarFile jf = new JarFile(file)) {
themeEntry = jf.getEntry("META-INF/theme");
if (themeEntry != null) {
List<String> names = readThemeNames(jf.getInputStream(themeEntry));
if (!names.isEmpty())
addOnName = names.get(0);
}
}
}
if (themeEntry == null) {
InstallSession<T> session = new InstallSession<>();
if (fileName.endsWith(".zip")) {
Path tmpDir = Files.createTempDirectory("addon");
Filing.unzip(file.toPath(), tmpDir);
session.install(tmpDir);
try {
return session.commit();
} finally {
Filing.deleteRecursiveIfExists(tmpDir.toFile());
}
} else {
session.install(file.toPath());
return session.commit();
}
} else {
/* Is a theme */
Path themes = getThemesDirectory();
Path targetThemeFile = themes.resolve(addOnName + ".jar");
if (Files.exists(targetThemeFile))
throw new Exception(String.format("The theme %s already exists.", addOnName));
Files.copy(file.toPath(), targetThemeFile);
if (ClassLoader.getSystemClassLoader() instanceof DynamicClassLoader) {
DynamicClassLoader dlc = (DynamicClassLoader) ClassLoader.getSystemClassLoader();
dlc.add(targetThemeFile.toUri().toURL());
T theme = (T) loadTheme(addOnName);
((Theme) theme).setArchive(targetThemeFile);
fireAdded(theme);
return theme;
} else
// TODO treat this is restart needed
return null;
}
}
public void pop(Controller controller) {
invoke("pop", controller);
invoke("pop" + controller.getClass().getSimpleName(), controller);
}
public void push(Controller controller) {
invoke("push", controller);
invoke("push" + controller.getClass().getSimpleName(), controller);
}
public void removeListener(Listener listener) {
listeners.remove(listener);
}
public Path getMacrosDirectory() throws IOException {
return getAddOnDirectory("macros");
}
public void start() {
for (CustomEffect effect : getCustomEffects()) {
try {
startDeviceEffects(effect);
} catch (Exception e) {
LOG.log(Level.ERROR, String.format("Failed to start custom effect %s.", effect.getId()), e);
}
}
context.getBackend().addListener(this);
for (Script s : getScripts()) {
try {
s.run();
} catch (Exception e) {
LOG.log(Level.ERROR, "Failed to start script.", e);
}
}
}
public void uninstall(AddOn addOn) throws Exception {
addOn.close();
Filing.deleteRecursiveIfExists(addOn.getArchive().toFile());
addOns.remove(new AddOnKey(addOn.getClass(), addOn.getId()));
fireRemoved(addOn);
}
protected void invoke(String method, Object... args) {
for (Script s : getScripts()) {
try {
s.invoke(method, args);
} catch (Exception e) {
LOG.log(Level.ERROR, String.format("Failed to invoke %s on script %s.", method, s.getArchive()), e);
}
}
}
// private Layout createLayoutFile(Path jsonFile) throws Exception {
// Layout layout = new Layout(jsonFile, context);
// layout.getLayout().setReadOnly(true);
// layout.setArchive(jsonFile);
// addOns.put(new AddOnKey(Layout.class, layout.getId()), layout);
// context.getLayouts().addLayout(layout.getLayout());
// return layout;
// }
//
// private CustomEffect createEffectFile(Path jsonFile) throws Exception {
// CustomEffect effect = new CustomEffect(jsonFile, context);
// effect.setArchive(jsonFile);
// return effect;
// }
//
// private CustomEffect createEffectFile(JsonObject object) throws Exception {
// return new CustomEffect(object, context);
// }
protected void startDeviceEffects(CustomEffect effect) throws Exception {
for (Device dev : context.getBackend().getDevices()) {
startDeviceEffects(effect, dev);
}
}
protected void startDeviceEffects(CustomEffect effect, Device dev) {
CustomEffectHandler handler = new CustomEffectHandler(effect.getName(), new Sequence(effect.getSequence()));
handler.setReadOnly(true);
context.getEffectManager().add(dev, handler);
effect.getHandlers().add(handler);
}
private <T extends AddOn> void fireAdded(T theme) {
for (int i = listeners.size() - 1; i >= 0; i--) {
listeners.get(i).addOnAdded(theme);
}
}
private <T extends AddOn> void fireRemoved(T theme) {
for (int i = listeners.size() - 1; i >= 0; i--) {
listeners.get(i).addOnRemoved(theme);
}
}
private Path getAddOnDirectory(String type) throws IOException {
Path addOns = getAddOnsDirectory().resolve(type);
if (!Files.exists(addOns))
Files.createDirectories(addOns);
return addOns;
}
private Path getScriptsDirectory() throws IOException {
return getAddOnDirectory("scripts");
}
private Path getEffectsDirectory() throws IOException {
return getAddOnDirectory("effects");
}
private Path getThemesDirectory() throws IOException {
return getAddOnDirectory("themes");
}
private Path getLayoutsDirectory() throws IOException {
return getAddOnDirectory("layouts");
}
private Theme loadTheme(String t) throws IOException, MalformedURLException {
String defpath = "themes/" + t + "/theme.properties";
URL tu = ClassLoader.getSystemResource(defpath);
if (tu == null)
throw new IOException(
String.format("Theme definition for %s does not contain a resource named %s.", t, defpath));
Theme td = readThemeDef(t, tu);
addOns.put(new AddOnKey(Theme.class, t), td);
return td;
}
private Theme readThemeDef(String ti, URL def) throws IOException, MalformedURLException {
Properties p = new Properties();
try (InputStream in = def.openStream()) {
p.load(in);
}
String tus = def.toExternalForm();
int idx = tus.lastIndexOf('/');
tus = tus.substring(0, idx);
return new Theme(this, ti, p, new URL(tus));
}
private List<String> readThemeNames(InputStream themeIn) throws IOException, MalformedURLException {
List<String> themes = new ArrayList<>();
try (BufferedReader r = new BufferedReader(new InputStreamReader(themeIn))) {
String line;
while ((line = r.readLine()) != null) {
line = line.trim();
if (!line.startsWith("#") && line.length() > 0) {
themes.add(line);
}
}
}
return themes;
}
class InstallSession<A extends AddOn> {
String addOnName;
A addOn = null;
Path targetDir;
Path targetFile;
Path sourceFile;
Path sourceDir;
List<Path> resources = new ArrayList<>();
void install(Path file) throws Exception {
if (Files.isDirectory(file)) {
/*
* If the path is a directory, look for something that looks like a plugin or an
* add-on metadata file
*/
sourceDir = file;
try (DirectoryStream<Path> stream = Files.newDirectoryStream(file)) {
for (Path path : stream) {
if (!Files.isDirectory(path)) {
try {
installFile(path);
sourceFile = path;
} catch (IllegalArgumentException iae) {
}
}
}
}
if (sourceFile != null) {
Files.walkFileTree(file, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path innerFile, BasicFileAttributes attrs) throws IOException {
if (!Files.isDirectory(innerFile) && !innerFile.equals(sourceFile)) {
resources.add(file.relativize(innerFile));
}
return FileVisitResult.CONTINUE;
}
});
} else
throw new IOException(String
.format("The file %s does not contain a theme, and is not a script or JSON add-on.", file));
} else {
/* Otherwise its just a meta-data file of some sort */
sourceFile = file;
installFile(file);
}
}
@SuppressWarnings("unchecked")
void installFile(Path file) throws Exception {
String fileName = file.getFileName().toString();
if (fileName.endsWith(".json")) {
JsonObject toJson = Json.toJson(file).getAsJsonObject();
if (toJson.has("addOnType")) {
/*
* Parse the JSON from the source file first, then use the ID embedded within to
* determine the add-on id, and thus its actual installed location
*/
String type = toJson.get("addOnType").getAsString();
if (type.equals("CUSTOMEFFECT")) {
addOn = (A) new CustomEffect(toJson, context);
targetDir = getEffectsDirectory().resolve(addOn.getId());
} else if (type.equals("LAYOUT")) {
addOn = (A) new Layout(toJson, context);
targetDir = getLayoutsDirectory().resolve(addOn.getId());
} else
throw new IOException(String.format("Unknown add-on type %s", type));
addOnName = addOn.getId();
targetFile = targetDir.resolve(addOnName + ".json");
} else {
throw new IllegalArgumentException(
"Could not determine add-on type. The JSON had no addOnType attribute.");
}
} else if (fileName.endsWith(".plugin.groovy")) {
/*
* If this is just a single file, then we use file name for the plugin ID, and
* create a directory of the same name, and place the script in that.
*/
int idx = fileName.indexOf(".plugin.groovy");
addOnName = fileName.substring(0, idx);
targetDir = getScriptsDirectory().resolve(addOnName);
targetFile = targetDir.resolve(addOnName + ".plugin.groovy");
addOn = (A) new Script(file, context, groovy);
} else {
throw new IllegalArgumentException(String
.format("The file %s does not contain a theme, and is not a script or JSON add-on.", file));
}
}
public A commit() throws Exception {
if (Files.exists(targetDir)) {
Filing.deleteRecursiveIfExists(targetDir.toFile());
}
Files.createDirectories(targetDir);
/* Copy main artifact */
Files.copy(sourceFile, targetFile);
addOn.setArchive(targetDir);
/* Copy other artifacts */
if (sourceDir != null) {
for (Path resource : resources) {
Files.copy(sourceDir.resolve(resource), targetDir.resolve(resource));
}
}
addOns.put(new AddOnKey(addOn.getClass(), addOn.getId()), addOn);
fireAdded(addOn);
if (addOn instanceof CustomEffect) {
startDeviceEffects((CustomEffect) addOn);
} else if (addOn instanceof Script) {
((Script) addOn).run();
((Script) addOn).install();
} else if (addOn instanceof Layout) {
DeviceLayout layout = ((Layout) addOn).getLayout();
layout.setBase(addOn.getArchive().toUri().toURL());
layout.setReadOnly(true);
context.getLayouts().addLayout(layout);
}
return (A) addOn;
}
}
@Override
public void deviceAdded(Device device) {
for (CustomEffect effect : getCustomEffects()) {
try {
startDeviceEffects(effect, device);
} catch (Exception e) {
LOG.log(Level.ERROR, "Failed to start script.", e);
}
}
}
@Override
public void deviceRemoved(Device device) {
}
}
| 20,991 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
CustomEffect.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/addons/CustomEffect.java | package uk.co.bithatch.snake.ui.addons;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import uk.co.bithatch.snake.lib.animation.AudioParameters;
import uk.co.bithatch.snake.lib.animation.Interpolation;
import uk.co.bithatch.snake.lib.animation.KeyFrame;
import uk.co.bithatch.snake.lib.animation.KeyFrameCell;
import uk.co.bithatch.snake.lib.animation.Sequence;
import uk.co.bithatch.snake.lib.animation.KeyFrame.KeyFrameCellSource;
import uk.co.bithatch.snake.ui.App;
import uk.co.bithatch.snake.ui.effects.CustomEffectHandler;
public class CustomEffect extends AbstractJsonAddOn {
final static System.Logger LOG = System.getLogger(CustomEffect.class.getName());
private Sequence sequence;
private List<CustomEffectHandler> handlers = new ArrayList<>();
CustomEffect(Path path, App context) throws IOException {
super(path, context);
}
CustomEffect(JsonObject object, App context) throws IOException {
super(object, context);
}
public List<CustomEffectHandler> getHandlers() {
return handlers;
}
public CustomEffect(String id) {
super(id);
}
public Sequence getSequence() {
return sequence;
}
public void setSequence(Sequence sequence) {
this.sequence = sequence;
}
@Override
public String toString() {
return name;
}
@Override
public URL getScreenshot() {
return null;
}
@Override
public void close() throws Exception {
for (CustomEffectHandler h : handlers) {
if (h.getDevice() != null)
context.getEffectManager().remove(h);
}
}
@Override
protected void construct(JsonObject addOnJson) {
/* Sequence */
JsonObject sequenceJson = addOnJson.get("sequence").getAsJsonObject();
sequence = new Sequence();
sequence.setFps(sequenceJson.has("fps") ? sequenceJson.get("fps").getAsInt() : 25);
sequence.setSpeed(sequenceJson.has("speed") ? sequenceJson.get("speed").getAsFloat() : 1);
sequence.setRepeat(sequenceJson.has("repeat") ? sequenceJson.get("repeat").getAsBoolean() : true);
sequence.setInterpolation(
sequenceJson.has("interpolation") ? Interpolation.get(sequenceJson.get("interpolation").getAsString())
: Interpolation.linear);
if (sequenceJson.has("audio")) {
sequence.setAudioParameters(createAudioParametersFromJson(sequenceJson.get("audio").getAsJsonObject()));
}
JsonArray frames = sequenceJson.get("frames").getAsJsonArray();
for (JsonElement frame : frames) {
JsonObject framesObject = frame.getAsJsonObject();
/* Frame */
KeyFrame keyFrame = new KeyFrame();
keyFrame.setInterpolation(framesObject.has("interpolation")
? Interpolation.get(framesObject.get("interpolation").getAsString())
: Interpolation.sequence);
keyFrame.setHoldFor(framesObject.has("holdFor") ? framesObject.get("holdFor").getAsLong() : 0);
/* Rows */
JsonArray rows = framesObject.get("rows").getAsJsonArray();
KeyFrameCell[][] rowsArray = new KeyFrameCell[rows.size()][];
int rowIndex = 0;
for (JsonElement row : rows) {
List<KeyFrameCell> colsArray = new ArrayList<>();
JsonArray cols = row.getAsJsonArray();
for (JsonElement col : cols) {
if (col.isJsonArray()) {
/* Used versions 1.0-SNAPSHOT-24 and earlier, every cell was a colour */
JsonArray rgb = col.getAsJsonArray();
KeyFrameCell cell = new KeyFrameCell(
new int[] { rgb.get(0).getAsInt(), rgb.get(1).getAsInt(), rgb.get(2).getAsInt() });
colsArray.add(cell);
} else {
/* Newer builds, each cell is an object */
JsonObject job = col.getAsJsonObject();
JsonArray arr = job.get("value").getAsJsonArray();
JsonArray sources = job.get("sources").getAsJsonArray();
var srcs = new ArrayList<>();
for (JsonElement e : sources) {
srcs.add(KeyFrameCellSource.valueOf(e.getAsString()));
}
KeyFrameCell cell = new KeyFrameCell(
new int[] { arr.get(0).getAsInt(), arr.get(1).getAsInt(), arr.get(2).getAsInt() },
srcs.toArray(new KeyFrameCellSource[0]));
cell.setInterpolation(job.has("interpolation")
? Interpolation.fromName(job.get("interpolation").getAsString())
: Interpolation.keyframe);
colsArray.add(cell);
}
}
rowsArray[rowIndex++] = colsArray.toArray(new KeyFrameCell[0]);
rowIndex++;
}
keyFrame.setFrame(rowsArray);
sequence.add(keyFrame);
}
}
@Override
protected void store(JsonObject addOnJson) {
JsonObject sequenceInfo = new JsonObject();
sequenceInfo.addProperty("repeat", sequence.isRepeat());
sequenceInfo.addProperty("fps", sequence.getFps());
sequenceInfo.addProperty("speed", sequence.getSpeed());
sequenceInfo.addProperty("interpolation", sequence.getInterpolation().getName());
if (sequence.getAudioParameters() != null)
sequenceInfo.add("audio", getAudioParametersJson(sequence.getAudioParameters()));
JsonArray frameInfo = new JsonArray();
for (KeyFrame kf : sequence) {
JsonObject keyFrameInfo = new JsonObject();
keyFrameInfo.addProperty("interpolation", kf.getInterpolation().getName());
keyFrameInfo.addProperty("holdFor", kf.getHoldFor());
JsonArray rowInfo = new JsonArray();
for (KeyFrameCell[] row : kf.getFrame()) {
JsonArray colInfo = new JsonArray();
for (KeyFrameCell col : row) {
JsonObject keycellJson = new JsonObject();
JsonArray rgb = new JsonArray();
rgb.add(col.getValues()[0]);
rgb.add(col.getValues()[1]);
rgb.add(col.getValues()[2]);
JsonArray srcs = new JsonArray();
srcs.add(col.getSources()[0].name());
srcs.add(col.getSources()[1].name());
srcs.add(col.getSources()[2].name());
keycellJson.add("sources", srcs);
keycellJson.addProperty("interpolation", col.getInterpolation().getName());
keycellJson.add("value", rgb);
colInfo.add(keycellJson);
}
rowInfo.add(colInfo);
}
keyFrameInfo.add("rows", rowInfo);
frameInfo.add(keyFrameInfo);
}
sequenceInfo.add("frames", frameInfo);
addOnJson.add("sequence", sequenceInfo);
}
private AudioParameters createAudioParametersFromJson(JsonObject json) {
AudioParameters p = new AudioParameters();
p.setLow(json.has("low") ? json.get("low").getAsInt() : 0);
p.setHigh(json.has("high") ? json.get("high").getAsInt() : 255);
p.setGain(json.has("gain") ? json.get("gain").getAsFloat() : 1.0f);
return p;
}
private JsonElement getAudioParametersJson(AudioParameters audioParameters) {
JsonObject obj = new JsonObject();
obj.addProperty("low", audioParameters.getLow());
obj.addProperty("high", audioParameters.getHigh());
obj.addProperty("gain", audioParameters.getGain());
return obj;
}
}
| 6,790 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
AbstractAddOn.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/addons/AbstractAddOn.java | package uk.co.bithatch.snake.ui.addons;
import java.net.URL;
import java.nio.file.Path;
public abstract class AbstractAddOn implements AddOn {
protected String name;
protected String url;
protected String license;
protected String description;
protected String author;
protected String id;
protected Path archive;
protected URL location;
protected String[] supportedModels = new String[0];
protected String[] unsupportedModels = new String[0];
protected String[] supportedLayouts = new String[0];
protected String[] unsupportedLayouts = new String[0];
public AbstractAddOn() {
super();
}
public String[] getSupportedModels() {
return supportedModels;
}
public void setSupportedModels(String[] supportedModels) {
this.supportedModels = supportedModels;
}
public String[] getUnsupportedModels() {
return unsupportedModels;
}
public void setUnsupportedModels(String[] unsupportedModels) {
this.unsupportedModels = unsupportedModels;
}
public String[] getSupportedLayouts() {
return supportedLayouts;
}
public void setSupportedLayouts(String[] supportedLayouts) {
this.supportedLayouts = supportedLayouts;
}
public String[] getUnsupportedLayouts() {
return unsupportedLayouts;
}
public void setUnsupportedLayouts(String[] unsupportedLayouts) {
this.unsupportedLayouts = unsupportedLayouts;
}
@Override
public URL getLocation() {
return location;
}
@Override
public String getId() {
return id;
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public String getLicense() {
return license;
}
public void setLicense(String license) {
this.license = license;
}
@Override
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Path getArchive() {
return archive;
}
public void setArchive(Path archive) {
this.archive = archive;
}
} | 2,236 | 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/addons/Macros.java | package uk.co.bithatch.snake.ui.addons;
import java.io.IOException;
import java.nio.file.Path;
import com.google.gson.JsonObject;
import uk.co.bithatch.macrolib.JsonMacroStorage;
import uk.co.bithatch.macrolib.MacroProfile;
import uk.co.bithatch.snake.ui.App;
public class Macros extends AbstractJsonAddOn {
final static System.Logger LOG = System.getLogger(Macros.class.getName());
private MacroProfile profile;
Macros(Path path, App context) throws IOException {
super(path, context);
}
Macros(JsonObject object, App context) throws IOException {
super(object, context);
}
public Macros(String id) {
super(id);
}
public MacroProfile getProfile() {
return profile;
}
public void setProfile(MacroProfile layout) {
this.profile = layout;
}
@Override
public String toString() {
return name;
}
@Override
public void setArchive(Path archive) {
super.setArchive(archive);
// if (profile != null)
// try {
// profile.setBase(archive.toUri().toURL());
// } catch (MalformedURLException e) {
// throw new IllegalStateException("Failed to set base.", e);
// }
}
@Override
public void close() throws Exception {
// context.getLayouts().remove(profile);
}
@Override
protected void construct(JsonObject addOnJson) {
/* Layout */
JsonObject sequenceJson = addOnJson.get("layout").getAsJsonObject();
JsonMacroStorage s;
// profile = new DeviceLayout(null, sequenceJson);
// if (profile.getName() == null)
// profile.setName(getName());
}
@Override
protected void store(JsonObject addOnJson) {
// JsonObject layoutObject = new JsonObject();
// profile.store(layoutObject);
// addOnJson.add("layout", layoutObject);
}
}
| 1,690 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
Script.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/addons/Script.java | package uk.co.bithatch.snake.ui.addons;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;
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.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;
import uk.co.bithatch.snake.ui.App;
public class Script extends AbstractAddOn implements BackendListener, Listener {
final static System.Logger LOG = System.getLogger(Script.class.getName());
private groovy.lang.Script script;
private Binding bindings;
private App context;
private int lastLevel;
private GroovyScriptEngine groovy;
public Script(Path scriptDir, App context, GroovyScriptEngine groovy) throws Exception {
id = scriptDir.getFileName().toString();
this.archive = scriptDir;
this.context = context;
this.groovy = groovy;
}
public Object run() throws Exception {
List<Device> devices = context.getBackend().getDevices();
for (Device d : devices) {
d.addListener(this);
}
bindings = new Binding();
bindings.setProperty("snake", context);
bindings.setProperty("driver", context.getBackend());
bindings.setProperty("devices", devices);
bindings.setProperty("device", devices.isEmpty() ? null : devices.get(0));
script = groovy.createScript(id + "/" + id + ".plugin.groovy", bindings);
description = defaultIfBlank((String) script.getProperty("description"), "");
author = defaultIfBlank((String) script.getProperty("author"), "");
license = defaultIfBlank((String) script.getProperty("license"), "");
name = defaultIfBlank((String) script.getProperty("name"), id);
supportedLayouts = (String[]) script.getProperty("supportedLayouts");
supportedModels = (String[]) script.getProperty("supportedModels");
unsupportedLayouts = (String[]) script.getProperty("unsupportedLayouts");
unsupportedModels = (String[]) script.getProperty("unsupportedModels");
context.getBackend().addListener(this);
return script.invokeMethod("run", null);
}
@Override
public URL getScreenshot() {
return null;
}
@Override
public void close() throws Exception {
context.getBackend().removeListener(this);
}
@Override
public void deviceAdded(Device device) {
invoke("deviceAdded", device);
}
@Override
public void deviceRemoved(Device device) {
invoke("deviceRemoved", device);
}
@Override
public void changed(Device device, Region region) {
if (device.getCapabilities().contains(Capability.BATTERY)) {
int level = device.getBattery();
if (level != lastLevel) {
invoke("battery", device);
lastLevel = level;
}
}
invoke("change", device, region);
}
@Override
public void activeMapChanged(ProfileMap map) {
}
@Override
public void profileAdded(Profile profile) {
}
@Override
public void profileRemoved(Profile profile) {
}
public void install() {
invoke("install");
}
public void uninstall() {
invoke("uninstall");
}
protected String defaultIfBlank(String val, String def) {
return val == null || val.equals("") ? def : val;
}
protected boolean invoke(String method, Object... args) {
List<Object> arglist = new ArrayList<>(Arrays.asList(args));
do {
try {
/* Only bother to match signatures based on size */
for (Method m : script.getClass().getMethods()) {
if (m.getName().equals(method) && m.getParameterCount() == arglist.size()) {
m.invoke(script, arglist.toArray(new Object[0]));
return true;
}
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
| SecurityException e) {
throw new IllegalStateException("Failed to invoke script method.", e);
}
if (!arglist.isEmpty())
arglist.remove(arglist.size() - 1);
else
return false;
} while (true);
}
@Override
public void mapAdded(ProfileMap profile) {
}
@Override
public void mapChanged(ProfileMap profile) {
}
@Override
public void mapRemoved(ProfileMap profile) {
}
}
| 4,318 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
PeaksAudioEffectMode.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/effects/PeaksAudioEffectMode.java | package uk.co.bithatch.snake.ui.effects;
import uk.co.bithatch.jdraw.Gradient;
import uk.co.bithatch.jdraw.RGBCanvas;
public class PeaksAudioEffectMode implements AudioEffectMode {
private double[] peakHeights;
private double[] peakAcceleration;
private RGBCanvas canvas;
private AudioEffectHandler handler;
private Gradient bg;
@Override
public Boolean isNeedsFFT() {
return null;
}
public void frame(double[] audio) {
float freq = (float) audio.length / (float) canvas.getWidth();
int actualCols = (int) ((float) audio.length / freq) + 1;
canvas.clear();
canvas.translate((canvas.getWidth() - actualCols) / 2, 0);
for (int i = 0; i < audio.length; i += freq) {
int col = (int) ((float) i / freq);
int rows = (int) (audio[i] * (double) (canvas.getHeight()));
canvas.setGradient(bg);
if (rows > peakHeights[i]) {
peakHeights[i] = rows;
peakAcceleration[i] = 0.0;
} else {
peakAcceleration[i] += 0.1f;
peakHeights[i] -= peakAcceleration[i];
}
if (peakHeights[i] < 0)
peakHeights[i] = 0;
if(rows > 0)
canvas.fillRect(col, canvas.getHeight() - rows, 1, rows);
canvas.setGradient(null);
canvas.setColour(handler.getColor3());
canvas.fillRect(col, (int)Math.round(canvas.getHeight() - peakHeights[i]), 1, 1);
}
canvas.translate(0, 0);
}
@Override
public void init(RGBCanvas canvas, AudioEffectHandler handler) {
peakHeights = new double[256];
peakAcceleration = new double[256];
this.handler = handler;
this.canvas = canvas;
update();
}
@Override
public void update() {
bg = new Gradient(new float[] { 0f, 1.0f }, handler.getColor1(), handler.getColor2());
}
} | 1,675 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
BlinkEffectHandler.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/effects/BlinkEffectHandler.java | package uk.co.bithatch.snake.ui.effects;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import uk.co.bithatch.snake.lib.Colors;
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;
import uk.co.bithatch.snake.lib.layouts.Cell;
import uk.co.bithatch.snake.ui.AbstractEffectController;
import uk.co.bithatch.snake.ui.SchedulerManager.Queue;
public class BlinkEffectHandler
extends AbstractEffectHandler<Matrix, AbstractEffectController<Matrix, BlinkEffectHandler>> {
private ScheduledFuture<?> task;
private boolean on;
private Matrix effect;
private List<Cell> highlights = new ArrayList<>();
public BlinkEffectHandler() {
}
@Override
public void removed(Device device) {
}
@Override
public boolean isRegions() {
return false;
}
@Override
public void deactivate(Lit component) {
synchronized (highlights) {
task.cancel(false);
on = false;
frame(component);
}
}
@Override
public void update(Lit component) {
component.updateEffect(effect);
}
public Matrix getEffect() {
return effect;
}
@Override
protected Matrix onActivate(Lit component) {
effect = component.createEffect(Matrix.class);
int[] dw = Lit.getDevice(component).getMatrixSize();
effect.setCells(new int[dw[0]][dw[1]][3]);
on = true;
reset(component);
return effect;
}
protected synchronized void reset(Lit component) {
if (task != null)
task.cancel(false);
task = getContext().getSchedulerManager().get(Queue.DEVICE_IO).scheduleAtFixedRate(() -> {
frame(component);
on = !on;
}, 0, 250, TimeUnit.MILLISECONDS);
}
@Override
public Class<AbstractEffectController<Matrix, BlinkEffectHandler>> getOptionsController() {
throw new UnsupportedOperationException();
}
@Override
public boolean isSupported(Lit component) {
return true;
}
@Override
public URL getEffectImage(int size) {
return null;
}
@Override
public String getDisplayName() {
return getClass().getSimpleName();
}
@Override
protected void onStore(Lit component, AbstractEffectController<Matrix, BlinkEffectHandler> controller)
throws Exception {
}
void frame(Lit component) {
synchronized (highlights) {
for (Cell h : highlights) {
effect.getCells()[h.getY()][h.getX()] = on ? Colors.COLOR_BLACK : new int[] { 0xff, 0xff, 0xff };
}
}
update(component);
}
public void clear(Lit component) {
synchronized (highlights) {
highlights.clear();
effect.clear();
reset(component);
}
}
public void highlight(Lit component, int matrixX, int matrixY) {
highlight(component, new Cell(matrixX, matrixY));
}
public void highlight(Lit component, Cell... cells) {
synchronized (highlights) {
if (cells.length == highlights.size()) {
for (Cell c : cells) {
if (!highlights.contains(c)) {
doHighlight(component, cells);
return;
}
}
} else
doHighlight(component, cells);
}
}
protected void doHighlight(Lit component, Cell... cells) {
highlights.clear();
effect.clear();
highlights.addAll(Arrays.asList(cells));
reset(component);
}
@Override
public Class<? extends Effect> getBackendEffectClass() {
return Matrix.class;
}
}
| 3,396 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
BurstyAudioEffectMode.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/effects/BurstyAudioEffectMode.java | package uk.co.bithatch.snake.ui.effects;
import uk.co.bithatch.jdraw.RGBCanvas;
import uk.co.bithatch.snake.lib.Colors;
public class BurstyAudioEffectMode implements AudioEffectMode {
private RGBCanvas canvas;
private AudioEffectHandler handler;
private double[] totData = new double[256];
private int[][] colData = new int[256][3];
@Override
public Boolean isNeedsFFT() {
return true;
}
public void frame(double[] audio) {
int totalCells = canvas.getHeight() * canvas.getWidth();
float frac = (float) audio.length / (float) totalCells;
for (int i = 0; i < audio.length; i++) {
if (totData[i] > 0) {
totData[i] -= 0.5f;
if (totData[i] <= 0) {
totData[i] = 0;
colData[i] = randomFromColourSet();
}
}
}
for (int i = 0; i < audio.length; i++) {
totData[i] += audio[i] *= 2f;
if (totData[i] > 1)
totData[i] = 1;
}
canvas.clear();
for (int i = 0; i < canvas.getHeight(); i++) {
for (int j = 0; j < canvas.getWidth(); j++) {
int idx = (int) ((((float) i * (float) canvas.getWidth()) + (float) j) * frac);
canvas.setColour(Colors.getInterpolated(RGBCanvas.BLACK, colData[idx], (float) totData[idx]));
canvas.plot(j, i);
}
}
}
@Override
public void init(RGBCanvas canvas, AudioEffectHandler handler) {
this.handler = handler;
this.canvas = canvas;
for (int i = 0; i < colData.length; i++) {
colData[i] = randomFromColourSet();
}
update();
}
private int[] randomFromColourSet() {
double rnd = Math.random();
if (rnd < 0.334) {
return handler.getColor1();
} else if (rnd < 0.667) {
return handler.getColor2();
} else {
return handler.getColor3();
}
}
@Override
public void update() {
}
} | 1,713 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
ReactiveEffectHandler.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/effects/ReactiveEffectHandler.java | package uk.co.bithatch.snake.ui.effects;
import java.util.prefs.Preferences;
import uk.co.bithatch.snake.lib.Colors;
import uk.co.bithatch.snake.lib.Lit;
import uk.co.bithatch.snake.lib.effects.Reactive;
import uk.co.bithatch.snake.ui.ReactiveOptions;
import uk.co.bithatch.snake.ui.SchedulerManager.Queue;
public class ReactiveEffectHandler extends AbstractBackendEffectHandler<Reactive, ReactiveOptions> {
public ReactiveEffectHandler() {
super(Reactive.class, ReactiveOptions.class);
}
@Override
protected void onLoad(Preferences prefs, Reactive effect) {
effect.setSpeed(prefs.getInt("speed", 100));
effect.setColor(Colors.fromHex(prefs.get("color", "#00ff00")));
}
@Override
protected void onSave(Preferences prefs, Reactive effect) {
prefs.putInt("speed", effect.getSpeed());
prefs.put("color", Colors.toHex(effect.getColor()));
}
@Override
protected void onStore(Lit component, ReactiveOptions controller) throws Exception {
Reactive reactive = (Reactive) controller.getEffect().clone();
reactive.setColor(controller.getColor());
reactive.setSpeed(controller.getSpeed());
getContext().getSchedulerManager().get(Queue.DEVICE_IO).execute(() -> component.setEffect(reactive));
save(component, reactive);
}
}
| 1,252 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
RippleEffectHandler.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/effects/RippleEffectHandler.java | package uk.co.bithatch.snake.ui.effects;
import java.util.prefs.Preferences;
import uk.co.bithatch.snake.lib.Colors;
import uk.co.bithatch.snake.lib.Lit;
import uk.co.bithatch.snake.lib.effects.Ripple;
import uk.co.bithatch.snake.lib.effects.Ripple.Mode;
import uk.co.bithatch.snake.ui.RippleOptions;
import uk.co.bithatch.snake.ui.SchedulerManager.Queue;
public class RippleEffectHandler extends AbstractBackendEffectHandler<Ripple, RippleOptions> {
public RippleEffectHandler() {
super(Ripple.class, RippleOptions.class);
}
@Override
protected void onLoad(Preferences prefs, Ripple effect) {
effect.setMode(Mode.valueOf(prefs.get("mode", Mode.RANDOM.name())));
effect.setRefreshRate(prefs.getDouble("refreshRate", 100));
effect.setColor(Colors.fromHex(prefs.get("color", "#00ff00")));
}
@Override
protected void onSave(Preferences prefs, Ripple effect) {
prefs.put("mode", effect.getMode().name());
prefs.putDouble("refreshRate", effect.getRefreshRate());
prefs.put("color", Colors.toHex(effect.getColor()));
}
@Override
protected void onStore(Lit component, RippleOptions controller) throws Exception {
Ripple ripple = (Ripple) controller.getEffect().clone();
ripple.setMode(controller.getMode());
ripple.setColor(controller.getColor());
ripple.setRefreshRate(controller.getRefreshRate());
getContext().getSchedulerManager().get(Queue.DEVICE_IO).execute(() -> component.setEffect(ripple));
save(component, ripple);
}
}
| 1,470 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
BreathEffectHandler.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/effects/BreathEffectHandler.java | package uk.co.bithatch.snake.ui.effects;
import java.util.prefs.Preferences;
import uk.co.bithatch.snake.lib.Colors;
import uk.co.bithatch.snake.lib.Lit;
import uk.co.bithatch.snake.lib.effects.Breath;
import uk.co.bithatch.snake.lib.effects.Breath.Mode;
import uk.co.bithatch.snake.ui.BreathOptions;
import uk.co.bithatch.snake.ui.SchedulerManager.Queue;
public class BreathEffectHandler extends AbstractBackendEffectHandler<Breath, BreathOptions> {
public BreathEffectHandler() {
super(Breath.class, BreathOptions.class);
}
@Override
protected void onLoad(Preferences prefs, Breath effect) {
effect.setMode(Mode.valueOf(prefs.get("mode", Mode.RANDOM.name())));
effect.setColor(Colors.fromHex(prefs.get("color", "#00ff00")));
effect.setColor1(Colors.fromHex(prefs.get("color2", "#00ff00")));
effect.setColor2(Colors.fromHex(prefs.get("color1", "#0000ff")));
}
@Override
protected void onSave(Preferences prefs, Breath effect) {
prefs.put("mode", effect.getMode().name());
prefs.put("color", Colors.toHex(effect.getColor()));
prefs.put("color1", Colors.toHex(effect.getColor1()));
prefs.put("color2", Colors.toHex(effect.getColor2()));
}
@Override
protected void onStore(Lit component, BreathOptions controller) throws Exception {
Breath breath = (Breath) controller.getEffect().clone();
breath.setMode(controller.getMode());
breath.setColor(controller.getColor());
breath.setColor1(controller.getColor1());
breath.setColor2(controller.getColor2());
getContext().getSchedulerManager().get(Queue.DEVICE_IO).execute(() -> component.setEffect(breath));
save(component, breath);
}
}
| 1,630 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
AudioEffectHandler.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/effects/AudioEffectHandler.java | package uk.co.bithatch.snake.ui.effects;
import java.lang.System.Logger.Level;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.prefs.Preferences;
import uk.co.bithatch.jdraw.CompoundBacking;
import uk.co.bithatch.jdraw.DoubleBufferBacking;
import uk.co.bithatch.jdraw.RGBCanvas;
import uk.co.bithatch.jimpulse.Impulse;
import uk.co.bithatch.snake.lib.Colors;
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;
import uk.co.bithatch.snake.ui.AudioOptions;
import uk.co.bithatch.snake.ui.SchedulerManager.Queue;
import uk.co.bithatch.snake.ui.audio.AudioManager.Listener;
import uk.co.bithatch.snake.ui.drawing.MatrixBacking;
public class AudioEffectHandler extends AbstractPersistentEffectHandler<Matrix, AudioOptions> {
public final static int[] BLACK = new int[3];
private AudioEffectMode mode;
private Matrix effect;
private int width;
private int height;
private Impulse impulse;
private int[][][] frame;
private Map<Lit, Listener> listeners = new HashMap<>();
private CompoundBacking backing;
private Class<? extends AudioEffectMode> modeClass = ExpandAudioEffectMode.class;
private int[] color1 = RGBCanvas.RED;
private int[] color2 = RGBCanvas.ORANGE;
private int[] color3 = RGBCanvas.GREEN;
private DoubleBufferBacking buffer;
private RGBCanvas canvas;
public AudioEffectHandler() {
super(Matrix.class, AudioOptions.class);
}
@Override
public boolean isRegions() {
return false;
}
@Override
public void removed(Device device) {
}
@Override
public void deactivate(Lit component) {
getContext().getAudioManager().removeListener(listeners.get(component));
}
@Override
public void update(Lit component) {
Lit.getDevice(component).updateEffect(effect);
}
public Matrix getEffect() {
return effect;
}
public CompoundBacking getBacking() {
return backing;
}
@Override
protected Matrix onActivate(Lit component) {
effect = component.createEffect(Matrix.class);
/* Load the configuration for this effect */
onLoad(getEffectPreferences(component), effect);
int[] dw = Lit.getDevice(component).getMatrixSize();
height = dw[0];
width = dw[1];
frame = new int[height][width][3];
backing = new CompoundBacking(new MatrixBacking(width, height, frame));
buffer = new DoubleBufferBacking(backing);
canvas = new RGBCanvas(buffer);
createMode();
effect.setCells(frame);
Listener listener = (snapshot) -> {
getContext().getSchedulerManager().get(Queue.DEVICE_IO).submit(() -> frame(component, snapshot));
};
listeners.put(component, listener);
getContext().getAudioManager().addListener(listener);
return effect;
}
protected void createMode() {
try {
mode = modeClass.getConstructor().newInstance();
} catch (Exception e) {
LOG.log(Level.ERROR, "Failed to configured mode. Defaulting.", e);
mode = new ExpandAudioEffectMode();
}
mode.init(canvas, this);
canvas.reset();
}
@Override
public Class<AudioOptions> getOptionsController() {
return AudioOptions.class;
}
@Override
public boolean isSupported(Lit component) {
return true;
}
@Override
public URL getEffectImage(int size) {
return getContext().getConfiguration().getTheme().getEffectImage(size, "audio");
}
@Override
public String getDisplayName() {
return bundle.getString("effect.Audio");
}
@SuppressWarnings("unchecked")
@Override
protected void onLoad(Preferences prefs, Matrix effect) {
try {
modeClass = (Class<? extends AudioEffectMode>) getClass().getClassLoader()
.loadClass(prefs.get("mode", PeaksAudioEffectMode.class.getName()));
} catch (ClassNotFoundException e) {
modeClass = PeaksAudioEffectMode.class;
}
color1 = Colors.fromHex(prefs.get("color1", Colors.toHex(RGBCanvas.RED)));
color2 = Colors.fromHex(prefs.get("color2", Colors.toHex(RGBCanvas.ORANGE)));
color3 = Colors.fromHex(prefs.get("color3", Colors.toHex(RGBCanvas.GREEN)));
}
@Override
protected void onSave(Preferences prefs, Matrix effect) {
prefs.put("mode", mode == null ? "" : modeClass.getName());
prefs.put("color1", Colors.toHex(color1));
prefs.put("color2", Colors.toHex(color2));
prefs.put("color3", Colors.toHex(color3));
}
@Override
protected void onStore(Lit component, AudioOptions controller) throws Exception {
color1 = controller.getColor1();
color2 = controller.getColor2();
color3 = controller.getColor3();
if (!controller.getMode().equals(modeClass)) {
modeClass = controller.getMode();
createMode();
}
if (impulse != null) {
impulse.setSourceIndex(controller.getSource() == null ? 0 : controller.getSource().getIndex());
}
mode.update();
save(component, null);
}
void frame(Lit component, double[] audio) {
try {
mode.frame(audio);
buffer.commit();
update(component);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public Class<? extends Effect> getBackendEffectClass() {
return Matrix.class;
}
public int[] getColor1() {
return color1;
}
public int[] getColor2() {
return color2;
}
public int[] getColor3() {
return color3;
}
public Class<? extends AudioEffectMode> getMode() {
return modeClass;
}
}
| 5,289 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
CustomEffectHandler.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/effects/CustomEffectHandler.java | package uk.co.bithatch.snake.ui.effects;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import com.sshtools.icongenerator.IconBuilder.TextContent;
import javafx.scene.Node;
import uk.co.bithatch.snake.lib.Device;
import uk.co.bithatch.snake.lib.Lit;
import uk.co.bithatch.snake.lib.animation.AudioParameters;
import uk.co.bithatch.snake.lib.animation.FramePlayer;
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.effects.Effect;
import uk.co.bithatch.snake.lib.effects.Matrix;
import uk.co.bithatch.snake.ui.CustomOptions;
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.widgets.GeneratedIcon;
public class CustomEffectHandler extends AbstractEffectHandler<Sequence, CustomOptions> {
private static final String PREF_HOLD_FOR = "holdFor";
private static final String PREF_FPX = "fps";
private static final String PREF_FRAMES = "frames";
private static final String PREF_INTERPOLATION = "interpolation";
private static final String PREF_REPEAT = "repeat";
private static final String PREF_SPEED = "speed";
private String name;
private FramePlayer player;
private Sequence sequence;
private boolean readOnly;
public CustomEffectHandler() {
this(null);
}
public CustomEffectHandler(String name) {
this(name, null);
}
public CustomEffectHandler(String name, Sequence sequence) {
this.name = name;
if (sequence == null) {
sequence = new Sequence();
sequence.setInterpolation(Interpolation.linear);
sequence.setSpeed(1);
sequence.setFps(25);
sequence.setRepeat(true);
sequence.add(new KeyFrame());
}
this.sequence = sequence;
}
@Override
public Class<? extends Effect> getBackendEffectClass() {
return Matrix.class;
}
public boolean isReadOnly() {
return readOnly;
}
public void setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
}
public void setSequence(Sequence sequence) {
this.sequence = sequence;
}
@Override
public void added(Device device) {
if (!isReadOnly())
Prefs.addToStringSet(getContext().getEffectManager().getPreferences(device),
EffectManager.PREF_CUSTOM_EFFECTS, getName());
}
@Override
public void removed(Device device) {
if (getPlayer().isPlaying())
getPlayer().stop();
if (!isReadOnly()) {
Prefs.removeFromStringSet(getContext().getEffectManager().getPreferences(device),
EffectManager.PREF_CUSTOM_EFFECTS, getName());
try {
getEffectPreferences(device).removeNode();
} catch (BackingStoreException e) {
throw new IllegalStateException("Failed to remove effect.", e);
}
}
}
@Override
public String getDisplayName() {
return name == null || name.length() == 0 ? bundle.getString("effect.Custom") : name;
}
@Override
public URL getEffectImage(int size) {
return getContext().getConfiguration().getTheme().getEffectImage(size, Matrix.class);
}
public Node getEffectImageNode(int size, int viewSize) {
GeneratedIcon ib = new GeneratedIcon();
ib.setPrefWidth(viewSize);
ib.setPrefHeight(viewSize);
ib.setMinWidth(viewSize);
ib.setMinHeight(viewSize);
ib.setMaxWidth(viewSize);
ib.setMaxHeight(viewSize);
ib.setText(getDisplayName());
ib.setTextContent(TextContent.INITIALS);
return ib;
}
@Override
public String getName() {
return name;
}
@Override
public Class<CustomOptions> getOptionsController() {
return CustomOptions.class;
}
public FramePlayer getPlayer() {
return player;
}
public Sequence getSequence() {
return sequence;
}
@Override
public boolean isSupported(Lit component) {
return component == null ? false : component.getSupportedEffects().contains(Matrix.class);
}
public void setName(String name) {
this.name = name;
}
protected void addDefaultFrames(Lit component) {
Device dev = Lit.getDevice(component);
int[] dim = dev.getMatrixSize();
KeyFrame f1 = new KeyFrame();
f1.setColor(new int[] { 0xff, 0x00, 0x00 }, dim[0], dim[1]);
f1.setHoldFor(TimeUnit.SECONDS.toMillis(5));
sequence.add(f1);
KeyFrame f2 = new KeyFrame();
f2.setColor(new int[] { 0x00, 0xff, 0x00 }, dim[0], dim[1]);
f2.setHoldFor(TimeUnit.SECONDS.toMillis(5));
sequence.add(f2);
KeyFrame f3 = new KeyFrame();
f3.setColor(new int[] { 0x00, 0x00, 0xff }, dim[0], dim[1]);
f3.setHoldFor(TimeUnit.SECONDS.toMillis(5));
sequence.add(f3);
}
@Override
public void deactivate(Lit component) {
if (player.isPlaying())
player.stop();
}
@Override
public void update(Lit component) {
Matrix effect = (Matrix) component.getEffect();
component.updateEffect(effect);
}
@Override
protected Sequence onActivate(Lit component) {
if (!player.isReady()) {
player.setDevice(Lit.getDevice(component));
player.setSequence(getSequence());
Matrix effect = component.createEffect(Matrix.class);
onLoad(component, getEffectPreferences(component), effect);
player.setEffect(effect);
}
if (player.isPaused())
player.setPaused(false);
else if (!player.isPlaying())
player.play();
return getSequence();
}
protected void onLoad(Lit component, Preferences matrix, Matrix effect) {
Preferences framesPrefs = matrix.node(PREF_FRAMES);
sequence.setFps(matrix.getInt(PREF_FPX, 25));
sequence.setRepeat(matrix.getBoolean(PREF_REPEAT, true));
sequence.setSpeed(matrix.getFloat(PREF_SPEED, 1));
int low = matrix.getInt("audioLow", 0);
int high = matrix.getInt("audioHigh", 255);
float gain = matrix.getFloat("audioGain", 1f);
if (low != 0 || high != 255 || gain != 1) {
AudioParameters parameters = new AudioParameters();
parameters.setLow(low);
parameters.setHigh(high);
parameters.setGain(gain);
sequence.setAudioParameters(parameters);
}
sequence.setInterpolation(Interpolation.get(matrix.get(PREF_INTERPOLATION, Interpolation.linear.getName())));
sequence.clear();
try {
String[] childrenNames = framesPrefs.childrenNames();
for (String frameId : childrenNames) {
Preferences frameNode = framesPrefs.node(frameId);
KeyFrame frame = load(frameNode);
sequence.add(frame);
}
} catch (BackingStoreException bse) {
throw new IllegalStateException("Could not load matrix effect configuration.", bse);
}
/* Must have one frame */
if (sequence.isEmpty()) {
addDefaultFrames(component);
if (!isReadOnly())
onSave(matrix);
}
}
protected void onSave(Preferences prefs) {
if (readOnly)
throw new IllegalStateException("This is a read only effect.");
/* Delete existing matrix */
Preferences customNode = prefs.node(PREF_FRAMES);
try {
customNode.removeNode();
customNode = prefs.node(PREF_FRAMES);
} catch (BackingStoreException bse) {
throw new IllegalStateException("Failed to remove old custom.", bse);
}
int id = 1;
prefs.put(PREF_INTERPOLATION, sequence.getInterpolation().getName());
prefs.putBoolean(PREF_REPEAT, sequence.isRepeat());
prefs.putInt(PREF_FPX, sequence.getFps());
prefs.putFloat(PREF_SPEED, sequence.getSpeed());
AudioParameters audio = sequence.getAudioParameters();
if (audio == null) {
prefs.remove("audioLow");
prefs.remove("audioHigh");
prefs.remove("audioGain");
} else {
prefs.putInt("audioLow", audio.getLow());
prefs.putInt("audioHigh", audio.getHigh());
prefs.putFloat("audioGain", audio.getGain());
}
for (KeyFrame frame : sequence) {
Preferences framePref = customNode.node(String.valueOf(id++));
save(frame, framePref);
}
}
@Override
public boolean isRegions() {
return false;
}
@Override
public boolean hasOptions() {
return super.hasOptions() && !isReadOnly();
}
@Override
protected void onSetContext() {
player = new FramePlayer(getContext().getSchedulerManager().get(Queue.DEVICE_IO),
getContext().getAudioManager());
}
@Override
protected void onStore(Lit component, CustomOptions controller) throws Exception {
onSave(getEffectPreferences(component));
}
public KeyFrame load(Preferences node) {
var rows = node.getInt("rows", 0);
var cols = node.getInt("cols", -1);
KeyFrameCell[][] frame = null;
if (rows != 0) {
frame = new KeyFrameCell[rows][];
if (cols == -1) {
/*
* Used versions 1.0-SNAPSHOT-24 and earlier, there were only rows, with each
* row a long string of colours for each cell
*/
for (int i = 0; i < rows; i++) {
var data = node.get("row" + i, "");
if (!data.equals("")) {
var rowRgb = data.split(":");
var row = new KeyFrameCell[rowRgb.length];
int col = 0;
for (String rgb : rowRgb) {
row[col++] = new KeyFrameCell(new int[] { Integer.parseInt(rgb.substring(0, 2), 16),
Integer.parseInt(rgb.substring(2, 4), 16),
Integer.parseInt(rgb.substring(4, 6), 16) }, KeyFrameCellSource.COLOR);
}
frame[i] = row;
}
}
} else {
for (int i = 0; i < rows; i++) {
var row = new KeyFrameCell[cols];
for (int j = 0; j < cols; j++) {
var data = node.get("cell" + i + "," + j, "");
if (!data.equals("")) {
var args = data.split(":");
List<KeyFrameCellSource> l = new ArrayList<>();
for (String a : args[0].split(",")) {
l.add(KeyFrameCellSource.valueOf(a));
}
var rgb = args[1];
row[j] = new KeyFrameCell(
new int[] { Integer.parseInt(rgb.substring(0, 2), 16),
Integer.parseInt(rgb.substring(2, 4), 16),
Integer.parseInt(rgb.substring(4, 6), 16) },
l.toArray(new KeyFrameCellSource[0]));
row[j].setInterpolation(Interpolation.fromName(args[2]));
}
}
frame[i] = row;
}
}
}
var keyFrame = new KeyFrame();
keyFrame.setInterpolation(
Interpolation.get(node.get(PREF_INTERPOLATION, keyFrame.getInterpolation().getName())));
keyFrame.setHoldFor(node.getLong(PREF_HOLD_FOR, keyFrame.getHoldFor()));
keyFrame.setFrame(frame);
return keyFrame;
}
void save(KeyFrame keyFrame, Preferences node) {
if (readOnly)
throw new IllegalStateException("This is a read only effect.");
KeyFrameCell[][] frame = keyFrame.getFrame();
node.put(PREF_INTERPOLATION, keyFrame.getInterpolation().getName());
node.putLong(PREF_HOLD_FOR, keyFrame.getHoldFor());
if (frame != null) {
int rowCount = 0;
int colCount = 0;
for (KeyFrameCell[] row : frame) {
colCount = 0;
/* Remove the pre 1.0-SNAPSHOT-24 storage data if there is any */
node.remove("row" + rowCount);
for (KeyFrameCell col : row) {
if (col == null) {
node.remove("cell" + rowCount + "," + colCount);
} else {
StringBuilder b = new StringBuilder();
b.append(Strings.toSeparatedList(",", Arrays.asList(col.getSources())));
b.append(":");
b.append(String.format("%02x%02x%02x", col.getValues()[0], col.getValues()[1],
col.getValues()[2]));
b.append(":");
b.append(col.getInterpolation().getName());
node.put("cell" + rowCount + "," + colCount, b.toString());
}
colCount++;
}
rowCount++;
}
node.putInt("rows", rowCount);
node.putInt("cols", colCount);
}
}
}
| 11,544 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
EffectAcquisition.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/effects/EffectAcquisition.java | package uk.co.bithatch.snake.ui.effects;
import java.util.Set;
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.ui.EffectHandler;
public interface EffectAcquisition extends AutoCloseable {
public interface EffectChangeListener {
void effectChanged(Lit component, EffectHandler<?, ?> effect);
}
<E extends Effect> E getEffectInstance(Lit component);
Device getDevice();
EffectHandler<?, ?> getEffect(Lit lit);
void activate(Lit lit, EffectHandler<?, ?> effect);
void deactivate(Lit lit);
void remove(Lit lit);
void update(Lit lit);
Set<Lit> getLitAreas();
void addListener(EffectChangeListener listener);
void removeListener(EffectChangeListener listener);
<E extends EffectHandler<?, ?>> E activate(Lit lit, Class<E> class1);
}
| 862 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
ExpandAudioEffectMode.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/effects/ExpandAudioEffectMode.java | package uk.co.bithatch.snake.ui.effects;
import uk.co.bithatch.jdraw.Gradient;
import uk.co.bithatch.jdraw.RGBCanvas;
public class ExpandAudioEffectMode implements AudioEffectMode {
private RGBCanvas canvas;
private Gradient bg;
private AudioEffectHandler handler;
@Override
public Boolean isNeedsFFT() {
return true;
}
public void frame(double[] audio) {
int width = canvas.getWidth();
int height = canvas.getHeight();
int l = audio.length;
float freq = (float) audio.length / (float) width;
int actualCols = (int) ((float) audio.length / freq) + 1;
canvas.clear();
canvas.translate((width - actualCols) / 2, 0);
canvas.setGradient(bg);
float step = (float) 1 / (float) width;
for (float i = 0; i < 1; i += step) {
double amp = audio[(int) (i * (float) l)];
int barHeight = (int) (amp * height);
if (barHeight > 0) {
canvas.fillRect((int) ((i / step)), height / 2 - barHeight / 2, 1, barHeight);
}
}
canvas.translate(0, 0);
}
@Override
public void init(RGBCanvas canvas, AudioEffectHandler handler) {
this.canvas = canvas;
this.handler = handler;
update();
}
@Override
public void update() {
bg = new Gradient(new float[] { 0f, 0.5f, 1.0f }, handler.getColor1(), handler.getColor2(),
handler.getColor3());
}
} | 1,293 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
AbstractEffectHandler.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/effects/AbstractEffectHandler.java | package uk.co.bithatch.snake.ui.effects;
import java.lang.System.Logger.Level;
import java.util.ResourceBundle;
import java.util.prefs.Preferences;
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.ui.AbstractEffectController;
import uk.co.bithatch.snake.ui.App;
import uk.co.bithatch.snake.ui.EffectHandler;
public abstract class AbstractEffectHandler<E, C extends AbstractEffectController<E, ?>>
implements EffectHandler<E, C> {
final static System.Logger LOG = System.getLogger(AbstractEffectHandler.class.getName());
protected final static ResourceBundle bundle = ResourceBundle.getBundle(EffectHandler.class.getName());
private App context;
private Device device;
@Override
public final void open(App context, Device device) {
this.context = context;
this.device = device;
onSetContext();
}
public final Device getDevice() {
return device;
}
@Override
public App getContext() {
return context;
}
@Override
public final E activate(Lit component) {
select(component);
if (component instanceof Device && isRegions()) {
/* If device, select the same effect on all of the regions as well */
for (Region r : ((Device) component).getRegions())
select(r);
}
return onActivate(component);
}
@Override
public final void select(Lit component) {
/* Save this as the currently activated effect */
getContext().getEffectManager().getPreferences(component).put(EffectManager.PREF_EFFECT, getName());
if (!(component instanceof Device)) {
/* Because switching to individual regions, clear out the saved device effect */
getContext().getEffectManager().getPreferences(Lit.getDevice(component)).put(EffectManager.PREF_EFFECT, "");
}
}
@Override
public final void store(Lit component, C controller) {
try {
onStore(component, controller);
} catch (Exception e) {
LOG.log(Level.ERROR, "Failed to update effect.", e);
}
}
@Override
public void update(Lit component) {
}
protected abstract E onActivate(Lit component);
protected abstract void onStore(Lit component, C controller) throws Exception;
protected void onSetContext() {
}
protected Preferences getEffectPreferences(Lit component) {
return getContext().getEffectManager().getPreferences(component).node(getName());
}
}
| 2,361 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
LineyAudioEffectMode.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/effects/LineyAudioEffectMode.java | package uk.co.bithatch.snake.ui.effects;
import uk.co.bithatch.jdraw.RGBCanvas;
public class LineyAudioEffectMode implements AudioEffectMode {
private RGBCanvas canvas;
private AudioEffectHandler handler;
private double[] totData;
@Override
public Boolean isNeedsFFT() {
return true;
}
public void frame(double[] audio) {
double t = 0;
for (double d : audio)
t += d;
t /= (double) audio.length;
int width = canvas.getWidth();
totData[width - 1] = Math.min(1, t);
System.arraycopy(totData, 1, totData, 0, totData.length - 1);
canvas.clear();
canvas.setColour(handler.getColor1());
int height = canvas.getHeight();
int h = (int) ((float) height / 2.0);
int y = h;
for (int j = 0; j < width; j++) {
if (totData[j] < 0.334) {
canvas.setColour(handler.getColor1());
} else if (totData[j] < 0.667) {
canvas.setColour(handler.getColor2());
} else {
canvas.setColour(handler.getColor3());
}
int ny = (int) ((double) height * totData[j]);
if (j == 0)
canvas.plot(j, height - ny);
else {
canvas.drawLine(j - 1, height - y, j, height - ny);
}
y = ny;
}
}
@Override
public void init(RGBCanvas canvas, AudioEffectHandler handler) {
this.handler = handler;
this.canvas = canvas;
totData = new double[canvas.getWidth()];
update();
}
@Override
public void update() {
}
} | 1,362 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
StaticEffectHandler.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/effects/StaticEffectHandler.java | package uk.co.bithatch.snake.ui.effects;
import java.util.prefs.Preferences;
import uk.co.bithatch.snake.lib.Colors;
import uk.co.bithatch.snake.lib.Lit;
import uk.co.bithatch.snake.lib.effects.Static;
import uk.co.bithatch.snake.ui.SchedulerManager.Queue;
import uk.co.bithatch.snake.ui.StaticOptions;
public class StaticEffectHandler extends AbstractBackendEffectHandler<Static, StaticOptions> {
public StaticEffectHandler() {
super(Static.class, StaticOptions.class);
}
@Override
protected void onLoad(Preferences prefs, Static effect) {
effect.setColor(Colors.fromHex(prefs.get("color", "#00ff00")));
}
@Override
protected void onSave(Preferences prefs, Static effect) {
prefs.put("color", Colors.toHex(effect.getColor()));
}
@Override
protected void onStore(Lit component, StaticOptions controller) throws Exception {
Static staticEffect = (Static) controller.getEffect().clone();
staticEffect.setColor(controller.getColor());
getContext().getSchedulerManager().get(Queue.DEVICE_IO).execute(() -> component.setEffect(staticEffect));
save(component, staticEffect);
}
}
| 1,107 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
OffEffectHandler.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/effects/OffEffectHandler.java | package uk.co.bithatch.snake.ui.effects;
import uk.co.bithatch.snake.lib.Lit;
import uk.co.bithatch.snake.lib.effects.Off;
import uk.co.bithatch.snake.ui.AbstractBackendEffectController;
public class OffEffectHandler extends AbstractBackendEffectHandler<Off, AbstractBackendEffectController<Off, ?>> {
public OffEffectHandler() {
super(Off.class, null);
}
@Override
protected void onStore(Lit component, AbstractBackendEffectController<Off, ?> controller) throws Exception {
}
}
| 490 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
EffectManager.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/effects/EffectManager.java | package uk.co.bithatch.snake.ui.effects;
import java.io.Closeable;
import java.io.IOException;
import java.lang.System.Logger.Level;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
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.ServiceLoader;
import java.util.Set;
import java.util.Stack;
import java.util.prefs.Preferences;
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.Lit;
import uk.co.bithatch.snake.lib.Region;
import uk.co.bithatch.snake.lib.effects.Effect;
import uk.co.bithatch.snake.lib.effects.Off;
import uk.co.bithatch.snake.ui.App;
import uk.co.bithatch.snake.ui.EffectHandler;
import uk.co.bithatch.snake.ui.util.Prefs;
public class EffectManager implements BackendListener, Closeable {
private final class EffectAcquisitionImpl implements EffectAcquisition {
private final Device device;
private final Stack<EffectAcquisitionImpl> stack;
private Map<Lit, EffectHandler<?, ?>> effects = new HashMap<>();
private List<EffectChangeListener> listeners = new ArrayList<>();
private Map<Lit, EffectHandler<?, ?>> active = Collections.synchronizedMap(new HashMap<>());
private Map<Lit, Object> activations = Collections.synchronizedMap(new HashMap<>());
private EffectAcquisitionImpl(Device device, Stack<EffectAcquisitionImpl> stack) {
this.device = device;
this.stack = stack;
}
@SuppressWarnings("unchecked")
public <E extends Effect> E getEffectInstance(Lit component) {
return (E) activations.get(component);
}
@Override
public void deactivate(Lit lit) {
/* This current effect */
EffectHandler<?, ?> effect = effects.get(lit);
if (effect != null) {
if (LOG.isLoggable(Level.DEBUG))
LOG.log(Level.DEBUG,
String.format("De-activating effect %s on %s", effect.getDisplayName(), lit.toString()));
effect.deactivate(lit);
}
}
@Override
public void remove(Lit lit) {
/* This current effect */
EffectHandler<?, ?> effect = effects.remove(lit);
if (effect != null) {
if (LOG.isLoggable(Level.INFO))
LOG.log(Level.INFO,
String.format("Removing effect %s on %s", effect.getDisplayName(), lit.toString()));
active.remove(lit);
activations.remove(lit);
effect.deactivate(lit);
for (int i = listeners.size() - 1; i >= 0; i--)
listeners.get(i).effectChanged(lit, effect);
}
}
@Override
public void activate(Lit lit, EffectHandler<?, ?> effect) {
if (LOG.isLoggable(Level.DEBUG))
LOG.log(Level.DEBUG,
String.format("Activating effect %s on %s", effect.getDisplayName(), lit.toString()));
/* Activate the new effect */
if (lit.getSupportedEffects().contains(effect.getBackendEffectClass())) {
if (effect.isRegions()) {
if (lit instanceof Device) {
deactivateDevicesRegions((Device) lit);
for (Region r : ((Device) lit).getRegions())
effects.put(r, effect);
} else {
deactivateLitsDevice(lit);
effects.put(lit, effect);
}
} else {
/*
* Effect doesn't support regions, so first of all it must only be activated as
* a whole Device
*/
if (!(lit instanceof Device)) {
throw new IllegalArgumentException("Cannot set individual regions for this effect.");
}
deactivateDevicesRegions((Device) lit);
effects.put((Device) lit, effect);
}
activations.put(lit, effect.activate(lit));
active.put(lit, effect);
} else
throw new UnsupportedOperationException(String.format("Effect %s is not supported on %s", effect, lit));
for (int i = listeners.size() - 1; i >= 0; i--)
listeners.get(i).effectChanged(lit, effect);
if (LOG.isLoggable(Level.DEBUG))
LOG.log(Level.DEBUG, String.format("Now %d effects, %d activations, and %d active in acq. %s",
effects.size(), activations.size(), active.size(), hashCode()));
}
public void addListener(EffectChangeListener listener) {
this.listeners.add(listener);
}
@Override
public void close() throws Exception {
synchronized (acquisitions) {
stack.remove(this);
/*
* Deactivate all the effects this acquisition used. Some effects may need to
* turn off timers etc
*
*/
for (Lit lit : new ArrayList<>(getLitAreas())) {
deactivate(lit);
}
/* If no acquisitions left, turn off effects */
if (acquisitions.isEmpty()) {
activate(device, EffectManager.this.getEffect(device, OffEffectHandler.class));
} else {
/* Return to the previous acquisitions effect */
Stack<EffectAcquisitionImpl> deviceStack = acquisitions.get(device);
if (deviceStack != null && !deviceStack.isEmpty()) {
EffectAcquisition iface = deviceStack.peek();
for (Lit subLit : iface.getLitAreas()) {
EffectHandler<?, ?> litEffect = iface.getEffect(subLit);
if (litEffect != null)
activate(subLit, litEffect);
}
}
}
}
}
@Override
public Device getDevice() {
return device;
}
@SuppressWarnings("resource")
@Override
public EffectHandler<?, ?> getEffect(Lit lit) {
if (effects.containsKey(lit)) {
return effects.get(lit);
} else {
String effectName = getPreferences(lit).get(EffectManager.PREF_EFFECT, "");
if (lit instanceof Device) {
if (effectName.equals("")) {
EffectHandler<?, ?> leffect = null;
for (Region r : Lit.getDevice(lit).getRegions()) {
EffectHandler<?, ?> reffect = getEffect(r);
if (leffect != null && !Objects.equals(reffect, leffect)) {
/* Different effects on different regions */
return null;
}
leffect = reffect;
}
/* Same effect on same regions */
return leffect;
}
}
return EffectManager.this.getEffect(Lit.getDevice(lit), effectName);
}
}
@Override
public Set<Lit> getLitAreas() {
return effects.keySet();
}
public void removeListener(EffectChangeListener listener) {
this.listeners.remove(listener);
}
@Override
public void update(Lit lit) {
/*
* Only update if this is actually the head aquisition. We will update the
* current effect when all acquisitions are released and this becomes the head.
*/
synchronized (acquisitions) {
if (this == stack.peek()) {
if (lit instanceof Device) {
for (Region r : Lit.getDevice(lit).getRegions()) {
EffectHandler<?, ?> litEffect = effects.get(r);
if (litEffect != null)
litEffect.update(r);
}
} else {
EffectHandler<?, ?> litEffect = effects.get(lit);
if (litEffect != null)
litEffect.update(lit);
}
}
}
}
@Override
public <E extends EffectHandler<?, ?>> E activate(Lit region, Class<E> class1) {
E fx = findEffect(region, class1);
if (fx != null)
activate(region, fx);
return fx;
}
protected void deactivateDevicesRegions(Device lit) {
/* If there are region region effects, deactivate and remove those first */
for (Region r : lit.getRegions()) {
EffectHandler<?, ?> regionEffect = effects.remove(r);
if (regionEffect != null) {
if (LOG.isLoggable(Level.DEBUG))
LOG.log(Level.DEBUG, String.format("Deactivating devices region effect %s on %s",
regionEffect.getDisplayName(), lit.toString()));
regionEffect.deactivate(r);
active.remove(r);
activations.remove(r);
}
}
deactivateLitsDevice(lit);
}
protected void deactivateLitsDevice(Lit region) {
/*
* Effect supports regions, so remove and deactivate any device effect and if
* activating a device, replace with individual regions.
*/
Device litDevice = Lit.getDevice(region);
EffectHandler<?, ?> deviceEffect = effects.remove(litDevice);
if (deviceEffect != null) {
if (LOG.isLoggable(Level.DEBUG))
LOG.log(Level.DEBUG, String.format("Deactivating regions device effect %s on %s",
deviceEffect.getDisplayName(), region.toString()));
deviceEffect.deactivate(litDevice);
active.remove(litDevice);
activations.remove(litDevice);
}
}
}
public interface Listener {
void effectAdded(Device component, EffectHandler<?, ?> effect);
void effectRemoved(Device component, EffectHandler<?, ?> effect);
}
public static final String PREF_EFFECT = "effect";
public static final String PREF_SYNC = "sync";
final static System.Logger LOG = System.getLogger(EffectManager.class.getName());
static final String PREF_CUSTOM_EFFECTS = "customEffects";
private Map<Device, Stack<EffectAcquisitionImpl>> acquisitions = new HashMap<>();
private App context;
private Map<Device, Map<String, EffectHandler<?, ?>>> effectHandlers = Collections
.synchronizedMap(new LinkedHashMap<>());
private List<Listener> listeners = new ArrayList<>();
public EffectManager(App context) {
this.context = context;
}
public EffectAcquisition acquire(Device device) {
Stack<EffectAcquisitionImpl> stack = getStack(device);
if (!stack.isEmpty()) {
stack.peek().deactivate(device);
}
EffectAcquisitionImpl iface = new EffectAcquisitionImpl(device, stack);
stack.add(iface);
return iface;
}
public void add(Device device, EffectHandler<?, ?> handler) {
if (device == null)
throw new IllegalArgumentException("Must provide device.");
if (LOG.isLoggable(Level.DEBUG))
LOG.log(Level.DEBUG, String.format("Adding effect handler %s to device %s", device.getName(),
handler.getClass().getName()));
Map<String, EffectHandler<?, ?>> deviceEffectHandlers = getDeviceEffectHandlers(device);
checkForName(handler, deviceEffectHandlers);
if (handler.getName() == null || handler.getName().equals(""))
throw new IllegalArgumentException("No name.");
if (handler.getContext() == null)
handler.open(context, device);
deviceEffectHandlers.put(handler.getName(), handler);
handler.added(device);
for (int i = listeners.size() - 1; i >= 0; i--)
listeners.get(i).effectAdded(device, handler);
}
public void open() {
context.getBackend().addListener(this);
try {
context.getBackend().setSync(context.getPreferences().getBoolean(PREF_SYNC, false));
}
catch(Exception e) {
LOG.log(Level.ERROR, "Failed to set sync state.", e);
}
}
public void addListener(Listener listener) {
this.listeners.add(listener);
}
public Map<String, EffectHandler<?, ?>> getDeviceEffectHandlers(Device device) {
Map<String, EffectHandler<?, ?>> deviceEffectHandlers = effectHandlers.get(device);
if (deviceEffectHandlers == null) {
deviceEffectHandlers = new LinkedHashMap<>();
effectHandlers.put(device, deviceEffectHandlers);
for (EffectHandler<?, ?> handler : ServiceLoader.load(EffectHandler.class)) {
addEffect(device, handler);
}
Preferences devPrefs = getPreferences(device);
for (String custom : Prefs.getStringSet(devPrefs, PREF_CUSTOM_EFFECTS)) {
CustomEffectHandler effect = new CustomEffectHandler();
effect.setName(custom);
effect.load(devPrefs.node(custom));
addEffect(device, effect);
}
}
return deviceEffectHandlers;
}
public Preferences getDevicePreferences(Device device) {
return context.getPreferences(device).node("effects");
}
@SuppressWarnings("unchecked")
public <E extends AbstractBackendEffectHandler<?, ?>> E getEffect(Device device, Class<E> effect) {
return (E) getEffect(device, effect.getSimpleName());
}
@SuppressWarnings("unchecked")
public <H extends EffectHandler<?, ?>> H getEffect(Device device, String name) {
return (H) getDeviceEffectHandlers(device).get(name);
}
public Set<EffectHandler<?, ?>> getEffects(Lit component) {
Set<EffectHandler<?, ?>> filteredHandlers = new LinkedHashSet<>();
Map<String, EffectHandler<?, ?>> deviceEffectHandlers = getDeviceEffectHandlers(Lit.getDevice(component));
for (EffectHandler<?, ?> h : deviceEffectHandlers.values()) {
if (h.isSupported(component)) {
filteredHandlers.add(h);
}
}
return filteredHandlers;
}
public EffectAcquisition getHeadAcquisition(Device device) {
synchronized (acquisitions) {
return acquisitions.get(device).peek();
}
}
public Preferences getPreferences(Lit component) {
if (component instanceof Device)
return getDevicePreferences((Device) component).node("device");
else if (component instanceof Region)
return getDevicePreferences(((Region) component).getDevice()).node("region")
.node(((Region) component).getName().name());
else
throw new IllegalArgumentException(
String.format("Unsuported %s type %s", Lit.class.getName(), component.getClass().getName()));
}
public EffectAcquisition getRootAcquisition(Device device) {
synchronized (acquisitions) {
Stack<EffectAcquisitionImpl> stack = getStack(device);
return stack.isEmpty() ? null : stack.firstElement();
}
}
public boolean isSupported(Lit component, Class<? extends EffectHandler<?, ?>> clazz) {
return findEffect(component, clazz) != null || isMatrixEffect(component, clazz);
}
protected boolean isMatrixEffect(Lit component, Class<? extends EffectHandler<?, ?>> clazz) {
/* TODO make this better */
return (clazz.equals(CustomEffectHandler.class) || clazz.equals(AudioEffectHandler.class))
&& Lit.getDevice(component).getCapabilities().contains(Capability.MATRIX);
}
public void remove(EffectHandler<?, ?> handler) {
Map<String, EffectHandler<?, ?>> deviceEffectHandlers = getDeviceEffectHandlers(handler.getDevice());
if (deviceEffectHandlers.containsKey(handler.getName())) {
/* Deactivate the effect on any device or region that is using it */
synchronized (acquisitions) {
for (Map.Entry<Device, Stack<EffectAcquisitionImpl>> en : acquisitions.entrySet()) {
for (EffectAcquisitionImpl acq : en.getValue()) {
for (Lit r : new ArrayList<>(acq.active.keySet())) {
if (acq.active.get(r).equals(handler)) {
acq.deactivate(r);
}
}
}
}
}
deviceEffectHandlers.remove(handler.getName());
handler.removed(handler.getDevice());
/*
* Set the first available effect back on every region on every device in the
* stack
*/
synchronized (acquisitions) {
for (Map.Entry<Device, Stack<EffectAcquisitionImpl>> en : acquisitions.entrySet()) {
for (EffectAcquisitionImpl acq : en.getValue()) {
Set<EffectHandler<?, ?>> effectsNow = getEffects(handler.getDevice());
if (!effectsNow.isEmpty())
acq.activate(handler.getDevice(), effectsNow.iterator().next());
}
}
}
for (int i = listeners.size() - 1; i >= 0; i--)
listeners.get(i).effectRemoved(handler.getDevice(), handler);
}
}
public void removeListener(Listener listener) {
this.listeners.remove(listener);
}
protected void addEffect(Device device, EffectHandler<?, ?> handler) {
Map<String, EffectHandler<?, ?>> deviceEffectHandlers = getDeviceEffectHandlers(device);
if (deviceEffectHandlers.containsKey(handler.getName())) {
throw new IllegalStateException(String.format(
"Attempt to register more than one effect named %s. Please rename the %s implementation, only the class name itself is used and must be unique.",
handler.getName(), EffectHandler.class.getName()));
}
deviceEffectHandlers.put(handler.getName(), handler);
if (LOG.isLoggable(Level.DEBUG))
LOG.log(Level.DEBUG,
String.format("Adding effect %s, serviced by %s", handler.getName(), handler.getClass().getName()));
handler.open(context, device);
}
protected void checkForName(EffectHandler<?, ?> handler, Map<String, EffectHandler<?, ?>> deviceEffectHandlers) {
if (deviceEffectHandlers.containsKey(handler.getName())) {
throw new IllegalStateException(String.format(
"Attempt to register more than one effect named %s. Please rename the %s implementation, only the class name itself is used and must be unique.",
handler.getName(), EffectHandler.class.getName()));
}
}
protected Stack<EffectAcquisitionImpl> getStack(Device device) {
Stack<EffectAcquisitionImpl> stack = acquisitions.get(device);
if (stack == null) {
stack = new Stack<>();
acquisitions.put(device, stack);
}
return stack;
}
@SuppressWarnings("unchecked")
private <H extends EffectHandler<?, ?>> H findEffect(Lit component, Class<H> clazz) {
for (EffectHandler<?, ?> eh : getEffects(component)) {
if (eh.getClass().equals(clazz))
return (H) eh;
}
return null;
}
public boolean isSync() {
return context.getBackend().isSync();
}
public void setSync(boolean sync) {
context.getBackend().setSync(sync);
context.getPreferences().putBoolean("sync", sync);
}
@Override
public void deviceAdded(Device device) {
addDevice(device);
}
@Override
public void deviceRemoved(Device device) {
removeDevice(device);
}
protected void removeDevice(Device device) {
synchronized (acquisitions) {
Stack<EffectAcquisitionImpl> acq = acquisitions.get(device);
while (acq != null && !acq.isEmpty()) {
try {
EffectAcquisitionImpl pop = acq.pop();
pop.close();
} catch (Exception e) {
LOG.log(Level.ERROR, "Failed to close effect acquisition.", e);
}
}
acquisitions.remove(device);
}
}
public void addDevice(Device dev) {
synchronized (acquisitions) {
if (LOG.isLoggable(Level.DEBUG))
LOG.log(Level.DEBUG, String.format("Adding device %s to effect manager.", dev.getName()));
/* Acquire an effects controller for this device */
EffectAcquisition acq = acquire(dev);
EffectHandler<?, ?> deviceEffect = acq.getEffect(dev);
boolean activated = false;
if (deviceEffect != null && !deviceEffect.isRegions()) {
/* Always activates at device level */
acq.activate(dev, deviceEffect);
activated = true;
} else {
/* No effect configured for device as a whole, check the regions */
for (Region r : dev.getRegions()) {
EffectHandler<?, ?> regionEffect = acq.getEffect(r);
if (regionEffect != null && regionEffect.isRegions()) {
try {
acq.activate(r, regionEffect);
activated = true;
} catch (UnsupportedOperationException uoe) {
if (LOG.isLoggable(Level.DEBUG))
LOG.log(Level.WARNING, "Failed to activate effect.", uoe);
}
}
}
}
/* Now try at device level */
if (!activated && deviceEffect != null) {
acq.activate(dev, deviceEffect);
activated = true;
}
if (!activated) {
/* Get the first effect and activate on whole device */
Set<EffectHandler<?, ?>> effects = getEffects(dev);
Iterator<EffectHandler<?, ?>> it = effects.iterator();
while (it.hasNext()) {
EffectHandler<?, ?> fx = it.next();
if (dev.getSupportedEffects().contains(fx.getBackendEffectClass())) {
acq.activate(dev, fx);
break;
}
}
}
}
}
@Override
public void close() throws IOException {
synchronized (acquisitions) {
while (!acquisitions.isEmpty()) {
Device device = acquisitions.keySet().iterator().next();
if (context.getConfiguration().isTurnOffOnExit()) {
device.setEffect(new Off());
}
removeDevice(device);
}
}
}
}
| 19,266 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
OnEffectHandler.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/effects/OnEffectHandler.java | package uk.co.bithatch.snake.ui.effects;
import uk.co.bithatch.snake.lib.Lit;
import uk.co.bithatch.snake.lib.effects.On;
import uk.co.bithatch.snake.ui.AbstractBackendEffectController;
public class OnEffectHandler extends AbstractBackendEffectHandler<On, AbstractBackendEffectController<On, ?>> {
public OnEffectHandler() {
super(On.class, null);
}
@Override
protected void onStore(Lit component, AbstractBackendEffectController<On, ?> controller) throws Exception {
}
}
| 482 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
StarlightEffectHandler.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/effects/StarlightEffectHandler.java | package uk.co.bithatch.snake.ui.effects;
import java.util.prefs.Preferences;
import uk.co.bithatch.snake.lib.Colors;
import uk.co.bithatch.snake.lib.Lit;
import uk.co.bithatch.snake.lib.effects.Starlight;
import uk.co.bithatch.snake.lib.effects.Starlight.Mode;
import uk.co.bithatch.snake.ui.SchedulerManager.Queue;
import uk.co.bithatch.snake.ui.StarlightOptions;
public class StarlightEffectHandler extends AbstractBackendEffectHandler<Starlight, StarlightOptions> {
public StarlightEffectHandler() {
super(Starlight.class, StarlightOptions.class);
}
@Override
protected void onLoad(Preferences prefs, Starlight effect) {
effect.setMode(Mode.valueOf(prefs.get("mode", Mode.RANDOM.name())));
effect.setColor(Colors.fromHex(prefs.get("color", "#00ff00")));
effect.setColor1(Colors.fromHex(prefs.get("color2", "#00ff00")));
effect.setColor2(Colors.fromHex(prefs.get("color1", "#0000ff")));
effect.setSpeed(prefs.getInt("speed", 100));
}
@Override
protected void onSave(Preferences prefs, Starlight effect) {
prefs.put("mode", effect.getMode().name());
prefs.put("color", Colors.toHex(effect.getColor()));
prefs.put("color1", Colors.toHex(effect.getColor1()));
prefs.put("color2", Colors.toHex(effect.getColor2()));
prefs.putInt("speed", effect.getSpeed());
}
@Override
protected void onStore(Lit component, StarlightOptions controller) throws Exception {
Starlight starlight = (Starlight) controller.getEffect().clone();
starlight.setMode(controller.getMode());
starlight.setColor(controller.getColor());
starlight.setColor1(controller.getColor1());
starlight.setColor2(controller.getColor2());
starlight.setSpeed(controller.getSpeed());
getContext().getSchedulerManager().get(Queue.DEVICE_IO).execute(() -> component.setEffect(starlight));
save(component, starlight);
}
}
| 1,830 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
WaveEffectHandler.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/effects/WaveEffectHandler.java | package uk.co.bithatch.snake.ui.effects;
import java.util.prefs.Preferences;
import uk.co.bithatch.snake.lib.Lit;
import uk.co.bithatch.snake.lib.effects.Wave;
import uk.co.bithatch.snake.lib.effects.Wave.Direction;
import uk.co.bithatch.snake.ui.SchedulerManager.Queue;
import uk.co.bithatch.snake.ui.WaveOptions;
public class WaveEffectHandler extends AbstractBackendEffectHandler<Wave, WaveOptions> {
public WaveEffectHandler() {
super(Wave.class, WaveOptions.class);
}
@Override
protected void onLoad(Preferences prefs, Wave effect) {
effect.setDirection(Direction.valueOf(prefs.get("direction", Direction.FORWARD.name())));
}
@Override
protected void onSave(Preferences prefs, Wave effect) {
prefs.put("direction", effect.getDirection().name());
}
@Override
protected void onStore(Lit component, WaveOptions controller) throws Exception {
Wave wave = (Wave) controller.getEffect().clone();
Direction dir = controller.getDirection();
wave.setDirection(dir);
getContext().getSchedulerManager().get(Queue.DEVICE_IO).execute(() -> component.setEffect(wave));
save(component, wave);
}
}
| 1,122 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
BlobbyAudioEffectMode.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/effects/BlobbyAudioEffectMode.java | package uk.co.bithatch.snake.ui.effects;
import uk.co.bithatch.jdraw.RGBCanvas;
public class BlobbyAudioEffectMode implements AudioEffectMode {
private RGBCanvas canvas;
private int[] col1;
private int[] col2;
private AudioEffectHandler handler;
@Override
public Boolean isNeedsFFT() {
return true;
}
public void frame(double[] audio) {
int width = canvas.getWidth();
int height = canvas.getHeight();
int l = audio.length;
canvas.clear();
float step = (float) 1 / (float) width;
canvas.setColour(col2);
for (float i = 0; i < 1; i += step) {
int index = (int) (i * (float) l);
double amp = audio[index];
int barHeight = (int) Math.round(amp * ((float) width / 2.0));
if (barHeight > 0) {
int arcs = (int) Math.round(Math.max(1, (float) barHeight));
for (int j = 0; j < arcs; j++) {
canvas.drawArc(0, 1, (int) (1 + j),
Math.round(Math.toDegrees((Math.PI * 2 / height) * (i / (l / height)))),
Math.round(Math.toDegrees((Math.PI * 2 / width) * (i / (l / width) + 1) - .05)));
}
}
if (i == 0)
canvas.setColour(col1);
}
}
@Override
public void init(RGBCanvas canvas, AudioEffectHandler handler) {
this.handler = handler;
this.canvas = canvas;
update();
}
@Override
public void update() {
col1 = handler.getColor1();
col2 = handler.getColor2();
}
} | 1,349 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
AbstractBackendEffectHandler.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/effects/AbstractBackendEffectHandler.java | package uk.co.bithatch.snake.ui.effects;
import uk.co.bithatch.snake.lib.Lit;
import uk.co.bithatch.snake.lib.effects.Effect;
import uk.co.bithatch.snake.ui.AbstractBackendEffectController;
import uk.co.bithatch.snake.ui.SchedulerManager.Queue;
public abstract class AbstractBackendEffectHandler<E extends Effect, O extends AbstractBackendEffectController<E, ?>>
extends AbstractPersistentEffectHandler<E, O> {
protected AbstractBackendEffectHandler(Class<E> clazz, Class<O> controllerClass) {
super(clazz, controllerClass);
}
public Class<E> getBackendEffectClass() {
return getEffectClass();
}
@Override
protected final E onActivate(Lit component) {
E effect = (E) component.createEffect(getEffectClass());
/* Load the configuration for this effect */
onLoad(getEffectPreferences(component), effect);
getContext().getSchedulerManager().get(Queue.DEVICE_IO).execute(() -> component.setEffect(effect));
return effect;
}
}
| 954 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
AudioEffectMode.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/effects/AudioEffectMode.java | package uk.co.bithatch.snake.ui.effects;
import uk.co.bithatch.jdraw.RGBCanvas;
public interface AudioEffectMode {
void init(RGBCanvas canvas, AudioEffectHandler handler);
Boolean isNeedsFFT();
void frame(double[] frame);
void update();
} | 248 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
PulsateEffectHandler.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/effects/PulsateEffectHandler.java | package uk.co.bithatch.snake.ui.effects;
import uk.co.bithatch.snake.lib.Lit;
import uk.co.bithatch.snake.lib.effects.Pulsate;
import uk.co.bithatch.snake.ui.AbstractBackendEffectController;
public class PulsateEffectHandler
extends AbstractBackendEffectHandler<Pulsate, AbstractBackendEffectController<Pulsate, ?>> {
public PulsateEffectHandler() {
super(Pulsate.class, null);
}
@Override
protected void onStore(Lit component, AbstractBackendEffectController<Pulsate, ?> controller) throws Exception {
}
}
| 520 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
SpectrumEffectHandler.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/effects/SpectrumEffectHandler.java | package uk.co.bithatch.snake.ui.effects;
import uk.co.bithatch.snake.lib.Lit;
import uk.co.bithatch.snake.lib.effects.Spectrum;
import uk.co.bithatch.snake.ui.AbstractBackendEffectController;
public class SpectrumEffectHandler
extends AbstractBackendEffectHandler<Spectrum, AbstractBackendEffectController<Spectrum, ?>> {
public SpectrumEffectHandler() {
super(Spectrum.class, null);
}
@Override
protected void onStore(Lit component, AbstractBackendEffectController<Spectrum, ?> controller) throws Exception {
}
}
| 528 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
AbstractPersistentEffectHandler.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/effects/AbstractPersistentEffectHandler.java | package uk.co.bithatch.snake.ui.effects;
import java.net.URL;
import java.util.prefs.Preferences;
import uk.co.bithatch.snake.lib.Lit;
import uk.co.bithatch.snake.ui.AbstractEffectController;
public abstract class AbstractPersistentEffectHandler<E, O extends AbstractEffectController<E, ?>>
extends AbstractEffectHandler<E, O> {
private Class<E> clazz;
private Class<O> controllerClass;
protected AbstractPersistentEffectHandler(Class<E> clazz, Class<O> controllerClass) {
this.clazz = clazz;
this.controllerClass = controllerClass;
}
@Override
public URL getEffectImage(int size) {
return getContext().getConfiguration().getTheme().getEffectImage(size, clazz);
}
protected Class<E> getEffectClass() {
return clazz;
}
@Override
public Class<O> getOptionsController() {
return controllerClass;
}
@Override
public boolean isSupported(Lit component) {
return component.getSupportedEffects().contains(clazz);
}
@Override
public String getDisplayName() {
return bundle.getString("effect." + clazz.getSimpleName());
}
public void save(Lit component, E effect) {
onSave(getEffectPreferences(component), effect);
}
public void load(Lit component, E effect) {
onLoad(getEffectPreferences(component), effect);
}
protected void onLoad(Preferences prefs, E effect) {
}
protected void onSave(Preferences prefs, E effect) {
}
}
| 1,376 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
Tray.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/tray/Tray.java | package uk.co.bithatch.snake.ui.tray;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.RenderingHints;
//import java.awt.AlphaComposite;
//import java.awt.Color;
//import java.awt.Font;
//import java.awt.Graphics2D;
//import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.System.Logger.Level;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import javax.swing.JMenu;
import javax.swing.JSeparator;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import org.kordamp.ikonli.fontawesome.FontAwesome;
import org.kordamp.ikonli.fontawesome.FontAwesomeIkonHandler;
import dorkbox.systemTray.Checkbox;
import dorkbox.systemTray.Entry;
import dorkbox.systemTray.Menu;
import dorkbox.systemTray.MenuItem;
import dorkbox.systemTray.Separator;
import dorkbox.systemTray.SystemTray;
import dorkbox.systemTray.util.SystemTrayFixes;
import dorkbox.updates.Updates;
import javafx.application.Platform;
import uk.co.bithatch.macrolib.MacroSystem.RecordingListener;
import uk.co.bithatch.macrolib.RecordingSession;
import uk.co.bithatch.macrolib.RecordingState;
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.Device.Listener;
import uk.co.bithatch.snake.lib.Grouping;
import uk.co.bithatch.snake.lib.Item;
import uk.co.bithatch.snake.lib.Lit;
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.ui.App;
import uk.co.bithatch.snake.ui.BatteryControl;
import uk.co.bithatch.snake.ui.Configuration;
import uk.co.bithatch.snake.ui.Configuration.TrayIcon;
import uk.co.bithatch.snake.ui.DeviceDetails;
import uk.co.bithatch.snake.ui.EffectHandler;
import uk.co.bithatch.snake.ui.Macros;
import uk.co.bithatch.snake.ui.SchedulerManager.Queue;
import uk.co.bithatch.snake.ui.effects.EffectAcquisition;
import uk.co.bithatch.snake.widgets.Direction;
public class Tray implements AutoCloseable, BackendListener, Listener, PreferenceChangeListener, RecordingListener {
final static System.Logger LOG = System.getLogger(Tray.class.getName());
final static ResourceBundle bundle = ResourceBundle.getBundle(Tray.class.getName());
private Configuration cfg;
private App context;
// private Font font;
private SystemTray systemTray;
private List<Entry> menuEntries = new ArrayList<>();
private Timer timer;
private Font font;
public Tray(App context) throws Exception {
this.context = context;
// font = Font.createFont(Font.TRUETYPE_FONT, App.class.getResourceAsStream("fontawesome-webfont.ttf"));
cfg = context.getConfiguration();
cfg.getNode().addPreferenceChangeListener(this);
context.getMacroManager().getMacroSystem().addRecordingListener(this);
context.getBackend().addListener(this);
for (Device dev : context.getBackend().getDevices()) {
dev.addListener(this);
}
SwingUtilities.invokeLater(() -> {
Updates.INSTANCE.setENABLE(cfg.isTelemetry());
adjustTray();
});
}
@Override
public void close() throws Exception {
context.getMacroManager().getMacroSystem().removeRecordingListener(this);
cfg.getNode().removePreferenceChangeListener(this);
if (systemTray != null) {
systemTray.shutdown();
systemTray = null;
}
}
Menu addDevice(Device device, Menu toMenu) throws IOException {
var img = context.getDefaultImage(device.getType(), context.getCache().getCachedImage(device.getImage()));
Menu menu = null;
if (img.startsWith("http:") || img.startsWith("https:")) {
var url = new URL(img);
var path = url.getPath();
var idx = path.lastIndexOf('/');
if (idx != -1) {
path = path.substring(idx + 1);
}
var tf = File.createTempFile("snake", path);
tf.deleteOnExit();
try (var fos = new FileOutputStream(tf)) {
try (InputStream is = url.openStream()) {
is.transferTo(fos);
img = tf.getAbsolutePath();
}
} catch(IOException ioe) {
try(InputStream in = SystemTrayFixes.class.getResource("error_32.png").openStream()) {
menu = new Menu(device.getName(), in);
}
if(LOG.isLoggable(Level.DEBUG))
LOG.log(Level.WARNING, "Failed to load device image.", ioe);
else
LOG.log(Level.WARNING, "Failed to load device image. " + ioe.getMessage() );
}
} else if (img.startsWith("file:")) {
img = img.substring(5);
}
if(toMenu == null) {
if(menu == null)
menu = new Menu(device.getName(), img);
}
else
menu = toMenu;
/* Open */
var openDev = new MenuItem(bundle.getString("open"), (e) -> Platform.runLater(() -> {
try {
context.open();
context.openDevice(device);
} catch (Exception ex) {
}
}));
menu.add(openDev);
menuEntries.add(openDev);
if (device.getCapabilities().contains(Capability.MACROS)) {
var macros = new MenuItem(bundle.getString("macros"), createAwesomeIcon(FontAwesome.PLAY_CIRCLE, 32),
(e) -> {
Platform.runLater(() -> {
context.open();
context.push(Macros.class, Direction.FROM_BOTTOM).setDevice(device);
});
});
menu.add(macros);
menuEntries.add(macros);
}
if (device.getCapabilities().contains(Capability.BRIGHTNESS)) {
brightnessMenu(menu, device);
}
if (device.getCapabilities().contains(Capability.DPI)) {
dpiMenu(menu, device);
}
if (device.getCapabilities().contains(Capability.POLL_RATE)) {
pollRateMenu(menu, device);
}
if (device.getCapabilities().contains(Capability.GAME_MODE)) {
gameMode(menu, device);
}
menu.add(new JSeparator());
if (!device.getSupportedEffects().isEmpty()) {
addEffectsMenu(device, menu, device, toMenu != null);
menu.add(new JSeparator());
}
boolean sep;
for (var r : device.getRegions()) {
var mi = new Menu(bundle.getString("region." + r.getName().name()));
mi.setImage(context.getConfiguration().getTheme().getRegionImage(24, r.getName()));
menu.add(mi);
if (toMenu != null)
menuEntries.add(mi);
sep = false;
if (r.getCapabilities().contains(Capability.BRIGHTNESS_PER_REGION)) {
brightnessMenu(mi, r);
sep = true;
}
if (r.getCapabilities().contains(Capability.EFFECT_PER_REGION)) {
if (sep) {
mi.add(new JSeparator());
}
addEffectsMenu(r, mi, device, toMenu != null);
}
}
return menu;
}
void addEffectsMenu(Lit lit, Menu menu, Device device, boolean addToRoot) {
EffectHandler<?, ?> configurable = null;
EffectAcquisition acq = context.getEffectManager().getRootAcquisition(Lit.getDevice(lit));
if (acq == null)
return;
EffectHandler<?, ?> selected = acq.getEffect(lit);
for (EffectHandler<?, ?> fx : context.getEffectManager().getEffects(lit)) {
var mi = new MenuItem(fx.getDisplayName(), (e) -> {
context.getSchedulerManager().get(Queue.DEVICE_IO).execute(() -> acq.activate(lit, fx));
});
mi.setImage(fx.getEffectImage(24));
menu.add(mi);
if (fx.hasOptions() && fx.equals(selected)) {
configurable = fx;
}
if (addToRoot)
menuEntries.add(mi);
}
EffectHandler<?, ?> fConfigurable = configurable;
if (configurable != null) {
var mi = new MenuItem(bundle.getString("effectOptions"), createAwesomeIcon(FontAwesome.GEAR, 32), (e) -> {
Platform.runLater(() -> {
context.open();
var dev = context.push(DeviceDetails.class, Direction.FROM_RIGHT);
dev.setDevice(device);
dev.configure(lit, fConfigurable);
});
});
menu.add(mi);
if (addToRoot)
menuEntries.add(mi);
}
}
BufferedImage createAwesomeIcon(FontAwesome string, int sz) {
return createAwesomeIcon(string, sz, 100);
}
BufferedImage createAwesomeIcon(FontAwesome string, int sz, int opac) {
return createAwesomeIcon(string, sz, opac, null, 0);
}
BufferedImage createAwesomeIcon(FontAwesome fontAwesome, int sz, int opac, Color col, double rot) {
var bim = new BufferedImage(sz, sz, BufferedImage.TYPE_INT_ARGB);
var graphics = (Graphics2D) bim.getGraphics();
graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
var szf = (int) ((float) sz * 0.75f);
String str = Character.toString(fontAwesome.getCode());
FontAwesomeIkonHandler handler = new FontAwesomeIkonHandler();
if (font == null) {
try {
InputStream stream = handler.getFontResourceAsStream();
font = Font.createFont(Font.TRUETYPE_FONT, stream);
GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(font);
stream.close();
handler.setFont(font);
} catch (FontFormatException | IOException ffe) {
throw new IllegalStateException(ffe);
}
}
var fnt = font.deriveFont((float) szf);
graphics.setFont(fnt);
if (opac != 100) {
graphics.setComposite(makeComposite((float) opac / 100.0f));
}
var icon = cfg.getTrayIcon();
if (col == null) {
switch (icon) {
case LIGHT:
graphics.setColor(Color.WHITE);
break;
case DARK:
graphics.setColor(Color.BLACK);
break;
default:
// TODO
break;
}
} else {
graphics.setColor(col);
}
graphics.translate(sz / 2, sz / 2);
graphics.rotate(Math.toRadians(rot));
graphics.translate(-(graphics.getFontMetrics().stringWidth(str) / 2f),
(graphics.getFontMetrics().getHeight() / 2f));
graphics.drawString(str, 0, 0);
return bim;
}
AlphaComposite makeComposite(float alpha) {
int type = AlphaComposite.SRC_OVER;
return (AlphaComposite.getInstance(type, alpha));
}
void adjustTray() {
var icon = cfg.getTrayIcon();
if (systemTray == null && icon != TrayIcon.OFF) {
systemTray = SystemTray.get();
if (systemTray == null) {
throw new RuntimeException("Unable to load SystemTray!");
}
setImage();
systemTray.setStatus(bundle.getString("title"));
Menu menu = systemTray.getMenu();
if (menu == null) {
systemTray.setMenu(new JMenu(bundle.getString("title")));
}
rebuildMenu();
} else if (systemTray != null && icon == TrayIcon.OFF) {
systemTray.setEnabled(false);
} else if (systemTray != null) {
systemTray.setEnabled(true);
setImage();
rebuildMenu();
}
}
private void rebuildMenu() {
clearMenus();
if (systemTray != null) {
var menu = systemTray.getMenu();
try {
boolean devices = false;
List<Device> devs = context.getBackend().getDevices();
var backend = context.getBackend();
var globals = false;
/* Record */
if (context.getMacroManager().getMacroSystem().isRecording()) {
var recordDev = new MenuItem(bundle.getString("stopRecording"), (e) -> Platform.runLater(() -> {
context.getMacroManager().getMacroSystem().stopRecording();
}));
menu.add(recordDev);
menuEntries.add(recordDev);
if (context.getMacroManager().getMacroSystem().getRecordingSession()
.getRecordingState() == RecordingState.PAUSED) {
var unpauseDev = new MenuItem(bundle.getString("unpauseRecording"),
(e) -> Platform.runLater(() -> {
context.getMacroManager().getMacroSystem().togglePauseRecording();
}));
menu.add(unpauseDev);
menuEntries.add(unpauseDev);
} else {
var pauseDev = new MenuItem(bundle.getString("pauseRecording"), (e) -> Platform.runLater(() -> {
context.getMacroManager().getMacroSystem().togglePauseRecording();
}));
menu.add(pauseDev);
menuEntries.add(pauseDev);
}
} else {
var recordDev = new MenuItem(bundle.getString("record"), (e) -> Platform.runLater(() -> {
context.getMacroManager().getMacroSystem().startRecording();
}));
menu.add(recordDev);
menuEntries.add(recordDev);
}
if (devs.size() == 1) {
addDevice(devs.get(0), menu);
devices = true;
} else {
var mi = new MenuItem(bundle.getString("open"), (e) -> context.open());
menuEntries.add(mi);
menu.add(mi);
addSeparator(menu);
if (backend.getCapabilities().contains(Capability.BRIGHTNESS)) {
brightnessMenu(menu, backend);
globals = true;
}
if (backend.getCapabilities().contains(Capability.GAME_MODE)) {
gameMode(menu, backend);
globals = true;
}
if (globals)
addSeparator(menu);
for (Device dev : devs) {
var devmenu = addDevice(dev, null);
systemTray.getMenu().add(devmenu);
menuEntries.add(devmenu);
devices = true;
}
}
if (devices)
addSeparator(menu);
} catch (Exception e) {
// TODO add error item / tooltip?
systemTray.setTooltip("Erro!");
e.printStackTrace();
}
var quit = new MenuItem(bundle.getString("quit"), (e) -> context.close(true));
menuEntries.add(quit);
menu.add(quit).setShortcut('q');
}
}
private void addSeparator(Menu menu) {
Separator sep = new Separator();
menu.add(sep);
menuEntries.add(sep);
}
private void clearMenus() {
if (systemTray != null) {
var menu = systemTray.getMenu();
for (Entry dev : menuEntries) {
menu.remove(dev);
}
}
menuEntries.clear();
}
private void gameMode(Menu menu, Grouping backend) {
Checkbox checkbox = new Checkbox();
checkbox.setCallback((e) -> backend.setGameMode(checkbox.getChecked()));
checkbox.setEnabled(true);
checkbox.setChecked(backend.isGameMode());
checkbox.setShortcut('g');
checkbox.setText(bundle.getString("gameMode"));
menu.add(checkbox);
menuEntries.add(checkbox);
}
private void brightnessMenu(Menu menu, Item backend) {
var bri = new Menu(bundle.getString("brightness"), createAwesomeIcon(FontAwesome.SUN_O, 32));
menu.add(bri);
for (String b : new String[] { "off", "10", "20", "50", "75", "100" }) {
bri.add(new MenuItem(bundle.getString("brightness." + b),
createAwesomeIcon(b.equals("off") ? FontAwesome.TOGGLE_OFF : FontAwesome.SUN_O, 32,
b.equals("off") ? 25 : Integer.parseInt(b)),
(e) -> {
backend.setBrightness(b.equals("off") ? 0 : Short.parseShort(b));
}));
}
menuEntries.add(bri);
}
private void dpiMenu(Menu menu, Device device) {
var dpiMenu = new Menu(bundle.getString("dpi"), createAwesomeIcon(FontAwesome.MOUSE_POINTER, 32));
menu.add(dpiMenu);
short[] dpis = new short[] { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1500, 2000, 3000, 4000, 8000,
16000, 32000 };
for (short dpi : dpis) {
if (dpi <= device.getMaxDPI()) {
dpiMenu.add(new MenuItem(MessageFormat.format(bundle.getString("deviceDpi"), dpi), (e) -> {
device.setDPI(dpi, dpi);
}));
}
}
menuEntries.add(dpiMenu);
}
private void pollRateMenu(Menu menu, Device device) {
var pollRateMenu = new Menu(bundle.getString("pollRate"), createAwesomeIcon(FontAwesome.SIGNAL, 32));
menu.add(pollRateMenu);
int[] pollRates = new int[] { 125, 500, 1000 };
for (int pollRate : pollRates) {
pollRateMenu.add(new MenuItem(MessageFormat.format(bundle.getString("devicePollRate"), pollRate), (e) -> {
device.setPollRate(pollRate);
}));
}
menuEntries.add(pollRateMenu);
}
private void setImage() {
var icon = cfg.getTrayIcon();
boolean recording = context.getMacroManager().getMacroSystem().isRecording();
if (!recording && context.getBackend().getCapabilities().contains(Capability.BATTERY) && cfg.isShowBattery()
&& (!cfg.isWhenLow() || (cfg.isWhenLow()
&& context.getBackend().getBattery() <= context.getBackend().getLowBatteryThreshold()))) {
Color col = null;
String status = BatteryControl.getBatteryStyle(context.getBackend().getLowBatteryThreshold(),
context.getBackend().getBattery());
if ("danger".equals(status))
col = Color.RED;
else if ("warning".equals(status))
col = Color.ORANGE;
systemTray.setImage(createAwesomeIcon(BatteryControl.getBatteryIcon(context.getBackend().getBattery()), 32,
100, col, 270));
} else {
String name = "tray";
if (recording)
name = "tray-recording";
switch (icon) {
case LIGHT:
systemTray.setImage(App.class.getResource("icons/" + name + "-light64.png"));
break;
case DARK:
systemTray.setImage(App.class.getResource("icons/" + name + "-dark64.png"));
break;
case AUTO:
// TODO
case COLOR:
default:
systemTray.setImage(context.getConfiguration().getTheme().getResource("icons/" + name + "64.png"));
break;
}
}
}
@Override
public void deviceAdded(Device device) {
device.addListener(this);
SwingUtilities.invokeLater(() -> rebuildMenu());
}
@Override
public void deviceRemoved(Device device) {
device.removeListener(this);
SwingUtilities.invokeLater(() -> rebuildMenu());
}
@Override
public void changed(Device device, Region region) {
SwingUtilities.invokeLater(() -> {
if (timer == null) {
timer = new Timer(500, (e) -> {
rebuildMenu();
});
timer.setRepeats(false);
}
timer.restart();
});
}
@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) {
}
@Override
public void preferenceChange(PreferenceChangeEvent evt) {
if (evt.getKey().equals(Configuration.PREF_THEME) || evt.getKey().equals(Configuration.PREF_TRAY_ICON)
|| evt.getKey().equals(Configuration.PREF_SHOW_BATTERY)
|| evt.getKey().equals(Configuration.PREF_WHEN_LOW)) {
SwingUtilities.invokeLater(() -> adjustTray());
}
else if (evt.getKey().equals(Configuration.PREF_THEME)) {
SwingUtilities.invokeLater(() -> Updates.INSTANCE.setENABLE(cfg.isTelemetry()));
}
}
@Override
public void recordingStateChange(RecordingSession session) {
SwingUtilities.invokeLater(() -> adjustTray());
}
@Override
public void eventRecorded() {
}
}
| 18,255 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
MatrixBacking.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/drawing/MatrixBacking.java | package uk.co.bithatch.snake.ui.drawing;
import uk.co.bithatch.jdraw.Backing;
public class MatrixBacking implements Backing {
private int[][][] matrix;
private boolean rot;
private int width;
private int height;
public MatrixBacking(int width, int height, int[][][] matrix) {
this.matrix = matrix;
if (height < 3) {
rot = true;
this.height = width;
this.width = height;
} else {
this.width = width;
this.height = height;
}
}
@Override
public void plot(int x, int y, int[] rgb) {
if (rot) {
matrix[x][y][0] = rgb[0];
matrix[x][y][1] = rgb[1];
matrix[x][y][2] = rgb[02];
} else {
matrix[y][x][0] = rgb[0];
matrix[y][x][1] = rgb[1];
matrix[y][x][2] = rgb[02];
}
}
@Override
public int getWidth() {
return width;
}
@Override
public int getHeight() {
return height;
}
}
| 839 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
JavaFXBacking.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/drawing/JavaFXBacking.java | package uk.co.bithatch.snake.ui.drawing;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import uk.co.bithatch.jdraw.Backing;
import uk.co.bithatch.jdraw.RGBCanvas;
public class JavaFXBacking implements Backing {
private int height;
private int width;
private int zoom;
private GraphicsContext ctx;
private Canvas canvas;
private int[] rgb;
private boolean rot;
public JavaFXBacking(int width, int height) {
this.width = width;
this.height = height;
if (height > width) {
if (height > 20)
zoom = 20;
else
zoom = 40;
canvas = new Canvas(height * zoom, width * zoom);
rot = true;
} else {
if (width > 20)
zoom = 20;
else
zoom = 40;
canvas = new Canvas(width * zoom, height * zoom);
}
ctx = canvas.getGraphicsContext2D();
}
public Canvas getCanvas() {
return canvas;
}
@Override
public int getWidth() {
return width;
}
@Override
public int getHeight() {
return height;
}
@Override
public void plot(int x, int y, int[] rgb) {
if (this.rgb == null || rgb != this.rgb) {
this.rgb = rgb;
ctx.setFill(new Color((float) rgb[0] / 255.0, (float) rgb[1] / 255.0, (float) rgb[2] / 255.0, 1));
}
if (rot) {
if (rgb.equals(RGBCanvas.BLACK)) {
ctx.clearRect(y * zoom, x * zoom, zoom, zoom);
} else
ctx.fillRect(y * zoom, x * zoom, zoom, zoom);
} else {
if (rgb.equals(RGBCanvas.BLACK)) {
ctx.clearRect(x * zoom, y * zoom, zoom, zoom);
} else
ctx.fillRect(x * zoom, y * zoom, zoom, zoom);
}
}
}
| 1,570 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
ListWrapper.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/util/ListWrapper.java | package uk.co.bithatch.snake.ui.util;
import java.util.ArrayList;
import java.util.List;
import javafx.collections.ModifiableObservableListBase;
public abstract class ListWrapper<I, O> extends ModifiableObservableListBase<O> {
private List<I> list;
public ListWrapper() {
this(new ArrayList<>());
}
public ListWrapper(List<I> list) {
this.list = list;
}
public List<I> getList() {
return list;
}
public void setList(List<I> list) {
this.list = list;
}
@Override
public O get(int index) {
return convertToWrapped(list.get(index));
}
@Override
public int size() {
return list.size();
}
@Override
protected void doAdd(int index, O element) {
list.add(index, convertToNative(element));
}
@Override
protected O doSet(int index, O element) {
return convertToWrapped(list.set(index, convertToNative(element)));
}
@Override
protected O doRemove(int index) {
return convertToWrapped(list.remove(index));
}
O convertToWrapped(I in) {
return in == null ? null : doConvertToWrapped(in);
}
I convertToNative(O in) {
return in == null ? null : doConvertToNative(in);
}
protected abstract O doConvertToWrapped(I in);
protected I doConvertToNative(O in) {
throw new UnsupportedOperationException();
}
} | 1,257 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
Visitor.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/util/Visitor.java | package uk.co.bithatch.snake.ui.util;
public interface Visitor<O> {
void visit(O object);
}
| 95 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
Time.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/util/Time.java | package uk.co.bithatch.snake.ui.util;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.util.Duration;
public class Time {
public static class Timer {
private Timeline timer;
private Duration duration;
private EventHandler<ActionEvent> task;
public Timer(Duration duration, EventHandler<ActionEvent> task) {
this.duration = duration;
this.task = task;
}
public synchronized void reset() {
if (timer == null) {
timer = new Timeline(new KeyFrame(duration, task));
}
timer.playFromStart();
}
public synchronized void cancel() {
if (timer != null) {
timer.stop();
timer = null;
}
}
}
public static String formatTime(long millis) {
java.time.Duration diff = java.time.Duration.ofMillis(millis);
return String.format("%d:%02d:%02d", diff.toHours(), diff.toMinutesPart(), diff.toSecondsPart());
}
}
| 958 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
Language.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/util/Language.java | package uk.co.bithatch.snake.ui.util;
public class Language {
public static boolean[] toBinaryArray(int value) {
return toBinaryArray(value, -1);
}
public static boolean[] toBinaryArray(int value, int length) {
String bin = Integer.toBinaryString(value);
if (length != -1) {
while (bin.length() < length)
bin = "0" + bin;
}
boolean[] arr = new boolean[length == -1 ? bin.length() : length];
for (int i = 0; i < arr.length; i++) {
arr[i] = bin.charAt(i) == '1';
}
return arr;
}
}
| 512 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
PreferenceBinding.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/util/PreferenceBinding.java | package uk.co.bithatch.snake.ui.util;
import java.io.Closeable;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import java.util.prefs.Preferences;
import javafx.beans.property.Property;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
public class PreferenceBinding implements Closeable, PreferenceChangeListener {
abstract class Binding<T> implements ChangeListener<T> {
Property<T> property;
String key;
public Binding(Property<T> property, String key) {
super();
this.property = property;
this.key = key;
property.addListener(this);
}
public void unbind() {
property.removeListener(this);
}
abstract void changed(String newValue);
}
private Preferences node;
private Map<String, Binding<?>> map = new HashMap<>();
public PreferenceBinding(Preferences node) {
this.node = node;
node.addPreferenceChangeListener(this);
}
public void bind(String key, Property<Boolean> property, boolean defaultValue) {
boolean value = node.getBoolean(key, defaultValue);
property.setValue(value);
var binding = new Binding<Boolean>(property, key) {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
node.putBoolean(key, newValue);
}
@Override
void changed(String newValue) {
property.setValue(Boolean.valueOf(newValue));
}
};
map.put(key, binding);
}
@Override
public void close() throws IOException {
for (Iterator<Map.Entry<String, Binding<?>>> it = map.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, Binding<?>> binding = it.next();
binding.getValue().unbind();
it.remove();
}
node.removePreferenceChangeListener(this);
}
@Override
public void preferenceChange(PreferenceChangeEvent evt) {
Binding<?> b = map.get(evt.getKey());
b.changed(evt.getNewValue());
}
}
| 2,027 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
Maths.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/util/Maths.java | package uk.co.bithatch.snake.ui.util;
public class Maths {
public static double distance(double startX, double startY, double endX, double endY) {
return Math.sqrt(Math.pow(endX - startX, 2) + Math.pow(endY - startY, 2));
}
}
| 232 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
BasicList.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/util/BasicList.java | package uk.co.bithatch.snake.ui.util;
import java.util.ArrayList;
import java.util.List;
import javafx.collections.ModifiableObservableListBase;
public class BasicList<J> extends ModifiableObservableListBase<J> {
private List<J> list;
public BasicList() {
this(new ArrayList<>());
}
public BasicList(List<J> list) {
this.list = list;
}
public List<J> getList() {
return list;
}
public void setList(List<J> list) {
this.list = list;
}
@Override
public J get(int index) {
return list.get(index);
}
@Override
public int size() {
return list.size();
}
@Override
protected void doAdd(int index, J element) {
list.add(index, element);
}
@Override
protected J doSet(int index, J element) {
return list.set(index, element);
}
@Override
protected J doRemove(int index) {
return list.remove(index);
}
} | 847 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
Prefs.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/util/Prefs.java | package uk.co.bithatch.snake.ui.util;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.prefs.Preferences;
public class Prefs {
public final static String PREF_DECORATED = "decorated";
public final static boolean PREF_DECORATED_DEFAULT = false;
public final static Set<String> addToStringSet(Preferences node, String key, String value) {
Set<String> set = new LinkedHashSet<>(getStringSet(node, key));
set.add(value);
setStringCollection(node, key, set);
return set;
}
public final static Set<String> removeFromStringSet(Preferences node, String key, String value) {
Set<String> set = new LinkedHashSet<>(getStringSet(node, key));
set.remove(value);
setStringCollection(node, key, set);
return set;
}
public final static Set<String> getStringSet(Preferences node, String key) {
return getStringSet(node, key, Collections.emptySet());
}
public final static Set<String> getStringSet(Preferences node, String key, Set<String> defaultValue) {
String val = node.get(key, "");
if (val.equals(""))
return defaultValue;
else
return new LinkedHashSet<>(Arrays.asList(val.split(",")));
}
public final static String[] getStringList(Preferences node, String key, String... defaultValue) {
String val = node.get(key, "");
if (val.equals(""))
return defaultValue;
else
return val.split(",");
}
public final static void setStringCollection(Preferences node, String key, Collection<String> values) {
node.put(key, String.join(",", values));
}
public final static void setStringList(Preferences node, String key, String... values) {
node.put(key, String.join(",", values));
}
}
| 1,742 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
Delta.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/util/Delta.java | package uk.co.bithatch.snake.ui.util;
public class Delta {
private double x, y;
public Delta() {
}
public Delta(double x, double y) {
super();
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public boolean isZero() {
return x == 0 && y == 0;
}
@Override
public String toString() {
return "Delta [x=" + x + ", y=" + y + "]";
}
} | 508 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
Filing.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/util/Filing.java | package uk.co.bithatch.snake.ui.util;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Filing {
public static void unzip(Path zip, Path destDir) throws IOException {
byte[] buffer = new byte[1024];
try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(zip))) {
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
Files.createDirectories(destDir);
Path newFile = newFile(destDir, zipEntry);
Files.createDirectories(destDir.getParent());
try (OutputStream fos = Files.newOutputStream(newFile)) {
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
}
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
}
}
public static Path newFile(Path destinationDir, ZipEntry zipEntry) throws IOException {
Path destFile = destinationDir.resolve(zipEntry.getName());
String destDirPath = destinationDir.toRealPath().toString();
Files.createDirectories(destFile.getParent());
String destFilePath = destFile.getParent().toRealPath().resolve(destFile.getFileName()).toString();
if (!destFilePath.startsWith(destDirPath + File.separator)) {
throw new IOException("Entry is outside of the target dir: " + zipEntry.getName());
}
return destFile;
}
/**
* Recursively deletes `item`, which may be a directory. Symbolic links will be
* deleted instead of their referents. Returns a boolean indicating whether
* `item` still exists. http://stackoverflow.com/questions/8666420
*
* @param item file to delete
* @return deleted OK
*/
public static boolean deleteRecursiveIfExists(File item) {
if (!item.exists())
return true;
if (!Files.isSymbolicLink(item.toPath()) && item.isDirectory()) {
File[] subitems = item.listFiles();
for (File subitem : subitems)
if (!deleteRecursiveIfExists(subitem))
return false;
}
return item.delete();
}
}
| 2,062 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
CompoundIterator.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/util/CompoundIterator.java | package uk.co.bithatch.snake.ui.util;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
public class CompoundIterator<I> implements Iterator<I> {
private List<Iterator<? extends I>> iterators = new LinkedList<>();
private Iterator<Iterator<? extends I>> iteratorsIterator;
private Iterator<? extends I> iterator;
private I element;
private I current;
public CompoundIterator() {
}
@SuppressWarnings("unchecked")
public CompoundIterator(Iterator<? extends I>... iterators) {
this.iterators.addAll(Arrays.asList(iterators));
}
public void addIterator(Iterator<? extends I> iterator) {
if (iteratorsIterator != null)
throw new IllegalStateException("Cannot add iterators after started iterating.");
iterators.add(iterator);
}
@Override
public void remove() {
if(current == null)
throw new IllegalStateException();
iterator.remove();
}
@Override
public boolean hasNext() {
checkNext();
return iterator != null;
}
private void checkNext() {
if (element == null) {
if (iteratorsIterator == null)
iteratorsIterator = iterators.iterator();
while (true) {
if (iterator == null)
if (iteratorsIterator.hasNext())
iterator = iteratorsIterator.next();
else
break;
if (iterator.hasNext()) {
element = iterator.next();
break;
} else
iterator = null;
}
}
}
@Override
public I next() {
checkNext();
if (element == null)
throw new NoSuchElementException();
try {
return element;
} finally {
current = element;
element = null;
}
}
}
| 1,652 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
Strings.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui/src/main/java/uk/co/bithatch/snake/ui/util/Strings.java | package uk.co.bithatch.snake.ui.util;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.List;
public class Strings {
public static String toSeparatedList(String separator, Iterable<? extends Object> values) {
StringBuilder b = new StringBuilder();
for (Object o : values) {
if (b.length() > 0)
b.append(separator);
b.append(String.valueOf(o));
}
return b.toString();
}
public static List<String> addIfNotAdded(List<String> target, String... source) {
for (String s : source) {
if (!target.contains(s))
target.add(s);
}
return target;
}
public static List<String> addIfNotAdded(List<String> target, List<String> source) {
for (String s : source) {
if (!target.contains(s))
target.add(s);
}
return target;
}
public static String toId(String name) {
return name.toLowerCase().replace(" ", "-").replace("_", "-").replaceAll("[^a-z0-9\\-]", "");
}
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);
}
}
public static boolean isBlank(String string) {
return string == null || string.length() == 0;
}
public static String[] toStringArray(String separatorRegex, String stringList) {
return isBlank(stringList) ? new String[0] : stringList.split(separatorRegex);
}
public static String defaultIfBlank(String str, String defaultValue) {
return isBlank(str) ? defaultValue : str;
}
public static String basename(String url) {
int idx = url.lastIndexOf("/");
if (idx == -1)
return null;
else
return url.substring(idx + 1);
}
public static String extension(String url) {
int idx = url.lastIndexOf(".");
if (idx == -1)
return null;
else
return url.substring(idx + 1);
}
public static String changeExtension(String path, String ext) {
int idx = path.lastIndexOf(".");
return idx == -1 ? path + "." + ext : path.substring(0, idx) + "." + ext;
}
public static String toName(String name) {
if (name == null || name.length() == 0)
return name;
// TODO bit weak
return (name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase()).replace('_', ' ');
}
}
| 2,430 | 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-linux/src/main/java/module-info.java | module uk.co.bithatch.snake.ui.linux {
requires transitive uk.co.bithatch.snake.ui;
provides uk.co.bithatch.snake.ui.PlatformService with uk.co.bithatch.snake.ui.linux.LinuxPlatformService;
} | 193 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
LinuxPlatformService.java | /FileExtraction/Java_unseen/bithatch_snake/snake-ui-linux/src/main/java/uk/co/bithatch/snake/ui/linux/LinuxPlatformService.java | package uk.co.bithatch.snake.ui.linux;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import uk.co.bithatch.snake.ui.App;
import uk.co.bithatch.snake.ui.PlatformService;
public class LinuxPlatformService implements PlatformService {
private static final String SNAKE_RAZER_DESKTOP = "snake-razer.desktop";
private static final String BETA_CHANNEL = System.getProperty("forker.betaChannel",
"http://www.bithatch.co.uk/repositories/snake/snapshot");
private static final String STABLE_CHANNEL = System.getProperty("forker.releaseChannel",
"http://www.bithatch.co.uk/repositories/snake/stable");
@Override
public String getAvailableVersion() {
return System.getProperty("forker.availableVersion", getInstalledVersion());
}
@Override
public String getInstalledVersion() {
return System.getProperty("forker.installedVersion", "Unknown");
}
@Override
public boolean isBetas() {
try {
Path appCfg = getAppCfg();
Path path = checkDir(appCfg).resolve("updates");
if (Files.exists(path))
return contains(path, "remote-manifest " + BETA_CHANNEL);
else {
path = checkDir(appCfg.toAbsolutePath().getParent()).resolve("app.cfg");
return Files.exists(path) && contains(path, "default-remote-manifest " + BETA_CHANNEL);
}
} catch (IOException ioe) {
return false;
}
}
@Override
public boolean isCheckForUpdates() {
try {
Path path = checkDir(getAppCfg()).resolve("updates");
return !Files.exists(path) || !contains(path, "update-on-exit") || contains(path, "update-on-exit 100");
} catch (IOException ioe) {
return false;
}
}
@Override
public boolean isStartOnLogin() {
File f = getAutostartFile();
if (!f.exists())
return false;
try (BufferedReader r = new BufferedReader(new FileReader(f))) {
String line;
while ((line = r.readLine()) != null) {
line = line.trim();
if (line.startsWith("X-GNOME-Autostart-enabled=")) {
return line.substring(26).equals("true");
}
}
} catch (IOException ioe) {
}
return false;
}
@Override
public boolean isUpdateableApp() {
return Files.exists(Paths.get("manifest.xml")) || isDev();
}
@Override
public boolean isUpdateAutomatically() {
try {
Path path = checkDir(getAppCfg()).resolve("updates");
return !Files.exists(path) || !contains(path, "update-on-exit") || contains(path, "update-on-exit 99");
} catch (IOException ioe) {
return false;
}
}
@Override
public boolean isUpdateAvailable() {
return "true".equals(System.getProperty("forker.updateAvailable"));
}
@Override
public boolean isUpdated() {
return "true".equals(System.getProperty("forker.updated"));
}
@Override
public void setBetas(boolean betas) {
reconfig(isCheckForUpdates(), isUpdateAutomatically(), betas);
}
@Override
public void setCheckForUpdates(boolean checkForUpdates) {
reconfig(checkForUpdates, isUpdateAutomatically(), isBetas());
}
@Override
public void setStartOnLogin(boolean startOnLogin) throws IOException {
if (isStartOnLogin() != startOnLogin)
writeDesktopFile(getAutostartFile(), "Snake", "Control and configure your Razer devices", startOnLogin,
"-- --no-open");
}
@Override
public void setUpdateAutomatically(boolean updateAutomatically) {
reconfig(isCheckForUpdates(), updateAutomatically, isBetas());
}
protected Path checkDir(Path dir) throws IOException {
if (!Files.exists(dir)) {
Files.createDirectories(dir);
}
return dir;
}
protected boolean contains(Path path, String str) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(Files.newInputStream(path)))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.trim().startsWith(str)) {
return true;
}
}
}
return false;
}
protected Path getAppCfg() {
if (isDev())
return Paths.get("target/image/app.cfg.d");
else
return Paths.get("app.cfg.d");
}
protected boolean isDev() {
return Files.exists(Paths.get("pom.xml"));
}
protected void reconfig(boolean check, boolean auto, boolean betas) {
try {
Path path = checkDir(getAppCfg()).resolve("updates");
try (PrintWriter pw = new PrintWriter(new OutputStreamWriter(Files.newOutputStream(path)), true)) {
if (check) {
if (!auto)
pw.println("update-on-exit 100");
} else {
pw.println("update-on-exit 99");
}
if (betas)
pw.println("remote-manifest " + BETA_CHANNEL);
else
pw.println("remote-manifest " + STABLE_CHANNEL);
}
} catch (IOException ioe) {
throw new IllegalStateException("Failed to change update state.", ioe);
}
}
File getAutostartFile() {
return new File(System.getProperty("user.home") + File.separator + ".config" + File.separator + "autostart"
+ File.separator + SNAKE_RAZER_DESKTOP);
}
File getShare() {
return new File(System.getProperty("user.home") + File.separator + ".local" + File.separator + "share");
}
File getShortcutFile() {
return new File(getShare(), "applications" + File.separator + SNAKE_RAZER_DESKTOP);
}
private File checkFilesParent(File file) throws IOException {
if (!file.exists() && !file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
throw new IOException(String.format("Failed to create parent folder for %s.", file));
}
return file;
}
private void writeDesktopFile(File file, String name, String comment, Boolean autoStart, String... execArgs)
throws IOException, FileNotFoundException {
checkFilesParent(file);
try (PrintWriter pw = new PrintWriter(new FileWriter(file))) {
pw.println("#!/usr/bin/env xdg-open");
pw.println("[Desktop Entry]");
pw.println("Version=1.0");
pw.println("Terminal=false");
File iconFile = checkFilesParent(new File(getShare(), "pixmaps" + File.separator + "snake-razer.png"));
try (FileOutputStream fos = new FileOutputStream(iconFile)) {
try (InputStream in = App.class.getResourceAsStream("icons/app512.png")) {
in.transferTo(fos);
}
}
pw.println("Icon=" + iconFile.getAbsolutePath());
pw.println("Exec=" + System.getProperty("user.dir") + File.separator + "bin/snake"
+ (execArgs.length == 0 ? "" : " " + String.join(" ", execArgs)));
pw.println("Name=" + name);
pw.println("Comment=" + comment);
pw.println("Categories=Utility;Core;");
pw.println("StartupNotify=false");
pw.println("Type=Application");
pw.println("Keywords=razer;snake;mamba;chroma;deathadder");
if (autoStart != null) {
pw.println("X-GNOME-Autostart-enabled=" + autoStart);
}
}
}
}
| 6,911 | 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-updater/src/main/java/module-info.java | module uk.co.bithatch.snake.updater {
requires java.desktop;
requires java.prefs;
requires java.logging;
requires transitive javafx.controls;
requires transitive javafx.graphics;
requires transitive javafx.fxml;
requires transitive com.sshtools.forker.updater;
requires transitive com.sshtools.forker.wrapper;
requires transitive com.goxr3plus.fxborderlessscene;
exports uk.co.bithatch.snake.updater;
opens uk.co.bithatch.snake.updater;
opens uk.co.bithatch.snake.updater.icons;
requires transitive org.kordamp.ikonli.fontawesome;
requires transitive org.kordamp.ikonli.javafx;
provides com.sshtools.forker.updater.UpdateHandler with uk.co.bithatch.snake.updater.JavaFXUpdateHandler;
provides com.sshtools.forker.updater.InstallHandler with uk.co.bithatch.snake.updater.JavaFXInstallHandler;
provides com.sshtools.forker.updater.UninstallHandler with uk.co.bithatch.snake.updater.JavaFXUninstallHandler;
} | 938 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
JavaFXUpdateHandler.java | /FileExtraction/Java_unseen/bithatch_snake/snake-updater/src/main/java/uk/co/bithatch/snake/updater/JavaFXUpdateHandler.java | package uk.co.bithatch.snake.updater;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.Semaphore;
import com.sshtools.forker.updater.Entry;
import com.sshtools.forker.updater.UpdateHandler;
import com.sshtools.forker.updater.UpdateSession;
public class JavaFXUpdateHandler implements UpdateHandler {
private static JavaFXUpdateHandler instance;
public static JavaFXUpdateHandler get() {
if (instance == null)
/* For when launching from development environment */
instance = new JavaFXUpdateHandler();
return instance;
}
private UpdateHandler delegate;
private Semaphore flag = new Semaphore(1);
private UpdateSession updater;
public JavaFXUpdateHandler() {
instance = this;
flag.acquireUninterruptibly();
}
@Override
public void complete() {
flag.acquireUninterruptibly();
try {
delegate.complete();
} finally {
flag.release();
}
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public void startUpdateRollback() {
flag.acquireUninterruptibly();
try {
delegate.startUpdateRollback();
} finally {
flag.release();
}
}
@Override
public void updateRollbackProgress(float progress) {
flag.acquireUninterruptibly();
try {
delegate.updateRollbackProgress(progress);
} finally {
flag.release();
}
}
@Override
public void completedManifestLoad(URL location) {
flag.acquireUninterruptibly();
try {
delegate.completedManifestLoad(location);
} finally {
flag.release();
}
}
@Override
public void doneDownloadFile(Entry file) throws Exception {
flag.acquireUninterruptibly();
try {
delegate.doneDownloadFile(file);
} finally {
flag.release();
}
}
@Override
public void failed(Throwable error) {
flag.acquireUninterruptibly();
try {
delegate.failed(error);
} finally {
flag.release();
}
}
public UpdateSession getSession() {
return updater;
}
@Override
public void init(UpdateSession updater) {
this.updater = updater;
new Thread() {
public void run() {
try {
Bootstrap.main(updater.tool().getArguments());
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
public boolean isActive() {
return updater != null;
}
@Override
public boolean noUpdates(Callable<Void> task) {
flag.acquireUninterruptibly();
try {
return delegate.noUpdates(task);
} finally {
flag.release();
}
}
public void setDelegate(UpdateHandler delegate) {
if (this.delegate != null)
throw new IllegalStateException("Delegate already set.");
this.delegate = delegate;
delegate.init(updater);
flag.release();
}
@Override
public void startDownloadFile(Entry file, int index) throws Exception {
flag.acquireUninterruptibly();
try {
delegate.startDownloadFile(file, index);
} finally {
flag.release();
}
}
@Override
public void updateDone(boolean upgradeError) {
}
@Override
public void startDownloads() throws Exception {
flag.acquireUninterruptibly();
try {
delegate.startDownloads();
} finally {
flag.release();
}
}
@Override
public void startingManifestLoad(URL location) {
flag.acquireUninterruptibly();
try {
delegate.startingManifestLoad(location);
} finally {
flag.release();
}
}
@Override
public void updateDownloadFileProgress(Entry entry, float progress) throws Exception {
flag.acquireUninterruptibly();
try {
delegate.updateDownloadFileProgress(entry, progress);
} finally {
flag.release();
}
}
@Override
public void updateDownloadProgress(float progress) throws Exception {
flag.acquireUninterruptibly();
try {
delegate.updateDownloadProgress(progress);
} finally {
flag.release();
}
}
@Override
public boolean updatesComplete(Callable<Void> task) throws Exception {
flag.acquireUninterruptibly();
try {
return delegate.updatesComplete(task);
} finally {
flag.release();
}
}
@Override
public Void prep(Callable<Void> callback) {
flag.acquireUninterruptibly();
try {
return delegate.prep(callback);
} finally {
flag.release();
}
}
@Override
public Void value() {
flag.acquireUninterruptibly();
try {
return delegate.value();
} finally {
flag.release();
}
}
}
| 4,263 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
JavaFXUninstallHandler.java | /FileExtraction/Java_unseen/bithatch_snake/snake-updater/src/main/java/uk/co/bithatch/snake/updater/JavaFXUninstallHandler.java | package uk.co.bithatch.snake.updater;
import java.nio.file.Path;
import java.util.concurrent.Callable;
import java.util.concurrent.Semaphore;
import com.sshtools.forker.updater.UninstallHandler;
import com.sshtools.forker.updater.UninstallSession;
import com.sshtools.forker.updater.test.UninstallTest;
public class JavaFXUninstallHandler implements UninstallHandler {
public static void main(String[] args) throws Exception {
UninstallTest.main(args, new JavaFXUninstallHandler());
}
private static JavaFXUninstallHandler instance;
public static JavaFXUninstallHandler get() {
if (instance == null)
/* For when launching from development environment */
instance = new JavaFXUninstallHandler();
return instance;
}
private UninstallHandler delegate;
private Semaphore flag = new Semaphore(1);
private UninstallSession session;
public JavaFXUninstallHandler() {
instance = this;
flag.acquireUninterruptibly();
}
@Override
public boolean isCancelled() {
return delegate.isCancelled();
}
@Override
public Boolean prep(Callable<Void> callable) {
flag.acquireUninterruptibly();
try {
return delegate.prep(callable);
} finally {
flag.release();
}
}
@Override
public Boolean value() {
flag.acquireUninterruptibly();
try {
return delegate.value();
} finally {
flag.release();
}
}
@Override
public void complete() {
flag.acquireUninterruptibly();
try {
delegate.complete();
} finally {
flag.release();
}
}
@Override
public void failed(Throwable error) {
flag.acquireUninterruptibly();
try {
delegate.failed(error);
} finally {
flag.release();
}
}
public UninstallSession getSession() {
return session;
}
@Override
public void init(UninstallSession session) {
this.session = session;
new Thread() {
public void run() {
try {
Bootstrap.main(new String[0]);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
@Override
public void uninstallFile(Path file, Path d, int index) throws Exception {
flag.acquireUninterruptibly();
try {
delegate.uninstallFile(file, d, index);
} finally {
flag.release();
}
}
@Override
public void uninstallDone() {
flag.acquireUninterruptibly();
try {
delegate.uninstallDone();
} finally {
flag.release();
}
}
@Override
public void uninstallFileDone(Path file) throws Exception {
flag.acquireUninterruptibly();
try {
delegate.uninstallFileDone(file);
} finally {
flag.release();
}
}
@Override
public void uninstallFileProgress(Path file, float progress) throws Exception {
flag.acquireUninterruptibly();
try {
delegate.uninstallFileProgress(file, progress);
} finally {
flag.release();
}
}
@Override
public void uninstallProgress(float progress) throws Exception {
flag.acquireUninterruptibly();
try {
delegate.uninstallProgress(progress);
} finally {
flag.release();
}
}
public boolean isActive() {
return session != null;
}
public void setDelegate(UninstallHandler delegate) {
if (this.delegate != null)
throw new IllegalStateException("Delegate already set.");
this.delegate = delegate;
delegate.init(session);
flag.release();
}
@Override
public void startUninstall() throws Exception {
flag.acquireUninterruptibly();
try {
delegate.startUninstall();
} finally {
flag.release();
}
}
}
| 3,399 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
Install.java | /FileExtraction/Java_unseen/bithatch_snake/snake-updater/src/main/java/uk/co/bithatch/snake/updater/Install.java | package uk.co.bithatch.snake.updater;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.ResourceBundle;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import com.sshtools.forker.common.OS;
import com.sshtools.forker.updater.AppManifest;
import com.sshtools.forker.updater.DesktopShortcut;
import com.sshtools.forker.updater.InstallHandler;
import com.sshtools.forker.updater.InstallSession;
import com.sshtools.forker.updater.Updater;
import com.sshtools.forker.wrapper.Configuration;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TextField;
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.VBox;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
public class Install implements Controller, InstallHandler {
/** The logger. */
protected Logger logger = Logger.getGlobal();
final static ResourceBundle bundle = ResourceBundle.getBundle(Install.class.getName());
final static Preferences PREFS = Preferences.userRoot().node("uk").node("co").node("bithatch").node("snake")
.node("ui");
private static final String SNAKE_RAZER_DESKTOP = "snake-razer";
@FXML
private Button browse;
@FXML
private Hyperlink install;
@FXML
private TextField installLocation;
@FXML
private CheckBox installShortcut;
@FXML
private CheckBox launch;
@FXML
private BorderPane options;
@FXML
private ProgressIndicator progress;
@FXML
private VBox progressContainer;
@FXML
private Label status;
@FXML
private Label title;
@FXML
private BorderPane titleBar;
private Scene scene;
private InstallSession session;
private Bootstrap bootstrap;
private Callable<Void> callback;
private ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
@Override
public Path prep(Callable<Void> callable) {
this.callback = callable;
return null;
}
@Override
public Path value() {
return Paths.get(installLocation.textProperty().get());
}
@Override
public void installDone() {
}
@Override
public void complete() {
bootstrap.setInstalled();
if (OS.getJavaPath().startsWith(System.getProperty("java.io.tmpdir"))) {
logger.info("Running from temporary runtime");
Path installedRuntime = Paths.get(installLocation.getText(), "bin",
com.sun.jna.Platform.isWindows() ? "java.exe" : "java");
if (Files.exists(installedRuntime)) {
Configuration cfg = session.tool().getConfiguration();
cfg.setProperty("java", installedRuntime.toString());
session.tool().setLaunchDirectory(new File(installLocation.getText()));
cfg.setProperty("cwd", installLocation.toString());
logger.info(String.format("Found alternative runtime at %s", installedRuntime));
}
}
try {
if (installShortcut.selectedProperty().get()) {
session.installShortcut(new DesktopShortcut(SNAKE_RAZER_DESKTOP)
.comment("Control and configure your Razer devices").name("Snake")
.executable(installLocation.textProperty().get() + File.separator + "bin/snake")
.addCategories("Utility", "Core").addKeywords("razer", "snake", "mamba", "chroma", "deathadder")
.icon(Install.class.getResource("icons/app512.png").toExternalForm()));
} else {
session.uninstallShortcut(SNAKE_RAZER_DESKTOP);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
Platform.runLater(() -> {
message("success");
status.getStyleClass().add("success");
});
executor.shutdown();
}
public void doneDownloads() throws Throwable {
Platform.runLater(() -> {
bootstrap.getStage().show();
message("doneDownloads");
});
}
@Override
public void failed(Throwable t) {
Platform.runLater(() -> {
message("failed", t.getMessage() == null ? "No message supplied." : t.getMessage());
progress.visibleProperty().set(false);
progress.managedProperty().set(false);
status.getStyleClass().add("danger");
});
}
@Override
public Scene getScene() {
return scene;
}
@Override
public void init(InstallSession session) {
this.session = session;
titleBar.setBackground(new Background(
new BackgroundImage(new Image(getClass().getResource("titleBar.png").toExternalForm(), true),
BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER,
new BackgroundSize(100d, 100d, true, true, false, true))));
title.setFont(Bootstrap.font);
progressContainer.managedProperty().bind(progressContainer.visibleProperty());
options.managedProperty().bind(options.visibleProperty());
progressContainer.visibleProperty().set(false);
launch.setSelected(this.session.tool() == null ? false
: this.session.tool().getConfiguration().getSwitch("run-on-install", false));
installLocation.textProperty().set(PREFS.get("installLocation", session.base().toString()));
installLocation.textProperty().addListener((e) -> checkInstallable());
status.textProperty().set(bundle.getString("preparing"));
progress.setProgress(-1);
bootstrap.getStage().show();
Updater updater = this.session.tool();
if (updater != null)
updater.closeSplash();
}
@Override
public void installFile(Path file, Path d, int index) throws Exception {
Platform.runLater(() -> {
bootstrap.getStage().show();
message("installFile", file.getFileName().toString());
});
}
@Override
public void installFileDone(Path file) throws Exception {
message("installFileDone", file.getFileName().toString());
}
@Override
public void installFileProgress(Path file, float progress) throws Exception {
}
@Override
public void installProgress(float frac) throws Exception {
Platform.runLater(() -> progress.progressProperty().set(frac));
}
public void setBootstrap(Bootstrap bootstrap) {
this.bootstrap = bootstrap;
}
@Override
public void setScene(Scene scene) {
this.scene = scene;
}
@Override
public void startInstall() throws Exception {
Platform.runLater(() -> {
options.visibleProperty().set(false);
progressContainer.visibleProperty().set(true);
bootstrap.getStage().show();
message("startInstall");
});
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public void startInstallRollback() {
Platform.runLater(() -> {
bootstrap.getStage().show();
Platform.runLater(() -> progress.progressProperty().set(0));
message("startInstallRollback");
});
}
@Override
public void installRollbackProgress(float frac) {
Platform.runLater(() -> {
bootstrap.getStage().show();
Platform.runLater(() -> progress.progressProperty().set(frac));
message("installRollbackProgress");
});
}
protected void checkInstallable() {
Path p = value();
install.disableProperty()
.set(Files.isRegularFile(p) || (!isExistsAndIsEmpty(p) && Files.exists(p) && !isSameAppId(p)));
}
@FXML
void evtBrowse(ActionEvent evt) {
DirectoryChooser fileChooser = new DirectoryChooser();
fileChooser.setTitle(bundle.getString("selectTarget"));
Path dir = value();
while (dir != null) {
if (Files.isDirectory(dir)) {
break;
}
dir = dir.getParent();
}
if (dir == null)
fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));
else {
fileChooser.setInitialDirectory(dir.toFile());
}
File file = fileChooser.showDialog((Stage) getScene().getWindow());
if (file != null) {
installLocation.textProperty().set(file.getPath());
}
}
@FXML
void evtClose(ActionEvent evt) {
bootstrap.close();
}
@FXML
void evtInstall(ActionEvent evt) {
PREFS.put("installLocation", installLocation.textProperty().get());
boolean doLaunch = launch.selectedProperty().get();
Updater tool = this.session.tool();
if (tool != null) {
tool.getConfiguration().setProperty("run-on-install", doLaunch);
tool.getConfiguration().setProperty("daemon", doLaunch);
}
new Thread() {
public void run() {
try {
callback.call();
} catch (Exception e) {
throw new IllegalStateException("Failed to continue installation.", e);
}
}
}.start();
}
@FXML
void evtMin(ActionEvent evt) {
Stage stage = (Stage) ((Hyperlink) evt.getSource()).getScene().getWindow();
stage.setIconified(true);
}
void message(String key, String... args) {
if (Platform.isFxApplicationThread()) {
String txt = MessageFormat.format(bundle.getString(key), (Object[]) args);
status.textProperty().set(txt);
} else
Platform.runLater(() -> message(key, args));
}
private boolean isExistsAndIsEmpty(Path p) {
if (Files.exists(p) && Files.isDirectory(p)) {
return p.toFile().list().length == 0;
}
return false;
}
private boolean isSameAppId(Path p) {
Path manifest = p.resolve("manifest.xml");
if (Files.exists(manifest)) {
try {
AppManifest m = new AppManifest(manifest);
return m.id().equals(session.manifest().id());
} catch (IOException ioe) {
}
}
return false;
}
}
| 9,613 | 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-updater/src/main/java/uk/co/bithatch/snake/updater/Controller.java | package uk.co.bithatch.snake.updater;
import javafx.scene.Scene;
public interface Controller {
Scene getScene();
void setScene(Scene scene);
}
| 150 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
Update.java | /FileExtraction/Java_unseen/bithatch_snake/snake-updater/src/main/java/uk/co/bithatch/snake/updater/Update.java | package uk.co.bithatch.snake.updater;
import java.nio.file.Path;
import java.text.MessageFormat;
import java.util.ResourceBundle;
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 com.sshtools.forker.updater.Entry;
import com.sshtools.forker.updater.UpdateHandler;
import com.sshtools.forker.updater.UpdateSession;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
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.stage.Stage;
public class Update implements Controller, UpdateHandler {
final static ResourceBundle bundle = ResourceBundle.getBundle(Update.class.getName());
@FXML
private ProgressIndicator progress;
@FXML
private Label status;
@FXML
private Label title;
@FXML
private BorderPane titleBar;
private Bootstrap bootstrap;
private ScheduledFuture<?> checkTask;
private ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
private Scene scene;
@Override
public void complete() {
Platform.runLater(() -> {
message("success");
status.getStyleClass().add("success");
});
executor.shutdown();
bootstrap.close();
}
public void doneCheckUpdateFile(Entry file, boolean requires) throws Throwable {
message("doneCheckUpdateFile", file.path().getFileName().toString());
}
public void doneCheckUpdates() throws Throwable {
message("doneCheckUpdates");
}
@Override
public void doneDownloadFile(Entry file) throws Exception {
}
public void doneDownloadFile(Entry file, Path path) throws Throwable {
message("doneDownloadFile", file.path().getFileName().toString());
}
public void doneDownloads() throws Throwable {
Platform.runLater(() -> {
bootstrap.getStage().show();
message("doneDownloads");
});
}
@Override
public void failed(Throwable t) {
Platform.runLater(() -> {
message("failed", t.getMessage() == null ? "No message supplied." : t.getMessage());
status.getStyleClass().add("danger");
});
}
@Override
public Scene getScene() {
return scene;
}
@Override
public void init(UpdateSession session) {
titleBar.setBackground(new Background(
new BackgroundImage(new Image(getClass().getResource("titleBar.png").toExternalForm(), true),
BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER,
new BackgroundSize(100d, 100d, true, true, false, true))));
title.setFont(Bootstrap.font);
status.textProperty().set(bundle.getString("check"));
progress.setProgress(-1);
if (bootstrap.isInstalled()) {
Platform.runLater(() -> bootstrap.getStage().show());
} else {
/*
* Don't show the stage just yet, instead start the check process in the
* background, and only show the stage if it is taking more that a few seconds.
* This will prevent the update window being shown in most cases (except people
* with slow networks to the update server)
*/
if (session.tool().getConfiguration().getProperty("update-on-exit") == null) {
checkTask = executor.schedule(() -> {
Platform.runLater(() -> bootstrap.getStage().show());
}, 5, TimeUnit.SECONDS);
}
}
}
@Override
public boolean noUpdates(Callable<Void> task) {
if (checkTask != null)
checkTask.cancel(false);
Platform.runLater(() -> {
status.textProperty().set(bundle.getString("noUpdates"));
status.getStyleClass().add("success");
});
return true;
}
public void ready() {
if (checkTask != null)
checkTask.cancel(false);
Platform.runLater(() -> bootstrap.getStage().show());
status.textProperty().set(bundle.getString("ready"));
}
public void setBootstrap(Bootstrap bootstrap) {
this.bootstrap = bootstrap;
}
@Override
public void setScene(Scene scene) {
this.scene = scene;
}
public void startCheckUpdateFile(Entry file) throws Throwable {
message("startCheckUpdateFile", file.path().getFileName().toString());
}
public void startCheckUpdates() throws Throwable {
message("startCheckUpdates");
}
@Override
public void startDownloadFile(Entry file, int index) throws Exception {
Platform.runLater(() -> {
bootstrap.getStage().show();
message("startDownloadFile", file.path().getFileName().toString());
});
}
@Override
public void updateDone(boolean upgradeError) {
}
@Override
public void startDownloads() throws Exception {
Platform.runLater(() -> {
bootstrap.getStage().show();
message("startDownloads");
});
}
public void updateCheckUpdatesProgress(float frac) throws Throwable {
Platform.runLater(() -> progress.progressProperty().set(frac));
}
@Override
public void updateDownloadFileProgress(Entry file, float frac) throws Exception {
}
@Override
public void updateDownloadProgress(float frac) throws Exception {
Platform.runLater(() -> progress.progressProperty().set(frac));
}
public void validatingFile(Entry file, Path path) throws Throwable {
message("validatingFile", file.path().getFileName().toString());
}
@FXML
void evtClose(ActionEvent evt) {
bootstrap.close();
}
@FXML
void evtMin(ActionEvent evt) {
Stage stage = (Stage) ((Hyperlink) evt.getSource()).getScene().getWindow();
stage.setIconified(true);
}
void message(String key, String... args) {
if (Platform.isFxApplicationThread()) {
String txt = MessageFormat.format(bundle.getString(key), (Object[]) args);
status.textProperty().set(txt);
} else
Platform.runLater(() -> message(key, args));
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public void startUpdateRollback() {
Platform.runLater(() -> {
bootstrap.getStage().show();
Platform.runLater(() -> progress.progressProperty().set(0));
message("startUpdateRollback");
});
}
@Override
public void updateRollbackProgress(float frac) {
Platform.runLater(() -> {
bootstrap.getStage().show();
Platform.runLater(() -> progress.progressProperty().set(frac));
message("updateRollbackProgress");
});
}
@Override
public Void prep(Callable<Void> callback) {
return null;
}
@Override
public Void value() {
return null;
}
}
| 6,625 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
Bootstrap.java | /FileExtraction/Java_unseen/bithatch_snake/snake-updater/src/main/java/uk/co/bithatch/snake/updater/Bootstrap.java | package uk.co.bithatch.snake.updater;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import java.util.stream.Collectors;
import com.goxr3plus.fxborderlessscene.borderless.BorderlessScene;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class Bootstrap extends Application {
public static Font font;
public static List<Image> images;
public static final String REMOTE_CONFIG = "http://blue/repository/config.xml";
final static ResourceBundle bundle = ResourceBundle.getBundle(Bootstrap.class.getName());
private static Bootstrap instance;
static {
font = Font.loadFont(Install.class.getResource("FROSTBITE-Narrow.ttf").toExternalForm(), 12);
}
public static void main(String[] args) throws Exception {
if (instance == null)
launch(args);
else {
instance.relaunch(args);
}
}
private boolean installed;
private Stage primaryStage;
private StackPane stack;
{
instance = this;
}
public void close() {
if (!Platform.isFxApplicationThread()) {
Platform.runLater(() -> close());
return;
}
try {
primaryStage.close();
}
catch(Exception e) {
// TODO investigate further. Some strange NPE exception coming from JavaFX when
// the installer exits (no run-on-install).
}
}
public Stage getStage() {
return primaryStage;
}
@Override
public void init() {
System.setProperty("suppress.warning", "true");
List<String> sizes = List.of("32", "64", "96", "128", "256", "512");
images = sizes.stream().map(s -> ("/uk/co/bithatch/snake/updater/icons/app" + s + ".png"))
.map(s -> getClass().getResource(s).toExternalForm()).map(Image::new).collect(Collectors.toList());
}
public boolean isInstalled() {
return installed;
}
@SuppressWarnings("unchecked")
public <C extends Controller> C openScene(Class<C> controller) throws IOException {
URL resource = controller.getResource(controller.getSimpleName() + ".fxml");
FXMLLoader loader = new FXMLLoader();
loader.setResources(ResourceBundle.getBundle(controller.getName()));
loader.setLocation(resource);
Parent root = loader.load(resource.openStream());
C controllerInst = (C) loader.getController();
if (controllerInst == null) {
throw new IOException("Controller not found. Check controller in FXML");
}
root.getStylesheets().add(controller.getResource(Bootstrap.class.getSimpleName() + ".css").toExternalForm());
URL controllerCssUrl = controller.getResource(controller.getSimpleName() + ".css");
if (controllerCssUrl != null)
root.getStylesheets().add(controllerCssUrl.toExternalForm());
Scene scene = new Scene(root);
controllerInst.setScene(scene);
scene.getRoot().getStyleClass().add("rootPane");
return controllerInst;
}
public void setInstalled() {
this.installed = true;
}
@Override
public void start(Stage primaryStage) throws Exception {
this.primaryStage = primaryStage;
recreate();
}
private void recreate() throws IOException {
Parent node = null;
Install install = null;
Update update = null;
Uninstall uninstall = null;
if (JavaFXUpdateHandler.get().isActive()) {
update = openScene(Update.class);
update.setBootstrap(this);
node = update.getScene().getRoot();
} else if (JavaFXUninstallHandler.get().isActive()) {
uninstall = openScene(Uninstall.class);
uninstall.setBootstrap(this);
node = uninstall.getScene().getRoot();
} else if (JavaFXInstallHandler.get().isActive()) {
install = openScene(Install.class);
install.setBootstrap(this);
node = install.getScene().getRoot();
} else
throw new IllegalStateException("No handler active.");
if (stack == null) {
stack = new StackPane(node);
AnchorPane anchor = new AnchorPane(stack);
AnchorPane.setBottomAnchor(stack, 0d);
AnchorPane.setLeftAnchor(stack, 0d);
AnchorPane.setTopAnchor(stack, 0d);
AnchorPane.setRightAnchor(stack, 0d);
BorderlessScene primaryScene = new BorderlessScene(primaryStage, StageStyle.TRANSPARENT, anchor, 460, 200);
((BorderlessScene) primaryScene).setMoveControl(node);
((BorderlessScene) primaryScene).setSnapEnabled(false);
primaryStage.setScene(primaryScene);
primaryStage.setResizable(false);
primaryStage.getIcons().addAll(images);
primaryStage.setTitle(bundle.getString("title"));
} else {
stack.getChildren().clear();
stack.getChildren().add(node);
}
/* This will release the lock and let everything start */
if (install != null) {
JavaFXInstallHandler.get().setDelegate(install);
} else if (uninstall != null) {
JavaFXUninstallHandler.get().setDelegate(uninstall);
}else {
JavaFXUpdateHandler.get().setDelegate(update);
}
}
private void relaunch(String[] args) {
if (!Platform.isFxApplicationThread()) {
Platform.runLater(() -> relaunch(args));
return;
}
try {
recreate();
} catch (Exception e) {
throw new IllegalStateException("Failed to relaunch.", e);
}
}
}
| 5,263 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
Uninstall.java | /FileExtraction/Java_unseen/bithatch_snake/snake-updater/src/main/java/uk/co/bithatch/snake/updater/Uninstall.java | package uk.co.bithatch.snake.updater;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.ResourceBundle;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.logging.Logger;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import com.sshtools.forker.updater.UninstallHandler;
import com.sshtools.forker.updater.UninstallSession;
import com.sshtools.forker.updater.Uninstaller;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
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.VBox;
import javafx.stage.Stage;
public class Uninstall implements Controller, UninstallHandler {
/** The logger. */
protected Logger logger = Logger.getGlobal();
private final static ResourceBundle bundle = ResourceBundle.getBundle(Uninstall.class.getName());
private final static Preferences PREFS = Preferences.userRoot().node("uk").node("co").node("bithatch").node("snake");
private static final String SNAKE_RAZER_DESKTOP = "snake-razer";
@FXML
private Hyperlink install;
@FXML
private CheckBox deleteAll;
@FXML
private BorderPane options;
@FXML
private ProgressIndicator progress;
@FXML
private VBox progressContainer;
@FXML
private Label status;
@FXML
private Label title;
@FXML
private BorderPane titleBar;
private Scene scene;
private UninstallSession session;
private Bootstrap bootstrap;
private Callable<Void> callback;
private ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
@Override
public Boolean prep(Callable<Void> callable) {
this.callback = callable;
return null;
}
@Override
public Boolean value() {
return deleteAll.selectedProperty().getValue();
}
@Override
public void uninstallDone() {
}
@Override
public void complete() {
bootstrap.setInstalled();
Platform.runLater(() -> {
message("success");
status.getStyleClass().add("success");
});
executor.shutdown();
}
@Override
public void failed(Throwable t) {
Platform.runLater(() -> {
message("failed", t.getMessage() == null ? "No message supplied." : t.getMessage());
progress.visibleProperty().set(false);
progress.managedProperty().set(false);
status.getStyleClass().add("danger");
});
}
@Override
public Scene getScene() {
return scene;
}
@Override
public void init(UninstallSession session) {
this.session = session;
titleBar.setBackground(new Background(
new BackgroundImage(new Image(getClass().getResource("titleBar.png").toExternalForm(), true),
BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER,
new BackgroundSize(100d, 100d, true, true, false, true))));
title.setFont(Bootstrap.font);
progressContainer.managedProperty().bind(progressContainer.visibleProperty());
options.managedProperty().bind(options.visibleProperty());
progressContainer.visibleProperty().set(false);
session.addFile(getShare().resolve("pixmaps").resolve("snake-razer.png"));
session.addFile(getConf().resolve("autostart").resolve("snake-razer.desktop"));
session.addDirectory(session.base().resolve("addons"));
session.addFile(session.base().resolve("app.args"));
status.textProperty().set(bundle.getString("preparing"));
progress.setProgress(-1);
bootstrap.getStage().show();
Uninstaller uninstaller = this.session.tool();
if (uninstaller != null)
uninstaller.closeSplash();
}
@Override
public void uninstallFile(Path file, Path d, int index) throws Exception {
Platform.runLater(() -> {
bootstrap.getStage().show();
message("uninstallFile", file.getFileName().toString());
});
}
@Override
public void uninstallFileDone(Path file) throws Exception {
message("uninstallFileDone", file.getFileName().toString());
}
@Override
public void uninstallFileProgress(Path file, float progress) throws Exception {
}
@Override
public void uninstallProgress(float frac) throws Exception {
Platform.runLater(() -> progress.progressProperty().set(frac));
}
public void setBootstrap(Bootstrap bootstrap) {
this.bootstrap = bootstrap;
}
@Override
public void setScene(Scene scene) {
this.scene = scene;
}
@Override
public void startUninstall() throws Exception {
Platform.runLater(() -> {
options.visibleProperty().set(false);
progressContainer.visibleProperty().set(true);
bootstrap.getStage().show();
message("startUninstall");
try {
session.uninstallShortcut(SNAKE_RAZER_DESKTOP);
} catch (IOException ioe) {
ioe.printStackTrace();
}
try {
if (deleteAll.selectedProperty().get()) {
PREFS.removeNode();
}
} catch (BackingStoreException bse) {
bse.printStackTrace();
}
});
}
@Override
public boolean isCancelled() {
return false;
}
@FXML
void evtClose(ActionEvent evt) {
bootstrap.close();
}
@FXML
void evtUninstall(ActionEvent evt) {
new Thread() {
public void run() {
try {
callback.call();
} catch (Exception e) {
throw new IllegalStateException("Failed to continue installation.", e);
}
}
}.start();
}
@FXML
void evtMin(ActionEvent evt) {
Stage stage = (Stage) ((Hyperlink) evt.getSource()).getScene().getWindow();
stage.setIconified(true);
}
void message(String key, String... args) {
if (Platform.isFxApplicationThread()) {
String txt = MessageFormat.format(bundle.getString(key), (Object[]) args);
status.textProperty().set(txt);
} else
Platform.runLater(() -> message(key, args));
}
Path getShare() {
return getHome().resolve(".local").resolve("share");
}
Path getHome() {
return Paths.get(System.getProperty("user.home"));
}
Path getConf() {
return getHome().resolve(".config");
}
}
| 6,326 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
JavaFXInstallHandler.java | /FileExtraction/Java_unseen/bithatch_snake/snake-updater/src/main/java/uk/co/bithatch/snake/updater/JavaFXInstallHandler.java | package uk.co.bithatch.snake.updater;
import java.nio.file.Path;
import java.util.concurrent.Callable;
import java.util.concurrent.Semaphore;
import com.sshtools.forker.updater.InstallHandler;
import com.sshtools.forker.updater.InstallSession;
import com.sshtools.forker.updater.test.InstallTest;
public class JavaFXInstallHandler implements InstallHandler {
public static void main(String[] args) throws Exception {
InstallTest.main(args, new JavaFXInstallHandler());
}
private static JavaFXInstallHandler instance;
public static JavaFXInstallHandler get() {
if (instance == null)
/* For when launching from development environment */
instance = new JavaFXInstallHandler();
return instance;
}
private InstallHandler delegate;
private Semaphore flag = new Semaphore(1);
private InstallSession session;
public JavaFXInstallHandler() {
instance = this;
flag.acquireUninterruptibly();
}
@Override
public boolean isCancelled() {
return delegate.isCancelled();
}
@Override
public void installRollbackProgress(float progress) {
flag.acquireUninterruptibly();
try {
delegate.installRollbackProgress(progress);
} finally {
flag.release();
}
}
@Override
public void startInstallRollback() throws Exception {
flag.acquireUninterruptibly();
try {
delegate.startInstallRollback();
} finally {
flag.release();
}
}
@Override
public Path prep(Callable<Void> callable) {
flag.acquireUninterruptibly();
try {
return delegate.prep(callable);
} finally {
flag.release();
}
}
@Override
public Path value() {
flag.acquireUninterruptibly();
try {
return delegate.value();
} finally {
flag.release();
}
}
@Override
public void complete() {
flag.acquireUninterruptibly();
try {
delegate.complete();
} finally {
flag.release();
}
}
@Override
public void failed(Throwable error) {
flag.acquireUninterruptibly();
try {
delegate.failed(error);
} finally {
flag.release();
}
}
public InstallSession getSession() {
return session;
}
@Override
public void init(InstallSession session) {
this.session = session;
new Thread() {
public void run() {
try {
Bootstrap.main(session.tool() == null ? new String[0] : session.tool().getArguments());
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
@Override
public void installFile(Path file, Path d, int index) throws Exception {
flag.acquireUninterruptibly();
try {
delegate.installFile(file, d, index);
} finally {
flag.release();
}
}
@Override
public void installDone() {
flag.acquireUninterruptibly();
try {
delegate.installDone();
} finally {
flag.release();
}
}
@Override
public void installFileDone(Path file) throws Exception {
flag.acquireUninterruptibly();
try {
delegate.installFileDone(file);
} finally {
flag.release();
}
}
@Override
public void installFileProgress(Path file, float progress) throws Exception {
flag.acquireUninterruptibly();
try {
delegate.installFileProgress(file, progress);
} finally {
flag.release();
}
}
@Override
public void installProgress(float progress) throws Exception {
flag.acquireUninterruptibly();
try {
delegate.installProgress(progress);
} finally {
flag.release();
}
}
public boolean isActive() {
return session != null;
}
public void setDelegate(InstallHandler delegate) {
if (this.delegate != null)
throw new IllegalStateException("Delegate already set.");
this.delegate = delegate;
delegate.init(session);
flag.release();
}
@Override
public void startInstall() throws Exception {
flag.acquireUninterruptibly();
try {
delegate.startInstall();
} finally {
flag.release();
}
}
}
| 3,776 | Java | .java | bithatch/snake | 66 | 4 | 11 | 2020-10-17T07:55:01Z | 2021-10-09T19:26:18Z |
DefinitionsAnalysis.java | /FileExtraction/Java_unseen/hluwa_PrivacyDog/src/main/java/DefinitionsAnalysis.java | import soot.Unit;
import soot.Value;
import soot.jimple.DefinitionStmt;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.scalar.ForwardFlowAnalysis;
import soot.toolkits.scalar.Pair;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class DefinitionsAnalysis extends ForwardFlowAnalysis<Unit, ValueSet> {
ValueSet emptySet = new ValueSet();
/**
* Construct the analysis from a DirectedGraph representation of a Body.
*
* @param graph
*/
public DefinitionsAnalysis(DirectedGraph graph) {
super(graph);
doAnalysis();
}
@Override
protected void flowThrough(ValueSet in, Unit d, ValueSet out) {
in.copy(out);
if (d instanceof DefinitionStmt) {
DefinitionStmt defStmt = (DefinitionStmt) d;
Value leftOp = defStmt.getLeftOp();
AbstractValue value = new AbstractValue(leftOp);
value.values.add(new Pair<>(defStmt.getRightOp(), d));
if (out.contains(value)) {
out.varToValues.remove(value.o);
}
out.add(value);
}
}
public List<Pair<Object, Unit>> solveOf(Unit location, Object o) {
return solveOf(location, o, false);
}
public List<Pair<Object, Unit>> solveOf(Unit location, Object o, boolean before) {
ValueSet vs = before ? this.getFlowBefore(location) : this.getFlowAfter(location);
if (vs.varToValues.containsKey(o)) {
return vs.varToValues.get(o).values;
}
return new ArrayList<>();
}
@Override
protected ValueSet newInitialFlow() {
return emptySet.clone();
}
@Override
protected void merge(ValueSet in1, ValueSet in2, ValueSet out) {
in1.union(in2, out);
}
@Override
protected void copy(ValueSet source, ValueSet dest) {
dest.varToValues = new HashMap<>();
for (Object var : source.varToValues.keySet()) {
dest.varToValues.put(var, source.varToValues.get(var).clone());
}
}
}
| 2,082 | Java | .java | hluwa/PrivacyDog | 38 | 3 | 0 | 2020-07-23T02:26:35Z | 2023-03-26T15:24:13Z |
Rule.java | /FileExtraction/Java_unseen/hluwa_PrivacyDog/src/main/java/Rule.java | import java.util.List;
import java.util.Map;
public class Rule {
private String name;
private List<Condition> conditions;
public Rule() {
}
@Override
public String toString() {
return "Rule{" +
"name='" + name + '\'' +
", conditions=" + conditions +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Condition> getConditions() {
return conditions;
}
public void setConditions(List<Condition> conditions) {
this.conditions = conditions;
}
}
class Condition {
private String className;
private String methodName;
private String classPattern;
private String methodPattern;
private String stringPattern;
private int paramsCount = -1;
private Map<Integer, String> arguments;
public String getClassPattern() {
return classPattern;
}
public void setClassPattern(String classPattern) {
this.classPattern = classPattern;
}
public String getMethodPattern() {
return methodPattern;
}
public void setMethodPattern(String methodPattern) {
this.methodPattern = methodPattern;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public Map<Integer, String> getArguments() {
return arguments;
}
public void setArguments(Map<Integer, String> arguments) {
this.arguments = arguments;
}
public int getParamsCount() {
return paramsCount;
}
public void setParamsCount(int paramsCount) {
this.paramsCount = paramsCount;
}
public String getStringPattern() {
return stringPattern;
}
public void setStringPattern(String stringPattern) {
this.stringPattern = stringPattern;
}
public boolean isInvokeCondition() {
return !conditionEmpty(className) || !conditionEmpty(classPattern)
|| !conditionEmpty(methodName) || !conditionEmpty(methodPattern)
|| !conditionEmpty(paramsCount) || !conditionEmpty(arguments);
}
private boolean conditionEmpty(String key) {
return key == null || key.isEmpty();
}
private boolean conditionEmpty(int key) {
return key == -1;
}
private boolean conditionEmpty(Map key) {
return key == null || key.size() == 0;
}
@Override
public String toString() {
return "Condition{" +
"className='" + className + '\'' +
", methodName='" + methodName + '\'' +
", classPattern='" + classPattern + '\'' +
", methodPattern='" + methodPattern + '\'' +
", stringPattern='" + stringPattern + '\'' +
", paramsCount=" + paramsCount +
", arguments=" + arguments +
'}';
}
}
| 3,197 | Java | .java | hluwa/PrivacyDog | 38 | 3 | 0 | 2020-07-23T02:26:35Z | 2023-03-26T15:24:13Z |
ValueSet.java | /FileExtraction/Java_unseen/hluwa_PrivacyDog/src/main/java/ValueSet.java | import soot.Unit;
import soot.toolkits.scalar.AbstractFlowSet;
import soot.toolkits.scalar.Pair;
import java.util.*;
class AbstractValue {
Object o;
List<Pair<Object, Unit>> values = new ArrayList<>();
Map<String, Unit> conditions = new TreeMap<>();
public AbstractValue() {
}
public AbstractValue(Object obj) {
this.o = obj;
}
@Override
public AbstractValue clone() {
AbstractValue res = new AbstractValue(this.o);
res.values = new ArrayList<>(values);
res.conditions = new TreeMap<>(this.conditions);
return res;
}
@Override
public boolean equals(Object o) {
return o != null && hashCode() == o.hashCode();
}
@Override
public int hashCode() {
return Objects.hash(Arrays.hashCode(values.toArray()), Arrays.hashCode(conditions.values().toArray()), this.o);
}
}
public class ValueSet extends AbstractFlowSet<AbstractValue> {
public Map<Object, AbstractValue> varToValues = new HashMap<>();
public ValueSet() {
}
@Override
public ValueSet clone() {
ValueSet res = new ValueSet();
res.varToValues = new HashMap<>();
for (Object var : this.varToValues.keySet()) {
res.varToValues.put(var, this.varToValues.get(var).clone());
}
return res;
}
@Override
public boolean isEmpty() {
return this.varToValues.isEmpty();
}
@Override
public int size() {
return this.varToValues.size();
}
@Override
public void add(AbstractValue obj) {
if (contains(obj)) {
AbstractValue dest = this.varToValues.get(obj.o);
for (Pair<Object, Unit> value : obj.values) {
if (!dest.values.contains(value)) {
dest.values.add(value);
}
}
} else {
this.varToValues.put(obj.o, obj);
}
}
@Override
public void remove(AbstractValue obj) {
if (contains(obj)) {
AbstractValue dest = this.varToValues.get(obj.o);
for (Pair<Object, Unit> value : obj.values) {
if (!dest.values.contains(value)) {
dest.values.remove(value);
}
}
if (dest.values.isEmpty()) {
this.varToValues.remove(obj.o);
}
}
}
public void intersection(ValueSet other, ValueSet dest) {
for (AbstractValue obj : this) {
if (other.contains(obj)) {
List<Pair<Object, Unit>> destValues = new ArrayList<>();
List<Pair<Object, Unit>> values1 = other.varToValues.get(obj.o).values;
List<Pair<Object, Unit>> values2 = this.varToValues.get(obj.o).values;
for (Pair<Object, Unit> value : values1) {
if (values2.contains(value)) {
destValues.add(value);
}
}
if (!destValues.isEmpty()) {
AbstractValue n = new AbstractValue();
n.o = obj.o;
n.values = destValues;
dest.add(n);
}
}
}
}
@Override
public boolean contains(AbstractValue obj) {
for (Object o : this.varToValues.keySet()) {
if (o.equals(obj.o)) {
return true;
}
}
return false;
}
@Override
public Iterator<AbstractValue> iterator() {
return this.varToValues.values().iterator();
}
@Override
public List<AbstractValue> toList() {
return (List<AbstractValue>) this.varToValues.values();
}
}
| 3,730 | Java | .java | hluwa/PrivacyDog | 38 | 3 | 0 | 2020-07-23T02:26:35Z | 2023-03-26T15:24:13Z |
PrivacyDog.java | /FileExtraction/Java_unseen/hluwa_PrivacyDog/src/main/java/PrivacyDog.java | import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.lingala.zip4j.ZipFile;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.ParseException;
import soot.G;
import soot.PackManager;
import soot.Scene;
import soot.Transform;
import soot.options.Options;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.logging.Logger;
public class PrivacyDog {
static String targetPath = "";
static String outputPath = null;
static String ruleFilePath = "privacydog.json";
private static Rule[] rules;
private static final Logger logger = Logger.getLogger("PrivacyDog");
private static void setupSoot(String taskPath) throws IOException {
G.reset();
Options.v().set_wrong_staticness(Options.wrong_staticness_ignore);
Options.v().set_allow_phantom_refs(true);
Options.v().set_allow_phantom_elms(true);
Options.v().set_ignore_resolving_levels(true);
Options.v().set_ignore_resolution_errors(true);
Options.v().set_no_bodies_for_excluded(true);
Options.v().set_whole_program(false);
Options.v().set_coffi(true);
Options.v().set_throw_analysis(Options.throw_analysis_dalvik);
Options.v().set_soot_classpath(Scene.defaultJavaClassPath());
Options.v().setPhaseOption("cg", "all-reachable:true");
Options.v().setPhaseOption("jb.dae", "enabled:false");
Options.v().setPhaseOption("jb.uce", "enabled:false");
Options.v().setPhaseOption("jj.dae", "enabled:false");
Options.v().setPhaseOption("jj.uce", "enabled:false");
Options.v().setPhaseOption("jtp.dae", "enabled:false");
Options.v().setPhaseOption("jtp.uce", "enabled:false");
if (taskPath.endsWith(".apk") || taskPath.endsWith(".dex")) {
Options.v().set_src_prec(Options.src_prec_apk);
Options.v().set_process_multiple_dex(true);
}
if (taskPath.endsWith(".aar")) {
List<String> processList = new ArrayList<>();
ZipFile zipFile = new ZipFile(taskPath);
Path tempPath = Files.createTempDirectory(null);
zipFile.extractAll(tempPath.toString());
for (File file : Objects.requireNonNull(new File(tempPath.toString()).listFiles())) {
if (isCodeFile(file)) {
processList.add(file.getPath());
}
}
Options.v().set_process_dir(processList);
} else {
Options.v().set_process_dir(Collections.singletonList(taskPath));
}
Scene.v().loadNecessaryClasses();
}
private static void setupRule() {
File ruleFile = new File(ruleFilePath);
if (!ruleFile.exists()) {
logger.warning("Unable to found rule file,Using inner default rules.");
try {
InputStream assetStream = PrivacyDog.class.getClassLoader().getResourceAsStream("privacydog.json");
assert assetStream != null;
rules = new Gson().fromJson(new InputStreamReader(assetStream), Rule[].class);
} catch (Exception e) {
logger.warning("Can't read rules from assets.");
}
return;
}
try {
rules = new Gson().fromJson(new FileReader(ruleFile), Rule[].class);
} catch (Exception e) {
logger.warning("Parse rule fatal: " + e.toString());
}
}
public static boolean isCodeFile(File file) {
return file.isFile() && (file.getName().endsWith(".jar")
|| file.getName().endsWith(".apk")
|| file.getName().endsWith(".dex")
|| file.getName().endsWith(".aar"));
}
public static void main(String[] args) {
CommandLineParser parser = new DefaultParser();
org.apache.commons.cli.Options options = new org.apache.commons.cli.Options();
options.addOption("t", "target", true, "target file or folder path;");
options.addOption("r", "rule", true, "rule file path, default is 'privacydog.json';");
options.addOption("o", "output", true, "output json to folder;");
try {
CommandLine commandLine = parser.parse(options, args);
if (!commandLine.hasOption("t")) {
System.err.println("Please input target path from '-t' option.");
return;
}
targetPath = commandLine.getOptionValue("t");
if (commandLine.hasOption("r")) {
ruleFilePath = commandLine.getOptionValue("r");
}
if (commandLine.hasOption("o")) {
String o = commandLine.getOptionValue("o");
if (!(new File(o).exists() && new File(o).isDirectory())) {
System.err.println("Output need directory path;");
return;
}
outputPath = o;
}
} catch (ParseException e) {
e.printStackTrace();
}
setupRule();
if (rules == null || rules.length == 0) {
logger.warning("The rule is empty");
return;
}
File targetPath = new File(PrivacyDog.targetPath);
if (!targetPath.exists()) {
logger.warning("The target path is not exists");
return;
}
List<File> files = new ArrayList<>();
if (targetPath.isDirectory()) {
for (File file : Objects.requireNonNull(new File(PrivacyDog.targetPath).listFiles())) {
if (isCodeFile(file)) {
files.add(file);
}
}
} else if (isCodeFile(targetPath)) {
files.add(targetPath);
}
for (File file : files) {
System.out.println("\n" + file.getName());
try {
setupSoot(file.getPath());
} catch (IOException e) {
e.printStackTrace();
continue;
}
PrivacyDetectionTransformer transformer = new PrivacyDetectionTransformer(rules);
PackManager.v().getPack("jtp").add(new Transform("jtp.privacy_detection", transformer));
PackManager.v().runPacks();
Map<Rule, List<StmtLocation>> resultMap = transformer.getResultMap();
Map<String, Map<String, List<String>>> jsonObject = new HashMap<>();
for (Rule rule : resultMap.keySet()) {
System.out.println("\t" + rule.getName());
Map<String, List<String>> locationMap = new HashMap<>();
jsonObject.put(rule.getName(), locationMap);
List<StmtLocation> locations = resultMap.get(rule);
locations.sort(Comparator.comparing(StmtLocation::getClassName));
for (StmtLocation location : locations) {
System.out.printf("\t\t%s->%s :%s%n",
location.getBody().getMethod().getDeclaringClass().getName(),
location.getBody().getMethod().getName(),
location.getStmt());
String locationSig = String.format("%s->%s", location.getBody().getMethod().getDeclaringClass().getName(), location.getBody().getMethod().getName());
if (!locationMap.containsKey(locationSig)) {
locationMap.put(locationSig, new ArrayList<>());
}
locationMap.get(locationSig).add(location.getStmt().toString());
}
}
String jsonData = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create().toJson(jsonObject);
System.out.println(jsonData);
if (outputPath != null) {
try {
FileWriter writer = new FileWriter(new File(outputPath, file.getName() + ".json"));
writer.write(jsonData);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
| 8,277 | Java | .java | hluwa/PrivacyDog | 38 | 3 | 0 | 2020-07-23T02:26:35Z | 2023-03-26T15:24:13Z |
PrivacyDetectionTransformer.java | /FileExtraction/Java_unseen/hluwa_PrivacyDog/src/main/java/PrivacyDetectionTransformer.java | import soot.Body;
import soot.BodyTransformer;
import soot.Unit;
import soot.Value;
import soot.jimple.*;
import soot.toolkits.scalar.Pair;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.util.regex.Pattern.CASE_INSENSITIVE;
import static soot.util.cfgcmd.CFGGraphType.EXCEPTIONAL_UNIT_GRAPH;
public class PrivacyDetectionTransformer extends BodyTransformer {
private Rule[] rules;
private final List<Pair<StmtLocation, Rule>> result = new ArrayList<>();
private final Map<Rule, List<StmtLocation>> resultMap = new HashMap<>();
public PrivacyDetectionTransformer(Rule[] rules) {
this.rules = rules;
}
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
if (rules == null || rules.length == 0) {
return;
}
DefinitionsAnalysis vsa = null;
for (Unit unit : b.getUnits()) {
if (unit == null) {
continue;
}
StmtLocation stmtLocation = new StmtLocation((Stmt) unit, b);
for (Rule rule : rules) {
for (Condition condition : rule.getConditions()) {
if (!verifyStringPattern((Stmt) unit, condition)) {
continue;
}
if (condition.isInvokeCondition()) {
if (!((Stmt) unit).containsInvokeExpr()) {
continue;
}
InvokeExpr invokeExpr = ((Stmt) unit).getInvokeExpr();
if (!verifyClass(invokeExpr, condition)
|| !verifyMethod(invokeExpr, condition)) {
continue;
}
if (vsa == null) {
vsa = new DefinitionsAnalysis(EXCEPTIONAL_UNIT_GRAPH.buildGraph(b));
}
if (!verifyArguments(invokeExpr, condition, (Stmt) unit, vsa)) {
continue;
}
}
result.add(new Pair<>(stmtLocation, rule));
if (!resultMap.containsKey(rule)) {
resultMap.put(rule, new ArrayList<>());
}
resultMap.get(rule).add(stmtLocation);
break;
}
}
}
}
private boolean verifyStringPattern(Stmt statement, Condition condition) {
return condition.getStringPattern() == null || Pattern.compile(condition.getStringPattern()).matcher(statement.toString()).find();
}
private boolean verifyClass(InvokeExpr invokeExpr, Condition condition) {
String invokeClassName = invokeExpr.getMethod().getDeclaringClass().getName();
if (condition.getClassName() != null) {
if (condition.getClassName().equals(invokeClassName)) {
return true;
} else if (condition.getClassPattern() == null) {
return false;
}
}
if (condition.getClassPattern() != null) {
Pattern pattern = Pattern.compile(condition.getClassPattern(), CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(invokeClassName);
return matcher.find();
}
return true;
}
private boolean verifyMethod(InvokeExpr invokeExpr, Condition condition) {
String invokeMethodName = invokeExpr.getMethod().getName();
if (condition.getMethodName() != null) {
if (condition.getMethodName().equals(invokeMethodName)) {
return true;
} else if (condition.getMethodPattern() == null) {
return false;
}
}
if (condition.getMethodPattern() != null) {
Pattern pattern = Pattern.compile(condition.getMethodPattern(), CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(invokeMethodName);
return matcher.find();
}
return true;
}
private boolean verifyArguments(InvokeExpr invokeExpr, Condition condition, Stmt stmt, DefinitionsAnalysis vsa) {
if (condition.getParamsCount() != -1 && condition.getParamsCount() != invokeExpr.getArgCount()) {
return false;
}
if (condition.getArguments() != null && condition.getArguments().size() != 0) {
for (int argIndex : condition.getArguments().keySet()) {
if (argIndex >= invokeExpr.getArgCount()) {
return false;
}
boolean matches = false;
Pattern pattern = Pattern.compile(condition.getArguments().get(argIndex));
Value value = invokeExpr.getArg(argIndex);
if (value instanceof Constant) {
Matcher matcher = pattern.matcher(value.toString());
if (matcher.find()) {
continue;
}
}
List<Pair<Object, Unit>> valuePairs = vsa.solveOf(stmt, value, true);
for (Pair<Object, Unit> pair : valuePairs) {
Object maybeValue = pair.getO1();
String maybeValueString;
if (maybeValue instanceof StringConstant) {
maybeValueString = ((StringConstant) maybeValue).value;
} else if (maybeValue instanceof IntConstant) {
maybeValueString = String.valueOf(((IntConstant) maybeValue).value);
} else {
maybeValueString = maybeValue.toString();
}
Matcher matcher = pattern.matcher(maybeValueString);
matches = matcher.find();
if (matches) {
break;
}
}
if (!matches) {
return false;
}
}
}
return true;
}
public Rule[] getRules() {
return rules;
}
public void setRules(Rule[] rules) {
this.rules = rules;
}
public List<Pair<StmtLocation, Rule>> getResult() {
return result;
}
public Map<Rule, List<StmtLocation>> getResultMap() {
return resultMap;
}
}
class StmtLocation {
private Stmt stmt;
private Body body;
StmtLocation(Stmt stmt, Body body) {
this.stmt = stmt;
this.body = body;
}
public Stmt getStmt() {
return stmt;
}
public void setStmt(Stmt stmt) {
this.stmt = stmt;
}
public Body getBody() {
return body;
}
public void setBody(Body body) {
this.body = body;
}
public String getClassName() {
try {
return this.getBody().getMethod().getDeclaringClass().getName();
} catch (Exception e) {
return "";
}
}
}
| 7,136 | Java | .java | hluwa/PrivacyDog | 38 | 3 | 0 | 2020-07-23T02:26:35Z | 2023-03-26T15:24:13Z |
ExampleUnitTest.java | /FileExtraction/Java_unseen/freenet-mobile_app/app/src/test/java/org/freenetproject/mobile/ExampleUnitTest.java | package org.freenetproject.mobile;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | 386 | Java | .java | freenet-mobile/app | 123 | 14 | 33 | 2020-06-20T04:14:03Z | 2024-04-06T18:03:20Z |
App.java | /FileExtraction/Java_unseen/freenet-mobile_app/app/src/main/java/org/freenetproject/mobile/App.java | package org.freenetproject.mobile;
import android.app.Application;
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
}
}
| 186 | Java | .java | freenet-mobile/app | 123 | 14 | 33 | 2020-06-20T04:14:03Z | 2024-04-06T18:03:20Z |
BatteryLevelReceiver.java | /FileExtraction/Java_unseen/freenet-mobile_app/app/src/main/java/org/freenetproject/mobile/receivers/BatteryLevelReceiver.java | package org.freenetproject.mobile.receivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import org.freenetproject.mobile.services.node.Manager;
public class BatteryLevelReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Log.i("Freenet", "Stopping service from low battery level");
Manager.getInstance().stopService(context);
}
}
| 504 | Java | .java | freenet-mobile/app | 123 | 14 | 33 | 2020-06-20T04:14:03Z | 2024-04-06T18:03:20Z |
PowerConnectionReceiver.java | /FileExtraction/Java_unseen/freenet-mobile_app/app/src/main/java/org/freenetproject/mobile/receivers/PowerConnectionReceiver.java | package org.freenetproject.mobile.receivers;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import org.freenetproject.mobile.services.node.Manager;
import java.util.Objects;
public class PowerConnectionReceiver extends BroadcastReceiver {
@SuppressLint("UnsafeProtectedBroadcastReceiver")
@Override
public void onReceive(Context context, Intent intent) {
Log.d("Freenet", "onReceive");
// only if configured to manage start/stop
switch(Objects.requireNonNull(intent.getAction())){
case Intent.ACTION_POWER_CONNECTED:
Log.i("Freenet", "Resuming service from power change");
new Thread(() -> {
Manager.getInstance().resumeService(context, Manager.CONTEXT_BATTERY);
}).start();
break;
case Intent.ACTION_POWER_DISCONNECTED:
Log.i("Freenet", "Pausing service from power change");
new Thread(() -> {
Manager.getInstance().pauseService(context, Manager.CONTEXT_BATTERY);
}).start();
break;
}
}
}
| 1,259 | Java | .java | freenet-mobile/app | 123 | 14 | 33 | 2020-06-20T04:14:03Z | 2024-04-06T18:03:20Z |
MainViewModel.java | /FileExtraction/Java_unseen/freenet-mobile_app/app/src/main/java/org/freenetproject/mobile/ui/main/viewmodel/MainViewModel.java | package org.freenetproject.mobile.ui.main.viewmodel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;
import org.freenetproject.mobile.services.node.Manager;
/**
* Class responsible for exposing data to the UI. It also exposes methods for the UI to interact with,
* such as startService and stopService.
*/
public class MainViewModel extends ViewModel {
Manager manager = Manager.getInstance();
private LiveData<Manager.Status> status = manager.getStatus();
public MainViewModel() {
super();
}
}
| 552 | Java | .java | freenet-mobile/app | 123 | 14 | 33 | 2020-06-20T04:14:03Z | 2024-04-06T18:03:20Z |
MainFragment.java | /FileExtraction/Java_unseen/freenet-mobile_app/app/src/main/java/org/freenetproject/mobile/ui/main/activity/MainFragment.java | package org.freenetproject.mobile.ui.main.activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.google.common.collect.ImmutableMap;
import org.freenetproject.mobile.BuildConfig;
import org.freenetproject.mobile.R;
import org.freenetproject.mobile.services.node.Manager;
import org.freenetproject.mobile.ui.about.activity.AboutActivity;
import org.freenetproject.mobile.ui.bootstrap.activity.BootstrapActivity;
import org.freenetproject.mobile.ui.acknowledgement.activity.AcknowledgementActivity;
import org.freenetproject.mobile.ui.acknowledgement.activity.AcknowledgementFragment;
import org.freenetproject.mobile.ui.main.viewmodel.MainViewModel;
import org.freenetproject.mobile.ui.notification.Notification;
import org.freenetproject.mobile.ui.settings.activity.SettingsActivity;
import java.util.Map;
public class MainFragment extends Fragment {
static final Map<Integer, Integer> STATUS_ACTION_MAP = ImmutableMap.<Integer, Integer>builder()
.put(Manager.Status.STARTED.ordinal(), R.drawable.ic_baseline_power_settings_new_24)
.put(Manager.Status.PAUSED.ordinal(), R.drawable.ic_baseline_power_settings_new_24)
.put(Manager.Status.STOPPED.ordinal(), R.drawable.ic_baseline_play_circle_outline_24)
.put(Manager.Status.ERROR.ordinal(), R.drawable.ic_baseline_replay_24)
.build();
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
SharedPreferences prefs = getContext().getSharedPreferences(
getContext().getPackageName(), Context.MODE_PRIVATE
);
if (!prefs.getBoolean(AcknowledgementFragment.ACKNOWLEDGEMENT_KEY, false)) {
startActivity(new Intent(getContext(), AcknowledgementActivity.class));
}
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main, container, false);
}
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
new ViewModelProvider(requireActivity()).get(MainViewModel.class);
Manager manager = Manager.getInstance();
updateSharedPreferences(manager, view);
updateSettings(manager, view);
updateAbout(manager, view);
updateControls(manager, view);
updateStatus(manager, view);
updateStatusDetail(manager, view);
}
private void updateControls(Manager m, View view) {
Button controlButton = view.findViewById(R.id.control_button);
controlButton.setOnClickListener(view1 -> {
new Thread(() -> {
// Return right aways if for some reason it is still working (either
// starting up or stopping).
if (m.isTransitioning()) {
return;
}
// When running or paused the node can be shutdown,but it can not
// be paused or started.
if (m.isStopped()) {
m.startService(view.getContext());
} else if (m.isRunning() || m.isPaused()) {
m.restartService(view.getContext());
} else if (m.hasError()) {
m.resetService(view.getContext());
}
}).start();
});
m.getStatus().observe(getViewLifecycleOwner(), status -> {
controlButton
.setEnabled(
!m.isTransitioning()
);
controlButton.setBackgroundResource(
STATUS_ACTION_MAP.containsKey(m.getStatus().getValue().ordinal()) ?
STATUS_ACTION_MAP.get(m.getStatus().getValue().ordinal()) :
R.drawable.ic_baseline_play_circle_outline_24
);
});
}
private void updateStatus(Manager m, View view) {
TextView statusText = view.findViewById(R.id.node_status);
m.getStatus().observe(getViewLifecycleOwner(), status -> {
if (status.equals(Manager.Status.STARTED)) {
statusText.setText(R.string.node_running);
} else if (status.equals(Manager.Status.STARTING_UP)) {
statusText.setText(R.string.node_starting_up);
} else if (status.equals(Manager.Status.PAUSED)) {
statusText.setText(R.string.node_paused);
} else if (status.equals(Manager.Status.STOPPING)) {
statusText.setText(R.string.node_shutting_down);
} else if (status.equals(Manager.Status.ERROR)) {
statusText.setText(R.string.error_starting_up);
} else {
statusText.setText(getString(R.string.app_version, BuildConfig.VERSION_NAME));
}
});
}
private void updateStatusDetail(Manager m, View view) {
TextView detailText = view.findViewById(R.id.node_status_detail);
m.getStatus().observe(getViewLifecycleOwner(), status -> {
detailText.setOnClickListener(null);
if (status.equals(Manager.Status.STARTED)) {
detailText.setText(R.string.tap_to_navigate);
detailText.setOnClickListener(view12 -> {
startActivity(
new Intent(getContext(), BootstrapActivity.class)
);
});
} else if (status.equals(Manager.Status.STARTING_UP)) {
detailText.setText(R.string.may_take_a_while);
} else if (status.equals(Manager.Status.ERROR)) {
detailText.setText(R.string.error_detail);
} else {
detailText.setText("");
}
});
}
private void updateSharedPreferences(Manager m, View view) {
SharedPreferences sharedPref = requireActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
m.getStatus().observe(getViewLifecycleOwner(), status -> {
editor.putInt("status", m.getStatus().getValue().ordinal());
editor.apply();
});
}
private void updateSettings(Manager m, View view) {
Button settings = view.findViewById(R.id.settings_button);
settings.setOnClickListener(view1 -> {
startActivity(new Intent(getActivity(), SettingsActivity.class));
});
}
private void updateAbout(Manager m, View view) {
Button settings = view.findViewById(R.id.about_button);
settings.setOnClickListener(view1 -> {
startActivity(new Intent(getActivity(), AboutActivity.class));
});
}
} | 7,077 | Java | .java | freenet-mobile/app | 123 | 14 | 33 | 2020-06-20T04:14:03Z | 2024-04-06T18:03:20Z |
MainActivity.java | /FileExtraction/Java_unseen/freenet-mobile_app/app/src/main/java/org/freenetproject/mobile/ui/main/activity/MainActivity.java | package org.freenetproject.mobile.ui.main.activity;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import org.freenetproject.mobile.R;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PreferenceManager.setDefaultValues(this, R.xml.root_preferences, false);
}
@Override
public void onStop() {
super.onStop();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
} | 1,376 | Java | .java | freenet-mobile/app | 123 | 14 | 33 | 2020-06-20T04:14:03Z | 2024-04-06T18:03:20Z |
Notification.java | /FileExtraction/Java_unseen/freenet-mobile_app/app/src/main/java/org/freenetproject/mobile/ui/notification/Notification.java | package org.freenetproject.mobile.ui.notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import org.freenetproject.mobile.R;
import org.freenetproject.mobile.services.node.Manager;
import org.freenetproject.mobile.ui.main.activity.MainActivity;
import java.util.Observer;
/**
* Class responsible for creating the notification in order to be able to run Freenet on background.
*/
public class Notification {
private static android.app.Notification.Builder builder;
private static NotificationManager nm;
private static Manager manager = Manager.getInstance();
private static final String CHANNEL_ID = "FREENET SERVICE";
/**
* Create a notification to remain on background.
*
* @param context Application context
* @return
*/
public static android.app.Notification show(Context context) {
nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel nc = null;
nc = new NotificationChannel(CHANNEL_ID, context.getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH);
nc.setDescription(context.getString(R.string.app_name));
nc.enableLights(true);
nc.setLightColor(Color.BLUE);
nm.createNotificationChannel(nc);
}
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
builder = new android.app.Notification.Builder(context);
} else {
builder = new android.app.Notification.Builder(context, CHANNEL_ID);
}
builder
.setContentTitle(context.getString(R.string.node_running))
.setContentText(context.getString(R.string.connected_to_the_network))
.setSmallIcon(R.drawable.ic_freenet_logo_notification)
.setContentIntent(
PendingIntent.getActivity(
context,
0,
new Intent(
context.getApplicationContext(), MainActivity.class
),
PendingIntent.FLAG_UPDATE_CURRENT
)
);
manager.getStatus().observeForever(status -> {
if (status.equals(Manager.Status.STARTED)) {
builder.setContentTitle(context.getString(R.string.node_running));
builder.setContentText(context.getString(R.string.connected_to_the_network));
} else if (status.equals(Manager.Status.PAUSED)) {
builder.setContentTitle(context.getString(R.string.node_paused));
builder.setContentText(context.getString(R.string.battery_and_data));
} else if (status.equals(Manager.Status.ERROR)) {
builder.setContentTitle(context.getString(R.string.error_starting_up));
builder.setContentText(context.getString(R.string.error_detail));
}
nm.notify(1, builder.build());
});
return builder.build();
}
/**
* Removes all notifications.
* @param context
*/
public static void remove(Context context) {
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancelAll();
}
}
| 3,547 | Java | .java | freenet-mobile/app | 123 | 14 | 33 | 2020-06-20T04:14:03Z | 2024-04-06T18:03:20Z |
SettingsActivity.java | /FileExtraction/Java_unseen/freenet-mobile_app/app/src/main/java/org/freenetproject/mobile/ui/settings/activity/SettingsActivity.java | package org.freenetproject.mobile.ui.settings.activity;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.format.Formatter;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.SwitchPreferenceCompat;
import org.freenetproject.mobile.R;
import org.freenetproject.mobile.proxy.Simple;
public class SettingsActivity extends AppCompatActivity {
private static String localIp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
localIp = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
}
public static class SettingsFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
SwitchPreferenceCompat editPref = findPreference("web_access");
editPref.setSummary(
getActivity().getApplicationContext().getString(
R.string.web_access_summary,
localIp,
Simple.defaultLocalPort
)
);
}
}
} | 1,831 | Java | .java | freenet-mobile/app | 123 | 14 | 33 | 2020-06-20T04:14:03Z | 2024-04-06T18:03:20Z |
BootstrapActivity.java | /FileExtraction/Java_unseen/freenet-mobile_app/app/src/main/java/org/freenetproject/mobile/ui/bootstrap/activity/BootstrapActivity.java | package org.freenetproject.mobile.ui.bootstrap.activity;
import android.os.Bundle;
import android.webkit.WebView;
import androidx.appcompat.app.AppCompatActivity;
import org.freenetproject.mobile.R;
public class BootstrapActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bootstrap);
WebView wv = (WebView) findViewById(R.id.bootstrap_webview);
wv.loadUrl("file:///android_asset/index.html");
}
}
| 566 | Java | .java | freenet-mobile/app | 123 | 14 | 33 | 2020-06-20T04:14:03Z | 2024-04-06T18:03:20Z |
AcknowledgementFragment.java | /FileExtraction/Java_unseen/freenet-mobile_app/app/src/main/java/org/freenetproject/mobile/ui/acknowledgement/activity/AcknowledgementFragment.java | package org.freenetproject.mobile.ui.acknowledgement.activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.fragment.app.Fragment;
import org.freenetproject.mobile.R;
import org.freenetproject.mobile.ui.main.activity.MainActivity;
public class AcknowledgementFragment extends Fragment {
private SharedPreferences prefs;
public static final String ACKNOWLEDGEMENT_KEY = "acknowledgement";
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
prefs = getContext().getSharedPreferences(
getContext().getPackageName(), Context.MODE_PRIVATE
);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_acknowledgement, container, false);
}
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
AppCompatCheckBox acknowledgement = view.findViewById(R.id.acknowledgement);
acknowledgement.setText(Html.fromHtml(getString(R.string.acknowledgement_text)));
acknowledgement.setMovementMethod(LinkMovementMethod.getInstance());
acknowledgement.setOnCheckedChangeListener((buttonView, isChecked) -> {
prefs.edit()
.putBoolean(ACKNOWLEDGEMENT_KEY, isChecked)
.apply();
if (isChecked) {
activateMainActivity();
}
});
}
private void activateMainActivity() {
Intent intent = new Intent(getContext(), MainActivity.class);
startActivity(intent);
}
} | 2,008 | Java | .java | freenet-mobile/app | 123 | 14 | 33 | 2020-06-20T04:14:03Z | 2024-04-06T18:03:20Z |
AcknowledgementActivity.java | /FileExtraction/Java_unseen/freenet-mobile_app/app/src/main/java/org/freenetproject/mobile/ui/acknowledgement/activity/AcknowledgementActivity.java | package org.freenetproject.mobile.ui.acknowledgement.activity;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.fragment.app.Fragment;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.SwitchPreferenceCompat;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.View;
import org.freenetproject.mobile.R;
import org.freenetproject.mobile.proxy.Simple;
import org.freenetproject.mobile.ui.main.activity.MainActivity;
import org.freenetproject.mobile.ui.settings.activity.SettingsActivity;
public class AcknowledgementActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_acknowledgement);
}
} | 969 | Java | .java | freenet-mobile/app | 123 | 14 | 33 | 2020-06-20T04:14:03Z | 2024-04-06T18:03:20Z |
AboutActivity.java | /FileExtraction/Java_unseen/freenet-mobile_app/app/src/main/java/org/freenetproject/mobile/ui/about/activity/AboutActivity.java | package org.freenetproject.mobile.ui.about.activity;
import android.os.Bundle;
import android.webkit.WebView;
import androidx.appcompat.app.AppCompatActivity;
import org.freenetproject.mobile.BuildConfig;
import org.freenetproject.mobile.R;
import freenet.node.Version;
public class AboutActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
WebView wv = (WebView) findViewById(R.id.about_webview);
wv.loadData(
getResources().getString(
R.string.text_about,
BuildConfig.VERSION_NAME,
Version.publicVersion(),
String.valueOf(Version.buildNumber())
),
"text/html; charset=utf-8",
null
);
}
} | 932 | Java | .java | freenet-mobile/app | 123 | 14 | 33 | 2020-06-20T04:14:03Z | 2024-04-06T18:03:20Z |
Simple.java | /FileExtraction/Java_unseen/freenet-mobile_app/app/src/main/java/org/freenetproject/mobile/proxy/Simple.java | package org.freenetproject.mobile.proxy;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* From: https://resources.oreilly.com/examples/9781565923713/blob/master/SimpleProxyServer.java
*/
public class Simple implements Runnable {
public static int defaultLocalPort = 9999;
public void run(String remotehost, int remoteport, int localport) throws IOException {
// Create a ServerSocket to listen for connections with
ServerSocket ss = new ServerSocket(localport);
// Create buffers for client-to-server and server-to-client communication.
// We make one final so it can be used in an anonymous class below.
// Note the assumptions about the volume of traffic in each direction...
final byte[] request = new byte[1024];
byte[] reply = new byte[4096];
// This is a server that never returns, so enter an infinite loop.
while (true) {
// Variables to hold the sockets to the client and to the server.
Socket client = null, server = null;
try {
// Wait for a connection on the local port
client = ss.accept();
// Get client streams. Make them final so they can
// be used in the anonymous thread below.
final InputStream from_client = client.getInputStream();
final OutputStream to_client = client.getOutputStream();
// Make a connection to the real server
// If we cannot connect to the server, send an error to the
// client, disconnect, then continue waiting for another connection.
try {
server = new Socket(remotehost, remoteport);
} catch (IOException e) {
client.close();
continue;
}
// Get server streams.
final InputStream from_server = server.getInputStream();
final OutputStream to_server = server.getOutputStream();
// Make a thread to read the client's requests and pass them to the
// server. We have to use a separate thread because requests and
// responses may be asynchronous.
Thread t = new Thread() {
public void run() {
int bytes_read;
try {
while ((bytes_read = from_client.read(request)) != -1) {
to_server.write(request, 0, bytes_read);
to_server.flush();
}
} catch (IOException ignored) {
}
// the client closed the connection to us, so close our
// connection to the server. This will also cause the
// server-to-client loop in the main thread exit.
try {
to_server.close();
} catch (IOException e) {
}
}
};
// Start the client-to-server request thread running
t.start();
// Meanwhile, in the main thread, read the server's responses
// and pass them back to the client. This will be done in
// parallel with the client-to-server request thread above.
int bytes_read;
try {
while ((bytes_read = from_server.read(reply)) != -1) {
to_client.write(reply, 0, bytes_read);
to_client.flush();
}
} catch (IOException ignored) {
}
// The server closed its connection to us, so close our
// connection to our client. This will make the other thread exit.
to_client.close();
} catch (IOException e) {
System.err.println(e);
}
// Close the sockets no matter what happens each time through the loop.
finally {
try {
if (server != null) server.close();
if (client != null) client.close();
} catch (IOException ignored) {
}
}
}
}
@Override
public void run() {
Log.d("Freenet", "Proxy thread started");
try {
run("127.0.0.1", 8888, defaultLocalPort);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 4,801 | Java | .java | freenet-mobile/app | 123 | 14 | 33 | 2020-06-20T04:14:03Z | 2024-04-06T18:03:20Z |
Manager.java | /FileExtraction/Java_unseen/freenet-mobile_app/app/src/main/java/org/freenetproject/mobile/services/node/Manager.java | package org.freenetproject.mobile.services.node;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.util.Log;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import com.jakewharton.processphoenix.ProcessPhoenix;
import org.freenetproject.mobile.R;
import org.freenetproject.mobile.ui.main.activity.MainActivity;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import org.freenetproject.mobile.Runner;
import org.freenetproject.mobile.Installer;
/**
* Class responsible for exposing data to the UI. It also exposes methods for the UI to interact with,
* such as startService and stopService.
*/
public class Manager {
private static Manager instance = null;
private final Runner runner = Runner.getInstance();
public enum Status {
STARTING_UP,
STARTED,
STOPPING,
STOPPED,
ERROR,
INSTALLING,
PAUSED,
PAUSING // when adding a new state that has transitions be sure to update isTransitioning method
}
public static final String CONTEXT_NETWORK = "network";
public static final String CONTEXT_BATTERY = "battery";
private Map<String, Boolean> contextRunFlag = new HashMap<String, Boolean>() {{
put(CONTEXT_NETWORK, true);
put(CONTEXT_BATTERY, true);
}};
private MutableLiveData<Status> status = new MutableLiveData<Status>();
private Manager() {
status.postValue(
runner.isStarted() ? Status.STARTED : Status.STOPPED
);
}
public static Manager getInstance() {
if (instance == null) {
instance = new Manager();
}
return instance;
}
public LiveData<Status> getStatus() {
return status;
}
/**
* Start the service through the Runner class. Also install the node if it's not already installed.
*
* On one hand it starts the actual node through the Runner class and on the other hand it starts
* the Services.Node.Service service to be able to keep running on the background.
*
* Checks if the node is installed and install it otherwise.
*
* @param context Application context.
* @return
*/
public int startService(Context context) {
if (!Installer.getInstance().isInstalled()) {
status.postValue(Status.INSTALLING);
try {
Resources res = context.getResources();
Installer.getInstance().install(
context.getDir("data", Context.MODE_PRIVATE).getAbsolutePath(),
res.openRawResource(R.raw.seednodes),
res.openRawResource(R.raw.freenet),
res.openRawResource(R.raw.bookmarks),
res.getConfiguration().locale.getDisplayLanguage()
);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
int ret = startNode();
if (ret == 0) {
Intent serviceIntent = new Intent(context, Service.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(serviceIntent);
} else {
context.startService(serviceIntent);
}
} else {
Log.e("Freenet", "Error starting freenet (" + ret + ")");
status.postValue(Status.ERROR);
}
return 0;
}
private int startNode() {
status.postValue(Status.STARTING_UP);
int ret = -1;
try {
ret = runner.start(new String[]{Installer.getInstance().getFreenetIniPath()});
if (ret == 0) {
status.postValue(Status.STARTED);
} else if (ret == -1) {
// Already running
status.postValue(Status.STARTED);
} else {
status.postValue(Status.ERROR);
}
} catch (Exception e) {
status.postValue(Status.ERROR);
}
return ret;
}
/**
* Stops the service through the Runner class. Also stops the Services.Node.Service.
*
* @param context Application context.
* @return
*/
public int stopService(Context context) {
Intent serviceIntent = new Intent(context, Service.class);
context.stopService(serviceIntent);
try {
if (runner.stop() != 0) {
status.postValue(Status.ERROR);
}
status.postValue(Status.STOPPED);
} catch (Exception e) {
status.postValue(Status.ERROR);
}
return 0;
}
/**
* Stop the node and restart the application.
*
* @param context
* @return
*/
public int restartService(Context context) {
stopService(context);
Log.i("Freenet", "Calling rebirth");
ProcessPhoenix.triggerRebirth(
context,
new Intent(
context,
MainActivity.class
)
);
return 0;
}
/**
* Pauses the node running on the device while maintaining the service running on foreground.
*
* @param context
* @return
*/
public int pauseService(Context context, String serviceContext) {
if (isPaused()) {
return -1;
}
contextRunFlag.put(serviceContext, false);
status.postValue(Status.PAUSING);
try {
if (runner.pause() == 0) {
status.postValue(Status.PAUSED);
} else {
status.postValue(Status.ERROR);
}
} catch (Exception e) {
status.postValue(Status.ERROR);
}
return 0;
}
/**
* Starts up or resume a service.
*
* @param context
* @return
*/
public int resumeService(Context context, String serviceContext) {
if (!isPaused()) {
return -2;
}
contextRunFlag.put(serviceContext, true);
for (Boolean value : contextRunFlag.values()) {
if (!value)
return -3; // a given context has flagged not to run
}
status.postValue(Status.STARTING_UP);
try {
if (runner.resume() == 0) {
status.postValue(Status.STARTED);
} else {
status.postValue(Status.ERROR);
}
} catch (Exception e) {
status.postValue(Status.ERROR);
}
return 0;
}
public Boolean resetService(Context context) {
Intent serviceIntent = new Intent(context, Service.class);
context.stopService(serviceIntent);
try {
runner.stop();
} catch (Exception e) {
Log.e("Freenet", "Error stopping node: " + e.getMessage());
}
Log.i("Freenet", "Calling rebirth");
ProcessPhoenix.triggerRebirth(
context,
new Intent(
context,
MainActivity.class
)
);
return true;
}
public Boolean isStopped() {
return status.getValue().equals(Status.STOPPED);
}
public Boolean isPaused() {
return status.getValue().equals(Status.PAUSED);
}
public Boolean isRunning() {
return status.getValue().equals(Status.STARTED);
}
public Boolean hasError() {
return status.getValue().equals(Status.ERROR);
}
public Boolean isTransitioning() {
Status value = status.getValue();
return !value.equals(Status.STARTED)
&& !value.equals(Status.STOPPED)
&& !value.equals(Status.PAUSED);
}
}
| 7,907 | Java | .java | freenet-mobile/app | 123 | 14 | 33 | 2020-06-20T04:14:03Z | 2024-04-06T18:03:20Z |
Service.java | /FileExtraction/Java_unseen/freenet-mobile_app/app/src/main/java/org/freenetproject/mobile/services/node/Service.java | package org.freenetproject.mobile.services.node;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.os.IBinder;
import android.util.Log;
import androidx.preference.PreferenceManager;
import org.freenetproject.mobile.proxy.Simple;
import org.freenetproject.mobile.receivers.BatteryLevelReceiver;
import org.freenetproject.mobile.receivers.PowerConnectionReceiver;
import org.freenetproject.mobile.ui.notification.Notification;
public class Service extends android.app.Service {
PowerConnectionReceiver powerConnectionReceiver = new PowerConnectionReceiver();
ConnectivityManager connectivityManager;
ConnectivityManager.NetworkCallback networkCallback;
Thread proxyThread = null;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("Freenet", "Called service onStartCommand");
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
Boolean preserveBattery = sharedPreferences.getBoolean("preserve_battery", true);
// Register power connection receiver
if (preserveBattery) {
IntentFilter powerConnectedFilter = new IntentFilter();
powerConnectedFilter.addAction(Intent.ACTION_POWER_CONNECTED);
powerConnectedFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
registerReceiver(powerConnectionReceiver, powerConnectedFilter);
registerReceiver(new BatteryLevelReceiver(), new IntentFilter(
Intent.ACTION_BATTERY_LOW));
}
Boolean preserveData = sharedPreferences.getBoolean("preserve_data",true);
// Register network callback
if (preserveData) {
Context context = getApplicationContext();
NetworkRequest networkRequest = new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.build();
connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
Log.d("Freenet", "Resuming service from network change");
Manager.getInstance().resumeService(context, Manager.CONTEXT_NETWORK);
}
@Override
public void onLost(Network network) {
Log.d("Freenet", "Pausing service from network change");
Manager.getInstance().pauseService(context, Manager.CONTEXT_NETWORK);
}
};
connectivityManager.registerNetworkCallback(networkRequest, networkCallback);
}
Boolean webAccess = sharedPreferences.getBoolean("web_access",false);
if (webAccess) {
if (proxyThread != null) proxyThread.interrupt();
proxyThread = new Thread(new Simple(), "simple-proxy-server");
proxyThread.start();
}
startForeground(1, Notification.show(this));
return android.app.Service.START_STICKY;
}
@Override
public void onDestroy() {
Log.i("Freenet", "Stopping service");
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
Boolean preserveBattery = sharedPreferences.getBoolean("preserve_battery", true);
if (preserveBattery) unregisterReceiver(powerConnectionReceiver);
Boolean preserveData = sharedPreferences.getBoolean("preserve_data",true);
if (preserveData) connectivityManager.unregisterNetworkCallback(networkCallback);
Boolean webAccess = sharedPreferences.getBoolean("web_access",false);
if (webAccess) {
if (proxyThread != null) proxyThread.interrupt();
}
Notification.remove(getApplicationContext());
stopForeground(true);
stopSelf();
super.onDestroy();
}
public IBinder onBind(Intent intent) {
return null;
}
}
| 4,431 | Java | .java | freenet-mobile/app | 123 | 14 | 33 | 2020-06-20T04:14:03Z | 2024-04-06T18:03:20Z |
ManagementFactory.java | /FileExtraction/Java_unseen/freenet-mobile_app/app/src/main/java/java/lang/management/ManagementFactory.java | package java.lang.management;
/**
* Overwriting ManagementFactory to be able to run on 1492 on android where these
* libraries are missing and probably are not going to be added anything soon.
*/
public class ManagementFactory {
public static ThreadMXBean getThreadMXBean() {
return new ThreadMXBean();
}
}
| 327 | Java | .java | freenet-mobile/app | 123 | 14 | 33 | 2020-06-20T04:14:03Z | 2024-04-06T18:03:20Z |
ExampleInstrumentedTest.java | /FileExtraction/Java_unseen/freenet-mobile_app/app/src/androidTest/java/org/freenetproject/mobile/ExampleInstrumentedTest.java | package org.freenetproject.mobile;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("org.freenetproject.mobile", appContext.getPackageName());
}
} | 764 | Java | .java | freenet-mobile/app | 123 | 14 | 33 | 2020-06-20T04:14:03Z | 2024-04-06T18:03:20Z |
BEncoder.java | /FileExtraction/Java_unseen/CSEMike_OneSwarm-Community-Server/src/org/gudy/azureus2/core3/util/BEncoder.java | /*
* BEncoder.java
*
* Created on June 4, 2003, 10:17 PM
* Copyright (C) 2003, 2004, 2005, 2006 Aelitis, All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* AELITIS, SAS au capital de 46,603.30 euros
* 8 Allee Lenotre, La Grille Royale, 78600 Le Mesnil le Roi, France.
*/
package org.gudy.azureus2.core3.util;
import java.io.*;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.*;
//import org.gudy.azureus2.core3.xml.util.XUXmlWriter;
/**
* A set of utility methods to encode a Map into a bencoded array of byte.
* integer are represented as Long, String as byte[], dictionnaries as Map, and list as List.
*
* @author TdC_VgA
*/
public class
BEncoder
{
private static final int BUFFER_DOUBLE_LIMIT = 256*1024;
private static final byte[] MINUS_1_BYTES = "-1".getBytes();
public static byte[]
encode(
Map object )
throws IOException
{
return( encode( object, false ));
}
public static byte[]
encode(
Map object,
boolean url_encode )
throws IOException
{
BEncoder encoder = new BEncoder(url_encode);
encoder.encodeObject( object);
return( encoder.toByteArray());
}
private byte[] current_buffer = new byte[256];
private int current_buffer_pos = 0;
private byte[][] old_buffers;
private byte[] int_buffer = new byte[12];
private boolean url_encode;
private
BEncoder(
boolean _url_encode )
{
url_encode = _url_encode;
}
private void
encodeObject(
Object object)
throws IOException
{
if ( object instanceof String || object instanceof Float){
String tempString = (object instanceof String) ? (String)object : String.valueOf((Float)object);
ByteBuffer bb = ByteBuffer.wrap(tempString.getBytes("UTF-8"));
writeInt( bb.limit() );
writeChar(':');
writeByteBuffer(bb );
}else if(object instanceof Map){
Map tempMap = (Map)object;
SortedMap tempTree = null;
// unfortunately there are some occasions where we want to ensure that
// the 'key' of the map is not mangled by assuming its UTF-8 encodable.
// In particular the response from a tracker scrape request uses the
// torrent hash as the KEY. Hence the introduction of the type below
// to allow the constructor of the Map to indicate that the keys should
// be extracted using a BYTE_ENCODING
boolean byte_keys = object instanceof ByteEncodedKeyHashMap;
//write the d
writeChar('d');
//are we sorted?
if ( tempMap instanceof TreeMap ){
tempTree = (TreeMap)tempMap;
}else{
tempTree = new TreeMap(tempMap);
}
Iterator it = tempTree.entrySet().iterator();
while( it.hasNext()){
Map.Entry entry = (Map.Entry)it.next();
Object o_key = entry.getKey();
Object value = entry.getValue();
if ( value != null ){
if ( o_key instanceof byte[]){
encodeObject( o_key );
encodeObject( value );
}else{
String key = (String)o_key;
if ( byte_keys ){
try{
encodeObject( Charset.forName( "ISO-8859-1" ).encode(key));
encodeObject( tempMap.get(key));
}catch( UnsupportedEncodingException e ){
throw( new IOException( "BEncoder: unsupport encoding: " + e.getMessage()));
}
}else{
encodeObject( key ); // Key goes in as UTF-8
encodeObject( value);
}
}
}
}
writeChar('e');
}else if(object instanceof List){
List tempList = (List)object;
//write out the l
writeChar('l');
for(int i = 0; i<tempList.size(); i++){
encodeObject( tempList.get(i));
}
writeChar('e');
}else if(object instanceof Long){
Long tempLong = (Long)object;
//write out the l
writeChar('i');
writeLong(tempLong.longValue());
writeChar('e');
}else if(object instanceof Integer){
Integer tempInteger = (Integer)object;
//write out the l
writeChar('i');
writeInt(tempInteger.intValue());
writeChar('e');
}else if(object instanceof byte[]){
byte[] tempByteArray = (byte[])object;
writeInt(tempByteArray.length);
writeChar(':');
if ( url_encode ){
writeBytes(URLEncoder.encode(new String(tempByteArray, "UTF-8"), "UTF-8" ).getBytes());
}else{
writeBytes(tempByteArray);
}
}else if(object instanceof ByteBuffer ){
ByteBuffer bb = (ByteBuffer)object;
writeInt(bb.limit());
writeChar(':');
writeByteBuffer(bb);
}else if ( object == null ){
// ideally we'd bork here but I don't want to run the risk of breaking existing stuff so just log
System.err.println( "Attempt to encode a null value" );
}else{
System.err.println( "Attempt to encode an unsupported entry type: " + object.getClass() + ";value=" + object);
}
}
private void
writeChar(
char c )
{
int rem = current_buffer.length - current_buffer_pos;
if ( rem > 0 ){
current_buffer[current_buffer_pos++] = (byte)c;
}else{
int next_buffer_size = current_buffer.length < BUFFER_DOUBLE_LIMIT?(current_buffer.length << 1):(current_buffer.length + BUFFER_DOUBLE_LIMIT );
byte[] new_buffer = new byte[ next_buffer_size ];
new_buffer[ 0 ] = (byte)c;
if ( old_buffers == null ){
old_buffers = new byte[][]{ current_buffer };
}else{
byte[][] new_old_buffers = new byte[old_buffers.length+1][];
System.arraycopy( old_buffers, 0, new_old_buffers, 0, old_buffers.length );
new_old_buffers[ old_buffers.length ] = current_buffer;
old_buffers = new_old_buffers;
}
current_buffer = new_buffer;
current_buffer_pos = 1;
}
}
private void
writeInt(
int i )
{
// we get a bunch of -1 values, optimise
if ( i == -1 ){
writeBytes( MINUS_1_BYTES );
return;
}
int start = intToBytes( i );
writeBytes( int_buffer, start, 12 - start );
}
private void
writeLong(
long l )
{
if ( l <= Integer.MAX_VALUE && l >= Integer.MIN_VALUE ){
writeInt((int)l);
}else{
writeBytes(Long.toString( l ).getBytes());
}
}
private void
writeBytes(
byte[] bytes )
{
writeBytes( bytes, 0, bytes.length );
}
private void
writeBytes(
byte[] bytes,
int offset,
int length )
{
int rem = current_buffer.length - current_buffer_pos;
if ( rem >= length ){
System.arraycopy( bytes, offset, current_buffer, current_buffer_pos, length );
current_buffer_pos += length;
}else{
if ( rem > 0 ){
System.arraycopy( bytes, offset, current_buffer, current_buffer_pos, rem );
length -= rem;
}
int next_buffer_size = current_buffer.length < BUFFER_DOUBLE_LIMIT?(current_buffer.length << 1):(current_buffer.length + BUFFER_DOUBLE_LIMIT );
byte[] new_buffer = new byte[ Math.max( next_buffer_size, length + 512 ) ];
System.arraycopy( bytes, offset + rem, new_buffer, 0, length );
if ( old_buffers == null ){
old_buffers = new byte[][]{ current_buffer };
}else{
byte[][] new_old_buffers = new byte[old_buffers.length+1][];
System.arraycopy( old_buffers, 0, new_old_buffers, 0, old_buffers.length );
new_old_buffers[ old_buffers.length ] = current_buffer;
old_buffers = new_old_buffers;
}
current_buffer = new_buffer;
current_buffer_pos = length;
}
}
private void
writeByteBuffer(
ByteBuffer bb )
{
writeBytes( bb.array(), bb.arrayOffset() + bb.position(), bb.remaining());
}
private byte[]
toByteArray()
{
if ( old_buffers == null ){
byte[] res = new byte[current_buffer_pos];
System.arraycopy( current_buffer, 0, res, 0, current_buffer_pos );
// System.out.println( "-> " + current_buffer_pos );
return( res );
}else{
int total = current_buffer_pos;
for (int i=0;i<old_buffers.length;i++){
total += old_buffers[i].length;
}
byte[] res = new byte[total];
int pos = 0;
//String str = "";
for (int i=0;i<old_buffers.length;i++){
byte[] buffer = old_buffers[i];
int len = buffer.length;
System.arraycopy( buffer, 0, res, pos, len );
pos += len;
//str += (str.length()==0?"":",") + len;
}
System.arraycopy( current_buffer, 0, res, pos, current_buffer_pos );
//System.out.println( "-> " + str + "," + current_buffer_pos );
return( res );
}
}
private static Object
normaliseObject(
Object o )
{
if ( o instanceof Integer ){
o = new Long(((Integer)o).longValue());
}else if ( o instanceof Boolean ){
o = new Long(((Boolean)o).booleanValue()?1:0);
}else if ( o instanceof Float ){
o = String.valueOf((Float)o);
}else if ( o instanceof byte[] ){
try{
o = new String((byte[])o,"UTF-8");
}catch( Throwable e ){
}
}
return( o );
}
public static boolean
objectsAreIdentical(
Object o1,
Object o2 )
{
if ( o1 == null && o2 == null ){
return( true );
}else if ( o1 == null || o2 == null ){
return( false );
}
if ( o1.getClass() != o2.getClass()){
if ( ( o1 instanceof Map && o2 instanceof Map ) ||
( o1 instanceof List && o2 instanceof List )){
// things actually OK
}else{
o1 = normaliseObject( o1 );
o2 = normaliseObject( o2 );
if ( o1.getClass() != o2.getClass()){
//Debug.out( "Failed to normalise classes " + o1.getClass() + "/" + o2.getClass());
return( false );
}
}
}
if ( o1 instanceof Long ||
o1 instanceof String ){
return( o1.equals( o2 ));
}else if ( o1 instanceof byte[] ){
return( Arrays.equals((byte[])o1,(byte[])o2 ));
}else if ( o1 instanceof List ){
return( listsAreIdentical((List)o1,(List)o2));
}else if ( o1 instanceof Map ){
return( mapsAreIdentical((Map)o1,(Map)o2));
}else if ( o1 instanceof Integer ||
o1 instanceof Boolean ||
o1 instanceof Float ||
o1 instanceof ByteBuffer ){
return( o1.equals( o2 ));
}else{
//( "Invalid type: " + o1 );
return( false );
}
}
public static boolean
listsAreIdentical(
List list1,
List list2 )
{
if ( list1 == null && list2 == null ){
return( true );
}else if ( list1 == null || list2 == null ){
return( false );
}
if ( list1.size() != list2.size()){
return( false );
}
for ( int i=0;i<list1.size();i++){
if ( !objectsAreIdentical( list1.get(i), list2.get(i))){
return( false );
}
}
return( true );
}
public static boolean
mapsAreIdentical(
Map map1,
Map map2 )
{
if ( map1 == null && map2 == null ){
return( true );
}else if ( map1 == null || map2 == null ){
return( false );
}
if ( map1.size() != map2.size()){
return( false );
}
Iterator it = map1.keySet().iterator();
while( it.hasNext()){
Object key = it.next();
Object v1 = map1.get(key);
Object v2 = map2.get(key);
if ( !objectsAreIdentical( v1, v2 )){
return( false );
}
}
return( true );
}
public static Map
cloneMap(
Map map )
{
if ( map == null ){
return( null );
}
Map res = new TreeMap();
Iterator it = map.entrySet().iterator();
while( it.hasNext()){
Map.Entry entry = (Map.Entry)it.next();
Object key = entry.getKey();
Object value = entry.getValue();
// keys must be String (or very rarely byte[])
if ( key instanceof byte[] ){
key = ((byte[])key).clone();
}
res.put( key, clone( value ));
}
return( res );
}
public static List
cloneList(
List list )
{
if ( list == null ){
return( null );
}
List res = new ArrayList(list.size());
Iterator it = list.iterator();
while( it.hasNext()){
res.add( clone( it.next()));
}
return( res );
}
public static Object
clone(
Object obj )
{
if ( obj instanceof List ){
return( cloneList((List)obj));
}else if ( obj instanceof Map ){
return( cloneMap((Map)obj));
}else if ( obj instanceof byte[]){
return(((byte[])obj).clone());
}else{
// assume immutable - String,Long etc
return( obj );
}
}
/*
* The following code is from Integer.java as we don't want to
*/
final static byte[] digits = {
'0' , '1' , '2' , '3' , '4' , '5' ,
'6' , '7' , '8' , '9' , 'a' , 'b' ,
'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
'o' , 'p' , 'q' , 'r' , 's' , 't' ,
'u' , 'v' , 'w' , 'x' , 'y' , 'z'
};
final static byte [] DigitTens = {
'0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
'1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
'2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
'3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
'4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
'5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
'6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
'7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
'8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
'9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
} ;
final static byte [] DigitOnes = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
} ;
/**
* writes to int_buffer and returns start position in buffer (always runs to end of buffer)
* @param i
* @return
*/
private int
intToBytes(
int i )
{
int q, r;
int charPos = 12;
byte sign = 0;
if (i < 0) {
sign = '-';
i = -i;
}
// Generate two digits per iteration
while (i >= 65536) {
q = i / 100;
// really: r = i - (q * 100);
r = i - ((q << 6) + (q << 5) + (q << 2));
i = q;
int_buffer [--charPos] = DigitOnes[r];
int_buffer [--charPos] = DigitTens[r];
}
// Fall thru to fast mode for smaller numbers
// assert(i <= 65536, i);
for (;;) {
q = (i * 52429) >>> (16+3);
r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ...
int_buffer [--charPos] = digits [r];
i = q;
if (i == 0) break;
}
if (sign != 0) {
int_buffer [--charPos] = sign;
}
return charPos;
}
}
| 18,517 | Java | .java | CSEMike/OneSwarm-Community-Server | 10 | 3 | 5 | 2009-11-11T17:20:04Z | 2011-05-19T17:17:41Z |
Base32.java | /FileExtraction/Java_unseen/CSEMike_OneSwarm-Community-Server/src/org/gudy/azureus2/core3/util/Base32.java | /*
* Created on 04-Mar-2005
* Created by Paul Gardner
* Copyright (C) 2004, 2005, 2006 Aelitis, All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* AELITIS, SAS au capital de 46,603.30 euros
* 8 Allee Lenotre, La Grille Royale, 78600 Le Mesnil le Roi, France.
*
*/
package org.gudy.azureus2.core3.util;
/**
* @author parg
* Derived from com.bitzi.util.Base32.java
* (PD) 2001 The Bitzi Corporation
* Please see http://bitzi.com/publicdomain for more info.
*
*/
public class
Base32
{
private static final String base32Chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
private static final int[] base32Lookup =
{ 0xFF,0xFF,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F, // '0', '1', '2', '3', '4', '5', '6', '7'
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, // '8', '9', ':', ';', '<', '=', '>', '?'
0xFF,0x00,0x01,0x02,0x03,0x04,0x05,0x06, // '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G'
0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E, // 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O'
0x0F,0x10,0x11,0x12,0x13,0x14,0x15,0x16, // 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W'
0x17,0x18,0x19,0xFF,0xFF,0xFF,0xFF,0xFF, // 'X', 'Y', 'Z', '[', '\', ']', '^', '_'
0xFF,0x00,0x01,0x02,0x03,0x04,0x05,0x06, // '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g'
0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E, // 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o'
0x0F,0x10,0x11,0x12,0x13,0x14,0x15,0x16, // 'p', 'q', 'r', 's', 't', 'u', 'v', 'w'
0x17,0x18,0x19,0xFF,0xFF,0xFF,0xFF,0xFF // 'x', 'y', 'z', '{', '|', '}', '~', 'DEL'
};
public static String
encode(
final byte[] bytes )
{
int i =0, index = 0, digit = 0;
int currByte, nextByte;
StringBuffer base32 = new StringBuffer((bytes.length+7)*8/5);
while(i < bytes.length)
{
currByte = (bytes[i]>=0) ? bytes[i] : (bytes[i]+256); // unsign
/* Is the current digit going to span a byte boundary? */
if (index > 3)
{
if ((i+1)<bytes.length)
nextByte = (bytes[i+1]>=0) ? bytes[i+1] : (bytes[i+1]+256);
else
nextByte = 0;
digit = currByte & (0xFF >> index);
index = (index + 5) % 8;
digit <<= index;
digit |= nextByte >> (8 - index);
i++;
}
else
{
digit = (currByte >> (8 - (index + 5))) & 0x1F;
index = (index + 5) % 8;
if (index == 0)
i++;
}
base32.append(base32Chars.charAt(digit));
}
return base32.toString();
}
public static byte[]
decode(
final String base32 )
{
int i, index, lookup, offset, digit;
byte[] bytes = new byte[base32.length()*5/8];
for(i = 0, index = 0, offset = 0; i < base32.length(); i++)
{
lookup = base32.charAt(i) - '0';
/* Skip chars outside the lookup table */
if ( lookup < 0 || lookup >= base32Lookup.length)
continue;
digit = base32Lookup[lookup];
/* If this digit is not in the table, ignore it */
if (digit == 0xFF)
continue;
if (index <= 3)
{
index = (index + 5) % 8;
if (index == 0)
{
bytes[offset] |= digit;
offset++;
if(offset>=bytes.length) break;
}
else
bytes[offset] |= digit << (8 - index);
}
else
{
index = (index + 5) % 8;
bytes[offset] |= (digit >>> index);
offset++;
if(offset>=bytes.length) break;
bytes[offset] |= digit << (8 - index);
}
}
return bytes;
}
} | 4,467 | Java | .java | CSEMike/OneSwarm-Community-Server | 10 | 3 | 5 | 2009-11-11T17:20:04Z | 2011-05-19T17:17:41Z |
ByteEncodedKeyHashMap.java | /FileExtraction/Java_unseen/CSEMike_OneSwarm-Community-Server/src/org/gudy/azureus2/core3/util/ByteEncodedKeyHashMap.java | /*
* File : ByteEncodedKeyMap.java
* Created : 31-Oct-2003
* By : parg
*
* Azureus - a Java Bittorrent client
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details ( see the LICENSE file ).
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.gudy.azureus2.core3.util;
/**
* @author parg
*/
import java.util.HashMap;
public class
ByteEncodedKeyHashMap
extends HashMap
{
}
| 978 | Java | .java | CSEMike/OneSwarm-Community-Server | 10 | 3 | 5 | 2009-11-11T17:20:04Z | 2011-05-19T17:17:41Z |
ByteFormatter.java | /FileExtraction/Java_unseen/CSEMike_OneSwarm-Community-Server/src/org/gudy/azureus2/core3/util/ByteFormatter.java | /*
* Created on 2 juil. 2003
* Copyright (C) 2003, 2004, 2005, 2006 Aelitis, All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* AELITIS, SAS au capital de 46,603.30 euros
* 8 Allee Lenotre, La Grille Royale, 78600 Le Mesnil le Roi, France.
*
*/
package org.gudy.azureus2.core3.util;
/**
* @author Olivier
*
*/
import java.nio.ByteBuffer;
public class ByteFormatter
{
final static char[] HEXDIGITS = {
'0' , '1' , '2' , '3' , '4' , '5' ,
'6' , '7' , '8' , '9' , 'A' , 'B' ,
'C' , 'D' , 'E' , 'F' };
public static String
nicePrint(
String str )
{
return( nicePrint(str.getBytes(),true));
}
public static String nicePrint(byte[] data) {
return( nicePrint( data, false ));
}
public static String nicePrint(byte[] data, int max){
return( nicePrint( data, false, max ));
}
public static String nicePrint( ByteBuffer data ) {
byte[] raw = new byte[ data.limit() ];
for( int i=0; i < raw.length; i++ ) {
raw[i] = data.get( i );
}
return nicePrint( raw );
}
public static String
nicePrint(
byte[] data,
boolean tight)
{
return( nicePrint( data, tight, 1024 ));
}
public static String
nicePrint(
byte[] data,
boolean tight,
int max_length )
{
if (data == null) {
return "";
}
int dataLength = data.length;
if (dataLength > max_length) {
dataLength = max_length;
}
int size = dataLength * 2;
if (!tight) {
size += (dataLength - 1) / 4;
}
char[] out = new char[size];
try {
int pos = 0;
for (int i = 0; i < dataLength; i++) {
if ((!tight) && (i % 4 == 0) && i > 0) {
out[pos++] = ' ';
}
out[pos++] = HEXDIGITS[(byte) ((data[i] >> 4) & 0xF)];
out[pos++] = HEXDIGITS[(byte) (data[i] & 0xF)];
}
} catch (Exception e) {
e.printStackTrace();
}
try {
return new String(out) + (data.length > max_length?"...":"");
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static String nicePrint(byte b) {
byte b1 = (byte) ((b >> 4) & 0x0000000F);
byte b2 = (byte) (b & 0x0000000F);
return nicePrint2(b1) + nicePrint2(b2);
}
public static String nicePrint2(byte b) {
String out = "";
switch (b) {
case 0 :
out = "0";
break;
case 1 :
out = "1";
break;
case 2 :
out = "2";
break;
case 3 :
out = "3";
break;
case 4 :
out = "4";
break;
case 5 :
out = "5";
break;
case 6 :
out = "6";
break;
case 7 :
out = "7";
break;
case 8 :
out = "8";
break;
case 9 :
out = "9";
break;
case 10 :
out = "A";
break;
case 11 :
out = "B";
break;
case 12 :
out = "C";
break;
case 13 :
out = "D";
break;
case 14 :
out = "E";
break;
case 15 :
out = "F";
break;
}
return out;
}
public static String
encodeString(
byte[] bytes )
{
return( nicePrint( bytes, true ));
}
public static String
encodeString(
byte[] bytes,
int offset,
int len )
{
byte[] x = new byte[len];
System.arraycopy( bytes, offset, x, 0, len );
return( nicePrint( x, true ));
}
public static byte[]
decodeString(
String str )
{
char[] chars = str.toCharArray();
int chars_length = chars.length - chars.length%2;
byte[] res = new byte[chars_length/2];
for (int i=0;i<chars_length;i+=2){
String b = new String(chars,i,2);
res[i/2] = (byte)Integer.parseInt(b,16);
}
return( res );
}
/**
* Convert a Network Byte Order byte array into an int
*
* @param array
* @return
*
* @since 3.0.1.5
*/
public static int
byteArrayToInt(
byte[] array)
{
return (array[0] << 24) & 0xff000000 | (array[1] << 16) & 0x00ff0000
| (array[2] << 8) & 0x0000ff00 | array[3] & 0x000000ff;
}
}
| 4,771 | Java | .java | CSEMike/OneSwarm-Community-Server | 10 | 3 | 5 | 2009-11-11T17:20:04Z | 2011-05-19T17:17:41Z |
SHA1.java | /FileExtraction/Java_unseen/CSEMike_OneSwarm-Community-Server/src/org/gudy/azureus2/core3/util/SHA1.java | /*
* Created on Apr 12, 2004
* Created by Olivier Chalouhi
* Modified Apr 13, 2004 by Alon Rohter
* Copyright (C) 2004, 2005, 2006 Aelitis, All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* AELITIS, SAS au capital de 46,603.30 euros
* 8 Allee Lenotre, La Grille Royale, 78600 Le Mesnil le Roi, France.
*
*/
package org.gudy.azureus2.core3.util;
import java.nio.ByteBuffer;
/**
* SHA-1 message digest class.
*/
public final class SHA1 {
private int h0,h1,h2,h3,h4;
private ByteBuffer finalBuffer;
private ByteBuffer saveBuffer;
private int s0,s1,s2,s3,s4;
private long length;
private long saveLength;
/**
* Create a new SHA-1 message digest hasher.
*/
public SHA1() {
finalBuffer = ByteBuffer.allocate(64);
finalBuffer.position(0);
finalBuffer.limit(64);
saveBuffer = ByteBuffer.allocate(64);
saveBuffer.position(0);
saveBuffer.limit(64);
reset();
}
final private void transform(final byte[] ar, int offset) {
int w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15;
int a,b,c,d,e;
/*
* we're using direct array access instead of buffer.getInt() since it is significantly faster
* combined with the chunk-fetching on direct byte buffers this is 30(direct) to 100%(heap) faster
* than the previous implementation
*/
w0 = (ar[offset++]&0xff) << 24 | (ar[offset++]&0xff) << 16 | (ar[offset++]&0xff) << 8 | (ar[offset++]&0xff);
w1 = (ar[offset++]&0xff) << 24 | (ar[offset++]&0xff) << 16 | (ar[offset++]&0xff) << 8 | (ar[offset++]&0xff);
w2 = (ar[offset++]&0xff) << 24 | (ar[offset++]&0xff) << 16 | (ar[offset++]&0xff) << 8 | (ar[offset++]&0xff);
w3 = (ar[offset++]&0xff) << 24 | (ar[offset++]&0xff) << 16 | (ar[offset++]&0xff) << 8 | (ar[offset++]&0xff);
w4 = (ar[offset++]&0xff) << 24 | (ar[offset++]&0xff) << 16 | (ar[offset++]&0xff) << 8 | (ar[offset++]&0xff);
w5 = (ar[offset++]&0xff) << 24 | (ar[offset++]&0xff) << 16 | (ar[offset++]&0xff) << 8 | (ar[offset++]&0xff);
w6 = (ar[offset++]&0xff) << 24 | (ar[offset++]&0xff) << 16 | (ar[offset++]&0xff) << 8 | (ar[offset++]&0xff);
w7 = (ar[offset++]&0xff) << 24 | (ar[offset++]&0xff) << 16 | (ar[offset++]&0xff) << 8 | (ar[offset++]&0xff);
w8 = (ar[offset++]&0xff) << 24 | (ar[offset++]&0xff) << 16 | (ar[offset++]&0xff) << 8 | (ar[offset++]&0xff);
w9 = (ar[offset++]&0xff) << 24 | (ar[offset++]&0xff) << 16 | (ar[offset++]&0xff) << 8 | (ar[offset++]&0xff);
w10 = (ar[offset++]&0xff) << 24 | (ar[offset++]&0xff) << 16 | (ar[offset++]&0xff) << 8 | (ar[offset++]&0xff);
w11 = (ar[offset++]&0xff) << 24 | (ar[offset++]&0xff) << 16 | (ar[offset++]&0xff) << 8 | (ar[offset++]&0xff);
w12 = (ar[offset++]&0xff) << 24 | (ar[offset++]&0xff) << 16 | (ar[offset++]&0xff) << 8 | (ar[offset++]&0xff);
w13 = (ar[offset++]&0xff) << 24 | (ar[offset++]&0xff) << 16 | (ar[offset++]&0xff) << 8 | (ar[offset++]&0xff);
w14 = (ar[offset++]&0xff) << 24 | (ar[offset++]&0xff) << 16 | (ar[offset++]&0xff) << 8 | (ar[offset++]&0xff);
w15 = (ar[offset++]&0xff) << 24 | (ar[offset++]&0xff) << 16 | (ar[offset++]&0xff) << 8 | (ar[offset]&0xff);
a = h0 ; b = h1 ; c = h2 ; d = h3 ; e = h4;
e += ((a << 5) | ( a >>> 27)) + w0 + ((b & c) | ((~b ) & d)) + 0x5A827999 ;
b = (b << 30) | (b >>> 2) ;
d += ((e << 5) | ( e >>> 27)) + w1 + ((a & b) | ((~a ) & c)) + 0x5A827999 ;
a = (a << 30) | (a >>> 2) ;
c += ((d << 5) | ( d >>> 27)) + w2 + ((e & a) | ((~e ) & b)) + 0x5A827999 ;
e = (e << 30) | (e >>> 2) ;
b += ((c << 5) | ( c >>> 27)) + w3 + ((d & e) | ((~d ) & a)) + 0x5A827999 ;
d = (d << 30) | (d >>> 2) ;
a += ((b << 5) | ( b >>> 27)) + w4 + ((c & d) | ((~c ) & e)) + 0x5A827999 ;
c = (c << 30) | (c >>> 2) ;
e += ((a << 5) | ( a >>> 27)) + w5 + ((b & c) | ((~b ) & d)) + 0x5A827999 ;
b = (b << 30) | (b >>> 2) ;
d += ((e << 5) | ( e >>> 27)) + w6 + ((a & b) | ((~a ) & c)) + 0x5A827999 ;
a = (a << 30) | (a >>> 2) ;
c += ((d << 5) | ( d >>> 27)) + w7 + ((e & a) | ((~e ) & b)) + 0x5A827999 ;
e = (e << 30) | (e >>> 2) ;
b += ((c << 5) | ( c >>> 27)) + w8 + ((d & e) | ((~d ) & a)) + 0x5A827999 ;
d = (d << 30) | (d >>> 2) ;
a += ((b << 5) | ( b >>> 27)) + w9 + ((c & d) | ((~c ) & e)) + 0x5A827999 ;
c = (c << 30) | (c >>> 2) ;
e += ((a << 5) | ( a >>> 27)) + w10 + ((b & c) | ((~b ) & d)) + 0x5A827999 ;
b = (b << 30) | (b >>> 2) ;
d += ((e << 5) | ( e >>> 27)) + w11 + ((a & b) | ((~a ) & c)) + 0x5A827999 ;
a = (a << 30) | (a >>> 2) ;
c += ((d << 5) | ( d >>> 27)) + w12 + ((e & a) | ((~e ) & b)) + 0x5A827999 ;
e = (e << 30) | (e >>> 2) ;
b += ((c << 5) | ( c >>> 27)) + w13 + ((d & e) | ((~d ) & a)) + 0x5A827999 ;
d = (d << 30) | (d >>> 2) ;
a += ((b << 5) | ( b >>> 27)) + w14 + ((c & d) | ((~c ) & e)) + 0x5A827999 ;
c = (c << 30) | (c >>> 2) ;
e += ((a << 5) | ( a >>> 27)) + w15 + ((b & c) | ((~b ) & d)) + 0x5A827999 ;
b = (b << 30) | (b >>> 2) ;
w0 = w13 ^ w8 ^ w2 ^ w0; w0 = (w0 << 1) | (w0 >>> 31) ;
d += ((e << 5) | ( e >>> 27)) + w0 + ((a & b) | ((~a ) & c)) + 0x5A827999 ;
a = (a << 30) | (a >>> 2) ;
w1 = w14 ^ w9 ^ w3 ^ w1; w1 = (w1 << 1) | (w1 >>> 31) ;
c += ((d << 5) | ( d >>> 27)) + w1 + ((e & a) | ((~e ) & b)) + 0x5A827999 ;
e = (e << 30) | (e >>> 2) ;
w2 = w15 ^ w10 ^ w4 ^ w2; w2 = (w2 << 1) | (w2 >>> 31) ;
b += ((c << 5) | ( c >>> 27)) + w2 + ((d & e) | ((~d ) & a)) + 0x5A827999 ;
d = (d << 30) | (d >>> 2) ;
w3 = w0 ^ w11 ^ w5 ^ w3; w3 = (w3 << 1) | (w3 >>> 31) ;
a += ((b << 5) | ( b >>> 27)) + w3 + ((c & d) | ((~c ) & e)) + 0x5A827999 ;
c = (c << 30) | (c >>> 2) ;
w4 = w1 ^ w12 ^ w6 ^ w4; w4 = (w4 << 1) | (w4 >>> 31) ;
e += ((a << 5) | ( a >>> 27)) + w4 + (b ^ c ^ d) + 0x6ED9EBA1 ;
b = (b << 30) | (b >>> 2) ;
w5 = w2 ^ w13 ^ w7 ^ w5; w5 = (w5 << 1) | (w5 >>> 31) ;
d += ((e << 5) | ( e >>> 27)) + w5 + (a ^ b ^ c) + 0x6ED9EBA1 ;
a = (a << 30) | (a >>> 2) ;
w6 = w3 ^ w14 ^ w8 ^ w6; w6 = (w6 << 1) | (w6 >>> 31) ;
c += ((d << 5) | ( d >>> 27)) + w6 + (e ^ a ^ b) + 0x6ED9EBA1 ;
e = (e << 30) | (e >>> 2) ;
w7 = w4 ^ w15 ^ w9 ^ w7; w7 = (w7 << 1) | (w7 >>> 31) ;
b += ((c << 5) | ( c >>> 27)) + w7 + (d ^ e ^ a) + 0x6ED9EBA1 ;
d = (d << 30) | (d >>> 2) ;
w8 = w5 ^ w0 ^ w10 ^ w8; w8 = (w8 << 1) | (w8 >>> 31) ;
a += ((b << 5) | ( b >>> 27)) + w8 + (c ^ d ^ e) + 0x6ED9EBA1 ;
c = (c << 30) | (c >>> 2) ;
w9 = w6 ^ w1 ^ w11 ^ w9; w9 = (w9 << 1) | (w9 >>> 31) ;
e += ((a << 5) | ( a >>> 27)) + w9 + (b ^ c ^ d) + 0x6ED9EBA1 ;
b = (b << 30) | (b >>> 2) ;
w10 = w7 ^ w2 ^ w12 ^ w10; w10 = (w10 << 1) | (w10 >>> 31) ;
d += ((e << 5) | ( e >>> 27)) + w10 + (a ^ b ^ c) + 0x6ED9EBA1 ;
a = (a << 30) | (a >>> 2) ;
w11 = w8 ^ w3 ^ w13 ^ w11; w11 = (w11 << 1) | (w11 >>> 31) ;
c += ((d << 5) | ( d >>> 27)) + w11 + (e ^ a ^ b) + 0x6ED9EBA1 ;
e = (e << 30) | (e >>> 2) ;
w12 = w9 ^ w4 ^ w14 ^ w12; w12 = (w12 << 1) | (w12 >>> 31) ;
b += ((c << 5) | ( c >>> 27)) + w12 + (d ^ e ^ a) + 0x6ED9EBA1 ;
d = (d << 30) | (d >>> 2) ;
w13 = w10 ^ w5 ^ w15 ^ w13; w13 = (w13 << 1) | (w13 >>> 31) ;
a += ((b << 5) | ( b >>> 27)) + w13 + (c ^ d ^ e) + 0x6ED9EBA1 ;
c = (c << 30) | (c >>> 2) ;
w14 = w11 ^ w6 ^ w0 ^ w14; w14 = (w14 << 1) | (w14 >>> 31) ;
e += ((a << 5) | ( a >>> 27)) + w14 + (b ^ c ^ d) + 0x6ED9EBA1 ;
b = (b << 30) | (b >>> 2) ;
w15 = w12 ^ w7 ^ w1 ^ w15; w15 = (w15 << 1) | (w15 >>> 31) ;
d += ((e << 5) | ( e >>> 27)) + w15 + (a ^ b ^ c) + 0x6ED9EBA1 ;
a = (a << 30) | (a >>> 2) ;
w0 = w13 ^ w8 ^ w2 ^ w0; w0 = (w0 << 1) | (w0 >>> 31) ;
c += ((d << 5) | ( d >>> 27)) + w0 + (e ^ a ^ b) + 0x6ED9EBA1 ;
e = (e << 30) | (e >>> 2) ;
w1 = w14 ^ w9 ^ w3 ^ w1; w1 = (w1 << 1) | (w1 >>> 31) ;
b += ((c << 5) | ( c >>> 27)) + w1 + (d ^ e ^ a) + 0x6ED9EBA1 ;
d = (d << 30) | (d >>> 2) ;
w2 = w15 ^ w10 ^ w4 ^ w2; w2 = (w2 << 1) | (w2 >>> 31) ;
a += ((b << 5) | ( b >>> 27)) + w2 + (c ^ d ^ e) + 0x6ED9EBA1 ;
c = (c << 30) | (c >>> 2) ;
w3 = w0 ^ w11 ^ w5 ^ w3; w3 = (w3 << 1) | (w3 >>> 31) ;
e += ((a << 5) | ( a >>> 27)) + w3 + (b ^ c ^ d) + 0x6ED9EBA1 ;
b = (b << 30) | (b >>> 2) ;
w4 = w1 ^ w12 ^ w6 ^ w4; w4 = (w4 << 1) | (w4 >>> 31) ;
d += ((e << 5) | ( e >>> 27)) + w4 + (a ^ b ^ c) + 0x6ED9EBA1 ;
a = (a << 30) | (a >>> 2) ;
w5 = w2 ^ w13 ^ w7 ^ w5; w5 = (w5 << 1) | (w5 >>> 31) ;
c += ((d << 5) | ( d >>> 27)) + w5 + (e ^ a ^ b) + 0x6ED9EBA1 ;
e = (e << 30) | (e >>> 2) ;
w6 = w3 ^ w14 ^ w8 ^ w6; w6 = (w6 << 1) | (w6 >>> 31) ;
b += ((c << 5) | ( c >>> 27)) + w6 + (d ^ e ^ a) + 0x6ED9EBA1 ;
d = (d << 30) | (d >>> 2) ;
w7 = w4 ^ w15 ^ w9 ^ w7; w7 = (w7 << 1) | (w7 >>> 31) ;
a += ((b << 5) | ( b >>> 27)) + w7 + (c ^ d ^ e) + 0x6ED9EBA1 ;
c = (c << 30) | (c >>> 2) ;
w8 = w5 ^ w0 ^ w10 ^ w8; w8 = (w8 << 1) | (w8 >>> 31) ;
e += ((a << 5) | ( a >>> 27)) + w8 + ((b & c) | (b & d) | (c & d)) + 0x8F1BBCDC ;
b = (b << 30) | (b >>> 2) ;
w9 = w6 ^ w1 ^ w11 ^ w9; w9 = (w9 << 1) | (w9 >>> 31) ;
d += ((e << 5) | ( e >>> 27)) + w9 + ((a & b) | (a & c) | (b & c)) + 0x8F1BBCDC ;
a = (a << 30) | (a >>> 2) ;
w10 = w7 ^ w2 ^ w12 ^ w10; w10 = (w10 << 1) | (w10 >>> 31) ;
c += ((d << 5) | ( d >>> 27)) + w10 + ((e & a) | (e & b) | (a & b)) + 0x8F1BBCDC ;
e = (e << 30) | (e >>> 2) ;
w11 = w8 ^ w3 ^ w13 ^ w11; w11 = (w11 << 1) | (w11 >>> 31) ;
b += ((c << 5) | ( c >>> 27)) + w11 + ((d & e) | (d & a) | (e & a)) + 0x8F1BBCDC ;
d = (d << 30) | (d >>> 2) ;
w12 = w9 ^ w4 ^ w14 ^ w12; w12 = (w12 << 1) | (w12 >>> 31) ;
a += ((b << 5) | ( b >>> 27)) + w12 + ((c & d) | (c & e) | (d & e)) + 0x8F1BBCDC ;
c = (c << 30) | (c >>> 2) ;
w13 = w10 ^ w5 ^ w15 ^ w13; w13 = (w13 << 1) | (w13 >>> 31) ;
e += ((a << 5) | ( a >>> 27)) + w13 + ((b & c) | (b & d) | (c & d)) + 0x8F1BBCDC ;
b = (b << 30) | (b >>> 2) ;
w14 = w11 ^ w6 ^ w0 ^ w14; w14 = (w14 << 1) | (w14 >>> 31) ;
d += ((e << 5) | ( e >>> 27)) + w14 + ((a & b) | (a & c) | (b & c)) + 0x8F1BBCDC ;
a = (a << 30) | (a >>> 2) ;
w15 = w12 ^ w7 ^ w1 ^ w15; w15 = (w15 << 1) | (w15 >>> 31) ;
c += ((d << 5) | ( d >>> 27)) + w15 + ((e & a) | (e & b) | (a & b)) + 0x8F1BBCDC ;
e = (e << 30) | (e >>> 2) ;
w0 = w13 ^ w8 ^ w2 ^ w0; w0 = (w0 << 1) | (w0 >>> 31) ;
b += ((c << 5) | ( c >>> 27)) + w0 + ((d & e) | (d & a) | (e & a)) + 0x8F1BBCDC ;
d = (d << 30) | (d >>> 2) ;
w1 = w14 ^ w9 ^ w3 ^ w1; w1 = (w1 << 1) | (w1 >>> 31) ;
a += ((b << 5) | ( b >>> 27)) + w1 + ((c & d) | (c & e) | (d & e)) + 0x8F1BBCDC ;
c = (c << 30) | (c >>> 2) ;
w2 = w15 ^ w10 ^ w4 ^ w2; w2 = (w2 << 1) | (w2 >>> 31) ;
e += ((a << 5) | ( a >>> 27)) + w2 + ((b & c) | (b & d) | (c & d)) + 0x8F1BBCDC ;
b = (b << 30) | (b >>> 2) ;
w3 = w0 ^ w11 ^ w5 ^ w3; w3 = (w3 << 1) | (w3 >>> 31) ;
d += ((e << 5) | ( e >>> 27)) + w3 + ((a & b) | (a & c) | (b & c)) + 0x8F1BBCDC ;
a = (a << 30) | (a >>> 2) ;
w4 = w1 ^ w12 ^ w6 ^ w4; w4 = (w4 << 1) | (w4 >>> 31) ;
c += ((d << 5) | ( d >>> 27)) + w4 + ((e & a) | (e & b) | (a & b)) + 0x8F1BBCDC ;
e = (e << 30) | (e >>> 2) ;
w5 = w2 ^ w13 ^ w7 ^ w5; w5 = (w5 << 1) | (w5 >>> 31) ;
b += ((c << 5) | ( c >>> 27)) + w5 + ((d & e) | (d & a) | (e & a)) + 0x8F1BBCDC ;
d = (d << 30) | (d >>> 2) ;
w6 = w3 ^ w14 ^ w8 ^ w6; w6 = (w6 << 1) | (w6 >>> 31) ;
a += ((b << 5) | ( b >>> 27)) + w6 + ((c & d) | (c & e) | (d & e)) + 0x8F1BBCDC ;
c = (c << 30) | (c >>> 2) ;
w7 = w4 ^ w15 ^ w9 ^ w7; w7 = (w7 << 1) | (w7 >>> 31) ;
e += ((a << 5) | ( a >>> 27)) + w7 + ((b & c) | (b & d) | (c & d)) + 0x8F1BBCDC ;
b = (b << 30) | (b >>> 2) ;
w8 = w5 ^ w0 ^ w10 ^ w8; w8 = (w8 << 1) | (w8 >>> 31) ;
d += ((e << 5) | ( e >>> 27)) + w8 + ((a & b) | (a & c) | (b & c)) + 0x8F1BBCDC ;
a = (a << 30) | (a >>> 2) ;
w9 = w6 ^ w1 ^ w11 ^ w9; w9 = (w9 << 1) | (w9 >>> 31) ;
c += ((d << 5) | ( d >>> 27)) + w9 + ((e & a) | (e & b) | (a & b)) + 0x8F1BBCDC ;
e = (e << 30) | (e >>> 2) ;
w10 = w7 ^ w2 ^ w12 ^ w10; w10 = (w10 << 1) | (w10 >>> 31) ;
b += ((c << 5) | ( c >>> 27)) + w10 + ((d & e) | (d & a) | (e & a)) + 0x8F1BBCDC ;
d = (d << 30) | (d >>> 2) ;
w11 = w8 ^ w3 ^ w13 ^ w11; w11 = (w11 << 1) | (w11 >>> 31) ;
a += ((b << 5) | ( b >>> 27)) + w11 + ((c & d) | (c & e) | (d & e)) + 0x8F1BBCDC ;
c = (c << 30) | (c >>> 2) ;
w12 = w9 ^ w4 ^ w14 ^ w12; w12 = (w12 << 1) | (w12 >>> 31) ;
e += ((a << 5) | ( a >>> 27)) + w12 + (b ^ c ^ d) + 0xCA62C1D6 ;
b = (b << 30) | (b >>> 2) ;
w13 = w10 ^ w5 ^ w15 ^ w13; w13 = (w13 << 1) | (w13 >>> 31) ;
d += ((e << 5) | ( e >>> 27)) + w13 + (a ^ b ^ c) + 0xCA62C1D6 ;
a = (a << 30) | (a >>> 2) ;
w14 = w11 ^ w6 ^ w0 ^ w14; w14 = (w14 << 1) | (w14 >>> 31) ;
c += ((d << 5) | ( d >>> 27)) + w14 + (e ^ a ^ b) + 0xCA62C1D6 ;
e = (e << 30) | (e >>> 2) ;
w15 = w12 ^ w7 ^ w1 ^ w15; w15 = (w15 << 1) | (w15 >>> 31) ;
b += ((c << 5) | ( c >>> 27)) + w15 + (d ^ e ^ a) + 0xCA62C1D6 ;
d = (d << 30) | (d >>> 2) ;
w0 = w13 ^ w8 ^ w2 ^ w0; w0 = (w0 << 1) | (w0 >>> 31) ;
a += ((b << 5) | ( b >>> 27)) + w0 + (c ^ d ^ e) + 0xCA62C1D6 ;
c = (c << 30) | (c >>> 2) ;
w1 = w14 ^ w9 ^ w3 ^ w1; w1 = (w1 << 1) | (w1 >>> 31) ;
e += ((a << 5) | ( a >>> 27)) + w1 + (b ^ c ^ d) + 0xCA62C1D6 ;
b = (b << 30) | (b >>> 2) ;
w2 = w15 ^ w10 ^ w4 ^ w2; w2 = (w2 << 1) | (w2 >>> 31) ;
d += ((e << 5) | ( e >>> 27)) + w2 + (a ^ b ^ c) + 0xCA62C1D6 ;
a = (a << 30) | (a >>> 2) ;
w3 = w0 ^ w11 ^ w5 ^ w3; w3 = (w3 << 1) | (w3 >>> 31) ;
c += ((d << 5) | ( d >>> 27)) + w3 + (e ^ a ^ b) + 0xCA62C1D6 ;
e = (e << 30) | (e >>> 2) ;
w4 = w1 ^ w12 ^ w6 ^ w4; w4 = (w4 << 1) | (w4 >>> 31) ;
b += ((c << 5) | ( c >>> 27)) + w4 + (d ^ e ^ a) + 0xCA62C1D6 ;
d = (d << 30) | (d >>> 2) ;
w5 = w2 ^ w13 ^ w7 ^ w5; w5 = (w5 << 1) | (w5 >>> 31) ;
a += ((b << 5) | ( b >>> 27)) + w5 + (c ^ d ^ e) + 0xCA62C1D6 ;
c = (c << 30) | (c >>> 2) ;
w6 = w3 ^ w14 ^ w8 ^ w6; w6 = (w6 << 1) | (w6 >>> 31) ;
e += ((a << 5) | ( a >>> 27)) + w6 + (b ^ c ^ d) + 0xCA62C1D6 ;
b = (b << 30) | (b >>> 2) ;
w7 = w4 ^ w15 ^ w9 ^ w7; w7 = (w7 << 1) | (w7 >>> 31) ;
d += ((e << 5) | ( e >>> 27)) + w7 + (a ^ b ^ c) + 0xCA62C1D6 ;
a = (a << 30) | (a >>> 2) ;
w8 = w5 ^ w0 ^ w10 ^ w8; w8 = (w8 << 1) | (w8 >>> 31) ;
c += ((d << 5) | ( d >>> 27)) + w8 + (e ^ a ^ b) + 0xCA62C1D6 ;
e = (e << 30) | (e >>> 2) ;
w9 = w6 ^ w1 ^ w11 ^ w9; w9 = (w9 << 1) | (w9 >>> 31) ;
b += ((c << 5) | ( c >>> 27)) + w9 + (d ^ e ^ a) + 0xCA62C1D6 ;
d = (d << 30) | (d >>> 2) ;
w10 = w7 ^ w2 ^ w12 ^ w10; w10 = (w10 << 1) | (w10 >>> 31) ;
a += ((b << 5) | ( b >>> 27)) + w10 + (c ^ d ^ e) + 0xCA62C1D6 ;
c = (c << 30) | (c >>> 2) ;
w11 = w8 ^ w3 ^ w13 ^ w11; w11 = (w11 << 1) | (w11 >>> 31) ;
e += ((a << 5) | ( a >>> 27)) + w11 + (b ^ c ^ d) + 0xCA62C1D6 ;
b = (b << 30) | (b >>> 2) ;
w12 = w9 ^ w4 ^ w14 ^ w12; w12 = (w12 << 1) | (w12 >>> 31) ;
d += ((e << 5) | ( e >>> 27)) + w12 + (a ^ b ^ c) + 0xCA62C1D6 ;
a = (a << 30) | (a >>> 2) ;
w13 = w10 ^ w5 ^ w15 ^ w13; w13 = (w13 << 1) | (w13 >>> 31) ;
c += ((d << 5) | ( d >>> 27)) + w13 + (e ^ a ^ b) + 0xCA62C1D6 ;
e = (e << 30) | (e >>> 2) ;
w14 = w11 ^ w6 ^ w0 ^ w14; w14 = (w14 << 1) | (w14 >>> 31) ;
b += ((c << 5) | ( c >>> 27)) + w14 + (d ^ e ^ a) + 0xCA62C1D6 ;
d = (d << 30) | (d >>> 2) ;
w15 = w12 ^ w7 ^ w1 ^ w15; w15 = (w15 << 1) | (w15 >>> 31) ;
a += ((b << 5) | ( b >>> 27)) + w15 + (c ^ d ^ e) + 0xCA62C1D6 ;
c = (c << 30) | (c >>> 2) ;
h0 += a;
h1 += b;
h2 += c;
h3 += d;
h4 += e;
}
private void completeFinalBuffer(ByteBuffer buffer) {
if(finalBuffer.position() == 0)
return;
while(buffer.remaining() > 0 && finalBuffer.remaining() > 0) {
finalBuffer.put(buffer.get());
}
if(finalBuffer.remaining() == 0) {
transform(finalBuffer.array(),0);
finalBuffer.rewind();
}
}
/**
* Resets the SHA-1 to initial state for a new message digest calculation.
* Must be called before starting a new hash calculation.
*/
public void reset() {
h0 = 0x67452301;
h1 = 0xEFCDAB89;
h2 = 0x98BADCFE;
h3 = 0x10325476;
h4 = 0xC3D2E1F0;
length = 0;
finalBuffer.clear();
}
// must be a multiple of 64
private static final int cacheSize = 4*1024;
// cache block to reduce expensive native access for direct byte buffers
private byte[] cacheBlock;
/**
* Starts or continues a SHA-1 message digest calculation.
* Only the remaining bytes of the given ByteBuffer are used.
* @param buffer input data
*/
public void update(ByteBuffer buffer) {
length += buffer.remaining();
//Save current position to leave given buffer unchanged
int position = buffer.position();
//Complete the final buffer if needed
completeFinalBuffer(buffer);
if(!buffer.hasArray() || buffer.isDirect())
{
if(cacheBlock == null) // only allocate if we process direct byte buffers
cacheBlock = new byte[cacheSize];
while(buffer.remaining() >= 64)
{
int toProcess = Math.min(buffer.remaining()-buffer.remaining()%64,cacheSize);
buffer.get(cacheBlock, 0, toProcess);
for(int i = 0;i < toProcess; i+=64)
transform(cacheBlock,i);
}
} else // use direct array access for heap buffers
{
final int endPos = buffer.position()+buffer.remaining()-buffer.remaining()%64;
final int internalEndPos = endPos+buffer.arrayOffset();
for(int i = buffer.arrayOffset()+buffer.position();i < internalEndPos;i+=64)
transform(buffer.array(),i);
buffer.position(endPos);
}
if(buffer.remaining() != 0) {
finalBuffer.put(buffer);
}
buffer.position(position);
}
/**
* Finishes the SHA-1 message digest calculation.
* @return 20-byte hash result
*/
public byte[] digest() {
byte[] result = new byte[20];
finalBuffer.put((byte)0x80);
if(finalBuffer.remaining() < 8) {
while(finalBuffer.remaining() > 0) {
finalBuffer.put((byte)0);
}
finalBuffer.position(0);
transform(finalBuffer.array(),0);
finalBuffer.position(0);
}
while(finalBuffer.remaining() > 8) {
finalBuffer.put((byte)0);
}
finalBuffer.putLong(length << 3);
finalBuffer.position(0);
transform(finalBuffer.array(),0);
finalBuffer.position(0);
finalBuffer.putInt(h0);
finalBuffer.putInt(h1);
finalBuffer.putInt(h2);
finalBuffer.putInt(h3);
finalBuffer.putInt(h4);
finalBuffer.rewind();
finalBuffer.get(result, 0, 20);
return result;
}
/**
* Finishes the SHA-1 message digest calculation, by first performing a final update
* from the given input buffer, then completing the calculation as with digest().
* @param buffer input data
* @return 20-byte hash result
*/
public byte[] digest(ByteBuffer buffer) {
update( buffer );
return digest();
}
/**
* Save the current digest state.
* This allows the resuming of a SHA-1 calculation, even after a digest calculation
* is finished with digest().
*/
public void saveState() {
s0=h0;
s1=h1;
s2=h2;
s3=h3;
s4=h4;
saveLength = length;
int position = finalBuffer.position();
finalBuffer.rewind();
finalBuffer.limit(position);
saveBuffer.clear();
saveBuffer.put(finalBuffer);
saveBuffer.flip();
finalBuffer.limit(64);
finalBuffer.position( position );
}
/**
* Restore the digest to its previously-saved state.
*/
public void restoreState() {
h0=s0;
h1=s1;
h2=s2;
h3=s3;
h4=s4;
length = saveLength;
finalBuffer.clear();
finalBuffer.put(saveBuffer);
}
}
| 19,956 | Java | .java | CSEMike/OneSwarm-Community-Server | 10 | 3 | 5 | 2009-11-11T17:20:04Z | 2011-05-19T17:17:41Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.