Implement screen-capture/reading bot. Identify scores/numbers and song

selected along with difficulty chosen for Project Diva Megamix.
secondmonitor
sigonasr2 4 years ago
commit feb8361c7a
  1. 6
      DivaBot/.classpath
  2. 17
      DivaBot/.project
  3. 2
      DivaBot/.settings/org.eclipse.core.resources.prefs
  4. 11
      DivaBot/.settings/org.eclipse.jdt.core.prefs
  5. 11
      DivaBot/bin/.gitignore
  6. 141
      DivaBot/colorData
  7. 1074
      DivaBot/src/MyRobot.java
  8. 75
      DivaBot/src/SongData.java
  9. 332
      DivaBot/src/TypeFace.java
  10. 219
      DivaBot/src/sig/utils/Audio.java
  11. 17
      DivaBot/src/sig/utils/DebugUtils.java
  12. 146
      DivaBot/src/sig/utils/DrawUtils.java
  13. 339
      DivaBot/src/sig/utils/FileUtils.java
  14. 35
      DivaBot/src/sig/utils/GithubUtils.java
  15. 45
      DivaBot/src/sig/utils/ImageUtils.java
  16. 48
      DivaBot/src/sig/utils/JavaUtils.java
  17. 37
      DivaBot/src/sig/utils/MemoryUtils.java
  18. 10
      DivaBot/src/sig/utils/ReflectUtils.java
  19. 30
      DivaBot/src/sig/utils/SoundUtils.java
  20. 137
      DivaBot/src/sig/utils/TextUtils.java
  21. 32
      DivaBot/src/sig/utils/TimeUtils.java
  22. BIN
      DivaBot/typeface1.png
  23. BIN
      DivaBot/typeface2.png

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="output" path="bin"/>
</classpath>

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>DivaBot</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

@ -0,0 +1,2 @@
eclipse.preferences.version=1
encoding//src/MyRobot.java=UTF-8

@ -0,0 +1,11 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.8

@ -0,0 +1,11 @@
/MyRobot$1.class
/MyRobot$2.class
/MyRobot$3.class
/MyRobot$4.class
/MyRobot$5.class
/MyRobot.class
/SongData.class
/TypeFace$ImgRectangle.class
/TypeFace$Pixel.class
/TypeFace.class
/sig/

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

@ -0,0 +1,75 @@
import java.awt.Color;
import sig.utils.FileUtils;
public class SongData {
String title;
Color[] songCode;
final static float TOLERANCE = 0.95f;
public SongData(String title,Color[] songCode) {
this.title=title;
this.songCode=songCode;
}
public static SongData getByTitle(String title) {
for (SongData s : MyRobot.SONGS) {
if (s.title.equalsIgnoreCase(title)) {
return s;
}
}
return null;
}
public static SongData compareData(Color[] data) {
for (SongData s : MyRobot.SONGS) {
int matched = 0;
for (int i=0;i<s.songCode.length;i++) {
if (data[i].equals(s.songCode[i])) {
matched++;
}
}
if (matched/(double)s.songCode.length>=TOLERANCE) {
System.out.println(matched+"/"+s.songCode.length+" pixels matched for song "+s.title);
return s;
} else {
//System.out.println(matched+"/"+s.songCode.length+" pixels matched for song "+s.title);
}
}
return null;
}
public static void saveSongToFile(String title, Color[] data) {
StringBuilder sb = new StringBuilder(title);
sb.append(":");
boolean first = true;
for (Color pixel : data) {
if (first) {
first=false;
} else {
sb.append(",");
}
sb.append(pixel.getRGB());
//Color c = new Color(9,true);
}
FileUtils.logToFile(sb.toString(),"colorData");
}
public static void loadSongsFromFile() {
String[] data = FileUtils.readFromFile("colorData");
MyRobot.SONGS = new SongData[data.length];
for (int i=0;i<data.length;i++) {
SongData sd = ParseSong(data[i]);
MyRobot.SONGS[i]=sd;
}
}
public static SongData ParseSong(String s) {
String[] split = s.split(":");
String title = split[0];
String[] data = split[1].split(",");
Color[] colors = new Color[data.length];
for (int i=0;i<data.length;i++) {
colors[i]=new Color(Integer.parseInt(data[i]),true);
}
return new SongData(title,colors);
}
}

