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 |
---|---|---|---|---|---|---|---|---|---|---|---|
MentionNodeRenderer.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/markdown/extension/mention/internal/MentionNodeRenderer.java | package com.fastaccess.provider.markdown.extension.mention.internal;
import com.fastaccess.provider.markdown.extension.mention.Mention;
import org.commonmark.node.Node;
import org.commonmark.renderer.NodeRenderer;
import org.commonmark.renderer.html.HtmlNodeRendererContext;
import org.commonmark.renderer.html.HtmlWriter;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
public class MentionNodeRenderer implements NodeRenderer {
private final HtmlNodeRendererContext context;
private final HtmlWriter html;
public MentionNodeRenderer(HtmlNodeRendererContext context) {
this.context = context;
this.html = context.getWriter();
}
@Override public Set<Class<? extends Node>> getNodeTypes() {
return Collections.singleton(Mention.class);
}
@Override public void render(Node node) {
Map<String, String> attributes = context.extendAttributes(node, "mention", Collections.emptyMap());
html.tag("mention", attributes);
renderChildren(node);
html.tag("/mention");
}
private void renderChildren(Node parent) {
Node node = parent.getFirstChild();
while (node != null) {
Node next = node.getNext();
context.render(node);
node = next;
}
}
}
| 1,320 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
Fitzpatrick.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/emoji/Fitzpatrick.java | package com.fastaccess.provider.emoji;
/**
* Enum that represents the Fitzpatrick modifiers supported by the emojis.
*/
public enum Fitzpatrick {
/**
* Fitzpatrick modifier of type 1/2 (pale white/white)
*/
TYPE_1_2("\uD83C\uDFFB"),
/**
* Fitzpatrick modifier of type 3 (cream white)
*/
TYPE_3("\uD83C\uDFFC"),
/**
* Fitzpatrick modifier of type 4 (moderate brown)
*/
TYPE_4("\uD83C\uDFFD"),
/**
* Fitzpatrick modifier of type 5 (dark brown)
*/
TYPE_5("\uD83C\uDFFE"),
/**
* Fitzpatrick modifier of type 6 (black)
*/
TYPE_6("\uD83C\uDFFF");
/**
* The unicode representation of the Fitzpatrick modifier
*/
public final String unicode;
Fitzpatrick(String unicode) {
this.unicode = unicode;
}
public static Fitzpatrick fitzpatrickFromUnicode(String unicode) {
for (Fitzpatrick v : values()) {
if (v.unicode.equals(unicode)) {
return v;
}
}
return null;
}
public static Fitzpatrick fitzpatrickFromType(String type) {
try {
return Fitzpatrick.valueOf(type.toUpperCase());
} catch (IllegalArgumentException e) {
return null;
}
}
}
| 1,169 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
Emoji.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/emoji/Emoji.java | package com.fastaccess.provider.emoji;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
/**
* This class represents an emoji.<br>
* <br>
* This object is immutable so it can be used safely in a multithreaded context.
*
* @author Vincent DURMONT [[email protected]]
*/
public class Emoji {
private final String description;
private final boolean supportsFitzpatrick;
private final List<String> aliases;
private final List<String> tags;
private String unicode;
private String htmlDec;
private String htmlHex;
/**
* Constructor for the Emoji.
*
* @param description
* The description of the emoji
* @param supportsFitzpatrick
* Whether the emoji supports Fitzpatrick modifiers
* @param aliases
* the aliases for this emoji
* @param tags
* the tags associated with this emoji
* @param bytes
* the bytes that represent the emoji
*/
protected Emoji(
String description,
boolean supportsFitzpatrick,
List<String> aliases,
List<String> tags,
byte... bytes
) {
this.description = description;
this.supportsFitzpatrick = supportsFitzpatrick;
this.aliases = Collections.unmodifiableList(aliases);
this.tags = Collections.unmodifiableList(tags);
int count = 0;
try {
this.unicode = new String(bytes, "UTF-8");
int stringLength = getUnicode().length();
String[] pointCodes = new String[stringLength];
String[] pointCodesHex = new String[stringLength];
for (int offset = 0; offset < stringLength; ) {
final int codePoint = getUnicode().codePointAt(offset);
pointCodes[count] = String.format(Locale.getDefault(), "&#%d;", codePoint);
pointCodesHex[count++] = String.format("&#x%x;", codePoint);
offset += Character.charCount(codePoint);
}
this.htmlDec = stringJoin(pointCodes, count);
this.htmlHex = stringJoin(pointCodesHex, count);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
* Method to replace String.join, since it was only introduced in java8
*
* @param array
* the array to be concatenated
* @return concatenated String
*/
private String stringJoin(String[] array, int count) {
String joined = "";
for (int i = 0; i < count; i++)
joined += array[i];
return joined;
}
/**
* Returns the description of the emoji
*
* @return the description
*/
public String getDescription() {
return this.description;
}
/**
* Returns wether the emoji supports the Fitzpatrick modifiers or not
*
* @return true if the emoji supports the Fitzpatrick modifiers
*/
public boolean supportsFitzpatrick() {
return this.supportsFitzpatrick;
}
/**
* Returns the aliases of the emoji
*
* @return the aliases (unmodifiable)
*/
public List<String> getAliases() {
return this.aliases;
}
/**
* Returns the tags of the emoji
*
* @return the tags (unmodifiable)
*/
public List<String> getTags() {
return this.tags;
}
/**
* Returns the unicode representation of the emoji
*
* @return the unicode representation
*/
public String getUnicode() {
return this.unicode;
}
/**
* Returns the unicode representation of the emoji associated with the
* provided Fitzpatrick modifier.<br>
* If the modifier is null, then the result is similar to
* {@link Emoji#getUnicode()}
*
* @param fitzpatrick
* the fitzpatrick modifier or null
* @return the unicode representation
* @throws UnsupportedOperationException
* if the emoji doesn't support the Fitzpatrick modifiers
*/
public String getUnicode(Fitzpatrick fitzpatrick) {
if (!this.supportsFitzpatrick()) {
throw new UnsupportedOperationException(
"Cannot get the unicode with a fitzpatrick modifier, " +
"the emoji doesn't support fitzpatrick."
);
} else if (fitzpatrick == null) {
return this.getUnicode();
}
return this.getUnicode() + fitzpatrick.unicode;
}
/**
* Returns the HTML decimal representation of the emoji
*
* @return the HTML decimal representation
*/
public String getHtmlDecimal() {
return this.htmlDec;
}
/**
* @return the HTML hexadecimal representation
* @deprecated identical to {@link #getHtmlHexadecimal()} for backwards-compatibility. Use that instead.
*/
public String getHtmlHexidecimal() {
return this.getHtmlHexadecimal();
}
/**
* Returns the HTML hexadecimal representation of the emoji
*
* @return the HTML hexadecimal representation
*/
public String getHtmlHexadecimal() {
return this.htmlHex;
}
@Override
public boolean equals(Object other) {
return !(other == null || !(other instanceof Emoji)) &&
((Emoji) other).getUnicode().equals(getUnicode());
}
@Override
public int hashCode() {
return unicode.hashCode();
}
/**
* Returns the String representation of the Emoji object.<br>
* <br>
* Example:<br>
* <code>Emoji {
* description='smiling face with open mouth and smiling eyes',
* supportsFitzpatrick=false,
* aliases=[smile],
* tags=[happy, joy, pleased],
* unicode='😄',
* htmlDec='&#128516;',
* htmlHex='&#x1f604;'
* }</code>
*
* @return the string representation
*/
@Override
public String toString() {
return "Emoji{" +
"description='" + description + '\'' +
", supportsFitzpatrick=" + supportsFitzpatrick +
", aliases=" + aliases +
", tags=" + tags +
", unicode='" + unicode + '\'' +
", htmlDec='" + htmlDec + '\'' +
", htmlHex='" + htmlHex + '\'' +
'}';
}
}
| 6,457 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
EmojiParser.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/emoji/EmojiParser.java | package com.fastaccess.provider.emoji;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Provides methods to parse strings with emojis.
*
* @author Vincent DURMONT [[email protected]]
*/
public class EmojiParser {
private static final Pattern ALIAS_CANDIDATE_PATTERN =
Pattern.compile("(?<=:)\\+?(\\w|\\||\\-)+(?=:)");
/**
* See {@link #parseToAliases(String, FitzpatrickAction)} with the action
* "PARSE"
*
* @param input the string to parse
*
* @return the string with the emojis replaced by their alias.
*/
public static String parseToAliases(String input) {
return parseToAliases(input, FitzpatrickAction.PARSE);
}
/**
* Replaces the emoji's unicode occurrences by one of their alias
* (between 2 ':').<br>
* Example: <code>😄</code> will be replaced by <code>:smile:</code><br>
* <br>
* When a fitzpatrick modifier is present with a PARSE action, a "|" will be
* appendend to the alias, with the fitzpatrick type.<br>
* Example: <code>👦🏿</code> will be replaced by
* <code>:boy|type_6:</code><br>
* The fitzpatrick types are: type_1_2, type_3, type_4, type_5, type_6<br>
* <br>
* When a fitzpatrick modifier is present with a REMOVE action, the modifier
* will be deleted.<br>
* Example: <code>👦🏿</code> will be replaced by <code>:boy:</code><br>
* <br>
* When a fitzpatrick modifier is present with a IGNORE action, the modifier
* will be ignored.<br>
* Example: <code>👦🏿</code> will be replaced by <code>:boy:🏿</code><br>
*
* @param input the string to parse
* @param fitzpatrickAction the action to apply for the fitzpatrick modifiers
*
* @return the string with the emojis replaced by their alias.
*/
private static String parseToAliases(
String input,
final FitzpatrickAction fitzpatrickAction
) {
EmojiTransformer emojiTransformer = unicodeCandidate -> {
switch (fitzpatrickAction) {
default:
case PARSE:
if (unicodeCandidate.hasFitzpatrick()) {
return ":" +
unicodeCandidate.getEmoji().getAliases().get(0) +
"|" +
unicodeCandidate.getFitzpatrickType() +
":";
}
case REMOVE:
return ":" +
unicodeCandidate.getEmoji().getAliases().get(0) +
":";
case IGNORE:
return ":" +
unicodeCandidate.getEmoji().getAliases().get(0) +
":" +
unicodeCandidate.getFitzpatrickUnicode();
}
};
return parseFromUnicode(input, emojiTransformer);
}
/**
* Replaces the emoji's aliases (between 2 ':') occurrences and the html
* representations by their unicode.<br>
* Examples:<br>
* <code>:smile:</code> will be replaced by <code>😄</code><br>
* <code>&#128516;</code> will be replaced by <code>😄</code><br>
* <code>:boy|type_6:</code> will be replaced by <code>👦🏿</code>
*
* @param input the string to parse
*
* @return the string with the aliases and html representations replaced by
* their unicode.
*/
public static String parseToUnicode(String input) {
// Get all the potential aliases
List<AliasCandidate> candidates = getAliasCandidates(input);
// Replace the aliases by their unicode
String result = input;
for (AliasCandidate candidate : candidates) {
Emoji emoji = EmojiManager.getForAlias(candidate.alias);
if (emoji != null) {
if (
emoji.supportsFitzpatrick() ||
(!emoji.supportsFitzpatrick() && candidate.fitzpatrick == null)
) {
String replacement = emoji.getUnicode();
if (candidate.fitzpatrick != null) {
replacement += candidate.fitzpatrick.unicode;
}
result = result.replace(
":" + candidate.fullString + ":",
replacement
);
}
}
}
// Replace the html
for (Emoji emoji : EmojiManager.getAll()) {
result = result.replace(emoji.getHtmlHexadecimal(), emoji.getUnicode());
result = result.replace(emoji.getHtmlDecimal(), emoji.getUnicode());
}
return result;
}
private static List<AliasCandidate> getAliasCandidates(String input) {
List<AliasCandidate> candidates = new ArrayList<AliasCandidate>();
Matcher matcher = ALIAS_CANDIDATE_PATTERN.matcher(input);
matcher = matcher.useTransparentBounds(true);
while (matcher.find()) {
String match = matcher.group();
if (!match.contains("|")) {
candidates.add(new AliasCandidate(match, match, null));
} else {
String[] splitted = match.split("\\|");
if (splitted.length == 2 || splitted.length > 2) {
candidates.add(new AliasCandidate(match, splitted[0], splitted[1]));
} else {
candidates.add(new AliasCandidate(match, match, null));
}
}
}
return candidates;
}
/**
* See {@link #parseToHtmlDecimal(String, FitzpatrickAction)} with the action
* "PARSE"
*
* @param input the string to parse
*
* @return the string with the emojis replaced by their html decimal
* representation.
*/
public static String parseToHtmlDecimal(String input) {
return parseToHtmlDecimal(input, FitzpatrickAction.PARSE);
}
/**
* Replaces the emoji's unicode occurrences by their html representation.<br>
* Example: <code>😄</code> will be replaced by <code>&#128516;</code><br>
* <br>
* When a fitzpatrick modifier is present with a PARSE or REMOVE action, the
* modifier will be deleted from the string.<br>
* Example: <code>👦🏿</code> will be replaced by
* <code>&#128102;</code><br>
* <br>
* When a fitzpatrick modifier is present with a IGNORE action, the modifier
* will be ignored and will remain in the string.<br>
* Example: <code>👦🏿</code> will be replaced by
* <code>&#128102;🏿</code>
*
* @param input the string to parse
* @param fitzpatrickAction the action to apply for the fitzpatrick modifiers
*
* @return the string with the emojis replaced by their html decimal
* representation.
*/
private static String parseToHtmlDecimal(
String input,
final FitzpatrickAction fitzpatrickAction
) {
EmojiTransformer emojiTransformer = unicodeCandidate -> {
switch (fitzpatrickAction) {
default:
case PARSE:
case REMOVE:
return unicodeCandidate.getEmoji().getHtmlDecimal();
case IGNORE:
return unicodeCandidate.getEmoji().getHtmlDecimal() +
unicodeCandidate.getFitzpatrickUnicode();
}
};
return parseFromUnicode(input, emojiTransformer);
}
/**
* See {@link #parseToHtmlHexadecimal(String, FitzpatrickAction)} with the
* action "PARSE"
*
* @param input the string to parse
*
* @return the string with the emojis replaced by their html hex
* representation.
*/
public static String parseToHtmlHexadecimal(String input) {
return parseToHtmlHexadecimal(input, FitzpatrickAction.PARSE);
}
/**
* Replaces the emoji's unicode occurrences by their html hex
* representation.<br>
* Example: <code>👦</code> will be replaced by <code>&#x1f466;</code><br>
* <br>
* When a fitzpatrick modifier is present with a PARSE or REMOVE action, the
* modifier will be deleted.<br>
* Example: <code>👦🏿</code> will be replaced by
* <code>&#x1f466;</code><br>
* <br>
* When a fitzpatrick modifier is present with a IGNORE action, the modifier
* will be ignored and will remain in the string.<br>
* Example: <code>👦🏿</code> will be replaced by
* <code>&#x1f466;🏿</code>
*
* @param input the string to parse
* @param fitzpatrickAction the action to apply for the fitzpatrick modifiers
*
* @return the string with the emojis replaced by their html hex
* representation.
*/
private static String parseToHtmlHexadecimal(
String input,
final FitzpatrickAction fitzpatrickAction
) {
EmojiTransformer emojiTransformer = unicodeCandidate -> {
switch (fitzpatrickAction) {
default:
case PARSE:
case REMOVE:
return unicodeCandidate.getEmoji().getHtmlHexadecimal();
case IGNORE:
return unicodeCandidate.getEmoji().getHtmlHexadecimal() +
unicodeCandidate.getFitzpatrickUnicode();
}
};
return parseFromUnicode(input, emojiTransformer);
}
/**
* Removes all emojis from a String
*
* @param str the string to process
*
* @return the string without any emoji
*/
public static String removeAllEmojis(String str) {
EmojiTransformer emojiTransformer = unicodeCandidate -> "";
return parseFromUnicode(str, emojiTransformer);
}
/**
* Removes a set of emojis from a String
*
* @param str the string to process
* @param emojisToRemove the emojis to remove from this string
*
* @return the string without the emojis that were removed
*/
public static String removeEmojis(
String str,
final Collection<Emoji> emojisToRemove
) {
EmojiTransformer emojiTransformer = unicodeCandidate -> {
if (!emojisToRemove.contains(unicodeCandidate.getEmoji())) {
return unicodeCandidate.getEmoji().getUnicode() +
unicodeCandidate.getFitzpatrickUnicode();
}
return "";
};
return parseFromUnicode(str, emojiTransformer);
}
/**
* Removes all the emojis in a String except a provided set
*
* @param str the string to process
* @param emojisToKeep the emojis to keep in this string
*
* @return the string without the emojis that were removed
*/
public static String removeAllEmojisExcept(
String str,
final Collection<Emoji> emojisToKeep
) {
EmojiTransformer emojiTransformer = unicodeCandidate -> {
if (emojisToKeep.contains(unicodeCandidate.getEmoji())) {
return unicodeCandidate.getEmoji().getUnicode() +
unicodeCandidate.getFitzpatrickUnicode();
}
return "";
};
return parseFromUnicode(str, emojiTransformer);
}
/**
* Detects all unicode emojis in input string and replaces them with the
* return value of transformer.transform()
*
* @param input the string to process
* @param transformer emoji transformer to apply to each emoji
*
* @return input string with all emojis transformed
*/
private static String parseFromUnicode(
String input,
EmojiTransformer transformer
) {
int prev = 0;
StringBuilder sb = new StringBuilder();
List<UnicodeCandidate> replacements = getUnicodeCandidates(input);
for (UnicodeCandidate candidate : replacements) {
sb.append(input.substring(prev, candidate.getEmojiStartIndex()));
sb.append(transformer.transform(candidate));
prev = candidate.getFitzpatrickEndIndex();
}
return sb.append(input.substring(prev)).toString();
}
public static List<String> extractEmojis(String input) {
List<UnicodeCandidate> emojis = getUnicodeCandidates(input);
List<String> result = new ArrayList<String>();
for (UnicodeCandidate emoji : emojis) {
result.add(emoji.getEmoji().getUnicode());
}
return result;
}
/**
* Generates a list UnicodeCandidates found in input string. A
* UnicodeCandidate is created for every unicode emoticon found in input
* string, additionally if Fitzpatrick modifier follows the emoji, it is
* included in UnicodeCandidate. Finally, it contains start and end index of
* unicode emoji itself (WITHOUT Fitzpatrick modifier whether it is there or
* not!).
*
* @param input String to find all unicode emojis in
* @return List of UnicodeCandidates for each unicode emote in text
*/
private static List<UnicodeCandidate> getUnicodeCandidates(String input) {
char[] inputCharArray = input.toCharArray();
List<UnicodeCandidate> candidates = new ArrayList<UnicodeCandidate>();
for (int i = 0; i < input.length(); i++) {
int emojiEnd = getEmojiEndPos(inputCharArray, i);
if (emojiEnd != -1) {
Emoji emoji = EmojiManager.getByUnicode(input.substring(i, emojiEnd));
String fitzpatrickString = (emojiEnd + 2 <= input.length()) ?
new String(inputCharArray, emojiEnd, 2) :
null;
UnicodeCandidate candidate = new UnicodeCandidate(
emoji,
fitzpatrickString,
i
);
candidates.add(candidate);
i = candidate.getFitzpatrickEndIndex() - 1;
}
}
return candidates;
}
/**
* Returns end index of a unicode emoji if it is found in text starting at
* index startPos, -1 if not found.
* This returns the longest matching emoji, for example, in
* "\uD83D\uDC68\u200D\uD83D\uDC69\u200D\uD83D\uDC66"
* it will find alias:family_man_woman_boy, NOT alias:man
*
* @param text the current text where we are looking for an emoji
* @param startPos the position in the text where we should start looking for
* an emoji end
*
* @return the end index of the unicode emoji starting at startPos. -1 if not
* found
*/
private static int getEmojiEndPos(char[] text, int startPos) {
int best = -1;
for (int j = startPos + 1; j <= text.length; j++) {
EmojiTrie.Matches status = EmojiManager.isEmoji(Arrays.copyOfRange(
text,
startPos,
j
));
if (status.exactMatch()) {
best = j;
} else if (status.impossibleMatch()) {
return best;
}
}
return best;
}
public static class UnicodeCandidate {
private final Emoji emoji;
private final Fitzpatrick fitzpatrick;
private final int startIndex;
private UnicodeCandidate(Emoji emoji, String fitzpatrick, int startIndex) {
this.emoji = emoji;
this.fitzpatrick = Fitzpatrick.fitzpatrickFromUnicode(fitzpatrick);
this.startIndex = startIndex;
}
public Emoji getEmoji() {
return emoji;
}
public boolean hasFitzpatrick() {
return getFitzpatrick() != null;
}
public Fitzpatrick getFitzpatrick() {
return fitzpatrick;
}
public String getFitzpatrickType() {
return hasFitzpatrick() ? fitzpatrick.name().toLowerCase() : "";
}
public String getFitzpatrickUnicode() {
return hasFitzpatrick() ? fitzpatrick.unicode : "";
}
public int getEmojiStartIndex() {
return startIndex;
}
public int getEmojiEndIndex() {
return startIndex + emoji.getUnicode().length();
}
public int getFitzpatrickEndIndex() {
return getEmojiEndIndex() + (fitzpatrick != null ? 2 : 0);
}
}
static class AliasCandidate {
public final String fullString;
public final String alias;
public final Fitzpatrick fitzpatrick;
private AliasCandidate(
String fullString,
String alias,
String fitzpatrickString
) {
this.fullString = fullString;
this.alias = alias;
if (fitzpatrickString == null) {
this.fitzpatrick = null;
} else {
this.fitzpatrick = Fitzpatrick.fitzpatrickFromType(fitzpatrickString);
}
}
}
/**
* Enum used to indicate what should be done when a Fitzpatrick modifier is
* found.
*/
public enum FitzpatrickAction {
/**
* Tries to match the Fitzpatrick modifier with the previous emoji
*/
PARSE,
/**
* Removes the Fitzpatrick modifier from the string
*/
REMOVE,
/**
* Ignores the Fitzpatrick modifier (it will stay in the string)
*/
IGNORE
}
public interface EmojiTransformer {
String transform(UnicodeCandidate unicodeCandidate);
}
}
| 16,076 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
EmojiLoader.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/emoji/EmojiLoader.java | package com.fastaccess.provider.emoji;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Loads the emojis from a JSON database.
*
* @author Vincent DURMONT [[email protected]]
*/
class EmojiLoader {
private EmojiLoader() {}
static List<Emoji> loadEmojis(InputStream stream) throws IOException {
try {
JSONArray emojisJSON = new JSONArray(inputStreamToString(stream));
List<Emoji> emojis = new ArrayList<Emoji>(emojisJSON.length());
for (int i = 0; i < emojisJSON.length(); i++) {
Emoji emoji = buildEmojiFromJSON(emojisJSON.getJSONObject(i));
if (emoji != null) {
emojis.add(emoji);
}
}
return emojis;
} catch (Exception e) {
e.printStackTrace();
}
return Collections.emptyList();
}
private static String inputStreamToString(InputStream stream) throws IOException {
StringBuilder sb = new StringBuilder();
InputStreamReader isr = new InputStreamReader(stream, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String read;
while ((read = br.readLine()) != null) {
sb.append(read);
}
br.close();
return sb.toString();
}
private static Emoji buildEmojiFromJSON(JSONObject json) throws Exception {
if (!json.has("emoji")) {
return null;
}
byte[] bytes = json.getString("emoji").getBytes("UTF-8");
String description = null;
if (json.has("description")) {
description = json.getString("description");
}
boolean supportsFitzpatrick = false;
if (json.has("supports_fitzpatrick")) {
supportsFitzpatrick = json.getBoolean("supports_fitzpatrick");
}
List<String> aliases = jsonArrayToStringList(json.getJSONArray("aliases"));
List<String> tags = jsonArrayToStringList(json.getJSONArray("tags"));
return new Emoji(description, supportsFitzpatrick, aliases, tags, bytes);
}
private static List<String> jsonArrayToStringList(JSONArray array) {
List<String> strings = new ArrayList<String>(array.length());
try {
for (int i = 0; i < array.length(); i++) {
strings.add(array.getString(i));
}
} catch (Exception e) {
e.printStackTrace();
}
return strings;
}
}
| 2,683 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
EmojiManager.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/emoji/EmojiManager.java | package com.fastaccess.provider.emoji;
import com.fastaccess.App;
import com.fastaccess.helper.RxHelper;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;
/**
* Holds the loaded emojis and provides search functions.
*
* @author Vincent DURMONT [[email protected]]
*/
public class EmojiManager {
private static final String PATH = "emojis.json";
private static final Map<String, Emoji> EMOJIS_BY_ALIAS = new HashMap<>();
private static final Map<String, Set<Emoji>> EMOJIS_BY_TAG = new HashMap<>();
private static List<Emoji> ALL_EMOJIS;
private static EmojiTrie EMOJI_TRIE;
public static void load() {
RxHelper.safeObservable(Observable.fromCallable(() -> {
try {
InputStream stream = App.getInstance().getAssets().open(PATH);
List<Emoji> emojis = EmojiLoader.loadEmojis(stream);
ALL_EMOJIS = emojis;
for (Emoji emoji : emojis) {
for (String tag : emoji.getTags()) {
if (EMOJIS_BY_TAG.get(tag) == null) {
EMOJIS_BY_TAG.put(tag, new HashSet<>());
}
EMOJIS_BY_TAG.get(tag).add(emoji);
}
for (String alias : emoji.getAliases()) {
EMOJIS_BY_ALIAS.put(alias, emoji);
}
}
EMOJI_TRIE = new EmojiTrie(emojis);
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
return "";
})).subscribeOn(Schedulers.io()).subscribe();
}
private EmojiManager() {}
public static Set<Emoji> getForTag(String tag) {
if (tag == null) {
return null;
}
return EMOJIS_BY_TAG.get(tag);
}
public static Emoji getForAlias(String alias) {
if (alias == null) {
return null;
}
return EMOJIS_BY_ALIAS.get(trimAlias(alias));
}
private static String trimAlias(String alias) {
String result = alias;
if (result.startsWith(":")) {
result = result.substring(1, result.length());
}
if (result.endsWith(":")) {
result = result.substring(0, result.length() - 1);
}
return result;
}
public static Emoji getByUnicode(String unicode) {
if (unicode == null) {
return null;
}
return EMOJI_TRIE.getEmoji(unicode);
}
public static List<Emoji> getAll() {
return ALL_EMOJIS;
}
public static boolean isEmoji(String string) {
return string != null &&
EMOJI_TRIE.isEmoji(string.toCharArray()).exactMatch();
}
public static boolean isOnlyEmojis(String string) {
return string != null && EmojiParser.removeAllEmojis(string).isEmpty();
}
public static EmojiTrie.Matches isEmoji(char[] sequence) {
return EMOJI_TRIE.isEmoji(sequence);
}
public static Collection<String> getAllTags() {
return EMOJIS_BY_TAG.keySet();
}
}
| 3,355 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
EmojiTrie.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/emoji/EmojiTrie.java | package com.fastaccess.provider.emoji;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class EmojiTrie {
private Node root = new Node();
public EmojiTrie(Collection<Emoji> emojis) {
for (Emoji emoji : emojis) {
Node tree = root;
for (char c : emoji.getUnicode().toCharArray()) {
if (!tree.hasChild(c)) {
tree.addChild(c);
}
tree = tree.getChild(c);
}
tree.setEmoji(emoji);
}
}
/**
* Checks if sequence of chars contain an emoji.
*
* @param sequence
* Sequence of char that may contain emoji in full or partially.
* @return <li> Matches.EXACTLY if char sequence in its entirety is an emoji </li> <li> Matches.POSSIBLY if char sequence
* matches prefix of an emoji </li> <li> Matches.IMPOSSIBLE if char sequence matches no emoji or prefix of an emoji </li>
*/
public Matches isEmoji(char[] sequence) {
if (sequence == null) {
return Matches.POSSIBLY;
}
Node tree = root;
for (char c : sequence) {
if (!tree.hasChild(c)) {
return Matches.IMPOSSIBLE;
}
tree = tree.getChild(c);
}
return tree.isEndOfEmoji() ? Matches.EXACTLY : Matches.POSSIBLY;
}
/**
* Finds Emoji instance from emoji unicode
*
* @param unicode
* unicode of emoji to get
* @return Emoji instance if unicode matches and emoji, null otherwise.
*/
public Emoji getEmoji(String unicode) {
Node tree = root;
for (char c : unicode.toCharArray()) {
if (!tree.hasChild(c)) {
return null;
}
tree = tree.getChild(c);
}
return tree.getEmoji();
}
public enum Matches {
EXACTLY, POSSIBLY, IMPOSSIBLE;
public boolean exactMatch() {
return this == EXACTLY;
}
public boolean impossibleMatch() {
return this == IMPOSSIBLE;
}
public boolean possibleMatch() {
return this == POSSIBLY;
}
}
private class Node {
private Map<Character, Node> children = new HashMap<Character, Node>();
private Emoji emoji;
private void setEmoji(Emoji emoji) {
this.emoji = emoji;
}
private Emoji getEmoji() {
return emoji;
}
private boolean hasChild(char child) {
return children.containsKey(child);
}
private void addChild(char child) {
children.put(child, new Node());
}
private Node getChild(char child) {
return children.get(child);
}
private boolean isEndOfEmoji() {
return emoji != null;
}
}
}
| 2,953 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
ColorsProvider.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/colors/ColorsProvider.java | package com.fastaccess.provider.colors;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.annimon.stream.Collectors;
import com.annimon.stream.Stream;
import com.fastaccess.App;
import com.fastaccess.data.dao.LanguageColorModel;
import com.fastaccess.helper.InputHelper;
import com.fastaccess.helper.RxHelper;
import com.fastaccess.ui.widgets.color.ColorGenerator;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import io.reactivex.Observable;
/**
* Created by Kosh on 27 May 2017, 9:50 PM
*/
public class ColorsProvider {
private static List<String> POPULAR_LANG = Stream.of("Java", "Kotlin", "JavaScript", "Python", "CSS", "PHP",
"Ruby", "C++", "C", "Go", "Swift").toList();//predefined languages.
private static Map<String, LanguageColorModel> colors = new LinkedHashMap<>();
@SuppressLint("CheckResult") public static void load() {
if (colors.isEmpty()) {
RxHelper.safeObservable(Observable
.create(observableEmitter -> {
try {
Type type = new TypeToken<Map<String, LanguageColorModel>>() {}.getType();
try (InputStream stream = App.getInstance().getAssets().open("colors.json")) {
Gson gson = new Gson();
try (JsonReader reader = new JsonReader(new InputStreamReader(stream))) {
colors.putAll(gson.fromJson(reader, type));
observableEmitter.onNext("");
}
}
} catch (IOException e) {
e.printStackTrace();
observableEmitter.onError(e);
}
observableEmitter.onComplete();
}))
.subscribe(s -> {/**/}, Throwable::printStackTrace);
}
}
@NonNull public static ArrayList<String> languages() {
ArrayList<String> lang = new ArrayList<>();
lang.addAll(Stream.of(colors)
.filter(value -> value != null && !InputHelper.isEmpty(value.getKey()))
.map(Map.Entry::getKey)
.collect(Collectors.toCollection(ArrayList::new)));
lang.add(0, "All");
lang.addAll(1, POPULAR_LANG);
return lang;
}
@Nullable public static LanguageColorModel getColor(@NonNull String lang) {
return colors.get(lang);
}
@ColorInt public static int getColorAsColor(@NonNull String lang, @NonNull Context context) {
LanguageColorModel color = getColor(lang);
int langColor = ColorGenerator.getColor(context, lang);
if (color != null && !InputHelper.isEmpty(color.getColor())) {
try {langColor = Color.parseColor(color.getColor());} catch (Exception ignored) {}
}
return langColor;
}
}
| 3,414 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
NotificationSchedulerJobTask.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/tasks/notification/NotificationSchedulerJobTask.java |
package com.fastaccess.provider.tasks.notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import com.annimon.stream.Stream;
import com.fastaccess.R;
import com.fastaccess.data.dao.model.Comment;
import com.fastaccess.data.dao.model.Login;
import com.fastaccess.data.dao.model.Notification;
import com.fastaccess.data.dao.model.NotificationQueue;
import com.fastaccess.helper.AppHelper;
import com.fastaccess.helper.InputHelper;
import com.fastaccess.helper.ParseDateFormat;
import com.fastaccess.helper.PrefGetter;
import com.fastaccess.provider.markdown.MarkDownProvider;
import com.fastaccess.provider.rest.RestProvider;
import com.fastaccess.ui.modules.notification.NotificationActivity;
import com.firebase.jobdispatcher.Constraint;
import com.firebase.jobdispatcher.FirebaseJobDispatcher;
import com.firebase.jobdispatcher.GooglePlayDriver;
import com.firebase.jobdispatcher.Job;
import com.firebase.jobdispatcher.JobParameters;
import com.firebase.jobdispatcher.JobService;
import com.firebase.jobdispatcher.Lifetime;
import com.firebase.jobdispatcher.RetryStrategy;
import com.firebase.jobdispatcher.Trigger;
import java.util.List;
import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;
/**
* Created by Kosh on 19 Feb 2017, 6:32 PM
*/
public class NotificationSchedulerJobTask extends JobService {
private final static String JOB_ID = "fasthub_notification";
private final static String SINGLE_JOB_ID = "single_fasthub_notification";
private final static int THIRTY_MINUTES = 30 * 60;
private static final String NOTIFICATION_GROUP_ID = "FastHub";
@Override public boolean onStartJob(JobParameters job) {
if (!SINGLE_JOB_ID.equalsIgnoreCase(job.getTag())) {
if (PrefGetter.getNotificationTaskDuration() == -1) {
scheduleJob(this, -1, false);
finishJob(job);
return true;
}
}
Login login = null;
try {
login = Login.getUser();
} catch (Exception ignored) {}
if (login != null) {
RestProvider.getNotificationService(PrefGetter.isEnterprise())
.getNotifications(ParseDateFormat.getLastWeekDate())
.subscribeOn(Schedulers.io())
.subscribe(item -> {
AppHelper.cancelAllNotifications(getApplicationContext());
if (item != null) {
onSave(item.getItems(), job);
} else {
finishJob(job);
}
}, throwable -> jobFinished(job, true));
}
return true;
}
@Override public boolean onStopJob(JobParameters jobParameters) {
return false;
}
public static void scheduleJob(@NonNull Context context) {
int duration = PrefGetter.getNotificationTaskDuration();
scheduleJob(context, duration, false);
}
public static void scheduleJob(@NonNull Context context, int duration, boolean cancel) {
if (AppHelper.isGoogleAvailable(context)) {
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
dispatcher.cancel(SINGLE_JOB_ID);
if (cancel) dispatcher.cancel(JOB_ID);
if (duration == -1) {
dispatcher.cancel(JOB_ID);
return;
}
duration = duration <= 0 ? THIRTY_MINUTES : duration;
Job.Builder builder = dispatcher
.newJobBuilder()
.setTag(JOB_ID)
.setRetryStrategy(RetryStrategy.DEFAULT_LINEAR)
.setLifetime(Lifetime.FOREVER)
.setRecurring(true)
.setConstraints(Constraint.ON_ANY_NETWORK)
.setTrigger(Trigger.executionWindow(duration / 2, duration))
.setService(NotificationSchedulerJobTask.class);
dispatcher.mustSchedule(builder.build());
}
}
public static void scheduleOneTimeJob(@NonNull Context context) {
if (AppHelper.isGoogleAvailable(context)) {
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
Job.Builder builder = dispatcher
.newJobBuilder()
.setTag(SINGLE_JOB_ID)
.setReplaceCurrent(true)
.setRecurring(false)
.setTrigger(Trigger.executionWindow(30, 60))
.setConstraints(Constraint.ON_ANY_NETWORK)
.setService(NotificationSchedulerJobTask.class);
dispatcher.mustSchedule(builder.build());
}
}
private void onSave(@Nullable List<Notification> notificationThreadModels, JobParameters job) {
if (notificationThreadModels != null) {
Notification.save(notificationThreadModels);
onNotifyUser(notificationThreadModels, job);
}
}
private void onNotifyUser(@NonNull List<Notification> notificationThreadModels, JobParameters job) {
long count = Stream.of(notificationThreadModels)
.filter(Notification::isUnread)
.count();
if (count == 0) {
AppHelper.cancelAllNotifications(getApplicationContext());
finishJob(job);
return;
}
Context context = getApplicationContext();
int accentColor = ContextCompat.getColor(this, R.color.material_blue_700);
Notification first = notificationThreadModels.get(0);
Observable.fromIterable(notificationThreadModels)
.subscribeOn(Schedulers.io())
.filter(notification -> notification.isUnread() && first.getId() != notification.getId()
&& !NotificationQueue.exists(notification.getId()))
.take(10)
.flatMap(notification -> {
if (notification.getSubject() != null && notification.getSubject().getLatestCommentUrl() != null) {
return RestProvider.getNotificationService(PrefGetter.isEnterprise())
.getComment(notification.getSubject().getLatestCommentUrl())
.subscribeOn(Schedulers.io());
} else {
return Observable.empty();
}
}, (thread, comment) -> {
CustomNotificationModel customNotificationModel = new CustomNotificationModel();
String url;
if (comment != null && comment.getUser() != null) {
url = comment.getUser().getAvatarUrl();
if (!InputHelper.isEmpty(thread.getSubject().getLatestCommentUrl())) {
customNotificationModel.comment = comment;
customNotificationModel.url = url;
}
}
customNotificationModel.notification = thread;
return customNotificationModel;
})
.subscribeOn(Schedulers.io())
.subscribe(custom -> {
if (custom.comment != null) {
getNotificationWithComment(context, accentColor, custom.notification, custom.comment, custom.url);
} else {
showNotificationWithoutComment(context, accentColor, custom.notification, custom.url);
}
}, throwable -> finishJob(job), () -> {
if (!NotificationQueue.exists(first.getId())) {
android.app.Notification grouped = getSummaryGroupNotification(first, accentColor, notificationThreadModels.size() > 1);
showNotification(first.getId(), grouped);
}
NotificationQueue.put(notificationThreadModels)
.subscribe(aBoolean -> {/*do nothing*/}, Throwable::printStackTrace, () -> finishJob(job));
});
}
private void finishJob(JobParameters job) {
jobFinished(job, false);
}
private void showNotificationWithoutComment(Context context, int accentColor, Notification thread, String iconUrl) {
withoutComments(thread, context, accentColor);
}
private void withoutComments(Notification thread, Context context, int accentColor) {
android.app.Notification toAdd = getNotification(thread.getSubject().getTitle(), thread.getRepository().getFullName(),
thread.getRepository() != null ? thread.getRepository().getFullName() : "general")
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentIntent(getPendingIntent(thread.getId(), thread.getSubject().getUrl()))
.addAction(R.drawable.ic_github, context.getString(R.string.open), getPendingIntent(thread.getId(), thread
.getSubject().getUrl()))
.addAction(R.drawable.ic_eye_off, context.getString(R.string.mark_as_read), getReadOnlyPendingIntent(thread.getId(), thread
.getSubject().getUrl()))
.setWhen(thread.getUpdatedAt() != null ? thread.getUpdatedAt().getTime() : System.currentTimeMillis())
.setShowWhen(true)
.setColor(accentColor)
.setGroup(NOTIFICATION_GROUP_ID)
.build();
showNotification(thread.getId(), toAdd);
}
private void getNotificationWithComment(Context context, int accentColor, Notification thread, Comment comment, String url) {
withComments(comment, context, thread, accentColor);
}
private void withComments(Comment comment, Context context, Notification thread, int accentColor) {
android.app.Notification toAdd = getNotification(comment.getUser() != null ? comment.getUser().getLogin() : "",
MarkDownProvider.stripMdText(comment.getBody()),
thread.getRepository() != null ? thread.getRepository().getFullName() : "general")
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setSmallIcon(R.drawable.ic_notification)
.setStyle(new NotificationCompat.BigTextStyle()
.setBigContentTitle(comment.getUser() != null ? comment.getUser().getLogin() : "")
.bigText(MarkDownProvider.stripMdText(comment.getBody())))
.setWhen(comment.getCreatedAt().getTime())
.setShowWhen(true)
.addAction(R.drawable.ic_github, context.getString(R.string.open), getPendingIntent(thread.getId(),
thread.getSubject().getUrl()))
.addAction(R.drawable.ic_eye_off, context.getString(R.string.mark_as_read), getReadOnlyPendingIntent(thread.getId(),
thread.getSubject().getUrl()))
.setContentIntent(getPendingIntent(thread.getId(), thread.getSubject().getUrl()))
.setColor(accentColor)
.setGroup(NOTIFICATION_GROUP_ID)
.build();
showNotification(thread.getId(), toAdd);
}
private android.app.Notification getSummaryGroupNotification(@NonNull Notification thread, int accentColor, boolean toNotificationActivity) {
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,
new Intent(getApplicationContext(), NotificationActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = getNotification(thread.getSubject().getTitle(), thread.getRepository().getFullName(),
thread.getRepository() != null ? thread.getRepository().getFullName() : "general")
.setContentIntent(toNotificationActivity ? pendingIntent : getPendingIntent(thread.getId(), thread.getSubject().getUrl()))
.addAction(R.drawable.ic_github, getString(R.string.open), getPendingIntent(thread.getId(), thread
.getSubject().getUrl()))
.addAction(R.drawable.ic_eye_off, getString(R.string.mark_as_read), getReadOnlyPendingIntent(thread.getId(), thread
.getSubject().getUrl()))
.setWhen(thread.getUpdatedAt() != null ? thread.getUpdatedAt().getTime() : System.currentTimeMillis())
.setShowWhen(true)
.setSmallIcon(R.drawable.ic_notification)
.setColor(accentColor)
.setGroup(NOTIFICATION_GROUP_ID)
.setGroupSummary(true);
if (PrefGetter.isNotificationSoundEnabled()) {
builder.setDefaults(NotificationCompat.DEFAULT_ALL)
.setSound(PrefGetter.getNotificationSound(), AudioManager.STREAM_NOTIFICATION);
}
return builder.build();
}
private NotificationCompat.Builder getNotification(@NonNull String title, @NonNull String message, @NonNull String channelName) {
return new NotificationCompat.Builder(this, channelName)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true);
}
private void showNotification(long id, android.app.Notification notification) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(notification.getChannelId(),
notification.getChannelId(), NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.setShowBadge(true);
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(InputHelper.getSafeIntId(id), notification);
}
}
private PendingIntent getReadOnlyPendingIntent(long id, @NonNull String url) {
Intent intent = ReadNotificationService.start(getApplicationContext(), id, url, true);
return PendingIntent.getService(getApplicationContext(), InputHelper.getSafeIntId(id) / 2, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
private PendingIntent getPendingIntent(long id, @NonNull String url) {
Intent intent = ReadNotificationService.start(getApplicationContext(), id, url);
return PendingIntent.getService(getApplicationContext(), InputHelper.getSafeIntId(id), intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
private static class CustomNotificationModel {
public String url;
public Notification notification;
public Comment comment;
}
}
| 15,372 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
ReadNotificationService.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/tasks/notification/ReadNotificationService.java | package com.fastaccess.provider.tasks.notification;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import com.annimon.stream.LongStream;
import com.fastaccess.R;
import com.fastaccess.helper.AppHelper;
import com.fastaccess.helper.BundleConstant;
import com.fastaccess.helper.Bundler;
import com.fastaccess.helper.InputHelper;
import com.fastaccess.helper.PrefGetter;
import com.fastaccess.provider.rest.RestProvider;
import com.fastaccess.provider.scheme.SchemeParser;
import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;
/**
* Created by Kosh on 11 Mar 2017, 12:13 AM
*/
public class ReadNotificationService extends IntentService {
public static final int READ_SINGLE = 1;
public static final int READ_ALL = 2;
public static final int OPEN_NOTIFICATION = 3;
public static final int UN_SUBSCRIBE = 4;
private NotificationCompat.Builder notification;
private NotificationManager notificationManager;
public static void start(@NonNull Context context, long id) {
Intent intent = new Intent(context.getApplicationContext(), ReadNotificationService.class);
intent.putExtras(Bundler.start()
.put(BundleConstant.EXTRA_TYPE, READ_SINGLE)
.put(BundleConstant.ID, id)
.end());
context.startService(intent);
}
public static Intent start(@NonNull Context context, long id, @NonNull String url) {
return start(context, id, url, false);
}
public static Intent start(@NonNull Context context, long id, @NonNull String url, boolean onlyRead) {
Intent intent = new Intent(context.getApplicationContext(), ReadNotificationService.class);
intent.putExtras(Bundler.start()
.put(BundleConstant.EXTRA_TYPE, OPEN_NOTIFICATION)
.put(BundleConstant.EXTRA, url)
.put(BundleConstant.ID, id)
.put(BundleConstant.YES_NO_EXTRA, onlyRead)
.end());
return intent;
}
public static void unSubscribe(@NonNull Context context, long id) {
Intent intent = new Intent(context.getApplicationContext(), ReadNotificationService.class);
intent.putExtras(Bundler.start()
.put(BundleConstant.EXTRA_TYPE, UN_SUBSCRIBE)
.put(BundleConstant.ID, id)
.end());
context.startService(intent);
}
public static void start(@NonNull Context context, @NonNull long[] ids) {
Intent intent = new Intent(context.getApplicationContext(), ReadNotificationService.class);
intent.putExtras(Bundler.start()
.put(BundleConstant.EXTRA_TYPE, READ_ALL)
.put(BundleConstant.ID, ids)
.end());
context.startService(intent);
}
public ReadNotificationService() {
super(ReadNotificationService.class.getSimpleName());
}
@Override public void onCreate() {
super.onCreate();
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
@Override protected void onHandleIntent(@Nullable Intent intent) {
if (intent != null && intent.getExtras() != null) {
Bundle bundle = intent.getExtras();
int type = bundle.getInt(BundleConstant.EXTRA_TYPE);
if (type == READ_SINGLE) {
markSingleAsRead(bundle.getLong(BundleConstant.ID));
} else if (type == READ_ALL) {
markMultiAsRead(bundle.getLongArray(BundleConstant.ID));
} else if (type == OPEN_NOTIFICATION) {
openNotification(bundle.getLong(BundleConstant.ID), bundle.getString(BundleConstant.EXTRA),
bundle.getBoolean(BundleConstant.YES_NO_EXTRA));
} else if (type == UN_SUBSCRIBE) {
unSubscribeFromThread(bundle.getLong(BundleConstant.ID));
}
}
}
private void unSubscribeFromThread(long id) {
RestProvider.getNotificationService(PrefGetter.isEnterprise())
.unSubscribe(id)
.doOnSubscribe(disposable -> notify(id, getNotification().build()))
.subscribeOn(Schedulers.io())
.flatMap(notification1 -> Observable.create(subscriber -> markSingleAsRead(id)))
.subscribe(booleanResponse -> cancel(id), throwable -> cancel(id));
}
private void openNotification(long id, @Nullable String url, boolean readOnly) {
if (id > 0 && url != null) {
AppHelper.cancelNotification(this, InputHelper.getSafeIntId(id));
if (readOnly) {
markSingleAsRead(id);
} else if (!PrefGetter.isMarkAsReadEnabled()) {
markSingleAsRead(id);
}
if (!readOnly) {
SchemeParser.launchUri(getApplicationContext(), Uri.parse(url), true, true);
}
}
}
private void markMultiAsRead(@Nullable long[] ids) {
if (ids != null && ids.length > 0) {
LongStream.of(ids).forEach(this::markSingleAsRead);
}
}
private void markSingleAsRead(long id) {
com.fastaccess.data.dao.model.Notification.markAsRead(id);
RestProvider.getNotificationService(PrefGetter.isEnterprise())
.markAsRead(String.valueOf(id))
.doOnSubscribe(disposable -> notify(id, getNotification().build()))
.subscribeOn(Schedulers.io())
.subscribe(booleanResponse -> cancel(id), throwable -> cancel(id));
}
private NotificationCompat.Builder getNotification() {
if (notification == null) {
notification = new NotificationCompat.Builder(this, "read-notification")
.setContentTitle(getString(R.string.marking_as_read))
.setSmallIcon(R.drawable.ic_sync)
.setProgress(0, 100, true);
}
return notification;
}
private void notify(long id, Notification notification) {
notificationManager.notify(InputHelper.getSafeIntId(id), notification);
}
private void cancel(long id) {
notificationManager.cancel(InputHelper.getSafeIntId(id));
}
}
| 6,497 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
GithubActionService.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/tasks/git/GithubActionService.java | package com.fastaccess.provider.tasks.git;
import android.annotation.SuppressLint;
import android.app.IntentService;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import com.fastaccess.R;
import com.fastaccess.helper.BundleConstant;
import com.fastaccess.helper.Bundler;
import com.fastaccess.provider.rest.RestProvider;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
/**
* Created by Kosh on 12 Mar 2017, 2:25 PM
*/
@SuppressWarnings("ResultOfMethodCallIgnored") @SuppressLint("CheckResult")
public class GithubActionService extends IntentService {
public static final int STAR_REPO = 1;
public static final int UNSTAR_REPO = 2;
public static final int FORK_REPO = 3;
public static final int WATCH_REPO = 4;
public static final int UNWATCH_REPO = 5;
public static final int STAR_GIST = 6;
public static final int UNSTAR_GIST = 7;
public static final int FORK_GIST = 8;
private NotificationCompat.Builder notification;
private NotificationManager notificationManager;
@IntDef({
STAR_REPO,
UNSTAR_REPO,
FORK_REPO,
WATCH_REPO,
UNWATCH_REPO,
STAR_GIST,
UNSTAR_GIST,
FORK_GIST,
})
@Retention(RetentionPolicy.SOURCE) @interface GitActionType {}
public static void startForRepo(@NonNull Context context, @NonNull String login, @NonNull String repo,
@GitActionType int type, boolean isEnterprise) {
Intent intent = new Intent(context.getApplicationContext(), GithubActionService.class);
intent.putExtras(Bundler.start()
.put(BundleConstant.ID, repo)
.put(BundleConstant.EXTRA, login)
.put(BundleConstant.EXTRA_TYPE, type)
.put(BundleConstant.IS_ENTERPRISE, isEnterprise)
.end());
context.startService(intent);
}
public static void startForGist(@NonNull Context context, @NonNull String id, @GitActionType int type, boolean isEnterprise) {
Intent intent = new Intent(context.getApplicationContext(), GithubActionService.class);
intent.putExtras(Bundler.start()
.put(BundleConstant.ID, id)
.put(BundleConstant.EXTRA_TYPE, type)
.put(BundleConstant.IS_ENTERPRISE, isEnterprise)
.end());
context.startService(intent);
}
public GithubActionService() {
super(GithubActionService.class.getName());
}
@Override protected void onHandleIntent(@Nullable Intent intent) {
if (intent != null && intent.getExtras() != null) {
Bundle bundle = intent.getExtras();
@GitActionType int type = bundle.getInt(BundleConstant.EXTRA_TYPE);
String id = bundle.getString(BundleConstant.ID);
String login = bundle.getString(BundleConstant.EXTRA);
boolean isEnterprise = bundle.getBoolean(BundleConstant.IS_ENTERPRISE);
switch (type) {
case FORK_GIST:
forkGist(id, isEnterprise);
break;
case FORK_REPO:
forkRepo(id, login, isEnterprise);
break;
case STAR_GIST:
starGist(id, isEnterprise);
break;
case STAR_REPO:
starRepo(id, login, isEnterprise);
break;
case UNSTAR_GIST:
unStarGist(id, isEnterprise);
break;
case UNSTAR_REPO:
unStarRepo(id, login, isEnterprise);
break;
case UNWATCH_REPO:
unWatchRepo(id, login, isEnterprise);
break;
case WATCH_REPO:
watchRepo(id, login, isEnterprise);
break;
}
}
}
@Override public void onDestroy() {
super.onDestroy();
}
private void forkGist(@Nullable String id, boolean isEnterprise) {
if (id != null) {
String msg = getString(R.string.forking, getString(R.string.gist));
RestProvider.getGistService(isEnterprise)
.forkGist(id)
.doOnSubscribe(disposable -> showNotification(msg))
.subscribeOn(Schedulers.io())
.subscribe(response -> {
}, throwable -> hideNotification(msg), () -> hideNotification(msg));
}
}
private void forkRepo(@Nullable String id, @Nullable String login, boolean isEnterprise) {
if (id != null && login != null) {
String msg = getString(R.string.forking, id);
RestProvider.getRepoService(isEnterprise)
.forkRepo(login, id)
.doOnSubscribe(disposable -> showNotification(msg))
.subscribeOn(Schedulers.io())
.subscribe(response -> {
}, throwable -> hideNotification(msg), () -> hideNotification(msg));
}
}
private void starGist(@Nullable String id, boolean isEnterprise) {
if (id != null) {
String msg = getString(R.string.starring, getString(R.string.gist));
RestProvider.getGistService(isEnterprise)
.starGist(id)
.doOnSubscribe(disposable -> showNotification(msg))
.subscribeOn(Schedulers.io())
.subscribe(response -> {
}, throwable -> hideNotification(msg), () -> hideNotification(msg));
}
}
private void starRepo(@Nullable String id, @Nullable String login, boolean isEnterprise) {
if (id != null && login != null) {
String msg = getString(R.string.starring, id);
RestProvider.getRepoService(isEnterprise)
.starRepo(login, id)
.doOnSubscribe(disposable -> showNotification(msg))
.subscribeOn(Schedulers.io())
.subscribe(response -> {
}, throwable -> hideNotification(msg), () -> hideNotification(msg));
}
}
private void unStarGist(@Nullable String id, boolean isEnterprise) {
if (id != null) {
String msg = getString(R.string.un_starring, getString(R.string.gist));
RestProvider.getGistService(isEnterprise)
.unStarGist(id)
.doOnSubscribe(disposable -> showNotification(msg))
.subscribeOn(Schedulers.io())
.subscribe(response -> {
}, throwable -> hideNotification(msg), () -> hideNotification(msg));
}
}
private void unStarRepo(@Nullable String id, @Nullable String login, boolean isEnterprise) {
if (id != null && login != null) {
String msg = getString(R.string.un_starring, id);
RestProvider.getRepoService(isEnterprise)
.unstarRepo(login, id)
.doOnSubscribe(disposable -> showNotification(msg))
.subscribeOn(Schedulers.io())
.subscribe(response -> {
}, throwable -> hideNotification(msg), () -> hideNotification(msg));
}
}
private void unWatchRepo(@Nullable String id, @Nullable String login, boolean isEnterprise) {
if (id != null && login != null) {
String msg = getString(R.string.un_watching, id);
RestProvider.getRepoService(isEnterprise)
.unwatchRepo(login, id)
.doOnSubscribe(disposable -> showNotification(msg))
.subscribeOn(Schedulers.io())
.subscribe(response -> {
}, throwable -> hideNotification(msg), () -> hideNotification(msg));
}
}
private void watchRepo(@Nullable String id, @Nullable String login, boolean isEnterprise) {
if (id != null && login != null) {
String msg = getString(R.string.watching, id);
RestProvider.getRepoService(isEnterprise)
.watchRepo(login, id)
.doOnSubscribe(disposable -> showNotification(msg))
.subscribeOn(Schedulers.io())
.subscribe(response -> {
}, throwable -> hideNotification(msg), () -> hideNotification(msg));
}
}
private NotificationCompat.Builder getNotification(@NonNull String title) {
if (notification == null) {
notification = new NotificationCompat.Builder(this, title)
.setSmallIcon(R.drawable.ic_sync)
.setProgress(0, 100, true);
}
notification.setContentTitle(title);
return notification;
}
private NotificationManager getNotificationManager() {
if (notificationManager == null) {
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
return notificationManager;
}
private void showNotification(@NonNull String msg) {
getNotificationManager().notify(msg.hashCode(), getNotification(msg).build());
}
private void hideNotification(@NonNull String msg) {
getNotificationManager().cancel(msg.hashCode());
}
}
| 9,758 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
LinkParserHelper.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/scheme/LinkParserHelper.java | package com.fastaccess.provider.scheme;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;
import com.annimon.stream.Optional;
import com.annimon.stream.Stream;
import com.fastaccess.helper.InputHelper;
import com.fastaccess.helper.ObjectsCompat;
import com.fastaccess.helper.PrefGetter;
import java.util.Arrays;
import java.util.List;
/**
* Created by Kosh on 11 Apr 2017, 10:02 PM
*/
public class LinkParserHelper {
public static final String HOST_DEFAULT = "github.com";
public static final String PROTOCOL_HTTPS = "https";
static final String HOST_GISTS = "gist.github.com";
static final String HOST_GISTS_RAW = "gist.githubusercontent.com";
static final String RAW_AUTHORITY = "raw.githubusercontent.com";
static final String API_AUTHORITY = "api.github.com";
static final List<String> IGNORED_LIST = Arrays.asList("notifications", "settings", "blog",
"explore", "dashboard", "repositories", "logout", "sessions", "site", "security",
"contact", "about", "logos", "login", "pricing", "");
@SafeVarargs static <T> Optional<T> returnNonNull(@NonNull T... t) {
return Stream.of(t).filter(ObjectsCompat::nonNull).findFirst();
}
@NonNull static Uri getBlobBuilder(@NonNull Uri uri) {
boolean isSvg = "svg".equalsIgnoreCase(MimeTypeMap.getFileExtensionFromUrl(uri.toString()));
List<String> segments = uri.getPathSegments();
if (isSvg) {
Uri svgBlob = Uri.parse(uri.toString().replace("blob/", ""));
return svgBlob.buildUpon().authority(RAW_AUTHORITY).build();
}
Uri.Builder urlBuilder = new Uri.Builder();
String owner = segments.get(0);
String repo = segments.get(1);
String branch = segments.get(3);
urlBuilder.scheme("https")
.authority(API_AUTHORITY)
.appendPath("repos")
.appendPath(owner)
.appendPath(repo)
.appendPath("contents");
for (int i = 4; i < segments.size(); i++) {
urlBuilder.appendPath(segments.get(i));
}
if (uri.getQueryParameterNames() != null) {
for (String query : uri.getQueryParameterNames()) {
urlBuilder.appendQueryParameter(query, uri.getQueryParameter(query));
}
}
if (uri.getEncodedFragment() != null) {
urlBuilder.encodedFragment(uri.getEncodedFragment());
}
urlBuilder.appendQueryParameter("ref", branch);
return urlBuilder.build();
}
public static boolean isEnterprise(@Nullable String url) {
if (InputHelper.isEmpty(url) || !PrefGetter.isEnterprise()) return false;
String enterpriseUrl = PrefGetter.getEnterpriseUrl().toLowerCase();
url = url.toLowerCase();
return url.equalsIgnoreCase(enterpriseUrl) || url.startsWith(enterpriseUrl) || url.startsWith(getEndpoint(enterpriseUrl))
|| url.contains(enterpriseUrl) || enterpriseUrl.contains(url);
}
public static String stripScheme(@NonNull String url) {
try {
Uri uri = Uri.parse(url);
return !InputHelper.isEmpty(uri.getAuthority()) ? uri.getAuthority() : url;
} catch (Exception ignored) {}
return url;
}
@NonNull public static String getEndpoint(@NonNull String url) {
if (url.startsWith("http://")) {
url = url.replace("http://", "https://");
}
if (!url.startsWith("https://")) {
url = "https://" + url;
}
return getEnterpriseUrl(url);
}
@NonNull private static String getEnterpriseUrl(@NonNull String url) {
if (url.endsWith("/api/v3/")) {
return url;
} else if (url.endsWith("/api/")) {
return url + "v3/";
} else if (url.endsWith("/api")) {
return url + "/v3/";
} else if (url.endsWith("/api/v3")) {
return url + "/";
} else if (!url.endsWith("/")) {
return url + "/api/v3/";
} else if (url.endsWith("/")) {
return url + "api/v3/";
}
return url;
}
public static String getEnterpriseGistUrl(@NonNull String url, boolean isEnterprise) {
if (isEnterprise) {
Uri uri = Uri.parse(url);
boolean isGist = uri == null || uri.getPathSegments() == null ? url.contains("gist/") : uri.getPathSegments().get(0).equals("gist");
if (isGist) {
String enterpriseUrl = PrefGetter.getEnterpriseUrl();
if (!url.contains(enterpriseUrl + "/raw/")) {
url = url.replace(enterpriseUrl, enterpriseUrl + "/raw");
}
}
}
return url;
}
@Nullable public static String getGistId(@NonNull Uri uri) {
String gistId = null;
if (uri.toString().contains("raw/gist")) {
if (uri.getPathSegments().size() > 5) {
gistId = uri.getPathSegments().get(5);
}
} else if (uri.getPathSegments() != null) {
if (TextUtils.equals(LinkParserHelper.HOST_GISTS_RAW, uri.getAuthority())) {
if (uri.getPathSegments().size() > 1) {
gistId = uri.getPathSegments().get(1);
}
}
}
return gistId;
}
}
| 5,473 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
SchemeParser.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/scheme/SchemeParser.java | package com.fastaccess.provider.scheme;
import android.app.Activity;
import android.app.Application;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;
import com.annimon.stream.Optional;
import com.annimon.stream.Stream;
import com.fastaccess.helper.ActivityHelper;
import com.fastaccess.helper.BundleConstant;
import com.fastaccess.helper.InputHelper;
import com.fastaccess.helper.Logger;
import com.fastaccess.helper.PrefGetter;
import com.fastaccess.provider.markdown.MarkDownProvider;
import com.fastaccess.ui.modules.code.CodeViewerActivity;
import com.fastaccess.ui.modules.filter.issues.FilterIssuesActivity;
import com.fastaccess.ui.modules.gists.gist.GistActivity;
import com.fastaccess.ui.modules.repos.RepoPagerActivity;
import com.fastaccess.ui.modules.repos.RepoPagerMvp;
import com.fastaccess.ui.modules.repos.code.commit.details.CommitPagerActivity;
import com.fastaccess.ui.modules.repos.code.files.activity.RepoFilesActivity;
import com.fastaccess.ui.modules.repos.code.releases.ReleasesListActivity;
import com.fastaccess.ui.modules.repos.issues.create.CreateIssueActivity;
import com.fastaccess.ui.modules.repos.issues.issue.details.IssuePagerActivity;
import com.fastaccess.ui.modules.repos.projects.details.ProjectPagerActivity;
import com.fastaccess.ui.modules.repos.pull_requests.pull_request.details.PullRequestPagerActivity;
import com.fastaccess.ui.modules.repos.wiki.WikiActivity;
import com.fastaccess.ui.modules.search.SearchActivity;
import com.fastaccess.ui.modules.trending.TrendingActivity;
import com.fastaccess.ui.modules.user.UserPagerActivity;
import java.util.List;
import static com.fastaccess.provider.scheme.LinkParserHelper.API_AUTHORITY;
import static com.fastaccess.provider.scheme.LinkParserHelper.HOST_DEFAULT;
import static com.fastaccess.provider.scheme.LinkParserHelper.HOST_GISTS;
import static com.fastaccess.provider.scheme.LinkParserHelper.HOST_GISTS_RAW;
import static com.fastaccess.provider.scheme.LinkParserHelper.IGNORED_LIST;
import static com.fastaccess.provider.scheme.LinkParserHelper.PROTOCOL_HTTPS;
import static com.fastaccess.provider.scheme.LinkParserHelper.RAW_AUTHORITY;
import static com.fastaccess.provider.scheme.LinkParserHelper.getBlobBuilder;
import static com.fastaccess.provider.scheme.LinkParserHelper.returnNonNull;
/**
* Created by Kosh on 09 Dec 2016, 4:44 PM
*/
public class SchemeParser {
public static void launchUri(@NonNull Context context, @NonNull String url) {
launchUri(context, Uri.parse(url), false);
}
public static void launchUri(@NonNull Context context, @NonNull Uri data) {
launchUri(context, data, false);
}
public static void launchUri(@NonNull Context context, @NonNull Uri data, boolean showRepoBtn) {
launchUri(context, data, showRepoBtn, false);
}
public static void launchUri(@NonNull Context context, @NonNull Uri data, boolean showRepoBtn, boolean newDocument) {
Logger.e(data);
Intent intent = convert(context, data, showRepoBtn);
if (intent != null) {
intent.putExtra(BundleConstant.SCHEME_URL, data.toString());
if (newDocument) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
}
if (context instanceof Service || context instanceof Application) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
context.startActivity(intent);
} else {
Activity activity = ActivityHelper.getActivity(context);
if (activity != null) {
ActivityHelper.startCustomTab(activity, data);
} else {
ActivityHelper.openChooser(context, data);
}
}
}
@Nullable private static Intent convert(@NonNull Context context, Uri data, boolean showRepoBtn) {
if (data == null) return null;
if (InputHelper.isEmpty(data.getHost()) || InputHelper.isEmpty(data.getScheme())) {
String host = data.getHost();
if (InputHelper.isEmpty(host)) host = HOST_DEFAULT;
String scheme = data.getScheme();
if (InputHelper.isEmpty(scheme)) scheme = PROTOCOL_HTTPS;
String prefix = scheme + "://" + host;
String path = data.getPath();
if (!InputHelper.isEmpty(path)) {
if (path.charAt(0) == '/') {
data = Uri.parse(prefix + path);
} else {
data = Uri.parse(prefix + '/' + path);
}
} else {
data = Uri.parse(prefix);
}
}
if (data.getPathSegments() != null && !data.getPathSegments().isEmpty()) {
if (IGNORED_LIST.contains(data.getPathSegments().get(0))) return null;
return getIntentForURI(context, data, showRepoBtn);
}
return null;
}
@Nullable private static Intent getIntentForURI(@NonNull Context context, @NonNull Uri data, boolean showRepoBtn) {
String authority = data.getAuthority();
boolean isEnterprise = PrefGetter.isEnterprise() && LinkParserHelper.isEnterprise(authority == null ? data.toString() : authority);
if (HOST_GISTS.equals(data.getHost()) || "gist".equalsIgnoreCase(data.getPathSegments().get(0))) {
String extension = MimeTypeMap.getFileExtensionFromUrl(data.toString());
if (!InputHelper.isEmpty(extension) && !MarkDownProvider.isArchive(data.getLastPathSegment())) {
String url = data.toString();
return CodeViewerActivity.createIntent(context, url, url);
}
String gist = getGistId(data);
if (gist != null) {
return GistActivity.createIntent(context, gist, isEnterprise);
}
} else if (HOST_GISTS_RAW.equalsIgnoreCase(data.getHost())) {
return getGistFile(context, data);
} else {
if (MarkDownProvider.isArchive(data.toString())) return null;
if (TextUtils.equals(authority, HOST_DEFAULT) || TextUtils.equals(authority, RAW_AUTHORITY) ||
TextUtils.equals(authority, API_AUTHORITY) || isEnterprise) {
Intent trending = getTrending(context, data);
Intent projects = getRepoProject(context, data);
Intent userIntent = getUser(context, data);
Intent repoIssues = getRepoIssueIntent(context, data);
Intent repoPulls = getRepoPullRequestIntent(context, data);
Intent createIssueIntent = getCreateIssueIntent(context, data);
Intent pullRequestIntent = getPullRequestIntent(context, data, showRepoBtn);
Intent issueIntent = getIssueIntent(context, data, showRepoBtn);
Intent releasesIntent = getReleases(context, data, isEnterprise);
Intent repoIntent = getRepo(context, data);
Intent repoWikiIntent = getWiki(context, data);
Intent commit = getCommit(context, data, showRepoBtn);
Intent commits = getCommits(context, data, showRepoBtn);
Intent blob = getBlob(context, data);
Intent label = getLabel(context, data);
Intent search = getSearchIntent(context, data);
Optional<Intent> intentOptional = returnNonNull(trending, projects, search, userIntent, repoIssues, repoPulls,
pullRequestIntent, label, commit, commits, createIssueIntent, issueIntent, releasesIntent, repoIntent,
repoWikiIntent, blob);
Optional<Intent> empty = Optional.empty();
if (intentOptional != null && intentOptional.isPresent() && intentOptional != empty) {
Intent intent = intentOptional.get();
if (isEnterprise) {
if (intent.getExtras() != null) {
Bundle bundle = intent.getExtras();
bundle.putBoolean(BundleConstant.IS_ENTERPRISE, true);
intent.putExtras(bundle);
} else {
intent.putExtra(BundleConstant.IS_ENTERPRISE, true);
}
}
return intent;
} else {
Intent intent = getGeneralRepo(context, data);
if (isEnterprise) {
if (intent != null && intent.getExtras() != null) {
Bundle bundle = intent.getExtras();
bundle.putBoolean(BundleConstant.IS_ENTERPRISE, true);
intent.putExtras(bundle);
} else if (intent != null) {
intent.putExtra(BundleConstant.IS_ENTERPRISE, true);
}
}
return intent;
}
}
}
return null;
}
private static boolean getInvitationIntent(@NonNull Uri uri) {
List<String> segments = uri.getPathSegments();
return (segments != null && segments.size() == 3) && "invitations".equalsIgnoreCase(uri.getLastPathSegment());
}
@Nullable private static Intent getPullRequestIntent(@NonNull Context context, @NonNull Uri uri, boolean showRepoBtn) {
List<String> segments = uri.getPathSegments();
if (segments == null || segments.size() < 3) return null;
String owner = null;
String repo = null;
String number = null;
String fragment = uri.getEncodedFragment();//#issuecomment-332236665
Long commentId = null;
if (!InputHelper.isEmpty(fragment) && fragment.split("-").length > 1) {
fragment = fragment.split("-")[1];
if (!InputHelper.isEmpty(fragment)) {
try {
commentId = Long.parseLong(fragment);
} catch (Exception ignored) {}
}
}
if (segments.size() > 3) {
if (("pull".equals(segments.get(2)) || "pulls".equals(segments.get(2)))) {
owner = segments.get(0);
repo = segments.get(1);
number = segments.get(3);
} else if (("pull".equals(segments.get(3)) || "pulls".equals(segments.get(3))) && segments.size() > 4) {
owner = segments.get(1);
repo = segments.get(2);
number = segments.get(4);
} else {
return null;
}
}
if (InputHelper.isEmpty(number)) return null;
int issueNumber;
try {
issueNumber = Integer.parseInt(number);
} catch (NumberFormatException nfe) {
return null;
}
if (issueNumber < 1) return null;
return PullRequestPagerActivity.createIntent(context, repo, owner, issueNumber, showRepoBtn,
LinkParserHelper.isEnterprise(uri.toString()), commentId == null ? 0 : commentId);
}
@Nullable private static Intent getIssueIntent(@NonNull Context context, @NonNull Uri uri, boolean showRepoBtn) {
List<String> segments = uri.getPathSegments();
if (segments == null || segments.size() < 3) return null;
String owner = null;
String repo = null;
String number = null;
String fragment = uri.getEncodedFragment();//#issuecomment-332236665
Long commentId = null;
if (!InputHelper.isEmpty(fragment) && fragment.split("-").length > 1) {
fragment = fragment.split("-")[1];
if (!InputHelper.isEmpty(fragment)) {
try {
commentId = Long.parseLong(fragment);
} catch (Exception ignored) {}
}
}
if (segments.size() > 3) {
if (segments.get(2).equalsIgnoreCase("issues")) {
owner = segments.get(0);
repo = segments.get(1);
number = segments.get(3);
} else if (segments.get(3).equalsIgnoreCase("issues") && segments.size() > 4) {
owner = segments.get(1);
repo = segments.get(2);
number = segments.get(4);
} else {
return null;
}
}
if (InputHelper.isEmpty(number))
return null;
int issueNumber;
try {
issueNumber = Integer.parseInt(number);
} catch (NumberFormatException nfe) {
return null;
}
if (issueNumber < 1) return null;
return IssuePagerActivity.createIntent(context, repo, owner, issueNumber, showRepoBtn,
LinkParserHelper.isEnterprise(uri.toString()), commentId == null ? 0 : commentId);
}
@Nullable private static Intent getLabel(@NonNull Context context, @NonNull Uri uri) {
List<String> segments = uri.getPathSegments();
if (segments == null || segments.size() < 3) return null;
String owner = segments.get(0);
String repoName = segments.get(1);
String lastPath = segments.get(2);
if ("labels".equalsIgnoreCase(lastPath)) {
return FilterIssuesActivity.getIntent(context, owner, repoName, "label:\"" + segments.get(3) + "\"");
}
return null;
}
@Nullable private static Intent getRepo(@NonNull Context context, @NonNull Uri uri) {
List<String> segments = uri.getPathSegments();
if (segments == null || segments.size() < 2 || segments.size() > 3) return null;
String owner = segments.get(0);
String repoName = segments.get(1);
if (!InputHelper.isEmpty(repoName)) {
if (repoName.endsWith(".git")) repoName = repoName.replace(".git", "");
}
if (segments.size() == 3) {
String lastPath = uri.getLastPathSegment();
if ("milestones".equalsIgnoreCase(lastPath)) {
return RepoPagerActivity.createIntent(context, repoName, owner, RepoPagerMvp.CODE, 4);
} else if ("network".equalsIgnoreCase(lastPath)) {
return RepoPagerActivity.createIntent(context, repoName, owner, RepoPagerMvp.CODE, 3);
} else if ("stargazers".equalsIgnoreCase(lastPath)) {
return RepoPagerActivity.createIntent(context, repoName, owner, RepoPagerMvp.CODE, 2);
} else if ("watchers".equalsIgnoreCase(lastPath)) {
return RepoPagerActivity.createIntent(context, repoName, owner, RepoPagerMvp.CODE, 1);
} else if ("labels".equalsIgnoreCase(lastPath)) {
return RepoPagerActivity.createIntent(context, repoName, owner, RepoPagerMvp.CODE, 5);
} else {
return null;
}
} else {
return RepoPagerActivity.createIntent(context, repoName, owner);
}
}
@Nullable private static Intent getRepoProject(@NonNull Context context, @NonNull Uri uri) {
List<String> segments = uri.getPathSegments();
if (segments == null || segments.size() < 3) return null;
String owner = segments.get(0);
String repoName = segments.get(1);
if (segments.size() == 3 && "projects".equalsIgnoreCase(segments.get(2))) {
return RepoPagerActivity.createIntent(context, repoName, owner, RepoPagerMvp.PROJECTS);
} else if (segments.size() == 4 && "projects".equalsIgnoreCase(segments.get(2))) {
try {
int projectId = Integer.parseInt(segments.get(segments.size() - 1));
if (projectId > 0) {
return ProjectPagerActivity.Companion.getIntent(context, owner, repoName, projectId,
LinkParserHelper.isEnterprise(uri.toString()));
}
} catch (Exception ignored) {}
}
return null;
}
@Nullable private static Intent getWiki(@NonNull Context context, @NonNull Uri uri) {
List<String> segments = uri.getPathSegments();
if (segments == null || segments.size() < 3) return null;
if ("wiki".equalsIgnoreCase(segments.get(2))) {
String owner = segments.get(0);
String repoName = segments.get(1);
return WikiActivity.Companion.getWiki(context, repoName, owner,
"wiki".equalsIgnoreCase(uri.getLastPathSegment()) ? null : uri.getLastPathSegment());
}
return null;
}
/**
* [[k0shk0sh, FastHub, issues], k0shk0sh/fastHub/(issues,pulls,commits, etc)]
*/
@Nullable private static Intent getGeneralRepo(@NonNull Context context, @NonNull Uri uri) {
//TODO parse deeper links to their associate views. meantime fallback to repoPage
if (getInvitationIntent(uri)) {
return null;
}
boolean isEnterprise = PrefGetter.isEnterprise() && Uri.parse(LinkParserHelper.getEndpoint(PrefGetter.getEnterpriseUrl())).getAuthority()
.equalsIgnoreCase(uri.getAuthority());
if (uri.getAuthority().equals(HOST_DEFAULT) || uri.getAuthority().equals(API_AUTHORITY) || isEnterprise) {
List<String> segments = uri.getPathSegments();
if (segments == null || segments.isEmpty()) return null;
if (segments.size() == 1) {
return getUser(context, uri);
} else if (segments.size() > 1) {
if (segments.get(0).equalsIgnoreCase("repos") && segments.size() >= 2) {
String owner = segments.get(1);
String repoName = segments.get(2);
return RepoPagerActivity.createIntent(context, repoName, owner);
} else if ("orgs".equalsIgnoreCase(segments.get(0))) {
return null;
} else {
String owner = segments.get(0);
String repoName = segments.get(1);
return RepoPagerActivity.createIntent(context, repoName, owner);
}
}
}
return null;
}
@Nullable private static Intent getCommits(@NonNull Context context, @NonNull Uri uri, boolean showRepoBtn) {
List<String> segments = Stream.of(uri.getPathSegments())
.filter(value -> !value.equalsIgnoreCase("api") || !value.equalsIgnoreCase("v3"))
.toList();
if (segments == null || segments.isEmpty() || segments.size() < 3) return null;
String login = null;
String repoId = null;
String sha = null;
if (segments.size() > 3 && segments.get(3).equals("commits")) {
login = segments.get(1);
repoId = segments.get(2);
sha = segments.get(4);
} else if (segments.size() > 2 && segments.get(2).equals("commits")) {
login = segments.get(0);
repoId = segments.get(1);
sha = uri.getLastPathSegment();
}
if (login != null && sha != null && repoId != null) {
return CommitPagerActivity.createIntent(context, repoId, login, sha, showRepoBtn);
}
return null;
}
@Nullable private static Intent getCommit(@NonNull Context context, @NonNull Uri uri, boolean showRepoBtn) {
List<String> segments = Stream.of(uri.getPathSegments())
.filter(value -> !value.equalsIgnoreCase("api") || !value.equalsIgnoreCase("v3"))
.toList();
if (segments.size() < 3 || !"commit".equals(segments.get(2))) return null;
String login = segments.get(0);
String repoId = segments.get(1);
String sha = segments.get(3);
return CommitPagerActivity.createIntent(context, repoId, login, sha, showRepoBtn);
}
@Nullable private static String getGistId(@NonNull Uri uri) {
List<String> segments = uri.getPathSegments();
if (segments.size() != 1 && segments.size() != 2) return null;
String gistId = segments.get(segments.size() - 1);
if (InputHelper.isEmpty(gistId)) return null;
if (TextUtils.isDigitsOnly(gistId)) return gistId;
else if (gistId.matches("[a-fA-F0-9]+")) return gistId;
else return null;
}
@Nullable private static Intent getUser(@NonNull Context context, @NonNull Uri uri) {
List<String> segments = uri.getPathSegments();
if (segments != null && !segments.isEmpty() && segments.size() == 1) {
return UserPagerActivity.createIntent(context, segments.get(0));
} else if (segments != null && !segments.isEmpty() && segments.size() > 1 && segments.get(0).equalsIgnoreCase("orgs")) {
if ("invitation".equalsIgnoreCase(uri.getLastPathSegment())) {
return null;
} else if ("search".equalsIgnoreCase(uri.getLastPathSegment())) {
String query = uri.getQueryParameter("q");
return SearchActivity.getIntent(context, query);
} else {
return UserPagerActivity.createIntent(context, segments.get(1), true);
}
}
return null;
}
@Nullable private static Intent getBlob(@NonNull Context context, @NonNull Uri uri) {
List<String> segments = uri.getPathSegments();
if (segments == null || segments.size() < 4) return null;
String segmentTwo = segments.get(2);
String extension = MimeTypeMap.getFileExtensionFromUrl(uri.toString());
if (InputHelper.isEmpty(extension) || TextUtils.isDigitsOnly(extension)) {
Uri urlBuilder = LinkParserHelper.getBlobBuilder(uri);
return RepoFilesActivity.getIntent(context, urlBuilder.toString());
}
if (segmentTwo.equals("blob") || segmentTwo.equals("tree")) {
Uri urlBuilder = getBlobBuilder(uri);
Logger.e(urlBuilder);
return CodeViewerActivity.createIntent(context, urlBuilder.toString(), uri.toString());
} else {
String authority = uri.getAuthority();
if (TextUtils.equals(authority, RAW_AUTHORITY)) {
return CodeViewerActivity.createIntent(context, uri.toString(), uri.toString());
}
}
return null;
}
@Nullable private static Intent getRepoIssueIntent(@NonNull Context context, @NonNull Uri uri) {
List<String> segments = uri.getPathSegments();
if (segments != null && segments.size() == 3 && uri.getLastPathSegment().equalsIgnoreCase("issues")) {
String owner = segments.get(0);
String repo = segments.get(1);
Uri encoded = Uri.parse(uri.toString().replace("utf8=%E2%9C%93&", ""));
if (encoded.getQueryParameter("q") != null) {
String query = encoded.getQueryParameter("q");
return FilterIssuesActivity.getIntent(context, owner, repo, query);
}
return RepoPagerActivity.createIntent(context, repo, owner, RepoPagerMvp.ISSUES);
}
return null;
}
@Nullable private static Intent getRepoPullRequestIntent(@NonNull Context context, @NonNull Uri uri) {
List<String> segments = uri.getPathSegments();
if (segments != null && segments.size() == 3 && uri.getLastPathSegment().equalsIgnoreCase("pulls")) {
String owner = segments.get(0);
String repo = segments.get(1);
Uri encoded = Uri.parse(uri.toString().replace("utf8=%E2%9C%93&", ""));
if (encoded.getQueryParameter("q") != null) {
String query = encoded.getQueryParameter("q");
return FilterIssuesActivity.getIntent(context, owner, repo, query);
}
return RepoPagerActivity.createIntent(context, repo, owner, RepoPagerMvp.PULL_REQUEST);
}
return null;
}
@Nullable private static Intent getReleases(@NonNull Context context, @NonNull Uri uri, boolean isEnterprise) {
List<String> segments = uri.getPathSegments();
if (segments != null && segments.size() > 2) {
if (uri.getPathSegments().get(2).equals("releases")) {
String owner = segments.get(0);
String repo = segments.get(1);
String tag = uri.getLastPathSegment();
if (tag != null && !repo.equalsIgnoreCase(tag)) {
if (TextUtils.isDigitsOnly(tag)) {
return ReleasesListActivity.getIntent(context, owner, repo, InputHelper.toLong(tag), isEnterprise);
} else {
return ReleasesListActivity.getIntent(context, owner, repo, tag, isEnterprise);
}
}
return ReleasesListActivity.getIntent(context, owner, repo);
} else if (segments.size() > 3 && segments.get(3).equalsIgnoreCase("releases")) {
String owner = segments.get(1);
String repo = segments.get(2);
String tag = uri.getLastPathSegment();
if (tag != null && !repo.equalsIgnoreCase(tag)) {
if (TextUtils.isDigitsOnly(tag)) {
return ReleasesListActivity.getIntent(context, owner, repo, InputHelper.toLong(tag), isEnterprise);
} else {
return ReleasesListActivity.getIntent(context, owner, repo, tag, isEnterprise);
}
}
return ReleasesListActivity.getIntent(context, owner, repo);
}
return null;
}
return null;
}
@Nullable private static Intent getTrending(@NonNull Context context, @NonNull Uri uri) {
List<String> segments = uri.getPathSegments();
if (segments != null && !segments.isEmpty()) {
if (uri.getPathSegments().get(0).equals("trending")) {
String query = "";
String lang = "";
if (uri.getPathSegments().size() > 1) {
lang = uri.getPathSegments().get(1);
}
if (uri.getQueryParameterNames() != null && !uri.getQueryParameterNames().isEmpty()) {
query = uri.getQueryParameter("since");
}
return TrendingActivity.Companion.getTrendingIntent(context, lang, query);
}
return null;
}
return null;
}
/**
* https://github.com/owner/repo/issues/new
*/
@Nullable private static Intent getCreateIssueIntent(@NonNull Context context, @NonNull Uri uri) {
List<String> segments = uri.getPathSegments();
if (uri.getLastPathSegment() == null) return null;
if (segments == null || segments.size() < 3 || !uri.getLastPathSegment().equalsIgnoreCase("new")) return null;
if ("issues".equals(segments.get(2))) {
String owner = segments.get(0);
String repo = segments.get(1);
boolean isFeedback = "k0shk0sh/FastHub".equalsIgnoreCase(owner + "/" + repo);
return CreateIssueActivity.getIntent(context, owner, repo, isFeedback);
}
return null;
}
@Nullable private static Intent getGistFile(@NonNull Context context, @NonNull Uri uri) {
if (HOST_GISTS_RAW.equalsIgnoreCase(uri.getHost())) {
return CodeViewerActivity.createIntent(context, uri.toString(), uri.toString());
}
return null;
}
@Nullable private static Intent getSearchIntent(@NonNull Context context, @NonNull Uri uri) {
List<String> segments = uri.getPathSegments();
if (segments == null || segments.size() > 1) return null;
String search = segments.get(0);
if ("search".equalsIgnoreCase(search)) {
Uri encoded = Uri.parse(uri.toString().replace("utf8=%E2%9C%93&", ""));
String query = encoded.getQueryParameter("q");
Logger.e(encoded, query);
return SearchActivity.getIntent(context, query);
}
return null;
}
}
| 28,292 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
HtmlHelper.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/timeline/HtmlHelper.java | package com.fastaccess.provider.timeline;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import android.view.HapticFeedbackConstants;
import android.widget.PopupMenu;
import android.widget.TextView;
import com.fastaccess.R;
import com.fastaccess.helper.AppHelper;
import com.fastaccess.helper.PrefGetter;
import com.fastaccess.helper.ViewHelper;
import com.fastaccess.provider.scheme.SchemeParser;
import com.fastaccess.provider.timeline.handler.BetterLinkMovementExtended;
import com.fastaccess.provider.timeline.handler.DrawableHandler;
import com.fastaccess.provider.timeline.handler.EmojiHandler;
import com.fastaccess.provider.timeline.handler.HeaderHandler;
import com.fastaccess.provider.timeline.handler.HrHandler;
import com.fastaccess.provider.timeline.handler.ItalicHandler;
import com.fastaccess.provider.timeline.handler.LinkHandler;
import com.fastaccess.provider.timeline.handler.ListsHandler;
import com.fastaccess.provider.timeline.handler.MarginHandler;
import com.fastaccess.provider.timeline.handler.PreTagHandler;
import com.fastaccess.provider.timeline.handler.QuoteHandler;
import com.fastaccess.provider.timeline.handler.StrikethroughHandler;
import com.fastaccess.provider.timeline.handler.SubScriptHandler;
import com.fastaccess.provider.timeline.handler.SuperScriptHandler;
import com.fastaccess.provider.timeline.handler.TableHandler;
import com.fastaccess.provider.timeline.handler.UnderlineHandler;
import net.nightwhistler.htmlspanner.HtmlSpanner;
import net.nightwhistler.htmlspanner.handlers.BoldHandler;
/**
* Created by Kosh on 21 Apr 2017, 11:24 PM
*/
public class HtmlHelper {
public static void htmlIntoTextView(@NonNull TextView textView, @NonNull String html, int width) {
registerClickEvent(textView);
textView.setText(initHtml(textView, width).fromHtml(format(html).toString()));
}
private static void registerClickEvent(@NonNull TextView textView) {
BetterLinkMovementExtended betterLinkMovementMethod = BetterLinkMovementExtended.linkifyHtml(textView);
betterLinkMovementMethod.setOnLinkClickListener((view, url) -> {
SchemeParser.launchUri(view.getContext(), Uri.parse(url));
return true;
});
betterLinkMovementMethod.setOnLinkLongClickListener((view, url) -> {
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
PopupMenu menu = new PopupMenu(view.getContext(), view);
menu.setOnMenuItemClickListener(menuItem -> {
switch (menuItem.getItemId()) {
case R.id.copy:
AppHelper.copyToClipboard(view.getContext(), url);
return true;
case R.id.open:
SchemeParser.launchUri(view.getContext(), Uri.parse(url));
return true;
case R.id.open_new_window:
SchemeParser.launchUri(view.getContext(), Uri.parse(url), false, true);
return true;
default:
return false;
}
});
menu.inflate(R.menu.link_popup_menu);
menu.show();
return true;
});
}
private static HtmlSpanner initHtml(@NonNull TextView textView, int width) {
@PrefGetter.ThemeType int theme = PrefGetter.getThemeType();
@ColorInt int windowBackground = getWindowBackground(theme);
Drawable checked = ContextCompat.getDrawable(textView.getContext(), R.drawable.ic_checkbox_small);
Drawable unchecked = ContextCompat.getDrawable(textView.getContext(), R.drawable.ic_checkbox_empty_small);
HtmlSpanner mySpanner = new HtmlSpanner();
mySpanner.setStripExtraWhiteSpace(true);
mySpanner.registerHandler("pre", new PreTagHandler(windowBackground, true, theme));
mySpanner.registerHandler("code", new PreTagHandler(windowBackground, false, theme));
mySpanner.registerHandler("img", new DrawableHandler(textView, width));
mySpanner.registerHandler("g-emoji", new EmojiHandler());
mySpanner.registerHandler("blockquote", new QuoteHandler(windowBackground));
mySpanner.registerHandler("b", new BoldHandler());
mySpanner.registerHandler("strong", new BoldHandler());
mySpanner.registerHandler("i", new ItalicHandler());
mySpanner.registerHandler("em", new ItalicHandler());
mySpanner.registerHandler("ul", new MarginHandler());
mySpanner.registerHandler("ol", new MarginHandler());
mySpanner.registerHandler("li", new ListsHandler(checked, unchecked));
mySpanner.registerHandler("u", new UnderlineHandler());
mySpanner.registerHandler("strike", new StrikethroughHandler());
mySpanner.registerHandler("ins", new UnderlineHandler());
mySpanner.registerHandler("del", new StrikethroughHandler());
mySpanner.registerHandler("sub", new SubScriptHandler());
mySpanner.registerHandler("sup", new SuperScriptHandler());
mySpanner.registerHandler("a", new LinkHandler());
mySpanner.registerHandler("hr", new HrHandler(windowBackground, width, false));
mySpanner.registerHandler("emoji", new EmojiHandler());
mySpanner.registerHandler("mention", new LinkHandler());
mySpanner.registerHandler("h1", new HeaderHandler(1.5F));
mySpanner.registerHandler("h2", new HeaderHandler(1.4F));
mySpanner.registerHandler("h3", new HeaderHandler(1.3F));
mySpanner.registerHandler("h4", new HeaderHandler(1.2F));
mySpanner.registerHandler("h5", new HeaderHandler(1.1F));
mySpanner.registerHandler("h6", new HeaderHandler(1.0F));
if (width > 0) {
TableHandler tableHandler = new TableHandler();
tableHandler.setTextColor(ViewHelper.generateTextColor(windowBackground));
tableHandler.setTableWidth(width);
mySpanner.registerHandler("table", tableHandler);
}
return mySpanner;
}
@ColorInt public static int getWindowBackground(@PrefGetter.ThemeType int theme) {
if (theme == PrefGetter.AMLOD) {
return Color.parseColor("#0B162A");
} else if (theme == PrefGetter.BLUISH) {
return Color.parseColor("#111C2C");
} else if (theme == PrefGetter.DARK) {
return Color.parseColor("#22252A");
} else {
return Color.parseColor("#EEEEEE");
}
}
private static final String TOGGLE_START = "<span class=\"email-hidden-toggle\">";
private static final String TOGGLE_END = "</span>";
private static final String REPLY_START = "<div class=\"email-quoted-reply\">";
private static final String REPLY_END = "</div>";
private static final String SIGNATURE_START = "<div class=\"email-signature-reply\">";
private static final String SIGNATURE_END = "</div>";
private static final String HIDDEN_REPLY_START = "<div class=\"email-hidden-reply\" style=\" display:none\">";
private static final String HIDDEN_REPLY_END = "</div>";
private static final String BREAK = "<br>";
private static final String PARAGRAPH_START = "<p>";
private static final String PARAGRAPH_END = "</p>";
//https://github.com/k0shk0sh/GitHubSdk/blob/master/library/src/main/java/com/meisolsson/githubsdk/core/HtmlUtils.java
@NonNull public static CharSequence format(final String html) {
if (html == null || html.length() == 0) return "";
StringBuilder formatted = new StringBuilder(html);
strip(formatted, TOGGLE_START, TOGGLE_END);
strip(formatted, SIGNATURE_START, SIGNATURE_END);
strip(formatted, REPLY_START, REPLY_END);
strip(formatted, HIDDEN_REPLY_START, HIDDEN_REPLY_END);
if (replace(formatted, PARAGRAPH_START, BREAK)) replace(formatted, PARAGRAPH_END, BREAK);
trim(formatted);
return formatted;
}
private static void strip(final StringBuilder input, final String prefix, final String suffix) {
int start = input.indexOf(prefix);
while (start != -1) {
int end = input.indexOf(suffix, start + prefix.length());
if (end == -1)
end = input.length();
input.delete(start, end + suffix.length());
start = input.indexOf(prefix, start);
}
}
private static boolean replace(final StringBuilder input, final String from, final String to) {
int start = input.indexOf(from);
if (start == -1) return false;
final int fromLength = from.length();
final int toLength = to.length();
while (start != -1) {
input.replace(start, start + fromLength, to);
start = input.indexOf(from, start + toLength);
}
return true;
}
private static void trim(final StringBuilder input) {
int length = input.length();
int breakLength = BREAK.length();
while (length > 0) {
if (input.indexOf(BREAK) == 0) input.delete(0, breakLength);
else if (length >= breakLength && input.lastIndexOf(BREAK) == length - breakLength) input.delete(length - breakLength, length);
else if (Character.isWhitespace(input.charAt(0))) input.deleteCharAt(0);
else if (Character.isWhitespace(input.charAt(length - 1))) input.deleteCharAt(length - 1);
else break;
length = input.length();
}
}
}
| 9,683 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
TimelineProvider.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/timeline/TimelineProvider.java | package com.fastaccess.provider.timeline;
import android.content.Context;
import android.graphics.Color;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.text.style.BackgroundColorSpan;
import com.fastaccess.R;
import com.fastaccess.data.dao.LabelModel;
import com.fastaccess.data.dao.model.User;
import com.fastaccess.data.dao.timeline.GenericEvent;
import com.fastaccess.data.dao.timeline.SourceModel;
import com.fastaccess.data.dao.types.IssueEventType;
import com.fastaccess.helper.InputHelper;
import com.fastaccess.helper.ParseDateFormat;
import com.fastaccess.helper.PrefGetter;
import com.fastaccess.helper.ViewHelper;
import com.fastaccess.ui.widgets.SpannableBuilder;
import com.zzhoujay.markdown.style.CodeSpan;
import java.util.Date;
/**
* Created by Kosh on 20 Apr 2017, 7:18 PM
*/
public class TimelineProvider {
@NonNull public static SpannableBuilder getStyledEvents(@NonNull GenericEvent issueEventModel,
@NonNull Context context, boolean isMerged) {
IssueEventType event = issueEventModel.getEvent();
SpannableBuilder spannableBuilder = SpannableBuilder.builder();
Date date = issueEventModel.getCreatedAt() != null
? issueEventModel.getCreatedAt()
: issueEventModel.getAuthor() != null
? issueEventModel.getAuthor().getDate() : null;
if (event != null) {
String to = context.getString(R.string.to);
String from = context.getString(R.string.from);
String thisString = context.getString(R.string.this_value);
String in = context.getString(R.string.in_value);
if (event == IssueEventType.labeled || event == IssueEventType.unlabeled) {
spannableBuilder.bold(issueEventModel.getActor() != null ? issueEventModel.getActor().getLogin() : "anonymous");
spannableBuilder.append(" ").append(event.name().replaceAll("_", " "));
LabelModel labelModel = issueEventModel.getLabel();
int color = Color.parseColor("#" + labelModel.getColor());
spannableBuilder.append(" ").append(" " + labelModel.getName() + " ", new CodeSpan(color, ViewHelper.generateTextColor(color), 5));
spannableBuilder.append(" ").append(getDate(issueEventModel.getCreatedAt()));
} else if (event == IssueEventType.committed) {
spannableBuilder.append(issueEventModel.getMessage().replaceAll("\n", " "))
.append(" ")
.url(substring(issueEventModel.getSha()));
} else {
User user = null;
if (issueEventModel.getAssignee() != null && issueEventModel.getAssigner() != null) {
user = issueEventModel.getAssigner();
} else if (issueEventModel.getActor() != null) {
user = issueEventModel.getActor();
} else if (issueEventModel.getAuthor() != null) {
user = issueEventModel.getAuthor();
}
if (user != null) {
spannableBuilder.bold(user.getLogin());
}
if ((event == IssueEventType.review_requested || (event == IssueEventType.review_dismissed ||
event == IssueEventType.review_request_removed)) && user != null) {
appendReviews(issueEventModel, event, spannableBuilder, from, issueEventModel.getReviewRequester());
} else if (event == IssueEventType.closed || event == IssueEventType.reopened) {
if (isMerged) {
spannableBuilder.append(" ").append(IssueEventType.merged.name());
} else {
spannableBuilder
.append(" ")
.append(event.name().replaceAll("_", " "))
.append(" ")
.append(thisString);
}
if (issueEventModel.getCommitId() != null) {
spannableBuilder
.append(" ")
.append(in)
.append(" ")
.url(substring(issueEventModel.getCommitId()));
}
} else if (event == IssueEventType.assigned || event == IssueEventType.unassigned) {
spannableBuilder
.append(" ");
if ((user != null && issueEventModel.getAssignee() != null) && user.getLogin()
.equalsIgnoreCase(issueEventModel.getAssignee().getLogin())) {
spannableBuilder
.append(event == IssueEventType.assigned ? "self-assigned this" : "removed their assignment");
} else {
spannableBuilder
.append(event == IssueEventType.assigned ? "assigned" : "unassigned");
spannableBuilder
.append(" ")
.bold(issueEventModel.getAssignee() != null ? issueEventModel.getAssignee().getLogin() : "");
}
} else if (event == IssueEventType.locked || event == IssueEventType.unlocked) {
spannableBuilder
.append(" ")
.append(event == IssueEventType.locked ? "locked and limited conversation to collaborators" : "unlocked this " +
"conversation");
} else if (event == IssueEventType.head_ref_deleted || event == IssueEventType.head_ref_restored) {
spannableBuilder.append(" ").append(event.name().replaceAll("_", " "),
new BackgroundColorSpan(HtmlHelper.getWindowBackground(PrefGetter.getThemeType())));
} else if (event == IssueEventType.milestoned || event == IssueEventType.demilestoned) {
spannableBuilder.append(" ")
.append(event == IssueEventType.milestoned ? "added this to the" : "removed this from the")
.append(" ")
.bold(issueEventModel.getMilestone().getTitle())
.append(" ")
.append("milestone");
} else if (event == IssueEventType.deployed) {
spannableBuilder.append(" ")
.bold("deployed");
} else {
spannableBuilder.append(" ").append(event.name().replaceAll("_", " "));
}
if (event == IssueEventType.renamed) {
spannableBuilder
.append(" ")
.append(from)
.append(" ")
.bold(issueEventModel.getRename().getFromValue())
.append(" ")
.append(to)
.append(" ")
.bold(issueEventModel.getRename().getToValue());
} else if (event == IssueEventType.referenced || event == IssueEventType.merged) {
spannableBuilder
.append(" ")
.append("commit")
.append(" ")
.url(substring(issueEventModel.getCommitId()));
} else if (event == IssueEventType.cross_referenced) {
SourceModel sourceModel = issueEventModel.getSource();
if (sourceModel != null) {
String type = sourceModel.getType();
SpannableBuilder title = SpannableBuilder.builder();
if (sourceModel.getPullRequest() != null) {
if (sourceModel.getIssue() != null) title.url("#" + sourceModel.getIssue().getNumber());
type = "pull request";
} else if (sourceModel.getIssue() != null) {
title.url("#" + sourceModel.getIssue().getNumber());
} else if (sourceModel.getCommit() != null) {
title.url(substring(sourceModel.getCommit().getSha()));
} else if (sourceModel.getRepository() != null) {
title.url(sourceModel.getRepository().getName());
}
if (!InputHelper.isEmpty(title)) {
spannableBuilder.append(" ")
.append(thisString)
.append(" in ")
.append(type)
.append(" ")
.append(title);
}
}
}
spannableBuilder.append(" ").append(getDate(date));
}
}
return spannableBuilder;
}
private static void appendReviews(@NonNull GenericEvent issueEventModel, @NonNull IssueEventType event,
@NonNull SpannableBuilder spannableBuilder, @NonNull String from,
@NonNull User user) {
spannableBuilder.append(" ");
User reviewer = issueEventModel.getRequestedReviewer();
if (reviewer != null && user.getLogin().equalsIgnoreCase(reviewer.getLogin())) {
spannableBuilder
.append(event == IssueEventType.review_requested
? "self-requested a review" : "removed their request for review");
} else {
spannableBuilder
.append(event == IssueEventType.review_requested ? "Requested a review" : "dismissed the review")
.append(" ")
.append(reviewer != null && !reviewer.getLogin().equalsIgnoreCase(user.getLogin()) ? from : " ")
.append(reviewer != null && !reviewer.getLogin().equalsIgnoreCase(user.getLogin()) ? " " : "");
}
if (issueEventModel.getRequestedTeam() != null) {
String name = !InputHelper.isEmpty(issueEventModel.getRequestedTeam().getName())
? issueEventModel.getRequestedTeam().getName() : issueEventModel.getRequestedTeam().getSlug();
spannableBuilder
.bold(name)
.append(" ")
.append("team");
} else if (reviewer != null && !user.getLogin().equalsIgnoreCase(reviewer.getLogin())) {
spannableBuilder.bold(issueEventModel.getRequestedReviewer().getLogin());
}
}
@NonNull private static CharSequence getDate(@Nullable Date date) {
return ParseDateFormat.getTimeAgo(date);
}
@NonNull private static String substring(@Nullable String value) {
if (value == null) {
return "";
}
if (value.length() <= 7) return value;
else return value.substring(0, 7);
}
}
| 11,388 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
CommentsHelper.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/timeline/CommentsHelper.java | package com.fastaccess.provider.timeline;
import android.view.View;
import android.widget.TextView;
import com.annimon.stream.Collectors;
import com.annimon.stream.Stream;
import com.fastaccess.data.dao.ReactionsModel;
import com.fastaccess.data.dao.TimelineModel;
import com.fastaccess.data.dao.model.Comment;
import com.fastaccess.data.dao.types.ReactionTypes;
import com.fastaccess.ui.widgets.SpannableBuilder;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
/**
* Created by Kosh on 30 Mar 2017, 6:44 PM
*/
public class CommentsHelper {
private static final int LAUGH = 0x1F601;
private static final int SAD = 0x1F615;
private static final int THUMBS_UP = 0x1f44d;
private static final int THUMBS_DOWN = 0x1f44e;
private static final int HOORAY = 0x1f389;
private static final int HEART = 0x2764;
private static final int ROCKET = 0x1f680;
private static final int EYES = 0x1f440;
public static boolean isOwner(@NonNull String currentLogin, @NonNull String repoOwner, @NonNull String commentUser) {
return currentLogin.equalsIgnoreCase(repoOwner) || currentLogin.equalsIgnoreCase(commentUser);
}
private static String getEmojiByUnicode(int unicode) {
return new String(Character.toChars(unicode));
}
public static String getEmoji(@NonNull ReactionTypes reactionTypes) {
switch (reactionTypes) {
case HEART:
return getHeart();
case HOORAY:
return getHooray();
case MINUS_ONE:
return getThumbsDown();
case CONFUSED:
return getSad();
case LAUGH:
return getLaugh();
case ROCKET:
return getRocket();
case EYES:
return getEyes();
default:
return getThumbsUp();
}
}
public static String getLaugh() {
return getEmojiByUnicode(LAUGH);
}
public static String getSad() {
return getEmojiByUnicode(SAD);
}
public static String getThumbsUp() {
return getEmojiByUnicode(THUMBS_UP);
}
public static String getThumbsDown() {
return getEmojiByUnicode(THUMBS_DOWN);
}
public static String getHooray() {
return getEmojiByUnicode(HOORAY);
}
public static String getHeart() {
return getEmojiByUnicode(HEART);
}
public static String getRocket() {
return getEmojiByUnicode(ROCKET);
}
public static String getEyes() {
return getEmojiByUnicode(EYES);
}
@NonNull public static ArrayList<String> getUsers(@NonNull List<Comment> comments) {
return Stream.of(comments)
.filter(comment -> comment.getUser() != null)
.map(comment -> comment.getUser().getLogin())
.distinct()
.collect(Collectors.toCollection(ArrayList::new));
}
@NonNull public static ArrayList<String> getUsersByTimeline(@NonNull List<TimelineModel> comments) {
return Stream.of(comments)
.filter(timelineModel -> timelineModel.getComment() != null && timelineModel.getComment().getUser() != null)
.map(comment -> comment.getComment().getUser().getLogin())
.distinct()
.collect(Collectors.toCollection(ArrayList::new));
}
public static void appendEmojies(
@NonNull ReactionsModel reaction, @NonNull TextView thumbsUp,
@NonNull TextView thumbsUpReaction, @NonNull TextView thumbsDown,
@NonNull TextView thumbsDownReaction, @NonNull TextView hurray,
@NonNull TextView hurrayReaction, @NonNull TextView sad,
@NonNull TextView sadReaction, @NonNull TextView laugh,
@NonNull TextView laughReaction, @NonNull TextView heart,
@NonNull TextView heartReaction, @NonNull TextView rocket,
@NonNull TextView rocketReaction, @NonNull TextView eye,
@NonNull TextView eyeReaction, @NonNull View reactionsList
) {
SpannableBuilder spannableBuilder = SpannableBuilder.builder()
.append(CommentsHelper.getThumbsUp()).append(" ")
.append(String.valueOf(reaction.getPlusOne()))
.append(" ");
thumbsUp.setText(spannableBuilder);
thumbsUpReaction.setText(spannableBuilder);
thumbsUpReaction.setVisibility(reaction.getPlusOne() > 0 ? View.VISIBLE : View.GONE);
spannableBuilder = SpannableBuilder.builder()
.append(CommentsHelper.getThumbsDown()).append(" ")
.append(String.valueOf(reaction.getMinusOne()))
.append(" ");
thumbsDown.setText(spannableBuilder);
thumbsDownReaction.setText(spannableBuilder);
thumbsDownReaction.setVisibility(reaction.getMinusOne() > 0 ? View.VISIBLE : View.GONE);
spannableBuilder = SpannableBuilder.builder()
.append(CommentsHelper.getHooray()).append(" ")
.append(String.valueOf(reaction.getHooray()))
.append(" ");
hurray.setText(spannableBuilder);
hurrayReaction.setText(spannableBuilder);
hurrayReaction.setVisibility(reaction.getHooray() > 0 ? View.VISIBLE : View.GONE);
spannableBuilder = SpannableBuilder.builder()
.append(CommentsHelper.getSad()).append(" ")
.append(String.valueOf(reaction.getConfused()))
.append(" ");
sad.setText(spannableBuilder);
sadReaction.setText(spannableBuilder);
sadReaction.setVisibility(reaction.getConfused() > 0 ? View.VISIBLE : View.GONE);
spannableBuilder = SpannableBuilder.builder()
.append(CommentsHelper.getLaugh()).append(" ")
.append(String.valueOf(reaction.getLaugh()))
.append(" ");
laugh.setText(spannableBuilder);
laughReaction.setText(spannableBuilder);
laughReaction.setVisibility(reaction.getLaugh() > 0 ? View.VISIBLE : View.GONE);
spannableBuilder = SpannableBuilder.builder()
.append(CommentsHelper.getHeart()).append(" ")
.append(String.valueOf(reaction.getHeart()))
.append(" ");
heart.setText(spannableBuilder);
heartReaction.setText(spannableBuilder);
heartReaction.setVisibility(reaction.getHeart() > 0 ? View.VISIBLE : View.GONE);
spannableBuilder = SpannableBuilder.builder()
.append(CommentsHelper.getRocket()).append(" ")
.append(String.valueOf(reaction.getRocket()))
.append(" ");
rocket.setText(spannableBuilder);
rocketReaction.setText(spannableBuilder);
rocketReaction.setVisibility(reaction.getRocket() > 0 ? View.VISIBLE : View.GONE);
spannableBuilder = SpannableBuilder.builder()
.append(CommentsHelper.getEyes()).append(" ")
.append(String.valueOf(reaction.getEyes()));
eye.setText(spannableBuilder);
eyeReaction.setText(spannableBuilder);
eyeReaction.setVisibility(reaction.getEyes() > 0 ? View.VISIBLE : View.GONE);
if (reaction.getPlusOne() > 0 || reaction.getMinusOne() > 0
|| reaction.getLaugh() > 0 || reaction.getHooray() > 0
|| reaction.getConfused() > 0 || reaction.getHeart() > 0) {
reactionsList.setVisibility(View.VISIBLE);
reactionsList.setTag(true);
} else {
reactionsList.setVisibility(View.GONE);
reactionsList.setTag(false);
}
}
}
| 7,700 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
ReactionsProvider.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/timeline/ReactionsProvider.java | package com.fastaccess.provider.timeline;
import androidx.annotation.IdRes;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.fastaccess.data.dao.PostReactionModel;
import com.fastaccess.data.dao.ReactionsModel;
import com.fastaccess.data.dao.types.ReactionTypes;
import com.fastaccess.helper.InputHelper;
import com.fastaccess.helper.RxHelper;
import com.fastaccess.provider.rest.RestProvider;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.LinkedHashMap;
import java.util.Map;
import io.reactivex.Observable;
/**
* Created by Kosh on 09 Apr 2017, 10:40 AM
*/
public class ReactionsProvider {
public static final int HEADER = 0;
public static final int COMMENT = 1;
public static final int REVIEW_COMMENT = 2;
public static final int COMMIT = 3;
@IntDef({
HEADER,
COMMENT,
REVIEW_COMMENT,
COMMIT
})
@Retention(RetentionPolicy.SOURCE) public @interface ReactionType {}
private Map<Long, ReactionsModel> reactionsMap = new LinkedHashMap<>();
@Nullable public Observable onHandleReaction(@IdRes int viewId, long idOrNumber, @Nullable String login,
@Nullable String repoId, @ReactionType int reactionType, boolean isEnterprise) {
if (!InputHelper.isEmpty(login) && !InputHelper.isEmpty(repoId)) {
if (!isPreviouslyReacted(idOrNumber, viewId)) {
ReactionTypes reactionTypes = ReactionTypes.get(viewId);
if (reactionTypes != null) {
Observable<ReactionsModel> observable = null;
switch (reactionType) {
case COMMENT:
observable = RestProvider.getReactionsService(isEnterprise)
.postIssueCommentReaction(new PostReactionModel(reactionTypes.getPostContent()), login, repoId, idOrNumber);
break;
case HEADER:
observable = RestProvider.getReactionsService(isEnterprise)
.postIssueReaction(new PostReactionModel(reactionTypes.getPostContent()), login, repoId, idOrNumber);
break;
case REVIEW_COMMENT:
observable = RestProvider.getReactionsService(isEnterprise)
.postCommentReviewReaction(new PostReactionModel(reactionTypes.getPostContent()), login, repoId, idOrNumber);
break;
case COMMIT:
observable = RestProvider.getReactionsService(isEnterprise)
.postCommitReaction(new PostReactionModel(reactionTypes.getPostContent()), login, repoId, idOrNumber);
break;
}
if (observable == null) return null;
return RxHelper.safeObservable(observable)
.doOnNext(response -> getReactionsMap().put(idOrNumber, response));
}
} else {
ReactionsModel reactionsModel = getReactionsMap().get(idOrNumber);
if (reactionsModel != null) {
return RxHelper.safeObservable(RestProvider.getReactionsService(isEnterprise).delete(reactionsModel.getId()))
.doOnNext(booleanResponse -> {
if (booleanResponse.code() == 204) {
getReactionsMap().remove(idOrNumber);
}
});
}
}
}
return null;
}
public boolean isPreviouslyReacted(long idOrNumber, @IdRes int vId) {
ReactionsModel reactionsModel = getReactionsMap().get(idOrNumber);
if (reactionsModel == null || InputHelper.isEmpty(reactionsModel.getContent())) {
return false;
}
ReactionTypes type = ReactionTypes.get(vId);
return type != null && (type.getContent().equals(reactionsModel.getContent()) || type.getPostContent().equals(reactionsModel.getContent()));
}
public boolean isCallingApi(long id, int vId) {
ReactionsModel reactionsModel = getReactionsMap().get(id);
if (reactionsModel == null || InputHelper.isEmpty(reactionsModel.getContent())) {
return false;
}
ReactionTypes type = ReactionTypes.get(vId);
return type != null && (type.getContent().equals(reactionsModel.getContent()) || type.getPostContent().equals(reactionsModel.getContent()))
&& reactionsModel.isCallingApi();
}
@NonNull private Map<Long, ReactionsModel> getReactionsMap() {
return reactionsMap;
}
}
| 4,941 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
SuperScriptHandler.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/timeline/handler/SuperScriptHandler.java | package com.fastaccess.provider.timeline.handler;
import android.text.SpannableStringBuilder;
import android.text.style.RelativeSizeSpan;
import android.text.style.SuperscriptSpan;
import net.nightwhistler.htmlspanner.TagNodeHandler;
import org.htmlcleaner.TagNode;
public class SuperScriptHandler extends TagNodeHandler {
@Override public void handleTagNode(TagNode node, SpannableStringBuilder builder, int start, int end) {
builder.setSpan(new SuperscriptSpan(), start, end, 33);
builder.setSpan(new RelativeSizeSpan(0.8f), start, end, 33);
}
} | 577 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
UnderlineHandler.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/timeline/handler/UnderlineHandler.java | package com.fastaccess.provider.timeline.handler;
import android.text.SpannableStringBuilder;
import android.text.style.UnderlineSpan;
import net.nightwhistler.htmlspanner.TagNodeHandler;
import org.htmlcleaner.TagNode;
public class UnderlineHandler extends TagNodeHandler {
@Override public void handleTagNode(TagNode tagNode, SpannableStringBuilder spannableStringBuilder, int start, int end) {
spannableStringBuilder.setSpan(new UnderlineSpan(), start, end, 33);
}
} | 490 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
SubScriptHandler.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/timeline/handler/SubScriptHandler.java | package com.fastaccess.provider.timeline.handler;
import android.text.SpannableStringBuilder;
import android.text.style.RelativeSizeSpan;
import android.text.style.SubscriptSpan;
import net.nightwhistler.htmlspanner.TagNodeHandler;
import org.htmlcleaner.TagNode;
public class SubScriptHandler extends TagNodeHandler {
@Override public void handleTagNode(TagNode node, SpannableStringBuilder builder, int start, int end) {
builder.setSpan(new SubscriptSpan(), start, end, 33);
builder.setSpan(new RelativeSizeSpan(0.8f), start, end, 33);
}
} | 570 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
StrikethroughHandler.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/timeline/handler/StrikethroughHandler.java | package com.fastaccess.provider.timeline.handler;
import android.text.SpannableStringBuilder;
import android.text.style.StrikethroughSpan;
import net.nightwhistler.htmlspanner.TagNodeHandler;
import org.htmlcleaner.TagNode;
public class StrikethroughHandler extends TagNodeHandler {
@Override public void handleTagNode(TagNode node, SpannableStringBuilder builder, int start, int end) {
builder.setSpan(new StrikethroughSpan(), start, end, 33);
}
} | 470 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
HrHandler.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/timeline/handler/HrHandler.java | package com.fastaccess.provider.timeline.handler;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import net.nightwhistler.htmlspanner.TagNodeHandler;
import net.nightwhistler.htmlspanner.spans.CenterSpan;
import org.htmlcleaner.TagNode;
import lombok.AllArgsConstructor;
/**
* Created by kosh on 30/07/2017.
*/
@AllArgsConstructor public class HrHandler extends TagNodeHandler {
private final int color;
private final int width;
private final boolean isHeader;
@Override public void handleTagNode(TagNode tagNode, SpannableStringBuilder spannableStringBuilder, int i, int i1) {
spannableStringBuilder.append("\n");
SpannableStringBuilder builder = new SpannableStringBuilder("$");
HrSpan hrSpan = new HrSpan(color, width);
builder.setSpan(hrSpan, 0, builder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.setSpan(new CenterSpan(), 0, builder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.append("\n");
spannableStringBuilder.append(builder);
}
}
| 1,072 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
CodeBackgroundRoundedSpan.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/timeline/handler/CodeBackgroundRoundedSpan.java | package com.fastaccess.provider.timeline.handler;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.text.Layout;
import android.text.TextPaint;
import android.text.style.LeadingMarginSpan;
import android.text.style.LineBackgroundSpan;
import android.text.style.MetricAffectingSpan;
public class CodeBackgroundRoundedSpan extends MetricAffectingSpan implements LeadingMarginSpan, LineBackgroundSpan {
private final int color;
private final RectF rect = new RectF();
CodeBackgroundRoundedSpan(int color) {
this.color = color;
}
@Override public void updateMeasureState(TextPaint paint) {
apply(paint);
}
@Override public void updateDrawState(TextPaint paint) {
apply(paint);
}
private void apply(TextPaint paint) {
paint.setTypeface(Typeface.MONOSPACE);
}
@Override public void drawBackground(Canvas c, Paint p, int left, int right, int top, int baseline, int bottom,
CharSequence text, int start, int end, int lnum) {
Paint.Style style = p.getStyle();
int color = p.getColor();
p.setStyle(Paint.Style.FILL);
p.setColor(this.color);
rect.set(left, top, right, bottom);
c.drawRect(rect, p);
p.setColor(color);
p.setStyle(style);
}
@Override public int getLeadingMargin(boolean first) {
return 30;
}
@Override public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom,
CharSequence text, int start, int end, boolean first, Layout layout) {}
} | 1,731 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
TableHandler.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/timeline/handler/TableHandler.java | package com.fastaccess.provider.timeline.handler;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PixelFormat;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import androidx.annotation.NonNull;
import android.text.Layout.Alignment;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.style.AlignmentSpan;
import android.text.style.ImageSpan;
import net.nightwhistler.htmlspanner.TagNodeHandler;
import org.htmlcleaner.TagNode;
import java.util.ArrayList;
import java.util.List;
/**
* Handles simple HTML tables.
* <p>
* Since it renders these tables itself, it needs to know things like font size
* and text colour to use.
*
* @author Alex Kuiper
*/
public class TableHandler extends TagNodeHandler {
private int tableWidth = 500;
private Typeface typeFace = Typeface.DEFAULT;
private float textSize = 28f;
private int textColor = Color.BLACK;
private static final int PADDING = 20;
@Override public boolean rendersContent() {
return true;
}
@Override public void handleTagNode(TagNode node, SpannableStringBuilder builder, int start, int end) {
Table table = getTable(node);
for (int i = 0; i < table.getRows().size(); i++) {
List<Spanned> row = table.getRows().get(i);
builder.append("\uFFFC");
TableRowDrawable drawable = new TableRowDrawable(row, table.isDrawBorder());
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
builder.setSpan(new ImageSpan(drawable), start + i, builder.length(), 33);
}
builder.append("\uFFFC");
Drawable drawable = new TableRowDrawable(new ArrayList<Spanned>(), table.isDrawBorder());
drawable.setBounds(0, 0, tableWidth, 1);
builder.setSpan(new ImageSpan(drawable), builder.length() - 1, builder.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.setSpan((AlignmentSpan) () -> Alignment.ALIGN_CENTER, start, builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.append("\n");
}
public void setTableWidth(int tableWidth) {
this.tableWidth = tableWidth;
}
public void setTextColor(int textColor) {
this.textColor = textColor;
}
private void readNode(Object node, Table table) {
if (node instanceof TagNode) {
TagNode tagNode = (TagNode) node;
if (tagNode.getName().equals("td") || tagNode.getName().equals("th")) {
Spanned result = this.getSpanner().fromTagNode(tagNode);
table.addCell(result);
return;
}
if (tagNode.getName().equals("tr")) {
table.addRow();
}
for (Object child : tagNode.getChildTags()) {
readNode(child, table);
}
}
}
private Table getTable(TagNode node) {
String border = node.getAttributeByName("border");
boolean drawBorder = !"0".equals(border);
Table result = new Table(drawBorder);
readNode(node, result);
return result;
}
private TextPaint getTextPaint() {
TextPaint textPaint = new TextPaint();
textPaint.setColor(this.textColor);
textPaint.linkColor = this.textColor;
textPaint.setAntiAlias(true);
textPaint.setTextSize(this.textSize);
textPaint.setTypeface(this.typeFace);
return textPaint;
}
private int calculateRowHeight(List<Spanned> row) {
if (row.size() == 0) {
return 0;
}
TextPaint textPaint = getTextPaint();
int columnWidth = tableWidth / row.size();
int rowHeight = 0;
for (Spanned cell : row) {
StaticLayout layout = new StaticLayout(cell, textPaint, columnWidth
- 2 * PADDING, Alignment.ALIGN_NORMAL, 1.5f, 0.5f, true);
if (layout.getHeight() > rowHeight) {
rowHeight = layout.getHeight();
}
}
return rowHeight;
}
private class TableRowDrawable extends Drawable {
private List<Spanned> tableRow;
private int rowHeight;
private boolean paintBorder;
TableRowDrawable(List<Spanned> tableRow, boolean paintBorder) {
this.tableRow = tableRow;
this.rowHeight = calculateRowHeight(tableRow);
this.paintBorder = paintBorder;
}
@Override public void draw(@NonNull Canvas canvas) {
Paint paint = new Paint();
paint.setColor(textColor);
paint.setStyle(Style.STROKE);
int numberOfColumns = tableRow.size();
if (numberOfColumns == 0) {
return;
}
int columnWidth = tableWidth / numberOfColumns;
int offset;
for (int i = 0; i < numberOfColumns; i++) {
offset = i * columnWidth;
if (paintBorder) {
// The rect is open at the bottom, so there's a single line
// between rows.
canvas.drawRect(offset, 0, offset + columnWidth, rowHeight, paint);
}
StaticLayout layout = new StaticLayout(tableRow.get(i),
getTextPaint(), (columnWidth - 2 * PADDING),
Alignment.ALIGN_NORMAL, 1.5f, 0.5f, true);
canvas.translate(offset + PADDING, 0);
layout.draw(canvas);
canvas.translate(-1 * (offset + PADDING), 0);
}
}
@Override
public int getIntrinsicHeight() {
return rowHeight;
}
@Override
public int getIntrinsicWidth() {
return tableWidth;
}
@Override
public int getOpacity() {
return PixelFormat.OPAQUE;
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter cf) {
}
}
private class Table {
private boolean drawBorder;
private List<List<Spanned>> content = new ArrayList<>();
private Table(boolean drawBorder) {
this.drawBorder = drawBorder;
}
boolean isDrawBorder() {
return drawBorder;
}
void addRow() {
content.add(new ArrayList<>());
}
List<Spanned> getBottomRow() {
return content.get(content.size() - 1);
}
List<List<Spanned>> getRows() {
return content;
}
void addCell(Spanned text) {
if (content.isEmpty()) {
throw new IllegalStateException("No rows added yet");
}
getBottomRow().add(text);
}
}
} | 7,163 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
LinkHandler.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/timeline/handler/LinkHandler.java | package com.fastaccess.provider.timeline.handler;
import android.graphics.Color;
import android.text.SpannableStringBuilder;
import com.zzhoujay.markdown.style.LinkSpan;
import net.nightwhistler.htmlspanner.TagNodeHandler;
import org.htmlcleaner.TagNode;
/**
* Created by Kosh on 10 May 2017, 8:46 PM
*/
public class LinkHandler extends TagNodeHandler {
private final static int linkColor = Color.parseColor("#4078C0");
@Override public void handleTagNode(TagNode node, SpannableStringBuilder spannableStringBuilder, int start, int end) {
String href = node.getAttributeByName("href");
if (href != null) {
spannableStringBuilder.setSpan(new LinkSpan(href, linkColor), start, end, 33);
} else if (node.getText() != null) {
spannableStringBuilder.setSpan(new LinkSpan("https://github.com/" + node.getText().toString(), linkColor), start, end, 33);
}
}
}
| 929 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
ItalicHandler.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/timeline/handler/ItalicHandler.java | package com.fastaccess.provider.timeline.handler;
import android.graphics.Typeface;
import android.text.SpannableStringBuilder;
import com.zzhoujay.markdown.style.FontSpan;
import net.nightwhistler.htmlspanner.TagNodeHandler;
import org.htmlcleaner.TagNode;
/**
* Created by Kosh on 06 May 2017, 11:02 AM
*/
public class ItalicHandler extends TagNodeHandler {
public void handleTagNode(TagNode node, SpannableStringBuilder builder, int start, int end) {
builder.setSpan(new FontSpan(1, Typeface.ITALIC), start, builder.length(), 33);
}
} | 562 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
ListsHandler.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/timeline/handler/ListsHandler.java | package com.fastaccess.provider.timeline.handler;
import android.graphics.drawable.Drawable;
import androidx.annotation.Nullable;
import android.text.SpannableStringBuilder;
import com.fastaccess.helper.Logger;
import com.fastaccess.ui.widgets.SpannableBuilder;
import net.nightwhistler.htmlspanner.TagNodeHandler;
import org.htmlcleaner.TagNode;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
@NoArgsConstructor @AllArgsConstructor public class ListsHandler extends TagNodeHandler {
@Nullable private Drawable checked;
@Nullable private Drawable unchecked;
private int getMyIndex(TagNode node) {
if (node.getParent() == null) {
return -1;
} else {
int i = 1;
for (Object child : node.getParent().getChildren()) {
if (child == node) {
return i;
}
if (child instanceof TagNode) {
TagNode childNode = (TagNode) child;
if ("li".equals(childNode.getName())) {
++i;
}
}
}
return -1;
}
}
private String getParentName(TagNode node) {
return node.getParent() == null ? null : node.getParent().getName();
}
@Override public void beforeChildren(TagNode node, SpannableStringBuilder builder) {
TodoItems todoItem = null;
if (node.getChildTags() != null && node.getChildTags().length > 0) {
for (TagNode tagNode : node.getChildTags()) {
Logger.e(tagNode.getName(), tagNode.getText());
if (tagNode.getName() != null && tagNode.getName().equals("input")) {
todoItem = new TodoItems();
todoItem.isChecked = tagNode.getAttributeByName("checked") != null;
break;
}
}
}
if ("ol".equals(getParentName(node))) {
builder.append(String.valueOf(getMyIndex(node))).append(". ");
} else if ("ul".equals(getParentName(node))) {
if (todoItem != null) {
if (checked == null || unchecked == null) {
builder.append(todoItem.isChecked ? "☑" : "☐");
} else {
builder.append(SpannableBuilder.builder()
.append(todoItem.isChecked ? checked : unchecked))
.append(" ");
}
} else {
builder.append("\u2022 ");
}
}
}
@Override public void handleTagNode(TagNode tagNode, SpannableStringBuilder spannableStringBuilder, int i, int i1) {
appendNewLine(spannableStringBuilder);
}
static class TodoItems {
boolean isChecked;
}
}
| 2,832 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
BetterLinkMovementExtended.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/timeline/handler/BetterLinkMovementExtended.java | package com.fastaccess.provider.timeline.handler;
import android.content.Context;
import android.graphics.RectF;
import android.text.Layout;
import android.text.Selection;
import android.text.Spannable;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.BackgroundColorSpan;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by Kosh on 23 Apr 2017, 12:09 PM
* <p>
* credit to to https://github.com/Saketme/Better-Link-Movement-Method
*/
public class BetterLinkMovementExtended extends LinkMovementMethod {
private static final Class SPAN_CLASS = ClickableSpan.class;
private static final int LINKIFY_NONE = -2;
private BetterLinkMovementExtended.OnLinkClickListener onLinkClickListener;
private BetterLinkMovementExtended.OnLinkLongClickListener onLinkLongClickListener;
private final RectF touchedLineBounds = new RectF();
private boolean isUrlHighlighted;
private boolean touchStartedOverLink;
private int activeTextViewHashcode;
private final GestureDetector gestureDetector;
private final LinkClickGestureListener clickGestureListener = new LinkClickGestureListener();
private BetterLinkMovementExtended(Context context) {
gestureDetector = new GestureDetector(context, clickGestureListener);
}
private final class LinkClickGestureListener extends GestureDetector.SimpleOnGestureListener {
private GestureDetector.SimpleOnGestureListener listener = null;
@Override public boolean onDown(MotionEvent e) {
if(listener != null) listener.onDown(e);
return true;
}
@Override public boolean onSingleTapUp(MotionEvent e) {
return listener == null || listener.onSingleTapUp(e);
}
@Override public void onLongPress(MotionEvent e) {
if(listener != null) listener.onLongPress(e);
}
}
private static BetterLinkMovementExtended linkify(int linkifyMask, TextView textView) {
BetterLinkMovementExtended movementMethod = new BetterLinkMovementExtended(textView.getContext());
addLinks(linkifyMask, movementMethod, textView);
return movementMethod;
}
public static BetterLinkMovementExtended linkifyHtml(TextView textView) {
return linkify(LINKIFY_NONE, textView);
}
private static BetterLinkMovementExtended linkify(int linkifyMask, ViewGroup viewGroup) {
BetterLinkMovementExtended movementMethod = new BetterLinkMovementExtended(viewGroup.getContext());
rAddLinks(linkifyMask, viewGroup, movementMethod);
return movementMethod;
}
public static BetterLinkMovementExtended linkifyHtml(ViewGroup viewGroup) {
return linkify(LINKIFY_NONE, viewGroup);
}
public void setOnLinkClickListener(OnLinkClickListener onLinkClickListener) {
this.onLinkClickListener = onLinkClickListener;
}
public void setOnLinkLongClickListener(OnLinkLongClickListener onLinkLongClickListener) {
this.onLinkLongClickListener = onLinkLongClickListener;
}
private static void rAddLinks(int linkifyMask, ViewGroup viewGroup, BetterLinkMovementExtended movementMethod) {
for (int i = 0; i < viewGroup.getChildCount(); ++i) {
View child = viewGroup.getChildAt(i);
if (child instanceof ViewGroup) {
rAddLinks(linkifyMask, (ViewGroup) child, movementMethod);
} else if (child instanceof TextView) {
TextView textView = (TextView) child;
addLinks(linkifyMask, movementMethod, textView);
}
}
}
private static void addLinks(int linkifyMask, BetterLinkMovementExtended movementMethod, TextView textView) {
textView.setMovementMethod(movementMethod);
if (linkifyMask != LINKIFY_NONE) {
Linkify.addLinks(textView, linkifyMask);
}
}
public boolean onTouchEvent(TextView view, Spannable text, MotionEvent event) {
if (this.activeTextViewHashcode != view.hashCode()) {
this.activeTextViewHashcode = view.hashCode();
view.setAutoLinkMask(0);
}
BetterLinkMovementExtended.ClickableSpanWithText touchedClickableSpan = this.findClickableSpanUnderTouch(view, text, event);
if (touchedClickableSpan != null) {
this.highlightUrl(view, touchedClickableSpan, text);
} else {
this.removeUrlHighlightColor(view);
}
clickGestureListener.listener = new GestureDetector.SimpleOnGestureListener() {
@Override public boolean onDown(MotionEvent e) {
touchStartedOverLink = touchedClickableSpan != null;
return true;
}
@Override public boolean onSingleTapUp(MotionEvent e) {
if (touchedClickableSpan != null && touchStartedOverLink) {
dispatchUrlClick(view, touchedClickableSpan);
removeUrlHighlightColor(view);
}
touchStartedOverLink = false;
return true;
}
@Override public void onLongPress(MotionEvent e) {
if (touchedClickableSpan != null && touchStartedOverLink) {
dispatchUrlLongClick(view, touchedClickableSpan);
removeUrlHighlightColor(view);
}
touchStartedOverLink = false;
}
};
boolean ret = gestureDetector.onTouchEvent(event);
if(!ret && event.getAction() == MotionEvent.ACTION_UP) {
clickGestureListener.listener = null;
removeUrlHighlightColor(view);
this.touchStartedOverLink = false;
ret = true;
}
return ret;
}
private BetterLinkMovementExtended.ClickableSpanWithText findClickableSpanUnderTouch(TextView textView, Spannable text, MotionEvent event) {
int touchX = (int) event.getX();
int touchY = (int) event.getY();
touchX -= textView.getTotalPaddingLeft();
touchY -= textView.getTotalPaddingTop();
touchX += textView.getScrollX();
touchY += textView.getScrollY();
Layout layout = textView.getLayout();
int touchedLine = layout.getLineForVertical(touchY);
int touchOffset = layout.getOffsetForHorizontal(touchedLine, (float) touchX);
this.touchedLineBounds.left = layout.getLineLeft(touchedLine);
this.touchedLineBounds.top = (float) layout.getLineTop(touchedLine);
this.touchedLineBounds.right = layout.getLineWidth(touchedLine) + this.touchedLineBounds.left;
this.touchedLineBounds.bottom = (float) layout.getLineBottom(touchedLine);
if (this.touchedLineBounds.contains((float) touchX, (float) touchY)) {
Object[] spans = text.getSpans(touchOffset, touchOffset, SPAN_CLASS);
for (Object span : spans) {
if (span instanceof ClickableSpan) {
return ClickableSpanWithText.ofSpan(textView, (ClickableSpan) span);
}
}
return null;
} else {
return null;
}
}
private void highlightUrl(TextView textView, BetterLinkMovementExtended.ClickableSpanWithText spanWithText, Spannable text) {
if (!this.isUrlHighlighted) {
this.isUrlHighlighted = true;
int spanStart = text.getSpanStart(spanWithText.span());
int spanEnd = text.getSpanEnd(spanWithText.span());
Selection.removeSelection(text);
text.setSpan(new BackgroundColorSpan(textView.getHighlightColor()), spanStart, spanEnd, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
textView.setText(text);
Selection.setSelection(text, spanStart, spanEnd);
}
}
private void removeUrlHighlightColor(TextView textView) {
if (this.isUrlHighlighted) {
this.isUrlHighlighted = false;
Spannable text = (Spannable) textView.getText();
BackgroundColorSpan[] highlightSpans = text.getSpans(0, text.length(), BackgroundColorSpan.class);
for (BackgroundColorSpan highlightSpan : highlightSpans) {
text.removeSpan(highlightSpan);
}
try {
textView.setText(text);
Selection.removeSelection(text);
} catch (Exception ignored) {}
}
}
private void dispatchUrlClick(TextView textView, BetterLinkMovementExtended.ClickableSpanWithText spanWithText) {
String spanUrl = spanWithText.text();
boolean handled = this.onLinkClickListener != null && this.onLinkClickListener.onClick(textView, spanUrl);
if (!handled) {
spanWithText.span().onClick(textView);
}
}
private void dispatchUrlLongClick(TextView textView, BetterLinkMovementExtended.ClickableSpanWithText spanWithText) {
String spanUrl = spanWithText.text();
if(onLinkLongClickListener != null) onLinkLongClickListener.onLongClick(textView, spanUrl);
}
static class ClickableSpanWithText {
private ClickableSpan span;
private String text;
static BetterLinkMovementExtended.ClickableSpanWithText ofSpan(TextView textView, ClickableSpan span) {
Spanned s = (Spanned) textView.getText();
String text;
if (span instanceof URLSpan) {
text = ((URLSpan) span).getURL();
} else {
int start = s.getSpanStart(span);
int end = s.getSpanEnd(span);
text = s.subSequence(start, end).toString();
}
return new BetterLinkMovementExtended.ClickableSpanWithText(span, text);
}
private ClickableSpanWithText(ClickableSpan span, String text) {
this.span = span;
this.text = text;
}
ClickableSpan span() {
return this.span;
}
String text() {
return this.text;
}
}
public interface OnLinkClickListener {
boolean onClick(TextView view, String link);
}
public interface OnLinkLongClickListener {
boolean onLongClick(TextView view, String link);
}
}
| 10,503 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
PreTagHandler.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/timeline/handler/PreTagHandler.java | package com.fastaccess.provider.timeline.handler;
import android.graphics.Color;
import androidx.annotation.ColorInt;
import android.text.SpannableStringBuilder;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.TypefaceSpan;
import com.fastaccess.helper.PrefGetter;
import net.nightwhistler.htmlspanner.handlers.PreHandler;
import org.htmlcleaner.ContentNode;
import org.htmlcleaner.TagNode;
import lombok.AllArgsConstructor;
import static android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE;
/**
* Created by Kosh on 22 Apr 2017, 1:07 PM
*/
@AllArgsConstructor public class PreTagHandler extends PreHandler {
@ColorInt private final int color;
private final boolean isPre;
@PrefGetter.ThemeType private int theme;
private void getPlainText(StringBuffer buffer, Object node) {
if (node instanceof ContentNode) {
ContentNode contentNode = (ContentNode) node;
String text = contentNode.getContent().toString();
buffer.append(text);
} else if (node instanceof TagNode) {
TagNode tagNode = (TagNode) node;
for (Object child : tagNode.getChildren()) {
this.getPlainText(buffer, child);
}
}
}
private String replace(String text) {
return text.replaceAll(" ", "\u00A0")
.replaceAll("&", "&")
.replaceAll(""", "\"")
.replaceAll("¢", "¢")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll("§", "§")
.replaceAll("“", "“")
.replaceAll("”", "”")
.replaceAll("‘", "‘")
.replaceAll("’", "’")
.replaceAll("–", "\u2013")
.replaceAll("—", "\u2014")
.replaceAll("―", "\u2015");
}
@Override public void handleTagNode(TagNode node, SpannableStringBuilder builder, int start, int end) {
if (isPre) {
StringBuffer buffer = new StringBuffer();
buffer.append("\n");//fake padding top + make sure, pre is always by itself
getPlainText(buffer, node);
buffer.append("\n");//fake padding bottom + make sure, pre is always by itself
builder.append(replace(buffer.toString()));
builder.append("\n");
builder.setSpan(new CodeBackgroundRoundedSpan(color), start, builder.length(), SPAN_EXCLUSIVE_EXCLUSIVE);
builder.append("\n");
this.appendNewLine(builder);
this.appendNewLine(builder);
} else {
CharSequence text = node.getText();
builder.append(" ");
builder.append(replace(text.toString()));
builder.append(" ");
final int stringStart = start + 1;
final int stringEnd = builder.length() - 1;
builder.setSpan(new BackgroundColorSpan(color), stringStart, stringEnd, SPAN_EXCLUSIVE_EXCLUSIVE);
if (theme == PrefGetter.LIGHT) {
builder.setSpan(new ForegroundColorSpan(Color.RED), stringStart, stringEnd, SPAN_EXCLUSIVE_EXCLUSIVE);
}
builder.setSpan(new TypefaceSpan("monospace"), stringStart, stringEnd, SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
| 3,417 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
DrawableHandler.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/timeline/handler/DrawableHandler.java | package com.fastaccess.provider.timeline.handler;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import android.widget.TextView;
import com.fastaccess.helper.InputHelper;
import com.fastaccess.helper.PrefGetter;
import com.fastaccess.provider.scheme.SchemeParser;
import com.fastaccess.provider.timeline.handler.drawable.DrawableGetter;
import com.fastaccess.ui.widgets.SpannableBuilder;
import net.nightwhistler.htmlspanner.TagNodeHandler;
import net.nightwhistler.htmlspanner.spans.CenterSpan;
import org.htmlcleaner.TagNode;
import lombok.AllArgsConstructor;
import static android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE;
/**
* Created by Kosh on 22 Apr 2017, 1:09 PM
*/
@AllArgsConstructor public class DrawableHandler extends TagNodeHandler {
private TextView textView;
private int width;
@SuppressWarnings("ConstantConditions") private boolean isNull() {
return textView == null;
}
@Override public void handleTagNode(TagNode node, SpannableStringBuilder builder, int start, int end) {
String src = node.getAttributeByName("src");
if (!InputHelper.isEmpty(src)) {
if (!PrefGetter.isAutoImageDisabled()) {
builder.append("");
if (isNull()) return;
builder.append("\n");
DrawableGetter imageGetter = new DrawableGetter(textView, width);
builder.setSpan(new ImageSpan(imageGetter.getDrawable(src)), start, builder.length(), SPAN_EXCLUSIVE_EXCLUSIVE);
builder.append("\n");
} else {
builder.append(SpannableBuilder.builder().clickable("Image", v -> SchemeParser.launchUri(v.getContext(), src)));
builder.append("\n");
}
}
}
}
| 1,796 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
EmojiHandler.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/timeline/handler/EmojiHandler.java | package com.fastaccess.provider.timeline.handler;
import android.text.SpannableStringBuilder;
import com.fastaccess.helper.Logger;
import com.fastaccess.provider.emoji.Emoji;
import com.fastaccess.provider.emoji.EmojiManager;
import net.nightwhistler.htmlspanner.TagNodeHandler;
import org.htmlcleaner.TagNode;
/**
* Created by Kosh on 27 May 2017, 4:54 PM
*/
public class EmojiHandler extends TagNodeHandler {
@Override public void handleTagNode(TagNode node, SpannableStringBuilder builder, int start, int end) {
String emoji = node.getAttributeByName("alias");
if (emoji != null) {
Emoji unicode = EmojiManager.getForAlias(emoji);
if (unicode != null && unicode.getUnicode() != null) {
builder.replace(start, end, " " + unicode.getUnicode() + " ");
}
} else if (node.getText() != null) {
Logger.e(node.getText());
Emoji unicode = EmojiManager.getForAlias(node.getText().toString());
if (unicode != null && unicode.getUnicode() != null) {
builder.replace(start, end, " " + unicode.getUnicode() + " ");
}
}
}
@Override public void beforeChildren(TagNode node, SpannableStringBuilder builder) {
super.beforeChildren(node, builder);
}
}
| 1,318 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
MarginHandler.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/timeline/handler/MarginHandler.java | package com.fastaccess.provider.timeline.handler;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.LeadingMarginSpan;
import net.nightwhistler.htmlspanner.TagNodeHandler;
import org.htmlcleaner.TagNode;
/**
* Created by Kosh on 29 Apr 2017, 11:59 PM
*/
public class MarginHandler extends TagNodeHandler {
public void beforeChildren(TagNode node, SpannableStringBuilder builder) {
if (builder.length() > 0 && builder.charAt(builder.length() - 1) != 10) { //'10 = \n'
this.appendNewLine(builder);
}
}
public void handleTagNode(TagNode node, SpannableStringBuilder builder, int start, int end) {
builder.setSpan(new LeadingMarginSpan.Standard(30), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
this.appendNewLine(builder);
}
}
| 848 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
HrSpan.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/timeline/handler/HrSpan.java | package com.fastaccess.provider.timeline.handler;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import androidx.annotation.NonNull;
import android.text.style.LineHeightSpan;
import android.text.style.ReplacementSpan;
public class HrSpan extends ReplacementSpan implements LineHeightSpan {
private final int width;
private final int color;
HrSpan(int color, int width) {
this.color = color;
this.width = width;
Drawable drawable = new ColorDrawable(color);
}
@Override public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
return (int) paint.measureText(text, start, end);
}
@Override public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top,
int y, int bottom, @NonNull Paint paint) {
final int currentColor = paint.getColor();
paint.setColor(color);
paint.setStyle(Paint.Style.FILL);
int height = 10;
canvas.drawRect(new Rect(0, bottom - height, (int) x + width, bottom), paint);
paint.setColor(currentColor);
}
@Override public void chooseHeight(CharSequence text, int start, int end, int spanstartv, int v, Paint.FontMetricsInt fm) {
fm.top /= 3;
fm.ascent /= 3;
fm.bottom /= 3;
fm.descent /= 3;
}
} | 1,523 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
QuoteHandler.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/timeline/handler/QuoteHandler.java | package com.fastaccess.provider.timeline.handler;
import androidx.annotation.ColorInt;
import android.text.SpannableStringBuilder;
import com.zzhoujay.markdown.style.MarkDownQuoteSpan;
import net.nightwhistler.htmlspanner.TagNodeHandler;
import org.htmlcleaner.TagNode;
import lombok.AllArgsConstructor;
/**
* Created by Kosh on 23 Apr 2017, 11:30 AM
*/
@AllArgsConstructor public class QuoteHandler extends TagNodeHandler {
@ColorInt private int color;
@Override
public void handleTagNode(TagNode node, SpannableStringBuilder builder, int start, int end) {
try {
builder.setSpan(new MarkDownQuoteSpan(color), start + 1, builder.length(), 33);
} catch (IndexOutOfBoundsException e) {
builder.setSpan(new MarkDownQuoteSpan(color), start, builder.length(), 33);
}
}
}
| 842 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
UrlDrawable.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/timeline/handler/drawable/UrlDrawable.java | package com.fastaccess.provider.timeline.handler.drawable;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import androidx.annotation.NonNull;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.crashlytics.android.Crashlytics;
class UrlDrawable extends BitmapDrawable implements Drawable.Callback {
private Drawable drawable;
@SuppressWarnings("deprecation") UrlDrawable() {}
@Override public void draw(Canvas canvas) {
if (drawable != null) {
try {
drawable.draw(canvas);
} catch (Exception e) {
Crashlytics.logException(e);
e.printStackTrace();
}
if (drawable instanceof GifDrawable) {
if (!((GifDrawable) drawable).isRunning()) {
((GifDrawable) drawable).start();
}
}
}
}
public Drawable getDrawable() {
return drawable;
}
public void setDrawable(Drawable drawable) {
if (this.drawable != null) {
this.drawable.setCallback(null);
}
drawable.setCallback(this);
this.drawable = drawable;
}
@Override public void invalidateDrawable(@NonNull Drawable who) {
if (getCallback() != null) {
getCallback().invalidateDrawable(who);
}
}
@Override public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
if (getCallback() != null) {
getCallback().scheduleDrawable(who, what, when);
}
}
@Override public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
if (getCallback() != null) {
getCallback().unscheduleDrawable(who, what);
}
}
} | 1,883 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
GlideDrawableTarget.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/timeline/handler/drawable/GlideDrawableTarget.java | package com.fastaccess.provider.timeline.handler.drawable;
import android.graphics.Rect;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.widget.TextView;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.fastaccess.R;
import java.lang.ref.WeakReference;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
class GlideDrawableTarget extends SimpleTarget<Drawable> {
private final UrlDrawable urlDrawable;
private final WeakReference<TextView> container;
private final int width;
GlideDrawableTarget(UrlDrawable urlDrawable, WeakReference<TextView> container, int width) {
this.urlDrawable = urlDrawable;
this.container = container;
this.width = width;
}
@Override public void onResourceReady(final @NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
if (container != null && container.get() != null) {
TextView textView = container.get();
textView.post(() -> {
float width;
float height;
if (resource.getIntrinsicWidth() >= this.width) {
float downScale = (float) resource.getIntrinsicWidth() / this.width;
width = (float) (resource.getIntrinsicWidth() / downScale / 1.3);
height = (float) (resource.getIntrinsicHeight() / downScale / 1.3);
} else {
width = (float) resource.getIntrinsicWidth();
height = (float) resource.getIntrinsicHeight();
}
Rect rect = new Rect(0, 0, Math.round(width), Math.round(height));
resource.setBounds(rect);
urlDrawable.setBounds(rect);
urlDrawable.setDrawable(resource);
if (resource instanceof GifDrawable) {
urlDrawable.setCallback((Drawable.Callback) textView.getTag(R.id.drawable_callback));
((GifDrawable) resource).setLoopCount(GifDrawable.LOOP_FOREVER);
((GifDrawable) resource).start();
}
textView.setText(textView.getText());
textView.invalidate();
});
}
}
} | 2,413 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
DrawableGetter.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/timeline/handler/drawable/DrawableGetter.java | package com.fastaccess.provider.timeline.handler.drawable;
import android.content.Context;
import android.graphics.drawable.Drawable;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import android.text.Html;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.fastaccess.App;
import com.fastaccess.GlideApp;
import com.fastaccess.R;
import java.lang.ref.WeakReference;
import java.util.HashSet;
import java.util.Set;
/**
* Created by Kosh on 22 Apr 2017, 7:44 PM
*/
public class DrawableGetter implements Html.ImageGetter, Drawable.Callback {
private WeakReference<TextView> container;
private final Set<GlideDrawableTarget> cachedTargets;
private final int width;
public DrawableGetter(TextView tv, int width) {
tv.setTag(R.id.drawable_callback, this);
this.container = new WeakReference<>(tv);
this.cachedTargets = new HashSet<>();
this.width = width;
}
@Override public Drawable getDrawable(@NonNull String url) {
final UrlDrawable urlDrawable = new UrlDrawable();
if (container != null && container.get() != null) {
Context context = container.get().getContext();
final RequestBuilder load = Glide.with(context)
.load(url)
.placeholder(ContextCompat.getDrawable(context, R.drawable.ic_image))
.dontAnimate();
final GlideDrawableTarget target = new GlideDrawableTarget(urlDrawable, container, width);
load.into(target);
cachedTargets.add(target);
}
return urlDrawable;
}
@Override public void invalidateDrawable(@NonNull Drawable drawable) {
if (container != null && container.get() != null) {
container.get().invalidate();
}
}
@Override public void scheduleDrawable(@NonNull Drawable drawable, @NonNull Runnable runnable, long l) {}
@Override public void unscheduleDrawable(@NonNull Drawable drawable, @NonNull Runnable runnable) {}
public void clear(@NonNull DrawableGetter drawableGetter) {
if (drawableGetter.cachedTargets != null) {
for (GlideDrawableTarget target : drawableGetter.cachedTargets) {
GlideApp.with(App.getInstance()).clear(target);
}
}
}
}
| 2,395 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
PushNotificationService.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/fcm/PushNotificationService.java | package com.fastaccess.provider.fcm;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import androidx.core.app.NotificationCompat;
import com.fastaccess.R;
import com.fastaccess.data.dao.model.FastHubNotification;
import com.fastaccess.provider.rest.RestProvider;
import com.fastaccess.ui.modules.main.MainActivity;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import org.json.JSONObject;
import java.util.Date;
/**
* Created by Kosh on 16 Apr 2017, 1:17 PM
*/
public class PushNotificationService extends FirebaseMessagingService {
@Override public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage != null) {
if (remoteMessage.getData() != null && !remoteMessage.getData().isEmpty()) {
Date date = new Date(remoteMessage.getSentTime());
FastHubNotification fastHubNotification = RestProvider.gson
.fromJson(new JSONObject(remoteMessage.getData()).toString(), FastHubNotification.class);
fastHubNotification.setDate(date);
FastHubNotification.save(fastHubNotification);
} else if (remoteMessage.getNotification() != null) {
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
if (remoteMessage.getData() != null && !remoteMessage.getData().isEmpty()) {
title = title == null ? remoteMessage.getData().get("title") : title;
body = body == null ? remoteMessage.getData().get("message") : body;
}
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "In App-Notifications")
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.notify(1, notificationBuilder.build());
}
}
}
}
}
| 2,776 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
ImgurProvider.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/rest/ImgurProvider.java | package com.fastaccess.provider.rest;
import androidx.annotation.NonNull;
import com.fastaccess.BuildConfig;
import com.fastaccess.data.service.ImgurService;
import com.fastaccess.provider.rest.converters.GithubResponseConverter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.lang.reflect.Modifier;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
/**
* Created by Kosh on 15 Apr 2017, 7:59 PM
*/
public class ImgurProvider {
public final static Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
.setPrettyPrinting()
.create();
private ImgurProvider() {}
private static OkHttpClient provideOkHttpClient() {
OkHttpClient.Builder client = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) {
client.addInterceptor(new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY));
}
client.addInterceptor(chain -> {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder();
requestBuilder.header("Authorization", "Client-ID " + BuildConfig.IMGUR_CLIENT_ID);
requestBuilder.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
});
return client.build();
}
private static Retrofit provideRetrofit() {
return new Retrofit.Builder()
.baseUrl(BuildConfig.IMGUR_URL)
.client(provideOkHttpClient())
.addConverterFactory(new GithubResponseConverter(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
@NonNull public static ImgurService getImgurService() {
return provideRetrofit().create(ImgurService.class);
}
}
| 2,097 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
LoginProvider.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/rest/LoginProvider.java | package com.fastaccess.provider.rest;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.fastaccess.BuildConfig;
import com.fastaccess.data.service.LoginRestService;
import com.fastaccess.helper.InputHelper;
import com.fastaccess.provider.rest.converters.GithubResponseConverter;
import com.fastaccess.provider.rest.interceptors.AuthenticationInterceptor;
import com.fastaccess.provider.scheme.LinkParserHelper;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.lang.reflect.Modifier;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
/**
* Created by Kosh on 08 Feb 2017, 8:37 PM
*/
public class LoginProvider {
private final static Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
.setDateFormat("yyyy-MM-dd HH:mm:ss")
.setPrettyPrinting()
.create();
private static OkHttpClient provideOkHttpClient(@Nullable String authToken, @Nullable String otp) {
OkHttpClient.Builder client = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) {
client.addInterceptor(new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY));
}
client.addInterceptor(new AuthenticationInterceptor(authToken, otp));
return client.build();
}
private static Retrofit provideRetrofit(@Nullable String authToken, @Nullable String otp, @Nullable String enterpriseUrl) {
return new Retrofit.Builder()
.baseUrl(InputHelper.isEmpty(enterpriseUrl) ? BuildConfig.REST_URL : LinkParserHelper.getEndpoint(enterpriseUrl))
.client(provideOkHttpClient(authToken, otp))
.addConverterFactory(new GithubResponseConverter(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
public static LoginRestService getLoginRestService() {
return new Retrofit.Builder()
.baseUrl("https://github.com/login/oauth/")
.client(provideOkHttpClient(null, null))
.addConverterFactory(new GithubResponseConverter(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
.create(LoginRestService.class);
}
@NonNull public static LoginRestService getLoginRestService(@NonNull String authToken, @Nullable String otp,
@Nullable String endpoint) {
return provideRetrofit(authToken, otp, endpoint).create(LoginRestService.class);
}
}
| 2,914 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
RepoQueryProvider.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/rest/RepoQueryProvider.java | package com.fastaccess.provider.rest;
import androidx.annotation.NonNull;
import com.fastaccess.data.dao.types.IssueState;
/**
* Created by Kosh on 23 Mar 2017, 7:26 PM
*/
public class RepoQueryProvider {
@NonNull public static String getIssuesPullRequestQuery(@NonNull String owner, @NonNull String repo,
@NonNull IssueState issueState, boolean isPr) {
return "+" + "type:" + (isPr ? "pr" : "issue") +
"+" + "repo:" + owner + "/" +
repo + "+" + "is:" + issueState.name();
}
@NonNull public static String getMyIssuesPullRequestQuery(@NonNull String username, @NonNull IssueState issueState, boolean isPr) {
return "type:" + (isPr ? "pr" : "issue") +
"+" + "author:" + username +
"+is:" + issueState.name();
}
@NonNull public static String getAssigned(@NonNull String username, @NonNull IssueState issueState, boolean isPr) {
return "type:" + (isPr ? "pr" : "issue") +
"+" + "assignee:" + username +
"+is:" + issueState.name();
}
@NonNull public static String getMentioned(@NonNull String username, @NonNull IssueState issueState, boolean isPr) {
return "type:" + (isPr ? "pr" : "issue") +
"+" + "mentions:" + username +
"+is:" + issueState.name();
}
@NonNull public static String getReviewRequests(@NonNull String username, @NonNull IssueState issueState) {
return "type:pr" +
"+" + "review-requested:" + username +
"+is:" + issueState.name();
}
public static String getParticipated(@NonNull String username, @NonNull IssueState issueState, boolean isPr) {
return "type:" + (isPr ? "pr" : "issue") +
"+" + "involves:" + username +
"+is:" + issueState.name();
}
}
| 1,922 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
RestProvider.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/rest/RestProvider.java | package com.fastaccess.provider.rest;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import com.crashlytics.android.Crashlytics;
import com.fastaccess.BuildConfig;
import com.fastaccess.R;
import com.fastaccess.data.dao.GitHubErrorResponse;
import com.fastaccess.data.dao.GitHubStatusModel;
import com.fastaccess.data.service.ContentService;
import com.fastaccess.data.service.GistService;
import com.fastaccess.data.service.IssueService;
import com.fastaccess.data.service.NotificationService;
import com.fastaccess.data.service.OrganizationService;
import com.fastaccess.data.service.ProjectsService;
import com.fastaccess.data.service.PullRequestService;
import com.fastaccess.data.service.ReactionsService;
import com.fastaccess.data.service.RepoService;
import com.fastaccess.data.service.ReviewService;
import com.fastaccess.data.service.SearchService;
import com.fastaccess.data.service.UserRestService;
import com.fastaccess.helper.ActivityHelper;
import com.fastaccess.helper.InputHelper;
import com.fastaccess.helper.PrefGetter;
import com.fastaccess.provider.rest.converters.GithubResponseConverter;
import com.fastaccess.provider.rest.interceptors.AuthenticationInterceptor;
import com.fastaccess.provider.rest.interceptors.ContentTypeInterceptor;
import com.fastaccess.provider.rest.interceptors.PaginationInterceptor;
import com.fastaccess.provider.scheme.LinkParserHelper;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.File;
import java.lang.reflect.Modifier;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.reactivex.Observable;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.HttpException;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import tech.linjiang.pandora.Pandora;
/**
* Created by Kosh on 08 Feb 2017, 8:37 PM
*/
public class RestProvider {
public static final int PAGE_SIZE = 30;
private static OkHttpClient okHttpClient;
public final static Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
.setDateFormat("yyyy-MM-dd HH:mm:ss")
.disableHtmlEscaping()
.setPrettyPrinting()
.create();
public static OkHttpClient provideOkHttpClient() {
if (okHttpClient == null) {
OkHttpClient.Builder client = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) {
client.addInterceptor(new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY));
}
client.addInterceptor(new AuthenticationInterceptor());
client.addInterceptor(new PaginationInterceptor());
client.addInterceptor(new ContentTypeInterceptor());
client.addInterceptor(Pandora.get().getInterceptor());
okHttpClient = client.build();
}
return okHttpClient;
}
private static Retrofit provideRetrofit(boolean enterprise) {
return new Retrofit.Builder()
.baseUrl(enterprise && PrefGetter.isEnterprise() ? LinkParserHelper.getEndpoint(PrefGetter.getEnterpriseUrl()) : BuildConfig.REST_URL)
.client(provideOkHttpClient())
.addConverterFactory(new GithubResponseConverter(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
public static void downloadFile(@NonNull Context context, @NonNull String url) {
downloadFile(context, url, null);
}
public static void downloadFile(@NonNull Context context, @NonNull String url, @Nullable String extension) {
try {
if (InputHelper.isEmpty(url)) return;
boolean isEnterprise = LinkParserHelper.isEnterprise(url);
if (url.endsWith(".apk")) {
Activity activity = ActivityHelper.getActivity(context);
if (activity != null) {
ActivityHelper.startCustomTab(activity, url);
return;
}
}
Uri uri = Uri.parse(url);
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(uri);
String authToken = isEnterprise ? PrefGetter.getEnterpriseToken() : PrefGetter.getToken();
if (!TextUtils.isEmpty(authToken)) {
request.addRequestHeader("Authorization", authToken.startsWith("Basic") ? authToken : "token " + authToken);
}
String fileName = new File(url).getName();
if (!InputHelper.isEmpty(extension)) {
fileName += extension;
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
request.setTitle(fileName);
request.setDescription(context.getString(R.string.downloading_file));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
if (downloadManager != null) {
downloadManager.enqueue(request);
}
} catch (Exception e) {
e.printStackTrace();
Crashlytics.logException(e);
}
}
public static int getErrorCode(Throwable throwable) {
if (throwable instanceof HttpException) {
return ((HttpException) throwable).code();
}
return -1;
}
@NonNull public static UserRestService getUserService(boolean enterprise) {
return provideRetrofit(enterprise).create(UserRestService.class);
}
@NonNull public static GistService getGistService(boolean enterprise) {
return provideRetrofit(enterprise).create(GistService.class);
}
@NonNull public static RepoService getRepoService(boolean enterprise) {
return provideRetrofit(enterprise).create(RepoService.class);
}
@NonNull public static IssueService getIssueService(boolean enterprise) {
return provideRetrofit(enterprise).create(IssueService.class);
}
@NonNull public static PullRequestService getPullRequestService(boolean enterprise) {
return provideRetrofit(enterprise).create(PullRequestService.class);
}
@NonNull public static NotificationService getNotificationService(boolean enterprise) {
return provideRetrofit(enterprise).create(NotificationService.class);
}
@NonNull public static ReactionsService getReactionsService(boolean enterprise) {
return provideRetrofit(enterprise).create(ReactionsService.class);
}
@NonNull public static OrganizationService getOrgService(boolean enterprise) {
return provideRetrofit(enterprise).create(OrganizationService.class);
}
@NonNull public static ReviewService getReviewService(boolean enterprise) {
return provideRetrofit(enterprise).create(ReviewService.class);
}
@NonNull public static UserRestService getContribution() {
return new Retrofit.Builder()
.baseUrl(BuildConfig.REST_URL)
.addConverterFactory(new GithubResponseConverter(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
.create(UserRestService.class);
}
@NonNull public static SearchService getSearchService(boolean enterprise) {
return provideRetrofit(enterprise).create(SearchService.class);
}
@NonNull public static ContentService getContentService(boolean enterprise) {
return provideRetrofit(enterprise).create(ContentService.class);
}
@NonNull public static ProjectsService getProjectsService(boolean enterprise) {
return provideRetrofit(enterprise).create(ProjectsService.class);
}
@Nullable public static GitHubErrorResponse getErrorResponse(@NonNull Throwable throwable) {
ResponseBody body = null;
if (throwable instanceof HttpException) {
body = ((HttpException) throwable).response().errorBody();
}
if (body != null) {
try {
return gson.fromJson(body.string(), GitHubErrorResponse.class);
} catch (Exception ignored) {}
}
return null;
}
@NonNull public static Observable<GitHubStatusModel> gitHubStatus() {
return new Retrofit.Builder()
.baseUrl("https://kctbh9vrtdwd.statuspage.io/")
.client(provideOkHttpClient())
.addConverterFactory(new GithubResponseConverter(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
.create(ContentService.class)
.checkStatus();
}
public static void clearHttpClient() {
okHttpClient = null;
}
}
| 9,402 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
GithubResponseConverter.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/rest/converters/GithubResponseConverter.java | package com.fastaccess.provider.rest.converters;
import androidx.annotation.NonNull;
import com.google.gson.Gson;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import lombok.AllArgsConstructor;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* call that supports String & Gson and always uses json as its request body
*/
@AllArgsConstructor
public class GithubResponseConverter extends Converter.Factory {
private Gson gson;
@Override public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
try {
if (type == String.class) {
return new StringResponseConverter();
}
return GsonConverterFactory.create(gson).responseBodyConverter(type, annotations, retrofit);
} catch (OutOfMemoryError ignored) {
return null;
}
}
@Override public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations,
Annotation[] methodAnnotations, Retrofit retrofit) {
return GsonConverterFactory.create(gson).requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
}
public static class StringResponseConverter implements Converter<ResponseBody, String> {
@Override public String convert(@NonNull ResponseBody value) throws IOException {
return value.string();
}
}
}
| 1,661 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
OnLoadMore.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/rest/loadmore/OnLoadMore.java | package com.fastaccess.provider.rest.loadmore;
import androidx.annotation.Nullable;
import com.fastaccess.ui.base.mvp.BaseMvp;
import com.fastaccess.ui.widgets.recyclerview.scroll.InfiniteScroll;
public class OnLoadMore<P> extends InfiniteScroll {
private BaseMvp.PaginationListener<P> presenter;
@Nullable private P parameter;
public OnLoadMore(BaseMvp.PaginationListener<P> presenter) {
this(presenter, null);
}
public OnLoadMore(BaseMvp.PaginationListener<P> presenter, @Nullable P parameter) {
super();
this.presenter = presenter;
this.parameter = parameter;
}
public void setParameter(@Nullable P parameter) {
this.parameter = parameter;
}
@Nullable public P getParameter() {
return parameter;
}
@Override public boolean onLoadMore(int page, int totalItemsCount) {
if (presenter != null) {
presenter.setPreviousTotal(totalItemsCount);
return presenter.onCallApi(page + 1, parameter);
}
return false;
}
} | 1,062 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
PaginationInterceptor.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/rest/interceptors/PaginationInterceptor.java | package com.fastaccess.provider.rest.interceptors;
import android.net.Uri;
import androidx.annotation.NonNull;
import com.fastaccess.helper.InputHelper;
import java.io.IOException;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
public class PaginationInterceptor implements Interceptor {
@Override public Response intercept(@NonNull Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
Headers headers = chain.request().headers();
if (headers != null) {
if ((headers.values("Accept").contains("application/vnd.github.html") ||
headers.values("Accept").contains("application/vnd.github.VERSION.raw"))) {
return response;//return them as they are.
}
}
if (response.isSuccessful()) {
if (response.peekBody(1).string().equals("[")) {
String json = "{";
String link = response.header("link");
if (link != null) {
String[] links = link.split(",");
for (String link1 : links) {
String[] pageLink = link1.split(";");
String page = Uri.parse(pageLink[0].replaceAll("[<>]", "")).getQueryParameter("page");
String rel = pageLink[1].replaceAll("\"", "").replace("rel=", "");
if (page != null) json += String.format("\"%s\":\"%s\",", rel.trim(), page);
}
}
json += String.format("\"items\":%s}", response.body().string());
return response.newBuilder().body(ResponseBody.create(response.body().contentType(), json)).build();
} else if (response.header("link") != null) {
String link = response.header("link");
String pagination = "";
String[] links = link.split(",");
for (String link1 : links) {
String[] pageLink = link1.split(";");
String page = Uri.parse(pageLink[0].replaceAll("[<>]", "")).getQueryParameter("page");
String rel = pageLink[1].replaceAll("\"", "").replace("rel=", "");
if (page != null) pagination += String.format("\"%s\":\"%s\",", rel.trim(), page);
}
if (!InputHelper.isEmpty(pagination)) {//hacking for search pagination.
String body = response.body().string();
return response.newBuilder().body(ResponseBody.create(response.body().contentType(),
"{" + pagination + body.substring(1, body.length()))).build();
}
}
}
return response;
}
}
| 2,877 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
JsoupProvider.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/rest/jsoup/JsoupProvider.java | package com.fastaccess.provider.rest.jsoup;
import androidx.annotation.NonNull;
import com.fastaccess.BuildConfig;
import com.fastaccess.data.service.ScrapService;
import com.fastaccess.provider.rest.interceptors.AuthenticationInterceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import tech.linjiang.pandora.Pandora;
/**
* Created by Kosh on 02 Jun 2017, 12:47 PM
*/
public class JsoupProvider {
private static OkHttpClient okHttpClient;
private static OkHttpClient provideOkHttpClient() {
if (okHttpClient == null) {
OkHttpClient.Builder client = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) {
client.addInterceptor(new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY));
}
client.addInterceptor(Pandora.get().getInterceptor());
client.addInterceptor(new AuthenticationInterceptor(true));
okHttpClient = client.build();
}
return okHttpClient;
}
public static ScrapService getTrendingService(@NonNull String url) {
return new Retrofit.Builder()
.baseUrl(url)
.client(provideOkHttpClient())
.addConverterFactory(ScalarsConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
.create(ScrapService.class);
}
public static ScrapService getWiki() {
return new Retrofit.Builder()
.baseUrl("https://github.com/")
.client(provideOkHttpClient())
.addConverterFactory(ScalarsConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
.create(ScrapService.class);
}
}
| 2,025 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
ToGsonProvider.java | /FileExtraction/Java_unseen/k0shk0sh_FastHub/app/src/main/java/com/fastaccess/provider/gson/ToGsonProvider.java | package com.fastaccess.provider.gson;
import android.content.Context;
import androidx.annotation.NonNull;
import com.fastaccess.R;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import io.reactivex.Observable;
/**
* Created by Kosh on 26 Mar 2017, 10:07 PM
*/
public class ToGsonProvider {
public static Observable<String> getChangelog(@NonNull Context context) {
return Observable.fromCallable(() -> {
try (InputStream is = context.getResources().openRawResource(R.raw.changelog)) {
try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream()) {
byte[] buffer = new byte[is.available()];
int read = is.read(buffer);//ignore lint
byteStream.write(buffer);
return byteStream.toString();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
});
}
}
| 1,030 | Java | .java | k0shk0sh/FastHub | 5,696 | 930 | 343 | 2017-02-18T17:53:16Z | 2022-09-12T13:15:21Z |
TestOpenSkyApi.java | /FileExtraction/Java_unseen/openskynetwork_opensky-api/java/src/test/java/TestOpenSkyApi.java | import org.junit.Test;
import org.opensky.api.OpenSkyApi;
import org.opensky.model.OpenSkyStates;
import org.opensky.model.StateVector;
import java.io.IOException;
import static org.junit.Assert.*;
/**
* @author Markus Fuchs, [email protected]
*/
public class TestOpenSkyApi {
/** credentials to test authenticated API calls **/
static final String USERNAME = null;
static final String PASSWORD = null;
// serials which belong to the given account
static final Integer[] SERIALS = null;
@Test
public void testAnonGetStates() throws IOException, InterruptedException {
OpenSkyApi api = new OpenSkyApi();
long t0 = System.nanoTime();
OpenSkyStates os = api.getStates(0, null);
long t1 = System.nanoTime();
System.out.println("Request anonStates time = " + ((t1 - t0) / 1000000) + "ms");
assertTrue("More than 1 state vector", os.getStates().size() > 1);
int time = os.getTime();
// more than two requests withing ten seconds
os = api.getStates(0, null);
assertNull("No new data", os);
// wait ten seconds
Thread.sleep(10000);
// now we can retrieve states again
t0 = System.nanoTime();
os = api.getStates(0, null);
t1 = System.nanoTime();
System.out.println("Request anonStates time = " + ((t1 - t0) / 1000000) + "ms");
assertNotNull(os);
assertTrue("More than 1 state vector for second valid request", os.getStates().size() > 1);
assertNotEquals(time, os.getTime());
// test bounding box around Switzerland
api = new OpenSkyApi();
try {
api.getStates(0, null, new OpenSkyApi.BoundingBox(145.8389, 47.8229, 5.9962, 10.5226));
fail("Illegal coordinates should be detected");
} catch (RuntimeException re) {
// NOP
}
try {
api.getStates(0, null, new OpenSkyApi.BoundingBox(45.8389, -147.8229, 5.9962, 10.5226));
fail("Illegal coordinates should be detected");
} catch (RuntimeException re) {
// NOP
}
try {
api.getStates(0, null, new OpenSkyApi.BoundingBox(45.8389, 47.8229, 255.9962, 10.5226));
fail("Illegal coordinates should be detected");
} catch (RuntimeException re) {
// NOP
}
try {
api.getStates(0, null, new OpenSkyApi.BoundingBox(45.8389, 47.8229, 5.9962, -180.5226));
fail("Illegal coordinates should be detected");
} catch (RuntimeException re) {
// NOP
}
OpenSkyStates os2 = api.getStates(0, null, new OpenSkyApi.BoundingBox(45.8389, 47.8229, 5.9962, 10.5226));
assertTrue("Much less states in Switzerland area than world-wide", os2.getStates().size() < os.getStates().size() - 200);
}
// can only be tested with a valid account
@Test
public void testAuthGetStates() throws IOException, InterruptedException {
if (USERNAME == null || PASSWORD == null) {
System.out.println("WARNING: testAuthGetStates needs valid credentials and did not run");
return;
}
OpenSkyApi api = new OpenSkyApi(USERNAME, PASSWORD);
OpenSkyStates os = api.getStates(0, null);
assertTrue("More than 1 state vector", os.getStates().size() > 1);
int time = os.getTime();
// more than two requests withing ten seconds
os = api.getStates(0, null);
assertNull("No new data", os);
// wait five seconds
Thread.sleep(5000);
// now we can retrieve states again
long t0 = System.nanoTime();
os = api.getStates(0, null);
long t1 = System.nanoTime();
System.out.println("Request authStates time = " + ((t1 - t0) / 1000000) + "ms");
assertNotNull(os);
assertTrue("More than 1 state vector for second valid request", os.getStates().size() > 1);
assertNotEquals(time, os.getTime());
}
@Test
public void testAnonGetMyStates() {
OpenSkyApi api = new OpenSkyApi();
try {
api.getMyStates(0, null, null);
fail("Anonymous access of 'myStates' expected");
} catch (IllegalAccessError iae) {
// like expected
assertTrue("Mismatched exception message",
iae.getMessage().equals("Anonymous access of 'myStates' not allowed"));
} catch (IOException e) {
fail("Request should not be submitted");
}
}
@Test
public void testAuthGetMyStates() throws IOException {
/* DEBUG output:
System.setProperty("org.apache.commons.logging.Log","org.apache.commons.logging.impl.SimpleLog");
System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.wire", "DEBUG");
System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.impl.conn", "DEBUG");
System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.impl.client", "DEBUG");
System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.client", "DEBUG");
System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http", "DEBUG");
*/
if (USERNAME == null || PASSWORD == null) {
System.out.println("WARNING: testAuthGetMyStates needs valid credentials and did not run");
return;
}
OpenSkyApi api = new OpenSkyApi(USERNAME, PASSWORD);
OpenSkyStates os = api.getMyStates(0, null, SERIALS);
assertTrue("More than 1 state vector", os.getStates().size() > 1);
for (StateVector sv : os.getStates()) {
// all states contain at least one of the user's sensors
boolean gotOne = false;
for (Integer ser : SERIALS) {
gotOne = gotOne || sv.getSerials().contains(ser);
}
assertTrue(gotOne);
}
}
}
| 5,341 | Java | .java | openskynetwork/opensky-api | 324 | 121 | 13 | 2016-03-21T18:00:03Z | 2023-11-10T02:52:39Z |
TestOpenSkyStatesDeserializer.java | /FileExtraction/Java_unseen/openskynetwork_opensky-api/java/src/test/java/TestOpenSkyStatesDeserializer.java | import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.junit.Test;
import org.opensky.model.OpenSkyStates;
import org.opensky.model.OpenSkyStatesDeserializer;
import org.opensky.model.StateVector;
import java.io.IOException;
import java.util.Iterator;
import static org.junit.Assert.*;
/**
* @author Markus Fuchs, [email protected]
*/
public class TestOpenSkyStatesDeserializer {
// ["a086d8","FDX1869 ","United States",1507198218,1507198218,-121.8445,37.2541,6553.2,false,236.88,142.23,13.33,null,6743.7,"6714",false,0]
static final String validJson = "{" +
"\"time\":1002," +
"\"states\":[" +
"[\"cabeef\",\"ABCDEFG\",\"USA\",1001,1000,1.0,2.0,3.0,false,4.0,5.0,6.0,null,6743.7,\"6714\",false,0]," +
"[\"cabeef\",null,\"USA\",null,1000,null,null,null,false,4.0,5.0,6.0,null,null,\"6714\",false,0]," +
"[\"cabeef\",null,\"USA\",1001,null,1.0,2.0,3.0,false,null,null,null,null,6743.7,null,false,0]," +
"[\"cabeef\",\"ABCDEFG\",\"USA\",1001,1000,1.0,2.0,3.0,false,4.0,5.0,6.0,[1234,6543],6743.7,\"6714\",false,1]," +
"[\"cabeef\",\"ABCDEFG\",\"USA\",1001,1000,1.0,2.0,3.0,false,4.0,5.0,6.0,[1234],6743.7,\"6714\",true,8]," +
"[\"cabeef\",\"ABCDEFG\",\"USA\",1001,1000,1.0,2.0,3.0,true,4.0,5.0,6.0,[],null,null,false,0,\"additional_unused\",2]" +
"]}";
static final String invalidJson = "{" +
"\"time\":1002," +
"\"states\":[" +
"[null,\"ABCDEFG\",\"USA\",1001,1000,1.0,2.0,3.0,false,4.0,5.0,6.0,null]" +
"]}";
@Test(expected = JsonMappingException.class)
public void testInvalidDeser() throws IOException {
ObjectMapper mapper = new ObjectMapper();
SimpleModule sm = new SimpleModule();
sm.addDeserializer(OpenSkyStates.class, new OpenSkyStatesDeserializer());
mapper.registerModule(sm);
mapper.readValue(invalidJson, OpenSkyStates.class);
}
@Test(expected = JsonMappingException.class)
public void testInvalidDeser2() throws IOException {
ObjectMapper mapper = new ObjectMapper();
SimpleModule sm = new SimpleModule();
sm.addDeserializer(OpenSkyStates.class, new OpenSkyStatesDeserializer());
mapper.registerModule(sm);
// ObjectMapper throws Exception here
mapper.readValue("", OpenSkyStates.class);
}
@Test
public void testInvalidDeser3() throws IOException {
ObjectMapper mapper = new ObjectMapper();
SimpleModule sm = new SimpleModule();
sm.addDeserializer(OpenSkyStates.class, new OpenSkyStatesDeserializer());
mapper.registerModule(sm);
OpenSkyStates states = mapper.readValue("{}", OpenSkyStates.class);
assertEquals(0, states.getTime());
assertNull(states.getStates());
states = mapper.readValue("null", OpenSkyStates.class);
assertNull(states);
}
@Test
public void testDeser() throws IOException {
ObjectMapper mapper = new ObjectMapper();
SimpleModule sm = new SimpleModule();
sm.addDeserializer(OpenSkyStates.class, new OpenSkyStatesDeserializer());
mapper.registerModule(sm);
OpenSkyStates states = mapper.readValue(validJson, OpenSkyStates.class);
assertEquals("Correct Time", 1002, states.getTime());
assertEquals("Number states", 6, states.getStates().size());
// possible cases for state vectors
Iterator<StateVector> statesIt = states.getStates().iterator();
// "[\"cabeef\",\"ABCDEFG\",\"USA\",1001,1000,1.0,2.0,3.0,false,4.0,5.0,6.0,null,6743.7,"6714",false,0],"
StateVector sv = statesIt.next();
assertEquals( "cabeef", sv.getIcao24());
assertEquals("ABCDEFG", sv.getCallsign());
assertEquals("USA", sv.getOriginCountry());
assertEquals(new Double(1001), sv.getLastPositionUpdate());
assertEquals(new Double(1000), sv.getLastContact());
assertEquals(new Double(1.0), sv.getLongitude());
assertEquals(new Double(2.0), sv.getLatitude());
assertEquals(new Double(3.0), sv.getBaroAltitude());
assertEquals(new Double(4.0), sv.getVelocity());
assertEquals(new Double(5.0), sv.getHeading());
assertEquals(new Double(6.0), sv.getVerticalRate());
assertFalse(sv.isOnGround());
assertNull(sv.getSerials());
assertEquals(new Double(6743.7), sv.getGeoAltitude());
assertEquals("6714", sv.getSquawk());
assertFalse(sv.isSpi());
assertEquals(StateVector.PositionSource.ADS_B, sv.getPositionSource());
// "[\"cabeef\",null,\"USA\",null,1000,null,null,null,false,4.0,5.0,6.0,null,null,\"6714\",false,0],"
sv = statesIt.next();
assertEquals( "cabeef", sv.getIcao24());
assertNull(sv.getCallsign());
assertEquals("USA", sv.getOriginCountry());
assertNull(sv.getLastPositionUpdate());
assertEquals(new Double(1000), sv.getLastContact());
assertNull(sv.getLongitude());
assertNull(sv.getLatitude());
assertNull(sv.getGeoAltitude());
assertEquals(new Double(4.0), sv.getVelocity());
assertEquals(new Double(5.0), sv.getHeading());
assertEquals(new Double(6.0), sv.getVerticalRate());
assertFalse(sv.isOnGround());
assertNull(sv.getSerials());
assertNull(sv.getBaroAltitude());
assertEquals("6714", sv.getSquawk());
assertFalse(sv.isSpi());
assertEquals(StateVector.PositionSource.ADS_B, sv.getPositionSource());
// "[\"cabeef\",null,\"USA\",1001,null,1.0,2.0,3.0,false,null,null,null,null,6743.7,null,false,0],"
sv = statesIt.next();
assertEquals( "cabeef", sv.getIcao24());
assertNull(sv.getCallsign());
assertEquals("USA", sv.getOriginCountry());
assertEquals(new Double(1001), sv.getLastPositionUpdate());
assertNull(sv.getLastContact());
assertEquals(new Double(1.0), sv.getLongitude());
assertEquals(new Double(2.0), sv.getLatitude());
assertEquals(new Double(3.0), sv.getBaroAltitude());
assertNull(sv.getVelocity());
assertNull(sv.getHeading());
assertNull(sv.getVerticalRate());
assertFalse(sv.isOnGround());
assertNull(sv.getSerials());
assertEquals(new Double(6743.7), sv.getGeoAltitude());
assertNull(sv.getSquawk());
assertFalse(sv.isSpi());
assertEquals(StateVector.PositionSource.ADS_B, sv.getPositionSource());
// "[\"cabeef\",\"ABCDEFG\",\"USA\",1001,1000,1.0,2.0,3.0,false,4.0,5.0,6.0,[1234,6543],6743.7,\"6714\",false,1],"
sv = statesIt.next();
assertEquals( "cabeef", sv.getIcao24());
assertEquals("ABCDEFG", sv.getCallsign());
assertEquals("USA", sv.getOriginCountry());
assertEquals(new Double(1001), sv.getLastPositionUpdate());
assertEquals(new Double(1000), sv.getLastContact());
assertEquals(new Double(1.0), sv.getLongitude());
assertEquals(new Double(2.0), sv.getLatitude());
assertEquals(new Double(3.0), sv.getBaroAltitude());
assertEquals(new Double(4.0), sv.getVelocity());
assertEquals(new Double(5.0), sv.getHeading());
assertEquals(new Double(6.0), sv.getVerticalRate());
assertFalse(sv.isOnGround());
assertArrayEquals(new Integer[] {1234, 6543}, sv.getSerials().toArray(new Integer[sv.getSerials().size()]));
assertEquals(new Double(6743.7), sv.getGeoAltitude());
assertEquals("6714", sv.getSquawk());
assertFalse(sv.isSpi());
assertEquals(StateVector.PositionSource.ASTERIX, sv.getPositionSource());
// "[\"cabeef\",\"ABCDEFG\",\"USA\",1001,1000,1.0,2.0,3.0,false,4.0,5.0,6.0,[1234],6743.7,\"6714\",true,2],"
sv = statesIt.next();
assertEquals( "cabeef", sv.getIcao24());
assertEquals("ABCDEFG", sv.getCallsign());
assertEquals("USA", sv.getOriginCountry());
assertEquals(new Double(1001), sv.getLastPositionUpdate());
assertEquals(new Double(1000), sv.getLastContact());
assertEquals(new Double(1.0), sv.getLongitude());
assertEquals(new Double(2.0), sv.getLatitude());
assertEquals(new Double(3.0), sv.getBaroAltitude());
assertEquals(new Double(4.0), sv.getVelocity());
assertEquals(new Double(5.0), sv.getHeading());
assertEquals(new Double(6.0), sv.getVerticalRate());
assertFalse(sv.isOnGround());
assertArrayEquals(new Integer[] {1234}, sv.getSerials().toArray(new Integer[sv.getSerials().size()]));
assertEquals(new Double(6743.7), sv.getGeoAltitude());
assertEquals("6714", sv.getSquawk());
assertTrue(sv.isSpi());
assertEquals(StateVector.PositionSource.UNKNOWN, sv.getPositionSource());
// "[\"cabeef\",\"ABCDEFG\",\"USA\",1001,1000,1.0,2.0,3.0,true,4.0,5.0,6.0,[],null,null,false,0],"
sv = statesIt.next();
assertEquals( "cabeef", sv.getIcao24());
assertEquals("ABCDEFG", sv.getCallsign());
assertEquals("USA", sv.getOriginCountry());
assertEquals(new Double(1001), sv.getLastPositionUpdate());
assertEquals(new Double(1000), sv.getLastContact());
assertEquals(new Double(1.0), sv.getLongitude());
assertEquals(new Double(2.0), sv.getLatitude());
assertEquals(new Double(3.0), sv.getBaroAltitude());
assertEquals(new Double(4.0), sv.getVelocity());
assertEquals(new Double(5.0), sv.getHeading());
assertEquals(new Double(6.0), sv.getVerticalRate());
assertTrue(sv.isOnGround());
assertNull(sv.getSerials());
assertNull(sv.getGeoAltitude());
assertNull(sv.getSquawk());
assertFalse(sv.isSpi());
assertEquals(StateVector.PositionSource.ADS_B, sv.getPositionSource());
}
//@Test
public void testDeserSpeed() throws IOException {
ObjectMapper mapper = new ObjectMapper();
SimpleModule sm = new SimpleModule();
sm.addDeserializer(OpenSkyStates.class, new OpenSkyStatesDeserializer());
mapper.registerModule(sm);
long count = 1000000;
long t0 = System.nanoTime();
for (long i = 0; i < count; i++) {
mapper.readValue(validJson, OpenSkyStates.class);
}
long t1 = System.nanoTime();
System.out.println("Average time: " + ((t1 - t0) / count / 1000) + "µs");
}
}
| 9,536 | Java | .java | openskynetwork/opensky-api | 324 | 121 | 13 | 2016-03-21T18:00:03Z | 2023-11-10T02:52:39Z |
OpenSkyApi.java | /FileExtraction/Java_unseen/openskynetwork_opensky-api/java/src/main/java/org/opensky/api/OpenSkyApi.java | package org.opensky.api;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import okhttp3.*;
import org.opensky.model.OpenSkyStates;
import org.opensky.model.OpenSkyStatesDeserializer;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.util.*;
/**
* Main class of the OpenSky Network API. Instances retrieve data from OpenSky via HTTP
*
* @author Markus Fuchs, [email protected]
*/
public class OpenSkyApi {
private static final String HOST = "opensky-network.org";
private static final String API_ROOT = "https://" + HOST + "/api";
private static final String STATES_URI = API_ROOT + "/states/all";
private static final String MY_STATES_URI = API_ROOT + "/states/own";
private enum REQUEST_TYPE {
GET_STATES,
GET_MY_STATES
}
private final boolean authenticated;
private final ObjectMapper mapper;
private final OkHttpClient okHttpClient;
private final Map<REQUEST_TYPE, Long> lastRequestTime;
private static class BasicAuthInterceptor implements Interceptor {
private final String credentials;
BasicAuthInterceptor(String username, String password) {
credentials = Credentials.basic(username, password);
}
@Override
public Response intercept(Chain chain) throws IOException {
Request req = chain.request()
.newBuilder()
.header("Authorization", credentials)
.build();
return chain.proceed(req);
}
}
/**
* Create an instance of the API for anonymous access.
*/
public OpenSkyApi() {
this(null, null);
}
/**
* Create an instance of the API for authenticated access
* @param username an OpenSky username
* @param password an OpenSky password for the given username
*/
public OpenSkyApi(String username, String password) {
lastRequestTime = new HashMap<>();
// set up JSON mapper
mapper = new ObjectMapper();
SimpleModule sm = new SimpleModule();
sm.addDeserializer(OpenSkyStates.class, new OpenSkyStatesDeserializer());
mapper.registerModule(sm);
authenticated = username != null && password != null;
if (authenticated) {
okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new BasicAuthInterceptor(username, password))
.build();
} else {
okHttpClient = new OkHttpClient();
}
}
/** Make the actual HTTP Request and return the parsed response
* @param baseUri base uri to request
* @param nvps name value pairs to be sent as query parameters
* @return parsed states
* @throws IOException if there was an HTTP error
*/
private OpenSkyStates getResponse(String baseUri, Collection<AbstractMap.Entry<String,String>> nvps) throws IOException {
HttpUrl parsedUrl = HttpUrl.parse(baseUri);
if (parsedUrl == null) {
throw new MalformedURLException("Could not parse uri " + baseUri);
}
HttpUrl.Builder urlBuilder = parsedUrl.newBuilder();
for (AbstractMap.Entry<String,String> nvp : nvps) {
urlBuilder.addQueryParameter(nvp.getKey(), nvp.getValue());
}
Request req = new Request.Builder()
.url(urlBuilder.build())
.build();
Response response = okHttpClient.newCall(req).execute();
if (!response.isSuccessful()) {
throw new IOException("Could not get OpenSky Vectors, response " + response);
}
String contentType = response.header("Content-Type");
Charset charset = null;
if (contentType != null) {
MediaType mediaType = MediaType.parse(contentType);
if (mediaType != null) {
charset = mediaType.charset();
}
}
if (charset != null) {
return mapper.readValue(new InputStreamReader(response.body().byteStream(), charset), OpenSkyStates.class);
} else {
throw new IOException("Could not read charset in response. Content-Type is " + contentType);
}
}
/**
* Prevent client from sending too many requests. Checks are applied on server-side, too.
* @param type identifies calling function (GET_STATES or GET_MY_STATES)
* @param timeDiffAuth time im ms that must be in between two consecutive calls if user is authenticated
* @param timeDiffNoAuth time im ms that must be in between two consecutive calls if user is not authenticated
* @return true if request may be issued, false otherwise
*/
private boolean checkRateLimit(REQUEST_TYPE type, long timeDiffAuth, long timeDiffNoAuth) {
Long t = lastRequestTime.get(type);
long now = System.currentTimeMillis();
lastRequestTime.put(type, now);
return (t == null || (authenticated && now - t > timeDiffAuth) || (!authenticated && now - t > timeDiffNoAuth));
}
/**
* Get states from server and handle errors
* @throws IOException if there was an HTTP error
*/
private OpenSkyStates getOpenSkyStates(String baseUri, ArrayList<AbstractMap.Entry<String,String>> nvps) throws IOException {
try {
return getResponse(baseUri, nvps);
} catch (MalformedURLException e) {
// this should not happen
e.printStackTrace();
throw new RuntimeException("Programming Error in OpenSky API. Invalid URI. Please report a bug");
} catch (JsonParseException | JsonMappingException e) {
// this should not happen
e.printStackTrace();
throw new RuntimeException("Programming Error in OpenSky API. Could not parse JSON Data. Please report a bug");
}
}
/**
* Represents a bounding box of WGS84 coordinates (decimal degrees) that encompasses a certain area. It is
* defined by a lower and upper bound for latitude and longitude.
*/
public static class BoundingBox {
private double minLatitude;
private double minLongitude;
private double maxLatitude;
private double maxLongitude;
/**
* Create a bounding box, given the lower and upper bounds for latitude and longitude.
*/
public BoundingBox(double minLatitude, double maxLatitude, double minLongitude, double maxLongitude) {
checkLatitude(minLatitude);
checkLatitude(maxLatitude);
checkLongitude(minLongitude);
checkLongitude(maxLongitude);
this.minLatitude = minLatitude;
this.minLongitude = minLongitude;
this.maxLatitude = maxLatitude;
this.maxLongitude = maxLongitude;
}
public double getMinLatitude() {
return minLatitude;
}
public double getMinLongitude() {
return minLongitude;
}
public double getMaxLatitude() {
return maxLatitude;
}
public double getMaxLongitude() {
return maxLongitude;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof BoundingBox)) return false;
BoundingBox that = (BoundingBox) o;
if (Double.compare(that.minLatitude, minLatitude) != 0) return false;
if (Double.compare(that.minLongitude, minLongitude) != 0) return false;
if (Double.compare(that.maxLatitude, maxLatitude) != 0) return false;
return Double.compare(that.maxLongitude, maxLongitude) == 0;
}
@Override
public int hashCode() {
int result;
long temp;
temp = Double.doubleToLongBits(minLatitude);
result = (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(minLongitude);
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(maxLatitude);
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(maxLongitude);
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
private void checkLatitude(double lat) {
if (lat < -90 || lat > 90) throw new RuntimeException(String.format("Illegal latitude %f. Must be within [-90, 90]", lat));
}
private void checkLongitude(double lon) {
if (lon < -180 || lon > 180) throw new RuntimeException(String.format("Illegal longitude %f. Must be within [-90, 90]", lon));
}
}
/**
* Retrieve state vectors for a given time. If time == 0 the most recent ones are taken.
* Optional filters might be applied for ICAO24 addresses.
*
* @param time Unix time stamp (seconds since epoch).
* @param icao24 retrieve only state vectors for the given ICAO24 addresses. If {@code null}, no filter will be applied on the ICAO24 address.
* @return {@link OpenSkyStates} if request was successful, {@code null} otherwise or if there's no new data/rate limit reached
* @throws IOException if there was an HTTP error
*/
public OpenSkyStates getStates(int time, String[] icao24) throws IOException {
ArrayList<AbstractMap.Entry<String,String>> nvps = new ArrayList<>();
if (icao24 != null) {
for (String i : icao24) {
nvps.add(new AbstractMap.SimpleImmutableEntry<>("icao24", i));
}
}
nvps.add(new AbstractMap.SimpleImmutableEntry<>("time", Integer.toString(time)));
return checkRateLimit(REQUEST_TYPE.GET_STATES, 4900, 9900) ? getOpenSkyStates(STATES_URI, nvps) : null;
}
/**
* Retrieve state vectors for a given time. If time == 0 the most recent ones are taken.
* Optional filters might be applied for ICAO24 addresses.
* Furthermore, data can be retrieved for a certain area by using a bounding box.
*
* @param time Unix time stamp (seconds since epoch).
* @param icao24 retrieve only state vectors for the given ICAO24 addresses. If {@code null}, no filter will be applied on the ICAO24 address.
* @param bbox bounding box to retrieve data for a certain area. If {@code null}, no filter will be applied on the position.
* @return {@link OpenSkyStates} if request was successful, {@code null} otherwise or if there's no new data/rate limit reached
* @throws IOException if there was an HTTP error
*/
public OpenSkyStates getStates(int time, String[] icao24, BoundingBox bbox) throws IOException {
if (bbox == null) return getStates(time, icao24);
ArrayList<AbstractMap.Entry<String,String>> nvps = new ArrayList<>();
if (icao24 != null) {
for (String i : icao24) {
nvps.add(new AbstractMap.SimpleImmutableEntry<>("icao24", i));
}
}
nvps.add(new AbstractMap.SimpleImmutableEntry<>("time", Integer.toString(time)));
nvps.add(new AbstractMap.SimpleImmutableEntry<>("lamin", Double.toString(bbox.getMinLatitude())));
nvps.add(new AbstractMap.SimpleImmutableEntry<>("lamax", Double.toString(bbox.getMaxLatitude())));
nvps.add(new AbstractMap.SimpleImmutableEntry<>("lomin", Double.toString(bbox.getMinLongitude())));
nvps.add(new AbstractMap.SimpleImmutableEntry<>("lomax", Double.toString(bbox.getMaxLongitude())));
return checkRateLimit(REQUEST_TYPE.GET_STATES, 4900, 9900) ? getOpenSkyStates(STATES_URI, nvps) : null;
}
/**
* Retrieve state vectors for your own sensors. Authentication is required for this operation.
* If time = 0 the most recent ones are taken. Optional filters may be applied for ICAO24 addresses and sensor
* serial numbers.
*
* @param time Unix time stamp (seconds since epoch).
* @param icao24 retrieve only state vectors for the given ICAO24 addresses. If {@code null}, no filter will be applied on the ICAO24 address.
* @param serials retrieve only states of vehicles as seen by the given sensors. It expects an array of sensor serial numbers which belong to the given account. If {@code null}, no filter will be applied on the sensor.
* @return {@link OpenSkyStates} if request was successful, {@code null} otherwise or if there's no new data/rate limit reached
* @throws IOException if there was an HTTP error
*/
public OpenSkyStates getMyStates(int time, String[] icao24, Integer[] serials) throws IOException {
if (!authenticated) {
throw new IllegalAccessError("Anonymous access of 'myStates' not allowed");
}
ArrayList<AbstractMap.Entry<String,String>> nvps = new ArrayList<>();
if (icao24 != null) {
for (String i : icao24) {
nvps.add(new AbstractMap.SimpleImmutableEntry<>("icao24", i));
}
}
if (serials != null) {
for (Integer s : serials) {
nvps.add(new AbstractMap.SimpleImmutableEntry<>("serials", Integer.toString(s)));
}
}
nvps.add(new AbstractMap.SimpleImmutableEntry<>("time", Integer.toString(time)));
return checkRateLimit(REQUEST_TYPE.GET_MY_STATES, 900, 0) ? getOpenSkyStates(MY_STATES_URI, nvps) : null;
}
}
| 12,356 | Java | .java | openskynetwork/opensky-api | 324 | 121 | 13 | 2016-03-21T18:00:03Z | 2023-11-10T02:52:39Z |
OpenSkyStates.java | /FileExtraction/Java_unseen/openskynetwork_opensky-api/java/src/main/java/org/opensky/model/OpenSkyStates.java | package org.opensky.model;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.util.Collection;
/**
* Represents states of vehicles at a given time.
*
* @author Markus Fuchs, [email protected]
*/
@JsonDeserialize(using = OpenSkyStatesDeserializer.class)
public class OpenSkyStates {
private int time;
private Collection<StateVector> flightStates;
/**
* @return The point in time for which states are stored
*/
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
/**
* @return Actual states for this point in time
*/
public Collection<StateVector> getStates() {
if (flightStates == null || flightStates.isEmpty()) return null;
return this.flightStates;
}
public void setStates(Collection<StateVector> states) {
this.flightStates = states;
}
} | 853 | Java | .java | openskynetwork/opensky-api | 324 | 121 | 13 | 2016-03-21T18:00:03Z | 2023-11-10T02:52:39Z |
OpenSkyStatesDeserializer.java | /FileExtraction/Java_unseen/openskynetwork_opensky-api/java/src/main/java/org/opensky/model/OpenSkyStatesDeserializer.java | package org.opensky.model;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
/**
* Custom JSON deserializer for OpenSkyStates retrieved from the API.
*
* XXX Because actual state vectors arrive as array we need a custom deserializer like this.
* If anyone comes up with something better, feel free to create a pull request!
*
* @author Markus Fuchs, [email protected]
*/
public class OpenSkyStatesDeserializer extends StdDeserializer<OpenSkyStates> {
public OpenSkyStatesDeserializer() {
super(OpenSkyStates.class);
}
private Collection<StateVector> deserializeStates(JsonParser jp) throws IOException {
ArrayList<StateVector> result = new ArrayList<>();
for (JsonToken next = jp.nextToken(); next != null && next != JsonToken.END_ARRAY; next = jp.nextToken()) {
if (next == JsonToken.START_ARRAY) {
continue;
}
if (next == JsonToken.END_OBJECT) {
break;
}
String icao24 = jp.getText();
if ("null".equals(icao24)) {
throw new JsonParseException("Got 'null' icao24", jp.getCurrentLocation());
}
StateVector sv = new StateVector(icao24);
sv.setCallsign(jp.nextTextValue());
sv.setOriginCountry(jp.nextTextValue());
sv.setLastPositionUpdate((jp.nextToken() != null && jp.getCurrentToken() != JsonToken.VALUE_NULL ? jp.getDoubleValue() : null));
sv.setLastContact((jp.nextToken() != null && jp.getCurrentToken() != JsonToken.VALUE_NULL ? jp.getDoubleValue() : null));
sv.setLongitude((jp.nextToken() != null && jp.getCurrentToken() != JsonToken.VALUE_NULL ? jp.getDoubleValue() : null));
sv.setLatitude((jp.nextToken() != null && jp.getCurrentToken() != JsonToken.VALUE_NULL ? jp.getDoubleValue() : null));
sv.setBaroAltitude((jp.nextToken() != null && jp.getCurrentToken() != JsonToken.VALUE_NULL ? jp.getDoubleValue() : null));
sv.setOnGround(jp.nextBooleanValue());
sv.setVelocity((jp.nextToken() != null && jp.getCurrentToken() != JsonToken.VALUE_NULL ? jp.getDoubleValue() : null));
sv.setHeading((jp.nextToken() != null && jp.getCurrentToken() != JsonToken.VALUE_NULL ? jp.getDoubleValue() : null));
sv.setVerticalRate((jp.nextToken() != null && jp.getCurrentToken() != JsonToken.VALUE_NULL ? jp.getDoubleValue() : null));
// sensor serials if present
next = jp.nextToken();
if (next == JsonToken.START_ARRAY) {
for (next = jp.nextToken(); next != null && next != JsonToken.END_ARRAY; next = jp.nextToken()) {
sv.addSerial(jp.getIntValue());
}
}
sv.setGeoAltitude((jp.nextToken() != null && jp.getCurrentToken() != JsonToken.VALUE_NULL ? jp.getDoubleValue() : null));
sv.setSquawk(jp.nextTextValue());
sv.setSpi(jp.nextBooleanValue());
int psi = jp.nextIntValue(0);
StateVector.PositionSource ps = psi <= StateVector.PositionSource.values().length ?
StateVector.PositionSource.values()[psi] : StateVector.PositionSource.UNKNOWN;
sv.setPositionSource(ps);
// there are additional fields (upward compatibility), consume until end of this state vector array
next = jp.nextToken();
while (next != null && next != JsonToken.END_ARRAY) {
// ignore
next = jp.nextToken();
}
// consume "END_ARRAY" or next "START_ARRAY"
jp.nextToken();
result.add(sv);
}
return result;
}
@Override
public OpenSkyStates deserialize(JsonParser jp, DeserializationContext dc) throws IOException {
if (jp.getCurrentToken() != null && jp.getCurrentToken() != JsonToken.START_OBJECT) {
throw dc.mappingException(OpenSkyStates.class);
}
try {
OpenSkyStates res = new OpenSkyStates();
for (jp.nextToken(); jp.getCurrentToken() != null && jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
if (jp.getCurrentToken() == JsonToken.FIELD_NAME) {
if ("time".equalsIgnoreCase(jp.getCurrentName())) {
int t = jp.nextIntValue(0);
res.setTime(t);
} else if ("states".equalsIgnoreCase(jp.getCurrentName())) {
jp.nextToken();
res.setStates(deserializeStates(jp));
} else {
// ignore other fields, but consume value
jp.nextToken();
}
} // ignore others
}
return res;
} catch (JsonParseException jpe) {
throw dc.mappingException(OpenSkyStates.class);
}
}
}
| 4,516 | Java | .java | openskynetwork/opensky-api | 324 | 121 | 13 | 2016-03-21T18:00:03Z | 2023-11-10T02:52:39Z |
StateVector.java | /FileExtraction/Java_unseen/openskynetwork_opensky-api/java/src/main/java/org/opensky/model/StateVector.java | package org.opensky.model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
/**
* Represents the State of a vehicle as seen by the network at a particular time.
*
* @author Markus Fuchs, [email protected]
*/
public class StateVector implements Serializable {
private static final long serialVersionUID = -8285575266619754750L;
private Double geoAltitude;
private Double longitude;
private Double latitude;
private Double velocity;
private Double heading;
private Double verticalRate;
private String icao24;
private String callsign;
private boolean onGround;
private Double lastContact;
private Double lastPositionUpdate;
private String originCountry;
private String squawk;
private boolean spi;
private Double baroAltitude;
private PositionSource positionSource;
private Set<Integer> serials;
public StateVector(String icao24) {
if (icao24 == null) throw new RuntimeException("Invalid icao24. Must not be null");
this.icao24 = icao24;
this.serials = null;
}
/**
* @return geometric altitude in meters. Can be {@code null}.
*/
public Double getGeoAltitude() {
return geoAltitude;
}
public void setGeoAltitude(Double geoAltitude) {
this.geoAltitude = geoAltitude;
}
/**
* @return longitude in ellipsoidal coordinates (WGS-84) and degrees. Can be {@code null}
*/
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
/**
* @return latitude in ellipsoidal coordinates (WGS-84) and degrees. Can be {@code null}
*/
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
/**
* @return over ground in m/s. Can be {@code null} if information not present
*/
public Double getVelocity() {
return velocity;
}
public void setVelocity(Double velocity) {
this.velocity = velocity;
}
/**
* @return in decimal degrees (0 is north). Can be {@code null} if information not present
*/
public Double getHeading() {
return heading;
}
public void setHeading(Double heading) {
this.heading = heading;
}
/**
* @return in m/s, incline is positive, decline negative. Can be {@code null} if information not present.
*/
public Double getVerticalRate() {
return verticalRate;
}
public void setVerticalRate(Double verticalRate) {
this.verticalRate = verticalRate;
}
/**
* @return ICAO24 address of the transmitter in hex string representation.
*/
public String getIcao24() {
return icao24;
}
public void setIcao24(String icao24) {
this.icao24 = icao24;
}
/**
* @return callsign of the vehicle. Can be {@code null} if no callsign has been received.
*/
public String getCallsign() { return callsign; }
public void setCallsign(String callsign) {
this.callsign = callsign;
}
/**
* @return true if aircraft is on ground (sends ADS-B surface position reports).
*/
public boolean isOnGround() {
return onGround;
}
public void setOnGround(boolean onGround) {
this.onGround = onGround;
}
/**
* @return seconds since epoch of last message overall received by this transponder.
*/
public Double getLastContact() {
return lastContact;
}
public void setLastContact(Double lastContact) {
this.lastContact = lastContact;
}
/**
* @return seconds since epoch of last position report. Can be {@code null} if there was no position report received by OpenSky within 15s before.
*/
public Double getLastPositionUpdate() {
return lastPositionUpdate;
}
public void setLastPositionUpdate(Double lastPositionUpdate) {
this.lastPositionUpdate = lastPositionUpdate;
}
public void addSerial(int serial) {
if (this.serials == null) {
this.serials = new HashSet<>();
}
this.serials.add(serial);
}
/**
* @return serial numbers of sensors which received messages from the vehicle within the validity period of this state vector. {@code null} if information is not present, i.e., there was no filter for a sensor in the request
*/
public Set<Integer> getSerials() {
return this.serials;
}
/**
* @return the country inferred through the ICAO24 address
*/
public String getOriginCountry() {
return originCountry;
}
public void setOriginCountry(String originCountry) {
this.originCountry = originCountry;
}
/**
* @return transponder code aka squawk. Can be {@code null}
*/
public String getSquawk() {
return squawk;
}
public void setSquawk(String squawk) {
this.squawk = squawk;
}
/**
* @return whether flight status indicates special purpose indicator.
*/
public boolean isSpi() {
return spi;
}
public void setSpi(boolean spi) {
this.spi = spi;
}
/**
* @return barometric altitude in meters. Can be {@code null}.
*/
public Double getBaroAltitude() {
return baroAltitude;
}
public void setBaroAltitude(Double baroAltitude) {
this.baroAltitude = baroAltitude;
}
/**
* @return origin of this state's position
*/
public PositionSource getPositionSource() {
return positionSource;
}
public void setPositionSource(PositionSource positionSource) {
this.positionSource = positionSource;
}
@Override
public String toString() {
return "StateVector{" +
"geoAltitude=" + geoAltitude +
", longitude=" + longitude +
", latitude=" + latitude +
", velocity=" + velocity +
", heading=" + heading +
", verticalRate=" + verticalRate +
", icao24='" + icao24 + '\'' +
", callsign='" + callsign + '\'' +
", onGround=" + onGround +
", lastContact=" + lastContact +
", lastPositionUpdate=" + lastPositionUpdate +
", originCountry='" + originCountry + '\'' +
", squawk='" + squawk + '\'' +
", spi=" + spi +
", baroAltitude=" + baroAltitude +
", positionSource=" + positionSource +
", serials=" + serials +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof StateVector)) return false;
StateVector that = (StateVector) o;
if (onGround != that.onGround) return false;
if (spi != that.spi) return false;
if (geoAltitude != null ? !geoAltitude.equals(that.geoAltitude) : that.geoAltitude != null) return false;
if (longitude != null ? !longitude.equals(that.longitude) : that.longitude != null) return false;
if (latitude != null ? !latitude.equals(that.latitude) : that.latitude != null) return false;
if (velocity != null ? !velocity.equals(that.velocity) : that.velocity != null) return false;
if (heading != null ? !heading.equals(that.heading) : that.heading != null) return false;
if (verticalRate != null ? !verticalRate.equals(that.verticalRate) : that.verticalRate != null) return false;
if (!icao24.equals(that.icao24)) return false;
if (callsign != null ? !callsign.equals(that.callsign) : that.callsign != null) return false;
if (lastContact != null ? !lastContact.equals(that.lastContact) : that.lastContact != null) return false;
if (lastPositionUpdate != null ? !lastPositionUpdate.equals(that.lastPositionUpdate) : that.lastPositionUpdate != null)
return false;
if (originCountry != null ? !originCountry.equals(that.originCountry) : that.originCountry != null)
return false;
if (squawk != null ? !squawk.equals(that.squawk) : that.squawk != null) return false;
if (baroAltitude != null ? !baroAltitude.equals(that.baroAltitude) : that.baroAltitude != null) return false;
if (positionSource != that.positionSource) return false;
return serials != null ? serials.equals(that.serials) : that.serials == null;
}
@Override
public int hashCode() {
int result = geoAltitude != null ? geoAltitude.hashCode() : 0;
result = 31 * result + (longitude != null ? longitude.hashCode() : 0);
result = 31 * result + (latitude != null ? latitude.hashCode() : 0);
result = 31 * result + (velocity != null ? velocity.hashCode() : 0);
result = 31 * result + (heading != null ? heading.hashCode() : 0);
result = 31 * result + (verticalRate != null ? verticalRate.hashCode() : 0);
result = 31 * result + icao24.hashCode();
result = 31 * result + (callsign != null ? callsign.hashCode() : 0);
result = 31 * result + (onGround ? 1 : 0);
result = 31 * result + (lastContact != null ? lastContact.hashCode() : 0);
result = 31 * result + (lastPositionUpdate != null ? lastPositionUpdate.hashCode() : 0);
result = 31 * result + (originCountry != null ? originCountry.hashCode() : 0);
result = 31 * result + (squawk != null ? squawk.hashCode() : 0);
result = 31 * result + (spi ? 1 : 0);
result = 31 * result + (baroAltitude != null ? baroAltitude.hashCode() : 0);
result = 31 * result + (positionSource != null ? positionSource.hashCode() : 0);
result = 31 * result + (serials != null ? serials.hashCode() : 0);
return result;
}
public enum PositionSource {
ADS_B,
ASTERIX,
MLAT,
FLARM,
UNKNOWN
}
}
| 8,892 | Java | .java | openskynetwork/opensky-api | 324 | 121 | 13 | 2016-03-21T18:00:03Z | 2023-11-10T02:52:39Z |
org.eclipse.jdt.core.javabuilder.launch | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/.externalToolBuilders/org.eclipse.jdt.core.javabuilder.launch | <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.ui.externaltools.ProgramBuilderLaunchConfigurationType">
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_BUILDER_ENABLED" value="false"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_DISABLED_BUILDER" value="org.eclipse.jdt.core.javabuilder"/>
<mapAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS"/>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
</launchConfiguration>
| 545 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
EzColocalizationTest.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/test/java/EzColocalizationTest.java | import java.io.IOException;
import java.net.URISyntaxException;
import ezcol.files.FilesIO;
import ij.IJ;
import ij.ImageJ;
import ij.ImagePlus;
/**
* Test class for Coloc 2 functionality.
*
* @author Ellen T Arena
*/
public class EzColocalizationTest {
/**
* Main method for debugging.
*
* For debugging, it is convenient to have a method that starts ImageJ, loads an
* image and calls the plugin, e.g. after setting breakpoints.
*
* @param args unused
*/
public static void main(String[] args) {
// start ImageJ
ImageJ ij = new ImageJ();
/*
try {
for(int i = 1; i <= 3; i++)
FilesIO.getImagePlus("/test_images/Sample image C" + i + ".tif", true);
} catch (IOException | URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
IJ.error("Cannot find test images");
}*/
IJ.runPlugIn(EzColocalization_.class.getName(),"");
//TestFilesIO.test();
}
}
| 931 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
TestTieRank.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/test/java/testclasses/TestTieRank.java | package testclasses;
import ezcol.cell.DataSorter;
public class TestTieRank {
public static void test(){
double[] data = {1,2,2,3,Double.NaN,Double.NaN,Double.NaN,5,5,5};
DataSorter ds = new DataSorter();
ds.sort(data);
double[] rank = ds.getRank();
System.out.println("original data");
for(double d:data){
System.out.print(d+" ");
}
System.out.println();
System.out.println("rank");
for(double d:rank){
System.out.print(d+" ");
}
System.out.println();
int[] sortedIdx = ds.getSortIdx();
System.out.println("sortedIdx");
for(int d:sortedIdx){
System.out.print(d+" ");
}
System.out.println();
}
public static void compare(){
double nan = Double.NaN;
System.out.println(0>nan);
System.out.println(0<nan);
System.out.println(1>nan);
System.out.println(1<nan);
System.out.println(!false&&false);
}
}
| 868 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
TestFilesIO.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/test/java/testclasses/TestFilesIO.java | package testclasses;
import java.io.InputStream;
import ezcol.files.FilesIO;
import ij.IJ;
import ij.ImagePlus;
import ij.io.Opener;
public class TestFilesIO {
public static void test(){
ImagePlus imp = null;
InputStream is = FilesIO.class.getResourceAsStream("/test.tif");
if (is != null) {
Opener opener = new Opener();
imp = opener.openTiff(is, "test.tif");
imp.show();
}else
IJ.error("load failed");
}
}
| 439 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
TestTreeSet.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/test/java/testclasses/TestTreeSet.java | package testclasses;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import java.util.Vector;
import ezcol.debug.Debugger;
import ezcol.debug.Debugger;
import ezcol.visual.visual3D.Element3D;
public class TestTreeSet {
static int N = 160;
static Float[] nums = new Float[N];
static Comparator<Element> comparator = new Comparator<Element>() {
@Override
public int compare(Element o1, Element o2) {
// TODO Auto-generated method stub
if (o1.getzpos() < o2.getzpos())
return 1;
else if (o1.getzpos() > o2.getzpos())
return -1;
else
return 0;
}
};
static Set<Element> set = new TreeSet<Element>(comparator);
static List<Element> vect = new Vector<Element>();
public static void test() {
// TODO Auto-generated method stub
Random rnd = new Random();
for(int i=0;i<N;i++)
nums[i] = rnd.nextFloat();
//for(int i=0;i<N;i++)
// set.add(new Element((float)i));
for(int i=0;i<N;i++)
vect.add(new Element(nums[i]));
Iterator it;
/*it = set.iterator();
System.out.println("TreeSet: ");
while(it.hasNext())
System.out.print(((Element)it.next()).getzpos()+" ");
System.out.println();*/
/*it = vect.iterator();
System.out.println("Vector: ");
while(it.hasNext())
System.out.print(((Element)it.next()).getzpos()+" ");
System.out.println();*/
Element[] elements = vect.toArray(new Element[0]);
Debugger.setTime("set");
for(int i=0;i<N;i++){
set.remove(elements[i]);
set.add(elements[i]);
}
Debugger.printTime("set", "ms");
/*it = set.iterator();
System.out.println("TreeSet: ");
while(it.hasNext())
System.out.print(((Element)it.next()).getzpos()+" ");
System.out.println();*/
Debugger.setTime("sort");
Collections.sort(vect, comparator);
Debugger.printTime("sort", "ms");
/*it = vect.iterator();
System.out.println("Vector: ");
while(it.hasNext())
System.out.print(((Element)it.next()).getzpos()+" ");
System.out.println();*/
}
}
class Element{
float data;
public Element(float data){
this.data = data;
}
public void set(float data){
this.data = data;
}
public float getzpos(){
return data;
}
}
| 2,316 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
TestWindowManager.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/test/java/testclasses/TestWindowManager.java | package testclasses;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTabbedPane;
import javax.swing.LookAndFeel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import ij.IJ;
import ij.WindowManager;
import ij.measure.ResultsTable;
import ij.plugin.frame.RoiManager;
public class TestWindowManager {
public TestWindowManager(){
Test();
}
public void Test(){
ResultsTable rt = new ResultsTable();
rt.incrementCounter();
rt.addValue("Test", Double.NaN);
rt.show("Test");
if(RoiManager.getInstance()==null){
RoiManager roiManager = new RoiManager();
}
IJ.createImage("Test", 400, 400, 2, 8).show();
JFrame mainframe = new JFrame(getClass().getSimpleName());
if (!IJ.isWindows())
mainframe.setSize(430, 610);
else
mainframe.setSize(400, 585);
mainframe.setLocation(0, (int) (Toolkit.getDefaultToolkit().getScreenSize().getHeight()/2-mainframe.getHeight()/2));
mainframe.setResizable(false);
mainframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mainframe.setBounds(100, 100, 443, 650);
mainframe.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
if(e.getButton() == MouseEvent.BUTTON3){
JMenuItem anItem = new JMenuItem("Click Me!");
JMenuItem anItem2 = new JMenuItem("Close All!");
anItem2.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
WindowManager.closeAllWindows();
}
});
JPopupMenu menu = new JPopupMenu();
menu.add(anItem);
menu.add(anItem2);
menu.show(e.getComponent(),e.getX(),e.getY());
}
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
});
JButton analyze = new JButton("Analyze");
analyze.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
WindowManager.closeAllWindows();
}
});
JTabbedPane tabs = new JTabbedPane(JTabbedPane.TOP);
tabs.setOpaque(true);
tabs.addTab("Test", new JPanel());
JMenuItem anItem = new JMenuItem("Click Me!");
JMenuItem anItem2 = new JMenuItem("Close All!");
anItem2.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
LookAndFeel laf = UIManager.getLookAndFeel();
IJ.getDir("Test...");
if(IJ.isWindows()){
try {
UIManager.setLookAndFeel(laf);
} catch (UnsupportedLookAndFeelException e2) {
IJ.error("Errors in saving windows");
}
}
}
});
JMenu menu = new JMenu("Options");
menu.add(anItem);
menu.add(anItem2);
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
JPanel panel = new JPanel();
panel.add(analyze);
//panel.add(tabs);
mainframe.setJMenuBar(menuBar);
mainframe.setContentPane(panel);
mainframe.repaint();
mainframe.setVisible(true);
}
}
| 3,779 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
TestBackgroundProcessor.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/test/java/testclasses/TestBackgroundProcessor.java | package testclasses;
import ezcol.align.BackgroundProcessor;
import ezcol.main.PluginStatic;
import ij.ImagePlus;
import ij.WindowManager;
import ij.process.ByteProcessor;
import ij.process.ImageProcessor;
public class TestBackgroundProcessor {
public static void test(){
ImageProcessor ip = WindowManager.getCurrentImage().getProcessor();
BackgroundProcessor impBackground = new BackgroundProcessor(ip,"Default");
impBackground.setManualThresholds(new double[]{ip.getMinThreshold(), ip.getMaxThreshold()});
// Change in 1.1.0
// Do NOT subtract background is threshold is manually selected
//if (!ip.isBinary())
// impBackground.rollSubBackground(ip, 50, impBackground.detectBackground(ip));
// IDcell module
// because we have calculated the background so ipThred should have
// been
// generated, in case that ipThred is null, do it again.
ByteProcessor ipMask = impBackground.thredImp(BackgroundProcessor.DEFAULT_LIGHTBACKGROUND);
ImageProcessor ipStaticMask = BackgroundProcessor.thredImp(ip, "Default", BackgroundProcessor.DEFAULT_LIGHTBACKGROUND);
new ImagePlus("ipMask", ipMask).show();
}
}
| 1,140 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
TestExceptionReporter.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/test/java/testclasses/TestExceptionReporter.java | package testclasses;
import java.util.Random;
public class TestExceptionReporter {
public TestExceptionReporter(){
test();
}
private int n=10;
private void test(){
Random rnd = new Random();
for(int i=0;i<n;i++){
if(i==rnd.nextInt(n)){
stackTrace(Thread.currentThread());
break;
}
}
}
public void stackTrace(Thread thread){
StackTraceElement[] sts = thread.getStackTrace();
for(StackTraceElement st: sts)
System.out.println(st);
System.out.println("*******************************");
System.out.println(sts.toString());
}
}
| 575 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
TestGenericDialog.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/test/java/testclasses/TestGenericDialog.java | package testclasses;
import javax.swing.JButton;
import ij.gui.GenericDialog;
import ij.process.AutoThresholder;
public class TestGenericDialog {
public TestGenericDialog(){
test();
}
private void test(){
GenericDialog gd = new GenericDialog("Cell Filter");
String[] filters = AutoThresholder.getMethods();
gd.addChoice("cell filter", filters, filters[0]);
gd.addStringField("", "0-Infinity");
gd.add(new JButton("Add"));
gd.showDialog();
}
}
| 467 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
TestMaxMin.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/test/java/testclasses/TestMaxMin.java | package testclasses;
import ij.ImagePlus;
import ij.ImageStack;
import ij.WindowManager;
import ij.process.ImageProcessor;
public class TestMaxMin {
public TestMaxMin(){
test3();
}
public void test2(){
ImagePlus imp = WindowManager.getCurrentImage();
if(imp!=null){
System.out.println("Before: "+imp.getPixel(1, 1)[0]+", processor: "+imp.getProcessor().get(1, 1));
imp.getProcessor().subtract(5000);
System.out.println("After: "+imp.getPixel(1, 1)[0]+", processor: "+imp.getProcessor().get(1, 1));
ImageStack impStack=new ImageStack(imp.getWidth(),imp.getHeight(),imp.getStackSize());
for(int i=1;i<=impStack.getSize();i++){
impStack.setProcessor(imp.getStack().getProcessor(i).duplicate(), i);
System.out.println("Before stack["+i+"]: "+impStack.getProcessor(i).get(1, 1));
impStack.getProcessor(i).subtract(5000);
System.out.println("After: stack["+i+"]: "+impStack.getProcessor(i).get(1, 1));
}
//new ImagePlus("Result",impStack).show();
}
}
private int iTest;
public void test(){
ImagePlus imp = WindowManager.getCurrentImage();
if(imp!=null)
{
ImageStack impStack=new ImageStack(imp.getWidth(),imp.getHeight(),imp.getStackSize());
for(iTest=1;iTest<=impStack.getSize();iTest++){
/*new Thread(new Runnable(){
public void run(){
impStack.setProcessor(imp.getStack().getProcessor(iTest).duplicate(), iTest);
System.out.println(iTest+" stack, max: "+impStack.getProcessor(iTest).getStatistics().max+", min: "+impStack.getProcessor(iTest).getStatistics().min);
System.out.println(iTest+" DUP stack, max: "+impStack.getProcessor(iTest).duplicate().getStatistics().max+", min: "+impStack.getProcessor(iTest).duplicate().getStatistics().min);
}
}).start();*/
ImageProcessor oldip=imp.getStack().getProcessor(iTest).duplicate();
impStack.setProcessor(oldip.duplicate(), iTest);
System.out.println(iTest+" stack, max: "+impStack.getProcessor(iTest).getMax()+", min: "+impStack.getProcessor(iTest).getMin());
System.out.println(iTest+" oldip, max: "+oldip.getMax()+", min: "+oldip.getMin());
System.out.println(iTest+" oldip DUP, max: "+oldip.duplicate().getMax()+", min: "+oldip.duplicate().getMin());
}
}
else{
System.out.println("no imp");
}
}
public void test3(){
ImagePlus imp = WindowManager.getCurrentImage();
if(imp!=null){
ImageProcessor oldip=imp.getStack().getProcessor(1).duplicate();
oldip.resetMinAndMax();
System.out.println(iTest+" imp.getStack().getProcessor(1), max: "+imp.getStack().getProcessor(1).getMax()+", min: "+imp.getStack().getProcessor(1).getMin());
System.out.println(iTest+" oldip, max: "+oldip.getMax()+", min: "+oldip.getMin());
}
}
}
| 2,733 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
TestDebugProgressGlass.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/test/java/testclasses/TestDebugProgressGlass.java | package testclasses;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
import ezcol.visual.visual2D.ProgressGlassPane;
import ij.IJ;
public class TestDebugProgressGlass implements ActionListener {
private int n=10;
private JFrame mainframe;
private JButton analyze;
private ProgressGlassPane pg;
private JButton trial;
public TestDebugProgressGlass(){GUI();}
public void GUI()
{
mainframe = new JFrame("Name");
mainframe.setSize(400, 585);
if (!IJ.isWindows())mainframe.setSize(430, 610);
mainframe.setLocation(0, (int) (Toolkit.getDefaultToolkit().getScreenSize().getHeight()/2-mainframe.getHeight()/2));
mainframe.setResizable(false);
//mainframe.setIconImage(new ImageIcon(getClass().getResource("coloc.png")).getImage());
analyze = new JButton("Analyze");
analyze.addActionListener(this);
trial = new JButton("Try");
trial.addActionListener(this);
JPanel jp = new JPanel();
jp.add(analyze);
jp.add(trial);
mainframe.getContentPane().add(jp);
pg = new ProgressGlassPane();
mainframe.setGlassPane(pg);
mainframe.setVisible(true);
/*pg.setVisible(true);
int[] processes=new int[]{0,20,40,60,80,100};
for(int i=0;i<5;i++){
pg.setValue(processes[i]);
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
pg.setVisible(false);*/
}
public Thread testRun(int i)
{
Thread thread = new Thread(new Runnable(){
public void run(){
System.out.println("test "+i);
/*try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
);
thread.start();
return thread;
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Object origin=e.getSource();
if(origin==analyze)
execute().execute();
if(origin==trial)
{
System.out.println("Action Performed");
}
/*Thread[] allThreads=new Thread[n];
for(int i=0;i<n;i++)
allThreads[i]=testRun(i);
for(int i=0;i<n;i++){
try {
allThreads[i].join();
pg.setProgress((int)((float)i/n*100));
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}*/
//pg.setVisible(false);
}
private SwingWorker<Void, Integer> execute(){
return new SwingWorker<Void, Integer>(){
private Thread[] allThreads=new Thread[n];
@Override
protected Void doInBackground()
{
pg.setVisible(true);
for (int i = 0; i <= 5; i++)
{
//Generate a bunch of numbers
allThreads[i]=testRun(i);
//Pause in between
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Store them in the 'chunks' list
publish(i);
}
return null;
}
@Override
protected void process(List<Integer> chunks)
{
for(int i : chunks)
{
//Get the numbers in the 'chunks' list
//To use wherever/however you want
try {
allThreads[i].join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pg.setProgress(i*20);
System.out.println(i);
}
}
@Override
protected void done()
{
//Something to do when everything is done
//pg.setProgress(50);
pg.setVisible(false);
pg.setValue(0);
}
};
}
}
| 4,090 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
TestDebugCostes.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/test/java/testclasses/TestDebugCostes.java | package testclasses;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import ezcol.cell.CellData;
import ezcol.debug.Debugger;
import ezcol.main.PluginConstants;
import ezcol.metric.CostesThreshold;
import ezcol.metric.MetricCalculator;
import ezcol.visual.visual2D.ScatterPlotGenerator;
import ij.gui.Plot;
public class TestDebugCostes {
public static void testPCC(){
float[] Aarray = new float[]{1, 4 ,5, 6,7 ,2 ,10, 2};
float[] Barray = new float[]{2, 3, 5,10, 2, 0, 3, 3};
CostesThreshold costes = new CostesThreshold();
Debugger.print(costes.linregCostes(Aarray, Barray, -1, -1, true));
Debugger.print(costes.linregCostes(Aarray, Barray, 11, 11, false));
}
public static void testCostes(){
System.out.println("_____________________________");
CostesThreshold costes = new CostesThreshold();
//Positive test
float[] Aarray = new float[]{1, 4 ,5, 6,7 ,2 ,10, 2};
float[] Barray = new float[]{2, 3, 5,10, 2, 0, 3, 3};
//Debugger.printCurrentLine("Positive slope dynamic: ");
//Debugger.print(costes.getCostesThrd(Aarray, Barray));
//Debugger.printCurrentLine("Positive slope slow: ");
//Debugger.print(costes.getCostesThrdSlow(Aarray, Barray));
//Negative test
float[] A2array = new float[]{1, 3, 5, 7,10, 2 ,3, 9, 1};
float[] B2array = new float[]{10,8,11, 3, 4, 5, 2, 5, 8};
//Debugger.printCurrentLine("Negative slope dynamic: ");
//Debugger.print(costes.getCostesThrd(A2array, B2array));
//Debugger.printCurrentLine("Negative slope slow: ");
//Debugger.print(costes.getCostesThrdSlow(A2array, B2array));
int length = 100;
float[] A3array = new float[length];
float[] B3array = new float[length];
//long seed = 860563119486512L;//System.nanoTime();
//long seed = 871613141857114L;//System.nanoTime();
//long seed = 874058088730499L;//System.nanoTime();
long seed = System.nanoTime();
Debugger.printCurrentLine("seed: " + seed);
Random random = new Random(seed);
for (int i = 0; i < length; i++) {
A3array[i] = random.nextInt(10000) + 1;
B3array[i] = random.nextInt(10000) + 1;
}
//Debugger.print(costes.linreg(A3array, B3array));
Debugger.print(costes.linregCostes(A3array, B3array, -10, -10, true));
double[] tmpTholds = costes.getCostesThrd(A3array, B3array);
Debugger.printCurrentLine("Random dynamic: ");
Debugger.print(tmpTholds);
/*Set<Integer> dataSet = new HashSet<Integer>(costes.dataSet);
if(dataSet.size() < costes.dataSet.size()){
// There are duplicates
Debugger.printCurrentLine("DUPLICATES!!!!!!!!!");
}
float[] Alist = new float[costes.dataSet.size()];
float[] Blist = new float[costes.dataSet.size()];
for(int i =0; i< costes.dataSet.size(); i++){
Alist[i] = A3array[costes.dataSet.get(i)];
Blist[i] = B3array[costes.dataSet.get(i)];
}*/
//double PCC1 = costes.linregCostes(Alist, Blist, -10, -10, true)[2];
//Debugger.printCurrentLine("dynamic PCC list: " + (PCC1 * PCC1));
double PCC = costes.linregCostes(A3array, B3array, (float)tmpTholds[0], (float)tmpTholds[1], false)[2];
Debugger.printCurrentLine("dynamic PCC using linregCostes: " + (PCC * PCC));
double[] slowTholds = costes.getCostesThrdSlow(A3array, B3array);
Debugger.printCurrentLine("Random slow: ");
Debugger.print(slowTholds);
ScatterPlotGenerator spg = new ScatterPlotGenerator(
TestDebugCostes.class.getSimpleName(), "Channel 1", "Channel 2",
new float[][]{A3array}, new float[][]{B3array},
new String[]{""});
//Debugger.print(tmps);
//Debugger.printCurrentLine("(0, "+(int)tmps[1]+") to ("+(int)(- tmps[1] / tmps[0])+", 0)");
//spg.addRegressionLine();
//spg.addDashLines((float)tmpTholds[0], (float)tmpTholds[1], 0);
//spg.addSolidLines((float)slowTholds[0], (float)slowTholds[1], 0);
//spg.addCostes();
spg.show();
}
}
| 3,886 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
TestDebugOutputWindow.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/test/java/testclasses/TestDebugOutputWindow.java | package testclasses;
import java.util.Random;
import ezcol.visual.visual2D.OutputWindow;
public class TestDebugOutputWindow extends OutputWindow{
public TestDebugOutputWindow(){
addImage("Channel 1", null);
addImage("Channel 2", null);
addImage("Channel 3", null);
Random rnd = new Random();
for(int t=0;t<5;t++){
double [] data = new double[rnd.nextInt(100)+1];
for(int i=0;i<data.length;i++)
data[i] = rnd.nextDouble();
addMetric(data);
}
double [] data = new double[rnd.nextInt(100)+1];
for(int i=0;i<data.length;i++)
data[i] = rnd.nextDouble();
addMetric(data);
showLogWindow();
}
}
| 637 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
Test3DScatterPlot.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/test/java/testclasses/Test3DScatterPlot.java | package testclasses;
import java.awt.Color;
import java.awt.Image;
import java.lang.reflect.Array;
import java.util.Random;
import ij.ImagePlus;
//import intra.jRenderer3D.*;
public class Test3DScatterPlot {
public static void test(){
/*JRenderer3D jRenderer3D = new JRenderer3D(125, 125, 125);
jRenderer3D.setBufferSize(512,512);
Random rnd = new Random();
for(int i=0;i<10;i++){
jRenderer3D.addPoint3D(rnd.nextInt(250), rnd.nextInt(250), rnd.nextInt(250), 5, Color.WHITE,JRenderer3D.POINT_SPHERE);
}
//jRenderer3D.setPoints3DDrawMode(JRenderer3D.POINT_SPHERE);
jRenderer3D.setBackgroundColor(0xFF000050); // dark blue background<br />
//jRenderer3D.setZAspectRatio(4); // set the z-aspect ratio to 4<br />
jRenderer3D.setTransformScale(1.5); // scale factor<br />
jRenderer3D.setTransformRotationXYZ(80, 0, 160); // rotation angles (in degrees)
jRenderer3D.doRendering();
ImagePlus impNew = new ImagePlus("rendered image", jRenderer3D.getImage());
impNew.show();*/
//new New3DSurfacePlot().run("");
}
public static void testGeneric(){
Integer[][][] cellCs = new Integer[2][3][4];
//Integer[][] testA = (Integer[][])append2D(cellCs,cellCs[0][0].getClass());
Integer[][] testB = (Integer[][])append2D(cellCs,Integer.class);
}
private static <T> T[] append2D(T[][] data, Class<? extends T> type) {
if (data == null)
return null;
int length = 0;
for (int i = 0; i < data.length; i++) {
if (data[i] != null)
length += data[i].length;
}
@SuppressWarnings("unchecked")
T[] result = (T[]) Array.newInstance(type, length);
length = 0;
for (int i = 0; i < data.length; i++) {
if (data[i] != null) {
for (int j = 0; j < data[i].length; j++)
result[length + j] = data[i][j];
length += data[i].length;
}
}
return result;
}
}
| 1,841 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
TestHistogramWindow.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/test/java/testclasses/TestHistogramWindow.java | package testclasses;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionAdapter;
import java.util.List;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
import ezcol.files.FilesIO;
import ezcol.metric.StringCompiler;
import ezcol.visual.visual2D.HistogramGenerator;
import ezcol.visual.visual2D.ProgressGlassPane;
import ij.IJ;
import ij.ImagePlus;
import ij.WindowManager;
import ij.measure.ResultsTable;
public class TestHistogramWindow implements ActionListener{
final int repeat = 2;
private ProgressGlassPane pg;
private JFrame mainframe;
public TestHistogramWindow(){
gui();
execute();
}
public TestHistogramWindow(boolean t){
finishStack();
}
private void gui(){
mainframe = new JFrame(getClass().getSimpleName());
if (!IJ.isWindows())
mainframe.setSize(430, 610);
else
mainframe.setSize(400, 585);
mainframe.setLocation(0, (int) (Toolkit.getDefaultToolkit().getScreenSize().getHeight()/2-mainframe.getHeight()/2));
mainframe.setResizable(false);
if(FilesIO.getResource("coloc.gif")!=null)
mainframe.setIconImage(new ImageIcon(FilesIO.getResource("coloc.gif")).getImage());
mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainframe.setBounds(100, 100, 443, 650);
JButton analyze = new JButton("Analyze");
analyze.addActionListener(this);
JPanel mainpanel = new JPanel();
JTextArea jtb = new JTextArea(20,20);
jtb.setLineWrap(true);
jtb.setEditable(true);
mainpanel.add(analyze);
mainpanel.add(jtb);
mainframe.getContentPane().add(mainpanel);
pg=new ProgressGlassPane();
pg.requestFocus();
pg.addMouseListener(new MouseAdapter() {});
pg.addMouseMotionListener(new MouseMotionAdapter() {});
pg.addKeyListener(new KeyAdapter() {});
mainframe.setGlassPane(pg);
mainframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mainframe.setVisible(true);
}
private void finishStack(){
HistogramGenerator histogramAll=new HistogramGenerator();
ResultsTable rt = new ResultsTable();
Random rand = new Random();
double[] x=new double[3000];
while(rt.getCounter()<x.length)
rt.incrementCounter();
for(int i=0;i<repeat;i++){
for(int j=0;j<x.length;j++){
if(rand.nextDouble()<0.2)
x[j]=Double.NaN;
else
x[j]=rand.nextDouble();
rt.setValue("Metric "+i, j, x[j]);
}
histogramAll.addToHistogramStack("Metric "+i, x);
}
histogramAll.showHistogramStack();
//ImagePlus imp = WindowManager.getCurrentImage();
//imp.duplicate().show();
//TestStackWindow tsw = new TestStackWindow(imp.duplicate());
//rt.show(getClass().getName());
}
private void execute(){
SwingWorker<Void, Integer> swVI = new SwingWorker<Void, Integer>(){
@Override
protected Void doInBackground()
{
pg.setVisible(true);
for (int iFrame=1;iFrame<=repeat;iFrame++)
{
if(isCancelled())
break;
//Work on each element
applyToStack(iFrame);
//Store them in the 'chunks' list
publish(iFrame);
}
return null;
}
@Override
protected void process(List<Integer> chunks)
{
for(int iFrame : chunks)
{
//Get the numbers in the 'chunks' list
//To use wherever/however you want
if(isCancelled())
break;
pg.setProgress(iFrame*100/(repeat));
//No delay should be put here otherwise
//the progress wouldn't show up
}
}
@Override
protected void done()
{
//Something to do when everything is done
//We have to wait here until the analysis is done
while(!isDone());
if(!isCancelled())
finishStack();
pg.setVisible(false);
pg.setValue(0);
}
};
swVI.execute();
}
private void applyToStack(int iFrame){
try {
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
execute();
}
}
| 4,612 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
TestScreenSize.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/test/java/testclasses/TestScreenSize.java | package testclasses;
import java.awt.Dimension;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class TestScreenSize {
public static void test(){
//Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
//System.out.println("width: "+screenSize.getWidth()+", length: "+screenSize.getHeight());
GraphicsDevice[] allScreens = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
int i=0;
for(GraphicsDevice curGs : allScreens)
{
System.out.println("Monitor: "+(i++));
GraphicsConfiguration curGc = curGs.getDefaultConfiguration();
Rectangle bounds = curGc.getBounds();
System.out.println(bounds.getX() + "," + bounds.getY() + " " + bounds.getWidth() + "x" + bounds.getHeight());
}
int numMonitor = allScreens.length-1;
JFrame mainframe = new JFrame("PLUGIN_NAME");
mainframe.setSize(400, 585);
JPanel superPanel = new JPanel();
superPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
JButton jbutton = new JButton("Switch");
jbutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
GraphicsDevice[] allScreens = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
GraphicsDevice myScreen = mainframe.getGraphicsConfiguration().getDevice();
int myScreenIndex = -1;
for (int i = 0; i < allScreens.length; i++) {
if (allScreens[i].equals(myScreen))
{
myScreenIndex = i;
break;
}
}
Rectangle oldBounds = allScreens[myScreenIndex].getDefaultConfiguration().getBounds();
Rectangle bounds = allScreens[numMonitor-myScreenIndex].getDefaultConfiguration().getBounds();
Rectangle mainBounds = mainframe.getBounds();
mainBounds.x = mainBounds.x - oldBounds.x;
mainBounds.y = mainBounds.y - oldBounds.y;
mainframe.setBounds(new Rectangle(bounds.x+mainBounds.x,bounds.y+mainBounds.y,mainBounds.width,mainBounds.height));
}
});
superPanel.add(jbutton);
mainframe.setContentPane(superPanel);
mainframe.setVisible(true);
}
}
| 2,365 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
TestMaskMeasure.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/test/java/testclasses/TestMaskMeasure.java | package testclasses;
import ezcol.cell.ParticleAnalyzerMT;
import ij.ImagePlus;
import ij.WindowManager;
import ij.gui.Roi;
import ij.gui.ShapeRoi;
import ij.measure.Measurements;
import ij.measure.ResultsTable;
import ij.plugin.filter.Analyzer;
import ij.plugin.filter.ParticleAnalyzer;
import ij.plugin.frame.RoiManager;
import ij.process.ImageProcessor;
public class TestMaskMeasure {
public static void test(){
ImagePlus imp = WindowManager.getCurrentImage();
if(imp==null)
return;
ImageProcessor ip = imp.getProcessor();
ResultsTable tempResultTable = new ResultsTable();
Analyzer aSys = new Analyzer(imp, Measurements.MEAN + Measurements.MEDIAN + Measurements.AREA, tempResultTable); // System
RoiManager roiManager = new RoiManager();
ParticleAnalyzer analyzer = new ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, 0, null, 0.0, Double.POSITIVE_INFINITY);
ParticleAnalyzer.setRoiManager(roiManager);
analyzer.analyze(imp);
Roi[] rois = roiManager.getRoisAsArray();
ip.resetRoi();
ShapeRoi shapeRoi = new ShapeRoi(ip.getRoi());
for(Roi roi: rois){
shapeRoi.xor(new ShapeRoi(roi));
}
imp.setRoi(shapeRoi);
// Possible problem
aSys.measure();
roiManager.addRoi(imp.getRoi());
imp.restoreRoi();
tempResultTable.show("windowTitle");
}
}
| 1,314 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
TestStackWindow.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/test/java/testclasses/TestStackWindow.java | package testclasses;
import java.awt.Panel;
import javax.swing.JButton;
import ij.IJ;
import ij.ImagePlus;
import ij.gui.StackWindow;
@SuppressWarnings("serial")
public class TestStackWindow extends StackWindow {
private boolean doUpdate;
private ImagePlus srcImp;
public TestStackWindow(ImagePlus imp) {
super(imp);
setup(imp);
// TODO Auto-generated constructor stub
}
private void setup(ImagePlus imp) {
// TODO Auto-generated method stub
Panel buttons = new Panel();
buttons.add(new JButton("A"));
buttons.add(new JButton("B"));
buttons.add(new JButton("C"));
add(buttons);
pack();
buttons.setVisible(false);
pack();
}
@Override
public void run() {
while (!done) {
if (doUpdate && srcImp!=null) {
if (srcImp.getRoi()!=null)
IJ.wait(50); //delay to make sure the roi has been updated
if (srcImp!=null) {
System.out.println("srcImp!=null");
}
}
synchronized(this) {
if (doUpdate) {
doUpdate = false; //and loop again
} else {
try {wait();} //notify wakes up the thread
catch(InterruptedException e) { //interrupted tells the thread to exit
return;
}
}
}
synchronized(this) {
try {wait();}
catch(InterruptedException e) {}
}
if (done) return;
if (slice>0) {
int s = slice;
slice = 0;
if (s!=imp.getCurrentSlice())
imp.setSlice(s);
}
}
}
}
| 1,420 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
TestUndoTextArea.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/test/java/testclasses/TestUndoTextArea.java | package testclasses;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.Document;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
import ij.IJ;
//https://web.archive.org/web/20100114122417/http://exampledepot.com/egs/javax.swing.undo/UndoText.html
public class TestUndoTextArea {
@SuppressWarnings("serial")
public TestUndoTextArea(){
JTextArea textcomp = new JTextArea();
final UndoManager undo = new UndoManager();
Document doc = textcomp.getDocument();
// Listen for undo and redo events
doc.addUndoableEditListener(new UndoableEditListener() {
public void undoableEditHappened(UndoableEditEvent evt) {
undo.addEdit(evt.getEdit());
}
});
// Create an undo action and add it to the text component
textcomp.getActionMap().put("Undo",
new AbstractAction("Undo") {
public void actionPerformed(ActionEvent evt) {
try {
if (undo.canUndo()) {
undo.undo();
}
} catch (CannotUndoException e) {
}
}
});
// Bind the undo action to ctl-Z
textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
// Create a redo action and add it to the text component
textcomp.getActionMap().put("Redo",
new AbstractAction("Redo") {
public void actionPerformed(ActionEvent evt) {
try {
if (undo.canRedo()) {
undo.redo();
}
} catch (CannotRedoException e) {
}
}
});
// Bind the redo action to ctl-Y
textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
JFrame mainframe = new JFrame(getClass().getSimpleName());
if (!IJ.isWindows())
mainframe.setSize(430, 610);
else
mainframe.setSize(400, 585);
mainframe.setLocation(0, (int) (Toolkit.getDefaultToolkit().getScreenSize().getHeight()/2-mainframe.getHeight()/2));
mainframe.setResizable(false);
mainframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mainframe.setBounds(100, 100, 443, 650);
mainframe.add(textcomp);
mainframe.setVisible(true);
}
}
| 2,519 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
TestHeatChartStackWindow.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/test/java/testclasses/TestHeatChartStackWindow.java | package testclasses;
import java.awt.Dimension;
import ezcol.visual.visual2D.HeatChart;
import ezcol.visual.visual2D.HeatChartStackWindow;
public class TestHeatChartStackWindow {
public TestHeatChartStackWindow(){
double[][] data = new double[10][10];
for(int i=0;i<data.length;i++)
for(int j=0;j<data[i].length;j++)
data[i][j]=i+j;
HeatChart heatChart = new HeatChart(data);
heatChart.setCellSize(new Dimension(50,50));
new HeatChartStackWindow(heatChart);
}
}
| 484 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
TestRemoveComponent.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/test/java/testclasses/TestRemoveComponent.java | package testclasses;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TestRemoveComponent {
static boolean added = true;
public static void test(){
JFrame jframe = new JFrame("name");
jframe.setSize(new Dimension(500,500));
JLabel jlabel = new JLabel("test");
JPanel jpanel = new JPanel();
jframe.getContentPane().add(jpanel);
GridBagLayout gbl = new GridBagLayout();
gbl.columnWidths = new int[]{0, 0};
gbl.rowHeights = new int[]{0, 0, 0};
gbl.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
jpanel.setLayout(gbl);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(0, 0, 5, 5);
gbc.gridx = 0;
gbc.gridy = 0;
jpanel.add(jlabel,gbc);
jpanel.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
if(added){
Container jc = jlabel.getParent();
if(jc!=null)
jc.remove(jlabel);
}
else{
Container jc = jlabel.getParent();
GridBagLayout tgbl = (GridBagLayout)jc.getLayout();
GridBagConstraints tgbc = tgbl.getConstraints(jlabel);
jpanel.add(jlabel,tgbc);
}
added = !added;
jpanel.revalidate();
jpanel.repaint();
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
});
jframe.setVisible(true);
}
}
| 2,110 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
TestDebugScatterPlot.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/test/java/testclasses/TestDebugScatterPlot.java | package testclasses;
import java.util.Random;
import ezcol.visual.visual2D.PlotStackWindow;
import ezcol.visual.visual2D.ScatterPlotGenerator;
public class TestDebugScatterPlot {
public TestDebugScatterPlot()
{test();}
public static void test(){
Random rand = new Random();
float[][] x=new float[1][1000];
float[][] y=new float[1][1000];
for(int i=0;i<x.length;i++)
for(int j=0;j<x[0].length;j++)
{
x[i][j]=rand.nextInt(65535) + 1;
y[i][j]=rand.nextInt(65535) + 1;
}
ScatterPlotGenerator spg=new ScatterPlotGenerator();
for(int i=0;i<x.length;i++)
spg.addPlot(x[i], y[i]);
spg.showPlot(true);
}
public static void test2(){
Random rand = new Random();
float[][] x=new float[1][1000];
float[][] y=new float[1][1000];
for(int i=0;i<x.length;i++)
for(int j=0;j<x[0].length;j++)
{
x[i][j]=rand.nextInt(65535) + 1;
y[i][j]=rand.nextInt(65535) + 1;
}
PlotStackWindow psw = new ScatterPlotGenerator("test2","Channel 1","Channel 2",
x,y,null).show();
}
}
| 1,061 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
TestDrawingSpeed.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/test/java/testclasses/TestDrawingSpeed.java | package testclasses;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.MemoryImageSource;
import java.util.Random;
public class TestDrawingSpeed {
static int width = 512, height = 624;
static Color background = Color.GRAY;
static int sizeA = 34, sizeB = 17;
static int xlen = 21, ylen = 30;
static int N = 1;
public static void test2() {
Random rnd = new Random();
Image retimage;
Graphics g;
Color tempcolor;
long time;
time = System.currentTimeMillis();
int[] bufferPixels = new int[width * height];
for (int i = 0; i < N; i++) {
int x = rnd.nextInt(width);
int y = rnd.nextInt(height);
drawEllipse(bufferPixels, width, height, x - sizeA / 2, y - sizeA / 2, sizeA, sizeB);
x = rnd.nextInt(width);
y = rnd.nextInt(height);
drawEllipse(bufferPixels, width, height, x - sizeA / 2, y - sizeA / 2, sizeB, sizeA);
x = rnd.nextInt(width);
y = rnd.nextInt(height);
drawEllipse(bufferPixels, width, height, x - sizeA / 2, y - sizeA / 2, sizeA, sizeA);
x = rnd.nextInt(width);
y = rnd.nextInt(height);
drawEllipse(bufferPixels, width, height, x - sizeA / 2, y - sizeA / 2, sizeA + 21, sizeA + 21);
}
MemoryImageSource source = new MemoryImageSource(width, height, bufferPixels, 0, width);
Image image = Toolkit.getDefaultToolkit().createImage(source);
retimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
g = retimage.getGraphics();
tempcolor = g.getColor();
g.setColor(background);
g.fillRect(0, 0, width, height);
g.setColor(tempcolor);
g.drawImage(image, 0, 0, null);
System.out.println("draw on TYPE_INT_RGB : " + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
new ij.ImagePlus("test2", retimage).show();
}
public static void test6() {
Random rnd = new Random();
Image retimage;
Graphics g;
Color tempcolor;
long time;
time = System.currentTimeMillis();
int[] bufferPixels = new int[width * height];
for (int i = 0; i < N; i++) {
int x = rnd.nextInt(width);
int y = rnd.nextInt(height);
fillOval(bufferPixels, width, height, x - sizeA / 2, y - sizeA / 2, sizeA, sizeB);
x = rnd.nextInt(width);
y = rnd.nextInt(height);
fillOval(bufferPixels, width, height, x - sizeA / 2, y - sizeA / 2, sizeB, sizeA);
x = rnd.nextInt(width);
y = rnd.nextInt(height);
fillOval(bufferPixels, width, height, x - sizeA / 2, y - sizeA / 2, sizeA, sizeA);
x = rnd.nextInt(width);
y = rnd.nextInt(height);
fillOval(bufferPixels, width, height, x - sizeA / 2, y - sizeA / 2, sizeA + 21, sizeA + 21);
}
MemoryImageSource source = new MemoryImageSource(width, height, bufferPixels, 0, width);
Image image = Toolkit.getDefaultToolkit().createImage(source);
retimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
g = retimage.getGraphics();
tempcolor = g.getColor();
g.setColor(background);
g.fillRect(0, 0, width, height);
g.setColor(tempcolor);
g.drawImage(image, 0, 0, null);
System.out.println("draw on TYPE_INT_RGB : " + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
new ij.ImagePlus("test2", retimage).show();
}
public static void test4() {
Random rnd = new Random();
Image retimage;
Graphics g;
Color tempcolor;
long time;
time = System.currentTimeMillis();
int[] bufferPixels = new int[width * height];
for (int i = 0; i < N; i++) {
int x = width / 2;// rnd.nextInt(width);
int y = height / 2;// rnd.nextInt(height);
// int xlen = rnd.nextInt(width / 10);
// int ylen = rnd.nextInt(height / 10);
drawLine(bufferPixels, width, height, x, y, x + xlen, y + ylen);
drawLine(bufferPixels, width, height, x, y, x + xlen, y);
drawLine(bufferPixels, width, height, x, y, x + xlen, y - ylen);
drawLine(bufferPixels, width, height, x, y, x, y - ylen);
drawLine(bufferPixels, width, height, x, y, x - xlen, y - ylen);
drawLine(bufferPixels, width, height, x, y, x - xlen, y);
drawLine(bufferPixels, width, height, x, y, x - xlen, y + ylen);
drawLine(bufferPixels, width, height, x, y, x, y + ylen);
drawRect(bufferPixels, width, height, x - xlen - 1, y - ylen - 1, xlen * 2 + 2, ylen * 2 + 2);
}
MemoryImageSource source = new MemoryImageSource(width, height, bufferPixels, 0, width);
Image image = Toolkit.getDefaultToolkit().createImage(source);
retimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
g = retimage.getGraphics();
tempcolor = g.getColor();
g.setColor(background);
g.fillRect(0, 0, width, height);
g.setColor(tempcolor);
g.drawImage(image, 0, 0, null);
System.out.println("draw on TYPE_INT_RGB : " + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
new ij.ImagePlus("test4", retimage).show();
}
public static void test8() {
Random rnd = new Random();
Image retimage;
Graphics g;
Color tempcolor;
long time;
time = System.currentTimeMillis();
int[] bufferPixels = new int[width * height];
for (int i = 0; i < N; i++) {
int x = rnd.nextInt(width);
int y = rnd.nextInt(height);
fillRect(bufferPixels, width, height, x - sizeA / 2, y - sizeA / 2, sizeA, sizeB);
x = rnd.nextInt(width);
y = rnd.nextInt(height);
fillRect(bufferPixels, width, height, x - sizeA / 2, y - sizeA / 2, sizeB, sizeA);
x = rnd.nextInt(width);
y = rnd.nextInt(height);
fillRect(bufferPixels, width, height, x - sizeA / 2, y - sizeA / 2, sizeA, sizeA);
x = rnd.nextInt(width);
y = rnd.nextInt(height);
fillRect(bufferPixels, width, height, x - sizeA / 2, y - sizeA / 2, sizeA + 21, sizeA + 21);
}
MemoryImageSource source = new MemoryImageSource(width, height, bufferPixels, 0, width);
Image image = Toolkit.getDefaultToolkit().createImage(source);
retimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
g = retimage.getGraphics();
tempcolor = g.getColor();
g.setColor(background);
g.fillRect(0, 0, width, height);
g.setColor(tempcolor);
g.drawImage(image, 0, 0, null);
System.out.println("draw on TYPE_INT_RGB : " + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
new ij.ImagePlus("test2", retimage).show();
}
public static void test10() {
Random rnd = new Random();
Image retimage;
Graphics g;
Color tempcolor;
long time;
int[] bufferPixels = new int[width * height];
time = System.currentTimeMillis();
for (int i = 0; i < N; i++) {
int x = rnd.nextInt(width);
int y = rnd.nextInt(height);
fillOval(bufferPixels, width, height, x - sizeA / 2, y - sizeA / 2, sizeA, sizeA);
x = rnd.nextInt(width);
y = rnd.nextInt(height);
fillOval(bufferPixels, width, height, x - sizeA / 2, y - sizeA / 2, sizeA + 21, sizeA + 21);
}
System.out.println("draw oval : " + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
time = System.currentTimeMillis();
for (int i = 0; i < N; i++) {
int x = rnd.nextInt(width);
int y = rnd.nextInt(height);
fillEllipse(bufferPixels, width, height, x - sizeA / 2, y - sizeA / 2, sizeA, sizeA);
x = rnd.nextInt(width);
y = rnd.nextInt(height);
fillEllipse(bufferPixels, width, height, x - sizeA / 2, y - sizeA / 2, sizeA + 21, sizeA + 21);
}
System.out.println("draw ellipse : " + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
MemoryImageSource source = new MemoryImageSource(width, height, bufferPixels, 0, width);
Image image = Toolkit.getDefaultToolkit().createImage(source);
retimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
g = retimage.getGraphics();
tempcolor = g.getColor();
g.setColor(background);
g.fillRect(0, 0, width, height);
g.setColor(tempcolor);
g.drawImage(image, 0, 0, null);
System.out.println("draw on TYPE_INT_RGB : " + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
new ij.ImagePlus("test2", retimage).show();
}
public static void test12() {
Random rnd = new Random();
Image retimage;
Graphics g;
Color tempcolor;
long time;
int[] bufferPixels = new int[width * height];
time = System.currentTimeMillis();
for (int i = 0; i < N; i++) {
int x = rnd.nextInt(width);
int y = rnd.nextInt(height);
drawOval(bufferPixels, width, height, x - sizeA / 2, y - sizeA / 2, sizeA, sizeA);
x = rnd.nextInt(width);
y = rnd.nextInt(height);
drawOval(bufferPixels, width, height, x - sizeA / 2, y - sizeA / 2, sizeA + 21, sizeA + 21);
}
System.out.println("draw oval : " + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
time = System.currentTimeMillis();
for (int i = 0; i < N; i++) {
int x = rnd.nextInt(width);
int y = rnd.nextInt(height);
drawEllipse(bufferPixels, width, height, x - sizeA / 2, y - sizeA / 2, sizeA, sizeA);
x = rnd.nextInt(width);
y = rnd.nextInt(height);
drawEllipse(bufferPixels, width, height, x - sizeA / 2, y - sizeA / 2, sizeA + 21, sizeA + 21);
}
System.out.println("draw ellipse : " + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
MemoryImageSource source = new MemoryImageSource(width, height, bufferPixels, 0, width);
Image image = Toolkit.getDefaultToolkit().createImage(source);
retimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
g = retimage.getGraphics();
tempcolor = g.getColor();
g.setColor(background);
g.fillRect(0, 0, width, height);
g.setColor(tempcolor);
g.drawImage(image, 0, 0, null);
System.out.println("draw on TYPE_INT_RGB : " + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
new ij.ImagePlus("test2", retimage).show();
}
/* http://www.geeksforgeeks.org/mid-point-line-generation-algorithm/ */
public static void drawLine(int[] pixels, int width, int height, int x1, int y1, int x2, int y2) {
int increX = y1 == y2 ? 0 : (y1 < y2 ? 1 : -1);
int increY = x1 == x2 ? 0 : (x1 < x2 ? 1 : -1);
// calculate dx & dy
int dy = y2 - y1;
int dx = x2 - x1;
int y1_y2 = y1 + y2, x1_x2 = x1 + x2;
boolean xDominant = dx * increY < dy * increX;
// initial value of decision parameter d
int d;
if (xDominant)
d = dx * increX - (dy / 2) * increY;
else
d = dy * increY - (dx / 2) * increX;
int x = x1, y = y1;
// Plot initial given point
// putpixel(x,y) can be used to print pixel
// of line in graphics
drawDot(pixels, width, x, y);
drawDot(pixels, width, x1_x2 - x, y1_y2 - y);
// System.out.println("X1: " + X1 + ", Y1: " + Y1 + ", X1_X2 - x: " +
// (X1_X2 - x) + ", Y1_Y2 - y: " + (Y1_Y2 - y));
// System.out.println("X1: " + X1 + ", Y1: " + Y1 + ", X2: " + X2 + ",
// Y2: " + Y2);
// System.out.println("increX: " + increX + ", increY: " + increY);
if (increX == 0 && increY == 0)
return;
boolean notMid = true;
// iterate through value of X
while (notMid) {
// System.out.println("y: "+y+", Y2 - dy / 2: "+(Y2 - dy / 2));
// System.out.println("x: " + x + ", y: " + y + ", d: " + d);
// E or East is chosen
if (xDominant) {
if (d * increX * increY <= 0) {
d += dx * increX;
}
// NE or North East is chosen
else {
d += (dx * increX - dy * increY);
x += increY;
}
y += increX;
notMid = (increX >= 0 && y <= y1_y2 / 2) || (increX <= 0 && y >= y1_y2 / 2);
} else {
if (d * increX * increY <= 0) {
d += dy * increY;
} else {
d += (dy * increY - dx * increX);
y += increX;
}
x += increY;
notMid = (increY >= 0 && x <= x1_x2 / 2) || (increY <= 0 && x >= x1_x2 / 2);
}
// Plot intermediate points
// putpixel(x,y) is used to print pixel
// of line in graphics
drawDot(pixels, width, x, y);
drawDot(pixels, width, x1_x2 - x, y1_y2 - y);
}
}
private static void drawDot(int[] pixels, int offset, int x, int y, int value) {
int idx = y * offset + x;
if (x >= 0 && x < offset && y >= 0 && y < pixels.length / offset)
pixels[idx] = value;
}
private static void drawDot(int[] pixels, int offset, int x, int y) {
drawDot(pixels, offset, x, y, Color.WHITE.getRGB());
}
public static void drawOval2(int[] pixels, int width, int height, int sx, int sy, int w, int h) {
int x, y;
int a = (w + 1) / 2, b = (h + 1) / 2;
int a2 = a * a, b2 = b * b;
int cx = (w - 1) / 2, cy = (h + 1) / 2;
x = w;
y = b;
drawDot(pixels, width, x + sx, y + sy);
// When radius is zero only a single
// point will be printed
if (w > 0) {
drawDot(pixels, width, x + sx, h - y + sy);
drawDot(pixels, width, w - x + sx, y + sy);
drawDot(pixels, width, w - x + sx, h - y + sy);
}
// Initialising the value of P
int P = (x - cx) * (x - cx) * b2 - (x - cx) * b2 + b2 / 4 + a2 - a2 * b2;
while (x - cx > y - cy) {
System.out.println("x: " + (x - a) + ", y: " + (y - b) + ", P: " + P);
y++;
// Mid-point is inside or on the perimeter
if (P <= 0)
P = P + 2 * (y - cy) * a2 + a2;
// Mid-point is outside the perimeter
else {
x--;
P = P + 2 * (y - cy) * a2 + a2 - 2 * (x - cx) * b2;
}
// All the perimeter points have already been printed
if (x - cx < y - cy)
break;
// Printing the generated point and its reflection
// in the other octants after translation
drawDot(pixels, width, x + sx, y + sy);
drawDot(pixels, width, x + sx, h - y + sy);
drawDot(pixels, width, w - x + sx, h - y + sy);
drawDot(pixels, width, w - x + sx, y + sy);
}
x = a;
y = h;
drawDot(pixels, width, x + sx, y + sy);
// When radius is zero only a single
// point will be printed
if (h > 0) {
drawDot(pixels, width, w - x + sx, y + sy);
drawDot(pixels, width, x + sx, h - y + sy);
drawDot(pixels, width, w - x + sx, h - y + sy);
}
P = (y - cy) * (y - cy) * a2 - (y - cy) * a2 + a2 / 4 + b2 - a2 * b2;
while (x - cx < y - cy) {
x++;
// Mid-point is inside or on the perimeter
if (P <= 0)
P = P + 2 * (x - cx) * b2 + b2;
// Mid-point is outside the perimeter
else {
y--;
P = P + 2 * (x - cx) * b2 + b2 - 2 * (y - cy) * a2;
}
// All the perimeter points have already been printed
if (x - cx > y - cy)
break;
// Printing the generated point and its reflection
// in the other octants after translation
drawDot(pixels, width, x + sx, y + sy);
drawDot(pixels, width, x + sx, h - y + sy);
drawDot(pixels, width, w - x + sx, h - y + sy);
drawDot(pixels, width, w - x + sx, y + sy);
}
drawRect(pixels, width, height, sx - 1, sy - 1, w + 2, h + 2);
}
public static void drawOval(int[] pixels, int width, int height, int sx, int sy, int w, int h) {
if(w==h)
drawCircle(pixels,width,height,sx,sy,w);
else
drawEllipse(pixels,width,height,sx,sy,w,h);
}
/* http://www.geeksforgeeks.org/mid-point-circle-drawing-algorithm/ */
public static void drawEllipse(int[] pixels, int width, int height, int sx, int sy, int w, int h) {
int x, y;
int offsetA = w % 2, offsetB = h % 2;
int a = (w - offsetA) / 2, b = (h - offsetB) / 2;
int a2 = a * a, b2 = b * b;
int cx = (w + offsetA) / 2, cy = (h + offsetB) / 2;
x = w - cx;
y = b - cy;
drawDot(pixels, width, x + cx + sx, y + cy + sy);
// When radius is zero only a single
// point will be printed
if (w > 0) {
drawDot(pixels, width, x + cx + sx, h - y - cy + sy);
drawDot(pixels, width, w - x - cx + sx, y + cy + sy);
drawDot(pixels, width, w - x - cx + sx, h - y - cy + sy);
}
// Initialising the value of P
int P = x * x * b2 - x * b2 + b2 / 4 + a2 - a2 * b2;
while (x * b >= y * a) {
// System.out.println("x: " + x + ", y: " + y);
y++;
// Mid-point is inside or on the perimeter
if (P <= 0)
P = P + 2 * y * a2 + a2;
// Mid-point is outside the perimeter
else {
x--;
P = P + 2 * y * a2 + a2 - 2 * x * b2;
}
// All the perimeter points have already been printed
if (x * b < y * a)
break;
// Printing the generated point and its reflection
// in the other octants after translation
drawDot(pixels, width, x + cx + sx, y + cy + sy);
drawDot(pixels, width, x + cx + sx, h - y - cy + sy);
drawDot(pixels, width, w - x - cx + sx, h - y - cy + sy);
drawDot(pixels, width, w - x - cx + sx, y + cy + sy);
}
x = a - cx;
y = h - cy;
drawDot(pixels, width, x + cx + sx, y + cy + sy);
// When radius is zero only a single
// point will be printed
if (w > 0) {
drawDot(pixels, width, x + cx + sx, h - y - cy + sy);
drawDot(pixels, width, w - x - cx + sx, y + cy + sy);
drawDot(pixels, width, w - x - cx + sx, h - y - cy + sy);
}
P = y * y * a2 - y * a2 + a2 / 4 + b2 - a2 * b2;
while (x * b <= y * a) {
//System.out.println("x: " + x + ", y: " + y);
x++;
// Mid-point is inside or on the perimeter
if (P <= 0)
P = P + 2 * x * b2 + b2;
// Mid-point is outside the perimeter
else {
y--;
P = P + 2 * x * b2 + b2 - 2 * y * a2;
}
// All the perimeter points have already been printed
if (x * b > y * a)
break;
// Printing the generated point and its reflection
// in the other octants after translation
drawDot(pixels, width, x + cx + sx, y + cy + sy);
drawDot(pixels, width, x + cx + sx, h - y - cy + sy);
drawDot(pixels, width, w - x - cx + sx, h - y - cy + sy);
drawDot(pixels, width, w - x - cx + sx, y + cy + sy);
}
drawRect(pixels, width, height, sx - 1, sy - 1, w + 2, h + 2);
}
public static void drawCircle(int[] pixels, int width, int height, int sx, int sy, int size) {
int x, y;
int offset = size % 2;
int r = (size - offset) / 2;
int c = (size + offset) / 2;
x = size - c;
y = r - c;
drawDot(pixels, width, x + c + sx, y + c + sy);
// When radius is zero only a single
// point will be printed
if (size > 0) {
drawDot(pixels, width, x + c + sx, size - y - c + sy);
drawDot(pixels, width, size - x - c + sx, y + c + sy);
drawDot(pixels, width, size - x - c + sx, size - y - c + sy);
drawDot(pixels, width, y + c + sx, x + c + sy);
drawDot(pixels, width, y + c + sx, size - x - c + sy);
drawDot(pixels, width, size - y - c + sx, x + c + sy);
drawDot(pixels, width, size - y - c + sx, size - x - c + sy);
}
// Initialising the value of P
int P = x * x - x + 1 - r * r;
while (x > y) {
//System.out.println("x: " + x + ", y: " + y + ", P: "+P + ", r: "+r);
y++;
// Mid-point is inside or on the perimeter
if (P <= 0)
P += + 2 * y + 1;
// Mid-point is outside the perimeter
else {
x--;
P += + 2 * y + 1 - 2 * x;
}
// All the perimeter points have already been printed
if (x < y)
break;
// Printing the generated point and its reflection
// in the other octants after translation
drawDot(pixels, width, x + c + sx, y + c + sy);
drawDot(pixels, width, x + c + sx, size - y - c + sy);
drawDot(pixels, width, size - x - c + sx, size - y - c + sy);
drawDot(pixels, width, size - x - c + sx, y + c + sy);
if(x!=y){
drawDot(pixels, width, y + c + sx, x + c + sy);
drawDot(pixels, width, y + c + sx, size - x - c + sy);
drawDot(pixels, width, size - y - c + sx, size - x - c + sy);
drawDot(pixels, width, size - y - c + sx, x + c + sy);
}
}
}
public static void fillOval(int[] pixels, int width, int height, int sx, int sy, int w, int h){
if(w==h)
fillCircle(pixels,width,height,sx,sy,w);
else
fillEllipse(pixels,width,height,sx,sy,w,h);
}
public static void fillCircle(int[] pixels, int width, int height, int sx, int sy, int size) {
int x, y;
int offset = size % 2;
int r = (size - offset) / 2;
int c = (size + offset) / 2;
x = size - c;
y = r - c;
drawDot(pixels, width, x + c + sx, y + c + sy);
// When radius is zero only a single
// point will be printed
if (size > 0) {
for (int j = size - y - c; j <= y+c; j++) {
drawDot(pixels, width, x + c + sx, j + sy);
drawDot(pixels, width, size - x - c + sx, j + sy);
drawDot(pixels, width, j + sx, x +c + sy);
drawDot(pixels, width, j + sx, size - x - c + sy);
}
}
// Initialising the value of P
int P = x * x - x + 1 - r * r;
while (x > y) {
//System.out.println("x: " + x + ", y: " + y + ", P: "+P + ", r: "+r);
y++;
// Mid-point is inside or on the perimeter
if (P <= 0)
P += + 2 * y + 1;
// Mid-point is outside the perimeter
else {
x--;
P += + 2 * y + 1 - 2 * x;
}
// All the perimeter points have already been printed
if (x < y)
break;
// Printing the generated point and its reflection
// in the other octants after translation
for (int j = size - y - c; j <= y+c; j++) {
drawDot(pixels, width, x + c + sx, j + sy);
drawDot(pixels, width, size - x - c + sx, j + sy);
drawDot(pixels, width, j + sx, x +c + sy);
drawDot(pixels, width, j + sx, size - x - c + sy);
}
}
for (int i = size - x - c + sx; i <= x + c + sx; i++) {
for (int j = size - y - c + sy; j <= y + c + sy; j++) {
drawDot(pixels, width, i, j);
}
}
}
public static void fillEllipse(int[] pixels, int width, int height, int sx, int sy, int w, int h) {
int x, y;
int offsetA = w % 2, offsetB = h % 2;
int a = (w - offsetA) / 2, b = (h - offsetB) / 2;
int a2 = a * a, b2 = b * b;
int cx = (w + offsetA) / 2, cy = (h + offsetB) / 2;
int innerX, innerY;
x = w - cx;
y = b - cy;
// When radius is zero only a single
// point will be printed
if (w > 0) {
for (int j = h - y - cy + sy; j <= y + cy + sy; j++) {
drawDot(pixels, width, x + cx + sx, j);
drawDot(pixels, width, w - x - cx + sx, j);
}
}
// Initialising the value of P
int P = x * x * b2 - x * b2 + b2 / 4 + a2 - a2 * b2;
while (x * b >= y * a) {
// System.out.println("x: " + x + ", y: " + y);
y++;
// Mid-point is inside or on the perimeter
if (P <= 0)
P = P + 2 * y * a2 + a2;
// Mid-point is outside the perimeter
else {
x--;
P = P + 2 * y * a2 + a2 - 2 * x * b2;
}
// All the perimeter points have already been printed
if (x * b < y * a)
break;
// Printing the generated point and its reflection
// in the other octants after translation
for (int j = h - y - cy + sy; j <= y + cy + sy; j++) {
drawDot(pixels, width, x + cx + sx, j);
drawDot(pixels, width, w - x - cx + sx, j);
}
}
innerX = x;
innerY = y;
x = a - cx;
y = h - cy;
// When radius is zero only a single
// point will be printed
if (h > 0) {
for (int i = w - x - cx + sx; i <= x + cx + sx; i++) {
drawDot(pixels, width, i, y + cy + sy);
drawDot(pixels, width, i, h - y - cy + sy);
}
}
P = y * y * a2 - y * a2 + a2 / 4 + b2 - a2 * b2;
while (x * b <= y * a) {
// System.out.println("x: " + x + ", y: " + y);
x++;
// Mid-point is inside or on the perimeter
if (P <= 0)
P = P + 2 * x * b2 + b2;
// Mid-point is outside the perimeter
else {
y--;
P = P + 2 * x * b2 + b2 - 2 * y * a2;
}
// All the perimeter points have already been printed
if (x * b > y * a)
break;
// Printing the generated point and its reflection
// in the other octants after translation
for (int i = w - x - cx + sx; i <= x + cx + sx; i++) {
drawDot(pixels, width, i, y + cy + sy);
drawDot(pixels, width, i, h - y - cy + sy);
}
}
innerX = x < innerX ? x : innerX;
innerY = y < innerY ? y : innerY;
for (int i = w - innerX - cx + sx; i <= innerX + cx + sx; i++) {
for (int j = h - innerY - cy + sy; j <= innerY + cy + sy; j++) {
drawDot(pixels, width, i, j);
}
}
drawRect(pixels, width, height, sx - 1, sy - 1, w + 2, h + 2);
}
public static void drawRect(int[] pixels, int width, int height, int x, int y, int w, int h) {
for (int i = x; i <= x + w; i++) {
drawDot(pixels, width, i, y, Color.YELLOW.getRGB());
drawDot(pixels, width, i, y + h, Color.YELLOW.getRGB());
}
for (int j = y; j <= y + h; j++) {
drawDot(pixels, width, x, j, Color.YELLOW.getRGB());
drawDot(pixels, width, x + w, j, Color.YELLOW.getRGB());
}
}
public static void fillRect(int[] pixels, int width, int height, int x, int y, int w, int h) {
for (int i = x; i <= x + w; i++) {
for (int j = y; j <= y + h; j++) {
drawDot(pixels, width, i, j, Color.YELLOW.getRGB());
}
}
}
public static void drawOval4(int[] pixels, int width, int height, int x, int y, int w, int h) {
int innerW = (w) / 2, innerH = (h) / 2;
int outerW = (w + 1) / 2, outerH = (h + 1) / 2;
int xCenter = w / 2, yCenter = h / 2;
for (int i = 0; i < w; i++) {
if (i + x >= width || i + x < 0)
continue;
for (int j = 0; j < h; j++) {
if (j + y >= height || j + y < 0)
continue;
if ((((i - xCenter) * (i - xCenter) * outerH * outerH
+ (j - yCenter) * (j - yCenter) * outerW * outerW) < outerW * outerW * outerH * outerH)
&& (((i - xCenter) * (i - xCenter) * innerH * innerH
+ (j - yCenter) * (j - yCenter) * innerW * innerW) >= innerW * innerW * innerH
* innerH)) {
pixels[(x + i) * width + y + j] = Color.WHITE.getRGB();
}
}
}
drawRect(pixels, width, height, x, y, w, h);
}
public static void test1() {
Random rnd = new Random();
Image retimage;
Graphics g;
Color tempcolor;
long time;
time = System.currentTimeMillis();
retimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
g = retimage.getGraphics();
tempcolor = g.getColor();
g.setColor(background);
g.fillRect(0, 0, width, height);
g.setColor(tempcolor);
for (int i = 0; i < N; i++) {
int x = rnd.nextInt(width);
int y = rnd.nextInt(height);
g.setColor(Color.WHITE);
g.drawOval(x - sizeA / 2, y - sizeA / 2, sizeA, sizeB);
x = rnd.nextInt(width);
y = rnd.nextInt(height);
g.drawOval(x - sizeA / 2, y - sizeA / 2, sizeB, sizeA);
x = rnd.nextInt(width);
y = rnd.nextInt(height);
g.drawOval(x - sizeA / 2, y - sizeA / 2, sizeA, sizeA);
x = rnd.nextInt(width);
y = rnd.nextInt(height);
g.drawOval(x - sizeA / 2, y - sizeA / 2, sizeA + 21, sizeA + 21);
g.setColor(Color.YELLOW);
g.drawRect(x - sizeA / 2 - 1, y - sizeA / 2 - 1, sizeA + 2, sizeB + 2);
}
System.out.println("draw on TYPE_INT_RGB : " + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
new ij.ImagePlus("test", retimage).show();
}
public static void test3() {
Random rnd = new Random();
Image retimage;
Graphics g;
Color tempcolor;
long time;
time = System.currentTimeMillis();
retimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
g = retimage.getGraphics();
tempcolor = g.getColor();
g.setColor(background);
g.fillRect(0, 0, width, height);
g.setColor(tempcolor);
for (int i = 0; i < N; i++) {
g.setColor(Color.WHITE);
int x = width / 2;// rnd.nextInt(width);
int y = height / 2;// rnd.nextInt(height);
// int xlen = rnd.nextInt(width / 10);
// int ylen = rnd.nextInt(height / 10);
g.drawLine(x, y, x + xlen, y + ylen);
g.drawLine(x, y, x + xlen, y);
g.drawLine(x, y, x + xlen, y - ylen);
g.drawLine(x, y, x, y - ylen);
g.drawLine(x, y, x - xlen, y - ylen);
g.drawLine(x, y, x - xlen, y);
g.drawLine(x, y, x - xlen, y + ylen);
g.drawLine(x, y, x, y + ylen);
g.setColor(Color.YELLOW);
g.drawRect(x - xlen - 1, y - ylen - 1, xlen * 2 + 2, ylen * 2 + 2);
}
System.out.println("draw on TYPE_INT_RGB : " + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
new ij.ImagePlus("test3", retimage).show();
}
}
| 27,825 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
TestRoiManager2Mask.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/test/java/testclasses/TestRoiManager2Mask.java | package testclasses;
import java.awt.Color;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import ij.IJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.gui.NewImage;
import ij.gui.Roi;
import ij.plugin.frame.RoiManager;
import ij.process.ByteProcessor;
import ij.process.ImageProcessor;
public class TestRoiManager2Mask {
public TestRoiManager2Mask(){
test();
}
private void test(){
ImagePlus imp = IJ.createImage("test", 400, 400, 5, 8);
imp = roiManager2Mask(imp);
if(imp!=null)
imp.show();
}
private ImagePlus roiManager2Mask(ImagePlus imp){
RoiManager roiManager = RoiManager.getInstance2();
if(roiManager==null)
return null;
Roi[] rois = roiManager.getRoisAsArray();
Map<Integer,List<Roi>> roiMap = new HashMap<Integer,List<Roi>>();
for(Roi roi : rois){
List<Roi> list = roiMap.get(roi.getPosition());
if(list==null)
list = new ArrayList<Roi>();
list.add(roi);
roiMap.put(roi.getPosition(), list);
}
int nSlices = imp.getNSlices(),
nFrames = imp.getNFrames(),
nChannels = imp.getNChannels();
imp = IJ.createHyperStack("Mask of Roi(s) in Roi Manager",
imp.getWidth(), imp.getHeight(), nChannels, nSlices, nChannels, 8);
ImageStack impStack = imp.getStack();
Roi[] allRois = roiMap.get(0).toArray(new Roi[0]);
int index;
for(int channel=1;channel<=nChannels;channel++)
for(int slice=1;slice<=nSlices;slice++)
for(int frame=1;frame<=nFrames;frame++){
index = (frame-1)*nChannels*nSlices + (slice-1)*nChannels + channel ;
List<Roi> list = roiMap.get(index);
if(list!=null){
Roi[] thisRois = new Roi[list.size()+allRois.length];
System.arraycopy(allRois, 0, thisRois, 0, allRois.length);
System.arraycopy(list.toArray(), 0, thisRois, allRois.length, list.size());
impStack.setProcessor(roi2mask(impStack.getProcessor(index),thisRois),index);
}
else{
impStack.setProcessor(roi2mask(impStack.getProcessor(index),allRois),index);
}
}
return imp;
}
private ByteProcessor roi2mask(ImageProcessor ip,Roi[] rois)
{
if(ip==null)
return null;
int w=ip.getWidth();
int h=ip.getHeight();
if(rois==null||rois.length<1)
return new ByteProcessor(w,h);
ByteProcessor result=new ByteProcessor(w,h);
result.setColor(Color.WHITE);
for (int i=0; i<rois.length; i++){
if(rois[i]!=null)
result.fill(rois[i]);
}
result.resetRoi();
result.invert();
return result;
}
}
| 2,509 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
EzColocalization_.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/EzColocalization_.java | import ij.Macro;
import ij.plugin.PlugIn;
import ezcol.main.AnalysisOperator;
import ezcol.main.GUI;
import ezcol.main.MacroHandler;
import ezcol.main.PluginStatic;
/**
* This class is put in the default package so that
* ImageJ could automatically load the plugin
* Some of
* @author Huanjie Sheng, Weston Stauffer, Han N. Lim
*
*/
public class EzColocalization_ implements PlugIn{
public void run(String arg) {
//IJ.error(System.getProperty("java.home")+"\n"+ToolProvider.getSystemJavaCompiler());
//ezcol.metric.getJDKpath.getJDKpath_test();
//pass the class name to the macrohandler in case of recording
PluginStatic.setPlugIn(getClass());
if (Macro.getOptions()==null){
new GUI();
}
else{
//MyDebug.printSelectedOptions(AnalysisOperator.getOptions());
if(!MacroHandler.macroSaveAndClose(Macro.getOptions())){
MacroHandler.macroInterpreter(Macro.getOptions());
new AnalysisOperator().execute(true);
}
}
}
}
| 1,046 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
MacroHandler.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/main/MacroHandler.java | package ezcol.main;
import java.io.File;
import java.util.Arrays;
import java.util.Hashtable;
import ij.IJ;
import ij.ImagePlus;
import ij.Menus;
import ij.WindowManager;
import ij.plugin.frame.Recorder;
import ezcol.metric.BasicCalculator;
import ezcol.metric.StringCompiler;
/**
* This class contains purely static variables to handle the recording and
* the interpretation of macro code.
* @author Huanjie Sheng
*
*/
public class MacroHandler extends PluginStatic{
//cell filters macro
private static final String[] MACRO_FILTERSTRINGS = macroStrArray(filterStrings);
private static final String[] MACRO_SIZEFILTERS = macroStrArray(SIZE_FILTERS);
//image macro
private static final String[] MACRO_IMGLABELS = macroStrArray(imgLabels);
//alignment macro
private static final String[] MACRO_ALLTHOLDS = macroStrArray(ALLTHOLDS);
//heatmaps macro
private static final String[] MACRO_HEATMAPS = macroStrArray(HEATMAPS);
private static final String[] MACRO_HEATMAPOPTS = macroStrArray(HEATMAPOPTS);
//analysis macro
private static final String[] MACRO_METRICNAMES = macroStrArray(METRICACRONYMS);
private static final String[] MACRO_OTHERNAMES = macroStrArray(OTHERNAMES);
//output macro
private static final String[] MACRO_OUTPUTMETRICS = macroStrArray(OUTPUTMETRICS);
private static final String[] MACRO_OUTPUTOTHERS = macroStrArray(OUTPUTOTHERS);
private static final String[] MACRO_METRIC_THOLDS = macroStrArray(METRIC_THOLDS);
/**
* This method reads the input string from ImageJ macro
* and retrieve all necessary parameters
* If the option is missing, the default value will be used
* @warning Please make sure all strings match to the corresponding strings in macroGenerator
* @param arg macro string
*/
public static void macroInterpreter(String arg){
if(arg==null||arg.length()<=0)
return;
int start=0, end=0;
//Check what should be done
//Find the images' names
ImagePlus temp = null;
for (int ipic=0;ipic<imps.length;ipic++){
start=arg.indexOf(MACRO_IMGLABELS[ipic]+"=");
if(start==-1){
imps[ipic] = null;
}else{
start += (MACRO_IMGLABELS[ipic]+"=").length();
end=arg.indexOf(" ", start);
if ((arg.charAt(start)+"").equals("[")){
start++;
end=arg.indexOf("]", start);
}
String imgTitle=arg.substring(start, end);
if(imgTitle.equals(ImageInfo.ROI_MANAGER)){
imps[ipic] = roiManager2Mask(temp);
// introduced in 1.1.3 force black background when ROI manager is used.
lightBacks[ipic] = false;
}
else if(imgTitle.equals(ImageInfo.NONE))
imps[ipic] = null;
else{
imps[ipic] = WindowManager.getImage(imgTitle);
temp = imps[ipic];
}
}
}
start=end+1;
//get rid of images' names to be safe
if(start>=arg.length())
return;
else
arg = arg.substring(start,arg.length());
//Macro.getOptions() adds a space after the string before returning it
if(arg.charAt(arg.length()-1)!=' ')
arg = arg + " ";
//However, this is absolutely necessary to add a space before arg
if(arg.charAt(0)!=' ')
arg = " " + arg;
for(int iColumn=0;iColumn<metric_chckes.length;iColumn++){
start = arg.indexOf(MACRO_METRICNAMES[iColumn]);
if(start==-1)
metric_chckes[iColumn] = false;
else{
end = start + MACRO_METRICNAMES[iColumn].length();
metric_chckes[iColumn] = arg.charAt(end)==' ' && arg.charAt(start-1)==' ';
}
}
boolean anyOtherMetric = false;
for(int iColumn=0;iColumn<other_chckes.length;iColumn++){
start = arg.indexOf(MACRO_OTHERNAMES[iColumn]);
if(start==-1)
other_chckes[iColumn] = false;
else{
end = start + MACRO_OTHERNAMES[iColumn].length();
other_chckes[iColumn] = arg.charAt(end)==' ' && arg.charAt(start-1)==' ';
}
anyOtherMetric |= other_chckes[iColumn];
}
if(other_chckes[CUSTOM]){
custom_chck = true;
start=arg.indexOf("custom-javafile=");
if(start==-1){
customCode_text = "";
}else{
start += ("custom-javafile=").length();
end=arg.indexOf(" ", start);
if ((arg.charAt(start)+"").equals("[")){
start++;
end=arg.indexOf("]", start);
}
String path=arg.substring(start, end);
customCode_text = StringCompiler.open(path);
}
}
for(int iThold=0;iThold<alignThold_combs.length;iThold++){
start=arg.indexOf("alignthold"+(iThold+1)+"=");
if(start==-1){
alignThold_combs[iThold] = DEFAULT_CHOICE;
if(iThold < align_chckes.length)
align_chckes[iThold] = false;
}else{
start += ("alignthold"+(iThold+1)+"=").length();
end=arg.indexOf(" ", start);
if ((arg.charAt(start)+"").equals("[")){
start++;
end=arg.indexOf("]", start);
}
String thresholdMethod = arg.substring(start, end);
alignThold_combs[iThold] = Arrays.asList(MACRO_ALLTHOLDS).indexOf(thresholdMethod);
if(iThold < align_chckes.length)
align_chckes[iThold] = true;
}
}
{
start = arg.indexOf("dows");
if(start==-1)
waterShed_chck = false;
else{
end = start + "dows".length();
waterShed_chck = (end>=arg.length() || arg.charAt(end) ==' ')
&& (start<=0 || arg.charAt(start-1)==' ');
}
}
for (int iSize=0;iSize<MACRO_SIZEFILTERS.length;iSize++){
start=arg.indexOf(MACRO_SIZEFILTERS[iSize]+"=");
if(start==-1){
filterMinSize_texts[iSize] = DEFAULT_MIN;
filterMaxSize_texts[iSize] = DEFAULT_MAX;
}else{
start += (SIZE_FILTERS[iSize]+"=").length();
end=arg.indexOf(" ", start);
if ((arg.charAt(start)+"").equals("[")){
start++;
end=arg.indexOf("]", start);
}
String tempSize=arg.substring(start, end);
double[] range = str2doubles(tempSize);
filterMinSize_texts[iSize] = range[0];
filterMaxSize_texts[iSize] = range[1];
}
}
for(int iFilter=0;iFilter<filter_combs.length;iFilter++){
//getFilterChoices
start=arg.indexOf("filter"+(iFilter+1)+"=");
if(start==-1){
filter_combs[iFilter] = DEFAULT_CHOICE;
}else{
start += (("filter"+(iFilter+1)+"=").length());
end=arg.indexOf(" ", start);
if ((arg.charAt(start)+"").equals("[")){
start++;
end=arg.indexOf( "]", start);
}
String thisFilter=arg.substring(start, end);
filter_combs[iFilter]=Arrays.asList(MACRO_FILTERSTRINGS).indexOf(thisFilter);
}
//getFilterRange
start=arg.indexOf("range"+(iFilter+1)+"=");
if(start==-1){
filterMinRange_texts[iFilter] = DEFAULT_MIN;
filterMaxRange_texts[iFilter] = DEFAULT_MAX;
}else{
start += (("range"+(iFilter+1)+"=").length());
end=arg.indexOf(" ", start);
if ((arg.charAt(start)+"").equals("[")){
start++;
end=arg.indexOf("]", start);
}
String filterRange=arg.substring(start, end);
double[] range = str2doubles(filterRange);
filterMinRange_texts[iFilter] = range[0];
filterMaxRange_texts[iFilter] = range[1];
}
}
adFilterChoices.clear();
end=0;
while(true){
start=arg.indexOf("filterA",end);
if(start==-1)
break;
start=arg.indexOf("=", start) + 1 ;
end=arg.indexOf(" ", start);
if ((arg.charAt(start)+"").equals("[")){
start++;
end=arg.indexOf( "]", start);
}
String thisFilter=arg.substring(start, end);
adFilterChoices.add(Arrays.asList(MACRO_FILTERSTRINGS).indexOf(thisFilter));
}
adMinRanges.clear();
adMaxRanges.clear();
end=0;
while(true){
start=arg.indexOf("rangeA",end);
if(start==-1)
break;
start=arg.indexOf("=", start) + 1 ;
end=arg.indexOf(" ", start);
if ((arg.charAt(start)+"").equals("[")){
start++;
end=arg.indexOf( "]", start);
}
String filterRange=arg.substring(start, end);
double[] range = str2doubles(filterRange);
adMinRanges.add(range[0]);
adMaxRanges.add(range[1]);
}
{
start = arg.indexOf("dosp");
if(start==-1)
scatter_chck = false;
else{
end = start + "dosp".length();
scatter_chck = arg.charAt(end)==' ' && arg.charAt(start-1)==' ';
}
}
{
start = arg.indexOf("domt");
if(start==-1)
matrix_chck = false;
else{
end = start + "domt".length();
matrix_chck = arg.charAt(end)==' ' && arg.charAt(start-1)==' ';
}
if(matrix_chck){
start=arg.indexOf("mmetric=");
if(start==-1){
matrixMetric_comb = DEFAULT_CHOICE;
}else{
start += ("mmetric=".length());
end = arg.indexOf(" ", start);
if (arg.charAt(start)=='['){
start++;
end=arg.indexOf("]", start);
}
matrixMetric_comb = Arrays.asList(matrixMetricList).indexOf(arg.substring(start, end));
}
start=arg.indexOf("mstats=");
if(start==-1){
matrixStats_comb = DEFAULT_CHOICE;
}else{
start += ("mstats=".length());
end = arg.indexOf(" ", start);
if (arg.charAt(start)=='['){
start++;
end=arg.indexOf("]", start);
}
matrixStats_comb = Arrays.asList(STATS_METHODS).indexOf(arg.substring(start, end));
}
for(int iTOS=0;iTOS<matrixFT_spin.length;iTOS++){
start=arg.indexOf("ft"+(iTOS+1)+"=");
if(start==-1){
matrixFT_spin[iTOS] = DEFAULT_FT;
}else{
start += ("ft"+(iTOS+1)+"=").length();
end=arg.indexOf(" ", start);
if ((arg.charAt(start)+"").equals("[")){
start++;
end=arg.indexOf("]", start);
}
String thisFT = arg.substring(start, end);
matrixFT_spin[iTOS] = (int)parseDouble(thisFT);
}
}
}
}
start=arg.indexOf("hmscale=");
if(start==-1){
heatmap_radio = DEFAULT_CHOICE;
}else{
start += ("hmscale=".length());
end = arg.indexOf(" ", start);
if (arg.charAt(start)=='['){
start++;
end=arg.indexOf("]", start);
}
heatmap_radio = Arrays.asList(MACRO_HEATMAPOPTS).indexOf(arg.substring(start, end));
}
for(int iHeat=0;iHeat<heatmapColor_combs.length;iHeat++){
start=arg.indexOf("hmcolor"+(iHeat+1)+"=");
if(start==-1){
heatmapColor_combs[iHeat] = DEFAULT_CHOICE;
heatmap_chckes[iHeat] = false;
}else{
start += (("hmcolor"+(iHeat+1)+"=").length());
end=arg.indexOf(" ", start);
if ((arg.charAt(start)+"").equals("[")){
start++;
end=arg.indexOf("]", start);
}
String thisHeatmap=arg.substring(start, end);
heatmapColor_combs[iHeat] = Arrays.asList(MACRO_HEATMAPS).indexOf(thisHeatmap);
heatmap_chckes[iHeat] = true;
}
}
int iFTs = metricThold_radios.length;
for(int iMetric=0;iMetric<metricThold_radios.length;iMetric++){
start=arg.indexOf("metricthold"+(iMetric+1)+"=");
if(start==-1){
metricThold_radios[iMetric] = DEFAULT_CHOICE;
}else{
start += (("metricthold"+(iMetric+1)+"=").length());
end=arg.indexOf(" ", start);
if ((arg.charAt(start)+"").equals("[")){
start++;
end=arg.indexOf("]", start);
}
String thisThold = arg.substring(start, end);
metricThold_radios[iMetric] = Arrays.asList(MACRO_METRIC_THOLDS).indexOf(thisThold);
}
if(metricThold_radios[iMetric]==IDX_THOLD_FT)
iFTs+=allFT_spins.length;
}
for(int iChannel=0;iChannel<allFT_spins.length;iChannel++){
for(int iMetric=0;iMetric<allFT_spins[iChannel].length;iMetric++){
start=arg.indexOf("allft-c"+(iChannel+1)+"-"+(iMetric+1)+"=");
if(start==-1){
allFT_spins[iChannel][iMetric] = DEFAULT_FT;
}else{
start += ("allft-c"+(iChannel+1)+"-"+(iMetric+1)+"=").length();
end=arg.indexOf(" ", start);
if ((arg.charAt(start)+"").equals("[")){
start++;
end=arg.indexOf("]", start);
}
String thisFT = arg.substring(start, end);
allFT_spins[iChannel][iMetric] = (int)parseDouble(thisFT);
}
}
}
/**
* retrieve metricTholds and allFTs to allTholds
* but not record it
*/
allTholds = new int[iFTs+1];
iFTs = 0;
for(int iMetric=0;iMetric<metricThold_radios.length;iMetric++){
if(metric_chckes[iMetric]){
allTholds[iFTs++] = BasicCalculator.getThold(metricThold_radios[iMetric]);
if(BasicCalculator.getThold(metricThold_radios[iMetric])==BasicCalculator.THOLD_FT)
for(int iChannel=0;iChannel<allFT_spins.length;iChannel++)
allTholds[iFTs++]=allFT_spins[iChannel][iMetric];
}else{
allTholds[iFTs++]=BasicCalculator.THOLD_NONE;
}
}
if (anyOtherMetric)
allTholds[allTholds.length-1] = BasicCalculator.THOLD_ALL;
else
allTholds[allTholds.length-1] = BasicCalculator.THOLD_NONE;
for(int iColumn=0;iColumn<outputMetric_chckes.length;iColumn++){
start = arg.indexOf(MACRO_OUTPUTMETRICS[iColumn]);
if(start==-1)
outputMetric_chckes[iColumn] = false;
else{
end = start + MACRO_OUTPUTMETRICS[iColumn].length();
outputMetric_chckes[iColumn] = arg.charAt(end)==' ' && arg.charAt(start-1)==' ';
}
}
for(int iColumn=0;iColumn<outputOpt_chckes.length;iColumn++){
start = arg.indexOf(MACRO_OUTPUTOTHERS[iColumn]);
if(start==-1)
outputOpt_chckes[iColumn] = false;
else{
end = start + MACRO_OUTPUTOTHERS[iColumn].length();
outputOpt_chckes[iColumn] = arg.charAt(end)==' ' && arg.charAt(start-1)==' ';
}
}
}
/**
* This method creates ImageJ macro code
* by converting the current setting to a string
* and passing it to the Recorder.
* @warning Please make sure all strings match to the corresponding strings in macroInterpreter
*/
private static void macroGenerator(){
@SuppressWarnings("rawtypes")
Hashtable table = Menus.getCommands();
String className = (String)table.get(pluginName);
if (className == null)
Recorder.record("//Warning: The Plugin class cannot be found");
Recorder.setCommand(pluginName);
for (int ipic=0;ipic<imps.length;ipic++)
if(imps[ipic]!=null)
Recorder.recordOption(MACRO_IMGLABELS[ipic],imps[ipic].getTitle());
for(int iColumn=0;iColumn<metric_chckes.length;iColumn++)
if(metric_chckes[iColumn])
Recorder.recordOption(MACRO_METRICNAMES[iColumn]);
for(int iColumn=0;iColumn<other_chckes.length;iColumn++)
if(other_chckes[iColumn])
Recorder.recordOption(MACRO_OTHERNAMES[iColumn]);
for(int iThold=0;iThold<alignThold_combs.length;iThold++)
Recorder.recordOption("alignthold"+(iThold+1),MACRO_ALLTHOLDS[alignThold_combs[iThold]]);
if(waterShed_chck)
Recorder.recordOption("dows");
for (int iSize=0;iSize<filterMinSize_texts.length;iSize++)
Recorder.recordOption(MACRO_SIZEFILTERS[iSize], getFilterRange(filterMinSize_texts[iSize],filterMaxSize_texts[iSize],false));
for(int iFilter=0;iFilter<filter_combs.length;iFilter++){
Recorder.recordOption("filter"+(iFilter+1), MACRO_FILTERSTRINGS[filter_combs[iFilter]]);
Recorder.recordOption("range"+(iFilter+1), getFilterRange(filterMinRange_texts[iFilter],filterMaxRange_texts[iFilter],filterBackRatio_texts[iFilter]));
}
for(int iFilter=0;iFilter<adFilterChoices.size();iFilter++){
Recorder.recordOption("filterA"+(iFilter+1), MACRO_FILTERSTRINGS[adFilterChoices.get(iFilter)]);
Recorder.recordOption("rangeA"+(iFilter+1), getFilterRange(adMinRanges.get(iFilter),adMaxRanges.get(iFilter),adBackRatios.get(iFilter)));
}
if(scatter_chck)
Recorder.recordOption("dosp");
if(matrix_chck)
Recorder.recordOption("domt");
Recorder.recordOption("hmscale", MACRO_HEATMAPOPTS[heatmap_radio]);
for(int iHeat=0;iHeat<heatmapColor_combs.length;iHeat++)
Recorder.recordOption("hmcolor"+(iHeat+1), MACRO_HEATMAPS[heatmapColor_combs[iHeat]]);
//Recorder.recordOption("tosscale",MACRO_TOSOPTS[mTOSscale]);
Recorder.recordOption("mmetric", matrixMetricList[matrixMetric_comb]);
Recorder.recordOption("mstats", STATS_METHODS[matrixStats_comb]);
for(int iFT=0;iFT<matrixFT_spin.length;iFT++){
Recorder.recordOption("mft"+(iFT+1),""+matrixFT_spin[iFT]);
}
for(int iMetric=0;iMetric<metricThold_radios.length;iMetric++)
Recorder.recordOption("metricthold"+(iMetric+1),MACRO_METRIC_THOLDS[metricThold_radios[iMetric]]);
for(int iChannel=0;iChannel<allFT_spins.length;iChannel++)
for(int iMetric=0;iMetric<allFT_spins[iChannel].length;iMetric++)
Recorder.recordOption("allft-c"+(iChannel+1)+"-"+(iMetric+1),""+allFT_spins[iChannel][iMetric]);
for(int iColumn=0;iColumn<outputMetric_chckes.length;iColumn++)
if(outputMetric_chckes[iColumn])
Recorder.recordOption(MACRO_OUTPUTMETRICS[iColumn]);
for(int iColumn=0;iColumn<outputOpt_chckes.length;iColumn++)
if(outputOpt_chckes[iColumn])
Recorder.recordOption(MACRO_OUTPUTOTHERS[iColumn]);
Recorder.saveCommand();
}
/**
* This type of recorder only records necessary informations.
*/
private static void macroSmartGenerator(){
@SuppressWarnings("rawtypes")
Hashtable table = Menus.getCommands();
String className = (String)table.get(pluginName);
if (className == null)
Recorder.record("//Warning: The Plugin class cannot be found");
Recorder.setCommand(pluginName);
retrieveOptions();
for (int ipic=0;ipic<imps.length;ipic++)
if(imps[ipic]!=null)
Recorder.recordOption(MACRO_IMGLABELS[ipic],imps[ipic].getTitle());
for(int iThold=0;iThold<alignThold_combs.length;iThold++)
if(iThold >= align_chckes.length ? ((options&RUN_ALIGN)!=0||(options&RUN_IDCELLS)!=0) : align_chckes[iThold])
Recorder.recordOption("alignthold"+(iThold+1),MACRO_ALLTHOLDS[alignThold_combs[iThold]]);
if((options&RUN_IDCELLS)!=0){
if(waterShed_chck)
Recorder.recordOption("dows");
for (int iSize=0;iSize<filterMinSize_texts.length;iSize++){
if(filterMinSize_texts[iSize]!=DEFAULT_MIN || filterMaxSize_texts[iSize]!=DEFAULT_MAX)
Recorder.recordOption(MACRO_SIZEFILTERS[iSize], getFilterRange(filterMinSize_texts[iSize],filterMaxSize_texts[iSize],false));
}
for(int iFilter=0;iFilter<filter_combs.length;iFilter++){
if(filterMinRange_texts[iFilter]!=DEFAULT_MIN || filterMaxRange_texts[iFilter]!=DEFAULT_MAX){
Recorder.recordOption("filter"+(iFilter+1), MACRO_FILTERSTRINGS[filter_combs[iFilter]]);
Recorder.recordOption("range"+(iFilter+1), getFilterRange(filterMinRange_texts[iFilter],filterMaxRange_texts[iFilter],filterBackRatio_texts[iFilter]));
}
}
for(int iFilter=0;iFilter<adFilterChoices.size();iFilter++){
if(adMinRanges.get(iFilter)!=DEFAULT_MIN || adMaxRanges.get(iFilter)!=DEFAULT_MAX){
Recorder.recordOption("filterA"+(iFilter+1), MACRO_FILTERSTRINGS[adFilterChoices.get(iFilter)]);
Recorder.recordOption("rangeA"+(iFilter+1), getFilterRange(adMinRanges.get(iFilter),adMaxRanges.get(iFilter),adBackRatios.get(iFilter)));
}
}
if(scatter_chck)
Recorder.recordOption("dosp");
if(matrix_chck)
Recorder.recordOption("domt");
}
if((options&RUN_HEAT)!=0){
Recorder.recordOption("hmscale", MACRO_HEATMAPOPTS[heatmap_radio]);
for(int iHeat=0;iHeat<heatmapColor_combs.length;iHeat++)
if(heatmap_chckes[iHeat])
Recorder.recordOption("hmcolor"+(iHeat+1), MACRO_HEATMAPS[heatmapColor_combs[iHeat]]);
}
if((options&RUN_MATRIX)!=0){
if(matrixMetric_comb!=DEFAULT_CHOICE)
Recorder.recordOption("mmetric", matrixMetricList[matrixMetric_comb]);
if(matrixStats_comb!=DEFAULT_CHOICE)
Recorder.recordOption("mstats", STATS_METHODS[matrixStats_comb]);
for(int iFT=0;iFT<nReporters;iFT++){
if(matrixFT_spin[iFT]!=DEFAULT_FT)
Recorder.recordOption("mft"+(iFT+1),""+matrixFT_spin[iFT]);
}
}
int recordChannel = nReporters < allFT_spins.length ? nReporters : allFT_spins.length;
for(int iMetric=0;iMetric<metric_chckes.length;iMetric++)
if(metric_chckes[iMetric]){
Recorder.recordOption(MACRO_METRICNAMES[iMetric]);
Recorder.recordOption("metricthold"+(iMetric+1),MACRO_METRIC_THOLDS[metricThold_radios[iMetric]]);
for(int iChannel=0;iChannel<recordChannel;iChannel++)
Recorder.recordOption("allft-c"+(iChannel+1)+"-"+(iMetric+1),""+allFT_spins[iChannel][iMetric]);
}
for(int iColumn=0;iColumn<other_chckes.length;iColumn++)
if(other_chckes[iColumn])
Recorder.recordOption(MACRO_OTHERNAMES[iColumn]);
if(other_chckes[CUSTOM]){
Recorder.recordPath("custom-javafile", StringCompiler.getDefaultPath());
}
for(int iColumn=0;iColumn<outputMetric_chckes.length;iColumn++)
if(outputMetric_chckes[iColumn])
Recorder.recordOption(MACRO_OUTPUTMETRICS[iColumn]);
for(int iColumn=0;iColumn<outputOpt_chckes.length;iColumn++)
if(outputOpt_chckes[iColumn])
Recorder.recordOption(MACRO_OUTPUTOTHERS[iColumn]);
Recorder.saveCommand();
}
public static void macroRecorder(boolean smart){
if(smart)
macroSmartGenerator();
else
macroGenerator();
}
private static String[] macroStrArray(String[] str){
String[] result=new String[str.length];
for(int i=0;i<str.length;i++)
result[i]=str[i].replaceAll(" ","_").toLowerCase();
return result;
}
public static GUI getProgressBar(){
return null;
}
public static void recordCloseAll(){
Recorder.setCommand(pluginName);
Recorder.recordOption("close_all");
Recorder.saveCommand();
}
public static void recordSaveAll(String dir){
Recorder.setCommand(pluginName);
Recorder.recordPath("save_all",dir);
Recorder.saveCommand();
}
public static boolean macroSaveAndClose(String arg){
if(arg==null||arg.length()<=0)
return false;
boolean saveOrClose = false;
int start=0, end=0;
String dir;
start=arg.indexOf("save_all=");
if(start!=-1){
start += "save_all=".length();
end=arg.indexOf(" ", start);
if ((arg.charAt(start)+"").equals("[")){
start++;
end = arg.indexOf("]", start);
}
dir = arg.substring(start, end);
//dir.replace("\\\\", "\\");
if (!(new File(dir)).isDirectory())
IJ.error("Cannot find the directory: "+dir);
else{
try{
saveAllWindows(dir);
saveOrClose = true;
}catch(Exception e){
IJ.error("Error in saving the results");
}
}
}
start=arg.indexOf("close_all");
if(start!=-1){
saveOrClose = true;
closeAllWindows();
}
return saveOrClose;
}
}
| 24,455 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
GUI.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/main/GUI.java | package ezcol.main;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.Panel;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.SystemColor;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Vector;
import java.beans.PropertyChangeEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComboBox;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JRadioButton;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTabbedPane;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.LookAndFeel;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.JTextArea;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.Element;
import javax.swing.text.JTextComponent;
import javax.swing.text.NumberFormatter;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.Utilities;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
import javax.swing.JSpinner;
import javax.swing.JFormattedTextField;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import ij.IJ;
import ij.ImageListener;
import ij.ImagePlus;
import ij.Prefs;
import ij.WindowManager;
import ij.gui.GenericDialog;
import ij.gui.ImageWindow;
import ij.gui.Overlay;
import ij.gui.Roi;
import ij.io.OpenDialog;
import ij.plugin.BrowserLauncher;
import ij.plugin.OverlayLabels;
import ij.plugin.frame.Recorder;
import ij.plugin.frame.RoiManager;
import ij.plugin.frame.ThresholdAdjuster;
import ij.process.ImageProcessor;
import ij.util.Java2;
import ij.process.AutoThresholder.Method;
import ezcol.align.BackgroundProcessor;
import ezcol.cell.CellFilterDialog;
import ezcol.cell.ParticleAnalyzerMT;
import ezcol.debug.ExceptionHandler;
import ezcol.files.FilesIO;
import ezcol.metric.BasicCalculator;
import ezcol.metric.StringCompiler;
import ezcol.visual.visual2D.ProgressGlassPane;
/**
*
* @author Huanjie Sheng, Weston Stauffer
*
*/
public class GUI extends PluginStatic
implements ActionListener, ChangeListener, ImageListener, WindowListener /* , PropertyChangeListener */ {
private static GUI staticGUI;
private static boolean adaptZoom = true;
// the main window and its main components of plugin
private JFrame mainframe;
private JPanel superPanel;
private JTabbedPane tabs;
private JLabel warning;
private JButton analyzeBtn;
// used to restore
private static ImagePlus[] oldImps = new ImagePlus[imps.length];
// indexes for tabs
public static final int INPUTTAB = 0, FILTERTAB = 1, VISUALTAB = 2, ANALYSISTAB = 3;
// all tabs
private JPanel inputTab;
private JPanel filterTab;
private JPanel visualTab;
private JPanel analysisTab;
// RightClick UI
JPopupMenu rightPopMenu = new JPopupMenu();
// Input UI
private String directory;
// image UI
private Vector<ImageInfo> info = new Vector<ImageInfo>();
private boolean imgIO = true, imgUpdate = false;
@SuppressWarnings("unchecked")
private JComboBox<ImageInfo>[] imgCombbxes = new JComboBox[imps.length];
private JLabel[] imgTitles = new JLabel[imps.length];
// alignment UI
private JCheckBox[] alignedChckbxes = new JCheckBox[align_chckes.length];
private JComboBox<?>[] alignTholdCombbxes = new JComboBox<?>[alignThold_combs.length];
private JButton doAlignmentBtn, resetAlignmentBtn, previewTholdBtn;
private boolean showThold;
private static final String[] PREVIEW_THOLD = { "Show Threshold(s)", "Hide Threshold(s)" };
// Add in 1.1.0 to save current Overlays on the images
private Overlay[] currentOverlays = new Overlay[imps.length];
// cell filters UI
private JTextField[] filterSizeTexts = new JTextField[SIZE_FILTERS.length];
private JTextField[] filterRangeTexts = new JTextField[filter_combs.length];
@SuppressWarnings("rawtypes")
private JComboBox[] filterCombbxes = new JComboBox[filter_combs.length];
private JCheckBox waterShedChckbx;
private JButton tryIDCells, btnMoreFilters;
// Visualization UI
// matrix heat maps UI
private JCheckBox matrixChckbx;
private JComboBox<String> matrixMetricCombbx;
private JComboBox<String> matrixStatsCombbx;
private JSpinner[] matrixFTSpinners = new JSpinner[MAX_NREPORTERS];
private JPanel[] paneMatrixSpinners = new JPanel[matrixFTSpinners.length];
// scatterplot UI
private JCheckBox scatterplotChckbx;
// heatmaps UI
private ButtonGroup heatmapTypeRadio = new ButtonGroup();
private JRadioButton[] heatmapRadiobtns = new JRadioButton[HEATMAPOPTS.length];
private JCheckBox[] heatmapChckbxes = new JCheckBox[heatmapColor_combs.length];
@SuppressWarnings("rawtypes")
private JComboBox[] heatmapColorCombbxes = new JComboBox[heatmapColor_combs.length];
private JButton previewVisual;
// Global Calibration
// indexes for subtabs
private static final int METRICSUBTAB = 0, INFOSUBTAB = 1, CUSTOMSUBTAB = 2;
// four colors are the colors of
// 1.metricSubTab, 2.mTOSSubTab, 3.distanceSubTab, 4.otherSubTab
// The order should be the same as the indexes above
public static final Color[] SUBTABCOLORS = { new Color(230, 230, 250), new Color(250, 235, 215),
new Color(240, 255, 240), new Color(255, 255, 224) };
public static final Color[] SUBLABELCOLORS = { new Color(150, 150, 255), Color.ORANGE, new Color(100, 255, 100),
Color.YELLOW };
// Analysis Tab
private JTabbedPane analysisSubTabs;
// analysis operator is used to run the analyses
private AnalysisOperator analysis;
// outputs UI
public static final int[] METRICS_2D_ONLY = { PCC, SRCC };
private JPanel metricSubTab;
private JRadioButton[][] metricTholdRadiobtns = new JRadioButton[METRICACRONYMS.length][METRIC_THOLDS.length];
private ButtonGroup[] metricRadioGroup = new ButtonGroup[METRICACRONYMS.length];
private JLabel[] lblMetricTholds = new JLabel[METRIC_THOLDS.length];
private JSpinner[][] allFTSpinners = new JSpinner[MAX_NREPORTERS][METRICACRONYMS.length];
private JLabel[] lblFTunits = new JLabel[allFTSpinners.length];
private JCheckBox[] metricChckbxes = new JCheckBox[METRICACRONYMS.length];
private JCheckBox[] otherChckbxes = new JCheckBox[OTHERNAMES.length];
// Custom UI
public static final int SUCCESS = 0, FAILURE = 1, RUN = 2, SKIP = 3;
private static final String[] CUSTOM_STATUS = { "Succeeded", "Failed", "Run", "Skip" };
private static final Color[] CUSTOM_COLORS = { new Color(0, 128, 0), Color.RED, Color.BLACK, Color.BLUE };
private static final String CUSTOM_URL = "https://docs.oracle.com/javase/tutorial/java/data/beyondmath.html";
private JPanel customSubTab;
private JScrollPane customCodeScrollpn;
private JTextArea customCodeTextbx;
private JButton runCustomBtn, resetCustomBtn, helpCustomBtn;
private JCheckBox customMetricChckbxes;
// Output UI
private JCheckBox[] outputMetricChckbxes = new JCheckBox[OUTPUTMETRICS.length];
private JCheckBox[] outputOptChckbxes = new JCheckBox[OUTPUTOTHERS.length];
private JPanel infoSubTab;
private JScrollPane infoScrollpn;
private JEditorPane infoTextpn;
private String[][] extraInfo = {
{ "Costes' Algorithm",
"Costes' algorithm is an automated algorithm for the selection of thresholds "
+ "for two reporter channels. It is typically used in conjunction with MCC.",
"https://www.sciencedirect.com/science/article/pii/S0006349504744392?via%3Dihub" },
{"Top Percentile of Pixels Threshold (FT)",
"The percentage of pixels identified as being above the threshold for a given channel. "
+ "For example an FT of 10% will identify the top 10% of pixels as above threshold.\n",
"http://bio.biologists.org/content/5/12/1882.long"
},
{ "Histogram",
"The histogram provided is a column graph where the height of each column "
+ "is proportional to the number of values within each sub-range of values in the sample.\n",
"https://en.wikipedia.org/wiki/Histogram" },
{ "Mask",
"Masks are binary images with an inverting lookup table (LUT) "
+ "that are used to visualize separate objects from the background.\n",
"https://imagej.nih.gov/ij/docs/guide/146-29.html#infobox:InvertedLutMask" },
{ "Region of Interest (ROI)", "An ROI is a subregion within an image that is identified for analysis.\n",
"https://imagej.net/ROIs" }
};
// about tab
private static final String ABOUT_TEXT = "Please refer to and cite:\n" + "Stauffer, W., Sheng, H., and Lim, H.N.\n"
+ "EzColocalization: An ImageJ plugin for visualizing and measuring colocalization \nin cells and organisms (2018)";
private JPanel aboutPanel;
private JButton email;
// please double check that pluginName,if changed, doesn't contain reserved
// symbols
private static final String URIEmail = "mailto:" + CONTACT + "?subject=Question%20about%20your%20"
+ pluginName.replaceAll(" ", "%20") + "%20plugin";
// progress glasspane
private ProgressGlassPane progressGlassPane;
// make a copy of Recorder.record to bypass the annoying additional lines
private volatile boolean recorderRecord;
public GUI() {
if (IJ.isMacro())
return;
if (staticGUI != null) {
WindowManager.toFront(staticGUI.mainframe);
return;
}
imgIO = false;
loadPreference();
checkParams();
gui();
imgIO = true;
staticGUI = this;
}
/**
* This is used for macro to generate GUI
*
* @param macro
*/
public GUI(boolean macro) {
// macroGUI();
}
/**
* This is used for test only
*
* @param test
*/
public GUI(int test) {
gui();
updateTicked(true);
}
public static GUI getGUI() {
return staticGUI;
}
/**
* Create the frame.
*/
private void gui() {
mainframe = new JFrame(pluginName);
mainframe.setSize(0, 0);
mainframe.setResizable(false);
if (FilesIO.getResource("coloc.gif") != null)
mainframe.setIconImage(new ImageIcon(FilesIO.getResource("coloc.gif")).getImage());
mainframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// This is the content panel
superPanel = new JPanel();
superPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
mainframe.setContentPane(superPanel);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[] { 0, 0, 0, 0, 0 };
gbl_contentPane.rowHeights = new int[] { 0, 0, 0, 0, 0 };
gbl_contentPane.columnWeights = new double[] { 0.0, 1.0, 0.0, 1.0, Double.MIN_VALUE };
gbl_contentPane.rowWeights = new double[] { 1.0, 1.0, 1.0, 1.0, Double.MIN_VALUE };
superPanel.setLayout(gbl_contentPane);
// This is the main tabbedpane
tabs = new JTabbedPane(JTabbedPane.TOP);
// tabs.setOpaque(true);
GridBagConstraints gbc_tabbedPane = new GridBagConstraints();
gbc_tabbedPane.gridheight = 2;
gbc_tabbedPane.gridwidth = 4;
gbc_tabbedPane.insets = new Insets(0, 0, 5, 0);
gbc_tabbedPane.fill = GridBagConstraints.BOTH;
gbc_tabbedPane.gridx = 0;
gbc_tabbedPane.gridy = 0;
superPanel.add(tabs, gbc_tabbedPane);
// tabs.getLayout();
// all functional tabs are initialized in the corresponding methods
// below
// These must be done after mainframe is initialized
inputTab();
filterTab();
visualTab();
analysisTab();
// outputTab();
// tab listener is added here to avoid calling it while inserting new
// tabs
tabs.addChangeListener(this);
// These must be done after mainframe is initialized
aboutPane();
rightMenu();
mainMenu();
progressGlassPane = new ProgressGlassPane();
// Let GlassPane block further inputs
progressGlassPane.requestFocusInWindow();
progressGlassPane.addMouseListener(new MouseAdapter() {
});
progressGlassPane.addMouseMotionListener(new MouseMotionAdapter() {
});
progressGlassPane.addKeyListener(new KeyAdapter() {
});
mainframe.setGlassPane(progressGlassPane);
mainframe.addWindowListener(this);
// updateGUI first so nChannels is reflected
updateGUI();
// read in images
updateImgList(null, null);
// clear the thresholds of selected images
resetThr();
// update selections based on selected images
updateSelection();
updateTicked();
// initialize input images options
// add none as a chioce to all input combo boxes
/**
* I just don't understand what the ImageJ's authors were thinking Why
* is a listener being added in a static way???
*/
ImagePlus.addImageListener(this);
// Sometimes the looking of the plugin changes for no reason
// Make sure it's good here
LookAndFeel thisLook = UIManager.getLookAndFeel();
Java2.setSystemLookAndFeel();
try {
UIManager.setLookAndFeel(thisLook);
} catch (UnsupportedLookAndFeelException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
IJ.log("" + e1);
}
mainframe.pack();
mainframe.setLocation(0, (int) (getIJScreenBounds().getHeight() / 2 - mainframe.getHeight() / 2));
mainframe.setVisible(true);
// adaptZoom after the main frame window is displayed to get proper
// position.
if (nbImgs != 0)
adaptZoom();
}
private void mainMenu() {
JMenuBar menuBar;
JMenu menu;
JMenuItem menuItem;
String menuString;
String[] menuStrings;
menuBar = new JMenuBar();
mainframe.setJMenuBar(menuBar);
{
// Build second menu in the menu bar.
menu = new JMenu("File");
menu.getAccessibleContext().setAccessibleDescription("This menu has functions related to file");
menuBar.add(menu);
menuString = "Open...";
menuItem = new JMenuItem(menuString);
menuItem.getAccessibleContext().setAccessibleDescription(menuString);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
LookAndFeel thisLook = UIManager.getLookAndFeel();
Java2.setSystemLookAndFeel();
try {
UIManager.setLookAndFeel(thisLook);
} catch (UnsupportedLookAndFeelException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
IJ.log("" + e1);
}
IJ.doCommand(((JMenuItem) (e.getSource())).getText());
}
});
menu.add(menuItem);
menuString = "Test Images";
menuItem = new JMenuItem(menuString);
menuItem.getAccessibleContext().setAccessibleDescription(menuString);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
FilesIO.openTiffs(true);
} catch (IOException | URISyntaxException e1) {
// TODO Auto-generated catch block
// e1.printStackTrace();
IJ.error("Error while loading sample images");
}
}
});
menu.add(menuItem);
menuString = "Exit";
menuItem = new JMenuItem(menuString);
menuItem.getAccessibleContext().setAccessibleDescription(menuString);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
exit();
}
});
menu.add(menuItem);
}
{
menu = new JMenu("Results");
menu.getAccessibleContext().setAccessibleDescription("This menu has functions related to file");
menuBar.add(menu);
menuItem = new JMenuItem("Save All...");
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String dir = saveAllWindows();
if (recorderRecord) {
MacroHandler.recordSaveAll(dir);
}
}
});
menu.add(menuItem);
menuItem = new JMenuItem("Close All");
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
closeAllWindows();
updateImgList(null, null);
if (recorderRecord) {
MacroHandler.recordCloseAll();
}
}
});
menu.add(menuItem);
menuItem = new JMenuItem("Select All");
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
chooseAll();
updateSelection();
}
});
menu.add(menuItem);
menuItem = new JMenuItem("Reset Params");
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
resetParams();
updateSelection();
}
});
menu.add(menuItem);
}
{
// Build the stack menu.
menu = new JMenu("Stack");
// menu.setMnemonic(KeyEvent.VK_A);
menu.getAccessibleContext().setAccessibleDescription("Stack related functions incorporated from ImageJ");
menuBar.add(menu);
menuStrings = new String[] { "Images to Stack", "Concatenate...", "Image Sequence..." };
// a group of JMenuItems
for (String menuString1 : menuStrings) {
menuItem = new JMenuItem(menuString1);
menuItem.getAccessibleContext().setAccessibleDescription(menuString1);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
IJ.doCommand(menuString1);
}
});
menu.add(menuItem);
}
}
{
// Build the stack menu.
menu = new JMenu("Settings");
// menu.setMnemonic(KeyEvent.VK_A);
menu.getAccessibleContext().setAccessibleDescription("PlugIn Settings");
menuBar.add(menu);
ButtonGroup group = new ButtonGroup();
// Avoid the scope problem by creating a temporary array here
// bad code
int[] idxReporters = new int[MAX_NREPORTERS - MIN_NREPORTERS + 1];
for (int i = MIN_NREPORTERS; i <= MAX_NREPORTERS; i++)
idxReporters[i - MIN_NREPORTERS] = i;
for (int i : idxReporters) {
menuItem = new JRadioButtonMenuItem(i + " Reporter Channels");
menuItem.setSelected(nReporters == i);
// menuItem.setMnemonic(KeyEvent.VK_2);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setNReporters(i);
}
});
group.add(menuItem);
menu.add(menuItem);
}
menu.addSeparator();
menuItem = new JCheckBoxMenuItem("Auto Layout");
menuItem.setSelected(adaptZoom);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
adaptZoom = ((JCheckBoxMenuItem) e.getSource()).isSelected();
}
});
menu.add(menuItem);
// Add in 1.1.0 to change previously unchangable parameters
menuItem = new JMenuItem("Parameters...");
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setParameters();
}
});
menu.add(menuItem);
menuItem = new JMenuItem("Plugin Info...");
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
IJ.error(pluginName, FilesIO.getPluginProperties());
}
});
menu.add(menuItem);
}
}
private void rightMenu() {
// Right Click popMenu UI
JMenuItem saveMenuItem, closeMenuItem, chooseMenuItem, resetMenuItem;
saveMenuItem = new JMenuItem("Save All...");
saveMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String dir = saveAllWindows();
if (recorderRecord) {
MacroHandler.recordSaveAll(dir);
}
}
});
closeMenuItem = new JMenuItem("Close All");
closeMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
closeAllWindows();
updateImgList(null, null);
if (recorderRecord) {
MacroHandler.recordCloseAll();
}
}
});
chooseMenuItem = new JMenuItem("Select All");
chooseMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
chooseAll();
updateSelection();
}
});
resetMenuItem = new JMenuItem("Reset Params");
resetMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
resetParams();
updateSelection();
}
});
rightPopMenu.add(saveMenuItem);
rightPopMenu.add(closeMenuItem);
rightPopMenu.add(chooseMenuItem);
rightPopMenu.add(resetMenuItem);
rightPopMenu.updateUI();
MouseListener ml = new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
if (e.getButton() == MouseEvent.BUTTON3)
rightPopMenu.show(e.getComponent(), e.getX(), e.getY());
else
rightPopMenu.setVisible(false);
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
};
tabs.addMouseListener(ml);
analysisSubTabs.addMouseListener(ml);
mainframe.addMouseListener(ml);
}
private void inputTab() {
// inputTab starts here
inputTab = new JPanel();
// inputTab.setBorder(null);
tabs.insertTab("Inputs", null, inputTab, null, INPUTTAB);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
gbl_panel.rowHeights = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0 };
gbl_panel.columnWeights = new double[] { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
Double.MIN_VALUE };
gbl_panel.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE };
inputTab.setLayout(gbl_panel);
JLabel spacer0 = new JLabel(" ");
GridBagConstraints gbc_label = new GridBagConstraints();
gbc_label.insets = new Insets(0, 0, 5, 5);
gbc_label.gridx = 4;
gbc_label.gridy = 0;
inputTab.add(spacer0, gbc_label);
JLabel lblImps2Analyze = new JLabel("Images for analysis");
lblImps2Analyze.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
GridBagConstraints gbc_lblImps2Analyze = new GridBagConstraints();
gbc_lblImps2Analyze.insets = new Insets(0, 0, 5, 0);
gbc_lblImps2Analyze.gridwidth = 11;
gbc_lblImps2Analyze.gridx = 0;
gbc_lblImps2Analyze.gridy = 1;
inputTab.add(lblImps2Analyze, gbc_lblImps2Analyze);
for (int i = 0; i < imgLabels.length; i++) {
imgTitles[i] = new JLabel(imgLabels[i]);
GridBagConstraints gbc_lblChannel = new GridBagConstraints();
gbc_lblChannel.gridwidth = 5;
gbc_lblChannel.insets = new Insets(0, 0, 5, 5);
gbc_lblChannel.gridx = 0;
gbc_lblChannel.gridy = 2 + i;
inputTab.add(imgTitles[i], gbc_lblChannel);
}
/*
* JLabel lblOrRoiManager = new JLabel(" or Mask"); GridBagConstraints
* gbc_lblOrRoiManager = new GridBagConstraints();
* gbc_lblOrRoiManager.anchor = GridBagConstraints.NORTH;
* gbc_lblOrRoiManager.gridwidth = 5; gbc_lblOrRoiManager.insets = new
* Insets(0, 0, 5, 5); gbc_lblOrRoiManager.gridx = 0;
* gbc_lblOrRoiManager.gridy = 5; inputTab.add(lblOrRoiManager,
* gbc_lblOrRoiManager);
*/
JLabel lblAlignment = new JLabel(" ");
GridBagConstraints gbc_lblAlignment = new GridBagConstraints();
gbc_lblAlignment.insets = new Insets(0, 0, 5, 5);
gbc_lblAlignment.anchor = GridBagConstraints.SOUTH;
gbc_lblAlignment.gridwidth = 10;
gbc_lblAlignment.gridx = 0;
gbc_lblAlignment.gridy = 6;
inputTab.add(lblAlignment, gbc_lblAlignment);
// ComboBoxes for choosing images
for (int ipic = 0; ipic < imgCombbxes.length; ipic++) {
imgCombbxes[ipic] = new JComboBox<ImageInfo>();
imgCombbxes[ipic].setRenderer(ImageInfo.RENDERER);
imgCombbxes[ipic].putClientProperty("index", ipic);
imgCombbxes[ipic].addActionListener(this);
imgCombbxes[ipic].addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
if (!showThold)
return;
@SuppressWarnings("unchecked")
JComboBox<ImageInfo> img = (JComboBox<ImageInfo>) e.getSource();
// When the JComboBox is disabled, we do not fire itemStateChanged
// listener to avoid any dangerous infinite loop
if (!img.isEnabled())
return;
ImageInfo item = (ImageInfo) e.getItem();
if (item.ID == ImageInfo.NONE_ID)
return;
int ipic = (int) img.getClientProperty("index");
// Manually adjusting the threshold, no need to autoupdate
if (getMethod(ALLTHOLDS[alignThold_combs[ipic]]) == null)
return;
if (e.getStateChange() == ItemEvent.SELECTED) {
// If the same image is selected for a channel with
// higher priority
// No need to update threshold
for (int i = ipic + 1; i < imgCombbxes.length; i++) {
if (imgCombbxes[i].getItemAt(imgCombbxes[i].getSelectedIndex()).equal(item))
return;
}
updateThr(ipic, item);
} else if (e.getStateChange() == ItemEvent.DESELECTED) {
int index = -1;
// Check to see if the same image is selected for
// another channel
for (int i = 0; i < imgCombbxes.length; i++) {
if (i == ipic)
continue;
if (imgCombbxes[i].getItemAt(imgCombbxes[i].getSelectedIndex()).equal(item)) {
index = i;
}
}
if (index == -1)
resetThr(ipic, item);
else if (index < ipic)
updateThr(index, item);
}
}
});
GridBagConstraints gbc_comboBox = new GridBagConstraints();
gbc_comboBox.gridwidth = 5;
gbc_comboBox.insets = new Insets(0, 0, 5, 10);
gbc_comboBox.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox.gridx = 5;
gbc_comboBox.gridy = ipic + 2;
inputTab.add(imgCombbxes[ipic], gbc_comboBox);
}
JLabel lblAlignmentOptions = new JLabel("Alignment and threshold options");
lblAlignmentOptions.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 0);
gbc_lblNewLabel.gridwidth = 11;
gbc_lblNewLabel.gridx = 0;
gbc_lblNewLabel.gridy = 7;
inputTab.add(lblAlignmentOptions, gbc_lblNewLabel);
JLabel lblThresholdAlgorithm = new JLabel("Select threshold algorithm");
GridBagConstraints gbc_lblThresholdAlgorithmOr = new GridBagConstraints();
gbc_lblThresholdAlgorithmOr.insets = new Insets(0, 0, 5, 10);
gbc_lblThresholdAlgorithmOr.gridwidth = 5;
gbc_lblThresholdAlgorithmOr.gridx = 5;
gbc_lblThresholdAlgorithmOr.gridy = 8;
inputTab.add(lblThresholdAlgorithm, gbc_lblThresholdAlgorithmOr);
// Checkboxes for choosing channels to be aligned
for (int iAlign = 0; iAlign < align_chckes.length; iAlign++) {
alignedChckbxes[iAlign] = new JCheckBox("Align " + imgLabels[iAlign]);
alignedChckbxes[iAlign].setSelected(align_chckes[iAlign]);
GridBagConstraints gbc_chckbxNewCheckBox = new GridBagConstraints();
gbc_chckbxNewCheckBox.gridwidth = 5;
gbc_chckbxNewCheckBox.insets = new Insets(0, 0, 5, 0);
gbc_chckbxNewCheckBox.gridx = 0;
gbc_chckbxNewCheckBox.gridy = 9 + iAlign;
inputTab.add(alignedChckbxes[iAlign], gbc_chckbxNewCheckBox);
}
JLabel lblPhaseThold1 = new JLabel(imgLabels[imgLabels.length - 1]);
GridBagConstraints gbc_lblPhasecontrast = new GridBagConstraints();
gbc_lblPhasecontrast.gridwidth = 5;
gbc_lblPhasecontrast.insets = new Insets(0, 0, 5, 0);
gbc_lblPhasecontrast.gridx = 0;
gbc_lblPhasecontrast.gridy = 9 + align_chckes.length;
inputTab.add(lblPhaseThold1, gbc_lblPhasecontrast);
JLabel lblPhaseThold2 = new JLabel(" ");
GridBagConstraints gbc_lblalignmentReference = new GridBagConstraints();
gbc_lblalignmentReference.anchor = GridBagConstraints.NORTH;
gbc_lblalignmentReference.gridwidth = 5;
gbc_lblalignmentReference.insets = new Insets(0, 0, 5, 0);
gbc_lblalignmentReference.gridx = 0;
gbc_lblalignmentReference.gridy = 10 + align_chckes.length;
inputTab.add(lblPhaseThold2, gbc_lblalignmentReference);
// ComboBoxes for choosing desired threshold algorithms
for (int iThold = 0; iThold < alignThold_combs.length; iThold++) {
alignTholdCombbxes[iThold] = new JComboBox<String>(ALLTHOLDS);
alignTholdCombbxes[iThold].addActionListener(this);
GridBagConstraints gbc_comboBox_align = new GridBagConstraints();
gbc_comboBox_align.gridwidth = 5;
gbc_comboBox_align.insets = new Insets(0, 0, 5, 10);
gbc_comboBox_align.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox_align.gridx = 5;
gbc_comboBox_align.gridy = 9 + iThold;
inputTab.add(alignTholdCombbxes[iThold], gbc_comboBox_align);
}
// Button to reset alignment
previewTholdBtn = new JButton();
previewTholdBtn.setText(PREVIEW_THOLD[showThold ? 1 : 0]);
previewTholdBtn.addActionListener(this);
GridBagConstraints gbc_btnPreviewThold = new GridBagConstraints();
gbc_btnPreviewThold.gridwidth = 12;
gbc_btnPreviewThold.insets = new Insets(0, 5, 5, 5);
gbc_btnPreviewThold.gridx = 0;
gbc_btnPreviewThold.gridy = 14;
inputTab.add(previewTholdBtn, gbc_btnPreviewThold);
// Button to preview alignment
doAlignmentBtn = new JButton("Preview");
doAlignmentBtn.addActionListener(this);
GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
gbc_btnNewButton.gridwidth = 6;
gbc_btnNewButton.insets = new Insets(0, 5, 5, 5);
gbc_btnNewButton.gridx = 0;
gbc_btnNewButton.gridy = 16;
inputTab.add(doAlignmentBtn, gbc_btnNewButton);
// Button to reset alignment
resetAlignmentBtn = new JButton("Reset");
resetAlignmentBtn.addActionListener(this);
GridBagConstraints gbc_btnReset = new GridBagConstraints();
gbc_btnReset.gridwidth = 6;
gbc_btnReset.insets = new Insets(0, 5, 5, 5);
gbc_btnReset.gridx = 6;
gbc_btnReset.gridy = 16;
inputTab.add(resetAlignmentBtn, gbc_btnReset);
// inputTab ends here
}
private void filterTab() {
// filterTab starts here
filterTab = new JPanel();
tabs.insertTab("Cell Filters", null, filterTab, null, FILTERTAB);
GridBagLayout gbl_panel_1 = new GridBagLayout();
gbl_panel_1.columnWidths = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
gbl_panel_1.rowHeights = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
gbl_panel_1.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0,
Double.MIN_VALUE };
gbl_panel_1.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, Double.MIN_VALUE };
filterTab.setLayout(gbl_panel_1);
JLabel spacer9 = new JLabel(" ");
GridBagConstraints gbc_label_2 = new GridBagConstraints();
gbc_label_2.insets = new Insets(0, 0, 5, 5);
gbc_label_2.gridx = 7;
gbc_label_2.gridy = 1;
filterTab.add(spacer9, gbc_label_2);
JLabel lblCellFilters = new JLabel("Pre-watershed filter: ");
// lblCellFilters.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
GridBagConstraints gbc_lblCellFilters = new GridBagConstraints();
gbc_lblCellFilters.insets = new Insets(0, 5, 5, 0);
gbc_lblCellFilters.gridwidth = 5;
gbc_lblCellFilters.gridx = 1;
gbc_lblCellFilters.gridy = 2;
gbc_lblCellFilters.anchor = GridBagConstraints.WEST;
filterTab.add(lblCellFilters, gbc_lblCellFilters);
// Labels of size filters and TextFields for size filters
for (int iFilter = 0; iFilter < SIZE_FILTERS.length; iFilter++) {
JLabel lblCourseSizepixels = new JLabel(SIZE_FILTERS[iFilter]);
GridBagConstraints gbc_lblCourseSizepixels = new GridBagConstraints();
gbc_lblCourseSizepixels.gridwidth = 2;
gbc_lblCourseSizepixels.insets = new Insets(0, 5, 5, 5);
gbc_lblCourseSizepixels.gridx = 1;
gbc_lblCourseSizepixels.gridy = 3 + iFilter * 2;
filterTab.add(lblCourseSizepixels, gbc_lblCourseSizepixels);
filterSizeTexts[iFilter] = new JTextField();
filterSizeTexts[iFilter]
.setText(getFilterRange(filterMinSize_texts[iFilter], filterMaxSize_texts[iFilter]));
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.insets = new Insets(0, 5, 5, 5);
gbc_textField.gridwidth = 2;
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 3;
gbc_textField.gridy = 3 + iFilter * 2;
filterTab.add(filterSizeTexts[iFilter], gbc_textField);
filterSizeTexts[iFilter].setColumns(10);
}
// Checkbox for watershed
waterShedChckbx = new JCheckBox("Watershed segmentation");
GridBagConstraints gbc_chckbxWatershedSegmentationto = new GridBagConstraints();
gbc_chckbxWatershedSegmentationto.anchor = GridBagConstraints.WEST;
gbc_chckbxWatershedSegmentationto.gridwidth = 3;
gbc_chckbxWatershedSegmentationto.insets = new Insets(0, 5, 5, 0);
gbc_chckbxWatershedSegmentationto.gridx = 1;
gbc_chckbxWatershedSegmentationto.gridy = 4;
filterTab.add(waterShedChckbx, gbc_chckbxWatershedSegmentationto);
// other filters
JLabel lblFluorescenceAndShape = new JLabel("Physical and signal intensity parameter filters: ");
GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
gbc_lblNewLabel_1.gridwidth = 5;
gbc_lblNewLabel_1.insets = new Insets(0, 5, 5, 0);
gbc_lblNewLabel_1.gridx = 1;
gbc_lblNewLabel_1.gridy = 6;
gbc_lblNewLabel_1.anchor = GridBagConstraints.WEST;
filterTab.add(lblFluorescenceAndShape, gbc_lblNewLabel_1);
// Names of all cell filters
for (int iFilter = 0; iFilter < filterCombbxes.length; iFilter++) {
JLabel lblCellFilter1 = new JLabel("Cell filter " + (iFilter + 1));
GridBagConstraints gbc_lblCellFilter = new GridBagConstraints();
gbc_lblCellFilter.gridwidth = 1;
gbc_lblCellFilter.insets = new Insets(0, 5, 5, 5);
gbc_lblCellFilter.gridx = 1;
gbc_lblCellFilter.gridy = 7 + iFilter;
filterTab.add(lblCellFilter1, gbc_lblCellFilter);
filterCombbxes[iFilter] = new JComboBox<String>(filterStrings);
filterCombbxes[iFilter].setSelectedIndex(filter_combs[iFilter]);
GridBagConstraints gbc_comboBox_filters = new GridBagConstraints();
gbc_comboBox_filters.gridwidth = 2;
gbc_comboBox_filters.insets = new Insets(0, 5, 5, 5);
gbc_comboBox_filters.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox_filters.gridx = 2;
gbc_comboBox_filters.gridy = 7 + iFilter;
filterTab.add(filterCombbxes[iFilter], gbc_comboBox_filters);
filterRangeTexts[iFilter] = new JTextField();
filterRangeTexts[iFilter]
.setText(getFilterRange(filterMinRange_texts[iFilter], filterMaxRange_texts[iFilter]));
GridBagConstraints gbc_TextField_filterRanges = new GridBagConstraints();
gbc_TextField_filterRanges.gridwidth = 2;
gbc_TextField_filterRanges.insets = new Insets(0, 5, 5, 5);
gbc_TextField_filterRanges.fill = GridBagConstraints.HORIZONTAL;
gbc_TextField_filterRanges.gridx = 4;
gbc_TextField_filterRanges.gridy = 7 + iFilter;
filterTab.add(filterRangeTexts[iFilter], gbc_TextField_filterRanges);
filterRangeTexts[iFilter].setColumns(10);
}
tryIDCells = new JButton("Preview");
tryIDCells.addActionListener(this);
GridBagConstraints gbc_btnPreview = new GridBagConstraints();
gbc_btnPreview.gridwidth = 1;
gbc_btnPreview.insets = new Insets(0, 5, 0, 5);
gbc_btnPreview.gridx = 3;
gbc_btnPreview.gridy = 15;
filterTab.add(tryIDCells, gbc_btnPreview);
btnMoreFilters = new JButton("More Filters...");
btnMoreFilters.addActionListener(this);
GridBagConstraints gbc_btnMoreFilters = new GridBagConstraints();
gbc_btnMoreFilters.gridwidth = 1;
gbc_btnMoreFilters.insets = new Insets(0, 5, 0, 5);
gbc_btnMoreFilters.gridx = 5;
gbc_btnMoreFilters.gridy = 15;
filterTab.add(btnMoreFilters, gbc_btnMoreFilters);
// filterTab ends here
}
private void visualTab() {
// visualTab starts here
visualTab = new JPanel();
tabs.insertTab("Visualization", null, visualTab, null, VISUALTAB);
GridBagLayout gbl_panel_2 = new GridBagLayout();
gbl_panel_2.columnWidths = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
gbl_panel_2.rowHeights = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
gbl_panel_2.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE };
gbl_panel_2.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE };
visualTab.setLayout(gbl_panel_2);
{// Heat maps options
JLabel lblHeatMaps = new JLabel("Heat maps");
lblHeatMaps.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
GridBagConstraints gbc_lblHeatMaps = new GridBagConstraints();
gbc_lblHeatMaps.gridwidth = 6;
gbc_lblHeatMaps.insets = new Insets(5, 0, 5, 0);
gbc_lblHeatMaps.gridx = 1;
gbc_lblHeatMaps.gridy = 1;
visualTab.add(lblHeatMaps, gbc_lblHeatMaps);
JLabel spacer7 = new JLabel("Scaling options: ");
GridBagConstraints gbc_label_4 = new GridBagConstraints();
gbc_label_4.insets = new Insets(0, 5, 5, 0);
gbc_label_4.gridwidth = 6;
gbc_label_4.gridx = 1;
gbc_label_4.gridy = 2;
gbc_label_4.anchor = GridBagConstraints.WEST;
visualTab.add(spacer7, gbc_label_4);
for (int iHeat = 0; iHeat < heatmapRadiobtns.length; iHeat++) {
heatmapRadiobtns[iHeat] = new JRadioButton(HEATMAPOPTS[iHeat]);
heatmapTypeRadio.add(heatmapRadiobtns[iHeat]);
if (heatmap_radio == iHeat)
heatmapRadiobtns[iHeat].setSelected(true);
GridBagConstraints gbc_rdbtnScaledByCell = new GridBagConstraints();
gbc_rdbtnScaledByCell.anchor = GridBagConstraints.WEST;
gbc_rdbtnScaledByCell.insets = new Insets(0, 0, 5, 0);
gbc_rdbtnScaledByCell.gridwidth = 2;
gbc_rdbtnScaledByCell.gridx = 1 + iHeat * 2;
gbc_rdbtnScaledByCell.gridy = 3;
visualTab.add(heatmapRadiobtns[iHeat], gbc_rdbtnScaledByCell);
}
JLabel lblColorMaps = new JLabel("Color maps:");
GridBagConstraints gbc_lblColorMaps = new GridBagConstraints();
gbc_lblColorMaps.insets = new Insets(0, 5, 5, 0);
gbc_lblColorMaps.anchor = GridBagConstraints.WEST;
gbc_lblColorMaps.gridwidth = 6;
gbc_lblColorMaps.gridx = 1;
gbc_lblColorMaps.gridy = 4;
visualTab.add(lblColorMaps, gbc_lblColorMaps);
// new Checkbox and Comboboxes for heatmaps
for (int iHeat = 0; iHeat < heatmapColor_combs.length; iHeat++) {
heatmapChckbxes[iHeat] = new JCheckBox("Channel " + (iHeat + 1));
GridBagConstraints gbc_checkBox_thold = new GridBagConstraints();
gbc_checkBox_thold.insets = new Insets(0, 5, 5, 5);
gbc_checkBox_thold.gridwidth = 2;
gbc_checkBox_thold.gridx = 1;
gbc_checkBox_thold.gridy = 5 + iHeat;
visualTab.add(heatmapChckbxes[iHeat], gbc_checkBox_thold);
heatmapColorCombbxes[iHeat] = new JComboBox<String>(HEATMAPS);
heatmapColorCombbxes[iHeat].setSelectedIndex(heatmapColor_combs[iHeat]);
GridBagConstraints gbc_comboBox_color = new GridBagConstraints();
//Change in 1.1.0 from 4 to 3 to avoid major widht change between 2 and 3 reporters
gbc_comboBox_color.gridwidth = 3;
gbc_comboBox_color.insets = new Insets(5, 5, 5, 5);
gbc_comboBox_color.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox_color.gridx = 3;
gbc_comboBox_color.gridy = 5 + iHeat;
visualTab.add(heatmapColorCombbxes[iHeat], gbc_comboBox_color);
}
JSeparator separator2 = new JSeparator();
separator2.setForeground(Color.BLACK);
separator2.setBackground(SUBTABCOLORS[METRICSUBTAB]);
GridBagConstraints gbc_separator2 = new GridBagConstraints();
gbc_separator2.insets = new Insets(0, 5, 5, 0);
gbc_separator2.fill = GridBagConstraints.BOTH;
gbc_separator2.gridwidth = 6;
gbc_separator2.gridx = 1;
gbc_separator2.gridy = 5 + heatmapColor_combs.length;
visualTab.add(separator2, gbc_separator2);
}
{// scatter plots option
JLabel lblScatterPlots = new JLabel("Scatterplots");
lblScatterPlots.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
GridBagConstraints gbc_lblSP = new GridBagConstraints();
gbc_lblSP.gridwidth = 6;
gbc_lblSP.insets = new Insets(0, 0, 5, 0);
gbc_lblSP.gridx = 1;
gbc_lblSP.gridy = 6 + heatmapColor_combs.length;
visualTab.add(lblScatterPlots, gbc_lblSP);
// Checkbox for Scatter Plot
scatterplotChckbx = new JCheckBox("Cell pixel intensity scatterplots");
scatterplotChckbx.setSelected(scatter_chck);
GridBagConstraints gbc_chckbxPISP = new GridBagConstraints();
gbc_chckbxPISP.gridwidth = 6;
gbc_chckbxPISP.anchor = GridBagConstraints.SOUTHWEST;
gbc_chckbxPISP.insets = new Insets(0, 10, 5, 0);
gbc_chckbxPISP.gridx = 1;
gbc_chckbxPISP.gridy = 7 + heatmapColor_combs.length;
;
visualTab.add(scatterplotChckbx, gbc_chckbxPISP);
/*
* JLabel lblScatterNote = new JLabel(
* " (Use distribution to dictate metric choice)");
* GridBagConstraints gbc_label_3 = new GridBagConstraints();
* gbc_label_3.gridwidth = 6; gbc_label_3.insets = new Insets(0, 5,
* 5, 0); gbc_label_3.anchor = GridBagConstraints.NORTHWEST;
* gbc_label_3.gridx = 1; gbc_label_3.gridy = 8 +
* heatmapColor_combs.length; ; visualTab.add(lblScatterNote,
* gbc_label_3);
*/
JSeparator separator = new JSeparator();
separator.setForeground(Color.BLACK);
separator.setBackground(SUBTABCOLORS[METRICSUBTAB]);
GridBagConstraints gbc_separator = new GridBagConstraints();
gbc_separator.insets = new Insets(0, 5, 5, 10);
gbc_separator.fill = GridBagConstraints.BOTH;
gbc_separator.gridwidth = 6;
gbc_separator.gridx = 1;
gbc_separator.gridy = 9 + heatmapColor_combs.length;
;
visualTab.add(separator, gbc_separator);
}
{// metric matrices options
JLabel lblMatrices = new JLabel("Metric matrices");
lblMatrices.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
GridBagConstraints gbc_lblVM = new GridBagConstraints();
gbc_lblVM.gridwidth = 6;
gbc_lblVM.insets = new Insets(0, 0, 5, 0);
gbc_lblVM.gridx = 1;
gbc_lblVM.gridy = 10 + heatmapColor_combs.length;
;
visualTab.add(lblMatrices, gbc_lblVM);
// Checkbox for Scatter Plot
matrixChckbx = new JCheckBox("Matrices of different combinations of fractions");
matrixChckbx.setSelected(matrix_chck);
GridBagConstraints gbc_chckbxTM = new GridBagConstraints();
gbc_chckbxTM.gridwidth = 6;
gbc_chckbxTM.fill = GridBagConstraints.HORIZONTAL;
gbc_chckbxTM.insets = new Insets(0, 10, 5, 0);
gbc_chckbxTM.gridx = 1;
gbc_chckbxTM.gridy = 11 + heatmapColor_combs.length;
;
visualTab.add(matrixChckbx, gbc_chckbxTM);
for (int iFT = 0; iFT < matrixFTSpinners.length; iFT++) {
paneMatrixSpinners[iFT] = new JPanel();
JLabel ftLabel = new JLabel("FT (Ch." + (iFT + 1) + ") ");
ftLabel.setToolTipText("Selected fraction percentage (FT) for channel" + (iFT + 1));
/*
* GridBagConstraints gbc_label_ft = new GridBagConstraints();
* gbc_label_ft.gridwidth = 1; gbc_label_ft.insets = new
* Insets(0, 10, 5, 5); gbc_label_ft.anchor =
* GridBagConstraints.EAST; gbc_label_ft.gridx = 1+iFT*2;
* gbc_label_ft.gridy = 12 + heatmapChoices.length;;
*/
paneMatrixSpinners[iFT].add(ftLabel);
matrixFTSpinners[iFT] = new JSpinner(new SpinnerNumberModel(matrixFT_spin[iFT], MINFT, MAXFT, STEPFT));
JLabel unitLabel = new JLabel("%");
paneMatrixSpinners[iFT].add(matrixFTSpinners[iFT]);
paneMatrixSpinners[iFT].add(unitLabel);
JSpinner.NumberEditor editor = new JSpinner.NumberEditor(matrixFTSpinners[iFT], "0");
matrixFTSpinners[iFT].setEditor(editor);
JFormattedTextField textField = ((JSpinner.NumberEditor) matrixFTSpinners[iFT].getEditor())
.getTextField();
textField.setEditable(true);
DefaultFormatterFactory factory = (DefaultFormatterFactory) textField.getFormatterFactory();
NumberFormatter formatter = (NumberFormatter) factory.getDefaultFormatter();
formatter.setAllowsInvalid(false);
GridBagConstraints gbc_Mspinner = new GridBagConstraints();
gbc_Mspinner.gridwidth = 2;
gbc_Mspinner.insets = new Insets(0, 0, 5, 0);
gbc_Mspinner.anchor = GridBagConstraints.WEST;
// gbc_Mspinner.fill = GridBagConstraints.HORIZONTAL;
gbc_Mspinner.gridx = 1 + iFT * 2;
gbc_Mspinner.gridy = 12 + heatmapColor_combs.length;
;
visualTab.add(paneMatrixSpinners[iFT], gbc_Mspinner);
}
{
JLabel metricLabel = new JLabel("Metric: ");
GridBagConstraints gbc_label_metric = new GridBagConstraints();
gbc_label_metric.gridwidth = 1;
gbc_label_metric.insets = new Insets(0, 10, 5, 5);
gbc_label_metric.anchor = GridBagConstraints.EAST;
gbc_label_metric.gridx = 1;
gbc_label_metric.gridy = 13 + heatmapColor_combs.length;
visualTab.add(metricLabel, gbc_label_metric);
matrixMetricCombbx = new JComboBox<String>(matrixMetricList);
matrixMetricCombbx.setSelectedIndex(matrixMetric_comb);
GridBagConstraints gbc_comboBox_metric = new GridBagConstraints();
gbc_comboBox_metric.gridwidth = 1;
gbc_comboBox_metric.insets = new Insets(0, 0, 5, 0);
gbc_comboBox_metric.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox_metric.gridx = 2;
gbc_comboBox_metric.gridy = 13 + heatmapColor_combs.length;
visualTab.add(matrixMetricCombbx, gbc_comboBox_metric);
}
{
JLabel statsLabel = new JLabel("Average: ");
GridBagConstraints gbc_label_stats = new GridBagConstraints();
gbc_label_stats.gridwidth = 1;
gbc_label_stats.insets = new Insets(0, 10, 5, 5);
gbc_label_stats.anchor = GridBagConstraints.EAST;
gbc_label_stats.gridx = 3;
gbc_label_stats.gridy = 13 + heatmapColor_combs.length;
visualTab.add(statsLabel, gbc_label_stats);
matrixStatsCombbx = new JComboBox<String>(STATS_METHODS);
matrixStatsCombbx.setSelectedIndex(matrixStats_comb);
GridBagConstraints gbc_comboBox_stats = new GridBagConstraints();
gbc_comboBox_stats.gridwidth = 1;
gbc_comboBox_stats.insets = new Insets(0, 0, 5, 0);
gbc_comboBox_stats.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox_stats.gridx = 4;
gbc_comboBox_stats.gridy = 13 + heatmapColor_combs.length;
visualTab.add(matrixStatsCombbx, gbc_comboBox_stats);
}
}
previewVisual = new JButton("Preview");
previewVisual.addActionListener(this);
GridBagConstraints gbc_button_preview = new GridBagConstraints();
gbc_button_preview.gridwidth = 6;
gbc_button_preview.insets = new Insets(10, 5, 10, 5);
gbc_button_preview.gridx = 1;
gbc_button_preview.gridy = 14 + heatmapColor_combs.length;
visualTab.add(previewVisual, gbc_button_preview);
// visualTab ends here
}
@SuppressWarnings("serial")
private void analysisTab() {
// analysisTab starts here
analysisTab = new JPanel();
analysisTab.setLayout(new GridLayout(1, 0, 0, 0));
// New analysisSubTab
analysisSubTabs = new JTabbedPane(JTabbedPane.TOP);
analysisTab.add(analysisSubTabs);
// addTabs
tabs.insertTab("Analysis", null, analysisTab, null, ANALYSISTAB);
// Add in 1.1.0 to group metricSubTab content in a separate function
metricSubTab();
analysisSubTabs.insertTab("Analysis Metrics", null, metricSubTab, null, METRICSUBTAB);
analysisSubTabs.setBackgroundAt(METRICSUBTAB, SUBLABELCOLORS[METRICSUBTAB]);
// Add in 1.1.0 for info regarding metric acronyms
infoSubTab();
analysisSubTabs.insertTab("Metrics Info", null, infoSubTab, null, INFOSUBTAB);
analysisSubTabs.setBackgroundAt(INFOSUBTAB, SUBLABELCOLORS[INFOSUBTAB]);
// Add in 1.1.0 to group customSubTab content in a separate function
customSubTab();
analysisSubTabs.insertTab("Custom", null, customSubTab, null, CUSTOMSUBTAB);
analysisSubTabs.setBackgroundAt(CUSTOMSUBTAB, SUBLABELCOLORS[CUSTOMSUBTAB]);
// analysisTab ends here
}
private void metricSubTab() {
metricSubTab = new JPanel();
metricSubTab.setBackground(SUBTABCOLORS[METRICSUBTAB]);
GridBagLayout gbl_panel_metricSubTab = new GridBagLayout();
gbl_panel_metricSubTab.columnWidths = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
gbl_panel_metricSubTab.rowHeights = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
gbl_panel_metricSubTab.columnWeights = new double[] { Double.MIN_VALUE, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, Double.MIN_VALUE };
gbl_panel_metricSubTab.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, Double.MIN_VALUE };
metricSubTab.setLayout(gbl_panel_metricSubTab);
JLabel lblColocalizationMetrics = new JLabel("Colocalization metrics");
lblColocalizationMetrics.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
GridBagConstraints gbc_lblColocalizationMetrics = new GridBagConstraints();
gbc_lblColocalizationMetrics.gridwidth = gbl_panel_metricSubTab.columnWidths.length;
gbc_lblColocalizationMetrics.insets = new Insets(0, 0, 5, 0);
gbc_lblColocalizationMetrics.gridx = 0;
gbc_lblColocalizationMetrics.gridy = 1;
metricSubTab.add(lblColocalizationMetrics, gbc_lblColocalizationMetrics);
JLabel lblMetricTholdsLabel = new JLabel("Threshold: ");
lblMetricTholdsLabel.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
GridBagConstraints gbc_lblMetricTholdsLabel = new GridBagConstraints();
gbc_lblMetricTholdsLabel.insets = new Insets(0, 5, 0, 5);
gbc_lblMetricTholdsLabel.gridx = 1;
gbc_lblMetricTholdsLabel.gridy = 2;
metricSubTab.add(lblMetricTholdsLabel, gbc_lblMetricTholdsLabel);
for (int iThold = 0; iThold < METRIC_THOLDS.length; iThold++) {
lblMetricTholds[iThold] = new JLabel(METRIC_THOLDS[iThold]);
lblMetricTholds[iThold].setFont(new Font("Lucida Grande", Font.PLAIN, 15));
lblMetricTholds[iThold].setToolTipText(METRIC_THOLDS_TIPS[iThold]);
GridBagConstraints gbc_lblMetricTholds = new GridBagConstraints();
gbc_lblMetricTholds.insets = new Insets(0, 5, 0, 5);
gbc_lblMetricTholds.gridx = 2 + iThold;
gbc_lblMetricTholds.gridy = 2;
metricSubTab.add(lblMetricTholds[iThold], gbc_lblMetricTholds);
}
for (int ipic = 0; ipic < allFTSpinners.length; ipic++) {
lblFTunits[ipic] = new JLabel("Ch." + (ipic + 1) + "%");
lblFTunits[ipic].setFont(new Font("Lucida Grande", Font.PLAIN, 15));
GridBagConstraints gbc_lblMetricTholdsFT2 = new GridBagConstraints();
gbc_lblMetricTholdsFT2.insets = new Insets(0, 5, 0, 5);
gbc_lblMetricTholdsFT2.gridx = 5 + ipic;
gbc_lblMetricTholdsFT2.gridy = 2;
metricSubTab.add(lblFTunits[ipic], gbc_lblMetricTholdsFT2);
}
for (int iMetric = 0; iMetric < METRICACRONYMS.length; iMetric++) {
metricChckbxes[iMetric] = new JCheckBox(METRICACRONYMS[iMetric]);
metricChckbxes[iMetric].setBackground(SUBTABCOLORS[METRICSUBTAB]);
metricChckbxes[iMetric].setToolTipText(METRICNAMES[iMetric]);
GridBagConstraints gbc_chckbxNewCheckBox_3 = new GridBagConstraints();
gbc_chckbxNewCheckBox_3.anchor = GridBagConstraints.WEST;
gbc_chckbxNewCheckBox_3.insets = new Insets(5, 5, 5, 5);
gbc_chckbxNewCheckBox_3.gridx = 1;
gbc_chckbxNewCheckBox_3.gridy = 3 + iMetric;
metricSubTab.add(metricChckbxes[iMetric], gbc_chckbxNewCheckBox_3);
metricRadioGroup[iMetric] = new ButtonGroup();
for (int iThold = 0; iThold < METRIC_THOLDS.length; iThold++) {
if (NO_THOLD_ALL.indexOf(iMetric) >= 0 && iThold == IDX_THOLD_ALL)
continue;
metricTholdRadiobtns[iMetric][iThold] = new JRadioButton();
metricRadioGroup[iMetric].add(metricTholdRadiobtns[iMetric][iThold]);
if (iThold == metricThold_radios[iMetric])
metricTholdRadiobtns[iMetric][iThold].setSelected(true);
metricTholdRadiobtns[iMetric][iThold].setBackground(SUBTABCOLORS[METRICSUBTAB]);
metricTholdRadiobtns[iMetric][iThold].putClientProperty("iMetric", iMetric);
if (iThold == IDX_THOLD_FT) {
metricTholdRadiobtns[iMetric][iThold].addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
Object origin = e.getSource();
int iMetric = (Integer) ((JRadioButton) origin).getClientProperty("iMetric");
if (e.getStateChange() == ItemEvent.SELECTED)
for (int i = 0; i < allFTSpinners.length; i++)
allFTSpinners[i][iMetric].setEnabled(true);
else if (e.getStateChange() == ItemEvent.DESELECTED)
for (int i = 0; i < allFTSpinners.length; i++)
allFTSpinners[i][iMetric].setEnabled(false);
}
});
}
GridBagConstraints gbc_rdbtnLinear = new GridBagConstraints();
gbc_rdbtnLinear.anchor = GridBagConstraints.CENTER;
gbc_rdbtnLinear.insets = new Insets(5, 5, 5, 5);
gbc_rdbtnLinear.gridx = 2 + iThold;
gbc_rdbtnLinear.gridy = 3 + iMetric;
metricSubTab.add(metricTholdRadiobtns[iMetric][iThold], gbc_rdbtnLinear);
}
if (metricRadioGroup[iMetric].getSelection() == null) {
int iThold = 0;
while (metricTholdRadiobtns[iMetric][iThold] == null)
iThold++;
metricTholdRadiobtns[iMetric][iThold].setSelected(true);
}
for (int ipic = 0; ipic < allFTSpinners.length; ipic++) {
allFTSpinners[ipic][iMetric] = new JSpinner(
new SpinnerNumberModel(allFT_spins[ipic][iMetric], MINFT, MAXFT, STEPFT));
GridBagConstraints gbc_spinner = new GridBagConstraints();
gbc_spinner.insets = new Insets(0, 5, 0, 5);
gbc_spinner.gridx = 5 + ipic;
gbc_spinner.gridy = 3 + iMetric;
metricSubTab.add(allFTSpinners[ipic][iMetric], gbc_spinner);
JSpinner.NumberEditor editor = new JSpinner.NumberEditor(allFTSpinners[ipic][iMetric], "0");
allFTSpinners[ipic][iMetric].setEditor(editor);
JFormattedTextField textField = ((JSpinner.NumberEditor) allFTSpinners[ipic][iMetric].getEditor())
.getTextField();
textField.setEditable(true);
DefaultFormatterFactory factory = (DefaultFormatterFactory) textField.getFormatterFactory();
NumberFormatter formatter = (NumberFormatter) factory.getDefaultFormatter();
formatter.setAllowsInvalid(false);
if (metricThold_radios[iMetric] != IDX_THOLD_FT) {
allFTSpinners[ipic][iMetric].setEnabled(false);
}
}
}
JLabel spacer5 = new JLabel(" ");
GridBagConstraints gbc_label_8 = new GridBagConstraints();
gbc_label_8.insets = new Insets(5, 5, 5, 5);
gbc_label_8.gridx = 3;
gbc_label_8.gridy = 7;
metricSubTab.add(spacer5, gbc_label_8);
JLabel lblOtherMetrics = new JLabel("Other metrics");
lblOtherMetrics.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
GridBagConstraints gbc_lblOtherMetrics = new GridBagConstraints();
gbc_lblOtherMetrics.insets = new Insets(0, 0, 5, 0);
gbc_lblOtherMetrics.gridwidth = gbl_panel_metricSubTab.columnWidths.length;
gbc_lblOtherMetrics.gridx = 0;
gbc_lblOtherMetrics.gridy = 8;
metricSubTab.add(lblOtherMetrics, gbc_lblOtherMetrics);
int NUMOFCOLUMNS = 2;
for (int i = 0; i < otherChckbxes.length; i++) {
otherChckbxes[i] = new JCheckBox(OTHERNAMES[i]);
otherChckbxes[i].setBackground(SUBTABCOLORS[METRICSUBTAB]);
GridBagConstraints gbc_chckbxNewCheckBox_11 = new GridBagConstraints();
gbc_chckbxNewCheckBox_11.gridwidth = 2;
gbc_chckbxNewCheckBox_11.insets = new Insets(5, 5, 5, 5);
gbc_chckbxNewCheckBox_11.gridx = 1 + i % NUMOFCOLUMNS * 4;
gbc_chckbxNewCheckBox_11.gridy = 9 + i / NUMOFCOLUMNS;
metricSubTab.add(otherChckbxes[i], gbc_chckbxNewCheckBox_11);
}
otherChckbxes[otherChckbxes.length - 1].addActionListener(this);
JSeparator separator = new JSeparator();
separator.setForeground(Color.BLACK);
separator.setBackground(SUBTABCOLORS[METRICSUBTAB]);
GridBagConstraints gbc_separator = new GridBagConstraints();
gbc_separator.insets = new Insets(0, 0, 5, 0);
gbc_separator.fill = GridBagConstraints.BOTH;
gbc_separator.gridwidth = gbl_panel_metricSubTab.columnWidths.length - 2;
gbc_separator.gridx = 1;
gbc_separator.gridy = 10;
metricSubTab.add(separator, gbc_separator);
JLabel lblForSelectedMetrics = new JLabel("For values of selected metric(s):");
lblForSelectedMetrics.setFont(new Font("Dialog", Font.PLAIN, 13));
GridBagConstraints gbc_lblForSelectedMetrics = new GridBagConstraints();
gbc_lblForSelectedMetrics.anchor = GridBagConstraints.CENTER;
gbc_lblForSelectedMetrics.gridwidth = gbl_panel_metricSubTab.columnWidths.length;
gbc_lblForSelectedMetrics.insets = new Insets(0, 10, 5, 5);
gbc_lblForSelectedMetrics.gridx = 0;
gbc_lblForSelectedMetrics.gridy = 11;
metricSubTab.add(lblForSelectedMetrics, gbc_lblForSelectedMetrics);
NUMOFCOLUMNS = 2;
for (int i = 0; i < outputMetricChckbxes.length; i++) {
outputMetricChckbxes[i] = new JCheckBox(OUTPUTMETRICS[i]);
outputMetricChckbxes[i].setBackground(SUBTABCOLORS[METRICSUBTAB]);
GridBagConstraints gbc_chckbxNewCheckBox_14 = new GridBagConstraints();
gbc_chckbxNewCheckBox_14.anchor = GridBagConstraints.WEST;
gbc_chckbxNewCheckBox_14.insets = new Insets(10, 10, 10, 10);
gbc_chckbxNewCheckBox_14.gridwidth = 2;
gbc_chckbxNewCheckBox_14.gridx = 1 + i % NUMOFCOLUMNS * 4;
gbc_chckbxNewCheckBox_14.gridy = 12 + i / NUMOFCOLUMNS;
metricSubTab.add(outputMetricChckbxes[i], gbc_chckbxNewCheckBox_14);
}
JLabel lblForCellIdentification = new JLabel("For cell identification function:");
lblForCellIdentification.setFont(new Font("Dialog", Font.PLAIN, 13));
GridBagConstraints gbc_lblForCellIdentification = new GridBagConstraints();
gbc_lblForCellIdentification.anchor = GridBagConstraints.CENTER;
gbc_lblForCellIdentification.gridwidth = gbl_panel_metricSubTab.columnWidths.length;
gbc_lblForCellIdentification.insets = new Insets(5, 10, 5, 5);
gbc_lblForCellIdentification.gridx = 0;
gbc_lblForCellIdentification.gridy = 13;
metricSubTab.add(lblForCellIdentification, gbc_lblForCellIdentification);
NUMOFCOLUMNS = 2;
for (int i = 0; i < outputOptChckbxes.length; i++) {
outputOptChckbxes[i] = new JCheckBox(OUTPUTOTHERS[i]);
outputOptChckbxes[i].setBackground(SUBTABCOLORS[METRICSUBTAB]);
GridBagConstraints gbc_chckbxRegionsOfInterest = new GridBagConstraints();
gbc_chckbxRegionsOfInterest.anchor = GridBagConstraints.WEST;
gbc_chckbxRegionsOfInterest.insets = new Insets(10, 10, 10, 10);
gbc_chckbxRegionsOfInterest.gridwidth = 2;
gbc_chckbxRegionsOfInterest.gridx = 1 + i % NUMOFCOLUMNS * 4;
gbc_chckbxRegionsOfInterest.gridy = 14 + i / NUMOFCOLUMNS;
metricSubTab.add(outputOptChckbxes[i], gbc_chckbxRegionsOfInterest);
}
}
private void customSubTab() {
// Custom function
customSubTab = new JPanel();
customSubTab.setBackground(SUBTABCOLORS[CUSTOMSUBTAB]);
GridBagLayout gbl_panel_9 = new GridBagLayout();
gbl_panel_9.columnWidths = new int[] { 0, 0, 0, 0, 0, 0, 0, 0 };
gbl_panel_9.rowHeights = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
gbl_panel_9.columnWeights = new double[] { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 };
gbl_panel_9.rowWeights = new double[] { 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
Double.MIN_VALUE };
customSubTab.setLayout(gbl_panel_9);
JLabel lblWriteYourOwn = new JLabel("Write your own function in Java below");
lblWriteYourOwn.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints gbc_lblWriteYourOwn = new GridBagConstraints();
gbc_lblWriteYourOwn.gridwidth = 12;
gbc_lblWriteYourOwn.insets = new Insets(0, 0, 5, 0);
gbc_lblWriteYourOwn.gridx = 0;
gbc_lblWriteYourOwn.gridy = 1;
customSubTab.add(lblWriteYourOwn, gbc_lblWriteYourOwn);
customMetricChckbxes = new JCheckBox("", custom_chck);
customMetricChckbxes.setHorizontalAlignment(JCheckBox.CENTER);
customMetricChckbxes.setBackground(SUBTABCOLORS[CUSTOMSUBTAB]);
if (custom_chck)
setCustomStatus(RUN);
else
setCustomStatus(SKIP);
customMetricChckbxes.addActionListener(this);
GridBagConstraints gbc_lblchckbxCustom = new GridBagConstraints();
gbc_lblchckbxCustom.gridwidth = 12;
gbc_lblchckbxCustom.insets = new Insets(0, 0, 5, 5);
// gbc_lblchckbxCustom.anchor = GridBagConstraints.WEST;
gbc_lblchckbxCustom.gridx = 0;
gbc_lblchckbxCustom.gridy = 2;
customSubTab.add(customMetricChckbxes, gbc_lblchckbxCustom);
customCodeTextbx = new JTextArea();
// customCode.setSize(tabWidth1,subTabHeight);
// if (!IJ.isWindows())customCode.setSize(tabWidth2, subTabHeight);
customCode_text = StringCompiler.getDefaultCode();
customCodeTextbx.setText(customCode_text);
customCodeTextbx.setEditable(true);
customCodeTextbx.setLineWrap(false);
customCodeTextbx.setTabSize(StringCompiler.tabSize);
// customCode.setPreferredSize(new Dimension(356, 112));
customCodeScrollpn = new JScrollPane(customCodeTextbx, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
TextLineNumber tln = new TextLineNumber(customCodeTextbx);
customCodeScrollpn.setRowHeaderView(tln);
customCodeScrollpn.setPreferredSize(new Dimension(0, 0));
GridBagConstraints gbc_textArea = new GridBagConstraints();
gbc_textArea.gridheight = 8;
gbc_textArea.gridwidth = 12;
gbc_textArea.insets = new Insets(5, 10, 5, 10);
gbc_textArea.fill = GridBagConstraints.BOTH;
gbc_textArea.gridx = 0;
gbc_textArea.gridy = 3;
customSubTab.add(customCodeScrollpn, gbc_textArea);
// The following block of code is retrieved from
// https://web.archive.org/web/20100114122417/http://exampledepot.com/egs/javax.swing.undo/UndoText.html
{
final UndoManager undoManager = new UndoManager();
// Listen for undo and redo events
customCodeTextbx.getDocument().addUndoableEditListener(new UndoableEditListener() {
public void undoableEditHappened(UndoableEditEvent evt) {
undoManager.addEdit(evt.getEdit());
}
});
// Create an undo action and add it to the text component
customCodeTextbx.getActionMap().put("Undo", new AbstractAction("Undo") {
public void actionPerformed(ActionEvent evt) {
try {
if (undoManager.canUndo()) {
undoManager.undo();
}
} catch (CannotUndoException e) {
}
}
});
// Bind the undo action to ctrl-Z
customCodeTextbx.getInputMap().put(KeyStroke.getKeyStroke("ctrl Z"), "Undo");
// Create a redo action and add it to the text component
customCodeTextbx.getActionMap().put("Redo", new AbstractAction("Redo") {
public void actionPerformed(ActionEvent evt) {
try {
if (undoManager.canRedo()) {
undoManager.redo();
}
} catch (CannotRedoException e) {
}
}
});
// Bind the redo action to ctrl-Y
customCodeTextbx.getInputMap().put(KeyStroke.getKeyStroke("ctrl Y"), "Redo");
}
runCustomBtn = new JButton("Compile");
runCustomBtn.addActionListener(this);
GridBagConstraints gbc_btn_runCustom = new GridBagConstraints();
gbc_btn_runCustom.gridwidth = 2;
gbc_btn_runCustom.insets = new Insets(10, 10, 10, 10);
gbc_btn_runCustom.gridx = 0;
gbc_btn_runCustom.gridy = 12;
customSubTab.add(runCustomBtn, gbc_btn_runCustom);
resetCustomBtn = new JButton("Reset");
resetCustomBtn.addActionListener(this);
GridBagConstraints gbc_btn_resetCustom = new GridBagConstraints();
gbc_btn_resetCustom.gridwidth = 2;
gbc_btn_resetCustom.insets = new Insets(10, 10, 10, 10);
gbc_btn_resetCustom.gridx = 3;
gbc_btn_resetCustom.gridy = 12;
customSubTab.add(resetCustomBtn, gbc_btn_resetCustom);
helpCustomBtn = new JButton("Resource");
helpCustomBtn.addActionListener(this);
GridBagConstraints gbc_btn_helpCustom = new GridBagConstraints();
gbc_btn_helpCustom.gridwidth = 2;
gbc_btn_helpCustom.insets = new Insets(10, 10, 10, 10);
gbc_btn_helpCustom.gridx = 6;
gbc_btn_helpCustom.gridy = 12;
customSubTab.add(helpCustomBtn, gbc_btn_helpCustom);
}
private void infoSubTab() {
infoSubTab = new JPanel();
infoSubTab.setBackground(SUBTABCOLORS[INFOSUBTAB]);
GridBagLayout gb_info_panel_1 = new GridBagLayout();
gb_info_panel_1.columnWidths = new int[] { 0, 0, 0 };
gb_info_panel_1.rowHeights = new int[] { 0, 0, 0 };
gb_info_panel_1.columnWeights = new double[] { Double.MIN_VALUE, 1.0, Double.MIN_VALUE };
gb_info_panel_1.rowWeights = new double[] { Double.MIN_VALUE, 1.0, Double.MIN_VALUE };
infoSubTab.setLayout(gb_info_panel_1);
infoTextpn = new JEditorPane();
infoTextpn.setEditable(false);
infoTextpn.addHyperlinkListener(new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
try {
BrowserLauncher.openURL(e.getURL().toString());
} catch (IOException ie) {
IJ.error(e.getURL().toString() + " cannot be opened");
}
}
});
StyledDocument doc = new HTMLDocument();
String newline = "\n";
infoTextpn.setContentType("text/html");
infoTextpn.setText("<html>" + "</html>"); // Document text is provided
// below.
doc = (HTMLDocument) infoTextpn.getDocument();
Style style;
style = doc.addStyle("Metric Name", null);
StyleConstants.setForeground(style, Color.RED);
StyleConstants.setBold(style, true);
StyleConstants.setFontFamily(style, "Arial Black");
StyleConstants.setFontSize(style, 12);
style = doc.addStyle("Metric Intepretation", null);
StyleConstants.setForeground(style, Color.BLACK);
StyleConstants.setFontFamily(style, "Arial");
StyleConstants.setFontSize(style, 12);
style = doc.addStyle("Other Name", null);
StyleConstants.setForeground(style, Color.BLUE);
StyleConstants.setBold(style, true);
StyleConstants.setFontFamily(style, "Arial Black");
StyleConstants.setFontSize(style, 12);
SimpleAttributeSet hrefAttr;
// Load the text pane with styled text.
try {
// Add in 1.1.0 a readme pane with all metric definitions
for (int iMetric = 0; iMetric < BasicCalculator.getNum(); iMetric++) {
String[] intpn = BasicCalculator.getIntpn(iMetric);
if (intpn == null || intpn[0] == null)
break;
style = doc.getStyle("Metric Name");
if(intpn[2] == null){
style.removeAttribute(HTML.Tag.A);
}else{
hrefAttr = new SimpleAttributeSet();
hrefAttr.addAttribute(HTML.Attribute.HREF, intpn[2]);
style.addAttribute(HTML.Tag.A, hrefAttr);
}
doc.insertString(doc.getLength(), intpn[0], style);
doc.insertString(doc.getLength(), newline, null);
doc.insertString(doc.getLength(), intpn[1], doc.getStyle("Metric Interpretation"));
doc.insertString(doc.getLength(), newline + newline, null);
}
for (int iExtra = 0; iExtra < extraInfo.length; iExtra++) {
style = doc.getStyle("Other Name");
if(extraInfo[iExtra][2] == null){
style.removeAttribute(HTML.Tag.A);
}else{
hrefAttr = new SimpleAttributeSet();
hrefAttr.addAttribute(HTML.Attribute.HREF, extraInfo[iExtra][2]);
style.addAttribute(HTML.Tag.A, hrefAttr);
}
doc.insertString(doc.getLength(), extraInfo[iExtra][0], style);
doc.insertString(doc.getLength(), newline, null);
doc.insertString(doc.getLength(), extraInfo[iExtra][1], doc.getStyle("Metric Interpretation"));
doc.insertString(doc.getLength(), newline + newline, null);
}
} catch (BadLocationException ble) {
IJ.error(PluginStatic.pluginName + " error", "Couldn't insert initial text into JEditorpane.");
}
infoScrollpn = new JScrollPane(infoTextpn, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
infoScrollpn.setPreferredSize(new Dimension(0, 0));
GridBagConstraints gbc_info_textpane = new GridBagConstraints();
gbc_info_textpane.gridheight = 1;
gbc_info_textpane.gridwidth = 1;
gbc_info_textpane.insets = new Insets(10, 10, 10, 10);
gbc_info_textpane.fill = GridBagConstraints.BOTH;
gbc_info_textpane.gridx = 1;
gbc_info_textpane.gridy = 1;
infoSubTab.add(infoScrollpn, gbc_info_textpane);
}
private void aboutPane() {
// aboutPanel starts here
aboutPanel = new JPanel();
GridBagConstraints gbc_panel_about = new GridBagConstraints();
gbc_panel_about.gridwidth = 4;
gbc_panel_about.insets = new Insets(0, 0, 5, 0);
gbc_panel_about.fill = GridBagConstraints.BOTH;
gbc_panel_about.gridx = 0;
gbc_panel_about.gridy = 2;
superPanel.add(aboutPanel, gbc_panel_about);
JTextArea txtrReference = new JTextArea();
txtrReference.setBackground(SystemColor.window);
txtrReference.setFont(new Font("Lucida Grande", Font.PLAIN, 10));
txtrReference.setText(ABOUT_TEXT);
txtrReference.setEditable(false);
aboutPanel.add(txtrReference);
warning = new JLabel("------------------------------------------");
warning.setForeground(Color.RED);
GridBagConstraints gbc_label_1 = new GridBagConstraints();
gbc_label_1.insets = new Insets(0, 0, 0, 5);
gbc_label_1.gridx = 1;
gbc_label_1.gridy = 3;
superPanel.add(warning, gbc_label_1);
// Master button here
analyzeBtn = new JButton("Analyze");
analyzeBtn.addActionListener(this);
GridBagConstraints gbc_btnAnalyze = new GridBagConstraints();
gbc_btnAnalyze.insets = new Insets(0, 0, 0, 5);
gbc_btnAnalyze.gridx = 2;
gbc_btnAnalyze.gridy = 3;
superPanel.add(analyzeBtn, gbc_btnAnalyze);
// Email button here
email = new JButton("Help");
email.setToolTipText("Email the author (" + CONTACT + ") for any question");
email.addActionListener(this);
GridBagConstraints gbc_btnNewButton_1 = new GridBagConstraints();
gbc_btnNewButton_1.anchor = GridBagConstraints.EAST;
gbc_btnNewButton_1.gridx = 3;
gbc_btnNewButton_1.gridy = 3;
superPanel.add(email, gbc_btnNewButton_1);
}
public synchronized void updateImgList(ImagePlus addImp, ImagePlus deleteImp) {
final byte NO_IMG = 4, NULL_IMG = 0, ADD_IMG = 1, DEL_IMG = 2, REPLACE_IMG = ADD_IMG + DEL_IMG;
// use as offset when new image labels are added to JCombobox
final int[] offset = new int[imgCombbxes.length];
boolean isOpened = false;
int idxClose = -1;
boolean updateListAll = addImp == null && deleteImp == null;
if (imgCombbxes == null)
return;
int[] selected = new int[imgCombbxes.length];
for (int ipic = 0; ipic < selected.length; ipic++) {
if (imgCombbxes[ipic] != null)
selected[ipic] = imgCombbxes[ipic].getSelectedIndex();
// general offset is set here, must be consistent to the loop below
offset[ipic] = 1;
}
// conditional offset is set here, must be consistent to the one
// outsidee the loop below
offset[offset.length - 1] = 2;
// img3dTOS
// final int d3TOSoffset = 1;
// int d3TOSselected = imgd3TOS.getSelectedIndex();
// This part
if (updateListAll) {
resetInfoArray();
for (int ipic = 0; ipic < imgCombbxes.length; ipic++) {
imgCombbxes[ipic].setEnabled(false);
imgCombbxes[ipic].removeAllItems();
imgCombbxes[ipic].addItem(NOIMAGE);
}
// imgs[imgs.length-1] has one additional element, please be
// cautious
// Because of this, the offset has been set as above;
imgCombbxes[imgCombbxes.length - 1].addItem(ROIMANAGER_IMAGE);
// img3dTOS
/*
* if(imgd3TOS!=null){ imgd3TOS.setEnabled(false);
* imgd3TOS.removeAllItems(); imgd3TOS.addItem(NOIMAGE); }
*/
}
// RGB and 8-bit color images are not taken into account
if (WindowManager.getImageCount() != 0) {
nbImgs = 0;
int[] IDList = WindowManager.getIDList();
for (int i = 0; i < IDList.length; i++) {
ImagePlus currImg = WindowManager.getImage(IDList[i]);
if (currImg.getType() != ImagePlus.COLOR_RGB) {
nbImgs++;
if (updateListAll) {
ImageInfo item = new ImageInfo(currImg);
info.insertElementAt(item, info.size() - 1);
for (int ipic = 0; ipic < imgCombbxes.length; ipic++)
imgCombbxes[ipic].insertItemAt(item, imgCombbxes[ipic].getItemCount() - offset[ipic]);
// img3dTOS
/*
* if(imgd3TOS!=null) imgd3TOS.insertItemAt(item,
* imgd3TOS.getItemCount()-d3TOSoffset);
*/
}
if (addImp != null && currImg == addImp)
isOpened = true;
} else {
// Do not add RGB or 8-bit color images
if (addImp != null && currImg == addImp)
isOpened = false;
}
}
}
if (deleteImp != null) {
for (int i = 0; i < info.size(); i++) {
if (info.elementAt(i).equalID(deleteImp)) {
idxClose = i;
break;
}
}
}
if (addImp != null && deleteImp == null) {
for (int i = 0; i < info.size(); i++) {
if (info.elementAt(i).equal(new ImageInfo(addImp))) {
addImp = null;
break;
}
}
}
if (!isOpened)
addImp = null;
if (idxClose < 0)
deleteImp = null;
byte updateTypeAfter = 0;
if (updateListAll)
updateTypeAfter = NO_IMG;
else
updateTypeAfter = (byte) ((addImp == null ? NULL_IMG : ADD_IMG) + (deleteImp == null ? NULL_IMG : DEL_IMG));
if (nbImgs <= 0) {
tabs.setSelectedIndex(0);
tabs.setEnabled(false);
analyzeBtn.setEnabled(false);
warning.setText("Image(s) should be opened to run analysis");
} else {
tabs.setEnabled(true);
analyzeBtn.setEnabled(true);
warning.setText("Please make sure everything is all set\n");
}
// insert new Image before [No Image]
switch (updateTypeAfter) {
case NULL_IMG:
return;
case NO_IMG:
// if (updateType == 0)
int i = 0;
for (int ipic = 0; ipic < selected.length; ipic++)
if (ipic < info.size() && imgCombbxes[ipic].isVisible())
selected[ipic] = i++;
else
selected[ipic] = imgCombbxes[ipic].getItemCount() - offset[ipic];
for (int ipic = 0; ipic < imgCombbxes.length; ipic++)
imgCombbxes[ipic].setEnabled(false);
// d3TOSselected = selected.length;
break;
case ADD_IMG: {
// Avoid adding one image twice
// if (updateType == (ADD_IMG + DEL_IMG) && addImp.getID() ==
// deleteImp.getID())
// return;
boolean noimg = true;
for (int ipic = 0; ipic < selected.length; ipic++) {
// If the selection is beyond known, it should be maintained
// If the JCombobox is not visible, its selection should also be
// maintained
// The way to maintain current selection is increasing the index
// by one
// Here the offset doesn't apply because ADD_IMG add one image
// at a time
// It is independent of the number of elements on the list
if (selected[ipic] >= info.size() || !imgCombbxes[ipic].isVisible())
selected[ipic]++;
else if (info.elementAt(selected[ipic]).equal(NOIMAGE)) {
if (noimg)
noimg = false;
else
selected[ipic]++;
}
}
ImageInfo item = new ImageInfo(addImp);
for (int ipic = 0; ipic < imgCombbxes.length; ipic++) {
imgCombbxes[ipic].setEnabled(false);
imgCombbxes[ipic].insertItemAt(item, imgCombbxes[ipic].getItemCount() - offset[ipic]);
}
// img3dTOS
/*
* if(imgd3TOS!=null){
*
* if(d3TOSselected>=info.size()) d3TOSselected++; else
* if(info.elementAt(d3TOSselected).equal(NOIMAGE)) if(noimg)
* noimg=false; else d3TOSselected++;
*
* imgd3TOS.setEnabled(false); imgd3TOS.insertItemAt(item,
* imgd3TOS.getItemCount()-d3TOSoffset); }
*/
// It is very important that this comes the last
info.insertElementAt(item, info.size() - 1);
break;
}
case DEL_IMG: {
info.remove(idxClose);
for (int ipic = 0; ipic < selected.length; ipic++) {
// Here the offset does apply because we always want to reset to
// done
// not additional elements.
if (selected[ipic] == idxClose)
selected[ipic] = info.size() - 1;
else if (selected[ipic] > idxClose)
selected[ipic]--;
}
for (int ipic = 0; ipic < imgCombbxes.length; ipic++) {
imgCombbxes[ipic].setEnabled(false);
imgCombbxes[ipic].removeItemAt(idxClose);
}
// img3dTOS
/*
* if(imgd3TOS!=null){ if(d3TOSselected==idxClose)
* d3TOSselected=info.size()-1; else if(d3TOSselected>idxClose)
* d3TOSselected--; imgd3TOS.setEnabled(false);
* imgd3TOS.removeItemAt(idxClose); }
*/
break;
}
case REPLACE_IMG: {
// String item=addImp.getTitle();
info.remove(idxClose);
ImageInfo item = new ImageInfo(addImp);
info.add(idxClose, item);
for (int ipic = 0; ipic < imgCombbxes.length; ipic++) {
imgCombbxes[ipic].setEnabled(false);
imgCombbxes[ipic].removeItemAt(idxClose);
imgCombbxes[ipic].insertItemAt(item, idxClose);
}
// img3dTOS
/*
* if(imgd3TOS!=null){ imgd3TOS.removeItemAt(idxClose);
* imgd3TOS.insertItemAt(item, idxClose); }
*/
break;
}
default:
break;
}
for (int ipic = 0; ipic < selected.length; ipic++) {
if (imgCombbxes[ipic] != null) {
if (selected[ipic] < 0)
selected[ipic] = 0;
if (selected[ipic] >= imgCombbxes[ipic].getItemCount())
selected[ipic] = imgCombbxes[ipic].getItemCount() - offset[ipic];
imgCombbxes[ipic].setSelectedIndex(selected[ipic]);
imgCombbxes[ipic].setEnabled(true);
}
}
/*
* //img3dTOS if(d3TOSselected < 0) d3TOSselected = 0; if(d3TOSselected
* >= imgd3TOS.getItemCount()) d3TOSselected = imgd3TOS.getItemCount() -
* d3TOSoffset;
*
*
* if(imgd3TOS.getSelectedIndex() != d3TOSselected)
* imgd3TOS.setSelectedIndex(d3TOSselected); imgd3TOS.setEnabled(true);
*/
}
public void resetInfoArray() {
info.clear();
info.add(NOIMAGE);
}
/**
* This only works for all three images were opened before the plugin is
* opened
*/
private void adaptZoom() {
if (!adaptZoom || imgCombbxes == null || imgCombbxes.length < 3)
return;
Rectangle thisScreen = getGUIScreenBounds();
int screenHeight = thisScreen.height;
int[] strImgs = new int[nChannels];
Window[] iwImgs = new Window[nChannels];
Window iwOpened = null;
for (int i = 0; i < nReporters; i++) {
if (imgCombbxes[i].getSelectedIndex() != -1) {
strImgs[i] = imgCombbxes[i].getItemAt(imgCombbxes[i].getSelectedIndex()).ID;
}
if (strImgs[i] == ImageInfo.NONE_ID)
iwImgs[i] = null;
else if (strImgs[i] == ImageInfo.ROI_MANAGER_ID)
iwImgs[i] = RoiManager.getInstance();
else
iwImgs[i] = WindowManager.getImage(strImgs[i]) == null ? null
: WindowManager.getImage(strImgs[i]).getWindow();
if (iwImgs[i] != null)
iwOpened = iwImgs[i];
}
if (imgCombbxes[imgCombbxes.length - 1].getSelectedIndex() != -1) {
strImgs[nReporters] = imgCombbxes[imgCombbxes.length - 1]
.getItemAt(imgCombbxes[imgCombbxes.length - 1].getSelectedIndex()).ID;
}
if (strImgs[nReporters] == ImageInfo.NONE_ID)
iwImgs[nReporters] = null;
else if (strImgs[nReporters] == ImageInfo.ROI_MANAGER_ID)
iwImgs[nReporters] = RoiManager.getInstance();
else
iwImgs[nReporters] = WindowManager.getImage(strImgs[nReporters]) == null ? null
: WindowManager.getImage(strImgs[nReporters]).getWindow();
if (iwImgs[nReporters] != null)
iwOpened = iwImgs[nReporters];
if (iwOpened == null)
return;
int nRows = nChannels / 2, nColumns = nChannels / nRows;
int height = 0;
int width = (int) (thisScreen.getX() + thisScreen.getWidth() - mainframe.getWidth() - mainframe.getX())
/ nColumns;
int maxHeight = screenHeight / nRows;
for (int i = 0; i < iwImgs.length; i++) {
if (iwImgs[i] == null)
continue;
if (iwImgs[i].getHeight() * width / iwImgs[i].getWidth() > height)
height = iwImgs[i].getHeight() * width / iwImgs[i].getWidth();
if (height > maxHeight) {
height = maxHeight;
width = iwImgs[i].getWidth() * maxHeight / iwImgs[i].getHeight();
}
}
int yOffset = (screenHeight - height * nRows) / 2;
for (int i = 0; i < iwImgs.length; i++) {
if (iwImgs[i] == null)
continue;
if (iwImgs[i] instanceof ImageWindow)
((ImageWindow) iwImgs[i]).setLocationAndSize(
mainframe.getWidth() + mainframe.getX() + width * (i % nColumns),
yOffset + thisScreen.y + height * (i / nColumns), width, height);
else {
iwImgs[i].setBounds(mainframe.getWidth() + mainframe.getX() + width * (i % nColumns),
yOffset + thisScreen.y + height * (i / nColumns), width, height);
iwImgs[i].pack();
}
// iwImgs[i].toFront();
}
// adaptedZoom=true;
}
private void updateTicked(boolean test) {
// handle alignment module
alignedChckbxes[0].setEnabled(true);
alignedChckbxes[1].setEnabled(true);
alignTholdCombbxes[0].setEnabled(true);
alignTholdCombbxes[1].setEnabled(true);
alignTholdCombbxes[2].setEnabled(true);
doAlignmentBtn.setEnabled(true);
resetAlignmentBtn.setEnabled(true);
// handle heatmap module
heatmapRadiobtns[0].setSelected(true);
heatmapRadiobtns[0].setEnabled(true);
heatmapColorCombbxes[0].setEnabled(true);
heatmapColorCombbxes[1].setEnabled(true);
// handle output choices
for (int i = 0; i < metricChckbxes.length; i++)
metricChckbxes[i].setEnabled(true);
for (int i = 0; i < otherChckbxes.length; i++)
otherChckbxes[i].setEnabled(true);
// handle tabs
tabs.setEnabled(true);
tabs.setEnabledAt(INPUTTAB, true);
tabs.setEnabledAt(FILTERTAB, true);
tabs.setEnabledAt(VISUALTAB, true);
tabs.setEnabledAt(ANALYSISTAB, true);
analysisSubTabs.setEnabled(true);
analysisSubTabs.setEnabledAt(METRICSUBTAB, true);
analysisSubTabs.setEnabledAt(CUSTOMSUBTAB, true);
analyzeBtn.setEnabled(true);
}
public void updateTicked() {
if (imgCombbxes == null)
return;
boolean anyReporter = false, allReporters = true;
// Reporter Channels
// Assumption that the first nReporters are enabled
for (int ipic = 0; ipic < nReporters; ipic++) {
boolean isPresent = imgCombbxes[ipic].isVisible() && imgCombbxes[ipic].getSelectedIndex() != -1
&& !imgCombbxes[ipic].getItemAt(imgCombbxes[ipic].getSelectedIndex()).equal(NOIMAGE);
alignedChckbxes[ipic].setEnabled(isPresent);
alignTholdCombbxes[ipic].setEnabled(isPresent);
heatmapColorCombbxes[ipic].setEnabled(isPresent);
heatmapChckbxes[ipic].setEnabled(isPresent);
if (!isPresent) {
alignedChckbxes[ipic].setSelected(false);
align_chckes[ipic] = false;
heatmapChckbxes[ipic].setSelected(false);
heatmap_chckes[ipic] = false;
}
anyReporter |= isPresent;
allReporters &= isPresent || !imgCombbxes[ipic].isVisible();
}
for (JCheckBox chckBx : otherChckbxes)
chckBx.setEnabled(anyReporter);
if (!anyReporter) {
for (int i = 0; i < otherChckbxes.length; i++) {
otherChckbxes[i].setSelected(false);
other_chckes[i] = false;
}
}
scatterplotChckbx.setEnabled(allReporters);
matrixChckbx.setEnabled(allReporters);
matrixMetricCombbx.setEnabled(allReporters);
matrixStatsCombbx.setEnabled(allReporters);
for (JSpinner jsp : matrixFTSpinners)
jsp.setEnabled(allReporters);
for (JCheckBox chckBx : metricChckbxes)
chckBx.setEnabled(allReporters);
for (JCheckBox chckBx : outputMetricChckbxes)
chckBx.setEnabled(allReporters);
if (!allReporters) {
scatterplotChckbx.setSelected(false);
matrixChckbx.setSelected(false);
for (int i = 0; i < metricChckbxes.length; i++) {
metricChckbxes[i].setSelected(false);
metric_chckes[i] = false;
}
for (int i = 0; i < outputMetricChckbxes.length; i++) {
outputMetricChckbxes[i].setSelected(false);
outputMetric_chckes[i] = false;
}
}
tabs.setEnabledAt(VISUALTAB, anyReporter);
analysisSubTabs.setEnabledAt(CUSTOMSUBTAB, anyReporter);
// Cell ID Channel although there is only one
for (int ipic = MAX_NCHANNELS - 1; ipic >= MAX_NREPORTERS; ipic--) {
boolean isPresent = imgCombbxes[ipic].isVisible() && imgCombbxes[ipic].getSelectedIndex() != -1
&& !imgCombbxes[ipic].getItemAt(imgCombbxes[ipic].getSelectedIndex()).equal(NOIMAGE);
if (!isPresent) {
for (int i = 0; i < nReporters; i++) {
alignedChckbxes[i].setEnabled(false);
align_chckes[i] = false;
}
}
alignTholdCombbxes[ipic].setEnabled(isPresent);
if (heatmapRadiobtns[0].isSelected() && !isPresent) {
heatmapRadiobtns[0].setSelected(false);
heatmapRadiobtns[1].setSelected(true);
}else if (!heatmapRadiobtns[0].isEnabled() && isPresent){
heatmapRadiobtns[0].setSelected(true);
}
heatmapRadiobtns[0].setEnabled(isPresent);
for (JCheckBox chckBx : outputOptChckbxes)
chckBx.setEnabled(isPresent);
if (!isPresent) {
for (int iAlign = 0; iAlign < nReporters; iAlign++) {
alignedChckbxes[iAlign].setSelected(false);
align_chckes[iAlign] = false;
}
for (int iOutput = 0; iOutput < outputOptChckbxes.length; iOutput++) {
outputOptChckbxes[iOutput].setSelected(false);
outputOpt_chckes[iOutput] = false;
}
}
tabs.setEnabledAt(FILTERTAB, isPresent);
previewTholdBtn.setEnabled(anyReporter || isPresent);
doAlignmentBtn.setEnabled(anyReporter && isPresent);
resetAlignmentBtn.setEnabled(anyReporter && isPresent);
tabs.setEnabledAt(ANALYSISTAB, anyReporter || isPresent);
analysisSubTabs.setEnabledAt(METRICSUBTAB, anyReporter || isPresent);
analyzeBtn.setEnabled(anyReporter || isPresent);
}
if (!tabs.isEnabledAt(tabs.getSelectedIndex()))
tabs.setSelectedIndex(INPUTTAB);
if (!analysisSubTabs.isEnabledAt(analysisSubTabs.getSelectedIndex()))
analysisSubTabs.setSelectedIndex(METRICSUBTAB);
}
private void loadPreference() {
// nChannel
nChannels = (int) Prefs.get(pluginName + "nChannels", nChannels);
// input tab
for (int iAlign = 0; iAlign < align_chckes.length; iAlign++)
align_chckes[iAlign] = Prefs.get(pluginName + "whichAlign" + iAlign, align_chckes[iAlign]);
for (int iThold = 0; iThold < alignThold_combs.length; iThold++)
alignThold_combs[iThold] = (int) Prefs.get(pluginName + "whichThold" + iThold, alignThold_combs[iThold]);
// cell filter tab
waterShed_chck = Prefs.get(pluginName + "doWaterShed", waterShed_chck);
for (int iSize = 0; iSize < filterMinSize_texts.length; iSize++) {
filterMinSize_texts[iSize] = Prefs.get(pluginName + "minSize" + iSize, filterMinSize_texts[iSize]);
filterMaxSize_texts[iSize] = Prefs.get(pluginName + "maxSize" + iSize, filterMaxSize_texts[iSize]);
}
for (int iFilter = 0; iFilter < filter_combs.length; iFilter++) {
filter_combs[iFilter] = (int) Prefs.get(pluginName + "filterChoice" + iFilter, filter_combs[iFilter]);
filterBackRatio_texts[iFilter] = Prefs.get(pluginName + "backRatio" + iFilter,
filterBackRatio_texts[iFilter]);
filterMinRange_texts[iFilter] = Prefs.get(pluginName + "minRange" + iFilter, filterMinRange_texts[iFilter]);
filterMinRange_texts[iFilter] = Prefs.get(pluginName + "minRange" + iFilter, filterMinRange_texts[iFilter]);
}
int adFilterNum = (int) Prefs.get(pluginName + "adFilterNum", adFilterChoices.size());
for (int iFilter = 0; iFilter < adFilterNum; iFilter++) {
adFilterChoices.add((int) Prefs.get(pluginName + "adFilterChoice" + iFilter, 0));
adBackRatios.add(Prefs.get(pluginName + "adBackRatio" + iFilter, false));
adMinRanges.add(Prefs.get(pluginName + "adMinRange" + iFilter, DEFAULT_MIN));
adMaxRanges.add(Prefs.get(pluginName + "adMaxRange" + iFilter, DEFAULT_MAX));
}
// visual tab
matrix_chck = Prefs.get(pluginName + "doMatrix", matrix_chck);
matrixMetric_comb = (int) Prefs.get(pluginName + "metricChoice", matrixMetric_comb);
matrixStats_comb = (int) Prefs.get(pluginName + "statsChoice", matrixStats_comb);
for (int iTOS = 0; iTOS < matrixFT_spin.length; iTOS++)
matrixFT_spin[iTOS] = (int) Prefs.get(pluginName + "numOfFT" + iTOS, matrixFT_spin[iTOS]);
scatter_chck = Prefs.get(pluginName + "doScatter", scatter_chck);
for (int iHeat = 0; iHeat < heatmap_chckes.length; iHeat++)
heatmap_chckes[iHeat] = Prefs.get(pluginName + "whichHeatmap" + iHeat, heatmap_chckes[iHeat]);
heatmap_radio = (int) Prefs.get(pluginName + "whichHeatmapOpt", heatmap_radio);
for (int iHeat = 0; iHeat < heatmapColor_combs.length; iHeat++)
heatmapColor_combs[iHeat] = (int) Prefs.get(pluginName + "heatmapChoice" + iHeat,
heatmapColor_combs[iHeat]);
// analysis tab
for (int iMetric = 0; iMetric < metric_chckes.length; iMetric++)
metric_chckes[iMetric] = Prefs.get(pluginName + "metricOpts" + iMetric, metric_chckes[iMetric]);
for (int iOpt = 0; iOpt < other_chckes.length; iOpt++)
other_chckes[iOpt] = Prefs.get(pluginName + "otherOpts" + iOpt, other_chckes[iOpt]);
custom_chck = Prefs.get(pluginName + "doCustom", custom_chck);
for (int iThold = 0; iThold < metricThold_radios.length; iThold++)
metricThold_radios[iThold] = (int) Prefs.get(pluginName + "metricThold" + iThold,
metricThold_radios[iThold]);
for (int iChannel = 0; iChannel < allFT_spins.length; iChannel++)
for (int iMetric = 0; iMetric < allFT_spins[iChannel].length; iMetric++)
allFT_spins[iChannel][iMetric] = (int) Prefs.get(pluginName + "allFT-c" + iChannel + "-" + iMetric,
allFT_spins[iChannel][iMetric]);
// output tab
for (int iMetric = 0; iMetric < outputMetric_chckes.length; iMetric++)
outputMetric_chckes[iMetric] = Prefs.get(pluginName + "outputMetric" + iMetric,
outputMetric_chckes[iMetric]);
for (int iOpt = 0; iOpt < outputOpt_chckes.length; iOpt++)
outputOpt_chckes[iOpt] = Prefs.get(pluginName + "outputOther" + iOpt, outputOpt_chckes[iOpt]);
}
private Overlay newOverlay() {
Overlay overlay = OverlayLabels.createOverlay();
overlay.drawLabels(false);
if (overlay.getLabelFont() == null && overlay.getLabelColor() == null) {
overlay.setLabelColor(Color.white);
overlay.drawBackgrounds(true);
}
overlay.drawNames(Prefs.useNamesAsLabels);
return overlay;
}
/*
* private void setOverlay(ImagePlus imp, Overlay overlay) { if (imp ==
* null) return; ImageCanvas ic = imp.getCanvas(); if (ic == null) {
* imp.setOverlay(overlay); return; } ic.setShowAllList(overlay);
* imp.setOverlay(overlay); imp.draw(); }
*/
private void resetRoi() {
for (int ipic = 0; ipic < imgCombbxes.length; ipic++) {
if (imgCombbxes[ipic] == null)
continue;
imps[ipic] = WindowManager.getImage(imgCombbxes[ipic].getItemAt(imgCombbxes[ipic].getSelectedIndex()).ID);
if (imps[ipic] == null)
continue;
imps[ipic].setOverlay(null);
imps[ipic].draw();
}
}
private void redoAlignment() {
if (imps == null)
return;
for (int ipic = 0; ipic < imgCombbxes.length; ipic++) {
if (imps[ipic] != null && oldImps[ipic] != null) {
ImagePlus tempImg = (ImagePlus) imps[ipic].clone();
imps[ipic].setImage(oldImps[ipic]);
imps[ipic].setTitle(oldImps[ipic].getTitle());
updateImgList(imps[ipic], tempImg);
}
}
}
private void previewIDCells() {
Roi[] rois = null;
if (roiCells != null)
rois = roiCells.getRoisAsArray();
Overlay overlay = null;
if (rois != null) {
overlay = newOverlay();
for (int i = 0; i < rois.length; i++)
overlay.add(rois[i]);
}
for (int ipic = 0; ipic < imps.length; ipic++) {
if (imps[ipic] != null) {
imps[ipic].setOverlay(overlay);
imps[ipic].draw();
}
}
}
public void retrieveParams() {
ImagePlus temp = null;
for (int ipic = 0; ipic < imgCombbxes.length; ipic++) {
if (!imgCombbxes[ipic].isEnabled())
imps[ipic] = null;
else if (imgCombbxes[ipic].getItemAt(imgCombbxes[ipic].getSelectedIndex()).equal(ROIMANAGER_IMAGE)){
imps[ipic] = roiManager2Mask(temp);
// introduced in 1.1.3 force black background when ROI manager is used.
lightBacks[ipic] = false;
}
else if (imgCombbxes[ipic].getItemAt(imgCombbxes[ipic].getSelectedIndex()).equal(NOIMAGE))
imps[ipic] = null;
else {
imps[ipic] = WindowManager
.getImage(imgCombbxes[ipic].getItemAt(imgCombbxes[ipic].getSelectedIndex()).ID);
temp = imps[ipic];
}
}
for (int iAlign = 0; iAlign < align_chckes.length; iAlign++) {
align_chckes[iAlign] = alignedChckbxes[iAlign].isSelected();
Prefs.set(pluginName + "whichAlign" + iAlign + "." + getVarName(align_chckes[iAlign]),
align_chckes[iAlign]);
align_chckes[iAlign] &= alignedChckbxes[iAlign].isEnabled();
}
for (int iThold = 0; iThold < alignTholdCombbxes.length; iThold++) {
alignThold_combs[iThold] = alignTholdCombbxes[iThold].getSelectedIndex();
Prefs.set(pluginName + "whichThold" + iThold + "." + getVarName(alignThold_combs[iThold]),
alignThold_combs[iThold]);
// Add in 1.1.0 save current thresholds by imageprocessor
// Do NOT save preference!
if (ALLTHOLDS[alignThold_combs[iThold]].equals(MANUAL_THOLD) && imps[iThold] != null) {
manualTholds[iThold][0] = imps[iThold].getProcessor().getMinThreshold();
manualTholds[iThold][1] = imps[iThold].getProcessor().getMaxThreshold();
}
}
waterShed_chck = waterShedChckbx.isSelected();
Prefs.set(pluginName + "doWaterShed" + "." + getVarName(waterShed_chck), waterShed_chck);
waterShed_chck &= waterShedChckbx.isEnabled();
for (int iSize = 0; iSize < filterMinSize_texts.length; iSize++) {
double[] range = str2doubles(filterSizeTexts[iSize].getText());
filterMinSize_texts[iSize] = range[0];
filterMaxSize_texts[iSize] = range[1];
Prefs.set(pluginName + "minSize" + iSize + "." + getVarName(filterMinSize_texts[iSize]),
filterMinSize_texts[iSize]);
Prefs.set(pluginName + "maxSize" + iSize + "." + getVarName(filterMaxSize_texts[iSize]),
filterMaxSize_texts[iSize]);
}
for (int iFilter = 0; iFilter < filter_combs.length; iFilter++) {
filter_combs[iFilter] = filterCombbxes[iFilter].getSelectedIndex();
double[] range = str2doubles(filterRangeTexts[iFilter].getText());
// This need to be changed
// if(filterRange.contains("X")||filterRange.contains("x"))
// backRatios[iFilter]=true;
filterMinRange_texts[iFilter] = range[0];
filterMaxRange_texts[iFilter] = range[1];
Prefs.set(pluginName + "filterChoice" + iFilter + "." + getVarName(filter_combs[iFilter]),
filter_combs[iFilter]);
Prefs.set(pluginName + "backRatio" + iFilter + "." + getVarName(filterBackRatio_texts[iFilter]),
filterBackRatio_texts[iFilter]);
Prefs.set(pluginName + "minRange" + iFilter + "." + getVarName(filterMinRange_texts[iFilter]),
filterMinRange_texts[iFilter]);
Prefs.set(pluginName + "maxRange" + iFilter + "." + getVarName(filterMaxRange_texts[iFilter]),
filterMaxRange_texts[iFilter]);
}
for (int iFilter = 0; iFilter < adFilterChoices.size(); iFilter++) {
Prefs.set(pluginName + "adFilterNum" + "." + getVarName(adFilterChoices.size()), adFilterChoices.size());
Prefs.set(pluginName + "adFilterChoice" + iFilter + "." + getVarName(adFilterChoices.get(iFilter)),
adFilterChoices.get(iFilter));
Prefs.set(pluginName + "adBackRatio" + iFilter + "." + getVarName(adBackRatios.get(iFilter)),
adBackRatios.get(iFilter));
Prefs.set(pluginName + "adMinRange" + iFilter + "." + getVarName(adMinRanges.get(iFilter)),
adMinRanges.get(iFilter));
Prefs.set(pluginName + "adMaxRange" + iFilter + "." + getVarName(adMaxRanges.get(iFilter)),
adMaxRanges.get(iFilter));
}
{// visualTab options
scatter_chck = scatterplotChckbx.isSelected();
Prefs.set(pluginName + "doScatter" + "." + getVarName(scatter_chck), scatter_chck);
scatter_chck &= scatterplotChckbx.isEnabled();
// heat map options
for (int iHeat = 0; iHeat < heatmapChckbxes.length; iHeat++) {
heatmap_chckes[iHeat] = heatmapChckbxes[iHeat].isSelected();
Prefs.set(pluginName + "whichHeatmap" + iHeat + "." + getVarName(heatmap_chckes[iHeat]), heatmap_radio);
heatmap_chckes[iHeat] &= heatmapChckbxes[iHeat].isEnabled();
}
for (int iHeat = 0; iHeat < heatmapRadiobtns.length; iHeat++) {
if (heatmapRadiobtns[iHeat].isSelected()) {
heatmap_radio = iHeat;
break;
}
}
Prefs.set(pluginName + "whichHeatmapOpt" + "." + getVarName(heatmap_radio), heatmap_radio);
for (int iHeat = 0; iHeat < heatmapColor_combs.length; iHeat++) {
heatmapColor_combs[iHeat] = heatmapColorCombbxes[iHeat].getSelectedIndex();
Prefs.set(pluginName + "heatmapChoice" + iHeat + "." + getVarName(heatmapColor_combs[iHeat]),
heatmapColor_combs[iHeat]);
}
// metric matrices
matrix_chck = matrixChckbx.isSelected();
Prefs.set(pluginName + "doMatrix" + "." + getVarName(matrix_chck), matrix_chck);
matrix_chck &= matrixChckbx.isEnabled();
matrixMetric_comb = matrixMetricCombbx.getSelectedIndex();
Prefs.set(pluginName + "metricChoice" + "." + getVarName(matrixMetric_comb), matrixMetric_comb);
matrixStats_comb = matrixStatsCombbx.getSelectedIndex();
Prefs.set(pluginName + "statsChoice" + "." + getVarName(matrixStats_comb), matrixStats_comb);
for (int iTOS = 0; iTOS < matrixFTSpinners.length; iTOS++) {
matrixFT_spin[iTOS] = (Integer) matrixFTSpinners[iTOS].getValue();
Prefs.set(pluginName + "numOfFT" + iTOS + "." + getVarName(matrixFT_spin[iTOS]), matrixFT_spin[iTOS]);
}
}
for (int iColumn = 0; iColumn < metric_chckes.length; iColumn++) {
metric_chckes[iColumn] = metricChckbxes[iColumn].isSelected();
Prefs.set(pluginName + "metricOpts" + iColumn + "." + getVarName(metric_chckes[iColumn]),
metric_chckes[iColumn]);
metric_chckes[iColumn] &= metricChckbxes[iColumn].isEnabled();
}
for (int iMetric = 0; iMetric < metricThold_radios.length; iMetric++) {
for (int iThold = 0; iThold < metricTholdRadiobtns[iMetric].length; iThold++) {
if (metricTholdRadiobtns[iMetric][iThold] != null && metricTholdRadiobtns[iMetric][iThold].isSelected())
metricThold_radios[iMetric] = iThold;
}
Prefs.set(pluginName + "metricThold" + iMetric + "." + getVarName(metricThold_radios[iMetric]),
metricThold_radios[iMetric]);
}
int iFTs = metricThold_radios.length;
for (int iMetric = 0; iMetric < metricThold_radios.length; iMetric++) {
for (int iThold = 0; iThold < metricTholdRadiobtns[iMetric].length; iThold++) {
if (metricTholdRadiobtns[iMetric][iThold] != null && metricTholdRadiobtns[iMetric][iThold].isSelected())
metricThold_radios[iMetric] = iThold;
if (metricThold_radios[iMetric] == IDX_THOLD_FT)
iFTs += allFT_spins.length;
}
Prefs.set(pluginName + "metricThold" + iMetric + "." + getVarName(metricThold_radios[iMetric]),
metricThold_radios[iMetric]);
}
for (int iChannel = 0; iChannel < allFT_spins.length; iChannel++)
for (int iMetric = 0; iMetric < allFT_spins[iChannel].length; iMetric++) {
try {
allFTSpinners[iChannel][iMetric].commitEdit();
} catch (ParseException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
}
allFT_spins[iChannel][iMetric] = (Integer) allFTSpinners[iChannel][iMetric].getValue();
Prefs.set(pluginName + "allFT-c" + iChannel + "-" + iMetric + "."
+ getVarName(allFT_spins[iChannel][iMetric]), allFT_spins[iChannel][iMetric]);
}
boolean anyOtherMetric = false;
for (int iColumn = 0; iColumn < other_chckes.length; iColumn++) {
other_chckes[iColumn] = otherChckbxes[iColumn].isSelected();
Prefs.set(pluginName + "otherOpts" + iColumn + "." + getVarName(other_chckes[iColumn]),
other_chckes[iColumn]);
other_chckes[iColumn] &= otherChckbxes[iColumn].isEnabled();
anyOtherMetric |= other_chckes[iColumn];
}
// DIYcode will be not recored because of it's complication
customCode_text = customCodeTextbx.getText();
// doCustom, however, is recored
custom_chck = customMetricChckbxes.isSelected();
Prefs.set(pluginName + "doCustom" + "." + getVarName(custom_chck), custom_chck);
custom_chck &= customMetricChckbxes.isEnabled();
for (int iColumn = 0; iColumn < outputMetric_chckes.length; iColumn++) {
outputMetric_chckes[iColumn] = outputMetricChckbxes[iColumn].isSelected();
Prefs.set(pluginName + "outputMetric" + iColumn + "." + getVarName(outputMetric_chckes[iColumn]),
outputMetric_chckes[iColumn]);
outputMetric_chckes[iColumn] &= outputMetricChckbxes[iColumn].isEnabled();
}
/**
* retrieve metricTholds and allFTs to allTholds but not record it Add
* one more term for average intensity and custom metric
*/
allTholds = new int[iFTs + 1];
iFTs = 0;
for (int iMetric = 0; iMetric < metricThold_radios.length; iMetric++) {
if (metric_chckes[iMetric]) {
allTholds[iFTs++] = BasicCalculator.getThold(metricThold_radios[iMetric]);
if (metricThold_radios[iMetric] == IDX_THOLD_FT) {
for (int iChannel = 0; iChannel < allFT_spins.length; iChannel++)
allTholds[iFTs++] = allFT_spins[iChannel][iMetric];
}
} else {
allTholds[iFTs++] = BasicCalculator.THOLD_NONE;
}
}
if (anyOtherMetric)
allTholds[allTholds.length - 1] = BasicCalculator.THOLD_ALL;
else
allTholds[allTholds.length - 1] = BasicCalculator.THOLD_NONE;
for (int iColumn = 0; iColumn < outputOpt_chckes.length; iColumn++) {
outputOpt_chckes[iColumn] = outputOptChckbxes[iColumn].isSelected();
Prefs.set(pluginName + "outputOther" + iColumn + "." + getVarName(outputOpt_chckes[iColumn]),
outputOpt_chckes[iColumn]);
outputOpt_chckes[iColumn] &= outputOptChckbxes[iColumn].isEnabled();
}
if (recorderRecord) {
MacroHandler.macroRecorder(true);
// Recorder.record("//The action can only be recorded with Macro
// language");
}
retrieveOptions();
}
private void handleBackSubThreshold(ImagePlus imp, int ipic) {
// Add in 1.1.0
// Do NOT subtract background is threshold is manually selected
// Use overlay to display thresholds instead of ColorModel
// This is because images are processed in the background
// The integrity of the original ImageProcessor must be maintained
ImageProcessor ip = imp.getProcessor().duplicate();
if(ip.isInvertedLut())
ip.invertLut();
// BackgroundProcessor impBackground = new BackgroundProcessor(ip,
// ALLTHOLDS[alignThold_combs[ipic]]);
// impBackground.setManualThresholds(manualTholds[alignThold_combs.length
// - 1]);
if (!ip.isBinary() && !ALLTHOLDS[alignThold_combs[ipic]].equals(PluginStatic.MANUAL_THOLD))
BackgroundProcessor.rollSubBackground(ip, rollingBallSizes[ipic], lightBacks[ipic]);
boolean lightBackground = lightBacks[ipic] != null ? lightBacks[ipic] : BackgroundProcessor.isLightBackground(imp);
ip.setAutoThreshold(Method.valueOf(ALLTHOLDS[alignThold_combs[ipic]]), !lightBackground,
ImageProcessor.NO_LUT_UPDATE);
if (lightBackground)
ip.threshold((int) ip.getMaxThreshold());
else
ip.threshold((int) ip.getMinThreshold());
ip = ip.convertToByteProcessor(false);
ip.invertLut();
if (lightBackground ^ Prefs.blackBackground)
ip.invert();
currentOverlays[ipic] = imp.getOverlay();
RoiManager roiParticles = new RoiManager(false);
if (!ParticleAnalyzerMT.analyzeWithHole(ip, roiParticles))
return;
Overlay thresholdOverlay = new Overlay();
for (int iRoi = 0; iRoi < roiParticles.getCount(); iRoi++) {
thresholdOverlay.add(roiParticles.getRoi(iRoi));
}
thresholdOverlay.setFillColor(Color.RED);
thresholdOverlay.setStrokeColor(null);
thresholdOverlay.setLabelColor(null);
imp.setOverlay(thresholdOverlay);
}
public void updateThr() {
for (int ipic = 0; ipic < imgCombbxes.length; ipic++) {
updateThr(ipic);
}
}
private void updateThr(int ipic) {
if (ipic < 0 || ipic >= imgCombbxes.length || imgCombbxes[ipic] == null
|| imgCombbxes[ipic].getSelectedIndex() == -1)
return;
updateThr(ipic, imgCombbxes[ipic].getItemAt(imgCombbxes[ipic].getSelectedIndex()));
}
private void updateThr(int ipic, ImageInfo info) {
if (ipic < 0 || ipic >= imgCombbxes.length || imgCombbxes[ipic] == null
|| imgCombbxes[ipic].getSelectedIndex() == -1)
return;
imgUpdate = false;
ImagePlus imp = WindowManager.getImage(info.ID);
if (imp != null) {
if (getMethod(ALLTHOLDS[alignThold_combs[ipic]]) == null) {
// ThresholdAdjuster tholdAd = new ThresholdAdjuster();
imp.getWindow().toFront();
ImageProcessor ip = imp.getProcessor();
// Add in 1.1.0 to ignore current Roi on the image
// Set the threshold ahead of ThresholdAdjuster so it will use
// it
if (ip.getMinThreshold() != ImageProcessor.NO_THRESHOLD)
ip.setThreshold(ip.getMinThreshold(), ip.getMaxThreshold(), ImageProcessor.RED_LUT);
// This has to be done to avoid automatically erase of the thresholds
IJ.run(imp, "Threshold...", null);
} else {
// Add in 1.1.0 to ignore current Roi on the image
// Do NOT use restoreRoi option since it will restore Roi on all
// images
Roi roi = imp.getRoi();
imp.deleteRoi();
if (preBackSub) {
handleBackSubThreshold(imp, ipic);
} else {
boolean lightback = lightBacks[ipic] != null ? lightBacks[ipic] : BackgroundProcessor.looksLightBackground(imp);
imp.getProcessor().setAutoThreshold(Method.valueOf(ALLTHOLDS[alignThold_combs[ipic]]),
!lightback, ImageProcessor.RED_LUT);
}
imp.setRoi(roi);
}
// We do not call updateAndDraw since it will notify ImageUpdated listener
// Instead, we update the canvas manually
// imp.updateAndDraw();
ImageWindow impWin = imp.getWindow();
if (impWin != null){
impWin.getCanvas().setImageUpdated();
}
imp.draw();
}
imgUpdate = true;
}
public void resetThr() {
for (int ipic = 0; ipic < imgCombbxes.length; ipic++) {
resetThr(ipic, imgCombbxes[ipic].getItemAt(imgCombbxes[ipic].getSelectedIndex()));
}
}
private void resetThr(int ipic, ImageInfo info) {
if (ipic < 0 || ipic >= imgCombbxes.length || imgCombbxes[ipic] == null
|| imgCombbxes[ipic].getSelectedIndex() == -1)
return;
imgUpdate = false;
ImagePlus imp = WindowManager.getImage(info.ID);
if (imp != null) {
if (getMethod(ALLTHOLDS[alignThold_combs[ipic]]) == null) {
// ThresholdAdjuster tholdAd = new ThresholdAdjuster();
ImageProcessor ip = imp.getProcessor();
double[] thresholds = new double[] { ip.getMinThreshold(), ip.getMaxThreshold() };
// Close the Threshold window so it loses focus
Window thesholdWindow = WindowManager.getWindow("Threshold");
if (thesholdWindow != null && (thesholdWindow instanceof ThresholdAdjuster))
((ThresholdAdjuster) thesholdWindow).close();
ip.resetThreshold();
ip.setThreshold(thresholds[0], thresholds[1], ImageProcessor.NO_LUT_UPDATE);
} else {
if (preBackSub)
imp.setOverlay(currentOverlays[ipic]);
imp.getProcessor().resetThreshold();
}
imp.updateAndDraw();
}
imgUpdate = true;
}
public void actionPerformed(ActionEvent e) {
recorderRecord = Recorder.record;
Recorder.record = false;
boolean doStack = (e.getModifiers() & ActionEvent.SHIFT_MASK) == 0;
Object origin = e.getSource();
imgUpdate = false;
for (int i = 0; i < imgCombbxes.length; i++) {
if (origin == imgCombbxes[i] && imgCombbxes[i].isEnabled()) {
adaptZoom();
updateTicked();
ImagePlus imp = WindowManager.getImage(imgCombbxes[i].getItemAt(imgCombbxes[i].getSelectedIndex()).ID);
if (imp != null)
imp.getWindow().toFront();
imgUpdate = true;
Recorder.record = recorderRecord;
return;
}
}
// Modifiers: none=16, shift=17, ctrl=18, alt=24
for (int iThold = 0; iThold < alignTholdCombbxes.length; iThold++) {
if (origin == alignTholdCombbxes[iThold]) {
alignThold_combs[iThold] = alignTholdCombbxes[iThold].getSelectedIndex();
if (showThold)
updateThr(iThold);
imgUpdate = true;
Recorder.record = recorderRecord;
return;
}
}
// prepare an email instead of opening the website
if (origin == email) {
Desktop desktop;
if (Desktop.isDesktopSupported() && (desktop = Desktop.getDesktop()).isSupported(Desktop.Action.MAIL)) {
try {
desktop.mail(new URI(URIEmail));
} catch (IOException | URISyntaxException e1) {
// TODO Auto-generated catch block
throw new RuntimeException("Desktop doesn't support mailto; mail is dead anyway ;)");
}
} else {
// TODO fallback to some Runtime.exec(..) voodoo?
throw new RuntimeException("Desktop doesn't support mailto; mail is dead anyway ;)");
}
} else if (origin == analyzeBtn) {
retrieveParams();
analysis = new AnalysisOperator(this);
analysis.prepAll();
analysis.execute(doStack);
} else if (origin == previewVisual) {
retrieveParams();
options &= MASK_VISUAL;
analysis = new AnalysisOperator(this);
analysis.prepVisual();
analysis.execute(doStack);
} else if (origin == previewTholdBtn) {
showThold = !showThold;
previewTholdBtn.setText(PREVIEW_THOLD[showThold ? 1 : 0]);
if (showThold)
updateThr();
else
resetThr();
} else if (origin == doAlignmentBtn) {
retrieveParams();
options &= MASK_ALIGNMENT;
analysis = new AnalysisOperator(this);
analysis.prepAlignment();
analysis.execute(doStack);
} else if (origin == resetAlignmentBtn) {
redoAlignment();
} else if (origin == tryIDCells) {
retrieveParams();
if (imps[imps.length - 1] != null) {
options = DO_ROIS;
analysis = new AnalysisOperator(this);
analysis.prepIDCells();
analysis.execute(false);
previewIDCells();
} else {
IJ.error(pluginName + " error",
"Missing Input in " + imgLabels[imgLabels.length - 1] + " for selected operation");
}
} else if (origin == btnMoreFilters) {
CellFilterDialog gdCellFilters = CellFilterDialog.getCellFilterDialog("More filters", mainframe);
gdCellFilters.showDialog();
if (gdCellFilters.wasOKed()) {
gdCellFilters.retrieveFilters(adFilterChoices, adBackRatios);
gdCellFilters.retrieveRanges(adMinRanges, adMaxRanges);
}
} else if (origin == runCustomBtn) {
// retrieveParams();
// doCustom=checkCustom.isSelected();
if (customMetricChckbxes.isSelected()) {
customCode_text = customCodeTextbx.getText();
StringCompiler testCode = new StringCompiler();
try {
if (testCode.compileCustom(customCode_text))
setCustomStatus(SUCCESS);
else {
setCustomStatus(FAILURE);
ExceptionHandler.print2log(true);
}
} catch (Exception e1) {
// TODO Auto-generated catch block
setCustomStatus(FAILURE);
e1.printStackTrace();
ExceptionHandler.handleException(e1);
}
}
} else if (origin == resetCustomBtn) {
customCodeTextbx.setText(StringCompiler.getDefaultCode());
setCustomStatus(SKIP);
customMetricChckbxes.setSelected(false);
otherChckbxes[otherChckbxes.length - 1].setSelected(false);
// need to queue the setValue function otherwise not working
SwingUtilities.invokeLater(new Runnable() {
public void run() {
customCodeScrollpn.getVerticalScrollBar().setValue(0);
}
});
} else if (origin == helpCustomBtn) {
try {
BrowserLauncher.openURL(CUSTOM_URL);
} catch (IOException ie) {
IJ.error(CUSTOM_URL + " cannot be opened");
}
} else if (origin == customMetricChckbxes) {
if (customMetricChckbxes.isSelected())
setCustomStatus(RUN);
else
setCustomStatus(SKIP);
otherChckbxes[otherChckbxes.length - 1].setSelected(customMetricChckbxes.isSelected());
} else if (origin == otherChckbxes[otherChckbxes.length - 1]) {
if (otherChckbxes[otherChckbxes.length - 1].isSelected())
setCustomStatus(RUN);
else
setCustomStatus(SKIP);
customMetricChckbxes.setSelected(otherChckbxes[otherChckbxes.length - 1].isSelected());
}
imgUpdate = true;
Recorder.record = recorderRecord;
return;
}
public void setImageListener(Boolean imgIO, Boolean imgUpdate) {
if (imgIO != null)
this.imgIO = imgIO;
if (imgUpdate != null)
this.imgUpdate = imgUpdate;
}
public void imageOpened(ImagePlus imp) {
if (imgIO) {
updateImgList(imp, null);
adaptZoom();
updateTicked();
}
}
public void imageClosed(ImagePlus imp) {
if (imgIO) {
updateImgList(null, imp);
adaptZoom();
updateTicked();
}
}
public void imageUpdated(ImagePlus imp) {
if (imgUpdate && imp.getID() != 0) {
// InvokeLater after the update of the current image
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// imgIO = false;
updateImgList(imp, imp);
// imgIO = true;
}
});
}
}
public void stateChanged(ChangeEvent e) {
Object origin = e.getSource();
if (origin == tabs && tabs.getSelectedIndex() != FILTERTAB)
resetRoi();
if (origin == tabs) {
switch (tabs.getSelectedIndex()) {
case FILTERTAB:
resetThr();
updateThr(imgCombbxes.length - 1);
break;
case INPUTTAB:
if (showThold)
updateThr();
else
resetThr();
break;
default:
resetThr();
}
}
}
/*
* public void propertyChange(PropertyChangeEvent e) { Object origin =
* e.getSource(); // if (origin==xyCalibTxt || origin==zCalibTxt)
* updateCostesRandParam();
*
* for (int iFT = 0; iFT < distFTLabels.length; iFT++) { if (origin ==
* distFTLabels[iFT]) { distFTs[iFT].setValue((int)
* parseDouble(distFTLabels[iFT].getText())); updateFT(iFT); } }
*
* }
*/
public void windowActivated(WindowEvent e) {
}
public void windowClosed(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
if (analysis != null)
analysis.cancel();
ImagePlus.removeImageListener(this);
resetThr();
mainframe.dispose();
WindowManager.removeWindow(mainframe);
staticGUI = null;
}
public void windowDeactivated(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowOpened(WindowEvent e) {
WindowManager.addWindow(mainframe);
}
@Deprecated
public void updateFT(int i) {
}
@Deprecated
public void updateSlice() {
}
static void retrieveOptions() {
PluginStatic.retrieveOptions();
// store the old images for reset alignment
for (int ipic = 0; ipic < imps.length; ipic++) {
if (imps[ipic] != null) {
// Add in 1.1.0 to ignore current Roi on the image
// Do NOT use restoreRoi because it might restore the previous
// Roi from a different run
Roi roi = imps[ipic].getRoi();
imps[ipic].deleteRoi();
oldImps[ipic] = imps[ipic].duplicate();
imps[ipic].setRoi(roi);
oldImps[ipic].setTitle(imps[ipic].getTitle());
} else
oldImps[ipic] = null;
}
}
void setCustomStatus(int status) {
if (customMetricChckbxes == null)
return;
switch (status) {
case SUCCESS:
customMetricChckbxes.setText(CUSTOM_STATUS[SUCCESS]);
customMetricChckbxes.setForeground(CUSTOM_COLORS[SUCCESS]);
break;
case FAILURE:
customMetricChckbxes.setText(CUSTOM_STATUS[FAILURE]);
customMetricChckbxes.setForeground(CUSTOM_COLORS[FAILURE]);
break;
case RUN:
customMetricChckbxes.setText(CUSTOM_STATUS[RUN]);
customMetricChckbxes.setForeground(CUSTOM_COLORS[RUN]);
break;
case SKIP:
customMetricChckbxes.setText(CUSTOM_STATUS[SKIP]);
customMetricChckbxes.setForeground(CUSTOM_COLORS[SKIP]);
break;
default:
break;
}
}
ProgressGlassPane getProgressGlassPane() {
return progressGlassPane;
}
public static String getVarName(float a) {
return "float";
}
public static String getVarName(int a) {
return "int";
}
public static String getVarName(boolean a) {
return "boolean";
}
public static String getVarName(byte a) {
return "byte";
}
public static String getVarName(char a) {
return "char";
}
public static String getVarName(long a) {
return "long";
}
public static String getVarName(short a) {
return "short";
}
public static String getVarName(double a) {
return "double";
}
/**
* This method make sure <code>ref</code> and <code>target</code> have the
* same length if <code>ref</code> is longer than <code>target</code>,
* <code>target</code> will be extended and the extra elements will be
* filled as in <code>ref</code>; if <code>target</code> is longer than
* <code>ref</code>, <code>target</code> will be truncated to the length of
* <code>ref</code>.
*
* @param ref
* reference array
* @param target
* desired array
* @return an array which is the same length as <code>ref</code> with the
* elements in <code>target</code>
*/
public static String[] convertNames(String[] ref, String[] target) {
String[] temp = target;
if (target.length > ref.length) {
target = new String[ref.length];
System.arraycopy(temp, 0, target, 0, ref.length);
} else if (target.length < ref.length) {
target = new String[ref.length];
System.arraycopy(temp, 0, target, 0, temp.length);
System.arraycopy(ref, temp.length, target, temp.length, ref.length - temp.length);
}
return target;
}
public String saveAllWindows() {
// I don't understand why ImageJ change the LookAndFeel while opening a
// simple directory dialog window
// However, I have to do this here to keep my looking
/*
* LookAndFeel laf = UIManager.getLookAndFeel(); String dir =
* IJ.getDirectory("Choose the directory to save the results...");
* if(IJ.isWindows()){ try { UIManager.setLookAndFeel(laf); } catch
* (UnsupportedLookAndFeelException e) { IJ.error(
* "Errors in saving windows"); } }
*/
String dir = getDirectory("Choose the directory to save the results...");
if (dir == null)
return null;
saveAllWindows(dir);
return dir;
}
/**
* This method is copied from
* <code>ij.io.DirectoryChooser.getDirectoryUsingJFileChooserOnThisThread</code>
* This is because DirectoryChooser reset the looking using
* <code>Java2.setSystemLookAndFeel()</code>}; This will mess up the looking
* of plugin window.
*
* @param title
* @return
*/
private String getDirectory(final String title) {
try {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle(title);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
String defaultDir = OpenDialog.getDefaultDirectory();
if (defaultDir != null) {
File f = new File(defaultDir);
if (IJ.debugMode)
IJ.log("DirectoryChooser,setSelectedFile: " + f);
chooser.setSelectedFile(f);
}
chooser.setApproveButtonText("Select");
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
directory = file.getAbsolutePath();
if (!directory.endsWith(File.separator))
directory += File.separator;
OpenDialog.setDefaultDirectory(directory);
}
} catch (Exception e) {
}
return directory;
}
public void updateSelection() {
// image UI
// DO NOT update Image list
// alignment UI
for (int i = 0; i < alignedChckbxes.length; i++) {
if (!alignedChckbxes[i].isEnabled())
align_chckes[i] = false;
alignedChckbxes[i].setSelected(align_chckes[i]);
}
for (int i = 0; i < alignTholdCombbxes.length; i++)
if (alignTholdCombbxes[i].isEnabled())
alignTholdCombbxes[i].setSelectedIndex(alignThold_combs[i]);
else
alignThold_combs[i] = alignTholdCombbxes[i].getSelectedIndex();
/**
* filters are never disabled, besides the code to retrieve the values
* is complicated no need to bother here
*/
for (int i = 0; i < filterSizeTexts.length; i++)
filterSizeTexts[i].setText(getFilterRange(filterMinSize_texts[i], filterMaxSize_texts[i]));
// cell filters UI
for (int i = 0; i < filterCombbxes.length; i++) {
filterCombbxes[i].setSelectedIndex(filter_combs[i]);
filterRangeTexts[i].setText(
getFilterRange(filterMinRange_texts[i], filterMaxRange_texts[i], filterBackRatio_texts[i]));
}
CellFilterDialog.reset();
if (!waterShedChckbx.isEnabled())
waterShed_chck = false;
waterShedChckbx.setSelected(waterShed_chck);
// Visualization UI
// matrix heat map UI
if (!matrixChckbx.isEnabled())
matrix_chck = false;
matrixChckbx.setSelected(matrix_chck);
if (matrixMetricCombbx.isEnabled())
matrixMetricCombbx.setSelectedIndex(matrixMetric_comb);
else
matrixMetric_comb = matrixMetricCombbx.getSelectedIndex();
if (matrixStatsCombbx.isEnabled())
matrixStatsCombbx.setSelectedIndex(matrixStats_comb);
else
matrixStats_comb = matrixStatsCombbx.getSelectedIndex();
for (int i = 0; i < matrixFTSpinners.length; i++) {
if (matrixFTSpinners[i].isEnabled())
matrixFTSpinners[i].setValue(matrixFT_spin[i]);
else
matrixFT_spin[i] = (Integer) matrixFTSpinners[i].getValue();
}
// scatterplot UI
if (!scatterplotChckbx.isEnabled())
scatter_chck = false;
scatterplotChckbx.setSelected(scatter_chck);
// heatmaps UI
for (int i = 0; i < heatmapRadiobtns.length; i++) {
if (i != heatmap_radio)
continue;
if(heatmapRadiobtns[heatmap_radio].isEnabled())
heatmapRadiobtns[heatmap_radio].setSelected(true);
else
heatmap_radio++;
}
for (int i = 0; i < heatmapChckbxes.length; i++) {
if (!heatmapChckbxes[i].isEnabled())
heatmap_chckes[i] = false;
heatmapChckbxes[i].setSelected(heatmap_chckes[i]);
if (heatmapColorCombbxes[i].isEnabled())
heatmapColorCombbxes[i].setSelectedIndex(heatmapColor_combs[i]);
else
heatmapColor_combs[i] = heatmapColorCombbxes[i].getSelectedIndex();
}
// Analysis Tab
// outputs UI
for (int i = 0; i < metricChckbxes.length; i++) {
if (!metricChckbxes[i].isEnabled())
metric_chckes[i] = false;
metricChckbxes[i].setSelected(metric_chckes[i]);
}
for (int i = 0; i < otherChckbxes.length; i++) {
if (!otherChckbxes[i].isEnabled())
other_chckes[i] = false;
otherChckbxes[i].setSelected(other_chckes[i]);
}
// analysis subtab
for (int i = 0; i < metricTholdRadiobtns.length; i++) {
for (int j = 0; j < metricTholdRadiobtns[i].length; j++) {
if (j == metricThold_radios[i] && metricTholdRadiobtns[i][j] != null
&& metricTholdRadiobtns[i][j].isEnabled())
metricTholdRadiobtns[i][j].setSelected(true);
else
metricThold_radios[i]++;
}
/*
* int count = 0; for (int j = 0; j < metricRadios[i].length; j++) {
* while (metricRadios[i][j] == null ||
* !metricRadios[i][j].isEnabled()) { j++; count++; } if
* (metricTholds[i] == j - count)
* metricRadios[i][j].setSelected(true); }
*/
}
for (int i = 0; i < allFTSpinners.length; i++) {
for (int j = 0; j < allFTSpinners[i].length; j++) {
boolean isEnabled = allFTSpinners[i][j].isEnabled();
if (isEnabled) {
try {
allFTSpinners[i][j].commitEdit();
} catch (ParseException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
}
allFTSpinners[i][j].setValue(allFT_spins[i][j]);
allFTSpinners[i][j].setEnabled(isEnabled);
} else {
allFT_spins[i][j] = (Integer) allFTSpinners[i][j].getValue();
}
}
}
// mTOS UI
/*
* for(int i=0;i<mTOSFTs.length;i++){ mTOSFTs[i].setValue(numOfFTs[i]);
* mTOSFTLabels[i].setValue(numOfFTs[i]); }
* mTOSRadios[mTOSscale].setSelected(true);
*
* //Distances to subcellular location UI
* distRadios[whichDist].setSelected(true);
*
* for(int iDist=0;iDist<distFTs.length;iDist++){
* distFTs[iDist].setValue(numOfDistFTs[iDist]);
* distFTLabels[iDist].setValue(numOfDistFTs[iDist]); }
*
* for(int i=0;i<distThresholders.length;i++)
* distThresholders[i].setSelectedIndex(whichDistTholds[i]);
*/
// Custom UI
if (!customMetricChckbxes.isEnabled())
custom_chck = false;
customMetricChckbxes.setSelected(custom_chck);
customCodeTextbx.setText(customCode_text);
if (custom_chck)
setCustomStatus(RUN);
else
setCustomStatus(SKIP);
// need to queue the setValue function otherwise not working
SwingUtilities.invokeLater(new Runnable() {
public void run() {
customCodeScrollpn.getVerticalScrollBar().setValue(0);
}
});
// Output UI
for (int i = 0; i < outputMetricChckbxes.length; i++) {
if (!outputMetricChckbxes[i].isEnabled())
outputMetric_chckes[i] = false;
outputMetricChckbxes[i].setSelected(outputMetric_chckes[i]);
}
for (int i = 0; i < outputOptChckbxes.length; i++) {
if (!outputOptChckbxes[i].isEnabled())
outputOpt_chckes[i] = false;
outputOptChckbxes[i].setSelected(outputOpt_chckes[i]);
}
}
private Rectangle getGUIScreenBounds() {
if (mainframe == null || !mainframe.isVisible())
return getIJScreenBounds();
else
return getScreenBounds(mainframe.getGraphicsConfiguration().getDevice());
}
private Rectangle getIJScreenBounds() {
GraphicsDevice ijScreen = IJ.getInstance().getGraphicsConfiguration().getDevice();
return getScreenBounds(ijScreen);
}
private Rectangle getScreenBounds(GraphicsDevice screen) {
GraphicsDevice[] gds = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
int ijScreenIndex = -1;
for (int i = 0; i < gds.length; i++) {
if (gds[i].equals(screen)) {
ijScreenIndex = i;
break;
}
}
if (ijScreenIndex == -1)
return new Rectangle(0, 0, 0, 0);
else {
GraphicsConfiguration gc = gds[ijScreenIndex].getDefaultConfiguration();
Rectangle bounds = gc.getBounds();
Insets screenInsets = Toolkit.getDefaultToolkit().getScreenInsets(gc);
Rectangle effectiveScreenArea = new Rectangle();
effectiveScreenArea.x = bounds.x + screenInsets.left;
effectiveScreenArea.y = bounds.y + screenInsets.top;
effectiveScreenArea.height = bounds.height - screenInsets.top - screenInsets.bottom;
effectiveScreenArea.width = bounds.width - screenInsets.left - screenInsets.right;
return effectiveScreenArea;
}
}
public void exit() {
mainframe.dispatchEvent(new WindowEvent(mainframe, WindowEvent.WINDOW_CLOSING));
}
public void setNReporters(int nReporter) {
nReporters = nReporter;
nChannels = nReporters + (MAX_NCHANNELS - MAX_NREPORTERS);
Prefs.set(pluginName + "nChannels" + "." + getVarName(nChannels), nChannels);
filterStrings = makeAllFilters(nReporters);
// imps = new ImagePlus[nChannels];
// whichAligns = newArray(DEFAULT_BOOLEAN,nReporter);
// whichTholds = newArray(DEFAULT_CHOICE,nChannels);
// whichHeatmap = newArray(DEFAULT_BOOLEAN,nReporter);
// numOfFTs = newArray(DEFAULT_CHOICE,nReporter);
// heatmapChoices = newArray(nReporter);
// allFTs = newArray(DEFAULT_FT, nReporter, METRICNAMES.length);
// numOfDistFTs = newArray(DEFAULT_FT,nReporter);
// whichDistTholds = newArray(DEFAULT_CHOICE,nReporter);
updateGUI();
updateTicked();
adaptZoom();
}
@SuppressWarnings("unchecked")
public void updateGUI() {
// nReporters:
for (int i = MIN_NREPORTERS; i < nReporters; i++) {
imgTitles[i].setVisible(true);
imgCombbxes[i].setVisible(true);
imgCombbxes[i].setEnabled(true);
alignTholdCombbxes[i].setVisible(true);
alignTholdCombbxes[i].setEnabled(true);
alignedChckbxes[i].setVisible(true);
alignedChckbxes[i].setEnabled(true);
paneMatrixSpinners[i].setVisible(true);
paneMatrixSpinners[i].setEnabled(true);
// matrixSpinners[i].setVisible(true);
heatmapChckbxes[i].setVisible(true);
heatmapChckbxes[i].setEnabled(true);
heatmapColorCombbxes[i].setVisible(true);
heatmapColorCombbxes[i].setEnabled(true);
for (int j = 0; j < METRICACRONYMS.length; j++) {
allFTSpinners[i][j].setVisible(true);
allFTSpinners[i][j].setEnabled(metricTholdRadiobtns[j][IDX_THOLD_FT].isSelected());
}
lblFTunits[i].setVisible(true);
for (int iFilter = 0; iFilter < filterCombbxes.length; iFilter++) {
DefaultComboBoxModel<String> cbm = (DefaultComboBoxModel<String>) filterCombbxes[iFilter].getModel();
for (int iString = 0; iString < INTEN_FILTERS.length; iString++) {
String temp = makeIntFilterString(INTEN_FILTERS[iString], i);
if (cbm.getIndexOf(temp) < 0)
cbm.addElement(temp);
}
}
// DefaultComboBoxModel<String> cbm = (DefaultComboBoxModel<String>)
// matrixMetricCombbx.getModel();
// if (cbm.getIndexOf("M" + (i + 1)) < 0)
// cbm.addElement("M" + (i + 1));
// some channels might not have input, adjust for that
// we need to call updateTicked() after updateGUI()
/*
* boolean isPresent = imgs[i].getSelectedIndex() != -1 &&
* !imgs[i].getItemAt(imgs[i].getSelectedIndex()).equal(NOIMAGE);
* alignedChecks[i].setEnabled(isPresent);
* thresholders[i].setEnabled(isPresent);
* heatmapColors[i].setEnabled(isPresent);
* heatmapChckbx[i].setEnabled(isPresent);
*/
}
for (int i = nReporters; i < MAX_NREPORTERS; i++) {
imgTitles[i].setVisible(false);
imgCombbxes[i].setVisible(false);
imgCombbxes[i].setEnabled(false);
alignTholdCombbxes[i].setVisible(false);
alignTholdCombbxes[i].setEnabled(false);
alignedChckbxes[i].setVisible(false);
alignedChckbxes[i].setEnabled(false);
paneMatrixSpinners[i].setVisible(false);
paneMatrixSpinners[i].setEnabled(false);
// matrixSpinners[i].setVisible(false);
heatmapChckbxes[i].setVisible(false);
heatmapChckbxes[i].setEnabled(false);
heatmapColorCombbxes[i].setVisible(false);
heatmapColorCombbxes[i].setEnabled(false);
for (int j = 0; j < METRICACRONYMS.length; j++) {
allFTSpinners[i][j].setVisible(false);
allFTSpinners[i][j].setEnabled(false);
}
lblFTunits[i].setVisible(false);
for (int iFilter = 0; iFilter < filterCombbxes.length; iFilter++) {
DefaultComboBoxModel<String> cbm = (DefaultComboBoxModel<String>) filterCombbxes[iFilter].getModel();
for (int iString = 0; iString < INTEN_FILTERS.length; iString++)
cbm.removeElement(makeIntFilterString(INTEN_FILTERS[iString], i));
}
// DefaultComboBoxModel<String> cbm = (DefaultComboBoxModel<String>)
// matrixMetricCombbx.getModel();
// cbm.removeElement("M" + (i + 1));
}
if (nReporters == 2) {
for (int i = 0; i < metricTholdRadiobtns.length; i++) {
metricTholdRadiobtns[i][IDX_THOLD_COSTES].setVisible(true);
metricTholdRadiobtns[i][IDX_THOLD_COSTES].setEnabled(true);
}
// lblMetricTholds[IDX_THOLD_ALL].setVisible(true);
lblMetricTholds[IDX_THOLD_COSTES].setVisible(true);
for (int iMetric : METRICS_2D_ONLY) {
for (JRadioButton jrb : metricTholdRadiobtns[iMetric]) {
if (jrb != null) {
jrb.setVisible(true);
jrb.setEnabled(true);
}
}
for (int i = 0; i < nReporters; i++) {
allFTSpinners[i][iMetric].setVisible(true);
allFTSpinners[i][iMetric].setEnabled(metricTholdRadiobtns[iMetric][IDX_THOLD_FT].isSelected());
}
metricChckbxes[iMetric].setVisible(true);
metricChckbxes[iMetric].setEnabled(true);
}
} else if (nReporters == 3) {
for (int i = 0; i < metricTholdRadiobtns.length; i++) {
metricTholdRadiobtns[i][IDX_THOLD_COSTES].setVisible(false);
metricTholdRadiobtns[i][IDX_THOLD_COSTES].setEnabled(false);
if (metricTholdRadiobtns[i][IDX_THOLD_COSTES].isSelected())
if (metricTholdRadiobtns[i][IDX_THOLD_ALL] == null)
metricTholdRadiobtns[i][IDX_THOLD_FT].setSelected(true);
else
metricTholdRadiobtns[i][IDX_THOLD_ALL].setSelected(true);
}
// lblMetricTholds[IDX_THOLD_ALL].setVisible(false);
lblMetricTholds[IDX_THOLD_COSTES].setVisible(false);
for (int iMetric : METRICS_2D_ONLY) {
for (JRadioButton jrb : metricTholdRadiobtns[iMetric]) {
if (jrb != null) {
jrb.setVisible(false);
jrb.setEnabled(false);
}
}
for (int i = 0; i < allFTSpinners.length; i++) {
allFTSpinners[i][iMetric].setVisible(false);
allFTSpinners[i][iMetric].setEnabled(metricTholdRadiobtns[iMetric][IDX_THOLD_FT].isSelected());
}
metricChckbxes[iMetric].setVisible(false);
metricChckbxes[iMetric].setEnabled(false);
}
}
customCode_text = StringCompiler.makeDefaultCode(nReporters);
customCodeTextbx.setText(customCode_text);
matrixMetricList = getMatrixMetrics(nReporters);
matrixMetricCombbx.setModel(new DefaultComboBoxModel<String>(matrixMetricList));
CellFilterDialog.syncFilter();
mainframe.getContentPane().revalidate();
mainframe.getContentPane().repaint();
}
/**
* Add in 1.1.0 to take in plugin parameters
*/
private void setParameters() {
GenericDialog gd = new GenericDialog(PluginStatic.pluginName + " parameters");
gd.addCheckbox("Background Subtraction before thresholding", preBackSub);
for (int iBall = 0; iBall < rollingBallSizes.length; iBall++)
if (imgCombbxes[iBall].isVisible())
gd.addNumericField("Rolling BallSize (" + imgLabels[iBall] + ")", rollingBallSizes[iBall], 0);
// PluginStatic.PHASE_ROLINGBALL_SIZE;
gd.addPanel(new Panel());
gd.addCheckbox("Use Manual Background Settings Below", manualBack);
for (int iBack = 0; iBack < lightBacks.length; iBack++)
if (imgCombbxes[iBack].isVisible())
gd.addCheckbox("Light Background (" + imgLabels[iBack] + ")",
lightBacks[iBack] != null ? lightBacks[iBack] : false);
gd.addPanel(new Panel());
gd.addCheckbox("Apply ROIs to all slices", doROIall);
gd.showDialog();
// Retrieve parameters
if (gd.wasOKed()) {
boolean cache_preBackSub = gd.getNextBoolean();
boolean changed = cache_preBackSub != preBackSub;
if (showThold)
resetThr();
for (int iBall = 0; iBall < rollingBallSizes.length; iBall++)
if (imgCombbxes[iBall].isVisible())
rollingBallSizes[iBall] = gd.getNextNumber();
preBackSub = cache_preBackSub;
if (showThold && changed)
updateThr();
manualBack = gd.getNextBoolean();
for (int iBack = 0; iBack < lightBacks.length; iBack++){
if (imgCombbxes[iBack].isVisible()){
if (manualBack) {
lightBacks[iBack] = gd.getNextBoolean();
}else{
lightBacks[iBack] = null;
gd.getNextBoolean();
}
}
}
doROIall = gd.getNextBoolean();
}
}
}
/**
* This class will display line numbers for a related text component. The text
* component must use the same line height for each line. TextLineNumber
* supports wrapped lines and will highlight the line number of the current
* line in the text component.
*
* This class was designed to be used as a component added to the row header
* of a JScrollPane.
*/
class TextLineNumber extends JPanel
implements CaretListener, DocumentListener, PropertyChangeListener
{
public final static float LEFT = 0.0f;
public final static float CENTER = 0.5f;
public final static float RIGHT = 1.0f;
private final static Border OUTER = new MatteBorder(0, 0, 0, 2, Color.GRAY);
private final static int HEIGHT = Integer.MAX_VALUE - 1000000;
// Text component this TextTextLineNumber component is in sync with
private JTextComponent component;
// Properties that can be changed
private boolean updateFont;
private int borderGap;
private Color currentLineForeground;
private float digitAlignment;
private int minimumDisplayDigits;
// Keep history information to reduce the number of times the component
// needs to be repainted
private int lastDigits;
private int lastHeight;
private int lastLine;
private HashMap<String, FontMetrics> fonts;
/**
* Create a line number component for a text component. This minimum
* display width will be based on 3 digits.
*
* @param component the related text component
*/
public TextLineNumber(JTextComponent component)
{
this(component, 3);
}
/**
* Create a line number component for a text component.
*
* @param component the related text component
* @param minimumDisplayDigits the number of digits used to calculate
* the minimum width of the component
*/
public TextLineNumber(JTextComponent component, int minimumDisplayDigits)
{
this.component = component;
setFont( component.getFont() );
setBorderGap( 5 );
setCurrentLineForeground( Color.RED );
setDigitAlignment( RIGHT );
setMinimumDisplayDigits( minimumDisplayDigits );
component.getDocument().addDocumentListener(this);
component.addCaretListener( this );
component.addPropertyChangeListener("font", this);
}
/**
* Gets the update font property
*
* @return the update font property
*/
public boolean getUpdateFont()
{
return updateFont;
}
/**
* Set the update font property. Indicates whether this Font should be
* updated automatically when the Font of the related text component
* is changed.
*
* @param updateFont when true update the Font and repaint the line
* numbers, otherwise just repaint the line numbers.
*/
public void setUpdateFont(boolean updateFont)
{
this.updateFont = updateFont;
}
/**
* Gets the border gap
*
* @return the border gap in pixels
*/
public int getBorderGap()
{
return borderGap;
}
/**
* The border gap is used in calculating the left and right insets of the
* border. Default value is 5.
*
* @param borderGap the gap in pixels
*/
public void setBorderGap(int borderGap)
{
this.borderGap = borderGap;
Border inner = new EmptyBorder(0, borderGap, 0, borderGap);
setBorder( new CompoundBorder(OUTER, inner) );
lastDigits = 0;
setPreferredWidth();
}
/**
* Gets the current line rendering Color
*
* @return the Color used to render the current line number
*/
public Color getCurrentLineForeground()
{
return currentLineForeground == null ? getForeground() : currentLineForeground;
}
/**
* The Color used to render the current line digits. Default is Coolor.RED.
*
* @param currentLineForeground the Color used to render the current line
*/
public void setCurrentLineForeground(Color currentLineForeground)
{
this.currentLineForeground = currentLineForeground;
}
/**
* Gets the digit alignment
*
* @return the alignment of the painted digits
*/
public float getDigitAlignment()
{
return digitAlignment;
}
/**
* Specify the horizontal alignment of the digits within the component.
* Common values would be:
* <ul>
* <li>TextLineNumber.LEFT
* <li>TextLineNumber.CENTER
* <li>TextLineNumber.RIGHT (default)
* </ul>
* @param currentLineForeground the Color used to render the current line
*/
public void setDigitAlignment(float digitAlignment)
{
this.digitAlignment =
digitAlignment > 1.0f ? 1.0f : digitAlignment < 0.0f ? -1.0f : digitAlignment;
}
/**
* Gets the minimum display digits
*
* @return the minimum display digits
*/
public int getMinimumDisplayDigits()
{
return minimumDisplayDigits;
}
/**
* Specify the mimimum number of digits used to calculate the preferred
* width of the component. Default is 3.
*
* @param minimumDisplayDigits the number digits used in the preferred
* width calculation
*/
public void setMinimumDisplayDigits(int minimumDisplayDigits)
{
this.minimumDisplayDigits = minimumDisplayDigits;
setPreferredWidth();
}
/**
* Calculate the width needed to display the maximum line number
*/
private void setPreferredWidth()
{
Element root = component.getDocument().getDefaultRootElement();
int lines = root.getElementCount();
int digits = Math.max(String.valueOf(lines).length(), minimumDisplayDigits);
// Update sizes when number of digits in the line number changes
if (lastDigits != digits)
{
lastDigits = digits;
FontMetrics fontMetrics = getFontMetrics( getFont() );
int width = fontMetrics.charWidth( '0' ) * digits;
Insets insets = getInsets();
int preferredWidth = insets.left + insets.right + width;
Dimension d = getPreferredSize();
d.setSize(preferredWidth, HEIGHT);
setPreferredSize( d );
setSize( d );
}
}
/**
* Draw the line numbers
*/
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// Determine the width of the space available to draw the line number
FontMetrics fontMetrics = component.getFontMetrics( component.getFont() );
Insets insets = getInsets();
int availableWidth = getSize().width - insets.left - insets.right;
// Determine the rows to draw within the clipped bounds.
Rectangle clip = g.getClipBounds();
int rowStartOffset = component.viewToModel( new Point(0, clip.y) );
int endOffset = component.viewToModel( new Point(0, clip.y + clip.height) );
while (rowStartOffset <= endOffset)
{
try
{
if (isCurrentLine(rowStartOffset))
g.setColor( getCurrentLineForeground() );
else
g.setColor( getForeground() );
// Get the line number as a string and then determine the
// "X" and "Y" offsets for drawing the string.
String lineNumber = getTextLineNumber(rowStartOffset);
int stringWidth = fontMetrics.stringWidth( lineNumber );
int x = getOffsetX(availableWidth, stringWidth) + insets.left;
int y = getOffsetY(rowStartOffset, fontMetrics);
g.drawString(lineNumber, x, y);
// Move to the next row
rowStartOffset = Utilities.getRowEnd(component, rowStartOffset) + 1;
}
catch(Exception e) {break;}
}
}
/*
* We need to know if the caret is currently positioned on the line we
* are about to paint so the line number can be highlighted.
*/
private boolean isCurrentLine(int rowStartOffset)
{
int caretPosition = component.getCaretPosition();
Element root = component.getDocument().getDefaultRootElement();
if (root.getElementIndex( rowStartOffset ) == root.getElementIndex(caretPosition))
return true;
else
return false;
}
/*
* Get the line number to be drawn. The empty string will be returned
* when a line of text has wrapped.
*/
protected String getTextLineNumber(int rowStartOffset)
{
Element root = component.getDocument().getDefaultRootElement();
int index = root.getElementIndex( rowStartOffset );
Element line = root.getElement( index );
if (line.getStartOffset() == rowStartOffset)
return String.valueOf(index + 1);
else
return "";
}
/*
* Determine the X offset to properly align the line number when drawn
*/
private int getOffsetX(int availableWidth, int stringWidth)
{
return (int)((availableWidth - stringWidth) * digitAlignment);
}
/*
* Determine the Y offset for the current row
*/
private int getOffsetY(int rowStartOffset, FontMetrics fontMetrics)
throws BadLocationException
{
// Get the bounding rectangle of the row
Rectangle r = component.modelToView( rowStartOffset );
int lineHeight = fontMetrics.getHeight();
int y = r.y + r.height;
int descent = 0;
// The text needs to be positioned above the bottom of the bounding
// rectangle based on the descent of the font(s) contained on the row.
if (r.height == lineHeight) // default font is being used
{
descent = fontMetrics.getDescent();
}
else // We need to check all the attributes for font changes
{
if (fonts == null)
fonts = new HashMap<String, FontMetrics>();
Element root = component.getDocument().getDefaultRootElement();
int index = root.getElementIndex( rowStartOffset );
Element line = root.getElement( index );
for (int i = 0; i < line.getElementCount(); i++)
{
Element child = line.getElement(i);
AttributeSet as = child.getAttributes();
String fontFamily = (String)as.getAttribute(StyleConstants.FontFamily);
Integer fontSize = (Integer)as.getAttribute(StyleConstants.FontSize);
String key = fontFamily + fontSize;
FontMetrics fm = fonts.get( key );
if (fm == null)
{
Font font = new Font(fontFamily, Font.PLAIN, fontSize);
fm = component.getFontMetrics( font );
fonts.put(key, fm);
}
descent = Math.max(descent, fm.getDescent());
}
}
return y - descent;
}
//
// Implement CaretListener interface
//
@Override
public void caretUpdate(CaretEvent e)
{
// Get the line the caret is positioned on
int caretPosition = component.getCaretPosition();
Element root = component.getDocument().getDefaultRootElement();
int currentLine = root.getElementIndex( caretPosition );
// Need to repaint so the correct line number can be highlighted
if (lastLine != currentLine)
{
repaint();
lastLine = currentLine;
}
}
//
// Implement DocumentListener interface
//
@Override
public void changedUpdate(DocumentEvent e)
{
documentChanged();
}
@Override
public void insertUpdate(DocumentEvent e)
{
documentChanged();
}
@Override
public void removeUpdate(DocumentEvent e)
{
documentChanged();
}
/*
* A document change may affect the number of displayed lines of text.
* Therefore the lines numbers will also change.
*/
private void documentChanged()
{
// View of the component has not been updated at the time
// the DocumentEvent is fired
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
try
{
int endPos = component.getDocument().getLength();
Rectangle rect = component.modelToView(endPos);
if (rect != null && rect.y != lastHeight)
{
setPreferredWidth();
repaint();
lastHeight = rect.y;
}
}
catch (BadLocationException ex) { /* nothing to do */ }
}
});
}
//
// Implement PropertyChangeListener interface
//
@Override
public void propertyChange(PropertyChangeEvent evt)
{
if (evt.getNewValue() instanceof Font)
{
if (updateFont)
{
Font newFont = (Font) evt.getNewValue();
setFont(newFont);
lastDigits = 0;
setPreferredWidth();
}
else
{
repaint();
}
}
}
}
| 146,943 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
PluginStatic.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/main/PluginStatic.java | package ezcol.main;
import java.awt.Color;
import java.awt.Frame;
import java.io.File;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import ij.IJ;
import ij.ImageJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.WindowManager;
import ij.gui.ImageWindow;
import ij.gui.Roi;
import ij.macro.Interpreter;
import ij.measure.ResultsTable;
import ij.plugin.frame.Editor;
import ij.plugin.frame.PlugInFrame;
import ij.plugin.frame.RoiManager;
import ij.process.AutoThresholder;
import ij.process.AutoThresholder.Method;
import ij.process.ByteProcessor;
import ij.process.ImageProcessor;
import ij.text.TextWindow;
import ij.util.Tools;
import ezcol.cell.CellFinder;
import ezcol.debug.ExceptionHandler;
import ezcol.files.FilesIO;
import ezcol.metric.MatrixCalculator;
import ezcol.metric.MatrixCalculator3D;
import ezcol.metric.StringCompiler;
import ezcol.visual.visual2D.HeatChartStackWindow;
/**
* This class contains all parameters needed for GUIframe, MacroHandler, and
* AnalysisOperator as well as static methods for implementation
* <p>
* Once a new field of input has been added, please follow the instruction
* below: <br>
* The following methods need to be changed: <br>
* {@code GUIframe.loadPreference, GUIframe.retrieveParams,
* GUIframe.GUI, MacroHandler} <br>
* The following methods might need to be changed: <br>
* {@code this.checkParams,this.retrieveOptions,GUIframe.retrieveOptions,
* AnalysisOperator.prepAll(and other methods start with prep)}
*
* @author Huanjie Sheng
*
*/
public abstract class PluginStatic implements PluginConstants {
// static variables are shared among derived/extended classes
// They are also stored in the memory shared by all instances
// record which result(s) to be calculated
protected static int options;
// effectively final
protected static String pluginName = "";
public static final String VERSION = FilesIO.getPluginProperties(FilesIO.VERSION);
public static final String CONTACT = "[email protected]";
/**
* <p>s\
* Arrays of options
* </p>
* They have to be matched with the corresponding name strings and/or
* options as the following:
* <p>
* LIST_METRICS -> METRICNAMES, metricOpts
* </p>
* <p>
* LIST_OTHERS -> OTHERNAMES, otherOpts
* </p>
* <p>
* LIST_ALIGNS -> whichAlings
* </p>
* <p>
* LIST_TOS -> TOSOPTS, mTOSscale
* </p>
* <p>
* LIST_DIST -> whichDist
* </p>
* <p>
* LIST_HEAT -> whichHeatmaps
* </p>
* <p>
* LIST_HEATMAPOPTS -> HEATMAPOPTS, whichHeatmapOpt
* </p>
* <p>
* LIST_OUTPUTMETRICS -> OUTPUTMETRICS, outputMetrics
* </p>
* <p>
* LIST_OUTPUTOTHERS -> OUTPUTOTHERS, outputOthers
* </p>
*/
public static final int[] LIST_METRICS = { DO_TOS, DO_PCC, DO_SRC, DO_ICQ, DO_MCC };
public static final int[] LIST_OTHERS = { // DO_CEN2NPOLE, DO_CEN2CEN,
DO_AVGINT, DO_CUSTOM };
public static final int[] LIST_TOS = { DO_LINEAR_TOS, DO_LOG2_TOS };
public static final int[] LIST_HEATMAPOPTS = { DO_HEAT_CELL, DO_HEAT_IMG, DO_HEAT_STACK };
public static final int[] LIST_OUTPUTMETRICS = { DO_SUMMARY, DO_HIST };
public static final int[] LIST_OUTPUTOTHERS = { DO_MASKS, DO_ROIS };
// indexes for metrics
// public static final int
// TOSH=0,TOSMAX=1,TOSMIN=2,MTOS=3,PCC=4,SRC=5,ICQ=6,M1_M2=7;
// image parameters
public static final int MAX_NCHANNELS = 4, MAX_NREPORTERS = 3, MIN_NREPORTERS = 2;
public static int nChannels = 3;
static int nReporters = nChannels - (MAX_NCHANNELS - MAX_NREPORTERS);
// The last channel is always used for cell identification
// Additional flourescence channels are added before it
static String[] imgLabels = makeImgLabels(MAX_NCHANNELS);
static ImagePlus[] imps = new ImagePlus[MAX_NCHANNELS];
static int nbImgs;
// alignment parameters
// Add in 1.1.0 to represent manual threshold option in alignThold_combs
public static final String MANUAL_THOLD = "*Manual*";
static final String[] ALLTHOLDS;
static{
String[] autoMethods = AutoThresholder.getMethods();
String manual_thold = MANUAL_THOLD.replace("*", "");
ALLTHOLDS = new String[autoMethods.length + 1];
int iThold = 0;
for (iThold = 0; iThold < autoMethods.length; iThold++){
if (manual_thold.compareTo(autoMethods[iThold]) < 0){
ALLTHOLDS[iThold] = MANUAL_THOLD;
iThold++;
break;
}else{
ALLTHOLDS[iThold] = autoMethods[iThold];
}
}
for (; iThold < ALLTHOLDS.length; iThold++){
ALLTHOLDS[iThold] = autoMethods[iThold - 1];
}
//System.arraycopy(autoMethods, 0, ALLTHOLDS, 0, autoMethods.length);
//ALLTHOLDS[autoMethods.length] = MANUAL_THOLD;
}
// Add in 1.1.0 to allow value presence search of Methods in AutoThresholder
static final Map<String, Method> THRESHOLD_METHODS;
static{
THRESHOLD_METHODS = new HashMap<String, Method>(Method.values().length);
for (Method method : Method.values()) {
THRESHOLD_METHODS.put(method.name(), method);
}
}
// Add in 1.1.0 to choose whether to do background subtraction before applying thresholds
static boolean preBackSub = DEFAULT_BOOLEAN;
static double[] rollingBallSizes = newArray(DEFAULT_ROLLINGBALL_SIZE, MAX_NCHANNELS);
// Add in 1.1.0 to choose whether to use skewness to automatically detect lightbackground
static boolean manualBack = DEFAULT_BOOLEAN;
static Boolean[] lightBacks = newArray(Boolean.class, (Boolean) null, MAX_NCHANNELS);
// Add in 1.1.3 to apply ROIs in ROImanager to all slices
static boolean doROIall = DEFAULT_BOOLEAN;
// Add in 1.1.0 to store manually selected thresholds
static double[][] manualTholds = newArray(ImageProcessor.NO_THRESHOLD, MAX_NCHANNELS, 2);
static boolean[] align_chckes = newArray(DEFAULT_BOOLEAN, MAX_NREPORTERS);
static int[] alignThold_combs = newArray(DEFAULT_CHOICE, MAX_NCHANNELS);
// static boolean[] darkBacks = {true,true,false};
// DO NOT use DEFAULT_BOOLEAN here because didAlignment is not one of the
// options
static boolean didAlignment = false;
// cell filters parameters
// A marker used to tell if the filter should be treated as signal to
// background ratio
public static final String SB_MARKER = CellFinder.SB_MARKER;
/**
* This needs to be consistent with
* <code>ij.measure.ResultsTable.defaultHeadings</code> All strings after
* the first space will be cut when transfered to filter strings in
* <code>ResultsTable</code>. The number between parentheses will be used as
* channel number and the letters will be disregarded Whether the filter
* will be applied or not dependes on CellFinder not the string put here
*
* @see CellFinder
* @see ResultsTable
*/
private static Class<?> EzColocalization;
static final String[] SHAPE_FILTERS = { "Area", "X", "Y", "Perim.", "BX", "BY", "Width", "Height", "Major", "Minor",
"Angle", "Circ.", "Feret", "FeretX", "FeretY", "FeretAngle", "MinFeret", "AR", "Round", "Solidity",
"%Area" };
static final String[] INTEN_FILTERS = { "Mean", "StdDev", "Mode", "Min", "Max", "Median", "Skew", "Kurt", "IntDen",
"RawIntDen", "Mean " + SB_MARKER, "Median " + SB_MARKER };
static String[] filterStrings = makeAllFilters(nReporters);
static final String[] SIZE_FILTERS = { "Area" };
static double[] filterMinSize_texts = newArray(DEFAULT_MIN, SIZE_FILTERS.length);
static double[] filterMaxSize_texts = newArray(DEFAULT_MAX, SIZE_FILTERS.length);
// filterChoices, minRanges, maxRanges, backRatios should have the same
// length
// we don't use default choice here, but default choice is still used in
// smart recording
// This is because the judgment to record is based on minRanges and
// maxRanges, so the filter choice doesn't matter
static int[] staticFilterChoices = { 0, 17, 21, 33, 24, 36, 25, 37 };
static int[] filter_combs = staticFilterChoices.clone();
static double[] filterMinRange_texts = newArray(DEFAULT_MIN, filter_combs.length);
static double[] filterMaxRange_texts = newArray(DEFAULT_MAX, filter_combs.length);
@Deprecated
static boolean[] filterBackRatio_texts = newArray(DEFAULT_BOOLEAN, filter_combs.length);
static ArrayList<Integer> adFilterChoices = new ArrayList<Integer>();
static ArrayList<Double> adMinRanges = new ArrayList<Double>();
static ArrayList<Double> adMaxRanges = new ArrayList<Double>();
static ArrayList<Boolean> adBackRatios = new ArrayList<Boolean>();
// roiCells might be problematic in parallel streams/multiple threads
static RoiManager roiCells = null;
static boolean waterShed_chck = DEFAULT_BOOLEAN;
// scatterplot parameter
static boolean scatter_chck = DEFAULT_BOOLEAN;
// metric matrices
static boolean matrix_chck = DEFAULT_BOOLEAN;
static final String[] STATS_METHODS = HeatChartStackWindow.getAllStatsMethods();
static String[] matrixMetricList = getMatrixMetrics(nReporters);
static int matrixMetric_comb = DEFAULT_CHOICE;
static int matrixStats_comb = DEFAULT_CHOICE;
static final int MINFT = DEFAULT_MIN_FT;
static final int MAXFT = DEFAULT_MAX_FT;
static final int STEPFT = 1;
static int[] matrixFT_spin = newArray(DEFAULT_FT, MAX_NREPORTERS);
// heatmaps parameters
static final String[] HEATMAPS = { "hot", "cool", "fire", "grays", "ice", "spectrum", "3-3-2 RGB", "red", "green",
"blue", "cyan", "magenta", "yellow", "redgreen" };
static final String[] HEATMAPOPTS = { "cell", "image", "stack" };
static boolean[] heatmap_chckes = newArray(DEFAULT_BOOLEAN, MAX_NREPORTERS);
static int heatmap_radio = DEFAULT_CHOICE;
// Again we don't use default choice here because it's determined by whether
// check box is checked or not
// If heat map is requested, then the choice must be recorded
static int[] heatmapColor_combs = newArray(MAX_NREPORTERS);
// metric parameters
static final String[] OTHERNAMES = { "Average Signal", "Custom Metric" };
//This must be consistent with METRICACRONYMS
public static final String[] METRICACRONYMS = { "TOS", "PCC", "SRCC", "ICQ", "MCC" };
public static final String[] METRICNAMES = {"Threshold Overlap Score",
"Pearson's Correlation Coefficient", "Spearman's Rank Correlation Coefficient",
"Intensity Correlation Quotient", "Manders' Colocalization Coefficient (M1, M2, and M3)"};
public static final int AVG_INT = 0, CUSTOM = 1;
public static final int TOS = 0, PCC = 1, SRCC = 2, ICQ = 3, MCC = 4;
// The index of "All" in METRIC_THOLDS
protected static final int IDX_THOLD_ALL = 0, IDX_THOLD_COSTES = 1, IDX_THOLD_FT = 2;
static final String[] METRIC_THOLDS = { "All", "Costes'", "FT" };
static final String[] METRIC_THOLDS_TIPS = { "All Pixels", "Costes' Algorithm",
"Top Percentile of Pixels Threshold" };
protected static final List<Integer> NO_THOLD_ALL = Arrays.asList(new Integer[] { TOS, MCC });
static boolean[] metric_chckes = newArray(DEFAULT_BOOLEAN, METRICACRONYMS.length);
static boolean[] other_chckes = newArray(DEFAULT_BOOLEAN, OTHERNAMES.length);
static int[] metricThold_radios = newArray(DEFAULT_CHOICE, METRICACRONYMS.length);
static int[][] allFT_spins = newArray(DEFAULT_FT, MAX_NREPORTERS, METRICACRONYMS.length);
// NO NEED TO LOAD BUT TO RETRIEVE
static int[] allTholds;
// Custom parameters
static String customCode_text = "";
static boolean custom_chck = DEFAULT_BOOLEAN;
// Output parameters
static final String[] OUTPUTMETRICS = { "Summary", "Histogram(s)" };
static final String[] OUTPUTOTHERS = { "Mask(s)", "ROI(s)" };
static boolean[] outputMetric_chckes = newArray(DEFAULT_BOOLEAN, OUTPUTMETRICS.length);
static boolean[] outputOpt_chckes = newArray(DEFAULT_BOOLEAN, OUTPUTOTHERS.length);
public static Vector<Frame> allFrames = new Vector<Frame>();
public static double parseDouble(String s) {
if (s == null)
return Double.NaN;
double value = Tools.parseDouble(s);
if (Double.isNaN(value)) {
if (s.startsWith("&"))
s = s.substring(1);
Interpreter interp = Interpreter.getInstance();
value = interp != null ? interp.getVariable2(s) : Double.NaN;
}
return value;
}
public static double[] str2doubles(String str) {
String[] minAndMax;
double mins, maxs;
minAndMax = Tools.split(str, "-");
mins = minAndMax.length >= 1 ? parseDouble(minAndMax[0].replaceAll("[[\\D+]&&[^\\.]]", "")) : Double.NaN;
maxs = minAndMax.length == 2 ? parseDouble(minAndMax[1].replaceAll("[[\\D+]&&[^\\.]]", "")) : Double.NaN;
mins = Double.isNaN(mins) ? DEFAULT_MIN : mins;
maxs = Double.isNaN(maxs) ? DEFAULT_MAX : maxs;
if (mins < DEFAULT_MIN)
mins = DEFAULT_MIN;
if (maxs < mins)
maxs = DEFAULT_MAX;
return new double[] { mins, maxs };
}
public static int getOptions() {
return options;
}
public static String[] getAllfilters() {
String[] allFilters = new String[filter_combs.length + adFilterChoices.size()];
for (int iFilter = 0; iFilter < filter_combs.length; iFilter++)
allFilters[iFilter] = filterStrings[filter_combs[iFilter]];
for (int iFilter = 0; iFilter < adFilterChoices.size(); iFilter++)
allFilters[iFilter + filter_combs.length] = filterStrings[adFilterChoices.get(iFilter)];
return allFilters;
}
public static double[] getAllMinRanges() {
double[] allMinRanges = new double[filterMinRange_texts.length + adMinRanges.size()];
System.arraycopy(filterMinRange_texts, 0, allMinRanges, 0, filterMinRange_texts.length);
for (int iFilter = 0; iFilter < adMinRanges.size(); iFilter++)
allMinRanges[iFilter + filterMinRange_texts.length] = adMinRanges.get(iFilter);
return allMinRanges;
}
public static double[] getAllMaxRanges() {
double[] allMaxRanges = new double[filterMaxRange_texts.length + adMaxRanges.size()];
System.arraycopy(filterMaxRange_texts, 0, allMaxRanges, 0, filterMaxRange_texts.length);
for (int iFilter = 0; iFilter < adMaxRanges.size(); iFilter++)
allMaxRanges[iFilter + filterMaxRange_texts.length] = adMaxRanges.get(iFilter);
return allMaxRanges;
}
public static boolean[] getAllBackRatios() {
boolean[] allBackRatios = new boolean[filterBackRatio_texts.length + adBackRatios.size()];
System.arraycopy(filterBackRatio_texts, 0, allBackRatios, 0, filterBackRatio_texts.length);
for (int iFilter = 0; iFilter < adBackRatios.size(); iFilter++)
allBackRatios[iFilter + filterBackRatio_texts.length] = adBackRatios.get(iFilter);
return allBackRatios;
}
public static String getFilterRange(double cmin, double cmax) {
return getFilterRange(cmin, cmax, false);
}
public static String getFilterRange(double cmin, double cmax, boolean back) {
// make filter range
int places = 0;
if ((int) cmin != cmin)
places = 2;
if ((int) cmax != cmax && cmax != Double.POSITIVE_INFINITY)
places = 2;
String minStr = ResultsTable.d2s(cmin, places);
if (minStr.indexOf("-") != -1) {
for (int i = places; i <= 6; i++) {
minStr = ResultsTable.d2s(cmin, i);
if (minStr.indexOf("-") == -1)
break;
}
}
String maxStr = ResultsTable.d2s(cmax, places);
String sizeStr;
if (back)
sizeStr = minStr + "X-" + maxStr + "X";
else
sizeStr = minStr + "-" + maxStr;
return sizeStr;
}
static boolean checkParams() {
boolean changed = false;
for (int iThold = 0; iThold < alignThold_combs.length; iThold++) {
if (alignThold_combs[iThold] >= ALLTHOLDS.length || alignThold_combs[iThold] < 0) {
alignThold_combs[iThold] = DEFAULT_CHOICE;
changed = true;
}
}
for (int iSize = 0; iSize < filterMinSize_texts.length; iSize++) {
if (filterMaxSize_texts[iSize] < filterMinSize_texts[iSize]) {
filterMinSize_texts[iSize] = DEFAULT_MIN;
filterMaxSize_texts[iSize] = DEFAULT_MAX;
changed = true;
} else {
if (filterMinSize_texts[iSize] < DEFAULT_MIN) {
filterMinSize_texts[iSize] = DEFAULT_MIN;
changed = true;
}
if (filterMaxSize_texts[iSize] > DEFAULT_MAX) {
filterMaxSize_texts[iSize] = DEFAULT_MAX;
changed = true;
}
}
}
for (int iFilter = 0; iFilter < filter_combs.length; iFilter++) {
if (filter_combs[iFilter] < 0 || filter_combs[iFilter] >= filterStrings.length) {
filter_combs[iFilter] = 0;
changed = true;
}
if (filterMaxRange_texts[iFilter] < filterMinRange_texts[iFilter]) {
filterMinRange_texts[iFilter] = DEFAULT_MIN;
filterMaxRange_texts[iFilter] = DEFAULT_MAX;
changed = true;
} else {
if (filterMinRange_texts[iFilter] < DEFAULT_MIN) {
filterMinRange_texts[iFilter] = DEFAULT_MIN;
changed = true;
}
if (filterMaxRange_texts[iFilter] > DEFAULT_MAX) {
filterMaxRange_texts[iFilter] = DEFAULT_MAX;
changed = true;
}
}
}
for (int iHeat = 0; iHeat < heatmapColor_combs.length; iHeat++) {
if (heatmapColor_combs[iHeat] < 0 || heatmapColor_combs[iHeat] >= HEATMAPS.length) {
heatmapColor_combs[iHeat] = HEATMAPS.length - 1;
changed = true;
}
}
if (heatmap_radio < 0 || heatmap_radio >= HEATMAPOPTS.length) {
heatmap_radio = DEFAULT_CHOICE;
changed = true;
}
for (int iTOS = 0; iTOS < matrixFT_spin.length; iTOS++) {
if (matrixFT_spin[iTOS] < MINFT || matrixFT_spin[iTOS] > MAXFT) {
matrixFT_spin[iTOS] = DEFAULT_FT;
changed = true;
}
}
return changed;
}
static void retrieveOptions() {
// This is important to remove all previous options because options is
// static
options = DO_NOTHING;
for (int iAlign = 0; iAlign < align_chckes.length; iAlign++)
if (imps[iAlign] != null && align_chckes[iAlign]) {
options |= DO_ALIGN;
break;
}
if (scatter_chck)
options |= DO_SCATTER;
if (matrix_chck)
options |= DO_MATRIX;
for (int iHeat = 0; iHeat < heatmap_chckes.length; iHeat++) {
if (heatmap_chckes[iHeat]) {
options |= DO_HEAT;
break;
}
}
if ((options & RUN_HEAT) != 0)
options |= LIST_HEATMAPOPTS[heatmap_radio];
for (int iMetric = 0; iMetric < metric_chckes.length; iMetric++)
if (metric_chckes[iMetric]) {
options |= LIST_METRICS[iMetric];
options |= DO_RESULTTABLE;
}
for (int iMetric = 0; iMetric < other_chckes.length; iMetric++)
if (other_chckes[iMetric]) {
options |= LIST_OTHERS[iMetric];
options |= DO_RESULTTABLE;
}
if (custom_chck)
options |= DO_CUSTOM;
for (int iMetric = 0; iMetric < outputMetric_chckes.length; iMetric++)
if (outputMetric_chckes[iMetric])
options |= LIST_OUTPUTMETRICS[iMetric];
for (int iMetric = 0; iMetric < outputOpt_chckes.length; iMetric++)
if (outputOpt_chckes[iMetric])
options |= LIST_OUTPUTOTHERS[iMetric];
// I don't know why I put this condition here, might be for a reason
// We will see.
// reset options to zero each time the options are retrieved
// if((options&RUN_METRICS_TOS)!=0)
// options |= DO_RESULTTABLE ;
}
/**
* This method is used to pass the filter strings to cell filter dialog
*
* @return a copy of <code>FILTERSTRINGS</code>
*/
public static String[] getFilterStrings() {
return filterStrings.clone();
}
@SuppressWarnings("unchecked")
public static<T> T[] newArray(Class<T> clazz, T value, int length){
T[] result = (T[]) Array.newInstance(clazz, length);
for (int i = 0; i < length; i++)
result[i] = value;
return result;
}
public static double[] newArray(double value, int length) {
double[] result = new double[length];
for (int i = 0; i < length; i++)
result[i] = value;
return result;
}
public static int[] newArray(int value, int length) {
int[] result = new int[length];
for (int i = 0; i < length; i++)
result[i] = value;
return result;
}
public static boolean[] newArray(boolean value, int length) {
boolean[] result = new boolean[length];
for (int i = 0; i < length; i++)
result[i] = value;
return result;
}
public static int[] newArray(int length) {
int[] result = new int[length];
for (int i = 0; i < length; i++)
result[i] = i;
return result;
}
public static int[][] newArray(int value, int height, int width) {
int[][] result = new int[height][width];
for (int i = 0; i < height; i++)
for (int j = 0; j < width; j++)
result[i][j] = value;
return result;
}
public static int[][] newArray(int[] arr, int length) {
int[][] result = new int[length][arr.length];
for (int i = 0; i < length; i++)
result[i] = arr.clone();
return result;
}
public static double[][] newArray(double value, int height, int width) {
double[][] result = new double[height][width];
for (int i = 0; i < height; i++)
for (int j = 0; j < width; j++)
result[i][j] = value;
return result;
}
public static double[][] newArray(double[] arr, int length) {
double[][] result = new double[length][arr.length];
for (int i = 0; i < length; i++)
result[i] = arr.clone();
return result;
}
public static float[][] newArray(float value, int height, int width) {
float[][] result = new float[height][width];
for (int i = 0; i < height; i++)
for (int j = 0; j < width; j++)
result[i][j] = value;
return result;
}
public static float[][] newArray(float[] arr, int length) {
float[][] result = new float[length][arr.length];
for (int i = 0; i < length; i++)
result[i] = arr.clone();
return result;
}
public static ByteProcessor roi2mask(ImageProcessor ip, Roi[] rois) {
if (ip == null)
return null;
int w = ip.getWidth();
int h = ip.getHeight();
if (rois == null || rois.length < 1)
return new ByteProcessor(w, h);
ByteProcessor result = new ByteProcessor(w, h);
result.setColor(Color.WHITE);
for (int i = 0; i < rois.length; i++) {
if (rois[i] != null)
result.fill(rois[i]);
}
result.resetRoi();
return result;
}
public static ImagePlus roiManager2Mask(ImagePlus imp) {
RoiManager roiManager = RoiManager.getInstance2();
if (roiManager == null) {
return null;
}
Roi[] rois = roiManager.getRoisAsArray();
int nSlices = 1, nFrames = 1, nChannels = 1, width = 0, height = 0;
if (imp == null) {
for (Roi roi : rois) {
if (nSlices < roi.getZPosition())
nSlices = roi.getZPosition();
if (nFrames < roi.getTPosition())
nFrames = roi.getTPosition();
if (nChannels < roi.getCPosition())
nChannels = roi.getCPosition();
if (roi.getImage() != null) {
if (width < roi.getImage().getWidth())
width = roi.getImage().getWidth();
if (height < roi.getImage().getHeight())
height = roi.getImage().getHeight();
}
}
if (width == 0)
width = 400;
if (height == 0)
height = 400;
} else {
width = imp.getWidth();
height = imp.getHeight();
nSlices = imp.getNSlices();
nFrames = imp.getNFrames();
nChannels = imp.getNChannels();
}
Map<Integer, List<Roi>> roiMap = new HashMap<Integer, List<Roi>>();
for (Roi roi : rois) {
List<Roi> list = roiMap.get(roi.getPosition());
if (list == null)
list = new ArrayList<Roi>();
list.add(roi);
roiMap.put(roi.getPosition(), list);
}
Roi[] allRois = roiMap.get(0) == null ? null : roiMap.get(0).toArray(new Roi[0]);
// Fixed a bug in 1.1.3 the second nChannels should read nFrames
imp = IJ.createHyperStack(ImageInfo.ROI_MANAGER, width, height, nChannels, nSlices, nFrames, 8);
ImageStack impStack = imp.getStack();
if (nSlices != 1 || nFrames != 1 || nChannels != 1 && !doROIall) {
boolean reporter;
reporter = false;
if (allRois != null) {
String str = "The following ROI(s) are not associated with a particular slice (they are applied to all slices): \n";
for (Roi roi : allRois) {
str += roi.getName() + "\n";
reporter = true;
}
if (reporter)
ExceptionHandler.addWarning(str);
}
reporter = false;
String warning = "The following ROI(s) are not included (index out of range): \n";
for (Roi roi : rois) {
if (roi.getPosition() > impStack.size()) {
warning += roi.getName() + "\n";
reporter = true;
}
}
if (reporter)
ExceptionHandler.addWarning(warning);
reporter = false;
warning = "The following ROI(s) might be mismatched (associated with hyperstack): \n";
for (Roi roi : rois) {
if (roi.getCPosition() > 1 || (roi.getZPosition() > 1 && roi.getTPosition() > 1)) {
warning += roi.getName() + "\n";
reporter = true;
}
}
if (reporter)
ExceptionHandler.addWarning(warning);
}
int index;
for (int channel = 1; channel <= nChannels; channel++)
for (int slice = 1; slice <= nSlices; slice++)
for (int frame = 1; frame <= nFrames; frame++) {
index = (frame - 1) * nChannels * nSlices + (slice - 1) * nChannels + channel;
if(doROIall){
impStack.setProcessor(roi2mask(impStack.getProcessor(index), rois), index);
}
else{
List<Roi> list = roiMap.get(index);
if (list != null) {
if(allRois!=null){
Roi[] thisRois = new Roi[list.size() + allRois.length];
System.arraycopy(allRois, 0, thisRois, 0, allRois.length);
System.arraycopy(list.toArray(), 0, thisRois, allRois.length, list.size());
impStack.setProcessor(roi2mask(impStack.getProcessor(index), thisRois), index);
}else{
impStack.setProcessor(roi2mask(impStack.getProcessor(index), list.toArray(new Roi[0])), index);
}
} else {
impStack.setProcessor(roi2mask(impStack.getProcessor(index), allRois), index);
}
}
}
imp.setStack(impStack);
return imp;
}
public static void resetParams() {
Arrays.fill(align_chckes, DEFAULT_BOOLEAN);
Arrays.fill(alignThold_combs, DEFAULT_CHOICE);
didAlignment = false;
// cell filters parameters
Arrays.fill(filterMinSize_texts, DEFAULT_MIN);
Arrays.fill(filterMaxSize_texts, DEFAULT_MAX);
// filterChoices, minRanges, maxRanges, backRatios should have the same
// length
// we don't use default choice here, but default choice is still used in
// smart recording
// This is because the judgment to record is based on minRanges and
// maxRanges, so the filter choice doesn't matter
filter_combs = staticFilterChoices.clone();
Arrays.fill(filterMinRange_texts, DEFAULT_MIN);
Arrays.fill(filterMaxRange_texts, DEFAULT_MAX);
Arrays.fill(filterBackRatio_texts, DEFAULT_BOOLEAN);
adFilterChoices.clear();
adMinRanges.clear();
adMaxRanges.clear();
adBackRatios.clear();
// roiCells might be problematic in parallel streams/multiple threads
roiCells = null;
waterShed_chck = DEFAULT_BOOLEAN;
// scatterplot parameter
scatter_chck = DEFAULT_BOOLEAN;
// matrix heat map parameter
matrix_chck = DEFAULT_BOOLEAN;
matrixMetric_comb = DEFAULT_CHOICE;
matrixStats_comb = DEFAULT_CHOICE;
Arrays.fill(matrixFT_spin, DEFAULT_FT);
// heatmaps parameters
Arrays.fill(heatmap_chckes, DEFAULT_BOOLEAN);
heatmap_radio = DEFAULT_CHOICE;
// This might not be the same as the initialization
for (int i = 0; i < heatmapColor_combs.length; i++)
heatmapColor_combs[i] = i;
// metric parameters
Arrays.fill(metric_chckes, DEFAULT_BOOLEAN);
Arrays.fill(other_chckes, DEFAULT_BOOLEAN);
Arrays.fill(metricThold_radios, DEFAULT_CHOICE);
for (int[] fts : allFT_spins)
Arrays.fill(fts, DEFAULT_FT);
allTholds = null;
// mTOS parameters
// mTOSscale = DEFAULT_CHOICE;
// DistancesX parameters
// whichDist = DEFAULT_CHOICE;
// Arrays.fill(numOfDistFTs,DEFAULT_FT);
// Arrays.fill(whichDistTholds,DEFAULT_CHOICE);
// Custom parameters
customCode_text = StringCompiler.getDefaultCode();
custom_chck = DEFAULT_BOOLEAN;
// Output parameters
Arrays.fill(outputMetric_chckes, DEFAULT_BOOLEAN);
Arrays.fill(outputOpt_chckes, DEFAULT_BOOLEAN);
}
public static void chooseAll() {
Arrays.fill(align_chckes, true);
// didAlignment = true;
// roiCells might be problematic in parallel streams/multiple threads
waterShed_chck = true;
// scatterplot parameter
scatter_chck = true;
matrix_chck = true;
// heatmaps parameters
Arrays.fill(heatmap_chckes, true);
// metric parameters
Arrays.fill(metric_chckes, true);
Arrays.fill(other_chckes, true);
// Custom parameters
custom_chck = true;
// Output parameters
Arrays.fill(outputMetric_chckes, true);
Arrays.fill(outputOpt_chckes, true);
}
public static void closeAllWindows() {
Frame currentFrame = WindowManager.getFrontWindow();
ImageWindow currentImage = WindowManager.getCurrentWindow();
for (Frame frame : allFrames) {
if (frame != null && (frame instanceof Editor)) {
((Editor) frame).close();
if (((Editor) frame).fileChanged())
return;
}
}
ImageJ ij = IJ.getInstance();
if (ij != null && ij.quitting() && IJ.getApplet() == null)
return;
for (Frame frame : allFrames) {
if (frame == null || !frame.isVisible())
continue;
if ((frame instanceof PlugInFrame) && !(frame instanceof Editor)) {
// frame.setVisible(false);
((PlugInFrame) frame).close();
} else if (frame instanceof TextWindow) {
// frame.setVisible(false);
((TextWindow) frame).close();
} else {
// frame.setVisible(false);
frame.dispose();
WindowManager.removeWindow(frame);
}
}
allFrames.clear();
if (currentFrame.isVisible())
WindowManager.setWindow(currentFrame);
if (currentImage.isVisible())
WindowManager.setCurrentWindow(currentImage);
}
public static void saveAllWindows(String dir) {
if (!(new File(dir)).isDirectory())
return;
Frame currentFrame = WindowManager.getFrontWindow();
ImageWindow currentImage = WindowManager.getCurrentWindow();
for (Iterator<Frame> iterator = allFrames.iterator(); iterator.hasNext();) {
Frame frame = iterator.next();
if (frame == null || !frame.isVisible()) {
iterator.remove();
continue;
}
WindowManager.setWindow(frame);
String name = frame.getTitle().replaceAll("\\.", "_");
if (frame instanceof TextWindow)
IJ.saveAs("Results", dir + name + ".txt");
else if (frame instanceof ImageWindow) {
WindowManager.setCurrentWindow((ImageWindow) frame);
IJ.saveAs("tif", dir + name + ".tif");
} else if (frame instanceof RoiManager)
IJ.saveAs("zip", dir + name + ".zip");
else {
IJ.error("Unknown window type cannot be saved");
WindowManager.setWindow(frame);
return;
}
}
WindowManager.setWindow(currentFrame);
WindowManager.setCurrentWindow(currentImage);
}
public static void cleanWindow() {
for (Iterator<Frame> iterator = allFrames.iterator(); iterator.hasNext();) {
Frame frame = iterator.next();
if (frame == null || !frame.isVisible()) {
iterator.remove();
continue;
}
}
}
public static synchronized void addWindow(Frame win) {
if (win != null)
allFrames.addElement(win);
}
public static synchronized void addWindow(ImagePlus imp) {
if (imp != null)
addWindow(imp.getWindow());
}
public static ResultsTable matrix2ResultsTable(double[][] data, double[] x, double[] y, boolean invertX,
boolean invertY) {
String[] strX = null, strY = null;
if (x != null) {
strX = new String[data.length];
for (int i = 0; i < strX.length; i++)
strX[i] = Double.toString(x[i]);
}
if (y != null) {
strY = new String[data[0].length];
for (int i = 0; i < strY.length; i++)
strY[i] = Double.toString(y[i]);
}
return matrix2ResultsTable(data, strX, strY, invertX, invertY);
}
public static ResultsTable matrix2ResultsTable(double[][] data, float[] x, float[] y, boolean invertX,
boolean invertY) {
String[] strX = null, strY = null;
if (x != null) {
strX = new String[data.length];
for (int i = 0; i < strX.length; i++)
strX[i] = Float.toString(x[i]);
}
if (y != null) {
strY = new String[data[0].length];
for (int i = 0; i < strY.length; i++)
strY[i] = Float.toString(y[i]);
}
return matrix2ResultsTable(data, strX, strY, invertX, invertY);
}
/**
* Convert a double matrix to a ResultsTable
*
* @param data
* must be a matrix, cannot be jagged array
* @param x
* @param y
* @param invertX
* @param invertY
* @return
*/
public static ResultsTable matrix2ResultsTable(double[][] data, String[] x, String[] y, boolean invertX,
boolean invertY) {
if (data == null)
return null;
ResultsTable rt = new ResultsTable();
if (x == null) {
x = new String[data.length];
for (int i = 0; i < x.length; i++)
x[i] = Integer.toString(i + 1);
}
if (y == null) {
y = new String[data[0].length];
for (int i = 0; i < y.length; i++)
y[i] = Integer.toString(i + 1);
}
int increX, startX, endX, increY, startY, endY;
if (invertX) {
increX = -1;
startX = data.length - 1;
endX = -1;
} else {
increX = 1;
startX = 0;
endX = data.length;
}
if (invertY) {
increY = -1;
startY = data[0].length - 1;
endY = -1;
} else {
increY = 1;
startY = 0;
endY = data[0].length;
}
rt.incrementCounter();
rt.addLabel("");
for (int iColumn = startX; iColumn != endX; iColumn += increX) {
rt.addValue(Integer.toString(iColumn + 1), x[iColumn]);
}
for (int iRow = startY; iRow != endY; iRow += increY) {
rt.incrementCounter();
rt.addLabel(y[iRow]);
for (int iColumn = startX; iColumn != endX; iColumn += increX) {
rt.addValue(Integer.toString(iColumn + 1), data[iColumn][iRow]);
}
}
rt.showRowNumbers(false);
return rt;
}
public static <E> Object[] other2objArray(E[] array) {
if (array == null)
return null;
Object[] objs = new Object[array.length];
for (int i = 0; i < objs.length; i++)
objs[i] = array[i];
return objs;
}
public static Object[] double2objArray(double[] array) {
if (array == null)
return null;
Object[] objs = new Object[array.length];
for (int i = 0; i < objs.length; i++)
objs[i] = array[i];
return objs;
}
public static <E> E[] flipArray(E[] array) {
if (array == null)
return null;
E temp;
for (int i = 0; i < array.length / 2; i++) {
temp = array[array.length - 1 - i];
array[array.length - 1 - i] = array[i];
array[i] = temp;
}
return array;
}
public static float[] obj2floatArray(Object[] array) {
if (array == null)
return null;
float[] objs = new float[array.length];
for (int i = 0; i < objs.length; i++)
try {
objs[i] = (float) array[i];
} catch (Exception e) {
objs[i] = Float.NaN;
}
return objs;
}
public static double round(double value, int places) {
if (places < 0)
places = 0;// throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
public static float round(float value, int places) {
if (places < 0)
places = 0;// throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.floatValue();
}
static String[] makeAllFilters(int nReporters) {
String[] result = new String[SHAPE_FILTERS.length + INTEN_FILTERS.length * nReporters];
System.arraycopy(SHAPE_FILTERS, 0, result, 0, SHAPE_FILTERS.length);
for (int iChannel = 0; iChannel < nReporters; iChannel++)
for (int iFilter = 0; iFilter < INTEN_FILTERS.length; iFilter++)
result[SHAPE_FILTERS.length + iFilter + INTEN_FILTERS.length * iChannel] = makeIntFilterString(
INTEN_FILTERS[iFilter], iChannel);
return result;
}
static String makeIntFilterString(String prefix, int iChannel) {
return prefix + " (Ch." + (iChannel + 1) + ")";
}
static String[] makeImgLabels(int nChannel) {
String[] result = new String[nChannel];
for (int i = 1; i < nChannel; i++)
result[i - 1] = "Reporter " + i +" (Ch."+i+")";
result[nChannel - 1] = "Cell identification input";
return result;
}
public static void setPlugIn(Class<?> clazz) {
EzColocalization = clazz;
PluginStatic.pluginName = clazz.getSimpleName().replace("_", " ");
}
public static String getPlugInName() {
return pluginName;
}
public static Class<?> getPlugInClass(){
return EzColocalization;
}
public static String getInfo() {
return getPlugInName() + "(" + VERSION + ")" + ", Please contact Han Lim at " + CONTACT + " for any question";
}
static String[] getMatrixMetrics(int dimension) {
if (dimension == 2)
return MatrixCalculator.getAllMetrics();
else if (dimension == 3)
return MatrixCalculator3D.getAllMetrics();
else
return null;
}
/**
* Return the selected method;
* return null if the method cannot be found
* @param name
* @return
*/
public static Method getMethod(String name){
if(THRESHOLD_METHODS.containsKey(name))
return THRESHOLD_METHODS.get(name);
else
return null;
}
}
| 36,563 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
PluginConstants.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/main/PluginConstants.java | package ezcol.main;
/**
* This interface contains all static final options It is not recommended to
* implement this interface It is used to group all options together
*
* @author Huanjie Sheng
*
*/
public interface PluginConstants {
public static final int DO_NOTHING = 0;
// The maximum index is 0x80000000;
// All static final int must be different if it starts with DO_
public static final int DO_MATRIX = 8;
public static final int DO_PCC = 16;
public static final int DO_SRC = 32;
public static final int DO_MCC = 64;
public static final int DO_ICQ = 128;
// calculate the distance between center to the nearest pole
public static final int DO_AVGINT = 256;
public static final int DO_ALIGN = 16384;
public static final int DO_SCATTER = 0x40000000;
public static final int DO_HEAT = 0x80000;
// heatmap options
public static final int DO_HEAT_CELL = 0x10000;
public static final int DO_HEAT_IMG = 0x20000;
public static final int DO_HEAT_STACK = 0x40000;
// TOS options
public static final int DO_LINEAR_TOS = 0x200000;
public static final int DO_LOG2_TOS = 0x400000;
// This has been removed from the UI
public static final int DO_LN_TOS = 0x800000;
// output metrics
public static final int DO_RESULTTABLE = 0x1000000;
public static final int DO_SUMMARY = 0x2000000;
public static final int DO_HIST = 0x10000000;
public static final int DO_CUSTOM = 0x20000000;
// output options
public static final int DO_MASKS = 4096;
public static final int DO_ROIS = 8192;
// Here are the combinations of required outputs
// They don't have to be different
// The combination determines whether specific class needs to be run
public static final int DO_TOS = DO_LINEAR_TOS | DO_LOG2_TOS;
public static final int RUN_ALIGN = DO_ALIGN;
public static final int RUN_HIST = DO_HIST;
public static final int RUN_SCATTER = DO_SCATTER;
public static final int RUN_HEAT = DO_HEAT;
public static final int RUN_MATRIX = DO_MATRIX;
public static final int RUN_TOS = DO_TOS;
public static final int RUN_METRICS = DO_TOS | DO_PCC | DO_SRC | DO_AVGINT | DO_MCC | DO_ICQ | DO_MCC | DO_CUSTOM;
public static final int RUN_CDP = RUN_MATRIX | RUN_METRICS | RUN_SCATTER;
public static final int RUN_IDCELLS = RUN_CDP | DO_HEAT_CELL | DO_MASKS | DO_ROIS;
public static final int RUN_SUMMARY = DO_SUMMARY;
public static final int RUN_RTS = DO_RESULTTABLE | DO_HIST | RUN_SUMMARY;
public static final int OPTS_HEAT = DO_HEAT_CELL | DO_HEAT_IMG | DO_HEAT_STACK;
public static final int OPTS_TOS = DO_LINEAR_TOS | DO_LOG2_TOS | DO_LN_TOS;
public static final int OPTS_OUTPUT = DO_RESULTTABLE | DO_SUMMARY | DO_HIST | DO_CUSTOM;
public static final int RQD_REPORTER = RUN_HEAT | DO_AVGINT | DO_CUSTOM | RUN_HIST | RUN_SUMMARY;
public static final int RQD_ALL_REPORTERS = RUN_MATRIX | RUN_SCATTER | DO_TOS | DO_PCC | DO_SRC | DO_MCC | DO_ICQ;
public static final int RQD_CELLID = RUN_ALIGN | DO_HEAT_CELL | DO_MASKS | DO_ROIS;
// Parameters
public static final int DEFAULT_MIN_FT = 1;
public static final int DEFAULT_MAX_FT = 99;
public static final double DEFAULT_ROLLINGBALL_SIZE = 50.0;
public static final double DEFAULT_MIN = 0.0;
public static final double DEFAULT_MAX = Double.POSITIVE_INFINITY;
public static final int DEFAULT_FT = 10;
public static final int DEFAULT_CHOICE = 0;
public static final boolean DEFAULT_BOOLEAN = false;
// Masks to avoid interference
public static final int MASK_ALIGNMENT = RUN_ALIGN;
public static final int MASK_VISUAL = RUN_HEAT | OPTS_HEAT | RUN_SCATTER | RUN_MATRIX;
public static final ImageInfo NOIMAGE = new ImageInfo(ImageInfo.NONE, ImageInfo.NONE_ID, 24);
public static final ImageInfo ROIMANAGER_IMAGE = new ImageInfo(ImageInfo.ROI_MANAGER, ImageInfo.ROI_MANAGER_ID, 24);
}
| 3,799 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
ImageInfo.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/main/ImageInfo.java | /*
* ImageInfo.java modified from ImgInfo.java
*
* Created on 14 janvier 2008, 21:11
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package ezcol.main;
import java.awt.Component;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JList;
import ij.*;
/**
*
* @author Fabrice Cordelies
*/
public class ImageInfo implements Comparable<ImageInfo>{
public static int default_length = 25;
public static final String NONE = "*None*";
public static final String ROI_MANAGER = "ROI Manager";
public static final int NONE_ID = 0;
public static final int ROI_MANAGER_ID = 1;
public String title;
public int ID;
public int bitDepth;
public static final ImageInfoListCellRenderer RENDERER = new ImageInfoListCellRenderer();
/** Creates a new instance of ImgInfo */
public ImageInfo() {
this.title=NONE;
this.ID=NONE_ID;
//Surprisingly, ImageJ does not have a static final field for bitDepth
//What a shame!
this.bitDepth=24;
}
/** Creates a new instance of ImgInfo */
public ImageInfo(String title,int ID,int bitDepth) {
this.title=title;
this.ID=ID;
this.bitDepth=bitDepth;
}
public ImageInfo(ImagePlus imp)
{
this.title=imp.getTitle();
this.ID=imp.getID();
this.bitDepth=imp.getBitDepth();
}
/**
* Do not check image title or bitdepth but only image ID
* @param imp
* @return
*/
public boolean equalID(ImagePlus imp)
{
//if(imp.getTitle()==title&&imp.getID()==ID&&imp.getBitDepth()==depth)
if(imp.getID()==ID)
return true;
else
return false;
}
public boolean equal(ImageInfo imp)
{
if(imp.title==this.title&&imp.ID==this.ID&&imp.bitDepth==this.bitDepth)
return true;
else
return false;
}
/*@Override
public String toString(){
return getTrimTitle(default_length);
}*/
public String getTrimTitle(int length){
if(title==null)
return title;
if(title.length()<length)
return title;
return title.substring(0, length);
}
@Override
public int compareTo(ImageInfo o) {
// TODO Auto-generated method stub
return equal(o)?0:this.ID-o.ID;
}
}
/**
* Custom Renderer for ImageInfo being used in JCombobox
* @author Huanjie Sheng
*
*/
@SuppressWarnings("serial")
class ImageInfoListCellRenderer extends DefaultListCellRenderer {
@SuppressWarnings("rawtypes")
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
if (value instanceof ImageInfo) {
value = ((ImageInfo)value).getTrimTitle(ImageInfo.default_length);
}
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
return this;
}
}
| 3,108 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
FilesIO.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/files/FilesIO.java | package ezcol.files;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import ezcol.debug.ExceptionHandler;
import ezcol.main.PluginStatic;
import ij.IJ;
import ij.ImagePlus;
import ij.io.Opener;
/**
* This class contains static utility IO method to read files for the plugin
*
* @author Huanjie Sheng
*
*/
public class FilesIO {
public static final String VERSION = "version";
public static final String BUILD_TIME = "buildtime";
public static final String JAVA_VERSION = "javaVersion";
public static final String IMAGEJ_VERSION = "imagejVersion";
private static final String IMAGE_DIRECTORY = "resources/images/";
public static URL getResource(String name) {
if (name.charAt(0) != '/')
name = "/" + IMAGE_DIRECTORY + name;
return FilesIO.class.getResource(name);
}
/**
* @param path
* the relative path of the file starting with '/'
* @param show
* @return
* @throws IOException
* @throws URISyntaxException
* @see https://imagej.nih.gov/ij/plugins/download/JAR_Resources_Demo.java
*/
public static ImagePlus getImagePlus(String path, boolean show) throws IOException, URISyntaxException {
/*
* URL url = FilesIO.class.getResource("/" + IMAGE_DIRECTORY + name); if
* (url == null){ return null; }
*/
String name = path;
if (path.lastIndexOf('/') != -1)
name = path.substring(path.lastIndexOf('/') + 1);
ImagePlus imp = null;
InputStream is = FilesIO.class.getResourceAsStream(path);
if (is != null) {
Opener opener = new Opener();
imp = opener.openTiff(is, name);
if (imp != null && show)
imp.show();
return imp;
} else {
throw new IOException("Cannot locate " + path);
}
}
public static void openTiffs(boolean show) throws IOException, URISyntaxException {
String[] strs = null;
try {
//I use EzColocalization_.class here because duplication of
//plugin name is not allowed in ImageJ
strs = getResourceListing(PluginStatic.getPlugInClass(), IMAGE_DIRECTORY);
} catch (URISyntaxException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ExceptionHandler.handleException(e);
IJ.log(""+e);
}
boolean hasImg = false;
for (String str : strs) {
if (isExtension(str, "tif")) {
getImagePlus("/" + IMAGE_DIRECTORY + str, show);
hasImg = true;
}
}
if (!hasImg){
IJ.error("Test images are lost");
}
}
/**
*
* @param clazz
* @param path
* @return
* @throws URISyntaxException
* @throws IOException
* Retrieved from
* http://www.uofr.net/~greg/java/get-resource-listing.html
*/
public static String[] getResourceListing(Class clazz, String path) throws URISyntaxException, IOException {
//Looking for jar using path might end up in a different jar
//We just assume we are using this jar
/*URL dirURL = clazz.getClassLoader().getResource(path);
if (dirURL != null && dirURL.getProtocol().equals("file")) {
// A file path: easy enough
return new File(dirURL.toURI()).list();
}
if (dirURL == null) {
//In case of a jar file, we can't actually find a directory. Have
// to assume the same jar as clazz.
String me = clazz.getName().replace(".", "/") + ".class";
dirURL = clazz.getClassLoader().getResource(me);
}*/
//This will be a bug if and only if there exists another jar
//which has exactly the same relative path of this class
String me = clazz.getName().replace(".", "/") + ".class";
URL dirURL = clazz.getClassLoader().getResource(me);
if (dirURL.getProtocol().equals("jar")) {
/* A JAR path */
String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!"));
//strip out only the JAR file
JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
Enumeration<JarEntry> entries = jar.entries(); // gives ALL entries
// in jar
Set<String> result = new HashSet<String>(); // avoid duplicates in
// case it is a
// subdirectory
while (entries.hasMoreElements()) {
String name = entries.nextElement().getName();
if (name.startsWith(path)) { // filter according to the path
String entry = name.substring(path.length());
int checkSubdir = entry.indexOf("/");
if (checkSubdir >= 0) {
// if it is a subdirectory, we just return the directory
// name
entry = entry.substring(0, checkSubdir);
}
result.add(entry);
}
}
return result.toArray(new String[result.size()]);
}else if(dirURL.getProtocol().equals("file")) {
// test mode and the directory is pointed to the class in bin
File folder = new File(dirURL.getPath().substring(1, dirURL.getPath().indexOf("bin") + 4) + IMAGE_DIRECTORY);
File[] listOfFiles = folder.listFiles();
Set<String> result = new HashSet<String>(); // avoid duplicates in
// case it is a
// subdirectory
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
result.add(listOfFiles[i].getName());
}
}
return result.toArray(new String[result.size()]);
}
throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
}
private static boolean isExtension(String name, String extension) {
int i = name.lastIndexOf('.');
if (i > 0 && i < name.length() - 1)
if (extension.equalsIgnoreCase(name.substring(i + 1).toLowerCase()))
return true;
return false;
}
public static String getPluginProperties() {
InputStream fins = FilesIO.class.getResourceAsStream("/project.properties");
Properties prop = new Properties();
if (fins == null)
return ("Plugin properties not found");
try {
prop.load(fins);
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
return ("Error while loading plugin properties");
}
String properties = "";
if (prop.getProperty(VERSION) != null)
properties += "Plugin Version: " + prop.getProperty(VERSION) + "\n";
if (prop.getProperty(BUILD_TIME) != null)
properties += "Built on: " + prop.getProperty(BUILD_TIME) + "\n";
properties += "------------------------------------------------- \n" + "Recommended Environment: \n";
if (prop.getProperty(JAVA_VERSION) != null)
properties += "Java Version: " + prop.getProperty(JAVA_VERSION) + "\n";
if (prop.getProperty(IMAGEJ_VERSION) != null)
properties += "ImageJ Version: " + prop.getProperty(IMAGEJ_VERSION) + "\n";
properties += "------------------------------------------------- \n" + "Your System Properties: \n";
properties += "Java Version: " + System.getProperty("java.version") + "\n";
properties += "ImageJ version: " + IJ.getVersion() + "\n";
properties += "Operating System: " + System.getProperty("os.name") + " (" + System.getProperty("os.version")
+ ")\n";
return properties;
}
public static String getPluginProperties(String key) {
InputStream fins = FilesIO.class.getResourceAsStream("project.properties");
Properties prop = new Properties();
if (fins == null)
return null;
try {
prop.load(fins);
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
return null;
}
if (prop.getProperty(key) != null)
return prop.getProperty(key);
else
return null;
}
}
| 7,583 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
CellDataProcessor.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/cell/CellDataProcessor.java | package ezcol.cell;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import ezcol.debug.ExceptionHandler;
import ij.measure.Calibration;
import ij.process.ImageProcessor;
import ij.process.ShortProcessor;
public class CellDataProcessor {
private int width, height, pixelCount, numOfCell;
private CellData[][] cellCs;
private int[] numOfPixel;
private int[][] pixelMask;
private float[][][] pixelCs;
private Calibration cal;
private List<Object> cellIDs;
private String prefix;
/*
* public boolean mask2data(final ImageProcessor c1, final ImageProcessor
* c2,boolean rank) { if(c1==null||c2==null) return false;
*
* if(c1.getWidth()!=c2.getWidth()||c1.getHeight()!=c2.getHeight()) return
* false;
*
* numOfCell=1; pixelC1=getFloatArray(c1); pixelC2=getFloatArray(c2); int
* width=c1.getWidth(),height=c1.getHeight(); float[] data1=new
* float[width*height],data2=new float[width*height]; double[] x=new
* double[width*height],y=new double[width*height]; int count=0;
* if(cal==null){ for(int w=0;w<width;w++){ for(int h=0;h<height;h++){
* data1[count]=pixelC1[w][h]; data2[count]=pixelC2[w][h]; x[count]=w;
* y[count]=h; count++; } } }else{ for(int w=0;w<width;w++){ for(int
* h=0;h<height;h++){ data1[count]=pixelC1[w][h];
* data2[count]=pixelC2[w][h]; //coordinates need to be calibrated
* x[count]=w*cal.pixelWidth; y[count]=h*cal.pixelHeight; count++; } } }
* cellC1=new CellData[1]; cellC2=new CellData[1]; cellC1[0]=new
* CellData(data1,x,y); cellC2[0]=new CellData(data2,x.clone(),y.clone());
* if(rank){ cellC1[0].sort(); cellC2[0].sort(); }
*
* return true; }
*/
@Deprecated
public int mask2data(ImageProcessor cell, ImageProcessor c1, ImageProcessor c2, boolean rank) {
return mask2data(cell, new ImageProcessor[] { c1, c2 }, rank);
}
public int mask2data(ImageProcessor cell, ImageProcessor[] chs, boolean rank) {
if (chs == null)
return 1;
ImageProcessor ic = null;
for (int i = 0; i < chs.length; i++) {
if (chs[i] != null) {
if ((ic != null) && (ic.getWidth() != chs[i].getWidth() || ic.getHeight() != chs[i].getHeight()))
return 1;
ic = chs[i];
}
}
if (ic == null)
return 1;
width = ic.getWidth();
height = ic.getHeight();
for (int i = 0; i < chs.length; i++) {
if (chs[i] == null)
chs[i] = new ShortProcessor(width, height);
}
int countCell = countMask2NumOfCell(cell);
if (countCell < 0) {
numOfCell = 1;
numOfPixel = new int[] { ic.getPixelCount() };
handleCellData(chs, rank);
} else if (countCell == 0){
cellCs = null;
numOfPixel = null;
ExceptionHandler.addWarning(Thread.currentThread(), "No cell is found based on the selected filters on some slices.\nApply ROIs to all slices in Settings->Parameters->Apply ROIs to all slices.");
return 2;
} else {
iniNumOfPixel();
pixelCs = new float[chs.length][][];
for (int i = 0; i < pixelCs.length; i++)
pixelCs[i] = getFloatArray(chs[i]);
iniCellCdata(chs.length);
handleCellData(rank);
}
for (int iChannel = 0; iChannel < cellCs.length; iChannel++) {
for (int iCell = 0; iCell < cellCs[iChannel].length; iCell++) {
cellCs[iChannel][iCell].setLabel(prefix + " cell " + (iCell + 1) + " (Ch." + (iChannel + 1) + ")");
}
}
return 0;
}
private int countMask2NumOfCell(ImageProcessor cell) {
numOfCell = 0;
if (cell == null)
return -1;
int width = cell.getWidth();
int height = cell.getHeight();
if (width != this.width || height != this.height)
return 0;
pixelCount = cell.getPixelCount();
pixelMask = cell.getIntArray();
Set<Integer> setOfIDs = new HashSet<Integer>();
for (int w = 0; w < width; w++) {
for (int h = 0; h < height; h++) {
if (pixelMask[w][h] == 0)
continue;
setOfIDs.add(pixelMask[w][h]);
}
}
numOfCell = setOfIDs.size();
cellIDs = Arrays.asList(setOfIDs.toArray());
// The following way is not safe in parallel programming
/*
* cell.resetMinAndMax(); cell.setThreshold(1, cell.getMax(),
* ImageProcessor.NO_LUT_UPDATE); ImageStatistics
* idxStat=ImageStatistics.getStatistics(cell, 272, null); idxStart =
* (int) idxStat.min; idxEnd = (int) idxStat.max; if(idxEnd>=idxStart)
* numOfCell = idxEnd-idxStart+1; else numOfCell = 0;
*/
return numOfCell;
}
/**
* This doesn't work if the image is calibrated
*
* public void setNumOfPixel(final ResultsTable tempCellTable) { float[]
* numOfPixel=null; if(tempCellTable!=null&&tempCellTable.getCounter()>0)
* numOfPixel=tempCellTable.getColumn(tempCellTable.getColumnIndex("Area"));
* if(numOfPixel!=null) this.setNumOfPixel(numOfPixel); }
*/
public CellData[] getCellData(int i) {
if (cellCs == null)
return null;
else if (i >= 0 && i < cellCs.length)
return cellCs[i];
else
return null;
}
public int getNumOfCell() {
return numOfCell;
}
public void setCalibration(Calibration cal) {
this.cal = cal;
}
public Calibration getCalibration() {
return cal;
}
private void iniNumOfPixel() {
numOfPixel = new int[numOfCell];
for (int w = 0; w < width; w++) {
for (int h = 0; h < height; h++) {
if (pixelMask[w][h] == 0)
continue;
numOfPixel[cellIDs.indexOf(pixelMask[w][h])]++;
}
}
}
private void iniCellCdata(int n) {
cellCs = new CellData[n][numOfCell];
for (int iChannel = 0; iChannel < cellCs.length; iChannel++) {
cellCs[iChannel] = new CellData[numOfCell];
if (numOfPixel != null && numOfCell == numOfPixel.length) {
for (int i = 0; i < numOfCell; i++)
cellCs[iChannel][i] = new CellData(numOfPixel[i]);
} else {
for (int i = 0; i < numOfCell; i++)
cellCs[iChannel][i] = new CellData(pixelCount);
}
}
}
private void handleCellData(ImageProcessor[] chs, boolean rank) {
// numOfCell = 1;
// numOfPixel = new int[]{chs[0].getPixelCount()};
cellCs = new CellData[chs.length][1];
for (int i = 0; i < chs.length; i++) {
try{
cellCs[i][0] = new CellData(numOfPixel[0]);
}
catch(Exception ex){
ExceptionHandler.addException(ex);
}
int index = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
cellCs[i][0].setData(chs[i].getPixel(x, y), x, y, index);
index++;
}
}
if (rank)
cellCs[i][0].sort();
}
}
private void handleCellData(boolean rank) {
for (int iChannel = 0; iChannel < cellCs.length; iChannel++) {
int[] tempNumOfPixel = new int[numOfCell];
if (cal == null) {
for (int w = 0; w < width; w++) {
for (int h = 0; h < height; h++) {
if (pixelMask[w][h] == 0)
continue;
int iCell = cellIDs.indexOf(pixelMask[w][h]);
cellCs[iChannel][iCell].setData(pixelCs[iChannel][w][h], w, h, tempNumOfPixel[iCell]);
tempNumOfPixel[iCell]++;
}
}
} else {
for (int w = 0; w < width; w++) {
for (int h = 0; h < height; h++) {
if (pixelMask[w][h] == 0)
continue;
int iCell = cellIDs.indexOf(pixelMask[w][h]);
cellCs[iChannel][iCell].setData(pixelCs[iChannel][w][h], w * cal.pixelWidth,
h * cal.pixelHeight, tempNumOfPixel[iCell]);
tempNumOfPixel[iCell]++;
}
}
}
if (rank) {
for (int iCell = 0; iCell < numOfCell; iCell++) {
cellCs[iChannel][iCell].sort();
}
}
}
}
private float[][] getFloatArray(final ImageProcessor ip) {
if (ip == null) {
float[][] result = new float[width][height];
for (int w = 0; w < width; w++)
for (int h = 0; h < height; h++)
result[w][h] = Float.NaN;
return result;
}
int width = ip.getWidth();
int height = ip.getHeight();
float[][] result = new float[width][height];
float[] cTable = ip.getCalibrationTable();
if (cTable == null) {
for (int w = 0; w < width; w++)
for (int h = 0; h < height; h++)
result[w][h] = ip.getf(w, h);
} else {
for (int w = 0; w < width; w++)
for (int h = 0; h < height; h++)
result[w][h] = cTable[ip.get(w, h)];
}
return result;
}
public void setLabel(String label) {
this.prefix = label;
}
public String getLabel() {
return this.prefix;
}
}
| 8,146 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
CellData.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/cell/CellData.java | package ezcol.cell;
/*
* This class is only for storing pixel values of cells so that the number of pixel
* of each cell could be varied to save memory
*/
public class CellData {
// all data are calibrated
private float[] data;
private double[] x;
private double[] y;
private double[] rank;
private int[] sortedIdx;
private float max;
private float min;
private boolean isSorted;
private String label;
public CellData() {
data = null;
x = null;
y = null;
isSorted = false;
}
public CellData(CellData cellData) {
data = cellData.data.clone();
x = cellData.x.clone();
y = cellData.y.clone();
rank = cellData.rank.clone();
sortedIdx = cellData.sortedIdx.clone();
max = cellData.max;
min = cellData.min;
isSorted = cellData.isSorted;
label = cellData.label;
}
public CellData(int numOfPixel) {
data = new float[numOfPixel];
x = new double[numOfPixel];
y = new double[numOfPixel];
isSorted = false;
}
public CellData(float[] data) {
this.data = data;
this.x = null;
this.y = null;
isSorted = false;
}
public CellData(float[] data, double[] x, double[] y) {
this.data = data;
this.x = x;
this.y = y;
isSorted = false;
}
public void setData(float[] data, double[] x, double[] y) {
this.data = data;
this.x = x;
this.y = y;
isSorted = false;
}
public void setData(float data, int x, int y, int idx) {
if (this.data != null && this.data.length > idx)
this.data[idx] = data;
if (this.x != null && this.x.length > idx)
this.x[idx] = x;
if (this.y != null && this.y.length > idx)
this.y[idx] = y;
isSorted = false;
}
public void setData(float[] data) {
this.data = data;
this.x = null;
this.y = null;
isSorted = false;
}
public void setData(float data, int idx) {
if (this.data != null && this.data.length > idx)
this.data[idx] = data;
isSorted = false;
}
public void setData(float data, double x, double y, int idx) {
if (this.data != null && this.data.length > idx)
this.data[idx] = data;
if (this.x != null && this.x.length > idx)
this.x[idx] = x;
if (this.y != null && this.y.length > idx)
this.y[idx] = y;
isSorted = false;
}
/**
* @param cellData
* @param fromidx
* @param toidx
*/
public void setData(CellData cellData, int fromidx, int toidx) {
if (cellData == null)
return;
data[toidx] = cellData.data[fromidx];
x[toidx] = cellData.x[fromidx];
y[toidx] = cellData.y[fromidx];
}
public void setLabel(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
public String getCellLabel() {
if(label.indexOf("(")!=-1)
return label.substring(0, label.indexOf("("));
else
return label;
}
public void sort() {
if (data == null || data.length == 0)
return;
DataSorter sortArr = new DataSorter();
sortArr.sort(data, data.length);
sortedIdx = sortArr.getSortIdx();
rank = sortArr.getRank();
if (sortedIdx != null) {
// NaN has an index which is larger than data.length
if (sortedIdx[0] < data.length)
max = data[sortedIdx[0]];
else
max = Float.NaN;
if (sortedIdx[sortedIdx.length - 1] < data.length)
min = data[sortedIdx[sortedIdx.length - 1]];
else
min = Float.NaN;
}
isSorted = true;
}
public boolean checkData() {
if (data == null || x == null || y == null)
return false;
if (data.length != x.length)
return false;
if (data.length != y.length)
return false;
return true;
}
public double getMax() {
return (double) max;
}
public double getMin() {
return (double) min;
}
public boolean isSorted() {
return isSorted;
}
// clone all arrhdays before handing out to prevent other classes
// from changing the arrays
public double[] getRank() {
if(rank == null)
sort();
return rank == null ? null : rank.clone();
}
public int[] getSortedIdx() {
return sortedIdx == null ? null : sortedIdx.clone();
}
public float[] getData() {
return data.clone();
}
public double[] getX() {
return x.clone();
}
public double[] getY() {
return y.clone();
}
public int length() {
if (data == null)
return 0;
else
return data.length;
}
public double getPixelRank(int i) {
if(rank == null)
sort();
if (rank != null && rank.length > i)
return rank[i];
else
return -1;
}
public int getPixelSortedIdx(int i) {
if (sortedIdx != null && sortedIdx.length > i)
return sortedIdx[i];
else
return -1;
}
public int getPX(int i) {
if (x != null && x.length > i)
return (int) x[i];
else
return -1;
}
public int getPY(int i) {
if (y != null && y.length > i)
return (int) y[i];
else
return -1;
}
public double getPixelX(int i) {
if (x != null && x.length > i)
return x[i];
else
return -1.0;
}
public double getPixelY(int i) {
if (y != null && y.length > i)
return y[i];
else
return -1.0;
}
public float getPixel(int i) {
if (data != null && data.length > i)
return data[i];
else
return Float.NaN;
}
public boolean equalData(CellData cellData) {
if (cellData == null)
return false;
float[] data = cellData.getData();
if (data == null || data.length != this.data.length)
return false;
for (int i = 0; i < data.length; i++)
if (data[i] != this.data[i])
return false;
return true;
}
/**
* Please be aware, the data points in new CellData though are marked NaN
* for those after the index(below the threshold) The sortedIdx and rank
* remain the same, and the data will NOT be sorted again.
*
* @param index/threshold
* @return
*/
public CellData getData(int index) {
if (index > length())
return this;
if (!isSorted())
sort();
CellData data = new CellData(this);
for (int i = 0; i < data.length(); i++)
data.data[i] = Float.NaN;
if (index < 0)
return data;
for (int i = 0; i < index; i++) {
data.data[data.sortedIdx[i] < data.length() ? data.sortedIdx[i]
: data.sortedIdx[i] - data.length()] = this.data[sortedIdx[i] < length() ? sortedIdx[i]
: sortedIdx[i] - length()];
}
return data;
}
}
| 6,076 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
CellFinder.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/cell/CellFinder.java | package ezcol.cell;
import java.awt.Color;
import java.awt.Rectangle;
import ij.*;
import ij.gui.Roi;
import ij.gui.ShapeRoi;
import ij.measure.Calibration;
import ij.measure.Measurements;
import ij.measure.ResultsTable;
import ij.plugin.filter.Analyzer;
import ij.plugin.filter.Binary;
import ij.plugin.filter.EDM;
import ij.plugin.frame.RoiManager;
import ij.process.ByteProcessor;
import ij.process.ImageProcessor;
import ij.process.ShortProcessor;
public class CellFinder {
private static final String[] FILTERS_SHAPE = { "Area", "X", "Y", "XM", "YM", "Perim.", "BX", "BY", "Width",
"Height", "Major", "Minor", "Angle", "Circ.", "Feret", "FeretX", "FeretY", "FeretAngle", "MinFeret", "AR",
"Round", "Solidity" };
private static final String[] FILTERS_FIRST = { "Mean", "Mode", "Min", "Max", "Median" };
private static final String[] FILTERS_HIGH = { "StdDev", "Skew", "Kurt", "%Area", "IntDen", "RawIntDen" };
public static final String SB_MARKER = "BgndRatio";
/**
* Terrible design here, why should these be consistent with the GUI GUI
* should get the list from here.
*/
private static int measurePhase = Measurements.AREA + Measurements.CENTROID + Measurements.CENTER_OF_MASS
+ Measurements.PERIMETER + Measurements.ELLIPSE + Measurements.RECT + Measurements.SHAPE_DESCRIPTORS
+ Measurements.FERET;
private static int measureFlourescent = Measurements.MEAN + Measurements.STD_DEV + Measurements.MODE
+ Measurements.MIN_MAX + Measurements.INTEGRATED_DENSITY + Measurements.MEDIAN + Measurements.SKEWNESS
+ Measurements.KURTOSIS + Measurements.AREA_FRACTION;
private static int measureBackground = Measurements.MEAN + Measurements.MEDIAN;
// Do Not Exclude Edge Particles before watershed to avoid false negative
private static int preAnalysis = ParticleAnalyzerMT.SHOW_MASKS;
private static int postAnalysis = ParticleAnalyzerMT.EXCLUDE_EDGE_PARTICLES + ParticleAnalyzerMT.ADD_TO_MANAGER;
private ImagePlus mask;
private ResultsTable rt1, rt2;
private ResultsTable[] rtChannels;
private ResultsTable[] rtBacks;
private ParticleAnalyzerMT cellParticles1, cellParticles2;
private double minSize1, maxSize1, minSize2, maxSize2;
private double minCirc1, maxCirc1, minCirc2, maxCirc2;
private String[] filterNames;
private double[] filterMin, filterMax;
// private boolean[] filterBackground;
private int numFilter;
private boolean[] deletedIndex;
private RoiManager roiParticles;
private ImagePlus impParticles;
private int[] cellIndexes;
private ImagePlus impParticlesFiltered;
private RoiManager roiParticlesFiltered;
private int[] cellIndexesFiltered;
private ResultsTable rtFiltered;
public CellFinder() {
this(null);
}
public CellFinder(ByteProcessor ip) {
if (ip != null)
mask = new ImagePlus("Mask", ip);
else
mask = new ImagePlus();
minCirc1 = 0.0;
minCirc2 = 0.0;
maxCirc1 = 1.0;
maxCirc2 = 1.0;
minSize1 = 0.0;
maxSize1 = Double.POSITIVE_INFINITY;
minSize2 = 0.0;
maxSize2 = Double.POSITIVE_INFINITY;
double[] inputmin = { 0 };
double[] inputmax = { Double.POSITIVE_INFINITY };
String[] inputnames = { "Area" };
initialFilters(inputnames, inputmin, inputmax);
}
public void setMask(ByteProcessor ip) {
if (ip != null)
mask = new ImagePlus("Mask", ip);
else
mask = new ImagePlus();
}
public void setMask(ByteProcessor ip, Calibration cal) {
if (ip != null) {
mask = new ImagePlus("Mask", ip.duplicate());
mask.setCalibration(cal);
} else {
mask = new ImagePlus();
mask.setCalibration(cal);
}
}
public void setSizeFilters(double[] minSize, double[] maxSize) {
if (minSize == null || maxSize == null)
return;
int len = minSize.length < maxSize.length ? minSize.length : maxSize.length;
switch (len) {
case 1:
minSize1 = minSize[0];
maxSize1 = maxSize[0];
break;
case 2:
minSize1 = minSize[0];
maxSize1 = maxSize[0];
minSize2 = minSize[1];
maxSize2 = maxSize[1];
break;
}
}
public void setCircFilters(double[] minCirc, double[] maxCirc) {
if (minCirc == null || maxCirc == null) {
return;
}
int len = minCirc.length < maxCirc.length ? minCirc.length : maxCirc.length;
switch (len) {
case 1:
minCirc1 = minCirc[0];
maxCirc1 = maxCirc[0];
break;
case 2:
minCirc1 = minCirc[0];
maxCirc1 = maxCirc[0];
minCirc2 = minCirc[1];
maxCirc2 = maxCirc[1];
break;
}
}
/**
* use two step intensity based thresholding method to get particles It's
* interesting that ParticleAnalyzer is robust to LUT and Inverting if it's
* run twice
*
* @param waterShed
*/
public void getParticles(boolean waterShed) {
ImagePlus mask1;
ImagePlus tempCurrentImg;
rt1 = new ResultsTable();
// 2616063 WITHOUT STACK
// 4188927 EVERYTHING
cellParticles1 = new ParticleAnalyzerMT(preAnalysis, measurePhase, rt1, minSize1, maxSize1, minCirc1, maxCirc1);
cellParticles1.setHideOutputImage(true);
cellParticles1.setHyperstack(mask);
// cellParticles1.setThreadResultsTable(rt1);
// avoid displaying rois
tempCurrentImg = WindowManager.getCurrentImage();
WindowManager.setTempCurrentImage(mask);
cellParticles1.analyze(mask);
WindowManager.setTempCurrentImage(tempCurrentImg);
mask1 = cellParticles1.getOutputImage();
if (waterShed) {
EDM waterSheded = new EDM();
waterSheded.toWatershed(mask1.getProcessor());
}
if (Prefs.blackBackground)
mask1.getProcessor().invert();
Binary fillHoles = new Binary();
fillHoles.setup("fill", mask1);
fillHoles.run(mask1.getProcessor());
if (rt2 == null)
rt2 = new ResultsTable();
cellParticles2 = new ParticleAnalyzerMT(postAnalysis, measurePhase, rt2, minSize2, maxSize2, minCirc2,
maxCirc2);
cellParticles2.setHideOutputImage(true);
if (roiParticles == null)
roiParticles = new RoiManager(false);
cellParticles2.setThreadRoiManager(roiParticles);
cellParticles2.setHyperstack(mask1);
// cellParticles2.setResultsTable(rt2);
// This part has been moved to the main function to keep safe in
// parallel programming
tempCurrentImg = WindowManager.getCurrentImage();
WindowManager.setTempCurrentImage(mask1);
cellParticles2.analyze(mask1);
WindowManager.setTempCurrentImage(tempCurrentImg);
// Sometimes ImageJ generate discontinuous numbers in count mask when
// doing multithreading
// In another word, count mask is not thread safe
// Therefore, we create our own count mask here
impParticles = roi2CountMask(roiParticles.getRoisAsArray(), mask1.getWidth(), mask1.getHeight());
cellIndexes = new int[roiParticles.getCount()];
for (int iCount = 0; iCount < roiParticles.getCount(); iCount++)
cellIndexes[iCount] = iCount;
}
// use ROIs to measure another image
private ResultsTable getMeasurements(ImageProcessor ip) {
ResultsTable tempResultTable = new ResultsTable();
if (ip == null)
return tempResultTable;
ImagePlus imp = new ImagePlus("ImageData", ip);
Analyzer aSys = new Analyzer(imp, measureFlourescent, tempResultTable); // System
// Analyzer
if (roiParticles == null)
return tempResultTable;
for (int iCount = 0; iCount < roiParticles.getCount(); iCount++) {
imp.setRoi(roiParticles.getRoi(iCount));
// Possible problem
aSys.measure();
}
imp.getProcessor().resetRoi();
return tempResultTable;
}
// use ROIs to measure another image and save the result as channel 1 or 2
private ResultsTable getBackgrounds(ImageProcessor ip) {
ResultsTable tempResultTable = new ResultsTable();
if (ip == null)
return tempResultTable;
ImagePlus imp = new ImagePlus("ImageData", ip);
RoiManager roiManager = new RoiManager(false);
Analyzer aSys = new Analyzer(imp, measureBackground, tempResultTable); // System
ParticleAnalyzerMT analyzer = new ParticleAnalyzerMT(ParticleAnalyzerMT.ADD_TO_MANAGER, 0, null, 0.0,
Double.POSITIVE_INFINITY);
analyzer.setThreadRoiManager(roiManager);
// I have to set current image to null to avoid the stupid ImageJ to
// open RoiManager
ImagePlus tempCurrentImg = WindowManager.getCurrentImage();
WindowManager.setTempCurrentImage(mask.duplicate());
analyzer.analyze(mask.duplicate());
WindowManager.setTempCurrentImage(tempCurrentImg);
Roi[] rois = roiManager.getRoisAsArray();
ip.resetRoi();
ShapeRoi shapeRoi = new ShapeRoi(ip.getRoi());
for (Roi roi : rois) {
shapeRoi.xor(new ShapeRoi(roi));
}
imp.setRoi(shapeRoi);
// Possible problem
aSys.measure();
ip.resetRoi();
return tempResultTable;
}
public void getMeasurements(ImageProcessor[] ips) {
rtChannels = new ResultsTable[ips.length];
rtBacks = new ResultsTable[ips.length];
for (int i = 0; i < ips.length; i++) {
ResultsTable tempResultTable = getMeasurements(ips[i]);
rtChannels[i] = tempResultTable;
tempResultTable = getBackgrounds(ips[i]);
rtBacks[i] = tempResultTable;
}
}
public void setResultsTable(ResultsTable rt2) {
this.rt2 = rt2;
}
public void setRoiManager(RoiManager roiParticles) {
this.roiParticles = roiParticles;
}
public RoiManager getOutputManager(boolean which) {
if (which)
return roiParticlesFiltered;
else
return roiParticles;
}
public ImagePlus getOutputImg(boolean which) {
if (which)
return impParticlesFiltered;
else
return impParticles;
}
public int[] getOutputIdx(boolean which) {
if (which)
return cellIndexesFiltered;
else
return cellIndexes;
}
public ResultsTable getOutputTable(boolean which) {
if (which)
return rtFiltered;
else
return rt2;
}
public boolean[] getDeletedIndexes() {
return deletedIndex;
}
/**
* filter cells based on cell shape measurements from the input resultstable
* The input ResultsTable should only contain cell shape filters
*
* @param rt
* @return
*/
private boolean[] filterParticles(ResultsTable rt) {
if (rt == null)
return null;
int numCells = rt.getCounter();
boolean[] deletedIndex = new boolean[numCells];
for (int iFilter = 0; iFilter < numFilter; iFilter++) {
// There should be no changed to the filterNames in this method
// But the following line is kept just in case.
String tempName = filterNames[iFilter];
if (filterNames[iFilter].indexOf(" ") != -1)
tempName = filterNames[iFilter].substring(0, filterNames[iFilter].indexOf(" "));
if (rt.columnExists(rt.getColumnIndex(tempName))) {
double[] metrics = rt.getColumnAsDoubles(rt.getColumnIndex(tempName));
for (int iCell = 0; iCell < numCells; iCell++) {
if (deletedIndex[iCell])
continue;
if (metrics[iCell] > filterMax[iFilter] || metrics[iCell] < filterMin[iFilter])
deletedIndex[iCell] = true;
}
}
}
return deletedIndex;
}
/**
* filter cells based on intensity measurements from the input resultstables
* of channel1 and channel2 The input ResultsTables should only contain
* intensity filters
*
* @param rt1
* @param rt2
* @return
*/
private boolean[] filterParticles(ResultsTable[] rts) {
if (rts == null || rts.length == 0)
return null;
int numCells = 0;
for (int i = 0; i < rts.length; i++) {
if (rts[i] == null)
continue;
if (numCells < rts[i].getCounter())
numCells = rts[i].getCounter();
}
boolean[] deletedIndex = new boolean[numCells];
for (int iFilter = 0; iFilter < numFilter; iFilter++) {
String tempName = filterNames[iFilter];
if (filterNames[iFilter].indexOf(" ") != -1)
tempName = filterNames[iFilter].substring(0, filterNames[iFilter].indexOf(" "));
// The assumption here is that filterNames do not contain any number
// except for channel number
int idxChannel = 0;
/**
* To explain: .* means any character from 0 to infinite occurrence,
* than the \\d+ (double backslash I think is just to escape the
* second backslash) and \d+ means a digit from 1 time to infinite.
*/
if (filterNames[iFilter].matches(".*\\d+.*"))
idxChannel = Integer.parseInt(filterNames[iFilter].replaceAll("[^0-9]", "")) - 1;
else
continue;
if (rts[idxChannel] != null && rts[idxChannel].columnExists(rts[idxChannel].getColumnIndex(tempName))) {
double[] metrics = rts[idxChannel].getColumnAsDoubles(rts[idxChannel].getColumnIndex(tempName));
for (int iCell = 0; iCell < rts[idxChannel].getCounter(); iCell++) {
if (deletedIndex[iCell])
continue;
boolean isRatio = isRatio(filterNames[iFilter]);
double background;
if (isRatio)
background = (rtBacks == null || idxChannel >= rtBacks.length || idxChannel < 0) ? 1.0
: (rtBacks[idxChannel].columnExists(rtBacks[idxChannel].getColumnIndex(tempName))
? rtBacks[idxChannel].getValue(tempName, 0) : 1.0);
else
background = 1.0;
if (metrics[iCell] > filterMax[iFilter] * background
|| metrics[iCell] < filterMin[iFilter] * background)
deletedIndex[iCell] = true;
}
}
}
return deletedIndex;
}
// perform two filterParticles functions
private void filterParticles() {
boolean[] deletedIndex1 = filterParticles(rt2);
boolean[] deletedIndex2 = filterParticles(rtChannels);
if (deletedIndex1 == null || deletedIndex2 == null)
return;
int minLength = deletedIndex1.length > deletedIndex2.length ? deletedIndex2.length : deletedIndex1.length;
this.deletedIndex = new boolean[minLength];
for (int i = 0; i < minLength; i++) {
this.deletedIndex[i] = deletedIndex1[i] || deletedIndex2[i];
}
}
// apply the result of filterParticle (an array of whether to remove
// particular cell or not)
public int[] applyFilters(boolean[] deletedIndex, int[] listOfObjects) {
if (deletedIndex == null)
return null;
int minLength = deletedIndex.length < listOfObjects.length ? deletedIndex.length : listOfObjects.length;
int numRemains = 0;
int[] indexes = new int[listOfObjects.length];
for (int iObj = 0; iObj < minLength; iObj++) {
if (!deletedIndex[iObj]) {
indexes[numRemains] = iObj;
numRemains++;
}
}
for (int iObj = minLength; iObj < listOfObjects.length; iObj++) {
indexes[numRemains] = iObj;
numRemains++;
}
int[] results = new int[numRemains];
for (int iObj = 0; iObj < numRemains; iObj++) {
results[iObj] = listOfObjects[indexes[iObj]];
}
return results;
}
// apply filters to any input Object
public Object[] applyFilters(boolean[] deletedIndex, Object[] listOfObjects) {
if (deletedIndex == null)
return null;
int minLength = deletedIndex.length < listOfObjects.length ? deletedIndex.length : listOfObjects.length;
int numRemains = 0;
int[] indexes = new int[listOfObjects.length];
for (int iObj = 0; iObj < minLength; iObj++) {
if (!deletedIndex[iObj]) {
indexes[numRemains] = iObj;
numRemains++;
}
}
for (int iObj = minLength; iObj < listOfObjects.length; iObj++) {
indexes[numRemains] = iObj;
numRemains++;
}
Object[] results = new Object[numRemains];
for (int iObj = 0; iObj < numRemains; iObj++) {
results[iObj] = listOfObjects[indexes[iObj]];
}
return results;
}
// apply filters to any input resulttable
public ResultsTable applyFilters(boolean[] deletedIndex, ResultsTable rt) {
if (deletedIndex == null)
return null;
int minLength = deletedIndex.length < rt.getCounter() ? deletedIndex.length : rt.getCounter();
ResultsTable results = new ResultsTable();
String[] columnNames = rt.getHeadings();
for (int iObj = 0; iObj < minLength; iObj++) {
if (deletedIndex[iObj])
continue;
results.incrementCounter();
if (columnNames[0].equals("Label")) {
results.addLabel(rt.getLabel(iObj));
} else {
results.addValue(columnNames[0], rt.getValue(columnNames[0], iObj));
}
for (int iColumn = 1; iColumn < columnNames.length; iColumn++)
results.addValue(columnNames[iColumn], rt.getValue(columnNames[iColumn], iObj));
}
for (int iObj = minLength; iObj < rt.getCounter(); iObj++) {
results.incrementCounter();
if (columnNames[0].equals("Label")) {
results.addLabel(rt.getLabel(iObj));
} else {
results.addValue(columnNames[0], rt.getValue(columnNames[0], iObj));
}
for (int iColumn = 1; iColumn < columnNames.length; iColumn++)
results.addValue(columnNames[iColumn], rt.getValue(columnNames[iColumn], iObj));
}
return results;
}
// apply filters to any input RoiManager
public RoiManager applyFilters(boolean[] deletedIndex, RoiManager roiManager) {
if (deletedIndex == null)
return null;
int minLength = deletedIndex.length < roiManager.getCount() ? deletedIndex.length : roiManager.getCount();
RoiManager roiFiltered = new RoiManager(false);
for (int iObj = 0; iObj < minLength; iObj++) {
if (!deletedIndex[iObj])
roiFiltered.addRoi(roiManager.getRoi(iObj));
}
for (int iObj = minLength; iObj < roiManager.getCount(); iObj++) {
roiFiltered.addRoi(roiManager.getRoi(iObj));
}
return roiFiltered;
}
// apply filters to any input image
public ImagePlus applyFilters(boolean[] deletedIndex, ImagePlus countMask) {
if (deletedIndex == null)
return null;
ImagePlus result = countMask.duplicate();
ImageProcessor ipResult = result.getProcessor();
int indexLength = (int) countMask.getProcessor().getStatistics().max;
int minLength = deletedIndex.length < indexLength ? deletedIndex.length : indexLength;
int[][] pixel = ipResult.getIntArray();
int width = result.getWidth();
int height = result.getHeight();
int[] newIndexes = new int[indexLength + 1];
int numCells = 1;
for (int i = 1; i <= minLength; i++) {
if (deletedIndex[i - 1])
newIndexes[i] = 0;
else {
newIndexes[i] = numCells;
numCells++;
}
}
for (int i = minLength + 1; i < newIndexes.length; i++) {
newIndexes[i] = numCells;
numCells++;
}
for (int w = width - 1; w >= 0; w--) {
for (int h = height - 1; h >= 0; h--) {
if (pixel[w][h] != 0)
ipResult.set(w, h, newIndexes[pixel[w][h]]);
}
}
ipResult.resetMinAndMax();
return result;
}
// apply filters automatically
public void applyFilters() {
filterParticles();
if (deletedIndex == null)
return;
impParticlesFiltered = applyFilters(deletedIndex, impParticles);
roiParticlesFiltered = applyFilters(deletedIndex, roiParticles);
cellIndexesFiltered = applyFilters(deletedIndex, cellIndexes);
rtFiltered = applyFilters(deletedIndex, rt2);
}
public void initialFilters(final String[] names, final double[] mins, final double[] maxes) {
initialFilters(names, mins, maxes, new boolean[names.length]);
}
public void initialFilters(final String[] names, final double[] mins, final double[] maxes,
final boolean[] backgrounds) {
if (!isDimensionEqual(names.length + " " + mins.length + " " + maxes.length)) {
numFilter = 0;
return;
}
numFilter = names.length;
filterNames = names;
filterMin = mins;
filterMax = maxes;
// filterBackground=backgrounds;
}
private boolean isDimensionEqual(String str) {
String[] strs = str.split(" ");
String temp;
if (strs.length > 0)
temp = strs[0];
else
return true;
for (int i = 0; i < strs.length; i++) {
if (!strs[i].equals(temp)) {
return false;
}
}
return true;
}
private ImagePlus roi2CountMask(Roi[] rois, int width, int height) {
if (rois == null)
return null;
ShortProcessor drawIP = new ShortProcessor(width, height);
drawIP.setColor(Color.BLACK);
drawIP.fill();
drawIP.setColor(Color.WHITE);
int grayLevel = 0;
for (int i = 0; i < rois.length; i++) {
grayLevel = i <= 65535 ? (i + 1) : 65535;
drawIP.setValue((double) grayLevel);
drawIP.setRoi(rois[i]);
drawIP.fill(drawIP.getMask());
}
drawIP.setRoi((Rectangle) null);
return new ImagePlus("Count Mask", drawIP);
}
private boolean isRatio(String filter) {
return filter.contains(SB_MARKER);
// return Arrays.asList(FILTERS_FIRST).contains(filter);}
}
}
| 19,816 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
ParticleAnalyzerMT.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/cell/ParticleAnalyzerMT.java | package ezcol.cell;
import java.awt.Frame;
import ezcol.debug.Debugger;
import ij.IJ;
import ij.ImagePlus;
import ij.Macro;
import ij.Prefs;
import ij.WindowManager;
import ij.gui.Roi;
import ij.macro.Interpreter;
import ij.measure.Measurements;
import ij.measure.ResultsTable;
import ij.plugin.filter.ParticleAnalyzer;
import ij.plugin.filter.ThresholdToSelection;
import ij.plugin.frame.RoiManager;
import ij.process.ImageProcessor;
import ij.process.ImageStatistics;
//This is a thread safe particleanalyzer in terms of roiManager and resultswindow
public class ParticleAnalyzerMT extends ParticleAnalyzer {
private RoiManager roiManager;
private RoiManager roiGarbageManager = new RoiManager(false);
private int lineWidth = 1;
private boolean hyperstack;
private boolean showResultsWindow = true;
/** Saves statistics for one particle in a results table. This is
a method subclasses may want to override. */
public ParticleAnalyzerMT(int options, int measurements, ResultsTable rt, double minSize, double maxSize, double minCirc, double maxCirc)
{super(options,measurements,rt,minSize,maxSize,minCirc,maxCirc);}
/** Constructs a ParticleAnalyzer using the default min and max circularity values (0 and 1). */
public ParticleAnalyzerMT(int options, int measurements, ResultsTable rt, double minSize, double maxSize)
{this(options, measurements, rt, minSize, maxSize, 0.0, 1.0);}
/** Default constructor */
public ParticleAnalyzerMT()
{super();}
public void setHyperstack(ImagePlus imp)
{hyperstack=imp.isHyperStack();}
public void setThreadLineWidth(int lineWidth)
{this.lineWidth=lineWidth;}
public void setThreadRoiManager(RoiManager roiManager){
this.roiManager = roiManager;
setRoiManager(roiGarbageManager);
}
public void setThreadResultsTable(ResultsTable rt)
{this.rt=rt;}
//override to make it thread safe
@Override
protected void saveResults(ImageStatistics stats, Roi roi) {
analyzer.saveResults(stats, roi);
if (recordStarts) {
rt.addValue("XStart", stats.xstart);
rt.addValue("YStart", stats.ystart);
}
if (addToManager) {
if (roiManager==null) {
if (Macro.getOptions()!=null && Interpreter.isBatchMode())
roiManager = Interpreter.getBatchModeRoiManager();
if (roiManager==null) {
Frame frame = WindowManager.getFrame("ROI Manager");
if (frame==null)
IJ.run("ROI Manager...");
frame = WindowManager.getFrame("ROI Manager");
if (frame==null || !(frame instanceof RoiManager))
{addToManager=false; return;}
roiManager = (RoiManager)frame;
}
if (resetCounter)
roiManager.runCommand("reset");
}
if (imp.getStackSize()>1) {
int n = imp.getCurrentSlice();
if (hyperstack) {
int[] pos = imp.convertIndexToPosition(n);
roi.setPosition(pos[0],pos[1],pos[2]);
} else
roi.setPosition(n);
}
if (lineWidth!=1)
roi.setStrokeWidth(lineWidth);
roiManager.add(imp, roi, rt.getCounter());
}
if (showResultsWindow && showResults)
rt.addResults();
}
public static boolean analyzeWithHole(ImageProcessor ip, RoiManager roiManager) {
ParticleAnalyzerMT cellParticles = new ParticleAnalyzerMT(SHOW_ROI_MASKS, 0, null, 0.0,
Double.POSITIVE_INFINITY);
cellParticles.setHideOutputImage(true);
if (!cellParticles.analyze(new ImagePlus("Thresholding", ip), ip))
return false;
ImagePlus countMask = cellParticles.getOutputImage();
ImageProcessor countProcessor = countMask.getProcessor();
ImageStatistics countStat = ImageStatistics.getStatistics(countProcessor, Measurements.MIN_MAX, null);
ThresholdToSelection tts = new ThresholdToSelection();
for (double iCell = 0.5; iCell < countStat.max; iCell++) {
countProcessor.setThreshold(iCell, iCell + 1, ImageProcessor.NO_LUT_UPDATE);
Roi roi = tts.convert(countProcessor);
if (roi != null)
roiManager.add(countMask, roi, (int) (iCell + 0.5));
}
return true;
}
public void dumpGarbageRois(){
roiGarbageManager.reset();
}
}
| 3,998 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
DataSorter.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/cell/DataSorter.java | package ezcol.cell;
import java.util.Vector;
import ezcol.debug.ExceptionHandler;
/*
* This is a class used to sort arrays so that the index of each number in the sorted array
* is accessible for calculating threshold overlap score
* the sorting is performed by quick sort algorithm
* the sorting is always in descending order
*/
public class DataSorter {
public static final int INT=1,FLOAT=2,DOUBLE=3;
private int[] sortIdx;
private int[] inputInt;
private float[] inputFloat;
private double [] inputDouble;
private int inputlength;
private int marker;
Object Output;
public void reset()
{
this.sortIdx=null;
this.inputlength=0;
this.inputDouble=null;
this.inputFloat=null;
this.inputInt=null;
}
/**
* sortedIdx can be array.length+index if the corresponding data point is NaN
* @return
*/
public int[] getSortIdx()
{return sortIdx.clone();}
/*
* Change in version 1.3
* now if sortIdx is array.length+index, rank will be set to Double.NaN
* Change in version 1.4
* it returns fraction rank (tie rank) now
*/
public double[] getRank()
{
if(sortIdx==null)
return null;
double[] rank=new double[sortIdx.length];
Vector<Integer> ties = new Vector<Integer>();
for(int i=1;i<=rank.length;i++){
if(sortIdx[i-1]>=sortIdx.length){
rank[sortIdx[i-1]-sortIdx.length]= Double.NaN ;
}
else if(getData(i-1).equals(getData(i))){
ties.add(i);
}
else if(ties.isEmpty()){
rank[sortIdx[i-1]] = i;
}
else {
ties.add(i);
double avg = 0.0;
for(Integer j:ties){
avg+=j;
}
avg/=ties.size();
for(Integer j:ties){
rank[sortIdx[j-1]]=avg;
}
ties.clear();
}
}
return rank;
}
public Number getData(int index){
if(index<0||index>=inputlength)
return Double.NaN;
else{
switch(marker){
case INT:
return inputInt[index];
case FLOAT:
return inputFloat[index];
case DOUBLE:
return inputDouble[index];
}
}
return Double.NaN;
}
public void sort(int[] inputArr)
{
if (inputArr == null || inputArr.length == 0) {
return;
}
marker = INT;
inputInt = inputArr.clone();
inputlength = inputArr.length;
sortIdx=new int[inputlength];
for (int idx=0;idx<inputlength;idx++){
this.sortIdx[idx] = idx;
}
quickSortInt(0, inputlength - 1);
Output=(Object) inputInt;
}
public void sort(int[] inputArr,int size)
{
if (inputArr == null || inputArr.length < size || size == 0) {
return;
}
marker = INT;
inputInt = inputArr.clone();
inputlength = size;
for (int i=0;i<size;i++)
inputInt[i]=inputArr[i];
sortIdx=new int[inputlength];
for (int idx=0;idx<inputlength;idx++){
this.sortIdx[idx] = idx;
}
quickSortInt(0, inputlength - 1);
Output=(Object) inputInt;
}
public void sort(float[] inputArr) {
if (inputArr == null || inputArr.length == 0) {
return;
}
marker = FLOAT;
inputFloat = inputArr.clone();
inputlength = inputArr.length;
sortIdx=new int[inputlength];
for (int idx=0;idx<inputlength;idx++){
if(Float.isNaN(inputArr[idx]))
this.sortIdx[idx] = idx+sortIdx.length;
else
this.sortIdx[idx] = idx;
}
quickSortFloat(0, inputlength - 1);
Output=(Object) inputFloat;
}
public void sort(float[] inputArr,int size) {
if (inputArr == null || inputArr.length < size || size == 0) {
return;
}
marker = FLOAT;
inputFloat = inputArr.clone();
inputlength = size;
sortIdx=new int[inputlength];
for (int idx=0;idx<inputlength;idx++){
if(Float.isNaN(inputArr[idx]))
this.sortIdx[idx] = idx+sortIdx.length;
else
this.sortIdx[idx] = idx;
}
quickSortFloat(0, inputlength - 1);
Output=(Object) inputFloat;
}
public void sort(double[] inputArr) {
if (inputArr == null || inputArr.length == 0) {
return;
}
marker = DOUBLE;
inputDouble = inputArr.clone();
inputlength = inputArr.length;
sortIdx=new int[inputlength];
for (int idx=0;idx<inputlength;idx++){
if(Double.isNaN(inputArr[idx]))
this.sortIdx[idx] = idx + sortIdx.length;
else
this.sortIdx[idx] = idx;
}
quickSortDouble(0, inputlength - 1);
Output=(Object) inputDouble;
}
public void sort(double[] inputArr,int size) {
if (inputArr == null || inputArr.length < size || size == 0) {
return;
}
marker = DOUBLE;
inputDouble = inputArr.clone();
inputlength = size;
for (int i=0;i<size;i++)
inputDouble[i]=inputArr[i];
sortIdx=new int[inputlength];
for (int idx=0;idx<inputlength;idx++){
if(Double.isNaN(inputArr[idx]))
this.sortIdx[idx] = idx+sortIdx.length;
else
this.sortIdx[idx] = idx;
}
quickSortDouble(0, inputlength - 1);
Output=(Object) inputDouble;
}
private void quickSortInt(int lowerIndex, int higherIndex) {
int i = lowerIndex;
int j = higherIndex;
int temp;
int tempIdx;
// calculate pivot number, I am taking pivot as middle index number
int pivot = inputInt[lowerIndex+(higherIndex-lowerIndex)/2];
// Divide into two inputInt
while (i <= j) {
/**
* In each iteration, we will identify a number from left side which
* is greater then the pivot value, and also we will identify a number
* from right side which is less then the pivot value. Once the search
* is done, then we exchange both numbers.
*/
while (inputInt[i] > pivot) {
i++;
}
while (inputInt[j] < pivot) {
j--;
}
if (i <= j) {
temp = inputInt[i];
inputInt[i] = inputInt[j];
inputInt[j] = temp;
tempIdx = sortIdx[i];
sortIdx[i] = sortIdx[j];
sortIdx[j] = tempIdx;
//move index to next position on both sides
i++;
j--;
}
}
// call quickSort() method recursively
if (lowerIndex < j)
quickSortInt(lowerIndex, j);
if (i < higherIndex)
quickSortInt(i, higherIndex);
}
private void quickSortFloat(int lowerIndex, int higherIndex) {
int i = lowerIndex;
int j = higherIndex;
float temp;
int tempIdx;
// calculate pivot number, I am taking pivot as middle index number
float pivot=0;
pivot = inputFloat[lowerIndex+(higherIndex-lowerIndex)/2];
// Divide into two inputFloat
while (i <= j) {
/**
* In each iteration, we will identify a number from left side which
* is greater then the pivot value, and also we will identify a number
* from right side which is less then the pivot value. Once the search
* is done, then we exchange both numbers.
*/
while (inputFloat[i] > pivot ||
(Float.isNaN(pivot)&&(!Float.isNaN(inputFloat[i])))) {
i++;
}
while (inputFloat[j] < pivot ||
(!Float.isNaN(pivot)&&Float.isNaN(inputFloat[j]))) {
j--;
}
if (i <= j) {
temp = inputFloat[i];
inputFloat[i] = inputFloat[j];
inputFloat[j] = temp;
tempIdx = sortIdx[i];
sortIdx[i] = sortIdx[j];
sortIdx[j] = tempIdx;
//move index to next position on both sides
i++;
j--;
}
}
// call quickSort() method recursively
if (lowerIndex < j)
quickSortFloat(lowerIndex, j);
if (i < higherIndex)
quickSortFloat(i, higherIndex);
}
private void quickSortDouble(int lowerIndex, int higherIndex) {
int i = lowerIndex;
int j = higherIndex;
double temp;
int tempIdx;
// calculate pivot number, I am taking pivot as middle index number
double pivot = inputDouble[lowerIndex+(higherIndex-lowerIndex)/2];
// Divide into two inputDouble
while (i <= j) {
/**
* In each iteration, we will identify a number from left side which
* is greater then the pivot value, and also we will identify a number
* from right side which is less then the pivot value. Once the search
* is done, then we exchange both numbers.
*/
while (inputDouble[i] > pivot ||
(Double.isNaN(pivot)&&!Double.isNaN(inputDouble[i]))) {
i++;
}
while (inputDouble[j] < pivot ||
(!Double.isNaN(pivot)&&Double.isNaN(inputDouble[j]))) {
j--;
}
if (i <= j) {
temp = inputDouble[i];
inputDouble[i] = inputDouble[j];
inputDouble[j] = temp;
tempIdx = sortIdx[i];
sortIdx[i] = sortIdx[j];
sortIdx[j] = tempIdx;
//move index to next position on both sides
i++;
j--;
}
}
// call quickSort() method recursively
if (lowerIndex < j)
quickSortDouble(lowerIndex, j);
if (i < higherIndex)
quickSortDouble(i, higherIndex);
}
public Object getResult(){
return Output;
}
}
| 10,111 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
CellFilterDialog.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/cell/CellFilterDialog.java | package ezcol.cell;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import ezcol.files.FilesIO;
import ezcol.main.PluginConstants;
import ezcol.main.PluginStatic;
import ij.IJ;
import ij.WindowManager;
import ij.plugin.ScreenGrabber;
@SuppressWarnings("serial")
public class CellFilterDialog extends JDialog implements ActionListener, KeyListener{
private static CellFilterDialog staticCellFilterDialog;
public static String[] filterStrings = PluginStatic.getFilterStrings();
private String filterLabel = "More filter ";
private int count = 0;
private static final int FILTER_HEIGHT = 32;
private static final int SCREEN_HEIGHT = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().height;
private boolean wasOKed, wasCanceled;
private final JPanel contentPanel = new JPanel();
private JPanel panel;
private GridBagLayout gbl_panel;
private JButton btnAddFilter;
private JButton btnOK, btnCancel;
private ArrayList<JLabel> filterNames = new ArrayList<JLabel>();
private ArrayList<JTextField> filterRanges = new ArrayList<JTextField>();
private ArrayList<JComboBox<String>> filterChoices = new ArrayList<JComboBox<String>>();
private ArrayList<JButton> btnsRemoveFilter = new ArrayList<JButton>();
public CellFilterDialog(){this("");}
public CellFilterDialog(String title){
this(title, WindowManager.getCurrentImage()!=null?
(Frame)WindowManager.getCurrentImage().getWindow():IJ.getInstance()!=null?IJ.getInstance():new Frame());
}
public CellFilterDialog(String title, Frame parent) {
super(parent==null?new Frame():parent, title, true);
}
public static CellFilterDialog getCellFilterDialog(){
if(staticCellFilterDialog==null){
staticCellFilterDialog = new CellFilterDialog();
}
return staticCellFilterDialog;
}
public static CellFilterDialog getCellFilterDialog(String title){
if(staticCellFilterDialog==null){
staticCellFilterDialog = new CellFilterDialog(title);
}
return staticCellFilterDialog;
}
public static CellFilterDialog getCellFilterDialog(String title, Frame parent){
if(staticCellFilterDialog==null){
staticCellFilterDialog = new CellFilterDialog(title,parent);
}
return staticCellFilterDialog;
}
public void retrieveFilters(ArrayList<Integer> filterChoices,ArrayList<Boolean> backRatios){
if(filterChoices == null || backRatios == null)
return;
filterChoices.clear();
backRatios.clear();
for(JComboBox<String> filters: this.filterChoices){
filterChoices.add(filters.getSelectedIndex());
backRatios.add(false);
}
}
public void retrieveRanges(ArrayList<Double> minRanges,ArrayList<Double> maxRanges){
if(minRanges == null || maxRanges == null){
return;
}
minRanges.clear();
maxRanges.clear();
for(JTextField ranges: filterRanges){
double[] range = PluginStatic.str2doubles(ranges.getText());
minRanges.add(range[0]);
maxRanges.add(range[1]);
}
}
public void showDialog(){
if(panel==null)
setUI();
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setVisible(true);
}
private void setUI(){
setTitle("More filters");
setBounds(100, 100, 502, 234);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{336, 0};
gridBagLayout.rowHeights = new int[]{20, 41, 15, 22, 20, 0};
gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
getContentPane().setLayout(gridBagLayout);
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
GridBagConstraints gbc_contentPanel = new GridBagConstraints();
gbc_contentPanel.fill = GridBagConstraints.BOTH;
gbc_contentPanel.insets = new Insets(0, 0, 5, 0);
gbc_contentPanel.gridx = 0;
gbc_contentPanel.gridy = 1;
getContentPane().add(contentPanel, gbc_contentPanel);
contentPanel.setLayout(new GridLayout(1, 0, 0, 0));
{
panel = new JPanel();
contentPanel.add(panel);
gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{19, 75, 17, 96, 31, 132, 0, 18, 0};
gbl_panel.rowHeights = new int[]{FILTER_HEIGHT, 0};
gbl_panel.columnWeights = new double[]{0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
{
count++;
JLabel lblNewLabel = new JLabel(filterLabel+count);
lblNewLabel.setFont(new Font("Arial", Font.PLAIN, 16));
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.fill = GridBagConstraints.HORIZONTAL;
gbc_lblNewLabel.insets = new Insets(2, 0, 2, 5);
gbc_lblNewLabel.gridx = 1;
gbc_lblNewLabel.gridy = 0;
panel.add(lblNewLabel, gbc_lblNewLabel);
filterNames.add(lblNewLabel);
}
{
JComboBox<String> comboBox = new JComboBox<String>(filterStrings);
GridBagConstraints gbc_comboBox = new GridBagConstraints();
gbc_comboBox.insets = new Insets(0, 0, 0, 5);
gbc_comboBox.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox.gridx = 3;
gbc_comboBox.gridy = 0;
panel.add(comboBox, gbc_comboBox);
filterChoices.add(comboBox);
}
{
JTextField textField = new JTextField();
textField.setText(PluginStatic.getFilterRange(PluginConstants.DEFAULT_MIN,PluginConstants.DEFAULT_MAX));
GridBagConstraints gbc_TextField = new GridBagConstraints();
gbc_TextField.insets = new Insets(0, 0, 0, 5);
gbc_TextField.fill = GridBagConstraints.HORIZONTAL;
gbc_TextField.gridx = 5;
gbc_TextField.gridy = 0;
panel.add(textField, gbc_TextField);
filterRanges.add(textField);
}
{
JButton button = new JButton();
button.setBorder(BorderFactory.createEmptyBorder());
button.setContentAreaFilled(false);
if(FilesIO.getResource("deleteIcon16.gif")!=null)
button.setIcon(new ImageIcon(FilesIO.getResource("deleteIcon16.gif")));
else
button.setText("X");
button.addActionListener(this);
GridBagConstraints gbc_button = new GridBagConstraints();
gbc_button.insets = new Insets(0, 5, 0, 5);
gbc_button.gridx = 6;
gbc_button.gridy = 0;
panel.add(button, gbc_button);
btnsRemoveFilter.add(button);
}
}
{
btnAddFilter = new JButton("Add Filter");
btnAddFilter.addActionListener(this);
GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
gbc_btnNewButton.insets = new Insets(0, 0, 5, 0);
gbc_btnNewButton.gridx = 0;
gbc_btnNewButton.gridy = 3;
getContentPane().add(btnAddFilter, gbc_btnNewButton);
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
GridBagConstraints gbc_buttonPane = new GridBagConstraints();
gbc_buttonPane.anchor = GridBagConstraints.NORTH;
gbc_buttonPane.fill = GridBagConstraints.HORIZONTAL;
gbc_buttonPane.gridx = 0;
gbc_buttonPane.gridy = 4;
getContentPane().add(buttonPane, gbc_buttonPane);
{
btnOK = new JButton("OK");
btnOK.setActionCommand("OK");
btnOK.addActionListener(this);
btnOK.addKeyListener(this);
buttonPane.add(btnOK);
getRootPane().setDefaultButton(btnOK);
}
{
btnCancel = new JButton("Cancel");
btnCancel.addActionListener(this);
btnCancel.addKeyListener(this);
buttonPane.add(btnCancel);
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
Object origin=e.getSource();
if(origin == btnAddFilter){
Rectangle rec =getBounds();
rec.height += FILTER_HEIGHT;
if(rec.height > SCREEN_HEIGHT)
return;
setBounds(rec);
int[] rowHeights = new int[gbl_panel.rowHeights.length+1];
double[] rowWeights = new double[gbl_panel.rowWeights.length+1];
rowHeights[0] = gbl_panel.rowHeights[0];
System.arraycopy(gbl_panel.rowHeights, 0, rowHeights, 1, gbl_panel.rowHeights.length);
rowWeights[0] = gbl_panel.rowWeights[0];
System.arraycopy(gbl_panel.rowWeights, 0, rowWeights, 1, gbl_panel.rowWeights.length);
gbl_panel.rowHeights = rowHeights;
gbl_panel.rowWeights = rowWeights;
// TODO Auto-generated method stub
count++;
JLabel lblNewLabel = new JLabel(filterLabel+count);
lblNewLabel.setFont(new Font("Arial", Font.PLAIN, 17));
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.fill = GridBagConstraints.HORIZONTAL;
gbc_lblNewLabel.insets = new Insets(0, 0, 0, 5);
gbc_lblNewLabel.gridx = 1;
gbc_lblNewLabel.gridy = count-1;
panel.add(lblNewLabel, gbc_lblNewLabel);
filterNames.add(lblNewLabel);
JComboBox<String> comboBox = new JComboBox<String>(filterStrings);
GridBagConstraints gbc_comboBox = new GridBagConstraints();
gbc_comboBox.insets = new Insets(0, 0, 0, 5);
gbc_comboBox.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox.gridx = 3;
gbc_comboBox.gridy = count-1;
panel.add(comboBox, gbc_comboBox);
filterChoices.add(comboBox);
JTextField textField = new JTextField();
textField.setText(PluginStatic.getFilterRange(PluginConstants.DEFAULT_MIN,PluginConstants.DEFAULT_MAX));
GridBagConstraints gbc_TextField = new GridBagConstraints();
gbc_TextField.insets = new Insets(0, 0, 0, 5);
gbc_TextField.fill = GridBagConstraints.HORIZONTAL;
gbc_TextField.gridx = 5;
gbc_TextField.gridy = count-1;
panel.add(textField, gbc_TextField);
filterRanges.add(textField);
JButton button = new JButton();
button.setBorder(BorderFactory.createEmptyBorder());
button.setContentAreaFilled(false);
if(FilesIO.getResource("deleteIcon16.gif")!=null)
button.setIcon(new ImageIcon(FilesIO.getResource("deleteIcon16.gif")));
else
button.setText("X");
button.addActionListener(this);
GridBagConstraints gbc_button = new GridBagConstraints();
gbc_button.insets = new Insets(0, 5, 0, 5);
gbc_button.gridx = 6;
gbc_button.gridy = count-1;
panel.add(button, gbc_button);
btnsRemoveFilter.add(button);
revalidate();
repaint();
}
int idx = btnsRemoveFilter.indexOf(origin);
if(idx != -1){
if(count == 1)
return;
Rectangle rec =getBounds();
rec.height -= FILTER_HEIGHT;
setBounds(rec);
int[] rowHeights = new int[gbl_panel.rowHeights.length-1];
double[] rowWeights = new double[gbl_panel.rowWeights.length-1];
System.arraycopy(gbl_panel.rowHeights, 1, rowHeights, 0, rowHeights.length);
System.arraycopy(gbl_panel.rowWeights, 1, rowWeights, 0, rowWeights.length);
gbl_panel.rowHeights = rowHeights;
gbl_panel.rowWeights = rowWeights;
panel.remove(filterNames.get(idx));
panel.remove(filterChoices.get(idx));
panel.remove(filterRanges.get(idx));
panel.remove(btnsRemoveFilter.get(idx));
filterNames.remove(idx);
filterChoices.remove(idx);
filterRanges.remove(idx);
btnsRemoveFilter.remove(idx);
//move up the components below the deleted filter
int newcount = idx+1;
for (Component comp : panel.getComponents()) {
if(comp == null || gbl_panel ==null)
continue;
GridBagConstraints gbc = gbl_panel.getConstraints(comp);
if(gbc!=null){
if(gbc.gridy>idx){
gbc.gridy--;
//This condition is not safe if there is additional JLabel
//However, we only have filterNames as JLabel
if(comp instanceof JLabel){
((JLabel)comp).setText(filterLabel+newcount);
newcount++;
}
}
gbl_panel.setConstraints(comp, gbc);
}
}
count--;
revalidate();
repaint();
}
if (origin==btnOK || origin==btnCancel) {
wasCanceled = origin==btnCancel;
if(wasCanceled)
staticCellFilterDialog = null;
wasOKed = origin==btnOK;
dispose();
}
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
IJ.setKeyDown(keyCode);
if (keyCode==KeyEvent.VK_ENTER) {
wasOKed = true;
dispose();
} else if (keyCode==KeyEvent.VK_ESCAPE) {
wasCanceled = true;
staticCellFilterDialog = null;
dispose();
IJ.resetEscape();
} else if (keyCode==KeyEvent.VK_W && (e.getModifiers()&Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())!=0) {
wasCanceled = true;
dispose();
}
}
@Override
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
IJ.setKeyUp(keyCode);
int flags = e.getModifiers();
boolean control = (flags & KeyEvent.CTRL_MASK) != 0;
boolean meta = (flags & KeyEvent.META_MASK) != 0;
boolean shift = (flags & KeyEvent.SHIFT_MASK) != 0;
if (keyCode==KeyEvent.VK_G && shift && (control||meta))
new ScreenGrabber().run("");
}
/** Returns true if the user clicked on "Cancel". */
public boolean wasCanceled() {
return wasCanceled;
}
/** Returns true if the user has clicked on "OK" or a macro is running. */
public boolean wasOKed() {
return wasOKed;
}
public static void reset(){
staticCellFilterDialog = null;
}
public static void syncFilter(){
reset();
filterStrings = PluginStatic.getFilterStrings();
}
}
| 13,780 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
Debugger.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/debug/Debugger.java | package ezcol.debug;
import java.awt.Font;
import java.awt.Frame;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import ezcol.cell.CellData;
import ezcol.main.PluginConstants;
import ezcol.main.PluginStatic;
import ezcol.visual.visual2D.HistogramStackWindow;
import ij.IJ;
import ij.ImagePlus;
import ij.WindowManager;
import ij.gui.StackWindow;
import ij.io.LogStream;
import ij.measure.ResultsTable;
import ij.text.TextPanel;
import ij.text.TextWindow;
import ij.util.Tools;
/**
* This class catches most if not all waring and error messages during analysis
* and print it in the log window.
*
* @author Huanjie Sheng
*
*/
public class Debugger implements PluginConstants {
// [0] Thread.getStackTrace
// [1] ExceptionReporter
// [2] The line where addError is called
private static final int TRACE_LINE = 2;
private static Map<String, Long> timeMap = new HashMap<String, Long>();
private static final String SEPARATOR = "-----------------------------------------------------";
public static void printStackTrace(int start, int end) {
if (Thread.currentThread() != null){
StackTraceElement[] stes = Thread.currentThread().getStackTrace();
if (start < 0)
start = 0;
if (end >= stes.length)
end = stes.length - 1;
if (end < start)
end = start;
else
System.out.println(SEPARATOR);
for (int i = start; i <= end; i++){
System.out.println(stes[i]);
}
if (end >= start)
System.out.println(SEPARATOR);
}
}
public static void printStackTrace(int num) {
printStackTrace(0, num - 1);
}
public static void printCurrentLine(String... strs) {
String ste = Thread.currentThread().getStackTrace()[TRACE_LINE].toString();
String separator = new String(new char[ste.length()]).replace('\0', '_');
System.out.println(separator);
System.out.println(ste);
for(String str: strs)
System.out.println(str);
System.out.println(separator);
}
public static void printCurrentLine(String str) {
String ste = Thread.currentThread().getStackTrace()[TRACE_LINE].toString();
String separator = new String(new char[ste.length()]).replace('\0', '_');
System.out.println(separator);
System.out.println(ste);
System.out.println(str);
System.out.println(separator);
}
public static<T> void printCurrentLine (T str){
String ste = Thread.currentThread().getStackTrace()[TRACE_LINE].toString();
String separator = new String(new char[ste.length()]).replace('\0', '_');
System.out.println(separator);
System.out.println(ste);
System.out.println(str);
System.out.println(separator);
}
public static void printCurrentLine() {
System.out.println(Thread.currentThread().getStackTrace()[TRACE_LINE]);
}
public static String currentLine() {
return "(" + Thread.currentThread().getStackTrace()[TRACE_LINE] + ")";
}
public static ResultsTable print2RT(float[] cellData, String title) {
ResultsTable rt = new ResultsTable();
if (cellData == null)
return rt;
for (int i = 0; i < cellData.length; i++) {
rt.incrementCounter();
rt.addValue(title, cellData[i]);
}
return rt;
}
public static ResultsTable print2RT(double[] cellData, String title) {
ResultsTable rt = new ResultsTable();
if (cellData == null)
return rt;
for (int i = 0; i < cellData.length; i++) {
rt.incrementCounter();
rt.addValue(title, cellData[i]);
}
return rt;
}
public static ResultsTable print2RT(int[] cellData, String title) {
ResultsTable rt = new ResultsTable();
if (cellData == null)
return rt;
for (int i = 0; i < cellData.length; i++) {
rt.incrementCounter();
rt.addValue(title, cellData[i]);
}
return rt;
}
public static void printMinMax(double[] cellData) {
if (cellData == null) {
System.out.println("input data is null");
return;
}
if (cellData.length == 0) {
System.out.println("input data has 0 element");
return;
}
double min = Double.POSITIVE_INFINITY, max = Double.NEGATIVE_INFINITY;
for (int i = 0; i < cellData.length; i++) {
if (min > cellData[i])
min = cellData[i];
if (max < cellData[i])
max = cellData[i];
}
System.out.println("max: " + max + ", min: " + min);
}
public static void print(Vector<?> data){
Iterator<?> it = data.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
public static void print(float[][] cellData){
if (cellData == null) {
System.out.println("input data is null");
return;
}
if (cellData.length == 0) {
System.out.println("input data has 0 element");
return;
}
for (int i = 0; i < cellData.length; i++){
if (cellData[i] != null){
for (int j = 0; j < cellData[i].length; j++)
System.out.print(cellData[i][j] + " ");
}
System.out.println();
}
}
public static void print(int[][] cellData){
if (cellData == null) {
System.out.println("input data is null");
return;
}
if (cellData.length == 0) {
System.out.println("input data has 0 element");
return;
}
for (int i = 0; i < cellData.length; i++){
if (cellData[i] != null){
for (int j = 0; j < cellData[i].length; j++)
System.out.print(cellData[i][j] + " ");
}
System.out.println();
}
}
public static void print(double[][] cellData){
if (cellData == null) {
System.out.println("input data is null");
return;
}
if (cellData.length == 0) {
System.out.println("input data has 0 element");
return;
}
for (int i = 0; i < cellData.length; i++){
if (cellData[i] != null){
for (int j = 0; j < cellData[i].length; j++)
System.out.print(cellData[i][j] + " ");
}
System.out.println();
}
}
public static void print(byte[][] cellData){
if (cellData == null) {
System.out.println("input data is null");
return;
}
if (cellData.length == 0) {
System.out.println("input data has 0 element");
return;
}
for (int i = 0; i < cellData.length; i++){
if (cellData[i] != null){
for (int j = 0; j < cellData[i].length; j++)
System.out.print(cellData[i][j] + " ");
}
System.out.println();
}
}
public static<T> void print(T[] data){
for(T element: data){
System.out.println(element);
}
}
public static void print(byte[] cellData) {
if (cellData == null) {
System.out.println("input data is null");
return;
}
if (cellData.length == 0) {
System.out.println("input data has 0 element");
return;
}
for (int i = 0; i < cellData.length; i++)
System.out.print(cellData[i] + " ");
System.out.println();
}
public static void print(boolean[] cellData) {
if (cellData == null) {
System.out.println("input data is null");
return;
}
if (cellData.length == 0) {
System.out.println("input data has 0 element");
return;
}
for (int i = 0; i < cellData.length; i++)
System.out.print(cellData[i] + " ");
System.out.println();
}
public static void print(int[] cellData) {
if (cellData == null) {
System.out.println("input data is null");
return;
}
if (cellData.length == 0) {
System.out.println("input data has 0 element");
return;
}
for (int i = 0; i < cellData.length; i++)
System.out.print(cellData[i] + " ");
System.out.println();
}
public static void print(float[] cellData) {
if (cellData == null) {
System.out.println("input data is null");
return;
}
if (cellData.length == 0) {
System.out.println("input data has 0 element");
return;
}
for (int i = 0; i < cellData.length; i++)
System.out.print(cellData[i] + " ");
System.out.println();
}
public static void print(double[] cellData) {
if (cellData == null) {
System.out.println("input data is null");
return;
}
if (cellData.length == 0) {
System.out.println("input data has 0 element");
return;
}
for (int i = 0; i < cellData.length; i++)
System.out.print(cellData[i] + " ");
System.out.println();
}
public static void print(float[] cellData1, float[] cellData2, int stopID) {
int len = cellData1.length > cellData2.length ? cellData1.length : cellData2.length;
for (int i = 0; i < len && i < stopID; i++)
System.out.println(i + " " + cellData1[i] + ", " + cellData2[i]);
}
public static void printCellData(CellData cellData1, CellData cellData2, int stopID) {
int len = cellData1.length() > cellData2.length() ? cellData1.length() : cellData2.length();
for (int i = 0; i < len && i < stopID; i++)
System.out.println(i + " " + cellData1.getPixel(i) + ", " + cellData2.getPixel(i));
}
public static void printCellData(CellData cellData1, CellData cellData2) {
int len = cellData1.length() > cellData2.length() ? cellData1.length() : cellData2.length();
for (int i = 0; i < len; i++)
if (!(Float.isNaN(cellData1.getPixel(i)) || Float.isNaN(cellData2.getPixel(i))))
System.out.println(i + " " + cellData1.getPixel(i) + ", " + cellData2.getPixel(i));
}
public static ResultsTable printCellData(CellData cellData1, CellData cellData2, ResultsTable rt) {
int len = cellData1.length() > cellData2.length() ? cellData1.length() : cellData2.length();
if (rt == null)
rt = new ResultsTable();
else
rt.reset();
for (int i = 0; i < len; i++) {
rt.incrementCounter();
rt.addValue("index", i);
rt.addValue("C1", cellData1.getPixel(i));
rt.addValue("C2", cellData2.getPixel(i));
}
return rt;
}
/**
* Print only the first time this method is called on a particular line
*/
private static StackTraceElement printLock = null;
public static void print1(String str) {
if (!Thread.currentThread().getStackTrace()[TRACE_LINE].equals(printLock)) {
printLock = Thread.currentThread().getStackTrace()[TRACE_LINE];
System.out.println(str);
}
}
public static long myTimer = System.currentTimeMillis();
public void debugHistogram() {
ImagePlus imp = IJ.openImage("D:\\360Sync\\OneDrive\\Temp\\test\\sodB-716_100_Phase-1.tif");
// ImagePlus imp = WindowManager.getCurrentImage();
if (imp == null) {
System.out.println("imp");
return;
}
imp.show();
IJ.run(imp, "Fire", "");
HistogramStackWindow plotstack = new HistogramStackWindow(imp);
if (plotstack instanceof StackWindow)
System.out.println("plotstack instanceof StackWindow");
if (plotstack instanceof HistogramStackWindow)
System.out.println("plotstack instanceof StackHistogramWindow");
}
public static void printCellData(CellData[] cellData) {
for (int i = 0; i < cellData.length; i++) {
if (cellData[i] == null)
continue;
System.out.print("Cell-" + i + ": ");
for (int iPixel = 0; iPixel < (cellData[i].length() <= 20 ? cellData[i].length() : 20); iPixel++) {
System.out.print(cellData[i].getPixel(iPixel) + " ");
}
System.out.println();
}
}
public static void printAllOptions(int options) {
System.out.println(String.format("%32s", Integer.toBinaryString(options)).replace(' ', '0') + " : options");
printAllOptions();
}
public static void printAllOptions() {
// System.out.println(String.format("%32s",
// Integer.toBinaryString(DO_TOSH)).replace(' ', '0') + " : DO_TOSH");
// System.out.println(String.format("%32s",
// Integer.toBinaryString(DO_TOSMAX)).replace(' ', '0') + " :
// DO_TOSMAX");
// System.out.println(String.format("%32s",
// Integer.toBinaryString(DO_TOSMIN)).replace(' ', '0') + " :
// DO_TOSMIN");
System.out.println(String.format("%32s", Integer.toBinaryString(DO_MATRIX)).replace(' ', '0') + " : DO_MTOS");
System.out.println(String.format("%32s", Integer.toBinaryString(DO_PCC)).replace(' ', '0') + " : DO_PCC");
System.out.println(String.format("%32s", Integer.toBinaryString(DO_SRC)).replace(' ', '0') + " : DO_SRC");
System.out.println(String.format("%32s", Integer.toBinaryString(DO_MCC)).replace(' ', '0') + " : DO_MCCT");
System.out.println(String.format("%32s", Integer.toBinaryString(DO_ICQ)).replace(' ', '0') + " : DO_ICQ");
System.out.println(String.format("%32s", Integer.toBinaryString(DO_AVGINT)).replace(' ', '0') + " : DO_AVGINT");
System.out
.println(String.format("%32s", Integer.toBinaryString(DO_SCATTER)).replace(' ', '0') + " : DO_SCATTER");
System.out.println(
String.format("%32s", Integer.toBinaryString(DO_HEAT_CELL)).replace(' ', '0') + " : DO_HEAT_CELL");
System.out.println(
String.format("%32s", Integer.toBinaryString(DO_HEAT_IMG)).replace(' ', '0') + " : DO_HEAT_IMG");
System.out.println(
String.format("%32s", Integer.toBinaryString(DO_HEAT_STACK)).replace(' ', '0') + " : DO_HEAT_STACK");
System.out.println(
String.format("%32s", Integer.toBinaryString(DO_LINEAR_TOS)).replace(' ', '0') + " : DO_LINEAR_TOS");
System.out.println(
String.format("%32s", Integer.toBinaryString(DO_LOG2_TOS)).replace(' ', '0') + " : DO_LOG10_TOS");
System.out.println(String.format("%32s", Integer.toBinaryString(DO_LN_TOS)).replace(' ', '0') + " : DO_LN_TOS");
System.out.println(
String.format("%32s", Integer.toBinaryString(DO_RESULTTABLE)).replace(' ', '0') + " : DO_RESULTTABLE");
System.out
.println(String.format("%32s", Integer.toBinaryString(DO_SUMMARY)).replace(' ', '0') + " : DO_SUMMARY");
System.out.println(String.format("%32s", Integer.toBinaryString(DO_HIST)).replace(' ', '0') + " : DO_HIST");
System.out.println(String.format("%32s", Integer.toBinaryString(DO_CUSTOM)).replace(' ', '0') + " : DO_CUSTOM");
System.out.println(String.format("%32s", Integer.toBinaryString(DO_MASKS)).replace(' ', '0') + " : DO_MASKS");
System.out.println(String.format("%32s", Integer.toBinaryString(DO_ROIS)).replace(' ', '0') + " : DO_ROIS");
}
public static void printSelectedOptions(int options) {
System.out.println(String.format("%32s", Integer.toBinaryString(options)).replace(' ', '0') + " : options");
if (options == 0) {
System.out.println("No option is selected");
return;
}
// if((options & DO_TOSH)!=0)
// System.out.println("DO_TOSH");
// if((options & DO_TOSMAX)!=0)
// System.out.println("DO_TOSMAX");
// if((options & DO_TOSMIN)!=0)
// System.out.println("DO_TOSMIN");
if ((options & DO_MATRIX) != 0)
System.out.println("DO_MTOS");
if ((options & DO_PCC) != 0)
System.out.println("DO_PCC");
if ((options & DO_SRC) != 0)
System.out.println("DO_SRC");
if ((options & DO_MCC) != 0)
System.out.println("DO_MCC");
if ((options & DO_ICQ) != 0)
System.out.println("DO_ICQ");
if ((options & DO_AVGINT) != 0)
System.out.println("DO_AVGINT");
if ((options & DO_SCATTER) != 0)
System.out.println("DO_SCATTER");
// if((options & DO_HEAT1)!=0)
// System.out.println("DO_HEAT1");
// if((options & DO_HEAT2)!=0)
// System.out.println("DO_HEAT2");
if ((options & DO_HEAT_CELL) != 0)
System.out.println("DO_HEAT_CELL");
if ((options & DO_HEAT_IMG) != 0)
System.out.println("DO_HEAT_IMG");
if ((options & DO_HEAT_STACK) != 0)
System.out.println("DO_HEAT_STACK");
if ((options & DO_LINEAR_TOS) != 0)
System.out.println("DO_LINEAR_TOS");
if ((options & DO_LOG2_TOS) != 0)
System.out.println("DO_LOG10_TOS");
if ((options & DO_LN_TOS) != 0)
System.out.println("DO_LN_TOS");
if ((options & DO_RESULTTABLE) != 0)
System.out.println("DO_RESULTTABLE");
if ((options & DO_SUMMARY) != 0)
System.out.println("DO_SUMMARY");
if ((options & DO_HIST) != 0)
System.out.println("DO_HIST");
if ((options & DO_CUSTOM) != 0)
System.out.println("DO_CUSTOM");
if ((options & DO_MASKS) != 0)
System.out.println("DO_MASKS");
if ((options & DO_ROIS) != 0)
System.out.println("DO_ROIS");
}
public static final String LOG_TITLE = PluginStatic.getPlugInName() + " errors";
private static TextWindow logWindow;
public static synchronized void log(String s) {
if (s == null)
return;
TextPanel logPanel = null;
if (logWindow == null && IJ.getInstance() != null) {
logWindow = new TextWindow(LOG_TITLE, "", 400, 250);
logPanel = logWindow.getTextPanel();
logPanel.setFont(new Font("SansSerif", Font.PLAIN, 16));
} else
logPanel = logWindow.getTextPanel();
if (logPanel != null) {
if (s.startsWith("\\"))
handleLogCommand(s);
else
logPanel.append(s);
} else {
LogStream.redirectSystem(false);
System.out.println(s);
}
logWindow.setVisible(true);
}
static void handleLogCommand(String s) {
if (logWindow == null)
return;
TextPanel logPanel = logWindow.getTextPanel();
if (s.equals("\\Closed"))
logPanel = null;
else if (s.startsWith("\\Update:")) {
int n = logPanel.getLineCount();
String s2 = s.substring(8, s.length());
if (n == 0)
logPanel.append(s2);
else
logPanel.setLine(n - 1, s2);
} else if (s.startsWith("\\Update")) {
int cindex = s.indexOf(":");
if (cindex == -1) {
logPanel.append(s);
return;
}
String nstr = s.substring(7, cindex);
int line = (int) Tools.parseDouble(nstr, -1);
if (line < 0 || line > 25) {
logPanel.append(s);
return;
}
int count = logPanel.getLineCount();
while (line >= count) {
log("");
count++;
}
String s2 = s.substring(cindex + 1, s.length());
logPanel.setLine(line, s2);
} else if (s.equals("\\Clear")) {
logPanel.clear();
} else if (s.startsWith("\\Heading:")) {
logPanel.updateColumnHeadings(s.substring(10));
} else if (s.equals("\\Close")) {
Frame f = WindowManager.getFrame("Log");
if (f != null && (f instanceof TextWindow))
((TextWindow) f).close();
} else
logPanel.append(s);
}
public static void getFields(String name, int modifier, Class<?> mother) {
Class<?> c = null;
try {
c = Class.forName(name);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
Field[] declaredFields = c.getDeclaredFields();
List<Field> staticFields = new ArrayList<Field>();
for (Field field : declaredFields) {
if ((field.getModifiers() == modifier) && (mother == null || mother.isAssignableFrom(field.getType())))
staticFields.add(field);
}
for (Field f : staticFields)
IJ.log(f.getName());
}
private static double roundDouble(double d) {
return roundDouble(d, 3);
}
private static double roundDouble(double d, int digit) {
BigDecimal bd = new BigDecimal(d);
bd = bd.round(new MathContext(3));
return bd.doubleValue();
}
public static String getTime(String name, String unit) {
double scalor;
switch (unit) {
case "s":
scalor = 1000000000;
break;
case "ms":
scalor = 1000000;
break;
case "ns":
scalor = 1;
break;
default:
scalor = 1000000;
unit = "ms";
break;
}
if (timeMap.containsKey(name))
return roundDouble((System.nanoTime() - timeMap.get(name)) / scalor) + " " + unit;
else
return "Time was not set";
}
public static void setTime(String name) {
timeMap.put(name, System.nanoTime());
}
public static long getTime(String name) {
if (timeMap.containsKey(name))
return System.nanoTime() - timeMap.get(name);
else
return System.nanoTime();
}
public static void printTime(String name, String unit){
System.out.println(getTime(name, unit));
}
public static int countNaN(float[] data) {
int count = 0;
for (int i = 0; i < data.length; i++) {
if(Float.isNaN(data[i]))
count ++;
}
return count;
}
}
| 19,398 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
ExceptionHandler.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/debug/ExceptionHandler.java | package ezcol.debug;
import java.awt.Font;
import java.awt.Frame;
import java.io.CharArrayWriter;
import java.io.PrintWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import ezcol.align.TurboRegMod;
import ezcol.cell.CellData;
import ezcol.main.PluginConstants;
import ezcol.main.PluginStatic;
import ezcol.visual.visual2D.HistogramStackWindow;
import ij.IJ;
import ij.ImagePlus;
import ij.Macro;
import ij.WindowManager;
import ij.gui.StackWindow;
import ij.io.LogStream;
import ij.measure.ResultsTable;
import ij.text.TextPanel;
import ij.text.TextWindow;
import ij.util.Tools;
/**
* This class catches most if not all waring and error messages during analysis
* and print it in the log window.
*
* @author Huanjie Sheng
*
*/
public class ExceptionHandler implements PluginConstants {
// [0] Thread.getStackTrace
// [1] ExceptionReporter
// [2] The line where addError is called
private static final int TRACE_LINE = 2;
private static final String SEPARATOR = "-------------------------";
private static Vector<String> errors = new Vector<String>();
private static Vector<String> warnings = new Vector<String>();
private static Vector<Throwable> exceptions = new Vector<Throwable>();
private static Vector<Thread> threads = new Vector<Thread>();
private static Set<String> synSet = Collections.synchronizedSet(new HashSet<String>());
public static final String LOG_TITLE = PluginStatic.getPlugInName() + " errors";
private static TextWindow logWindow;
public static final String NAN_WARNING = "NaN values are usually caused by \n"
+ "1. Too Many Ties (i.e. saturated pixels) \n"
+ "2. Too Few Pixels Above Thresholds (i.e. thresholds too high or cell too small)\n";
//+ "3. No thresholds (i.e. thresholds are set to 100% while calculating TOS)";
private static UncaughtExceptionHandler threadException = new UncaughtExceptionHandler() {
public void uncaughtException(Thread th, Throwable ex) {
threads.add(th);
exceptions.add(ex);
}
};
public void uncaughtException(Thread th, Throwable ex) {
threadException.uncaughtException(th, ex);
}
public static synchronized void addException(Exception ex) {
addStackTraceElements(ex.getStackTrace());
}
public static synchronized void addStackTraceElements(StackTraceElement[] stes) {
for (StackTraceElement ste : stes)
ExceptionHandler.addError(ste.toString());
}
public static synchronized void addError(String str) {
if (synSet.contains(str))
return;
synSet.add(str);
errors.addElement(str);
}
private static synchronized void addError(String str, int index) {
if (synSet.contains(str))
return;
synSet.add(str);
errors.insertElementAt(str, index);
}
public static void insertError(Thread thread, String str) {
addError("(" + thread.getStackTrace()[TRACE_LINE] + "): " + str, 0);
}
public static void addError(Object obj, String str) {
addError(obj.getClass().getName() + ": " + str);
}
public static void addError(Object obj, Thread thread, String str) {
addError(obj.getClass().getName() + "(" + thread.getStackTrace()[TRACE_LINE] + "): " + str);
}
public static void addError(Thread thread, String str) {
addError("(" + thread.getStackTrace()[TRACE_LINE] + "): " + str);
}
public static synchronized void addWarning(String str) {
if (synSet.contains(str))
return;
synSet.add(str);
warnings.addElement(str);
}
private static synchronized void addWarning(String str, int index) {
if (synSet.contains(str))
return;
synSet.add(str);
warnings.insertElementAt(str, index);
}
public static void insertWarning(Thread thread, String str) {
addWarning("(" + thread.getStackTrace()[TRACE_LINE] + "): " + str, 0);
}
public static void addWarning(Object obj, Thread thread, String str) {
addWarning(obj.getClass().getName() + "(" + thread.getStackTrace()[TRACE_LINE] + "): " + str);
}
public static void addWarning(Thread thread, String str) {
addWarning("(" + thread.getStackTrace()[TRACE_LINE] + "): " + str);
}
public static void addWarning(Object obj, String str) {
addWarning(obj.getClass().getName() + ": " + str);
}
public static UncaughtExceptionHandler getExceptionHandler() {
return threadException;
}
public static void flush() {
errors.clear();
warnings.clear();
synSet.clear();
}
public static void printStackTrace(int num) {
if (Thread.currentThread() != null)
for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
System.out.println(ste);
num--;
if (num <= 0)
break;
}
}
public static String currentLine() {
return "(" + Thread.currentThread().getStackTrace()[TRACE_LINE] + ")";
}
public static String getError(int index) {
if (index < errors.size())
return errors.elementAt(index);
else
return null;
}
public static String getWarning(int index) {
if (index < warnings.size())
return warnings.elementAt(index);
else
return null;
}
public static int errorSize() {
return errors.size();
}
public static int warningSize() {
return warnings.size();
}
public static int getCounter() {
return errors.size() + warnings.size();
}
public static void dump() {
dump(true);
}
public static void dump(boolean flush) {
System.out.println("All errors: ");
for (String str : errors)
System.out.println(str);
System.out.println("All warnings: ");
for (String str : warnings)
System.out.println(str);
if (flush)
flush();
}
public static void print2log() {
print2log(true);
}
public static void print2log(boolean flush) {
if (errors.size() > 0)
log("******************Errors******************");
for (String str : errors)
log(str);
if (warnings.size() > 0)
log("******************Warnings******************");
for (String str : warnings)
log(str);
if (flush)
flush();
}
public static synchronized void log(String s) {
if (s == null)
return;
TextPanel logPanel = null;
if (logWindow == null && IJ.getInstance() != null) {
logWindow = new TextWindow(LOG_TITLE, "", 400, 250);
logPanel = logWindow.getTextPanel();
logPanel.setFont(new Font("SansSerif", Font.PLAIN, 16));
} else
logPanel = logWindow.getTextPanel();
if (logPanel != null) {
if (s.startsWith("\\"))
handleLogCommand(s);
else
logPanel.append(s);
} else {
LogStream.redirectSystem(false);
System.out.println(s);
}
logWindow.setVisible(true);
}
static void handleLogCommand(String s) {
if (logWindow == null)
return;
TextPanel logPanel = logWindow.getTextPanel();
if (s.equals("\\Closed"))
logPanel = null;
else if (s.startsWith("\\Update:")) {
int n = logPanel.getLineCount();
String s2 = s.substring(8, s.length());
if (n == 0)
logPanel.append(s2);
else
logPanel.setLine(n - 1, s2);
} else if (s.startsWith("\\Update")) {
int cindex = s.indexOf(":");
if (cindex == -1) {
logPanel.append(s);
return;
}
String nstr = s.substring(7, cindex);
int line = (int) Tools.parseDouble(nstr, -1);
if (line < 0 || line > 25) {
logPanel.append(s);
return;
}
int count = logPanel.getLineCount();
while (line >= count) {
log("");
count++;
}
String s2 = s.substring(cindex + 1, s.length());
logPanel.setLine(line, s2);
} else if (s.equals("\\Clear")) {
logPanel.clear();
} else if (s.startsWith("\\Heading:")) {
logPanel.updateColumnHeadings(s.substring(10));
} else if (s.equals("\\Close")) {
Frame f = WindowManager.getFrame("Log");
if (f != null && (f instanceof TextWindow))
((TextWindow) f).close();
} else
logPanel.append(s);
}
public static void printSeparator() {
System.out.println(SEPARATOR);
}
public static void dumpVector(Vector<?> vec) {
for (int i = 0; i < vec.size(); i++)
System.out.println(vec.get(i));
}
/**
* Displays a stack trace.
*/
public static void handleException(Throwable e) {
if (Macro.MACRO_CANCELED.equals(e.getMessage()))
return;
CharArrayWriter caw = new CharArrayWriter();
PrintWriter pw = new PrintWriter(caw);
e.printStackTrace(pw);
String s = caw.toString();
if (IJ.getInstance() != null) {
s = IJ.getInstance().getInfo() + "\n \n" + PluginStatic.getInfo() + "\n \n" + s;
new TextWindow(PluginStatic.getPlugInName() + " Exception", s, 500, 340);
} else {
s = PluginStatic.getInfo() + "\n \n" + s;
new TextWindow(PluginStatic.getPlugInName() + " Exception", s, 500, 340);
}
}
}
| 8,785 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
BasicCalculator.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/metric/BasicCalculator.java | package ezcol.metric;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import ezcol.cell.CellData;
import ezcol.cell.DataSorter;
import ezcol.debug.ExceptionHandler;
import ezcol.main.PluginConstants;
public abstract class BasicCalculator {
public static final int DEFAULT_FT = PluginConstants.DEFAULT_FT;
// options determines which metric to calculate
// the list of options is in MetricResults
protected int options;
protected int numOfCell;
// pixel values of two channels, each element is one cell
protected CellData[][] cellCs, allCs, costesCs;
protected Map<Integer, CellData[]>[] ftCs;
// this should match with defaultColumnNames
public static final String SHOW_TOS_LINEAR = "TOS(linear)", SHOW_TOS_LOG2 = "TOS(log2)", SHOW_PCC = "PCC",
SHOW_SRC = "SRCC", SHOW_ICQ = "ICQ", SHOW_M1 = "M1", SHOW_M2 = "M2", SHOW_M3 = "M3",
SHOW_MCC = "M", SHOW_AVGINT = "Avg.Int.C", SHOW_CUSTOM = "Custom";
public static final int LAST_METRIC = 8;
static final String[] DEFAULT_METRIC_ACRONYMS = { SHOW_TOS_LINEAR, SHOW_TOS_LOG2, SHOW_PCC, SHOW_SRC, SHOW_ICQ, SHOW_MCC,
SHOW_AVGINT, SHOW_CUSTOM };
// this part include all variables which are calculated here
// Change in 1.1.0, for every metric, there is a string array with three elements
// name, interpretation, hyperlink
static final String[][] DEFAULT_INTPNS = makeIntpns();
/**
* percentages and can be used as markers
* MUST use negative numbers here so they do NOT overlap with selected
*/
public static final int THOLD_ALL = -1, THOLD_COSTES = -2, THOLD_FT = -3, THOLD_NONE = -4;
public static final int[] LIST_THOLD_OPTS = { THOLD_ALL, THOLD_COSTES, THOLD_FT };
protected int[] tholdMetrics;
protected int[][] tholdFTs;
// All derived classes should be put here
public BasicCalculator() {
cutoffs = new int[] { DEFAULT_FT, DEFAULT_FT };
numFT2SF();
}
public BasicCalculator(int options) {
this();
this.options = options;
}
public BasicCalculator(BasicCalculator callBase) {
this.options = callBase.options;
this.numOfCell = callBase.numOfCell;
this.cellCs = callBase.cellCs;
this.allCs = callBase.allCs;
this.costesCs = callBase.costesCs;
}
public static int getThold(int i) {
if (i < 0 || i >= LIST_THOLD_OPTS.length)
return THOLD_NONE;
else
return LIST_THOLD_OPTS[i];
}
/**
* get the number of metric names it is also the number of metrics
* calculated in the derived class
*
* @return
*/
public static int getNum() {
return DEFAULT_METRIC_ACRONYMS.length;
}
/**
* get the name of the metric
*
* @param i
* index of the metric
* @return the name of i-th metric
*/
public static String getNames(int i) {
if (i < 0 || i >= DEFAULT_METRIC_ACRONYMS.length)
return null;
return DEFAULT_METRIC_ACRONYMS[i];
}
/**
* get the interpretation of the i-th metric, the extended class should
* override this method
*
* @param i
* the index
* @return
*/
public static String[] getIntpn(int i) {
if (i < 0 || i >= DEFAULT_INTPNS.length)
return null;
return DEFAULT_INTPNS[i];
}
public static String[] getIntpn(int i, int channel) {
if (i < 0 || i >= DEFAULT_INTPNS.length)
return null;
String[] pair =DEFAULT_INTPNS[i];
return new String[]{pair[0]+" of Channel "+channel, pair[1]};
}
public static String[] getAllMetrics() {
return DEFAULT_METRIC_ACRONYMS.clone();
}
private static String[][] makeIntpns() {
String[][] pairs = new String[LAST_METRIC][2];
List<String> metricNames = Arrays.asList(DEFAULT_METRIC_ACRONYMS);
pairs[metricNames.indexOf(SHOW_TOS_LINEAR)] = new String[]{
"Threshold Overlap Score linearly rescaled [TOS(linear)]",
"TOS(linear) is a measure of the overlap of pixels above the threshold "
+ "for two or three reporter channels, normalized for the expected overlap to occur by chance, "
+ "which is rescaled so the value is a fraction of the difference between the null hypothesis and "
+ "the maximum possible colocalization or anticolocalization for the selected thresholds.\n"
+ "For example, 0.5 is halfway between the null distribution and complete overlap for the selected percentages.\n"
+ "\n"
+ "-1 = complete anticolocalization\n"
+ "0 = noncolocalization\n"
+ "1 = complete colocalization\n"
,
"http://bio.biologists.org/content/5/12/1882.long"
};
pairs[metricNames.indexOf(SHOW_TOS_LOG2)] = new String[]{
"Threshold Overlap Score logarithmically rescaled [TOS(log2)]",
"TOS(log) is the same as TOS(linear) except the rescaling is logarithmic instead of linear.\n"
+ "For example: 0.5 is halfway between the null distribution and complete overlap "
+ "of selected percentages on the log scale.\n"
+ "\n"
+ "-1 = complete anticolocalization\n"
+ "0 = noncolocalization\n"
+ "1 = complete colocalization\n"
,
"http://bio.biologists.org/content/5/12/1882.long"
};
pairs[metricNames.indexOf(SHOW_PCC)] = new String[]{
"Pearson's Correlation Coefficient (PCC)",
"PCC measures the correlation between the pixel values for two reporter channels.\n"
+ "\n"
+ "-1 = complete anticolocalization\n"
+ "0 = noncolocalization\n"
+ "1 = complete colocalization\n"
,
"https://en.wikipedia.org/wiki/Pearson_correlation_coefficient"
};
pairs[metricNames.indexOf(SHOW_SRC)] = new String[]{
"Spearman's Rank Correlation Coefficient (SRCC)",
"SRCC measures the ranked correlation of pixel values for two reporter channels.\n"
+ "\n"
+ "-1 = complete anticolocalization\n"
+ "0 = noncolocalization\n"
+ "1 = complete colocalization\n"
,
"https://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient"
};
pairs[metricNames.indexOf(SHOW_ICQ)] = new String[]{
"Intensity Correlation Quotient (ICQ)",
"ICQ measures the proportion of pixels that "
+ "are below or above the mean for all of two or three reporter channels.\n"
+ "\n"
+ "-0.5 = complete anticolocalization\n"
+ "0 = noncolocalization\n"
+ "0.5 = complete colocalization\n"
,
"http://www.jneurosci.org/content/24/16/4070.long"
};
pairs[metricNames.indexOf(SHOW_MCC)] = new String[]{
"Manders' Colocalization Coefficient (MCC; components M1, M2, and M3)",
"MCC measures the intensity weighted proportion of signal which overlaps above the thresholds for two or three channels.\n"
+ "\n"
+ "0 = complete anticolocalization \n"
+ "1 = complete colocalization \n"
,
"https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1365-2818.1993.tb03313.x"};
pairs[metricNames.indexOf(SHOW_AVGINT)] = new String[]{
"Average Signal Intensity (Avg.Int.)",
"Selection of the average signal intensity option generates a table that "
+ "has the average signal intensity of each reporter channel and "
+ "the physical measurements of each cell in the sample.\n",
null
};
pairs[metricNames.indexOf(SHOW_CUSTOM)] = new String[]{
"Custom Metric",
"Custom Metric allows users to code their own analysis of "
+ "the selected pixel values using mathematical functions in Java. "
+ "The calculation of PCC is provided as an example.\n",
null
};
return pairs;
}
public void setOptions(int options) {
this.options = options;
}
public double round(double value, int places) {
if (places < 0)
places = 0;// throw new IllegalArgumentException();
try {
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
} catch (Exception e) {
return value;
}
}
public double getMedian(float[] array) {
if (array == null)
return Double.NaN;
Arrays.sort(array);
double median;
if (array.length % 2 == 0)
median = ((double) array[array.length / 2] + (double) array[array.length / 2 - 1]) / 2;
else
median = (double) array[array.length / 2];
return median;
}
/**
* This is double because it only applies to the results
*
* @param array
* @return the median value of the input array
*/
public double getMedian(double[] array) {
if (array == null || array.length <= 0)
return Double.NaN;
Arrays.sort(array);
double median;
if (array.length % 2 == 0)
median = (array[array.length / 2] + array[array.length / 2 - 1]) / 2;
else
median = array[array.length / 2];
return median;
}
public float[] toFloatArray(double[] arr) {
if (arr == null)
return null;
int n = arr.length;
float[] ret = new float[n];
for (int i = 0; i < n; i++) {
ret[i] = (float) arr[i];
}
return ret;
}
/**
* <link>http://stackoverflow.com/questions/15725370/write-a-mode-method-in-
* java-to-find-the-most-frequently-occurring-element-in-an</link>
*
* @author codemania23
* @param array
* @return
*/
public double getMode(double[] array) {
if (array == null || array.length <= 0)
return Double.NaN;
Map<Double, Integer> hm = new HashMap<Double, Integer>();
double max = 1, temp = array[0];
for (int i = 0; i < array.length; i++) {
if (hm.get(array[i]) != null) {
int count = hm.get(array[i]);
count = count + 1;
hm.put(array[i], count);
if (count > max) {
max = count;
temp = array[i];
}
} else {
hm.put(array[i], 1);
}
}
return temp;
}
/**
* calculate the mean of the array
*
* @param array
* input array
* @return mean
*/
public double getMean(double[] array) {
if (array == null)
return Double.NaN;
double result = 0.0;
int size = array.length;
for (int i = 0; i < size; i++)
result += array[i];
return result / (double) size;
}
/**
* calculate the mean of the array
*
* @param array
* input array
* @return mean
*/
public double getMean(float[] array) {
if (array == null)
return Double.NaN;
double result = 0.0;
int size = array.length;
for (int i = 0; i < size; i++)
result += array[i];
return result / (double) size;
}
/**
* calculate standard deviation of the array
*
* @param a
* input array
* @param aMean
* mean of the input array for given size
* @return standard deviation
*/
public double getSTD(float[] a, double aMean) {
if (a == null)
return Double.NaN;
double[] b = new double[a.length];
for (int i = 0; i < a.length; i++)
b[i] = a[i] * a[i];
return Math.sqrt(getMean(b) - aMean * aMean);
}
/**
* calculate standard deviation of the array
*
* @param a
* input array
* @param aMean
* mean of the input array for given size
* @return standard deviation
*/
public double getSTD(double[] a, double aMean) {
if (a == null)
return Double.NaN;
double[] b = a.clone();
for (int i = 0; i < a.length; i++)
b[i] *= b[i];
return Math.sqrt(getMean(b) - aMean * aMean);
}
/**
* calculate the sum of the array
*
* @param a
* input array
* @return sum
*/
public double getSum(float[] a) {
if (a == null)
return Double.NaN;
double result = 0.0;
for (int i = 0; i < a.length; i++)
result += a[i];
return result;
}
/**
* calculate the sum of the array above the threshold
*
* @param a
* input array
* @param threshold
* @return sum of elements above the threshold
*/
public double getSum(float[] a, float threshold) {
if (a == null)
return Double.NaN;
double result = 0.0;
for (int i = 0; i < a.length; i++)
if (a[i] > threshold)
result += a[i];
return result;
}
/**
* Version 1.2 add: getMatrix
*
*/
protected int[] cutoffs;
protected double[][] sfsCs;
public BasicCalculator(int options, int[] cutoffs) {
this(cutoffs);
this.options = options;
}
public BasicCalculator(int[] cutoffs) {
if (cutoffs != null && cutoffs.length >= 2)
this.cutoffs = cutoffs.clone();
else
this.cutoffs = new int[] { 9, 9 };
numFT2SF();
}
public double[] getSFs(int channel, boolean reverse) {
if (sfsCs == null)
return null;
else if (channel < sfsCs.length) {
if (reverse) {
double[] temp = sfsCs[channel].clone();
for (int i = 0; i < temp.length; i++)
temp[i] = sfsCs[channel][temp.length - 1 - i];
return temp;
} else
return sfsCs[channel].clone();
}
return null;
}
/*
* get the selected percentages that will be used in the mTOS Update: change
* from number of selected percentages to fraction itself disregard the
* extra fraction
*/
protected void numFT2SF() {
sfsCs = new double[cutoffs.length][];
for (int i = 0; i < cutoffs.length; i++) {
sfsCs[i] = new double[ft2length(cutoffs[i])];
for (int place = 0; place < sfsCs[i].length; place++)
if ((place + 1) * cutoffs[i] < 100.0)
sfsCs[i][place] = (place + 1) * cutoffs[i] / 100.0;
else
sfsCs[i][place] = 1.0;
}
}
/*
* get the selected fractions that will be used in the matrix heat map
* Update: change from number of selected percentages to fraction itself
* disregard the extra fraction
*
* @return not the fraction but the percentage
*/
public int[] numFT2SF(int fraction) {
if (fraction < 0)
return null;
int[] tempsf = new int[ft2length(fraction)];
for (int place = 1; place <= tempsf.length; place++)
if (place * fraction < 100)
tempsf[place - 1] = place * fraction;
else
tempsf[place - 1] = 100;
// tempsf[place-1] = round(place*fraction,SFdecimal);
return tempsf;
}
public static int ft2length(int ft) {
// return 100/ft-1+(100%ft==0?0:1);
return 100 / ft + (100 % ft == 0 ? 0 : 1);
}
/*
* public void setSFDecimal(int places){ SFdecimal = places; }
*/
public void setCutoff(int[] icut) {
if (icut != null && icut.length >= 2) {
cutoffs = icut.clone();
numFT2SF();
}
}
protected boolean prepCellData(CellData[] cellC1, CellData[] cellC2, Object obj) {
return prepCellData(new CellData[][] { cellC1, cellC2 }, obj);
}
@SuppressWarnings("unchecked")
protected boolean prepCellData(CellData[][] cellCs, Object obj) {
int[] threshold = null;
CellData[] celliC = null;
for (int iChannel = 0; iChannel < cellCs.length; iChannel++) {
if (cellCs[iChannel] == null)
return false;
else if (celliC != null && cellCs[iChannel].length != celliC.length)
return false;
else
celliC = cellCs[iChannel];
}
try {
threshold = (int[]) obj;
} catch (Exception e) {
if (threshold == null || threshold.length <= 0)
return false;
// e.printStackTrace();
}
this.numOfCell = celliC.length;
int iMetric = 0;
tholdMetrics = new int[threshold.length];
tholdFTs = new int[threshold.length][cellCs.length];
for (int iThold = 0; iThold < threshold.length; iThold++) {
switch (threshold[iThold]) {
case THOLD_ALL:
if (allCs == null)
allCs = new CellData[cellCs.length][];
for (int iChannel = 0; iChannel < cellCs.length; iChannel++) {
if (cellCs[iChannel] == null || allCs[iChannel] != null)
continue;
allCs[iChannel] = cellCs[iChannel].clone();
}
break;
case THOLD_COSTES:
if (costesCs == null)
costesCs = new CellData[cellCs.length][];
// Higher dimensional Costes' method can be added in the latter
// version
if (costesCs[0] != null || costesCs[1] != null)
break;
costesCs[0] = new CellData[cellCs[0].length];
costesCs[1] = new CellData[cellCs[1].length];
for (int i = 0; i < numOfCell; i++) {
CostesThreshold costesThold = new CostesThreshold();
float[] dataA = cellCs[0][i].getData();
float[] dataB = cellCs[1][i].getData();
double[] costes = costesThold.getCostesThrd(dataA, dataB);
int length = dataA.length < dataB.length ? dataA.length : dataB.length;
costesCs[0][i] = new CellData(cellCs[0][i].length());
costesCs[1][i] = new CellData(cellCs[1][i].length());
for (int ip = 0; ip < length; ip++) {
if (dataA[ip] > costes[0])
costesCs[0][i].setData(dataA[ip], cellCs[0][i].getPixelX(ip), cellCs[0][i].getPixelY(ip),
ip);
else
costesCs[0][i].setData(Float.NaN, cellCs[0][i].getPixelX(ip), cellCs[0][i].getPixelY(ip),
ip);
if (dataB[ip] > costes[1])
costesCs[1][i].setData(dataB[ip], cellCs[1][i].getPixelX(ip), cellCs[1][i].getPixelY(ip),
ip);
else
costesCs[1][i].setData(Float.NaN, cellCs[1][i].getPixelX(ip), cellCs[1][i].getPixelY(ip),
ip);
}
costesCs[0][i].sort();
costesCs[1][i].sort();
}
break;
case THOLD_FT:
if (ftCs == null)
ftCs = new HashMap[cellCs.length];
int ft = 0;
for (int iChannel = 0; iChannel < cellCs.length; iChannel++) {
try {
ft = threshold[iThold + iChannel + 1];
} catch (Exception e) {
return false;
}
// Record the ft immediately
tholdFTs[iMetric][iChannel] = ft;
if (ftCs[iChannel] == null)
ftCs[iChannel] = new HashMap<Integer, CellData[]>();
if (ftCs[iChannel].get(ft) != null)
continue;
CellData[] ftC = new CellData[cellCs[iChannel].length];
for (int i = 0; i < numOfCell; i++) {
int tholdA = (int) Math.ceil(cellCs[iChannel][i].length() * (double) ft / 100.0);
double[] rankA = cellCs[iChannel][i].getRank();
int length = rankA.length;
ftC[i] = new CellData(cellCs[iChannel][i].length());
for (int ip = 0; ip < length; ip++) {
if (rankA[ip] <= tholdA)
ftC[i].setData(cellCs[iChannel][i].getPixel(ip), cellCs[iChannel][i].getPixelX(ip),
cellCs[iChannel][i].getPixelY(ip), ip);
else
ftC[i].setData(Float.NaN, cellCs[iChannel][i].getPixelX(ip),
cellCs[iChannel][i].getPixelY(ip), ip);
}
ftC[i].sort();
ftCs[iChannel].put(ft, ftC);
}
}
break;
default:
break;
}
// if threshold[iThold] is a threshold marker, record it
// otherwise, pass
switch (threshold[iThold]) {
case THOLD_ALL:
case THOLD_COSTES:
case THOLD_FT:
case THOLD_NONE:
tholdMetrics[iMetric++] = threshold[iThold];
}
}
return true;
}
/*
* What needs to be calculated and universally defined must be stated here
*/
protected int TOSdecimal = 3;
public void setDecimal(int places) {
TOSdecimal = places;
}
double[] getTOS(CellData dataA, CellData dataB) {
if (dataA == null || dataB == null)
return new double[] { Double.NaN, Double.NaN };
final float[] a = dataA.getData();
final float[] b = dataB.getData();
if (a == null || b == null || a.length != b.length || a.length == 0) {
ExceptionHandler.addError(Thread.currentThread(), "Null pointer in cell data and parameter");
return new double[] { Double.NaN, Double.NaN };
}
int size = a.length;
double A = 0.0, AandB = 0.0, B = 0.0;
for (int idx = 0; idx < size; idx++) {
if (!Double.isNaN(a[idx]))
A++;
if (!Double.isNaN(b[idx]))
B++;
if ((!Double.isNaN(a[idx])) && (!Double.isNaN(b[idx])))
AandB++;
}
if (A == 0 || B == 0) {
ExceptionHandler.addError(Thread.currentThread(), "Some cells are either too small or have equal pixel values");
}
double exp1 = B / size, exp2 = A / size;
double poratioselected = AandB / size / exp1 / exp2;
double maxPOratio = 1 / Math.max(exp1, exp2);
double minPOratio;
double tos_linear = Double.NaN, tos_log2 = Double.NaN;
if (exp1 + exp2 <= 1)
minPOratio = 0;
else
minPOratio = (exp1 + exp2 - 1) / (exp1 * exp2);
// tos_linear
if (poratioselected == 1) {
if (maxPOratio == 1 || minPOratio == 1)
tos_linear = Double.NaN;
else
tos_linear = 0;
} else if (poratioselected < 1) {
tos_linear = (1 - poratioselected) / (minPOratio - 1);
} else if (poratioselected > 1) {
tos_linear = (poratioselected - 1) / (maxPOratio - 1);
} else if (!Double.isNaN(poratioselected)) {
ExceptionHandler.addError(Thread.currentThread(), "Error in calculating linear TOS");
tos_linear = Double.NaN;
} else {
tos_linear = Double.NaN;
}
// tos_log2
if (poratioselected == 1) {
if (maxPOratio == 1 || minPOratio == 1)
tos_log2 = Double.NaN;
else
tos_log2 = 0;
} else if (poratioselected > maxPOratio) {
tos_log2 = 1;
} else if (poratioselected < minPOratio) {
tos_log2 = -1;
} else if (exp1 != 0.5 && exp2 != 0.5) {
double log2 = Math.log(2);
double m = log2 / Math.log((maxPOratio - 1) / (1 - minPOratio));
double n = (maxPOratio + minPOratio - 2) / ((maxPOratio - 1) * (1 - minPOratio));
tos_log2 = m * Math.log(n * (poratioselected - 1) + 1) / log2;
if (Double.isNaN(tos_log2)) {
ExceptionHandler.addError(Thread.currentThread(), "Error in calculationg log TOS");
}
} else if (exp1 == 0.5 || exp2 == 0.5) {
tos_log2 = 2 / (maxPOratio - minPOratio) * (poratioselected - 1);
} else if (!Double.isNaN(poratioselected)) {
ExceptionHandler.addError(Thread.currentThread(), "Error in calculating log TOS");
tos_log2 = Double.NaN;
}
tos_linear = round(tos_linear, TOSdecimal);
if (tos_linear > 1)
tos_linear = 1;
if (tos_linear < -1)
tos_linear = -1;
tos_log2 = round(tos_log2, TOSdecimal);
if (tos_log2 > 1)
tos_log2 = 1;
if (tos_log2 < -1)
tos_log2 = -1;
return new double[] { tos_linear, tos_log2 };
}
double getPCC(CellData dataA, CellData dataB) {
if (dataA == null || dataB == null)
return Double.NaN;
float[] ta = dataA.getData();
float[] tb = dataB.getData();
if (ta == null || tb == null || ta.length != tb.length)
return Double.NaN;
float[] a = ta;
float[] b = tb;
int num = 0;
for (int i = 0; i < ta.length; i++) {
if (Float.isNaN(ta[i]) || Float.isNaN(tb[i]))
continue;
a[num] = ta[i];
b[num] = tb[i];
num++;
}
a = Arrays.copyOfRange(a, 0, num);
b = Arrays.copyOfRange(b, 0, num);
double aMean = getMean(a);
double bMean = getMean(b);
float[] c = a.clone();
for (int i = 0; i < a.length; i++)
c[i] *= b[i];
return (getMean(c) - aMean * bMean) / (getSTD(a, aMean) * getSTD(b, bMean));
}
double getSRCC(CellData dataA, CellData dataB) {
if (dataA == null || dataB == null)
return Double.NaN;
if (!dataA.isSorted())
dataA.sort();
if (!dataB.isSorted())
dataB.sort();
// Sorting is done together to increase performance
// The sorted indexes and ranks can be found in CellData
double[] ranktA = dataA.getRank();
double[] ranktB = dataB.getRank();
if (ranktA == null || ranktB == null || ranktA.length != ranktB.length)
return Double.NaN;
double[] rankA = ranktA;
double[] rankB = ranktB;
int num = 0;
for (int i = 0; i < ranktA.length; i++) {
if (Double.isNaN(ranktA[i]) || Double.isNaN(ranktB[i]))
continue;
rankA[num] = ranktA[i];
rankB[num] = ranktB[i];
num++;
}
rankA = Arrays.copyOfRange(rankA, 0, num);
rankB = Arrays.copyOfRange(rankB, 0, num);
// we use double instead of integer here to avoid out of range
// because the number of pixels in one image could be very large
double aMean = getMean(rankA);
double bMean = getMean(rankB);
double[] c = rankA.clone();
for (int i = 0; i < rankA.length; i++)
c[i] *= rankB[i];
return (getMean(c) - aMean * bMean) / (getSTD(rankA, aMean) * getSTD(rankB, bMean));
}
double getICQ(CellData dataA, CellData dataB) {
if (dataA == null || dataB == null)
return Double.NaN;
float[] ta = dataA.getData();
float[] tb = dataB.getData();
if (ta == null || tb == null || ta.length != tb.length)
return Double.NaN;
float[] a = ta;
float[] b = tb;
int num = 0;
for (int i = 0; i < ta.length; i++) {
if (Float.isNaN(ta[i]) || Float.isNaN(tb[i]))
continue;
a[num] = ta[i];
b[num] = tb[i];
num++;
}
a = Arrays.copyOfRange(a, 0, num);
b = Arrays.copyOfRange(b, 0, num);
double aMean = getMean(a);
double bMean = getMean(b);
double ICQ = 0;
for (int i = 0; i < a.length; i++) {
if ((a[i] > aMean && b[i] > bMean) || (a[i] < aMean && b[i] < bMean))
ICQ++;
}
ICQ = ICQ / a.length - 0.5;
return ICQ;
}
/**
* Please use unprocessed data as inputs
*
* @param dataA
* @param dataB
* @return
*/
double[] getMCC(CellData dataA, CellData dataB) {
if (dataA == null || dataB == null)
return new double[] { Double.NaN, Double.NaN };
float[] a = dataA.getData();
float[] b = dataB.getData();
if (a == null || b == null || a.length != b.length)
return new double[] { Double.NaN, Double.NaN };
double[] AandB = getSum(a, b);
double[] result = new double[2];
result[0] = AandB[0] / AandB[2];
result[1] = AandB[1] / AandB[3];
return result;
}
/**
* calculate the sums of the arrays above the thresholds in each array and
* in both arrays
*
* @see <code>getSum(float[] ,float[] , double, double)</code>
* @param a
* input array 1
* @param b
* input array 2
* @param thresholdA
* threshold of array a
* @param thresholdB
* threshold of array b
* @return an array of four values as [0].sum of elements in a that is not
* NaN in a & not NaN in b [1].sum of elements in b that is not NaN
* in a & not NaN in b [2].sum of elements in a that is not NaN in a
* [3].sum of elements in b that is not NaN in b
*/
public double[] getSum(float[] a, float[] b) {
if (a == null || b == null || a.length != b.length)
return new double[] { Double.NaN, Double.NaN, Double.NaN, Double.NaN };
double[] results = new double[4];
for (int i = 0; i < a.length; i++) {
if (!Float.isNaN(a[i]) && !Float.isNaN(b[i])) {
results[0] += a[i];
results[1] += b[i];
}
if (!Float.isNaN(a[i]))
results[2] += a[i];
if (!Float.isNaN(b[i]))
results[3] += b[i];
}
return results;
}
public double[][] transpose(double[][] value) {
if (value == null || value.length <= 0)
return null;
double[][] result = new double[value[0].length][value.length];
for (int i = 0; i < value.length; i++) {
if (value[i].length != value[0].length)
return null;
for (int j = 0; j < value[i].length; j++)
result[j][i] = value[i][j];
}
return result;
}
double getPCC(float[]... data) {
if (data == null || data.length == 0)
return Double.NaN;
float[][] realData = data;
int numData = 0;
runCells: for (int iData = 0; iData < data[0].length; iData++) {
for (int iChannel = 0; iChannel < data.length; iChannel++) {
if (Float.isNaN(data[iChannel][iData])) {
continue runCells;
}
}
for (int iChannel = 0; iChannel < data.length; iChannel++) {
realData[iChannel][numData] = data[iChannel][iData];
}
numData++;
}
double[] means = new double[data.length];
for (int iChannel = 0; iChannel < data.length; iChannel++) {
realData[iChannel] = Arrays.copyOfRange(realData[iChannel], 0, numData);
means[iChannel] = getMean(realData[iChannel]);
}
double expProd = 0.0;
for (int iData = 0; iData < numData; iData++) {
double temp = 1.0;
for (int iChannel = 0; iChannel < realData.length; iChannel++) {
temp *= (realData[iChannel][iData] - means[iChannel]);
}
expProd += temp;
}
expProd /= numData;
double stdProd = 1.0;
for (int iChannel = 0; iChannel < realData.length; iChannel++) {
stdProd *= getSTD(realData[iChannel], means[iChannel]);
}
return expProd / stdProd;
}
double getSRCC(double[]... ranks) {
if (ranks == null || ranks.length == 0)
return Double.NaN;
double[][] realData = ranks;
int numData = 0;
runCells: for (int iData = 0; iData < ranks[0].length; iData++) {
for (int iChannel = 0; iChannel < ranks.length; iChannel++) {
if (Double.isNaN(ranks[iChannel][iData])) {
continue runCells;
}
}
for (int iChannel = 0; iChannel < ranks.length; iChannel++) {
realData[iChannel][numData] = ranks[iChannel][iData];
}
numData++;
}
double[] means = new double[ranks.length];
for (int iChannel = 0; iChannel < ranks.length; iChannel++) {
realData[iChannel] = Arrays.copyOfRange(realData[iChannel], 0, numData);
means[iChannel] = getMean(realData[iChannel]);
}
double expProd = 0.0;
for (int iData = 0; iData < numData; iData++) {
double temp = 1.0;
for (int iChannel = 0; iChannel < realData.length; iChannel++) {
temp *= (realData[iChannel][iData] - means[iChannel]);
}
expProd += temp;
}
expProd /= numData;
double stdProd = 1.0;
for (int iChannel = 0; iChannel < realData.length; iChannel++) {
stdProd *= getSTD(realData[iChannel], means[iChannel]);
}
return expProd / stdProd;
}
double getICQ(float[]... data) {
if (data == null || data.length == 0)
return Double.NaN;
float[][] realData = data;
int numData = 0;
runCells: for (int iData = 0; iData < data[0].length; iData++) {
for (int iChannel = 0; iChannel < data.length; iChannel++) {
if (Float.isNaN(data[iChannel][iData])) {
continue runCells;
}
}
for (int iChannel = 0; iChannel < data.length; iChannel++) {
realData[iChannel][numData] = data[iChannel][iData];
}
numData++;
}
double[] means = new double[data.length];
for (int iChannel = 0; iChannel < data.length; iChannel++) {
realData[iChannel] = Arrays.copyOfRange(realData[iChannel], 0, numData);
means[iChannel] = getMean(realData[iChannel]);
}
double ICQ = 0;
for (int iData = 0; iData < numData; iData++) {
Boolean toAdd = null;
for (int iChannel = 0; iChannel < data.length; iChannel++) {
if (realData[iChannel][iData] > means[iChannel]) {
if (toAdd == null) {
toAdd = true;
continue;
} else if (!toAdd) {
toAdd = null;
break;
} else
continue;
} else if (realData[iChannel][iData] < means[iChannel]) {
if (toAdd == null) {
toAdd = false;
continue;
} else if (toAdd) {
toAdd = null;
break;
} else
continue;
} else {
toAdd = null;
break;
}
}
if (toAdd != null)
ICQ++;
}
ICQ = ICQ / numData - 0.5;
return ICQ;
}
double[] getMCC(float[]... data) {
if (data == null || data.length == 0)
return null;
double[] overlaps = new double[data.length];
double[] denominators = new double[data.length];
for (int iData = 0; iData < data[0].length; iData++) {
boolean isOverlap = true;
for (int iChannel = 0; iChannel < data.length; iChannel++) {
if (Float.isNaN(data[iChannel][iData])) {
isOverlap = false;
} else {
denominators[iChannel] += data[iChannel][iData];
}
}
if (isOverlap) {
for (int iChannel = 0; iChannel < data.length; iChannel++) {
overlaps[iChannel] += data[iChannel][iData];
}
}
}
for (int iChannel = 0; iChannel < data.length; iChannel++) {
overlaps[iChannel] /= denominators[iChannel];
}
return overlaps;
}
double[] getTOS(float[]... data) {
if (data == null || data.length == 0)
return null;
int size = data[0].length;
double[] sumOnes = new double[data.length];
double sumAll = 0.0;
for (int idx = 0; idx < size; idx++) {
boolean isAll = true;
for (int iChannel = 0; iChannel < data.length; iChannel++) {
if (!Double.isNaN(data[iChannel][idx]))
sumOnes[iChannel]++;
else
isAll = false;
}
if (isAll)
sumAll++;
}
double[] exps = new double[data.length];
for (int iChannel = 0; iChannel < data.length; iChannel++) {
exps[iChannel] = sumOnes[iChannel] / size;
}
double prodExps = prodExp(exps, -1);
double aoRatioSelected = sumAll / size / prodExps;
double maxAOratio = findMin(exps) / prodExps;
double minAOratio;
double tos_linear = Double.NaN, tos_log2 = Double.NaN;
if (noOverlap(exps))
minAOratio = 0;
else
minAOratio = (getSum(exps) - data.length + 1) / prodExps;
// tos_linear
if (aoRatioSelected == 1) {
if (maxAOratio == 1 || minAOratio == 1)
tos_linear = Double.NaN;
else
tos_linear = 0;
} else if (aoRatioSelected < 1) {
tos_linear = (1 - aoRatioSelected) / (minAOratio - 1);
} else if (aoRatioSelected > 1) {
tos_linear = (aoRatioSelected - 1) / (maxAOratio - 1);
} else if (!Double.isNaN(aoRatioSelected)) {
ExceptionHandler.addError(Thread.currentThread(), "Error in calculating linear TOS");
tos_linear = Double.NaN;
} else {
tos_linear = Double.NaN;
}
// tos_log2
if (aoRatioSelected == 1) {
if (maxAOratio == 1 || minAOratio == 1)
tos_log2 = Double.NaN;
else
tos_log2 = 0;
} else if (aoRatioSelected > maxAOratio) {
tos_log2 = 1;
} else if (aoRatioSelected < minAOratio) {
tos_log2 = -1;
} else if (maxAOratio + minAOratio != 2) {
double log2 = Math.log(2);
double m = log2 / Math.log((maxAOratio - 1) / (1 - minAOratio));
double n = (maxAOratio + minAOratio - 2) / ((maxAOratio - 1) * (1 - minAOratio));
tos_log2 = m * Math.log(n * (aoRatioSelected - 1) + 1) / log2;
} else if (maxAOratio + minAOratio == 2) {
tos_log2 = 2 / (maxAOratio - minAOratio) * (aoRatioSelected - 1);
} else if (!Double.isNaN(aoRatioSelected)) {
ExceptionHandler.addError(Thread.currentThread(), "Error in calculating log TOS");
tos_log2 = Double.NaN;
}
tos_linear = round(tos_linear, TOSdecimal);
if (tos_linear > 1)
tos_linear = 1;
if (tos_linear < -1)
tos_linear = -1;
tos_log2 = round(tos_log2, TOSdecimal);
if (tos_log2 > 1)
tos_log2 = 1;
if (tos_log2 < -1)
tos_log2 = -1;
return new double[] { tos_linear, tos_log2 };
}
private double getSum(double[] a) {
if (a == null)
return Double.NaN;
double result = 0.0;
for (int i = 0; i < a.length; i++)
result += a[i];
return result;
}
private boolean noOverlap(double[] exp) {
DataSorter expSorter = new DataSorter();
expSorter.sort(exp);
double[] sortedExp = (double[]) expSorter.getResult();
for (int i = 1; i < sortedExp.length; i++) {
if (sumExp(sortedExp, sortedExp.length - 1 - i, sortedExp.length - 1) < i) {
return true;
}
}
return false;
}
private double findMax(double[] data) {
double result = Double.NEGATIVE_INFINITY;
for (double d : data) {
if (result < d)
result = d;
}
return result;
}
private double findMin(double[] data) {
double result = Double.POSITIVE_INFINITY;
for (double d : data) {
if (result > d)
result = d;
}
return result;
}
private double sumExp(double[] data, int startIdx, int endIdx) {
double result = 0.0;
if (data == null || data.length == 0)
return Double.NaN;
if (startIdx < 0 || startIdx >= data.length || endIdx < 0 || endIdx >= data.length || endIdx < startIdx) {
for (double d : data)
result += d;
return result;
}
for (int i = startIdx; i <= endIdx; i++) {
result += data[i];
}
return result;
}
private double prodExp(double[] data, int exp) {
double result = 1.0;
if (data == null || data.length == 0)
return Double.NaN;
if (exp < 0 || exp >= data.length) {
for (double d : data)
result *= d;
return result;
}
for (int i = 0; i < data.length; i++) {
if (i == exp)
continue;
else
result *= data[i];
}
return result;
}
}
| 35,524 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
CostesThreshold.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/metric/CostesThreshold.java | package ezcol.metric;
import java.util.ArrayList;
import ezcol.cell.DataSorter;
import ezcol.debug.ExceptionHandler;
public class CostesThreshold {
public CostesThreshold() {
};
public double[] linreg(float[] Aarray, float[] Barray) {
double[] coeff = new double[2];
int count = 0;
double sumA, sumB, sumAB, sumsqrA;
sumA = 0;
sumB = 0;
sumAB = 0;
sumsqrA = 0;
for (int m = 0; m < Aarray.length; m++) {
sumA += Aarray[m];
sumB += Barray[m];
sumAB += Aarray[m] * Barray[m];
sumsqrA += Aarray[m] * Aarray[m];
count++;
}
// 0:a, 1:b
coeff[0] = (count * sumAB - sumA * sumB) / (count * sumsqrA - sumA * sumA);
coeff[1] = (sumsqrA * sumB - sumA * sumAB) / (count * sumsqrA - sumA * sumA);
return coeff;
}
private double getPCC(int[] A, int[] B) {
if (A == null || B == null || A.length <= 0 || B.length <= 0 || A.length != B.length)
return Double.NaN;
double Asum = 0.0, Bsum = 0.0, ABsum = 0.0, A2sum = 0.0, B2sum = 0.0;
for (int i = 0; i < A.length; i++) {
Asum += A[i];
Bsum += B[i];
ABsum += A[i] * B[i];
A2sum += A[i] * A[i];
B2sum += B[i] * B[i];
}
int n = A.length;
double PCC = (n * ABsum - Asum * Bsum) / Math.sqrt((n * A2sum - Asum * Asum) * (n * B2sum - Bsum * Bsum));
return PCC;
}
/**
* Run Costes Algorithm to find costes thresholds
*
* @param Aarray
* input float values of channel 1
* @param Barray
* input float values of channel 2
* @return a double array with two elements [0]: Threshold of Channel 1 [1]:
* Threshold of Channel 2
*/
public double[] getCostesThrd(float[] Aarray, float[] Barray) {
double[] tmp = linreg(Aarray, Barray);
return getCostesThrd(Aarray, Barray, tmp[0], tmp[1]);
}
private double[] getCostesThrd(float[] Aarray, float[] Barray, double slope, double intercept) {
if (Aarray == null || Barray == null || Aarray.length <= 1 || Barray.length <= 1)
return new double[] { Double.NaN, Double.NaN };
int len = Aarray.length < Barray.length ? Aarray.length : Barray.length;
double Asum = 0.0, Bsum = 0.0, ABsum = 0.0, A2sum = 0.0, B2sum = 0.0;
// use a maximum PCC of 2.0 to account for double imprecision
double PCC = 2.0;
int n = 0;
double squarePCC, covariance;
double temp;
double[] projBarray = new double[len];
int[] sortedIdxes;
// Determine the rank of data points of pixels above Costes thresholds
// in sortedIdxes
// The data points should include CostesIdx and everything below it
// because sortedIdxes is the indexes in descending order.
int CostesIdx = -1;
double[] thresholds = new double[] { Double.NaN, Double.NaN };
// depending on the slope different dynamic programming is implemented
// It's possible to synthesize all these conditions into one
// However, I'm too lazy to do so.
if (slope < 0) {
projBarray = new double[len * 2];
for (int i = 0; i < len * 2; i++)
projBarray[i] = Double.NaN;
for (int i = 0; i < len; i++) {
temp = slope * Aarray[i] + intercept;
// If a point is below the line, it will always be below
// thresholds
// If a point is above the line, we need to record
// when it's removed and when it's added back
if (temp < Barray[i]) {
projBarray[i] = temp;
projBarray[i + len] = Barray[i];
}
}
DataSorter mySort = new DataSorter();
mySort.sort(projBarray);
sortedIdxes = mySort.getSortIdx();
for (int i = 0; i < len; i++) {
Asum += Aarray[i];
Bsum += Barray[i];
ABsum += Aarray[i] * Barray[i];
A2sum += Aarray[i] * Aarray[i];
B2sum += Barray[i] * Barray[i];
n++;
}
// Hold up the ties
// We always consider points laying on the thresholds to be below
// thresholds
// Therefore, some pixels that need to be added
ArrayList<Integer> tiesHolder = new ArrayList<Integer>();
// We use forward indexing here because NaN might be found at the
// end of
// sortedIdxes array. We don't want to deal with NaN.
// NaN is flagged by assigning a sortedIdx that is greater than or
// equal to the length of the array
// #see DataSorter.sort for more detail
for (int i = 0; i < 2 * len;) {
// spot NaN, it's time to stop
if (sortedIdxes[i] >= len * 2)
break;
// remove all points hold on by tieHolder back
// They were hold on until the next thresholds being selected
// This is because we always consider points on the threshold
// lines
// to be below thresholds
if (!tiesHolder.isEmpty()) {
for (int iTie : tiesHolder) {
Asum -= Aarray[iTie];
Bsum -= Barray[iTie];
ABsum -= Aarray[iTie] * Barray[iTie];
A2sum -= Aarray[iTie] * Aarray[iTie];
B2sum -= Barray[iTie] * Barray[iTie];
n--;
}
tiesHolder.clear();
}
// remove all the following data points on the threshold line
boolean pointAdded = false;
while (i < 2 * len) {
if (sortedIdxes[i] < len) {
Asum += Aarray[sortedIdxes[i]];
Bsum += Barray[sortedIdxes[i]];
ABsum += Aarray[sortedIdxes[i]] * Barray[sortedIdxes[i]];
A2sum += Aarray[sortedIdxes[i]] * Aarray[sortedIdxes[i]];
B2sum += Barray[sortedIdxes[i]] * Barray[sortedIdxes[i]];
n++;
i++;
pointAdded = true;
} else if (sortedIdxes[i] < 2 * len) {
if (pointAdded)
tiesHolder.add(sortedIdxes[i] - len);
else {
Asum -= Aarray[sortedIdxes[i] - len];
Bsum -= Barray[sortedIdxes[i] - len];
ABsum -= Aarray[sortedIdxes[i] - len] * Barray[sortedIdxes[i] - len];
A2sum -= Aarray[sortedIdxes[i] - len] * Aarray[sortedIdxes[i] - len];
B2sum -= Barray[sortedIdxes[i] - len] * Barray[sortedIdxes[i] - len];
n--;
}
i++;
} else {
ExceptionHandler.addError(Thread.currentThread(),
"Unprecedented error occurs in CostesThreshold");
return null;
}
// If the next data point has exactly the same value
// It should be removed, added or held
if (i >= 2 * len - 1 || sortedIdxes[i] >= 2 * len
|| projBarray[sortedIdxes[i - 1]] != projBarray[sortedIdxes[i]])
break;
}
covariance = n * ABsum - Asum * Bsum;
squarePCC = covariance * covariance / ((n * A2sum - Asum * Asum) * (n * B2sum - Bsum * Bsum));
// This line is commented out so that the minimum absolute value
// of
// PCC will be selected
// squarePCC=covariance>0 ? squarePCC : (-squarePCC);
if (squarePCC < PCC) {
//If point is added, use the normal index
//It should be noted that i has already increased before this recording
//If point is removed, use the next index
//There is no need to worry about boundary condition because
//the last index must be addition of a point/points.
if(pointAdded)
CostesIdx = i - 1;
else
CostesIdx = i;
PCC = squarePCC;
}
}
//projBarray[i] = temp;
//projBarray[i + len] = Barray[i];
if(CostesIdx < 0 || CostesIdx >= sortedIdxes.length){
ExceptionHandler.addError(Thread.currentThread(),
"Cannot compute Costes' thesholds");
}else{
if (sortedIdxes[CostesIdx] < len) {
thresholds[0] = Aarray[sortedIdxes[CostesIdx]];
thresholds[1] = projBarray[sortedIdxes[CostesIdx]];
}else if (sortedIdxes[CostesIdx] < 2 * len) {
thresholds[0] = (projBarray[sortedIdxes[CostesIdx]] - intercept) / slope;
thresholds[1] = projBarray[sortedIdxes[CostesIdx]];
}else{
ExceptionHandler.addError(Thread.currentThread(),
"Unprecedented error 2 occurs in CostesThreshold");
}
}
} else {
if (slope == 0)
for (int i = 0; i < len; i++) {
projBarray[i] = Aarray[i];
}
else {
for (int i = 0; i < len; i++) {
temp = slope * Aarray[i] + intercept;
projBarray[i] = temp < Barray[i] ? temp : Barray[i];
}
}
// sort the data array to get the order of elimination of pixels
// The order of elimination is determined by the projected value (to
// the
// linear regression line) of data point in Channel B
DataSorter mySort = new DataSorter();
mySort.sort(projBarray);
sortedIdxes = mySort.getSortIdx();
// avoid using Math.sqrt for better performance
for (int i = len - 1; i >= 0;) {
// remove all the following data points on the threshold line
while (i >= 0) {
Asum += Aarray[sortedIdxes[i]];
Bsum += Barray[sortedIdxes[i]];
ABsum += Aarray[sortedIdxes[i]] * Barray[sortedIdxes[i]];
A2sum += Aarray[sortedIdxes[i]] * Aarray[sortedIdxes[i]];
B2sum += Barray[sortedIdxes[i]] * Barray[sortedIdxes[i]];
n++;
i--;
if (i < 0 || projBarray[sortedIdxes[i + 1]] != projBarray[sortedIdxes[i]])
break;
}
covariance = n * ABsum - Asum * Bsum;
squarePCC = covariance * covariance / ((n * A2sum - Asum * Asum) * (n * B2sum - Bsum * Bsum));
// This line is commented out so that the minimum absolute value
// of
// PCC will be selected
// squarePCC=covariance>0 ? squarePCC : (-squarePCC);
if (squarePCC < PCC) {
CostesIdx = i + 1;
PCC = squarePCC;
}
}
if(CostesIdx < 0 || CostesIdx >= sortedIdxes.length){
ExceptionHandler.addError(Thread.currentThread(),
"Cannot compute Costes' thesholds");
}else{
if(projBarray[sortedIdxes[CostesIdx]] < Barray[sortedIdxes[CostesIdx]]){
thresholds[0] = Aarray[sortedIdxes[CostesIdx]];
thresholds[1] = projBarray[sortedIdxes[CostesIdx]];
}else{
thresholds[0] = (projBarray[sortedIdxes[CostesIdx]] - intercept) / slope;
thresholds[1] = projBarray[sortedIdxes[CostesIdx]];
}
}
}
return thresholds;
}
/**
* @deprecated This is a naive approach, and it's very slow
* @param Aarray
* @param Barray
* @return
*/
public double[] getCostesThrdSlow(float[] Aarray, float[] Barray){
if (Aarray == null || Barray == null)
return new double[] { Double.NaN, Double.NaN };
int len = Aarray.length < Barray.length ? Aarray.length : Barray.length;
double[] tmp = linreg(Aarray, Barray);
double slope = tmp[0];
double intercept = tmp[1];
double[] projAarray = new double[len * 2];
double[] projBarray = new double[len * 2];
double temp;
double[] thresholds = new double[2];
double PCC = 2.0;
for (int i = 0; i < len; i++) {
// add all possible threshold combinations
projAarray[i] = Aarray[i];
projAarray[i + len] = (Barray[i] - intercept) / slope;
projBarray[i] = slope * Aarray[i] + intercept;
projBarray[i + len] = Barray[i];
/*if(projAarray[i + len] < 0)
Debugger.printCurrentLine("projAarray[i + len]: "+ projAarray[i + len]);
if(projBarray[i] < 0)
Debugger.printCurrentLine("projBarray[i]: "+ projBarray[i]);*/
}
for (int i = 0; i < 2 * len; i++) {
temp = linregCostes(Aarray, Barray, projAarray[i], projBarray[i], false)[2];
if (temp * temp < PCC){
PCC = temp * temp;
thresholds[0] = projAarray[i];
thresholds[1] = projBarray[i];
}
}
return thresholds;
}
/**
* @param Aarray image A data
* @param Barray image B data
* @param TA threshold A
* @param TB threshold B
* @param direction: True above both (exclusive), False below either (inclusive)
* @return {slope, intercept, pcc}
*/
public double[] linregCostes(float[] Aarray, float[] Barray, double TA, double TB, boolean direction) {
if(Aarray == null || Barray == null){
return null;
}
int len = Aarray.length < Barray.length ? Aarray.length : Barray.length;
double cov = 0;
double varA = 0;
double varB = 0;
double[] coeff = new double[3];
int count = 0;
double sumA, sumB, sumAB, sumsqrA, Aarraymean, Barraymean;
sumA = 0;
sumB = 0;
sumAB = 0;
sumsqrA = 0;
Aarraymean = 0;
Barraymean = 0;
for (int m = 0; m < len; m++) {
if ((!direction && (Aarray[m] <= TA || Barray[m] <= TB)) ||
(direction && (Aarray[m] > TA && Barray[m] > TB))){
sumA += Aarray[m];
sumB += Barray[m];
sumAB += Aarray[m] * Barray[m];
sumsqrA += Aarray[m] * Aarray[m];
count++;
}
}
Aarraymean = sumA / count;
Barraymean = sumB / count;
for (int m = 0; m < len; m++) {
if ((!direction && (Aarray[m] <= TA || Barray[m] <= TB)) ||
(direction && (Aarray[m] > TA && Barray[m] > TB))){
cov += (Aarray[m] - Aarraymean) * (Barray[m] - Barraymean);
varA += (Aarray[m] - Aarraymean) * (Aarray[m] - Aarraymean);
varB += (Barray[m] - Barraymean) * (Barray[m] - Barraymean);
}
}
coeff[0] = (count * sumAB - sumA * sumB) / (count * sumsqrA - sumA * sumA);
coeff[1] = (sumsqrA * sumB - sumA * sumAB) / (count * sumsqrA - sumA * sumA);
coeff[2] = cov / (Math.sqrt(varA * varB));
return coeff;
}
}
| 12,749 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
MatrixCalculator3D.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/metric/MatrixCalculator3D.java | package ezcol.metric;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.util.HashMap;
import java.util.Map;
import ij.ImagePlus;
import ij.gui.ImageWindow;
import ij.measure.ResultsTable;
import ezcol.cell.CellData;
import ezcol.debug.ExceptionHandler;
import ezcol.main.PluginConstants;
import ezcol.visual.visual2D.HeatChart;
import ezcol.visual.visual3D.ScatterPlot3DWindow;
public class MatrixCalculator3D extends BasicCalculator {
public static final int DO_MATRIX = PluginConstants.DO_MATRIX, DO_LINEAR_TOS = PluginConstants.DO_LINEAR_TOS,
DO_LOG2_TOS = PluginConstants.DO_LOG2_TOS, DO_LN_TOS = PluginConstants.DO_LN_TOS,
OPTS_TOS = PluginConstants.OPTS_TOS;
public static final String SHOW_TOS_LINEAR = "TOS(linear)", SHOW_TOS_LOG2 = "TOS(log2)", SHOW_PCC = "PCC",
SHOW_SRC = "SRCC", SHOW_ICQ = "ICQ", SHOW_M1 = "M1", SHOW_M2 = "M2", SHOW_M3 = "M3";
// Although we can calculate n-dimensional results, we can only print up to
// 3d.
// Therefore, MCC is set to be M1, M2, and M3.
private int metricIdx;
private static final String[] METRIC_NAMES = { SHOW_TOS_LINEAR, SHOW_TOS_LOG2, SHOW_ICQ, SHOW_M1, SHOW_M2, SHOW_M3 };
// mMetric[iCell][iBox];
private double[][] mMetric;
// cellCs[iChannel][iCell];
// private CellData[][] cellCs;
private ResultsTable mTOSResultTable;
public MatrixCalculator3D() {
options = 0;
}
public MatrixCalculator3D(int[] cutoffs) {
options = DO_LINEAR_TOS | DO_MATRIX;
if (cutoffs != null && cutoffs.length >= 2)
this.cutoffs = cutoffs.clone();
else
this.cutoffs = new int[] { DEFAULT_FT, DEFAULT_FT };
numFT2SF();
}
public MatrixCalculator3D(int options, int[] cutoffs) {
this.options = options;
if (cutoffs != null && cutoffs.length >= 2)
this.cutoffs = cutoffs.clone();
else
this.cutoffs = new int[] { DEFAULT_FT, DEFAULT_FT };
numFT2SF();
}
public MatrixCalculator3D(BasicCalculator callBase) {
this.options = callBase.options;
this.numOfCell = callBase.numOfCell;
this.ftCs = callBase.ftCs;
this.allCs = callBase.allCs;
this.costesCs = callBase.costesCs;
}
public boolean calMetrics(CellData[][] cellCs, int metricIndex) {
if (!prepCellData(cellCs, new int[] { BasicCalculator.THOLD_ALL }))
return false;
metricIdx = metricIndex;
if ((options & DO_MATRIX) != 0)
mMetric = new double[numOfCell][];
else
mMetric = null;
for (int iCell = 0; iCell < numOfCell; iCell++) {
// also gives TOSmax and TOSmin
if (mMetric != null) {
this.cellCs = allCs;
mMetric[iCell] = getMatrix(iCell, metricIndex);
if (mMetric[iCell] == null) {
mMetric = null;
return false;
}
}
// get TOSmin and TOSmax are in getmTOS function
}
return true;
}
private void printmTOS() {
if (mMetric == null || sfsCs == null)
return;
if (mTOSResultTable == null)
mTOSResultTable = new ResultsTable();
else
mTOSResultTable.reset();
for (int iCell = 0; iCell < numOfCell; iCell++)
addToRT(mTOSResultTable, mMetric[iCell]);
}
private void addToRT(ResultsTable rt, double[] values) {
rt.incrementCounter();
int numBox = getMatrixSize();
for (int iBox = 0; iBox < numBox; iBox++) {
String valTitle = "";
for (int channel = 0; channel < sfsCs.length; channel++)
valTitle += "S" + (channel + 1) + "-" + sfsCs[channel][getSfsCsIdx(channel, iBox)];
rt.addValue(valTitle, values[iBox]);
}
}
private int getSfsCsIdx(int channel, int iBox) {
int idx = iBox;
for (int count2 = sfsCs.length - 1; count2 > channel; count2--) {
idx /= sfsCs[count2].length;
}
idx %= sfsCs[channel].length;
return idx;
}
public ResultsTable getResultsTable() {
if (mTOSResultTable == null)
printmTOS();
return mTOSResultTable;
}
/**
* Introduced in version 1.2
*/
/**
* This is used in getMatrices to update matrix heat map
*
* @param dataA
* @param dataB
* @param index
* @return
*/
protected double calMetric(CellData[] cellData, int index, boolean noTholdTOS) {
if (cellData == null || cellData.length < 2)
return Double.NaN;
/*
* int overlap = 0; for(int i=0;i<length;i++){ for(int
* iChannel=0;iChannel<cellData.length;iChannel++)
* if(Float.isNaN(cellData[iChannel].getPixel(i))){ overlap--; }
* overlap++; }
*
* CellData copyA = new CellData(overlap); CellData copyB = new
* CellData(overlap);
*
* for(int i=0, j=0;i<length;i++){ if(!Float.isNaN(dataA.getPixel(i)) &&
* !Float.isNaN(dataB.getPixel(i))){ copyA.setData(dataA, i, j);
* copyB.setData(dataB, i, j); j++; } }
*/
double result;
if (index < 0 || index >= METRIC_NAMES.length)
return Double.NaN;
String metricName = METRIC_NAMES[index];
switch (metricName) {
case SHOW_TOS_LINEAR:
result = getTOS(getCellPixels(cellData))[0];
break;
case SHOW_TOS_LOG2:
result = getTOS(getCellPixels(cellData))[1];
break;
case SHOW_PCC:
result = getPCC(getCellPixels(cellData));
break;
case SHOW_SRC:
result = getSRCC(getCellRanks(cellData));
break;
case SHOW_ICQ:
result = getICQ(getCellPixels(cellData));
break;
// case SHOW_CUSTOM:
// result = getCustom(copyA,copyB);
// break;
// case SHOW_AVGINT_C1:
// result = getAVGINT(copyA,copyB)[0];
// break;
// case SHOW_AVGINT_C2:
// result = getAVGINT(copyA,copyB)[1];
// break;
// Use unprocessed data here because points below thresholds are also
// informative
case SHOW_M1:
result = getMCC(getCellPixels(cellData))[0];
break;
case SHOW_M2:
result = getMCC(getCellPixels(cellData))[1];
break;
case SHOW_M3:
result = getMCC(getCellPixels(cellData))[2];
break;
default:
result = Double.NaN;
break;
}
if (Double.isNaN(result)) {
if (!((METRIC_NAMES[index] == SHOW_TOS_LINEAR || METRIC_NAMES[index] == SHOW_TOS_LOG2) && (noTholdTOS))) {
ExceptionHandler.addWarning(Thread.currentThread(), cellData[0].getCellLabel() + "(size:"
+ cellData[0].length() + ") returns a " + metricName + " value of NaN");
ExceptionHandler.insertWarning(Thread.currentThread(), ExceptionHandler.NAN_WARNING);
}
}
return result;
}
/**
* only for metric heat map
*/
public Object[] getColorValues(int index, int num) {
if (index < 0 || index >= METRIC_NAMES.length)
return null;
switch (METRIC_NAMES[index]) {
case SHOW_TOS_LINEAR:
case SHOW_TOS_LOG2:
case SHOW_PCC:
case SHOW_SRC:
return getColorValues(-1, 1, num);
case SHOW_ICQ:
return getColorValues(-0.5, 0.5, num);
case SHOW_M1:
case SHOW_M2:
case SHOW_M3:
return getColorValues(0, 1, num);
default:
return null;
}
}
/**
* over for metric heat map use
*/
public float[] getMetricRange(int index) {
if (index < 0 || index >= METRIC_NAMES.length)
return null;
switch (METRIC_NAMES[index]) {
case SHOW_TOS_LINEAR:
case SHOW_TOS_LOG2:
case SHOW_PCC:
case SHOW_SRC:
return new float[] { -1.0f, 0.0f, 1.0f };
case SHOW_ICQ:
return new float[] {-0.5f, 0.0f, 0.5f };
case SHOW_M1:
case SHOW_M2:
case SHOW_M3:
return new float[] { 0.0f, 0.5f, 1.0f };
default:
return null;
}
}
/**
* calculate the sums of the arrays above the thresholds in each array and
* in both arrays
*
* @see <code>MetricCalculator.getSum(float[] ,float[] , double, double)</code>
* @param a
* input array 1
* @param b
* input array 2
* @param thresholdA
* threshold of array a
* @param thresholdB
* threshold of array b
* @return an array of four values as [0].number of elements in a that is
* not NaN in a & not NaN in b [1].number of elements in b that is
* not NaN in a & not NaN in b [2].number of elements in a that is
* not NaN in a [3].number of elements in b that is not NaN in b
*/
public double[] getSum(float[] a, float[] b) {
if (a == null || b == null || a.length != b.length)
return new double[] { Double.NaN, Double.NaN, Double.NaN, Double.NaN };
double[] results = new double[4];
for (int i = 0; i < a.length; i++) {
if (!Float.isNaN(a[i]) && !Float.isNaN(b[i])) {
results[0]++;
results[1]++;
}
if (!Float.isNaN(a[i]))
results[2]++;
if (!Float.isNaN(b[i]))
results[3]++;
}
return results;
}
protected Object[] getColorValues(double min, double max, int numColorBar) {
Object[] inputC = new Object[numColorBar];
double increColorBar = (max - min) / (numColorBar - 1);
for (int i = 0; i < numColorBar; i++)
inputC[i] = round(min + increColorBar * i, 3);
return inputC;
}
public ResultsTable getMatrix(CellData[][] cellCs, int index) {
if (cellCs == null)
return null;
this.cellCs = cellCs;
numOfCell = Integer.MAX_VALUE;
for (int i = 0; i < cellCs.length; i++) {
if (cellCs[i] == null)
return null;
if (cellCs[i].length < numOfCell)
numOfCell = cellCs[i].length;
}
ResultsTable rt = new ResultsTable();
for (int iCell = 0; iCell < numOfCell; iCell++) {
double[] results = getMatrix(iCell, index);
rt.incrementCounter();
rt.addLabel(cellCs[0][iCell].getCellLabel());
addToRT(rt, results);
}
return rt;
}
/**
*
* @param iCell
* @param callBases
* @return
*/
private double[] getMatrix(int iCell, int show_idx) {
if (cellCs == null || sfsCs == null) {
ExceptionHandler.addError(Thread.currentThread(), "Null pointer in cell data and parameter");
return null;
}
double[] result = new double[getMatrixSize()];
int size = Integer.MAX_VALUE;
@SuppressWarnings("unchecked")
Map<Integer, CellData>[] trimMap = new HashMap[cellCs.length];
// sorting is done together to save time
for (int iChannel = 0; iChannel < cellCs.length; iChannel++) {
if (!cellCs[iChannel][iCell].isSorted())
cellCs[iChannel][iCell].sort();
if (cellCs[iChannel][iCell].length() < size)
size = cellCs[iChannel][iCell].length();
trimMap[iChannel] = new HashMap<Integer, CellData>();
}
int numBox = getMatrixSize();
for (int iBox = 0; iBox < numBox; iBox++) {
boolean noThold = false;
CellData[] trims = new CellData[cellCs.length];
for (int iChannel = 0; iChannel < sfsCs.length; iChannel++) {
int positive = (int) Math.ceil((size * sfsCs[iChannel][getSfsCsIdx(iChannel, iBox)]));
if (sfsCs[iChannel][getSfsCsIdx(iChannel, iBox)] >= 1.0)
noThold = true;
if (positive > size)
positive = size;
if (trimMap[iChannel].containsKey(positive)) {
trims[iChannel] = trimMap[iChannel].get(positive);
} else {
trims[iChannel] = cellCs[iChannel][iCell].getData(positive);
trimMap[iChannel].put(positive, trims[iChannel]);
}
}
double metricDouble = calMetric(trims, show_idx, noThold);
result[iBox] = metricDouble;
}
/*
* for (int selection1=0; selection1<sfsCs[0].length; selection1++){ int
* positiveA=(int) Math.ceil((size*sfsCs[0][selection1]));
* positiveA=positiveA<size?positiveA:size; CellData trimA =
* cellC1[iCell].getData(positiveA);
*
* for (int selection2=0; selection2<sfsCs[1].length; selection2++){ int
* positiveB=(int) Math.ceil((size*sfsCs[1][selection2]));
* positiveB=positiveB<size?positiveB:size; CellData trimB =
* cellC2[iCell].getData(positiveB);
*
* if(selection1==0&&selection2==sfsCs[1].length-1){ ; }
*
* double metricDouble = calMetric(trimA, trimB, show_idx);
*
* //store channel 1 selection as row, channel 2 as column
* result[selection2+selection1*sfsCs[1].length] = metricDouble;
*
* } }
*/
return result;
}
// number of boundaries not interval (interval+!)
public static int numColorBar = 6;
public HeatChart getHeatChart(double[][] medianmValues, String title) {
if (medianmValues == null)
return null;
double minTOS = -1.0, maxTOS = 1.0, nullTOS = 0.0;
double increColorBar = (maxTOS - minTOS) / (numColorBar - 1);
Object[] inputC1 = new Object[sfsCs[0].length];
Object[] inputC2 = new Object[sfsCs[1].length];
Object[] inputC = new Object[numColorBar];
HeatChart mTOSHeatChart = new HeatChart(medianmValues, minTOS, nullTOS, maxTOS);
// mTOSHeatChart.setTitle(title);
for (int i = 0; i < sfsCs[0].length; i++)
inputC1[sfsCs[0].length - 1 - i] = sfsCs[0][i] + "%";
for (int i = 0; i < sfsCs[1].length; i++)
inputC2[i] = sfsCs[1][i] + "%";
for (int i = 0; i < numColorBar; i++)
inputC[i] = round(minTOS + increColorBar * i, 3);
mTOSHeatChart.setXValues(inputC1);
mTOSHeatChart.setYValues(inputC2);
mTOSHeatChart.setTitleFont(new Font("Arial", Font.PLAIN, 32));
mTOSHeatChart.setXAxisLabel("Selected % 1");
mTOSHeatChart.setYAxisLabel("Selected % 2");
mTOSHeatChart.setAxisLabelsFont(new Font("Arial", Font.PLAIN, 18));
mTOSHeatChart.setAxisValuesFont(new Font("Arial", Font.PLAIN, 16));
mTOSHeatChart.setColorValuesFont(new Font("Arial", Font.PLAIN, 16));
mTOSHeatChart.setAxisThickness(0);
mTOSHeatChart.setBackgroundColour(Color.LIGHT_GRAY);
mTOSHeatChart.setLowValueColour(Color.BLUE);
mTOSHeatChart.setHighValueColour(Color.RED);
mTOSHeatChart.setMiddleValueColour(Color.WHITE);
mTOSHeatChart.setCellSize(new Dimension(50, 50));
mTOSHeatChart.setColorBarWidth(25);
mTOSHeatChart.setColorBarValues(inputC);
return mTOSHeatChart;
}
public ImageWindow getD3Heatmap(double[] synValues, int[] dimensions) {
float[] customScales = getMetricRange(metricIdx);
Color[] colorScales = { Color.BLUE, Color.WHITE, Color.RED };
int numBox = getMatrixSize(dimensions);
if(numBox == 0 || synValues == null || synValues.length < numBox)
return null;
float[][] xValues = new float[numBox][1];
float[][] yValues = new float[numBox][1];
float[][] zValues = new float[numBox][1];
float[] customColors = new float[numBox];
for (int iBox = 0; iBox < numBox; iBox++) {
xValues[iBox][0] = (float) sfsCs[0][getSfsCsIdx(0, iBox)];
yValues[iBox][0] = (float) sfsCs[1][getSfsCsIdx(1, iBox)];
zValues[iBox][0] = (float) sfsCs[2][getSfsCsIdx(2, iBox)];
customColors[iBox] = (float) synValues[iBox];
}
String title = getNames(metricIdx) + " " + getStatsName(statsMethod) + " Matrix";
ScatterPlot3DWindow sdw = new ScatterPlot3DWindow(title, "Channel 1", "Channel 2", "Channel 3", xValues,
yValues, zValues, 77, customColors, customScales, colorScales);
ScatterPlot3DWindow.setPlotTitle(title);
sdw.setRawResultsTable(getResultsTable());
sdw.setDefaultRotation(-240, 0, -45);
sdw.draw();
return sdw;
}
public ImageWindow getD3Heatmap() {
int[] dimensions = new int[sfsCs.length];
for (int i = 0; i < dimensions.length; i++) {
dimensions[i] = sfsCs[i].length;
}
return getD3Heatmap(getStatsMatrix(mMetric), dimensions);
}
public ImagePlus getHeatmap(double[][] medianmTValues, boolean show) {
if (medianmTValues == null)
return null;
HeatChart mTOSHeatChart = getHeatChart(medianmTValues, "metric matrix");
ImagePlus mTOSHeatmap = mTOSHeatChart.getImagePlus("metric matrix heatmap");
if (show)
mTOSHeatmap.show();
return mTOSHeatmap;
}
/**
* get the number of metric names it is also the number of metrics
* calculated in the derived class please use BasicCalculator.getNum() for
* DEFAULT_NAMES
*
* @return
*/
public static int getNum() {
return METRIC_NAMES.length < METRIC_NAMES.length ? METRIC_NAMES.length : METRIC_NAMES.length;
}
/**
* get the name of the metric please use BasicCalculator.getNum() for
* DEFAULT_IDXES
*
* @param i
* index of the metric
* @return the name of i-th metric
*/
public static String getNames(int i) {
if (i < 0 || i >= METRIC_NAMES.length)
return null;
return METRIC_NAMES[i];
}
public static String[] getAllMetrics() {
return METRIC_NAMES.clone();
}
private int getMatrixSize() {
int result = 1;
for (int i = 0; i < sfsCs.length; i++) {
result *= sfsCs[i].length;
}
return result;
}
private int getMatrixSize(int[] dimensions) {
if(dimensions == null || dimensions.length <= 0)
return 0;
int result = 1;
for (int i = 0; i < dimensions.length; i++) {
result *= dimensions[i];
}
return result;
}
public static final String MEDIAN = "Median", MEAN = "Mean", MODE = "Mode";
private int statsMethod = 0;
private static final String[] STATS_NAMES = { MEDIAN, MEAN, MODE };
private double[] getStatsMatrix(double[][] value) {
if(value == null || value.length <= 0)
return null;
double[][] tpValue = transpose(value);
double[] matrix = new double[value[0].length];
switch (STATS_NAMES[statsMethod]) {
case MEDIAN:
for (int iBox = 0; iBox < tpValue.length; iBox++)
matrix[iBox] = getMedian(tpValue[iBox]);
break;
case MEAN:
for (int iBox = 0; iBox < tpValue.length; iBox++)
matrix[iBox] = getMean(tpValue[iBox]);
break;
case MODE:
for (int iBox = 0; iBox < tpValue.length; iBox++)
matrix[iBox] = getMode(tpValue[iBox]);
break;
default:
return null;
}
return matrix;
}
public void setStatsMethod(int i) {
if (i < 0 || i >= STATS_NAMES.length)
statsMethod = i;
}
public void setStatsMethod(String name) {
for (int i = 0; i < STATS_NAMES.length; i++)
if (STATS_NAMES[i].equalsIgnoreCase(name)) {
statsMethod = i;
}
}
public String getStatsName(int i) {
if (i >= 0 || i < STATS_NAMES.length)
return STATS_NAMES[i];
else
return "";
}
private float[][] getCellPixels(CellData[] cellData) {
float[][] results = new float[cellData.length][];
for (int i = 0; i < cellData.length; i++)
results[i] = cellData[i].getData();
return results;
}
private double[][] getCellRanks(CellData[] cellData) {
double[][] results = new double[cellData.length][];
for (int i = 0; i < cellData.length; i++)
results[i] = cellData[i].getRank();
return results;
}
}
| 17,806 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
MatrixCalculator.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/metric/MatrixCalculator.java | package ezcol.metric;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import ij.ImagePlus;
import ij.measure.ResultsTable;
import ezcol.cell.CellData;
import ezcol.debug.ExceptionHandler;
import ezcol.main.PluginConstants;
import ezcol.visual.visual2D.HeatChart;
public class MatrixCalculator extends BasicCalculator {
public static final int DO_MATRIX = PluginConstants.DO_MATRIX, DO_LINEAR_TOS = PluginConstants.DO_LINEAR_TOS,
DO_LOG2_TOS = PluginConstants.DO_LOG2_TOS, DO_LN_TOS = PluginConstants.DO_LN_TOS,
OPTS_TOS = PluginConstants.OPTS_TOS;
public static final String SHOW_TOS_LINEAR = "TOS(linear)", SHOW_TOS_LOG2 = "TOS(log2)", SHOW_PCC = "PCC",
SHOW_SRC = "SRCC", SHOW_ICQ = "ICQ", SHOW_M1 = "M1", SHOW_M2 = "M2", SHOW_M3 = "M3";
private static final String[] METRIC_NAMES = { SHOW_TOS_LINEAR, SHOW_TOS_LOG2, SHOW_PCC, SHOW_SRC, SHOW_ICQ,
SHOW_M1, SHOW_M2 };
private double[][] mMetric;
private CellData[] cellC1, cellC2;
private ResultsTable mTOSResultTable;
// private ImagePlus mTOSmedianHeatmap;
// private ImagePlus mTOSallHeatmap;
public MatrixCalculator() {
options = 0;
}
public MatrixCalculator(int[] cutoffs) {
options = DO_LINEAR_TOS | DO_MATRIX;
if (cutoffs != null && cutoffs.length >= 2)
this.cutoffs = cutoffs.clone();
else
this.cutoffs = new int[] { DEFAULT_FT, DEFAULT_FT };
numFT2SF();
}
public MatrixCalculator(int options, int[] cutoffs) {
this.options = options;
if (cutoffs != null && cutoffs.length >= 2)
this.cutoffs = cutoffs.clone();
else
this.cutoffs = new int[] { DEFAULT_FT, DEFAULT_FT };
numFT2SF();
}
public MatrixCalculator(BasicCalculator callBase) {
this.options = callBase.options;
this.numOfCell = callBase.numOfCell;
this.ftCs = callBase.ftCs;
this.allCs = callBase.allCs;
this.costesCs = callBase.costesCs;
}
public boolean calMetrics(CellData[] cellC1, CellData[] cellC2, int metricIndex) {
if (!prepCellData(cellC1, cellC2, new int[] { BasicCalculator.THOLD_ALL }))
return false;
if ((options & DO_MATRIX) != 0) {
mMetric = new double[numOfCell][cutoffs[0] * cutoffs[1]];
for (int iCell = 0; iCell < numOfCell; iCell++) {
// also gives TOSmax and TOSmin
if (mMetric != null) {
this.cellC1 = allCs[0];
this.cellC2 = allCs[1];
mMetric[iCell] = getMatrix(iCell, metricIndex);
if (mMetric[iCell] == null) {
mMetric = null;
return false;
}
}
// get TOSmin and TOSmax are in getmTOS function
}
printmTOS();
} else {
mMetric = null;
}
return true;
}
private void printmTOS() {
if (mMetric == null || sfsCs == null)
return;
if (mTOSResultTable == null)
mTOSResultTable = new ResultsTable();
else
mTOSResultTable.reset();
for (int iCell = 0; iCell < numOfCell; iCell++) {
mTOSResultTable.incrementCounter();
// mTOSResultTable.addLabel("shot-"+(iFrame)+" "+"cell-"+(iCell+1));
for (int count1 = 0; count1 < sfsCs[0].length; count1++) {
for (int count2 = 0; count2 < sfsCs[1].length; count2++) {
mTOSResultTable.addValue("S1-" + sfsCs[0][count1] + "_S2-" + sfsCs[1][count2],
mMetric[iCell][count2 + sfsCs[1].length * count1]);
}
}
}
}
public ResultsTable getResultsTable() {
return mTOSResultTable;
}
/**
* Introduced in version 1.2
*/
/**
* This is used in getMatrices to update matrix heat map
*
* @param dataA
* @param dataB
* @param index
* @return
*/
protected double calMetric(CellData dataA, CellData dataB, int index, boolean noTholdA, boolean noTholdB) {
if (dataA == null || dataB == null)
return Double.NaN;
int length = dataA.length() < dataB.length() ? dataA.length() : dataB.length();
int overlap = 0;
for (int i = 0; i < length; i++) {
if (!Float.isNaN(dataA.getPixel(i)) && !Float.isNaN(dataB.getPixel(i)))
overlap++;
}
CellData copyA = new CellData(overlap);
CellData copyB = new CellData(overlap);
for (int i = 0, j = 0; i < length; i++) {
if (!Float.isNaN(dataA.getPixel(i)) && !Float.isNaN(dataB.getPixel(i))) {
copyA.setData(dataA, i, j);
copyB.setData(dataB, i, j);
j++;
}
}
double result;
if (index < 0 || index >= METRIC_NAMES.length)
return Double.NaN;
switch (METRIC_NAMES[index]) {
case SHOW_TOS_LINEAR:
result = getTOS(dataA, dataB)[0];
break;
case SHOW_TOS_LOG2:
result = getTOS(dataA, dataB)[1];
break;
case SHOW_PCC:
result = getPCC(copyA, copyB);
break;
case SHOW_SRC:
result = getSRCC(copyA, copyB);
break;
case SHOW_ICQ:
result = getICQ(copyA, copyB);
break;
// case SHOW_CUSTOM:
// result = getCustom(copyA,copyB);
// break;
// case SHOW_AVGINT_C1:
// result = getAVGINT(copyA,copyB)[0];
// break;
// case SHOW_AVGINT_C2:
// result = getAVGINT(copyA,copyB)[1];
// break;
// Use unprocessed data here because points below thresholds are also
// informative
case SHOW_M1:
result = getMCC(dataA, dataB)[0];
break;
case SHOW_M2:
result = getMCC(dataA, dataB)[1];
break;
default:
result = Double.NaN;
break;
}
if (Double.isNaN(result)) {
if (!((METRIC_NAMES[index] == SHOW_TOS_LINEAR || METRIC_NAMES[index] == SHOW_TOS_LOG2) && (noTholdA || noTholdB))) {
ExceptionHandler.addWarning(Thread.currentThread(), dataA.getCellLabel() + "(size:" + dataA.length()
+ ") returns a " + METRIC_NAMES[index] + " value of NaN");
ExceptionHandler.insertWarning(Thread.currentThread(), ExceptionHandler.NAN_WARNING);
}
}
return result;
}
/**
* only for metric heat map
*/
public Object[] getColorValues(int index, int num) {
if (index < 0 || index >= METRIC_NAMES.length)
return null;
switch (METRIC_NAMES[index]) {
case SHOW_TOS_LINEAR:
case SHOW_TOS_LOG2:
return getColorValues(-1, 1, num);
case SHOW_PCC:
return getColorValues(-1, 1, num);
case SHOW_SRC:
return getColorValues(-1, 1, num);
case SHOW_ICQ:
return getColorValues(-0.5, 0.5, num);
case SHOW_MCC:
case SHOW_M1:
case SHOW_M2:
case SHOW_M3:
return getColorValues(0, 1, num);
// case SHOW_M2:
// return getColorValues(0,1,num);
default:
return null;
}
}
/**
* over for metric heat map use
*/
public double[] getMetricRange(int index) {
if (index < 0 || index >= METRIC_NAMES.length)
return null;
switch (METRIC_NAMES[index]) {
case SHOW_TOS_LINEAR:
case SHOW_TOS_LOG2:
return new double[] { -1, 0, 1 };
case SHOW_PCC:
return new double[] { -1, 0, 1 };
case SHOW_SRC:
return new double[] { -1, 0, 1 };
case SHOW_ICQ:
return new double[] {-0.5, 0, 0.5 };
case SHOW_MCC:
case SHOW_M1:
case SHOW_M2:
case SHOW_M3:
return new double[] { 0, 0.5, 1 };
// case SHOW_M2:
// return new double[]{0,0.5,1};
default:
return null;
}
}
/**
* calculate the sums of the arrays above the thresholds in each array and
* in both arrays
*
* @see <code>MetricCalculator.getSum(float[] ,float[] , double, double)</code>
* @param a
* input array 1
* @param b
* input array 2
* @param thresholdA
* threshold of array a
* @param thresholdB
* threshold of array b
* @return an array of four values as [0].number of elements in a that is
* not NaN in a & not NaN in b [1].number of elements in b that is
* not NaN in a & not NaN in b [2].number of elements in a that is
* not NaN in a [3].number of elements in b that is not NaN in b
*/
public double[] getSum(float[] a, float[] b) {
if (a == null || b == null || a.length != b.length)
return new double[] { Double.NaN, Double.NaN, Double.NaN, Double.NaN };
double[] results = new double[4];
for (int i = 0; i < a.length; i++) {
if (!Float.isNaN(a[i]) && !Float.isNaN(b[i])) {
results[0]++;
results[1]++;
}
if (!Float.isNaN(a[i]))
results[2]++;
if (!Float.isNaN(b[i]))
results[3]++;
}
return results;
}
protected Object[] getColorValues(double min, double max, int numColorBar) {
Object[] inputC = new Object[numColorBar];
double increColorBar = (max - min) / (numColorBar - 1);
for (int i = 0; i < numColorBar; i++)
inputC[i] = round(min + increColorBar * i, 3);
return inputC;
}
public ResultsTable getMatrix(CellData[] cellC1, CellData[] cellC2, int index) {
if (cellC1 == null || cellC2 == null)
return null;
this.cellC1 = cellC1;
this.cellC2 = cellC2;
numOfCell = cellC1.length < cellC2.length ? cellC1.length : cellC2.length;
ResultsTable rt = new ResultsTable();
for (int iCell = 0; iCell < numOfCell; iCell++) {
double[] results = getMatrix(iCell, index);
rt.incrementCounter();
rt.addLabel(cellC1[iCell].getCellLabel());
for (int count1 = 0; count1 < sfsCs[0].length; count1++) {
for (int count2 = 0; count2 < sfsCs[1].length; count2++) {
rt.addValue("S1-" + sfsCs[0][count1] + "_S2-" + sfsCs[1][count2],
results[count2 + sfsCs[1].length * count1]);
}
}
}
return rt;
}
/**
*
* @param iCell
* @param callBases
* @return
*/
private double[] getMatrix(int iCell, int show_idx) {
if (cellC1 == null || cellC2 == null || sfsCs[0] == null || sfsCs[1] == null) {
ExceptionHandler.addError(Thread.currentThread(), "Null pointer in cell data and parameter");
return null;
}
double[] result = new double[sfsCs[0].length * sfsCs[1].length];
int size = cellC1[iCell].length() < cellC2[iCell].length() ? cellC1[iCell].length() : cellC2[iCell].length();
// sorting is done together to save time
if (!cellC1[iCell].isSorted())
cellC1[iCell].sort();
if (!cellC2[iCell].isSorted())
cellC2[iCell].sort();
// ResultsTable test =
for (int selection1 = 0; selection1 < sfsCs[0].length; selection1++) {
int positiveA = (int) Math.ceil((size * sfsCs[0][selection1]));
positiveA = positiveA < size ? positiveA : size;
CellData trimA = cellC1[iCell].getData(positiveA);
for (int selection2 = 0; selection2 < sfsCs[1].length; selection2++) {
int positiveB = (int) Math.ceil((size * sfsCs[1][selection2]));
positiveB = positiveB < size ? positiveB : size;
CellData trimB = cellC2[iCell].getData(positiveB);
if (selection1 == 0 && selection2 == sfsCs[1].length - 1) {
;
}
double metricDouble = calMetric(trimA, trimB, show_idx, sfsCs[0][selection1] >= 1.0,
sfsCs[1][selection2] >= 1.0);
// store channel 1 selection as row, channel 2 as column
result[selection2 + selection1 * sfsCs[1].length] = metricDouble;
}
}
return result;
}
// number of boundaries not interval (interval+!)
public static int numColorBar = 6;
public HeatChart getHeatChart(double[][] medianmValues, String title) {
if (medianmValues == null)
return null;
double minTOS = -1.0, maxTOS = 1.0, nullTOS = 0.0;
double increColorBar = (maxTOS - minTOS) / (numColorBar - 1);
Object[] inputC1 = new Object[sfsCs[0].length];
Object[] inputC2 = new Object[sfsCs[1].length];
Object[] inputC = new Object[numColorBar];
HeatChart mTOSHeatChart = new HeatChart(medianmValues, minTOS, nullTOS, maxTOS);
// mTOSHeatChart.setTitle(title);
for (int i = 0; i < sfsCs[0].length; i++)
inputC1[sfsCs[0].length - 1 - i] = sfsCs[0][i] + "%";
for (int i = 0; i < sfsCs[1].length; i++)
inputC2[i] = sfsCs[1][i] + "%";
for (int i = 0; i < numColorBar; i++)
inputC[i] = round(minTOS + increColorBar * i, 3);
mTOSHeatChart.setXValues(inputC1);
mTOSHeatChart.setYValues(inputC2);
mTOSHeatChart.setTitleFont(new Font("Arial", Font.PLAIN, 32));
mTOSHeatChart.setXAxisLabel("Selected % 1");
mTOSHeatChart.setYAxisLabel("Selected % 2");
mTOSHeatChart.setAxisLabelsFont(new Font("Arial", Font.PLAIN, 18));
mTOSHeatChart.setAxisValuesFont(new Font("Arial", Font.PLAIN, 16));
mTOSHeatChart.setColorValuesFont(new Font("Arial", Font.PLAIN, 16));
mTOSHeatChart.setAxisThickness(0);
mTOSHeatChart.setBackgroundColour(Color.LIGHT_GRAY);
mTOSHeatChart.setLowValueColour(Color.BLUE);
mTOSHeatChart.setHighValueColour(Color.RED);
mTOSHeatChart.setMiddleValueColour(Color.WHITE);
mTOSHeatChart.setCellSize(new Dimension(50, 50));
mTOSHeatChart.setColorBarWidth(25);
mTOSHeatChart.setColorBarValues(inputC);
return mTOSHeatChart;
}
public ImagePlus getHeatmap(double[][] medianmTValues, boolean show) {
if (medianmTValues == null)
return null;
HeatChart mTOSHeatChart = getHeatChart(medianmTValues, "metric matrix");
ImagePlus mTOSHeatmap = mTOSHeatChart.getImagePlus("metric matrix heatmap");
if (show)
mTOSHeatmap.show();
return mTOSHeatmap;
}
/**
* get the number of metric names it is also the number of metrics
* calculated in the derived class please use BasicCalculator.getNum() for
* DEFAULT_NAMES
*
* @return
*/
public static int getNum() {
return METRIC_NAMES.length;
}
/**
* get the name of the metric please use BasicCalculator.getNum() for
* DEFAULT_IDXES
*
* @param i
* index of the metric
* @return the name of i-th metric
*/
public static String getNames(int i) {
if (i < 0 || i >= METRIC_NAMES.length)
return null;
return METRIC_NAMES[i];
}
public static String[] getAllMetrics() {
return METRIC_NAMES.clone();
}
}
| 13,259 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
StringCompiler.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/metric/StringCompiler.java | package ezcol.metric;
import java.awt.Font;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.CharArrayReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Vector;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticListener;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import ij.IJ;
import ij.Menus;
import ij.Prefs;
import ij.gui.GenericDialog;
import ij.io.OpenDialog;
import ij.plugin.Macro_Runner;
import ij.plugin.PlugIn;
import ij.plugin.filter.PlugInFilter;
import ij.plugin.filter.PlugInFilterRunner;
import ij.plugin.frame.Editor;
import ezcol.debug.ExceptionHandler;
import ezcol.main.PluginStatic;
/**
* Dynamic java class compiler and executer <br>
* Demonstrate how to compile dynamic java source code, <br>
* instantiate instance of the class, and finally call method of the class <br>
*
* http://www.beyondlinux.com
*
*
*/
public class StringCompiler {
/** where shall the compiled class be saved to (should exist already) */
public static int tabSize = 2;
private static String classOutputFolder = System.getProperty("java.io.tmpdir");
private static String className = "customCode";
private static String funcName = "customFunc";
private static String defaultCode = makeDefaultCode(PluginStatic.nChannels);
private String runCode = defaultCode;
// please be aware that paramsObj is not used in execute(c1,c2) to
// accommodate parallel programming
private Object paramsObj[];
private Object instance;
private boolean compiled;
private File file;
private Class<?> thisClass;
public class MyDiagnosticListener implements DiagnosticListener<JavaFileObject> {
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
/*
* System.out.println("Line Number->" + diagnostic.getLineNumber());
* System.out.println("code->" + diagnostic.getCode());
* System.out.println("Message->" +
* diagnostic.getMessage(Locale.ENGLISH));
* System.out.println("Source->" + diagnostic.getSource());
* System.out.println(" ");
*/
}
}
/**
* java File Object represents an in-memory java source file <br>
* so there is no need to put the source file on hard disk
**/
public class InMemoryJavaFileObject extends SimpleJavaFileObject {
private String contents = null;
public InMemoryJavaFileObject(String className, String contents) throws Exception {
super(URI.create("string:///" + className.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
this.contents = contents;
}
public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
return contents;
}
}
/**
* Get a simple Java File Object ,<br>
* It is just for demo, content of the source code is dynamic in real use
* case
*/
private JavaFileObject getJavaFileObject() {
JavaFileObject so = null;
if(runCode == null || runCode.equals(""))
return so;
StringBuilder contents = new StringBuilder(runCode);
try {
so = new InMemoryJavaFileObject(className, contents.toString());
} catch (Exception exception) {
exception.printStackTrace();
ExceptionHandler.addException(exception);
}
return so;
}
public static String getDefaultPath(){
return classOutputFolder + className + ".java";
}
/*public static boolean isAdmin() {
if (Platform.isMac()) {
try {
Process p = Runtime.getRuntime().exec("id -Gn");
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is, StandardCharsets.US_ASCII);
BufferedReader br = new BufferedReader(isr);
p.waitFor();
int exitValue = p.exitValue();
String exitLine = br.readLine();
if (exitValue != 0 || exitLine == null || exitLine.isEmpty()) {
HandleError..
return false;
}
if (exitLine.matches(".*\\badmin\\b.*")) {
return true;
}
return false;
} catch (IOException | InterruptedException e) {
//HandleError..
}
}else{
String groups[] = (new com.sun.security.auth.module.NTSystem()).getGroupIDs();
for (String group : groups) {
if (group.equals("S-1-5-32-544"))
return true;
}
}
return false;
}*/
public boolean compileCustom() throws Exception {
compiled = false;
JavaFileObject file = getJavaFileObject();
Iterable<? extends JavaFileObject> files = Arrays.asList(file);
if (file == null || files == null)
return false;
// 2.Compile your files by JavaCompiler as foll
// get system compiler:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null || true) {
String path = getDefaultPath();
compiled = true;
compiled = compiled && save(path);
compiled = compiled && compileNotRun(path);
compiled = compiled && preExecute();
return compiled;
} else {
// for compilation diagnostic message processing on compilation
// WARNING/ERROR
MyDiagnosticListener c = new MyDiagnosticListener();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(c, Locale.ENGLISH, null);
// specify classes output folder
Iterable<String> options = Arrays.asList("-d", classOutputFolder);
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, c, options, null, files);
Boolean result = task.call();
if (result == true) {
preExecute();
compiled = true;
return true;
} else {
ExceptionHandler.addError(Thread.currentThread(), "Cannot compile custom code.");
return false;
}
}
}
public boolean compileCustom(String runCode) throws Exception {
setCode(runCode);
return compileCustom();
}
private boolean preExecute() {
// Create a File object on the root of the directory
// containing the class file
file = new File(classOutputFolder);
try {
// Convert File to a URL
URL url = file.toURI().toURL(); // file:/classes/demo
URL[] urls = new URL[] { url };
// Create a new class loader with the directory
@SuppressWarnings("resource")
ClassLoader loader = new URLClassLoader(urls);
// Load in the class; Class.childclass should be located in
// the directory file:/class/demo/
thisClass = loader.loadClass(className);
instance = thisClass.newInstance();
return true;
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ExceptionHandler.addException(e);
}
return false;
}
public void reset() {
if (file != null) {
file.delete();
file = null;
}
instance = null;
thisClass = null;
compiled = false;
paramsObj = null;
}
/**
* run class from the compiled byte code file by URLClassloader
*
* @deprecated
* @Warning This is not for parallel programming
*/
public Object execute() throws Exception {
if (!compiled || file == null)
return null;
try {
Class<?> params[] = null;
if (paramsObj != null) {
params = new Class<?>[paramsObj.length];
for (int i = 0; i < params.length; i++)
params[i] = paramsObj[i].getClass();
}
Method thisMethod = thisClass.getDeclaredMethod(funcName, params);
// run the testAdd() method on the instance:
Object returnedObj = thisMethod.invoke(instance, paramsObj);
return returnedObj;
} catch (Exception ex) {
file.delete();
// ex.printStackTrace();
return null;
}
}
public Object execute(float[] c1, float[] c2) throws Exception {
// use local variables here to run in parallel
Object[] paramsObj = new Object[2];
paramsObj[0] = c1;
paramsObj[1] = c2;
return execute(paramsObj);
}
public Object execute(float[]... cs) throws Exception {
// use local variables here to run in parallel
Object[] paramsObj = new Object[cs.length];
for (int i = 0; i < cs.length; i++)
paramsObj[i] = cs[i];
return execute(paramsObj);
}
public Object execute(Object[] paramsObj) throws Exception {
if (!compiled || file == null)
return null;
try {
Class<?> params[] = null;
if (paramsObj != null) {
params = new Class<?>[paramsObj.length];
for (int i = 0; i < params.length; i++) {
params[i] = paramsObj[i].getClass();
}
}
Method thisMethod = thisClass.getDeclaredMethod(funcName, params);
// run the testAdd() method on the instance:
Object returnedObj = thisMethod.invoke(instance, paramsObj);
return returnedObj;
} catch (Exception ex) {
file.delete();
ExceptionHandler.addException(ex);
return null;
}
}
public void setParams(Object[] paramsObj) {
this.paramsObj = paramsObj;
}
public void setParams(float[] c1, float[] c2) {
paramsObj = new Object[2];
paramsObj[0] = c1;
paramsObj[1] = c2;
}
public boolean isCompiled() {
return compiled;
}
public void resetCode() {
runCode = defaultCode;
}
public void setCode(String runCode) {
this.runCode = runCode;
}
public String getCode() {
return runCode;
}
public static String getDefaultCode() {
return defaultCode;
}
public void setNChannel(int nChannels) {
makeDefaultCode(nChannels);
resetCode();
}
public static String makeDefaultCode(int nChannels) {
String defaultCode = "public class " + className + " { \n"
+ " //DO NOT change the next line except for renaming input variables \n" + " public double "
+ funcName + "(";
for (int i = 1; i < nChannels; i++)
defaultCode += "float[] c" + i + ", ";
defaultCode += "float[] c" + nChannels + ") { \n" + " \n" + " /*Please write your code here \n"
+ " ";
for (int i = 1; i < nChannels; i++)
defaultCode += "c" + i + " and ";
defaultCode += "c" + nChannels + " are arrays of pixel values of \n"
+ " fluorescence channels in the same cell \n"
+ " Here is an example of how to calculate \n"
+ " " + (nChannels == 2 ? "Pearson's correlation coefficient" : nChannels + "-order moment")
+ " */ \n" + " \n" + " float[] c = c1.clone(); \n"
+ " for (int i = 0; i < c.length ; i++){ \n";
for (int i = 2; i <= nChannels; i++)
defaultCode += " c[i] *= c" + i + "[i]; \n";
defaultCode += " } \n" + " return ( getMean(c) - \n" + " ";
for (int i = 1; i < nChannels; i++)
defaultCode += "getMean(c" + i + ") * ";
defaultCode += "getMean(c" + nChannels + ")) / \n" + " (";
for (int i = 1; i < nChannels; i++)
defaultCode += "getSTD(c" + i + ") * ";
defaultCode += "getSTD(c" + nChannels + ")); \n" + " } \n" + " \n"
+ " private double getMean(float[] x) { \n" + " double result=0.0; \n"
+ " for (int i=0;i<x.length;i++) \n" + " result+=x[i]; \n"
+ " return result/x.length; \n" + " } \n" + " \n"
+ " private double getSTD(float[] x) { \n" + " float[] y = x.clone(); \n"
+ " for (int i=0;i<x.length;i++) \n" + " y[i]*=y[i]; \n"
+ " return java.lang.Math.sqrt(\n" + " getMean(y)-getMean(x)*getMean(x)); \n" + " } \n"
+ "} \n";
StringCompiler.defaultCode = defaultCode;
return defaultCode;
}
// This method is copied from ij.plugin.frame.Editor
public boolean save(String path) {
File f = new File(path);
if (f.exists() && !f.canWrite()) {
IJ.showMessage("Editor", "Unable to save because file is write-protected. \n \n" + path);
return false;
}
String text = runCode;
if(text.equals(""))
text = null;
if(text == null)
return false;
char[] chars = new char[text.length()];
text.getChars(0, text.length(), chars, 0);
try {
BufferedReader br = new BufferedReader(new CharArrayReader(chars));
BufferedWriter bw = new BufferedWriter(new FileWriter(path));
while (true) {
String s = br.readLine();
if (s == null)
break;
bw.write(s, 0, s.length());
bw.newLine();
}
bw.close();
return true;
// IJ.showStatus(text.length()+" chars saved to " + path);
// changes = false;
} catch (IOException e) {
ExceptionHandler.addException(e);
}
return false;
}
// The following code is copied from ij.plugin.Compiler
// Because ToolProvider.getSystemJavaCompiler() requires JDK instead of JRE
private static final int TARGET14 = 0, TARGET15 = 1, TARGET16 = 2, TARGET17 = 3, TARGET18 = 4;
private static final String[] targets = { "1.4", "1.5", "1.6", "1.7", "1.8" };
private static final String TARGET_KEY = "javac.target";
private static CompilerTool compilerTool;
private static String dir, name;
private static Editor errors;
private static boolean generateDebuggingInfo;
private static int target = (int) Prefs.get(TARGET_KEY, TARGET16);
private static boolean checkForUpdateDone;
public void run(String arg) {
if (arg.equals("edit"))
edit();
else if (arg.equals("options"))
showDialog();
else {
if (arg != null && arg.length() > 0 && !arg.endsWith(".java"))
IJ.error("Compiler", "File name must end with \".java\"");
else
compileNotRun(arg);
}
}
void edit() {
if (open("", "Open macro or plugin")) {
Editor ed = (Editor) IJ.runPlugIn("ij.plugin.frame.Editor", "");
if (ed != null)
ed.open(dir, name);
}
}
boolean compileNotRun(String path) {
if (!open(path, "Compile and Run Plugin..."))
return false;
if (name.endsWith(".class")) {
runPlugin(name.substring(0, name.length() - 1));
return false;
}
if (!isJavac()) {
// boolean pluginClassLoader =
// this.getClass().getClassLoader()==IJ.getClassLoader();
// boolean contextClassLoader =
// Thread.currentThread().getContextClassLoader()==IJ.getClassLoader();
if (IJ.debugMode)
IJ.log("javac not found: ");
if (!checkForUpdateDone) {
checkForUpdate("/plugins/compiler/Compiler.jar", "1.48c");
checkForUpdateDone = true;
}
Object compiler = IJ.runPlugIn("Compiler", dir + name);
if (IJ.debugMode)
IJ.log("plugin compiler: " + compiler);
if (compiler == null) {
boolean ok = Macro_Runner.downloadJar("/plugins/compiler/Compiler.jar");
if (ok)
IJ.runPlugIn("Compiler", dir + name);
}
return false;
}
if (compile(dir + name))
return true;
// runPlugin(name);
return false;
}
private void checkForUpdate(String plugin, String currentVersion) {
int slashIndex = plugin.lastIndexOf("/");
if (slashIndex == -1 || !plugin.endsWith(".jar"))
return;
String className = plugin.substring(slashIndex + 1, plugin.length() - 4);
File f = new File(
Prefs.getImageJDir() + "plugins" + File.separator + "jars" + File.separator + className + ".jar");
if (!f.exists() || !f.canWrite()) {
if (IJ.debugMode)
IJ.log("checkForUpdate: jar not found (" + plugin + ")");
return;
}
String version = null;
try {
Class c = IJ.getClassLoader().loadClass("Compiler");
version = "0.00a";
Method m = c.getDeclaredMethod("getVersion", new Class[0]);
version = (String) m.invoke(null, new Object[0]);
} catch (Exception e) {
}
if (version == null) {
if (IJ.debugMode)
IJ.log("checkForUpdate: class not found (" + className + ")");
return;
}
if (version.compareTo(currentVersion) >= 0) {
if (IJ.debugMode)
IJ.log("checkForUpdate: up to date (" + className + " " + version + ")");
return;
}
boolean ok = Macro_Runner.downloadJar(plugin);
if (IJ.debugMode)
IJ.log("checkForUpdate: " + className + " " + version + " " + ok);
}
boolean isJavac() {
if (compilerTool == null)
compilerTool = CompilerTool.getDefault();
return compilerTool != null;
}
boolean compile(String path) {
IJ.showStatus("compiling " + path);
String classpath = getClassPath(path);
Vector options = new Vector();
if (generateDebuggingInfo)
options.addElement("-g");
validateTarget();
options.addElement("-source");
options.addElement(targets[target]);
options.addElement("-target");
options.addElement(targets[target]);
options.addElement("-Xlint:unchecked");
options.addElement("-deprecation");
options.addElement("-classpath");
options.addElement(classpath);
Vector sources = new Vector();
sources.add(path);
if (IJ.debugMode) {
StringBuilder builder = new StringBuilder();
builder.append("javac");
for (int i = 0; i < options.size(); i++) {
builder.append(" ");
builder.append(options.get(i));
}
for (int i = 0; i < sources.size(); i++) {
builder.append(" ");
builder.append(sources.get(i));
}
IJ.log(builder.toString());
}
boolean errors = true;
String s = "not compiled";
if (compilerTool != null) {
final StringWriter outputWriter = new StringWriter();
errors = !compilerTool.compile(sources, options, outputWriter);
s = outputWriter.toString();
} else {
errors = true;
}
if (errors)
ExceptionHandler.addError(s);
//showErrors(s);
else
IJ.showStatus("done");
return !errors;
}
// Returns a string containing the Java classpath,
// the path to the directory containing the plugin,
// and paths to any .jar files in the plugins folder.
String getClassPath(String path) {
long start = System.currentTimeMillis();
StringBuffer sb = new StringBuffer();
sb.append(System.getProperty("java.class.path"));
File f = new File(path);
if (f != null) // add directory containing file to classpath
sb.append(File.pathSeparator + f.getParent());
String pluginsDir = Menus.getPlugInsPath();
if (pluginsDir != null)
addJars(pluginsDir, sb);
return sb.toString();
}
// Adds .jar files in plugins folder, and subfolders, to the classpath
void addJars(String path, StringBuffer sb) {
String[] list = null;
File f = new File(path);
if (f.exists() && f.isDirectory())
list = f.list();
if (list == null)
return;
if (!path.endsWith(File.separator))
path += File.separator;
for (int i = 0; i < list.length; i++) {
File f2 = new File(path + list[i]);
if (f2.isDirectory())
addJars(path + list[i], sb);
else if (list[i].endsWith(".jar") && (list[i].indexOf("_") == -1 || list[i].equals("loci_tools.jar")
|| list[i].contains("3D_Viewer"))) {
sb.append(File.pathSeparator + path + list[i]);
if (IJ.debugMode)
IJ.log("javac classpath: " + path + list[i]);
}
}
}
void showErrors(String s) {
if (errors == null || !errors.isVisible()) {
errors = (Editor) IJ.runPlugIn("ij.plugin.frame.Editor", "");
errors.setFont(new Font("Monospaced", Font.PLAIN, 12));
}
if (errors != null)
errors.display("Errors", s);
IJ.showStatus("done (errors)");
}
// open the .java source file and return its content
public static String open(String path){
File f = new File(path);
if (f.exists() && !f.canRead()) {
IJ.showMessage("Editor", "Unable to read because file is read-protected. \n \n" + path);
return "";
}
String text = "";
try {
BufferedReader br = new BufferedReader(new FileReader(path));
while (true) {
String s = br.readLine();
if (s == null)
break;
text += s + "\n";
}
br.close();
// IJ.showStatus(text.length()+" chars saved to " + path);
// changes = false;
} catch (IOException e) {
ExceptionHandler.addError(Thread.currentThread(), "Cannot find the source file for custom code");
}
return text;
}
// open the .java source file
boolean open(String path, String msg) {
boolean okay;
String fileName, directory;
if (path.equals("")) {
if (dir == null)
dir = IJ.getDirectory("plugins");
OpenDialog od = new OpenDialog(msg, dir, name);
directory = od.getDirectory();
fileName = od.getFileName();
okay = fileName != null;
String lcName = okay ? fileName.toLowerCase(Locale.US) : null;
if (okay) {
if (msg.startsWith("Compile")) {
if (!(lcName.endsWith(".java") || lcName.endsWith(".class"))) {
IJ.error("File name must end with \".java\" or \".class\".");
okay = false;
}
} else if (!(lcName.endsWith(".java") || lcName.endsWith(".txt") || lcName.endsWith(".ijm")
|| lcName.endsWith(".js"))) {
IJ.error("File name must end with \".java\", \".txt\" or \".js\".");
okay = false;
}
}
} else {
int i = path.lastIndexOf('/');
if (i == -1)
i = path.lastIndexOf('\\');
if (i > 0) {
directory = path.substring(0, i + 1);
fileName = path.substring(i + 1);
} else {
directory = "";
fileName = path;
}
okay = true;
}
if (okay) {
name = fileName;
dir = directory;
Editor.setDefaultDirectory(dir);
}
return okay;
}
// only show files with names ending in ".java"
// doesn't work with Windows
public boolean accept(File dir, String name) {
return name.endsWith(".java") || name.endsWith(".macro") || name.endsWith(".txt");
}
// run the plugin using a new class loader
void runPlugin(String name) {
name = name.substring(0, name.length() - 5); // remove ".java"
new PlugInExecuter(name);
}
public void showDialog() {
validateTarget();
GenericDialog gd = new GenericDialog("Compile and Run");
gd.addChoice("Target: ", targets, targets[target]);
gd.setInsets(15, 5, 0);
gd.addCheckbox("Generate debugging info (javac -g)", generateDebuggingInfo);
gd.addHelp(IJ.URL + "/docs/menus/edit.html#compiler");
gd.showDialog();
if (gd.wasCanceled())
return;
target = gd.getNextChoiceIndex();
generateDebuggingInfo = gd.getNextBoolean();
validateTarget();
}
void validateTarget() {
if (target < 0 || target > TARGET18)
target = TARGET16;
if (target > TARGET15 && !(IJ.isJava16() || IJ.isJava17() || IJ.isJava18()))
target = TARGET15;
if (target > TARGET16 && !(IJ.isJava17() || IJ.isJava18()))
target = TARGET16;
if (target > TARGET17 && !IJ.isJava18())
target = TARGET17;
Prefs.set(TARGET_KEY, target);
}
}
class PlugInExecuter implements Runnable {
private String plugin;
private Thread thread;
/**
* Create a new object that runs the specified plugin in a separate thread.
*/
PlugInExecuter(String plugin) {
this.plugin = plugin;
thread = new Thread(this, plugin);
thread.setPriority(Math.max(thread.getPriority() - 2, Thread.MIN_PRIORITY));
thread.start();
}
public void run() {
IJ.resetEscape();
IJ.runPlugIn("ij.plugin.ClassChecker", "");
runCompiledPlugin(plugin);
}
void runCompiledPlugin(String className) {
if (IJ.debugMode)
IJ.log("runCompiledPlugin: " + className);
IJ.resetClassLoader();
ClassLoader loader = IJ.getClassLoader();
Object thePlugIn = null;
try {
thePlugIn = (loader.loadClass(className)).newInstance();
if (thePlugIn instanceof PlugIn)
((PlugIn) thePlugIn).run("");
else if (thePlugIn instanceof PlugInFilter)
new PlugInFilterRunner(thePlugIn, className, "");
} catch (ClassNotFoundException e) {
if (className.indexOf('_') != -1)
IJ.error("Plugin or class not found: \"" + className + "\"\n(" + e + ")");
} catch (NoClassDefFoundError e) {
String err = e.getMessage();
int index = err != null ? err.indexOf("wrong name: ") : -1;
if (index > -1 && !className.contains(".")) {
String className2 = err.substring(index + 12, err.length() - 1);
className2 = className2.replace("/", ".");
runCompiledPlugin(className2);
return;
}
if (className.indexOf('_') != -1)
IJ.error("Plugin or class not found: \"" + className + "\"\n(" + e + ")");
} catch (Exception e) {
// IJ.error(""+e);
IJ.handleException(e); // Marcel Boeglin 2013.09.01
// Logger.getLogger(getClass().getName()).log(Level.SEVERE, null,
// e); //IDE output
}
}
}
abstract class CompilerTool {
public static class JavaxCompilerTool extends CompilerTool {
protected static Class charsetC;
protected static Class diagnosticListenerC;
protected static Class javaFileManagerC;
protected static Class toolProviderC;
public boolean compile(List sources, List options, StringWriter log) {
try {
Object javac = getJavac();
Class[] getStandardFileManagerTypes = new Class[] { diagnosticListenerC, Locale.class, charsetC };
Method getStandardFileManager = javac.getClass().getMethod("getStandardFileManager",
getStandardFileManagerTypes);
Object fileManager = getStandardFileManager.invoke(javac, new Object[] { null, null, null });
Class[] getJavaFileObjectsFromStringsTypes = new Class[] { Iterable.class };
Method getJavaFileObjectsFromStrings = fileManager.getClass().getMethod("getJavaFileObjectsFromStrings",
getJavaFileObjectsFromStringsTypes);
Object compilationUnits = getJavaFileObjectsFromStrings.invoke(fileManager, new Object[] { sources });
Class[] getTaskParamTypes = new Class[] { Writer.class, javaFileManagerC, diagnosticListenerC,
Iterable.class, Iterable.class, Iterable.class };
Method getTask = javac.getClass().getMethod("getTask", getTaskParamTypes);
Object task = getTask.invoke(javac,
new Object[] { log, fileManager, null, options, null, compilationUnits });
Method call = task.getClass().getMethod("call", new Class[0]);
Object result = call.invoke(task, new Object[0]);
return Boolean.TRUE.equals(result);
} catch (Exception e) {
//PrintWriter printer = new PrintWriter(log);
//e.printStackTrace(printer);
//printer.flush();
e.printStackTrace();
ExceptionHandler.addException(e);
}
return false;
}
protected Object getJavac() throws Exception {
if (charsetC == null)
charsetC = Class.forName("java.nio.charset.Charset");
if (diagnosticListenerC == null)
diagnosticListenerC = Class.forName("javax.tools.DiagnosticListener");
if (javaFileManagerC == null)
javaFileManagerC = Class.forName("javax.tools.JavaFileManager");
if (toolProviderC == null)
toolProviderC = Class.forName("javax.tools.ToolProvider");
Method get = toolProviderC.getMethod("getSystemJavaCompiler", new Class[0]);
return get.invoke(null, new Object[0]);
}
}
public static class LegacyCompilerTool extends CompilerTool {
protected static Class javacC;
boolean areErrors(String s) {
boolean errors = s != null && s.length() > 0;
if (errors && s.indexOf("1 warning") > 0 && s.indexOf("[deprecation] show()") > 0)
errors = false;
// if(errors&&s.startsWith("Note:com.sun.tools.javac")&&s.indexOf("error")==-1)
// errors = false;
return errors;
}
public boolean compile(List sources, List options, StringWriter log) {
try {
final String[] args = new String[sources.size() + options.size()];
int argsIndex = 0;
for (int optionsIndex = 0; optionsIndex < options.size(); optionsIndex++)
args[argsIndex++] = (String) options.get(optionsIndex);
for (int sourcesIndex = 0; sourcesIndex < sources.size(); sourcesIndex++)
args[argsIndex++] = (String) sources.get(sourcesIndex);
Object javac = getJavac();
Class[] compileTypes = new Class[] { String[].class, PrintWriter.class };
Method compile = javacC.getMethod("compile", compileTypes);
PrintWriter printer = new PrintWriter(log);
Object result = compile.invoke(javac, new Object[] { args, printer });
printer.flush();
return Integer.valueOf(0).equals(result) | !areErrors(log.toString());
} catch (Exception e) {
//e.printStackTrace(new PrintWriter(log));
e.printStackTrace();
ExceptionHandler.addException(e);
}
return false;
}
protected Object getJavac() throws Exception {
if (javacC == null)
javacC = Class.forName("com.sun.tools.javac.Main");
return javacC.newInstance();
}
}
public static CompilerTool getDefault() {
/*CompilerTool javax = new JavaxCompilerTool();
if (javax.isSupported()) {
if (IJ.debugMode)
IJ.log("javac: using javax.tool.JavaCompiler");
return javax;
}*/
CompilerTool legacy = new LegacyCompilerTool();
if (legacy.isSupported()) {
if (IJ.debugMode)
IJ.log("javac: using com.sun.tools.javac");
return legacy;
}
return null;
}
public abstract boolean compile(List sources, List options, StringWriter log);
protected abstract Object getJavac() throws Exception;
public boolean isSupported() {
try {
return null != getJavac();
} catch (Exception e) {
return false;
}
}
} | 28,562 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
OutputWindow.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/visual/visual2D/OutputWindow.java | package ezcol.visual.visual2D;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.Vector;
import ij.IJ;
import ij.ImagePlus;
import ezcol.debug.ExceptionHandler;
import ezcol.main.PluginStatic;
public class OutputWindow {
//This class shares the same constants with
public static final int DO_SUMMARY = PluginStatic.DO_SUMMARY;
public static final String CUSTOM_NAME = "Custom Metric";
public static final String CUSTOM_STRING = "These are the statistics of custom analysis.\n";
public static final String NAME_SUFFIX = "\n";
private String customName = CUSTOM_NAME;
private String customString = CUSTOM_STRING;
private int options;
private static final String SEPARATOR_LINE=("-----------------------------------------------------");
private static final String BLANK_SPACE=(" ");
private final Vector<Stats> moreStats = new Vector<Stats>();
private final Vector<ImgLabel> images = new Vector<ImgLabel>();
//use a map here in case different metric have different number of cells
private final Set<Integer> numOfCell = new HashSet<Integer>();
public void showLogWindow(){
IJ.log("Results Summary:");
IJ.log(BLANK_SPACE);
//add in image names obtained from plugin (also status of aligned/unaligned) and number of cells,
//this could be tricky with all the input combinations
for(ImgLabel image: images)
IJ.log(image.getLabel() + " image(s): " + image.getName() + " "
+ (image.isAligned()==null ? "" : (image.isAligned()?"(Aligned)":"(Unaligned)")));
//add in spacing lines and then need to get number of cells identified from plugin
IJ.log(BLANK_SPACE);
//if numbers of cell are the same for all metrics, print it here
//otherwise, print it for each cell
if(numOfCell.size()==1)
IJ.log("Number of cells analyzed = "+numOfCell.toArray()[0]+"\n");
IJ.log(BLANK_SPACE);
//All exceptions should be handled here
//this can be removed without affecting any other functions
ExceptionHandler.print2log();
IJ.log(SEPARATOR_LINE);
int custom = 0;
for(Stats stat : moreStats){
if(stat==null)
continue;
if(stat.getName()!=null)
IJ.log(stat.getName()+" "+NAME_SUFFIX);
else
IJ.log(customName+"_"+(++custom)+" "+NAME_SUFFIX);
if((options&DO_SUMMARY)!=0){
IJ.log("mean = "+stat.getMean());
IJ.log("standard deviation = "+stat.getStd());
IJ.log("median = "+stat.getMedian());
}
if(numOfCell.size()>1)
IJ.log("Number of cells = "+stat.getNum());
IJ.log(BLANK_SPACE);
IJ.log("Interpretation: ");
if(stat.getInterpretation()!=null)
IJ.log(stat.getInterpretation());
else
IJ.log(customString);
IJ.log(SEPARATOR_LINE);
}
}
public void setOption(int options){
this.options = options;
}
/**
* reset all arrays, vectors, and sets
*/
public void clear(){
moreStats.clear();
images.clear();
numOfCell.clear();
}
//function to calculate mean of array m, will need to get an array from plugin to perform calculation
private double mean(double[] m) {
if(m==null||m.length==0)
return Double.NaN;
double sum = 0;
for (int i = 0; i < m.length; i++) {
sum += m[i];
}
return sum / m.length;
}
//function to calculate median of array m, will need to get an array from plugin to perform calculation
private double median(double[] m) {
if(m==null||m.length==0)
return Double.NaN;
Arrays.sort(m);
int middle = m.length/2;
if (m.length%2 == 1) {
return m[middle];
} else {
return (m[middle-1] + m[middle]) / 2.0;
}
}
//function to calculate standard deviation of array m, will need to get an array from plugin to perform calculation
private double stdDeviation(double[] m) {
if(m==null||m.length==0)
return Double.NaN;
double sum = 0;
for (int i = 0; i < m.length; i++) {
sum += m[i];
}
double sigma = 0;
for (int i = 0; i < m.length; i++) {
sigma += (m[i]-(sum / m.length))*(m[i]-(sum / m.length));
}
return Math.sqrt(sigma/m.length);
}
/**
* Add a new metric with its interpretation
* @param values a double array of metric value, the length will be considered as the number of values
* @param name, the name of the metric
*/
public void addMetric(double[] values, String[] interpretation){
if(values == null)
return;
//The id has not been found so the metric will be added to the vector
moreStats.add(new Stats(values.length,mean(values),stdDeviation(values),median(values),interpretation));
numOfCell.add(values.length);
}
/**
* Add a new metric with its name
* @param values a double array of metric value, the length will be considered as the number of values
* @param name, the name of the metric
*/
public void addMetric(double[] values, String name){
addMetric(values, new String[]{name, null});
}
/**
* Add a new metric, which will be added as a custom metric
* @param values a double array of metric value, the length will be considered as the number of values
*/
public void addMetric(double[] values){
addMetric(values, new String[]{customName+" "+(moreStats.size()+1),customString});
customName = CUSTOM_NAME;
customString = CUSTOM_STRING;
}
/**
* Add a new image channel
* @param label the name of the channel
* @param imp the image of the channel
* @param aligned whether the image was aligned or not
*/
public void addImage(String label, ImagePlus imp, Boolean aligned){
images.add(new ImgLabel(label,imp,aligned));
}
/**
* implements <code>addImage(label, imp, aligned)</code> assuming the image was not aligned
* @see OutputWindow#addImage(String, ImagePlus, boolean)
*/
public void addImage(String label, ImagePlus imp){
images.add(new ImgLabel(label,imp));
}
public void setCustomName(String customName){
this.customName = customName;
}
public void setCustomString(String customString){
this.customString = customString;
}
}
class ImgLabel{
ImgLabel(String imgLabel,ImagePlus imp, Boolean aligned) {
this.imp = imp;
this.imgLabel = imgLabel;
this.aligned = aligned;
}
ImgLabel(String imgLabel,ImagePlus imp) {
this.imp = imp;
this.imgLabel = imgLabel;
this.aligned = null;
}
ImagePlus getImp() {return imp;}
String getName() { return imp==null?"":imp.getTitle(); }
String getLabel() { return imgLabel; }
Boolean isAligned() { return aligned; }
private ImagePlus imp;
private String imgLabel;
private Boolean aligned;
}
class Stats{
Stats(int num, double mean, double std, double median, String[] metric) {
this.num = num;
this.mean = mean;
this.std = std;
this.median = median;
if(metric==null){
this.name = null;
this.interpretation = null;
}else{
this.name = metric[0];
this.interpretation = metric[1];
}
}
int getNum() {return num;}
double getMedian() { return median; }
double getMean() { return mean; }
double getStd() { return std; }
String getInterpretation() { return interpretation;}
String getName() { return name;}
private int num;
private double mean;
private double std;
private double median;
private String name;
private String interpretation;
}
| 7,377 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
HeatGenerator.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/visual/visual2D/HeatGenerator.java | package ezcol.visual.visual2D;
import java.awt.Color;
import java.awt.image.IndexColorModel;
import ij.CompositeImage;
import ij.IJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.WindowManager;
import ij.gui.Roi;
import ij.io.FileInfo;
import ij.plugin.ImageCalculator;
import ij.plugin.frame.RoiManager;
import ij.process.ImageConverter;
import ij.process.ImageProcessor;
import ij.process.ImageStatistics;
import ezcol.debug.ExceptionHandler;
import ezcol.main.ImageInfo;
public class HeatGenerator {
private FileInfo fi;
private static final double[] Default_Scalar={0.0,1.0};
private static final double Default_Back=1.0;
private static final double[] Default_MAX={255.0,65535.0,255.0,65535.0};
//prepare LUT function modified from ImageJ function
public void prepColormap(String arg)
{
fi = new FileInfo();
fi.reds = new byte[256];
fi.greens = new byte[256];
fi.blues = new byte[256];
fi.lutSize = 256;
int nColors = 0;
if (arg.equals("*None*"))
return;
else if (arg.equals("hot"))
nColors = hot(fi.reds, fi.greens, fi.blues);
else if (arg.equals("cool"))
nColors = cool(fi.reds, fi.greens, fi.blues);
else if (arg.equals("fire"))
nColors = fire(fi.reds, fi.greens, fi.blues);
else if (arg.equals("grays"))
nColors = grays(fi.reds, fi.greens, fi.blues);
else if (arg.equals("ice"))
nColors = ice(fi.reds, fi.greens, fi.blues);
else if (arg.equals("spectrum"))
nColors = spectrum(fi.reds, fi.greens, fi.blues);
else if (arg.equals("3-3-2 RGB"))
nColors = rgb332(fi.reds, fi.greens, fi.blues);
else if (arg.equals("red"))
nColors = primaryColor(4, fi.reds, fi.greens, fi.blues);
else if (arg.equals("green"))
nColors = primaryColor(2, fi.reds, fi.greens, fi.blues);
else if (arg.equals("blue"))
nColors = primaryColor(1, fi.reds, fi.greens, fi.blues);
else if (arg.equals("cyan"))
nColors = primaryColor(3, fi.reds, fi.greens, fi.blues);
else if (arg.equals("magenta"))
nColors = primaryColor(5, fi.reds, fi.greens, fi.blues);
else if (arg.equals("yellow"))
nColors = primaryColor(6, fi.reds, fi.greens, fi.blues);
else if (arg.equals("redgreen"))
nColors = redGreen(fi.reds, fi.greens, fi.blues);
if (nColors<256)
interpolate(fi.reds, fi.greens, fi.blues, nColors);
}
@Deprecated
/*never used in the code*/
public void heatmap(ImagePlus imp, RoiManager[] roiTest,String Colormap,double[] scalar,double[] background,boolean Apply)
{
if(Colormap.equals(ImageInfo.NONE)||imp==null)
return;
if(scalar != null)
{
ImageStack iStack=imp.getStack();
for (int iFrame=1;iFrame<=iStack.getSize();iFrame++)
{
ImageProcessor impProcessor=iStack.getProcessor(iFrame);
if(roiTest==null&&background==null)
heatmap(impProcessor,null,scalar,Default_Back);
else if(roiTest==null)
heatmap(impProcessor,null,scalar,background[iFrame]);
else if(background==null)
heatmap(impProcessor,roiTest[iFrame],scalar);
}
}
if(Apply)
applyHeatMap(imp,Colormap,false,true);
}
public void heatmap(ImageProcessor impProcessor, RoiManager roiTest,double[] scalar)
{heatmap(impProcessor, roiTest,scalar,Default_Back); }
public void heatmap(ImageProcessor impProcessor, RoiManager roiTest)
{heatmap(impProcessor, roiTest,Default_Scalar,Default_Back); }
//change the pixel values to rescale the heat map
public void heatmap(ImageProcessor impProcessor, RoiManager roiTest,double[] scalar,double background){
if(scalar==null||impProcessor==null)
return;
if(roiTest==null){
impProcessor.resetMinAndMax();
impProcessor.subtract(scalar[0]*background);
impProcessor.multiply(getPosMax(impProcessor)/((scalar[1]-scalar[0])*background));
}
else{
impProcessor.setValue(0.0);
Roi[] roiAll=roiTest.getRoisAsArray();
int numRois=roiTest.getCount();
if(numRois==0){
impProcessor.resetRoi();
impProcessor.fill();
return;
}
ImageStatistics roiStatistics;
ImageProcessor tempMask=impProcessor.createProcessor(impProcessor.getWidth(),impProcessor.getHeight());
//combining rois is too slow, clear outside first before doing this
//ShapeRoi combinedRoi=new ShapeRoi(roiAll[0]);
for (int iRoi=0;iRoi<numRois;iRoi++){
impProcessor.setRoi(roiAll[iRoi]);
roiStatistics=impProcessor.getStatistics();
impProcessor.snapshot();
impProcessor.subtract(roiStatistics.min);
impProcessor.multiply(getPosMax(impProcessor)/(roiStatistics.max-roiStatistics.min));
impProcessor.reset(impProcessor.getMask());
tempMask.setColor(Color.WHITE);
tempMask.fill(roiAll[iRoi]);
//combinedRoi.or(new ShapeRoi(roiAll[iRoi]));
}
tempMask.invert();
imgCalculator("sub",impProcessor,tempMask);
tempMask=null;
//impProcessor.fillOutside(combinedRoi);
}
}
//apply LUT
public ImagePlus applyHeatMap(ImagePlus imp,String Colormap,boolean toRGB,boolean Show){
if(Colormap.equals(ImageInfo.NONE)||imp==null)
return imp;
prepColormap(Colormap);
showLut(fi,imp);
imp.deleteRoi();
imp.getProcessor().setMinAndMax(0.0,getPosMax(imp));
imp.updateImage();
if(toRGB)
new ImageConverter(imp).convertToRGB();
if(Show)
imp.show();
return imp;
}
//ImageCalculator using imageprocessor as inputs to clear the background outside the cell
private ImageProcessor imgCalculator(String Operator,ImageProcessor ip1, ImageProcessor ip2)
{
ImageCalculator imgCalcu=new ImageCalculator();
ImagePlus tempimp=imgCalcu.run(Operator,new ImagePlus("ip1",ip1),new ImagePlus("ip2",ip2));
if(tempimp!=null)
return tempimp.getProcessor();
else
return null;
}
int hot(byte[] reds, byte[] greens, byte[] blues) {
int[] r = {0,23,46,70,93,116,139,162,185,209,232,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255};
int[] g = {0,0,0,0,0,0,0,0,0,0,0,0,23,46,70,93,116,139,162,185,209,232,255,255,255,255,255,255,255,255,255,255};
int[] b = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,28,57,85,113,142,170,198,227,255};
for (int i=0; i<r.length; i++) {
reds[i] = (byte)r[i];
greens[i] = (byte)g[i];
blues[i] = (byte)b[i];
}
return r.length;
}
int cool(byte[] reds, byte[] greens, byte[] blues) {
int[] r = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,17,34,51,68,85,102,119,136,153,170,187,204,221,238,255};
int[] g = {0,18,34,51,68,85,102,119,136,153,170,187,204,221,238,255,255,238,221,204,187,170,153,136,119,102,85,68,51,34,17,0};
int[] b = {0,18,34,51,68,85,102,119,136,153,170,187,204,221,238,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255};
for (int i=0; i<r.length; i++) {
reds[i] = (byte)r[i];
greens[i] = (byte)g[i];
blues[i] = (byte)b[i];
}
return r.length;
}
int fire(byte[] reds, byte[] greens, byte[] blues) {
int[] r = {0,0,1,25,49,73,98,122,146,162,173,184,195,207,217,229,240,252,255,255,255,255,255,255,255,255,255,255,255,255,255,255};
int[] g = {0,0,0,0,0,0,0,0,0,0,0,0,0,14,35,57,79,101,117,133,147,161,175,190,205,219,234,248,255,255,255,255};
int[] b = {0,61,96,130,165,192,220,227,210,181,151,122,93,64,35,5,0,0,0,0,0,0,0,0,0,0,0,35,98,160,223,255};
for (int i=0; i<r.length; i++) {
reds[i] = (byte)r[i];
greens[i] = (byte)g[i];
blues[i] = (byte)b[i];
}
return r.length;
}
int grays(byte[] reds, byte[] greens, byte[] blues) {
for (int i=0; i<256; i++) {
reds[i] = (byte)i;
greens[i] = (byte)i;
blues[i] = (byte)i;
}
return 256;
}
int primaryColor(int color, byte[] reds, byte[] greens, byte[] blues) {
for (int i=0; i<256; i++) {
if ((color&4)!=0)
reds[i] = (byte)i;
if ((color&2)!=0)
greens[i] = (byte)i;
if ((color&1)!=0)
blues[i] = (byte)i;
}
return 256;
}
int ice(byte[] reds, byte[] greens, byte[] blues) {
int[] r = {0,0,0,0,0,0,19,29,50,48,79,112,134,158,186,201,217,229,242,250,250,250,250,251,250,250,250,250,251,251,243,230};
int[] g = {156,165,176,184,190,196,193,184,171,162,146,125,107,93,81,87,92,97,95,93,93,90,85,69,64,54,47,35,19,0,4,0};
int[] b = {140,147,158,166,170,176,209,220,234,225,236,246,250,251,250,250,245,230,230,222,202,180,163,142,123,114,106,94,84,64,26,27};
for (int i=0; i<r.length; i++) {
reds[i] = (byte)r[i];
greens[i] = (byte)g[i];
blues[i] = (byte)b[i];
}
return r.length;
}
int spectrum(byte[] reds, byte[] greens, byte[] blues) {
Color c;
for (int i=0; i<256; i++) {
c = Color.getHSBColor(i/255f, 1f, 1f);
reds[i] = (byte)c.getRed();
greens[i] = (byte)c.getGreen();
blues[i] = (byte)c.getBlue();
}
return 256;
}
int rgb332(byte[] reds, byte[] greens, byte[] blues)
{
for (int i=0; i<256; i++) {
reds[i] = (byte)(i&0xe0);
greens[i] = (byte)((i<<3)&0xe0);
blues[i] = (byte)((i<<6)&0xc0);
}
return 256;
}
int redGreen(byte[] reds, byte[] greens, byte[] blues) {
for (int i=0; i<128; i++) {
reds[i] = (byte)(i*2);
greens[i] = (byte)0;
blues[i] = (byte)0;
}
for (int i=128; i<256; i++) {
reds[i] = (byte)0;
greens[i] = (byte)(i*2);
blues[i] = (byte)0;
}
return 256;
}
//showLut function from ImageJ
void showLut(FileInfo fi, ImagePlus imp) {
//ImagePlus imp = WindowManager.getCurrentImage();
if (imp==null) { imp = WindowManager.getCurrentImage();}
if (imp.getType()==ImagePlus.COLOR_RGB)
ExceptionHandler.addError(Thread.currentThread(),"LUTs cannot be assiged to RGB Images.");
else if (imp.isComposite() && ((CompositeImage)imp).getMode()==IJ.GRAYSCALE) {
CompositeImage cimp = (CompositeImage)imp;
cimp.setMode(IJ.COLOR);
int saveC = cimp.getChannel();
IndexColorModel cm = new IndexColorModel(8, 256, fi.reds, fi.greens, fi.blues);
for (int c=1; c<=cimp.getNChannels(); c++) {
cimp.setC(c);
cimp.setChannelColorModel(cm);
}
imp.setC(saveC);
imp.updateAndRepaintWindow();
} else {
ImageProcessor ip = imp.getChannelProcessor();
IndexColorModel cm = new IndexColorModel(8, 256, fi.reds, fi.greens, fi.blues);
if (imp.isComposite())
((CompositeImage)imp).setChannelColorModel(cm);
else
ip.setColorModel(cm);
if (imp.getStackSize()>1)
imp.getStack().setColorModel(cm);
imp.updateAndRepaintWindow();
}
}
void interpolate(byte[] reds, byte[] greens, byte[] blues, int nColors) {
byte[] r = new byte[nColors];
byte[] g = new byte[nColors];
byte[] b = new byte[nColors];
System.arraycopy(reds, 0, r, 0, nColors);
System.arraycopy(greens, 0, g, 0, nColors);
System.arraycopy(blues, 0, b, 0, nColors);
double scale = nColors/256.0;
int i1, i2;
double fraction;
for (int i=0; i<256; i++) {
i1 = (int)(i*scale);
i2 = i1+1;
if (i2==nColors) i2 = nColors-1;
fraction = i*scale - i1;
//IJ.write(i+" "+i1+" "+i2+" "+fraction);
reds[i] = (byte)((1.0-fraction)*(r[i1]&255) + fraction*(r[i2]&255));
greens[i] = (byte)((1.0-fraction)*(g[i1]&255) + fraction*(g[i2]&255));
blues[i] = (byte)((1.0-fraction)*(b[i1]&255) + fraction*(b[i2]&255));
}
}
public double getPosMax(ImageProcessor impProcessor)
{
double MaxDepth=(double)impProcessor.getBitDepth();
if(MaxDepth==8)
MaxDepth=Default_MAX[0];
else if(MaxDepth==16)
MaxDepth=Default_MAX[1];
else if(MaxDepth==24)
MaxDepth=Default_MAX[2];
else if(MaxDepth==32)
MaxDepth=Default_MAX[3];
return MaxDepth;
}
public double getPosMax(ImagePlus imp)
{
return getPosMax(imp.getProcessor());
}
}
| 11,436 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
ProgressGlassPane.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/visual/visual2D/ProgressGlassPane.java | package ezcol.visual.visual2D;
//This is a modified version of the following class
//Retrived from http://www.java2s.com/Code/Java/Swing-Components/GlasspanePainting.htm
/*
* Copyright (c) 2007, Romain Guy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of the TimingFramework project 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
* OWNER 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.
*/
/**
*
* @author Romain Guy
*/
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.LinearGradientPaint;
import java.awt.Paint;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.util.Random;
import javax.swing.JComponent;
@SuppressWarnings("serial")
public class ProgressGlassPane extends JComponent{
private static final int BAR_WIDTH = 200;
private static final int BAR_HEIGHT = 10;
private static final Color TEXT_COLOR = new Color(0x333333);
//private static final Color BORDER_COLOR = new Color(0x333333);
private static final float[] GRADIENT_FRACTIONS = new float[] {
0.0f, 0.499f, 0.5f, 1.0f
};
private static final Color[] GRADIENT_COLORS = new Color[] {
Color.GRAY, Color.DARK_GRAY, Color.BLACK, Color.GRAY
};
private static final Color GRADIENT_COLOR2 = Color.WHITE;
private static final Color GRADIENT_COLOR1 = Color.GRAY;
private int wholeProgress = 100;
private String message = "Analyses in progress...";
private int progress = 0;
//new field(s)
private float alpha=0.65f;
private int oldProgress;
private Random random;
private String[] tips = {"Do you know?\nYou could hold \"Shift\" while pressing the button to ONLY run on the current slice of phase contrast channel.",
"Do you know?\nYou could send us an email by clicking the \"Email\" button at the bottom right corner.",
"Do you know?\nPutting a tip here is inspired by video games.",
"Do you know?\nYou could hold \"Alt\" while pressing any button to boost the performance. (Warning: it might be unstable)",
"Do you know?\nTo learn more about the metric, click the name in the subtab of \"Metrics info\" in \"Analysis\"",
"Do you know?\nThere might be additional information when the cursor hovers over buttons or labels",
"Do you know?\nThis plugin is available on GitHub at https://github.com/DrHanLim/EzColocalization",
"Do you know?\nYou can set the parameters of background subtraction in \"Parameters...\" of \"Settings\" menu"};
public ProgressGlassPane() {
setBackground(Color.WHITE);
setFont(new Font("Default", Font.BOLD, 16));
random = new Random();
}
public int getProgress() {
return progress;
}
/**
* This doesn't allow progress bar to roll back once increased to a higher value
* @param progress a integer from 0 to 100 determine the current progress
*/
public void setProgress(int progress) {
if(progress>wholeProgress)
progress=wholeProgress;
if(progress<0)
progress=0;
oldProgress = this.progress;
this.progress = progress;
// computes the damaged area
FontMetrics metrics = getGraphics().getFontMetrics(getFont());
int w = (int) (BAR_WIDTH * ((float) oldProgress / wholeProgress));
int x = w + (getWidth() - BAR_WIDTH) / 2;
int y = (getHeight() - BAR_HEIGHT) / 2;
y += metrics.getDescent() / 2;
w = (int) (BAR_WIDTH * ((float) progress / wholeProgress)) - w;
int h = BAR_HEIGHT;
repaint(x, y, w, h);
}
/**
* This is more flexible than setProgress allowing the progress bar to roll back
* @param progress a integer from 0 to 100 determine the current progress
*/
public void setValue(int progress) {
if(progress>wholeProgress)
progress=wholeProgress;
if(progress<0)
progress=0;
oldProgress = this.progress;
this.progress = progress;
// computes the damaged area
FontMetrics metrics = getGraphics().getFontMetrics(getFont());
int w = (int) (BAR_WIDTH);
int x = (getWidth() - BAR_WIDTH) / 2;
int y = (getHeight() - BAR_HEIGHT) / 2;
y += metrics.getDescent() / 2;
w = (int) (BAR_WIDTH) ;
int h = BAR_HEIGHT;
repaint(x, y, w, h);
}
@Override
protected void paintComponent(Graphics g) {
// enables anti-aliasing
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// gets the current clipping area
Rectangle clip = g.getClipBounds();
// sets a 65% translucent composite
AlphaComposite alpha = AlphaComposite.SrcOver.derive(this.alpha);
Composite composite = g2.getComposite();
g2.setComposite(alpha);
// fills the background
g2.setColor(getBackground());
g2.fillRect(clip.x, clip.y, clip.width, clip.height);
// centers the progress bar on screen
FontMetrics metrics = g.getFontMetrics();
int x = (getWidth() - BAR_WIDTH) / 2;
int y = (getHeight() - BAR_HEIGHT - metrics.getDescent()) / 2;
// draws the text
g2.setColor(TEXT_COLOR);
g2.drawString(message, x, y);
// goes to the position of the progress bar
y += metrics.getDescent();
// computes the size of the progress indicator
int w = (int) (BAR_WIDTH * ((float) progress / wholeProgress));
int h = BAR_HEIGHT;
// draws the content of the progress bar
Paint paint = g2.getPaint();
// bar's background
Paint gradient = new GradientPaint(x, y, GRADIENT_COLOR1,
x, y + h, GRADIENT_COLOR2);
g2.setPaint(gradient);
g2.fillRect(x, y, BAR_WIDTH, BAR_HEIGHT);
// actual progress
gradient = new LinearGradientPaint(x, y, x, y + h,
GRADIENT_FRACTIONS, GRADIENT_COLORS);
g2.setPaint(gradient);
g2.fillRect(x, y, w, h);
g2.setPaint(paint);
// draws the progress bar border
g2.drawRect(x, y, BAR_WIDTH, BAR_HEIGHT);
//draw the tip
drawStringMultiLine(g2,tips[random.nextInt(tips.length)], getWidth()/5*4,getWidth()/10, getHeight()/4*3);
g2.setComposite(composite);
}
/**
* A method to draw long text spliting automaticaly by giving the line width.
* Retrived from stackoverflow with sligntly modification so that '\n' is considered as a line splitter
* http://stackoverflow.com/questions/4413132/problems-with-newline-in-graphics2d-drawstring
* @author Ivan De Sousa Paz
* @param g
* @param text
* @param lineWidth
* @param x
* @param y
*/
protected void drawStringMultiLine(Graphics2D g, String wholeText, int lineWidth, int x, int y) {
FontMetrics m = g.getFontMetrics();
String[] breakedTexts = wholeText.split("\n");
for(String text : breakedTexts){
if(m.stringWidth(text) < lineWidth) {
g.drawString(text, x, y);
} else {
String[] words = text.split(" ");
String currentLine = words[0];
for(int i = 1; i < words.length; i++) {
if(m.stringWidth(currentLine+words[i]) < lineWidth) {
currentLine += " "+words[i];
} else {
g.drawString(currentLine, x, y);
y += m.getHeight();
currentLine = words[i];
}
}
if(currentLine.trim().length() > 0) {
g.drawString(currentLine, x, y);
}
}
y += m.getHeight();
}
}
}
| 9,535 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.