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
QuotedParameter.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/mime/impl/QuotedParameter.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 3/19/11 12:31 AM */ package xpertss.mime.impl; import xpertss.mime.Parameter; import xpertss.lang.Objects; // TODO Must a quoted parameter be a name/value pair or could it be simply a value?? public class QuotedParameter implements Parameter { private final String name; private final String value; public QuotedParameter(String name, String value) { this.name = Objects.notNull(name, "name"); this.value = Objects.notNull(value, "value"); } public String getName() { return name; } public String getValue() { return value; } public String toString() { return name + "=\"" + value + "\""; } }
740
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
RtspHeaderParserProvider.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/mime/impl/RtspHeaderParserProvider.java
package xpertss.mime.impl; import xpertss.mime.Header; import xpertss.mime.HeaderParser; import xpertss.mime.spi.HeaderParserProvider; import java.util.HashMap; import java.util.Map; /** * A collection of headers found in the Rtsp specification. */ public class RtspHeaderParserProvider implements HeaderParserProvider { private Map<String,HeaderParser> parsers = new HashMap<String,HeaderParser>(); // RTSP Headers not already defined in HTTP public RtspHeaderParserProvider() { parsers.put("BANDWIDTH", new SimpleHeaderParser("Bandwidth", Header.Type.Request)); parsers.put("BLOCKSIZE", new SimpleHeaderParser("Blocksize", Header.Type.Request)); parsers.put("CONFERENCE", new SimpleHeaderParser("Conference", Header.Type.Request)); parsers.put("CONTENT-BASE", new SimpleHeaderParser("Content-Base", Header.Type.Entity)); parsers.put("CSEQ", new SimpleHeaderParser("CSeq", Header.Type.General)); parsers.put("PROXY-REQUIRE", new SimpleHeaderParser("Proxy-Require", Header.Type.Request)); parsers.put("PUBLIC", new ComplexHeaderParser("Public", Header.Type.Response)); parsers.put("REQUIRE", new SimpleHeaderParser("Require", Header.Type.Request)); parsers.put("RTP-INFO", new ComplexHeaderParser("RTP-Info", Header.Type.Response)); parsers.put("SCALE", new SimpleHeaderParser("Scale", Header.Type.General)); parsers.put("SPEED", new SimpleHeaderParser("Speed", Header.Type.General)); parsers.put("SESSION", new SimpleHeaderParser("Session", Header.Type.General)); parsers.put("TIMESTAMP", new SimpleHeaderParser("Timestamp", Header.Type.General)); parsers.put("TRANSPORT", new ComplexHeaderParser("Transport", Header.Type.General)); parsers.put("UNSUPPORTED", new SimpleHeaderParser("Unsupported", Header.Type.Response)); } public HeaderParser create(String name) { return parsers.get(name.toUpperCase()); } }
2,116
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
MailHeaderParserProvider.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/mime/impl/MailHeaderParserProvider.java
package xpertss.mime.impl; import xpertss.mime.Header; import xpertss.mime.HeaderParser; import xpertss.mime.spi.HeaderParserProvider; import java.util.HashMap; import java.util.Map; /** * */ public class MailHeaderParserProvider implements HeaderParserProvider { private Map<String,HeaderParser> parsers = new HashMap<>(); public MailHeaderParserProvider() { // rfc822 parsers.put("RESENT-MESSAGE-ID", new SimpleHeaderParser("Resent-Message-ID", Header.Type.General)); parsers.put("IN-REPLY-TO", new ComplexHeaderParser("In-Reply-To", Header.Type.General)); parsers.put("MESSAGE-ID", new SimpleHeaderParser("Message-ID", Header.Type.General)); parsers.put("REFERENCES", new ComplexHeaderParser("References", Header.Type.General)); parsers.put("RETURN-PATH", new SimpleHeaderParser("Return-Path", Header.Type.General)); parsers.put("RECEIVED", new SimpleHeaderParser("Received", Header.Type.General)); parsers.put("RESENT-DATE", new SimpleHeaderParser("Resent-Date", Header.Type.General)); parsers.put("RESENT-SENDER", new SimpleHeaderParser("Resent-Sender", Header.Type.General)); parsers.put("RESENT-FROM", new SimpleHeaderParser("Resent-From", Header.Type.General)); parsers.put("REPLY-TO", new SimpleHeaderParser("Reply-To", Header.Type.General)); parsers.put("SENDER", new SimpleHeaderParser("Sender", Header.Type.General)); parsers.put("TO", new ComplexHeaderParser("To", Header.Type.General)); parsers.put("CC", new ComplexHeaderParser("Cc", Header.Type.General)); parsers.put("SUBJECT", new SimpleHeaderParser("Subject", Header.Type.General)); parsers.put("COMMENTS", new SimpleHeaderParser("Comments", Header.Type.General)); parsers.put("KEYWORDS", new ComplexHeaderParser("Keywords", Header.Type.General)); // Resent-Sender // Resent-To // Resent-Reply-To // rfc2045 parsers.put("MIME-VERSION", new SimpleHeaderParser("MIME-Version", Header.Type.General)); parsers.put("CONTENT-ID", new SimpleHeaderParser("Content-ID", Header.Type.General)); parsers.put("CONTENT-TRANSFER-ENCODING", new SimpleHeaderParser("Content-Transfer-Encoding", Header.Type.General)); parsers.put("CONTENT-DESCRIPTION", new SimpleHeaderParser("Content-Description", Header.Type.General)); parsers.put("CONTENT-DISPOSITION", new SimpleHeaderParser("Content-Disposition", Header.Type.General)); parsers.put("CONTENT-DURATION", new SimpleHeaderParser("Content-Duration", Header.Type.General)); // TODO Add Mail Headers // https://tools.ietf.org/html/rfc2045 // https://tools.ietf.org/html/rfc2046 // https://tools.ietf.org/html/rfc2047 // https://tools.ietf.org/html/rfc1123 // https://tools.ietf.org/html/rfc822 } @Override public HeaderParser create(String name) { return parsers.get(name.toUpperCase()); } }
3,273
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
ComplexHeaderParser.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/mime/impl/ComplexHeaderParser.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 3/18/11 9:19 PM */ package xpertss.mime.impl; import xpertss.mime.Header; import xpertss.mime.HeaderTokenizer; import xpertss.mime.HeaderValue; import xpertss.mime.MalformedException; import xpertss.mime.Parameter; import xpertss.lang.Objects; import xpertss.utils.Utils; import java.util.ArrayList; import java.util.List; import static xpertss.mime.HeaderTokenizer.MIME; /** * A complex header is any header which likely contains multiple parts separated * by a comma. This may include both named and unnamed parts. * <pre> * Range: npt=0.000- * RTP-Info: url=rtsp://stream.foo.com/AVAIL.sdp/trackID=2,url=rtsp://stream.foo.com/AVAIL.sdp/trackID=5 * Public: DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE, OPTIONS, ANNOUNCE, RECORD * If-Match: "etag1", "etag2", "etag3" * Accept: text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c * </pre> */ public class ComplexHeaderParser extends ParameterizedHeaderParser { private final Header.Type type; private final String name; protected ComplexHeaderParser(String name, Header.Type type) { this.name = Objects.notNull(name, "name"); this.type = Objects.notNull(type, "type"); } @Override protected Header doParse(CharSequence raw) throws MalformedException { HeaderTokenizer h = new HeaderTokenizer(raw, MIME); List<HeaderValue> values = new ArrayList<>(); List<String> parts = new ArrayList<>(); StringBuilder buf = new StringBuilder(); boolean complete = false; // First break them up into individual value pairs while(!complete) { HeaderTokenizer.Token token = h.next(); switch(token.getType()) { case HeaderTokenizer.Token.EOF: parts.add(Utils.trimAndClear(buf)); values.add(create(parts)); complete = true; break; case HeaderTokenizer.Token.LWS: buf.append(" "); // collapse whitespace continue; case ';': parts.add(Utils.trimAndClear(buf)); continue; case ',': parts.add(Utils.trimAndClear(buf)); values.add(create(parts)); continue; case HeaderTokenizer.Token.QUOTEDSTRING: buf.append('"').append(token.getValue()).append('"'); continue; case HeaderTokenizer.Token.COMMENT: buf.append('(').append(token.getValue()).append(')'); continue; default: buf.append(token.getValue()); } } return new ComplexValueHeader(name, type, values.toArray(new HeaderValue[values.size()])); } private HeaderValue create(List<String> parts) throws MalformedException { String[] valueParts = parts.remove(0).split("=", 2); if(valueParts.length == 1) return new SimpleHeaderValue(valueParts[0], createParams(parts)); return new NamedHeaderValue(valueParts[0], valueParts[1], createParams(parts)); } private Parameter[] createParams(List<String> parts) throws MalformedException { Parameter[] params = new Parameter[parts.size()]; String part = null; int i = 0; while(!parts.isEmpty() && (part = parts.remove(0)) != null) { params[i++] = doParameter(part); } return params; } }
3,435
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
ParameterizedHeaderParser.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/mime/impl/ParameterizedHeaderParser.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 3/19/11 8:34 AM */ package xpertss.mime.impl; import xpertss.mime.HeaderParser; import xpertss.mime.HeaderTokenizer; import xpertss.mime.MalformedException; import xpertss.mime.Parameter; import xpertss.utils.Utils; public abstract class ParameterizedHeaderParser extends HeaderParser { protected Parameter doParameter(String rawParam) throws MalformedException { HeaderTokenizer h = new HeaderTokenizer(rawParam, HeaderTokenizer.MIME); StringBuilder buf = new StringBuilder(); String name = null, value = null; boolean quoted = false; while(true) { HeaderTokenizer.Token token = h.next(); switch(token.getType()) { case HeaderTokenizer.Token.EOF: value = Utils.trimAndClear(buf); return (quoted) ? new QuotedParameter(name, value) : new SimpleParameter(name, value); case HeaderTokenizer.Token.LWS: buf.append(" "); // collapse whitespace continue; case '=': if(name != null) throw new MalformedException("malformed parameter"); name = Utils.trimAndClear(buf); continue; case HeaderTokenizer.Token.QUOTEDSTRING: quoted = true; default: buf.append(token.getValue()); } } } }
1,413
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
SimpleHeaderParser.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/mime/impl/SimpleHeaderParser.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 3/18/11 1:52 PM */ package xpertss.mime.impl; import xpertss.mime.Header; import xpertss.mime.HeaderTokenizer; import xpertss.mime.HeaderValue; import xpertss.mime.MalformedException; import xpertss.mime.Parameter; import xpertss.lang.Objects; import xpertss.utils.Utils; import java.util.ArrayList; import java.util.List; import static xpertss.mime.HeaderTokenizer.MIME; import static xpertss.mime.HeaderTokenizer.Token; /** * A simple header parser parses simple impl headers. A simple header is one that has only * a single unnamed value. Some examples include, Date, Server, Content-Length, Expires, * Age, Content-Type, Location, Referrer, etc. */ public class SimpleHeaderParser extends ParameterizedHeaderParser { private final Header.Type type; private final String name; protected SimpleHeaderParser(String name, Header.Type type) { this.name = Objects.notNull(name, "name"); this.type = Objects.notNull(type, "type"); } @Override protected Header doParse(CharSequence raw) throws MalformedException { HeaderTokenizer h = new HeaderTokenizer(raw, MIME); List<String> parts = new ArrayList<String>(); StringBuilder buf = new StringBuilder(); boolean complete = false; while(!complete) { HeaderTokenizer.Token token = h.next(); switch(token.getType()) { case Token.EOF: parts.add(Utils.trimAndClear(buf)); complete = true; break; case Token.LWS: buf.append(" "); // collapse whitespace continue; case ';': parts.add(Utils.trimAndClear(buf)); continue; case Token.QUOTEDSTRING: buf.append('"').append(token.getValue()).append('"'); continue; case Token.COMMENT: buf.append('(').append(token.getValue()).append(')'); continue; default: buf.append(token.getValue()); } } return new SingleValueHeader(name, type, create(parts)); } private HeaderValue create(List<String> parts) throws MalformedException { if(parts.size() == 1) return new SimpleHeaderValue(parts.get(0), new Parameter[0]); Parameter[] params = new Parameter[parts.size() - 1]; for(int i = 1; i < parts.size(); i++) params[i-1] = doParameter(parts.get(i)); return new SimpleHeaderValue(parts.get(0), params); } }
2,565
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
HttpHeaderParserProvider.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/mime/impl/HttpHeaderParserProvider.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 3/18/11 1:51 PM */ package xpertss.mime.impl; import xpertss.mime.Header; import xpertss.mime.HeaderParser; import xpertss.mime.spi.HeaderParserProvider; import java.util.HashMap; import java.util.Map; /** * This implementation breaks down impl headers into two main categories plus a few * header by header implementations. The two main categories include: SimpleHeaders * which have only a single unnamed value and ComplexHeaders which have multiple named * and unnamed values. * <p> * In addition to these two main categories which cover most of the possible impl * headers there are also a few header specific parsers for Cookies as an example * which do not conform to the standard parameter format. * <p> * The main reason for the two main categories is that the special character <b>,</b> * has two different meanings depending on the header. In some cases it denotes a * boundary between values such as is the case on the Allow header. In other cases it * denotes a separation of elements within a value such as its use in all Date related * headers. Due to this difference two header implementations needed to be developed to * parse that usage differently. */ public class HttpHeaderParserProvider implements HeaderParserProvider { private Map<String,HeaderParser> parsers = new HashMap<>(); public HttpHeaderParserProvider() { // General Headers (Cache-Control, Connection, Date, Pragma, Trailer, Transfer-Encoding, Upgrade, Via, Warning) parsers.put("CACHE-CONTROL", new ComplexHeaderParser("Cache-Control", Header.Type.General)); parsers.put("CONNECTION", new SimpleHeaderParser("Connection", Header.Type.General)); parsers.put("DATE", new SimpleHeaderParser("Date", Header.Type.General)); parsers.put("PRAGMA", new SimpleHeaderParser("Pragma", Header.Type.General)); parsers.put("TRAILER", new ComplexHeaderParser("Trailer", Header.Type.General)); parsers.put("TRANSFER-ENCODING", new ComplexHeaderParser("Transfer-Encoding", Header.Type.General)); parsers.put("UPGRADE", new ComplexHeaderParser("Upgrade", Header.Type.General)); parsers.put("VIA", new ComplexHeaderParser("Via", Header.Type.General)); // TODO Warning // Request Headers (Accept, Accept-Charset, Accept-Encoding, Accept-Language, Authorization, Expect, From, Host, // If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Max-Forwards, // Proxy-Authorization, Range, Referer, TE, User-Agent) parsers.put("ACCEPT", new ComplexHeaderParser("Accept", Header.Type.Request)); parsers.put("ACCEPT-CHARSET", new ComplexHeaderParser("Accept-Charset", Header.Type.Request)); parsers.put("ACCEPT-ENCODING", new ComplexHeaderParser("Accept-Encoding", Header.Type.Request)); parsers.put("ACCEPT-LANGUAGE", new ComplexHeaderParser("Accept-Language", Header.Type.Request)); parsers.put("EXPECT", new ComplexHeaderParser("Expect", Header.Type.Request)); parsers.put("FROM", new SimpleHeaderParser("From", Header.Type.Request)); parsers.put("HOST", new SimpleHeaderParser("Host", Header.Type.Request)); parsers.put("IF-MATCH", new ComplexHeaderParser("If-Match", Header.Type.Request)); parsers.put("IF-MODIFIED-SINCE", new SimpleHeaderParser("If-Modified-Since", Header.Type.Request)); parsers.put("IF-NONE-MATCH", new ComplexHeaderParser("If-None-Match", Header.Type.Request)); parsers.put("IF-RANGE", new SimpleHeaderParser("If-Range", Header.Type.Request)); parsers.put("IF-UNMODIFIED-SINCE", new SimpleHeaderParser("If-Unmodified-Since", Header.Type.Request)); parsers.put("MAX-FORWARDS", new SimpleHeaderParser("Max-Forwards", Header.Type.Request)); parsers.put("RANGE", new ComplexHeaderParser("Range", Header.Type.Request)); parsers.put("REFERER", new SimpleHeaderParser("Referer", Header.Type.Request)); parsers.put("TE", new ComplexHeaderParser("TE", Header.Type.Request)); parsers.put("USER-AGENT", new SimpleHeaderParser("User-Agent", Header.Type.Request)); parsers.put("AUTHORIZATION", new SimpleHeaderParser("Authorization", Header.Type.Request)); // kind of unique parsers.put("PROXY-AUTHORIZATION", new SimpleHeaderParser("Proxy-Authorization", Header.Type.Request)); // kind of unique // TODO Cookie // Response Headers (Accept-Ranges, Age, ETag, Location, Proxy-Authenticate, Retry-After, Server, Vary, // WWW-Authenticate) parsers.put("ACCEPT-RANGES", new ComplexHeaderParser("Accept-Ranges", Header.Type.Response)); parsers.put("AGE", new SimpleHeaderParser("Age", Header.Type.Response)); parsers.put("ETAG", new SimpleHeaderParser("ETag", Header.Type.Response)); parsers.put("LOCATION", new SimpleHeaderParser("Location", Header.Type.Response)); parsers.put("RETRY-AFTER", new SimpleHeaderParser("Retry-After", Header.Type.Response)); parsers.put("SERVER", new SimpleHeaderParser("Server", Header.Type.Response)); parsers.put("VARY", new ComplexHeaderParser("Vary", Header.Type.Response)); parsers.put("PROXY-AUTHENTICATE", new SimpleHeaderParser("Proxy-Authenticate", Header.Type.Response)); // kind of unique parsers.put("WWW-AUTHENTICATE", new SimpleHeaderParser("WWW-Authenticate", Header.Type.Response)); // kind of unique // TODO Set-Cookie and possibly Set-Cookie2 // Entity Headers (Allow, Content-Encoding, Content-Length, Content-Location, Content-MD5, Content-Range, // Content-Type, Expires, Last-Modified) parsers.put("ALLOW", new ComplexHeaderParser("Allow", Header.Type.Entity)); parsers.put("CONTENT-ENCODING", new ComplexHeaderParser("Content-Encoding", Header.Type.Entity)); parsers.put("CONTENT-LANGUAGE", new ComplexHeaderParser("Content-Language", Header.Type.Entity)); parsers.put("CONTENT-LENGTH", new SimpleHeaderParser("Content-Length", Header.Type.Entity)); parsers.put("CONTENT-LOCATION", new SimpleHeaderParser("Content-Location", Header.Type.Entity)); parsers.put("CONTENT-MD5", new SimpleHeaderParser("Content-MD5", Header.Type.Entity)); parsers.put("CONTENT-RANGE", new SimpleHeaderParser("Content-Range", Header.Type.Entity)); parsers.put("CONTENT-TYPE", new SimpleHeaderParser("Content-Type", Header.Type.Entity)); parsers.put("EXPIRES", new SimpleHeaderParser("Expires", Header.Type.Entity)); parsers.put("LAST-MODIFIED", new SimpleHeaderParser("Last-Modified", Header.Type.Entity)); } public HeaderParser create(String name) { return parsers.get(name.toUpperCase()); } }
7,201
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
ComplexValueHeader.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/mime/impl/ComplexValueHeader.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 3/18/11 11:55 PM */ package xpertss.mime.impl; import xpertss.lang.Strings; import xpertss.mime.Header; import xpertss.mime.HeaderValue; import xpertss.lang.Objects; public class ComplexValueHeader implements Header { private final String name; private final Type type; private final HeaderValue[] values; public ComplexValueHeader(String name, Type type, HeaderValue[] values) { this.name = Objects.notNull(name, "name"); this.type = Objects.notNull(type, "type"); this.values = Objects.notNull(values, "values"); } public String getName() { return name; } public String getValue() { StringBuilder buf = new StringBuilder(); for(HeaderValue value : values) { if(buf.length() > 0) buf.append(", "); buf.append(value.toString()); } return buf.toString(); } public Type getType() { return type; } public int size() { return values.length; } public HeaderValue getValue(int index) { return values[index]; } public HeaderValue getValue(String name) { for(HeaderValue value : values) if(Strings.equalIgnoreCase(name, value.getName())) return value; return null; } public String toString() { return String.format("%s: %s", getName(), getValue()); } }
1,414
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
NamedHeaderValue.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/mime/impl/NamedHeaderValue.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 3/18/11 9:45 PM */ package xpertss.mime.impl; import xpertss.lang.Strings; import xpertss.mime.HeaderValue; import xpertss.mime.Parameter; import xpertss.lang.Objects; public class NamedHeaderValue implements HeaderValue { private final String name; private final String value; private final Parameter[] params; public NamedHeaderValue(String name, String value, Parameter[] params) { this.name = Objects.notNull(name, "name"); this.value = Objects.notNull(value, "value"); this.params = Objects.notNull(params, "params"); } public String getName() { return name; } public String getValue() { if(value.indexOf('"') == 0 && value.lastIndexOf('"') == value.length() - 1) { return value.substring(1, value.length() - 1); } return value; } public int size() { return params.length; } public Parameter getParameter(int index) { return params[index]; } public Parameter getParameter(String name) { for(Parameter param : params) { if(Strings.equalIgnoreCase(name, param.getName())) return param; } return null; } public String toString() { StringBuilder buf = new StringBuilder(getName()).append("=").append(value); for(Parameter param : params) { buf.append("; ").append(param.toString()); } return buf.toString(); } }
1,484
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
SimpleHeaderValue.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/mime/impl/SimpleHeaderValue.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 3/18/11 9:30 PM */ package xpertss.mime.impl; import xpertss.lang.Strings; import xpertss.mime.HeaderValue; import xpertss.mime.Parameter; import xpertss.lang.Objects; public class SimpleHeaderValue implements HeaderValue { private final Parameter[] params; private final String value; public SimpleHeaderValue(String value, Parameter[] params) { this.value = Objects.notNull(value, "value"); this.params = Objects.notNull(params, "params"); } public String getName() { return null; } public String getValue() { if(value.indexOf('"') == 0 && value.lastIndexOf('"') == value.length() - 1) { return value.substring(1, value.length() - 1); } return value; } public int size() { return params.length; } public Parameter getParameter(int index) { return params[index]; } public Parameter getParameter(String name) { for(Parameter param : params) { if(Strings.equalIgnoreCase(name, param.getName())) return param; } return null; } public String toString() { StringBuilder buf = new StringBuilder(value); for(Parameter param : params) { buf.append("; ").append(param.toString()); } return buf.toString(); } }
1,367
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
SimpleParameter.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/mime/impl/SimpleParameter.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 3/18/11 9:42 PM */ package xpertss.mime.impl; import xpertss.lang.Objects; import xpertss.mime.Parameter; public class SimpleParameter implements Parameter { private final String name; private final String value; public SimpleParameter(String name, String value) { this.name = name; this.value = Objects.notNull(value, "value"); } public String getName() { return name; } public String getValue() { return value; } public String toString() { return (name == null) ? value : name + "=" + value; } }
645
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
HeaderParserProvider.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/mime/spi/HeaderParserProvider.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 3/18/11 11:16 AM */ package xpertss.mime.spi; import xpertss.mime.HeaderParser; /** * Service provider interface defining a means to locate HeaderParser's capable * of parsing named header values. */ public interface HeaderParserProvider { /** * Return a HeaderParser implementation for the named header or {@code null} * if this provider does not support the given header. * * @param name The header name for which a parser is desired * @return A parser capable of parsing the named header or {@code null} */ public HeaderParser create(String name); }
655
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
NioReactor.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/nio/NioReactor.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 3/14/11 12:53 PM */ package xpertss.nio; import xpertss.io.NIOUtils; import xpertss.lang.Objects; import xpertss.threads.Threads; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; public class NioReactor implements Runnable, NioService { private final List<NioAction> actions = Collections.synchronizedList(new ArrayList<NioAction>()); private volatile Thread thread; private NioProvider provider; private Selector selector; public NioReactor(NioProvider provider) { this.provider = Objects.notNull(provider, "provider"); } public void execute(NioAction action) { synchronized(this) { if(thread != Thread.currentThread() || action instanceof DeferredNioAction) { if(thread == null) activate(); actions.add(action); selector.wakeup(); } else { executeNow(action); } } } public boolean isSelectorThread() { return Thread.currentThread() == thread; } /** * Returns true if this server is active, false otherwise. */ public boolean isActive() { return (thread != null); } /** * Waits for this server to shutdown. */ public void await() { Threads.join(thread); } /** * Wait for the specified amount of time for this server to shutdown. This * will return false if this returned because it timed out before the server * completely shutdown, otherwise it will return true. * * @param timeout the time to wait * @param unit the unit the timeout value is measured with * @return True if the server shutdown within the allotted time */ public boolean await(long timeout, TimeUnit unit) { Threads.join(thread, timeout, unit); return (thread == null); } private void executeNow(NioAction action) { try { action.execute(selector); } catch(Exception ex) { action.getSelectable().shutdown(ex); } } private void passivate() { synchronized(this) { thread = null; NIOUtils.close(selector); selector = null; } } private void activate() { selector = NIOUtils.openSelector(); thread = provider.newThread(this); thread.start(); } public void run() { do { try { int count = selector.select(10); // Now execute any pending NIO Actions while(actions.size() > 0) executeNow(actions.remove(0)); // Process NIO events if(count > 0) { Set<SelectionKey> selectedKeys = selector.selectedKeys(); for(SelectionKey sk : selectedKeys) { if(sk.attachment() instanceof Selectable) { Selectable select = (Selectable) sk.attachment(); try { if(select instanceof AcceptHandler) { AcceptHandler handler = (AcceptHandler) select; if(sk.isValid() && sk.isAcceptable()) handler.handleAccept(); } else if(select instanceof DataHandler) { DataHandler handler = (DataHandler) select; if(sk.isValid() && sk.isReadable()) handler.handleRead(); if(sk.isValid() && sk.isWritable()) handler.handleWrite(); if(select instanceof ConnectHandler) { ConnectHandler connectable = (ConnectHandler) select; if(sk.isValid() && sk.isConnectable()) connectable.handleConnect(); } } else { assert false : select.getClass().getName(); } } catch(Exception ex) { select.shutdown(ex); } } else { assert sk.attachment() != null : "selection key with no attachment"; assert false : sk.attachment().getClass().getName(); } } selectedKeys.clear(); } // Now check the status of all user sockets Set<SelectionKey> keys = selector.keys(); for(SelectionKey key : keys) { if(key.isValid() && key.attachment() instanceof Checkable) { Checkable session = (Checkable) key.attachment(); try { session.handleCheckup(); } catch(Exception ex) { session.shutdown(ex); } } } } catch(Exception e) { provider.serviceException(e); } } while(!selector.keys().isEmpty() || !actions.isEmpty()); passivate(); } }
5,038
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
ReadyState.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/nio/ReadyState.java
package xpertss.nio; /** * */ public enum ReadyState { Open, Connecting, Connected, Closing, Closed }
126
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
NioStats.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/nio/NioStats.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 3/23/11 1:39 PM */ package xpertss.nio; /** */ public class NioStats { private long time = System.currentTimeMillis(); private long count; public void record(long amount) { if(amount > 0) { time = System.currentTimeMillis(); count += amount; } } public long getCount() { return count; } public long getTime() { return time; } }
475
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
NioService.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/nio/NioService.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 3/14/11 11:24 AM */ package xpertss.nio; public interface NioService { public void execute(NioAction action); public boolean isSelectorThread(); }
222
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
ConnectHandler.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/nio/ConnectHandler.java
package xpertss.nio; import java.io.IOException; /** */ public interface ConnectHandler extends Selectable { public void handleConnect() throws IOException; }
168
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
DataHandler.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/nio/DataHandler.java
/** * Copyright XpertSoftware All rights reserved. * * Date: Aug 12, 2007 * Time: 11:33:54 PM */ package xpertss.nio; import java.io.IOException; public interface DataHandler extends Selectable { public void handleRead() throws IOException; public void handleWrite() throws IOException; }
305
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
NioReader.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/nio/NioReader.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 3/23/11 9:23 AM */ package xpertss.nio; import java.io.IOException; import java.nio.ByteBuffer; public interface NioReader { public boolean readFrom(ByteBuffer src) throws IOException; }
259
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
NioProvider.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/nio/NioProvider.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 3/14/11 12:59 PM */ package xpertss.nio; public interface NioProvider { public Thread newThread(Runnable r); public void serviceException(Exception error); }
233
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
Selectable.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/nio/Selectable.java
/** * Copyright XpertSoftware All rights reserved. * * Date: Aug 12, 2007 * Time: 11:17:40 PM */ package xpertss.nio; import java.nio.channels.SelectableChannel; public interface Selectable { public SelectableChannel getChannel(); public void shutdown(Exception ex); }
286
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
DeferredNioAction.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/nio/DeferredNioAction.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 3/26/11 2:19 PM */ package xpertss.nio; /** * An extension to NioAction who's execution will be deferred until the next * loop of the reactor thread. By default execute calls into the reactor will * execute immediately if the calling thread is the reactor thread. This can * sometimes be undesirable as you want some other action to occur first. By * implementing the DeferredNioAction interface the action will be enqueued * for the next loop allowing all other operations to proceed in the meantime. */ public interface DeferredNioAction extends NioAction { }
636
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
AcceptHandler.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/nio/AcceptHandler.java
/** * Copyright XpertSoftware All rights reserved. * * Date: Aug 12, 2007 * Time: 11:28:38 PM */ package xpertss.nio; import java.io.IOException; public interface AcceptHandler extends Selectable { public void handleAccept() throws IOException; }
260
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
NioSession.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/nio/NioSession.java
package xpertss.nio; import java.io.IOException; import java.net.SocketAddress; import java.net.SocketOption; import java.util.Set; /** */ public interface NioSession { /** * Get the current ready status of this session. */ public ReadyState getReadyState(); /** * Returns the socket address of the remote peer. * * @return The socket address of the remote peer. */ public SocketAddress getRemoteAddress(); /** * Returns the socket address of local machine which is associated with this * session. * * @return The local socket address for this session. */ public SocketAddress getLocalAddress(); /** * This will return the listen address that established this IOSession if it * is a server side session. Otherwise, if it is a client side session this * will return the same value as {@link #getRemoteAddress()}. * * @return The service address associated with this session. */ public SocketAddress getServiceAddress(); /** * Sets the value of a socket option. * * @param name The socket option * @param value The value of the socket option. A value of {@code null} * may be a valid value for some socket options. * @return This session * * @throws UnsupportedOperationException If the socket option is not * supported by this session * @throws IllegalArgumentException If the value is not a valid value * for this socket option * @throws IOException If an I/O error occurs * @see java.net.StandardSocketOptions * @see xpertss.net.OptionalSocketOptions * @see xpertss.net.SSLSocketOptions */ <T> NioSession setOption(SocketOption<T> name, T value) throws IOException; /** * Returns the value of a socket option. * * @param name The socket option * @return The value of the socket option. A value of {@code null} may * be a valid value for some socket options. * @throws UnsupportedOperationException If the socket option is not * supported by this channel * @throws IOException If an I/O error occurs * @see java.net.StandardSocketOptions * @see xpertss.net.OptionalSocketOptions * @see xpertss.net.SSLSocketOptions */ <T> T getOption(SocketOption<T> name) throws IOException; /** * Returns a set of the socket options supported by this channel. * <p/> * This method will continue to return the set of options even after * the session has been closed. * * @return A set of the socket options supported by this session */ Set<SocketOption<?>> supportedOptions(); /** * Returns the time in millis when this session was created. The time is * always measured as the number of milliseconds since midnight, January * 1, 1970 UTC. * * @return The time in millis when this session was created. */ public long getCreationTime(); /** * Returns the time in millis when the last I/O operation occurred. The * time is always measured as the number of milliseconds since midnight, * January 1, 1970 UTC. * * @return The time in millis when the last I/O operation occured. */ public long getLastIoTime(); /** * Returns the time in millis when the last read operation occurred. The * time is always measured as the number of milliseconds since midnight, * January 1, 1970 UTC. * * @return The time in millis when the last read operation occurred */ public long getLastReadTime(); /** * Returns the time in millis when the lst write operation occurred. The * time is always measured as the number of milliseconds since midnight, * January 1, 1970 UTC. * * @return The time in millis when the lst write operation occurred */ public long getLastWriteTime(); /** * Return the number of bytes written to this session. */ public long getBytesWritten(); /** * Return the number of bytes read from this session. */ public long getBytesRead(); /** * Returns the value of user-defined attribute of this session. * * @param key the key of the attribute * @return <tt>null</tt> if there is no attribute with the specified key */ public Object getAttribute(String key); /** * Sets a user-defined attribute. * * @param key the key of the attribute * @param value the value of the attribute */ public void setAttribute(String key, Object value); /** * Removes a user-defined attribute with the specified key. * * @param key The key identifying the attribute to remove */ public void removeAttribute(String key); /** * Returns <tt>true</tt> if this session contains the attribute with * the specified <tt>key</tt>. * * @param key The key identifying the attribute to check existance of * @return true if the named attribute exists in this session */ public boolean hasAttribute(String key); /** * Returns the set of keys of all user-defined attributes. * * @return A set of attribute keys currently defined */ public Set<String> getAttributeKeys(); }
5,266
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
NioAction.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/nio/NioAction.java
/** * Copyright XpertSoftware All rights reserved. * * Date: Aug 12, 2007 * Time: 11:19:27 PM */ package xpertss.nio; import java.io.IOException; import java.nio.channels.Selector; public interface NioAction { public void execute(Selector selector) throws IOException; public Selectable getSelectable(); }
329
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
Checkable.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/nio/Checkable.java
package xpertss.nio; import java.io.IOException; /** * A {@link Selectable} subclass which wishes to be periodically checked so * that it may validate timeouts and other state. */ public interface Checkable extends Selectable { public void handleCheckup() throws IOException; }
288
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
NioWriter.java
/FileExtraction/Java_unseen/cfloersch_RtspClient/src/main/java/xpertss/nio/NioWriter.java
/** * Copyright XpertSoftware All rights reserved. * * Date: 3/23/11 9:24 AM */ package xpertss.nio; import java.io.IOException; import java.nio.ByteBuffer; public interface NioWriter { public boolean writeTo(ByteBuffer dst) throws IOException; }
258
Java
.java
cfloersch/RtspClient
18
8
0
2015-04-03T17:38:53Z
2023-06-15T15:10:43Z
module-info.java
/FileExtraction/Java_unseen/bithatch_snake/snake-widgets/src/main/java/module-info.java
module uk.co.bithatch.snake.widgets { requires transitive javafx.controls; requires transitive javafx.graphics; requires transitive javafx.fxml; requires transitive com.sshtools.icongenerator.javafx; exports uk.co.bithatch.snake.widgets; opens uk.co.bithatch.snake.widgets; }
294
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
SelectableArea.java
/FileExtraction/Java_unseen/bithatch_snake/snake-widgets/src/main/java/uk/co/bithatch/snake/widgets/SelectableArea.java
package uk.co.bithatch.snake.widgets; import java.util.List; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ObservableValue; import javafx.css.CssMetaData; import javafx.css.SimpleStyleableObjectProperty; import javafx.css.Styleable; import javafx.css.StyleableProperty; import javafx.css.StyleablePropertyFactory; import javafx.event.EventHandler; import javafx.geometry.BoundingBox; import javafx.geometry.Point2D; import javafx.scene.Node; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Pane; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; public class SelectableArea extends StackPane { private static final StyleablePropertyFactory<SelectableArea> FACTORY = new StyleablePropertyFactory<>( StackPane.getClassCssMetaData()); private static final CssMetaData<SelectableArea, Color> OUTLINE_COLOR = FACTORY .createColorCssMetaData("-snake-outline-color", s -> s.outlineColorProperty, Color.GRAY, true); private final StyleableProperty<Color> outlineColorProperty = new SimpleStyleableObjectProperty<>(OUTLINE_COLOR, this, "outlineColor"); private ObjectProperty<BoundingBox> selectableArea = new SimpleObjectProperty<>(null, "selectableArea"); private Point2D dragStart; private SelectPane selectPane; private DragWindow dragWindow; private EventHandler<MouseEvent> defaultClickHandler; private Node content; private final BooleanProperty selectableProperty = new SimpleBooleanProperty(true); public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() { return FACTORY.getCssMetaData(); } public SelectableArea() { getStyleClass().add("selectable-area"); selectPane = new SelectPane(); dragWindow = new DragWindow(); getChildren().add(selectPane); getChildren().add(dragWindow); dragWindow.widthProperty().bind(widthProperty()); dragWindow.heightProperty().bind(heightProperty()); selectableProperty.addListener((e, o, n) -> { if (!n && getSelectableArea() != null) setSelectableArea(null); }); } public EventHandler<MouseEvent> getDefaultClickHandler() { return defaultClickHandler; } public void setDefaultClickHandler(EventHandler<MouseEvent> defaultClickHandler) { this.defaultClickHandler = defaultClickHandler; } public void setContent(Node content) { if (this.content != null) getChildren().remove(content); getChildren().add(1, content); this.content = content; } public ObjectProperty<BoundingBox> selectableArea() { return selectableArea; } public BoundingBox getSelectableArea() { return selectableArea.get(); } public void setSelectableArea(BoundingBox selection) { this.selectableArea.set(selection); } @Override public List<CssMetaData<? extends Styleable, ?>> getCssMetaData() { return FACTORY.getCssMetaData(); } public final Color getOutlineColor() { return outlineColorProperty.getValue(); } @SuppressWarnings("unchecked") public ObservableValue<Color> outlineColorProperty() { return (ObservableValue<Color>) outlineColorProperty; } public final void setOutlineColor(Color lineColor) { outlineColorProperty.setValue(lineColor); } public final boolean isSelectable() { return selectableProperty.getValue(); } public BooleanProperty selectableProperty() { return selectableProperty; } public final void setSelectable(boolean selectable) { selectableProperty.setValue(selectable); } class SelectPane extends Pane { SelectPane() { setOnMousePressed((e) -> { if (isSelectable()) { dragStart = new Point2D(e.getX(), e.getY()); dragWindow.draw(); } }); setOnMouseDragged((e) -> { if (dragStart == null) /* Can get a drag without getting a press */ return; BoundingBox current = selectableArea.get(); double currX = dragStart.getX(); double currY = dragStart.getY(); double evtX = e.getX(); double evtY = e.getY(); if (current == null) { double dist = distance(currX, currY, evtX, evtY); if (dist < 10) { /* Not yet enough to start drag */ return; } } double szw = evtX - currX; double szh = evtY - currY; if (szw < 0) { currX = evtX; szw = current == null ? 0 : current.getMaxX() - currX; } if (szh < 0) { currY = evtY; szh = current == null ? 0 : current.getMaxY() - currY; } setSelectableArea(new BoundingBox(currX, currY, szw, szh)); dragWindow.draw(); e.consume(); }); setOnMouseReleased((e) -> { if (getSelectableArea() != null) { dragStart = null; setSelectableArea(null); dragWindow.draw(); e.consume(); } else if (defaultClickHandler != null) defaultClickHandler.handle(e); }); } } class DragWindow extends Canvas { DragWindow() { super(8, 8); draw(); setMouseTransparent(true); widthProperty().addListener(evt -> draw()); heightProperty().addListener(evt -> draw()); } @Override public boolean isResizable() { return true; } @Override public double minWidth(double height) { return content == null ? 0 : content.minWidth(height); } @Override public double minHeight(double width) { return content == null ? 0 : content.minHeight(width); } @Override public double prefWidth(double height) { return content == null ? 0 : content.prefWidth(height); } @Override public double prefHeight(double width) { return content == null ? 0 : content.prefHeight(width); } protected void draw() { GraphicsContext ctx = getGraphicsContext2D(); double canvasWidth = boundsInLocalProperty().get().getWidth(); double canvasHeight = boundsInLocalProperty().get().getHeight(); ctx.clearRect(0, 0, canvasWidth, canvasHeight); BoundingBox rect = selectableArea.get(); if (rect != null) { Color col = getOutlineColor(); ctx.setFill(col); ctx.setGlobalAlpha(0.25); ctx.fillRect(rect.getMinX(), rect.getMinY(), rect.getWidth(), rect.getHeight()); ctx.setGlobalAlpha(1); ctx.setStroke(col); ctx.beginPath(); ctx.setLineWidth(0.5); ctx.moveTo(rect.getMinX(), rect.getMinY()); ctx.lineTo(rect.getMinX(), rect.getMaxY()); ctx.lineTo(rect.getMaxX(), rect.getMaxY()); ctx.lineTo(rect.getMaxX(), rect.getMinY()); ctx.lineTo(rect.getMinX(), rect.getMinY()); ctx.stroke(); ctx.closePath(); } } } static double distance(double startX, double startY, double endX, double endY) { return Math.sqrt(Math.pow(endX - startX, 2) + Math.pow(endY - startY, 2)); } }
6,762
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
AbstractGraphic.java
/FileExtraction/Java_unseen/bithatch_snake/snake-widgets/src/main/java/uk/co/bithatch/snake/widgets/AbstractGraphic.java
package uk.co.bithatch.snake.widgets; import java.util.List; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ObservableValue; import javafx.css.CssMetaData; import javafx.css.PseudoClass; import javafx.css.SimpleStyleableObjectProperty; import javafx.css.Styleable; import javafx.css.StyleableProperty; import javafx.css.StyleablePropertyFactory; import javafx.scene.canvas.Canvas; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; public abstract class AbstractGraphic extends Canvas { private static final StyleablePropertyFactory<AbstractGraphic> FACTORY = new StyleablePropertyFactory<>( Canvas.getClassCssMetaData()); private static final CssMetaData<AbstractGraphic, Color> OUTLINE_COLOR = FACTORY .createColorCssMetaData("-snake-outline-color", s -> s.outlineColorProperty, Color.GRAY, true); public abstract void draw(); protected static final PseudoClass PSEUDO_CLASS_SELECTED = PseudoClass.getPseudoClass("selected"); public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() { return FACTORY.getCssMetaData(); } private final StyleableProperty<Color> outlineColorProperty = new SimpleStyleableObjectProperty<>(OUTLINE_COLOR, this, "outlineColor"); protected final ObjectProperty<Paint> ledColorProperty = new SimpleObjectProperty<>(this, "ledColor"); protected final BooleanProperty selectedProperty = new SimpleBooleanProperty(); public AbstractGraphic() { super(); } public AbstractGraphic(double width, double height) { super(width, height); widthProperty().addListener((e, o, n) -> draw()); heightProperty().addListener((e, o, n) -> draw()); ledColorProperty.addListener((e, o, n) -> draw()); selectedProperty.addListener((c, o, n) -> { pseudoClassStateChanged(PSEUDO_CLASS_SELECTED, isSelected()); applyCss(); draw(); }); } @Override public List<CssMetaData<? extends Styleable, ?>> getCssMetaData() { return FACTORY.getCssMetaData(); } public final Color getOutlineColor() { return outlineColorProperty.getValue(); } @SuppressWarnings("unchecked") public ObservableValue<Color> outlineColorProperty() { return (ObservableValue<Color>) outlineColorProperty; } public final void setOutlineColor(Color outlineColor) { outlineColorProperty.setValue(outlineColor); } public final boolean isSelected() { return selectedProperty.getValue(); } public BooleanProperty selectedProperty() { return selectedProperty; } public final void setSelected(boolean selected) { selectedProperty.setValue(selected); } public final Paint getLedColor() { return ledColorProperty.getValue(); } public ObservableValue<Paint> ledColorProperty() { return (ObservableValue<Paint>) ledColorProperty; } public final void setLedColor(Paint ledColor) { ledColorProperty.setValue(ledColor); } }
2,995
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
ColorBar.java
/FileExtraction/Java_unseen/bithatch_snake/snake-widgets/src/main/java/uk/co/bithatch/snake/widgets/ColorBar.java
package uk.co.bithatch.snake.widgets; import java.util.List; //import java.util.ResourceBundle; import java.util.ResourceBundle; import com.sshtools.icongenerator.AwesomeIcon; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.geometry.Bounds; import javafx.geometry.Point2D; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.Tooltip; import javafx.scene.effect.Glow; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; import javafx.stage.Popup; import javafx.stage.Window; import javafx.util.Duration; public class ColorBar extends HBox implements ColorChooser { final static ResourceBundle bundle = ResourceBundle.getBundle(ColorBar.class.getName()); final static Color[] COLORS = new Color[] { Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN, Color.BLUE, Color.INDIGO, Color.VIOLET, Color.WHITE }; final static String[] COLOR_NAMES = new String[] { bundle.getString("red"), bundle.getString("orange"), bundle.getString("yellow"), bundle.getString("green"), bundle.getString("blue"), bundle.getString("indigo"), bundle.getString("violet"), bundle.getString("white") }; private Color originalColor = Color.CRIMSON; private ObjectProperty<Color> color = new SimpleObjectProperty<>(Color.CRIMSON); private final Popup popup; private final LuxColorPalette palette; public ColorBar() { setAlignment(Pos.CENTER_LEFT); getStyleClass().add("iconBar"); palette = new LuxColorPalette(this); popup = new Popup(); popup.getContent().add(palette); GeneratedIcon icon = new GeneratedIcon(); JavaFX.size(icon, 32, 32); icon.setIcon(AwesomeIcon.EYEDROPPER); icon.getStyleClass().add("color-bar-icon"); icon.setStyle("-icon-color: black"); configureIcon(icon); icon.setOnMouseClicked(event -> { /* * JavaFX makes it impossible to augment the root user agent stylesheet in a way * that cascades to all new windows, of which Popup is one. This works around * the problem by copying the stylesheets from the picker buttons root (the most * likely place for the stylesheets). */ addIfNotAdded(popup.getScene().getRoot().getStylesheets(), ColorBar.this.getScene().getWindow().getScene().getRoot().getStylesheets()); originalColor = getColor(); palette.setColor(originalColor); Scene scene = getScene(); Window window = scene.getWindow(); popup.show(window); popup.setAutoHide(true); popup.setOnAutoHide(event2 -> updateHistory()); Bounds buttonBounds = getBoundsInLocal(); Point2D point = localToScreen(buttonBounds.getMinX(), buttonBounds.getMaxY()); popup.setX(point.getX() - 9); popup.setY(point.getY() - 9); }); getChildren().add(wrap(icon, bundle.getString("choose"))); int i = 0; for (Color c : COLORS) { GeneratedIcon colIcon = new GeneratedIcon(); colIcon.getStyleClass().add("color-bar-icon"); colIcon.setStyle("-icon-opacity: 1"); colIcon.setStyle("-icon-color: " + JavaFX.toHex(c)); JavaFX.size(colIcon, 16, 16); colIcon.setOnMouseClicked(event -> { setColor(c); }); configureIcon(colIcon); getChildren().add(wrap(colIcon, COLOR_NAMES[i++])); } colorProperty().addListener((e, o, n) -> icon.setStyle("-icon-color: " + JavaFX.toHex(n))); GeneratedIcon resetIcon = new GeneratedIcon(); JavaFX.size(resetIcon, 32, 32); resetIcon.setIcon(AwesomeIcon.ERASER); resetIcon.getStyleClass().add("color-bar-icon"); resetIcon.setStyle("-icon-color: black"); configureIcon(resetIcon); resetIcon.setOnMouseClicked(event -> { setColor(Color.BLACK); }); getChildren().add(wrap(resetIcon, bundle.getString("reset"))); } protected Label wrap(Node icon, String text) { Label l = new Label(); l.setGraphic(icon); Tooltip tooltip = new Tooltip(text); tooltip.setShowDelay(Duration.millis(200)); l.setTooltip(tooltip); return l; } protected void configureIcon(GeneratedIcon colIcon) { colIcon.setOnMouseEntered((e) -> colIcon.setEffect(new Glow(0.9))); colIcon.setOnMouseExited((e) -> colIcon.setEffect(null)); } /** * Store the current color in the history palette. */ public void updateHistory() { palette.addToHistory(color.get()); } public ObjectProperty<Color> colorProperty() { return color; } public void setColor(Color value) { color.set(value); palette.updateRandomColorSamples(); } public Color getColor() { return color.get(); } /** * Hide the color picker popup. */ public void hidePopup() { popup.hide(); } public void revertToOriginalColor() { setColor(originalColor); } public static List<String> addIfNotAdded(List<String> target, List<String> source) { for (String s : source) { if (!target.contains(s)) target.add(s); } return target; } }
4,864
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
KeyGraphic.java
/FileExtraction/Java_unseen/bithatch_snake/snake-widgets/src/main/java/uk/co/bithatch/snake/widgets/KeyGraphic.java
package uk.co.bithatch.snake.widgets; import javafx.scene.canvas.GraphicsContext; import javafx.scene.paint.Paint; public class KeyGraphic extends AbstractGraphic { public KeyGraphic() { this(22, 22); } public KeyGraphic(double width, double height) { super(width, height); } @Override public void draw() { Paint outlineColor = getOutlineColor(); Paint ledColor = getLedColor(); if(ledColor == null) ledColor = outlineColor; GraphicsContext ctx = getGraphicsContext2D(); double canvasWidth = boundsInLocalProperty().get().getWidth(); double canvasHeight = boundsInLocalProperty().get().getHeight(); ctx.clearRect(0, 0, canvasWidth, canvasHeight); ctx.setStroke(outlineColor); int lineWidth = 2; ctx.setLineWidth(lineWidth); ctx.strokeRect(lineWidth, lineWidth, canvasWidth - (lineWidth * 2), canvasHeight - (lineWidth * 2)); ctx.setFill(ledColor); ctx.fillRect(canvasWidth * 0.25f, canvasWidth * 0.25f, canvasWidth / 2f, canvasHeight / 2f); } }
993
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
AnimPane.java
/FileExtraction/Java_unseen/bithatch_snake/snake-widgets/src/main/java/uk/co/bithatch/snake/widgets/AnimPane.java
package uk.co.bithatch.snake.widgets; import javafx.animation.Animation; import javafx.animation.FadeTransition; import javafx.animation.Interpolator; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.Timeline; import javafx.scene.Node; import javafx.scene.layout.StackPane; import javafx.util.Duration; public class AnimPane extends StackPane { private Duration duration = Duration.millis(500); private Interpolator interpolator = Interpolator.EASE_BOTH; private Animation waiting; public Interpolator getInterpolator() { return interpolator; } public void setInterpolator(Interpolator interpolator) { this.interpolator = interpolator; } public Duration getDuration() { return duration; } public void setDuration(Duration duration) { this.duration = duration; } public void setContent(Direction dir, Node node) { doAnim(dir, node); } protected Node doAnim(Direction dir, Node node) { if(waiting != null) { waiting.stop(); waiting.getOnFinished().handle(null); waiting = null; } switch (dir) { case FROM_LEFT: return slideInFromLeft(node); case FROM_RIGHT: return slideInFromRight(node); case FROM_TOP: return slideInFromTop(node); case FROM_BOTTOM: return slideInFromBottom(node); default: return fadeIn(node); } } Node fadeIn(Node paneToAdd) { var paneToRemove = getChildren().isEmpty() ? null : getChildren().get(0); getChildren().add(paneToAdd); var fadeInTransition = new FadeTransition(duration); if (paneToRemove != null) { var fadeOutTransition = new FadeTransition(duration); fadeOutTransition.setOnFinished(evt -> { waiting = null; getChildren().remove(paneToRemove); }); fadeOutTransition.setNode(paneToRemove); fadeOutTransition.setFromValue(1); fadeOutTransition.setToValue(0); fadeOutTransition.play(); waiting = fadeOutTransition; } fadeInTransition.setNode(paneToAdd); fadeInTransition.setFromValue(0); fadeInTransition.setToValue(1); fadeInTransition.play(); return paneToRemove; } Node fadeOut(Node paneToAdd) { var paneToRemove = getChildren().get(0); getChildren().add(0, paneToAdd); var fadeOutTransition = new FadeTransition(duration); fadeOutTransition.setOnFinished(evt -> { waiting = null; getChildren().remove(paneToRemove); }); waiting = fadeOutTransition; fadeOutTransition.setNode(paneToRemove); fadeOutTransition.setFromValue(1); fadeOutTransition.setToValue(0); fadeOutTransition.play(); return paneToRemove; } Node slideInFromLeft(Node paneToAdd) { var paneToRemove = getChildren().get(0); paneToAdd.translateXProperty().set(-1 * getWidth()); getChildren().add(paneToAdd); var keyValue = new KeyValue(paneToAdd.translateXProperty(), 0, interpolator); KeyValue outKeyValue = new KeyValue(paneToRemove.translateXProperty(), getWidth(), interpolator); var keyFrame = new KeyFrame(duration, keyValue, outKeyValue); var timeline = new Timeline(keyFrame); timeline.setOnFinished(evt -> { getChildren().remove(paneToRemove); }); timeline.play(); waiting = timeline; return paneToRemove; } Node slideInFromRight(Node paneToAdd) { var paneToRemove = getChildren().get(0); paneToAdd.translateXProperty().set(getWidth()); getChildren().add(paneToAdd); var keyValue = new KeyValue(paneToAdd.translateXProperty(), 0, interpolator); KeyValue outKeyValue = new KeyValue(paneToRemove.translateXProperty(), -1 * getWidth(), interpolator); var keyFrame = new KeyFrame(duration, keyValue, outKeyValue); var timeline = new Timeline(keyFrame); timeline.setOnFinished(evt -> { waiting = null; getChildren().remove(paneToRemove); }); timeline.play(); waiting = timeline; return paneToRemove; } Node slideInFromBottom(Node paneToAdd) { var paneToRemove = getChildren().get(0); paneToAdd.translateYProperty().set(getHeight()); getChildren().add(paneToAdd); var keyValue = new KeyValue(paneToAdd.translateYProperty(), 0, interpolator); KeyValue outKeyValue = new KeyValue(paneToRemove.translateYProperty(), -getHeight(), interpolator); var keyFrame = new KeyFrame(duration, keyValue, outKeyValue); var timeline = new Timeline(keyFrame); timeline.setOnFinished(evt -> { waiting = null; getChildren().remove(paneToRemove); }); timeline.play(); waiting = timeline; return paneToRemove; } Node slideInFromTop(Node paneToAdd) { var paneToRemove = getChildren().get(0); paneToAdd.translateYProperty().set(-1 * getHeight()); getChildren().add(paneToAdd); var keyValue = new KeyValue(paneToAdd.translateYProperty(), 0, interpolator); KeyValue outKeyValue = new KeyValue(paneToRemove.translateYProperty(), getHeight(), interpolator); var keyFrame = new KeyFrame(duration, keyValue, outKeyValue); var timeline = new Timeline(keyFrame); timeline.setOnFinished(evt -> { waiting = null; getChildren().remove(paneToRemove); }); timeline.play(); waiting = timeline; return paneToRemove; } public Node getContent() { return getChildren().isEmpty() ? null : getChildren().get(getChildren().size() - 1); } }
5,154
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
GeneratedIcon.java
/FileExtraction/Java_unseen/bithatch_snake/snake-widgets/src/main/java/uk/co/bithatch/snake/widgets/GeneratedIcon.java
package uk.co.bithatch.snake.widgets; import java.util.List; import com.sshtools.icongenerator.AwesomeIcon; import com.sshtools.icongenerator.IconBuilder; import com.sshtools.icongenerator.IconBuilder.IconShape; import com.sshtools.icongenerator.IconBuilder.TextContent; import com.sshtools.icongenerator.javafx.JavaFXCanvasGenerator; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.beans.value.ObservableValue; import javafx.css.CssMetaData; import javafx.css.SimpleStyleableDoubleProperty; import javafx.css.SimpleStyleableObjectProperty; import javafx.css.Styleable; import javafx.css.StyleableProperty; import javafx.css.StyleablePropertyFactory; import javafx.scene.canvas.Canvas; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.text.Font; public class GeneratedIcon extends Pane { private static final StyleablePropertyFactory<GeneratedIcon> FACTORY = new StyleablePropertyFactory<>( Pane.getClassCssMetaData()); private static final CssMetaData<GeneratedIcon, Color> BORDER_COLOR = FACTORY .createColorCssMetaData("-icon-border-color", s -> s.borderColorProperty, null, false); private static final CssMetaData<GeneratedIcon, Number> BORDER_WIDTH = FACTORY .createSizeCssMetaData("-icon-border-width", s -> s.borderWidthProperty, -1, false); private static final CssMetaData<GeneratedIcon, Number> ICON_OPACITY = FACTORY .createSizeCssMetaData("-icon-opacity", s -> s.iconOpacityProperty, -1, false); private static final CssMetaData<GeneratedIcon, Number> FONT_SIZE = FACTORY.createSizeCssMetaData("-icon-font-size", s -> s.fontSizeProperty, -1, true); private static final CssMetaData<GeneratedIcon, Color> TEXT_COLOR = FACTORY .createColorCssMetaData("-icon-text-color", s -> s.textColorProperty, null, false); private static final CssMetaData<GeneratedIcon, Color> ICON_COLOR = FACTORY.createColorCssMetaData("-icon-color", s -> s.colorProperty, null, false); private static final CssMetaData<GeneratedIcon, Font> FONT = FACTORY.createFontCssMetaData("-icon-text-font", s -> s.fontProperty, null, false); private static final CssMetaData<GeneratedIcon, String> ICON_SHAPE = FACTORY.createStringCssMetaData("-icon-shape", s -> s.iconShapeProperty, null, false); private static final CssMetaData<GeneratedIcon, String> TEXT_CONTENT = FACTORY .createStringCssMetaData("-icon-text-content", s -> s.textContentProperty, null, false); private final StyleableProperty<Color> borderColorProperty = new SimpleStyleableObjectProperty<>(BORDER_COLOR, this, "borderColor"); private final StyleableProperty<Font> fontProperty = new SimpleStyleableObjectProperty<>(FONT, this, "font"); private final StyleableProperty<Number> borderWidthProperty = new SimpleStyleableDoubleProperty(BORDER_WIDTH, this, "borderWidth"); private final StyleableProperty<Number> iconOpacityProperty = new SimpleStyleableDoubleProperty(ICON_OPACITY, this, "iconOpacity"); private final StyleableProperty<Number> fontSizeProperty = new SimpleStyleableDoubleProperty(FONT_SIZE, this, "fontSize"); private final StyleableProperty<Color> textColorProperty = new SimpleStyleableObjectProperty<>(TEXT_COLOR, this, "textColor"); private final StyleableProperty<Color> colorProperty = new SimpleStyleableObjectProperty<>(ICON_COLOR, this, "color"); private final StyleableProperty<String> iconShapeProperty = new SimpleStyleableObjectProperty<>(ICON_SHAPE, this, "iconShape"); private final StyleableProperty<String> textContentProperty = new SimpleStyleableObjectProperty<>(TEXT_CONTENT, this, "textContent"); private final StringProperty textProperty = new SimpleStringProperty(); private final ObjectProperty<AwesomeIcon> iconProperty = new SimpleObjectProperty<AwesomeIcon>(this, "icon", null); private IconBuilder ib; public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() { return FACTORY.getCssMetaData(); } public GeneratedIcon() { ib = new IconBuilder(); /* NOTE: Hack to make it work inside SceneBuilder */ ib.generator(Canvas.class, new JavaFXCanvasGenerator()); widthProperty().addListener((c, o, n) -> { ib.width((float) prefWidth(0)); rebuild(); }); heightProperty().addListener((c, o, n) -> { ib.height((float) prefHeight(0)); rebuild(); }); borderColorProperty().addListener((c, o, n) -> { if (n == null) ib.borderColor(IconBuilder.AUTO_COLOR); else ib.borderColor(JavaFX.encode(n)); rebuild(); }); fontProperty().addListener((c, o, n) -> { resetFont(); rebuild(); }); borderWidthProperty().addListener((c, o, n) -> { if (getBorderWidth() == -1) ib.border(0); else ib.border((float) getBorderWidth()); rebuild(); }); iconOpacityProperty().addListener((c, o, n) -> { int opac = (int) (n.doubleValue() * 255.0); ib.backgroundOpacity(opac); rebuild(); }); textColorProperty().addListener((c, o, n) -> { if (n == null) ib.textColor(IconBuilder.AUTO_TEXT_COLOR); else ib.textColor(JavaFX.encode(getTextColor())); rebuild(); }); colorProperty().addListener((c, o, n) -> { if (n == null) { ib.color(IconBuilder.AUTO_COLOR); } else { ib.color(JavaFX.encode(getColor())); } rebuild(); }); iconShapeProperty().addListener((c, o, n) -> { if (n == null) ib.shape(IconShape.AUTOMATIC); else ib.shape(getIconShape()); rebuild(); }); textContentProperty().addListener((c, o, n) -> { ib.textContent(n == null ? null : TextContent.valueOf(n)); rebuild(); }); textProperty().addListener((c, o, n) -> { ib.text(n); rebuild(); }); iconProperty().addListener((c, o, n) -> { ib.icon(n); rebuild(); }); fontSizeProperty().addListener((c, o, n) -> { resetFont(); rebuild(); }); setupIcon(); } void setupIcon() { ib.width((float) prefWidth(0)); ib.height((float) prefHeight(0)); ib.text(getText()); if (getTextContent() != null) ib.textContent(getTextContent()); if (getColor() != null) ib.color(JavaFX.encode(getColor())); if (getTextColor() != null) ib.textColor(JavaFX.encode(getTextColor())); if (getIconShape() != null) ib.shape(getIconShape()); if (getBorderWidth() != -1) ib.border((float) getBorderWidth()); if (getBorderColor() != null) ib.borderColor(JavaFX.encode(getBorderColor())); if (getIconOpacity() != -1) { int opac = (int) (getIconOpacity() * 255.0); ib.backgroundOpacity(opac); } resetFont(); if (getIcon() != null) ib.icon(getIcon()); ib.bold(true); rebuild(); } protected void resetFont() { int fs = getFontSize(); if (getFont() != null) { ib.fontName(getFont().getFamily()); if (fs < 1) fs = (int) (getPrefWidth() * 0.5f); } if (fs > 0) { ib.fontSize(fs); } else ib.fontSize(0); } protected void rebuild() { Canvas build = ib.build(Canvas.class); if (getChildren().isEmpty()) getChildren().add(build); else getChildren().set(0, build); } @Override public List<CssMetaData<? extends Styleable, ?>> getCssMetaData() { return FACTORY.getCssMetaData(); } public final Color getBorderColor() { return borderColorProperty.getValue(); } @SuppressWarnings("unchecked") public ObservableValue<Color> borderColorProperty() { return (ObservableValue<Color>) borderColorProperty; } public final void setBorderColor(Color borderColor) { borderColorProperty.setValue(borderColor); } public final double getBorderWidth() { return borderWidthProperty.getValue().doubleValue(); } @SuppressWarnings("unchecked") public ObservableValue<Number> borderWidthProperty() { return (ObservableValue<Number>) borderWidthProperty; } public final void setBorderWidth(double borderWidth) { borderWidthProperty.setValue(borderWidth); } public final Color getTextColor() { return textColorProperty.getValue(); } @SuppressWarnings("unchecked") public ObservableValue<Color> textColorProperty() { return (ObservableValue<Color>) textColorProperty; } public final void setTextColor(Color textColor) { textColorProperty.setValue(textColor); } public final Color getColor() { return colorProperty.getValue(); } @SuppressWarnings("unchecked") public ObservableValue<Color> colorProperty() { return (ObservableValue<Color>) colorProperty; } public final void setColor(Color color) { colorProperty.setValue(color); } public final Font getFont() { return fontProperty.getValue(); } public final int getFontSize() { return fontSizeProperty.getValue().intValue(); } public final double getIconOpacity() { return iconOpacityProperty.getValue().doubleValue(); } @SuppressWarnings("unchecked") public ObservableValue<Font> fontProperty() { return (ObservableValue<Font>) fontProperty; } @SuppressWarnings("unchecked") public ObservableValue<Number> fontSizeProperty() { return (ObservableValue<Number>) fontSizeProperty; } public final void setFont(Font font) { fontProperty.setValue(font); } public final void setFontSize(int fontSize) { fontSizeProperty.setValue(fontSize); } public final void setIconOpacity(double iconOpacity) { iconOpacityProperty.setValue(iconOpacity); } public final IconShape getIconShape() { return iconShapeProperty.getValue() == null ? null : IconShape.valueOf(iconShapeProperty.getValue()); } @SuppressWarnings("unchecked") public ObservableValue<String> iconShapeProperty() { return (ObservableValue<String>) iconShapeProperty; } public final void setIconShape(IconShape shape) { iconShapeProperty.setValue(shape == null ? null : shape.name()); } public final TextContent getTextContent() { return textContentProperty.getValue() == null ? null : TextContent.valueOf(textContentProperty.getValue()); } @SuppressWarnings("unchecked") public ObservableValue<String> textContentProperty() { return (ObservableValue<String>) textContentProperty; } public final void setTextContent(TextContent textContent) { textContentProperty.setValue(textContent == null ? null : textContent.name()); } public final String getText() { return textProperty.getValue(); } public ObservableValue<String> textProperty() { return (ObservableValue<String>) textProperty; } public final void setText(String text) { textProperty.setValue(text); } public final AwesomeIcon getIcon() { return iconProperty.getValue(); } public ObservableValue<AwesomeIcon> iconProperty() { return (ObservableValue<AwesomeIcon>) iconProperty; } @SuppressWarnings("unchecked") public ObservableValue<Number> iconOpacityProperty() { return (ObservableValue<Number>) iconOpacityProperty; } public final void setIcon(AwesomeIcon icon) { iconProperty.setValue(icon); } }
10,890
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
SlideyStack.java
/FileExtraction/Java_unseen/bithatch_snake/snake-widgets/src/main/java/uk/co/bithatch/snake/widgets/SlideyStack.java
package uk.co.bithatch.snake.widgets; import java.util.Iterator; import java.util.Stack; import javafx.scene.Node; public class SlideyStack extends AnimPane { class Op { Direction dir; Node node; Op(Direction dir, Node node) { this.dir = dir; this.node = node; } } private Stack<Op> ops = new Stack<>(); public boolean isEmpty() { return ops.isEmpty(); } public void remove(Node node) { for (Iterator<Op> opIt = ops.iterator(); opIt.hasNext();) { Op op = opIt.next(); if (op.node == node) { opIt.remove(); getChildren().remove(op.node); break; } } } public void pop() { Op op = ops.pop(); doAnim(op.dir.opposite(), op.node); } public void push(Direction dir, Node node) { ops.push(new Op(dir, doAnim(dir, node))); } }
788
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
JavaFX.java
/FileExtraction/Java_unseen/bithatch_snake/snake-widgets/src/main/java/uk/co/bithatch/snake/widgets/JavaFX.java
package uk.co.bithatch.snake.widgets; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import javafx.animation.FadeTransition; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.control.ButtonBase; import javafx.scene.control.ListView; import javafx.scene.control.Tooltip; import javafx.scene.effect.Glow; import javafx.scene.image.ImageView; import javafx.scene.layout.Region; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.FileChooser; import javafx.util.Duration; public class JavaFX { static Text helper = new Text(); /** * Clips the children of the specified {@link Region} to its current size. This * requires attaching a change listener to the region’s layout bounds, as JavaFX * does not currently provide any built-in way to clip children. * * @param region the {@link Region} whose children to clip * @param arc the {@link Rectangle#arcWidth} and {@link Rectangle#arcHeight} * of the clipping {@link Rectangle} * @throws NullPointerException if {@code region} is {@code null} */ public static void clipChildren(Region region, double arc) { final Rectangle outputClip = new Rectangle(); outputClip.setArcWidth(arc); outputClip.setArcHeight(arc); region.setClip(outputClip); region.layoutBoundsProperty().addListener((ov, oldValue, newValue) -> { outputClip.setWidth(newValue.getWidth()); outputClip.setHeight(newValue.getHeight()); }); } public static void bindManagedToVisible(Node... node) { for (Node n : node) { n.managedProperty().bind(n.visibleProperty()); } } public static void fadeHide(Node node, float seconds) { fadeHide(node, seconds, null); } public static void fadeHide(Node node, float seconds, EventHandler<ActionEvent> onFinish) { FadeTransition anim = new FadeTransition(Duration.seconds(seconds)); anim.setCycleCount(1); anim.setNode(node); anim.setFromValue(1); anim.setToValue(0); anim.play(); if (onFinish != null) anim.onFinishedProperty().set(onFinish); } public static double computeTextWidth(Font font, String text, double wrappingWidth) { helper.setText(text); helper.setFont(font); helper.setWrappingWidth(0); double w = Math.min(helper.prefWidth(-1), wrappingWidth); helper.setWrappingWidth((int) Math.ceil(w)); return Math.ceil(helper.getLayoutBounds().getWidth()); } public static double computeTextHeight(Font font, String text, double wrappingWidth) { helper.setText(text); helper.setFont(font); helper.setWrappingWidth((int) wrappingWidth); return helper.getLayoutBounds().getHeight(); } public static void selectFilesDir(FileChooser fileChooser, String path) { Path dir = Paths.get(path); Path file = dir; 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()); } fileChooser.setInitialFileName(file.getFileName().toString()); } public static void size(Region node, double width, double height) { node.setPrefHeight(height); node.setPrefWidth(width); node.setMaxHeight(height); node.setMaxWidth(width); node.setMinHeight(height); node.setMinWidth(width); } public static void sizeToImage(ButtonBase button, double width, double height) { int sz = (int) width; int df = sz / 8; sz -= df; if (button.getGraphic() != null) { ImageView iv = ((ImageView) button.getGraphic()); iv.setFitWidth(width - df); iv.setFitHeight(height - df); iv.setSmooth(true); } else { int fs = (int) (sz * 0.6f); button.setStyle("-fx-font-size: " + fs + "px;"); } button.setMinSize(width, height); button.setMaxSize(width, height); button.setPrefSize(width, height); button.layout(); } public static String toHex(Color color) { return toHex(color, false); } public static String toHex(Color color, boolean opacity) { return toHex(color, opacity ? color.getOpacity() : -1); } public static String toHex(Color color, double opacity) { if (opacity > -1) return String.format("#%02x%02x%02x%02x", (int) (color.getRed() * 255), (int) (color.getGreen() * 255), (int) (color.getBlue() * 255), (int) (opacity * 255)); else return String.format("#%02x%02x%02x", (int) (color.getRed() * 255), (int) (color.getGreen() * 255), (int) (color.getBlue() * 255)); } public static Color toColor(int[] color) { return new Color((float) color[0] / 255f, (float) color[1] / 255f, (float) color[2] / 255f, 1); } public static int[] toRGB(Color color) { return new int[] { (int) (color.getRed() * 255.0), (int) (color.getGreen() * 255.0), (int) (color.getBlue() * 255.0) }; } public static String toHex(int[] rgb) { return String.format("#%02x%02x%02x", rgb[0], rgb[1], rgb[2]); } public static String toCssRGBA(Color color) { return String.format("rgba(%f,%f,%f,%f)", color.getRed(), color.getGreen(), color.getBlue(), color.getOpacity()); } public static void onAttachedToScene(Node node, Runnable onFinish) { ChangeListener<? super Parent> listener = new ChangeListener<>() { @Override public void changed(ObservableValue<? extends Parent> observable, Parent oldValue, Parent newValue) { if (oldValue == null && newValue != null) { if (newValue.parentProperty().get() == null) { onAttachedToScene(newValue, () -> onFinish.run()); } else { onFinish.run(); } node.parentProperty().removeListener(this); } } }; node.parentProperty().addListener(listener); } public static <T> void zoomTo(ListView<T> root, T item) { root.getSelectionModel().select(item); root.getFocusModel().focus(root.getSelectionModel().getSelectedIndex()); root.scrollTo(item); } public static int encodeRGB(int r, int g, int b) { return (r & 0xff) << 16 | (g & 0xff) << 8 | b & 0xff; } public static int encode(Color color) { return encodeRGB((int) (color.getRed() * 255.0), (int) (color.getGreen() * 255.0), (int) (color.getBlue() * 255.0)); } public static void glowOrDeemphasis(Node node, boolean highlight) { if (highlight) { node.getStyleClass().remove("deemphasis"); node.setEffect(new Glow(0.9)); } else { if (!node.getStyleClass().contains("deemphasis")) node.getStyleClass().add("deemphasis"); node.setEffect(null); } } public static Tooltip quickTooltip(String text) { Tooltip tt = new Tooltip(text); tt.setShowDelay(Duration.millis(250)); return tt; } }
6,847
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
AreaGraphic.java
/FileExtraction/Java_unseen/bithatch_snake/snake-widgets/src/main/java/uk/co/bithatch/snake/widgets/AreaGraphic.java
package uk.co.bithatch.snake.widgets; import javafx.scene.canvas.GraphicsContext; import javafx.scene.paint.Paint; public class AreaGraphic extends AbstractGraphic { public AreaGraphic() { this(22, 22); } public AreaGraphic(double width, double height) { super(width, height); } @Override public void draw() { Paint outlineColor = getOutlineColor(); Paint ledColor = getLedColor(); if(ledColor == null) ledColor = outlineColor; GraphicsContext ctx = getGraphicsContext2D(); double canvasWidth = boundsInLocalProperty().get().getWidth(); double canvasHeight = boundsInLocalProperty().get().getHeight(); ctx.clearRect(0, 0, canvasWidth, canvasHeight); ctx.setStroke(outlineColor); double lineWidth = 2; double halfLine = lineWidth / 2f; ctx.setLineWidth(lineWidth); ctx.beginPath(); ctx.moveTo(halfLine, halfLine); ctx.lineTo(halfLine + canvasWidth / 4, halfLine); ctx.moveTo(halfLine, halfLine); ctx.lineTo(halfLine, canvasWidth / 4 + halfLine); ctx.moveTo(canvasWidth - 1 - halfLine, halfLine); ctx.lineTo(canvasWidth * 0.75f - halfLine, halfLine); ctx.moveTo(canvasWidth - 1 - halfLine, halfLine); ctx.lineTo(canvasWidth - 1 - halfLine, halfLine + canvasWidth * 0.25f); ctx.moveTo(halfLine, canvasHeight - 1 - halfLine); ctx.lineTo(halfLine + canvasWidth / 4, canvasHeight - 1 - halfLine); ctx.moveTo(halfLine, canvasHeight - 1 - halfLine); ctx.lineTo(halfLine, canvasWidth * 0.75f - halfLine); ctx.moveTo(canvasWidth - 1 - halfLine, canvasHeight - 1 - halfLine); ctx.lineTo(canvasWidth * 0.75f - halfLine, canvasHeight - 1 - halfLine); ctx.moveTo(canvasWidth - 1 - halfLine, canvasHeight - 1 - halfLine); ctx.lineTo(canvasWidth - 1 - halfLine, canvasHeight * 0.75f - halfLine); ctx.stroke(); ctx.closePath(); ctx.setFill(ledColor); ctx.fillRect(canvasWidth * 0.35f, canvasHeight * 0.15f, canvasWidth * 0.25f, canvasWidth * 0.25f); ctx.fillOval(canvasWidth * 0.15f, canvasHeight * 0.55f, canvasWidth * 0.25f, canvasWidth * 0.25f); ctx.fillPolygon(new double[]{canvasWidth * 0.70f,canvasWidth * 0.80f, canvasWidth * 0.50f}, new double[]{canvasHeight * 0.45f, canvasHeight * 0.75f, canvasHeight * 0.75f}, 3); } }
2,241
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Direction.java
/FileExtraction/Java_unseen/bithatch_snake/snake-widgets/src/main/java/uk/co/bithatch/snake/widgets/Direction.java
package uk.co.bithatch.snake.widgets; public enum Direction { FROM_LEFT, FROM_RIGHT, FROM_TOP, FROM_BOTTOM, FADE; public Direction opposite() { switch (this) { case FROM_LEFT: return FROM_RIGHT; case FROM_RIGHT: return FROM_LEFT; case FROM_TOP: return FROM_BOTTOM; case FROM_BOTTOM: return FROM_TOP; default: return FADE; } } }
363
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
ColorChooser.java
/FileExtraction/Java_unseen/bithatch_snake/snake-widgets/src/main/java/uk/co/bithatch/snake/widgets/ColorChooser.java
package uk.co.bithatch.snake.widgets; import javafx.beans.property.ObjectProperty; import javafx.scene.paint.Color; public interface ColorChooser { void revertToOriginalColor(); void hidePopup(); void updateHistory(); Color getColor(); ObjectProperty<Color> colorProperty(); }
290
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
LuxColorPicker.java
/FileExtraction/Java_unseen/bithatch_snake/snake-widgets/src/main/java/uk/co/bithatch/snake/widgets/LuxColorPicker.java
/* Copyright 2018 Jesper Öqvist * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package uk.co.bithatch.snake.widgets; import java.util.List; import java.util.ResourceBundle; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.geometry.Bounds; import javafx.geometry.Point2D; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Popup; import javafx.stage.Window; /** * A simple HSV color picker control for JavaFX. * * <p> * The control consists of a button which can be clicked to bring up a color * palette. The button has an icon displaying the currently selected color. The * color palette uses a Hue gradient selector and a HSV 2D gradient. The color * palette also has color swatches with neighbour colors and previously selected * colors are. */ public class LuxColorPicker extends Button implements ColorChooser { final static ResourceBundle bundle = ResourceBundle.getBundle(LuxColorPicker.class.getName()); private Color originalColor = Color.CRIMSON; private ObjectProperty<Color> color = new SimpleObjectProperty<>(Color.CRIMSON); private final Popup popup; private final LuxColorPalette palette; public LuxColorPicker() { setText(bundle.getString("pick")); palette = new LuxColorPalette(this); popup = new Popup(); popup.getContent().add(palette); Rectangle colorSample = new Rectangle(12, 12); colorSample.setStroke(Color.DARKGRAY); colorSample.setStrokeWidth(1); colorSample.fillProperty().bind(color); setGraphic(colorSample); setOnAction(event -> { /* JavaFX makes it impossible to augment the root user agent stylesheet in * a way that cascades to all new windows, of which Popup is one. This * works around the problem by copying the stylesheets from the picker * buttons root (the most likely place for the stylesheets). */ addIfNotAdded(popup.getScene().getRoot().getStylesheets(), LuxColorPicker.this.getScene().getWindow().getScene().getRoot().getStylesheets()); originalColor = getColor(); palette.setColor(originalColor); Scene scene = getScene(); Window window = scene.getWindow(); popup.show(window); popup.setAutoHide(true); popup.setOnAutoHide(event2 -> updateHistory()); Bounds buttonBounds = getBoundsInLocal(); Point2D point = localToScreen(buttonBounds.getMinX(), buttonBounds.getMaxY()); popup.setX(point.getX() - 9); popup.setY(point.getY() - 9); }); } /** * Store the current color in the history palette. */ public void updateHistory() { palette.addToHistory(color.get()); } public ObjectProperty<Color> colorProperty() { return color; } public void setColor(Color value) { color.set(value); palette.updateRandomColorSamples(); } public Color getColor() { return color.get(); } /** * Hide the color picker popup. */ public void hidePopup() { popup.hide(); } public void revertToOriginalColor() { setColor(originalColor); } public static List<String> addIfNotAdded(List<String> target, List<String> source) { for(String s : source) { if(!target.contains(s)) target.add(s); } return target; } }
4,713
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
ProfileLEDs.java
/FileExtraction/Java_unseen/bithatch_snake/snake-widgets/src/main/java/uk/co/bithatch/snake/widgets/ProfileLEDs.java
package uk.co.bithatch.snake.widgets; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; public class ProfileLEDs extends HBox { private LEDGraphic blue; private LEDGraphic green; private LEDGraphic red; private boolean adjusting; private ObjectProperty<boolean[]> rgbs = new SimpleObjectProperty<>(null, "rgbs"); public ProfileLEDs() { red = new LEDGraphic(); red.setLedColor(Color.RED); red.setOnMouseClicked((e) -> { if (!adjusting) { boolean[] leds = getRgbs(); setRgbs(new boolean[] { !leds[0], leds[1], leds[2] }); } }); green = new LEDGraphic(); green.setLedColor(Color.GREEN); green.setOnMouseClicked((e) -> { if (!adjusting) { boolean[] leds = getRgbs(); setRgbs(new boolean[] { leds[0], !leds[1], leds[2] }); } }); blue = new LEDGraphic(); blue.setLedColor(Color.BLUE); blue.setOnMouseClicked((e) -> { if (!adjusting) { boolean[] leds = getRgbs(); setRgbs(new boolean[] { leds[0], leds[1], !leds[2] }); } }); getChildren().add(red); getChildren().add(green); getChildren().add(blue); rgbs.addListener((c, o, n) -> { adjusting = true; try { updateLEDs(n); } finally { adjusting = false; } }); setRgbs(new boolean[3]); } protected void updateLEDs(boolean[] n) { red.setSelected(n[0]); JavaFX.glowOrDeemphasis(red, n[0]); green.setSelected(n[1]); JavaFX.glowOrDeemphasis(green, n[1]); blue.setSelected(n[2]); JavaFX.glowOrDeemphasis(blue, n[2]); } public ObjectProperty<boolean[]> rgbs() { return rgbs; } public boolean[] getRgbs() { return rgbs.get(); } public void setRgbs(boolean[] rgbs) { this.rgbs.set(rgbs); updateLEDs(rgbs); } }
1,802
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Flinger.java
/FileExtraction/Java_unseen/bithatch_snake/snake-widgets/src/main/java/uk/co/bithatch/snake/widgets/Flinger.java
package uk.co.bithatch.snake.widgets; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import javafx.animation.TranslateTransition; import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; import javafx.beans.property.Property; import javafx.beans.property.ReadOnlyBooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleDoubleProperty; 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.geometry.HPos; import javafx.geometry.VPos; import javafx.scene.Node; import javafx.scene.input.MouseEvent; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.scene.shape.Rectangle; import javafx.util.Duration; public class Flinger extends StackPane { public enum Direction { VERTICAL, HORIZONTAL } private Pane container; private TranslateTransition slideTransition; private Rectangle slideClip; private Property<Direction> directionProperty = new SimpleObjectProperty<Direction>( Direction.HORIZONTAL); private BooleanProperty leftOrUpDisabledProperty = new SimpleBooleanProperty(); private BooleanProperty rightOrDownDisabledProperty = new SimpleBooleanProperty(); private DoubleProperty gapProperty = new SimpleDoubleProperty(); public Flinger() { setup(); directionProperty.addListener(new ChangeListener<Direction>() { @Override public void changed( ObservableValue<? extends Direction> observable, Direction oldValue, Direction newValue) { setup(); } }); // Handle events final AtomicReference<MouseEvent> deltaEvent = new AtomicReference<MouseEvent>(); setOnScroll(scr -> { if (scr.getDeltaY() < 0) { slideRightOrDown(); } else { slideLeftOrUp(); } }); setOnMousePressed(eh -> { deltaEvent.set(eh); }); // Handle drag events, will only allow drag until the first or last item // is revealed setOnMouseDragged(event -> { if (directionProperty.getValue().equals(Direction.HORIZONTAL)) { double delta = event.getX() - deltaEvent.get().getX(); double newX = container.getTranslateX() + delta; double containerWidth = container.prefWidth(getHeight()); if (newX + containerWidth < getWidth()) { newX = container.getTranslateX(); } else if (newX > 0) { newX = 0; } container.setTranslateX(newX); } if (directionProperty.getValue().equals(Direction.VERTICAL)) { double delta = event.getY() - deltaEvent.get().getY(); double newX = container.getTranslateY() + delta; double containerHeight = container.prefHeight(getWidth()); if (newX + containerHeight < getHeight()) { newX = container.getTranslateY(); } else if (newX > 0) { newX = 0; } container.setTranslateY(newX); } setAvailable(); deltaEvent.set(event); }); } public ReadOnlyBooleanProperty leftOrUpDisableProperty() { return leftOrUpDisabledProperty; } public ReadOnlyBooleanProperty rightOrDownDisableProperty() { return rightOrDownDisabledProperty; } public Property<Direction> directionProperty() { return directionProperty; } public DoubleProperty gapProperty() { return gapProperty; } public Pane getContent() { return container; } public void slideLeftOrUp() { /* * We should only get this action if the button is enabled, which means * at least one button is partially obscured on the left */ double scroll = 0; /* * The position of the child within the container. When we find a node * that crosses '0', that is how much this single scroll will adjust by, * so completely revealing the hidden side */ if (directionProperty.getValue().equals(Direction.VERTICAL)) { for (Node n : container.getChildren()) { double p = n.getLayoutY() + container.getTranslateY(); double amt = p + n.getLayoutBounds().getHeight(); if (amt >= 0) { scroll = Math.abs(n.getLayoutBounds().getHeight() - amt + gapProperty.get()); if (container.getTranslateY() + scroll > 0) { scroll = 0; break; } else if (scroll > 0) break; } } } else { for (Node n : container.getChildren()) { double p = n.getLayoutX() + container.getTranslateX(); double amt = p + n.getLayoutBounds().getWidth(); if (amt >= 0) { scroll = Math.abs(n.getLayoutBounds().getWidth() - amt); if (container.getTranslateX() + scroll > 0) { scroll = 0; break; } else if (scroll > 0) break; } } } setAvailable(); if (scroll > 0) { if (directionProperty.getValue().equals(Direction.VERTICAL)) { slideTransition.setFromY(container.getTranslateY()); slideTransition.setToY(container.getTranslateY() + scroll); } else { slideTransition.setFromX(container.getTranslateX()); slideTransition.setToX(container.getTranslateX() + scroll); } slideTransition.setOnFinished(ae -> { setAvailable(); }); slideTransition.play(); } } public void slideRightOrDown() { /* * We should only get this action if the button is enabled, which means * at least one button is partially obscured on the left */ double scroll = 0; ObservableList<Node> c = container.getChildren(); /* * Search backwards through the nodes until on whose X or Y position is * is in the visible portion */ if (directionProperty.getValue().equals(Direction.VERTICAL)) { for (int i = c.size() - 1; i >= 0; i--) { Node n = c.get(i); double p = n.getLayoutY() + container.getTranslateY(); if (p <= getHeight()) { scroll = n.getLayoutBounds().getHeight() + gapProperty.get() - (getHeight() - p); break; } } } else { for (int i = c.size() - 1; i >= 0; i--) { Node n = c.get(i); double p = n.getLayoutX() + container.getTranslateX(); if (p < getWidth()) { scroll = (getWidth() - (p + n.getLayoutBounds().getWidth() + 1 + gapProperty.get())) * -1; break; } } } setAvailable(); if (scroll > 0) { leftOrUpDisabledProperty.set(false); if (directionProperty.getValue().equals(Direction.VERTICAL)) { slideTransition.setFromY(container.getTranslateY()); slideTransition.setToY(container.getTranslateY() - scroll); } else { slideTransition.setFromX(container.getTranslateX()); slideTransition.setToX(container.getTranslateX() - scroll); } slideTransition.setOnFinished(ae -> { setAvailable(); }); slideTransition.play(); } } public void recentre() { setAvailable(); double centre = getLaunchBarOffset(); if (directionProperty.getValue().equals(Direction.VERTICAL)) { slideTransition.setFromY(container.getTranslateY()); slideTransition.setToY(centre); } else { slideTransition.setFromX(container.getTranslateX()); slideTransition.setToX(centre); } slideTransition.setOnFinished(eh -> setAvailable()); slideTransition.stop(); slideTransition.play(); } @Override protected void layoutChildren() { for (Node node : getChildren()) { layoutInArea(node, 0, 0, getWidth(), getHeight(), 0, HPos.LEFT, VPos.TOP); } } private double getLaunchBarOffset() { double centre = directionProperty.getValue().equals(Direction.VERTICAL) ? (getHeight() - container .prefHeight(getWidth())) / 2d : (getWidth() - container .prefWidth(getHeight())) / 2d; return centre; } private void requiredSpaceChanged() { layoutContainer(); } private void availableSpaceChanged() { layoutContainer(); } private void layoutContainer() { if (directionProperty.getValue().equals(Direction.VERTICAL)) { container.setTranslateX((getWidth() - container .prefWidth(getHeight())) / 2d); } else { container.setTranslateY((getHeight() - container .prefHeight(getWidth())) / 2d); } layout(); recentre(); } private void setup() { List<Node> children = null; if (container != null) { children = new ArrayList<Node>(container.getChildrenUnmodifiable()); container.getChildren().clear(); } getChildren().clear(); container = directionProperty.getValue().equals(Direction.VERTICAL) ? new VBox() : new HBox(); container.setPrefSize(USE_COMPUTED_SIZE, USE_COMPUTED_SIZE); if (directionProperty.getValue().equals(Direction.VERTICAL)) { ((VBox) container).spacingProperty().bind(gapProperty); } else { ((HBox) container).spacingProperty().bind(gapProperty); } widthProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { availableSpaceChanged(); } }); heightProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { availableSpaceChanged(); } }); /* * Watch for new children being added, and so changing the amount of * space required */ container.getChildren().addListener(new ListChangeListener<Node>() { @Override public void onChanged(ListChangeListener.Change<? extends Node> c) { requiredSpaceChanged(); } }); // Do not want the container managed, we lay it out ourselves container.setManaged(false); // Clip the content container to the width of this container slideClip = new Rectangle(); slideClip.widthProperty().bind(widthProperty()); slideClip.heightProperty().bind(heightProperty()); setClip(slideClip); // Transition for sliding slideTransition = new TranslateTransition(Duration.seconds(0.125), container); slideTransition.setAutoReverse(false); slideTransition.setCycleCount(1); // Add back any children if (children != null) { container.getChildren().addAll(children); } // Add the new container to the scene getChildren().add(container); } private void setAvailable() { if (directionProperty.getValue().equals(Direction.HORIZONTAL)) { leftOrUpDisabledProperty.set(container.getTranslateX() >= 0); rightOrDownDisabledProperty.set(container.getTranslateX() + container.prefWidth(getHeight()) <= getWidth()); } else { leftOrUpDisabledProperty.set(container.getTranslateY() >= 0); rightOrDownDisabledProperty.set(container.getTranslateY() + container.prefHeight(getWidth()) <= getHeight()); } } }
10,610
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
ImageButton.java
/FileExtraction/Java_unseen/bithatch_snake/snake-widgets/src/main/java/uk/co/bithatch/snake/widgets/ImageButton.java
package uk.co.bithatch.snake.widgets; import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.image.ImageView; public class ImageButton extends Button { private final String STYLE_NORMAL = "-fx-background-color: transparent; -fx-padding: 2, 2, 2, 2;"; private final String STYLE_PRESSED = "-fx-background-color: transparent; -fx-padding: 3 1 1 3;"; public ImageButton() { } public ImageButton(Image originalImage, double h, double w) { ImageView image = new ImageView(originalImage); image.setFitHeight(h); image.setFitHeight(w); image.setPreserveRatio(true); setGraphic(image); setStyle(STYLE_NORMAL); setOnMousePressed(event -> setStyle(STYLE_PRESSED)); setOnMouseReleased(event -> setStyle(STYLE_NORMAL)); } }
776
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
AccessoryGraphic.java
/FileExtraction/Java_unseen/bithatch_snake/snake-widgets/src/main/java/uk/co/bithatch/snake/widgets/AccessoryGraphic.java
package uk.co.bithatch.snake.widgets; import javafx.scene.canvas.GraphicsContext; import javafx.scene.paint.Paint; public class AccessoryGraphic extends AbstractGraphic { public AccessoryGraphic() { this(22, 22); } public AccessoryGraphic(double width, double height) { super(width, height); } @Override public void draw() { Paint outlineColor = getOutlineColor(); Paint ledColor = getLedColor(); if (ledColor == null) ledColor = outlineColor; GraphicsContext ctx = getGraphicsContext2D(); double canvasWidth = boundsInLocalProperty().get().getWidth(); double canvasHeight = boundsInLocalProperty().get().getHeight(); ctx.clearRect(0, 0, canvasWidth, canvasHeight); ctx.setStroke(outlineColor); double lineWidth = 2; double halfLine = lineWidth / 2f; ctx.setLineWidth(lineWidth); ctx.beginPath(); ctx.moveTo(halfLine, halfLine); ctx.lineTo( canvasWidth - halfLine, halfLine); ctx.lineTo(canvasWidth / 2, canvasHeight - halfLine); ctx.lineTo(halfLine, halfLine); ctx.stroke(); ctx.closePath(); ctx.beginPath(); ctx.moveTo(halfLine * 6, halfLine * 4); ctx.lineTo( canvasWidth - ( halfLine * 6 ), halfLine * 4); ctx.lineTo(canvasWidth / 2, canvasHeight - ( halfLine * 8 ) ); ctx.lineTo(halfLine * 6, halfLine * 4); ctx.setFill(ledColor); ctx.fill(); ctx.closePath(); } }
1,346
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
LuxColorPalette.java
/FileExtraction/Java_unseen/bithatch_snake/snake-widgets/src/main/java/uk/co/bithatch/snake/widgets/LuxColorPalette.java
/* Copyright 2018 Jesper Öqvist * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package uk.co.bithatch.snake.widgets; import javafx.beans.binding.Bindings; import javafx.beans.binding.ObjectBinding; import javafx.beans.property.DoubleProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ChangeListener; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.geometry.Insets; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.effect.DropShadow; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.image.WritableImage; import javafx.scene.image.WritablePixelFormat; import javafx.scene.image.PixelFormat; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.Pane; import javafx.scene.layout.Region; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.paint.CycleMethod; import javafx.scene.paint.LinearGradient; import javafx.scene.paint.Paint; import javafx.scene.paint.Stop; import javafx.scene.shape.Circle; import javafx.scene.shape.Rectangle; import java.io.IOException; import java.net.URL; import java.nio.IntBuffer; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.ResourceBundle; /** * HSV color palette for a simple JavaFX color picker. * * <p>The color palette shows a Hue gradient for picking the Hue value, * and a 2D HSV-gradient displaying a slice of the HSV color cube which * can be clicked to select the Saturation and Value components. * The color palette also has some swatches displaying neighbour colors * and previously selected colors. There is a large color swatch showing * the current color. * * <p>A cancel button is at the bottom right of the color palette, and the * current HTML color code is displayed in a text field at the bottom of the * palette. */ public class LuxColorPalette extends Region implements Initializable { private static final WritablePixelFormat<IntBuffer> PIXEL_FORMAT = PixelFormat.getIntArgbInstance(); /** Cached hue gradient image. */ private static final Image gradientImage; static { List<double[]> gradient = new ArrayList<>(); gradient.add(new double[] { 1, 0, 0, 0.00 }); gradient.add(new double[] { 1, 1, 0, 1 / 6.0 }); gradient.add(new double[] { 0, 1, 0, 2 / 6.0 }); gradient.add(new double[] { 0, 1, 1, 3 / 6.0 }); gradient.add(new double[] { 0, 0, 1, 4 / 6.0 }); gradient.add(new double[] { 1, 0, 1, 5 / 6.0 }); gradient.add(new double[] { 1, 0, 0, 1.00 }); gradientImage = drawGradient(522, 75, gradient); } private final ColorChooser colorPicker; private Random random = new Random(); private @FXML VBox palette; private @FXML ImageView huePicker; private @FXML Canvas colorSample; private @FXML TextField webColorCode; private @FXML Button saveBtn; private @FXML Button cancelBtn; private @FXML StackPane satValueRect; private @FXML Pane huePickerOverlay; private @FXML Region sample0; private @FXML Region sample1; private @FXML Region sample2; private @FXML Region sample3; private @FXML Region sample4; private @FXML Region history0; private @FXML Region history1; private @FXML Region history2; private @FXML Region history3; private @FXML Region history4; private final DoubleProperty hue = new SimpleDoubleProperty(); private final DoubleProperty saturation = new SimpleDoubleProperty(); private final DoubleProperty value = new SimpleDoubleProperty(); private final Circle satValIndicator = new Circle(9); private final Rectangle hueIndicator = new Rectangle(20, 69); private Region[] sample; private Region[] history; /** Updates the current color based on changes to the web color code. */ private ChangeListener<String> webColorListener = (observable, oldValue, newValue) -> { try { editingWebColorCode = true; Color color = Color.web(newValue); hue.set(color.getHue() / 360); saturation.set(color.getSaturation()); value.set(color.getBrightness()); } catch (IllegalArgumentException e) { // Harmless exception - ignored. } finally { editingWebColorCode = false; } }; /** * Set to true while the web color code listener is modifying the selected color. * * <p>When this is set to true the updating of the HTML color code is disabled to * avoid update loops. */ private boolean editingWebColorCode = false; public LuxColorPalette() { this(new ColorChooser() { private ObjectProperty<Color> color = new SimpleObjectProperty<>(Color.CRIMSON); @Override public void updateHistory() { } @Override public void revertToOriginalColor() { } @Override public void hidePopup() { } @Override public Color getColor() { return color.get(); } @Override public ObjectProperty<Color> colorProperty() { return color; } }); } public LuxColorPalette(ColorChooser colorPicker) { this.colorPicker = colorPicker; try { FXMLLoader loader = new FXMLLoader(getClass().getResource("LuxColorPalette.fxml")); loader.setController(this); getChildren().add(loader.load()); addEventFilter(KeyEvent.KEY_PRESSED, e -> { if (e.getCode() == KeyCode.ESCAPE) { e.consume(); colorPicker.revertToOriginalColor(); colorPicker.hidePopup(); } }); } catch (IOException e) { throw new Error(e); } } @Override public void initialize(URL location, ResourceBundle resources) { sample = new Region[] { sample0, sample1, sample2, sample3, sample4 }; history = new Region[] { history0, history1, history2, history3, history4 }; // Handle color selection on click. colorSample.setOnMouseClicked(event -> { colorPicker.updateHistory(); colorPicker.hidePopup(); }); webColorCode.textProperty().addListener(webColorListener); saveBtn.setOnAction(event -> { colorPicker.updateHistory(); colorPicker.hidePopup(); }); saveBtn.setDefaultButton(true); cancelBtn.setOnAction(event -> { colorPicker.revertToOriginalColor(); colorPicker.hidePopup(); }); satValueRect.setBackground( new Background(new BackgroundFill(Color.RED, CornerRadii.EMPTY, Insets.EMPTY))); satValueRect.backgroundProperty().bind(new ObjectBinding<Background>() { { bind(hue); } @Override protected Background computeValue() { return new Background( new BackgroundFill(Color.hsb(hue.get() * 360, 1.0, 1.0), CornerRadii.EMPTY, Insets.EMPTY)); } }); Pane saturationOverlay = new Pane(); saturationOverlay.setBackground(new Background(new BackgroundFill( new LinearGradient(0, 0, 1, 0, true, CycleMethod.NO_CYCLE, new Stop(0, Color.rgb(255, 255, 255, 1.0)), new Stop(1, Color.rgb(255, 255, 255, 0.0))), CornerRadii.EMPTY, Insets.EMPTY))); Pane valueOverlay = new Pane(); valueOverlay.setBackground(new Background(new BackgroundFill( new LinearGradient(0, 1, 0, 0, true, CycleMethod.NO_CYCLE, new Stop(0, Color.rgb(0, 0, 0, 1.0)), new Stop(1, Color.rgb(0, 0, 0, 0.0))), CornerRadii.EMPTY, Insets.EMPTY))); satValIndicator.layoutXProperty().bind(saturation.multiply(256)); satValIndicator.layoutYProperty().bind(Bindings.subtract(1, value).multiply(256)); satValIndicator.setStroke(Color.WHITE); satValIndicator.fillProperty().bind(new ObjectBinding<Paint>() { { bind(hue); bind(saturation); bind(value); } @Override protected Paint computeValue() { return Color.hsb(hue.get() * 360, saturation.get(), value.get()); } }); satValIndicator.setStrokeWidth(2); satValIndicator.setMouseTransparent(true); satValIndicator.setEffect(new DropShadow(5, Color.BLACK)); hueIndicator.setMouseTransparent(true); hueIndicator.setTranslateX(-10); hueIndicator.setTranslateY(3); hueIndicator.layoutXProperty().bind(hue.multiply(huePicker.fitWidthProperty())); hueIndicator.fillProperty().bind(new ObjectBinding<Paint>() { { bind(hue); } @Override protected Paint computeValue() { return Color.hsb(hue.get() * 360, 1.0, 1.0); } }); hueIndicator.setStroke(Color.WHITE); hueIndicator.setStrokeWidth(2); hueIndicator.setEffect(new DropShadow(5, Color.BLACK)); huePickerOverlay.getChildren().add(hueIndicator); huePickerOverlay.setClip(new Rectangle(522, 75)); valueOverlay.getChildren().add(satValIndicator); valueOverlay.setClip(new Rectangle(256, 256)); // Clip the indicator circle. satValueRect.getChildren().addAll(saturationOverlay, valueOverlay); setStyle( "-fx-background-color: -fx-background;" + "-fx-background-insets: 0;" + "-fx-background-radius: 4px"); DropShadow dropShadow = new DropShadow(); dropShadow.setColor(Color.color(0, 0, 0, 0.8)); dropShadow.setWidth(18); dropShadow.setHeight(18); setEffect(dropShadow); setHueGradient(); EventHandler<MouseEvent> hueMouseHandler = event -> hue.set(clamp(event.getX() / huePicker.getFitWidth())); huePickerOverlay.setOnMouseDragged(hueMouseHandler); huePickerOverlay.setOnMousePressed(hueMouseHandler); huePickerOverlay.setOnMouseReleased(event -> updateRandomColorSamples()); EventHandler<MouseEvent> mouseHandler = event -> { saturation.set(clamp(event.getX() / satValueRect.getWidth())); value.set(clamp(1 - event.getY() / satValueRect.getHeight())); }; valueOverlay.setOnMousePressed(mouseHandler); valueOverlay.setOnMouseDragged(mouseHandler); valueOverlay.setOnMouseReleased(event -> updateRandomColorSamples()); hue.addListener((observable, oldValue, newValue) -> updateCurrentColor(newValue.doubleValue(), saturation.get(), value.get())); saturation.addListener( (observable, oldValue, newValue) -> updateCurrentColor(hue.get(), newValue.doubleValue(), value.get())); value.addListener( (observable, oldValue, newValue) -> updateCurrentColor(hue.get(), saturation.get(), newValue.doubleValue())); EventHandler<MouseEvent> swatchClickHandler = event -> { if (event.getSource() instanceof Region) { Region swatch = (Region) event.getSource(); if (!swatch.getBackground().getFills().isEmpty()) { Color color = (Color) swatch.getBackground().getFills().get(0).getFill(); hue.set(color.getHue() / 360); saturation.set(color.getSaturation()); value.set(color.getBrightness()); } } }; for (Region region : history) { region.setOnMouseClicked(swatchClickHandler); } for (Region region : sample) { region.setOnMouseClicked(swatchClickHandler); } // Initialize history with random colors. for (Region swatch : history) { swatch.setBackground(new Background( new BackgroundFill(getRandomNearColor(colorPicker.getColor()), CornerRadii.EMPTY, Insets.EMPTY))); } } /** * Updates the nearby random color samples. */ void updateRandomColorSamples() { Color color = colorPicker.getColor(); for (Region swatch : sample) { swatch.setBackground(new Background( new BackgroundFill(getRandomNearColor(color), CornerRadii.EMPTY, Insets.EMPTY))); } } protected void setColor(Color color) { hue.set(color.getHue() / 360); saturation.set(color.getSaturation()); value.set(color.getBrightness()); } protected void addToHistory(Color color) { for (int i = history.length - 1; i >= 1; i -= 1) { history[i].setBackground(history[i - 1].getBackground()); } history[0].setBackground(new Background( new BackgroundFill(color, CornerRadii.EMPTY, Insets.EMPTY))); } private void setHueGradient() { huePicker.setImage(gradientImage); } private static double clamp(double value) { return (value < 0) ? 0 : (value > 1 ? 1 : value); } /** * Change the currently selected color and update UI state to match. */ private void updateCurrentColor(double hue, double saturation, double value) { Color newColor = Color.hsb(hue * 360, saturation, value); colorPicker.colorProperty().set(newColor); GraphicsContext gc = colorSample.getGraphicsContext2D(); gc.setFill(newColor); gc.fillRect(0, 0, colorSample.getWidth(), colorSample.getHeight()); if (!editingWebColorCode) { // Suspending the web color listener to avoid it tweaking the current color. webColorCode.textProperty().removeListener(webColorListener); webColorCode.setText(String.format("#%02X%02X%02X", (int) (newColor.getRed() * 255 + 0.5), (int) (newColor.getGreen() * 255 + 0.5), (int) (newColor.getBlue() * 255 + 0.5))); webColorCode.textProperty().addListener(webColorListener); } } private Color getRandomNearColor(Color color) { double hueMod = random.nextDouble() * .45; double satMod = random.nextDouble() * .75; double valMod = random.nextDouble() * .4; hueMod = 2 * (random.nextDouble() - .5) * 360 * hueMod * hueMod; satMod = 2 * (random.nextDouble() - .5) * satMod * satMod; valMod = 2 * (random.nextDouble() - .5) * valMod * valMod; double hue = color.getHue() + hueMod; double sat = Math.max(0, Math.min(1, color.getSaturation() + satMod)); double val = Math.max(0, Math.min(1, color.getBrightness() + valMod)); if (hue > 360) { hue -= 360; } else if (hue < 0) { hue += 360; } return Color.hsb(hue, sat, val); } protected static Image drawGradient(int width, int height, List<double[]> gradient) { int[] pixels = new int[width * height]; if (width <= 0 || height <= 0 || gradient.size() < 2) { throw new IllegalArgumentException(); } int x = 0; // Fill the first row. for (int i = 0; i < width; ++i) { double weight = i / (double) width; double[] c0 = gradient.get(x); double[] c1 = gradient.get(x + 1); double xx = (weight - c0[3]) / (c1[3] - c0[3]); while (x + 2 < gradient.size() && xx > 1) { x += 1; c0 = gradient.get(x); c1 = gradient.get(x + 1); xx = (weight - c0[3]) / (c1[3] - c0[3]); } xx = 0.5 * (Math.sin(Math.PI * xx - Math.PI / 2) + 1); double a = 1 - xx; double b = xx; int argb = getArgb(a * c0[0] + b * c1[0], a * c0[1] + b * c1[1], a * c0[2] + b * c1[2]); pixels[i] = argb; } // Copy the first row to the rest of the image. for (int j = 1; j < height; ++j) { System.arraycopy(pixels, 0, pixels, j * width, width); } WritableImage image = new WritableImage(width, height); image.getPixelWriter().setPixels(0, 0, width, height, PIXEL_FORMAT, pixels, 0, width); return image; } /** * @return int ARGB values corresponding to the given color */ private static int getArgb(double r, double g, double b) { return 0xFF000000 | ((int) (255 * r + .5) << 16) | ((int) (255 * g + .5) << 8) | (int) (255 * b + .5); } }
17,287
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
ColorBar2.java
/FileExtraction/Java_unseen/bithatch_snake/snake-widgets/src/main/java/uk/co/bithatch/snake/widgets/ColorBar2.java
package uk.co.bithatch.snake.widgets; import java.util.List; import java.util.ResourceBundle; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.geometry.Bounds; import javafx.geometry.Point2D; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.Tooltip; import javafx.scene.effect.Glow; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; import javafx.stage.Popup; import javafx.stage.Window; import javafx.util.Duration; public class ColorBar2 extends HBox implements ColorChooser { final static ResourceBundle bundle = ResourceBundle.getBundle(ColorBar.class.getName()); final static Color[] COLORS = new Color[] { Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN, Color.BLUE, Color.INDIGO, Color.VIOLET, Color.WHITE }; final static String[] COLOR_NAMES = new String[] { bundle.getString("red"), bundle.getString("orange"), bundle.getString("yellow"), bundle.getString("green"), bundle.getString("blue"), bundle.getString("indigo"), bundle.getString("violet"), bundle.getString("white") }; private Color originalColor = Color.CRIMSON; private ObjectProperty<Color> color = new SimpleObjectProperty<>(Color.CRIMSON); private final Popup popup; private final LuxColorPalette palette; public ColorBar2() { setAlignment(Pos.CENTER_LEFT); getStyleClass().add("iconBar"); palette = new LuxColorPalette(this); popup = new Popup(); popup.getContent().add(palette); LEDGraphic icon = new LEDGraphic(32, 32); // icon.setIcon(AwesomeIcon.EYEDROPPER); icon.getStyleClass().add("color-bar-icon"); icon.setStyle("-icon-color: black"); configureIcon(icon); icon.setOnMouseClicked(event -> { /* * JavaFX makes it impossible to augment the root user agent stylesheet in a way * that cascades to all new windows, of which Popup is one. This works around * the problem by copying the stylesheets from the picker buttons root (the most * likely place for the stylesheets). */ addIfNotAdded(popup.getScene().getRoot().getStylesheets(), ColorBar2.this.getScene().getWindow().getScene().getRoot().getStylesheets()); originalColor = getColor(); palette.setColor(originalColor); Scene scene = getScene(); Window window = scene.getWindow(); popup.show(window); popup.setAutoHide(true); popup.setOnAutoHide(event2 -> updateHistory()); Bounds buttonBounds = getBoundsInLocal(); Point2D point = localToScreen(buttonBounds.getMinX(), buttonBounds.getMaxY()); popup.setX(point.getX() - 9); popup.setY(point.getY() - 9); }); getChildren().add(wrap(icon, bundle.getString("choose"))); int i = 0; for (Color c : COLORS) { LEDGraphic colIcon = new LEDGraphic(16, 16); colIcon.getStyleClass().add("color-bar-icon"); colIcon.setStyle("-icon-opacity: 1"); colIcon.setStyle("-icon-color: " + JavaFX.toHex(c)); colIcon.setOnMouseClicked(event -> { setColor(c); }); configureIcon(colIcon); getChildren().add(wrap(colIcon, COLOR_NAMES[i++])); } colorProperty().addListener((e, o, n) -> icon.setStyle("-icon-color: " + JavaFX.toHex(n))); LEDGraphic resetIcon = new LEDGraphic(32, 32); // resetIcon.setIcon(AwesomeIcon.ERASER); resetIcon.getStyleClass().add("color-bar-icon"); resetIcon.setStyle("-icon-color: black"); configureIcon(resetIcon); resetIcon.setOnMouseClicked(event -> { setColor(Color.BLACK); }); getChildren().add(wrap(resetIcon, bundle.getString("reset"))); } protected Label wrap(Node icon, String text) { Label l = new Label(); l.setGraphic(icon); Tooltip tooltip = new Tooltip(text); tooltip.setShowDelay(Duration.millis(200)); l.setTooltip(tooltip); return l; } protected void configureIcon(LEDGraphic colIcon) { colIcon.setOnMouseEntered((e) -> colIcon.setEffect(new Glow(0.9))); colIcon.setOnMouseExited((e) -> colIcon.setEffect(null)); } /** * Store the current color in the history palette. */ public void updateHistory() { palette.addToHistory(color.get()); } public ObjectProperty<Color> colorProperty() { return color; } public void setColor(Color value) { color.set(value); palette.updateRandomColorSamples(); } public Color getColor() { return color.get(); } /** * Hide the color picker popup. */ public void hidePopup() { popup.hide(); } public void revertToOriginalColor() { setColor(originalColor); } public static List<String> addIfNotAdded(List<String> target, List<String> source) { for (String s : source) { if (!target.contains(s)) target.add(s); } return target; } }
4,687
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
LEDGraphic.java
/FileExtraction/Java_unseen/bithatch_snake/snake-widgets/src/main/java/uk/co/bithatch/snake/widgets/LEDGraphic.java
package uk.co.bithatch.snake.widgets; import javafx.scene.canvas.GraphicsContext; import javafx.scene.paint.Paint; public class LEDGraphic extends AbstractGraphic { public LEDGraphic() { this(22, 22); } public LEDGraphic(double width, double height) { super(width, height); } @Override public void draw() { Paint outlineColor = getOutlineColor(); Paint ledColor = getLedColor(); if (ledColor == null) ledColor = outlineColor; GraphicsContext ctx = getGraphicsContext2D(); double canvasWidth = boundsInLocalProperty().get().getWidth(); double canvasHeight = boundsInLocalProperty().get().getHeight(); ctx.clearRect(0, 0, canvasWidth, canvasHeight); ctx.setStroke(outlineColor); int lineWidth = 2; ctx.setLineWidth(lineWidth); ctx.strokeOval(lineWidth, lineWidth, canvasWidth - (lineWidth * 2), canvasHeight - (lineWidth * 2)); ctx.setFill(ledColor); ctx.fillOval(canvasWidth * 0.25f, canvasWidth * 0.25f, canvasWidth / 2f, canvasHeight / 2f); } }
994
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-app-linux/src/main/java/module-info.java
module uk.co.bithatch.snake.app.linux { requires transitive uk.co.bithatch.snake.lib; requires transitive uk.co.bithatch.snake.lib.backend.openrazer; requires transitive uk.co.bithatch.snake.ui.linux; exports uk.co.bithatch.snake.app.linux; }
257
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
App.java
/FileExtraction/Java_unseen/bithatch_snake/snake-app-linux/src/main/java/uk/co/bithatch/snake/app/linux/App.java
package uk.co.bithatch.snake.app.linux; public class App extends uk.co.bithatch.snake.ui.App { public static void main(String[] args) throws Exception { uk.co.bithatch.snake.ui.App.main(args); } }
203
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-lib/src/main/java/module-info.java
module uk.co.bithatch.snake.lib { requires transitive org.apache.commons.lang3; requires transitive java.prefs; requires transitive java.xml; requires transitive com.google.gson; requires jdk.crypto.ec; requires transitive uk.co.bithatch.linuxio; exports uk.co.bithatch.snake.lib; exports uk.co.bithatch.snake.lib.effects; exports uk.co.bithatch.snake.lib.layouts; exports uk.co.bithatch.snake.lib.binding; exports uk.co.bithatch.snake.lib.animation; opens uk.co.bithatch.snake.lib; opens uk.co.bithatch.snake.lib.layouts; uses uk.co.bithatch.snake.lib.Backend; }
605
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Json.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/Json.java
package uk.co.bithatch.snake.lib; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.file.Files; 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.JsonParser; public class Json { public static String[] toStringArray(JsonArray arr) { List<String> l = new ArrayList<>(); for (JsonElement el : arr) { l.add(el.getAsString()); } return l.toArray(new String[0]); } public static JsonArray toStringJsonArray(String... els) { JsonArray arr = new JsonArray(); for (String e : els) arr.add(e); return arr; } public static JsonElement toJson(Path fileName) throws IOException { try (BufferedReader r = Files.newBufferedReader(fileName)) { return JsonParser.parseReader(r); } } public static JsonElement toJson(InputStream in) throws IOException { try (BufferedReader r = new BufferedReader(new InputStreamReader(in))) { return JsonParser.parseReader(r); } } }
1,106
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
MacroSequence.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/MacroSequence.java
package uk.co.bithatch.snake.lib; import java.util.ArrayList; @SuppressWarnings("serial") @Deprecated public class MacroSequence extends ArrayList<Macro> { private Key key; public MacroSequence() { } public MacroSequence(Key key) { setMacroKey(key); } public Key getMacroKey() { return key; } public void setMacroKey(Key key) { this.key = key; } public void validate() throws ValidationException { for (Macro m : this) m.validate(); } }
468
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
ValidationException.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/ValidationException.java
package uk.co.bithatch.snake.lib; @SuppressWarnings("serial") public class ValidationException extends Exception { public ValidationException(String key) { super(key); } public ValidationException(String key, Throwable cause) { super(key, cause); } }
264
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Grouping.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/Grouping.java
package uk.co.bithatch.snake.lib; public interface Grouping extends Item { int getBattery(); boolean isCharging(); boolean isGameMode(); void setGameMode(boolean gameMode); }
184
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Region.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/Region.java
package uk.co.bithatch.snake.lib; public interface Region extends Item, Lit { public enum Name { BACKLIGHT, CHROMA, LEFT, LOGO, RIGHT, SCROLL; } Device getDevice(); Name getName(); }
206
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Backend.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/Backend.java
package uk.co.bithatch.snake.lib; import java.lang.System.Logger.Level; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; public interface Backend extends AutoCloseable, Grouping { final static System.Logger LOG = System.getLogger(Backend.class.getName()); public interface BackendListener { void deviceAdded(Device device); void deviceRemoved(Device device); } void addListener(BackendListener tray); default int getBattery() { int l = 0; int tot = 0; try { for (Device dev : getDevices()) { if (dev.getCapabilities().contains(Capability.BATTERY)) { l++; tot += dev.getBattery(); } } return l == 0 ? -1 : (int) ((float) tot / (float) l); } catch (Exception e) { LOG.log(Level.DEBUG, "Failed to get battery status.", e); return 0; } } default short getBrightness() { int tot = 0; int l = 0; try { for (Device d : getDevices()) { if (d.getCapabilities().contains(Capability.BRIGHTNESS)) { l++; tot += d.getBrightness(); } } } catch (Exception e) { throw new IllegalStateException("Failed to get overall brightness.", e); } return (short) ((float) tot / (float) l); } default Set<Capability> getCapabilities() { Set<Capability> l = new LinkedHashSet<>(); try { for (Device d : getDevices()) { l.addAll(d.getCapabilities()); } } catch (Exception e) { } return l; } List<Device> getDevices() throws Exception; default byte getLowBatteryThreshold() { try { int t = 0; int l = 0; for (Device d : getDevices()) { if (d.getCapabilities().contains(Capability.BATTERY)) { t += d.getLowBatteryThreshold(); l++; } } return (byte) ((float) t / (float) l); } catch (Exception e) { throw new IllegalStateException("Failed to get overall brightness.", e); } } String getName(); String getVersion(); void init() throws Exception; default boolean isCharging() { try { for (Device d : getDevices()) if (d.getCapabilities().contains(Capability.BATTERY) && d.isCharging()) return true; return false; } catch (Exception e) { throw new IllegalStateException("Failed to get charging state.", e); } } boolean isSync(); void removeListener(BackendListener tray); default void setBrightness(short brightness) { try { for (Device d : getDevices()) { if (d.getCapabilities().contains(Capability.BRIGHTNESS)) { d.setBrightness(brightness); } } } catch (Exception e) { throw new IllegalStateException("Failed to get overall brightness.", e); } } void setSync(boolean sync); default Device getDevice(String name) { try { for (Device dev : getDevices()) { if (dev.getName().equals(name)) return dev; } } catch (Exception e) { throw new IllegalStateException(String.format("Failed to find device with name %s.", name), e); } return null; } }
2,906
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
ControlInterface.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/ControlInterface.java
package uk.co.bithatch.snake.lib; import java.util.Set; import uk.co.bithatch.snake.lib.effects.Effect; public interface ControlInterface extends AutoCloseable { Effect getEffect(Lit lit); void setEffect(Lit lit, Effect effect); void update(Lit lit); Set<Lit> getLitAreas(); }
288
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Device.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/Device.java
package uk.co.bithatch.snake.lib; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import uk.co.bithatch.linuxio.EventCode; 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.ComponentType; public interface Device extends AutoCloseable, Grouping, Lit { public interface Listener { void changed(Device device, Region region); void activeMapChanged(ProfileMap map); void profileAdded(Profile profile); void profileRemoved(Profile profile); void mapAdded(ProfileMap profile); void mapChanged(ProfileMap profile); void mapRemoved(ProfileMap profile); } Set<EventCode> getSupportedInputEvents(); Set<Key> getSupportedLegacyKeys(); void addListener(Listener listener); void addMacro(MacroSequence macro); void deleteMacro(Key key); String exportMacros(); int getBattery(); default short getBrightness() { double tot = 0; int of = 0; for (Region r : getRegions()) { if (r.getCapabilities().contains(Capability.BRIGHTNESS_PER_REGION)) { tot += r.getBrightness(); of++; } } return (short) (tot / (double) of); } Set<Capability> getCapabilities(); int[] getDPI(); String getDriverVersion(); String getFirmware(); int getIdleTime(); String getImage(); String getImageUrl(BrandingImage image); String getKeyboardLayout(); byte getLowBatteryThreshold(); Map<Key, MacroSequence> getMacros(); /** * Matrix size. * * @return height, width */ int[] getMatrixSize(); int getMaxDPI(); String getMode(); String getName(); int getPollRate(); List<Region> getRegions(); boolean[] getProfileRGB(); void setProfileRGB(boolean[] rgb); String getSerial(); DeviceType getType(); void importMacros(String macros); boolean isCharging(); boolean isGameMode(); boolean isModeModifier(); boolean isSuspended(); void removeListener(Listener listener); void setBrightness(short brightness); void setDPI(short x, short y); void setGameMode(boolean gameMode); void setIdleTime(int idleTime); void setLowBatteryThreshold(byte threshold); void setModeModifier(boolean modify); void setPollRate(int pollRate); void setSuspended(boolean suspended); default List<Name> getRegionNames() { List<Name> l = new ArrayList<>(); for (Region r : getRegions()) { l.add(r.getName()); } return l; } default Set<ComponentType> getSupportedComponentTypes() { Set<ComponentType> l = new LinkedHashSet<>(); l.add(ComponentType.AREA); if (getCapabilities().contains(Capability.MATRIX)) l.add(ComponentType.LED); if (getCapabilities().contains(Capability.DEDICATED_MACRO_KEYS)) l.add(ComponentType.KEY); if (getCapabilities().contains(Capability.PROFILE_LEDS) || getCapabilities().contains(Capability.MACROS)) l.add(ComponentType.ACCESSORY); return l; } List<Profile> getProfiles(); Profile getActiveProfile(); Profile getProfile(String name); Profile addProfile(String name); default Region getRegion(Name region) { for (Region r : getRegions()) { if (r.getName().equals(region)) return r; } return null; } }
3,274
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Capability.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/Capability.java
package uk.co.bithatch.snake.lib; public enum Capability { BATTERY, BRIGHTNESS, BRIGHTNESS_PER_REGION, DEDICATED_MACRO_KEYS, DPI, EFFECT_PER_REGION, EFFECTS, GAME_MODE, KEYBOARD_LAYOUT, MACRO_MODE_MODIFIER, MACROS, MATRIX, POLL_RATE, RIPPLE_RANDOM, RIPPLE_SINGLE, STARLIGHT_DUAL, STARLIGHT_RANDOM, STARLIGHT_SINGLE, PROFILE_LEDS, MACRO_PROFILES, MACRO_RECORDING, MACRO_PROFILE_LEDS }
388
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
BrandingImage.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/BrandingImage.java
package uk.co.bithatch.snake.lib; public enum BrandingImage { PERSPECTIVE, SIDE, TOP; }
90
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
DeviceType.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/DeviceType.java
package uk.co.bithatch.snake.lib; public enum DeviceType { ACCESSORY, CORE, HEADSET, KEYBOARD, KEYPAD, MOUSE, MOUSEMAT, UNRECOGNISED; public static DeviceType[] concreteTypes() { return new DeviceType[] { MOUSE, MOUSEMAT, KEYBOARD, KEYPAD, CORE, HEADSET, ACCESSORY }; } }
279
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
MacroScript.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/MacroScript.java
package uk.co.bithatch.snake.lib; import java.io.File; import java.util.List; @Deprecated public class MacroScript implements Macro { private List<String> args; private String script; public List<String> getArgs() { return args; } public String getScript() { return script; } public void setArgs(List<String> args) { this.args = args; } public void setScript(String script) { this.script = script; } @Override public String toString() { return "MacroScript [script=" + script + ", args=" + args + "]"; } @Override public void validate() throws ValidationException { if (script == null || script.length() == 0) throw new ValidationException("macroScript.missingScript"); var f = new File(script); if (!f.exists() || !f.isFile()) { for(String path : System.getenv("PATH").split(":")) { if(new File(new File(path), script).exists()) return; } throw new ValidationException("macroScript.invalidScript"); } } }
972
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Item.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/Item.java
package uk.co.bithatch.snake.lib; import java.util.Set; import uk.co.bithatch.snake.lib.effects.Effect; public interface Item { short getBrightness(); Set<Capability> getCapabilities(); Set<Class<? extends Effect>> getSupportedEffects(); void setBrightness(short brightness); }
289
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
MacroKey.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/MacroKey.java
package uk.co.bithatch.snake.lib; @Deprecated public class MacroKey implements Macro { public enum State { DOWN, UP } private Key key = Key.M1; private long prePause; private State state = State.DOWN; public Key getKey() { return key; } public long getPrePause() { return prePause; } public State getState() { return state; } public void setKey(Key key) { this.key = key; } public void setPrePause(long prePause) { this.prePause = prePause; } public void setState(State state) { this.state = state; } @Override public String toString() { return "MacroKey [prePause=" + prePause + ", state=" + state + ", key=" + key + "]"; } @Override public void validate() throws ValidationException { if(state == null) throw new ValidationException("macroKey.missingState"); if(key == null) throw new ValidationException("macroKey.missingKey"); } }
898
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Key.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/Key.java
package uk.co.bithatch.snake.lib; import java.util.HashMap; import java.util.Map; @Deprecated public enum Key { APOSTROPHE, BACKSLASH, BACKSPACE, BACKTICK, CAPSLK, COMMA, CTXMENU, DASH, DELETE, DOWNARROW, END, ENTER, EQUALS, ESC, FN, FORWARDSLASH, GAMEMODE, HOME, INS, LEFTALT, LEFTARROW, LEFTCTRL, LEFTSHIFT, LEFTSQUAREBRACKET, M1, M2, M3, M4, M5, MACROMODE, NP0, NP1, NP2, NP3, NP4, NP5, NP6, NP7, NP8, NP9, NPASTERISK, NPDASH, NPFORWARDSLASH, NPPERIOD, NPPLUS, NUMLK, PAGEDOWN, PAGEUP, PAUSE, PERIOD, POUNDSIGN, PRTSCR, RETURN, RIGHTALT, RIGHTARROW, RIGHTCTRL, RIGHTSHIFT, RIGHTSQUAREBRACKET, SCRLK, SEMICOLON, SPACE, SUPER, TAB, UPARROW, ONE("1"), TWO("2"), THREE("3"), FOUR("4"), FIVE("5"), SIX("6"), SEVEN("7"), EIGHT("8"), NINE("9"), TEN("10"), ELEVEN("11"), TWELVE("12"), THIRTEEN("13"), FOURTEEN("14"), FIFTEEN("15"), SIXTEEN("16"), SEVENTEEN("17"), EIGHTEEN("18"), NINETEEN("19"), MODE_SWITCH, THUMB, UP, DOWN, LEFT, RIGHT; String nativeKeyName; Key() { this(null); } Key(String nativeKeyName) { this.nativeKeyName = nativeKeyName; Key.NameMap.codeToName.put(nativeKeyName, this); } public String nativeKeyName() { return nativeKeyName == null ? name() : nativeKeyName; } public static Key fromNativeKeyName(String nativeKeyName) { Key key = Key.NameMap.codeToName.get(nativeKeyName); if (key == null) throw new IllegalArgumentException(String.format("No input event with code %s", nativeKeyName)); return key; } static class NameMap { final static Map<String, Key> codeToName = new HashMap<>(); } }
1,557
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Lit.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/Lit.java
package uk.co.bithatch.snake.lib; import uk.co.bithatch.snake.lib.effects.Effect; public interface Lit extends Item { <E extends Effect> E createEffect(Class<E> clazz); Effect getEffect(); default boolean isSupported(Effect effect) { return getSupportedEffects().contains(effect.getClass()); } void setEffect(Effect effect); void updateEffect(Effect effect); static Device getDevice(Lit component) { return component == null ? null : (component instanceof Device ? ((Device) component) : ((Region) component).getDevice()); } }
551
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Colors.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/Colors.java
package uk.co.bithatch.snake.lib; public class Colors { public final static int[] COLOR_BLACK = new int[3]; public static int[] fromHex(String hex) { if (hex.startsWith("#")) hex = hex.substring(1); return new int[] { Integer.parseInt(hex.substring(0, 2), 16), Integer.parseInt(hex.substring(2, 4), 16), Integer.parseInt(hex.substring(4, 6), 16) }; } public static String toHex(int[] col) { return String.format("#%02x%02x%02x", col[0], col[1], col[2]); } public static int[] getInterpolated(int[] from, int[] to, float frac) { return new int[] { (int) ((to[0] - from[0]) * frac) + from[0], (int) ((to[1] - from[1]) * frac) + from[1], (int) ((to[2] - from[2]) * frac) + from[2] }; } public static int[] toIntHSB(int[] rgb) { float[] f = toHSB(rgb); return new int[] { (int) (f[0] * 255.0), (int) (f[1] * 255.0), (int) (f[2] * 255.0) }; } public static int[] toRGB(int[] hsb) { return toRGB((float) hsb[0] / 255.0f, (float) hsb[1] / 255.0f, (float) hsb[2] / 255.0f); } public static int[] toRGB(float[] hsb) { float hue = hsb[0]; float saturation = hsb[1]; float brightness = hsb[2]; return toRGB(hue, saturation, brightness); } public static int[] toRGB(float hue, float saturation, float brightness) { int r = 0, g = 0, b = 0; if (saturation == 0) { r = g = b = (int) (brightness * 255.0f + 0.5f); } else { float h = (hue - (float) Math.floor(hue)) * 6.0f; float f = h - (float) java.lang.Math.floor(h); float p = brightness * (1.0f - saturation); float q = brightness * (1.0f - saturation * f); float t = brightness * (1.0f - (saturation * (1.0f - f))); switch ((int) h) { case 0: r = (int) (brightness * 255.0f + 0.5f); g = (int) (t * 255.0f + 0.5f); b = (int) (p * 255.0f + 0.5f); break; case 1: r = (int) (q * 255.0f + 0.5f); g = (int) (brightness * 255.0f + 0.5f); b = (int) (p * 255.0f + 0.5f); break; case 2: r = (int) (p * 255.0f + 0.5f); g = (int) (brightness * 255.0f + 0.5f); b = (int) (t * 255.0f + 0.5f); break; case 3: r = (int) (p * 255.0f + 0.5f); g = (int) (q * 255.0f + 0.5f); b = (int) (brightness * 255.0f + 0.5f); break; case 4: r = (int) (t * 255.0f + 0.5f); g = (int) (p * 255.0f + 0.5f); b = (int) (brightness * 255.0f + 0.5f); break; case 5: r = (int) (brightness * 255.0f + 0.5f); g = (int) (p * 255.0f + 0.5f); b = (int) (q * 255.0f + 0.5f); break; } } return new int[] { r, g, b }; } public static float[] toHSB(int[] rgb) { int r = rgb[0]; int g = rgb[1]; int b = rgb[2]; float hue, saturation, brightness; float[] hsbvals = new float[3]; int cmax = (r > g) ? r : g; if (b > cmax) cmax = b; int cmin = (r < g) ? r : g; if (b < cmin) cmin = b; brightness = ((float) cmax) / 255.0f; if (cmax != 0) saturation = ((float) (cmax - cmin)) / ((float) cmax); else saturation = 0; if (saturation == 0) hue = 0; else { float redc = ((float) (cmax - r)) / ((float) (cmax - cmin)); float greenc = ((float) (cmax - g)) / ((float) (cmax - cmin)); float bluec = ((float) (cmax - b)) / ((float) (cmax - cmin)); if (r == cmax) hue = bluec - greenc; else if (g == cmax) hue = 2.0f + redc - bluec; else hue = 4.0f + greenc - redc; hue = hue / 6.0f; if (hue < 0) hue = hue + 1.0f; } hsbvals[0] = hue; hsbvals[1] = saturation; hsbvals[2] = brightness; return hsbvals; } }
3,483
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Macro.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/Macro.java
package uk.co.bithatch.snake.lib; @Deprecated public interface Macro { void validate() throws ValidationException; }
121
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
MacroURL.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/MacroURL.java
package uk.co.bithatch.snake.lib; import java.net.MalformedURLException; import java.net.URL; @Deprecated public class MacroURL implements Macro { private String url; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @Override public String toString() { return "MacroURL [url=" + url + "]"; } @Override public void validate() throws ValidationException { if (url == null || url.length() == 0) throw new ValidationException("macroURL.missingURL"); try { new URL(url); } catch (MalformedURLException e) { throw new ValidationException("macroURL.invalidURL"); } } }
644
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
BackendException.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/BackendException.java
package uk.co.bithatch.snake.lib; @SuppressWarnings("serial") public class BackendException extends RuntimeException { public BackendException() { super(); } public BackendException(String message) { super(message); } public BackendException(String message, Throwable cause) { super(message, cause); } public BackendException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public BackendException(Throwable cause) { super(cause); } }
568
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
FramePlayer.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/animation/FramePlayer.java
package uk.co.bithatch.snake.lib.animation; import java.lang.System.Logger.Level; import java.util.ArrayList; import java.util.Collections; //import java.util.Iterator; import java.util.List; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; //import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.lib.effects.Matrix; public class FramePlayer { final static System.Logger LOG = System.getLogger(FramePlayer.class.getName()); public interface FrameListener { void frameUpdate(KeyFrame frame, int[][][] rgb, float fac, long frameNumber); void pause(boolean pause); void started(Sequence sequence, Device device); void stopped(); } private Device device; private Matrix effect; private ScheduledExecutorService executor; private int index; private List<FrameListener> listeners = Collections.synchronizedList(new ArrayList<>()); private boolean paused; private long pauseStarted; private boolean run; private Sequence sequence; private long started; private ScheduledFuture<?> task; private Runnable waitingTask; private long waitingTime; private TimeUnit waitingUnit; private ScheduledFuture<?> elapsedTimer; private long targetNewTimeElapsed; private long lastTimeElapsed; private AudioDataProvider audioDataProvider; public FramePlayer(ScheduledExecutorService executor, AudioDataProvider audioDataProvider) { this.executor = executor; this.audioDataProvider = audioDataProvider; } public void addListener(FrameListener listener) { listeners.add(listener); } public Device getDevice() { return device; } public void setDevice(Device device) { this.device = device; } public Matrix getEffect() { return effect; } public void setEffect(Matrix effect) { this.effect = effect; } public Sequence getSequence() { return sequence; } public void setSequence(Sequence sequence) { this.sequence = sequence; } public KeyFrame getFrame() { long now = getTimeElapsed(); KeyFrame playFrame = null; for (int i = 0; i < sequence.size(); i++) { KeyFrame kf = sequence.get(i); if (now >= kf.getIndex()) { playFrame = kf; } else if (playFrame != null) return playFrame; } return sequence.get(sequence.size() - 1); } public long getFrameNumber() { return started == 0 ? 0 : (long) ((double) sequence.getFps() * ((double) getTimeElapsed() / 1000.0)); } public long getTimeElapsed() { if (paused) { return pauseStarted - started; } else { return started == 0 ? 0 : (long) ((double) (System.currentTimeMillis() - started) * (sequence.getSpeed())); } } public boolean isPaused() { return paused; } public boolean isActive() { return isPlaying() && !isPaused(); } public boolean isPlaying() { return run; } public void play() { if (run) throw new IllegalStateException("Already playing."); if (device == null) throw new IllegalStateException("No device set."); if (sequence == null) throw new IllegalStateException("No sequence set."); if (effect == null) throw new IllegalStateException("No effect set."); this.index = 0; if (sequence.isEmpty()) return; this.run = true; started = System.currentTimeMillis(); try { executor.execute(() -> { fireStarted(sequence, device); playFrame(effect); }); } catch (RejectedExecutionException ree) { // On shutdown try { stop(); } catch (Exception e) { } } } public void removeListener(FrameListener listener) { listeners.remove(listener); } public void restart() { if (device == null || sequence == null) throw new IllegalStateException("Never started."); if (isActive()) { executor.execute(() -> { if (isPlaying()) stop(); executor.execute(() -> play()); }); } else { executor.execute(() -> play()); } } public void setPaused(boolean paused) { if (paused != this.paused) { this.paused = paused; if (paused) { pauseStarted = System.currentTimeMillis(); } else if (!paused) { started += System.currentTimeMillis() - pauseStarted; if (waitingTask != null) { schedule(waitingTask, waitingTime, waitingUnit); clearWaitingTask(); } } executor.execute(() -> firePaused(paused)); } } protected void clearWaitingTask() { waitingTask = null; waitingTime = 0; waitingUnit = null; } public void setTimeElapsed(long newTimeElapsed) { if (isPlaying()) { targetNewTimeElapsed = newTimeElapsed; /* * This limits the rate at which the time elapsed changes to the current FPS. If * this is not done, the LED's may lag. */ if (elapsedTimer == null) { lastTimeElapsed = -1; elapsedTimer = executor.scheduleAtFixedRate(() -> { if (lastTimeElapsed == targetNewTimeElapsed) { elapsedTimer.cancel(false); elapsedTimer = null; } else { lastTimeElapsed = targetNewTimeElapsed; doSetTimeElapsed(targetNewTimeElapsed); } }, getFrameTime(), getFrameTime(), TimeUnit.MILLISECONDS); } } else throw new IllegalStateException("Must be paused to be able to set time elapsed."); } protected void doSetTimeElapsed(long newTimeElapsed) { /* * Get the difference in time between the frame we are currently on and the time * we wish to seek to. Then adjust the start time (and pause time) accordingly */ long timeElapsed = getTimeElapsed(); long diff = newTimeElapsed - timeElapsed; started -= diff; KeyFrame frame = getFrame(); index = sequence.indexOf(frame); // Interpolation ip = getFrameInterpolation(frame); Interpolation ip = frame.getBestInterpolation(); float progress = ip.equals(Interpolation.none) ? 0 : getFrameProgress(newTimeElapsed - frame.getIndex(), frame); KeyFrame nextFrame = getNextFrame(frame); int[][][] rgb = frame.getInterpolatedFrame(nextFrame, progress, audioDataProvider); drawFrame(effect, rgb); fireFrameUpdate(frame, rgb, progress); } public void stop() { if (!run) throw new IllegalStateException("Not running."); if (paused) { started += System.currentTimeMillis() - pauseStarted; paused = false; clearWaitingTask(); } run = false; if (task != null) { task.cancel(false); task = null; } executor.execute(() -> ended()); } protected int[][][] drawFrame(Matrix effect, int[][][] rgbs) { effect.setCells(rgbs); device.updateEffect(effect); return rgbs; } protected void ended() { started = 0; KeyFrame ff = sequence.get(0); int[][][] rgb = ff.getRGBFrame(audioDataProvider); drawFrame(effect, rgb); fireFrameUpdate(ff, rgb, 0); fireStopped(); } void fireFrameUpdate(KeyFrame keyFrame, int[][][] rgb, float fac) { synchronized (listeners) { long f = getFrameNumber(); for (int i = listeners.size() - 1; i >= 0; i--) { listeners.get(i).frameUpdate(keyFrame, rgb, fac, f); } } } void firePaused(boolean pause) { synchronized (listeners) { for (int i = listeners.size() - 1; i >= 0; i--) { listeners.get(i).pause(pause); } } } void fireStarted(Sequence seq, Device device) { synchronized (listeners) { for (int i = listeners.size() - 1; i >= 0; i--) { listeners.get(i).started(seq, device); } } } void fireStopped() { synchronized (listeners) { for (int i = listeners.size() - 1; i >= 0; i--) { listeners.get(i).stopped(); } } } // Interpolation getFrameInterpolation(KeyFrame playFrame) { // return playFrame.getInterpolation() == null || playFrame.getInterpolation().equals(Interpolation.sequence) // ? sequence.getInterpolation() // : playFrame.getInterpolation(); // } float getFrameProgress(long now, KeyFrame playFrame) { /** Work out how far along the frame we are */ return (float) ((double) now / (double) playFrame.getActualLength()); } KeyFrame getNextFrame(KeyFrame frame) { int idx = sequence.indexOf(frame); KeyFrame nextFrame = idx < sequence.size() - 1 ? sequence.get(idx + 1) : null; if (nextFrame == null) { nextFrame = sequence.get(0); } return nextFrame; } void playFrame(Matrix effect) { try { /* * Work out which keyframe we should be on. Most of the time, this will be the * first hit. It take more iterations if the timeline position is changed while * running */ long now = (long) ((double) (System.currentTimeMillis() - started) * sequence.getSpeed()); KeyFrame playFrame = null; int playIndex = -1; for (int i = index; i < sequence.size(); i++) { KeyFrame kf = sequence.get(i); if (now >= kf.getIndex()) { /* * It is at least this frame, check the next and exit it if 'now' is not yet at * the keyframes index */ playFrame = kf; playIndex = i; } else if (playFrame != null) break; } if (playFrame == null) { /* This should be impossible */ restart(); return; } if (index != playIndex) { /* * Frame has changed, mark the previous frame as played (so it can reset it's * can cells etc) */ sequence.get(index).played(); } index = playIndex; float frac = getFrameProgress(now - playFrame.getIndex(), playFrame); /* Decide on interpolation */ // Interpolation interpolation = getFrameInterpolation(playFrame); // // /* // * If no interpolation, draw the first frame only, but keep running at the same // * refresh rate until the next key frame starts // */ // if (interpolation.equals(Interpolation.none)) { // int[][][] rgbs = playFrame.getRGBFrame(); // if (index != lastDrawnIndex) { // lastDrawnIndex = index; // // drawFrame(effect, rgbs); // } // fireFrameUpdate(playFrame, rgbs, 0); // if (frac >= 1) { // if (sequence.isRepeat()) { // /* Repeating, so reset all the indexes and start point */ // started = System.currentTimeMillis(); // index = 0; // } else { // run = false; // } // frac = 1; // } // } else { /* * Get the next frame. This will be the next in the sequence if there is one, * the first frame if this frame is the last and repeat mode is on, or null if * this would be the first frame and repeat mode is off */ KeyFrame nextFrame = playIndex < sequence.size() - 1 ? sequence.get(playIndex + 1) : null; if (nextFrame == null) { if (sequence.isRepeat()) { /* At the end ? */ if (frac >= 1) { /* Repeating, so reset all the indexes and start point */ started = System.currentTimeMillis(); index = 0; frac = 1; } } else { /* At the end ? */ if (frac >= 1) { run = false; frac = 1; } } nextFrame = sequence.get(0); } // int[][][] rgbs = playFrame.getInterpolatedFrame(nextFrame, // interpolation.apply(frac)); int[][][] rgbs = playFrame.getInterpolatedFrame(nextFrame, frac, audioDataProvider); drawFrame(effect, rgbs); fireFrameUpdate(playFrame, rgbs, frac); // } /* Schedule the next frame */ if (run) schedule(() -> playFrame(effect), getFrameTime(), TimeUnit.MILLISECONDS); else { ended(); } } catch (Exception e) { LOG.log(Level.ERROR, "Frame failed. Stopping player.", e); stop(); } } protected int getFrameTime() { return 1000 / sequence.getFps(); } void schedule(Runnable r, long t, TimeUnit u) { if (paused) { if (waitingTask == null) { waitingTask = r; waitingTime = t; waitingUnit = u; return; } else throw new IllegalStateException("Cannot submit any tasks when paused."); } if (!executor.isShutdown()) task = executor.schedule(r, t, u); } public boolean isReady() { return device != null && sequence != null && effect != null; } }
11,820
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Interpolation.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/animation/Interpolation.java
package uk.co.bithatch.snake.lib.animation; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; /** * Borrowed from LibGdx * * @author Nathan Sweet */ public abstract class Interpolation { private final static Map<String, Interpolation> interpolations = new LinkedHashMap<>(); private String name; abstract public float apply(float a); public float apply(float start, float end, float a) { return start + (end - start) * apply(a); } public static final Interpolation none = new Interpolation("none") { @Override public float apply(float a) { throw new UnsupportedOperationException(); } }; public static final Interpolation sequence = new Interpolation("sequence") { @Override public float apply(float a) { throw new UnsupportedOperationException(); } }; public static final Interpolation keyframe = new Interpolation("keyframe") { @Override public float apply(float a) { throw new UnsupportedOperationException(); } }; public static final Interpolation linear = new Interpolation("linear") { @Override public float apply(float a) { return a; } }; public static final Interpolation fade = new Interpolation("fade") { @Override public float apply(float a) { return clamp(a * a * a * (a * (a * 6 - 15) + 10), 0, 1); } }; public static final Interpolation circle = new Interpolation("circle") { @Override public float apply(float a) { if (a <= 0.5f) { a *= 2; return (1 - sqrt(1 - a * a)) / 2; } a--; a *= 2; return (sqrt(1 - a * a) + 1) / 2; } }; public static final Interpolation circleIn = new Interpolation("circleIn") { @Override public float apply(float a) { return 1 - sqrt(1 - a * a); } }; public static final Interpolation circleOut = new Interpolation("circleOut") { @Override public float apply(float a) { a--; return sqrt(1 - a * a); } }; public static final Interpolation sine = new Interpolation("sine") { @Override public float apply(float a) { return (1 - cos(a * (float) Math.PI)) / 2; } }; public static final Interpolation sineIn = new Interpolation("sineIn") { @Override public float apply(float a) { return 1 - cos(a * (float) Math.PI / 2); } }; public static final Interpolation sineOut = new Interpolation("sineOut") { @Override public float apply(float a) { return sin(a * (float) Math.PI / 2); } }; public static final Interpolation exp10 = new Exp(2, 10, "exp10"); public static final Interpolation exp10In = new ExpIn(2, 10, "exp10In"); public static final Interpolation exp10Out = new ExpOut(2, 10, "exp10Out"); public static final Interpolation exp5 = new Exp(2, 5, "exp5"); public static final Interpolation exp5In = new ExpIn(2, 5, "exp5In"); public static final Interpolation exp5Out = new ExpOut(2, 5, "exp5Out"); public static final Elastic elastic = new Elastic(2, 10, "elastic"); public static final Elastic elasticIn = new ElasticIn(2, 10, "elasticIn"); public static final Elastic elasticOut = new ElasticOut(2, 10, "elasticOut"); public static final Interpolation swing = new Swing(1.5f, "swing"); public static final Interpolation swingIn = new SwingIn(2f, "swingIn"); public static final Interpolation swingOut = new SwingOut(2f, "swingOut"); public static final Interpolation bounce = new Bounce(4, "bounce"); public static final Interpolation bounceIn = new BounceIn(4, "bounceIn"); public static final Interpolation bounceOut = new BounceOut(4, "bounceOut"); public static final Pow pow2 = new Pow(2, "pow2"); public static final PowIn pow2In = new PowIn(2, "pow2In"); public static final PowOut pow2Out = new PowOut(2, "pow2Out"); public static final Pow pow3 = new Pow(3, "pow3"); public static final PowIn pow3In = new PowIn(3, "pow3In"); public static final PowOut pow3Out = new PowOut(3, "pow3Out"); public static final Pow pow4 = new Pow(4, "pow4"); public static final PowIn pow4In = new PowIn(4, "pow4In"); public static final PowOut pow4Out = new PowOut(4, "pow4Out"); public static final Pow pow5 = new Pow(5, "pow5"); public static final PowIn pow5In = new PowIn(5, "pow5In"); public static final PowOut pow5Out = new PowOut(5, "pow5Out"); public static class Pow extends Interpolation { final int power; public Pow(int power, String name) { super(name); this.power = power; } @Override public float apply(float a) { if (a <= 0.5f) return pow(a * 2, power) / 2; return pow((a - 1) * 2, power) / (power % 2 == 0 ? -2 : 2) + 1; } } public static class PowIn extends Pow { public PowIn(int power, String name) { super(power, name); } @Override public float apply(float a) { return pow(a, power); } } public static class PowOut extends Pow { public PowOut(int power, String name) { super(power, name); } @Override public float apply(float a) { return pow(a - 1, power) * (power % 2 == 0 ? -1 : 1) + 1; } } public static class Exp extends Interpolation { final float value, power, min, scale; public Exp(float value, float power, String name) { super(name); this.value = value; this.power = power; min = (float) Math.pow(value, -power); scale = 1 / (1 - min); } @Override public float apply(float a) { if (a <= 0.5f) return (pow(value, power * (a * 2 - 1)) - min) * scale / 2; return (2 - (pow(value, -power * (a * 2 - 1)) - min) * scale) / 2; } }; public static class ExpIn extends Exp { public ExpIn(float value, float power, String name) { super(value, power, name); } @Override public float apply(float a) { return (pow(value, power * (a - 1)) - min) * scale; } } public static class ExpOut extends Exp { public ExpOut(float value, float power, String name) { super(value, power, name); } @Override public float apply(float a) { return 1 - (pow(value, -power * a) - min) * scale; } } public static class Elastic extends Interpolation { final float value, power; public Elastic(float value, float power, String name) { super(name); this.value = value; this.power = power; } @Override public float apply(float a) { if (a <= 0.5f) { a *= 2; return pow(value, power * (a - 1)) * sin(a * 20) * 1.0955f / 2; } a = 1 - a; a *= 2; return 1 - (float) Math.pow(value, power * (a - 1)) * sin((a) * 20) * 1.0955f / 2; } } public static class ElasticIn extends Elastic { public ElasticIn(float value, float power, String name) { super(value, power, name); } @Override public float apply(float a) { return pow(value, power * (a - 1)) * sin(a * 20) * 1.0955f; } } public static class ElasticOut extends Elastic { public ElasticOut(float value, float power, String name) { super(value, power, name); } @Override public float apply(float a) { a = 1 - a; return (1 - pow(value, power * (a - 1)) * sin(a * 20) * 1.0955f); } } public static class Bounce extends BounceOut { public Bounce(float[] widths, float[] heights, String name) { super(widths, heights, name); } public Bounce(int bounces, String name) { super(bounces, name); } private float out(float a) { float test = a + widths[0] / 2; if (test < widths[0]) return test / (widths[0] / 2) - 1; return super.apply(a); } @Override public float apply(float a) { if (a <= 0.5f) return (1 - out(1 - a * 2)) / 2; return out(a * 2 - 1) / 2 + 0.5f; } } public static class BounceOut extends Interpolation { final float[] widths, heights; public BounceOut(float[] widths, float[] heights, String name) { super(name); if (widths.length != heights.length) throw new IllegalArgumentException("Must be the same number of widths and heights."); this.widths = widths; this.heights = heights; } public BounceOut(int bounces, String name) { super(name); if (bounces < 2 || bounces > 5) throw new IllegalArgumentException("bounces cannot be < 2 or > 5: " + bounces); widths = new float[bounces]; heights = new float[bounces]; heights[0] = 1; switch (bounces) { case 2: widths[0] = 0.6f; widths[1] = 0.4f; heights[1] = 0.33f; break; case 3: widths[0] = 0.4f; widths[1] = 0.4f; widths[2] = 0.2f; heights[1] = 0.33f; heights[2] = 0.1f; break; case 4: widths[0] = 0.34f; widths[1] = 0.34f; widths[2] = 0.2f; widths[3] = 0.15f; heights[1] = 0.26f; heights[2] = 0.11f; heights[3] = 0.03f; break; case 5: widths[0] = 0.3f; widths[1] = 0.3f; widths[2] = 0.2f; widths[3] = 0.1f; widths[4] = 0.1f; heights[1] = 0.45f; heights[2] = 0.3f; heights[3] = 0.15f; heights[4] = 0.06f; break; } widths[0] *= 2; } @Override public float apply(float a) { a += widths[0] / 2; float width = 0, height = 0; for (int i = 0, n = widths.length; i < n; i++) { width = widths[i]; if (a <= width) { height = heights[i]; break; } a -= width; } a /= width; float z = 4 / width * height * a; return 1 - (z - z * a) * width; } } public static class BounceIn extends BounceOut { public BounceIn(float[] widths, float[] heights, String name) { super(widths, heights, name); } public BounceIn(int bounces, String name) { super(bounces, name); } @Override public float apply(float a) { return 1 - super.apply(1 - a); } } public static class Swing extends Interpolation { private final float scale; public Swing(float scale, String name) { super(name); this.scale = scale * 2; } @Override public float apply(float a) { if (a <= 0.5f) { a *= 2; return a * a * ((scale + 1) * a - scale) / 2; } a--; a *= 2; return a * a * ((scale + 1) * a + scale) / 2 + 1; } } public static class SwingOut extends Interpolation { private final float scale; public SwingOut(float scale, String name) { super(name); this.scale = scale; } @Override public float apply(float a) { a--; return a * a * ((scale + 1) * a + scale) + 1; } } public static class SwingIn extends Interpolation { private final float scale; public SwingIn(float scale, String name) { super(name); this.scale = scale; } @Override public float apply(float a) { return a * a * ((scale + 1) * a - scale); } } private Interpolation(String name) { this.name = name; interpolations.put(name, this); } public String getName() { return name; } @Override public String toString() { return name; } public static Interpolation fromName(String name) { return interpolations.get(name); } public static Collection<Interpolation> interpolations() { return interpolations.values(); } static float pow(float fBase, float fExponent) { return (float) Math.pow(fBase, fExponent); } static float sqrt(float fValue) { return (float) Math.sqrt(fValue); } static float sin(float v) { return (float) Math.sin(v); } static float cos(float v) { return (float) Math.cos(v); } float clamp(float input, float min, float max) { return (input < min) ? min : (input > max) ? max : input; } public static Interpolation get(String name) { return interpolations.get(name); } }
11,269
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
KeyFrameCell.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/animation/KeyFrameCell.java
package uk.co.bithatch.snake.lib.animation; import java.util.Arrays; import uk.co.bithatch.snake.lib.Colors; import uk.co.bithatch.snake.lib.animation.KeyFrame.KeyFrameCellSource; public class KeyFrameCell { private int[] values = KeyFrame.BLACK; private Interpolation interpolation = Interpolation.keyframe; private KeyFrameCellSource[] sources = new KeyFrameCellSource[] { KeyFrameCellSource.COLOR, KeyFrameCellSource.COLOR, KeyFrameCellSource.COLOR }; public KeyFrameCell(int[] rgb) { this(rgb, KeyFrameCellSource.COLOR); } public KeyFrameCell(int[] rgb, KeyFrameCellSource... sources) { super(); if (sources.length == 1) { sources = new KeyFrameCellSource[] { sources[0], sources[0], sources[0] }; } if (sources.length != 3) throw new IllegalArgumentException("Must always specify 3 or 1 sources."); this.sources = sources; this.values = rgb == null ? new int[3] : new int[] { rgb[0], rgb[1], rgb[2] }; } public KeyFrameCell(KeyFrameCell otherCell) { copyFrom(otherCell); } public KeyFrameCellSource[] getSources() { return sources; } public void setSources(KeyFrameCellSource[] sources) { this.sources = sources; } public Interpolation getInterpolation() { return interpolation; } public void setInterpolation(Interpolation interpolate) { if (interpolate == null) throw new IllegalArgumentException(); this.interpolation = interpolate; } public int[] getValues() { return values; } public void setValues(int[] values) { this.values = values; } @Override public String toString() { return "KeyFrameCell [source=" + Arrays.asList(sources) + ", rgb=" + Colors.toHex(values) + "]"; } public void copyFrom(KeyFrameCell cell) { this.values = cell.values; this.interpolation = cell.interpolation; this.sources = cell.sources; } }
1,817
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
AudioParameters.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/animation/AudioParameters.java
package uk.co.bithatch.snake.lib.animation; public class AudioParameters { private int low = 0; private int high = 255; private float gain = 1.0f; public int getLow() { return low; } public void setLow(int low) { this.low = Math.max(0, Math.min(255, low)); } public int getHigh() { return high; } public void setHigh(int high) { this.high = Math.max(0, Math.min(255, high)); } public float getGain() { return gain; } public void setGain(float gain) { this.gain = Math.max(0.0f, Math.min(20.0f, gain)); } }
539
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Sequence.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/animation/Sequence.java
package uk.co.bithatch.snake.lib.animation; import java.util.AbstractList; import java.util.ArrayList; import java.util.List; public class Sequence extends AbstractList<KeyFrame> { private List<KeyFrame> backing = new ArrayList<>(); private int fps = 10; private Interpolation interpolation = Interpolation.linear; private boolean repeat = true; private float speed = 1.f; private long totalFrames; private long totalLength; private AudioParameters audioParameters; public Sequence() { } public Sequence(Sequence sequence) { this.fps = sequence.fps; this.interpolation = sequence.interpolation; this.repeat = sequence.repeat; this.speed = sequence.speed; this.totalFrames = sequence.totalFrames; this.totalLength = sequence.totalLength; for(KeyFrame f : sequence.backing) { this.backing.add(new KeyFrame(f)); } } public AudioParameters getAudioParameters() { return audioParameters; } public void setAudioParameters(AudioParameters audioParameters) { this.audioParameters = audioParameters; } @Override public void add(int index, KeyFrame e) { try { e.setSequence(this); backing.add(index, e); } finally { rebuildTimestats(); } } @Override public boolean add(KeyFrame e) { try { e.setSequence(this); return backing.add(e); } finally { rebuildTimestats(); } } @Override public void clear() { backing.clear(); rebuildTimestats(); } @Override public KeyFrame get(int index) { return backing.get(index); } public int getFps() { return fps; } public Interpolation getInterpolation() { return interpolation; } public float getSpeed() { return speed; } public long getTotalFrames() { return totalFrames; } public long getTotalLength() { return totalLength; } public boolean isRepeat() { return repeat; } @Override public KeyFrame remove(int index) { try { return backing.remove(index); } finally { rebuildTimestats(); } } public void setFps(int fps) { this.fps = fps; rebuildTimestats(); } public void setInterpolation(Interpolation interpolation) { this.interpolation = interpolation; } public void setRepeat(boolean repeat) { this.repeat = repeat; } public void setSpeed(float speed) { this.speed = speed; rebuildTimestats(); } @Override public int size() { return backing.size(); } void rebuildTimestats() { totalFrames = 0; totalLength = 0; for (KeyFrame f : this) { f.setIndex(totalLength); f.setStartFrame(totalFrames); long keyFrameLength = f.getActualLength(); long keyFrameFrames = f.getActualFrames(); totalFrames += keyFrameFrames; totalLength += keyFrameLength; } } public KeyFrame getFrameAt(long l) { KeyFrame playFrame = null; for (int i = 0; i < size(); i++) { KeyFrame kf = get(i); if (l >= kf.getIndex()) { playFrame = kf; } else if (playFrame != null) return playFrame; } return get(size() - 1); } }
2,944
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
KeyFrame.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/animation/KeyFrame.java
package uk.co.bithatch.snake.lib.animation; import uk.co.bithatch.snake.lib.Colors; public class KeyFrame { static final int[] BLACK = new int[3]; public enum KeyFrameCellSource { COLOR, RANDOM, AUDIO } private static final KeyFrameCell EMPTY = new KeyFrameCell(BLACK); private KeyFrameCell[][] frame; private long holdFor; private long index; private Interpolation interpolation = Interpolation.sequence; private Sequence sequence; private long startFrame; private int[][][] rgbFrame; public KeyFrame() { } public KeyFrame(KeyFrame frame) { this.frame = frame.frame; this.holdFor = frame.holdFor; this.index = frame.index; this.interpolation = frame.interpolation; this.sequence = frame.sequence; this.startFrame = frame.startFrame; } public KeyFrame(KeyFrameCell[][] frame, long holdFor, Interpolation interpolate) { super(); this.frame = frame; this.holdFor = holdFor; this.interpolation = interpolate; } public long getActualFrames() { return holdFor == 0 ? 1 : (long) ((double) sequence.getFps() * ((double) holdFor / 1000.0) / sequence.getSpeed()); } public long getActualLength() { return (long) ((double) (holdFor == 0 ? (long) ((1.0 / (float) sequence.getFps()) * 1000.0) : holdFor) / sequence.getSpeed()); } // public boolean isAudioColor(int x, int y) { // return getCell(x, y).getSource().equals(KeyFrameCellSource.AUDIO); // } // // public boolean isRGB(int x, int y) { // return getCell(x, y).getSource().equals(KeyFrameCellSource.COLOR); // } // // public boolean isRandomColor(int x, int y) { // return getCell(x, y).getSource().equals(KeyFrameCellSource.RANDOM); // } public KeyFrameCell getCell(int x, int y) { if (frame == null || y >= frame.length) return EMPTY; KeyFrameCell[] rowData = frame[y]; if (rowData == null || x >= rowData.length) return EMPTY; return rowData[x]; } public long getEndTime() { return getActualLength() + getIndex(); } // public void setRandomColor(int x, int y, int[] rgb) { // setCell(x, y, new KeyFrameCell(KeyFrameCellSource.RANDOM, rgb)); // } // // public void setFixedColor(int x, int y, int[] rgb) { // setCell(x, y, new KeyFrameCell(KeyFrameCellSource.COLOR, rgb)); // } // // public void setAudioColor(int x, int y, int[] rgb) { // setCell(x, y, new KeyFrameCell(KeyFrameCellSource.AUDIO, rgb)); // } public void setCell(int x, int y, KeyFrameCell cell) { frame[y][x] = cell; rgbFrame = null; } public void setRGB(int x, int y, int[] rrgb) { if (frame[y][x] == null) setCell(x, y, new KeyFrameCell(rrgb)); else frame[y][x].setValues(rrgb); rgbFrame = null; } public KeyFrameCell[][] getFrame() { return frame; } public int[][][] getRGBFrame(AudioDataProvider audioDataProvider) { if (rgbFrame == null) { int[][][] f = new int[frame.length][][]; for (int row = 0; row < frame.length; row++) { f[row] = new int[frame[row].length][]; for (int col = 0; col < frame[row].length; col++) { f[row][col] = getGeneratedCellColor(col, row, audioDataProvider); } } rgbFrame = f; } return rgbFrame; } public int[] getGeneratedCellColor(int x, int y, AudioDataProvider dataProvider) { KeyFrameCell cell = frame[y][x]; if (cell == null) { return BLACK; } else { int[] values = cell.getValues(); int[] hsv = new int[3]; double audioAvg = -1; int[] colAsHsv = Colors.toIntHSB(values); for (int i = 0; i < 3; i++) { switch (cell.getSources()[i]) { case AUDIO: if (dataProvider == null) { hsv[i] = colAsHsv[i]; } else { if (audioAvg == -1) { audioAvg = 0; double[] data = dataProvider.getSnapshot(); AudioParameters audioParameters = getSequence().getAudioParameters(); if (audioParameters == null) { for (double d : data) audioAvg += d; } else { for (int j = audioParameters.getLow(); j <= audioParameters.getHigh(); j++) { audioAvg += data[j] * audioParameters.getGain(); } } audioAvg /= data.length; } hsv[i] = (int) (audioAvg * 255.0); } break; case RANDOM: hsv[i] = (int) (Math.random() * 255.0); break; default: // TODO should be hsv converted to RGB hsv[i] = colAsHsv[i]; break; } } return Colors.toRGB(hsv); } } public long getHoldFor() { return holdFor; } public long getIndex() { return index; } public Interpolation getBestCellInterpolation(int x, int y) { Interpolation i = frame[y][x] == null ? null : frame[y][x].getInterpolation(); return i == null || i.equals(Interpolation.keyframe) ? getBestInterpolation() : i; } public int[][][] getInterpolatedFrame(KeyFrame nextFrame, float frac, AudioDataProvider dataProvider) { int[][][] next = nextFrame.getRGBFrame(dataProvider); int[][][] thisRGB = getRGBFrame(dataProvider); int[][][] newFrame = new int[frame.length][][]; for (int y = 0; y < frame.length; y++) { int[][] thisRow = thisRGB[y]; int[][] otherRow = next[y]; int[][] newRow = new int[thisRow.length][3]; for (int x = 0; x < newRow.length; x++) { Interpolation inter = getBestCellInterpolation(x, y); int[] thisCol = thisRow[x]; int[] otherCol = otherRow[x]; int[] newCol = newRow[x]; if (inter.equals(Interpolation.none)) { /* * If interpolation is none, then we query the source each frame rather than * interpolate a single value from one from to the next */ int[] rgb = getGeneratedCellColor(x, y, dataProvider); newCol[0] = rgb[0]; newCol[1] = rgb[1]; newCol[2] = rgb[2]; } else { float cellFrac = inter.apply(frac); newCol[0] = thisCol[0] + (int) (((float) otherCol[0] - (float) thisCol[0]) * cellFrac); newCol[1] = thisCol[1] + (int) (((float) otherCol[1] - (float) thisCol[1]) * cellFrac); newCol[2] = thisCol[2] + (int) (((float) otherCol[2] - (float) thisCol[2]) * cellFrac); } } newFrame[y] = newRow; } return newFrame; } public Interpolation getInterpolation() { return interpolation; } public int[] getOverallColor(AudioDataProvider audio) { return getOverallColor(audio, false); } public int[] getOverallColor(AudioDataProvider audio, boolean includeBlack) { if (frame == null) return Colors.COLOR_BLACK; long els = 0; long r = 0, g = 0, b = 0; for (int y = 0; y < frame.length; y++) { for (int x = 0; x < frame[y].length; x++) { int[] col = getGeneratedCellColor(x, y, audio); if (col[0] == 0 && col[1] == 0 && col[2] == 0) continue; els++; r += col[0]; g += col[1]; b += col[2]; } } return els == 0 ? Colors.COLOR_BLACK : new int[] { (int) (r / els), (int) (g / els), (int) (b / els) }; } public Sequence getSequence() { return sequence; } public long getStartFrame() { return startFrame; } public void setColor(int[] fillColor, int rows, int cols) { frame = new KeyFrameCell[rows][cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { frame[i][j] = new KeyFrameCell(fillColor); } } rgbFrame = null; } public void setFrame(KeyFrameCell[][] frame) { this.frame = frame; } public void setHoldFor(long holdFor) { try { this.holdFor = holdFor; } finally { if (sequence != null) { sequence.rebuildTimestats(); } } } public void setInterpolation(Interpolation interpolate) { this.interpolation = interpolate; } void setIndex(long index) { this.index = index; } void setSequence(Sequence sequence) { this.sequence = sequence; } void setStartFrame(long startFrame) { this.startFrame = startFrame; } // public int getRandomCells() { // int c = 0; // for (int y = 0; y < frame.length; y++) { // for (int x = 0; x < frame[y].length; x++) { // if (isRandomColor(x, y)) { // c++; // } // } // } // return c; // } // // public int getAudioCells() { // int c = 0; // for (int y = 0; y < frame.length; y++) { // for (int x = 0; x < frame[y].length; x++) { // if (isAudioColor(x, y)) { // c++; // } // } // } // return c; // } // // public int getRGBCells() { // int c = 0; // for (int y = 0; y < frame.length; y++) { // for (int x = 0; x < frame[y].length; x++) { // if (isRGB(x, y)) { // c++; // } // } // } // return c; // } public void played() { rgbFrame = null; } public Interpolation getBestInterpolation() { return interpolation == null || interpolation.equals(Interpolation.sequence) ? getSequence().getInterpolation() : interpolation; } }
8,564
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
MatrixIO.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/layouts/MatrixIO.java
package uk.co.bithatch.snake.lib.layouts; public interface MatrixIO extends IO { default boolean isMatrixLED() { return getMatrixX() > -1 && getMatrixY() > -1; } int getMatrixX(); int getMatrixY(); void setMatrixX(int matrixX); void setMatrixY(int matrixY); default void setMatrixXY(int x, int y) { setMatrixX(x); setMatrixY(y); } default void setMatrixXY(Cell pos) { if (pos == null) { setMatrixX(-1); setMatrixY(-1); } else { setMatrixX(pos.getX()); setMatrixY(pos.getY()); } } default Cell getMatrixXY() { return getMatrixX() == -1 || getMatrixY() == -1 ? null : new Cell(getMatrixX(), getMatrixY()); } MatrixCell getMatrixCell(); }
686
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
ViewPosition.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/layouts/ViewPosition.java
package uk.co.bithatch.snake.lib.layouts; import uk.co.bithatch.snake.lib.BrandingImage; public enum ViewPosition { TOP, BOTTOM, SIDE_1, SIDE_2, FRONT, BACK, THREE_D_1, THREE_D_2, MATRIX; public BrandingImage toBrandingImage() { switch (this) { case TOP: return BrandingImage.TOP; case SIDE_1: case SIDE_2: return BrandingImage.SIDE; case THREE_D_1: case THREE_D_2: return BrandingImage.PERSPECTIVE; default: return null; } } }
462
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
DeviceView.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/layouts/DeviceView.java
package uk.co.bithatch.snake.lib.layouts; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import uk.co.bithatch.snake.lib.Region.Name; import uk.co.bithatch.snake.lib.layouts.IO.IOListener; public class DeviceView implements IOListener { public interface Listener { void viewChanged(DeviceView view); default void elementAdded(DeviceView view, IO element) { } default void elementChanged(DeviceView view, IO element) { } default void elementRemoved(DeviceView view, IO element) { } } private List<Listener> listeners = new ArrayList<>(); private List<IO> elements = new ArrayList<>(); private Map<ComponentType, Map<Cell, IO>> elementMap = new HashMap<>(); private String imageUri; private ViewPosition position = ViewPosition.TOP; private boolean desaturateImage = false; private float imageScale = 1; private float imageOpacity = 1; private DeviceLayout layout; public DeviceView() { } public DeviceView(DeviceView view, DeviceLayout layout) { this.imageUri = view.imageUri; this.position = view.position; this.desaturateImage = view.desaturateImage; this.imageScale = view.imageScale; this.imageOpacity = view.imageOpacity; this.layout = layout; for (IO el : view.elements) { try { addElement((IO) el.clone()); } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } } } public void addListener(Listener listener) { listeners.add(listener); } public void removeListener(Listener listener) { listeners.remove(listener); } public DeviceLayout getLayout() { return layout; } public void setLayout(DeviceLayout layout) { this.layout = layout; } public List<IO> getElements() { return Collections.unmodifiableList(elements); } public List<IO> getElements(ComponentType type) { List<IO> elementsOfType = new ArrayList<>(); for (IO el : getElements()) { if (ComponentType.fromClass(el.getClass()).equals(type)) { elementsOfType.add(el); } } return elementsOfType; } public float getImageOpacity() { return imageOpacity; } public void setImageOpacity(float imageOpacity) { this.imageOpacity = imageOpacity; fireChanged(); } public Cell getNextFreeCell(ComponentType type) { int y = 0; int x = -1; Cell cellPosition = new Cell(0, 0); Map<Cell, IO> elementMap = getMapForType(type); while (true) { do { x++; if (x == layout.getMatrixWidth()) { x = 0; y++; if (y == layout.getMatrixHeight()) { y = x = -1; break; } } cellPosition = new Cell(x, y); } while (elementMap.containsKey(cellPosition)); if (x == -1) /* No more free spaces, will have to give up and leave to user to sort out */ throw new IllegalStateException("No more free cells."); /* Only return elements whose matrix cells are not disabled */ MatrixCell cell = layout.getViews().get(ViewPosition.MATRIX).getElement(ComponentType.MATRIX_CELL, x, y); if (cell == null || !cell.isDisabled()) break; } return cellPosition; } public void removeElement(IO element) { if (elements.contains(element)) { element.removeListener(this); elements.remove(element); if (element instanceof MatrixIO) { getMapForType(element) .remove(new Cell(((MatrixIO) element).getMatrixX(), ((MatrixIO) element).getMatrixY())); } fireElementRemoved(element); } } public void addElement(IO element) { if (!elements.contains(element)) { element.addListener(this); elements.add(element); if (element instanceof AbstractIO) { ((AbstractIO) element).setView(this); } if (element instanceof MatrixIO) { getMapForType(element) .put(new Cell(((MatrixIO) element).getMatrixX(), ((MatrixIO) element).getMatrixY()), element); } fireElementAdded(element); } } private Map<Cell, IO> getMapForType(IO element) { ComponentType ct = ComponentType.fromClass(element.getClass()); return getMapForType(ct); } protected Map<Cell, IO> getMapForType(ComponentType ct) { Map<Cell, IO> m = elementMap.get(ct); if (m == null) { m = new HashMap<>(); elementMap.put(ct, m); } return m; } public String getImageUri() { return imageUri; } public void setImageUri(String imageUri) { this.imageUri = imageUri; fireChanged(); } public ViewPosition getPosition() { return position; } public void setPosition(ViewPosition position) { this.position = position; if (layout != null) layout.updatePosition(this); fireChanged(); } public boolean isDesaturateImage() { return desaturateImage; } public void setDesaturateImage(boolean desaturateImage) { this.desaturateImage = desaturateImage; fireChanged(); } public float getImageScale() { return imageScale; } public void setImageScale(float imageScale) { this.imageScale = imageScale; fireChanged(); } @SuppressWarnings("unchecked") public <O extends IO> O getElement(ComponentType type, int matrixX, int matrixY) { return (O) getMapForType(type).get(new Cell(matrixX, matrixY)); } void fireChanged() { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).viewChanged(this); } void fireElementRemoved(IO element) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).elementRemoved(this, element); } void fireElementChanged(IO element) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).elementChanged(this, element); } void fireElementAdded(IO element) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).elementAdded(this, element); } public String getResolvedImageUri(URL base) { if (imageUri == null) return null; try { new URL(imageUri); } catch (MalformedURLException murle) { if (base != null) { return base.toExternalForm() + "/" + imageUri; } else { if (imageUri.startsWith("/")) { return new File(imageUri).toURI().toString(); } } } return imageUri; } @Override public String toString() { return "DeviceView [elements=" + elements + ", imageUri=" + imageUri + ", position=" + position + ", desaturateImage=" + desaturateImage + ", imageScale=" + imageScale + ", imageOpacity=" + imageOpacity + "]"; } @Override public void elementChanged(IO element) { fireElementChanged(element); } public IO getAreaElement(Name name) { for (IO el : elements) { if (el instanceof Area && name != null && name.equals(((Area) el).getRegion())) return el; } return null; } }
6,644
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
AbstractIO.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/layouts/AbstractIO.java
package uk.co.bithatch.snake.lib.layouts; import java.util.ArrayList; import java.util.List; public abstract class AbstractIO implements IO { private String label; private float x; private float y; private List<IOListener> listeners = new ArrayList<>(); private DeviceView view; protected AbstractIO() { this((DeviceView) null); } protected AbstractIO(DeviceView view) { this.view = view; } protected AbstractIO(AbstractIO io) { this.label = io.label; this.x = io.x; this.y = io.y; } @Override public DeviceView getView() { return view; } @Override public void addListener(IOListener listener) { listeners.add(listener); } @Override public void removeListener(IOListener listener) { listeners.remove(listener); } @Override public String getLabel() { return label; } @Override public void setLabel(String label) { this.label = label; fireChanged(); } @Override public float getX() { return x; } @Override public float getY() { return y; } @Override public void setX(float x) { this.x = x; fireChanged(); } @Override public void setY(float y) { this.y = y; fireChanged(); } @Override public String toString() { return "AbstractIO [label=" + label + ", x=" + x + ", y=" + y + "]"; } @Override public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } void fireChanged() { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).elementChanged(this); } public void setView(DeviceView view) { this.view = view; } protected static String toName(String name) { if (name == null || name.length() == 0) return name; return (name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase()).replace('_', ' '); } }
1,780
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
RegionIO.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/layouts/RegionIO.java
package uk.co.bithatch.snake.lib.layouts; import uk.co.bithatch.snake.lib.Region; public interface RegionIO { Region.Name getRegion(); void setRegion(Region.Name region); }
179
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-lib/src/main/java/uk/co/bithatch/snake/lib/layouts/Layout.java
package uk.co.bithatch.snake.lib.layouts; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.System.Logger.Level; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.Properties; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.stream.JsonReader; @Deprecated public class Layout { final static System.Logger LOG = System.getLogger(Layout.class.getName()); private final static Map<String, Layout> layouts = new HashMap<>(); private final static Map<String, String> layoutToName = new HashMap<>(); private final static Map<String, String> nameToLayout = new HashMap<>(); static { Properties p = new Properties(); try (InputStream in = Layout.class.getResourceAsStream("languages.properties")) { p.load(in); for (Object k : p.keySet()) { String v = p.getProperty((String) k); layoutToName.put((String) k, v); nameToLayout.put(v, (String) k); } } catch (IOException ioe) { throw new IllegalStateException("Failed to load language mappings."); } } public static Layout get(String layout, int width, int height) { String key = layout + "_" + width; if (!layouts.containsKey(key)) { URL resource = Layout.class.getResource(width + ".json"); if (resource == null) throw new IllegalStateException( String.format("No keyboard layout for language %s and matrix width %d.", layout, width)); try (InputStream in = resource.openStream()) { JsonObject jsonObject = JsonParser.parseReader(new JsonReader(new InputStreamReader(in))) .getAsJsonObject(); JsonElement map = jsonObject.get(layout); String layoutName = layout; boolean exact = true; if (map == null) { layoutName = layoutToName.get(layout); map = layout == null ? null : jsonObject.get(layoutName); } else { layout = nameToLayout.get(layoutName); } if (map == null && !"US".equals(layoutName) && !"en_US".equals(layout)) { LOG.log(Level.WARNING, String.format("No exact map for %s, using 'US'", layout)); layout = "en_US"; layoutName = "US"; map = jsonObject.get(layout); if (map == null) throw new IOException(String.format("Could not find any layout in %s for keyboard layout %s", resource, layout)); exact = false; } Layout layoutObj = new Layout(); layoutObj.setKeys(new MatrixCell[height][width]); layoutObj.setLayout(layout); layoutObj.setName(layoutName); layoutObj.setX(width); layoutObj.setY(height); layoutObj.setExact(exact); layoutObj.setKeys(new MatrixCell[height][]); for (int r = 0; r < height; r++) { MatrixCell[] rowArr = new MatrixCell[width]; layoutObj.getKeys()[r] = rowArr; } JsonObject mapObj = map.getAsJsonObject(); for (int r = 0; r < height; r++) { MatrixCell[] rowArr = new MatrixCell[width]; layoutObj.getKeys()[r] = rowArr; JsonElement row = mapObj.get("row" + r); if (row == null) LOG.log(Level.WARNING, String.format("No row %d in map %s for layout %s", r, resource, layout)); JsonArray rowObj = row.getAsJsonArray(); for (JsonElement el : rowObj) { JsonObject elObj = el.getAsJsonObject(); MatrixCell keyObj = new MatrixCell(); JsonElement labelEl = elObj.get("label"); keyObj.setLabel(labelEl.isJsonNull() ? null : labelEl.getAsString()); keyObj.setDisabled(elObj.has("disabled") ? elObj.get("disabled").getAsBoolean() : false); keyObj.setWidth(elObj.has("width") ? elObj.get("width").getAsInt() : 0); JsonElement matrix = elObj.get("matrix"); if (matrix != null) { JsonArray arr = matrix.getAsJsonArray(); keyObj.setMatrixY(arr.get(0).getAsInt()); keyObj.setMatrixX(arr.get(1).getAsInt()); } layoutObj.getKeys()[(int)keyObj.getMatrixY()][(int)keyObj.getMatrixX()] = keyObj; } } layouts.put(key, layoutObj); return layoutObj; } catch (IOException ioe) { throw new IllegalStateException( String.format("Failed to read keyboard layout for language %s and matrix width %d from %s.", layout, width, resource)); } } return layouts.get(key); } private boolean exact; private MatrixCell[][] keys; private String layout; private String name; private int x; private int y; public MatrixCell[][] getKeys() { return keys; } public String getLayout() { return layout; } public String getName() { return name; } public int getX() { return x; } public int getY() { return y; } public boolean isExact() { return exact; } public void setExact(boolean exact) { this.exact = exact; } public void setKeys(MatrixCell[][] keys) { this.keys = keys; } public void setLayout(String layout) { this.layout = layout; } public void setName(String name) { this.name = name; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } }
5,077
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
LED.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/layouts/LED.java
package uk.co.bithatch.snake.lib.layouts; public class LED extends AbstractMatrixIO { public LED() { super(); } public LED(DeviceView view) { super(view); } public LED(LED led) { super(led); } @Override public Object clone() throws CloneNotSupportedException { return new LED(this); } }
311
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Area.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/layouts/Area.java
package uk.co.bithatch.snake.lib.layouts; import uk.co.bithatch.snake.lib.Region; public class Area extends AbstractIO implements RegionIO { private Region.Name region; public Area() { super(); } public Area(DeviceView view) { super(view); } public Area(Area area) { super(area); region = area.region; } public Region.Name getRegion() { return region; } public void setRegion(Region.Name region) { this.region = region; fireChanged(); } @Override public String getDefaultLabel() { return region == null ? getClass().getSimpleName() : toName(region.name()); } @Override public Object clone() throws CloneNotSupportedException { return new Area(this); } }
699
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
ComponentType.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/layouts/ComponentType.java
package uk.co.bithatch.snake.lib.layouts; public enum ComponentType { LED, KEY, AREA, ACCESSORY, MATRIX_CELL; public IO createElement() { switch (this) { case LED: return new LED(); case KEY: return new Key(); case ACCESSORY: return new Accessory(); default: return new Area(); } } public static ComponentType fromClass(Class<? extends IO> clazz) { if (clazz.equals(uk.co.bithatch.snake.lib.layouts.LED.class)) { return LED; } else if (clazz.equals(uk.co.bithatch.snake.lib.layouts.Key.class)) { return KEY; } else if (clazz.equals(uk.co.bithatch.snake.lib.layouts.Area.class)) { return AREA; } else if (clazz.equals(uk.co.bithatch.snake.lib.layouts.MatrixCell.class)) { return MATRIX_CELL; } else if (clazz.equals(uk.co.bithatch.snake.lib.layouts.Accessory.class)) { return ACCESSORY; } else throw new IllegalArgumentException("Unknown type."); } public boolean isShowByDefault() { switch (this) { case AREA: case ACCESSORY: return false; default: return true; } } }
1,048
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Key.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/layouts/Key.java
package uk.co.bithatch.snake.lib.layouts; import java.util.Objects; import uk.co.bithatch.linuxio.EventCode; public class Key extends AbstractMatrixIO { private EventCode eventCode; private uk.co.bithatch.snake.lib.Key legacyKey; public Key() { super(); } public Key(DeviceView view) { super(view); } public Key(Key key) { super(key); eventCode = key.eventCode; } public uk.co.bithatch.snake.lib.Key getLegacyKey() { return legacyKey; } public void setLegacyKey(uk.co.bithatch.snake.lib.Key legacyKey) { if (!Objects.equals(legacyKey, this.legacyKey)) { this.legacyKey = legacyKey; fireChanged(); } } public EventCode getEventCode() { return eventCode; } @Override public String getDefaultLabel() { if (eventCode == null || isMatrixLED()) return super.getDefaultLabel(); else { if (eventCode.name().startsWith("BTN_")) { return toName(eventCode.name().substring(4)) + " Button"; } else if (eventCode.name().startsWith("KEY_")) { return toName(eventCode.name().substring(4)) + " Key"; } else return toName(eventCode.name()); } } public void setEventCode(EventCode eventCode) { if (!Objects.equals(eventCode, this.eventCode)) { this.eventCode = eventCode; fireChanged(); } } @Override public Object clone() throws CloneNotSupportedException { return new Key(this); } }
1,368
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Cell.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/layouts/Cell.java
package uk.co.bithatch.snake.lib.layouts; public class Cell { private final int x; private final int y; public Cell(int x, int y) { this.y = y; this.x = x; } public Cell(MatrixIO matrixIO) { this.y = matrixIO.getMatrixY(); this.x = matrixIO.getMatrixX(); } public int getX() { return x; } public int getY() { return y; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Cell other = (Cell) obj; if (y != other.y) return false; if (x != other.x) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + y; result = prime * result + x; return result; } @Override public String toString() { return "Cell [y=" + y + ", x=" + x + "]"; } }
890
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
IO.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/layouts/IO.java
package uk.co.bithatch.snake.lib.layouts; public interface IO extends Cloneable { public interface IOListener { void elementChanged(IO element); } void addListener(IOListener listener); void removeListener(IOListener listener); String getLabel(); String getDefaultLabel(); default String getDisplayLabel() { String label = getLabel(); if (label == null) return getDefaultLabel(); else return label; } float getX(); float getY(); void setX(float x); void setY(float y); void setLabel(String label); DeviceView getView(); Object clone() throws CloneNotSupportedException; }
615
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
MatrixCell.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/layouts/MatrixCell.java
package uk.co.bithatch.snake.lib.layouts; import java.util.Objects; import uk.co.bithatch.snake.lib.Region; public class MatrixCell extends AbstractMatrixIO implements RegionIO { private int width; private boolean disabled; private Region.Name region = Region.Name.CHROMA; public MatrixCell() { super(); } public MatrixCell(DeviceView view) { super(view); } public MatrixCell(MatrixCell cell) { super(cell); width = cell.width; disabled = cell.disabled; region = cell.region; } public Region.Name getRegion() { return region; } public void setRegion(Region.Name region) { if (!Objects.equals(region, this.region)) { this.region = region; fireChanged(); } } public boolean isDisabled() { return disabled; } public void setDisabled(boolean disabled) { this.disabled = disabled; fireChanged(); } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; fireChanged(); } @Override public String toString() { return "MatrixCell [region=" + region + ", width=" + width + ", disabled=" + disabled + ", getMatrixX()=" + getMatrixX() + ", getMatrixY()=" + getMatrixY() + ", getLabel()=" + getLabel() + ", getX()=" + getX() + ", getY()=" + getY() + "]"; } @Override public Object clone() throws CloneNotSupportedException { return new MatrixCell(this); } }
1,374
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
DeviceLayouts.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/layouts/DeviceLayouts.java
package uk.co.bithatch.snake.lib.layouts; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.google.gson.JsonElement; import uk.co.bithatch.snake.lib.Capability; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.lib.Json; public class DeviceLayouts implements uk.co.bithatch.snake.lib.layouts.DeviceLayout.Listener { public interface Listener { default void layoutChanged(DeviceLayout layout) { } default void layoutAdded(DeviceLayout layout) { } default void layoutRemoved(DeviceLayout layout) { } default void viewChanged(DeviceLayout layout, DeviceView view) { } default void viewElementAdded(DeviceLayout layout, DeviceView view, IO element) { } default void viewElementChanged(DeviceLayout layout, DeviceView view, IO element) { } default void viewElementRemoved(DeviceLayout layout, DeviceView view, IO element) { } default void viewAdded(DeviceLayout layout, DeviceView view) { } default void viewRemoved(DeviceLayout layout, DeviceView view) { } } private List<DeviceLayout> layouts = new ArrayList<>(); private List<Listener> listeners = new ArrayList<>(); public void addListener(Listener listener) { listeners.add(listener); } public void removeListener(Listener listener) { listeners.remove(listener); } public void registerLayout(DeviceLayout layout) { doAddLayout(layout); } public void addLayout(DeviceLayout layout) { doAddLayout(layout); for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).layoutAdded(layout); } protected void doAddLayout(DeviceLayout layout) { if (layouts.contains(layout)) throw new IllegalStateException("Already contains this layout."); DeviceLayout oldLayout = findLayout(layout.getName()); if (oldLayout != null) { remove(layout); } layouts.add(layout); layout.addListener(this); } public boolean hasOfficialLayout(Device device) { return getLayoutResource(device.getName() + ".json") != null; } public boolean hasLayout(Device device) { /* First look for a registered layout for this device */ for (DeviceLayout layout : layouts) { if (layout.getName().equals(device.getName())) { return true; } } /* TODO when there are user layouts */ return hasOfficialLayout(device); } public DeviceLayout getLayout(Device device) { /* First look for a registered layout for this device */ DeviceLayout layout = findLayout(device.getName()); if (layout != null) return layout; /* Now look for a default resource with the device name */ URL res = getLayoutResource(device.getName() + ".json"); if (res == null) { /* That doesn't exist. Is there a matrix layout we can convert? */ if (device.getCapabilities().contains(Capability.KEYBOARD_LAYOUT)) { DeviceLayout deviceLayout = new DeviceLayout(device); deviceLayout.addView(createMatrixView(device)); addLayout(deviceLayout); return deviceLayout; } else { DeviceLayout deviceLayout = new DeviceLayout(device); addLayout(deviceLayout); return deviceLayout; } } else { try (InputStream in = res.openStream()) { JsonElement json = Json.toJson(in); DeviceLayout builtInlayout = new DeviceLayout(res, json.getAsJsonObject()); builtInlayout.setReadOnly(true); doAddLayout(builtInlayout); return builtInlayout; } catch (Exception ioe) { throw new IllegalStateException(String.format("Failed to load built-in layout.", res), ioe); } } } public static DeviceView createMatrixView(Device device) { DeviceView v = new DeviceView(); int w = device.getMatrixSize()[1]; int h = device.getMatrixSize()[0]; Layout legacyLayout = device.getCapabilities().contains(Capability.KEYBOARD_LAYOUT) ? Layout.get(device.getKeyboardLayout(), w, h) : null; v.setPosition(ViewPosition.MATRIX); if (legacyLayout == null) { int number = 1; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { MatrixCell k = new MatrixCell(v); k.setMatrixX(x); k.setMatrixY(y); v.addElement(k); } } } else { for (MatrixCell[] row : legacyLayout.getKeys()) { for (MatrixCell col : row) { if (col != null) v.addElement(col); } } } return v; } protected DeviceLayout findLayout(String name) { for (DeviceLayout layout : layouts) { if (layout.getName().equals(name)) { return layout; } } return null; } public void remove(DeviceLayout layout) { if (layouts.remove(layout)) { layout.removeListener(this); for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).layoutRemoved(layout); } } public List<DeviceLayout> getLayouts() { return Collections.unmodifiableList(layouts); } @Override public void layoutChanged(DeviceLayout layout, DeviceView view) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).layoutChanged(layout); } @Override public void viewRemoved(DeviceLayout layout, DeviceView view) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).viewRemoved(layout, view); } @Override public void viewChanged(DeviceLayout layout, DeviceView view) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).viewChanged(layout, view); } @Override public void viewAdded(DeviceLayout layout, DeviceView view) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).viewAdded(layout, view); } @Override public void viewElementAdded(DeviceLayout layout, DeviceView view, IO element) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).viewElementAdded(layout, view, element); } @Override public void viewElementRemoved(DeviceLayout layout, DeviceView view, IO element) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).viewElementRemoved(layout, view, element); } @Override public void viewElementChanged(DeviceLayout layout, DeviceView view, IO element) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).viewElementChanged(layout, view, element); } protected URL getLayoutResource(String name) { URL res = getClass().getResource(name); if (res == null) { res = ClassLoader.getSystemClassLoader() .getResource(DeviceLayouts.class.getPackageName().replace('.', '/') + "/" + name); return res; } else { return res; } } }
6,525
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
AbstractMatrixIO.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/layouts/AbstractMatrixIO.java
package uk.co.bithatch.snake.lib.layouts; public abstract class AbstractMatrixIO extends AbstractIO implements MatrixIO { private int matrixX; private int matrixY; protected AbstractMatrixIO() { super(); } protected AbstractMatrixIO(DeviceView view) { super(view); } protected AbstractMatrixIO(AbstractMatrixIO io) { super(io); matrixX = io.matrixX; matrixY = io.matrixY; } @Override public String getDefaultLabel() { MatrixCell cell = getMatrixCell(); if (cell == null || cell == this) { DeviceView view = getView(); if(view != null && view.getLayout().getMatrixWidth() == 1) return String.format("%d", matrixY); else if(view != null && view.getLayout().getMatrixHeight() == 1) return String.format("%d", matrixX); else return String.format("%d,%d", matrixX, matrixY); } else return cell.getDisplayLabel(); } public int getMatrixX() { return matrixX; } public void setMatrixX(int matrixX) { if (matrixX != this.matrixX) { if (matrixX != -1 && getView() != null && getView().getLayout() != null && (matrixX < -1 || matrixX >= getView().getLayout().getMatrixWidth())) throw new IllegalArgumentException( String.format("Matrix X of %d is greater than the matrix width of %d", matrixX, getView().getLayout().getMatrixWidth())); this.matrixX = matrixX; fireChanged(); } } public int getMatrixY() { return matrixY; } public void setMatrixY(int matrixY) { if (matrixY != this.matrixY) { if (matrixY != -1 && getView() != null && getView().getLayout() != null && (matrixY < -1 || matrixY >= getView().getLayout().getMatrixHeight())) throw new IllegalArgumentException( String.format("Matrix Y of %d is greater than the matrix height of %d", matrixY, getView().getLayout().getMatrixHeight())); this.matrixY = matrixY; fireChanged(); } } @Override public String toString() { return "AbstractMatrixIO [hashCode=" + hashCode() + ",clazz=" + getClass() + ",matrixX=" + matrixX + ", matrixY=" + matrixY + ", getLabel()=" + getLabel() + ", getWidth()=" + getX() + ",y=" + getY() + "]"; } @Override public MatrixCell getMatrixCell() { DeviceView view = getView(); if (view == null) return null; return (MatrixCell) view.getLayout().getViews().get(ViewPosition.MATRIX).getElement(ComponentType.MATRIX_CELL, getMatrixX(), getMatrixY()); } }
2,405
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Accessory.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/layouts/Accessory.java
package uk.co.bithatch.snake.lib.layouts; public class Accessory extends AbstractIO { public enum AccessoryType { PROFILES; } private AccessoryType type = AccessoryType.PROFILES; public Accessory() { super(); } public Accessory(DeviceView view) { super(view); } public Accessory(Accessory key) { super(key); type = key.type; } public AccessoryType getAccessory() { return type; } public void setAccessory(AccessoryType type) { this.type = type; fireChanged(); } @Override public Object clone() throws CloneNotSupportedException { return new Accessory(this); } @Override public String getDefaultLabel() { return type == null ? getClass().getSimpleName() : toName(type.name()); } }
730
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
DeviceLayout.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/layouts/DeviceLayout.java
package uk.co.bithatch.snake.lib.layouts; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import uk.co.bithatch.linuxio.EventCode; import uk.co.bithatch.snake.lib.Capability; import uk.co.bithatch.snake.lib.Device; import uk.co.bithatch.snake.lib.DeviceType; import uk.co.bithatch.snake.lib.Region; import uk.co.bithatch.snake.lib.Region.Name; import uk.co.bithatch.snake.lib.layouts.Accessory.AccessoryType; public class DeviceLayout implements uk.co.bithatch.snake.lib.layouts.DeviceView.Listener { public interface Listener { void layoutChanged(DeviceLayout layout, DeviceView view); void viewRemoved(DeviceLayout layout, DeviceView view); void viewChanged(DeviceLayout layout, DeviceView view); void viewElementAdded(DeviceLayout layout, DeviceView view, IO element); void viewElementChanged(DeviceLayout layout, DeviceView view, IO element); void viewElementRemoved(DeviceLayout layout, DeviceView view, IO element); void viewAdded(DeviceLayout layout, DeviceView view); } private Map<ViewPosition, DeviceView> views = Collections.synchronizedMap(new LinkedHashMap<>()); private String name; private int matrixWidth; private int matrixHeight; private boolean readOnly; private URL base; private DeviceType deviceType = DeviceType.UNRECOGNISED; private List<Listener> listeners = new ArrayList<>(); private Map<String, Object> clientProperties = Collections.synchronizedMap(new HashMap<>()); public DeviceLayout() { } public DeviceLayout(DeviceLayout layout) { this.name = layout.name; this.matrixHeight = layout.matrixHeight; this.matrixWidth = layout.matrixWidth; this.readOnly = layout.readOnly; try { this.base = layout.base == null ? null : new URL(layout.base.toExternalForm()); } catch (MalformedURLException e) { throw new IllegalStateException(e); } this.deviceType = layout.deviceType; for (Map.Entry<ViewPosition, DeviceView> en : layout.views.entrySet()) { DeviceView view = new DeviceView(en.getValue(), this); view.addListener(this); views.put(en.getKey(), view); } } public DeviceLayout(Device device) { this.name = device.getName(); this.deviceType = device.getType(); if (device.getCapabilities().contains(Capability.MATRIX)) { this.matrixHeight = device.getMatrixSize()[0]; this.matrixWidth = device.getMatrixSize()[1]; } } @SuppressWarnings("unchecked") public DeviceLayout(URL metaData, JsonObject sequenceJson) { setBase(getParent(metaData)); setName(sequenceJson.has("name") ? sequenceJson.get("name").getAsString() : getNameFromArchive(metaData)); setMatrixHeight(sequenceJson.get("matrixHeight").getAsInt()); setMatrixWidth(sequenceJson.get("matrixWidth").getAsInt()); if (sequenceJson.has("clientProperties")) { clientProperties .putAll((Map<String, Object>) new Gson().fromJson(sequenceJson.get("clientProperties"), Map.class)); } setDeviceType(DeviceType.valueOf(sequenceJson.get("deviceType").getAsString())); JsonArray frames = sequenceJson.get("views").getAsJsonArray(); for (JsonElement viewElement : frames) { JsonObject viewObject = viewElement.getAsJsonObject(); /* View */ DeviceView view = new DeviceView(); view.setLayout(this); view.setDesaturateImage( viewObject.has("desaturateImage") ? viewObject.get("desaturateImage").getAsBoolean() : false); view.setImageOpacity(viewObject.has("imageOpacity") ? viewObject.get("imageOpacity").getAsFloat() : 1); view.setImageScale(viewObject.has("imageScale") ? viewObject.get("imageScale").getAsFloat() : 1); view.setImageUri(viewObject.has("imageUri") ? viewObject.get("imageUri").getAsString() : null); view.setPosition(ViewPosition.valueOf(viewObject.get("position").getAsString())); /* Elements */ JsonArray elements = viewObject.get("elements").getAsJsonArray(); for (JsonElement elementRow : elements) { JsonObject elementObject = elementRow.getAsJsonObject(); ComponentType viewType = ComponentType.valueOf(elementObject.get("type").getAsString()); IO element = null; switch (viewType) { case LED: LED led = new LED(view); configureMatrixIO(elementObject, led); element = led; break; case KEY: Key key = new Key(view); if (elementObject.has("eventCode")) { key.setEventCode(EventCode.valueOf(elementObject.get("eventCode").getAsString())); } if (elementObject.has("legacyKey")) { key.setLegacyKey( uk.co.bithatch.snake.lib.Key.valueOf(elementObject.get("legacyKey").getAsString())); } configureMatrixIO(elementObject, key); element = key; break; case MATRIX_CELL: MatrixCell matrixCell = new MatrixCell(view); configureMatrixIO(elementObject, matrixCell); matrixCell.setRegion( elementObject.has("region") ? Region.Name.valueOf(elementObject.get("region").getAsString()) : null); element = matrixCell; break; case AREA: Area area = new Area(view); area.setRegion( elementObject.has("region") ? Region.Name.valueOf(elementObject.get("region").getAsString()) : null); element = area; break; case ACCESSORY: Accessory accesory = new Accessory(view); accesory.setAccessory(elementObject.has("accessory") ? AccessoryType.valueOf(elementObject.get("accessory").getAsString()) : null); element = accesory; break; default: throw new UnsupportedOperationException(); } element.setLabel(elementObject.has("label") ? elementObject.get("label").getAsString() : null); element.setX(elementObject.has("x") ? elementObject.get("x").getAsFloat() : 0); element.setY(elementObject.has("y") ? elementObject.get("y").getAsFloat() : 0); view.addElement(element); } addView(view); } } protected String getNameFromArchive(URL url) { if (url == null) return null; else if (url.getPath() == null) return url.toExternalForm(); else { String path = url.getPath(); int idx = path.lastIndexOf('/'); if (idx != -1) { path = path.substring(idx + 1); } idx = path.lastIndexOf('.'); if (idx != -1) { path = path.substring(0, idx); } try { return URLDecoder.decode(path, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } } protected void configureMatrixIO(JsonObject elementObject, MatrixIO led) { if (elementObject.has("matrixX") || elementObject.has("matrixY")) { led.setMatrixX(elementObject.has("matrixX") ? elementObject.get("matrixX").getAsInt() : 0); led.setMatrixY(elementObject.has("matrixY") ? elementObject.get("matrixY").getAsInt() : 0); } else { led.setMatrixXY(null); } } public Map<String, Object> getClientProperties() { return clientProperties; } public void addListener(Listener listener) { listeners.add(listener); } public void removeListener(Listener listener) { listeners.remove(listener); } public DeviceType getDeviceType() { return deviceType; } public void setDeviceType(DeviceType deviceType) { this.deviceType = deviceType; fireChanged(null); } public boolean isReadOnly() { return readOnly; } public void setReadOnly(boolean readOnly) { this.readOnly = readOnly; fireChanged(null); } public Map<ViewPosition, DeviceView> getViews() { return views; } public void addView(DeviceView view) { synchronized (views) { view.setLayout(this); view.addListener(this); views.put(view.getPosition(), view); } fireViewAdded(view); } public String getName() { return name; } public void setName(String name) { this.name = name; fireChanged(null); } public int getMatrixWidth() { return matrixWidth; } public void setMatrixWidth(int matrixWidth) { this.matrixWidth = matrixWidth; fireChanged(null); } public int getMatrixHeight() { return matrixHeight; } public void setMatrixHeight(int matrixHeight) { this.matrixHeight = matrixHeight; fireChanged(null); } public void removeView(ViewPosition position) { DeviceView view = views.remove(position); if (view != null) { view.removeListener(this); fireViewRemoved(view); } } public void setBase(URL base) { this.base = base; fireChanged(null); } public URL getBase() { return base; } void fireChanged(DeviceView view) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).layoutChanged(this, view); } void fireViewAdded(DeviceView view) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).viewAdded(this, view); } void fireViewChanged(DeviceView view) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).viewChanged(this, view); } void fireViewElementAdded(DeviceView view, IO element) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).viewElementAdded(this, view, element); } void fireViewElementChanged(DeviceView view, IO element) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).viewElementChanged(this, view, element); } void fireViewElementRemoved(DeviceView view, IO element) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).viewElementRemoved(this, view, element); } void fireViewRemoved(DeviceView view) { for (int i = listeners.size() - 1; i >= 0; i--) listeners.get(i).viewRemoved(this, view); } @Override public void viewChanged(DeviceView view) { fireViewChanged(view); } @Override public String toString() { return "DeviceLayout [views=" + views + ", name=" + name + ", matrixWidth=" + matrixWidth + ", matrixHeight=" + matrixHeight + ", readOnly=" + readOnly + ", base=" + base + ", deviceType=" + deviceType + "]"; } @Override public void elementAdded(DeviceView view, IO element) { fireViewElementAdded(view, element); } @Override public void elementRemoved(DeviceView view, IO element) { fireViewElementRemoved(view, element); } @Override public void elementChanged(DeviceView view, IO element) { fireViewElementChanged(view, element); } public void setViews(List<DeviceView> newViews) { synchronized (views) { views.clear(); for (DeviceView v : newViews) views.put(v.getPosition(), v); } fireChanged(null); } public DeviceView getViewThatHas(ComponentType area) { synchronized (views) { for (Map.Entry<ViewPosition, DeviceView> en : views.entrySet()) { for (IO el : en.getValue().getElements()) { if (ComponentType.fromClass(el.getClass()) == area) { return en.getValue(); } } } } return null; } public List<DeviceView> getViewsThatHave(ComponentType area) { List<DeviceView> v = new ArrayList<>(); synchronized (views) { for (Map.Entry<ViewPosition, DeviceView> en : views.entrySet()) { for (IO el : en.getValue().getElements()) { if (ComponentType.fromClass(el.getClass()) == area) { v.add(en.getValue()); break; } } } } return v; } void updatePosition(DeviceView deviceView) { synchronized (views) { Map<ViewPosition, DeviceView> m = new LinkedHashMap<>(); for (DeviceView v : views.values()) { m.put(v.getPosition(), v); } views.clear(); views.putAll(m); } } public Set<EventCode> getSupportedInputEvents() { Set<EventCode> EventCodes = new LinkedHashSet<>(); synchronized (views) { for (DeviceView v : views.values()) { for (IO el : v.getElements()) { if (el instanceof Key) { Key k = (Key) el; if (k.getEventCode() != null) EventCodes.add(k.getEventCode()); } } } } return EventCodes; } public Set<uk.co.bithatch.snake.lib.Key> getSupportedLegacyKeys() { Set<uk.co.bithatch.snake.lib.Key> EventCodes = new LinkedHashSet<>(); synchronized (views) { for (DeviceView v : views.values()) { for (IO el : v.getElements()) { if (el instanceof Key) { Key k = (Key) el; if (k.getLegacyKey() != null) EventCodes.add(k.getLegacyKey()); } } } } return EventCodes; } public void store(JsonObject layoutObject) { layoutObject.addProperty("matrixHeight", getMatrixHeight()); layoutObject.addProperty("matrixWidth", getMatrixWidth()); layoutObject.addProperty("deviceType", getDeviceType().name()); if (clientProperties.size() > 0) { layoutObject.add("clientProperties", new Gson().toJsonTree(clientProperties)); } JsonArray frameInfo = new JsonArray(); for (DeviceView deviceView : getViews().values()) { JsonObject viewObject = new JsonObject(); viewObject.addProperty("desaturateImage", deviceView.isDesaturateImage()); viewObject.addProperty("imageOpacity", deviceView.getImageOpacity()); if (deviceView.getImageUri() != null) viewObject.addProperty("imageUri", deviceView.getImageUri()); viewObject.addProperty("imageScale", deviceView.getImageScale()); viewObject.addProperty("position", deviceView.getPosition().name()); JsonArray elementsArray = new JsonArray(); for (IO element : deviceView.getElements()) { JsonObject elementObject = new JsonObject(); elementObject.addProperty("type", ComponentType.fromClass(element.getClass()).name()); elementObject.addProperty("x", element.getX()); elementObject.addProperty("y", element.getY()); elementObject.addProperty("label", element.getLabel()); if (element instanceof Area) { Name region = ((Area) element).getRegion(); if (region != null) elementObject.addProperty("region", region.name()); } if (element instanceof Accessory) { AccessoryType type = ((Accessory) element).getAccessory(); if (type != null) elementObject.addProperty("accessory", type.name()); } if (element instanceof MatrixCell) { Name region = ((MatrixCell) element).getRegion(); if (region != null) elementObject.addProperty("region", region.name()); } if (element instanceof Key && ((Key) element).getEventCode() != null) { elementObject.addProperty("eventCode", ((Key) element).getEventCode().name()); } if (element instanceof Key && ((Key) element).getLegacyKey() != null) { elementObject.addProperty("legacyKey", ((Key) element).getLegacyKey().name()); } if (element instanceof MatrixIO && ((MatrixIO) element).isMatrixLED()) { elementObject.addProperty("matrixX", ((MatrixIO) element).getMatrixX()); elementObject.addProperty("matrixY", ((MatrixIO) element).getMatrixY()); } elementsArray.add(elementObject); } viewObject.add("elements", elementsArray); frameInfo.add(viewObject); } layoutObject.add("views", frameInfo); } @SuppressWarnings("unchecked") public <T> T getClientProperty(String key) { synchronized (clientProperties) { if (!clientProperties.containsKey(key)) { throw new IllegalArgumentException("No such property."); } return (T) clientProperties.get(key); } } @SuppressWarnings("unchecked") public <T> T getClientProperty(String key, T defaultValue) { synchronized (clientProperties) { return clientProperties.containsKey(key) ? (T) clientProperties.get(key) : defaultValue; } } private static URL getParent(URL url) { try { String urlPath = url.toExternalForm(); int idx = urlPath.lastIndexOf('!'); if (idx == -1) { URI uri = url.toURI(); return (uri.getPath().endsWith("/") ? uri.resolve("..") : uri.resolve(".")).toURL(); } else { idx = urlPath.lastIndexOf('/'); return new URL(urlPath.substring(0, idx)); } } catch (MalformedURLException | URISyntaxException e) { throw new IllegalStateException("Failed to get parent URL.", e); } } }
16,095
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Wave.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/effects/Wave.java
package uk.co.bithatch.snake.lib.effects; public class Wave extends Effect { public enum Direction { BACKWARD, FORWARD } private Direction direction = Direction.FORWARD; public Wave() { } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Wave other = (Wave) obj; if (direction != other.direction) return false; return true; } public Direction getDirection() { return direction; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((direction == null) ? 0 : direction.hashCode()); return result; } public void setDirection(Direction direction) { this.direction = direction; } @Override public String toString() { return "Wave [direction=" + direction + "]"; } }
881
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Spectrum.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/effects/Spectrum.java
package uk.co.bithatch.snake.lib.effects; public class Spectrum extends Effect { public Spectrum() { } }
110
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Starlight.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/effects/Starlight.java
package uk.co.bithatch.snake.lib.effects; import java.util.Arrays; public class Starlight extends Effect { public enum Mode { DUAL, RANDOM, SINGLE } private int[] color = new int[] { 0, 255, 0 }; private int[] color1 = new int[] { 0, 255, 0 }; private int[] color2 = new int[] { 0, 0, 255 }; private Mode mode = Mode.SINGLE; private int speed = 100; public Starlight() { } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Starlight other = (Starlight) obj; if (!Arrays.equals(color, other.color)) return false; if (!Arrays.equals(color1, other.color1)) return false; if (!Arrays.equals(color2, other.color2)) return false; if (mode != other.mode) return false; if (speed != other.speed) return false; return true; } public int[] getColor() { return color; } public int[] getColor1() { return color1; } public int[] getColor2() { return color2; } public Mode getMode() { return mode; } public int getSpeed() { return speed; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(color); result = prime * result + Arrays.hashCode(color1); result = prime * result + Arrays.hashCode(color2); result = prime * result + ((mode == null) ? 0 : mode.hashCode()); result = prime * result + speed; return result; } public void setColor(int[] color) { this.color = color; } public void setColor1(int[] color1) { this.color1 = color1; } public void setColor2(int[] color2) { this.color2 = color2; } public void setMode(Mode mode) { this.mode = mode; } public void setSpeed(int speed) { this.speed = speed; } @Override public String toString() { return "Starlight [mode=" + mode + ", speed=" + speed + ", color=" + Arrays.toString(color) + ", color1=" + Arrays.toString(color1) + ", color2=" + Arrays.toString(color2) + "]"; } }
2,028
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Ripple.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/effects/Ripple.java
package uk.co.bithatch.snake.lib.effects; import java.util.Arrays; public class Ripple extends Effect { public enum Mode { RANDOM, SINGLE } private int[] color = new int[] { 0, 255, 0 }; private Mode mode = Mode.SINGLE; private double refreshRate = 100; public Ripple() { } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Ripple other = (Ripple) obj; if (!Arrays.equals(color, other.color)) return false; if (mode != other.mode) return false; if (Double.doubleToLongBits(refreshRate) != Double.doubleToLongBits(other.refreshRate)) return false; return true; } public int[] getColor() { return color; } public Mode getMode() { return mode; } public double getRefreshRate() { return refreshRate; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(color); result = prime * result + ((mode == null) ? 0 : mode.hashCode()); long temp; temp = Double.doubleToLongBits(refreshRate); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } public void setColor(int[] color) { this.color = color; } public void setMode(Mode mode) { this.mode = mode; } public void setRefreshRate(double refreshRate) { this.refreshRate = refreshRate; } @Override public String toString() { return "Ripple [mode=" + mode + ", color=" + Arrays.toString(color) + ", refreshRate=" + refreshRate + "]"; } }
1,571
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
On.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/effects/On.java
package uk.co.bithatch.snake.lib.effects; public class On extends Effect { public On() { } }
97
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Breath.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/effects/Breath.java
package uk.co.bithatch.snake.lib.effects; import java.util.Arrays; public class Breath extends Effect { public enum Mode { DUAL, RANDOM, SINGLE } private int[] color = new int[] { 0, 255, 0 }; private int[] color1 = new int[] { 0, 255, 0 }; private int[] color2 = new int[] { 0, 0, 255 }; private Mode mode = Mode.SINGLE; public Breath() { } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Breath other = (Breath) obj; if (!Arrays.equals(color, other.color)) return false; if (!Arrays.equals(color1, other.color1)) return false; if (!Arrays.equals(color2, other.color2)) return false; if (mode != other.mode) return false; return true; } public int[] getColor() { return color; } public int[] getColor1() { return color1; } public int[] getColor2() { return color2; } public Mode getMode() { return mode; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(color); result = prime * result + Arrays.hashCode(color1); result = prime * result + Arrays.hashCode(color2); result = prime * result + ((mode == null) ? 0 : mode.hashCode()); return result; } public void setColor(int[] color) { this.color = color; } public void setColor1(int[] color1) { this.color1 = color1; } public void setColor2(int[] color2) { this.color2 = color2; } public void setMode(Mode mode) { this.mode = mode; } @Override public String toString() { return "Breath [mode=" + mode + ", color=" + Arrays.toString(color) + ", color1=" + Arrays.toString(color1) + ", color2=" + Arrays.toString(color2) + "]"; } }
1,781
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z
Reactive.java
/FileExtraction/Java_unseen/bithatch_snake/snake-lib/src/main/java/uk/co/bithatch/snake/lib/effects/Reactive.java
package uk.co.bithatch.snake.lib.effects; import java.util.Arrays; public class Reactive extends Effect { private int[] color = new int[] { 0, 255, 0 }; private int speed = 100; public Reactive() { } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Reactive other = (Reactive) obj; if (!Arrays.equals(color, other.color)) return false; if (speed != other.speed) return false; return true; } public int[] getColor() { return color; } public int getSpeed() { return speed; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(color); result = prime * result + speed; return result; } public void setColor(int[] color) { this.color = color; } public void setSpeed(int speed) { this.speed = speed; } @Override public String toString() { return "Reactive [color=" + Arrays.toString(color) + ", speed=" + speed + "]"; } }
1,067
Java
.java
bithatch/snake
66
4
11
2020-10-17T07:55:01Z
2021-10-09T19:26:18Z