Started rewriting math screen and conversion logics

This commit is contained in:
XDrake99 2017-04-10 22:50:43 +02:00
parent b89883147b
commit c2df21d682
91 changed files with 1219 additions and 1015 deletions

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<classpath> <classpath>
<classpathentry excluding="org/warp/picalculator/deprecatedmath/|org/warp/picalculator/device/PIDisplay.java|org/warp/picalculator/device/graphicengine/Display.java" kind="src" path="src"/> <classpathentry excluding="org/warp/picalculator/deprecatedmath/|org/warp/picalculator/device/PIDisplay.java|org/warp/picalculator/device/graphicengine/Display.java|com/rits/cloning/|com/rits/perspectives/|com/rits/|com/|org/warp/picalculator/TestCalcBenchmark.java" kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="src" path="res"/> <classpathentry kind="src" path="res"/>
<classpathentry exported="true" kind="con" path="org.eclipse.jdt.USER_LIBRARY/JOGL"/> <classpathentry exported="true" kind="con" path="org.eclipse.jdt.USER_LIBRARY/JOGL"/>

BIN
res/draft2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

View File

@ -116,8 +116,7 @@ public class BMPFile extends Component {
final byte rgb[] = new byte[3]; final byte rgb[] = new byte[3];
size = (biWidth * biHeight) - 1; size = (biWidth * biHeight) - 1;
pad = 4 - ((biWidth * 3) % 4); pad = 4 - ((biWidth * 3) % 4);
if (pad == 4) if (pad == 4) {
{
pad = 0; // <==== Bug correction pad = 0; // <==== Bug correction
} }
rowCount = 1; rowCount = 1;

View File

@ -14,6 +14,9 @@ public class Main {
public static Main instance; public static Main instance;
public static boolean haxMode = true; public static boolean haxMode = true;
public static String[] args; public static String[] args;
public static final String calculatorName = "WarpPI";
public static final String calculatorNameLOWER = "warppi";
public static final String calculatorNameUPPER = "WARPPI";
public Main(String[] args) throws InterruptedException { public Main(String[] args) throws InterruptedException {
this(new LoadingScreen(), args); this(new LoadingScreen(), args);
@ -23,7 +26,7 @@ public class Main {
instance = this; instance = this;
Thread.currentThread().setPriority(Thread.MAX_PRIORITY); Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Thread.currentThread().setName("Main thread"); Thread.currentThread().setName("Main thread");
this.args = args; Main.args = args;
beforeStart(); beforeStart();
new DisplayManager(screen); new DisplayManager(screen);
Utils.debug.println("Shutdown..."); Utils.debug.println("Shutdown...");

View File

@ -7,22 +7,22 @@ public class TestCalcBenchmark {
public static void main(String[] args) throws Error { public static void main(String[] args) throws Error {
Utils.debugOn = true; Utils.debugOn = true;
int times = 1; final int times = 1;
MathContext mc = new MathContext(); final MathContext mc = new MathContext();
long time1 = System.nanoTime(); final long time1 = System.nanoTime();
mc.parseInputString("5WABCDEFGHIWABCDEFGHIWABCDEFGHIWABCDEFGHIWABCDEFGHIWABCDEFGHI"); mc.parseInputString("5WABCDEFGHIWABCDEFGHIWABCDEFGHIWABCDEFGHIWABCDEFGHIWABCDEFGHI");
long time2 = System.nanoTime(); final long time2 = System.nanoTime();
for (int i = 0; i < times; i++) { for (int i = 0; i < times; i++) {
if (i == 1) { if (i == 1) {
Utils.debugOn = false; Utils.debugOn = false;
} }
mc.f2 = mc.solveExpression(mc.f); mc.f2 = mc.solveExpression(mc.f);
} }
long time3 = System.nanoTime(); final long time3 = System.nanoTime();
// System.out.println(mc.f2.get(0).toString()); // System.out.println(mc.f2.get(0).toString());
System.out.println("PARSING\t"+((time2-time1) / 1000000d / ((double) times)) + " milliseconds"); System.out.println("PARSING\t" + ((time2 - time1) / 1000000d / (times)) + " milliseconds");
System.out.println("WORK\t"+((time3-time2) / 1000000d / ((double) times)) + " milliseconds"); System.out.println("WORK\t" + ((time3 - time2) / 1000000d / (times)) + " milliseconds");
System.out.println("TOTAL\t"+((time3-time1) / 1000000d / ((double) times)) + " milliseconds"); System.out.println("TOTAL\t" + ((time3 - time1) / 1000000d / (times)) + " milliseconds");
} }
} }

View File

@ -23,7 +23,7 @@ public class TestDrivers {
try { try {
Class.forName(className); Class.forName(className);
return true; return true;
} catch( ClassNotFoundException e ) { } catch (final ClassNotFoundException e) {
return false; return false;
} }
} }

View File

@ -8,17 +8,14 @@ import org.warp.picalculator.gui.graphicengine.RenderingLoop;
import org.warp.picalculator.device.Keyboard; import org.warp.picalculator.device.Keyboard;
import org.warp.picalculator.device.Keyboard.Key; import org.warp.picalculator.device.Keyboard.Key;
import org.warp.picalculator.device.KeyboardEventListener; import org.warp.picalculator.device.KeyboardEventListener;
import org.warp.picalculator.gui.GUIErrorMessage;
import org.warp.picalculator.gui.expression.BlockContainer; import org.warp.picalculator.gui.expression.BlockContainer;
import org.warp.picalculator.gui.expression.containers.NormalInputContainer; import org.warp.picalculator.gui.expression.containers.NormalInputContainer;
import org.warp.picalculator.gui.graphicengine.BinaryFont; import org.warp.picalculator.gui.graphicengine.BinaryFont;
import org.warp.picalculator.gui.graphicengine.Skin; import org.warp.picalculator.gui.graphicengine.Skin;
import org.warp.picalculator.gui.graphicengine.cpu.CPUEngine;
import org.warp.picalculator.gui.graphicengine.gpu.GPUEngine; import org.warp.picalculator.gui.graphicengine.gpu.GPUEngine;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.MathematicalSymbols; import org.warp.picalculator.math.MathematicalSymbols;
import org.warp.picalculator.math.functions.Expression; import org.warp.picalculator.math.functions.Expression;
import org.warp.picalculator.math.functions.Root;
import org.warp.picalculator.math.parser.MathParser; import org.warp.picalculator.math.parser.MathParser;
public class TestGPU { public class TestGPU {
@ -107,9 +104,9 @@ public class TestGPU {
case EQUAL: case EQUAL:
Expression expr; Expression expr;
try { try {
expr = MathParser.parseInput(new MathContext(), c.root); expr = MathParser.parseInput(new MathContext(), c);
System.out.println("Parsed input:" + expr.toString()); System.out.println("Parsed input:" + expr.toString());
} catch (Error e) { } catch (final Error e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -131,7 +128,7 @@ public class TestGPU {
private static class Scene implements RenderingLoop { private static class Scene implements RenderingLoop {
private BinaryFont exampleFont; private final BinaryFont exampleFont;
private final Skin exampleSkin; private final Skin exampleSkin;
private final Renderer r; private final Renderer r;
@ -148,7 +145,6 @@ public class TestGPU {
BlockContainer.initializeFonts(d.loadFont("ex"), d.loadFont("big")); BlockContainer.initializeFonts(d.loadFont("ex"), d.loadFont("big"));
//New expression framework test //New expression framework test
c = new NormalInputContainer(false, 0, 200); c = new NormalInputContainer(false, 0, 200);
c.typeChar(MathematicalSymbols.DIVISION); c.typeChar(MathematicalSymbols.DIVISION);
@ -209,7 +205,7 @@ public class TestGPU {
if (lastTime == 0) { if (lastTime == 0) {
lastTime = System.currentTimeMillis(); lastTime = System.currentTimeMillis();
} }
double delta = System.currentTimeMillis()-lastTime; final double delta = System.currentTimeMillis() - lastTime;
lastTime = System.currentTimeMillis(); lastTime = System.currentTimeMillis();
c.beforeRender((float) (delta / 1000d)); c.beforeRender((float) (delta / 1000d));
c.draw(d, r, 10, 220); c.draw(d, r, 10, 220);

View File

@ -37,8 +37,6 @@ import org.warp.picalculator.math.functions.Variable;
import org.warp.picalculator.math.functions.equations.Equation; import org.warp.picalculator.math.functions.equations.Equation;
import org.warp.picalculator.math.functions.equations.EquationsSystemPart; import org.warp.picalculator.math.functions.equations.EquationsSystemPart;
import com.rits.cloning.Cloner;
public class Utils { public class Utils {
public static final int scale = 24; public static final int scale = 24;
@ -52,8 +50,6 @@ public class Utils {
public static boolean debugOn; public static boolean debugOn;
public static boolean debugThirdScreen; public static boolean debugThirdScreen;
public static Cloner cloner = new Cloner();
public static final class DebugStream extends StringWriter { public static final class DebugStream extends StringWriter {
public void println(String str) { public void println(String str) {
@ -198,7 +194,8 @@ public class Utils {
return true; return true;
} }
public static boolean areThereOnlySettedUpFunctionsSumsMultiplicationsEquationsAndSystems(ObjectArrayList<Function> fl) { public static boolean areThereOnlySettedUpFunctionsSumsMultiplicationsEquationsAndSystems(
ObjectArrayList<Function> fl) {
for (int i = 0; i < fl.size(); i++) { for (int i = 0; i < fl.size(); i++) {
if (!(fl.get(i) instanceof Number || fl.get(i) instanceof Variable || fl.get(i) instanceof Multiplication || fl.get(i) instanceof Sum || fl.get(i) instanceof SumSubtraction || fl.get(i) instanceof Subtraction || fl.get(i) instanceof Equation || fl.get(i) instanceof EquationsSystemPart || fl.get(i) instanceof Expression)) { if (!(fl.get(i) instanceof Number || fl.get(i) instanceof Variable || fl.get(i) instanceof Multiplication || fl.get(i) instanceof Sum || fl.get(i) instanceof SumSubtraction || fl.get(i) instanceof Subtraction || fl.get(i) instanceof Equation || fl.get(i) instanceof EquationsSystemPart || fl.get(i) instanceof Expression)) {
if (fl.get(i) instanceof FunctionSingle) { if (fl.get(i) instanceof FunctionSingle) {
@ -537,13 +534,12 @@ public class Utils {
return results; return results;
} }
public static Function[][] joinFunctionsResults(ObjectArrayList<ObjectArrayList<Function>> ln) { public static Function[][] joinFunctionsResults(ObjectArrayList<ObjectArrayList<Function>> ln) {
final int[] sizes = new int[ln.size()]; final int[] sizes = new int[ln.size()];
for (int i = 0; i < ln.size(); i++) { for (int i = 0; i < ln.size(); i++) {
sizes[i] = ln.get(i).size(); sizes[i] = ln.get(i).size();
} }
int[] curs = new int[sizes.length]; final int[] curs = new int[sizes.length];
int total = 0; int total = 0;
for (int i = 0; i < ln.size(); i++) { for (int i = 0; i < ln.size(); i++) {
if (i == 0) { if (i == 0) {
@ -615,27 +611,27 @@ public class Utils {
public static void printSystemResourcesUsage() { public static void printSystemResourcesUsage() {
System.out.println("============"); System.out.println("============");
OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean(); final OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
for (Method method : operatingSystemMXBean.getClass().getDeclaredMethods()) { for (final Method method : operatingSystemMXBean.getClass().getDeclaredMethods()) {
method.setAccessible(true); method.setAccessible(true);
if (method.getName().startsWith("get") && Modifier.isPublic(method.getModifiers())) { if (method.getName().startsWith("get") && Modifier.isPublic(method.getModifiers())) {
Object value; Object value;
try { try {
value = method.invoke(operatingSystemMXBean); value = method.invoke(operatingSystemMXBean);
} catch (Exception e) { } catch (final Exception e) {
value = e; value = e;
} // try } // try
boolean percent = false; boolean percent = false;
boolean mb = false; boolean mb = false;
String displayName = method.getName(); final String displayName = method.getName();
String displayValue = value.toString(); final String displayValue = value.toString();
if (displayName.endsWith("CpuLoad")) { if (displayName.endsWith("CpuLoad")) {
percent = true; percent = true;
} }
if (displayName.endsWith("MemorySize")) { if (displayName.endsWith("MemorySize")) {
mb = true; mb = true;
} }
ObjectArrayList<String> arr = new ObjectArrayList<>(); final ObjectArrayList<String> arr = new ObjectArrayList<>();
arr.add("getFreePhysicalMemorySize"); arr.add("getFreePhysicalMemorySize");
arr.add("getProcessCpuLoad"); arr.add("getProcessCpuLoad");
arr.add("getSystemCpuLoad"); arr.add("getSystemCpuLoad");
@ -644,13 +640,13 @@ public class Utils {
if (percent) { if (percent) {
try { try {
System.out.println(displayName + " = " + (((int) (Float.parseFloat(displayValue) * 10000f)) / 100f) + "%"); System.out.println(displayName + " = " + (((int) (Float.parseFloat(displayValue) * 10000f)) / 100f) + "%");
}catch(Exception ex) { } catch (final Exception ex) {
System.out.println(displayName + " = " + displayValue); System.out.println(displayName + " = " + displayValue);
} }
} else if (mb) { } else if (mb) {
try { try {
System.out.println(displayName + " = " + (Long.parseLong(displayValue) / 1024L / 1024L) + " MB"); System.out.println(displayName + " = " + (Long.parseLong(displayValue) / 1024L / 1024L) + " MB");
}catch(Exception ex) { } catch (final Exception ex) {
System.out.println(displayName + " = " + displayValue); System.out.println(displayName + " = " + displayValue);
} }
} else { } else {
@ -665,8 +661,7 @@ public class Utils {
public static boolean isRunningOnRaspberry() { public static boolean isRunningOnRaspberry() {
if (System.getProperty("os.name").equals("Linux")) { if (System.getProperty("os.name").equals("Linux")) {
final File file = new File("/etc", "os-release"); final File file = new File("/etc", "os-release");
try (FileInputStream fis = new FileInputStream(file); try (FileInputStream fis = new FileInputStream(file); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis))) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis))) {
String string; String string;
while ((string = bufferedReader.readLine()) != null) { while ((string = bufferedReader.readLine()) != null) {
if (string.toLowerCase().contains("raspbian")) { if (string.toLowerCase().contains("raspbian")) {

View File

@ -0,0 +1,88 @@
package org.warp.picalculator.device;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;
import org.warp.picalculator.Main;
public class CacheFile {
private String path;
private ObjectOutputStream lastOOS;
private FileOutputStream lastFOS;
private ObjectInputStream lastOIS;
private FileInputStream lastFIS;
public CacheFile() {
do {
path = UUID.randomUUID().toString()+".ser";
} while (Files.exists(Paths.get(path)));
try {
Files.createTempFile(Main.calculatorNameLOWER, "");
} catch (IOException e) {
e.printStackTrace();
}
}
public ObjectOutputStream getObjectOutputStram() {
if (lastOOS == null) {
try {
return new ObjectOutputStream(new FileOutputStream(path));
} catch (IOException e) {
e.printStackTrace();
return lastOOS;
}
} else {
return lastOOS;
}
}
public ObjectInputStream getObjectInputStram() {
if (lastOIS == null) {
try {
return new ObjectInputStream(new FileInputStream(path));
} catch (IOException e) {
return lastOIS;
}
} else {
return lastOIS;
}
}
public void closeStreams() {
try {
if (lastOOS != null) {
lastOOS.close();
lastOOS = null;
}
if (lastFOS != null) {
lastFOS.close();
lastFOS = null;
}
if (lastOIS != null) {
lastOIS.close();
lastOIS = null;
}
if (lastFIS != null) {
lastFIS.close();
lastFIS = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void dispose() {
closeStreams();
try {
Files.deleteIfExists(Paths.get(path));
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -703,7 +703,7 @@ public class Keyboard {
if (additionalListener != null) { if (additionalListener != null) {
try { try {
done = additionalListener.keyPressed(k); done = additionalListener.keyPressed(k);
} catch (Exception ex) { } catch (final Exception ex) {
new GUIErrorMessage(ex); new GUIErrorMessage(ex);
} }
} }
@ -713,7 +713,7 @@ public class Keyboard {
boolean scrdone = false; boolean scrdone = false;
try { try {
scrdone = scr.keyPressed(k); scrdone = scr.keyPressed(k);
} catch (Exception ex) { } catch (final Exception ex) {
new GUIErrorMessage(ex); new GUIErrorMessage(ex);
} }
if (scr != null && scr.initialized && scrdone) { if (scr != null && scr.initialized && scrdone) {

View File

@ -33,13 +33,13 @@ public class RAWFont {
public void create(String name) { public void create(String name) {
try { try {
loadFont("/font_" + name + ".rft"); loadFont("/font_" + name + ".rft");
} catch (IOException e) { } catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
System.exit(1); System.exit(1);
} }
chars32 = new int[(maxBound - minBound) * charIntCount]; chars32 = new int[(maxBound - minBound) * charIntCount];
for (int charIndex = 0; charIndex < maxBound - minBound; charIndex++) { for (int charIndex = 0; charIndex < maxBound - minBound; charIndex++) {
boolean[] currentChar = rawchars[charIndex]; final boolean[] currentChar = rawchars[charIndex];
if (currentChar == null) { if (currentChar == null) {
int currentInt = 0; int currentInt = 0;
int currentBit = 0; int currentBit = 0;
@ -66,7 +66,7 @@ public class RAWFont {
} }
Object obj = new Object(); Object obj = new Object();
WeakReference<Object> ref = new WeakReference<>(obj); final WeakReference<Object> ref = new WeakReference<>(obj);
obj = null; obj = null;
while (ref.get() != null) { while (ref.get() != null) {
System.gc(); System.gc();
@ -74,9 +74,9 @@ public class RAWFont {
} }
private void loadFont(String string) throws IOException { private void loadFont(String string) throws IOException {
URL res = Main.instance.getClass().getResource(string); final URL res = Main.instance.getClass().getResource(string);
int[] file = Utils.realBytes(Utils.convertStreamToByteArray(res.openStream(), res.getFile().length())); final int[] file = Utils.realBytes(Utils.convertStreamToByteArray(res.openStream(), res.getFile().length()));
int filelength = file.length; final int filelength = file.length;
if (filelength >= 16) { if (filelength >= 16) {
if (file[0x0] == 114 && file[0x1] == 97 && file[0x2] == 119 && file[0x3] == 0xFF && file[0x8] == 0xFF && file[0xD] == 0xFF) { if (file[0x0] == 114 && file[0x1] == 97 && file[0x2] == 119 && file[0x3] == 0xFF && file[0x8] == 0xFF && file[0xD] == 0xFF) {
charW = file[0x4] << 8 | file[0x5]; charW = file[0x4] << 8 | file[0x5];
@ -92,8 +92,8 @@ public class RAWFont {
int index = 0x12; int index = 0x12;
while (index < filelength) { while (index < filelength) {
try { try {
int charIndex = file[index] << 8 | file[index+1]; final int charIndex = file[index] << 8 | file[index + 1];
boolean[] rawchar = new boolean[charS]; final boolean[] rawchar = new boolean[charS];
int charbytescount = 0; int charbytescount = 0;
while (charbytescount * 8 < charS) { while (charbytescount * 8 < charS) {
charbytescount += 1; charbytescount += 1;
@ -110,8 +110,7 @@ public class RAWFont {
} }
rawchars[charIndex - minBound] = rawchar; rawchars[charIndex - minBound] = rawchar;
index += 2 + charbytescount; index += 2 + charbytescount;
} } catch (final Exception ex) {
catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
System.out.println(string); System.out.println(string);
System.exit(-1); System.exit(-1);
@ -127,8 +126,8 @@ public class RAWFont {
public int[] getCharIndexes(String txt) { public int[] getCharIndexes(String txt) {
final int l = txt.length(); final int l = txt.length();
int[] indexes = new int[l]; final int[] indexes = new int[l];
char[] chars = txt.toCharArray(); final char[] chars = txt.toCharArray();
for (int i = 0; i < l; i++) { for (int i = 0; i < l; i++) {
indexes[i] = (chars[i] & 0xFFFF) - minBound; indexes[i] = (chars[i] & 0xFFFF) - minBound;
} }
@ -137,12 +136,12 @@ public class RAWFont {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private void saveArray(int[] screen, String coutputpng) { private void saveArray(int[] screen, String coutputpng) {
BufferedImage bi = new BufferedImage(300, 200, BufferedImage.TYPE_INT_RGB); final BufferedImage bi = new BufferedImage(300, 200, BufferedImage.TYPE_INT_RGB);
final int[] a = ((DataBufferInt) bi.getRaster().getDataBuffer()).getData(); final int[] a = ((DataBufferInt) bi.getRaster().getDataBuffer()).getData();
System.arraycopy(screen, 0, a, 0, screen.length); System.arraycopy(screen, 0, a, 0, screen.length);
try { try {
ImageIO.write(bi, "PNG", new File(coutputpng)); ImageIO.write(bi, "PNG", new File(coutputpng));
} catch (IOException ex) { } catch (final IOException ex) {
Logger.getLogger(RAWFont.class.getName()).log(Level.SEVERE, null, ex); Logger.getLogger(RAWFont.class.getName()).log(Level.SEVERE, null, ex);
} }
} }
@ -151,7 +150,6 @@ public class RAWFont {
final int screenLength = screen.length; final int screenLength = screen.length;
int screenPos = 0; int screenPos = 0;
int currentInt; int currentInt;
int currentIntBitPosition; int currentIntBitPosition;
int bitData; int bitData;
@ -165,7 +163,7 @@ public class RAWFont {
for (int dx = 0; dx < charW; dx++) { for (int dx = 0; dx < charW; dx++) {
j = x + cpos + dx; j = x + cpos + dx;
if (j > 0 & j < screenSize[0]) { if (j > 0 & j < screenSize[0]) {
int bit = dx + dy * charW; final int bit = dx + dy * charW;
currentInt = (int) (Math.floor(bit) / (intBits)); currentInt = (int) (Math.floor(bit) / (intBits));
currentIntBitPosition = bit - (currentInt * intBits); currentIntBitPosition = bit - (currentInt * intBits);
bitData = (chars32[charIndex * charIntCount + currentInt] >> currentIntBitPosition) & 1; bitData = (chars32[charIndex * charIntCount + currentInt] >> currentIntBitPosition) & 1;

View File

@ -1,10 +1,6 @@
package org.warp.picalculator.gui; package org.warp.picalculator.gui;
import java.io.IOException; import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import org.warp.picalculator.Main; import org.warp.picalculator.Main;
@ -373,7 +369,7 @@ public final class DisplayManager implements RenderingLoop {
} }
//Working thread //Working thread
Thread workThread = new Thread(() -> { final Thread workThread = new Thread(() -> {
try { try {
while (true) { while (true) {
float dt = 0; float dt = 0;

View File

@ -6,25 +6,25 @@ import org.warp.picalculator.Error;
public class GUIErrorMessage { public class GUIErrorMessage {
private String err; private final String err;
private long creationTime; private final long creationTime;
public GUIErrorMessage(Error e) { public GUIErrorMessage(Error e) {
this.err = e.getLocalizedMessage(); err = e.getLocalizedMessage();
this.creationTime = System.currentTimeMillis(); creationTime = System.currentTimeMillis();
} }
public GUIErrorMessage(Exception ex) { public GUIErrorMessage(Exception ex) {
err = ex.getLocalizedMessage(); err = ex.getLocalizedMessage();
this.creationTime = System.currentTimeMillis(); creationTime = System.currentTimeMillis();
} }
public void draw(GraphicEngine g, Renderer r, String msg) { public void draw(GraphicEngine g, Renderer r, String msg) {
int scrW = g.getWidth(); final int scrW = g.getWidth();
int scrH = g.getHeight(); final int scrH = g.getHeight();
int width = 200; final int width = 200;
int height = 20; final int height = 20;
int margin = 4; final int margin = 4;
r.glClearSkin(); r.glClearSkin();
r.glColor(0x00000000); r.glColor(0x00000000);
r.glFillRect(scrW - width - margin, scrH - height - margin, width, height, 0, 0, 0, 0); r.glFillRect(scrW - width - margin, scrH - height - margin, width, height, 0, 0, 0, 0);

View File

@ -1,23 +1,19 @@
package org.warp.picalculator.gui; package org.warp.picalculator.gui;
public class GraphicUtils { public class GraphicUtils {
public static final float sin(float rad) public static final float sin(float rad) {
{
return sin[(int) (rad * radToIndex) & SIN_MASK]; return sin[(int) (rad * radToIndex) & SIN_MASK];
} }
public static final float cos(float rad) public static final float cos(float rad) {
{
return cos[(int) (rad * radToIndex) & SIN_MASK]; return cos[(int) (rad * radToIndex) & SIN_MASK];
} }
public static final float sinDeg(float deg) public static final float sinDeg(float deg) {
{
return sin[(int) (deg * degToIndex) & SIN_MASK]; return sin[(int) (deg * degToIndex) & SIN_MASK];
} }
public static final float cosDeg(float deg) public static final float cosDeg(float deg) {
{
return cos[(int) (deg * degToIndex) & SIN_MASK]; return cos[(int) (deg * degToIndex) & SIN_MASK];
} }
@ -27,8 +23,7 @@ public class GraphicUtils {
private static final float degFull, degToIndex; private static final float degFull, degToIndex;
private static final float[] sin, cos; private static final float[] sin, cos;
static static {
{
RAD = (float) Math.PI / 180.0f; RAD = (float) Math.PI / 180.0f;
DEG = 180.0f / (float) Math.PI; DEG = 180.0f / (float) Math.PI;
@ -44,15 +39,13 @@ public class GraphicUtils {
sin = new float[SIN_COUNT]; sin = new float[SIN_COUNT];
cos = new float[SIN_COUNT]; cos = new float[SIN_COUNT];
for (int i = 0; i < SIN_COUNT; i++) for (int i = 0; i < SIN_COUNT; i++) {
{
sin[i] = (float) Math.sin((i + 0.5f) / SIN_COUNT * radFull); sin[i] = (float) Math.sin((i + 0.5f) / SIN_COUNT * radFull);
cos[i] = (float) Math.cos((i + 0.5f) / SIN_COUNT * radFull); cos[i] = (float) Math.cos((i + 0.5f) / SIN_COUNT * radFull);
} }
// Four cardinal directions (credits: Nate) // Four cardinal directions (credits: Nate)
for (int i = 0; i < 360; i += 90) for (int i = 0; i < 360; i += 90) {
{
sin[(int) (i * degToIndex) & SIN_MASK] = (float) Math.sin(i * Math.PI / 180.0); sin[(int) (i * degToIndex) & SIN_MASK] = (float) Math.sin(i * Math.PI / 180.0);
cos[(int) (i * degToIndex) & SIN_MASK] = (float) Math.cos(i * Math.PI / 180.0); cos[(int) (i * degToIndex) & SIN_MASK] = (float) Math.cos(i * Math.PI / 180.0);
} }

View File

@ -3,7 +3,9 @@ package org.warp.picalculator.gui;
public interface GraphicalElement { public interface GraphicalElement {
/** /**
* Recompute element's dimension parameters, like <strong>width</strong>, <strong>height</strong>, <strong>line</strong> or <strong>length</strong>. * Recompute element's dimension parameters, like <strong>width</strong>,
* <strong>height</strong>, <strong>line</strong> or
* <strong>length</strong>.
*/ */
public void recomputeDimensions(); public void recomputeDimensions();
@ -21,7 +23,8 @@ public interface GraphicalElement {
/** /**
* *
* @return Position of the vertical alignment line of the element, relative to itself. * @return Position of the vertical alignment line of the element, relative
* to itself.
*/ */
public int getLine(); public int getLine();
} }

View File

@ -3,7 +3,6 @@ package org.warp.picalculator.gui.expression;
import org.warp.picalculator.gui.GraphicalElement; import org.warp.picalculator.gui.GraphicalElement;
import org.warp.picalculator.gui.graphicengine.GraphicEngine; import org.warp.picalculator.gui.graphicengine.GraphicEngine;
import org.warp.picalculator.gui.graphicengine.Renderer; import org.warp.picalculator.gui.graphicengine.Renderer;
import org.warp.picalculator.math.parser.features.interfaces.Feature;
public abstract class Block implements GraphicalElement { public abstract class Block implements GraphicalElement {
@ -14,9 +13,12 @@ public abstract class Block implements GraphicalElement {
/** /**
* *
* @param r Graphic Renderer class. * @param r
* @param x Position relative to the window. * Graphic Renderer class.
* @param y Position relative to the window. * @param x
* Position relative to the window.
* @param y
* Position relative to the window.
* @param small * @param small
*/ */
public abstract void draw(GraphicEngine ge, Renderer r, int x, int y, Caret caret); public abstract void draw(GraphicEngine ge, Renderer r, int x, int y, Caret caret);

View File

@ -2,8 +2,6 @@ package org.warp.picalculator.gui.expression;
import org.warp.picalculator.gui.graphicengine.GraphicEngine; import org.warp.picalculator.gui.graphicengine.GraphicEngine;
import org.warp.picalculator.gui.graphicengine.Renderer; import org.warp.picalculator.gui.graphicengine.Renderer;
import org.warp.picalculator.math.parser.features.FeatureChar;
import org.warp.picalculator.math.parser.features.interfaces.Feature;
public class BlockChar extends Block { public class BlockChar extends Block {

View File

@ -41,7 +41,7 @@ public class BlockContainer implements GraphicalElement {
this.minWidth = minWidth; this.minWidth = minWidth;
this.minHeight = minHeight; this.minHeight = minHeight;
this.withBorder = withBorder; this.withBorder = withBorder;
for (Block b: content) { for (final Block b : content) {
if (b.isSmall() != small) { if (b.isSmall() != small) {
b.setSmall(small); b.setSmall(small);
} }
@ -63,11 +63,15 @@ public class BlockContainer implements GraphicalElement {
} }
public void appendBlock(Block b) { public void appendBlock(Block b) {
appendBlockUnsafe(b);
recomputeDimensions();
}
public void appendBlockUnsafe(Block b) {
if (b.isSmall() != small) { if (b.isSmall() != small) {
b.setSmall(small); b.setSmall(small);
} }
content.add(b); content.add(b);
recomputeDimensions();
} }
public void removeBlock(Block b) { public void removeBlock(Block b) {
@ -91,11 +95,16 @@ public class BlockContainer implements GraphicalElement {
/** /**
* *
* @param ge Graphic Engine class. * @param ge
* @param r Graphic Renderer class of <b>ge</b>. * Graphic Engine class.
* @param x Position relative to the window. * @param r
* @param y Position relative to the window. * Graphic Renderer class of <b>ge</b>.
* @param caret Position of the caret. * @param x
* Position relative to the window.
* @param y
* Position relative to the window.
* @param caret
* Position of the caret.
*/ */
public void draw(GraphicEngine ge, Renderer r, int x, int y, Caret caret) { public void draw(GraphicEngine ge, Renderer r, int x, int y, Caret caret) {
int paddingX = 1; int paddingX = 1;
@ -114,11 +123,13 @@ public class BlockContainer implements GraphicalElement {
r.glDrawLine(x + paddingX + width - 1, y, x + paddingX + width - 1, y + height - 1); r.glDrawLine(x + paddingX + width - 1, y, x + paddingX + width - 1, y + height - 1);
r.glDrawLine(x + paddingX, y + height - 1, x + paddingX + width - 1, y + height - 1); r.glDrawLine(x + paddingX, y + height - 1, x + paddingX + width - 1, y + height - 1);
} else { } else {
for (Block b : content) { for (final Block b : content) {
caret.skip(1); caret.skip(1);
b.draw(ge, r, x + paddingX, y + line - b.line, caret); b.draw(ge, r, x + paddingX, y + line - b.line, caret);
paddingX += b.getWidth(); paddingX += b.getWidth();
if (caret.getRemaining() == 0) BlockContainer.drawCaret(ge, r, caret, x + paddingX, y+line-b.line, b.height); if (caret.getRemaining() == 0) {
BlockContainer.drawCaret(ge, r, caret, x + paddingX, y + line - b.line, b.height);
}
paddingX += 1; paddingX += 1;
} }
} }
@ -129,17 +140,17 @@ public class BlockContainer implements GraphicalElement {
boolean added = false; boolean added = false;
if (caret.getRemaining() == 0) { if (caret.getRemaining() == 0) {
this.addBlock(0, newBlock); addBlock(0, newBlock);
added = true; added = true;
} }
int pos = 0; int pos = 0;
for (Block b : content) { for (final Block b : content) {
caret.skip(1); caret.skip(1);
pos++; pos++;
added = added | b.putBlock(caret, newBlock); added = added | b.putBlock(caret, newBlock);
if (caret.getRemaining() == 0) { if (caret.getRemaining() == 0) {
this.addBlock(pos, newBlock); addBlock(pos, newBlock);
added = true; added = true;
} }
} }
@ -154,13 +165,13 @@ public class BlockContainer implements GraphicalElement {
boolean removed = false; boolean removed = false;
int pos = 0; int pos = 0;
for (Block b : content) { for (final Block b : content) {
caret.skip(1); caret.skip(1);
pos++; pos++;
int deltaCaret = caret.getRemaining(); final int deltaCaret = caret.getRemaining();
removed = removed | b.delBlock(caret); removed = removed | b.delBlock(caret);
if (caret.getRemaining() == 0 || (removed == false && deltaCaret >= 0 && caret.getRemaining() < 0)) { if (caret.getRemaining() == 0 || (removed == false && deltaCaret >= 0 && caret.getRemaining() < 0)) {
this.removeAt(pos-1); removeAt(pos - 1);
caret.setPosition(caret.getPosition() - deltaCaret); caret.setPosition(caret.getPosition() - deltaCaret);
removed = true; removed = true;
} }
@ -172,7 +183,6 @@ public class BlockContainer implements GraphicalElement {
return removed; return removed;
} }
@Override @Override
public void recomputeDimensions() { public void recomputeDimensions() {
int l = 0; //Line int l = 0; //Line
@ -180,7 +190,7 @@ public class BlockContainer implements GraphicalElement {
int h2 = 0; //Height under the line. h = h2 + l int h2 = 0; //Height under the line. h = h2 + l
int h = 0; //Height int h = 0; //Height
for (Block b : content) { for (final Block b : content) {
w += b.getWidth() + 1; w += b.getWidth() + 1;
final int bl = b.getLine(); final int bl = b.getLine();
final int bh = b.getHeight(); final int bh = b.getHeight();
@ -280,12 +290,14 @@ public class BlockContainer implements GraphicalElement {
} }
private static void checkInitialized() { private static void checkInitialized() {
if (!initialized) throw new ExceptionInInitializerError("Please initialize BlockContainer by running the method BlockContainer.initialize(...) first!"); if (!initialized) {
throw new ExceptionInInitializerError("Please initialize BlockContainer by running the method BlockContainer.initialize(...) first!");
}
} }
public int computeCaretMaxBound() { public int computeCaretMaxBound() {
int maxpos = 0; int maxpos = 0;
for (Block b : content) { for (final Block b : content) {
maxpos += 1 + b.computeCaretMaxBound(); maxpos += 1 + b.computeCaretMaxBound();
} }
return maxpos + 1; return maxpos + 1;

View File

@ -1,11 +1,7 @@
package org.warp.picalculator.gui.expression; package org.warp.picalculator.gui.expression;
import org.warp.picalculator.Main;
import org.warp.picalculator.gui.graphicengine.GraphicEngine; import org.warp.picalculator.gui.graphicengine.GraphicEngine;
import org.warp.picalculator.gui.graphicengine.Renderer; import org.warp.picalculator.gui.graphicengine.Renderer;
import org.warp.picalculator.math.parser.features.interfaces.Feature;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
public class BlockDivision extends Block { public class BlockDivision extends Block {
@ -19,8 +15,8 @@ public class BlockDivision extends Block {
private int h1; private int h1;
public BlockDivision() { public BlockDivision() {
this.containerUp = new BlockContainer(false); containerUp = new BlockContainer(false);
this.containerDown = new BlockContainer(false); containerDown = new BlockContainer(false);
recomputeDimensions(); recomputeDimensions();
} }
@ -82,8 +78,8 @@ public class BlockDivision extends Block {
@Override @Override
public void setSmall(boolean small) { public void setSmall(boolean small) {
this.small = small; this.small = small;
this.containerUp.setSmall(small); containerUp.setSmall(small);
this.containerDown.setSmall(small); containerDown.setSmall(small);
recomputeDimensions(); recomputeDimensions();
} }

View File

@ -10,7 +10,7 @@ public class BlockParenthesis extends Block {
private final BlockContainer containerNumber; private final BlockContainer containerNumber;
public BlockParenthesis() { public BlockParenthesis() {
this.containerNumber = new BlockContainer(false); containerNumber = new BlockContainer(false);
recomputeDimensions(); recomputeDimensions();
} }
@ -43,15 +43,15 @@ public class BlockParenthesis extends Block {
@Override @Override
public void recomputeDimensions() { public void recomputeDimensions() {
this.width = containerNumber.getWidth()+BlockContainer.getDefaultCharWidth(small)*2; width = containerNumber.getWidth() + BlockContainer.getDefaultCharWidth(small) * 2;
this.height = containerNumber.getHeight(); height = containerNumber.getHeight();
this.line = containerNumber.getLine(); line = containerNumber.getLine();
} }
@Override @Override
public void setSmall(boolean small) { public void setSmall(boolean small) {
this.small = small; this.small = small;
this.containerNumber.setSmall(small); containerNumber.setSmall(small);
recomputeDimensions(); recomputeDimensions();
} }

View File

@ -1,11 +1,7 @@
package org.warp.picalculator.gui.expression; package org.warp.picalculator.gui.expression;
import org.warp.picalculator.Main;
import org.warp.picalculator.gui.graphicengine.GraphicEngine; import org.warp.picalculator.gui.graphicengine.GraphicEngine;
import org.warp.picalculator.gui.graphicengine.Renderer; import org.warp.picalculator.gui.graphicengine.Renderer;
import org.warp.picalculator.math.parser.features.interfaces.Feature;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
public class BlockSquareRoot extends Block { public class BlockSquareRoot extends Block {
@ -16,7 +12,7 @@ public class BlockSquareRoot extends Block {
private int h1; private int h1;
public BlockSquareRoot() { public BlockSquareRoot() {
this.containerNumber = new BlockContainer(false); containerNumber = new BlockContainer(false);
recomputeDimensions(); recomputeDimensions();
} }
@ -72,7 +68,7 @@ public class BlockSquareRoot extends Block {
@Override @Override
public void setSmall(boolean small) { public void setSmall(boolean small) {
this.small = small; this.small = small;
this.containerNumber.setSmall(small); containerNumber.setSmall(small);
recomputeDimensions(); recomputeDimensions();
} }

View File

@ -9,7 +9,7 @@ public class Caret {
public Caret(CaretState state, int pos) { public Caret(CaretState state, int pos) {
this.state = state; this.state = state;
this.pos = pos; this.pos = pos;
this.remaining = pos; remaining = pos;
} }
public void skip(int i) { public void skip(int i) {
@ -29,21 +29,21 @@ public class Caret {
} }
public void flipState() { public void flipState() {
if (this.state == CaretState.VISIBLE_ON) { if (state == CaretState.VISIBLE_ON) {
this.state = CaretState.VISIBLE_OFF; state = CaretState.VISIBLE_OFF;
} else if (this.state == CaretState.VISIBLE_OFF) { } else if (state == CaretState.VISIBLE_OFF) {
this.state = CaretState.VISIBLE_ON; state = CaretState.VISIBLE_ON;
} }
} }
public void turnOn() { public void turnOn() {
if (this.state == CaretState.VISIBLE_OFF) { if (state == CaretState.VISIBLE_OFF) {
this.state = CaretState.VISIBLE_ON; state = CaretState.VISIBLE_ON;
} }
} }
public void setPosition(int i) { public void setPosition(int i) {
this.pos = i; pos = i;
} }
public void resetRemaining() { public void resetRemaining() {

View File

@ -1,7 +1,5 @@
package org.warp.picalculator.gui.expression; package org.warp.picalculator.gui.expression;
public enum CaretState { public enum CaretState {
VISIBLE_ON, VISIBLE_ON, VISIBLE_OFF, HIDDEN
VISIBLE_OFF,
HIDDEN
} }

View File

@ -1,5 +1,8 @@
package org.warp.picalculator.gui.expression.containers; package org.warp.picalculator.gui.expression.containers;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.warp.picalculator.gui.GraphicalElement; import org.warp.picalculator.gui.GraphicalElement;
import org.warp.picalculator.gui.expression.Block; import org.warp.picalculator.gui.expression.Block;
import org.warp.picalculator.gui.expression.BlockContainer; import org.warp.picalculator.gui.expression.BlockContainer;
@ -9,12 +12,17 @@ import org.warp.picalculator.gui.expression.layouts.InputLayout;
import org.warp.picalculator.gui.graphicengine.GraphicEngine; import org.warp.picalculator.gui.graphicengine.GraphicEngine;
import org.warp.picalculator.gui.graphicengine.Renderer; import org.warp.picalculator.gui.graphicengine.Renderer;
public abstract class InputContainer implements GraphicalElement, InputLayout { import it.unimi.dsi.fastutil.Arrays;
public final BlockContainer root; import it.unimi.dsi.fastutil.objects.ObjectArrayList;
public abstract class InputContainer implements GraphicalElement, InputLayout, Serializable {
private static final long serialVersionUID = 923589369317765667L;
private final BlockContainer root;
private Caret caret; private Caret caret;
private static final float CARET_DURATION = 0.5f; private static final float CARET_DURATION = 0.5f;
private float caretTime; private float caretTime;
private int maxPosition = 0; private int maxPosition = 0;
private boolean parsed = false;
public InputContainer() { public InputContainer() {
caret = new Caret(CaretState.VISIBLE_ON, 0); caret = new Caret(CaretState.VISIBLE_ON, 0);
@ -32,7 +40,7 @@ public abstract class InputContainer implements GraphicalElement, InputLayout {
} }
public void typeChar(char c) { public void typeChar(char c) {
Block b = parseChar(c); final Block b = parseChar(c);
if (b != null) { if (b != null) {
caret.resetRemaining(); caret.resetRemaining();
if (root.putBlock(caret, b)) { if (root.putBlock(caret, b)) {
@ -63,7 +71,7 @@ public abstract class InputContainer implements GraphicalElement, InputLayout {
} }
public void moveLeft() { public void moveLeft() {
int curPos = caret.getPosition(); final int curPos = caret.getPosition();
if (curPos > 0) { if (curPos > 0) {
caret.setPosition(curPos - 1); caret.setPosition(curPos - 1);
} }
@ -72,7 +80,7 @@ public abstract class InputContainer implements GraphicalElement, InputLayout {
} }
public void moveRight() { public void moveRight() {
int curPos = caret.getPosition(); final int curPos = caret.getPosition();
if (curPos + 1 < maxPosition) { if (curPos + 1 < maxPosition) {
caret.setPosition(curPos + 1); caret.setPosition(curPos + 1);
} }
@ -102,7 +110,8 @@ public abstract class InputContainer implements GraphicalElement, InputLayout {
/** /**
* *
* @param delta Time, in seconds * @param delta
* Time, in seconds
* @return true if something changed * @return true if something changed
*/ */
public boolean beforeRender(float delta) { public boolean beforeRender(float delta) {
@ -121,10 +130,14 @@ public abstract class InputContainer implements GraphicalElement, InputLayout {
/** /**
* *
* @param ge Graphic Engine class. * @param ge
* @param r Graphic Renderer class of <b>ge</b>. * Graphic Engine class.
* @param x Position relative to the window. * @param r
* @param y Position relative to the window. * Graphic Renderer class of <b>ge</b>.
* @param x
* Position relative to the window.
* @param y
* Position relative to the window.
*/ */
public void draw(GraphicEngine ge, Renderer r, int x, int y) { public void draw(GraphicEngine ge, Renderer r, int x, int y) {
caret.resetRemaining(); caret.resetRemaining();
@ -137,4 +150,37 @@ public abstract class InputContainer implements GraphicalElement, InputLayout {
maxPosition = root.computeCaretMaxBound(); maxPosition = root.computeCaretMaxBound();
recomputeDimensions(); recomputeDimensions();
} }
public boolean isEmpty() {
return maxPosition <= 1;
}
public int getCaretMaxPosition() {
return maxPosition;
}
public void setCaretPosition(int pos) {
if (pos > 0 && pos < maxPosition) {
caret.setPosition(pos);
}
caret.turnOn();
caretTime = 0;
}
public void setParsed(boolean parsed) {
this.parsed = parsed;
}
public boolean isAlreadyParsed() {
return parsed;
}
/**
* <strong>WARNING! DO NOT MODIFY THIS ARRAY!!!</strong>
*
* @return an arraylist representing the content
*/
public ObjectArrayList<Block> getContent() {
return root.getContent();
}
} }

View File

@ -2,12 +2,9 @@ package org.warp.picalculator.gui.expression.containers;
import org.warp.picalculator.gui.expression.Block; import org.warp.picalculator.gui.expression.Block;
import org.warp.picalculator.gui.expression.BlockChar; import org.warp.picalculator.gui.expression.BlockChar;
import org.warp.picalculator.gui.expression.BlockContainer;
import org.warp.picalculator.gui.expression.BlockDivision; import org.warp.picalculator.gui.expression.BlockDivision;
import org.warp.picalculator.gui.expression.BlockParenthesis; import org.warp.picalculator.gui.expression.BlockParenthesis;
import org.warp.picalculator.gui.expression.BlockSquareRoot; import org.warp.picalculator.gui.expression.BlockSquareRoot;
import org.warp.picalculator.gui.expression.Caret;
import org.warp.picalculator.gui.expression.CaretState;
import org.warp.picalculator.math.MathematicalSymbols; import org.warp.picalculator.math.MathematicalSymbols;
public class NormalInputContainer extends InputContainer { public class NormalInputContainer extends InputContainer {

View File

@ -1,15 +1,19 @@
package org.warp.picalculator.gui.expression.containers; package org.warp.picalculator.gui.expression.containers;
import java.io.Serializable;
import org.warp.picalculator.gui.GraphicalElement; import org.warp.picalculator.gui.GraphicalElement;
import org.warp.picalculator.gui.expression.Block; import org.warp.picalculator.gui.expression.Block;
import org.warp.picalculator.gui.expression.BlockContainer; import org.warp.picalculator.gui.expression.BlockContainer;
import org.warp.picalculator.gui.expression.Caret; import org.warp.picalculator.gui.expression.Caret;
import org.warp.picalculator.gui.expression.CaretState; import org.warp.picalculator.gui.expression.CaretState;
import org.warp.picalculator.gui.expression.layouts.InputLayout;
import org.warp.picalculator.gui.graphicengine.GraphicEngine; import org.warp.picalculator.gui.graphicengine.GraphicEngine;
import org.warp.picalculator.gui.graphicengine.Renderer; import org.warp.picalculator.gui.graphicengine.Renderer;
public abstract class OutputContainer implements GraphicalElement, OutputLayout { import it.unimi.dsi.fastutil.objects.ObjectArrayList;
public abstract class OutputContainer implements GraphicalElement, OutputLayout, Serializable {
private static final long serialVersionUID = -5714825964892683571L;
public final BlockContainer root; public final BlockContainer root;
private final Caret caret = new Caret(CaretState.HIDDEN, 0); private final Caret caret = new Caret(CaretState.HIDDEN, 0);
@ -25,6 +29,14 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout
root = new BlockContainer(small); root = new BlockContainer(small);
} }
public void setContent(ObjectArrayList<Block> blocks) {
root.clear();
for (Block b : blocks) {
root.appendBlockUnsafe(b);
}
recomputeDimensions();
}
@Override @Override
public void recomputeDimensions() { public void recomputeDimensions() {
root.recomputeDimensions(); root.recomputeDimensions();
@ -47,7 +59,8 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout
/** /**
* *
* @param delta Time, in seconds * @param delta
* Time, in seconds
*/ */
public void beforeRender(double delta) { public void beforeRender(double delta) {
@ -55,10 +68,14 @@ public abstract class OutputContainer implements GraphicalElement, OutputLayout
/** /**
* *
* @param ge Graphic Engine class. * @param ge
* @param r Graphic Renderer class of <b>ge</b>. * Graphic Engine class.
* @param x Position relative to the window. * @param r
* @param y Position relative to the window. * Graphic Renderer class of <b>ge</b>.
* @param x
* Position relative to the window.
* @param y
* Position relative to the window.
*/ */
public void draw(GraphicEngine ge, Renderer r, int x, int y) { public void draw(GraphicEngine ge, Renderer r, int x, int y) {
root.draw(ge, r, x, y, caret); root.draw(ge, r, x, y, caret);

View File

@ -1,7 +1,5 @@
package org.warp.picalculator.gui.graphicengine; package org.warp.picalculator.gui.graphicengine;
import java.awt.FontMetrics;
public interface Renderer { public interface Renderer {
public void glColor3i(int r, int gg, int b); public void glColor3i(int r, int gg, int b);
@ -25,7 +23,8 @@ public interface Renderer {
public void glDrawLine(float x0, float y0, float x1, float y1); public void glDrawLine(float x0, float y0, float x1, float y1);
public void glFillRect(float x, float y, float width, float height, float uvX, float uvY, float uvWidth, float uvHeight); public void glFillRect(float x, float y, float width, float height, float uvX, float uvY, float uvWidth,
float uvHeight);
public void glFillColor(float x, float y, float width, float height); public void glFillColor(float x, float y, float width, float height);

View File

@ -87,7 +87,7 @@ public class CPUEngine implements GraphicEngine {
@Override @Override
public void start(RenderingLoop d) { public void start(RenderingLoop d) {
INSTANCE.setRenderingLoop(d); INSTANCE.setRenderingLoop(d);
Thread th = new Thread(() -> { final Thread th = new Thread(() -> {
try { try {
double extratime = 0; double extratime = 0;
while (initialized) { while (initialized) {
@ -464,7 +464,7 @@ public class CPUEngine implements GraphicEngine {
do { do {
Thread.sleep(500); Thread.sleep(500);
} while (initialized); } while (initialized);
} catch (InterruptedException e) { } catch (final InterruptedException e) {
} }
} }

View File

@ -5,7 +5,6 @@ import java.io.IOException;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import org.warp.picalculator.Main;
import org.warp.picalculator.gui.graphicengine.GraphicEngine; import org.warp.picalculator.gui.graphicengine.GraphicEngine;
import org.warp.picalculator.gui.graphicengine.Skin; import org.warp.picalculator.gui.graphicengine.Skin;
import org.warp.picalculator.gui.graphicengine.cpu.CPUEngine.CPURenderer; import org.warp.picalculator.gui.graphicengine.cpu.CPUEngine.CPURenderer;

View File

@ -9,7 +9,6 @@ import org.warp.picalculator.gui.graphicengine.BinaryFont;
import org.warp.picalculator.gui.graphicengine.Skin; import org.warp.picalculator.gui.graphicengine.Skin;
import com.jogamp.opengl.GLProfile; import com.jogamp.opengl.GLProfile;
import com.jogamp.opengl.egl.EGL;
public class GPUEngine implements org.warp.picalculator.gui.graphicengine.GraphicEngine { public class GPUEngine implements org.warp.picalculator.gui.graphicengine.GraphicEngine {
@ -47,8 +46,8 @@ public class GPUEngine implements org.warp.picalculator.gui.graphicengine.Graphi
@Override @Override
public void setDisplayMode(int ww, int wh) { public void setDisplayMode(int ww, int wh) {
this.size[0] = ww; size[0] = ww;
this.size[1] = wh; size[1] = wh;
wnd.window.setSize(Utils.debugOn ? ww * 2 : ww, Utils.debugOn ? wh * 2 : wh); wnd.window.setSize(Utils.debugOn ? ww * 2 : ww, Utils.debugOn ? wh * 2 : wh);
} }
@ -93,7 +92,7 @@ public class GPUEngine implements org.warp.picalculator.gui.graphicengine.Graphi
@Override @Override
public void repaint() { public void repaint() {
if (d != null & r != null && r.gl != null) { if (d != null & r != null && GPURenderer.gl != null) {
d.refresh(); d.refresh();
} }
} }
@ -119,14 +118,14 @@ public class GPUEngine implements org.warp.picalculator.gui.graphicengine.Graphi
do { do {
Thread.sleep(500); Thread.sleep(500);
} while (initialized | created); } while (initialized | created);
} catch (InterruptedException e) { } catch (final InterruptedException e) {
} }
} }
@Override @Override
public boolean isSupported() { public boolean isSupported() {
boolean available = GLProfile.isAvailable(GLProfile.GL2ES1); final boolean available = GLProfile.isAvailable(GLProfile.GL2ES1);
if (!available) { if (!available) {
System.err.println(GLProfile.glAvailabilityToString()); System.err.println(GLProfile.glAvailabilityToString());
} }

View File

@ -1,11 +1,8 @@
package org.warp.picalculator.gui.graphicengine.gpu; package org.warp.picalculator.gui.graphicengine.gpu;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import javax.imageio.ImageIO;
import org.warp.picalculator.gui.graphicengine.GraphicEngine; import org.warp.picalculator.gui.graphicengine.GraphicEngine;
import org.warp.picalculator.gui.graphicengine.BinaryFont; import org.warp.picalculator.gui.graphicengine.BinaryFont;
import org.warp.picalculator.gui.graphicengine.cpu.CPUFont; import org.warp.picalculator.gui.graphicengine.cpu.CPUFont;

View File

@ -1,6 +1,5 @@
package org.warp.picalculator.gui.graphicengine.gpu; package org.warp.picalculator.gui.graphicengine.gpu;
import java.awt.FontMetrics;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
@ -43,9 +42,9 @@ public class GPURenderer implements Renderer {
@Override @Override
public void glColor3i(int r, int gg, int b) { public void glColor3i(int r, int gg, int b) {
final float red = ((float)r) / 255f; final float red = (r) / 255f;
final float gre = ((float)gg) / 255f; final float gre = (gg) / 255f;
final float blu = ((float)b) / 255f; final float blu = (b) / 255f;
currentColor = new float[] { red, gre, blu, 1.0f, red, gre, blu, 1.0f, red, gre, blu, 1.0f, red, gre, blu, 1.0f, }; currentColor = new float[] { red, gre, blu, 1.0f, red, gre, blu, 1.0f, red, gre, blu, 1.0f, red, gre, blu, 1.0f, };
} }
@ -75,10 +74,10 @@ public class GPURenderer implements Renderer {
@Override @Override
public void glClearColor(int rgb) { public void glClearColor(int rgb) {
final float alpha = (float)((rgb >> 24) & 0xFF) / 255f; final float alpha = ((rgb >> 24) & 0xFF) / 255f;
final float red = (float)((rgb >> 16) & 0xFF) / 255f; final float red = ((rgb >> 16) & 0xFF) / 255f;
final float green = (float)((rgb >> 8) & 0xFF) / 255f; final float green = ((rgb >> 8) & 0xFF) / 255f;
final float blue = (float)(rgb & 0xFF) / 255f; final float blue = (rgb & 0xFF) / 255f;
glClearColor4f(red, green, blue, alpha); glClearColor4f(red, green, blue, alpha);
} }
@ -117,7 +116,8 @@ public class GPURenderer implements Renderer {
} }
@Override @Override
public void glFillRect(float x, float y, float width, float height, float uvX, float uvY, float uvWidth, float uvHeight) { public void glFillRect(float x, float y, float width, float height, float uvX, float uvY, float uvWidth,
float uvHeight) {
enableTexture(); enableTexture();
uvWidth /= currentTexWidth; uvWidth /= currentTexWidth;
uvX /= currentTexWidth; uvX /= currentTexWidth;
@ -145,7 +145,7 @@ public class GPURenderer implements Renderer {
@Override @Override
public void glDrawStringLeft(float x, float y, String text) { public void glDrawStringLeft(float x, float y, String text) {
final int txtLen = text.length(); final int txtLen = text.length();
int[] txtArray = currentFont.getCharIndexes(text); final int[] txtArray = currentFont.getCharIndexes(text);
int tableIndexX; int tableIndexX;
int tableIndexY; int tableIndexY;
for (int currentCharIndex = 0; currentCharIndex < txtLen; currentCharIndex++) { for (int currentCharIndex = 0; currentCharIndex < txtLen; currentCharIndex++) {
@ -167,9 +167,9 @@ public class GPURenderer implements Renderer {
@Override @Override
public void glDrawCharLeft(int x, int y, char ch) { public void glDrawCharLeft(int x, int y, char ch) {
int index = currentFont.getCharIndex(ch); final int index = currentFont.getCharIndex(ch);
int tableIndexX = index % currentFont.memoryWidthOfEachColumn; final int tableIndexX = index % currentFont.memoryWidthOfEachColumn;
int tableIndexY = (index - tableIndexX) / currentFont.memoryWidthOfEachColumn; final int tableIndexY = (index - tableIndexX) / currentFont.memoryWidthOfEachColumn;
glFillRect(x, y, currentFont.charW, currentFont.charH, tableIndexX * currentFont.charW, tableIndexY * currentFont.charH, currentFont.charW, currentFont.charH); glFillRect(x, y, currentFont.charW, currentFont.charH, tableIndexX * currentFont.charW, tableIndexY * currentFont.charH, currentFont.charW, currentFont.charH);
} }
@ -208,7 +208,7 @@ public class GPURenderer implements Renderer {
final ByteArrayOutputStream os = new ByteArrayOutputStream(); final ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(img, "png", os); ImageIO.write(img, "png", os);
final InputStream fis = new ByteArrayInputStream(os.toByteArray()); final InputStream fis = new ByteArrayInputStream(os.toByteArray());
Texture tex = TextureIO.newTexture(fis, false, TextureIO.PNG); final Texture tex = TextureIO.newTexture(fis, false, TextureIO.PNG);
tex.setTexParameteri(gl, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST); tex.setTexParameteri(gl, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST);
tex.setTexParameteri(gl, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST); tex.setTexParameteri(gl, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST);
return tex; return tex;
@ -248,10 +248,10 @@ public class GPURenderer implements Renderer {
precTexEnabled = currentTexEnabled; precTexEnabled = currentTexEnabled;
precTex = currentTex; precTex = currentTex;
if (currentTexEnabled) { if (currentTexEnabled) {
gl.glEnable(GL2ES1.GL_TEXTURE_2D); gl.glEnable(GL.GL_TEXTURE_2D);
currentTex.bind(gl); currentTex.bind(gl);
} else { } else {
gl.glDisable(GL2ES1.GL_TEXTURE_2D); gl.glDisable(GL.GL_TEXTURE_2D);
} }
} }

View File

@ -5,6 +5,7 @@ import java.io.IOException;
import org.warp.picalculator.gui.graphicengine.GraphicEngine; import org.warp.picalculator.gui.graphicengine.GraphicEngine;
import org.warp.picalculator.gui.graphicengine.Skin; import org.warp.picalculator.gui.graphicengine.Skin;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2ES1; import com.jogamp.opengl.GL2ES1;
import com.jogamp.opengl.GLException; import com.jogamp.opengl.GLException;
import com.jogamp.opengl.util.texture.Texture; import com.jogamp.opengl.util.texture.Texture;
@ -33,12 +34,12 @@ public class GPUSkin implements Skin {
@Override @Override
public void initialize(GraphicEngine d) { public void initialize(GraphicEngine d) {
try { try {
BufferedImage i = GPURenderer.openTexture(texturePath); final BufferedImage i = GPURenderer.openTexture(texturePath);
GL2ES1 gl = ((GPURenderer)d.getRenderer()).gl; final GL2ES1 gl = GPURenderer.gl;
t = GPURenderer.importTexture(i); t = GPURenderer.importTexture(i);
w = i.getWidth(); w = i.getWidth();
h = i.getHeight(); h = i.getHeight();
t.setTexParameteri(gl, GL2ES1.GL_TEXTURE_MAG_FILTER, GL2ES1.GL_NEAREST); t.setTexParameteri(gl, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST);
initialized = true; initialized = true;
} catch (GLException | IOException e) { } catch (GLException | IOException e) {
e.printStackTrace(); e.printStackTrace();

View File

@ -33,13 +33,10 @@ import com.jogamp.opengl.GL2ES1;
import com.jogamp.opengl.GLAutoDrawable; import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.GLEventListener; import com.jogamp.opengl.GLEventListener;
import com.jogamp.opengl.GLProfile; import com.jogamp.opengl.GLProfile;
import com.jogamp.opengl.fixedfunc.GLLightingFunc;
import com.jogamp.opengl.fixedfunc.GLMatrixFunc; import com.jogamp.opengl.fixedfunc.GLMatrixFunc;
import com.jogamp.opengl.fixedfunc.GLPointerFunc; import com.jogamp.opengl.fixedfunc.GLPointerFunc;
import com.jogamp.opengl.GLCapabilities; import com.jogamp.opengl.GLCapabilities;
import com.jogamp.nativewindow.util.DimensionImmutable;
import com.jogamp.nativewindow.util.PixelFormat;
import com.jogamp.nativewindow.util.PixelRectangle;
import com.jogamp.newt.NewtFactory;
import com.jogamp.newt.event.KeyEvent; import com.jogamp.newt.event.KeyEvent;
import com.jogamp.newt.event.KeyListener; import com.jogamp.newt.event.KeyListener;
import com.jogamp.newt.event.WindowEvent; import com.jogamp.newt.event.WindowEvent;
@ -49,16 +46,10 @@ import com.jogamp.newt.opengl.GLWindow;
import com.jogamp.opengl.util.*; import com.jogamp.opengl.util.*;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.nio.ByteBuffer;
import java.util.Collection;
import org.warp.picalculator.Utils; import org.warp.picalculator.Utils;
import org.warp.picalculator.device.Keyboard; import org.warp.picalculator.device.Keyboard;
import org.warp.picalculator.device.Keyboard.Key; import org.warp.picalculator.device.Keyboard.Key;
import org.warp.picalculator.gui.DisplayManager; import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.gui.graphicengine.GraphicEngine;
/** /**
* *
@ -277,9 +268,9 @@ class NEWTWindow implements GLEventListener {
gl.glEnable(GL.GL_TEXTURE_2D); gl.glEnable(GL.GL_TEXTURE_2D);
//Transparency //Transparency
gl.glEnable(GL2ES1.GL_BLEND); gl.glEnable(GL.GL_BLEND);
gl.glBlendFunc(GL2ES1.GL_SRC_ALPHA, GL2ES1.GL_ONE_MINUS_SRC_ALPHA); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
gl.glShadeModel(GL2ES1.GL_FLAT); gl.glShadeModel(GLLightingFunc.GL_FLAT);
try { try {
renderer.currentTex = ((GPUSkin) disp.loadSkin("test.png")).t; renderer.currentTex = ((GPUSkin) disp.loadSkin("test.png")).t;
@ -329,7 +320,7 @@ class NEWTWindow implements GLEventListener {
public void display(GLAutoDrawable glad) { public void display(GLAutoDrawable glad) {
final GL2ES1 gl = glad.getGL().getGL2ES1(); final GL2ES1 gl = glad.getGL().getGL2ES1();
renderer.gl = gl; GPURenderer.gl = gl;
gl.glEnableClientState(GLPointerFunc.GL_COLOR_ARRAY); gl.glEnableClientState(GLPointerFunc.GL_COLOR_ARRAY);
gl.glEnableClientState(GLPointerFunc.GL_VERTEX_ARRAY); gl.glEnableClientState(GLPointerFunc.GL_VERTEX_ARRAY);
@ -341,7 +332,7 @@ class NEWTWindow implements GLEventListener {
renderer.endDrawCycle(); renderer.endDrawCycle();
renderer.gl = null; GPURenderer.gl = null;
gl.glDisableClientState(GLPointerFunc.GL_COLOR_ARRAY); gl.glDisableClientState(GLPointerFunc.GL_COLOR_ARRAY);
gl.glDisableClientState(GLPointerFunc.GL_TEXTURE_COORD_ARRAY); gl.glDisableClientState(GLPointerFunc.GL_TEXTURE_COORD_ARRAY);

View File

@ -29,7 +29,7 @@ public class KeyboardDebugScreen extends Screen {
@Override @Override
public void render() { public void render() {
Renderer renderer = DisplayManager.renderer; final Renderer renderer = DisplayManager.renderer;
fonts[2].use(DisplayManager.engine); fonts[2].use(DisplayManager.engine);
renderer.glColor4f(0.75f, 0.0f, 0.0f, 1.0f); renderer.glColor4f(0.75f, 0.0f, 0.0f, 1.0f);
renderer.glDrawStringRight(Main.screenSize[0] - 10, 30, "-" + keyevent.toUpperCase() + "-"); renderer.glDrawStringRight(Main.screenSize[0] - 10, 30, "-" + keyevent.toUpperCase() + "-");

View File

@ -1,8 +1,5 @@
package org.warp.picalculator.gui.screens; package org.warp.picalculator.gui.screens;
import static org.warp.picalculator.gui.DisplayManager.colore;
import static org.warp.picalculator.gui.DisplayManager.fonts;
import org.warp.picalculator.Main; import org.warp.picalculator.Main;
import org.warp.picalculator.device.Keyboard.Key; import org.warp.picalculator.device.Keyboard.Key;
import org.warp.picalculator.gui.DisplayManager; import org.warp.picalculator.gui.DisplayManager;

View File

@ -1,11 +1,7 @@
package org.warp.picalculator.gui.screens; package org.warp.picalculator.gui.screens;
import java.awt.image.BufferedImage;
import java.io.IOException; import java.io.IOException;
import javax.imageio.ImageIO;
import org.warp.picalculator.Main;
import org.warp.picalculator.device.Keyboard; import org.warp.picalculator.device.Keyboard;
import org.warp.picalculator.device.Keyboard.Key; import org.warp.picalculator.device.Keyboard.Key;
import org.warp.picalculator.gui.DisplayManager; import org.warp.picalculator.gui.DisplayManager;
@ -37,7 +33,7 @@ public class MarioScreen extends Screen {
try { try {
skin = DisplayManager.engine.loadSkin("marioskin.png"); skin = DisplayManager.engine.loadSkin("marioskin.png");
groundskin = DisplayManager.engine.loadSkin("marioground.png"); groundskin = DisplayManager.engine.loadSkin("marioground.png");
} catch (IOException e) { } catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }

View File

@ -4,19 +4,20 @@ import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.util.Collections; import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import org.warp.picalculator.Error; import org.warp.picalculator.Error;
import org.warp.picalculator.Errors; import org.warp.picalculator.Errors;
import org.warp.picalculator.Main;
import org.warp.picalculator.Utils; import org.warp.picalculator.Utils;
import org.warp.picalculator.device.Keyboard; import org.warp.picalculator.device.Keyboard;
import org.warp.picalculator.device.Keyboard.Key; import org.warp.picalculator.device.Keyboard.Key;
import org.warp.picalculator.gui.DisplayManager; import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.gui.expression.Block;
import org.warp.picalculator.gui.expression.BlockContainer; import org.warp.picalculator.gui.expression.BlockContainer;
import org.warp.picalculator.gui.expression.containers.InputContainer; import org.warp.picalculator.gui.expression.containers.InputContainer;
import org.warp.picalculator.gui.expression.containers.NormalInputContainer; import org.warp.picalculator.gui.expression.containers.NormalInputContainer;
@ -34,6 +35,8 @@ import org.warp.picalculator.math.MathematicalSymbols;
import org.warp.picalculator.math.functions.Variable; import org.warp.picalculator.math.functions.Variable;
import org.warp.picalculator.math.functions.Variable.VariableValue; import org.warp.picalculator.math.functions.Variable.VariableValue;
import org.warp.picalculator.math.functions.equations.Equation; import org.warp.picalculator.math.functions.equations.Equation;
import org.warp.picalculator.math.parser.MathParser;
import org.warp.picalculator.math.functions.Expression;
import org.warp.picalculator.math.functions.Number; import org.warp.picalculator.math.functions.Number;
public class MathInputScreen extends Screen { public class MathInputScreen extends Screen {
@ -55,7 +58,7 @@ public class MathInputScreen extends Screen {
try { try {
BlockContainer.initializeFonts(DisplayManager.engine.loadFont("ex"), DisplayManager.engine.loadFont("big")); BlockContainer.initializeFonts(DisplayManager.engine.loadFont("ex"), DisplayManager.engine.loadFont("big"));
} catch (IOException e) { } catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
System.exit(1); System.exit(1);
} }
@ -88,7 +91,7 @@ public class MathInputScreen extends Screen {
@Override @Override
public void renderStatusbar() { public void renderStatusbar() {
Renderer renderer = DisplayManager.renderer; final Renderer renderer = DisplayManager.renderer;
renderer.glColor3f(1, 1, 1); renderer.glColor3f(1, 1, 1);
final int pos = 2; final int pos = 2;
final int spacersNumb = 1; final int spacersNumb = 1;
@ -111,7 +114,7 @@ public class MathInputScreen extends Screen {
userInput.draw(DisplayManager.engine, DisplayManager.renderer, padding, padding + 20); userInput.draw(DisplayManager.engine, DisplayManager.renderer, padding, padding + 20);
if (!result.root.getContent().isEmpty()) { if (!result.root.getContent().isEmpty()) {
result.draw(DisplayManager.engine, DisplayManager.renderer, DisplayManager.engine.getWidth() - 2, DisplayManager.engine.getHeight() - 2); result.draw(DisplayManager.engine, DisplayManager.renderer, DisplayManager.engine.getWidth() - result.getWidth() - 2, DisplayManager.engine.getHeight() - result.getHeight() - 2);
} }
} }
@ -127,6 +130,7 @@ public class MathInputScreen extends Screen {
@Override @Override
public boolean keyPressed(Key k) { public boolean keyPressed(Key k) {
Utils.debug.println(k.toString());
switch (k) { switch (k) {
case STEP: case STEP:
// if (newExpression.length() > 0) { // if (newExpression.length() > 0) {
@ -160,46 +164,51 @@ public class MathInputScreen extends Screen {
// } // }
// return true; // return true;
case SIMPLIFY: case SIMPLIFY:
// if (DisplayManager.error != null) { if (DisplayManager.error != null) {
// Utils.debug.println("Resetting after error..."); //TODO: make the error management a global API rather than being relegated to this screen.
// DisplayManager.error = null; Utils.debug.println("Resetting after error...");
// currentExpression = null; DisplayManager.error = null;
// calc.f = null; calc.f = null;
// calc.f2 = null; calc.f2 = null;
// calc.resultsCount = 0; calc.resultsCount = 0;
// return true; return true;
// } else { } else {
// try { try {
// try { try {
// if (!firstStep) { if (!userInput.isAlreadyParsed() && !userInput.isEmpty()) {
// step(); Expression expr = MathParser.parseInput(calc, userInput);
// } else { if (calc.f == null | calc.f2 == null) {
// if (newExpression != currentExpression && newExpression.length() > 0) { calc.f = new ObjectArrayList<>();
// changeEquationScreen(); calc.f2 = new ObjectArrayList<>();
// interpreta(true); } else {
calc.f.clear();
calc.f2.clear();
}
calc.f.add(expr);
ObjectArrayList<Function> resultExpression = expr.solve();
ObjectArrayList<Block> resultBlocks = MathParser.parseOutput(calc, resultExpression);
result.setContent(resultBlocks);
// showVariablesDialog(() -> { // showVariablesDialog(() -> {
// currentExpression = newExpression; // currentExpression = newExpression;
// simplify(); // simplify();
// }); // });
// } }
// } } catch (final Exception ex) {
// } catch (final Exception ex) { if (Utils.debugOn) {
// if (Utils.debugOn) { ex.printStackTrace();
// ex.printStackTrace(); }
// } throw new Error(Errors.SYNTAX_ERROR);
// throw new Error(Errors.SYNTAX_ERROR); }
// } } catch (final Error e) {
// } catch (final Error e) { final StringWriter sw = new StringWriter();
// final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw);
// final PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw);
// e.printStackTrace(pw); d.errorStackTrace = sw.toString().toUpperCase().replace("\t", " ").replace("\r", "").split("\n");
// d.errorStackTrace = sw.toString().toUpperCase().replace("\t", " ").replace("\r", "").split("\n"); DisplayManager.error = e.id.toString();
// DisplayManager.error = e.id.toString(); System.err.println(e.id);
// System.err.println(e.id); }
// }
// return true;
// }
return true; return true;
}
case NUM0: case NUM0:
typeChar('0'); typeChar('0');
return true; return true;
@ -317,13 +326,13 @@ public class MathInputScreen extends Screen {
} }
return true; return true;
case SURD_MODE: case SURD_MODE:
// calc.exactMode = !calc.exactMode; calc.exactMode = !calc.exactMode;
// if (calc.exactMode == false) { if (calc.exactMode == false) {
// calc.f2 = solveExpression(calc.f2); calc.f2 = solveExpression(calc.f2);
// } else { } else {
// currentExpression = ""; result.clear();
// Keyboard.keyPressed(Key.SIMPLIFY); Keyboard.keyPressed(Key.SIMPLIFY);
// } }
return true; return true;
case debug1: case debug1:
DisplayManager.INSTANCE.setScreen(new EmptyScreen()); DisplayManager.INSTANCE.setScreen(new EmptyScreen());
@ -436,9 +445,6 @@ public class MathInputScreen extends Screen {
results.clear(); results.clear();
results.addAll(hs); results.addAll(hs);
calc.f2 = results; calc.f2 = results;
for (final Function rf : calc.f2) {
rf.recomputeDimensions(null);
}
} }
Utils.debug.println(calc.f2.toString()); Utils.debug.println(calc.f2.toString());
} catch (final Exception ex) { } catch (final Exception ex) {
@ -479,9 +485,6 @@ public class MathInputScreen extends Screen {
results.clear(); results.clear();
results.addAll(hs); results.addAll(hs);
calc.f2 = results; calc.f2 = results;
for (final Function rf : calc.f2) {
rf.recomputeDimensions(null);
}
} }
} catch (final Exception ex) { } catch (final Exception ex) {
if (Utils.debugOn) { if (Utils.debugOn) {
@ -499,20 +502,19 @@ public class MathInputScreen extends Screen {
} }
} }
@SuppressWarnings("unused")
@Deprecated
private void changeEquationScreen() { private void changeEquationScreen() {
if (currentExpression != null && currentExpression.length() > 0) { throw new NotImplementedException();
final MathInputScreen cloned = clone(); //
cloned.caretPos = cloned.currentExpression.length(); // if (!userInput.isEmpty()) {
cloned.newExpression = cloned.currentExpression; // final MathInputScreen cloned = clone();
cloned.scrollX = fontBig.getStringWidth(cloned.currentExpression); // cloned.userInput.setCaretPosition(cloned.userInput.getCaretMaxPosition()-1);
try { // DisplayManager.INSTANCE.replaceScreen(cloned);
cloned.interpreta(true); // initialized = false;
} catch (final Error e) {} // DisplayManager.INSTANCE.setScreen(this);
DisplayManager.INSTANCE.replaceScreen(cloned); //
initialized = false; // }
DisplayManager.INSTANCE.setScreen(this);
}
} }
public void typeChar(char chr) { public void typeChar(char chr) {
@ -594,15 +596,17 @@ public class MathInputScreen extends Screen {
} }
@Override @Override
@Deprecated
public MathInputScreen clone() { public MathInputScreen clone() {
final MathInputScreen es = this; throw new NotImplementedException();
final MathInputScreen es2 = new MathInputScreen(); // final MathInputScreen es = this;
es2.errorLevel = es.errorLevel; // final MathInputScreen es2 = new MathInputScreen();
es2.mustRefresh = es.mustRefresh; // es2.errorLevel = es.errorLevel;
es2.calc = Utils.cloner.deepClone(es.calc); // es2.mustRefresh = es.mustRefresh;
es2.userInput = Utils.cloner.deepClone(es.userInput); // es2.calc = Utils.cloner.deepClone(es.calc);
es2.result = Utils.cloner.deepClone(es.result); // es2.userInput = Utils.cloner.deepClone(es.userInput);
return es2; // es2.result = Utils.cloner.deepClone(es.result);
// return es2;
} }
} }

View File

@ -1,10 +1,8 @@
package org.warp.picalculator.gui.screens; package org.warp.picalculator.gui.screens;
import org.warp.picalculator.Error;
import org.warp.picalculator.Main; import org.warp.picalculator.Main;
import org.warp.picalculator.device.Keyboard.Key; import org.warp.picalculator.device.Keyboard.Key;
import org.warp.picalculator.gui.DisplayManager; import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.math.MathContext;
public class SolveEquationScreen extends Screen { public class SolveEquationScreen extends Screen {

View File

@ -8,6 +8,7 @@ public interface Function {
/** /**
* Returns this function and its children in a string form. * Returns this function and its children in a string form.
*
* @return This function and its children in a string form. * @return This function and its children in a string form.
*/ */
@Override @Override
@ -18,27 +19,34 @@ public interface Function {
/** /**
* Deep clone this function. * Deep clone this function.
*
* @return A clone of this function. * @return A clone of this function.
*/ */
public Function clone(); public Function clone();
/** /**
* Generic method to change a parameter in a known position. * Generic method to change a parameter in a known position.
* @param index parameter index. *
* @param var parameter. * @param index
* parameter index.
* @param var
* parameter.
* @return A new instance of this function. * @return A new instance of this function.
*/ */
public Function setParameter(int index, Function var) throws IndexOutOfBoundsException; public Function setParameter(int index, Function var) throws IndexOutOfBoundsException;
/** /**
* Generic method to retrieve a parameter in a known position. * Generic method to retrieve a parameter in a known position.
* @param index parameter index. *
* @param index
* parameter index.
* @return The requested parameter. * @return The requested parameter.
*/ */
public Function getParameter(int index) throws IndexOutOfBoundsException; public Function getParameter(int index) throws IndexOutOfBoundsException;
/** /**
* Retrieve the current Math Context used by this function * Retrieve the current Math Context used by this function
*
* @return Calculator mathContext * @return Calculator mathContext
*/ */
public MathContext getMathContext(); public MathContext getMathContext();
@ -50,6 +58,7 @@ public interface Function {
/** /**
* The current simplification status of this function and it's childrens * The current simplification status of this function and it's childrens
*
* @return boolean * @return boolean
*/ */
public boolean isSimplified(); public boolean isSimplified();

View File

@ -7,8 +7,6 @@ import java.util.List;
import org.warp.picalculator.Error; import org.warp.picalculator.Error;
import org.warp.picalculator.Utils; import org.warp.picalculator.Utils;
import com.rits.cloning.Cloner;
public abstract class FunctionDynamic implements Function { public abstract class FunctionDynamic implements Function {
public FunctionDynamic(MathContext root) { public FunctionDynamic(MathContext root) {
this.root = root; this.root = root;
@ -37,7 +35,7 @@ public abstract class FunctionDynamic implements Function {
} }
public FunctionDynamic setParameters(final List<Function> value) { public FunctionDynamic setParameters(final List<Function> value) {
FunctionDynamic f = this.clone(); final FunctionDynamic f = clone();
final int vsize = value.size(); final int vsize = value.size();
final Function[] tmp = new Function[vsize]; final Function[] tmp = new Function[vsize];
for (int i = 0; i < vsize; i++) { for (int i = 0; i < vsize; i++) {
@ -48,7 +46,7 @@ public abstract class FunctionDynamic implements Function {
} }
public FunctionDynamic setParameters(final Function[] value) { public FunctionDynamic setParameters(final Function[] value) {
FunctionDynamic f = this.clone(); final FunctionDynamic f = clone();
f.functions = value; f.functions = value;
return f; return f;
} }
@ -60,13 +58,13 @@ public abstract class FunctionDynamic implements Function {
@Override @Override
public FunctionDynamic setParameter(int index, Function value) { public FunctionDynamic setParameter(int index, Function value) {
FunctionDynamic f = this.clone(); final FunctionDynamic f = clone();
f.functions[index] = value; f.functions[index] = value;
return f; return f;
} }
public FunctionDynamic appendParameter(Function value) { public FunctionDynamic appendParameter(Function value) {
FunctionDynamic f = this.clone(); final FunctionDynamic f = clone();
f.functions = Arrays.copyOf(f.functions, f.functions.length + 1); f.functions = Arrays.copyOf(f.functions, f.functions.length + 1);
f.functions[f.functions.length - 1] = value; f.functions[f.functions.length - 1] = value;
return f; return f;
@ -74,6 +72,7 @@ public abstract class FunctionDynamic implements Function {
/** /**
* Retrieve the current number of parameters. * Retrieve the current number of parameters.
*
* @return The number of parameters. * @return The number of parameters.
*/ */
public int getParametersLength() { public int getParametersLength() {
@ -81,7 +80,7 @@ public abstract class FunctionDynamic implements Function {
} }
public FunctionDynamic setParametersLength(int length) { public FunctionDynamic setParametersLength(int length) {
FunctionDynamic f = this.clone(); final FunctionDynamic f = clone();
f.functions = Arrays.copyOf(functions, length); f.functions = Arrays.copyOf(functions, length);
return f; return f;
} }
@ -97,16 +96,19 @@ public abstract class FunctionDynamic implements Function {
} }
/** /**
* The current simplification status of this function, assuming that its children are already simplified. * The current simplification status of this function, assuming that its
* @return <strong>true</strong> if this function can be solved, otherwise <strong>false</strong>. * children are already simplified.
*
* @return <strong>true</strong> if this function can be solved, otherwise
* <strong>false</strong>.
*/ */
protected abstract boolean isSolvable(); protected abstract boolean isSolvable();
@Override @Override
public final ObjectArrayList<Function> simplify() throws Error { public final ObjectArrayList<Function> simplify() throws Error {
boolean solved = true; boolean solved = true;
Function[] fncs = getParameters(); final Function[] fncs = getParameters();
for (Function f : fncs) { for (final Function f : fncs) {
if (f.isSimplified() == false) { if (f.isSimplified() == false) {
solved = false; solved = false;
break; break;
@ -118,12 +120,12 @@ public abstract class FunctionDynamic implements Function {
result = new ObjectArrayList<>(); result = new ObjectArrayList<>();
final ObjectArrayList<ObjectArrayList<Function>> ln = new ObjectArrayList<>(); final ObjectArrayList<ObjectArrayList<Function>> ln = new ObjectArrayList<>();
for (int i = 0; i < fncs.length; i++) { for (final Function fnc : fncs) {
ObjectArrayList<Function> l = new ObjectArrayList<>(); final ObjectArrayList<Function> l = new ObjectArrayList<>();
if (fncs[i].isSimplified()) { if (fnc.isSimplified()) {
l.add(fncs[i]); l.add(fnc);
} else { } else {
l.addAll(fncs[i].simplify()); l.addAll(fnc.simplify());
} }
ln.add(l); ln.add(l);
} }
@ -139,9 +141,12 @@ public abstract class FunctionDynamic implements Function {
} }
/** /**
* Solves only this function, assuming that its children are already simplified and it can be solved. * Solves only this function, assuming that its children are already
* simplified and it can be solved.
*
* @return The solved function. * @return The solved function.
* @throws Error Errors during computation, like a/0 or similar. * @throws Error
* Errors during computation, like a/0 or similar.
*/ */
protected abstract ObjectArrayList<Function> solve() throws Error; protected abstract ObjectArrayList<Function> solve() throws Error;

View File

@ -8,24 +8,32 @@ import org.warp.picalculator.Utils;
public abstract class FunctionOperator implements Function { public abstract class FunctionOperator implements Function {
/** /**
* Create a new instance of FunctionOperator. The Math Context will be the same of <strong>value1</strong>'s. * Create a new instance of FunctionOperator. The Math Context will be the
* @throws NullPointerException when value1 is null. * same of <strong>value1</strong>'s.
* @param value1 The parameter of this function. *
* @param value2 The parameter of this function. * @throws NullPointerException
* when value1 is null.
* @param value1
* The parameter of this function.
* @param value2
* The parameter of this function.
*/ */
public FunctionOperator(Function value1, Function value2) throws NullPointerException { public FunctionOperator(Function value1, Function value2) throws NullPointerException {
this.mathContext = value1.getMathContext(); mathContext = value1.getMathContext();
parameter1 = value1; parameter1 = value1;
parameter2 = value2; parameter2 = value2;
} }
/** /**
* Create a new instance of FunctionOperator. * Create a new instance of FunctionOperator.
* @param value1 The parameter of this function. *
* @param value2 The parameter of this function. * @param value1
* The parameter of this function.
* @param value2
* The parameter of this function.
*/ */
public FunctionOperator(MathContext mc, Function value1, Function value2) { public FunctionOperator(MathContext mc, Function value1, Function value2) {
this.mathContext = mc; mathContext = mc;
parameter1 = value1; parameter1 = value1;
parameter2 = value2; parameter2 = value2;
} }
@ -53,22 +61,24 @@ public abstract class FunctionOperator implements Function {
/** /**
* *
* @param var First parameter. * @param var
* First parameter.
* @return A new instance of this function. * @return A new instance of this function.
*/ */
public FunctionOperator setParameter1(Function var) { public FunctionOperator setParameter1(Function var) {
FunctionOperator s = this.clone(); final FunctionOperator s = clone();
s.parameter1 = var; s.parameter1 = var;
return s; return s;
} }
/** /**
* *
* @param var Second parameter. * @param var
* Second parameter.
* @return A new instance of this function. * @return A new instance of this function.
*/ */
public FunctionOperator setParameter2(Function var) { public FunctionOperator setParameter2(Function var) {
FunctionOperator s = this.clone(); final FunctionOperator s = clone();
s.parameter2 = var; s.parameter2 = var;
return s; return s;
} }
@ -77,9 +87,9 @@ public abstract class FunctionOperator implements Function {
public FunctionOperator setParameter(int index, Function var) throws IndexOutOfBoundsException { public FunctionOperator setParameter(int index, Function var) throws IndexOutOfBoundsException {
switch (index) { switch (index) {
case 0: case 0:
return this.setParameter1(var); return setParameter1(var);
case 1: case 1:
return this.setParameter2(var); return setParameter2(var);
default: default:
throw new IndexOutOfBoundsException(); throw new IndexOutOfBoundsException();
} }
@ -89,9 +99,9 @@ public abstract class FunctionOperator implements Function {
public Function getParameter(int index) throws IndexOutOfBoundsException { public Function getParameter(int index) throws IndexOutOfBoundsException {
switch (index) { switch (index) {
case 0: case 0:
return this.getParameter1(); return getParameter1();
case 1: case 1:
return this.getParameter2(); return getParameter2();
default: default:
throw new IndexOutOfBoundsException(); throw new IndexOutOfBoundsException();
} }
@ -108,8 +118,11 @@ public abstract class FunctionOperator implements Function {
} }
/** /**
* The current simplification status of this function, assuming that its children are already simplified. * The current simplification status of this function, assuming that its
* @return <strong>true</strong> if this function can be solved, otherwise <strong>false</strong>. * children are already simplified.
*
* @return <strong>true</strong> if this function can be solved, otherwise
* <strong>false</strong>.
*/ */
protected abstract boolean isSolvable(); protected abstract boolean isSolvable();
@ -137,7 +150,7 @@ public abstract class FunctionOperator implements Function {
final Function[][] results = Utils.joinFunctionsResults(l1, l2); final Function[][] results = Utils.joinFunctionsResults(l1, l2);
for (final Function[] f : results) { for (final Function[] f : results) {
result.add(this.setParameter1(f[0]).setParameter2(f[1])); result.add(setParameter1(f[0]).setParameter2(f[1]));
} }
} }
@ -145,9 +158,12 @@ public abstract class FunctionOperator implements Function {
} }
/** /**
* Solves only this function, assuming that its children are already simplified and it can be solved. * Solves only this function, assuming that its children are already
* simplified and it can be solved.
*
* @return The solved function. * @return The solved function.
* @throws Error Errors during computation, like a/0 or similar. * @throws Error
* Errors during computation, like a/0 or similar.
*/ */
protected abstract ObjectArrayList<Function> solve() throws Error; protected abstract ObjectArrayList<Function> solve() throws Error;

View File

@ -7,9 +7,13 @@ import org.warp.picalculator.Error;
public abstract class FunctionSingle implements Function { public abstract class FunctionSingle implements Function {
/** /**
* Create a new instance of FunctionSingle. The Math Context will be the same of <strong>value</strong>'s. * Create a new instance of FunctionSingle. The Math Context will be the
* @throws NullPointerException when value is null. * same of <strong>value</strong>'s.
* @param value The parameter of this function. *
* @throws NullPointerException
* when value is null.
* @param value
* The parameter of this function.
*/ */
public FunctionSingle(Function value) throws NullPointerException { public FunctionSingle(Function value) throws NullPointerException {
mathContext = value.getMathContext(); mathContext = value.getMathContext();
@ -18,8 +22,11 @@ public abstract class FunctionSingle implements Function {
/** /**
* Create a new instance of FunctionSingle. * Create a new instance of FunctionSingle.
* @param mathContext Math Context *
* @param value The parameter of this function. * @param mathContext
* Math Context
* @param value
* The parameter of this function.
*/ */
public FunctionSingle(MathContext mathContext, Function value) { public FunctionSingle(MathContext mathContext, Function value) {
this.mathContext = mathContext; this.mathContext = mathContext;
@ -41,13 +48,15 @@ public abstract class FunctionSingle implements Function {
public Function getParameter() { public Function getParameter() {
return parameter; return parameter;
} }
/** /**
* *
* @param var Parameter. * @param var
* Parameter.
* @return A new instance of this function. * @return A new instance of this function.
*/ */
public FunctionSingle setParameter(Function value) { public FunctionSingle setParameter(Function value) {
FunctionSingle s = this.clone(); final FunctionSingle s = clone();
s.parameter = value; s.parameter = value;
return s; return s;
} }
@ -98,11 +107,13 @@ public abstract class FunctionSingle implements Function {
return result; return result;
} }
/** /**
* Solves only this function, assuming that its children are already simplified and it can be solved. * Solves only this function, assuming that its children are already
* simplified and it can be solved.
*
* @return The solved function. * @return The solved function.
* @throws Error Errors during computation, like a/0 or similar. * @throws Error
* Errors during computation, like a/0 or similar.
*/ */
protected abstract ObjectArrayList<Function> solve() throws Error; protected abstract ObjectArrayList<Function> solve() throws Error;
@ -112,8 +123,11 @@ public abstract class FunctionSingle implements Function {
} }
/** /**
* The current simplification status of this function, assuming that its children are already simplified. * The current simplification status of this function, assuming that its
* @return <strong>true</strong> if this function can be solved, otherwise <strong>false</strong>. * children are already simplified.
*
* @return <strong>true</strong> if this function can be solved, otherwise
* <strong>false</strong>.
*/ */
protected abstract boolean isSolvable(); protected abstract boolean isSolvable();

View File

@ -12,7 +12,7 @@ import org.warp.picalculator.math.functions.equations.Equation;
import org.warp.picalculator.math.functions.equations.EquationsSystem; import org.warp.picalculator.math.functions.equations.EquationsSystem;
import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
public class MathContext { public class MathContext {
@ -122,4 +122,17 @@ public class MathContext {
} }
}*/ }*/
@Override
@Deprecated
public MathContext clone() {
// MathContext mc = new MathContext();
// mc.angleMode = this.angleMode;
// mc.exactMode = this.exactMode;
// mc.f = this.f;
// mc.f2 = this.f2;
// mc.variablesValues = this.variablesValues;
// mc.resultsCount = this.resultsCount;
// return mc;
throw new NotImplementedException();
}
} }

View File

@ -27,7 +27,6 @@ public class MathematicalSymbols {
public static final char ARC_TANGENT = 'Ⓗ'; public static final char ARC_TANGENT = 'Ⓗ';
public static final char PI = 'π'; public static final char PI = 'π';
public static final char[] functionsNSN = new char[] { NTH_ROOT, POWER }; public static final char[] functionsNSN = new char[] { NTH_ROOT, POWER };
public static final char[] functionsSN = new char[] { SQUARE_ROOT, POWER_OF_TWO, MINUS, SINE, COSINE, TANGENT, ARC_SINE, ARC_COSINE, ARC_TANGENT }; public static final char[] functionsSN = new char[] { SQUARE_ROOT, POWER_OF_TWO, MINUS, SINE, COSINE, TANGENT, ARC_SINE, ARC_COSINE, ARC_TANGENT };

View File

@ -3,14 +3,9 @@ package org.warp.picalculator.math.functions;
import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import org.warp.picalculator.Error; import org.warp.picalculator.Error;
import org.warp.picalculator.Utils;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.gui.GraphicalElement;
import org.warp.picalculator.gui.graphicengine.cpu.CPUEngine;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionOperator; import org.warp.picalculator.math.FunctionOperator;
import org.warp.picalculator.math.MathematicalSymbols;
import org.warp.picalculator.math.rules.FractionsRule1; import org.warp.picalculator.math.rules.FractionsRule1;
import org.warp.picalculator.math.rules.FractionsRule11; import org.warp.picalculator.math.rules.FractionsRule11;
import org.warp.picalculator.math.rules.FractionsRule12; import org.warp.picalculator.math.rules.FractionsRule12;
@ -26,8 +21,8 @@ public class Division extends FunctionOperator {
@Override @Override
protected boolean isSolvable() { protected boolean isSolvable() {
Function variable1 = getParameter1(); final Function variable1 = getParameter1();
Function variable2 = getParameter2(); final Function variable2 = getParameter2();
if (FractionsRule1.compare(this)) { if (FractionsRule1.compare(this)) {
return true; return true;
} }
@ -50,7 +45,7 @@ public class Division extends FunctionOperator {
if (getMathContext().exactMode) { if (getMathContext().exactMode) {
try { try {
return ((Number) variable1).divide((Number) variable2).isInteger(); return ((Number) variable1).divide((Number) variable2).isInteger();
} catch (Error e) { } catch (final Error e) {
return false; return false;
} }
} else { } else {
@ -62,8 +57,8 @@ public class Division extends FunctionOperator {
@Override @Override
public ObjectArrayList<Function> solve() throws Error { public ObjectArrayList<Function> solve() throws Error {
Function variable1 = getParameter1(); final Function variable1 = getParameter1();
Function variable2 = getParameter2(); final Function variable2 = getParameter2();
ObjectArrayList<Function> result = new ObjectArrayList<>(); ObjectArrayList<Function> result = new ObjectArrayList<>();
if (FractionsRule1.compare(this)) { if (FractionsRule1.compare(this)) {
result = FractionsRule1.execute(this); result = FractionsRule1.execute(this);
@ -94,11 +89,11 @@ public class Division extends FunctionOperator {
@Override @Override
public FunctionOperator clone() { public FunctionOperator clone() {
return new Division(this.getMathContext(), this.getParameter1(), this.getParameter2()); return new Division(getMathContext(), getParameter1(), getParameter2());
} }
@Override @Override
public String toString() { public String toString() {
return "("+this.getParameter1()+")/("+this.getParameter2()+")"; return "(" + getParameter1() + ")/(" + getParameter2() + ")";
} }
} }

View File

@ -1,12 +1,7 @@
package org.warp.picalculator.math.functions; package org.warp.picalculator.math.functions;
import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import java.util.List;
import org.warp.picalculator.Error; import org.warp.picalculator.Error;
import org.warp.picalculator.Utils;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.gui.graphicengine.cpu.CPUEngine;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
@ -18,7 +13,6 @@ public class EmptyNumber implements Function {
private final MathContext root; private final MathContext root;
@Override @Override
public ObjectArrayList<Function> simplify() throws Error { public ObjectArrayList<Function> simplify() throws Error {
// TODO Auto-generated method stub // TODO Auto-generated method stub

View File

@ -12,7 +12,6 @@ import java.util.regex.Pattern;
import org.warp.picalculator.Error; import org.warp.picalculator.Error;
import org.warp.picalculator.Errors; import org.warp.picalculator.Errors;
import org.warp.picalculator.Utils; import org.warp.picalculator.Utils;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionDynamic; import org.warp.picalculator.math.FunctionDynamic;
@ -628,7 +627,7 @@ public class Expression extends FunctionDynamic {
public String toString() { public String toString() {
String s = "("; String s = "(";
if (functions.length > 0) { if (functions.length > 0) {
for (Function f : functions) { for (final Function f : functions) {
if (f == null) { if (f == null) {
s += "[null],"; s += "[null],";
} else { } else {

View File

@ -1,13 +1,7 @@
package org.warp.picalculator.math.functions; package org.warp.picalculator.math.functions;
import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import java.util.List;
import org.warp.picalculator.Error; import org.warp.picalculator.Error;
import org.warp.picalculator.Utils;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.gui.graphicengine.BinaryFont;
import org.warp.picalculator.gui.graphicengine.cpu.CPUEngine;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;

View File

@ -5,9 +5,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import org.warp.picalculator.Error; import org.warp.picalculator.Error;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionSingle;
import org.warp.picalculator.math.FunctionOperator; import org.warp.picalculator.math.FunctionOperator;
import org.warp.picalculator.math.MathematicalSymbols;
import org.warp.picalculator.math.rules.ExponentRule15; import org.warp.picalculator.math.rules.ExponentRule15;
import org.warp.picalculator.math.rules.ExponentRule16; import org.warp.picalculator.math.rules.ExponentRule16;
import org.warp.picalculator.math.rules.FractionsRule14; import org.warp.picalculator.math.rules.FractionsRule14;
@ -29,8 +27,8 @@ public class Multiplication extends FunctionOperator {
@Override @Override
protected boolean isSolvable() { protected boolean isSolvable() {
Function variable1 = getParameter1(); final Function variable1 = getParameter1();
Function variable2 = getParameter2(); final Function variable2 = getParameter2();
if (variable1 instanceof Number & variable2 instanceof Number) { if (variable1 instanceof Number & variable2 instanceof Number) {
return true; return true;
} }

View File

@ -4,13 +4,9 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import org.warp.picalculator.Error; import org.warp.picalculator.Error;
import org.warp.picalculator.Errors; import org.warp.picalculator.Errors;
import org.warp.picalculator.Utils;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.gui.graphicengine.cpu.CPUEngine;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionSingle; import org.warp.picalculator.math.FunctionSingle;
import org.warp.picalculator.math.MathematicalSymbols;
import org.warp.picalculator.math.rules.ExpandRule1; import org.warp.picalculator.math.rules.ExpandRule1;
import org.warp.picalculator.math.rules.ExpandRule5; import org.warp.picalculator.math.rules.ExpandRule5;

View File

@ -7,16 +7,11 @@ import java.util.LinkedList;
import java.util.List; import java.util.List;
import org.nevec.rjm.BigDecimalMath; import org.nevec.rjm.BigDecimalMath;
import org.nevec.rjm.BigIntegerMath;
import org.warp.picalculator.Error; import org.warp.picalculator.Error;
import org.warp.picalculator.Utils; import org.warp.picalculator.Utils;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.gui.graphicengine.BinaryFont;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
import com.rits.cloning.Cloner;
public class Number implements Function { public class Number implements Function {
private final MathContext root; private final MathContext root;
@ -123,9 +118,9 @@ public class Number implements Function {
public List<Function> simplify() throws Error { public List<Function> simplify() throws Error {
final List<Function> result = new ObjectArrayList<>(); final List<Function> result = new ObjectArrayList<>();
if (root.exactMode) { if (root.exactMode) {
Number divisor = new Number(root, BigInteger.TEN.pow(getNumberOfDecimalPlaces())); final Number divisor = new Number(root, BigInteger.TEN.pow(getNumberOfDecimalPlaces()));
Number numb = new Number(root, term.multiply(divisor.term)); final Number numb = new Number(root, term.multiply(divisor.term));
Division div = new Division(root, numb, divisor); final Division div = new Division(root, numb, divisor);
result.add(div); result.add(div);
} else { } else {
result.add(this); result.add(this);

View File

@ -6,7 +6,6 @@ import org.warp.picalculator.Error;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionOperator; import org.warp.picalculator.math.FunctionOperator;
import org.warp.picalculator.math.MathematicalSymbols;
import org.warp.picalculator.math.rules.ExponentRule1; import org.warp.picalculator.math.rules.ExponentRule1;
import org.warp.picalculator.math.rules.ExponentRule2; import org.warp.picalculator.math.rules.ExponentRule2;
import org.warp.picalculator.math.rules.ExponentRule3; import org.warp.picalculator.math.rules.ExponentRule3;

View File

@ -5,11 +5,9 @@ import java.math.BigInteger;
import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import org.warp.picalculator.Error; import org.warp.picalculator.Error;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionOperator; import org.warp.picalculator.math.FunctionOperator;
import org.warp.picalculator.math.MathematicalSymbols;
public class Root extends FunctionOperator { public class Root extends FunctionOperator {

View File

@ -4,11 +4,9 @@ import java.math.BigInteger;
import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import org.warp.picalculator.Error; import org.warp.picalculator.Error;
import org.warp.picalculator.Utils;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionSingle; import org.warp.picalculator.math.FunctionSingle;
import org.warp.picalculator.math.MathematicalSymbols;
public class RootSquare extends FunctionSingle { public class RootSquare extends FunctionSingle {

View File

@ -6,7 +6,6 @@ import org.warp.picalculator.Error;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionOperator; import org.warp.picalculator.math.FunctionOperator;
import org.warp.picalculator.math.MathematicalSymbols;
import org.warp.picalculator.math.rules.ExpandRule1; import org.warp.picalculator.math.rules.ExpandRule1;
import org.warp.picalculator.math.rules.ExpandRule5; import org.warp.picalculator.math.rules.ExpandRule5;
import org.warp.picalculator.math.rules.NumberRule3; import org.warp.picalculator.math.rules.NumberRule3;

View File

@ -5,12 +5,9 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import org.warp.picalculator.Error; import org.warp.picalculator.Error;
import org.warp.picalculator.Errors; import org.warp.picalculator.Errors;
import org.warp.picalculator.Utils;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionOperator; import org.warp.picalculator.math.FunctionOperator;
import org.warp.picalculator.math.MathematicalSymbols;
import org.warp.picalculator.math.rules.NumberRule3; import org.warp.picalculator.math.rules.NumberRule3;
import org.warp.picalculator.math.rules.NumberRule5; import org.warp.picalculator.math.rules.NumberRule5;
import org.warp.picalculator.math.rules.NumberRule7; import org.warp.picalculator.math.rules.NumberRule7;

View File

@ -4,13 +4,9 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import org.warp.picalculator.Error; import org.warp.picalculator.Error;
import org.warp.picalculator.Errors; import org.warp.picalculator.Errors;
import org.warp.picalculator.Utils;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.gui.graphicengine.cpu.CPUEngine;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionOperator; import org.warp.picalculator.math.FunctionOperator;
import org.warp.picalculator.math.MathematicalSymbols;
import org.warp.picalculator.math.rules.ExpandRule1; import org.warp.picalculator.math.rules.ExpandRule1;
import org.warp.picalculator.math.rules.NumberRule3; import org.warp.picalculator.math.rules.NumberRule3;
import org.warp.picalculator.math.rules.NumberRule4; import org.warp.picalculator.math.rules.NumberRule4;

View File

@ -3,9 +3,6 @@ package org.warp.picalculator.math.functions;
import java.util.List; import java.util.List;
import org.warp.picalculator.Error; import org.warp.picalculator.Error;
import org.warp.picalculator.Utils;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.gui.graphicengine.cpu.CPUEngine;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;

View File

@ -4,13 +4,9 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import java.util.List; import java.util.List;
import org.warp.picalculator.Error; import org.warp.picalculator.Error;
import org.warp.picalculator.Utils;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
import com.rits.cloning.Cloner;
public class Variable implements Function { public class Variable implements Function {
protected char var; protected char var;
@ -94,9 +90,7 @@ public class Variable implements Function {
} }
public static enum V_TYPE { public static enum V_TYPE {
KNOWN, KNOWN, UNKNOWN, SOLUTION
UNKNOWN,
SOLUTION
} }
@Override @Override

View File

@ -11,13 +11,10 @@ import org.warp.picalculator.Errors;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionOperator; import org.warp.picalculator.math.FunctionOperator;
import org.warp.picalculator.math.MathematicalSymbols;
import org.warp.picalculator.math.SolveMethod; import org.warp.picalculator.math.SolveMethod;
import org.warp.picalculator.math.functions.Number; import org.warp.picalculator.math.functions.Number;
import org.warp.picalculator.math.functions.Subtraction; import org.warp.picalculator.math.functions.Subtraction;
import com.rits.cloning.Cloner;
public class Equation extends FunctionOperator { public class Equation extends FunctionOperator {
public Equation(MathContext root, Function value1, Function value2) { public Equation(MathContext root, Function value1, Function value2) {
@ -81,8 +78,7 @@ public class Equation extends FunctionOperator {
@Override @Override
public Equation clone() { public Equation clone() {
final Cloner cloner = new Cloner(); return new Equation(mathContext, parameter1, parameter2);
return cloner.deepClone(this);
} }
@Override @Override

View File

@ -4,7 +4,6 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import java.util.List; import java.util.List;
import org.warp.picalculator.Error; import org.warp.picalculator.Error;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionDynamic; import org.warp.picalculator.math.FunctionDynamic;

View File

@ -1,14 +1,10 @@
package org.warp.picalculator.math.functions.equations; package org.warp.picalculator.math.functions.equations;
import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import java.util.List;
import org.warp.picalculator.Error; import org.warp.picalculator.Error;
import org.warp.picalculator.gui.DisplayManager;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionSingle; import org.warp.picalculator.math.FunctionSingle;
import org.warp.picalculator.math.MathematicalSymbols;
public class EquationsSystemPart extends FunctionSingle { public class EquationsSystemPart extends FunctionSingle {

View File

@ -6,7 +6,6 @@ import org.warp.picalculator.Error;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionSingle; import org.warp.picalculator.math.FunctionSingle;
import org.warp.picalculator.math.MathematicalSymbols;
public class ArcCosine extends FunctionSingle { public class ArcCosine extends FunctionSingle {

View File

@ -6,7 +6,6 @@ import org.warp.picalculator.Error;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionSingle; import org.warp.picalculator.math.FunctionSingle;
import org.warp.picalculator.math.MathematicalSymbols;
public class ArcSine extends FunctionSingle { public class ArcSine extends FunctionSingle {

View File

@ -6,7 +6,6 @@ import org.warp.picalculator.Error;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionSingle; import org.warp.picalculator.math.FunctionSingle;
import org.warp.picalculator.math.MathematicalSymbols;
public class ArcTangent extends FunctionSingle { public class ArcTangent extends FunctionSingle {

View File

@ -6,7 +6,6 @@ import org.warp.picalculator.Error;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionSingle; import org.warp.picalculator.math.FunctionSingle;
import org.warp.picalculator.math.MathematicalSymbols;
public class Cosine extends FunctionSingle { public class Cosine extends FunctionSingle {

View File

@ -8,7 +8,6 @@ import org.warp.picalculator.math.AngleMode;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionSingle; import org.warp.picalculator.math.FunctionSingle;
import org.warp.picalculator.math.MathematicalSymbols;
import org.warp.picalculator.math.functions.Number; import org.warp.picalculator.math.functions.Number;
public class Sine extends FunctionSingle { public class Sine extends FunctionSingle {

View File

@ -6,7 +6,6 @@ import org.warp.picalculator.Error;
import org.warp.picalculator.math.MathContext; import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionSingle; import org.warp.picalculator.math.FunctionSingle;
import org.warp.picalculator.math.MathematicalSymbols;
public class Tangent extends FunctionSingle { public class Tangent extends FunctionSingle {

View File

@ -1,11 +1,16 @@
package org.warp.picalculator.math.parser; package org.warp.picalculator.math.parser;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import org.warp.picalculator.Error; import org.warp.picalculator.Error;
import org.warp.picalculator.Errors; import org.warp.picalculator.Errors;
import org.warp.picalculator.gui.expression.Block; import org.warp.picalculator.gui.expression.Block;
import org.warp.picalculator.gui.expression.BlockChar; import org.warp.picalculator.gui.expression.BlockChar;
import org.warp.picalculator.gui.expression.BlockContainer; import org.warp.picalculator.gui.expression.BlockContainer;
import org.warp.picalculator.gui.expression.BlockDivision; import org.warp.picalculator.gui.expression.BlockDivision;
import org.warp.picalculator.gui.expression.containers.InputContainer;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.FunctionOperator; import org.warp.picalculator.math.FunctionOperator;
import org.warp.picalculator.math.FunctionSingle; import org.warp.picalculator.math.FunctionSingle;
@ -15,6 +20,8 @@ import org.warp.picalculator.math.functions.Number;
import org.warp.picalculator.math.functions.Subtraction; import org.warp.picalculator.math.functions.Subtraction;
import org.warp.picalculator.math.functions.Sum; import org.warp.picalculator.math.functions.Sum;
import org.warp.picalculator.math.functions.SumSubtraction; import org.warp.picalculator.math.functions.SumSubtraction;
import org.warp.picalculator.math.functions.Variable;
import org.warp.picalculator.math.functions.Variable.V_TYPE;
import org.warp.picalculator.math.functions.Division; import org.warp.picalculator.math.functions.Division;
import org.warp.picalculator.math.functions.Expression; import org.warp.picalculator.math.functions.Expression;
import org.warp.picalculator.math.functions.Multiplication; import org.warp.picalculator.math.functions.Multiplication;
@ -23,6 +30,7 @@ import org.warp.picalculator.math.parser.features.FeatureDivision;
import org.warp.picalculator.math.parser.features.FeatureMultiplication; import org.warp.picalculator.math.parser.features.FeatureMultiplication;
import org.warp.picalculator.math.parser.features.FeatureNumber; import org.warp.picalculator.math.parser.features.FeatureNumber;
import org.warp.picalculator.math.parser.features.FeatureSum; import org.warp.picalculator.math.parser.features.FeatureSum;
import org.warp.picalculator.math.parser.features.FeatureVariable;
import org.warp.picalculator.math.parser.features.interfaces.Feature; import org.warp.picalculator.math.parser.features.interfaces.Feature;
import org.warp.picalculator.math.parser.features.interfaces.FeatureDouble; import org.warp.picalculator.math.parser.features.interfaces.FeatureDouble;
@ -30,27 +38,67 @@ import com.sun.org.apache.xpath.internal.functions.Function2Args;
import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import it.unimi.dsi.fastutil.objects.ObjectListIterator; import it.unimi.dsi.fastutil.objects.ObjectListIterator;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
public class MathParser { public class MathParser {
public static Expression parseInput(MathContext context, BlockContainer root) throws Error { public static Expression parseInput(MathContext context, InputContainer c) throws Error {
Expression result; Expression result;
Function resultFunction = parseContainer(context, root); final Function resultFunction = parseContainer(context, c.getContent());
result = new Expression(context, resultFunction); result = new Expression(context, resultFunction);
return result; return result;
} }
private static Function parseContainer(final MathContext context, final BlockContainer container) throws Error { public static ObjectArrayList<Block> parseOutput(MathContext context, ObjectArrayList<Function> expr) {
final ObjectArrayList<Block> blocks = container.getContent(); final ObjectArrayList<Block> resultBlocks = new ObjectArrayList<>();
for (Function f : expr) {
resultBlocks.addAll(parseFunction(context, f));
}
return resultBlocks;
}
private static ObjectArrayList<Block> parseFunction(MathContext context, Function func) {
ObjectArrayList<Block> result = new ObjectArrayList<>();
if (func instanceof FunctionOperator) {
ObjectArrayList<Block> sub1 = parseFunction(context, func.getParameter(0));
ObjectArrayList<Block> sub2 = parseFunction(context, func.getParameter(1));
if (func instanceof Sum) {
result.addAll(sub1);
result.add(new BlockChar(MathematicalSymbols.SUM));
result.addAll(sub2);
return result;
}
}
if (func instanceof Number) {
Number numb = (Number) func;
BigDecimal decimal = numb.getTerm();
String numberString;
if (numb.isInteger()) {
BigInteger integ = decimal.toBigInteger();
numberString = integ.toString();
} else {
numberString = decimal.toPlainString();
}
for (char c : numberString.toCharArray()) {
result.add(new BlockChar(c));
}
return result;
}
throw new UnsupportedOperationException("Unknown function " + func.getClass().getSimpleName());
}
private static Function parseContainer(final MathContext context, final Iterable<Block> blocks) throws Error {
final ObjectArrayList<Feature> blockFeatures = new ObjectArrayList<>(); final ObjectArrayList<Feature> blockFeatures = new ObjectArrayList<>();
for (final Block block : blocks) { for (final Block block : blocks) {
Feature blockFeature = parseBlock(context, block); final Feature blockFeature = parseBlock(context, block);
blockFeatures.add(blockFeature); blockFeatures.add(blockFeature);
} }
Function result = joinFeatures(context, blockFeatures); final Function result = joinFeatures(context, blockFeatures);
return result; return result;
} }
@ -58,15 +106,15 @@ public class MathParser {
Feature result; Feature result;
int blockType = block.getClassID(); final int blockType = block.getClassID();
switch (blockType) { switch (blockType) {
case BlockChar.CLASS_ID: case BlockChar.CLASS_ID:
result = new FeatureChar(((BlockChar) block).getChar()); result = new FeatureChar(((BlockChar) block).getChar());
break; break;
case BlockDivision.CLASS_ID: case BlockDivision.CLASS_ID:
BlockDivision bd = (BlockDivision) block; final BlockDivision bd = (BlockDivision) block;
Function upper = parseContainer(context, bd.getUpperContainer()); final Function upper = parseContainer(context, bd.getUpperContainer().getContent());
Function lower = parseContainer(context, bd.getLowerContainer()); final Function lower = parseContainer(context, bd.getLowerContainer().getContent());
result = new FeatureDivision(upper, lower); result = new FeatureDivision(upper, lower);
break; break;
default: default:
@ -80,7 +128,7 @@ public class MathParser {
features = fixFeatures(context, features); features = fixFeatures(context, features);
ObjectArrayList<Function> process = makeFunctions(context, features); final ObjectArrayList<Function> process = makeFunctions(context, features);
fixStack(context, process); fixStack(context, process);
@ -97,7 +145,7 @@ public class MathParser {
ObjectListIterator<Function> stackIterator = process.listIterator(process.size()); ObjectListIterator<Function> stackIterator = process.listIterator(process.size());
Function lastElement = null; Function lastElement = null;
while (stackIterator.hasPrevious()) { while (stackIterator.hasPrevious()) {
Function f = stackIterator.previous(); final Function f = stackIterator.previous();
if (f instanceof FunctionSingle) { if (f instanceof FunctionSingle) {
if (((FunctionSingle) f).getParameter() == null) { if (((FunctionSingle) f).getParameter() == null) {
@ -115,17 +163,14 @@ public class MathParser {
//Phase 2 //Phase 2
stackIterator = process.listIterator(); stackIterator = process.listIterator();
while (stackIterator.hasNext()) { while (stackIterator.hasNext()) {
Function f = stackIterator.next(); final Function f = stackIterator.next();
final int curIndex = stackIterator.previousIndex(); final int curIndex = stackIterator.previousIndex();
if (f instanceof Multiplication || f instanceof Division) { if (f instanceof Multiplication || f instanceof Division) {
if (curIndex - 1 >= 0 && stackIterator.hasNext()) { if (curIndex - 1 >= 0 && stackIterator.hasNext()) {
Function next = process.get(curIndex+1); final Function next = process.get(curIndex + 1);
Function prev = process.get(curIndex-1); final Function prev = process.get(curIndex - 1);
stackIterator.set( stackIterator.set(f.setParameter(0, prev).setParameter(1, next));
f.setParameter(0, prev)
.setParameter(1, next)
);
process.remove(curIndex + 1); process.remove(curIndex + 1);
process.remove(curIndex - 1); process.remove(curIndex - 1);
} else { } else {
@ -139,17 +184,28 @@ public class MathParser {
//Phase 3 //Phase 3
stackIterator = process.listIterator(); stackIterator = process.listIterator();
while (stackIterator.hasNext()) { while (stackIterator.hasNext()) {
Function f = stackIterator.next(); final Function f = stackIterator.next();
final int curIndex = stackIterator.previousIndex();
if (f instanceof Sum || f instanceof Subtraction || f instanceof SumSubtraction) { if (f instanceof Sum || f instanceof Subtraction || f instanceof SumSubtraction) {
if (curIndex - 1 >= 0 && stackIterator.hasNext()) {
final Function next = process.get(curIndex + 1);
final Function prev = process.get(curIndex - 1);
stackIterator.set(f.setParameter(0, prev).setParameter(1, next));
process.remove(curIndex + 1);
process.remove(curIndex - 1);
} else {
if (f.getParameter(0) == null || f.getParameter(1) == null) {
throw new Error(Errors.MISSING_ARGUMENTS, "There is a function at the end without any argument specified.");
}
}
} }
} }
//Phase 4 //Phase 4
stackIterator = process.iterator(); stackIterator = process.iterator();
while (stackIterator.hasNext()) { while (stackIterator.hasNext()) {
Function f = stackIterator.next(); final Function f = stackIterator.next();
if (f instanceof Function2Args) { if (f instanceof Function2Args) {
@ -157,27 +213,37 @@ public class MathParser {
} }
} }
private static ObjectArrayList<Function> makeFunctions(MathContext context, ObjectArrayList<Feature> features) throws Error { private static ObjectArrayList<Function> makeFunctions(MathContext context, ObjectArrayList<Feature> features)
ObjectArrayList<Function> process = new ObjectArrayList<>(); throws Error {
final ObjectArrayList<Function> process = new ObjectArrayList<>();
for (Feature f : features) { for (final Feature f : features) {
if (f instanceof FeatureDivision) { if (f instanceof FeatureDivision) {
process.add(new Division(context, (Function) ((FeatureDouble) f).getChild1(), (Function) ((FeatureDouble) f).getChild2())); process.add(new Division(context, (Function) ((FeatureDouble) f).getChild1(), (Function) ((FeatureDouble) f).getChild2()));
} else if (f instanceof FeatureMultiplication) { } else if (f instanceof FeatureMultiplication) {
process.add(new Multiplication(context, (Function) ((FeatureDouble) f).getChild1(), (Function) ((FeatureDouble) f).getChild2())); process.add(new Multiplication(context, (Function) ((FeatureDouble) f).getChild1(), (Function) ((FeatureDouble) f).getChild2()));
} else if (f instanceof FeatureVariable) {
process.add(new Variable(context, ((FeatureVariable) f).ch, ((FeatureVariable) f).varType));
} else if (f instanceof FeatureSum) {
process.add(new Sum(context, (Function) ((FeatureDouble) f).getChild1(), (Function) ((FeatureDouble) f).getChild2()));
// } else if (f instanceof FeatureSubtraction) {
// process.add(new Subtraction(context, (Function) ((FeatureDouble) f).getChild1(), (Function) ((FeatureDouble) f).getChild2()));
// } else if (f instanceof FeatureSumSubtraction) {
// process.add(new SumSubtraction(context, (Function) ((FeatureDouble) f).getChild1(), (Function) ((FeatureDouble) f).getChild2()));
} else if (f instanceof FeatureNumber) { } else if (f instanceof FeatureNumber) {
process.add(new Number(context, ((FeatureNumber) f).getNumberString())); process.add(new Number(context, ((FeatureNumber) f).getNumberString()));
} else if (f instanceof FeatureChar) { } else if (f instanceof FeatureChar) {
//All the char features must have been changed already before //All the char features must have been changed already before
throw new Error(Errors.SYNTAX_ERROR, "\"" + f.getClass().getSimpleName().toString() + "\" can't be converted into a Function!"); throw new Error(Errors.SYNTAX_ERROR, "\"" + f.getClass().getSimpleName() + "\" can't be converted into a Function!");
} else { } else {
throw new Error(Errors.SYNTAX_ERROR, "\"" + f.getClass().getSimpleName().toString() + "\" can't be converted into a Function!"); throw new Error(Errors.SYNTAX_ERROR, "\"" + f.getClass().getSimpleName() + "\" can't be converted into a Function!");
} }
} }
return process; return process;
} }
private static ObjectArrayList<Feature> fixFeatures(final MathContext context, ObjectArrayList<Feature> features) throws Error { private static ObjectArrayList<Feature> fixFeatures(final MathContext context, ObjectArrayList<Feature> features)
throws Error {
features = fixMinuses(context, features); features = fixMinuses(context, features);
@ -190,14 +256,16 @@ public class MathParser {
/** /**
* Create function features from char features * Create function features from char features
*
* @param context * @param context
* @param features * @param features
* @return * @return
*/ */
private static ObjectArrayList<Feature> convertFunctionChars(MathContext context, ObjectArrayList<Feature> features) throws Error { private static ObjectArrayList<Feature> convertFunctionChars(MathContext context, ObjectArrayList<Feature> features)
ObjectArrayList<Feature> process = new ObjectArrayList<>(); throws Error {
final ObjectArrayList<Feature> process = new ObjectArrayList<>();
for (Feature f : features) { for (final Feature f : features) {
if (f instanceof FeatureChar) { if (f instanceof FeatureChar) {
final char featureChar = ((FeatureChar) f).ch; final char featureChar = ((FeatureChar) f).ch;
Feature result = null; Feature result = null;
@ -210,6 +278,14 @@ public class MathParser {
break; break;
} }
//TODO: Temporary solution. In near future Variables will be distint objects and they will have a color. So they will be no longer a BlockChar/FeatureChar
for (char var : MathematicalSymbols.variables) {
if ( featureChar == var) {
result = new FeatureVariable(featureChar, V_TYPE.UNKNOWN);
break;
}
}
if (result == null) { if (result == null) {
throw new Error(Errors.SYNTAX_ERROR, "Char " + featureChar + " isn't a known feature"); throw new Error(Errors.SYNTAX_ERROR, "Char " + featureChar + " isn't a known feature");
} }
@ -225,20 +301,21 @@ public class MathParser {
/** /**
* Make numbers [-][1][2][+][-][3] => [-12] * Make numbers [-][1][2][+][-][3] => [-12]
*
* @param context * @param context
* @param features * @param features
* @return * @return
*/ */
private static ObjectArrayList<Feature> makeNumbers(MathContext context, ObjectArrayList<Feature> features) { private static ObjectArrayList<Feature> makeNumbers(MathContext context, ObjectArrayList<Feature> features) {
ObjectArrayList<Feature> process = new ObjectArrayList<>(); final ObjectArrayList<Feature> process = new ObjectArrayList<>();
FeatureNumber numberBuffer = null; FeatureNumber numberBuffer = null;
for (Feature f : features) { for (final Feature f : features) {
if (f instanceof FeatureChar) { if (f instanceof FeatureChar) {
final FeatureChar bcf = (FeatureChar) f; final FeatureChar bcf = (FeatureChar) f;
final char[] numbers = MathematicalSymbols.numbers; final char[] numbers = MathematicalSymbols.numbers;
boolean isNumber = false; boolean isNumber = false;
for (char n : numbers) { for (final char n : numbers) {
if (bcf.ch == n) { if (bcf.ch == n) {
isNumber = true; isNumber = true;
break; break;
@ -270,23 +347,25 @@ public class MathParser {
/** /**
* Fix minuses [-][1][2][+][-][3][-][2] => [-][12][+][-][3][][2] * Fix minuses [-][1][2][+][-][3][-][2] => [-][12][+][-][3][][2]
*
* @param context * @param context
* @param features * @param features
* @return * @return
* @throws Error * @throws Error
*/ */
private static ObjectArrayList<Feature> fixMinuses(final MathContext context, ObjectArrayList<Feature> features) throws Error { private static ObjectArrayList<Feature> fixMinuses(final MathContext context, ObjectArrayList<Feature> features)
ObjectArrayList<Feature> process = new ObjectArrayList<>(); throws Error {
final ObjectArrayList<Feature> process = new ObjectArrayList<>();
Feature lastFeature = null; Feature lastFeature = null;
for (Feature f : features) { for (final Feature f : features) {
if (f instanceof FeatureChar && ((FeatureChar) f).ch == MathematicalSymbols.SUBTRACTION) { if (f instanceof FeatureChar && ((FeatureChar) f).ch == MathematicalSymbols.SUBTRACTION) {
boolean isNegativeOfNumber = false; boolean isNegativeOfNumber = false;
if (lastFeature == null) { if (lastFeature == null) {
isNegativeOfNumber = true; isNegativeOfNumber = true;
} else if (lastFeature instanceof FeatureChar) { } else if (lastFeature instanceof FeatureChar) {
FeatureChar lcf = (FeatureChar) lastFeature; final FeatureChar lcf = (FeatureChar) lastFeature;
final char[] operators = MathematicalSymbols.functionsNSN; final char[] operators = MathematicalSymbols.functionsNSN;
for (char operator : operators) { for (final char operator : operators) {
if (lcf.ch == operator) { if (lcf.ch == operator) {
isNegativeOfNumber = true; isNegativeOfNumber = true;
break; break;

View File

@ -0,0 +1,15 @@
package org.warp.picalculator.math.parser.features;
import org.warp.picalculator.math.functions.Variable.V_TYPE;
import org.warp.picalculator.math.parser.features.interfaces.Feature;
public class FeatureVariable extends FeatureChar {
public V_TYPE varType;
public FeatureVariable(char ch, V_TYPE varType) {
super(ch);
this.varType = varType;
}
}

View File

@ -1,4 +1,3 @@
package org.warp.picalculator.math.parser.features.interfaces; package org.warp.picalculator.math.parser.features.interfaces;
public interface FeatureBasic extends Feature { public interface FeatureBasic extends Feature {}
}

View File

@ -2,7 +2,10 @@ package org.warp.picalculator.math.parser.features.interfaces;
public interface FeatureDouble extends Feature { public interface FeatureDouble extends Feature {
public Object getChild1(); public Object getChild1();
public void setChild1(Object obj); public void setChild1(Object obj);
public Object getChild2(); public Object getChild2();
public void setChild2(Object obj); public void setChild2(Object obj);
} }

View File

@ -2,9 +2,14 @@ package org.warp.picalculator.math.parser.features.interfaces;
public interface FeatureMultiple extends Feature { public interface FeatureMultiple extends Feature {
public Object[] getChildren(); public Object[] getChildren();
public Object getChild(int index); public Object getChild(int index);
public int getChildCount(); public int getChildCount();
public void setChild(int index, Object obj); public void setChild(int index, Object obj);
public void setChildren(Object[] objs); public void setChildren(Object[] objs);
public void addChild(Object obj); public void addChild(Object obj);
} }

View File

@ -2,5 +2,6 @@ package org.warp.picalculator.math.parser.features.interfaces;
public interface FeatureSingle extends Feature { public interface FeatureSingle extends Feature {
public Object getChild(); public Object getChild();
public void setChild(Object obj); public void setChild(Object obj);
} }

View File

@ -7,7 +7,6 @@ import org.warp.picalculator.math.MathContext;
import org.warp.picalculator.math.Function; import org.warp.picalculator.math.Function;
import org.warp.picalculator.math.functions.Expression; import org.warp.picalculator.math.functions.Expression;
import org.warp.picalculator.math.functions.Multiplication; import org.warp.picalculator.math.functions.Multiplication;
import org.warp.picalculator.math.functions.Number;
import org.warp.picalculator.math.functions.Power; import org.warp.picalculator.math.functions.Power;
/** /**

View File

@ -39,7 +39,7 @@ public class FractionsRule11 {
Function b; Function b;
Function c; Function c;
Division div2 = (Division) fnc.getParameter2(); final Division div2 = (Division) fnc.getParameter2();
a = fnc.getParameter1(); a = fnc.getParameter1();
b = div2.getParameter1(); b = div2.getParameter1();

View File

@ -38,7 +38,6 @@ public class VariableRule2 {
final Function a = m1.getParameter1(); final Function a = m1.getParameter1();
final Function x = fnc.getParameter2(); final Function x = fnc.getParameter2();
FunctionOperator rets; FunctionOperator rets;
if (fnc instanceof Sum) { if (fnc instanceof Sum) {
rets = new Sum(root, a, new Number(root, 1)); rets = new Sum(root, a, new Number(root, 1));