@ -0,0 +1,332 @@
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import sig.utils.ImageUtils;
public class TypeFace {
final static int WIDTH = 32;
final static int HEIGHT = 32;
final static int NUMBER_COUNT = 10;
int blue_minthreshold = 75;
int green_minthreshold = 0;
int red_minthreshold = 0;
int blue_maxthreshold = 255;
int green_maxthreshold = 150;
int red_maxthreshold = 100;
boolean darkFillCheck = true;
Color[][] numbers = new Color[WIDTH*HEIGHT][NUMBER_COUNT];
BufferedImage baseImg;
public TypeFace(BufferedImage img) {
this.baseImg = img;
for (int k=0;k<NUMBER_COUNT;k++) {
for (int i=0;i<WIDTH;i++) {
for (int j=0;j<HEIGHT;j++) {
numbers[i*HEIGHT+j][k]=new Color(baseImg.getRGB(i+k*WIDTH, j),true);
}
}
}
}
public int extractNumbersFromImage(BufferedImage img) {
int midY = img.getHeight()/2;
int X = 0;
String extractedNumbers = "";
int state = 0;
BufferedImage numberImg = null;
final boolean DEBUG_IMG = false;
while (X<img.getWidth()) {
boolean success=true;
Color p = new Color(img.getRGB(X, midY),true);
switch (state) {
case 0:{
//Search for a dark pixel.
if (p.getBlue()>blue_minthreshold && p.getBlue()<blue_maxthreshold &&
p.getGreen()>green_minthreshold && p.getGreen()<green_maxthreshold &&
p.getRed()>red_minthreshold && p.getRed()<red_maxthreshold) {
//We found a dark pixel.
state=1;
if (darkFillCheck) {
success = fillDark(img,X,midY,0,0);
if (!success) {
//We're done.
X=img.getWidth();
break;
}
}
if (DEBUG_IMG) {
try {
BufferedImage img2 = ImageUtils.copyBufferedImage(img);
img2.setRGB(X, midY, Color.RED.getRGB());
ImageIO.write(img2,"png",new File("stage1_"+System.currentTimeMillis()+".png"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}break;
case 1:{
//Move right until light pixel.
if (p.getBlue()>200 && p.getGreen()>200 && p.getRed()>200) {
state=2;
if (DEBUG_IMG) {
try {
BufferedImage img2 = ImageUtils.copyBufferedImage(img);
img2.setRGB(X, midY, Color.RED.getRGB());
ImageIO.write(img2,"png",new File("stage2_"+System.currentTimeMillis()+".png"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}break;
case 2:{
//Fill algorithm until entire number is filled.
ImgRectangle i = new ImgRectangle();
success = fill(img,X,midY,0,0,i);
if (!success) {
//We're done.
X=img.getWidth();
break;
} else {
X+=i.maxX-1;
numberImg = i.createImage();
//X+=numberImg.getWidth();
state=3;
if (DEBUG_IMG) {
try {
BufferedImage img2 = ImageUtils.copyBufferedImage(img);
img2.setRGB(X, midY, Color.RED.getRGB());
ImageIO.write(img2,"png",new File("stage3_"+System.currentTimeMillis()+".png"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}break;
case 3:{
//Figure out which number in the typeface it best represents.
if (numberImg.getHeight()>numberImg.getWidth()) {
numberImg = ImageUtils.toBufferedImage(numberImg.getScaledInstance(-1, HEIGHT, Image.SCALE_FAST));
} else {
numberImg = ImageUtils.toBufferedImage(numberImg.getScaledInstance(WIDTH, -1, Image.SCALE_FAST));
}
try {
ImageIO.write(numberImg,"png",new File("number_"+System.currentTimeMillis()+".png"));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(numberImg.getWidth()+"x"+numberImg.getHeight());
int[] hits = new int[NUMBER_COUNT];
double highestRatio = 0;
int highest = 0;
for (int k=0;k<NUMBER_COUNT;k++) {
for (int i=0;i<WIDTH;i++) {
for (int j=0;j<HEIGHT;j++) {
if (i<numberImg.getWidth() &&
j<numberImg.getHeight()) {
Color pixel = new Color(numberImg.getRGB(i, j));
if (numbers[i*HEIGHT+j][k].getRed()==pixel.getRed() && numbers[i*HEIGHT+j][k].getRed()==pixel.getGreen() && numbers[i*HEIGHT+j][k].getBlue()==pixel.getBlue()) {
hits[k]++;
//System.out.println("Hit for "+((k+1)%NUMBER_COUNT)+"! "+hits[k] + "/"+numbers[i*HEIGHT+j][k]+"/"+pixel);
if ((double)hits[k]/(WIDTH*HEIGHT)>highestRatio) {
highestRatio = (double)(hits[k])/(WIDTH*HEIGHT);
highest=k;
}
}
}
}
}
}
System.out.println("Matches closest to "+((highest+1)%NUMBER_COUNT)+" with "+highestRatio);
extractedNumbers+=Integer.toString((highest+1)%NUMBER_COUNT);
state=4;
}break;
case 4:{
//Find dark pixels again.
if (p.getBlue()>blue_minthreshold && p.getBlue()<blue_maxthreshold &&
p.getGreen()>green_minthreshold && p.getGreen()<green_maxthreshold &&
p.getRed()>red_minthreshold && p.getRed()<red_maxthreshold) {
//We found a dark pixel. Back to the start.
state=0;
if (DEBUG_IMG) {
try {
BufferedImage img2 = ImageUtils.copyBufferedImage(img);
img2.setRGB(X, midY, Color.RED.getRGB());
ImageIO.write(img2,"png",new File("stage4_"+System.currentTimeMillis()+".png"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}break;
}
X++;
}
System.out.println("Got "+extractedNumbers);
if (extractedNumbers.length()==0) {
return -1;
} else {
return Integer.parseInt(extractedNumbers);
}
}
public boolean fillDark(BufferedImage img,int startX,int startY,int x,int y) {
//rect.AddPixel(new Point(x,y), Color.BLACK);
img.setRGB(startX+x, startY+y, Color.BLACK.getRGB());
Color p = null;
if (startX+x+1<img.getWidth()) {
p = new Color(img.getRGB(startX+x+1, startY+y));
if (p.getBlue()>blue_minthreshold && p.getBlue()<blue_maxthreshold &&
p.getGreen()>green_minthreshold && p.getGreen()<green_maxthreshold &&
p.getRed()>red_minthreshold && p.getRed()<red_maxthreshold) {
fillDark(img,startX,startY,x+1,y);
}
} else {
return false;
}
if (startX+x-1>0) {
p = new Color(img.getRGB(startX+x-1, startY+y));
if (p.getBlue()>blue_minthreshold && p.getBlue()<blue_maxthreshold &&
p.getGreen()>green_minthreshold && p.getGreen()<green_maxthreshold &&
p.getRed()>red_minthreshold && p.getRed()<red_maxthreshold) {
fillDark(img,startX,startY,x-1,y);
}
} else {
return false;
}
if (startY+y+1<img.getHeight()) {
p = new Color(img.getRGB(startX+x, startY+y+1));
if (p.getBlue()>blue_minthreshold && p.getBlue()<blue_maxthreshold &&
p.getGreen()>green_minthreshold && p.getGreen()<green_maxthreshold &&
p.getRed()>red_minthreshold && p.getRed()<red_maxthreshold) {
fillDark(img,startX,startY,x,y+1);
}
} else {
return false;
}
if (startY+y-1>0) {
p = new Color(img.getRGB(startX+x, startY+y-1));
if (p.getBlue()>blue_minthreshold && p.getBlue()<blue_maxthreshold &&
p.getGreen()>green_minthreshold && p.getGreen()<green_maxthreshold &&
p.getRed()>red_minthreshold && p.getRed()<red_maxthreshold) {
fillDark(img,startX,startY,x,y-1);
}
} else {
return false;
}
return true;
}
public boolean fill(BufferedImage img,int startX,int startY,int x,int y,ImgRectangle rect) {
rect.AddPixel(new Point(x,y), Color.BLACK);
img.setRGB(startX+x, startY+y, Color.BLACK.getRGB());
Color p = null;
if (startX+x+1<img.getWidth()) {
p = new Color(img.getRGB(startX+x+1, startY+y));
if (p.getBlue()>200 && p.getGreen()>200 && p.getRed()>200) {
fill(img,startX,startY,x+1,y,rect);
}
} else {
return false;
}
if (startX+x-1>0) {
p = new Color(img.getRGB(startX+x-1, startY+y));
if (p.getBlue()>200 && p.getGreen()>200 && p.getRed()>200) {
fill(img,startX,startY,x-1,y,rect);
}
} else {
return false;
}
if (startY+y+1<img.getHeight()) {
p = new Color(img.getRGB(startX+x, startY+y+1));
if (p.getBlue()>200 && p.getGreen()>200 && p.getRed()>200) {
fill(img,startX,startY,x,y+1,rect);
}
} else {
return false;
}
if (startY+y-1>0) {
p = new Color(img.getRGB(startX+x, startY+y-1));
if (p.getBlue()>200 && p.getGreen()>200 && p.getRed()>200) {
fill(img,startX,startY,x,y-1,rect);
}
} else {
return false;
}
return true;
}
class ImgRectangle{
int minX=0,maxX=0,minY=0,maxY=0;
List<Pixel> p = new ArrayList<Pixel>();
void AddPixel(Point p, Color c) {
this.p.add(new Pixel(p,c));
if (p.x<minX) {
minX=p.x;
}
if (p.x>maxX) {
maxX=p.x;
}
if (p.y<minY) {
minY=p.y;
}
if (p.y>maxY) {
maxY=p.y;
}
}
BufferedImage createImage() {
int finalWidth = maxX-minX+1;
int offsetX = 0;
int finalHeight = maxY-minY+1;
int offsetY = 0;
if (finalWidth > finalHeight) {
//Add padding for height.
offsetY += (finalWidth-finalHeight)/2;
finalHeight+= offsetY*2;
}
if (finalHeight > finalWidth) {
//Add padding for width.
offsetX += (finalHeight-finalWidth)/2;
finalWidth+= offsetX*2;
}
BufferedImage bufferedImage = new BufferedImage(finalWidth, finalHeight,
BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = bufferedImage.createGraphics();
graphics.setPaint ( new Color ( 255, 255, 255 ) );
graphics.fillRect ( 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight() );
for (Pixel pixel : p) {
bufferedImage.setRGB(pixel.p.x-minX+offsetX, pixel.p.y-minY+offsetY, pixel.c.getRGB());
}
return bufferedImage;
}
}
class Pixel{
Point p;
Color c;
Pixel(Point p,Color c) {
this.p=p;
this.c=c;
}
}
}

@ -0,0 +1,219 @@
package sig.utils;
import java.util.ArrayList;
import java.util.List;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.BooleanControl;
import javax.sound.sampled.CompoundControl;
import javax.sound.sampled.Control;
import javax.sound.sampled.Control.Type;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.Mixer.Info;
public class Audio {
public static void main(String[] args) throws Exception {
System.out.println(getHierarchyInfo());
System.out.println(getMasterOutputVolume());
}
public static void setMasterOutputVolume(float value) {
if (value < 0 || value > 1)
throw new IllegalArgumentException(
"Volume can only be set to a value from 0 to 1. Given value is illegal: " + value);
Line line = getMasterOutputLine();
if (line == null) throw new RuntimeException("Master output port not found");
boolean opened = open(line);
try {
FloatControl control = getVolumeControl(line);
if (control == null)
throw new RuntimeException("Volume control not found in master port: " + toString(line));
control.setValue(value);
} finally {
if (opened) line.close();
}
}
public static Float getMasterOutputVolume() {
Line line = getMasterOutputLine();
if (line == null) return null;
boolean opened = open(line);
try {
FloatControl control = getVolumeControl(line);
if (control == null) return null;
return control.getValue();
} finally {
if (opened) line.close();
}
}
public static void setMasterOutputMute(boolean value) {
Line line = getMasterOutputLine();
if (line == null) throw new RuntimeException("Master output port not found");
boolean opened = open(line);
try {
BooleanControl control = getMuteControl(line);
if (control == null)
throw new RuntimeException("Mute control not found in master port: " + toString(line));
control.setValue(value);
} finally {
if (opened) line.close();
}
}
public static Boolean getMasterOutputMute() {
Line line = getMasterOutputLine();
if (line == null) return null;
boolean opened = open(line);
try {
BooleanControl control = getMuteControl(line);
if (control == null) return null;
return control.getValue();
} finally {
if (opened) line.close();
}
}
public static Line getMasterOutputLine() {
for (Mixer mixer : getMixers()) {
for (Line line : getAvailableOutputLines(mixer)) {
if (line.getLineInfo().toString().contains("Master")) return line;
}
}
return null;
}
public static FloatControl getVolumeControl(Line line) {
if (!line.isOpen()) throw new RuntimeException("Line is closed: " + toString(line));
return (FloatControl) findControl(FloatControl.Type.VOLUME, line.getControls());
}
public static BooleanControl getMuteControl(Line line) {
if (!line.isOpen()) throw new RuntimeException("Line is closed: " + toString(line));
return (BooleanControl) findControl(BooleanControl.Type.MUTE, line.getControls());
}
private static Control findControl(Type type, Control... controls) {
if (controls == null || controls.length == 0) return null;
for (Control control : controls) {
if (control.getType().equals(type)) return control;
if (control instanceof CompoundControl) {
CompoundControl compoundControl = (CompoundControl) control;
Control member = findControl(type, compoundControl.getMemberControls());
if (member != null) return member;
}
}
return null;
}
public static List<Mixer> getMixers() {
Info[] infos = AudioSystem.getMixerInfo();
List<Mixer> mixers = new ArrayList<Mixer>(infos.length);
for (Info info : infos) {
Mixer mixer = AudioSystem.getMixer(info);
mixers.add(mixer);
}
return mixers;
}
public static List<Line> getAvailableOutputLines(Mixer mixer) {
return getAvailableLines(mixer, mixer.getTargetLineInfo());
}
public static List<Line> getAvailableInputLines(Mixer mixer) {
return getAvailableLines(mixer, mixer.getSourceLineInfo());
}
private static List<Line> getAvailableLines(Mixer mixer, Line.Info[] lineInfos) {
List<Line> lines = new ArrayList<Line>(lineInfos.length);
for (Line.Info lineInfo : lineInfos) {
Line line;
line = getLineIfAvailable(mixer, lineInfo);
if (line != null) lines.add(line);
}
return lines;
}
public static Line getLineIfAvailable(Mixer mixer, Line.Info lineInfo) {
try {
return mixer.getLine(lineInfo);
} catch (LineUnavailableException ex) {
return null;
}
}
public static String getHierarchyInfo() {
StringBuilder sb = new StringBuilder();
for (Mixer mixer : getMixers()) {
sb.append("Mixer: ").append(toString(mixer)).append("\n");
for (Line line : getAvailableOutputLines(mixer)) {
sb.append(" OUT: ").append(toString(line)).append("\n");
boolean opened = open(line);
for (Control control : line.getControls()) {
sb.append(" Control: ").append(toString(control)).append("\n");
if (control instanceof CompoundControl) {
CompoundControl compoundControl = (CompoundControl) control;
for (Control subControl : compoundControl.getMemberControls()) {
sb.append(" Sub-Control: ").append(toString(subControl)).append("\n");
}
}
}
if (opened) line.close();
}
for (Line line : getAvailableOutputLines(mixer)) {
sb.append(" IN: ").append(toString(line)).append("\n");
boolean opened = open(line);
for (Control control : line.getControls()) {
sb.append(" Control: ").append(toString(control)).append("\n");
if (control instanceof CompoundControl) {
CompoundControl compoundControl = (CompoundControl) control;
for (Control subControl : compoundControl.getMemberControls()) {
sb.append(" Sub-Control: ").append(toString(subControl)).append("\n");
}
}
}
if (opened) line.close();
}
sb.append("\n");
}
return sb.toString();
}
public static boolean open(Line line) {
if (line.isOpen()) return false;
try {
line.open();
} catch (LineUnavailableException ex) {
return false;
}
return true;
}
public static String toString(Control control) {
if (control == null) return null;
return control.toString() + " (" + control.getType().toString() + ")";
}
public static String toString(Line line) {
if (line == null) return null;
Line.Info info = line.getLineInfo();
return info.toString();// + " (" + line.getClass().getSimpleName() + ")";
}
public static String toString(Mixer mixer) {
if (mixer == null) return null;
StringBuilder sb = new StringBuilder();
Info info = mixer.getMixerInfo();
sb.append(info.getName());
sb.append(" (").append(info.getDescription()).append(")");
sb.append(mixer.isOpen() ? " [open]" : " [closed]");
return sb.toString();
}
}

@ -0,0 +1,17 @@
package sig.utils;
public class DebugUtils {
public static void showStackTrace() {
System.out.println("Trace:"+getStackTrace());
}
public static String getStackTrace() {
StackTraceElement[] stacktrace = new Throwable().getStackTrace();
StringBuilder stack = new StringBuilder("Mini stack tracer:");
for (int i=0;i<Math.min(10, stacktrace.length);i++) {
stack.append("\n"+stacktrace[i].getClassName()+": **"+stacktrace[i].getFileName()+"** "+stacktrace[i].getMethodName()+"():"+stacktrace[i].getLineNumber());
}
return stack.toString();
}
}

@ -0,0 +1,146 @@
package sig.utils;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.font.TextAttribute;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.text.AttributedString;
import sig.MyPanel;
public class DrawUtils {
public static void drawOutlineText(Graphics g, Font font, double x, double y, int outline_size, Color text_color, Color shadow_color, String message) {
drawOutlineText(g,font,x,y,0,0,1,outline_size,text_color,shadow_color,message);
}
public static void drawOutlineText(Graphics g, Font font, double x, double y, int font_thickness, int outline_thickness, Color text_color, Color shadow_color, String message) {
drawOutlineText(g,font,x,y,0,0,font_thickness,outline_thickness,text_color,shadow_color,message);
}
static void drawOutlineText(Graphics g, Font font, double x, double y, double xoffset, double yoffset, int font_thickness, int outline_thickness, Color text_color, Color shadow_color, String message) {
if (message.length()>0) {
AttributedString as = new AttributedString(message);
as.addAttribute(TextAttribute.FONT, font);
as.addAttribute(TextAttribute.KERNING,TextAttribute.KERNING_ON);
as.addAttribute(TextAttribute.WIDTH,TextAttribute.WIDTH_EXTENDED);
as.addAttribute(TextAttribute.TRACKING,0.5);
g.setColor(shadow_color);
Graphics2D g2 = (Graphics2D) g;
FontRenderContext frc = g2.getFontMetrics(font).getFontRenderContext();
GlyphVector gv = font.createGlyphVector(frc, message);
Shape shape = gv.getOutline((int)(x+xoffset),(int)(y+yoffset));
g2.setClip(null);
g2.setStroke(new BasicStroke(font_thickness + outline_thickness*2));
g2.setColor(shadow_color);
g2.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.draw(shape);
GlyphVector gv2 = font.createGlyphVector(frc, message);
Shape shape2 = gv2.getOutline((int)(x+xoffset),(int)(y+yoffset));
g2.setClip(null);
g2.setStroke(new BasicStroke(font_thickness));
g2.setColor(text_color);
g2.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.draw(shape2);
g2.setColor(text_color);
g2.drawString(as.getIterator(),(int)(x+xoffset),(int)(y+yoffset));
}
}
public static void drawCenteredOutlineText(Graphics g, Font font, double x, double y, int font_size, int outline_size, Color text_color, Color shadow_color, String message) {
Rectangle2D textBounds = TextUtils.calculateStringBoundsFont(message, font);
drawOutlineText(g,font,x,y,-textBounds.getWidth()/2,-textBounds.getHeight()/2,font_size,outline_size,text_color,shadow_color,message);
}
public static void drawCenteredOutlineText(Graphics g, Font font, double x, double y, int outline_size, Color text_color, Color shadow_color, String message) {
drawCenteredOutlineText(g,font,x,y,1,outline_size,text_color,shadow_color,message);
}
public static void drawText(Graphics g, double x, double y, Color color, String message) {
if (message.length()>0) {
AttributedString as = new AttributedString(message);
as.addAttribute(TextAttribute.FONT, MyPanel.programFont);
g.setColor(color);
g.drawString(as.getIterator(),(int)x,(int)y);
}
}
public static void drawTextFont(Graphics g, Font font, double x, double y, Color color, String message) {
if (message.length()>0) {
AttributedString as = new AttributedString(message);
as.addAttribute(TextAttribute.FONT, font);
g.setColor(color);
g.drawString(as.getIterator(),(int)x,(int)y);
}
}
public static void drawHealthbar(Graphics g, Rectangle bounds, double pct, Color healthbarcol) {
g.setColor(Color.BLACK);
g.draw3DRect((int)bounds.getX(), (int)bounds.getY(), (int)bounds.getWidth(), (int)bounds.getHeight(), true);
g.setColor(healthbarcol);
g.fill3DRect((int)bounds.getX()+1, (int)bounds.getY()+1, (int)(bounds.getWidth()*pct)-1, (int)bounds.getHeight()-1, true);
}
/**
* Centers the text along the X Axis.
*/
public static void drawCenteredText(Graphics g, Font font, int x, int y, Color color, String text) {
AttributedString as = new AttributedString(text);
as.addAttribute(TextAttribute.FONT, font);
g.setColor(color);
Rectangle2D textBounds = TextUtils.calculateStringBoundsFont(text, font);
g.drawString(as.getIterator(),(int)(x-textBounds.getWidth()/2),(int)(y+textBounds.getHeight()));
}
public static Color convertStringToColor(String s) {
String[] split = s.split(",");
if (split.length==3) {
return new Color(
Math.min(Math.abs(Integer.parseInt(split[0])),255),
Math.min(Math.abs(Integer.parseInt(split[1])),255),
Math.min(Math.abs(Integer.parseInt(split[2])),255));
} else
if (split.length==4) {
return new Color(
Math.min(Math.abs(Integer.parseInt(split[0])),255),
Math.min(Math.abs(Integer.parseInt(split[1])),255),
Math.min(Math.abs(Integer.parseInt(split[2])),255),
Math.min(Math.abs(Integer.parseInt(split[3])),255));
} else {
System.out.println("WARNING! Invalid Color string specified ("+s+").");
return null;
}
}
public static void drawImage(Graphics g, Image img, double x, double y, Color blend_col, ImageObserver source) {
BufferedImage tmp = new BufferedImage(img.getWidth(source),img.getHeight(source),BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = tmp.createGraphics();
g2.drawImage(img, 0, 0, null);
g2.setComposite(AlphaComposite.SrcAtop);
g2.setColor(blend_col);
g2.fillRect(0, 0, img.getWidth(source), img.getHeight(source));
g2.dispose();
g.drawImage(tmp,(int)x,(int)y,source);
}
public static void drawImageScaled(Graphics g, Image img, double x, double y, double xsize, double ysize, Color blend_col, ImageObserver source) {
BufferedImage tmp = new BufferedImage(img.getWidth(source),img.getHeight(source),BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = tmp.createGraphics();
g2.drawImage(img, 0, 0, null);
g2.setComposite(AlphaComposite.SrcAtop);
g2.setColor(blend_col);
g2.fillRect(0, 0, img.getWidth(source), img.getHeight(source));
g2.dispose();
g.drawImage(tmp,(int)x,(int)y,(int)xsize,(int)ysize,source);
}
public static Color invertColor(Color c) {
return new Color(255-c.getRed(),255-c.getGreen(),255-c.getBlue(),255);
}
}

@ -0,0 +1,339 @@
package sig.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import sig.sigIRC;
import sig.modules.RabiRaceModule;
import sig.modules.ChatLog.ChatLogMessage;
public class FileUtils {
public static String[] readFromFile(String filename) {
File file = new File(filename);
//System.out.println(file.getAbsolutePath());
List<String> contents= new ArrayList<String>();
if (file.exists()) {
try(
FileReader fw = new FileReader(filename);
BufferedReader bw = new BufferedReader(fw);)
{
String readline = bw.readLine();
do {
if (readline!=null) {
//System.out.println(readline);
contents.add(readline);
readline = bw.readLine();
}} while (readline!=null);
fw.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return contents.toArray(new String[contents.size()]);
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
private static String readFilter(Reader rd, HashMap<Long,String> channel_ids) throws IOException {
StringBuilder sb = new StringBuilder();
boolean allowed=false;
boolean quotation_mark=false;
boolean endquotation_mark=false;
boolean foundChannel=false;
boolean nextBrace=false;
boolean outputStuff=false;
String numb = "";
int braceCount=0;
int channelCount=0;
int vals=0;
int cp;
while ((cp = rd.read()) != -1) {
if (braceCount==0) {
allowed=true;
} else
if (braceCount==1 && !quotation_mark){
quotation_mark=true;
numb="";
allowed=false;
} else
if (!endquotation_mark) {
if ((char)cp >= '0' &&
(char)cp <= '9') {
allowed=false;
numb+=(char)cp;
} else {
allowed=false;
endquotation_mark=true;
try {
if (channel_ids.containsKey(Long.parseLong(numb))) {
if (channelCount>=1) {
sb.append(",");
}
sb.append("\""+numb+"\"");
foundChannel=true;
System.out.println("Found channel "+numb);
outputStuff=true;
}
} catch (NumberFormatException e) {
}
}
} else
if (!nextBrace && foundChannel) {
allowed=true;
if ((char)cp == '{') {
nextBrace=true;
}
} else
if (foundChannel) {
allowed=true;
if (braceCount==1) {
allowed=false;
channelCount++;
quotation_mark=false;
endquotation_mark=false;
foundChannel=false;
nextBrace=false;
}
} else {
allowed=false;
if (braceCount==1) {
allowed=false;
quotation_mark=false;
endquotation_mark=false;
foundChannel=false;
nextBrace=false;
}
}
/*if (outputStuff && vals++<1000) {
System.out.print((char)cp);
}*/
if ((char)cp == '{') {
braceCount++;
//System.out.println("Brace count is "+braceCount+".");
} else
if ((char)cp == '}') {
braceCount--;
//System.out.println("Brace count is "+braceCount+".");
}
if (allowed) {
sb.append((char) cp);
}
}
sb.append("}");
//System.out.println("=============");
//System.out.println(sb.toString());
return sb.toString();
}
public static JSONObject readJsonFromUrlWithFilter(String url, HashMap<Long,String> filter) throws IOException, JSONException {
return readJsonFromUrlWithFilter(url,filter,null,false);
}
public static JSONObject readJsonFromFileWithFilter(String file, HashMap<Long,String> filter) throws IOException, JSONException {
InputStream is = new FileInputStream(new File(file));
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readFilter(rd,filter);
JSONObject json = new JSONObject(jsonText);
jsonText=null;
return json;
} finally {
is.close();
}
}
public static JSONObject readJsonFromUrlWithFilter(String url, HashMap<Long,String> filter, String file, boolean writeToFile) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readFilter(rd,filter);
if (writeToFile) {
writetoFile(new String[]{jsonText},file);
}
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
return readJsonFromUrl(url,null,false);
}
public static JSONArray readJsonArrayFromUrl(String url) throws IOException, JSONException {
return readJsonArrayFromUrl(url,null,false);
}
public static JSONObject readJsonFromFile(String file) throws IOException, JSONException {
InputStream is = new FileInputStream(new File(file));
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
jsonText=null;
return json;
} finally {
is.close();
}
}
public static JSONObject readJsonFromUrl(String url, String file, boolean writeToFile) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
if (writeToFile) {
writetoFile(new String[]{jsonText},file);
}
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static JSONArray readJsonArrayFromUrl(String url, String file, boolean writeToFile) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
if (writeToFile) {
writetoFile(new String[]{jsonText},file);
}
JSONArray json = new JSONArray(jsonText);
return json;
} finally {
is.close();
}
}
public static void logToFile(String message, String filename) {
logToFile(message,filename,false);
}
public static void logToFile(String message, String filename, boolean outputToChatLog) {
File file = new File(filename);
try {
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file, true);
PrintWriter pw = new PrintWriter(fw);
pw.println(message);
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void writetoFile(String[] data, String filename) {
File file = new File(filename);
try {
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file,false);
PrintWriter pw = new PrintWriter(fw);
for (String s : data) {
pw.println(s);
}
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void copyFile(File source, File dest) throws IOException {
FileChannel sourceChannel = null;
FileChannel destChannel = null;
try {
sourceChannel = new FileInputStream(source).getChannel();
destChannel = new FileOutputStream(dest).getChannel();
destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
}finally{
sourceChannel.close();
destChannel.close();
}
}
public static void deleteFile(String filename) {
File file = new File(filename);
if (file.exists()) {
file.delete();
}
}
public static void downloadFileFromUrl(String url, String file,boolean bearer) throws IOException, JSONException {
File filer = new File(file);
filer.createNewFile();
URL website = new URL(url);
HttpURLConnection connection = (HttpURLConnection) website.openConnection();
/*for (String s : connection.getHeaderFields().keySet()) {
System.out.println(s+": "+connection.getHeaderFields().get(s));
}*/
connection.setRequestMethod("GET");
//connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/vnd.twitchtv.v5+json");
connection.setRequestProperty("Authorization", ((bearer)?"Bearer":"OAuth") + " "+sigIRC.oauth.replace("oauth:", ""));
if (sigIRC.CLIENTID.length()!=0) {
connection.setRequestProperty("Client-ID", sigIRC.CLIENTID);
//System.out.println("Using "+ sigIRC.oauth+"/"+sigIRC.CLIENTID);
}
try {
ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream());
FileOutputStream fos = new FileOutputStream(file);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
} catch (ConnectException e) {
System.out.println("Failed to connect, moving on...");
}
}
public static void downloadFileFromUrl(String url, String file) throws IOException, JSONException {
downloadFileFromUrl(url,file,false); //Uses OAUTH instead of Bearer
}
}

@ -0,0 +1,35 @@
package sig.utils;
import java.io.IOException;
import java.util.Arrays;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class GithubUtils {
public static int getSizeOfFileFromLatestGithubCommit(String filename) {
try {
JSONObject data = FileUtils.readJsonFromUrl("https://api.github.com/repos/sigonasr2/sigIRCv2");
String url = data.getString("commits_url").replace("{/sha}", "");
JSONArray data_array = FileUtils.readJsonArrayFromUrl(url);
JSONObject dat = data_array.getJSONObject(0);
JSONObject datapoint1 = dat.getJSONObject("commit");
datapoint1 = datapoint1.getJSONObject("tree");
url = datapoint1.getString("url");
data = FileUtils.readJsonFromUrl(url);
data_array = data.getJSONArray("tree");
for (int i=0;i<data_array.length();i++) {
JSONObject file_data = data_array.getJSONObject(i);
if (file_data.getString("path").equals(filename)) {
return file_data.getInt("size");
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return -1;
}
}

@ -0,0 +1,45 @@
package sig.utils;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
public class ImageUtils {
/**
* Converts a given Image into a BufferedImage
*
* @param img The Image to be converted
* @return The converted BufferedImage
*/
public static BufferedImage toBufferedImage(Image img)
{
if (img instanceof BufferedImage)
{
return (BufferedImage) img;
}
// Create a buffered image with transparency
BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
// Draw the image on to the buffered image
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();
// Return the buffered image
return bimage;
}
public static BufferedImage copyBufferedImage(BufferedImage img)
{
// Create a buffered image with transparency
BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
// Draw the image on to the buffered image
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();
// Return the buffered image
return bimage;
}
}

@ -0,0 +1,48 @@
package sig.utils;
import java.lang.reflect.Field;
public class JavaUtils {
public JavaUtils clone() {
JavaUtils newpos = new JavaUtils();
for (Field f : this.getClass().getDeclaredFields()) {
if (ReflectUtils.isCloneable(f)) {
try {
f.set(newpos, f.get(this));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return newpos;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.getClass().getName()+"(");
boolean first=false;
for (Field f : this.getClass().getDeclaredFields()) {
if (!first) {
try {
sb.append(f.getName()+"="+f.get(this));
first=true;
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
try {
sb.append(","+f.getName()+"="+f.get(this));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
sb.append(")");
return sb.toString();
}
}

@ -0,0 +1,37 @@
package sig.utils;
import com.sun.jna.Native;
import com.sun.jna.platform.win32.Advapi32;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.WinNT;
import com.sun.jna.platform.win32.WinDef.DWORD;
import com.sun.jna.platform.win32.WinNT.HANDLEByReference;
public class MemoryUtils {
/**
* Enables debug privileges for this process, required for OpenProcess() to
* get processes other than the current user
*/
public static void enableDebugPrivilege() {
HANDLEByReference hToken = new HANDLEByReference();
boolean success = Advapi32.INSTANCE.OpenProcessToken(Kernel32.INSTANCE.GetCurrentProcess(),
WinNT.TOKEN_QUERY | WinNT.TOKEN_ADJUST_PRIVILEGES, hToken);
if (!success) {
System.out.println("OpenProcessToken failed. Error: {}" + Native.getLastError());
return;
}
WinNT.LUID luid = new WinNT.LUID();
success = Advapi32.INSTANCE.LookupPrivilegeValue(null, WinNT.SE_DEBUG_NAME, luid);
if (!success) {
System.out.println("LookupprivilegeValue failed. Error: {}" + Native.getLastError());
return;
}
WinNT.TOKEN_PRIVILEGES tkp = new WinNT.TOKEN_PRIVILEGES(1);
tkp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(luid, new DWORD(WinNT.SE_PRIVILEGE_ENABLED));
success = Advapi32.INSTANCE.AdjustTokenPrivileges(hToken.getValue(), false, tkp, 0, null, null);
if (!success) {
System.out.println("AdjustTokenPrivileges failed. Error: {}" + Native.getLastError());
}
Kernel32.INSTANCE.CloseHandle(hToken.getValue());
}
}

@ -0,0 +1,10 @@
package sig.utils;
import java.lang.reflect.Field;
public class ReflectUtils {
public static boolean isCloneable(Field f) {
int mods = f.getModifiers();
return mods<8;
}
}

@ -0,0 +1,30 @@
package sig.utils;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class SoundUtils {
public static void playSound(String filename) {
AudioInputStream audioInputStream;
try {
audioInputStream = AudioSystem.getAudioInputStream(new File(filename).getAbsoluteFile());
Clip clip;
try {
clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

@ -0,0 +1,137 @@
package sig.utils;
import java.awt.Color;
import java.awt.Font;
import java.awt.Point;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
import sig.sigIRC;
public class TextUtils {
public static Rectangle2D calculateStringBoundsFont(String msg, Font font) {
FontRenderContext frc = sigIRC.panel.getFontMetrics(font).getFontRenderContext();
return font.getStringBounds(msg, frc);
}
public static String replaceFirst(String sourcestring, String findstring, String replacestring) {
int pos = sourcestring.indexOf(findstring);
if (pos>=0) {
String piece1 = sourcestring.substring(0,pos);
String piece2 = sourcestring.substring(pos+findstring.length(),sourcestring.length());
//basemsg = basemsg.replaceFirst(e.getEmoteName(),e.getSpaceFiller());
sourcestring = piece1+replacestring+piece2;
}
return sourcestring;
}
public static boolean isAlphanumeric(String str) {
return str.matches("^[a-zA-Z0-9!\\-.?'\":,\\+ ]+$");
}
public static boolean isNumeric(String str)
{
if (str.length()>0) {
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
} else {
return false;
}
}
public static boolean isInteger(String s, int radix) {
if(s.isEmpty()) return false;
for(int i = 0; i < s.length(); i++) {
if(i == 0 && s.charAt(i) == '-') {
if(s.length() == 1) return false;
else continue;
}
if(Character.digit(s.charAt(i),radix) < 0) return false;
}
return true;
}
public static String convertSecondsToTimeFormat(int seconds) {
StringBuilder sb = new StringBuilder();
int sec = seconds%60;
int min = (seconds/60)%60;
int hrs = (seconds/3600)%24;
if (hrs>0) {
if (hrs>=10) {
sb.append(hrs);
} else {
sb.append(0);
sb.append(hrs);
}
sb.append(":");
}
if (min>=10) {
sb.append(min);
} else {
sb.append(0);
sb.append(min);
}
sb.append(":");
if (sec>=10) {
sb.append(sec);
} else {
sb.append(0);
sb.append(sec);
}
return sb.toString();
}
public static String getActualChannelName() {
return sigIRC.channel.replaceFirst("#", "");
}
/**
* Converts a three CSV value to RGB value.
*/
public static Color convertStringToColor(String col) {
String[] split = col.split(",");
return new Color(Integer.parseInt(split[0]),Integer.parseInt(split[1]),Integer.parseInt(split[2]));
}
public static List<String> WrapText(String msg, Font font, double width) {
List<String> displayMessage = new ArrayList<String>();
String rawmessage = msg;
int textWidth = (int)TextUtils.calculateStringBoundsFont(rawmessage, font).getWidth();
int maxWidth = (int)width;
do {
rawmessage = BreakTextAtNextSection(rawmessage+" ",font,displayMessage,maxWidth);
textWidth = (int)TextUtils.calculateStringBoundsFont(rawmessage, font).getWidth();
} while (textWidth>maxWidth);
if (rawmessage.length()>0) {
displayMessage.add(rawmessage);
}
return displayMessage;
//System.out.println(displayMessage+": "+messageDisplaySize);
}
private static String BreakTextAtNextSection(String msg, Font font, List<String> list, int maxWidth) {
int marker = 1;
int textWidth = (int)TextUtils.calculateStringBoundsFont(msg.substring(0, marker), font).getWidth();
while (textWidth<maxWidth) {
if (marker<msg.length()) {
int tempmarker = msg.indexOf(' ', marker);
if (tempmarker!=-1) {
textWidth = (int)TextUtils.calculateStringBoundsFont(msg.substring(0, tempmarker), font).getWidth();
if (textWidth<maxWidth) {
marker = tempmarker+1;
}
//System.out.println(msg.substring(0, marker)+" | "+textWidth);
} else {
marker=msg.length();
break;
}
} else {
break;
}
}
String currentText = msg.substring(0, marker);
list.add(currentText);
return msg.substring(marker, msg.length());
}
}

@ -0,0 +1,32 @@
package sig.utils;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
public class TimeUtils {
public static String GetTimeDifferenceFromCurrentDate(Date pastDate) {
long totalseconds = (Calendar.getInstance().getTimeInMillis()-pastDate.getTime())/1000;
//System.out.println("Total Seconds: "+totalseconds);
long seconds = (long)(totalseconds);
long minutes = (long)(seconds/60);
long hours = (long)(minutes/60);
long days = (long)(hours/24);
StringBuilder string = new StringBuilder();
DecimalFormat df = new DecimalFormat("00");
if (days>0) {
string.append(days);
}
if (hours>0) {
string.append(((string.length()>0)?":":"")+(hours%24));
}
if (minutes>0) {
string.append(((string.length()>0)?":":"")+df.format((minutes%60)));
}
if (seconds>0) {
string.append(((string.length()>0)?":":"")+df.format((seconds%60)));
}
return string.toString();
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Loading…
Cancel
Save