code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
package hr.fer.anna.tests.uniform;
import java.util.Random;
import hr.fer.anna.exceptions.IllegalActionException;
import hr.fer.anna.exceptions.SimulationException;
import hr.fer.anna.exceptions.UnknownAddressException;
import hr.fer.anna.interfaces.IInternalDebugger;
import hr.fer.anna.model.Word;
import hr.fer.anna.simulator.Simulator;
import hr.fer.anna.uniform.Address;
import hr.fer.anna.uniform.Constant;
import hr.fer.anna.uniform.SimpleMemory;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Testira SimpleMemory - jednostavnu memoriju
* @author Boran
*
*/
public class SimpleMemoryTest {
/**
* Memorija koju testiramo
*/
private SimpleMemory memory;
/**
* Sabirnica koja nam služi za testiranje
*/
private BusForTesting busForTesting;
/**
* Veličina memorije (u riječima)
*/
private static int MEMORY_SIZE = 1024;
/**
* Širina riječi memorije
*/
private static int WORD_WIDTH = 8;
/**
* Broj testova po slučaju testiranja
*/
private static int NUMBER_OF_TESTS = 84000;
/**
* Simulator koji obavlja simulaciju
*/
private Simulator simulator;
/**
* Generator slučajnih brojeva
*/
private Random random;
/**
* Testira odašiljanje IllegalActionExceptiona prilikom obavljanja operacija gdje
* se očekuje ta iznimka.
*/
private static IInternalDebugger acceptOnlyIllegalActionException = new IInternalDebugger() {
public boolean reportException(SimulationException simulationException) {
Assert.assertEquals("Nedopuštena iznimka!", IllegalActionException.class, simulationException.getClass());
return false;
}
};
/**
* Proglašava test neuspjelim ako se dogodi ikakva iznimka tokom simulacije.
*/
private static IInternalDebugger noAllowedExceptions = new IInternalDebugger() {
public boolean reportException(SimulationException simulationException) {
Assert.fail("Nedopuštena iznimka: " + simulationException.getMessage());
return false;
}
};
/**
* Inicijalizira sve potrebno za pojedini test
*
*/
@Before
public void init() {
this.simulator = new Simulator();
this.memory = new SimpleMemory(MEMORY_SIZE, WORD_WIDTH);
this.simulator.registerEventListener(this.memory);
this.simulator.registerEventSetter(this.memory);
this.random = new Random();
this.busForTesting = new BusForTesting();
this.busForTesting.setExpectedBusUnit(this.memory);
}
/**
* Testira pisanje i čitanje memorije tako što zapisuje pojedini podatak i kasnije
* ga čita iz memorije.
*/
@Test
public void testReadWrite() {
for (int i = 0; i < NUMBER_OF_TESTS; i++) {
Address address = Address.fromWord(new Constant(random.nextInt(MEMORY_SIZE)));
Word word = new Constant((byte)(random.nextInt() & 0xFF));
busForTesting.setExpectedAddress(address);
busForTesting.setExpectedWord(word);
try {
this.memory.requestWrite(busForTesting, address, word);
} catch (IllegalActionException ignorable) {
} catch (UnknownAddressException ignorable) {
}
simulator.run();
try {
this.memory.requestRead(busForTesting, address);
} catch (IllegalActionException ignorable) {
} catch (UnknownAddressException ignorable) {
}
simulator.run();
}
}
/**
* Provjerava ograničenje pristupa memoriji koja već obavlja neku operaciju.
*
*/
@Test
public void testAccessingBusy() throws IllegalActionException {
this.simulator.setInternalDebugger(acceptOnlyIllegalActionException);
try {
this.memory.requestRead(busForTesting, Address.fromWord(new Constant(random.nextInt(1024))));
this.memory.requestRead(busForTesting, Address.fromWord(new Constant(random.nextInt(1024))));
this.memory.requestRead(busForTesting, Address.fromWord(new Constant(random.nextInt(1024))));
this.simulator.run();
} catch (UnknownAddressException ignorable) {
}
}
/**
* Testira čitanje proizvoljnih adresa
*
*/
@Test
public void testReadRandomAddress() {
this.simulator.setInternalDebugger(noAllowedExceptions);
for (int i = 0; i < NUMBER_OF_TESTS; i++) {
try {
Address address = Address.fromWord(new Constant(random.nextInt(1024)));
busForTesting.setExpectedAddress(address);
busForTesting.setExpectedWord(null);
this.memory.requestRead(busForTesting, address);
} catch (Exception e) {
Assert.fail("Dogodila se greška: " + e.getMessage());
}
this.simulator.run();
}
}
}
| Java |
package hr.fer.anna.tests.uniform;
import hr.fer.anna.model.Word;
import hr.fer.anna.uniform.Constant;
import java.util.Random;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Testira klasu konstanata
* @author Boran
*
*/
public class ConstantTest {
/** Broj testova */
private static final int NUM_OF_TEST = 0;
/** Generator slučajnih brojeva */
private Random random;
/**
* Inicijalizacija
*/
@Before
public void init() {
this.random = new Random();
}
/**
* Testira ispravno zapisivanje konstanata kao riječi
*/
@Test
public void testData() {
int i;
for (i = 0; i < NUM_OF_TEST; i++) {
byte a = (byte)(random.nextInt() & 0x7F);
Word word = new Constant(a);
Assert.assertEquals("Zapisi nisu jednaki!", a, Byte.parseByte(word.getHexString(), 16));
}
for (i = 0; i < NUM_OF_TEST; i++) {
int a = random.nextInt() & 0x7FFFFFFF;
Word word = new Constant(a);
Assert.assertEquals("Zapisi nisu jednaki!", a, Integer.parseInt(word.getHexString(), 16));
}
for (i = 0; i < NUM_OF_TEST; i++) {
long a = random.nextLong() & 0x7FFFFFFFFFFFFFFFL;
Word word = new Constant(a);
Assert.assertEquals("Zapisi nisu jednaki!", a, Long.parseLong(word.getHexString(), 16));
}
}
}
| Java |
package hr.fer.anna.tests.uniform;
import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.Assert;
import hr.fer.anna.exceptions.IllegalActionException;
import hr.fer.anna.exceptions.UnknownAddressException;
import hr.fer.anna.interfaces.IBus;
import hr.fer.anna.interfaces.IBusUnit;
import hr.fer.anna.model.Word;
import hr.fer.anna.uniform.Address;
/**
* Klasa vanjske jedinice koja se koristi za testiranje.
* @author boran
*
*/
public class BusUnitForTesting implements IBusUnit {
/**
* Adresa za koju očekujemo da će joj sabirnica pristupiti.
*/
private Address expectedAddress;
/**
* Broj lokalnih adresa ove jedinice.
*/
private int localAddresses;
/**
* Da li jedinica treba odgovoriti na zahtjev? True ako da, false inače.
*/
private boolean doCallback;
/**
* Adresabilno spremište podataka.
*/
private Map<Address, Word> data;
/**
* Konstruktor koji stvara vanjsku jedinicu zadanog raspona lokalnih adresa
* @param localAddresses raspon (broj) lokalnih adresa
*/
public BusUnitForTesting(int localAddresses) {
this.localAddresses = localAddresses;
this.data = new LinkedHashMap<Address, Word>(localAddresses);
}
public int getLocalAddresses() {
return this.localAddresses;
}
public boolean isBusy() {
return false;
}
public void requestRead(IBus bus, Address localAddress)
throws IllegalActionException, UnknownAddressException {
Assert.assertEquals("Krivoj adresi se pristupa!", this.expectedAddress, localAddress);
if (this.doCallback) {
if (!data.containsKey(localAddress)) {
data.put(localAddress, new Word());
}
bus.busUnitReadCallback(this, localAddress, data.get(localAddress));
}
}
public void requestWrite(IBus bus, Address localAddress, Word word)
throws IllegalActionException, UnknownAddressException {
Assert.assertEquals("Krivoj adresi se pristupa!", this.expectedAddress, localAddress);
if (this.doCallback) {
if (!data.containsKey(localAddress)) {
data.put(localAddress, new Word());
}
data.get(localAddress).set(word);
bus.busUnitWriteCallback(this, localAddress);
}
}
/**
* Postavlja da li jedinica treba odgovoriti na zahtjeve sabirnice
* @param state true ako treba, false inače
*/
public void setDoCallback(boolean state) {
this.doCallback = state;
}
/**
* Postavlja lokalnu adresu koju očekujemo da nam sabirnica mapira.
* @param expectedAddress lokalna adresa (na jedinici)
*/
public void setExpectedAddress(Address expectedAddress) {
this.expectedAddress = expectedAddress;
}
}
| Java |
package hr.fer.anna.tests.uniform;
import hr.fer.anna.uniform.Constant;
import hr.fer.anna.uniform.Register;
import org.junit.Assert;
import org.junit.Test;
/**
* Testovi registara
*
* @author Boran
*
*/
public class RegisterTest {
/**
* Testira postavljanje bitova unutar registra
*/
@Test
public void runSetBitTest() {
Register reg = new Register(64);
long value = 1;
for (int index = 0; index < 64; value = 2*value, index++) {
reg.setBit(index, true);
Assert.assertEquals("Neispravno postavljanje bitova! Bit na poziciji " + index + " nije postavljen!", Long.toHexString(value).toUpperCase(), reg.getHexString().toUpperCase());
reg.setBit(index, false);
}
}
/**
* Testira dohvaćanje bita unutar registra
*/
@Test
public void runGetBitTest() {
Register reg = new Register(64);
long value = 1;
for (int index = 0; index < 64; value = 2*value, index++) {
reg.set(new Constant(value));
Assert.assertEquals("Neispravno dohvaćanje bitova! Bit na poziciji " + index + " nije postavljen!", true, reg.getBit(index));
for (int others = 0; others < 64; others++) {
if (others != index) {
Assert.assertEquals("Neispravno dohvaćanje bitova! Bit na poziciji " + others + " ne smije biti postavljen!", false, reg.getBit(others));
}
}
}
}
}
| Java |
package hr.fer.anna.tests.uniform;
import java.util.Random;
import hr.fer.anna.exceptions.IllegalActionException;
import hr.fer.anna.exceptions.UnknownAddressException;
import hr.fer.anna.model.Word;
import hr.fer.anna.uniform.Address;
import hr.fer.anna.uniform.Constant;
import hr.fer.anna.uniform.PlainBus;
import org.junit.Before;
import org.junit.Test;
/**
* Testovi obične sabirnice (PlainBus)
* @author Boran
*
*/
public class PlainBusTest {
/** Broj vanjskih jedinica koje će se spojit i testirat */
private static final int NUM_OF_UNITS = 4;
/** Broj testova za svaku vanjsku jedinicu */
private static final int NUM_OF_TESTS = 1000;
/** Sabirnica koju testiramo */
private PlainBus plainBus;
/** Generator slučajnih brojeva */
private Random random;
/** Upravljač sabirnice kojeg koristimo radi testiranja */
private BusMasterForTesting busMaster;
@Before
public void init() {
this.random = new Random();
this.plainBus = new PlainBus();
this.busMaster = new BusMasterForTesting();
}
/**
* Testira da li bus ispravno mappira globalne adrese na lokalne adrese jedinice
* kojoj treba pristupiti.
*
*/
@Test
public void testUnitMapping() throws Exception {
int startAddress = 0;
for (int i = 0; i < NUM_OF_UNITS; i++) {
int addressSpaceSize = random.nextInt(256) + 1;
BusUnitForTesting busUnit = new BusUnitForTesting(addressSpaceSize);
busUnit.setDoCallback(true);
this.plainBus.registerBusUnit(busUnit, Address.fromWord(new Constant(startAddress)));
for (int j = 0; j < NUM_OF_TESTS; j++) {
int expectedLocalAddress = random.nextInt(addressSpaceSize);
busUnit.setExpectedAddress(Address.fromWord((new Constant(expectedLocalAddress))));
this.plainBus.requestRead(busMaster, Address.fromWord(new Constant(startAddress + expectedLocalAddress)));
}
startAddress += addressSpaceSize;
}
}
/**
* Testira da li bus ispravno dojavljuje da je zauzet. Dojavlivanje se vrši prikladnom iznimkom.
*
*/
@Test(expected = IllegalActionException.class)
public void testBusBusy() throws Exception {
int startAddress = 0;
for (int i = 0; i < NUM_OF_UNITS; i++) {
int addressSpaceSize = random.nextInt(256) + 1;
BusUnitForTesting busUnit = new BusUnitForTesting(addressSpaceSize);
this.plainBus.registerBusUnit(busUnit, Address.fromWord(new Constant(startAddress)));
for (int j = 0; j < NUM_OF_TESTS; j++) {
int expectedLocalAddress = random.nextInt(addressSpaceSize);
busUnit.setExpectedAddress(Address.fromWord((new Constant(expectedLocalAddress))));
this.plainBus.requestRead(busMaster, Address.fromWord(new Constant(startAddress + expectedLocalAddress)));
}
startAddress += addressSpaceSize;
}
}
/**
* Testira pristupanje još nepoznatim adresama (adresama na koje nije mappirana nijedna jedinica još)
*
*/
@Test(expected = UnknownAddressException.class)
public void testBusUnknownAddress() throws Exception {
this.plainBus.requestRead(busMaster, Address.fromWord(new Constant(random.nextInt())));
}
/**
* Testira pisanje po sabirnice, zatim čitanje sa sabirnice. Metoda zapravo
* testira transparentnost sabirnice pri prosljeđivanju podataka.
*/
@Test
public void testBusWriteRead() throws Exception {
int startAddress = 0;
for (int i = 0; i < NUM_OF_UNITS; i++) {
int addressSpaceSize = random.nextInt(256) + 1;
BusUnitForTesting busUnit = new BusUnitForTesting(addressSpaceSize);
busUnit.setDoCallback(true);
this.plainBus.registerBusUnit(busUnit, Address.fromWord(new Constant(startAddress)));
for (int j = 0; j < NUM_OF_TESTS; j++) {
int expectedLocalAddress = random.nextInt(addressSpaceSize);
Word expectedWord = new Constant(random.nextInt());
busUnit.setExpectedAddress(Address.fromWord((new Constant(expectedLocalAddress))));
busMaster.setExpectedAddress(Address.fromWord(new Constant(startAddress + expectedLocalAddress)));
this.plainBus.requestWrite(busMaster, Address.fromWord(new Constant(startAddress + expectedLocalAddress)), expectedWord);
busMaster.setExpecetedWord(expectedWord);
this.plainBus.requestRead(busMaster, Address.fromWord(new Constant(startAddress + expectedLocalAddress)));
}
startAddress += addressSpaceSize;
}
}
}
| Java |
package hr.fer.anna.tests.frisc;
import java.io.File;
import java.io.FileNotFoundException;
import hr.fer.anna.exceptions.SyntaxError;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Ivan
*
*/
public class AssemblerTest {
// /**
// * Asembliranje jednostavnog jednolinijskog koda.
// *
// * @throws SyntaxError
// */
// @Test
// public void assembleTest01() throws SyntaxError {
// String code = "\tADD R7, R2, R1";
// byte[] assembled = Assembler.assemble(code);
// byte[] ispravno = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0xf4,
// (byte) 0x20 };
//
// Assert.assertEquals(new ByteArray(ispravno), new ByteArray(assembled));
// }
//
// /**
// * Asembliranje jednolinijskog koda uz dodatak komentara i višestrukih
// * tabova.
// *
// * @throws SyntaxError
// */
// @Test
// public void assembleTest02() throws SyntaxError {
// String code = "\tADD R7, R2, R1\t\t \t; komentar\tkk da";
// byte[] assembled = Assembler.assemble(code);
// byte[] ispravno = intToByteArray(0x20F40000);
//
// Assert.assertEquals(new ByteArray(ispravno), new ByteArray(assembled));
// }
//
// /**
// * Asembliranje dvolinijskog koda uz dodatak komentara i višestrukih tabova.
// *
// * @throws SyntaxError
// */
// @Test
// public void assembleTest03() throws SyntaxError {
// String code = "\tADD R7, R2, R1\t\t \t; komentar\tkk da\n"
// + "\tADD r1, %D 123,r1;kom .\n";
// byte[] assembled = Assembler.assemble(code);
// ByteArray ispravno = new ByteArray(intToByteArray(0x20F40000));
// ispravno.append(intToByteArray(0x2490007B));
//
// Assert.assertEquals(ispravno, new ByteArray(assembled));
// }
//
// /**
// * Asembliranje dvolinijskog koda uz dodatak komentara, višestrukih tabova
// * te praznog reda i reda koji se sastoji samo od komentara.
// *
// * @throws SyntaxError
// */
// @Test
// public void assembleTest04() throws SyntaxError {
// String code = "\tADD R7, R2, R1\t\t \t; komentar\tkk da\n"
// + "\n"
// + "\t;blah\n"
// + "\tADD r1, %D 123,r1;kom .\n";
// byte[] assembled = Assembler.assemble(code);
// ByteArray ispravno = new ByteArray(intToByteArray(0x20F40000));
// ispravno.append(intToByteArray(0x2490007B));
//
// Assert.assertEquals(ispravno, new ByteArray(assembled));
// }
//
// /**
// * Provjera baza konstanti (%H|D|O|B oznaka).
// *
// * @throws SyntaxError
// */
// @Test
// public void assembleTest05() throws SyntaxError {
// String code = "\tADD r1, %D 123,r1;kom .\n"
// + "\tADD r1, %H 123,r1;kom .\n"
// + "\tADD r1, %B 1010,r1;kom .\n"
// + "\tADD r1, %O 123,r1;kom .\n";
// byte[] assembled = Assembler.assemble(code);
// ByteArray ispravno = new ByteArray(intToByteArray(0x2490007B));
// ispravno.append(intToByteArray(0x24900123));
// ispravno.append(intToByteArray(0x2490000A));
// ispravno.append(intToByteArray(0x24900053));
//
// Assert.assertEquals(ispravno, new ByteArray(assembled));
// }
//
// /**
// * Provjera baza konstanti (%H|D|O|B oznaka + `BASE pseudonaredba).
// *
// * @throws SyntaxError
// */
// @Test
// public void assembleTest06() throws SyntaxError {
// String code = "\tADD r1, %D 123,r1;kom .\n"
// + "\tADD r1, 123,r1;kom .\n"
// + "\t`Base B\n"
// + "\tADD r1, 1010,r1;kom .\n"
// + "\t`Base O\n"
// + "\tADD r1, 123,r1;kom .\n"
// + "\tADD r1, 124,r1;kom .\n";
//
// byte[] assembled = Assembler.assemble(code);
// ByteArray ispravno = new ByteArray(intToByteArray(0x2490007B));
// ispravno.append(intToByteArray(0x24900123));
// ispravno.append(intToByteArray(0x2490000A));
// ispravno.append(intToByteArray(0x24900053));
// ispravno.append(intToByteArray(0x24900054));
//
// Assert.assertEquals(ispravno, new ByteArray(assembled));
// }
//
// /**
// * Ispitivanje labela. EQU + naredba.
// *
// * @throws SyntaxError
// */
// @Test
// public void assembleTest07() throws SyntaxError {
// String code = "LBL `EQU\t%D 123\n"
// + "\tADD r1, LBL,r1;kom .\n";
// byte[] assembled = Assembler.assemble(code);
// ByteArray ispravno = new ByteArray(intToByteArray(0x2490007B));
//
// Assert.assertEquals(ispravno, new ByteArray(assembled));
// }
//
// /**
// * Ispitivanje pseudonaredbi `ORG i DW.
// *
// * @throws SyntaxError
// */
// @Test
// public void assembleTest08() throws SyntaxError {
// String code = "\t DW 1\n"
// + "\t`ORG 8\n"
// + "\tDW 15;kom .";
// byte[] assembled = Assembler.assemble(code);
// ByteArray ispravno = new ByteArray(intToByteArray(1));
// ispravno.append(intToByteArray(0));
// ispravno.append(intToByteArray(0x15));
//
// Assert.assertEquals(ispravno, new ByteArray(assembled));
// }
//
// /**
// * Finalni test 01: 1. labos iz ARH1, vj. 1
// *
// * @throws SyntaxError
// * @throws FileNotFoundException
// */
// @Test
// public void assembleTest09() throws SyntaxError, FileNotFoundException {
// //byte[] assembled =
// Assembler.assemble(new File("tests-data/frisc-assembler/ik42696_lab1_vj1.a"));
//// ByteArray ispravno = new ByteArray(intToByteArray(1));
//// ispravno.append(intToByteArray(0));
//// ispravno.append(intToByteArray(0x15));
////
//// Assert.assertEquals(ispravno, new ByteArray(assembled));
// }
//
// /**
// * Prebacivanje integera u niz byteova.
// *
// * @param num Broj koji želimo rastaviti na byteove.
// * @return Niz byteova dobivenih rastavljanjem predatog broja.
// */
// private byte[] intToByteArray(int num) {
// return new byte[] { (byte) (num & 0xFF), (byte) ((num >> 8) & 0xFF),
// (byte) ((num >> 16) & 0xFF), (byte) ((num >> 24) & 0xFF) };
// }
//
// /**
// * Klasa za maskiranje byte[] tipa podataka radi usporedbe jednakosti.
// */
// private class ByteArray {
// /** Osnovni niz. */
// byte[] array;
//
// /**
// * Konstruktor.
// *
// * @param array Niz koji maskiramo.
// */
// public ByteArray(byte[] array) {
// this.array = array;
// }
//
// /**
// * Metoda za uspoređivanje.
// */
// @Override
// public boolean equals(Object obj) {
// if (!(obj instanceof ByteArray))
// return false;
//
// ByteArray ba = (ByteArray) obj;
// try {
// for (int i = 0; i < this.array.length; i++) {
// if (ba.array[i] != this.array[i])
// return false;
// }
// } catch (IndexOutOfBoundsException e) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
//// int num = 0;
//// int pomak = 0;
//
// for (int i = 0; i < array.length; i++) {
// sb.append(array[i] + "-");
//// num |= (array[i] << pomak) & (0xFF << pomak);
//// pomak += 8;
//// if (pomak == 32) {
//// pomak = 0;
//// sb.append(Integer.toHexString(num));
//// num = 0;
//// }
// }
//
//// if (array.length % 4 != 0) {
//// sb.append(Integer.toHexString(num));
//// }
//
// return sb.toString();
// }
//
// public byte[] append(byte[] dodatni) {
// byte[] novi = new byte[this.array.length + dodatni.length];
//
// for (int i = 0; i < this.array.length; i++) {
// novi[i] = this.array[i];
// }
//
// for (int i = this.array.length; i < this.array.length
// + dodatni.length; i++) {
// novi[i] = dodatni[i - this.array.length];
// }
//
// this.array = novi;
// return this.array;
// }
//
// /**
// * Getter arraya.
// *
// * @return Array sa podatcima.
// */
// public byte[] getArray() {
// return this.array;
// }
// }
}
| Java |
package hr.fer.anna.tests.model;
import java.util.Random;
import hr.fer.anna.model.Word;
import hr.fer.anna.uniform.Constant;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Testovi elementarne riječi
* @author Boran
*
*/
public class WordTest {
/** Broj numeričkih testova (zbrajanje, oduzimanje, ...) */
private static final int NUM_OF_NUMERIC_TESTS = 1000;
/** Generator pseudo-slučajnih brojeva */
private Random random;
/**
* Inicijalizacija (generator slučajnih brojeva, ...)
*/
@Before
public void init() {
this.random = new Random();
}
/**
* Provjerava ispitivanje jednakosti 2 riječi
*/
@Test
public void testEquals() {
Word wordA = new Constant(16);
Word wordB = new Constant(16);
Assert.assertEquals("Riječi trebaju biti jednake!", true, wordA.equals(wordB));
wordA = new Constant(15600);
wordB = new Constant(15600);
Assert.assertEquals("Riječi trebaju biti jednake!", true, wordA.equals(wordB));
wordA = new Constant(32600);
wordB = new Constant(15600);
Assert.assertEquals("Riječi ne smiju biti jednake!", false, wordA.equals(wordB));
}
/**
* Provjerava ispravnost metode getHexString kao i sam zapis vrijednosti
* unutar riječi
*/
@Test
public void testHexString() {
for (int i = 0; i < NUM_OF_NUMERIC_TESTS; i++) {
long a = random.nextLong();
Word wordA = new Constant(a);
Assert.assertEquals("Zapis ili getHexString() nije dobro implementiran!", Long.toHexString(a).toUpperCase(), wordA.getHexString().toUpperCase());
}
}
/**
* Testira postavljanje riječi
*
*/
@Test
public void testSet() {
for (int i = 0; i < NUM_OF_NUMERIC_TESTS; i++) {
long a = random.nextLong();
Word expected = new Constant(a);
Word actual = new Word(expected.getWidth());
actual.set(expected);
Assert.assertEquals("Postavljanje nije dobro implementirano!", expected, actual);
}
}
/**
* Testira operaciju zbrajanja riječi
*/
@Test
public void testAdd() {
for (int i = 0; i < NUM_OF_NUMERIC_TESTS; i++) {
long a = random.nextLong() & 0x3FFFFFFFFFFFFFFFL;
long b = random.nextLong() & 0x3FFFFFFFFFFFFFFFL;
Word wordA = new Constant(a);
Word wordB = new Constant(b);
Word actual = Word.add(wordA, wordB);
Word expected = new Constant(a+b);
Assert.assertEquals("Zbrojevi nisu jednaki!", expected, actual);
}
}
/**
* Testira operaciju oduzimanja riječi
*/
@Test
public void testSub() {
for (int i = 0; i < NUM_OF_NUMERIC_TESTS; i++) {
long a = random.nextLong() & 0x3FFFFFFFFFFFFFFFL;
long b = random.nextLong() & 0x3FFFFFFFFFFFFFFFL;
Word wordA = new Constant(a);
Word wordB = new Constant(b);
Word actual = Word.sub(wordA, wordB);
Word expected = new Constant(a-b);
Assert.assertEquals("Razlike nisu jednaki!", expected, actual);
}
}
/**
* Testira operaciju posmicanja ulijevo
*/
@Test
public void testShiftLeft() {
int i;
System.out.println("8-bit tests:");
for (i = 0; i < NUM_OF_NUMERIC_TESTS; i++) {
byte a = (byte) (random.nextInt() & 0x0F);
int loc = random.nextInt() & 0x07;
Word wordA = new Constant(a);
Word actual = Word.shiftLeft(wordA, loc);
Word expected = new Constant((byte)((a & 0xFF) << loc));
System.out.println(Integer.toHexString(a) + " << " + loc);
Assert.assertEquals("Posmak ulijevo nije dobro implementiran!", expected, actual);
}
System.out.println("32-bit tests:");
for (i = 0; i < NUM_OF_NUMERIC_TESTS; i++) {
int a = random.nextInt();
int loc = random.nextInt() & 0x1F;
Word wordA = new Constant(a);
Word actual = Word.shiftLeft(wordA, loc);
Word expected = new Constant((a << loc));
System.out.println(Integer.toHexString(a) + " << " + loc);
Assert.assertEquals("Posmak ulijevo nije dobro implementiran!", expected, actual);
}
System.out.println("64-bit tests:");
for (i = 0; i < NUM_OF_NUMERIC_TESTS; i++) {
long a = random.nextLong();
int loc = random.nextInt() & 0x3F;
Word wordA = new Constant(a);
Word actual = Word.shiftLeft(wordA, loc);
Word expected = new Constant((long)(a << loc));
System.out.println(Long.toHexString(a) + " << " + loc);
Assert.assertEquals("Posmak ulijevo nije dobro implementiran!", expected, actual);
}
}
/**
* Testira operaciju posmicanja udesno
*/
@Test
public void testShiftRight() {
int i;
System.out.println("8-bit tests:");
for (i = 0; i < NUM_OF_NUMERIC_TESTS; i++) {
byte a = (byte) (random.nextInt() & 0x0F);
int loc = random.nextInt() & 0x07;
Word wordA = new Constant(a);
Word actual = Word.shiftRight(wordA, loc);
Word expected = new Constant((byte)(a >>> loc));
System.out.println(Integer.toHexString(a) + " >> " + loc);
Assert.assertEquals("Posmak udesno nije dobro implementiran!", expected, actual);
}
System.out.println("32-bit tests:");
for (i = 0; i < NUM_OF_NUMERIC_TESTS; i++) {
int a = random.nextInt();
int loc = random.nextInt() & 0x1F;
Word wordA = new Constant(a);
Word actual = Word.shiftRight(wordA, loc);
Word expected = new Constant((int)(a >>> loc));
System.out.println(Integer.toHexString(a) + " >> " + loc);
Assert.assertEquals("Posmak udesno nije dobro implementiran!", expected, actual);
}
System.out.println("64-bit tests:");
for (i = 0; i < NUM_OF_NUMERIC_TESTS; i++) {
long a = random.nextLong();
int loc = random.nextInt() & 0x3F;
Word wordA = new Constant(a);
Word actual = Word.shiftRight(wordA, loc);
Word expected = new Constant((long)(a >>> loc));
System.out.println(Long.toHexString(a) + " >> " + loc);
Assert.assertEquals("Posmak udesno nije dobro implementiran!", expected, actual);
}
}
/**
* Testira invertiranje (logički not)
*/
@Test
public void testInvert() {
for (int i = 0; i < NUM_OF_NUMERIC_TESTS; i++) {
long a = random.nextLong();
Word wordA = new Constant(a);
Word actual = Word.not(wordA);
Word expected = new Constant(~a);
Assert.assertEquals("NOT operacija nije dobro implementirana!", expected, actual);
}
}
/**
* Testira provođenje ostalih logičkih operacija (xor, or, and)
*/
@Test
public void testLogical() {
for (int i = 0; i < NUM_OF_NUMERIC_TESTS; i++) {
long a = random.nextLong();
long b = random.nextLong();
Word wordA = new Constant(a);
Word wordB = new Constant(b);
Word actual = Word.xor(wordA, wordB);
Word expected = new Constant(a ^ b);
Assert.assertEquals("XOR operacija nije dobro implementirana!", expected, actual);
actual = Word.or(wordA, wordB);
expected = new Constant(a | b);
Assert.assertEquals("OR operacija nije dobro implementirana!", expected, actual);
actual = Word.and(wordA, wordB);
expected = new Constant(a & b);
Assert.assertEquals("AND operacija nije dobro implementirana!", expected, actual);
}
}
}
| Java |
package hr.fer.anna.interfaces;
import hr.fer.anna.model.UnitReport;
import hr.fer.anna.simulator.Simulator;
/**
* Sučelje komponenti koje mogu postaviti evente simulatoru.
*/
public interface IEventSetter {
/**
* Inicijaliziranje postavki (usklađivanje vremenskog pomaka, postavljanje poč. evenata)
* za simulator sim.
*
* @param sim Simulator na koji se pripremamo.
*/
public void init(Simulator sim);
/**
* Dohvat opisa komponente.
*
* @return Opis komponente.
*/
public UnitReport describe();
}
| Java |
package hr.fer.anna.interfaces;
import hr.fer.anna.exceptions.IllegalActionException;
import hr.fer.anna.exceptions.UnknownAddressException;
import hr.fer.anna.model.Word;
import hr.fer.anna.uniform.Address;
/**
* Sučelje memorijskog modela. Svaka kontrola koja sadržava veću količinu memorijskog
* prostora u sebi i ne želi mappirati registre može koristiti memorijski model.
*/
public interface IMemoryModel {
/**
* Registrira novog slušača promjene memorijskog modela.
* @param watcher slušač
*/
public void registerWatcher(IMemoryModelWatcher watcher);
/**
* Odregistrira slušača promjene memorijskog modela.
* @param watcher slušač
*/
public void unregisterWatcher(IMemoryModelWatcher watcher);
/**
* Zapisuje zadanu riječ na zadanu adresu memorijskog spremišta.
* @param word riječ
* @param address adresa
* @throws UnknownAddressException u slučaju da ne postoji zadana adresa
* @throws IllegalActionException u slučaju da nije moguće pisati po zadanoj adresi
*/
public void write(Word word, Address address) throws UnknownAddressException, IllegalActionException;
/**
* Zapisuje slijedno više riječi počevši od zadane početne adrese
* @param words riječi
* @param address početna adresa
* @throws UnknownAddressException u slučaju da neka od adresa ne postoji
* @throws IllegalActionException u slučaju da nije moguće zapisati na neku adresu
*/
public void write(Word[] words, Address address) throws UnknownAddressException, IllegalActionException;
/**
* Čita riječ sa zadane adrese memorijskog spremišta
* @param address adresa
* @return riječ koje se nalazi na zadanoj adresi
* @throws UnknownAddressException u slučaju da ne postoji zadana adresa
* @throws IllegalActionException u slučaju da nije moguće čitati zadanu adresu
*/
public Word read(Address address) throws UnknownAddressException, IllegalActionException;
}
| Java |
package hr.fer.anna.interfaces;
import hr.fer.anna.model.Word;
import hr.fer.anna.uniform.Address;
/**
* Komponente koje čitaju sa sabirnice moraju implementirati ovo sučelje jer ovo sučelje sadrži
* povratnu vezu i metode za sinkronizirano čitanje.
* @author Boran
*/
public interface IBusMaster {
/**
* Sabirnica ovom metodom postavlja čekanje upravljaču sve dok opet nije u stanju
* prihvaćati zahtjeve upravljača.
*
* @param bus sabirnica koja postavlja čekanje, obično <code>this</code>
* @param state true za postavljanje čekanja, false za isključivanje čekanja
*/
public void waitBus(IBus bus, boolean state);
/**
* Sabirnica ovom metodom dojavljuje završetak čitanja i vraća pročitanu riječ.
*
* @param bus sabirnica koja javlja završetak, obično <code>this</code>
* @param globalAddress adresa s koje se čitalo
* @param word pročitana riječ
*/
public void busReadCallback(IBus bus, Address globalAddress, Word word);
/**
* Sabirnica ovom metodom dojavljuje završetak pisanja.
*
* @param bus sabirnica koja javlja završetak, obično <code>this</code>
* @param globalAddress adresa na koju se pisalo
*/
public void busWriteCallback(IBus bus, Address globalAddress);
}
| Java |
package hr.fer.anna.interfaces;
import hr.fer.anna.exceptions.BusAddressTaken;
import hr.fer.anna.exceptions.IllegalActionException;
import hr.fer.anna.exceptions.UnknownAddressException;
import hr.fer.anna.model.Word;
import hr.fer.anna.uniform.Address;
/**
* Sučelje sabirnice.
* @author Boran
*
*/
public interface IBus {
/**
* Registriranje jedinica s kojih sabirnica čita podatke i na koje sabirnica
* piše podatke.
*
* @param busUnit jedinica koju treba registrirati
* @param startAddress zahtjevana početna adresa jedinice
*
* @throws UnknownAddressException Ukoliko na sabirnici ne postoji adresa na koju bi se preslikala neka od lokalnih adresa jedinice
*
* @throws BusAddressTaken Ukoliko je na sabirnici već zauzeta neka od adresa na koju bi se jedinica preslikala.
*/
public void registerBusUnit(IBusUnit busUnit, Address startAddress) throws UnknownAddressException, BusAddressTaken;
/**
* Postavljanje zahtjeva za pisanje na sabirnicu.
*
* @param busMaster upravljač sabirnice koji postavlja zahtjev, obično <code>this</code>
* @param globalAddress adresa (na sabirnici) na koju se želi pisati
* @param word riječ koja se želi upisati
*
* @throws UnknownAddressException Ukoliko adresa ne postoji na sabirnici.
* @throws IllegalActionException Ukoliko nije moguće pisati na traženu adressu.
*/
public void requestWrite(IBusMaster busMaster, Address globalAddress, Word word) throws UnknownAddressException, IllegalActionException;
/**
* Postavljanje zahtjeva za čitanjem sa sabirnice.
*
* @param busMaster upravljač sabirnice koji postavlja ovaj zahjev, obično <code>this</code>
* @param globalAddress adresa (na sabirnici) s koje se želi čitati
*
* @throws UnknownAddressException Ukoliko adresa na postoji na sabirnici.
* @throws IllegalActionException Ukoliko nije moguće čitati s tražene adrese.
*/
public void requestRead(IBusMaster busMaster, Address globalAddress) throws UnknownAddressException, IllegalActionException;
/**
* Dojava sabirnici da je završeno upisivanje na jedinicu.
*
* @param busUnit jedinica koja dojavljuje završetak, obično <code>this</code>
* @param localAddress lokalna adresa na jedinici
*/
public void busUnitWriteCallback(IBusUnit busUnit, Address localAddress);
/**
* Dojava sabirnici da je završeno čitanje i slanje sabirnici pročitane riječi.
*
* @param busUnit jedinica koja dojavljuje završetak, obično <code>this</code>
* @param localAddress lokalna adresa na jedinici
* @param word pročitana riječ
*/
public void busUnitReadCallback(IBusUnit busUnit, Address localAddress, Word word);
/**
* Da li je trenutno sabirnica zauzeta, da li izvršava neku akciju čitanja ili pisanja sa neke
* jedinice.
*
* @return true ako je bus zauzet, false inače
*/
public boolean isBusy();
/**
* Dohvaća trenutnog upravljača ovom sabirnicom.
*
* @return upravljač sabirnice
*/
public IBusMaster getBusMaster();
/**
* Postavlja novog upravljača ovom sabirnicom.
*
* @param newBusMaster novi upravljač sabirnice
*
* @throws IllegalActionException Ako je sabirnica zauzeta ili ako ju trenutni upravljač ne želi pustiti.
*/
public void setBusMaster(IBusMaster newBusMaster) throws IllegalActionException;
}
| Java |
package hr.fer.anna.interfaces;
public interface IProcessor {
/**
* Zaustavljanje upravljačke jedinice.
*/
void halt();
/**
* Resetira procesor
*/
void reset();
}
| Java |
package hr.fer.anna.interfaces;
import hr.fer.anna.events.SimulationEvent;
import hr.fer.anna.exceptions.SimulationException;
/**
* Sučelje komponenti koje mogu slušati i reagirati na eventove.
* @author Boran
*
*/
public interface IEventListener {
/**
* Metoda koja implementira djelovanje komponente na zaprimljeni event.
* @param event zaprimljeni event
* @throws SimulationException u slučaju greške prilikom obrade eventa
*/
public void act(SimulationEvent event) throws SimulationException;
/**
* Metoda koja vraća eventove koji interesiraju ovog slušača.
*/
public SimulationEvent[] getEvents();
}
| Java |
package hr.fer.anna.interfaces;
import hr.fer.anna.model.Word;
import hr.fer.anna.uniform.Address;
/**
* Pratitelj promjena memorijskog modela. Kao promjena memorijskog modela smatra
* se promjena jedne od riječi koje sadržava memorijski model.
* @author Boran
*
*/
public interface IMemoryModelWatcher {
/**
* Dojavljuje promjenu modela slušaču.
* @param model memorijski model koji se promijenio
* @param address adresa na kojoj se dogodila promjena
* @param word nova riječ na lokaciji
*/
public void update(IMemoryModel model, Address address, Word word);
}
| Java |
package hr.fer.anna.interfaces;
import hr.fer.anna.uniform.Register;
import java.util.List;
/**
* Sučelje dekodera instrukcija koji primljenu instrukciju pretvara u mikroinstrukcije
* koje svi procesori koji se koriste mikroinstrukcijskim paketom znaju izvršavati.
* @author Boran
*
*/
public interface IInstructionDecoder {
/**
* Dekodira instrukciju zapisanu u instrukcijskom registru u mikroinstrukcije.
* @param instructionRegister instrukcijski registar
* @return lista mikroinstrukcija koje su ekvivalentne instrukciji u instrukcijskom registru
*/
public List<IMicroinstruction> decode(Register instructionRegister);
}
| Java |
package hr.fer.anna.interfaces;
import hr.fer.anna.model.Word;
/**
* Sučelje razreda koji prikazuje promjene neke riječi.
*
* @author Boran
*
*/
public interface IWordChangeListener {
/**
* Dojava promjene modela.
*
* @param word Riječ koja se prati.
*/
public void update(Word word);
}
| Java |
package hr.fer.anna.interfaces;
import hr.fer.anna.exceptions.IllegalActionException;
import hr.fer.anna.exceptions.UnknownAddressException;
import hr.fer.anna.model.Word;
import hr.fer.anna.uniform.Address;
/**
* Sučelje sklopa s kojeg sabirnica čita podatke i na koji se preko sabirnice
* podatci pišu.
*/
public interface IBusUnit {
/**
* Veličina adresabilnog prostora jedinice.
*
* @return broj lokacija kojima se može pristupati (čitati ili pisati).
*/
public int getLocalAddresses();
/**
* Postavljanje zahtjeva jedinici na sabirnici za pisanje 1 riječi
*
* @param bus sabirnica koja postavlja zahtjev, uobičajeno <code>this</code>
* @param localAddress lokalna adresa (adresa na jedinici)
* @param word riječ koju želimo upisati
*
* @throws IllegalActionException
* Ukoliko se riječ ne može upisati.
* @throws UnknownAddressException
* Ukoliko ne postoji <code>localAddress</code> na jedinici.
*/
public void requestWrite(IBus bus, Address localAddress, Word word) throws IllegalActionException, UnknownAddressException;
/**
* Postavljanje zahtjeva za čitanje 1 riječi sa jedinice na sabirnici.
*
* @param bus sabrnici koja postavlja zahtjev, uobičajeno <code>this</code>
* @param localAddress lokalna adresa (adresa na jedinici)
*
* @throws IllegalActionException
* Ukoliko nije moguće pročitati riječ.
* @throws UnknownAddressException
* Ukoliko ne postoji <code>localAddress</code> na jedinici.
*/
public void requestRead(IBus bus, Address localAddress) throws IllegalActionException, UnknownAddressException;
/**
* Ispituje da li je vanjska jedinica zauzeta. Zauzeta vanjska jedinica ne može primati više operacija.
*
* @return true ako je zauzeta, false inače
*/
public boolean isBusy();
}
| Java |
package hr.fer.anna.interfaces;
import hr.fer.anna.exceptions.SimulationException;
/**
* Debugger koji mora moći primiti sve iznimke koje se mogu dogoditi tokom simulacije.
* Preko ovog sučelja debugger može zaustaviti simulaciju ako procijeni da se simulator
* ne može oporaviti.
* @author Boran
*
*/
public interface IInternalDebugger {
/**
* Prijavljuje iznimku debuggeru. Debugger uzvraća da li se simulacija može nastaviti
* ili je treba prekinuti.
*
* @param simulationException iznimka koja se dogodila tokom simulacije
* @return true ako se simulacija može nastaviti, false inače
*/
public boolean reportException(SimulationException simulationException);
}
| Java |
package hr.fer.anna.interfaces;
/**
* Sučelje registra koji čuva zastavice.
* @author Boran
*
*/
public interface IFlagsRegister {
public void setCarry(boolean state);
public boolean getCarry();
public void setZero(boolean state);
public boolean getZero();
public void setOverflow(boolean state);
public boolean getOverflow();
public void setNegative();
public boolean getNegative();
public void setPositive();
public boolean getPositive();
/**
* Briše sve zastavice osim negative ili positive koje su uvijek definirane kao komplement
* jedna drugoj. Kod njih briše onu primarnu koja je definirana, a druga poprima komplementarnu
* vrijednost.
*/
public void clear();
}
| Java |
package hr.fer.anna.interfaces;
import hr.fer.anna.exceptions.MicrocodeException;
/**
* Općenita klasa mikroinstrukcije koju procesorska jezgra izvršava. Mikroinstrukcije su
* namijenene kao pomoć pri dizajnu procesora. Rade samo interno unutar procesorske jezgre
* i svaka mikroinstrukcija se mora izvršiti unutar jednog ciklusa. Rezultati mikroinstrukcija
* su trenutno vidljivi osim ako nije drukčije napomenuto.
* @author Boran
*
*/
public interface IMicroinstruction {
/**
* Izvršava mikroinstrukciju. Rezultati su trenutno vidljivi nakon uspješnog završetka
* ove metode osim ako nije drukčije napomenuto. Povratna vrijednost označava da li
* smo stvorili nekakav hazard zbog čeka treba pričekati i izvesti ostale mikroinstrukcije
* tek nakon što se hazard riješi.
*
* @return true ako se dogodio hazard, false inače
*
* @throws MicrocodeException u slučaju nekakve greške prilikom izvođenja mikroinstrukcije
*/
public boolean execute() throws MicrocodeException;
}
| Java |
package hr.fer.anna.exceptions;
/**
* Iznimka koja se baca u slučaju kada se pokušava raditi nešto što nije dopušteno. Primjer
* je čitanje s lokacije koja ne podržava čitanje, pisanje u lokaciju koja ne podržava pisanja
* ili pristupanje zauzetoj komponenti.
* @author Boran
*
*/
public class IllegalActionException extends SimulationException {
private static final long serialVersionUID = 1L;
public IllegalActionException(String msg) {
super(msg);
}
}
| Java |
package hr.fer.anna.exceptions;
/**
* Iznimka koja se baca kada se pokuša preslikati nova vanjska jedinica na neku od adresa
* koja je već pridjeljenja nekoj drugoj jedinici.
* @author Boran
*
*/
public class BusAddressTaken extends Exception {
private static final long serialVersionUID = 1L;
public BusAddressTaken(String errorMsg) {
super(errorMsg);
}
}
| Java |
package hr.fer.anna.exceptions;
/**
* Klasa koja predstavlja općenitu iznimku koja se može javiti pri simulaciji. Od ove klase
* se deriviraju sve ostale klase iznimaka koje se mogu dogoditi pri simulaciji.
* @author Boran
*
*/
public class SimulationException extends Exception {
private static final long serialVersionUID = 1L;
/**
* Defaultni konstruktor iznimke.
*/
public SimulationException() {
}
/**
* Konstruktor iznimke kojemu se može predati tekstualni opis iznimke.
* @param message tekstulani opis
*/
public SimulationException(String message) {
super(message);
}
/**
* Konstruktor iznimke kojemu se može predati uzrok i tekstualni opis iznimke.
* @param message tekstulani opis
* @param cause uzrok iznimke
*/
public SimulationException(String message, Exception cause) {
super(message, cause);
}
}
| Java |
package hr.fer.anna.exceptions;
/**
* Iznimka za slučaj kada ne postoji adresa kojoj se želi pristupati.
* @author Boran
*
*/
public class UnknownAddressException extends SimulationException {
private static final long serialVersionUID = 1L;
public UnknownAddressException(String msg) {
super(msg);
}
}
| Java |
package hr.fer.anna.exceptions;
public class SyntaxError extends Exception {
private static final long serialVersionUID = 1L;
/**
* Konstruktor koji prima tekstulano objašnjenje iznimke.
* @param message tekst iznimke
*/
public SyntaxError(String message) {
super(message);
}
/**
* Konstruktor koji prima tekstulano objašnjenje i uzrok iznimke
* @param message tekst iznimke
* @param cause uzrok
*/
public SyntaxError(String message, SimulationException cause) {
super(message, cause);
}
@Override
public String toString() {
return getMessage();
}
}
| Java |
package hr.fer.anna.exceptions;
/**
* Klasa općenite iznimke koja se može dogoditi prilikom izvođenja mikroinstrukcije.
* @author Boran
*
*/
public class MicrocodeException extends Exception {
private static final long serialVersionUID = 1L;
/**
* Konstruktor koji prima tekstulano objašnjenje iznimke.
* @param message tekst iznimke
*/
public MicrocodeException(String message) {
super(message);
}
/**
* Konstruktor koji prima tekstulano objašnjenje i uzrok iznimke
* @param message tekst iznimke
* @param cause uzrok
*/
public MicrocodeException(String message, SimulationException cause) {
super(message, cause);
}
}
| Java |
package hr.fer.anna.exceptions;
// TODO: Neka netko komentira ovo, inače ću špatulom ovo izbrisati :P
public class InvalidRequest extends SimulationException {
private static final long serialVersionUID = 1L;
public InvalidRequest(String msg) {
super(msg);
}
}
| Java |
package hr.fer.anna.microcode;
import hr.fer.anna.exceptions.MicrocodeException;
import hr.fer.anna.exceptions.SimulationException;
import hr.fer.anna.interfaces.IBus;
import hr.fer.anna.interfaces.IBusMaster;
import hr.fer.anna.interfaces.IMicroinstruction;
import hr.fer.anna.model.Word;
import hr.fer.anna.uniform.Address;
/**
* Mikroinstrukcija spremanja na sabirnicu. Za ovu mikroinstrukciju se ne može garantirati
* da će rezultat biti trenutno vidljiv, čak se ne može garantirati niti vidljivost rezultata
* u istom ciklusu. Potreban je stoga oprez prilikom korištenja ove mikroinstrukcije.
* @author Boran
*
*/
public class StoreMicroinstruction implements IMicroinstruction {
/** Upravljač sabirnice koji izvršava ovu mikroinstrukciju (čita podatke) */
private IBusMaster busMaster;
/** Riječ iz koje se zapisuju podaci */
private Word dataWord;
/** Bus na koji se zapisuju podaci */
private IBus bus;
/** Riječ koja sadrži adresu */
private Word addressWord;
/**
* Stvara novu mikroinstrukciju spremanja na adresu na sabirnici podatkovne riječi
* @param busMaster upravljač sabirnicom koji želi čitati, obično <code>this</code>
* @param dataWord podatkovna riječ
* @param bus sabirnica
* @param addressWord riječ koja sadrži adresu
*/
public StoreMicroinstruction(IBusMaster busMaster, Word dataWord, IBus bus, Word addressWord) {
this.busMaster = busMaster;
this.dataWord = dataWord;
this.bus = bus;
this.addressWord = addressWord;
}
/**
* Izvršava ovu mikroinstrukciju tako da spremi na određenu adresu na sabirnici podatak
* koji se nalazi u podatkovnom registru. Svi ovi parametri su zadani prilikom stvaranja
* instance ove mikroinstrukcije. Nije moguće garantirati vidljive rezultate niti trenutno
* niti unutar trenutnog ciklusa.
*
* @return true hazard se događa
*
* @throws MicrocodeException u slučaju greške prilikom obavljanja mikroinstrukcije
*/
public boolean execute() throws MicrocodeException {
try {
this.bus.requestWrite(busMaster, Address.fromWord(addressWord), dataWord);
} catch (SimulationException e) {
throw new MicrocodeException("Pisanje na sabirnicu nije uspjelo!", e);
}
return true;
}
}
| Java |
package hr.fer.anna.microcode;
import hr.fer.anna.exceptions.MicrocodeException;
import hr.fer.anna.interfaces.IFlagsRegister;
import hr.fer.anna.interfaces.IMicroinstruction;
/**
* Mikroinstrukcija uvjetnog izvođenja mikroinstrukcije koju omotava. Ova mikroinstrukcija
* provjerava uvjete i ako su uvjeti zadovoljeni, izvodi omotanu mikroinstrukciju. Uvjeti
* su stanja zastavica.
* @author Boran
*
*/
public class ConditionalMicroinstruction implements IMicroinstruction {
/** Da li testiramo zastavicu negative/positive */
private boolean testNegative;
/** Da li testiramo zastavicu zero */
private boolean testZero;
/** Da li testiramo zastavicu carry */
private boolean testCarry;
/** Da li testiramo zastavicu overflow */
private boolean testOverflow;
/** Tražena vrijednost negative zastavice */
private boolean negative;
/** Tražena vrijednost zero zastavice */
private boolean zero;
/** Tražena vrijednost carry zastavice */
private boolean carry;
/** Tražena vrijednost overflow zastavice */
private boolean overflow;
/** Registar zastavica unutar kojeg se provjeravaju uvjeti */
private IFlagsRegister flagsRegister;
/** Začahurena mikroinstrukcija koja se izvršava samo ako su zadovoljeni uvjeti */
private IMicroinstruction encapsulated;
/**
* Stvara mikroinstrukciju uvjetnog izvođenja koja izvodi omotanu mikroinstrukciju
* ako su zadovoljeni uvjeti stanja registra zastavica. Nakon stvaranja objekta nije
* postavljen niti jedan uvjet i treba ih dodatno postaviti metodama test...
* @param flagsRegister registar zastavica koje se ispituju
* @param encapsulated omotana mikroinstrukcija koja se treba izvesti ako su zadovoljeni uvjeti
*/
public ConditionalMicroinstruction(IFlagsRegister flagsRegister, IMicroinstruction encapsulated) {
super();
this.testNegative = false;
this.testZero = false;
this.testCarry = false;
this.testOverflow = false;
this.flagsRegister = flagsRegister;
this.encapsulated = encapsulated;
}
/**
* Mikroinstrukcija će izvesti omotanu mikroinstrukciju ako je zastavica zero
* postavljena u traženo stanje stanje.
* @param status traženo stanje zero zastavice
* @return trenutna mikroinstrukcija
*/
public ConditionalMicroinstruction testZero(boolean status) {
this.testZero = true;
this.zero = status;
return this;
}
/**
* Mikroinstrukcija će izvesti omotanu mikroinstrukciju ako je zastavica carry
* postavljena u traženo stanje stanje.
* @param status traženo stanje carry zastavice
* @return trenutna mikroinstrukcija
*/
public ConditionalMicroinstruction testCarry(boolean status) {
this.testCarry = true;
this.carry = status;
return this;
}
/**
* Mikroinstrukcija će izvesti omotanu mikroinstrukciju ako je zastavica negative
* postavljena u traženo stanje stanje.
* @param status traženo stanje negative zastavice
* @return trenutna mikroinstrukcija
*/
public ConditionalMicroinstruction testNegative(boolean status) {
this.testNegative = true;
this.negative = status;
return this;
}
/**
* Mikroinstrukcija će izvesti omotanu mikroinstrukciju ako je zastavica overflow
* postavljena u traženo stanje stanje.
* @param status traženo stanje overflow zastavice
* @return trenutna mikroinstrukcija
*/
public ConditionalMicroinstruction testOverflow(boolean status) {
this.testOverflow = true;
this.overflow = status;
return this;
}
/**
* Mikroinstrukcija se izvodi tako da se izvodi omotana mikroinstrukcija ako su
* zadovoljena stanja zastavica postavljena u konstruktoru, inače se izvela samo provjera uvjeta.
*
* @return stanje hazarda ovisi o omotanoj mikroinstrukciji
*
* @throws MicrocodeException u slučaju nekakve greške
*/
public boolean execute() throws MicrocodeException {
if(testNegative && flagsRegister.getNegative() != negative ||
testZero && flagsRegister.getZero() != zero ||
testCarry && flagsRegister.getCarry() != carry ||
testOverflow && flagsRegister.getOverflow() != overflow) {
return false;
}
return encapsulated.execute();
}
/**
* Računa virtualnu zastavicu greater iz zastavica flags registra.
*
* @return true ako bi virtualna zastavica greater bila postavljena nakon
* ALU operacije, false inače
*/
protected boolean getGreater() {
// (N XOR V) = 0 AND Z = 0
boolean N, V, Z;
N = flagsRegister.getNegative();
V = flagsRegister.getOverflow();
Z = flagsRegister.getZero();
return !(N ^ V) && !Z;
}
/**
* Računa virtualnu zastavicu less iz zastavica flags registra.
*
* @return true ako bi virtualna zastavica less bila postavljena nakon ALU
* operacije, false inače
*/
protected boolean getLess() {
// (N XOR V) = 1
boolean N, V;
N = flagsRegister.getNegative();
V = flagsRegister.getOverflow();
return N ^ V;
}
/**
* Računa virtualnu zastavicu equal iz zastavica flags registra.
*
* @return true ako bi virtualna zastavca equal bila postavljena nakon ALU
* operacije, false inače
*/
protected boolean getEqual() {
// Z = 1
boolean Z;
Z = flagsRegister.getZero();
return Z;
}
}
| Java |
package hr.fer.anna.microcode;
import hr.fer.anna.interfaces.IFlagsRegister;
import hr.fer.anna.model.Word;
import hr.fer.anna.uniform.Register;
/**
* Mikroinstrukcija aritmetičke operacije oduzimanja. Ova mikroinstrukcije prvo briše
* registar zastavica, a zatim postavlja zastavice ovisno o rezultatu operacije oduzimanja.
* @author Boran
*
*/
// Oduzimanje je samo poseban slučaj zbrajanja
public class SubtractMicroinstruction extends AddMicroinstruction {
/**
* Stvara novu mikroinstrukciju koja oduzima od vrijednosti predanog registra vrijednost
* unutar drugog predanog registra i rezultat sprema u odredišni registar.
* @param regDest odredišni registar
* @param Word registar od čije vrijednost oduzimamo
* @param Word registra čiju vrijednost oduzimamo
* @param flagsRegister registar zastavica koji treba osvježiti nakon obavljene operacije
*/
public SubtractMicroinstruction(Register regDest, Word wordA, Word wordB, IFlagsRegister flagsRegister) {
super(regDest, wordA, wordB, flagsRegister);
super.subtract = true;
}
}
| Java |
package hr.fer.anna.microcode;
import hr.fer.anna.interfaces.IFlagsRegister;
import hr.fer.anna.interfaces.IMicroinstruction;
import hr.fer.anna.model.Word;
import hr.fer.anna.uniform.Register;
public abstract class GenericLogicMicroinstruction implements IMicroinstruction {
/** Prvi operand */
protected Word wordA;
/** Drugi operand */
protected Word wordB;
/** Rezultat */
protected Register regRes;
/** Registar zastavica */
protected IFlagsRegister flags;
/**
* Stvara novu mikroinstrukciju općenite logičke operacije nad 2 registra
* @param wordA prvi operand
* @param wordB drugi operand
* @param regRes rezultat
* @param flags zastavice
*/
public GenericLogicMicroinstruction(Word wordA, Word wordB, Register regRes, IFlagsRegister flags) {
this.wordA = wordA;
this.wordB = wordB;
this.regRes = regRes;
this.flags = flags;
}
}
| Java |
package hr.fer.anna.microcode;
import hr.fer.anna.interfaces.IFlagsRegister;
import hr.fer.anna.interfaces.IMicroinstruction;
import hr.fer.anna.uniform.Register;
/**
* Metode koje služe za implementiranje mikroinstrukcija posmaka i rotacije.
* Metode su generičke i za upotrebu ih je potrebno omotati u wrapper.
* @author Boran
*
*/
public abstract class GenericShiftMicroinstruction implements IMicroinstruction {
/** Registar unutar kojeg će se odviti općenito posmicanje */
protected Register reg;
/** Registar zastavica */
protected IFlagsRegister flags;
/**
* Stvara novu mikroinstrukciju općenitog posmaka.
* @param reg registar unutar kojeg treba obaviti posmak
* @param flags registar zastavica koji treba osvježiti
*/
public GenericShiftMicroinstruction(Register reg, IFlagsRegister flags) {
this.reg = reg;
this.flags = flags;
}
// /**
// * Rotira registar udesno
// * @param reg registar
// */
// protected void rotateRegisterRight(Register reg) {
// shiftRegisterRight(reg, reg.getBit(0));
// }
//
// /**
// * Rotira registar ulijevo
// * @param reg registar
// */
// protected void rotateRegisterLeft(Register reg) {
// shiftRegisterLeft(reg, reg.getBit(reg.getWidth()));
// }
//
// /**
// * Posmiče registar reg ulijevo, moguće je postaviti bit koji će nadopuniti prazno mjesto.
// * @param reg registar koji treba posmaknuti u lijevu stranu
// * @param bit koji će nadopuniti prazno mjesto
// * @return bit koji je <q>ispao</q>
// */
// protected boolean shiftRegisterLeft(Register reg, boolean fill) {
// long result = (reg.getValue() << 1) | (fill ? 1 : 0);
// boolean fallout = reg.getBit(reg.getWidth() - 1);
//
//
// return fallout;
// }
//
// /**
// * Posmiče registar udesno, moguće je postaviti bit koji će nadopuniti prazno mjesto.
// * @param reg registar koji treba posmaknuti u desnu stranu
// * @param fill bit koji će nadopuniti prazno mjesto
// * @return bit koji je <q>ispao</q>
// */
// protected boolean shiftRegisterRight(Register reg, boolean fill) {
// long result = (reg.getValue() >>> 1) | (fill ? 1L << (reg.getWidth() * 8 - 1) : 0);
// boolean fallout = reg.getBit(0);
//
// reg.setValue(result);
//
// return fallout;
// }
}
| Java |
package hr.fer.anna.microcode;
import hr.fer.anna.exceptions.MicrocodeException;
import hr.fer.anna.interfaces.IMicroinstruction;
import hr.fer.anna.model.Word;
import hr.fer.anna.uniform.Register;
/**
* Mikroinstrukcija skoka (promjene programskog brojila). Ova mikroinstrukcija obavlja skok
* na adresu (ukoliko se radi o apsolutnom skoku) inače skače za relativan odmak (ukoliko
* se radi o relativnom skoku). Pod pojmom skakanja podrazumijeva se samo promjena programskog
* brojila na novu vrijednost.
* @author Boran
*
*/
public class JumpMicroinstruction implements IMicroinstruction {
/**
* Registar programskog brojila.
*/
private Register pc;
/**
* Riječ koja sadrži adresu na koju treba skočiti ili za koju treba skočiti.
*/
private Word addressWord;
/**
* true ako se radi o apsolutnom skoku, false ako se radi o relativnom skoku
*/
private boolean absolute;
/**
* Stvara primjerak mikroinstrukcija skoka (promjene programskog brojila).
* @param pc registar programskog brojila
* @param addressWord riječ koja sadrži relativnu ili apsolutnu adresu
* @param absolute true ako se radi o apsolutnom skoku, false ako se radi o relativnom
*/
public JumpMicroinstruction(Register pc, Word addressWord, boolean absolute) {
this.pc = pc;
this.addressWord = addressWord;
this.absolute = absolute;
}
/**
* Obavlja mikroinstrukciju tako da mijenja vrijednost registra programskog brojila.
* Ukoliko se radi o apsolutnom skoku postavlja novu vrijednost, a ukoliko se radi o
* relativnom skoku, pribraja vrijednosti programskog brojila odmak. Svi parametri su
* predani konstruktoru tokom inicijalizacije ove mikroinstrukcije.
*
* @return false hazard se ne događa kod mikroinstrukcija grananja
*
* @throws MicrocodeException ukoliko dođe do nekakve greške
*/
public boolean execute() throws MicrocodeException {
if (absolute == true) {
pc.set(addressWord);
} else {
pc.set(Word.add(pc, addressWord));
}
return false;
}
}
| Java |
package hr.fer.anna.microcode;
import hr.fer.anna.exceptions.MicrocodeException;
import hr.fer.anna.exceptions.SimulationException;
import hr.fer.anna.interfaces.IBus;
import hr.fer.anna.interfaces.IBusMaster;
import hr.fer.anna.interfaces.IMicroinstruction;
import hr.fer.anna.model.Word;
import hr.fer.anna.uniform.Address;
/**
* Mikroinstrukcija čitanja sa sabirnice. Za ovu mikroinstrukciju se ne može garantirati
* da će rezultat biti trenutno vidljiv, čak se ne može garantirati niti vidljivost rezultata
* u istom ciklusu. Potreban je stoga oprez prilikom korištenja ove mikroinstrukcije.
* @author Boran
*
*/
public class LoadMicroinstruction implements IMicroinstruction {
/** Upravljač sabirnice koji izvršava ovu mikroinstrukciju (čita podatke) */
private IBusMaster busMaster;
/** Sabirnica s koje se čitaju podaci */
private IBus bus;
/** Podatkovna riječ koja sadrži adresu */
private Word addressWord;
/**
* Stvara novu mikroinstrukciju čitanja sa adrese na sabirnici u podatkovni registar
* @param busMaster upravljač sabirnicom koji želi čitati, obično <code>this</code>
* @param bus sabirnica
* @param addressWord registar koji sadrži adresu (adresni registar)
*/
public LoadMicroinstruction(IBusMaster busMaster, IBus bus, Word addressWord) {
this.busMaster = busMaster;
this.bus = bus;
this.addressWord = addressWord;
}
/**
* Izvršava ovu mikroinstrukciju tako da sa određene adrese na sabirnici pročita podatak
* u podatkovni registar. Svi ovi parametri su zadani prilikom stvaranja instance
* ove mikroinstrukcije. Nije moguće garantirati vidljive rezultate niti trenutno
* niti unutar trenutnog ciklusa.
*
* @return true hazard se uvijek događa prilikom čitanja memorije
*
* @throws MicrocodeException u slučaju greške prilikom obavljanja mikroinstrukcije
*/
public boolean execute() throws MicrocodeException {
try {
this.bus.requestRead(busMaster, Address.fromWord(addressWord));
} catch (SimulationException e) {
throw new MicrocodeException("Čitanje sa sabirnice nije uspjelo!", e);
}
return true;
}
}
| Java |
package hr.fer.anna.microcode;
import hr.fer.anna.exceptions.MicrocodeException;
import hr.fer.anna.interfaces.IMicroinstruction;
import hr.fer.anna.model.Word;
import hr.fer.anna.uniform.Register;
/**
* Mikroinstrukcija postavlja zadanu vrijednost ili vrijednost zadanog registra u drugi
* (odredišni) registar. Pri tome se mijenja samo odredišni registar.
* @author Boran
*
*/
public class MoveMicroinstruction implements IMicroinstruction {
/** Izvorišna podatkovna riječ */
private Word srcWord;
/** Odredišni registar */
private Register destReg;
/**
* Stvara primjerak mikroinstrukcije koja sprema vrijednost podatkovne riječi u registar
* @param srcWord podatkovna riječ
* @param destReg registar
*/
public MoveMicroinstruction(Word srcWord, Register destReg) {
this.srcWord = srcWord;
this.destReg = destReg;
}
/**
* Obavlja mikroinstrukciju tako da spremi zadanu vrijednost ili vrijednost zadanog
* registra u drugi (odredišni) registar.
*
* @return false hazard se ne događa
*
* @throws MicrocodeException u slučaju nekakve greške
*/
public boolean execute() throws MicrocodeException {
try {
destReg.set(srcWord);
} catch (IllegalArgumentException e) {
throw new MicrocodeException("Nije moguće spremiti vrijednost u registar! Širine se razlikuju!");
}
return false;
}
}
| Java |
package hr.fer.anna.microcode;
import hr.fer.anna.exceptions.MicrocodeException;
import hr.fer.anna.interfaces.IFlagsRegister;
import hr.fer.anna.interfaces.IMicroinstruction;
import hr.fer.anna.model.Word;
import hr.fer.anna.uniform.Constant;
import hr.fer.anna.uniform.Register;
/**
* Mikroinstrukcija aritmetičke operacije zbrajanja. Ova mikroinstrukcije prvo briše
* registar zastavica, a zatim postavlja zastavice ovisno o rezultatu operacije zbrajanja.
* @author Boran
*
*/
public class AddMicroinstruction implements IMicroinstruction {
/** Prvi pribrojnik */
private Word wordA;
/** Drugi pribrojnik */
private Word wordB;
/** Registar u koji spremamo rezultat */
private Register regDest;
/** Registar zastavica kojem osvježavamo zastavice */
private IFlagsRegister flagsRegister;
/** True ako se zapravo radi o oduzimanju (što je samo poseban slučaj zbrajanja) */
protected boolean subtract;
/**
* Stvara novu mikroinstrukciju koja zbraja vrijednosti predanih podatkovnih riječi
* @param regDest odredišni registar
* @param wordA prvi operand
* @param wordB drugi operand
* @param flagsRegister registar zastavica koji treba osvježiti nakon obavljene operacije
*/
public AddMicroinstruction(Register regDest, Word wordA, Word wordB, IFlagsRegister flagsRegister) {
this.regDest = regDest;
this.wordA = wordA;
this.wordB = wordB;
this.flagsRegister = flagsRegister;
this.subtract = false;
}
/**
* Bit predznaka vrijednosti registra u 2-komplement zapisu
* @param reg registar
* @return true ako je vrijednost negativna, false inače
*/
private boolean registerSign(Register reg) {
return reg.getBit(reg.getWidth() - 1);
}
/**
* Izvršava mikroistrukciju zbrajanja. Zastavice se prije izvršavanja operacije brišu,
* a nakon izvršanja se postavljaju ovisno o rezultatu. Svi parametri uključeni se predaju
* tokom stvaranja primjerka mikroinstrukcije.
*
* @return false hazard se ne događa
*
* @throws MicrocodeException ukoliko dođe do nekakve greške
*/
public boolean execute() throws MicrocodeException {
// TODO: Dovršiti ovo
flagsRegister.clear();
Register regA = new Register(regDest.getWidth());
Register regB = new Register(regDest.getWidth());
regA.set(wordA);
if(subtract) {
regB.set(Word.not(wordB));
} else {
regB.set(wordB);
}
flagsRegister.setCarry(Word.add(regDest, regA, regB, subtract));
if(regDest.equals(new Constant(0))) {
flagsRegister.setZero(true);
}
boolean signResult = registerSign(regDest);
if(signResult == true) {
flagsRegister.setNegative();
} else {
flagsRegister.setPositive();
}
boolean signA = registerSign(regA);
boolean signB = registerSign(regB);
// Overflow nastupa kada su predznaci operanada isti, a predznak rezultata različit
flagsRegister.setOverflow(signA && signB && !signResult || !signA && !signB && signResult);
return false;
}
}
| Java |
package hr.fer.anna.oisc;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import hr.fer.anna.GUI.ArchDisplay;
import hr.fer.anna.exceptions.BusAddressTaken;
import hr.fer.anna.exceptions.UnknownAddressException;
import hr.fer.anna.interfaces.IWordChangeListener;
import hr.fer.anna.model.Word;
import hr.fer.anna.uniform.Address;
import hr.fer.anna.uniform.Constant;
import hr.fer.anna.uniform.PlainBus;
import hr.fer.anna.uniform.SimpleMemory;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.util.concurrent.*;
public class OISCArchDisplay extends ArchDisplay {
private JPanel modelPanel;
private JPanel simPanel;
private JPanel parent;
private Cpu cpu;
private PlainBus bus;
private SimpleMemory memory;
// private long startingSimulationTime;
private static final int MEMORY_SIZE = 1024;
private String code;
public OISCArchDisplay(JPanel myParent){
parent = myParent;
this.bus = new PlainBus();
this.cpu = new Cpu(this.bus);
this.memory = new SimpleMemory(MEMORY_SIZE, 32);
try {
this.bus.registerBusUnit(this.memory, Address.fromWord(new Constant(0)));
} catch (UnknownAddressException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (BusAddressTaken e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
// this.startingSimulationTime = Simulator.getSimulator().getSimulatorTime();
modelPanel = new JPanel();
modelPanel.add(new JLabel("Nema nekih opcija za OISC :)"));
simPanel = new JPanel();
simPanel.setLayout(new BorderLayout());
// add z status
final JPanel statusPane = new JPanel();
statusPane.setLayout(new BoxLayout(statusPane, BoxLayout.PAGE_AXIS));
statusPane.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 10));
JPanel pcPane = new JPanel();
final JLabel pcLabel = new JLabel("PC: ");
pcPane.add(pcLabel);
statusPane.add(pcPane);
// Memory lane :)))
final JPanel memoryPane = new JPanel();
memoryPane.setLayout(new BoxLayout(memoryPane, BoxLayout.PAGE_AXIS));
memoryPane.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 10));
memoryPane.add(new JLabel("Memory:"));
memoryPane.add(Box.createRigidArea(new Dimension(0, 10)));
final JLabel memoryLabel = new JLabel("");
memoryPane.add(memoryLabel);
statusPane.add(memoryPane);
simPanel.add(BorderLayout.CENTER, statusPane);
// add z buttonz
JPanel buttonPane = new JPanel();
JButton startSimButton = new JButton("Run simulation");
startSimButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
bus = new PlainBus();
cpu = new Cpu(bus);
memory = new SimpleMemory(MEMORY_SIZE, 32);
try {
bus.registerBusUnit(memory, Address.fromWord(new Constant(0)));
} catch (UnknownAddressException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (BusAddressTaken e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// startingSimulationTime = Simulator.getSimulator().getSimulatorTime();
if ( code != null )
assemble(code);
memoryLabel.setText("<running sim>");
pcLabel.setText("PC: <running sim>");
ExecutorService exec = Executors.newFixedThreadPool(1);
// exec.execute(Simulator.getSimulator());
exec.shutdown();
}
});
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
buttonPane.add(Box.createHorizontalGlue());
buttonPane.add(startSimButton);
simPanel.add(BorderLayout.SOUTH, buttonPane);
this.cpu.describe().getRegister("PC").registerListener(new IWordChangeListener() {
public void update(Word word) {
if(word.getHexString().equals("10")) {
pcLabel.setText("PC: " + word.getHexString());
Word peek;
try {
peek = memory.read(Address.fromWord(new Constant(0)));
} catch (Exception e){
memoryLabel.setText("Memory exploded");
return;
}
memoryLabel.setText("<html>");
memoryLabel.setText(memoryLabel.getText() + peek.getHexString() + "<br>");
cpu.halt();
}
}
});
}
public String assemble(String code) {
this.code = code;
try {
this.memory.write(Assembler.assemble(code), Address.fromWord(new Constant(0)));
} catch (Exception e){
return e.toString();
}
return new String("Assembly successfull!");
}
public JPanel getSimPanel(){
return simPanel;
}
public JPanel getModelPanel(){
return modelPanel;
}
}
| Java |
package hr.fer.anna.oisc;
import java.util.ArrayList;
import java.util.List;
import hr.fer.anna.model.Word;
import hr.fer.anna.uniform.Constant;
import hr.fer.anna.exceptions.SyntaxError;
/**
* OISC asembler.
* NAPOMENE:<br />
* Labele nisu podržane.<br />
* Kod počinje od 0. pozicije, ne nakon taba.<br />
* Argumenti su odvojeni s ' '.<br />
* Kodovi:<br />
* SUBNEG: xx|address1(10)|address2(10)|address3(10)
* HALT: 0
* mem[address2] = mem[address2] - mem[address1]
* if negative jump address3
*/
public class Assembler {
/**
* Dekodiranje jedne naredbe.
*
* @param instruction Naredba.
* @return Byte-code naredbe.
*/
private static Word decode(String instruction) throws SyntaxError {
String[] inst = instruction.split(" ");
Word instructionWord = new Word();
int value = 0;
if (inst[0].equals("SUBNEG")) {
value = Integer.parseInt(inst[1]);
value <<= 10;
value |= Integer.parseInt(inst[2]);
value <<= 10;
value |= Integer.parseInt(inst[3]);
}
else throw new SyntaxError("Syntax error: " + instruction);
instructionWord.set(new Constant(value));
return instructionWord;
}
/**
* Punjenje memorije asembliranim byte-codeom.
*
* @param code Kod koji moramo asemblirati.
* @return kod zapisan u polju bajtova
*/
public static Word[] assemble(String code) throws SyntaxError {
String[] instruction = code.split("\n");
List<Word> byteCode = new ArrayList<Word>();
for (int i = 0; i < instruction.length; i++){
try {
byteCode.add(decode(instruction[i]));
} catch (SyntaxError e) {
throw new SyntaxError("Syntax error on line " + Integer.toString(i + 1));
}
}
return byteCode.toArray(new Word[0]);
}
}
| Java |
package hr.fer.anna.oisc;
import java.util.LinkedList;
import java.util.List;
import hr.fer.anna.interfaces.IBus;
import hr.fer.anna.interfaces.IBusMaster;
import hr.fer.anna.interfaces.IFlagsRegister;
import hr.fer.anna.interfaces.IInstructionDecoder;
import hr.fer.anna.interfaces.IMicroinstruction;
import hr.fer.anna.microcode.ConditionalMicroinstruction;
import hr.fer.anna.microcode.JumpMicroinstruction;
import hr.fer.anna.microcode.LoadMicroinstruction;
import hr.fer.anna.microcode.MoveMicroinstruction;
import hr.fer.anna.microcode.StoreMicroinstruction;
import hr.fer.anna.microcode.SubtractMicroinstruction;
import hr.fer.anna.model.Word;
import hr.fer.anna.uniform.Constant;
import hr.fer.anna.uniform.Register;
/**
* Dekodira jedinu OISC instrukciju.
* @author Boran
*
*/
public class InstructionDecoder implements IInstructionDecoder {
/** Upravljač sabirnice */
private IBusMaster busMaster;
/** Sabirnica preko koje se čita i piše */
private IBus bus;
/** Registar programskog brojila */
private Register pc;
/** Akumulator */
private Register accumulator;
/** Podatkovni registar */
private Register dataRegister;
/** Registar zastavica */
private IFlagsRegister flagsRegister;
/**
* Konstruktor novog dekodera instrukcija
* @param busMaster upravljač sabirnice kojeg programiramo mikroinstrukcijama
* @param bus sabirnica preko koje se čita i piše
* @param dataRegister podatkovni registar
* @param accuReg akumulator
* @param pc registar programskog brojila
* @param flagsRegister registar zastavica
*/
public InstructionDecoder(IBusMaster busMaster, IBus bus, Register dataRegister, Register accuReg, Register pc, IFlagsRegister flagsRegister) {
this.busMaster = busMaster;
this.bus = bus;
this.pc = pc;
this.dataRegister = dataRegister;
this.accumulator = accuReg;
this.flagsRegister = flagsRegister;
}
/**
* subneg address1 address2 address3 - subtract and branch if negative
* mem[address2] = mem[address2] - mem[address1]
* if negative branch mem-address3
* xx|address1(10)|address2(10)|address3(10)
*/
public List<IMicroinstruction> decode(Register instructionRegister) {
List<IMicroinstruction> microinstructions = new LinkedList<IMicroinstruction>();
if(instructionRegister.equals(new Constant(0))) {
return microinstructions;
}
Word mask = new Constant((1 << 10) - 1);
Word address1 = Word.and(Word.shiftRight(instructionRegister, 20), mask);
Word address2 = Word.and(Word.shiftRight(instructionRegister, 10), mask);
Word address3 = Word.and(instructionRegister, mask);
// Učitaj s prve adrese i spremi u akumulator
microinstructions.add(new LoadMicroinstruction(busMaster, bus, address1));
microinstructions.add(new MoveMicroinstruction(dataRegister, accumulator));
// Učitaj s druge adrese i oduzmi
microinstructions.add(new LoadMicroinstruction(busMaster, bus, address2));
microinstructions.add(new SubtractMicroinstruction(accumulator, dataRegister, accumulator, flagsRegister));
// Pomakni rezultat u podatkovni registar i spremi na lokaciju 2
microinstructions.add(new MoveMicroinstruction(accumulator, dataRegister));
microinstructions.add(new StoreMicroinstruction(busMaster, dataRegister, bus, address2));
// Skači ako je postavljena zastavica negative nakon alu operacije
microinstructions.add(
new ConditionalMicroinstruction(
flagsRegister,
new JumpMicroinstruction(
pc,
address3,
true
)
).testNegative(true)
);
return microinstructions;
}
}
| Java |
package hr.fer.anna.oisc;
import hr.fer.anna.interfaces.IFlagsRegister;
import hr.fer.anna.uniform.Register;
/**
* Status register OISC-a. Organizacija:
* x...x|NMI0|IRQ1|IRQ0|GIE|ENMI2|EIRQ1|EIRQ0|Z|V|C|N<br />
* NMI2, IRQ1 i IRQ0 su flagovi koji označavaju postavljen interrupt.
*
* @author Ivan
*/
public class StatusRegister extends Register implements IFlagsRegister {
/**
* Konstruktor.
*/
public StatusRegister() {
super(32);
}
public boolean getCarry() {
return getBit(1);
}
public boolean getZero() {
return getBit(3);
}
public boolean getOverflow() {
return getBit(2);
}
public boolean getNegative() {
return getBit(0);
}
public boolean getPositive() {
return !getNegative();
}
public void setCarry(boolean state) {
setBit(1, state);
}
public void setZero(boolean state) {
setBit(3, state);
}
public void setOverflow(boolean state) {
setBit(2, state);
}
public void setNegative() {
setBit(0, true);
}
public void setPositive() {
setBit(0, false);
}
/**
* Postavljanje/brisanje interrupta.
*
* @param port Port na koji postavljamo ili sa kojeg brišemo interrupt.
* @param value True ako postavljamo interrupt, false ako brišemo.
*/
public void setInterrupt(String port, boolean value) {
// TODO: Moj je prijedlog da se ovo stavi unutar mape za kompleksnije interrupte,
// naravno da kod ovoga to nećemo raditi :). Recimo mapa koja bi dohvaćala index bita
// koji se postavlja ili briše.
if (port.equals("NMI0")) {
setBit(10, value);
} else if (port.equals("IRQ1")) {
setBit(9, value);
} else if (port.equals("IRQ0")) {
setBit(8, value);
} else {
throw new IllegalArgumentException("Interrupt port \"" + port + "\" ne postoji!");
}
}
/**
* Je li omogućeno postavljanje interrupta na port <code>port</code>.
*
* @param port Port koji provjeravamo.
* @return True ako je postavljanje omogućeno, false ako nije.
*/
public boolean isInterruptEnabled(String port) {
boolean global;
global = getBit(7);
if (port.equals("NMI0")) {
// TODO: I nemaskirajući se može ugasiti, razlika je samo da se nemaskirajući može
// pojaviti unutar maskirajućeg.
return getBit(6) && global;
} else if (port.equals("IRQ1")) {
return getBit(5) && global;
} else if (port.equals("IRQ0")) {
return getBit(4) && global;
} else {
throw new IllegalArgumentException("Interrupt port \"" + port + "\" ne postoji!");
}
}
}
| Java |
package hr.fer.anna.oisc;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import hr.fer.anna.events.NextProcessorStateEvent;
import hr.fer.anna.events.ProcessorEvent;
import hr.fer.anna.events.SimulationEvent;
import hr.fer.anna.exceptions.IllegalActionException;
import hr.fer.anna.exceptions.MicrocodeException;
import hr.fer.anna.exceptions.SimulationException;
import hr.fer.anna.exceptions.UnknownAddressException;
import hr.fer.anna.interfaces.IBus;
import hr.fer.anna.interfaces.IBusMaster;
import hr.fer.anna.interfaces.IEventListener;
import hr.fer.anna.interfaces.IEventSetter;
import hr.fer.anna.interfaces.IInstructionDecoder;
import hr.fer.anna.interfaces.IMicroinstruction;
import hr.fer.anna.interfaces.IProcessor;
import hr.fer.anna.simulator.Simulator;
import hr.fer.anna.simulator.handles;
import hr.fer.anna.uniform.Address;
import hr.fer.anna.uniform.Constant;
import hr.fer.anna.uniform.Register;
import hr.fer.anna.model.UnitReport;
import hr.fer.anna.model.Word;
/**
* Realizacija OISC CPU-a.
*/
public class Cpu implements IProcessor, IBusMaster, IEventSetter, IEventListener {
/** Flag koji određuje je li procesor aktivan. */
private boolean isRunning;
/** Registar stanja i zastavica. */
private StatusRegister statusReg;
/** PC registar. */
private Register pc;
/** Data registar. */
private Register dataReg;
/** Address registar. */
private Register addressReq;
/** Code registar. */
private Register codeReq;
/** Akumulator. */
private Register accuReg;
/** Red mikroinstrukcija koje treba izvršavati */
private Queue<IMicroinstruction> microinstructionCache;
/** Dekoder instrukcija */
private IInstructionDecoder instructionDecoder;
/** Simulator na kojeg smo spojeni */
private Simulator simulator;
/** Sabirnica spojena na procesor */
private IBus bus;
private static interface IAction {
public ProcessorState run() throws MicrocodeException, IllegalActionException, UnknownAddressException;
}
private IAction loadAction = new IAction() {
@Override
public ProcessorState run() throws MicrocodeException, IllegalActionException, UnknownAddressException {
bus.requestRead(Cpu.this, pc.getAddress());
pc.set(Word.add(pc, Constant.ONE));
return ProcessorState.DECODE_INSTRUCTION;
}
};
private IAction decodeAction = new IAction() {
@Override
public ProcessorState run() throws MicrocodeException {
microinstructionCache.addAll(instructionDecoder.decode(codeReq));
if (microinstructionCache.isEmpty()) {
halt();
}
simulator.setNewEvent(new NextProcessorStateEvent(Cpu.this, Cpu.this));
return ProcessorState.EXECUTE_INSTRUCTION;
}
};
private IAction executeAction = new IAction() {
@Override
public ProcessorState run() throws MicrocodeException {
while (!microinstructionCache.isEmpty()) {
// Ako se dogodio hazard, izlazimo i čekamo da se hazard riješi
// prije nastavka izvršavanja
IMicroinstruction microinstruction = microinstructionCache.remove();
if (microinstruction.execute()) {
break;
}
}
if (!microinstructionCache.isEmpty()) {
// Ako ima još mikroinstrukcija, to moramo u sljedećem ciklusu obavit
// čekamo otklanjanje hazarda koje će nam biti dojavljeno
return ProcessorState.EXECUTE_INSTRUCTION;
} else {
simulator.setNewEvent(new NextProcessorStateEvent(Cpu.this, Cpu.this));
return ProcessorState.LOAD_INSTRUCTION;
}
}
};
/** Stanja procesora (procesor je stroj s konačnim brojem stanja) */
private enum ProcessorState {
/** Učitavanje instrukcije iz memorije */
LOAD_INSTRUCTION,
/** Dekodiranje pročitane instrukcije */
DECODE_INSTRUCTION,
/** Izvršavanje instrukcije nakon što je ona dekodirana */
EXECUTE_INSTRUCTION,
/** Rad procesora je zaustavljen */
HALTED;
}
private Map<ProcessorState, IAction> actions = new HashMap<Cpu.ProcessorState, Cpu.IAction>();
/** Trenutno stanje u kojem se nalazi procesor */
private ProcessorState currentProcessorState;
/** Iduće stanje u koje procesor treba ići */
private ProcessorState nextProcessorState;
/**
* Konstruktor.
*/
public Cpu(IBus bus) {
this.bus = bus;
try {
this.bus.setBusMaster(this);
} catch (IllegalActionException ignorable) {
}
this.nextProcessorState = ProcessorState.LOAD_INSTRUCTION;
this.isRunning = true;
// Specijalni registri
this.statusReg = new StatusRegister();
this.pc = new Register();
this.dataReg = new Register();
this.codeReq = new Register();
this.addressReq = new Register();
this.accuReg = new Register();
this.microinstructionCache = new LinkedList<IMicroinstruction>();
this.instructionDecoder = new InstructionDecoder(this, this.bus, this.dataReg, this.accuReg, this.pc, this.statusReg);
this.actions.put(ProcessorState.LOAD_INSTRUCTION, loadAction);
this.actions.put(ProcessorState.DECODE_INSTRUCTION, decodeAction);
this.actions.put(ProcessorState.EXECUTE_INSTRUCTION, executeAction);
}
@Override
public void halt() {
this.isRunning = false;
this.nextProcessorState = ProcessorState.HALTED;
}
@Override
public void reset() {
this.isRunning = true;
this.nextProcessorState = ProcessorState.LOAD_INSTRUCTION;
}
public void init(Simulator sim) {
this.simulator = sim;
simulator.setNewEvent(new NextProcessorStateEvent(this, this));
}
public UnitReport describe() {
UnitReport report = new UnitReport("CPU", "OISC v1.0");
report.addRegister(this.pc, "PC", "Programsko brojilo");
report.addRegister(this.dataReg, "DR", "Podatkovni registar");
report.addRegister(this.addressReq, "AR", "Adresni registar");
report.addRegister(this.codeReq, "IR", "Instrukcijski registar");
report.addRegister(this.accuReg, "A", "Akumulator");
return report;
}
public void waitBus(IBus bus, boolean state) {
}
@handles(events = ProcessorEvent.class)
public void act(SimulationEvent event) throws SimulationException {
if (!this.isRunning) {
return;
}
currentProcessorState = nextProcessorState;
try {
nextProcessorState = actions.get(currentProcessorState).run();
} catch (MicrocodeException e) {
throw new SimulationException("CPU Exception", e);
}
}
public SimulationEvent[] getEvents() {
return new SimulationEvent[]{new ProcessorEvent(this)};
}
public void busReadCallback(IBus bus, Address globalAddress, Word word) {
if(currentProcessorState == ProcessorState.LOAD_INSTRUCTION) {
this.codeReq.set(word);
} else if(currentProcessorState == ProcessorState.EXECUTE_INSTRUCTION) {
this.dataReg.set(word);
}
simulator.setNewEvent(new NextProcessorStateEvent(this, this));
}
public void busWriteCallback(IBus bus, Address globalAddress) {
simulator.setNewEvent(new NextProcessorStateEvent(this, this));
}
}
| Java |
package hr.fer.anna.uniform;
import hr.fer.anna.model.Word;
/**
* Klasa koja predstavlja adrese. Adrese su predstavljene NBC-om. Uspoređuju se
* po svom sadržaju, neovisno o širini riječi kojom su predstavljene.
* @author Boran
*
*/
public class Address extends Word implements Comparable<Address> {
/**
* Stvara adresu iz zadane podatkovne riječi u kojoj je zapisana adresa
* @param addressWord podatkovna riječ koja sadrži adresu
*/
public Address(Word addressWord) {
super(addressWord);
}
/**
* Stvara adresu iz zadane podatkovne riječi u kojoj je zapisana adresa
* @param addressWord podatkovna riječ koja sadrži adresu
*/
public static Address fromWord(Word addressWord) {
return new Address(addressWord);
}
/**
* Dvije adrese su jednake ako pokazuju na istu lokaciju, neovisno o tome kako
* su predstavljene.
*/
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Word)) {
return false;
}
Word other = (Word) obj;
return this.getHexString().equals(other.getHexString());
}
@Override
public int hashCode() {
return this.getHexString().hashCode();
}
/**
* Adrese se uspoređuju prema lokaciji na koju pokazuju, neovisno o tome kako
* su predstavljene.
*/
public int compareTo(Address o) {
if (this.groups > o.groups) {
for (int i = this.groups - 1; i >= o.groups; i--) {
if (this.data[i] > 0) {
return 1;
}
}
}
if (this.groups < o.groups) {
for (int i = o.groups - 1; i >= this.groups; i--) {
if (o.data[i] > 0) {
return -1;
}
}
}
for (int i = this.groups - 1; i >= 0; i--) {
if (this.data[i] > o.data[i]) {
return 1;
} else if (this.data[i] < o.data[i]) {
return -1;
}
}
return 0;
}
}
| Java |
package hr.fer.anna.uniform;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import hr.fer.anna.events.BusUnitOperationCompletedEvent;
import hr.fer.anna.events.BusUnitOperationEvent;
import hr.fer.anna.events.BusUnitReadStartEvent;
import hr.fer.anna.events.BusUnitWriteStartEvent;
import hr.fer.anna.events.SimulationEvent;
import hr.fer.anna.exceptions.IllegalActionException;
import hr.fer.anna.exceptions.SimulationException;
import hr.fer.anna.exceptions.UnknownAddressException;
import hr.fer.anna.interfaces.IBus;
import hr.fer.anna.interfaces.IBusUnit;
import hr.fer.anna.interfaces.IEventListener;
import hr.fer.anna.interfaces.IEventSetter;
import hr.fer.anna.interfaces.IMemoryModel;
import hr.fer.anna.interfaces.IMemoryModelWatcher;
import hr.fer.anna.model.UnitReport;
import hr.fer.anna.model.Word;
import hr.fer.anna.simulator.Simulator;
/**
* Jednostavna memorija koja ne podržava više istodobnih akcija. Moguće je samo obaviti čitanje
* jedne lokacije ili upisivanje u jednu lokacije u isto vrijeme. Nakon zatraživanja jedne od
* ovih dviju operacija, potrebno je pričekati da memorija obavi operaciju prije zahtijevanja
* druge operacije.
* @author Boran
*
*/
public class SimpleMemory implements IMemoryModel, IBusUnit, IEventListener, IEventSetter {
/**
* Čekanje prilikom pisanja u memoriju
*/
private static final int writeDelay = 2;
/**
* Čekanje priliko čitanja iz memorije
*/
private static final int readDelay = 2;
/**
* Slušači promjene memorijskog modela.
*/
private List<IMemoryModelWatcher> watchers;
/** true ako je komponenta zauzeta, false inače */
private boolean busy;
/**
* Simulator na koji smo spojeni
*/
private Simulator simulator;
/** Spremnik podataka. */
private Map<Address, Word> memoryData;
/** Veličina memorije. */
private int memSize;
/** Širina riječi memorije. */
private int width;
/**
* Konstruktor.
*
* @param size Veličina memorije (u riječima).
* @param width Širina riječi memorije.
*/
public SimpleMemory (int size, int width) {
this.watchers = new LinkedList<IMemoryModelWatcher>();
this.memSize = size;
this.width = width;
this.memoryData = new HashMap<Address, Word>(size);
busy = false;
}
/**
* Metoda implementira djelovanje komponente na eventove upućene toj komponenti.
*/
public void act(SimulationEvent event) throws SimulationException {
BusUnitOperationEvent busUnitOperationEvent = (BusUnitOperationEvent) event;
if(busUnitOperationEvent.isCompleted()) {
if(busUnitOperationEvent.reading()) {
busUnitOperationEvent.getBus().busUnitReadCallback(this, busUnitOperationEvent.getLocalAddress(), read(busUnitOperationEvent.getLocalAddress()));
} else if (busUnitOperationEvent.writing()) {
busUnitOperationEvent.getBus().busUnitWriteCallback(this, busUnitOperationEvent.getLocalAddress());
}
this.release(busUnitOperationEvent.getBus());
} else {
this.acquire(busUnitOperationEvent.getBus());
if(busUnitOperationEvent.reading()) {
this.simulator.setNewEvent(new BusUnitOperationCompletedEvent(busUnitOperationEvent), readDelay);
} else if(busUnitOperationEvent.writing()) {
this.simulator.setNewEvent(new BusUnitOperationCompletedEvent(busUnitOperationEvent), writeDelay);
if(busUnitOperationEvent.getWords()[0].getWidth() != this.width) {
throw new IllegalActionException("Pokušaj zapisivanja riječi šire od širine memorije!");
}
write(busUnitOperationEvent.getWords(), busUnitOperationEvent.getLocalAddress());
}
}
}
/**
* Preuzimanje memorije od sabirnice prilikom čitanja/pisanja
* @param bus sabirnica
*/
private void acquire(IBus bus) throws IllegalActionException {
if (this.busy) {
throw new IllegalActionException("Memorija je već zauzeta!");
}
this.busy = true;
}
/**
* Otpuštanje memorije od sabirnice prilikom čitanja/pisanja
* @param bus sabirnica
*/
private void release(IBus bus) {
this.busy = false;
}
public void init(Simulator sim) {
this.simulator = sim;
}
public UnitReport describe() {
return null;
}
public int getLocalAddresses() {
return this.memSize;
}
public SimulationEvent[] getEvents() {
return new SimulationEvent[]{new BusUnitOperationEvent(this)};
}
@Override
public void requestRead(IBus bus, Address localAddress)
throws IllegalActionException, UnknownAddressException {
this.simulator.setNewEvent(new BusUnitReadStartEvent(bus, this, localAddress));
}
@Override
public void requestWrite(IBus bus, Address localAddress, Word word)
throws IllegalActionException, UnknownAddressException {
this.simulator.setNewEvent(new BusUnitWriteStartEvent(bus, this, localAddress, new Word[]{word}));
}
public boolean isBusy() {
return this.busy;
}
public Word read(Address address) throws UnknownAddressException, IllegalActionException {
if(!this.memoryData.containsKey(address)) {
return new Word(this.width);
} else {
return this.memoryData.get(address);
}
}
public void write(Word word, Address address) throws UnknownAddressException, IllegalActionException {
if(!this.memoryData.containsKey(address)) {
this.memoryData.put(address, new Word(this.width));
}
this.memoryData.get(address).set(word);
for(IMemoryModelWatcher watcher : this.watchers) {
watcher.update(this, address, word);
}
}
public void write(Word[] words, Address address) throws UnknownAddressException, IllegalActionException {
for (int i = 0; i < words.length; i++) {
write(words[i], Address.fromWord(Word.add(address, new Constant(i))));
}
}
public void registerWatcher(IMemoryModelWatcher watcher) {
this.watchers.add(watcher);
}
public void unregisterWatcher(IMemoryModelWatcher watcher) {
this.watchers.remove(watcher);
}
}
| Java |
package hr.fer.anna.uniform;
public class AddressRange implements Comparable<AddressRange> {
/** Početna adresa (uključena) */
private Address startAddress;
/** Konačna adresa (uključena) */
private Address endAddress;
/**
* Stvara novi interval adresa predstavljen početnom i konačnom adresom
* @param startAddress početna adresa intervala (uključena)
* @param endAddress konačna adresa intervala (uključena)
*/
public AddressRange(Address startAddress, Address endAddress) {
this.startAddress = startAddress;
this.endAddress = endAddress;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof AddressRange)) {
return false;
}
AddressRange other = (AddressRange) obj;
return this.startAddress.equals(other.startAddress) && this.endAddress.equals(other.endAddress);
}
@Override
public int hashCode() {
return this.startAddress.hashCode() ^ this.endAddress.hashCode();
}
public int compareTo(AddressRange o) {
int start = this.startAddress.compareTo(o.startAddress);
if(start == 0) {
return this.endAddress.compareTo(o.endAddress);
} else {
return start;
}
}
/**
* Dohvaća početnu adresu intervala koja je uključena u interval
* @return početna adresa
*/
public Address getStartAddress() {
return startAddress;
}
/**
* Dohvaća krajnju adresu intervala koja je uključena u interval
* @return krajnja adresa
*/
public Address getEndAddress() {
return endAddress;
}
/**
* Provjerava da li se predana adresa nalazi u intervalu [a, b]
* @param address predana adresa
* @return true ako se predana adresa nalazi u intervalu, false inače
*/
public boolean inRange(Address address) {
return (address.compareTo(this.startAddress) >= 0 && address.compareTo(this.endAddress) <= 0);
}
}
| Java |
package hr.fer.anna.uniform;
import hr.fer.anna.model.Word;
/**
* Registar procesora (privatni i javni).
*
* @author Boran
*/
public class Register extends Word {
/**
* Defaultni konstruktor, stvara 32-bitni registar i
* postavlja vrijednost na 0.
*/
public Register() {
this(32);
}
/**
* Stvara registar zadane širine i postavlja vrijednost na 0.
*
* @param width Širina registra (u bitovima).
*/
public Register(int width) {
super(width);
}
/**
* Dohvat jednog bita iz registra pod indeksom <code>index</code>.
*
* @param index Indeks bita čija vrijednost nas zanima.
* @return Vrijednost bita pod indeksom <code>index</code>, true ako je postavljen, false inače.
*/
public boolean getBit(int index) {
if(index >= getWidth() || index < 0) {
throw new IllegalArgumentException(
"Index mora biti unutar intervala [0, " + (getWidth() - 1) + "]. Unijeli ste: " + index);
}
int group = (int) Math.round(Math.floor(index / (double)super.groupSize));
int offset = index - group*super.groupSize;
return ((super.data[group] >> offset) & 1) == 1 ? true : false;
}
/**
* Postavljanje jednog bita iz registra pod indeksom <code>index</code>.
*
* @param index Indeks bita kojeg postavljamo.
* @param value Vrijednost na koju treba postaviti bit
*/
public void setBit(int index, boolean value) {
if(index >= getWidth() || index < 0) {
throw new IllegalArgumentException(
"Index mora biti unutar intervala [0, " + (getWidth() - 1) + "]. Unijeli ste: " + index);
}
int group = (int) Math.round(Math.floor(index / (double)super.groupSize));
int offset = index - group*super.groupSize;
if(value) {
super.data[group] |= (1 << offset);
} else {
super.data[group] &= ~(1 << offset);
}
updateListeners();
}
/**
* Briše vrijednost registra tako da su svi bitovi jednaki 0
*
*/
public void clear() {
for (int i = 0; i < this.data.length; i++) {
this.data[i] = 0;
}
}
/**
* Vraća adresu zapisanu u registru
* @return adresa
*/
public Address getAddress() {
return new Address(this);
}
}
| Java |
package hr.fer.anna.uniform;
/**
* Interrupt port procesora.
*
* @author Ivan
*/
public class InterruptPort {
/** Naziv porta. */
protected String name;
/** Početna adresa prekidnog potprograma. */
protected long address;
/** Je li port otvoren ili zatvoren. */
protected boolean isOpen;
/** Radi li se o portu za maskirajuće ili nemaskirajuće prekide. */
protected boolean isMaskable;
/**
* Konstruktor otvorenog porta za maskirajuće prekide.
*
* @param name Naziv porta.
* @param address Početna adresa prekidnog potprograma.
*/
public InterruptPort(String name, long address) {
this.name = name;
this.address = address;
this.isOpen = true;
this.isMaskable = true;
}
/**
* Konstruktor.
*
* @param name Naziv porta.
* @param address Početna adresa prekidnog potprograma.
* @param isOpen Je li port otvoren (true) ili zatvoren (false).
* @param isMaskable Radi li se o maskirajućem ili nemaskirajućem prekidnom portu.
*/
public InterruptPort(String name, long address, boolean isOpen, boolean isMaskable) {
this.name = name;
this.address = address;
this.isOpen = isOpen;
this.isMaskable = isMaskable;
}
/**
* Dohvat početne adresa prekidnog potprograma.
* @return Početna adresa prekidnog potprograma.
*/
public long getAddress() {
return this.address;
}
/**
* Dohvat naziva porta.
*
* @return Naziv porta.
*/
public String getName() {
return this.name;
}
/**
* Je li port otvoren ili zatvoren.
*
* @return Je li port otvoren ili zatvoren.
*/
public boolean isOpen() {
return this.isOpen;
}
/**
* Radi li se o portu za maskirajuće ili nemaskirajuće prekide.
*
* @return Radi li se o portu za maskirajuće ili nemaskirajuće prekide.
*/
public boolean isMaskable() {
return this.isMaskable;
}
/**
* Otvaranje ili zatvaranje porta.
*
* @param isOpen True ako želimo port otvoriti, odnosno false ako želimo port zatvoriti.
*/
public void setIsOpen(boolean isOpen) {
this.isOpen = isOpen;
}
}
| Java |
package hr.fer.anna.uniform;
import hr.fer.anna.model.Word;
/**
* Klasa konstanti koje se mogu koristit programski
* @author Boran
*
*/
public class Constant extends Word {
/** Vrijednost 0 */
public static final Constant ZERO = new Constant(0);
/** Vrijednost 1 */
public static final Constant ONE = new Constant(1);
/**
* Stvara 8-bitnu konstantu zadane vrijednost
* @param value vrijednost
*/
public Constant(byte value) {
super(8);
super.data[0] = (int)value & 0xFF;
}
/**
* Stvara 16-bitnu konstantu zadane vrijednost
* @param value vrijednost
*/
public Constant(short value) {
super(64);
super.data[0] = (int)value & 0xFFFF;
}
/**
* Stvara 32-bitnu konstantu zadane vrijednost
* @param value vrijednost
*/
public Constant(int value) {
super(32);
super.data[0] = value & 0x00FFFFFF;
super.data[1] = value >>> 24;
}
/**
* Stvara 64-bitnu konstantu zadane vrijednost
* @param value vrijednost
*/
public Constant(long value) {
super(64);
super.data[0] = (int) (value & 0x00FFFFFF);
super.data[1] = (int) ((value >>> 24) & 0x00FFFFFF);
super.data[2] = (int) (value >>> 48);
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public String toString() {
return super.toString();
}
}
| Java |
package hr.fer.anna.uniform;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import hr.fer.anna.exceptions.BusAddressTaken;
import hr.fer.anna.exceptions.IllegalActionException;
import hr.fer.anna.exceptions.UnknownAddressException;
import hr.fer.anna.interfaces.IBus;
import hr.fer.anna.interfaces.IBusMaster;
import hr.fer.anna.interfaces.IBusUnit;
import hr.fer.anna.model.Word;
/**
* Implementacija vrlo jednostavne sabirnice. Uloga sabirnici je dvostrano
* mappiranje globalnih adresa na lokalne adrese na jedinici koja pripada sabirnici.
* Sabirnica prima zahtjeve čitanja/pisanja i prosljeđuje ih odgovarajućoj jedinici.
* Sve dok jedinica ne obavi operaciju, smatra se da ni sabirnica nije obavila operaciju
* te ne može primati više operacija.
* @author Boran
*
*/
public class PlainBus implements IBus {
/** Trenutni upravljač ovom sabirnicom */
private IBusMaster busMaster;
/** true ako je bus zauzet i ne može primati operacije, false inače */
private boolean busy;
/** Mapiranje jedinica u globalne adrese */
private Map<IBusUnit, AddressRange> unitToAddress;
/** Mapiranje globalnih adresa na jedinice */
private Map<AddressRange, IBusUnit> addressToUnit;
public PlainBus() {
unitToAddress = new HashMap<IBusUnit, AddressRange>();
addressToUnit = new LinkedHashMap<AddressRange, IBusUnit>();
}
@Override
public void setBusMaster(IBusMaster newBusMaster) throws IllegalActionException {
if (this.busy) {
throw new IllegalActionException("Sabirnica je zauzeta!");
} else {
this.busMaster = newBusMaster;
}
}
@Override
public IBusMaster getBusMaster() {
return this.busMaster;
}
@Override
public boolean isBusy() {
return this.busy;
}
@Override
public void registerBusUnit(IBusUnit busUnit, Address startAddress)
throws UnknownAddressException, BusAddressTaken {
AddressRange addressRange = new AddressRange(startAddress, new Address(Word.add(startAddress, new Constant(busUnit.getLocalAddresses() - 1))));
unitToAddress.put(busUnit, addressRange);
addressToUnit.put(addressRange, busUnit);
}
@Override
public void requestRead(IBusMaster busMaster, Address globalAddress)
throws UnknownAddressException, IllegalActionException {
IBusUnit busUnit = getBusUnitFromGlobalAddress(globalAddress);
Address localAddress = getLocalAddressFromGlobal(busUnit, globalAddress);
this.acquire(busMaster);
busUnit.requestRead(this, localAddress);
}
@Override
public void busUnitReadCallback(IBusUnit busUnit, Address localAddress,
Word word) {
this.busMaster.busReadCallback(this, getGlobalAddressFromLocal(busUnit, localAddress), word);
this.release(busMaster);
}
@Override
public void requestWrite(IBusMaster busMaster, Address globalAddress,
Word word) throws UnknownAddressException, IllegalActionException {
IBusUnit busUnit = getBusUnitFromGlobalAddress(globalAddress);
Address localAddress = getLocalAddressFromGlobal(busUnit, globalAddress);
this.acquire(busMaster);
busUnit.requestWrite(this, localAddress, word);
}
@Override
public void busUnitWriteCallback(IBusUnit busUnit, Address localAddress) {
this.busMaster.busWriteCallback(this, getGlobalAddressFromLocal(busUnit, localAddress));
this.release(busMaster);
}
/**
* Zauzimanje sabirnice od strane upravljača sabirnice
* @param busMaster upravljač sabirnice
* @throws IllegalActionException u slučaju da je sabirnica već zauzeta
*/
private void acquire(IBusMaster busMaster) throws IllegalActionException {
setBusMaster(busMaster);
this.busy = true;
busMaster.waitBus(this, true);
}
/**
* Otpuštanje sabirnice od strane upravljača sabirnice
* @param busMaster upravljač sabirnice
*/
private void release(IBusMaster busMaster) {
this.busy = false;
busMaster.waitBus(this, false);
}
/**
* Dohvaća globalnu adresu na sabirnici iz para (jedinica, lokalnaAdresa)
* @param busUnit jedinica
* @param localAddress lokalna adresa (na jedinice)
* @return globalna adresa na sabirnici
*/
private Address getGlobalAddressFromLocal(IBusUnit busUnit,
Address localAddress) {
return new Address(Word.add(unitToAddress.get(busUnit).getStartAddress(), localAddress));
}
/**
* Dohvaća lokalnu adresu na jedinici iz globalne adrese na sabirnici
* @param busUnit jedinica
* @param globalAddress globalna adresa (na sabirnici)
* @return lokalna adresa (na jedinici)
*/
private Address getLocalAddressFromGlobal(IBusUnit busUnit, Address globalAddress) {
return new Address(Word.sub(globalAddress, unitToAddress.get(busUnit).getStartAddress()));
}
/**
* Dohvaća jedinicu kojoj pripada predana globalna adresa na sabirnici.
* @param globalAddress globalna adresa (na sabirnici)
* @return jedinica
*/
private IBusUnit getBusUnitFromGlobalAddress(Address globalAddress) throws UnknownAddressException {
for(AddressRange addressRange: addressToUnit.keySet()) {
if(addressRange.inRange(globalAddress)) {
return addressToUnit.get(addressRange);
}
}
throw new UnknownAddressException("Ta adresa nije nigdje mapirana!");
}
}
| Java |
package hr.fer.anna.events;
import hr.fer.anna.exceptions.IllegalActionException;
import hr.fer.anna.interfaces.IBus;
import hr.fer.anna.interfaces.IBusUnit;
import hr.fer.anna.model.Word;
import hr.fer.anna.uniform.Address;
/**
* Općeniti event koji se javlja prilikom rada jedinice na sabirnici
* @author Boran
*
*/
public class BusUnitOperationEvent extends SimulationEvent {
/** Sabirnica koja je odaslala ovaj event */
protected IBus bus;
/** Jedinica na sabirnici od koje zahtijevamo početak operacije */
protected IBusUnit busUnit;
/** Adresa unutar jedinice */
protected Address localAddress;
/** Riječi koje treba zapisati, ako pišemo */
protected Word[] words;
/** true ako pišemo, false ako ne pišemo */
protected boolean writing;
/** true ako čitamo, false ako ne čitamo */
protected boolean reading;
/** true ako je obavljena operacija, false inače */
protected boolean completed;
/**
* Defaultni konstruktor, služi isključivo za registriranje slušača.
*
* @param busUnit jedinica na sabirnici kojoj je event namijenjen
*/
public BusUnitOperationEvent(IBusUnit busUnit) {
super();
this.busUnit = busUnit;
}
/**
* Konstruktor za stvaranje općenitog eventa koji se javlja na sabirnici.
*
* @param bus sabirnica koja je postavila event
* @param busUnit jedinica kojoj se pristupa
* @param localAddress adresa unutar jedinice na sabirnici kojoj se pristupa
*/
public BusUnitOperationEvent(IBus bus, IBusUnit busUnit, Address localAddress) {
this.bus = bus;
this.busUnit = busUnit;
this.localAddress = localAddress;
}
/**
* Vraća adresu unutar jedinice na sabirnici.
*
* @return adresa
*/
public Address getLocalAddress() {
return this.localAddress;
}
/**
* Da li je obavljena operacija?
*
* @return true ako da, false inače
*/
public boolean isCompleted() {
return this.completed;
}
/**
* Vraća jedinicu na sabirnici kojoj je odaslan ovaj event.
*
* @return jedinica na sabirnici
*/
public IBusUnit getBusUnit() {
return this.busUnit;
}
/**
* Da li čitamo?
*
* @return true ako da, false inače
*/
public boolean reading() {
return this.reading;
}
/**
* Da li pišemo?
*
* @return true ako da, false inače
*/
public boolean writing() {
return this.writing;
}
/**
* Vraća podatke koje treba zapisati, ako se radi o zapisivanju. Ako se radi o čitanju,
* vraća podatke samo ako je obavljena operacija.
* @return riječi koje treba zapisati
*
* @throws IllegalActionException u slučaju da se radi o čitanju i operacija još nije završena
*/
public Word[] getWords() throws IllegalActionException {
if(!writing()) {
if(reading() && !isCompleted()) {
throw new IllegalActionException("Podaci još nisu dostupni jer nije obavljena operacija čitanja!");
}
}
return this.words;
}
/**
* Vraća bus koji je postavio ovaj event
*
* @return bus
*/
public IBus getBus() {
return this.bus;
}
/**
* Dva su eventa ovog tipa jednaka ako se radi o istoj jedinici na sabirnici. Jednakost
* služi za prosljeđivanje eventova slušačima koji su se na njih pretplatili.
*/
public boolean equals(Object obj) {
if(!(obj instanceof BusUnitOperationEvent)) {
return false;
}
BusUnitOperationEvent other = (BusUnitOperationEvent) obj;
return this.busUnit == other.busUnit;
}
public int hashCode() {
return this.busUnit.hashCode();
}
}
| Java |
package hr.fer.anna.events;
/**
* Event završetka operacije na jedinici. Event se odašilje kada je jedinica izvršila
* operaciju i sada treba dojaviti to sabinici.
* @author Boran
*
*/
public class BusUnitOperationCompletedEvent extends BusUnitOperationEvent {
/**
* Konstruktor koji stvara event završetka na temelju eventa početka operacije
* na jedinici.
* @param cause uzročni event koji je prouzrokovao ovaj event
*/
public BusUnitOperationCompletedEvent(BusUnitOperationEvent cause) {
super(cause.getBus(), cause.getBusUnit(), cause.getLocalAddress());
this.words = cause.words;
this.reading = cause.reading;
this.writing = cause.writing;
this.completed = true;
this.setCause(cause);
}
}
| Java |
package hr.fer.anna.events;
import hr.fer.anna.interfaces.IEventSetter;
import hr.fer.anna.interfaces.IProcessor;
/**
* Procesor odašilje ovaj event kao signal sebi da u idućem trenutku treba preći
* u iduće stanje.
* @author Boran
*
*/
public class NextProcessorStateEvent extends ProcessorEvent {
/**
* Konstruktor eventa prelaska u iduće stanje.
* @param eventSource jedinica koja je odaslala ovaj event, obično sam procesor
* @param processor procesor kome je namijenjen ovaj event prelaska u iduće stanje
*/
public NextProcessorStateEvent(IEventSetter eventSource, IProcessor processor) {
super(eventSource, processor);
}
}
| Java |
package hr.fer.anna.events;
import hr.fer.anna.interfaces.IBus;
import hr.fer.anna.interfaces.IBusUnit;
import hr.fer.anna.uniform.Address;
/**
* Event početka čitanja sa jedinice na sabirnici.
* @author Boran
*
*/
public class BusUnitReadStartEvent extends BusUnitOperationEvent {
/**
* Konstruktor eventa početka čitanja sa vanjske jedinice
* @param bus sabirnica koja je postavila zahtjev
* @param busUnit jedinica na sabirnici koja treba obaviti operaciju čitanja
* @param localAddress lokalna adresa jedinice s koje se čita
*/
public BusUnitReadStartEvent(IBus bus, IBusUnit busUnit, Address localAddress) {
super(bus, busUnit, localAddress);
this.reading = true;
this.writing = false;
this.completed = false;
}
}
| Java |
package hr.fer.anna.events;
import java.util.HashSet;
import java.util.Set;
import hr.fer.anna.interfaces.IEventSetter;
/**
* Container događaja (eventa).
* Služi za upravljanje eventom.
*/
public class SimulationEvent {
/** Komponenta koja je postavila event. */
private IEventSetter eventSource;
/** Vrijeme kad se event treba izvršiti. */
private long timeIndex;
/** Lista evenata o kojima trenutni event ovisi */
private Set<SimulationEvent> dependencies;
/** Event koji je zaslužan za stvaranje ovog eventa */
private SimulationEvent eventCause;
/**
* Defaultni konstruktor, služi isključivo za registriranje slušača.
*/
public SimulationEvent() {
this.dependencies = new HashSet<SimulationEvent>();
}
/**
* Konstruktor koji stvara tek osnovni event koji se mora izvršiti trenutno.
*
* @param eventSource Komponenta koja je postavila event
*/
public SimulationEvent(IEventSetter eventSource) {
this();
this.timeIndex = 0;
this.eventSource = eventSource;
}
/**
* Konstruktor koji stvara event koji se mora izvršiti u nekom trenutku.
*
* @param eventSource Komponenta koja je postavila event.
* @param myTimeIndex Vrijeme kad se event treba izvršiti.
*/
public SimulationEvent(IEventSetter eventSource, long myTimeIndex) {
this(eventSource);
this.timeIndex = myTimeIndex;
this.dependencies = new HashSet<SimulationEvent>();
}
/**
* Getter eventSourcea.
*
* @return Komponentu koja je postavila event.
*/
public IEventSetter getEventSource() {
return this.eventSource;
}
/**
* Da li trenutni event ovisi o eventu koji je prosljeđen.
*
* @param event Prosljeđen event (onaj za kojem želimo znati da li trenutni o njemu ovisi).
* @return True ako ovisi, inače false.
*/
public boolean checkDependency(SimulationEvent event) {
return this.dependencies.contains(event);
}
/**
* Postavlja trenutni event ovisan o prosljeđenom eventu.
*
* @param event Prosljeđen event (onaj za koji želimo da trenutni event bude ovisan o njemu).
*/
public void addDependency(SimulationEvent event) {
this.dependencies.add(event);
}
/**
* Dohvaća event koji je bio uzrok stvaranju ovog eventa.
* @return event uzročnik
*/
public SimulationEvent getCause() {
return this.eventCause;
}
/**
* Postavlja uzročnika nastajanja ovog eventa.
*
* @param eventCause event radi kojeg je stvoren ovaj event
*/
public void setCause(SimulationEvent eventCause) {
this.eventCause = eventCause;
}
/**
* Getter timeIndexa.
*
* @return Vrijeme kad se event treba izvršiti.
*/
public long getTimeIndex() {
return this.timeIndex;
}
/**
* Setter timeIndexa.
*
* @param timeIndex Vrijeme kad se event treba izvršiti.
*/
public void setTimeIndex(long timeIndex) {
this.timeIndex = timeIndex;
}
/**
* Dva eventa su jednaka ako su istog tipa.
*
* @return True ako su objekti ekvivalentni, inače false.
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
} else if (!(obj instanceof SimulationEvent)) {
return false;
} else {
return true;
}
}
/**
* Hash kod objekta. Jedini uvjet koji se postavlja je da dva jednaka prema metodi equals
* objekta imaju isti hash kod.
*
* @return Hash objekta.
*/
@Override
public int hashCode() {
return 0;
}
}
| Java |
package hr.fer.anna.events;
import hr.fer.anna.interfaces.IEventSetter;
import hr.fer.anna.interfaces.IProcessor;
/**
* Općeniti eventovi koji su namijenjeni procesoru.
* @author Boran
*
*/
public class ProcessorEvent extends SimulationEvent {
/** Procesor koji treba primiti i obraditi ovaj event */
private IProcessor processor;
/**
* Defaultni konstruktor, isključiva svrha mu je za uspoređivanje eventova.
* @param processor procesor kojemu je namijenjen event
*/
public ProcessorEvent(IProcessor processor) {
super();
this.processor = processor;
}
/**
* Konstruktor eventa.
*
* @param eventSource Objekt koji je postavio event.
* @param cpu Procesor koji treba primiti ovaj event.
*/
public ProcessorEvent(IEventSetter eventSource, IProcessor processor) {
super(eventSource);
this.processor = processor;
}
/**
* Konstruktor eventa.
*
* @param eventSource Objekt koji je postavio event.
* @param myTimeIndex Vrijeme kada se event treba obraditi.
* @param cpu procesor koji treba primiti i obraditi ovaj event
*/
public ProcessorEvent(IEventSetter eventSource, long myTimeIndex, IProcessor processor) {
super(eventSource, myTimeIndex);
this.processor = processor;
}
/**
* Dohvaća procesor koji treba primiti i obraditi ovaj event.
*
* @return procesor
*/
public IProcessor getCpu() {
return this.processor;
}
/**
* Dva su procesorska eventa jednaka ako su namijenjena su istom procesoru.
*/
public boolean equals(Object obj) {
if(!(obj instanceof ProcessorEvent)) {
return false;
}
ProcessorEvent other = (ProcessorEvent) obj;
return this.processor == other.processor;
}
public int hashCode() {
return this.processor.hashCode();
}
}
| Java |
package hr.fer.anna.events;
import hr.fer.anna.interfaces.IBus;
import hr.fer.anna.interfaces.IBusUnit;
import hr.fer.anna.model.Word;
import hr.fer.anna.uniform.Address;
/**
* Event početka pisanja u jedinicu na sabirnici.
* @author Boran
*
*/
public class BusUnitWriteStartEvent extends BusUnitOperationEvent {
/**
* Konstruktor eventa početka pisanja u jedinicu
* @param bus sabirnica koja je postavila zahtjev
* @param busUnit jedinica na sabirnici koja treba obaviti operaciju pisanja
* @param localAddress lokalna adresa jedinice na koju se piše
* @param words riječi koje se upisuju
*/
public BusUnitWriteStartEvent(IBus bus, IBusUnit busUnit, Address localAddress, Word[] words) {
super(bus, busUnit, localAddress);
this.words = words;
this.reading = false;
this.writing = true;
this.completed = false;
}
}
| Java |
package hr.fer.anna.GUI;
/**
* Poštar koji doprema razne poruke korisničkom sučelju.
*
* @author Ivan
*/
public class Postman {
private Postman() {
}
private static class SingletonHolder {
private static final Postman INSTANCE = new Postman();
}
public static Postman get() {
return SingletonHolder.INSTANCE;
}
/**
* Slanje poruke o greški.
*
* @param errMsg
*/
public void sendErrorMsg(String errMsg) {
// TODO: Napisati...
}
// TODO: Napisati sučelje err receivera i implementirati observer pattern
public void registerErrorReceiver() {
}
}
| Java |
package hr.fer.anna.GUI;
import java.awt.GridLayout;
import javax.swing.JPanel;
public class SimulatorView extends JPanel {
static final long serialVersionUID = 1;
private Project parent;
private boolean open;
private JPanel simPanel;
/**
* Default ModelView constructor.
*
* TODO: everything
*/
public SimulatorView(Project myParent){
parent = myParent;
open = false;
simPanel = new JPanel();
this.setLayout(new GridLayout());
add(simPanel);
}
public void setOpen(boolean value){
open = value;
}
public boolean isOpen(){
return open;
}
public JPanel getSimPanel() {
return simPanel;
}
public void setSimPanel(JPanel simmPanel) {
this.simPanel = simmPanel;
}
}
| Java |
package hr.fer.anna.GUI;
import hr.fer.anna.exceptions.*;
/**
* Class that contains all stuff behind managing one project.
* Including but not limited to:
* Model view, Editor view, Simulation view
* Filename, Project configuration
*
* @author marko
* @version 0.1
*/
public class Project {
private ModelView modelView;
private EditorView editorView;
private SimulatorView simView;
private Window parent;
private String code;
private String name;
private ArchDisplay arch;
public ArchDisplay getArch() {
return arch;
}
public void setArch(ArchDisplay arch) {
this.arch = arch;
simView.getSimPanel().add( arch.getSimPanel() );
}
/**
* Creates "unnamed" project.
*
* TODO: everything
*/
Project(Window myParent){
setParent(myParent);
editorView = new EditorView(this);
simView = new SimulatorView(this);
modelView = new ModelView(this);
setProjectName("New project");
showModelView();
}
public void setProjectName(String newName){
name = newName;
modelView.updateName();
if ( modelView.isOpen() ){
try {
parent.setTabName(parent.getTabIndex(modelView), name + " - model");
}
catch (InvalidRequest e){
//TODO: nist
}
}
if ( editorView.isOpen() ){
try {
parent.setTabName(parent.getTabIndex(editorView), name + " - editor");
}
catch (InvalidRequest e){
//TODO: nist
}
}
if ( simView.isOpen() ){
try {
parent.setTabName(parent.getTabIndex(simView), name + " - status");
}
catch (InvalidRequest e){
//TODO: nist
}
}
}
public String getProjectName(){
return name;
}
public void showModelView(){
if ( !modelView.isOpen() ) {
modelView.setOpen(true);
parent.addTab(getProjectName() + " - model", modelView);
}
}
public void showEditorView(){
if ( !editorView.isOpen() ) {
editorView.setOpen(true);
parent.addTab(getProjectName() + " - code", editorView);
}
try {
parent.setTabFocus(parent.getTabIndex(editorView));
}
catch ( InvalidRequest e ){
}
}
public void showSimView(){
if ( !simView.isOpen() ) {
simView.setOpen(true);
parent.addTab(getProjectName() + " - status", simView);
}
try {
parent.setTabFocus(parent.getTabIndex(simView));
}
catch ( InvalidRequest e ){
}
}
/**
* Returns the ModelView component for this project.
*
* @author marko
*/
public ModelView getModelView(){
return modelView;
}
/**
* Return the EditorView component for this project.
*/
public EditorView getEditorView(){
return editorView;
}
public Window getParent() {
return parent;
}
public void setParent(Window parent) {
this.parent = parent;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String assemble(){
return arch.assemble(code);
}
}
| Java |
package hr.fer.anna.GUI;
import javax.swing.JPanel;
public abstract class ArchDisplay {
public abstract JPanel getModelPanel();
public abstract JPanel getSimPanel();
public abstract String assemble(String code);
}
| Java |
package hr.fer.anna.GUI;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JComboBox;
/**
* Component to be used as a tabComponent.
* Contains the model configuration dialogue.
*
* @author marko
* @version 0.1
*/
public class ModelView extends JPanel {
static final long serialVersionUID = 1;
private Project parent;
boolean open;
JTextField nameTextField;
/**
* Default ModelView constructor.
*
* TODO: everything
* @author Marko
*/
public void updateName(){
nameTextField.setText(parent.getProjectName());
}
public ModelView(Project myParent){
parent = myParent;
open = false;
setLayout(new BorderLayout());
// add z properties
JPanel modelPane = new JPanel();
modelPane.setLayout(new BoxLayout(modelPane, BoxLayout.PAGE_AXIS));
modelPane.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 10));
// project name
JPanel namePane = new JPanel();
namePane.setLayout(new BoxLayout(namePane, BoxLayout.LINE_AXIS));
JLabel nameLabel = new JLabel("Project name:");
namePane.add(nameLabel);
namePane.add(Box.createRigidArea(new Dimension(10, 0)));
nameTextField = new JTextField(20);
//nameTextField.setText(parent.getProjectName());
nameTextField.setMaximumSize(new Dimension(100, 30));
nameTextField.setText(parent.getProjectName());
nameTextField.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
parent.setProjectName(nameTextField.getText());
}
});
namePane.add(nameTextField);
namePane.add(Box.createHorizontalGlue());
modelPane.add(namePane);
// Arch chooser
JPanel classPane = new JPanel();
classPane.setLayout(new BoxLayout(classPane, BoxLayout.LINE_AXIS));
classPane.add(new JLabel("Architecture:"));
classPane.add(Box.createRigidArea(new Dimension(10, 0)));
String[] defaultClasses = { "OISC" };
JComboBox classCombo = new JComboBox(defaultClasses);
classCombo.setMaximumSize(new Dimension(200, 30));
classPane.add(classCombo);
classPane.add(Box.createHorizontalGlue());
modelPane.add(classPane);
// determine the correct arch
ArchDisplay selectedArch = new hr.fer.anna.oisc.OISCArchDisplay(this);
if ( classCombo.getSelectedItem().toString() == "OISC" )
selectedArch = new hr.fer.anna.oisc.OISCArchDisplay(this);
parent.setArch(selectedArch);
// Arch pane
JPanel archPane = selectedArch.getModelPanel();
modelPane.add(archPane);
modelPane.add(Box.createVerticalGlue());
add(BorderLayout.CENTER, modelPane);
// add z buttonz
JPanel buttonPane = new JPanel();
JButton codeButton = new JButton("Editor");
JButton simulateButton = new JButton("Simulator");
codeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
parent.showEditorView();
}
});
simulateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
parent.showSimView();
}
});
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
buttonPane.add(Box.createHorizontalGlue());
buttonPane.add(codeButton);
buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPane.add(simulateButton);
add(BorderLayout.SOUTH, buttonPane);
}
public void setOpen(boolean value){
open = value;
}
public boolean isOpen(){
return open;
}
}
| Java |
package hr.fer.anna.GUI;
import hr.fer.anna.exceptions.*;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.UIManager;
/**
* Main frame
*
* @author Ivan
* @version 0.2
*/
public class Window extends JFrame {
public static final long serialVersionUID = 1;
// TODO: array or something....
private ArrayList<Project> project;
/**
* GUI Constructor
*
* @author Ivan
* @since 0.1
*/
public Window() {
initGUI();
// TODO: Set some normal size, dynamic?
this.setSize(500, 400);
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.setTitle("ANNA");
this.setLocationByPlatform(true);
this.setVisible(true);
}
private JLabel statusBar;
private JMenuBar menuBar;
private JTabbedPane mainArea;
protected void addTab(String name, JPanel tab){
mainArea.addTab(name, tab);
}
protected int getTabIndex(JComponent tab) throws InvalidRequest{
int i = mainArea.indexOfComponent(tab);
if ( i == -1 ) throw new InvalidRequest("");
return i;
}
protected int getTabIndex(String name){
return mainArea.indexOfTab(name);
}
protected void setTabName(int tab, String name){
mainArea.setTitleAt(tab, name);
}
protected void setTabFocus(int tab){
mainArea.setSelectedIndex(tab);
}
/**
* Initialize the GUI.
*
* @author Marko
* @since 0.2
*/
protected void initGUI() {
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e){
// TODO: ajdontnow, blow shit up
}
getContentPane().setLayout(new BorderLayout());
// Adds the menu bar
menuBar = new JMenuBar();
JMenu menuFile = new JMenu("File");
JMenu menuHelp = new JMenu("Help");
menuBar.add(menuFile);
JMenuItem menuExit = new JMenuItem("Exit");
JMenuItem menuNew = new JMenuItem("New");
menuFile.add(menuNew);
menuFile.add(menuExit);
final Window me = this;
project = new ArrayList<Project>(0);
menuNew.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
// TODO: add to thread, could be slow
project.add(new Project(me));
}
});
menuExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
// TODO: cleanup?
System.exit(0);
}
});
menuBar.add(menuHelp);
JMenuItem menuAbout = new JMenuItem("About");
menuHelp.add(menuAbout);
// About box, TODO: organize this a lot! :)
final JPanel aboutPanel = new JPanel();
final JLabel aboutLabel = new JLabel("ANNA Nije Novi Atlas :)");
aboutPanel.add(aboutLabel);
menuAbout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
mainArea.addTab("About", aboutPanel);
}
});
add(BorderLayout.NORTH, menuBar);
// Adds the status bar
statusBar = new JLabel("Welcome to ANNA, the only simulator that cares!");
add(BorderLayout.SOUTH, statusBar);
// Adds the main work area, tabbed, oh yeah! :)
mainArea = new JTabbedPane();
add(BorderLayout.CENTER, mainArea);
}
/**
* Main entry point for the application
*
* @param args
* Command line arguments
* @author Ivan
* @since 0.1
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Window();
}
});
return;
}
}
| Java |
package hr.fer.anna.GUI;
import org.jedit.syntax.*;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
/**
* Component to be used as a tabComponent.
* Contains the assembly editor and debug info.
*
* @author marko
* @version 0.1
*/
public class EditorView extends JPanel {
static final long serialVersionUID = 1;
private JLabel editorArea;
private Project parent;
private boolean open;
/**
* Default ModelView constructor.
*
* TODO: everything
*/
public EditorView(Project myParent){
parent = myParent;
open = false;
setLayout(new BorderLayout());
// add z text area
final JPanel editorPane = new JPanel();
editorPane.setLayout(new BoxLayout(editorPane, BoxLayout.PAGE_AXIS));
editorPane.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 10));
final JEditTextArea textArea = new JEditTextArea();
textArea.setTokenMarker(new PythonTokenMarker());
textArea.setCaretBlinkEnabled(true);
editorPane.add(textArea);
add(BorderLayout.CENTER, editorPane);
// add z buttonz
JPanel buttonPane = new JPanel();
JButton assembleButton = new JButton("Assemble");
assembleButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
parent.setCode( textArea.getText() );
String ret = parent.assemble();
JOptionPane.showMessageDialog(editorPane, ret, "Assembly return", JOptionPane.INFORMATION_MESSAGE);
}
});
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
buttonPane.add(Box.createHorizontalGlue());
buttonPane.add(assembleButton);
add(BorderLayout.SOUTH, buttonPane);
}
public void setOpen(boolean value){
open = value;
}
public boolean isOpen(){
return open;
}
}
| Java |
package hr.fer.anna.frisc.assembler;
/**
* Naredba programa.
*
* @author Ivan
*/
public class Command {
private byte[] byteCode;
private int column;
private int line;
private Command nextCommand;
public Command(byte[] byteCode, int column, int line) {
super();
this.column = column;
this.line = line;
this.byteCode = byteCode;
}
public int getColumn() {
return column;
}
public int getLine() {
return line;
}
/**
* @return Strojni kod naredbe.
*/
public byte[] getByteCode() {
return byteCode;
}
public Command getNextCommand() {
return nextCommand;
}
public void setNextCommand(Command nextCommand) {
this.nextCommand = nextCommand;
}
}
| Java |
package hr.fer.anna.frisc.assembler;
import java.util.HashMap;
public class SymLookup {
private HashMap<Integer, String> hashMap;
public SymLookup() {
hashMap = new HashMap<Integer, String>();
hashMap.put(28,"STOREH");
hashMap.put(59,"UVJ_Z");
hashMap.put(75,"OKTALNA_KONSTANTA");
hashMap.put(27,"STOREB");
hashMap.put(53,"UVJ_V");
hashMap.put(6,"PSEUDO_POSTO");
hashMap.put(72,"KRAJ_REDA");
hashMap.put(58,"UVJ_P");
hashMap.put(37,"HALT");
hashMap.put(55,"UVJ_N");
hashMap.put(57,"UVJ_M");
hashMap.put(51,"UVJ_C");
hashMap.put(64,"UVJ_UGT");
hashMap.put(71,"POCETNA_PRAZNINA");
hashMap.put(68,"UVJ_SGT");
hashMap.put(22,"MOVE");
hashMap.put(66,"UVJ_UGE");
hashMap.put(30,"POP");
hashMap.put(11,"SUB");
hashMap.put(18,"SHR");
hashMap.put(70,"UVJ_SGE");
hashMap.put(25,"LOADH");
hashMap.put(17,"SHL");
hashMap.put(24,"LOADB");
hashMap.put(65,"UVJ_ULT");
hashMap.put(12,"SBC");
hashMap.put(61,"UVJ_EQ");
hashMap.put(77,"KOMENTAR");
hashMap.put(43,"AP_DW");
hashMap.put(3,"L_ZAGRADA");
hashMap.put(42,"AP_DS");
hashMap.put(69,"UVJ_SLT");
hashMap.put(26,"STORE");
hashMap.put(63,"UVJ_ULE");
hashMap.put(40,"AP_END");
hashMap.put(76,"LABELA");
hashMap.put(39,"AP_ORG");
hashMap.put(8,"SR_REGISTAR");
hashMap.put(67,"UVJ_SLE");
hashMap.put(5,"PLUS");
hashMap.put(2,"ZAREZ");
hashMap.put(44,"DW");
hashMap.put(32,"JR");
hashMap.put(9,"ADD");
hashMap.put(10,"ADC");
hashMap.put(31,"JP");
hashMap.put(29,"PUSH");
hashMap.put(46,"DH");
hashMap.put(21,"ROTR");
hashMap.put(23,"LOAD");
hashMap.put(45,"DB");
hashMap.put(20,"ROTL");
hashMap.put(0,"EOF");
hashMap.put(4,"D_ZAGRADA");
hashMap.put(50,"PSEUDO_O");
hashMap.put(15,"OR");
hashMap.put(49,"PSEUDO_H");
hashMap.put(1,"error");
hashMap.put(48,"PSEUDO_D");
hashMap.put(47,"PSEUDO_B");
hashMap.put(34,"RET");
hashMap.put(7,"REGISTAR");
hashMap.put(74,"HEKSA_KONSTANTA");
hashMap.put(60,"UVJ_NZ");
hashMap.put(41,"AP_EQU");
hashMap.put(54,"UVJ_NV");
hashMap.put(38,"AP_BASE");
hashMap.put(56,"UVJ_NN");
hashMap.put(73,"DEKADSKA_KONSTANTA");
hashMap.put(36,"RETN");
hashMap.put(14,"AND");
hashMap.put(62,"UVJ_NE");
hashMap.put(35,"RETI");
hashMap.put(52,"UVJ_NC");
hashMap.put(19,"ASHR");
hashMap.put(33,"CALL");
hashMap.put(13,"CMP");
hashMap.put(16,"XOR");
}
public String lookup(int sym) {
return hashMap.get(sym);
}
}
| Java |
package hr.fer.anna.frisc.assembler;
import java.io.IOException;
import java.io.StringReader;
/**
* Procesiranje prije asembliranja.
* - Dodavanje oznake '^' umjesto praznine na početku linije.
* - Mijenja uvjete iz _EQ u &EQ (radi problema sa lexom)
*
* @author Ivan
*
*/
public class Preprocessor {
public static String process(String code) {
try {
code = hackCondition(code);
code = addBeginningSpaceMark(code);
return code;
} catch (IOException e) {
return null;
}
}
/**
* Zaobilazak problema sa lexom.
* Izraz JR_EQ lex prepoznaje (iz nepoznatog razloga) kao labelu
* umjesto naredbu i uvjet.
* Sad su uvjeti &EQ umjesto _EQ.
*
* @param code
* @return
*/
private static String hackCondition(String code) {
return code.replaceAll("(?i)(JP|JR|CALL|RET|RETI|RETN|HALT)_([C|NC|V|NV|N|NN|M|P|Z|NZ|EQ|NE|ULE|UGT|ULT|UGE|SLE|SGT|SLT|SGE])", "$1&$2");
}
/**
* Svim linijama koje počinju s prazninom dodaje posebnu
* oznaku '^' umjesto praznine da bi se znalo da je to
* početna praznina.
*
* @param code Programski kod.
* @return Kod s označenim početnim prazninama.
* @throws IOException
*/
private static String addBeginningSpaceMark(String code) throws IOException {
StringReader reader = new StringReader(code);
StringBuilder sb = new StringBuilder(code.length());
boolean nl = true;
while (true) {
int ch = reader.read();
if (ch == -1) break;
if ((ch == ' ' || ch == '\t') && nl) {
sb.append('^');
} else {
sb.append((char) ch);
}
nl = (ch == '\n');
}
return sb.toString();
}
}
| Java |
package hr.fer.anna.frisc.assembler;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Stack;
public class Assemble {
public static String readFile(File f) throws Exception {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
} catch (FileNotFoundException ex) {
throw new Exception("Ne postoji datoteka " + f.getName());
} catch (Exception e) {
throw new Exception("Nemogu otvoriti datoteku " + f.getName());
}
StringBuilder sb = new StringBuilder();
try {
int c;
while ((c = reader.read()) != -1) {
sb.append((char) c);
}
} catch (Exception e) {
throw new Exception("Nemogu čitati iz datoteke " + f.getName());
}
return sb.toString();
}
public static Commands assemble(File f) throws Exception {
return assemble(readFile(f));
}
public static Commands assemble(String code) {
String preprocessedCode = Preprocessor.process(code);
Commands naredbe = null;
Stack<String> cmdLblStack = new Stack<String>();
Map<String, Integer> labels = new HashMap<String, Integer>();
System.out.println("Start!");
Stack<Integer> niz = new Stack<Integer>();
try {
// SymLookup look = new SymLookup();
// LexicalAnalyser la = new LexicalAnalyser(new StringReader(preprocessedCode));
// while (true) {
// Symbol s = la.next_token();
// if (s == null || s.sym == AssemblerLabelsSym.EOF) {
// break;
// } else {
// System.out.println(look.lookup(s.sym));
// }
// }
// if (1+1==3-1) {
// System.out.println("KRAJ!!!");
// return null;
// }
// TODO: Poveži labele
AssemblerLabels aslc = new AssemblerLabels(
new LexicalAnalyser(new StringReader(preprocessedCode)));
aslc.parse();
LabelsMap.get().printContents();
//AssemblerCup asm = new AssemblerCup(new LexicalAnalyser(new StringReader(preprocessedCode)));
//asm.parse() // TODO Neka parse() vraća Commands
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Kraj");
return naredbe;
}
}
| Java |
package hr.fer.anna.frisc.assembler;
import java.io.File;
public class Test {
public static void main(String[] args) throws Exception {
Assemble.assemble(new File("tests-data/frisc-assembler/ik42696_lab1_vj1.a"));
}
}
| Java |
package hr.fer.anna.frisc.assembler;
import java.util.HashMap;
import java.util.Map;
/**
* Mapiranje labela.
* Inicijalizacija i način korištenja malo krše ideju singletona,
* no i ovo je ok.
*
* @author Ivan
*/
public class LabelsMap {
private Map<String, Integer> labels;
private LabelsMap() {
this.labels = new HashMap<String, Integer>();
}
/**
* Inicijalizacija
*/
public void init() {
this.labels.clear();
}
private static class SingletonHolder {
private static final LabelsMap INSTANCE = new LabelsMap();
}
public static LabelsMap get() {
return SingletonHolder.INSTANCE;
}
public void mapLabel(String label, Integer value) {
this.labels.put(label, value);
}
public Integer getLabelValue(String label) {
return this.labels.get(label);
}
public void printContents() {
for (String key : this.labels.keySet()) {
System.out.println(key + " - " + this.labels.get(key));
}
}
}
| Java |
package hr.fer.anna.frisc.assembler;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Niz naredbi koji predstavlja program.
*
* @author Ivan
*
* TODO: Prebaciti u odgovarajući paket
*/
public class Commands implements Iterable<Command> {
private List<Command> commands;
public Commands() {
this.commands = new ArrayList<Command>();
}
public void addCommand(byte[] byteCode, int column, int line) {
this.commands.add(new Command(byteCode, column, line));
}
public Command getCommand(int index) {
return commands.get(index);
}
@Override
public Iterator<Command> iterator() {
return new Iterator<Command>() {
private int nextCommand = 0;
@Override
public void remove() {
throw new UnsupportedOperationException("Method is not supported for this class");
}
@Override
public Command next() {
return commands.get(nextCommand++);
}
@Override
public boolean hasNext() {
return (nextCommand < commands.size());
}
};
}
}
| Java |
package hr.fer.anna.simulator;
import hr.fer.anna.events.SimulationEvent;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
/**
* Queue koji drži elemente koje treba izvršavati, elementi su poredani prema
* rastućim vremenskim indeksima i tako da se elementi o kojima su neki drugi
* elementi ovisni nalaze prije njih, formalno, za bilo koja 2 elementa A i B
* gdje se A nalazi prije B vrijedi: A.getTimeIndex() < B.getTimeIndex &&
* B.checkDependency(A) == true
*
* @author Boran
*
*/
public class EventQueue extends LinkedList<SimulationEvent> {
private static final long serialVersionUID = 1L;
/**
* Defaultni konstruktor, vraća prazan EventQueue.
*/
public EventQueue() {
super();
}
/**
* Dodaje element e tako da i dalje vrijede svojstva EventQueue-a.
*/
@Override
public boolean add(SimulationEvent e) {
// TODO: Ovo treba bolje implementirati (npr, možda čak preko Set-a, ali
// ne dirati onda equals i hashCode metode
int newPos = 0;
Iterator<SimulationEvent> iterator = iterator();
while (iterator.hasNext()) {
SimulationEvent compareToEvent = iterator.next();
if (e.getTimeIndex() < compareToEvent.getTimeIndex()
|| compareToEvent.checkDependency(e)) {
break;
}
newPos++;
}
super.add(newPos, e);
return true;
}
/**
* Dodaje kolekciju elemenata tako da i dalje vrijede svojstva EventQueue-a.
*/
@Override
public boolean addAll(Collection<? extends SimulationEvent> c) {
// TODO: Optimizirati ovo
for (SimulationEvent e : c) {
if (add(e) == false) {
return false;
}
}
return true;
}
}
| Java |
package hr.fer.anna.simulator;
import hr.fer.anna.events.SimulationEvent;
import hr.fer.anna.exceptions.SimulationException;
import hr.fer.anna.interfaces.IEventListener;
import hr.fer.anna.interfaces.IEventSetter;
import hr.fer.anna.interfaces.IInternalDebugger;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Simulator. Glavna komponenta simulacije koja spaja i kontrolira ostale
* komponente.
*/
public class Simulator implements Runnable {
/** Vrijeme simulacije. */
protected long time;
/** Flag kojim se zaustavlja simulacija. */
protected volatile boolean isRunning;
/** Flag kojim se pauzira simulacija. */
protected volatile boolean isPaused;
/** Kolekcija evenata koji se trebaju izvršiti. */
protected EventQueue eventQueue;
/** Za svaki event vraća slušače koji su za njega zainteresirani. */
protected Map<SimulationEvent, Set<IEventListener>> eventListeners;
/** Debugger kojemu se šalju sve iznimke tokom simulacije */
protected IInternalDebugger internalDebugger;
/**
* Konstruktor simulatora.
*/
public Simulator() {
this.eventQueue = new EventQueue();
this.isRunning = false;
this.isPaused = false;
this.eventListeners = new HashMap<SimulationEvent, Set<IEventListener>>();
}
/**
* Postavljanje novog eventa u eventQueue, ako unutar eventa nije zadan
* trenutak izvršavanja, vrijeme izvršavanja će postati trenutno vrijeme
* simulatora.
*
* @param e Novi event.
*/
public void setNewEvent(SimulationEvent e) {
if (e.getTimeIndex() < this.time) {
e.setTimeIndex(this.time);
}
this.eventQueue.add(e);
}
/**
* Postavljanje novog eventa koji se treba izvršiti u nekom određenom
* trenutku.
*
* @param e Novi event
* @param timeIndex Trenutak u kojem se treba izvršiti
*/
public void setNewEvent(SimulationEvent e, long timeIndex) {
e.setTimeIndex(timeIndex);
setNewEvent(e);
}
/**
* Postavljanje novog eventa koji se treba izvršiti nakon što protekne određeno
* vrijeme od trenutnog trenutka.
*
* @param e Novi event
* @param timeOffset Za koliko se treba izvršiti event
*/
public void setNewEvent(SimulationEvent e, int timeOffset) {
e.setTimeIndex(time + timeOffset);
setNewEvent(e);
}
/**
* Odregistrira slušača.
*
* @param eventListener Slušač.
*/
public void unregisterEventListener(IEventListener eventListener) {
for(SimulationEvent event : eventListener.getEvents()) {
this.eventListeners.get(event).remove(eventListener);
}
}
/**
* Registrira postavljatela eventova
* @param eventSetter postavljatelj eventova
*/
public void registerEventSetter(IEventSetter eventSetter) {
eventSetter.init(this);
}
/**
* Registrira postavljatelje eventova
* @param eventSetters postavljatelji eventova
*/
public void registerEventSetters(IEventSetter[] eventSetters) {
for(IEventSetter eventSetter : eventSetters) {
registerEventSetter(eventSetter);
}
}
/**
* Registrira slušača na eventove koje slušača interesiraju.
*
* @param eventListener Slušač.
*/
public void registerEventListener(IEventListener eventListener) {
for (Method method : eventListener.getClass().getMethods()) {
if(method.isAnnotationPresent(handles.class)) {
handles what = method.getAnnotation(handles.class);
for (Class<? extends SimulationEvent> event : what.events()) {
System.out.println(event.toString());
}
}
}
for(SimulationEvent event : eventListener.getEvents()) {
if (!this.eventListeners.containsKey(event)) {
this.eventListeners.put(event, new HashSet<IEventListener>());
}
this.eventListeners.get(event).add(eventListener);
}
}
/**
* Registrira slušače na eventove koje slušače interesiraju.
* Svakog slušača registrira samo na eventove koji njega interesiraju.
* @param eventListeners Slušači.
*/
public void registerEventListeners(IEventListener[] eventListeners) {
for(IEventListener eventListener : eventListeners) {
registerEventListener(eventListener);
}
}
/**
* Nastavak simulacije nakon pauze.
*/
public synchronized void continueSimulation() {
this.isPaused = false;
}
/**
* Pauziranje simulacije.
*/
public synchronized void pauseSimulation() {
this.isPaused = true;
}
/**
* Zaustavljanje simulacije.
*/
public void stopSimulation() {
this.eventQueue.clear();
this.isRunning = false;
}
/**
* Dohvaća debuggera simulacije
* @return debugger simulacije
*/
public IInternalDebugger getInternalDebugger() {
return this.internalDebugger;
}
/**
* Postavlja novog debuggera simulacije
* @param internalDebugger novi debugger simulacije
*/
public void setInternalDebugger(IInternalDebugger internalDebugger) {
this.internalDebugger = internalDebugger;
}
/**
* Simuliranje. Pseudokod glavnog dijela: <br />
* 1) Dohvati event. <br />
* 2) Postavi novo simulacijsko vrijeme. <br />
* 3) Prosljedi event slušačima koji su se pretplatili na njega. <br />
*/
public void run() {
this.time = 0;
this.isRunning = true;
SimulationEvent event = null;
while (this.isRunning) {
while (this.isPaused); // Pauziranje simulatora
if (this.eventQueue.isEmpty()) {
this.isRunning = false;
break;
}
event = this.eventQueue.remove();
this.time = event.getTimeIndex();
if (this.eventListeners.containsKey(event)) {
for (IEventListener eventListener : this.eventListeners.get(event)) {
try {
eventListener.act(event);
} catch (SimulationException e) {
// TODO: Što ako ne postoji interni debugger?
if(!(this.internalDebugger.reportException(e))) {
this.stopSimulation();
}
}
}
}
}
}
/**
* Getter vremena simulacije.
*
* @return Vrijeme simulacije.
*/
public long getSimulatorTime() {
return this.time;
}
/**
* Je li simulacija pauzirana.
*
* @return True ako je simulacija pauzirana, inače false.
*/
public boolean isPaused() {
return this.isPaused;
}
}
| Java |
package hr.fer.anna.simulator;
import hr.fer.anna.events.SimulationEvent;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Anotacija obilježava eventove koji interesiraju slušača. Dodaje se metodi koja
* treba reagirati na te eventove.
* @author Boran
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface handles {
/**
* Eventovi na koje je metoda spremna reagirati.
* @return eventovi
*/
public Class<? extends SimulationEvent>[] events();
}
| Java |
package hr.fer.anna.model;
import hr.fer.anna.interfaces.IWordChangeListener;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Riječ je elementarna jedinica modela za zapisivanje podataka. Varijabilne je širine (u bitovima).
* @author Boran
*
*/
public class Word {
/** Podatkovni bitovi grupirani u 24-bitne grupe (int se koristi radi predznaka i drugih ograničenja VM-a) */
protected int[] data;
/** Predefinirana veličina grupe - 24-bita */
protected final int groupSize = 24;
/** Broj 24-bitnih grupa koje riječ zauzima */
protected int groups;
/** Širina (u bitovima) */
protected int width;
/** Bit viška pri određenim operacijama, služi kasnije za aritmetičke i logičke operacije */
protected boolean excessBit;
/** Slušači promjene vrijednosti podatkovne riječi. */
protected Set<IWordChangeListener> listeners;
/**
* Defaultni konstruktor, stvara podatkovnu riječ širine 32 bita
*/
public Word() {
this(32);
}
/**
* Konstrukor koji stvara podatkovnu riječ zadane širine
* @param width širina (u bitovima)
*/
public Word(int width) {
this.width = width;
groups = (int) Math.round(Math.ceil(width / (double) groupSize));
data = new int[groups];
excessBit = false;
}
/**
* Stvara podatkovnu riječ istog sadržaja (kloniranog) kao predana podatkovna riječ
* @param word podatkovna riječ
*/
public Word(Word word) {
this.groups = word.groups;
this.excessBit = false;
this.width = word.width;
this.data = word.data.clone();
}
/**
* Dohvaća širinu podatkovne riječi.
*
* @return Širina podatkovne riječi (u bitovima)
*/
public int getWidth() {
return this.width;
}
/**
* Registriranje slušača promjene vrijednosti podatkovne riječi.
*
* @param listener Pratitelj promjene koji se registrira.
*/
public void registerListener(IWordChangeListener listener) {
if (this.listeners == null) {
this.listeners = new HashSet<IWordChangeListener>();
}
this.listeners.add(listener);
}
/**
* Micanje registracije slušača promjene vrijednosti podatkovne riječi.
*
* @param listener Pratitelj promjene koji miče registraciju.
*/
public void unregisterListener(IWordChangeListener listener) {
if (this.listeners == null) {
return;
}
this.listeners.remove(listener);
}
/**
* Javljanje slušačima da je došlo do promjene.
*/
protected void updateListeners() {
if (this.listeners == null) {
return;
}
for (IWordChangeListener listener : this.listeners) {
listener.update(this);
}
}
/**
* Postavlja novu vrijednost podatkovne riječi (klonira predanu). Ovu metodu
* je preporučeno koristiti za postavljanje riječi. Samo u rijetkim slučajevima
* je dozvoljeno pridruživanje reference jer to može dovesti do neželjenih posljedica.
* @param word nova vrijednost
* @return riječ
*/
public Word set(Word word) {
if (word.width != this.width) {
throw new IllegalArgumentException("Širina nove vrijednosti je veća od širine podatkovne riječi! Nije moguće pridružiti novu vrijednost!");
}
for (int i = 0; i < this.data.length; i++) {
this.data[i] = word.data[i];
}
updateListeners();
return this;
}
/**
* Vraća vrijednost riječi zapisanu kao heksadecimalni broj
* @return hex-vrijednost riječi
*/
public String getHexString() {
StringBuilder sb = new StringBuilder((int) Math.round(Math.ceil(this.width / 8.0)));
int i = this.groups - 1;
while (this.data[i] == 0 && i > 0) {
i--;
}
sb.append(Integer.toHexString(this.data[i]));
for (i--; i >= 0; i--) {
for (int shift = 20; shift >= 0; shift -= 4) {
int hex = (this.data[i] >>> shift) & 0xF;
if (hex < 10) {
sb.append(hex);
} else {
sb.append((char)((int)'a' + hex - 10));
}
}
}
return sb.toString().toUpperCase();
}
/**
* Dvije su podatkovne riječi jednake ako su iste širine i istog su sadržaja
* (bitovi na pozicijama <code>i</code> su jednaki).
*/
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Word)) {
return false;
}
Word other = (Word) obj;
if (this.width != other.width) {
return false;
}
return Arrays.equals(this.data, other.data);
}
@Override
public int hashCode() {
return Arrays.hashCode(this.data);
}
/**
* Obavlja operaciju <code>or</code> između podatkovnih riječi i vraća rezultat.
* @param word1 prvi operand
* @param word2 drugi operand
* @return rezultat je bitwise-or podatkovnih riječi
*/
public static Word or(Word word1, Word word2) {
assertEqualWordLengths(word1, word2);
Word res = new Word(word1.width);
for (int i = 0; i < res.data.length; i++) {
res.data[i] = (word1.data[i] | word2.data[i]);
}
return res;
}
/**
* Obavlja operaciju <code>and</code> između podatkovnih riječi i vraća rezultat.
* @param word1 prvi operand
* @param word2 drugi operand
* @return rezultat je bitwise-and podatkovnih riječi
*/
public static Word and(Word word1, Word word2) {
assertEqualWordLengths(word1, word2);
Word res = new Word(word1.width);
for (int i = 0; i < res.data.length; i++) {
res.data[i] = (word1.data[i] & word2.data[i]);
}
return res;
}
/**
* Obavlja operaciju <code>xor</code> između podatkovnih riječi i vraća rezultat.
* @param word1 prvi operand
* @param word2 drugi operand
* @return rezultat je bitwise-xor podatkovnih riječi
*/
public static Word xor(Word word1, Word word2) {
assertEqualWordLengths(word1, word2);
Word res = new Word(word1.width);
for (int i = 0; i < res.data.length; i++) {
res.data[i] = (word1.data[i] ^ word2.data[i]);
}
return res;
}
/**
* Obavlja operaciju <code>not</code> podatkovne riječi i vraća rezultat.
* @param word podatkovna riječ
* @return rezultat je bitwise-not podatkovne riječi
*/
public static Word not(Word word) {
Word res = new Word(word.width);
for (int i = 0; i < res.data.length; i++) {
res.data[i] = ~word.data[i];
}
cleanExtraBits(res);
return res;
}
public static Word add(Word word1, Word word2) {
Word result = new Word(word1.width);
add(result, word1, word2, false);
return result;
}
/**
* Obavlja operaciju zbrajanja dviju podatkovnih riječi i sprema rezultat
* @param result riječ u koju će biti spremljen rezultat
* @param word1 prvi operand
* @param word2 drugi operand
* @param carryIn ulazni prijenos
* @return izlazni prijenos
*/
public static boolean add(Word result, Word word1, Word word2, boolean carryIn) {
assertEqualWordLengths(word1, word2);
int carryNext = carryIn ? 1 : 0;
for (int i = 0; i < result.data.length; i++) {
int tempRes = (int)word1.data[i] + (int)word2.data[i] + carryNext;
if(tempRes > 0xFFFFFF) {
carryNext = 1;
} else {
carryNext = 0;
}
result.data[i] = tempRes;
}
cleanExtraBits(result);
return result.excessBit;
}
/**
* Obavlja operaciju oduzimanja drugog operanda od prvog operanda
* @param word1 prvi operand
* @param word2 drugi operand
* @return zbroj podatkovnih riječi
*/
public static Word sub(Word word1, Word word2) {
assertEqualWordLengths(word1, word2);
Word result = new Word(word1.width);
Word inverted = Word.not(word2);
add(result, word1, inverted, true);
return result;
}
/**
* Obavlja logički posmak ulijevo za <code>locations</code> mjesta. Pomicanje ulijevo je
* ekvivalentno množenju s 2.
* @param word riječ koju treba posmaknuti
* @param locations za koliko pozicija posmaknuti
* @return posmaknuta riječ
*/
public static Word shiftLeft(Word word, int locations) {
if(locations < 0) {
throw new IllegalArgumentException("Broj lokacija mora biti pozitivan broj!");
}
Word res = new Word(word.width);
for (int i = 0; i < word.groups; i++) {
int groupShift = locations / word.groupSize;
int offset = locations - groupShift*word.groupSize;
if(i+groupShift < word.groups) {
res.data[i+groupShift] |= (word.data[i] << offset);
}
if(i+groupShift < word.groups-1) {
res.data[i+groupShift+1] |= (word.data[i] >>> (word.groupSize - offset));
}
}
cleanExtraBits(res);
return res;
}
/**
* Obavlja logički posmak udesno predane riječi za <code>locations</code> mjesta. Posmicanje
* udesno ekvivalentno je dijeljenju s 2.
* @param word riječ koju treba posmaknuti
* @param locations za koliko treba posmaknuti
* @return posmaknuta riječ
*/
public static Word shiftRight(Word word, int locations) {
if(locations < 0) {
throw new IllegalArgumentException("Broj lokacija mora biti pozitivan broj!");
}
Word res = new Word(word.width);
for (int i = 0; i < word.groups; i++) {
int groupShift = locations / word.groupSize;
int offset = locations - groupShift*word.groupSize;
if(i-groupShift >= 0) {
res.data[i-groupShift] |= (word.data[i] >>> offset);
}
if(i-groupShift > 0) {
res.data[i-groupShift-1] |= (word.data[i] << (word.groupSize - offset));
}
}
cleanExtraBits(res);
return res;
}
/**
* Brine se da su riječi jednake širine. U slučaju da nisu, baca iznimku.
* @param word1 prva riječ
* @param word2 druga riječ
*/
private static void assertEqualWordLengths(Word word1, Word word2) {
if (word1.width != word2.width) {
throw new IllegalArgumentException("Širine podaktovnih riječi nisu jednake");
}
}
/**
* Čisti bitove riječi koji su višak unutar grupe
* @param word riječ
*/
private static void cleanExtraBits(Word word) {
for (int i = 0; i < word.groups; i++) {
word.data[i] &= 0xFFFFFF;
}
int lastGroupCount = word.width - (word.groups-1)*word.groupSize;
word.excessBit = ((word.data[word.data.length-1] >> lastGroupCount) & 1) == 1 ? true : false;
// Čisti sve bitove zadnje grupe koji su viškovi
word.data[word.groups-1] &= ((1 << lastGroupCount) - 1);
}
@Override
public String toString() {
return this.getHexString();
}
}
| Java |
package hr.fer.anna.model;
import hr.fer.anna.uniform.Register;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
* Opisnik komponente.
*
* @author Ivan, Boran
*/
public class UnitReport {
/** Registri komponente. */
private Map<String, Register> registers;
/** Opis pojedinog registra. */
private Map<String, String> registerDescription;
/** Naziv komponente koju opisujemo. */
private String unitName;
/** Kratak opis komponente. */
private String unitDescription;
/**
* Konstruktor.
*/
public UnitReport(String unitName, String unitDecription) {
this.unitName = unitName;
this.unitDescription = unitDecription;
this.registers = new LinkedHashMap<String, Register>();
this.registerDescription = new LinkedHashMap<String, String>();
}
/**
* Dodavanje registra.
*
* @param reg Registar koji dodajemo.
* @param registerName Naziv registra koji dodajemo.
* @param registerDescription Opis registra kojeg dodajemo.
*/
public void addRegister(Register register, String registerName, String registerDescription) {
this.registers.put(registerName, register);
this.registerDescription.put(registerName, registerDescription);
}
/**
* Enumeracija svih registara komponente.
*
* @return Komplet registara komponente (njihova imena).
*/
public Set<String> enumerateRegisters() {
return this.registers.keySet();
}
/**
* Dohvat određenog registra komponente.
*
* @param name Naziv registra kojeg želimo dohvatiti.
* @return Traženi registar.
*/
public Register getRegister(String registerName) {
return this.registers.get(registerName);
}
/**
* Dohvat opisa registra.
*
* @param registerName Naziv registra čiji opis želimo dohvatiti.
* @return Opis registra.
*/
public String getRegisterDescription(String registerName) {
return this.registerDescription.get(registerName);
}
/**
* Dohvat naziva komponente.
*
* @return Naziv komponente.
*/
public String getUnitName() {
return this.unitName;
}
/**
* Dohvat kratkog opisa komponente.
*
* @return Kratak opis.
*/
public String getUnitDescription() {
return this.unitDescription;
}
}
| Java |
package org.jedit.syntax;
/*
* KeywordMap.java - Fast keyword->id map
* Copyright (C) 1998, 1999 Slava Pestov
* Copyright (C) 1999 Mike Dillon
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
import javax.swing.text.Segment;
/**
* A <code>KeywordMap</code> is similar to a hashtable in that it maps keys
* to values. However, the `keys' are Swing segments. This allows lookups of
* text substrings without the overhead of creating a new string object.
* <p>
* This class is used by <code>CTokenMarker</code> to map keywords to ids.
*
* @author Slava Pestov, Mike Dillon
* @version $Id: KeywordMap.java,v 1.16 1999/12/13 03:40:30 sp Exp $
*/
public class KeywordMap
{
/**
* Creates a new <code>KeywordMap</code>.
* @param ignoreCase True if keys are case insensitive
*/
public KeywordMap(boolean ignoreCase)
{
this(ignoreCase, 52);
this.ignoreCase = ignoreCase;
}
/**
* Creates a new <code>KeywordMap</code>.
* @param ignoreCase True if the keys are case insensitive
* @param mapLength The number of `buckets' to create.
* A value of 52 will give good performance for most maps.
*/
public KeywordMap(boolean ignoreCase, int mapLength)
{
this.mapLength = mapLength;
this.ignoreCase = ignoreCase;
map = new Keyword[mapLength];
}
/**
* Looks up a key.
* @param text The text segment
* @param offset The offset of the substring within the text segment
* @param length The length of the substring
*/
public byte lookup(Segment text, int offset, int length)
{
if(length == 0)
return Token.NULL;
Keyword k = map[getSegmentMapKey(text, offset, length)];
while(k != null)
{
if(length != k.keyword.length)
{
k = k.next;
continue;
}
if(SyntaxUtilities.regionMatches(ignoreCase,text,offset,
k.keyword))
return k.id;
k = k.next;
}
return Token.NULL;
}
/**
* Adds a key-value mapping.
* @param keyword The key
* @Param id The value
*/
public void add(String keyword, byte id)
{
int key = getStringMapKey(keyword);
map[key] = new Keyword(keyword.toCharArray(),id,map[key]);
}
/**
* Returns true if the keyword map is set to be case insensitive,
* false otherwise.
*/
public boolean getIgnoreCase()
{
return ignoreCase;
}
/**
* Sets if the keyword map should be case insensitive.
* @param ignoreCase True if the keyword map should be case
* insensitive, false otherwise
*/
public void setIgnoreCase(boolean ignoreCase)
{
this.ignoreCase = ignoreCase;
}
// protected members
protected int mapLength;
protected int getStringMapKey(String s)
{
return (Character.toUpperCase(s.charAt(0)) +
Character.toUpperCase(s.charAt(s.length()-1)))
% mapLength;
}
protected int getSegmentMapKey(Segment s, int off, int len)
{
return (Character.toUpperCase(s.array[off]) +
Character.toUpperCase(s.array[off + len - 1]))
% mapLength;
}
// private members
class Keyword
{
public Keyword(char[] keyword, byte id, Keyword next)
{
this.keyword = keyword;
this.id = id;
this.next = next;
}
public char[] keyword;
public byte id;
public Keyword next;
}
private Keyword[] map;
private boolean ignoreCase;
}
| Java |
package org.jedit.syntax;
/*
* PatchTokenMarker.java - DIFF patch token marker
* Copyright (C) 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
import javax.swing.text.Segment;
/**
* Patch/diff token marker.
*
* @author Slava Pestov
* @version $Id: PatchTokenMarker.java,v 1.7 1999/12/13 03:40:30 sp Exp $
*/
public class PatchTokenMarker extends TokenMarker
{
public byte markTokensImpl(byte token, Segment line, int lineIndex)
{
if(line.count == 0)
return Token.NULL;
switch(line.array[line.offset])
{
case '+': case '>':
addToken(line.count,Token.KEYWORD1);
break;
case '-': case '<':
addToken(line.count,Token.KEYWORD2);
break;
case '@': case '*':
addToken(line.count,Token.KEYWORD3);
break;
default:
addToken(line.count,Token.NULL);
break;
}
return Token.NULL;
}
public boolean supportsMultilineTokens()
{
return false;
}
}
| Java |
package org.jedit.syntax;
/*
* ShellScriptTokenMarker.java - Shell script token marker
* Copyright (C) 1998, 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
import javax.swing.text.Segment;
/**
* Shell script token marker.
*
* @author Slava Pestov
* @version $Id: ShellScriptTokenMarker.java,v 1.18 1999/12/13 03:40:30 sp Exp $
*/
public class ShellScriptTokenMarker extends TokenMarker
{
// public members
public static final byte LVARIABLE = Token.INTERNAL_FIRST;
public byte markTokensImpl(byte token, Segment line, int lineIndex)
{
char[] array = line.array;
byte cmdState = 0; // 0 = space before command, 1 = inside
// command, 2 = after command
int offset = line.offset;
int lastOffset = offset;
int length = line.count + offset;
if(token == Token.LITERAL1 && lineIndex != 0
&& lineInfo[lineIndex - 1].obj != null)
{
String str = (String)lineInfo[lineIndex - 1].obj;
if(str != null && str.length() == line.count
&& SyntaxUtilities.regionMatches(false,line,
offset,str))
{
addToken(line.count,Token.LITERAL1);
return Token.NULL;
}
else
{
addToken(line.count,Token.LITERAL1);
lineInfo[lineIndex].obj = str;
return Token.LITERAL1;
}
}
boolean backslash = false;
loop: for(int i = offset; i < length; i++)
{
int i1 = (i+1);
char c = array[i];
if(c == '\\')
{
backslash = !backslash;
continue;
}
switch(token)
{
case Token.NULL:
switch(c)
{
case ' ': case '\t': case '(': case ')':
backslash = false;
if(cmdState == 1/*insideCmd*/)
{
addToken(i - lastOffset,Token.KEYWORD1);
lastOffset = i;
cmdState = 2; /*afterCmd*/
}
break;
case '=':
backslash = false;
if(cmdState == 1/*insideCmd*/)
{
addToken(i - lastOffset,token);
lastOffset = i;
cmdState = 2; /*afterCmd*/
}
break;
case '&': case '|': case ';':
if(backslash)
backslash = false;
else
cmdState = 0; /*beforeCmd*/
break;
case '#':
if(backslash)
backslash = false;
else
{
addToken(i - lastOffset,token);
addToken(length - i,Token.COMMENT1);
lastOffset = length;
break loop;
}
break;
case '$':
if(backslash)
backslash = false;
else
{
addToken(i - lastOffset,token);
cmdState = 2; /*afterCmd*/
lastOffset = i;
if(length - i >= 2)
{
switch(array[i1])
{
case '(':
continue;
case '{':
token = LVARIABLE;
break;
default:
token = Token.KEYWORD2;
break;
}
}
else
token = Token.KEYWORD2;
}
break;
case '"':
if(backslash)
backslash = false;
else
{
addToken(i - lastOffset,token);
token = Token.LITERAL1;
lineInfo[lineIndex].obj = null;
cmdState = 2; /*afterCmd*/
lastOffset = i;
}
break;
case '\'':
if(backslash)
backslash = false;
else
{
addToken(i - lastOffset,token);
token = Token.LITERAL2;
cmdState = 2; /*afterCmd*/
lastOffset = i;
}
break;
case '<':
if(backslash)
backslash = false;
else
{
if(length - i > 1 && array[i1] == '<')
{
addToken(i - lastOffset,
token);
token = Token.LITERAL1;
lastOffset = i;
lineInfo[lineIndex].obj =
new String(array,i + 2,
length - (i+2));
}
}
break;
default:
backslash = false;
if(Character.isLetter(c))
{
if(cmdState == 0 /*beforeCmd*/)
{
addToken(i - lastOffset,token);
lastOffset = i;
cmdState++; /*insideCmd*/
}
}
break;
}
break;
case Token.KEYWORD2:
backslash = false;
if(!Character.isLetterOrDigit(c) && c != '_')
{
if(i != offset && array[i-1] == '$')
{
addToken(i1 - lastOffset,token);
lastOffset = i1;
token = Token.NULL;
continue;
}
else
{
addToken(i - lastOffset,token);
lastOffset = i;
token = Token.NULL;
}
}
break;
case Token.LITERAL1:
if(backslash)
backslash = false;
else if(c == '"')
{
addToken(i1 - lastOffset,token);
cmdState = 2; /*afterCmd*/
lastOffset = i1;
token = Token.NULL;
}
else
backslash = false;
break;
case Token.LITERAL2:
if(backslash)
backslash = false;
else if(c == '\'')
{
addToken(i1 - lastOffset,Token.LITERAL1);
cmdState = 2; /*afterCmd*/
lastOffset = i1;
token = Token.NULL;
}
else
backslash = false;
break;
case LVARIABLE:
backslash = false;
if(c == '}')
{
addToken(i1 - lastOffset,Token.KEYWORD2);
lastOffset = i1;
token = Token.NULL;
}
break;
default:
throw new InternalError("Invalid state: " + token);
}
}
switch(token)
{
case Token.NULL:
if(cmdState == 1)
addToken(length - lastOffset,Token.KEYWORD1);
else
addToken(length - lastOffset,token);
break;
case Token.LITERAL2:
addToken(length - lastOffset,Token.LITERAL1);
break;
case Token.KEYWORD2:
addToken(length - lastOffset,token);
token = Token.NULL;
break;
case LVARIABLE:
addToken(length - lastOffset,Token.INVALID);
token = Token.NULL;
break;
default:
addToken(length - lastOffset,token);
break;
}
return token;
}
}
| Java |
package org.jedit.syntax;
/*
* SyntaxStyle.java - A simple text style class
* Copyright (C) 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
import java.awt.*;
import java.util.StringTokenizer;
/**
* A simple text style class. It can specify the color, italic flag,
* and bold flag of a run of text.
* @author Slava Pestov
* @version $Id: SyntaxStyle.java,v 1.6 1999/12/13 03:40:30 sp Exp $
*/
public class SyntaxStyle
{
/**
* Creates a new SyntaxStyle.
* @param color The text color
* @param italic True if the text should be italics
* @param bold True if the text should be bold
*/
public SyntaxStyle(Color color, boolean italic, boolean bold)
{
this.color = color;
this.italic = italic;
this.bold = bold;
}
/**
* Returns the color specified in this style.
*/
public Color getColor()
{
return color;
}
/**
* Returns true if no font styles are enabled.
*/
public boolean isPlain()
{
return !(bold || italic);
}
/**
* Returns true if italics is enabled for this style.
*/
public boolean isItalic()
{
return italic;
}
/**
* Returns true if boldface is enabled for this style.
*/
public boolean isBold()
{
return bold;
}
/**
* Returns the specified font, but with the style's bold and
* italic flags applied.
*/
public Font getStyledFont(Font font)
{
if(font == null)
throw new NullPointerException("font param must not"
+ " be null");
if(font.equals(lastFont))
return lastStyledFont;
lastFont = font;
lastStyledFont = new Font(font.getFamily(),
(bold ? Font.BOLD : 0)
| (italic ? Font.ITALIC : 0),
font.getSize());
return lastStyledFont;
}
/**
* Returns the font metrics for the styled font.
*/
public FontMetrics getFontMetrics(Font font)
{
if(font == null)
throw new NullPointerException("font param must not"
+ " be null");
if(font.equals(lastFont) && fontMetrics != null)
return fontMetrics;
lastFont = font;
lastStyledFont = new Font(font.getFamily(),
(bold ? Font.BOLD : 0)
| (italic ? Font.ITALIC : 0),
font.getSize());
fontMetrics = Toolkit.getDefaultToolkit().getFontMetrics(
lastStyledFont);
return fontMetrics;
}
/**
* Sets the foreground color and font of the specified graphics
* context to that specified in this style.
* @param gfx The graphics context
* @param font The font to add the styles to
*/
public void setGraphicsFlags(Graphics gfx, Font font)
{
Font _font = getStyledFont(font);
gfx.setFont(_font);
gfx.setColor(color);
}
/**
* Returns a string representation of this object.
*/
public String toString()
{
return getClass().getName() + "[color=" + color +
(italic ? ",italic" : "") +
(bold ? ",bold" : "") + "]";
}
// private members
private Color color;
private boolean italic;
private boolean bold;
private Font lastFont;
private Font lastStyledFont;
private FontMetrics fontMetrics;
}
| Java |
package org.jedit.syntax;
/*
* TokenMarker.java - Generic token marker
* Copyright (C) 1998, 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
import javax.swing.text.Segment;
import java.util.*;
/**
* A token marker that splits lines of text into tokens. Each token carries
* a length field and an indentification tag that can be mapped to a color
* for painting that token.<p>
*
* For performance reasons, the linked list of tokens is reused after each
* line is tokenized. Therefore, the return value of <code>markTokens</code>
* should only be used for immediate painting. Notably, it cannot be
* cached.
*
* @author Slava Pestov
* @version $Id: TokenMarker.java,v 1.32 1999/12/13 03:40:30 sp Exp $
*
* @see org.gjt.sp.jedit.syntax.Token
*/
public abstract class TokenMarker
{
/**
* A wrapper for the lower-level <code>markTokensImpl</code> method
* that is called to split a line up into tokens.
* @param line The line
* @param lineIndex The line number
*/
public Token markTokens(Segment line, int lineIndex)
{
if(lineIndex >= length)
{
throw new IllegalArgumentException("Tokenizing invalid line: "
+ lineIndex);
}
lastToken = null;
LineInfo info = lineInfo[lineIndex];
LineInfo prev;
if(lineIndex == 0)
prev = null;
else
prev = lineInfo[lineIndex - 1];
byte oldToken = info.token;
byte token = markTokensImpl(prev == null ?
Token.NULL : prev.token,line,lineIndex);
info.token = token;
/*
* This is a foul hack. It stops nextLineRequested
* from being cleared if the same line is marked twice.
*
* Why is this necessary? It's all JEditTextArea's fault.
* When something is inserted into the text, firing a
* document event, the insertUpdate() method shifts the
* caret (if necessary) by the amount inserted.
*
* All caret movement is handled by the select() method,
* which eventually pipes the new position to scrollTo()
* and calls repaint().
*
* Note that at this point in time, the new line hasn't
* yet been painted; the caret is moved first.
*
* scrollTo() calls offsetToX(), which tokenizes the line
* unless it is being called on the last line painted
* (in which case it uses the text area's painter cached
* token list). What scrollTo() does next is irrelevant.
*
* After scrollTo() has done it's job, repaint() is
* called, and eventually we end up in paintLine(), whose
* job is to paint the changed line. It, too, calls
* markTokens().
*
* The problem was that if the line started a multiline
* token, the first markTokens() (done in offsetToX())
* would set nextLineRequested (because the line end
* token had changed) but the second would clear it
* (because the line was the same that time) and therefore
* paintLine() would never know that it needed to repaint
* subsequent lines.
*
* This bug took me ages to track down, that's why I wrote
* all the relevant info down so that others wouldn't
* duplicate it.
*/
if(!(lastLine == lineIndex && nextLineRequested))
nextLineRequested = (oldToken != token);
lastLine = lineIndex;
addToken(0,Token.END);
return firstToken;
}
/**
* An abstract method that splits a line up into tokens. It
* should parse the line, and call <code>addToken()</code> to
* add syntax tokens to the token list. Then, it should return
* the initial token type for the next line.<p>
*
* For example if the current line contains the start of a
* multiline comment that doesn't end on that line, this method
* should return the comment token type so that it continues on
* the next line.
*
* @param token The initial token type for this line
* @param line The line to be tokenized
* @param lineIndex The index of the line in the document,
* starting at 0
* @return The initial token type for the next line
*/
protected abstract byte markTokensImpl(byte token, Segment line,
int lineIndex);
/**
* Returns if the token marker supports tokens that span multiple
* lines. If this is true, the object using this token marker is
* required to pass all lines in the document to the
* <code>markTokens()</code> method (in turn).<p>
*
* The default implementation returns true; it should be overridden
* to return false on simpler token markers for increased speed.
*/
public boolean supportsMultilineTokens()
{
return true;
}
/**
* Informs the token marker that lines have been inserted into
* the document. This inserts a gap in the <code>lineInfo</code>
* array.
* @param index The first line number
* @param lines The number of lines
*/
public void insertLines(int index, int lines)
{
if(lines <= 0)
return;
length += lines;
ensureCapacity(length);
int len = index + lines;
System.arraycopy(lineInfo,index,lineInfo,len,
lineInfo.length - len);
for(int i = index + lines - 1; i >= index; i--)
{
lineInfo[i] = new LineInfo();
}
}
/**
* Informs the token marker that line have been deleted from
* the document. This removes the lines in question from the
* <code>lineInfo</code> array.
* @param index The first line number
* @param lines The number of lines
*/
public void deleteLines(int index, int lines)
{
if (lines <= 0)
return;
int len = index + lines;
length -= lines;
System.arraycopy(lineInfo,len,lineInfo,
index,lineInfo.length - len);
}
/**
* Returns the number of lines in this token marker.
*/
public int getLineCount()
{
return length;
}
/**
* Returns true if the next line should be repainted. This
* will return true after a line has been tokenized that starts
* a multiline token that continues onto the next line.
*/
public boolean isNextLineRequested()
{
return nextLineRequested;
}
// protected members
/**
* The first token in the list. This should be used as the return
* value from <code>markTokens()</code>.
*/
protected Token firstToken;
/**
* The last token in the list. New tokens are added here.
* This should be set to null before a new line is to be tokenized.
*/
protected Token lastToken;
/**
* An array for storing information about lines. It is enlarged and
* shrunk automatically by the <code>insertLines()</code> and
* <code>deleteLines()</code> methods.
*/
protected LineInfo[] lineInfo;
/**
* The number of lines in the model being tokenized. This can be
* less than the length of the <code>lineInfo</code> array.
*/
protected int length;
/**
* The last tokenized line.
*/
protected int lastLine;
/**
* True if the next line should be painted.
*/
protected boolean nextLineRequested;
/**
* Creates a new <code>TokenMarker</code>. This DOES NOT create
* a lineInfo array; an initial call to <code>insertLines()</code>
* does that.
*/
protected TokenMarker()
{
lastLine = -1;
}
/**
* Ensures that the <code>lineInfo</code> array can contain the
* specified index. This enlarges it if necessary. No action is
* taken if the array is large enough already.<p>
*
* It should be unnecessary to call this under normal
* circumstances; <code>insertLine()</code> should take care of
* enlarging the line info array automatically.
*
* @param index The array index
*/
protected void ensureCapacity(int index)
{
if(lineInfo == null)
lineInfo = new LineInfo[index + 1];
else if(lineInfo.length <= index)
{
LineInfo[] lineInfoN = new LineInfo[(index + 1) * 2];
System.arraycopy(lineInfo,0,lineInfoN,0,
lineInfo.length);
lineInfo = lineInfoN;
}
}
/**
* Adds a token to the token list.
* @param length The length of the token
* @param id The id of the token
*/
protected void addToken(int length, byte id)
{
if(id >= Token.INTERNAL_FIRST && id <= Token.INTERNAL_LAST)
throw new InternalError("Invalid id: " + id);
if(length == 0 && id != Token.END)
return;
if(firstToken == null)
{
firstToken = new Token(length,id);
lastToken = firstToken;
}
else if(lastToken == null)
{
lastToken = firstToken;
firstToken.length = length;
firstToken.id = id;
}
else if(lastToken.next == null)
{
lastToken.next = new Token(length,id);
lastToken = lastToken.next;
}
else
{
lastToken = lastToken.next;
lastToken.length = length;
lastToken.id = id;
}
}
/**
* Inner class for storing information about tokenized lines.
*/
public class LineInfo
{
/**
* Creates a new LineInfo object with token = Token.NULL
* and obj = null.
*/
public LineInfo()
{
}
/**
* Creates a new LineInfo object with the specified
* parameters.
*/
public LineInfo(byte token, Object obj)
{
this.token = token;
this.obj = obj;
}
/**
* The id of the last token of the line.
*/
public byte token;
/**
* This is for use by the token marker implementations
* themselves. It can be used to store anything that
* is an object and that needs to exist on a per-line
* basis.
*/
public Object obj;
}
}
| Java |
package org.jedit.syntax;
/*
* EiffelTokenMarker.java - Eiffel token marker
* Copyright (C) 1999 Slava Pestov
* Copyright (C) 1999 Artur Biesiadowski
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
import javax.swing.text.Segment;
/**
* Eiffel token Marker.
*
* @author Artur Biesiadowski
*/
public class EiffelTokenMarker extends TokenMarker
{
public EiffelTokenMarker()
{
this.keywords = getKeywords();
}
public byte markTokensImpl(byte token, Segment line, int lineIndex)
{
char[] array = line.array;
int offset = line.offset;
lastOffset = offset;
lastKeyword = offset;
int length = line.count + offset;
boolean backslash = false;
loop: for(int i = offset; i < length; i++)
{
int i1 = (i+1);
char c = array[i];
if(c == '%')
{
backslash = !backslash;
continue;
}
switch(token)
{
case Token.NULL:
switch(c)
{
case '"':
doKeyword(line,i,c);
if(backslash)
backslash = false;
else
{
addToken(i - lastOffset,token);
token = Token.LITERAL1;
lastOffset = lastKeyword = i;
}
break;
case '\'':
doKeyword(line,i,c);
if(backslash)
backslash = false;
else
{
addToken(i - lastOffset,token);
token = Token.LITERAL2;
lastOffset = lastKeyword = i;
}
break;
case ':':
if(lastKeyword == offset)
{
if(doKeyword(line,i,c))
break;
backslash = false;
addToken(i1 - lastOffset,Token.LABEL);
lastOffset = lastKeyword = i1;
}
else if(doKeyword(line,i,c))
break;
break;
case '-':
backslash = false;
doKeyword(line,i,c);
if(length - i > 1)
{
switch(array[i1])
{
case '-':
addToken(i - lastOffset,token);
addToken(length - i,Token.COMMENT1);
lastOffset = lastKeyword = length;
break loop;
}
}
break;
default:
backslash = false;
if(!Character.isLetterOrDigit(c)
&& c != '_')
doKeyword(line,i,c);
break;
}
break;
case Token.COMMENT1:
case Token.COMMENT2:
throw new RuntimeException("Wrong eiffel parser state");
case Token.LITERAL1:
if(backslash)
backslash = false;
else if(c == '"')
{
addToken(i1 - lastOffset,token);
token = Token.NULL;
lastOffset = lastKeyword = i1;
}
break;
case Token.LITERAL2:
if(backslash)
backslash = false;
else if(c == '\'')
{
addToken(i1 - lastOffset,Token.LITERAL1);
token = Token.NULL;
lastOffset = lastKeyword = i1;
}
break;
default:
throw new InternalError("Invalid state: "
+ token);
}
}
if(token == Token.NULL)
doKeyword(line,length,'\0');
switch(token)
{
case Token.LITERAL1:
case Token.LITERAL2:
addToken(length - lastOffset,Token.INVALID);
token = Token.NULL;
break;
case Token.KEYWORD2:
addToken(length - lastOffset,token);
if(!backslash)
token = Token.NULL;
default:
addToken(length - lastOffset,token);
break;
}
return token;
}
public static KeywordMap getKeywords()
{
if(eiffelKeywords == null)
{
eiffelKeywords = new KeywordMap(true);
eiffelKeywords.add("alias", Token.KEYWORD1);
eiffelKeywords.add("all", Token.KEYWORD1);
eiffelKeywords.add("and", Token.KEYWORD1);
eiffelKeywords.add("as", Token.KEYWORD1);
eiffelKeywords.add("check", Token.KEYWORD1);
eiffelKeywords.add("class", Token.KEYWORD1);
eiffelKeywords.add("creation", Token.KEYWORD1);
eiffelKeywords.add("debug", Token.KEYWORD1);
eiffelKeywords.add("deferred", Token.KEYWORD1);
eiffelKeywords.add("do", Token.KEYWORD1);
eiffelKeywords.add("else",Token.KEYWORD1);
eiffelKeywords.add("elseif", Token.KEYWORD1);
eiffelKeywords.add("end", Token.KEYWORD1);
eiffelKeywords.add("ensure", Token.KEYWORD1);
eiffelKeywords.add("expanded", Token.KEYWORD1);
eiffelKeywords.add("export", Token.KEYWORD1);
eiffelKeywords.add("external", Token.KEYWORD1);
eiffelKeywords.add("feature", Token.KEYWORD1);
eiffelKeywords.add("from", Token.KEYWORD1);
eiffelKeywords.add("frozen", Token.KEYWORD1);
eiffelKeywords.add("if", Token.KEYWORD1);
eiffelKeywords.add("implies",Token.KEYWORD1);
eiffelKeywords.add("indexing", Token.KEYWORD1);
eiffelKeywords.add("infix", Token.KEYWORD1);
eiffelKeywords.add("inherit", Token.KEYWORD1);
eiffelKeywords.add("inspect", Token.KEYWORD1);
eiffelKeywords.add("invariant", Token.KEYWORD1);
eiffelKeywords.add("is", Token.KEYWORD1);
eiffelKeywords.add("like", Token.KEYWORD1);
eiffelKeywords.add("local", Token.KEYWORD1);
eiffelKeywords.add("loop", Token.KEYWORD1);
eiffelKeywords.add("not", Token.KEYWORD1);
eiffelKeywords.add("obsolete", Token.KEYWORD1);
eiffelKeywords.add("old",Token.KEYWORD1);
eiffelKeywords.add("once", Token.KEYWORD1);
eiffelKeywords.add("or", Token.KEYWORD1);
eiffelKeywords.add("prefix", Token.KEYWORD1);
eiffelKeywords.add("redefine", Token.KEYWORD1);
eiffelKeywords.add("rename", Token.KEYWORD1);
eiffelKeywords.add("require", Token.KEYWORD1);
eiffelKeywords.add("rescue", Token.KEYWORD1);
eiffelKeywords.add("retry", Token.KEYWORD1);
eiffelKeywords.add("select", Token.KEYWORD1);
eiffelKeywords.add("separate", Token.KEYWORD1);
eiffelKeywords.add("then",Token.KEYWORD1);
eiffelKeywords.add("undefine", Token.KEYWORD1);
eiffelKeywords.add("until", Token.KEYWORD1);
eiffelKeywords.add("variant", Token.KEYWORD1);
eiffelKeywords.add("when", Token.KEYWORD1);
eiffelKeywords.add("xor", Token.KEYWORD1);
eiffelKeywords.add("current",Token.LITERAL2);
eiffelKeywords.add("false",Token.LITERAL2);
eiffelKeywords.add("precursor",Token.LITERAL2);
eiffelKeywords.add("result",Token.LITERAL2);
eiffelKeywords.add("strip",Token.LITERAL2);
eiffelKeywords.add("true",Token.LITERAL2);
eiffelKeywords.add("unique",Token.LITERAL2);
eiffelKeywords.add("void",Token.LITERAL2);
}
return eiffelKeywords;
}
// private members
private static KeywordMap eiffelKeywords;
private boolean cpp;
private KeywordMap keywords;
private int lastOffset;
private int lastKeyword;
private boolean doKeyword(Segment line, int i, char c)
{
int i1 = i+1;
boolean klassname = false;
int len = i - lastKeyword;
byte id = keywords.lookup(line,lastKeyword,len);
if ( id == Token.NULL )
{
klassname = true;
for ( int at = lastKeyword; at < lastKeyword + len; at++ )
{
char ch = line.array[at];
if ( ch != '_' && !Character.isUpperCase(ch) )
{
klassname = false;
break;
}
}
if ( klassname )
id = Token.KEYWORD3;
}
if(id != Token.NULL)
{
if(lastKeyword != lastOffset)
addToken(lastKeyword - lastOffset,Token.NULL);
addToken(len,id);
lastOffset = i;
}
lastKeyword = i1;
return false;
}
}
| Java |
package org.jedit.syntax;
/*
* InputHandler.java - Manages key bindings and executes actions
* Copyright (C) 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
import javax.swing.text.*;
import javax.swing.JPopupMenu;
import java.awt.event.*;
import java.awt.Component;
import java.util.*;
/**
* An input handler converts the user's key strokes into concrete actions.
* It also takes care of macro recording and action repetition.<p>
*
* This class provides all the necessary support code for an input
* handler, but doesn't actually do any key binding logic. It is up
* to the implementations of this class to do so.
*
* @author Slava Pestov
* @version $Id: InputHandler.java,v 1.14 1999/12/13 03:40:30 sp Exp $
* @see org.gjt.sp.jedit.textarea.DefaultInputHandler
*/
public abstract class InputHandler extends KeyAdapter
{
/**
* If this client property is set to Boolean.TRUE on the text area,
* the home/end keys will support 'smart' BRIEF-like behaviour
* (one press = start/end of line, two presses = start/end of
* viewscreen, three presses = start/end of document). By default,
* this property is not set.
*/
public static final String SMART_HOME_END_PROPERTY = "InputHandler.homeEnd";
public static final ActionListener BACKSPACE = new backspace();
public static final ActionListener BACKSPACE_WORD = new backspace_word();
public static final ActionListener DELETE = new delete();
public static final ActionListener DELETE_WORD = new delete_word();
public static final ActionListener END = new end(false);
public static final ActionListener DOCUMENT_END = new document_end(false);
public static final ActionListener SELECT_END = new end(true);
public static final ActionListener SELECT_DOC_END = new document_end(true);
public static final ActionListener INSERT_BREAK = new insert_break();
public static final ActionListener INSERT_TAB = new insert_tab();
public static final ActionListener HOME = new home(false);
public static final ActionListener DOCUMENT_HOME = new document_home(false);
public static final ActionListener SELECT_HOME = new home(true);
public static final ActionListener SELECT_DOC_HOME = new document_home(true);
public static final ActionListener NEXT_CHAR = new next_char(false);
public static final ActionListener NEXT_LINE = new next_line(false);
public static final ActionListener NEXT_PAGE = new next_page(false);
public static final ActionListener NEXT_WORD = new next_word(false);
public static final ActionListener SELECT_NEXT_CHAR = new next_char(true);
public static final ActionListener SELECT_NEXT_LINE = new next_line(true);
public static final ActionListener SELECT_NEXT_PAGE = new next_page(true);
public static final ActionListener SELECT_NEXT_WORD = new next_word(true);
public static final ActionListener OVERWRITE = new overwrite();
public static final ActionListener PREV_CHAR = new prev_char(false);
public static final ActionListener PREV_LINE = new prev_line(false);
public static final ActionListener PREV_PAGE = new prev_page(false);
public static final ActionListener PREV_WORD = new prev_word(false);
public static final ActionListener SELECT_PREV_CHAR = new prev_char(true);
public static final ActionListener SELECT_PREV_LINE = new prev_line(true);
public static final ActionListener SELECT_PREV_PAGE = new prev_page(true);
public static final ActionListener SELECT_PREV_WORD = new prev_word(true);
public static final ActionListener REPEAT = new repeat();
public static final ActionListener TOGGLE_RECT = new toggle_rect();
// Default action
public static final ActionListener INSERT_CHAR = new insert_char();
private static Hashtable actions;
static
{
actions = new Hashtable();
actions.put("backspace",BACKSPACE);
actions.put("backspace-word",BACKSPACE_WORD);
actions.put("delete",DELETE);
actions.put("delete-word",DELETE_WORD);
actions.put("end",END);
actions.put("select-end",SELECT_END);
actions.put("document-end",DOCUMENT_END);
actions.put("select-doc-end",SELECT_DOC_END);
actions.put("insert-break",INSERT_BREAK);
actions.put("insert-tab",INSERT_TAB);
actions.put("home",HOME);
actions.put("select-home",SELECT_HOME);
actions.put("document-home",DOCUMENT_HOME);
actions.put("select-doc-home",SELECT_DOC_HOME);
actions.put("next-char",NEXT_CHAR);
actions.put("next-line",NEXT_LINE);
actions.put("next-page",NEXT_PAGE);
actions.put("next-word",NEXT_WORD);
actions.put("select-next-char",SELECT_NEXT_CHAR);
actions.put("select-next-line",SELECT_NEXT_LINE);
actions.put("select-next-page",SELECT_NEXT_PAGE);
actions.put("select-next-word",SELECT_NEXT_WORD);
actions.put("overwrite",OVERWRITE);
actions.put("prev-char",PREV_CHAR);
actions.put("prev-line",PREV_LINE);
actions.put("prev-page",PREV_PAGE);
actions.put("prev-word",PREV_WORD);
actions.put("select-prev-char",SELECT_PREV_CHAR);
actions.put("select-prev-line",SELECT_PREV_LINE);
actions.put("select-prev-page",SELECT_PREV_PAGE);
actions.put("select-prev-word",SELECT_PREV_WORD);
actions.put("repeat",REPEAT);
actions.put("toggle-rect",TOGGLE_RECT);
actions.put("insert-char",INSERT_CHAR);
}
/**
* Returns a named text area action.
* @param name The action name
*/
public static ActionListener getAction(String name)
{
return (ActionListener)actions.get(name);
}
/**
* Returns the name of the specified text area action.
* @param listener The action
*/
public static String getActionName(ActionListener listener)
{
Enumeration enu = getActions();
while(enu.hasMoreElements())
{
String name = (String)enu.nextElement();
ActionListener _listener = getAction(name);
if(_listener == listener)
return name;
}
return null;
}
/**
* Returns an enumeration of all available actions.
*/
public static Enumeration getActions()
{
return actions.keys();
}
/**
* Adds the default key bindings to this input handler.
* This should not be called in the constructor of this
* input handler, because applications might load the
* key bindings from a file, etc.
*/
public abstract void addDefaultKeyBindings();
/**
* Adds a key binding to this input handler.
* @param keyBinding The key binding (the format of this is
* input-handler specific)
* @param action The action
*/
public abstract void addKeyBinding(String keyBinding, ActionListener action);
/**
* Removes a key binding from this input handler.
* @param keyBinding The key binding
*/
public abstract void removeKeyBinding(String keyBinding);
/**
* Removes all key bindings from this input handler.
*/
public abstract void removeAllKeyBindings();
/**
* Grabs the next key typed event and invokes the specified
* action with the key as a the action command.
* @param action The action
*/
public void grabNextKeyStroke(ActionListener listener)
{
grabAction = listener;
}
/**
* Returns if repeating is enabled. When repeating is enabled,
* actions will be executed multiple times. This is usually
* invoked with a special key stroke in the input handler.
*/
public boolean isRepeatEnabled()
{
return repeat;
}
/**
* Enables repeating. When repeating is enabled, actions will be
* executed multiple times. Once repeating is enabled, the input
* handler should read a number from the keyboard.
*/
public void setRepeatEnabled(boolean repeat)
{
this.repeat = repeat;
}
/**
* Returns the number of times the next action will be repeated.
*/
public int getRepeatCount()
{
return (repeat ? Math.max(1,repeatCount) : 1);
}
/**
* Sets the number of times the next action will be repeated.
* @param repeatCount The repeat count
*/
public void setRepeatCount(int repeatCount)
{
this.repeatCount = repeatCount;
}
/**
* Returns the macro recorder. If this is non-null, all executed
* actions should be forwarded to the recorder.
*/
public InputHandler.MacroRecorder getMacroRecorder()
{
return recorder;
}
/**
* Sets the macro recorder. If this is non-null, all executed
* actions should be forwarded to the recorder.
* @param recorder The macro recorder
*/
public void setMacroRecorder(InputHandler.MacroRecorder recorder)
{
this.recorder = recorder;
}
/**
* Returns a copy of this input handler that shares the same
* key bindings. Setting key bindings in the copy will also
* set them in the original.
*/
public abstract InputHandler copy();
/**
* Executes the specified action, repeating and recording it as
* necessary.
* @param listener The action listener
* @param source The event source
* @param actionCommand The action command
*/
public void executeAction(ActionListener listener, Object source,
String actionCommand)
{
// create event
ActionEvent evt = new ActionEvent(source,
ActionEvent.ACTION_PERFORMED,
actionCommand);
// don't do anything if the action is a wrapper
// (like EditAction.Wrapper)
if(listener instanceof Wrapper)
{
listener.actionPerformed(evt);
return;
}
// remember old values, in case action changes them
boolean _repeat = repeat;
int _repeatCount = getRepeatCount();
// execute the action
if(listener instanceof InputHandler.NonRepeatable)
listener.actionPerformed(evt);
else
{
for(int i = 0; i < Math.max(1,repeatCount); i++)
listener.actionPerformed(evt);
}
// do recording. Notice that we do no recording whatsoever
// for actions that grab keys
if(grabAction == null)
{
if(recorder != null)
{
if(!(listener instanceof InputHandler.NonRecordable))
{
if(_repeatCount != 1)
recorder.actionPerformed(REPEAT,String.valueOf(_repeatCount));
recorder.actionPerformed(listener,actionCommand);
}
}
// If repeat was true originally, clear it
// Otherwise it might have been set by the action, etc
if(_repeat)
{
repeat = false;
repeatCount = 0;
}
}
}
/**
* Returns the text area that fired the specified event.
* @param evt The event
*/
public static JEditTextArea getTextArea(EventObject evt)
{
if(evt != null)
{
Object o = evt.getSource();
if(o instanceof Component)
{
// find the parent text area
Component c = (Component)o;
for(;;)
{
if(c instanceof JEditTextArea)
return (JEditTextArea)c;
else if(c == null)
break;
if(c instanceof JPopupMenu)
c = ((JPopupMenu)c)
.getInvoker();
else
c = c.getParent();
}
}
}
// this shouldn't happen
System.err.println("BUG: getTextArea() returning null");
System.err.println("Report this to Slava Pestov <sp@gjt.org>");
return null;
}
// protected members
/**
* If a key is being grabbed, this method should be called with
* the appropriate key event. It executes the grab action with
* the typed character as the parameter.
*/
protected void handleGrabAction(KeyEvent evt)
{
// Clear it *before* it is executed so that executeAction()
// resets the repeat count
ActionListener _grabAction = grabAction;
grabAction = null;
executeAction(_grabAction,evt.getSource(),
String.valueOf(evt.getKeyChar()));
}
// protected members
protected ActionListener grabAction;
protected boolean repeat;
protected int repeatCount;
protected InputHandler.MacroRecorder recorder;
/**
* If an action implements this interface, it should not be repeated.
* Instead, it will handle the repetition itself.
*/
public interface NonRepeatable {}
/**
* If an action implements this interface, it should not be recorded
* by the macro recorder. Instead, it will do its own recording.
*/
public interface NonRecordable {}
/**
* For use by EditAction.Wrapper only.
* @since jEdit 2.2final
*/
public interface Wrapper {}
/**
* Macro recorder.
*/
public interface MacroRecorder
{
void actionPerformed(ActionListener listener,
String actionCommand);
}
public static class backspace implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
JEditTextArea textArea = getTextArea(evt);
if(!textArea.isEditable())
{
textArea.getToolkit().beep();
return;
}
if(textArea.getSelectionStart()
!= textArea.getSelectionEnd())
{
textArea.setSelectedText("");
}
else
{
int caret = textArea.getCaretPosition();
if(caret == 0)
{
textArea.getToolkit().beep();
return;
}
try
{
textArea.getDocument().remove(caret - 1,1);
}
catch(BadLocationException bl)
{
bl.printStackTrace();
}
}
}
}
public static class backspace_word implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
JEditTextArea textArea = getTextArea(evt);
int start = textArea.getSelectionStart();
if(start != textArea.getSelectionEnd())
{
textArea.setSelectedText("");
}
int line = textArea.getCaretLine();
int lineStart = textArea.getLineStartOffset(line);
int caret = start - lineStart;
String lineText = textArea.getLineText(textArea
.getCaretLine());
if(caret == 0)
{
if(lineStart == 0)
{
textArea.getToolkit().beep();
return;
}
caret--;
}
else
{
String noWordSep = (String)textArea.getDocument().getProperty("noWordSep");
caret = TextUtilities.findWordStart(lineText,caret,noWordSep);
}
try
{
textArea.getDocument().remove(
caret + lineStart,
start - (caret + lineStart));
}
catch(BadLocationException bl)
{
bl.printStackTrace();
}
}
}
public static class delete implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
JEditTextArea textArea = getTextArea(evt);
if(!textArea.isEditable())
{
textArea.getToolkit().beep();
return;
}
if(textArea.getSelectionStart()
!= textArea.getSelectionEnd())
{
textArea.setSelectedText("");
}
else
{
int caret = textArea.getCaretPosition();
if(caret == textArea.getDocumentLength())
{
textArea.getToolkit().beep();
return;
}
try
{
textArea.getDocument().remove(caret,1);
}
catch(BadLocationException bl)
{
bl.printStackTrace();
}
}
}
}
public static class delete_word implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
JEditTextArea textArea = getTextArea(evt);
int start = textArea.getSelectionStart();
if(start != textArea.getSelectionEnd())
{
textArea.setSelectedText("");
}
int line = textArea.getCaretLine();
int lineStart = textArea.getLineStartOffset(line);
int caret = start - lineStart;
String lineText = textArea.getLineText(textArea
.getCaretLine());
if(caret == lineText.length())
{
if(lineStart + caret == textArea.getDocumentLength())
{
textArea.getToolkit().beep();
return;
}
caret++;
}
else
{
String noWordSep = (String)textArea.getDocument().getProperty("noWordSep");
caret = TextUtilities.findWordEnd(lineText,caret,noWordSep);
}
try
{
textArea.getDocument().remove(start,
(caret + lineStart) - start);
}
catch(BadLocationException bl)
{
bl.printStackTrace();
}
}
}
public static class end implements ActionListener
{
private boolean select;
public end(boolean select)
{
this.select = select;
}
public void actionPerformed(ActionEvent evt)
{
JEditTextArea textArea = getTextArea(evt);
int caret = textArea.getCaretPosition();
int lastOfLine = textArea.getLineEndOffset(
textArea.getCaretLine()) - 1;
int lastVisibleLine = textArea.getFirstLine()
+ textArea.getVisibleLines();
if(lastVisibleLine >= textArea.getLineCount())
{
lastVisibleLine = Math.min(textArea.getLineCount() - 1,
lastVisibleLine);
}
else
lastVisibleLine -= (textArea.getElectricScroll() + 1);
int lastVisible = textArea.getLineEndOffset(lastVisibleLine) - 1;
int lastDocument = textArea.getDocumentLength();
if(caret == lastDocument)
{
textArea.getToolkit().beep();
return;
}
else if(!Boolean.TRUE.equals(textArea.getClientProperty(
SMART_HOME_END_PROPERTY)))
caret = lastOfLine;
else if(caret == lastVisible)
caret = lastDocument;
else if(caret == lastOfLine)
caret = lastVisible;
else
caret = lastOfLine;
if(select)
textArea.select(textArea.getMarkPosition(),caret);
else
textArea.setCaretPosition(caret);
}
}
public static class document_end implements ActionListener
{
private boolean select;
public document_end(boolean select)
{
this.select = select;
}
public void actionPerformed(ActionEvent evt)
{
JEditTextArea textArea = getTextArea(evt);
if(select)
textArea.select(textArea.getMarkPosition(),
textArea.getDocumentLength());
else
textArea.setCaretPosition(textArea
.getDocumentLength());
}
}
public static class home implements ActionListener
{
private boolean select;
public home(boolean select)
{
this.select = select;
}
public void actionPerformed(ActionEvent evt)
{
JEditTextArea textArea = getTextArea(evt);
int caret = textArea.getCaretPosition();
int firstLine = textArea.getFirstLine();
int firstOfLine = textArea.getLineStartOffset(
textArea.getCaretLine());
int firstVisibleLine = (firstLine == 0 ? 0 :
firstLine + textArea.getElectricScroll());
int firstVisible = textArea.getLineStartOffset(
firstVisibleLine);
if(caret == 0)
{
textArea.getToolkit().beep();
return;
}
else if(!Boolean.TRUE.equals(textArea.getClientProperty(
SMART_HOME_END_PROPERTY)))
caret = firstOfLine;
else if(caret == firstVisible)
caret = 0;
else if(caret == firstOfLine)
caret = firstVisible;
else
caret = firstOfLine;
if(select)
textArea.select(textArea.getMarkPosition(),caret);
else
textArea.setCaretPosition(caret);
}
}
public static class document_home implements ActionListener
{
private boolean select;
public document_home(boolean select)
{
this.select = select;
}
public void actionPerformed(ActionEvent evt)
{
JEditTextArea textArea = getTextArea(evt);
if(select)
textArea.select(textArea.getMarkPosition(),0);
else
textArea.setCaretPosition(0);
}
}
public static class insert_break implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
JEditTextArea textArea = getTextArea(evt);
if(!textArea.isEditable())
{
textArea.getToolkit().beep();
return;
}
textArea.setSelectedText("\n");
}
}
public static class insert_tab implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
JEditTextArea textArea = getTextArea(evt);
if(!textArea.isEditable())
{
textArea.getToolkit().beep();
return;
}
textArea.overwriteSetSelectedText("\t");
}
}
public static class next_char implements ActionListener
{
private boolean select;
public next_char(boolean select)
{
this.select = select;
}
public void actionPerformed(ActionEvent evt)
{
JEditTextArea textArea = getTextArea(evt);
int caret = textArea.getCaretPosition();
if(caret == textArea.getDocumentLength())
{
textArea.getToolkit().beep();
return;
}
if(select)
textArea.select(textArea.getMarkPosition(),
caret + 1);
else
textArea.setCaretPosition(caret + 1);
}
}
public static class next_line implements ActionListener
{
private boolean select;
public next_line(boolean select)
{
this.select = select;
}
public void actionPerformed(ActionEvent evt)
{
JEditTextArea textArea = getTextArea(evt);
int caret = textArea.getCaretPosition();
int line = textArea.getCaretLine();
if(line == textArea.getLineCount() - 1)
{
textArea.getToolkit().beep();
return;
}
int magic = textArea.getMagicCaretPosition();
if(magic == -1)
{
magic = textArea.offsetToX(line,
caret - textArea.getLineStartOffset(line));
}
caret = textArea.getLineStartOffset(line + 1)
+ textArea.xToOffset(line + 1,magic);
if(select)
textArea.select(textArea.getMarkPosition(),caret);
else
textArea.setCaretPosition(caret);
textArea.setMagicCaretPosition(magic);
}
}
public static class next_page implements ActionListener
{
private boolean select;
public next_page(boolean select)
{
this.select = select;
}
public void actionPerformed(ActionEvent evt)
{
JEditTextArea textArea = getTextArea(evt);
int lineCount = textArea.getLineCount();
int firstLine = textArea.getFirstLine();
int visibleLines = textArea.getVisibleLines();
int line = textArea.getCaretLine();
firstLine += visibleLines;
if(firstLine + visibleLines >= lineCount - 1)
firstLine = lineCount - visibleLines;
textArea.setFirstLine(firstLine);
int caret = textArea.getLineStartOffset(
Math.min(textArea.getLineCount() - 1,
line + visibleLines));
if(select)
textArea.select(textArea.getMarkPosition(),caret);
else
textArea.setCaretPosition(caret);
}
}
public static class next_word implements ActionListener
{
private boolean select;
public next_word(boolean select)
{
this.select = select;
}
public void actionPerformed(ActionEvent evt)
{
JEditTextArea textArea = getTextArea(evt);
int caret = textArea.getCaretPosition();
int line = textArea.getCaretLine();
int lineStart = textArea.getLineStartOffset(line);
caret -= lineStart;
String lineText = textArea.getLineText(textArea
.getCaretLine());
if(caret == lineText.length())
{
if(lineStart + caret == textArea.getDocumentLength())
{
textArea.getToolkit().beep();
return;
}
caret++;
}
else
{
String noWordSep = (String)textArea.getDocument().getProperty("noWordSep");
caret = TextUtilities.findWordEnd(lineText,caret,noWordSep);
}
if(select)
textArea.select(textArea.getMarkPosition(),
lineStart + caret);
else
textArea.setCaretPosition(lineStart + caret);
}
}
public static class overwrite implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
JEditTextArea textArea = getTextArea(evt);
textArea.setOverwriteEnabled(
!textArea.isOverwriteEnabled());
}
}
public static class prev_char implements ActionListener
{
private boolean select;
public prev_char(boolean select)
{
this.select = select;
}
public void actionPerformed(ActionEvent evt)
{
JEditTextArea textArea = getTextArea(evt);
int caret = textArea.getCaretPosition();
if(caret == 0)
{
textArea.getToolkit().beep();
return;
}
if(select)
textArea.select(textArea.getMarkPosition(),
caret - 1);
else
textArea.setCaretPosition(caret - 1);
}
}
public static class prev_line implements ActionListener
{
private boolean select;
public prev_line(boolean select)
{
this.select = select;
}
public void actionPerformed(ActionEvent evt)
{
JEditTextArea textArea = getTextArea(evt);
int caret = textArea.getCaretPosition();
int line = textArea.getCaretLine();
if(line == 0)
{
textArea.getToolkit().beep();
return;
}
int magic = textArea.getMagicCaretPosition();
if(magic == -1)
{
magic = textArea.offsetToX(line,
caret - textArea.getLineStartOffset(line));
}
caret = textArea.getLineStartOffset(line - 1)
+ textArea.xToOffset(line - 1,magic);
if(select)
textArea.select(textArea.getMarkPosition(),caret);
else
textArea.setCaretPosition(caret);
textArea.setMagicCaretPosition(magic);
}
}
public static class prev_page implements ActionListener
{
private boolean select;
public prev_page(boolean select)
{
this.select = select;
}
public void actionPerformed(ActionEvent evt)
{
JEditTextArea textArea = getTextArea(evt);
int firstLine = textArea.getFirstLine();
int visibleLines = textArea.getVisibleLines();
int line = textArea.getCaretLine();
if(firstLine < visibleLines)
firstLine = visibleLines;
textArea.setFirstLine(firstLine - visibleLines);
int caret = textArea.getLineStartOffset(
Math.max(0,line - visibleLines));
if(select)
textArea.select(textArea.getMarkPosition(),caret);
else
textArea.setCaretPosition(caret);
}
}
public static class prev_word implements ActionListener
{
private boolean select;
public prev_word(boolean select)
{
this.select = select;
}
public void actionPerformed(ActionEvent evt)
{
JEditTextArea textArea = getTextArea(evt);
int caret = textArea.getCaretPosition();
int line = textArea.getCaretLine();
int lineStart = textArea.getLineStartOffset(line);
caret -= lineStart;
String lineText = textArea.getLineText(textArea
.getCaretLine());
if(caret == 0)
{
if(lineStart == 0)
{
textArea.getToolkit().beep();
return;
}
caret--;
}
else
{
String noWordSep = (String)textArea.getDocument().getProperty("noWordSep");
caret = TextUtilities.findWordStart(lineText,caret,noWordSep);
}
if(select)
textArea.select(textArea.getMarkPosition(),
lineStart + caret);
else
textArea.setCaretPosition(lineStart + caret);
}
}
public static class repeat implements ActionListener,
InputHandler.NonRecordable
{
public void actionPerformed(ActionEvent evt)
{
JEditTextArea textArea = getTextArea(evt);
textArea.getInputHandler().setRepeatEnabled(true);
String actionCommand = evt.getActionCommand();
if(actionCommand != null)
{
textArea.getInputHandler().setRepeatCount(
Integer.parseInt(actionCommand));
}
}
}
public static class toggle_rect implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
JEditTextArea textArea = getTextArea(evt);
textArea.setSelectionRectangular(
!textArea.isSelectionRectangular());
}
}
public static class insert_char implements ActionListener,
InputHandler.NonRepeatable
{
public void actionPerformed(ActionEvent evt)
{
JEditTextArea textArea = getTextArea(evt);
String str = evt.getActionCommand();
int repeatCount = textArea.getInputHandler().getRepeatCount();
if(textArea.isEditable())
{
StringBuffer buf = new StringBuffer();
for(int i = 0; i < repeatCount; i++)
buf.append(str);
textArea.overwriteSetSelectedText(buf.toString());
}
else
{
textArea.getToolkit().beep();
}
}
}
}
| Java |
package org.jedit.syntax;
/*
* PythonTokenMarker.java - Python token marker
* Copyright (C) 1999 Jonathan Revusky
* Copyright (C) 1998, 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
import javax.swing.text.Segment;
/**
* Python token marker.
*
* @author Jonathan Revusky
* @version $Id: PythonTokenMarker.java,v 1.3 1999/12/14 04:20:35 sp Exp $
*/
public class PythonTokenMarker extends TokenMarker
{
private static final byte TRIPLEQUOTE1 = Token.INTERNAL_FIRST;
private static final byte TRIPLEQUOTE2 = Token.INTERNAL_LAST;
public PythonTokenMarker()
{
this.keywords = getKeywords();
}
public byte markTokensImpl(byte token, Segment line, int lineIndex)
{
char[] array = line.array;
int offset = line.offset;
lastOffset = offset;
lastKeyword = offset;
int length = line.count + offset;
boolean backslash = false;
loop: for(int i = offset; i < length; i++)
{
int i1 = (i+1);
char c = array[i];
if(c == '\\')
{
backslash = !backslash;
continue;
}
switch(token)
{
case Token.NULL:
switch(c)
{
case '#':
if(backslash)
backslash = false;
else
{
doKeyword(line,i,c);
addToken(i - lastOffset,token);
addToken(length - i,Token.COMMENT1);
lastOffset = lastKeyword = length;
break loop;
}
break;
case '"':
doKeyword(line,i,c);
if(backslash)
backslash = false;
else
{
addToken(i - lastOffset,token);
if(SyntaxUtilities.regionMatches(false,
line,i1,"\"\""))
{
token = TRIPLEQUOTE1;
}
else
{
token = Token.LITERAL1;
}
lastOffset = lastKeyword = i;
}
break;
case '\'':
doKeyword(line,i,c);
if(backslash)
backslash = false;
else
{
addToken(i - lastOffset,token);
if(SyntaxUtilities.regionMatches(false,
line,i1,"''"))
{
token = TRIPLEQUOTE2;
}
else
{
token = Token.LITERAL2;
}
lastOffset = lastKeyword = i;
}
break;
default:
backslash = false;
if(!Character.isLetterOrDigit(c)
&& c != '_')
doKeyword(line,i,c);
break;
}
break;
case Token.LITERAL1:
if(backslash)
backslash = false;
else if(c == '"')
{
addToken(i1 - lastOffset,token);
token = Token.NULL;
lastOffset = lastKeyword = i1;
}
break;
case Token.LITERAL2:
if(backslash)
backslash = false;
else if(c == '\'')
{
addToken(i1 - lastOffset,Token.LITERAL1);
token = Token.NULL;
lastOffset = lastKeyword = i1;
}
break;
case TRIPLEQUOTE1:
if(backslash)
backslash = false;
else if(SyntaxUtilities.regionMatches(false,
line,i,"\"\"\""))
{
addToken((i+=4) - lastOffset,
Token.LITERAL1);
token = Token.NULL;
lastOffset = lastKeyword = i;
}
break;
case TRIPLEQUOTE2:
if(backslash)
backslash = false;
else if(SyntaxUtilities.regionMatches(false,
line,i,"'''"))
{
addToken((i+=4) - lastOffset,
Token.LITERAL1);
token = Token.NULL;
lastOffset = lastKeyword = i;
}
break;
default:
throw new InternalError("Invalid state: "
+ token);
}
}
switch(token)
{
case TRIPLEQUOTE1:
case TRIPLEQUOTE2:
addToken(length - lastOffset,Token.LITERAL1);
break;
case Token.NULL:
doKeyword(line,length,'\0');
default:
addToken(length - lastOffset,token);
break;
}
return token;
}
public static KeywordMap getKeywords()
{
if (pyKeywords == null)
{
pyKeywords = new KeywordMap(false);
pyKeywords.add("and",Token.KEYWORD3);
pyKeywords.add("not",Token.KEYWORD3);
pyKeywords.add("or",Token.KEYWORD3);
pyKeywords.add("if",Token.KEYWORD1);
pyKeywords.add("for",Token.KEYWORD1);
pyKeywords.add("assert",Token.KEYWORD1);
pyKeywords.add("break",Token.KEYWORD1);
pyKeywords.add("continue",Token.KEYWORD1);
pyKeywords.add("elif",Token.KEYWORD1);
pyKeywords.add("else",Token.KEYWORD1);
pyKeywords.add("except",Token.KEYWORD1);
pyKeywords.add("exec",Token.KEYWORD1);
pyKeywords.add("finally",Token.KEYWORD1);
pyKeywords.add("raise",Token.KEYWORD1);
pyKeywords.add("return",Token.KEYWORD1);
pyKeywords.add("try",Token.KEYWORD1);
pyKeywords.add("while",Token.KEYWORD1);
pyKeywords.add("def",Token.KEYWORD2);
pyKeywords.add("class",Token.KEYWORD2);
pyKeywords.add("del",Token.KEYWORD2);
pyKeywords.add("from",Token.KEYWORD2);
pyKeywords.add("global",Token.KEYWORD2);
pyKeywords.add("import",Token.KEYWORD2);
pyKeywords.add("in",Token.KEYWORD2);
pyKeywords.add("is",Token.KEYWORD2);
pyKeywords.add("lambda",Token.KEYWORD2);
pyKeywords.add("pass",Token.KEYWORD2);
pyKeywords.add("print",Token.KEYWORD2);
}
return pyKeywords;
}
// private members
private static KeywordMap pyKeywords;
private KeywordMap keywords;
private int lastOffset;
private int lastKeyword;
private boolean doKeyword(Segment line, int i, char c)
{
int i1 = i+1;
int len = i - lastKeyword;
byte id = keywords.lookup(line,lastKeyword,len);
if(id != Token.NULL)
{
if(lastKeyword != lastOffset)
addToken(lastKeyword - lastOffset,Token.NULL);
addToken(len,id);
lastOffset = i;
}
lastKeyword = i1;
return false;
}
}
| Java |
package org.jedit.syntax;
/*
* SyntaxUtilities.java - Utility functions used by syntax colorizing
* Copyright (C) 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
import javax.swing.text.*;
import java.awt.*;
/**
* Class with several utility functions used by jEdit's syntax colorizing
* subsystem.
*
* @author Slava Pestov
* @version $Id: SyntaxUtilities.java,v 1.9 1999/12/13 03:40:30 sp Exp $
*/
public class SyntaxUtilities
{
/**
* Checks if a subregion of a <code>Segment</code> is equal to a
* string.
* @param ignoreCase True if case should be ignored, false otherwise
* @param text The segment
* @param offset The offset into the segment
* @param match The string to match
*/
public static boolean regionMatches(boolean ignoreCase, Segment text,
int offset, String match)
{
int length = offset + match.length();
char[] textArray = text.array;
if(length > text.offset + text.count)
return false;
for(int i = offset, j = 0; i < length; i++, j++)
{
char c1 = textArray[i];
char c2 = match.charAt(j);
if(ignoreCase)
{
c1 = Character.toUpperCase(c1);
c2 = Character.toUpperCase(c2);
}
if(c1 != c2)
return false;
}
return true;
}
/**
* Checks if a subregion of a <code>Segment</code> is equal to a
* character array.
* @param ignoreCase True if case should be ignored, false otherwise
* @param text The segment
* @param offset The offset into the segment
* @param match The character array to match
*/
public static boolean regionMatches(boolean ignoreCase, Segment text,
int offset, char[] match)
{
int length = offset + match.length;
char[] textArray = text.array;
if(length > text.offset + text.count)
return false;
for(int i = offset, j = 0; i < length; i++, j++)
{
char c1 = textArray[i];
char c2 = match[j];
if(ignoreCase)
{
c1 = Character.toUpperCase(c1);
c2 = Character.toUpperCase(c2);
}
if(c1 != c2)
return false;
}
return true;
}
/**
* Returns the default style table. This can be passed to the
* <code>setStyles()</code> method of <code>SyntaxDocument</code>
* to use the default syntax styles.
*/
public static SyntaxStyle[] getDefaultSyntaxStyles()
{
SyntaxStyle[] styles = new SyntaxStyle[Token.ID_COUNT];
styles[Token.COMMENT1] = new SyntaxStyle(Color.black,true,false);
styles[Token.COMMENT2] = new SyntaxStyle(new Color(0x990033),true,false);
styles[Token.KEYWORD1] = new SyntaxStyle(Color.black,false,true);
styles[Token.KEYWORD2] = new SyntaxStyle(Color.magenta,false,false);
styles[Token.KEYWORD3] = new SyntaxStyle(new Color(0x009600),false,false);
styles[Token.LITERAL1] = new SyntaxStyle(new Color(0x650099),false,false);
styles[Token.LITERAL2] = new SyntaxStyle(new Color(0x650099),false,true);
styles[Token.LABEL] = new SyntaxStyle(new Color(0x990033),false,true);
styles[Token.OPERATOR] = new SyntaxStyle(Color.black,false,true);
styles[Token.INVALID] = new SyntaxStyle(Color.red,false,true);
return styles;
}
/**
* Paints the specified line onto the graphics context. Note that this
* method munges the offset and count values of the segment.
* @param line The line segment
* @param tokens The token list for the line
* @param styles The syntax style list
* @param expander The tab expander used to determine tab stops. May
* be null
* @param gfx The graphics context
* @param x The x co-ordinate
* @param y The y co-ordinate
* @return The x co-ordinate, plus the width of the painted string
*/
public static int paintSyntaxLine(Segment line, Token tokens,
SyntaxStyle[] styles, TabExpander expander, Graphics gfx,
int x, int y)
{
Font defaultFont = gfx.getFont();
Color defaultColor = gfx.getColor();
int offset = 0;
for(;;)
{
byte id = tokens.id;
if(id == Token.END)
break;
int length = tokens.length;
if(id == Token.NULL)
{
if(!defaultColor.equals(gfx.getColor()))
gfx.setColor(defaultColor);
if(!defaultFont.equals(gfx.getFont()))
gfx.setFont(defaultFont);
}
else
styles[id].setGraphicsFlags(gfx,defaultFont);
line.count = length;
x = Utilities.drawTabbedText(line,x,y,gfx,expander,0);
line.offset += length;
offset += length;
tokens = tokens.next;
}
return x;
}
// private members
private SyntaxUtilities() {}
}
| Java |
package org.jedit.syntax;
/*
* SQLTokenMarker.java - Generic SQL token marker
* Copyright (C) 1999 mike dillon
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
import javax.swing.text.Segment;
/**
* SQL token marker.
*
* @author mike dillon
* @version $Id: SQLTokenMarker.java,v 1.6 1999/04/19 05:38:20 sp Exp $
*/
public class SQLTokenMarker extends TokenMarker
{
private int offset, lastOffset, lastKeyword, length;
// public members
public SQLTokenMarker(KeywordMap k)
{
this(k, false);
}
public SQLTokenMarker(KeywordMap k, boolean tsql)
{
keywords = k;
isTSQL = tsql;
}
public byte markTokensImpl(byte token, Segment line, int lineIndex)
{
offset = lastOffset = lastKeyword = line.offset;
length = line.count + offset;
loop:
for(int i = offset; i < length; i++)
{
switch(line.array[i])
{
case '*':
if(token == Token.COMMENT1 && length - i >= 1 && line.array[i+1] == '/')
{
token = Token.NULL;
i++;
addToken((i + 1) - lastOffset,Token.COMMENT1);
lastOffset = i + 1;
}
else if (token == Token.NULL)
{
searchBack(line, i);
addToken(1,Token.OPERATOR);
lastOffset = i + 1;
}
break;
case '[':
if(token == Token.NULL)
{
searchBack(line, i);
token = Token.LITERAL1;
literalChar = '[';
lastOffset = i;
}
break;
case ']':
if(token == Token.LITERAL1 && literalChar == '[')
{
token = Token.NULL;
literalChar = 0;
addToken((i + 1) - lastOffset,Token.LITERAL1);
lastOffset = i + 1;
}
break;
case '.': case ',': case '(': case ')':
if (token == Token.NULL) {
searchBack(line, i);
addToken(1, Token.NULL);
lastOffset = i + 1;
}
break;
case '+': case '%': case '&': case '|': case '^':
case '~': case '<': case '>': case '=':
if (token == Token.NULL) {
searchBack(line, i);
addToken(1,Token.OPERATOR);
lastOffset = i + 1;
}
break;
case ' ': case '\t':
if (token == Token.NULL) {
searchBack(line, i, false);
}
break;
case ':':
if(token == Token.NULL)
{
addToken((i+1) - lastOffset,Token.LABEL);
lastOffset = i + 1;
}
break;
case '/':
if(token == Token.NULL)
{
if (length - i >= 2 && line.array[i + 1] == '*')
{
searchBack(line, i);
token = Token.COMMENT1;
lastOffset = i;
i++;
}
else
{
searchBack(line, i);
addToken(1,Token.OPERATOR);
lastOffset = i + 1;
}
}
break;
case '-':
if(token == Token.NULL)
{
if (length - i >= 2 && line.array[i+1] == '-')
{
searchBack(line, i);
addToken(length - i,Token.COMMENT1);
lastOffset = length;
break loop;
}
else
{
searchBack(line, i);
addToken(1,Token.OPERATOR);
lastOffset = i + 1;
}
}
break;
case '!':
if(isTSQL && token == Token.NULL && length - i >= 2 &&
(line.array[i+1] == '=' || line.array[i+1] == '<' || line.array[i+1] == '>'))
{
searchBack(line, i);
addToken(1,Token.OPERATOR);
lastOffset = i + 1;
}
break;
case '"': case '\'':
if(token == Token.NULL)
{
token = Token.LITERAL1;
literalChar = line.array[i];
addToken(i - lastOffset,Token.NULL);
lastOffset = i;
}
else if(token == Token.LITERAL1 && literalChar == line.array[i])
{
token = Token.NULL;
literalChar = 0;
addToken((i + 1) - lastOffset,Token.LITERAL1);
lastOffset = i + 1;
}
break;
default:
break;
}
}
if(token == Token.NULL)
searchBack(line, length, false);
if(lastOffset != length)
addToken(length - lastOffset,token);
return token;
}
// protected members
protected boolean isTSQL = false;
// private members
private KeywordMap keywords;
private char literalChar = 0;
private void searchBack(Segment line, int pos)
{
searchBack(line, pos, true);
}
private void searchBack(Segment line, int pos, boolean padNull)
{
int len = pos - lastKeyword;
byte id = keywords.lookup(line,lastKeyword,len);
if(id != Token.NULL)
{
if(lastKeyword != lastOffset)
addToken(lastKeyword - lastOffset,Token.NULL);
addToken(len,id);
lastOffset = pos;
}
lastKeyword = pos + 1;
if (padNull && lastOffset < pos)
addToken(pos - lastOffset, Token.NULL);
}
}
| Java |
package org.jedit.syntax;
/*
* Token.java - Generic token
* Copyright (C) 1998, 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
/**
* A linked list of tokens. Each token has three fields - a token
* identifier, which is a byte value that can be looked up in the
* array returned by <code>SyntaxDocument.getColors()</code>
* to get a color value, a length value which is the length of the
* token in the text, and a pointer to the next token in the list.
*
* @author Slava Pestov
* @version $Id: Token.java,v 1.12 1999/12/13 03:40:30 sp Exp $
*/
public class Token
{
/**
* Normal text token id. This should be used to mark
* normal text.
*/
public static final byte NULL = 0;
/**
* Comment 1 token id. This can be used to mark a comment.
*/
public static final byte COMMENT1 = 1;
/**
* Comment 2 token id. This can be used to mark a comment.
*/
public static final byte COMMENT2 = 2;
/**
* Literal 1 token id. This can be used to mark a string
* literal (eg, C mode uses this to mark "..." literals)
*/
public static final byte LITERAL1 = 3;
/**
* Literal 2 token id. This can be used to mark an object
* literal (eg, Java mode uses this to mark true, false, etc)
*/
public static final byte LITERAL2 = 4;
/**
* Label token id. This can be used to mark labels
* (eg, C mode uses this to mark ...: sequences)
*/
public static final byte LABEL = 5;
/**
* Keyword 1 token id. This can be used to mark a
* keyword. This should be used for general language
* constructs.
*/
public static final byte KEYWORD1 = 6;
/**
* Keyword 2 token id. This can be used to mark a
* keyword. This should be used for preprocessor
* commands, or variables.
*/
public static final byte KEYWORD2 = 7;
/**
* Keyword 3 token id. This can be used to mark a
* keyword. This should be used for data types.
*/
public static final byte KEYWORD3 = 8;
/**
* Operator token id. This can be used to mark an
* operator. (eg, SQL mode marks +, -, etc with this
* token type)
*/
public static final byte OPERATOR = 9;
/**
* Invalid token id. This can be used to mark invalid
* or incomplete tokens, so the user can easily spot
* syntax errors.
*/
public static final byte INVALID = 10;
/**
* The total number of defined token ids.
*/
public static final byte ID_COUNT = 11;
/**
* The first id that can be used for internal state
* in a token marker.
*/
public static final byte INTERNAL_FIRST = 100;
/**
* The last id that can be used for internal state
* in a token marker.
*/
public static final byte INTERNAL_LAST = 126;
/**
* The token type, that along with a length of 0
* marks the end of the token list.
*/
public static final byte END = 127;
/**
* The length of this token.
*/
public int length;
/**
* The id of this token.
*/
public byte id;
/**
* The next token in the linked list.
*/
public Token next;
/**
* Creates a new token.
* @param length The length of the token
* @param id The id of the token
*/
public Token(int length, byte id)
{
this.length = length;
this.id = id;
}
/**
* Returns a string representation of this token.
*/
public String toString()
{
return "[id=" + id + ",length=" + length + "]";
}
}
| Java |
package org.jedit.syntax;
/*
* CCTokenMarker.java - C++ token marker
* Copyright (C) 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
import javax.swing.text.Segment;
/**
* C++ token marker.
*
* @author Slava Pestov
* @version $Id: CCTokenMarker.java,v 1.6 1999/12/13 03:40:29 sp Exp $
*/
public class CCTokenMarker extends CTokenMarker
{
public CCTokenMarker()
{
super(true,getKeywords());
}
public static KeywordMap getKeywords()
{
if(ccKeywords == null)
{
ccKeywords = new KeywordMap(false);
ccKeywords.add("and", Token.KEYWORD3);
ccKeywords.add("and_eq", Token.KEYWORD3);
ccKeywords.add("asm", Token.KEYWORD2); //
ccKeywords.add("auto", Token.KEYWORD1); //
ccKeywords.add("bitand", Token.KEYWORD3);
ccKeywords.add("bitor", Token.KEYWORD3);
ccKeywords.add("bool",Token.KEYWORD3);
ccKeywords.add("break", Token.KEYWORD1); //
ccKeywords.add("case", Token.KEYWORD1); //
ccKeywords.add("catch", Token.KEYWORD1);
ccKeywords.add("char", Token.KEYWORD3); //
ccKeywords.add("class", Token.KEYWORD3);
ccKeywords.add("compl", Token.KEYWORD3);
ccKeywords.add("const", Token.KEYWORD1); //
ccKeywords.add("const_cast", Token.KEYWORD3);
ccKeywords.add("continue", Token.KEYWORD1); //
ccKeywords.add("default", Token.KEYWORD1); //
ccKeywords.add("delete", Token.KEYWORD1);
ccKeywords.add("do",Token.KEYWORD1); //
ccKeywords.add("double" ,Token.KEYWORD3); //
ccKeywords.add("dynamic_cast", Token.KEYWORD3);
ccKeywords.add("else", Token.KEYWORD1); //
ccKeywords.add("enum", Token.KEYWORD3); //
ccKeywords.add("explicit", Token.KEYWORD1);
ccKeywords.add("export", Token.KEYWORD2);
ccKeywords.add("extern", Token.KEYWORD2); //
ccKeywords.add("false", Token.LITERAL2);
ccKeywords.add("float", Token.KEYWORD3); //
ccKeywords.add("for", Token.KEYWORD1); //
ccKeywords.add("friend", Token.KEYWORD1);
ccKeywords.add("goto", Token.KEYWORD1); //
ccKeywords.add("if", Token.KEYWORD1); //
ccKeywords.add("inline", Token.KEYWORD1);
ccKeywords.add("int", Token.KEYWORD3); //
ccKeywords.add("long", Token.KEYWORD3); //
ccKeywords.add("mutable", Token.KEYWORD3);
ccKeywords.add("namespace", Token.KEYWORD2);
ccKeywords.add("new", Token.KEYWORD1);
ccKeywords.add("not", Token.KEYWORD3);
ccKeywords.add("not_eq", Token.KEYWORD3);
ccKeywords.add("operator", Token.KEYWORD3);
ccKeywords.add("or", Token.KEYWORD3);
ccKeywords.add("or_eq", Token.KEYWORD3);
ccKeywords.add("private", Token.KEYWORD1);
ccKeywords.add("protected", Token.KEYWORD1);
ccKeywords.add("public", Token.KEYWORD1);
ccKeywords.add("register", Token.KEYWORD1);
ccKeywords.add("reinterpret_cast", Token.KEYWORD3);
ccKeywords.add("return", Token.KEYWORD1); //
ccKeywords.add("short", Token.KEYWORD3); //
ccKeywords.add("signed", Token.KEYWORD3); //
ccKeywords.add("sizeof", Token.KEYWORD1); //
ccKeywords.add("static", Token.KEYWORD1); //
ccKeywords.add("static_cast", Token.KEYWORD3);
ccKeywords.add("struct", Token.KEYWORD3); //
ccKeywords.add("switch", Token.KEYWORD1); //
ccKeywords.add("template", Token.KEYWORD3);
ccKeywords.add("this", Token.LITERAL2);
ccKeywords.add("throw", Token.KEYWORD1);
ccKeywords.add("true", Token.LITERAL2);
ccKeywords.add("try", Token.KEYWORD1);
ccKeywords.add("typedef", Token.KEYWORD3); //
ccKeywords.add("typeid", Token.KEYWORD3);
ccKeywords.add("typename", Token.KEYWORD3);
ccKeywords.add("union", Token.KEYWORD3); //
ccKeywords.add("unsigned", Token.KEYWORD3); //
ccKeywords.add("using", Token.KEYWORD2);
ccKeywords.add("virtual", Token.KEYWORD1);
ccKeywords.add("void", Token.KEYWORD1); //
ccKeywords.add("volatile", Token.KEYWORD1); //
ccKeywords.add("wchar_t", Token.KEYWORD3);
ccKeywords.add("while", Token.KEYWORD1); //
ccKeywords.add("xor", Token.KEYWORD3);
ccKeywords.add("xor_eq", Token.KEYWORD3);
// non ANSI keywords
ccKeywords.add("NULL", Token.LITERAL2);
}
return ccKeywords;
}
// private members
private static KeywordMap ccKeywords;
}
| Java |
/*
* BatchFileTokenMarker.java - Batch file token marker
* Copyright (C) 1998, 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
package org.jedit.syntax;
import javax.swing.text.Segment;
/**
* Batch file token marker.
*
* @author Slava Pestov
* @version $Id: BatchFileTokenMarker.java,v 1.20 1999/12/13 03:40:29 sp Exp $
*/
public class BatchFileTokenMarker extends TokenMarker
{
public byte markTokensImpl(byte token, Segment line, int lineIndex)
{
char[] array = line.array;
int offset = line.offset;
int lastOffset = offset;
int length = line.count + offset;
if(SyntaxUtilities.regionMatches(true,line,offset,"rem"))
{
addToken(line.count,Token.COMMENT1);
return Token.NULL;
}
loop: for(int i = offset; i < length; i++)
{
int i1 = (i+1);
switch(token)
{
case Token.NULL:
switch(array[i])
{
case '%':
addToken(i - lastOffset,token);
lastOffset = i;
if(length - i <= 3 || array[i+2] == ' ')
{
addToken(2,Token.KEYWORD2);
i += 2;
lastOffset = i;
}
else
token = Token.KEYWORD2;
break;
case '"':
addToken(i - lastOffset,token);
token = Token.LITERAL1;
lastOffset = i;
break;
case ':':
if(i == offset)
{
addToken(line.count,Token.LABEL);
lastOffset = length;
break loop;
}
break;
case ' ':
if(lastOffset == offset)
{
addToken(i - lastOffset,Token.KEYWORD1);
lastOffset = i;
}
break;
}
break;
case Token.KEYWORD2:
if(array[i] == '%')
{
addToken(i1 - lastOffset,token);
token = Token.NULL;
lastOffset = i1;
}
break;
case Token.LITERAL1:
if(array[i] == '"')
{
addToken(i1 - lastOffset,token);
token = Token.NULL;
lastOffset = i1;
}
break;
default:
throw new InternalError("Invalid state: " + token);
}
}
if(lastOffset != length)
{
if(token != Token.NULL)
token = Token.INVALID;
else if(lastOffset == offset)
token = Token.KEYWORD1;
addToken(length - lastOffset,token);
}
return Token.NULL;
}
public boolean supportsMultilineTokens()
{
return false;
}
}
| Java |
package org.jedit.syntax;
/*
* PHPTokenMarker.java - Token marker for PHP
* Copyright (C) 1999 Clancy Malcolm
* Based on HTMLTokenMarker.java Copyright (C) 1998, 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
import javax.swing.text.Segment;
/**
* PHP token marker.
*
* @author Clancy Malcolm
* @version $Id: PHPTokenMarker.java,v 1.1 1999/12/14 04:20:35 sp Exp $
*/
public class PHPTokenMarker extends TokenMarker
{
public static final byte SCRIPT = Token.INTERNAL_FIRST;
public byte markTokensImpl(byte token, Segment line, int lineIndex)
{
char[] array = line.array;
int offset = line.offset;
lastOffset = offset;
lastKeyword = offset;
int length = line.count + offset;
boolean backslash = false;
loop: for(int i = offset; i < length; i++)
{
int i1 = (i+1);
char c = array[i];
if(c == '\\')
{
backslash = !backslash;
continue;
}
switch(token)
{
case Token.NULL: // HTML text
backslash = false;
switch(c)
{
case '<':
addToken(i - lastOffset,token);
lastOffset = lastKeyword = i;
if(SyntaxUtilities.regionMatches(false,
line,i1,"!--"))
{
i += 3;
token = Token.COMMENT1;
}
else if(SyntaxUtilities.regionMatches(
true,line,i1,"?php"))
{
addToken(5,Token.LABEL);
lastOffset = lastKeyword = (i += 4) + 1;
token = SCRIPT;
}
else if(SyntaxUtilities.regionMatches(
true,line,i1,"?"))
{
addToken(2,Token.LABEL);
lastOffset = lastKeyword = (i += 1) + 1;
token = SCRIPT;
}
else if(SyntaxUtilities.regionMatches(
true,line,i1,"script>"))
{
addToken(8,Token.LABEL);
lastOffset = lastKeyword = (i += 7) + 1;
token = SCRIPT;
}
else
{
token = Token.KEYWORD1;
}
break;
case '&':
addToken(i - lastOffset,token);
lastOffset = lastKeyword = i;
token = Token.KEYWORD2;
break;
}
break;
case Token.KEYWORD1: // Inside a tag
backslash = false;
if(c == '>')
{
addToken(i1 - lastOffset,token);
lastOffset = lastKeyword = i1;
token = Token.NULL;
}
break;
case Token.KEYWORD2: // Inside an entity
backslash = false;
if(c == ';')
{
addToken(i1 - lastOffset,token);
lastOffset = lastKeyword = i1;
token = Token.NULL;
break;
}
break;
case Token.COMMENT1: // Inside a comment
backslash = false;
if(SyntaxUtilities.regionMatches(false,line,i,"-->"))
{
addToken(i + 3 - lastOffset,token);
i += 2;
lastOffset = lastKeyword = i + 1;
token = Token.NULL;
}
break;
case SCRIPT: // Inside a JavaScript or PHP
switch(c)
{
case '<':
backslash = false;
doKeyword(line,i,c);
if(SyntaxUtilities.regionMatches(true,
line,i1,"/script>"))
{
//Ending the script
addToken(i - lastOffset,
Token.KEYWORD3);
addToken(9,Token.LABEL);
lastOffset = lastKeyword = (i += 8) + 1;
token = Token.NULL;
}
else
{
// < operator
addToken(i - lastOffset,
Token.KEYWORD3);
addToken(1,Token.OPERATOR);
lastOffset = lastKeyword = i1;
}
break;
case '?':
backslash = false;
doKeyword(line, i, c);
if (array[i1] == '>')
{
//Ending the script
addToken(i - lastOffset,
Token.KEYWORD3);
addToken(2,Token.LABEL);
lastOffset = lastKeyword = (i += 1) + 1;
token = Token.NULL;
}
else
{
//? operator
addToken(i - lastOffset, Token.KEYWORD3);
addToken(1,Token.OPERATOR);
lastOffset = lastKeyword = i1;
}
break;
case '"':
if(backslash)
backslash = false;
else
{
doKeyword(line,i,c);
addToken(i - lastOffset,Token.KEYWORD3);
lastOffset = lastKeyword = i;
token = Token.LITERAL1;
}
break;
case '\'':
if(backslash)
backslash = false;
else
{
doKeyword(line,i,c);
addToken(i - lastOffset,Token.KEYWORD3);
lastOffset = lastKeyword = i;
token = Token.LITERAL2;
}
break;
case '#':
doKeyword(line,i,c);
addToken(i - lastOffset,Token.KEYWORD3);
addToken(length - i,Token.COMMENT2);
lastOffset = lastKeyword = length;
break loop;
case '/':
backslash = false;
doKeyword(line,i,c);
if(length - i > 1) /*This is the same as if(length > i + 1) */
{
addToken(i - lastOffset,Token.KEYWORD3);
lastOffset = lastKeyword = i;
if(array[i1] == '/')
{
addToken(length - i,Token.COMMENT2);
lastOffset = lastKeyword = length;
break loop;
}
else if(array[i1] == '*')
{
token = Token.COMMENT2;
}
else
{
// / operator
addToken(i - lastOffset, Token.KEYWORD3);
addToken(1,Token.OPERATOR);
lastOffset = lastKeyword = i1;
}
}
else
{
// / operator
addToken(i - lastOffset, Token.KEYWORD3);
addToken(1,Token.OPERATOR);
lastOffset = lastKeyword = i1;
}
break;
default:
backslash = false;
if(!Character.isLetterOrDigit(c)
&& c != '_' && c != '$')
{
doKeyword(line,i,c);
if (c != ' ')
{
//assume non alphanumeric characters are operators
addToken(i - lastOffset, Token.KEYWORD3);
addToken(1,Token.OPERATOR);
lastOffset = lastKeyword = i1;
}
}
break;
}
break;
case Token.LITERAL1: // Script "..."
if(backslash)
backslash = false;
else if(c == '"')
{
addToken(i1 - lastOffset,Token.LITERAL1);
lastOffset = lastKeyword = i1;
token = SCRIPT;
}
break;
case Token.LITERAL2: // Script '...'
if(backslash)
backslash = false;
else if(c == '\'')
{
addToken(i1 - lastOffset,Token.LITERAL1);
lastOffset = lastKeyword = i1;
token = SCRIPT;
}
break;
case Token.COMMENT2: // Inside a Script comment
backslash = false;
if(c == '*' && length - i > 1 && array[i1] == '/')
{
addToken(i + 2 - lastOffset,Token.COMMENT2);
i += 1;
lastOffset = lastKeyword = i + 1;
token = SCRIPT;
}
break;
default:
throw new InternalError("Invalid state: "
+ token);
}
}
switch(token)
{
case Token.LITERAL1:
addToken(length - lastOffset,Token.LITERAL1);
break;
case Token.LITERAL2:
addToken(length - lastOffset,Token.LITERAL2);
break;
case Token.KEYWORD2:
addToken(length - lastOffset,Token.INVALID);
token = Token.NULL;
break;
case SCRIPT:
doKeyword(line,length,'\0');
addToken(length - lastOffset,Token.KEYWORD3);
break;
default:
addToken(length - lastOffset,token);
break;
}
return token;
}
// private members
private static KeywordMap keywords;
private int lastOffset;
private int lastKeyword;
static
{
keywords = new KeywordMap(false);
keywords.add("function",Token.KEYWORD2);
keywords.add("class",Token.KEYWORD2);
keywords.add("var",Token.KEYWORD2);
keywords.add("require",Token.KEYWORD2);
keywords.add("include",Token.KEYWORD2);
keywords.add("else",Token.KEYWORD1);
keywords.add("elseif",Token.KEYWORD1);
keywords.add("do",Token.KEYWORD1);
keywords.add("for",Token.KEYWORD1);
keywords.add("if",Token.KEYWORD1);
keywords.add("endif",Token.KEYWORD1);
keywords.add("in",Token.KEYWORD1);
keywords.add("new",Token.KEYWORD1);
keywords.add("return",Token.KEYWORD1);
keywords.add("while",Token.KEYWORD1);
keywords.add("endwhile",Token.KEYWORD1);
keywords.add("with",Token.KEYWORD1);
keywords.add("break",Token.KEYWORD1);
keywords.add("switch",Token.KEYWORD1);
keywords.add("case",Token.KEYWORD1);
keywords.add("continue",Token.KEYWORD1);
keywords.add("default",Token.KEYWORD1);
keywords.add("echo",Token.KEYWORD1);
keywords.add("false",Token.KEYWORD1);
keywords.add("this",Token.KEYWORD1);
keywords.add("true",Token.KEYWORD1);
keywords.add("array",Token.KEYWORD1);
keywords.add("extends",Token.KEYWORD1);
}
private boolean doKeyword(Segment line, int i, char c)
{
int i1 = i+1;
int len = i - lastKeyword;
byte id = keywords.lookup(line,lastKeyword,len);
if(id != Token.NULL)
{
if(lastKeyword != lastOffset)
addToken(lastKeyword - lastOffset,Token.KEYWORD3);
addToken(len,id);
lastOffset = i;
}
lastKeyword = i1;
return false;
}
}
| Java |
package org.jedit.syntax;
/*
* TextAreaDefaults.java - Encapsulates default values for various settings
* Copyright (C) 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
import javax.swing.JPopupMenu;
import java.awt.Color;
/**
* Encapsulates default settings for a text area. This can be passed
* to the constructor once the necessary fields have been filled out.
* The advantage of doing this over calling lots of set() methods after
* creating the text area is that this method is faster.
*/
public class TextAreaDefaults
{
private static TextAreaDefaults DEFAULTS;
public InputHandler inputHandler;
public SyntaxDocument document;
public boolean editable;
public boolean caretVisible;
public boolean caretBlinks;
public boolean blockCaret;
public int electricScroll;
public int cols;
public int rows;
public SyntaxStyle[] styles;
public Color caretColor;
public Color selectionColor;
public Color lineHighlightColor;
public boolean lineHighlight;
public Color bracketHighlightColor;
public boolean bracketHighlight;
public Color eolMarkerColor;
public boolean eolMarkers;
public boolean paintInvalid;
public JPopupMenu popup;
/**
* Returns a new TextAreaDefaults object with the default values filled
* in.
*/
public static TextAreaDefaults getDefaults()
{
if(DEFAULTS == null)
{
DEFAULTS = new TextAreaDefaults();
DEFAULTS.inputHandler = new DefaultInputHandler();
DEFAULTS.inputHandler.addDefaultKeyBindings();
DEFAULTS.document = new SyntaxDocument();
DEFAULTS.editable = true;
DEFAULTS.caretVisible = true;
DEFAULTS.caretBlinks = true;
DEFAULTS.electricScroll = 3;
DEFAULTS.cols = 80;
DEFAULTS.rows = 25;
DEFAULTS.styles = SyntaxUtilities.getDefaultSyntaxStyles();
DEFAULTS.caretColor = Color.red;
DEFAULTS.selectionColor = new Color(0xccccff);
DEFAULTS.lineHighlightColor = new Color(0xe0e0e0);
DEFAULTS.lineHighlight = true;
DEFAULTS.bracketHighlightColor = Color.black;
DEFAULTS.bracketHighlight = true;
DEFAULTS.eolMarkerColor = new Color(0x009999);
DEFAULTS.eolMarkers = true;
DEFAULTS.paintInvalid = true;
}
return DEFAULTS;
}
}
| Java |
package org.jedit.syntax;
/*
* TeXTokenMarker.java - TeX/LaTeX/AMS-TeX token marker
* Copyright (C) 1998 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
import javax.swing.text.Segment;
/**
* TeX token marker.
*
* @author Slava Pestov
* @version $Id: TeXTokenMarker.java,v 1.16 1999/12/13 03:40:30 sp Exp $
*/
public class TeXTokenMarker extends TokenMarker
{
// public members
public static final byte BDFORMULA = Token.INTERNAL_FIRST;
public static final byte EDFORMULA = (byte)(Token.INTERNAL_FIRST + 1);
public byte markTokensImpl(byte token, Segment line, int lineIndex)
{
char[] array = line.array;
int offset = line.offset;
int lastOffset = offset;
int length = line.count + offset;
boolean backslash = false;
loop: for(int i = offset; i < length; i++)
{
int i1 = (i+1);
char c = array[i];
// if a backslash is followed immediately
// by a non-alpha character, the command at
// the non-alpha char. If we have a backslash,
// some text, and then a non-alpha char,
// the command ends before the non-alpha char.
if(Character.isLetter(c))
{
backslash = false;
}
else
{
if(backslash)
{
// \<non alpha>
// we skip over this character,
// hence the `continue'
backslash = false;
if(token == Token.KEYWORD2 || token == EDFORMULA)
token = Token.KEYWORD2;
addToken(i1 - lastOffset,token);
lastOffset = i1;
if(token == Token.KEYWORD1)
token = Token.NULL;
continue;
}
else
{
//\blah<non alpha>
// we leave the character in
// the stream, and it's not
// part of the command token
if(token == BDFORMULA || token == EDFORMULA)
token = Token.KEYWORD2;
addToken(i - lastOffset,token);
if(token == Token.KEYWORD1)
token = Token.NULL;
lastOffset = i;
}
}
switch(c)
{
case '%':
if(backslash)
{
backslash = false;
break;
}
addToken(i - lastOffset,token);
addToken(length - i,Token.COMMENT1);
lastOffset = length;
break loop;
case '\\':
backslash = true;
if(token == Token.NULL)
{
token = Token.KEYWORD1;
addToken(i - lastOffset,Token.NULL);
lastOffset = i;
}
break;
case '$':
backslash = false;
if(token == Token.NULL) // singe $
{
token = Token.KEYWORD2;
addToken(i - lastOffset,Token.NULL);
lastOffset = i;
}
else if(token == Token.KEYWORD1) // \...$
{
token = Token.KEYWORD2;
addToken(i - lastOffset,Token.KEYWORD1);
lastOffset = i;
}
else if(token == Token.KEYWORD2) // $$aaa
{
if(i - lastOffset == 1 && array[i-1] == '$')
{
token = BDFORMULA;
break;
}
token = Token.NULL;
addToken(i1 - lastOffset,Token.KEYWORD2);
lastOffset = i1;
}
else if(token == BDFORMULA) // $$aaa$
{
token = EDFORMULA;
}
else if(token == EDFORMULA) // $$aaa$$
{
token = Token.NULL;
addToken(i1 - lastOffset,Token.KEYWORD2);
lastOffset = i1;
}
break;
}
}
if(lastOffset != length)
addToken(length - lastOffset,token == BDFORMULA
|| token == EDFORMULA ? Token.KEYWORD2 :
token);
return (token != Token.KEYWORD1 ? token : Token.NULL);
}
}
| Java |
package org.jedit.syntax;
/*
* SyntaxDocument.java - Document that can be tokenized
* Copyright (C) 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.undo.UndoableEdit;
/**
* A document implementation that can be tokenized by the syntax highlighting
* system.
*
* @author Slava Pestov
* @version $Id: SyntaxDocument.java,v 1.14 1999/12/13 03:40:30 sp Exp $
*/
public class SyntaxDocument extends PlainDocument
{
/**
* Returns the token marker that is to be used to split lines
* of this document up into tokens. May return null if this
* document is not to be colorized.
*/
public TokenMarker getTokenMarker()
{
return tokenMarker;
}
/**
* Sets the token marker that is to be used to split lines of
* this document up into tokens. May throw an exception if
* this is not supported for this type of document.
* @param tm The new token marker
*/
public void setTokenMarker(TokenMarker tm)
{
tokenMarker = tm;
if(tm == null)
return;
tokenMarker.insertLines(0,getDefaultRootElement()
.getElementCount());
tokenizeLines();
}
/**
* Reparses the document, by passing all lines to the token
* marker. This should be called after the document is first
* loaded.
*/
public void tokenizeLines()
{
tokenizeLines(0,getDefaultRootElement().getElementCount());
}
/**
* Reparses the document, by passing the specified lines to the
* token marker. This should be called after a large quantity of
* text is first inserted.
* @param start The first line to parse
* @param len The number of lines, after the first one to parse
*/
public void tokenizeLines(int start, int len)
{
if(tokenMarker == null || !tokenMarker.supportsMultilineTokens())
return;
Segment lineSegment = new Segment();
Element map = getDefaultRootElement();
len += start;
try
{
for(int i = start; i < len; i++)
{
Element lineElement = map.getElement(i);
int lineStart = lineElement.getStartOffset();
getText(lineStart,lineElement.getEndOffset()
- lineStart - 1,lineSegment);
tokenMarker.markTokens(lineSegment,i);
}
}
catch(BadLocationException bl)
{
bl.printStackTrace();
}
}
/**
* Starts a compound edit that can be undone in one operation.
* Subclasses that implement undo should override this method;
* this class has no undo functionality so this method is
* empty.
*/
public void beginCompoundEdit() {}
/**
* Ends a compound edit that can be undone in one operation.
* Subclasses that implement undo should override this method;
* this class has no undo functionality so this method is
* empty.
*/
public void endCompoundEdit() {}
/**
* Adds an undoable edit to this document's undo list. The edit
* should be ignored if something is currently being undone.
* @param edit The undoable edit
*
* @since jEdit 2.2pre1
*/
public void addUndoableEdit(UndoableEdit edit) {}
// protected members
protected TokenMarker tokenMarker;
/**
* We overwrite this method to update the token marker
* state immediately so that any event listeners get a
* consistent token marker.
*/
protected void fireInsertUpdate(DocumentEvent evt)
{
if(tokenMarker != null)
{
DocumentEvent.ElementChange ch = evt.getChange(
getDefaultRootElement());
if(ch != null)
{
tokenMarker.insertLines(ch.getIndex() + 1,
ch.getChildrenAdded().length -
ch.getChildrenRemoved().length);
}
}
super.fireInsertUpdate(evt);
}
/**
* We overwrite this method to update the token marker
* state immediately so that any event listeners get a
* consistent token marker.
*/
protected void fireRemoveUpdate(DocumentEvent evt)
{
if(tokenMarker != null)
{
DocumentEvent.ElementChange ch = evt.getChange(
getDefaultRootElement());
if(ch != null)
{
tokenMarker.deleteLines(ch.getIndex() + 1,
ch.getChildrenRemoved().length -
ch.getChildrenAdded().length);
}
}
super.fireRemoveUpdate(evt);
}
}
| Java |
package org.jedit.syntax;
/*
* JavaScriptTokenMarker.java - JavaScript token marker
* Copyright (C) 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
import javax.swing.text.Segment;
/**
* JavaScript token marker.
*
* @author Slava Pestov
* @version $Id: JavaScriptTokenMarker.java,v 1.3 1999/12/13 03:40:29 sp Exp $
*/
public class JavaScriptTokenMarker extends CTokenMarker
{
public JavaScriptTokenMarker()
{
super(false,getKeywords());
}
public static KeywordMap getKeywords()
{
if(javaScriptKeywords == null)
{
javaScriptKeywords = new KeywordMap(false);
javaScriptKeywords.add("function",Token.KEYWORD3);
javaScriptKeywords.add("var",Token.KEYWORD3);
javaScriptKeywords.add("else",Token.KEYWORD1);
javaScriptKeywords.add("for",Token.KEYWORD1);
javaScriptKeywords.add("if",Token.KEYWORD1);
javaScriptKeywords.add("in",Token.KEYWORD1);
javaScriptKeywords.add("new",Token.KEYWORD1);
javaScriptKeywords.add("return",Token.KEYWORD1);
javaScriptKeywords.add("while",Token.KEYWORD1);
javaScriptKeywords.add("with",Token.KEYWORD1);
javaScriptKeywords.add("break",Token.KEYWORD1);
javaScriptKeywords.add("case",Token.KEYWORD1);
javaScriptKeywords.add("continue",Token.KEYWORD1);
javaScriptKeywords.add("default",Token.KEYWORD1);
javaScriptKeywords.add("false",Token.LABEL);
javaScriptKeywords.add("this",Token.LABEL);
javaScriptKeywords.add("true",Token.LABEL);
}
return javaScriptKeywords;
}
// private members
private static KeywordMap javaScriptKeywords;
}
| Java |
package org.jedit.syntax;
/*
* TextAreaPainter.java - Paints the text area
* Copyright (C) 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
import javax.swing.ToolTipManager;
import javax.swing.text.*;
import javax.swing.JComponent;
import java.awt.event.MouseEvent;
import java.awt.*;
/**
* The text area repaint manager. It performs double buffering and paints
* lines of text.
* @author Slava Pestov
* @version $Id: TextAreaPainter.java,v 1.24 1999/12/13 03:40:30 sp Exp $
*/
public class TextAreaPainter extends JComponent implements TabExpander
{
/**
* Creates a new repaint manager. This should be not be called
* directly.
*/
public TextAreaPainter(JEditTextArea textArea, TextAreaDefaults defaults)
{
this.textArea = textArea;
setAutoscrolls(true);
setDoubleBuffered(true);
setOpaque(true);
ToolTipManager.sharedInstance().registerComponent(this);
currentLine = new Segment();
currentLineIndex = -1;
setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
setFont(new Font("Monospaced",Font.PLAIN,14));
setForeground(Color.black);
setBackground(Color.white);
blockCaret = defaults.blockCaret;
styles = defaults.styles;
cols = defaults.cols;
rows = defaults.rows;
caretColor = defaults.caretColor;
selectionColor = defaults.selectionColor;
lineHighlightColor = defaults.lineHighlightColor;
lineHighlight = defaults.lineHighlight;
bracketHighlightColor = defaults.bracketHighlightColor;
bracketHighlight = defaults.bracketHighlight;
paintInvalid = defaults.paintInvalid;
eolMarkerColor = defaults.eolMarkerColor;
eolMarkers = defaults.eolMarkers;
}
/**
* Returns if this component can be traversed by pressing the
* Tab key. This returns false.
*/
public final boolean isManagingFocus()
{
return false;
}
/**
* Returns the syntax styles used to paint colorized text. Entry <i>n</i>
* will be used to paint tokens with id = <i>n</i>.
* @see org.gjt.sp.jedit.syntax.Token
*/
public final SyntaxStyle[] getStyles()
{
return styles;
}
/**
* Sets the syntax styles used to paint colorized text. Entry <i>n</i>
* will be used to paint tokens with id = <i>n</i>.
* @param styles The syntax styles
* @see org.gjt.sp.jedit.syntax.Token
*/
public final void setStyles(SyntaxStyle[] styles)
{
this.styles = styles;
repaint();
}
/**
* Returns the caret color.
*/
public final Color getCaretColor()
{
return caretColor;
}
/**
* Sets the caret color.
* @param caretColor The caret color
*/
public final void setCaretColor(Color caretColor)
{
this.caretColor = caretColor;
invalidateSelectedLines();
}
/**
* Returns the selection color.
*/
public final Color getSelectionColor()
{
return selectionColor;
}
/**
* Sets the selection color.
* @param selectionColor The selection color
*/
public final void setSelectionColor(Color selectionColor)
{
this.selectionColor = selectionColor;
invalidateSelectedLines();
}
/**
* Returns the line highlight color.
*/
public final Color getLineHighlightColor()
{
return lineHighlightColor;
}
/**
* Sets the line highlight color.
* @param lineHighlightColor The line highlight color
*/
public final void setLineHighlightColor(Color lineHighlightColor)
{
this.lineHighlightColor = lineHighlightColor;
invalidateSelectedLines();
}
/**
* Returns true if line highlight is enabled, false otherwise.
*/
public final boolean isLineHighlightEnabled()
{
return lineHighlight;
}
/**
* Enables or disables current line highlighting.
* @param lineHighlight True if current line highlight should be enabled,
* false otherwise
*/
public final void setLineHighlightEnabled(boolean lineHighlight)
{
this.lineHighlight = lineHighlight;
invalidateSelectedLines();
}
/**
* Returns the bracket highlight color.
*/
public final Color getBracketHighlightColor()
{
return bracketHighlightColor;
}
/**
* Sets the bracket highlight color.
* @param bracketHighlightColor The bracket highlight color
*/
public final void setBracketHighlightColor(Color bracketHighlightColor)
{
this.bracketHighlightColor = bracketHighlightColor;
invalidateLine(textArea.getBracketLine());
}
/**
* Returns true if bracket highlighting is enabled, false otherwise.
* When bracket highlighting is enabled, the bracket matching the
* one before the caret (if any) is highlighted.
*/
public final boolean isBracketHighlightEnabled()
{
return bracketHighlight;
}
/**
* Enables or disables bracket highlighting.
* When bracket highlighting is enabled, the bracket matching the
* one before the caret (if any) is highlighted.
* @param bracketHighlight True if bracket highlighting should be
* enabled, false otherwise
*/
public final void setBracketHighlightEnabled(boolean bracketHighlight)
{
this.bracketHighlight = bracketHighlight;
invalidateLine(textArea.getBracketLine());
}
/**
* Returns true if the caret should be drawn as a block, false otherwise.
*/
public final boolean isBlockCaretEnabled()
{
return blockCaret;
}
/**
* Sets if the caret should be drawn as a block, false otherwise.
* @param blockCaret True if the caret should be drawn as a block,
* false otherwise.
*/
public final void setBlockCaretEnabled(boolean blockCaret)
{
this.blockCaret = blockCaret;
invalidateSelectedLines();
}
/**
* Returns the EOL marker color.
*/
public final Color getEOLMarkerColor()
{
return eolMarkerColor;
}
/**
* Sets the EOL marker color.
* @param eolMarkerColor The EOL marker color
*/
public final void setEOLMarkerColor(Color eolMarkerColor)
{
this.eolMarkerColor = eolMarkerColor;
repaint();
}
/**
* Returns true if EOL markers are drawn, false otherwise.
*/
public final boolean getEOLMarkersPainted()
{
return eolMarkers;
}
/**
* Sets if EOL markers are to be drawn.
* @param eolMarkers True if EOL markers should be drawn, false otherwise
*/
public final void setEOLMarkersPainted(boolean eolMarkers)
{
this.eolMarkers = eolMarkers;
repaint();
}
/**
* Returns true if invalid lines are painted as red tildes (~),
* false otherwise.
*/
public boolean getInvalidLinesPainted()
{
return paintInvalid;
}
/**
* Sets if invalid lines are to be painted as red tildes.
* @param paintInvalid True if invalid lines should be drawn, false otherwise
*/
public void setInvalidLinesPainted(boolean paintInvalid)
{
this.paintInvalid = paintInvalid;
}
/**
* Adds a custom highlight painter.
* @param highlight The highlight
*/
public void addCustomHighlight(Highlight highlight)
{
highlight.init(textArea,highlights);
highlights = highlight;
}
/**
* Highlight interface.
*/
public interface Highlight
{
/**
* Called after the highlight painter has been added.
* @param textArea The text area
* @param next The painter this one should delegate to
*/
void init(JEditTextArea textArea, Highlight next);
/**
* This should paint the highlight and delgate to the
* next highlight painter.
* @param gfx The graphics context
* @param line The line number
* @param y The y co-ordinate of the line
*/
void paintHighlight(Graphics gfx, int line, int y);
/**
* Returns the tool tip to display at the specified
* location. If this highlighter doesn't know what to
* display, it should delegate to the next highlight
* painter.
* @param evt The mouse event
*/
String getToolTipText(MouseEvent evt);
}
/**
* Returns the tool tip to display at the specified location.
* @param evt The mouse event
*/
public String getToolTipText(MouseEvent evt)
{
if(highlights != null)
return highlights.getToolTipText(evt);
else
return null;
}
/**
* Returns the font metrics used by this component.
*/
public FontMetrics getFontMetrics()
{
return fm;
}
/**
* Sets the font for this component. This is overridden to update the
* cached font metrics and to recalculate which lines are visible.
* @param font The font
*/
public void setFont(Font font)
{
super.setFont(font);
fm = Toolkit.getDefaultToolkit().getFontMetrics(font);
textArea.recalculateVisibleLines();
}
/**
* Repaints the text.
* @param g The graphics context
*/
public void paint(Graphics gfx)
{
tabSize = fm.charWidth(' ') * ((Integer)textArea
.getDocument().getProperty(
PlainDocument.tabSizeAttribute)).intValue();
Rectangle clipRect = gfx.getClipBounds();
gfx.setColor(getBackground());
gfx.fillRect(clipRect.x,clipRect.y,clipRect.width,clipRect.height);
// We don't use yToLine() here because that method doesn't
// return lines past the end of the document
int height = fm.getHeight();
int firstLine = textArea.getFirstLine();
int firstInvalid = firstLine + clipRect.y / height;
// Because the clipRect's height is usually an even multiple
// of the font height, we subtract 1 from it, otherwise one
// too many lines will always be painted.
int lastInvalid = firstLine + (clipRect.y + clipRect.height - 1) / height;
try
{
TokenMarker tokenMarker = textArea.getDocument()
.getTokenMarker();
int x = textArea.getHorizontalOffset();
for(int line = firstInvalid; line <= lastInvalid; line++)
{
paintLine(gfx,tokenMarker,line,x);
}
if(tokenMarker != null && tokenMarker.isNextLineRequested())
{
int h = clipRect.y + clipRect.height;
repaint(0,h,getWidth(),getHeight() - h);
}
}
catch(Exception e)
{
System.err.println("Error repainting line"
+ " range {" + firstInvalid + ","
+ lastInvalid + "}:");
e.printStackTrace();
}
}
/**
* Marks a line as needing a repaint.
* @param line The line to invalidate
*/
public final void invalidateLine(int line)
{
repaint(0,textArea.lineToY(line) + fm.getMaxDescent() + fm.getLeading(),
getWidth(),fm.getHeight());
}
/**
* Marks a range of lines as needing a repaint.
* @param firstLine The first line to invalidate
* @param lastLine The last line to invalidate
*/
public final void invalidateLineRange(int firstLine, int lastLine)
{
repaint(0,textArea.lineToY(firstLine) + fm.getMaxDescent() + fm.getLeading(),
getWidth(),(lastLine - firstLine + 1) * fm.getHeight());
}
/**
* Repaints the lines containing the selection.
*/
public final void invalidateSelectedLines()
{
invalidateLineRange(textArea.getSelectionStartLine(),
textArea.getSelectionEndLine());
}
/**
* Implementation of TabExpander interface. Returns next tab stop after
* a specified point.
* @param x The x co-ordinate
* @param tabOffset Ignored
* @return The next tab stop after <i>x</i>
*/
public float nextTabStop(float x, int tabOffset)
{
int offset = textArea.getHorizontalOffset();
int ntabs = ((int)x - offset) / tabSize;
return (ntabs + 1) * tabSize + offset;
}
/**
* Returns the painter's preferred size.
*/
public Dimension getPreferredSize()
{
Dimension dim = new Dimension();
dim.width = fm.charWidth('w') * cols;
dim.height = fm.getHeight() * rows;
return dim;
}
/**
* Returns the painter's minimum size.
*/
public Dimension getMinimumSize()
{
return getPreferredSize();
}
// package-private members
int currentLineIndex;
Token currentLineTokens;
Segment currentLine;
// protected members
protected JEditTextArea textArea;
protected SyntaxStyle[] styles;
protected Color caretColor;
protected Color selectionColor;
protected Color lineHighlightColor;
protected Color bracketHighlightColor;
protected Color eolMarkerColor;
protected boolean blockCaret;
protected boolean lineHighlight;
protected boolean bracketHighlight;
protected boolean paintInvalid;
protected boolean eolMarkers;
protected int cols;
protected int rows;
protected int tabSize;
protected FontMetrics fm;
protected Highlight highlights;
protected void paintLine(Graphics gfx, TokenMarker tokenMarker,
int line, int x)
{
Font defaultFont = getFont();
Color defaultColor = getForeground();
currentLineIndex = line;
int y = textArea.lineToY(line);
if(line < 0 || line >= textArea.getLineCount())
{
if(paintInvalid)
{
paintHighlight(gfx,line,y);
styles[Token.INVALID].setGraphicsFlags(gfx,defaultFont);
gfx.drawString("~",0,y + fm.getHeight());
}
}
else if(tokenMarker == null)
{
paintPlainLine(gfx,line,defaultFont,defaultColor,x,y);
}
else
{
paintSyntaxLine(gfx,tokenMarker,line,defaultFont,
defaultColor,x,y);
}
}
protected void paintPlainLine(Graphics gfx, int line, Font defaultFont,
Color defaultColor, int x, int y)
{
paintHighlight(gfx,line,y);
textArea.getLineText(line,currentLine);
gfx.setFont(defaultFont);
gfx.setColor(defaultColor);
y += fm.getHeight();
x = Utilities.drawTabbedText(currentLine,x,y,gfx,this,0);
if(eolMarkers)
{
gfx.setColor(eolMarkerColor);
gfx.drawString(".",x,y);
}
}
protected void paintSyntaxLine(Graphics gfx, TokenMarker tokenMarker,
int line, Font defaultFont, Color defaultColor, int x, int y)
{
textArea.getLineText(currentLineIndex,currentLine);
currentLineTokens = tokenMarker.markTokens(currentLine,
currentLineIndex);
paintHighlight(gfx,line,y);
gfx.setFont(defaultFont);
gfx.setColor(defaultColor);
y += fm.getHeight();
x = SyntaxUtilities.paintSyntaxLine(currentLine,
currentLineTokens,styles,this,gfx,x,y);
if(eolMarkers)
{
gfx.setColor(eolMarkerColor);
gfx.drawString(".",x,y);
}
}
protected void paintHighlight(Graphics gfx, int line, int y)
{
if(line >= textArea.getSelectionStartLine()
&& line <= textArea.getSelectionEndLine())
paintLineHighlight(gfx,line,y);
if(highlights != null)
highlights.paintHighlight(gfx,line,y);
if(bracketHighlight && line == textArea.getBracketLine())
paintBracketHighlight(gfx,line,y);
if(line == textArea.getCaretLine())
paintCaret(gfx,line,y);
}
protected void paintLineHighlight(Graphics gfx, int line, int y)
{
int height = fm.getHeight();
y += fm.getLeading() + fm.getMaxDescent();
int selectionStart = textArea.getSelectionStart();
int selectionEnd = textArea.getSelectionEnd();
if(selectionStart == selectionEnd)
{
if(lineHighlight)
{
gfx.setColor(lineHighlightColor);
gfx.fillRect(0,y,getWidth(),height);
}
}
else
{
gfx.setColor(selectionColor);
int selectionStartLine = textArea.getSelectionStartLine();
int selectionEndLine = textArea.getSelectionEndLine();
int lineStart = textArea.getLineStartOffset(line);
int x1, x2;
if(textArea.isSelectionRectangular())
{
int lineLen = textArea.getLineLength(line);
x1 = textArea._offsetToX(line,Math.min(lineLen,
selectionStart - textArea.getLineStartOffset(
selectionStartLine)));
x2 = textArea._offsetToX(line,Math.min(lineLen,
selectionEnd - textArea.getLineStartOffset(
selectionEndLine)));
if(x1 == x2)
x2++;
}
else if(selectionStartLine == selectionEndLine)
{
x1 = textArea._offsetToX(line,
selectionStart - lineStart);
x2 = textArea._offsetToX(line,
selectionEnd - lineStart);
}
else if(line == selectionStartLine)
{
x1 = textArea._offsetToX(line,
selectionStart - lineStart);
x2 = getWidth();
}
else if(line == selectionEndLine)
{
x1 = 0;
x2 = textArea._offsetToX(line,
selectionEnd - lineStart);
}
else
{
x1 = 0;
x2 = getWidth();
}
// "inlined" min/max()
gfx.fillRect(x1 > x2 ? x2 : x1,y,x1 > x2 ?
(x1 - x2) : (x2 - x1),height);
}
}
protected void paintBracketHighlight(Graphics gfx, int line, int y)
{
int position = textArea.getBracketPosition();
if(position == -1)
return;
y += fm.getLeading() + fm.getMaxDescent();
int x = textArea._offsetToX(line,position);
gfx.setColor(bracketHighlightColor);
// Hack!!! Since there is no fast way to get the character
// from the bracket matching routine, we use ( since all
// brackets probably have the same width anyway
gfx.drawRect(x,y,fm.charWidth('(') - 1,
fm.getHeight() - 1);
}
protected void paintCaret(Graphics gfx, int line, int y)
{
if(textArea.isCaretVisible())
{
int offset = textArea.getCaretPosition()
- textArea.getLineStartOffset(line);
int caretX = textArea._offsetToX(line,offset);
int caretWidth = ((blockCaret ||
textArea.isOverwriteEnabled()) ?
fm.charWidth('w') : 1);
y += fm.getLeading() + fm.getMaxDescent();
int height = fm.getHeight();
gfx.setColor(caretColor);
if(textArea.isOverwriteEnabled())
{
gfx.fillRect(caretX,y + height - 1,
caretWidth,1);
}
else
{
gfx.drawRect(caretX,y,caretWidth - 1,height - 1);
}
}
}
}
| Java |
package org.jedit.syntax;
/*
* JEditTextArea.java - jEdit's text component
* Copyright (C) 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.undo.*;
import javax.swing.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.*;
import java.util.Enumeration;
import java.util.Vector;
/**
* jEdit's text area component. It is more suited for editing program
* source code than JEditorPane, because it drops the unnecessary features
* (images, variable-width lines, and so on) and adds a whole bunch of
* useful goodies such as:
* <ul>
* <li>More flexible key binding scheme
* <li>Supports macro recorders
* <li>Rectangular selection
* <li>Bracket highlighting
* <li>Syntax highlighting
* <li>Command repetition
* <li>Block caret can be enabled
* </ul>
* It is also faster and doesn't have as many problems. It can be used
* in other applications; the only other part of jEdit it depends on is
* the syntax package.<p>
*
* To use it in your app, treat it like any other component, for example:
* <pre>JEditTextArea ta = new JEditTextArea();
* ta.setTokenMarker(new JavaTokenMarker());
* ta.setText("public class Test {\n"
* + " public static void main(String[] args) {\n"
* + " System.out.println(\"Hello World\");\n"
* + " }\n"
* + "}");</pre>
*
* @author Slava Pestov
* @version $Id: JEditTextArea.java,v 1.36 1999/12/13 03:40:30 sp Exp $
*/
public class JEditTextArea extends JComponent
{
/**
* Adding components with this name to the text area will place
* them left of the horizontal scroll bar. In jEdit, the status
* bar is added this way.
*/
public static String LEFT_OF_SCROLLBAR = "los";
/**
* Creates a new JEditTextArea with the default settings.
*/
public JEditTextArea()
{
this(TextAreaDefaults.getDefaults());
}
/**
* Creates a new JEditTextArea with the specified settings.
* @param defaults The default settings
*/
public JEditTextArea(TextAreaDefaults defaults)
{
// Enable the necessary events
enableEvents(AWTEvent.KEY_EVENT_MASK);
// Initialize some misc. stuff
painter = new TextAreaPainter(this,defaults);
documentHandler = new DocumentHandler();
listenerList = new EventListenerList();
caretEvent = new MutableCaretEvent();
lineSegment = new Segment();
bracketLine = bracketPosition = -1;
blink = true;
// Initialize the GUI
setLayout(new ScrollLayout());
add(CENTER,painter);
add(RIGHT,vertical = new JScrollBar(JScrollBar.VERTICAL));
add(BOTTOM,horizontal = new JScrollBar(JScrollBar.HORIZONTAL));
// Add some event listeners
vertical.addAdjustmentListener(new AdjustHandler());
horizontal.addAdjustmentListener(new AdjustHandler());
painter.addComponentListener(new ComponentHandler());
painter.addMouseListener(new MouseHandler());
painter.addMouseMotionListener(new DragHandler());
addFocusListener(new FocusHandler());
// Load the defaults
setInputHandler(defaults.inputHandler);
setDocument(defaults.document);
editable = defaults.editable;
caretVisible = defaults.caretVisible;
caretBlinks = defaults.caretBlinks;
electricScroll = defaults.electricScroll;
popup = defaults.popup;
// We don't seem to get the initial focus event?
focusedComponent = this;
}
/**
* Returns if this component can be traversed by pressing
* the Tab key. This returns false.
*/
public final boolean isManagingFocus()
{
return true;
}
/**
* Returns the object responsible for painting this text area.
*/
public final TextAreaPainter getPainter()
{
return painter;
}
/**
* Returns the input handler.
*/
public final InputHandler getInputHandler()
{
return inputHandler;
}
/**
* Sets the input handler.
* @param inputHandler The new input handler
*/
public void setInputHandler(InputHandler inputHandler)
{
this.inputHandler = inputHandler;
}
/**
* Returns true if the caret is blinking, false otherwise.
*/
public final boolean isCaretBlinkEnabled()
{
return caretBlinks;
}
/**
* Toggles caret blinking.
* @param caretBlinks True if the caret should blink, false otherwise
*/
public void setCaretBlinkEnabled(boolean caretBlinks)
{
this.caretBlinks = caretBlinks;
if(!caretBlinks)
blink = false;
painter.invalidateSelectedLines();
}
/**
* Returns true if the caret is visible, false otherwise.
*/
public final boolean isCaretVisible()
{
return (!caretBlinks || blink) && caretVisible;
}
/**
* Sets if the caret should be visible.
* @param caretVisible True if the caret should be visible, false
* otherwise
*/
public void setCaretVisible(boolean caretVisible)
{
this.caretVisible = caretVisible;
blink = true;
painter.invalidateSelectedLines();
}
/**
* Blinks the caret.
*/
public final void blinkCaret()
{
if(caretBlinks)
{
blink = !blink;
painter.invalidateSelectedLines();
}
else
blink = true;
}
/**
* Returns the number of lines from the top and button of the
* text area that are always visible.
*/
public final int getElectricScroll()
{
return electricScroll;
}
/**
* Sets the number of lines from the top and bottom of the text
* area that are always visible
* @param electricScroll The number of lines always visible from
* the top or bottom
*/
public final void setElectricScroll(int electricScroll)
{
this.electricScroll = electricScroll;
}
/**
* Updates the state of the scroll bars. This should be called
* if the number of lines in the document changes, or when the
* size of the text are changes.
*/
public void updateScrollBars()
{
if(vertical != null && visibleLines != 0)
{
vertical.setValues(firstLine,visibleLines,0,getLineCount());
vertical.setUnitIncrement(2);
vertical.setBlockIncrement(visibleLines);
}
int width = painter.getWidth();
if(horizontal != null && width != 0)
{
horizontal.setValues(-horizontalOffset,width,0,width * 5);
horizontal.setUnitIncrement(painter.getFontMetrics()
.charWidth('w'));
horizontal.setBlockIncrement(width / 2);
}
}
/**
* Returns the line displayed at the text area's origin.
*/
public final int getFirstLine()
{
return firstLine;
}
/**
* Sets the line displayed at the text area's origin without
* updating the scroll bars.
*/
public void setFirstLine(int firstLine)
{
if(firstLine == this.firstLine)
return;
int oldFirstLine = this.firstLine;
this.firstLine = firstLine;
if(firstLine != vertical.getValue())
updateScrollBars();
painter.repaint();
}
/**
* Returns the number of lines visible in this text area.
*/
public final int getVisibleLines()
{
return visibleLines;
}
/**
* Recalculates the number of visible lines. This should not
* be called directly.
*/
public final void recalculateVisibleLines()
{
if(painter == null)
return;
int height = painter.getHeight();
int lineHeight = painter.getFontMetrics().getHeight();
int oldVisibleLines = visibleLines;
visibleLines = height / lineHeight;
updateScrollBars();
}
/**
* Returns the horizontal offset of drawn lines.
*/
public final int getHorizontalOffset()
{
return horizontalOffset;
}
/**
* Sets the horizontal offset of drawn lines. This can be used to
* implement horizontal scrolling.
* @param horizontalOffset offset The new horizontal offset
*/
public void setHorizontalOffset(int horizontalOffset)
{
if(horizontalOffset == this.horizontalOffset)
return;
this.horizontalOffset = horizontalOffset;
if(horizontalOffset != horizontal.getValue())
updateScrollBars();
painter.repaint();
}
/**
* A fast way of changing both the first line and horizontal
* offset.
* @param firstLine The new first line
* @param horizontalOffset The new horizontal offset
* @return True if any of the values were changed, false otherwise
*/
public boolean setOrigin(int firstLine, int horizontalOffset)
{
boolean changed = false;
int oldFirstLine = this.firstLine;
if(horizontalOffset != this.horizontalOffset)
{
this.horizontalOffset = horizontalOffset;
changed = true;
}
if(firstLine != this.firstLine)
{
this.firstLine = firstLine;
changed = true;
}
if(changed)
{
updateScrollBars();
painter.repaint();
}
return changed;
}
/**
* Ensures that the caret is visible by scrolling the text area if
* necessary.
* @return True if scrolling was actually performed, false if the
* caret was already visible
*/
public boolean scrollToCaret()
{
int line = getCaretLine();
int lineStart = getLineStartOffset(line);
int offset = Math.max(0,Math.min(getLineLength(line) - 1,
getCaretPosition() - lineStart));
return scrollTo(line,offset);
}
/**
* Ensures that the specified line and offset is visible by scrolling
* the text area if necessary.
* @param line The line to scroll to
* @param offset The offset in the line to scroll to
* @return True if scrolling was actually performed, false if the
* line and offset was already visible
*/
public boolean scrollTo(int line, int offset)
{
// visibleLines == 0 before the component is realized
// we can't do any proper scrolling then, so we have
// this hack...
if(visibleLines == 0)
{
setFirstLine(Math.max(0,line - electricScroll));
return true;
}
int newFirstLine = firstLine;
int newHorizontalOffset = horizontalOffset;
if(line < firstLine + electricScroll)
{
newFirstLine = Math.max(0,line - electricScroll);
}
else if(line + electricScroll >= firstLine + visibleLines)
{
newFirstLine = (line - visibleLines) + electricScroll + 1;
if(newFirstLine + visibleLines >= getLineCount())
newFirstLine = getLineCount() - visibleLines;
if(newFirstLine < 0)
newFirstLine = 0;
}
int x = _offsetToX(line,offset);
int width = painter.getFontMetrics().charWidth('w');
if(x < 0)
{
newHorizontalOffset = Math.min(0,horizontalOffset
- x + width + 5);
}
else if(x + width >= painter.getWidth())
{
newHorizontalOffset = horizontalOffset +
(painter.getWidth() - x) - width - 5;
}
return setOrigin(newFirstLine,newHorizontalOffset);
}
/**
* Converts a line index to a y co-ordinate.
* @param line The line
*/
public int lineToY(int line)
{
FontMetrics fm = painter.getFontMetrics();
return (line - firstLine) * fm.getHeight()
- (fm.getLeading() + fm.getMaxDescent());
}
/**
* Converts a y co-ordinate to a line index.
* @param y The y co-ordinate
*/
public int yToLine(int y)
{
FontMetrics fm = painter.getFontMetrics();
int height = fm.getHeight();
return Math.max(0,Math.min(getLineCount() - 1,
y / height + firstLine));
}
/**
* Converts an offset in a line into an x co-ordinate. This is a
* slow version that can be used any time.
* @param line The line
* @param offset The offset, from the start of the line
*/
public final int offsetToX(int line, int offset)
{
// don't use cached tokens
painter.currentLineTokens = null;
return _offsetToX(line,offset);
}
/**
* Converts an offset in a line into an x co-ordinate. This is a
* fast version that should only be used if no changes were made
* to the text since the last repaint.
* @param line The line
* @param offset The offset, from the start of the line
*/
public int _offsetToX(int line, int offset)
{
TokenMarker tokenMarker = getTokenMarker();
/* Use painter's cached info for speed */
FontMetrics fm = painter.getFontMetrics();
getLineText(line,lineSegment);
int segmentOffset = lineSegment.offset;
int x = horizontalOffset;
/* If syntax coloring is disabled, do simple translation */
if(tokenMarker == null)
{
lineSegment.count = offset;
return x + Utilities.getTabbedTextWidth(lineSegment,
fm,x,painter,0);
}
/* If syntax coloring is enabled, we have to do this because
* tokens can vary in width */
else
{
Token tokens;
if(painter.currentLineIndex == line
&& painter.currentLineTokens != null)
tokens = painter.currentLineTokens;
else
{
painter.currentLineIndex = line;
tokens = painter.currentLineTokens
= tokenMarker.markTokens(lineSegment,line);
}
Toolkit toolkit = painter.getToolkit();
Font defaultFont = painter.getFont();
SyntaxStyle[] styles = painter.getStyles();
for(;;)
{
byte id = tokens.id;
if(id == Token.END)
{
return x;
}
if(id == Token.NULL)
fm = painter.getFontMetrics();
else
fm = styles[id].getFontMetrics(defaultFont);
int length = tokens.length;
if(offset + segmentOffset < lineSegment.offset + length)
{
lineSegment.count = offset - (lineSegment.offset - segmentOffset);
return x + Utilities.getTabbedTextWidth(
lineSegment,fm,x,painter,0);
}
else
{
lineSegment.count = length;
x += Utilities.getTabbedTextWidth(
lineSegment,fm,x,painter,0);
lineSegment.offset += length;
}
tokens = tokens.next;
}
}
}
/**
* Converts an x co-ordinate to an offset within a line.
* @param line The line
* @param x The x co-ordinate
*/
public int xToOffset(int line, int x)
{
TokenMarker tokenMarker = getTokenMarker();
/* Use painter's cached info for speed */
FontMetrics fm = painter.getFontMetrics();
getLineText(line,lineSegment);
char[] segmentArray = lineSegment.array;
int segmentOffset = lineSegment.offset;
int segmentCount = lineSegment.count;
int width = horizontalOffset;
if(tokenMarker == null)
{
for(int i = 0; i < segmentCount; i++)
{
char c = segmentArray[i + segmentOffset];
int charWidth;
if(c == '\t')
charWidth = (int)painter.nextTabStop(width,i)
- width;
else
charWidth = fm.charWidth(c);
if(painter.isBlockCaretEnabled())
{
if(x - charWidth <= width)
return i;
}
else
{
if(x - charWidth / 2 <= width)
return i;
}
width += charWidth;
}
return segmentCount;
}
else
{
Token tokens;
if(painter.currentLineIndex == line && painter
.currentLineTokens != null)
tokens = painter.currentLineTokens;
else
{
painter.currentLineIndex = line;
tokens = painter.currentLineTokens
= tokenMarker.markTokens(lineSegment,line);
}
int offset = 0;
Toolkit toolkit = painter.getToolkit();
Font defaultFont = painter.getFont();
SyntaxStyle[] styles = painter.getStyles();
for(;;)
{
byte id = tokens.id;
if(id == Token.END)
return offset;
if(id == Token.NULL)
fm = painter.getFontMetrics();
else
fm = styles[id].getFontMetrics(defaultFont);
int length = tokens.length;
for(int i = 0; i < length; i++)
{
char c = segmentArray[segmentOffset + offset + i];
int charWidth;
if(c == '\t')
charWidth = (int)painter.nextTabStop(width,offset + i)
- width;
else
charWidth = fm.charWidth(c);
if(painter.isBlockCaretEnabled())
{
if(x - charWidth <= width)
return offset + i;
}
else
{
if(x - charWidth / 2 <= width)
return offset + i;
}
width += charWidth;
}
offset += length;
tokens = tokens.next;
}
}
}
/**
* Converts a point to an offset, from the start of the text.
* @param x The x co-ordinate of the point
* @param y The y co-ordinate of the point
*/
public int xyToOffset(int x, int y)
{
int line = yToLine(y);
int start = getLineStartOffset(line);
return start + xToOffset(line,x);
}
/**
* Returns the document this text area is editing.
*/
public final SyntaxDocument getDocument()
{
return document;
}
/**
* Sets the document this text area is editing.
* @param document The document
*/
public void setDocument(SyntaxDocument document)
{
if(this.document == document)
return;
if(this.document != null)
this.document.removeDocumentListener(documentHandler);
this.document = document;
document.addDocumentListener(documentHandler);
select(0,0);
updateScrollBars();
painter.repaint();
}
/**
* Returns the document's token marker. Equivalent to calling
* <code>getDocument().getTokenMarker()</code>.
*/
public final TokenMarker getTokenMarker()
{
return document.getTokenMarker();
}
/**
* Sets the document's token marker. Equivalent to caling
* <code>getDocument().setTokenMarker()</code>.
* @param tokenMarker The token marker
*/
public final void setTokenMarker(TokenMarker tokenMarker)
{
document.setTokenMarker(tokenMarker);
}
/**
* Returns the length of the document. Equivalent to calling
* <code>getDocument().getLength()</code>.
*/
public final int getDocumentLength()
{
return document.getLength();
}
/**
* Returns the number of lines in the document.
*/
public final int getLineCount()
{
return document.getDefaultRootElement().getElementCount();
}
/**
* Returns the line containing the specified offset.
* @param offset The offset
*/
public final int getLineOfOffset(int offset)
{
return document.getDefaultRootElement().getElementIndex(offset);
}
/**
* Returns the start offset of the specified line.
* @param line The line
* @return The start offset of the specified line, or -1 if the line is
* invalid
*/
public int getLineStartOffset(int line)
{
Element lineElement = document.getDefaultRootElement()
.getElement(line);
if(lineElement == null)
return -1;
else
return lineElement.getStartOffset();
}
/**
* Returns the end offset of the specified line.
* @param line The line
* @return The end offset of the specified line, or -1 if the line is
* invalid.
*/
public int getLineEndOffset(int line)
{
Element lineElement = document.getDefaultRootElement()
.getElement(line);
if(lineElement == null)
return -1;
else
return lineElement.getEndOffset();
}
/**
* Returns the length of the specified line.
* @param line The line
*/
public int getLineLength(int line)
{
Element lineElement = document.getDefaultRootElement()
.getElement(line);
if(lineElement == null)
return -1;
else
return lineElement.getEndOffset()
- lineElement.getStartOffset() - 1;
}
/**
* Returns the entire text of this text area.
*/
public String getText()
{
try
{
return document.getText(0,document.getLength());
}
catch(BadLocationException bl)
{
bl.printStackTrace();
return null;
}
}
/**
* Sets the entire text of this text area.
*/
public void setText(String text)
{
try
{
document.beginCompoundEdit();
document.remove(0,document.getLength());
document.insertString(0,text,null);
}
catch(BadLocationException bl)
{
bl.printStackTrace();
}
finally
{
document.endCompoundEdit();
}
}
/**
* Returns the specified substring of the document.
* @param start The start offset
* @param len The length of the substring
* @return The substring, or null if the offsets are invalid
*/
public final String getText(int start, int len)
{
try
{
return document.getText(start,len);
}
catch(BadLocationException bl)
{
bl.printStackTrace();
return null;
}
}
/**
* Copies the specified substring of the document into a segment.
* If the offsets are invalid, the segment will contain a null string.
* @param start The start offset
* @param len The length of the substring
* @param segment The segment
*/
public final void getText(int start, int len, Segment segment)
{
try
{
document.getText(start,len,segment);
}
catch(BadLocationException bl)
{
bl.printStackTrace();
segment.offset = segment.count = 0;
}
}
/**
* Returns the text on the specified line.
* @param lineIndex The line
* @return The text, or null if the line is invalid
*/
public final String getLineText(int lineIndex)
{
int start = getLineStartOffset(lineIndex);
return getText(start,getLineEndOffset(lineIndex) - start - 1);
}
/**
* Copies the text on the specified line into a segment. If the line
* is invalid, the segment will contain a null string.
* @param lineIndex The line
*/
public final void getLineText(int lineIndex, Segment segment)
{
int start = getLineStartOffset(lineIndex);
getText(start,getLineEndOffset(lineIndex) - start - 1,segment);
}
/**
* Returns the selection start offset.
*/
public final int getSelectionStart()
{
return selectionStart;
}
/**
* Returns the offset where the selection starts on the specified
* line.
*/
public int getSelectionStart(int line)
{
if(line == selectionStartLine)
return selectionStart;
else if(rectSelect)
{
Element map = document.getDefaultRootElement();
int start = selectionStart - map.getElement(selectionStartLine)
.getStartOffset();
Element lineElement = map.getElement(line);
int lineStart = lineElement.getStartOffset();
int lineEnd = lineElement.getEndOffset() - 1;
return Math.min(lineEnd,lineStart + start);
}
else
return getLineStartOffset(line);
}
/**
* Returns the selection start line.
*/
public final int getSelectionStartLine()
{
return selectionStartLine;
}
/**
* Sets the selection start. The new selection will be the new
* selection start and the old selection end.
* @param selectionStart The selection start
* @see #select(int,int)
*/
public final void setSelectionStart(int selectionStart)
{
select(selectionStart,selectionEnd);
}
/**
* Returns the selection end offset.
*/
public final int getSelectionEnd()
{
return selectionEnd;
}
/**
* Returns the offset where the selection ends on the specified
* line.
*/
public int getSelectionEnd(int line)
{
if(line == selectionEndLine)
return selectionEnd;
else if(rectSelect)
{
Element map = document.getDefaultRootElement();
int end = selectionEnd - map.getElement(selectionEndLine)
.getStartOffset();
Element lineElement = map.getElement(line);
int lineStart = lineElement.getStartOffset();
int lineEnd = lineElement.getEndOffset() - 1;
return Math.min(lineEnd,lineStart + end);
}
else
return getLineEndOffset(line) - 1;
}
/**
* Returns the selection end line.
*/
public final int getSelectionEndLine()
{
return selectionEndLine;
}
/**
* Sets the selection end. The new selection will be the old
* selection start and the bew selection end.
* @param selectionEnd The selection end
* @see #select(int,int)
*/
public final void setSelectionEnd(int selectionEnd)
{
select(selectionStart,selectionEnd);
}
/**
* Returns the caret position. This will either be the selection
* start or the selection end, depending on which direction the
* selection was made in.
*/
public final int getCaretPosition()
{
return (biasLeft ? selectionStart : selectionEnd);
}
/**
* Returns the caret line.
*/
public final int getCaretLine()
{
return (biasLeft ? selectionStartLine : selectionEndLine);
}
/**
* Returns the mark position. This will be the opposite selection
* bound to the caret position.
* @see #getCaretPosition()
*/
public final int getMarkPosition()
{
return (biasLeft ? selectionEnd : selectionStart);
}
/**
* Returns the mark line.
*/
public final int getMarkLine()
{
return (biasLeft ? selectionEndLine : selectionStartLine);
}
/**
* Sets the caret position. The new selection will consist of the
* caret position only (hence no text will be selected)
* @param caret The caret position
* @see #select(int,int)
*/
public final void setCaretPosition(int caret)
{
select(caret,caret);
}
/**
* Selects all text in the document.
*/
public final void selectAll()
{
select(0,getDocumentLength());
}
/**
* Moves the mark to the caret position.
*/
public final void selectNone()
{
select(getCaretPosition(),getCaretPosition());
}
/**
* Selects from the start offset to the end offset. This is the
* general selection method used by all other selecting methods.
* The caret position will be start if start < end, and end
* if end > start.
* @param start The start offset
* @param end The end offset
*/
public void select(int start, int end)
{
int newStart, newEnd;
boolean newBias;
if(start <= end)
{
newStart = start;
newEnd = end;
newBias = false;
}
else
{
newStart = end;
newEnd = start;
newBias = true;
}
if(newStart < 0 || newEnd > getDocumentLength())
{
throw new IllegalArgumentException("Bounds out of"
+ " range: " + newStart + "," +
newEnd);
}
// If the new position is the same as the old, we don't
// do all this crap, however we still do the stuff at
// the end (clearing magic position, scrolling)
if(newStart != selectionStart || newEnd != selectionEnd
|| newBias != biasLeft)
{
int newStartLine = getLineOfOffset(newStart);
int newEndLine = getLineOfOffset(newEnd);
if(painter.isBracketHighlightEnabled())
{
if(bracketLine != -1)
painter.invalidateLine(bracketLine);
updateBracketHighlight(end);
if(bracketLine != -1)
painter.invalidateLine(bracketLine);
}
painter.invalidateLineRange(selectionStartLine,selectionEndLine);
painter.invalidateLineRange(newStartLine,newEndLine);
document.addUndoableEdit(new CaretUndo(
selectionStart,selectionEnd));
selectionStart = newStart;
selectionEnd = newEnd;
selectionStartLine = newStartLine;
selectionEndLine = newEndLine;
biasLeft = newBias;
fireCaretEvent();
}
// When the user is typing, etc, we don't want the caret
// to blink
blink = true;
caretTimer.restart();
// Disable rectangle select if selection start = selection end
if(selectionStart == selectionEnd)
rectSelect = false;
// Clear the `magic' caret position used by up/down
magicCaret = -1;
scrollToCaret();
}
/**
* Returns the selected text, or null if no selection is active.
*/
public final String getSelectedText()
{
if(selectionStart == selectionEnd)
return null;
if(rectSelect)
{
// Return each row of the selection on a new line
Element map = document.getDefaultRootElement();
int start = selectionStart - map.getElement(selectionStartLine)
.getStartOffset();
int end = selectionEnd - map.getElement(selectionEndLine)
.getStartOffset();
// Certain rectangles satisfy this condition...
if(end < start)
{
int tmp = end;
end = start;
start = tmp;
}
StringBuffer buf = new StringBuffer();
Segment seg = new Segment();
for(int i = selectionStartLine; i <= selectionEndLine; i++)
{
Element lineElement = map.getElement(i);
int lineStart = lineElement.getStartOffset();
int lineEnd = lineElement.getEndOffset() - 1;
int lineLen = lineEnd - lineStart;
lineStart = Math.min(lineStart + start,lineEnd);
lineLen = Math.min(end - start,lineEnd - lineStart);
getText(lineStart,lineLen,seg);
buf.append(seg.array,seg.offset,seg.count);
if(i != selectionEndLine)
buf.append('\n');
}
return buf.toString();
}
else
{
return getText(selectionStart,
selectionEnd - selectionStart);
}
}
/**
* Replaces the selection with the specified text.
* @param selectedText The replacement text for the selection
*/
public void setSelectedText(String selectedText)
{
if(!editable)
{
throw new InternalError("Text component"
+ " read only");
}
document.beginCompoundEdit();
try
{
if(rectSelect)
{
Element map = document.getDefaultRootElement();
int start = selectionStart - map.getElement(selectionStartLine)
.getStartOffset();
int end = selectionEnd - map.getElement(selectionEndLine)
.getStartOffset();
// Certain rectangles satisfy this condition...
if(end < start)
{
int tmp = end;
end = start;
start = tmp;
}
int lastNewline = 0;
int currNewline = 0;
for(int i = selectionStartLine; i <= selectionEndLine; i++)
{
Element lineElement = map.getElement(i);
int lineStart = lineElement.getStartOffset();
int lineEnd = lineElement.getEndOffset() - 1;
int rectStart = Math.min(lineEnd,lineStart + start);
document.remove(rectStart,Math.min(lineEnd - rectStart,
end - start));
if(selectedText == null)
continue;
currNewline = selectedText.indexOf('\n',lastNewline);
if(currNewline == -1)
currNewline = selectedText.length();
document.insertString(rectStart,selectedText
.substring(lastNewline,currNewline),null);
lastNewline = Math.min(selectedText.length(),
currNewline + 1);
}
if(selectedText != null &&
currNewline != selectedText.length())
{
int offset = map.getElement(selectionEndLine)
.getEndOffset() - 1;
document.insertString(offset,"\n",null);
document.insertString(offset + 1,selectedText
.substring(currNewline + 1),null);
}
}
else
{
document.remove(selectionStart,
selectionEnd - selectionStart);
if(selectedText != null)
{
document.insertString(selectionStart,
selectedText,null);
}
}
}
catch(BadLocationException bl)
{
bl.printStackTrace();
throw new InternalError("Cannot replace"
+ " selection");
}
// No matter what happends... stops us from leaving document
// in a bad state
finally
{
document.endCompoundEdit();
}
setCaretPosition(selectionEnd);
}
/**
* Returns true if this text area is editable, false otherwise.
*/
public final boolean isEditable()
{
return editable;
}
/**
* Sets if this component is editable.
* @param editable True if this text area should be editable,
* false otherwise
*/
public final void setEditable(boolean editable)
{
this.editable = editable;
}
/**
* Returns the right click popup menu.
*/
public final JPopupMenu getRightClickPopup()
{
return popup;
}
/**
* Sets the right click popup menu.
* @param popup The popup
*/
public final void setRightClickPopup(JPopupMenu popup)
{
this.popup = popup;
}
/**
* Returns the `magic' caret position. This can be used to preserve
* the column position when moving up and down lines.
*/
public final int getMagicCaretPosition()
{
return magicCaret;
}
/**
* Sets the `magic' caret position. This can be used to preserve
* the column position when moving up and down lines.
* @param magicCaret The magic caret position
*/
public final void setMagicCaretPosition(int magicCaret)
{
this.magicCaret = magicCaret;
}
/**
* Similar to <code>setSelectedText()</code>, but overstrikes the
* appropriate number of characters if overwrite mode is enabled.
* @param str The string
* @see #setSelectedText(String)
* @see #isOverwriteEnabled()
*/
public void overwriteSetSelectedText(String str)
{
// Don't overstrike if there is a selection
if(!overwrite || selectionStart != selectionEnd)
{
setSelectedText(str);
return;
}
// Don't overstrike if we're on the end of
// the line
int caret = getCaretPosition();
int caretLineEnd = getLineEndOffset(getCaretLine());
if(caretLineEnd - caret <= str.length())
{
setSelectedText(str);
return;
}
document.beginCompoundEdit();
try
{
document.remove(caret,str.length());
document.insertString(caret,str,null);
}
catch(BadLocationException bl)
{
bl.printStackTrace();
}
finally
{
document.endCompoundEdit();
}
}
/**
* Returns true if overwrite mode is enabled, false otherwise.
*/
public final boolean isOverwriteEnabled()
{
return overwrite;
}
/**
* Sets if overwrite mode should be enabled.
* @param overwrite True if overwrite mode should be enabled,
* false otherwise.
*/
public final void setOverwriteEnabled(boolean overwrite)
{
this.overwrite = overwrite;
painter.invalidateSelectedLines();
}
/**
* Returns true if the selection is rectangular, false otherwise.
*/
public final boolean isSelectionRectangular()
{
return rectSelect;
}
/**
* Sets if the selection should be rectangular.
* @param overwrite True if the selection should be rectangular,
* false otherwise.
*/
public final void setSelectionRectangular(boolean rectSelect)
{
this.rectSelect = rectSelect;
painter.invalidateSelectedLines();
}
/**
* Returns the position of the highlighted bracket (the bracket
* matching the one before the caret)
*/
public final int getBracketPosition()
{
return bracketPosition;
}
/**
* Returns the line of the highlighted bracket (the bracket
* matching the one before the caret)
*/
public final int getBracketLine()
{
return bracketLine;
}
/**
* Adds a caret change listener to this text area.
* @param listener The listener
*/
public final void addCaretListener(CaretListener listener)
{
listenerList.add(CaretListener.class,listener);
}
/**
* Removes a caret change listener from this text area.
* @param listener The listener
*/
public final void removeCaretListener(CaretListener listener)
{
listenerList.remove(CaretListener.class,listener);
}
/**
* Deletes the selected text from the text area and places it
* into the clipboard.
*/
public void cut()
{
if(editable)
{
copy();
setSelectedText("");
}
}
/**
* Places the selected text into the clipboard.
*/
public void copy()
{
if(selectionStart != selectionEnd)
{
Clipboard clipboard = getToolkit().getSystemClipboard();
String selection = getSelectedText();
int repeatCount = inputHandler.getRepeatCount();
StringBuffer buf = new StringBuffer();
for(int i = 0; i < repeatCount; i++)
buf.append(selection);
clipboard.setContents(new StringSelection(buf.toString()),null);
}
}
/**
* Inserts the clipboard contents into the text.
*/
public void paste()
{
if(editable)
{
Clipboard clipboard = getToolkit().getSystemClipboard();
try
{
// The MacOS MRJ doesn't convert \r to \n,
// so do it here
String selection = ((String)clipboard
.getContents(this).getTransferData(
DataFlavor.stringFlavor))
.replace('\r','\n');
int repeatCount = inputHandler.getRepeatCount();
StringBuffer buf = new StringBuffer();
for(int i = 0; i < repeatCount; i++)
buf.append(selection);
selection = buf.toString();
setSelectedText(selection);
}
catch(Exception e)
{
getToolkit().beep();
System.err.println("Clipboard does not"
+ " contain a string");
}
}
}
/**
* Called by the AWT when this component is removed from it's parent.
* This stops clears the currently focused component.
*/
public void removeNotify()
{
super.removeNotify();
if(focusedComponent == this)
focusedComponent = null;
}
/**
* Forwards key events directly to the input handler.
* This is slightly faster than using a KeyListener
* because some Swing overhead is avoided.
*/
public void processKeyEvent(KeyEvent evt)
{
if(inputHandler == null)
return;
switch(evt.getID())
{
case KeyEvent.KEY_TYPED:
inputHandler.keyTyped(evt);
break;
case KeyEvent.KEY_PRESSED:
inputHandler.keyPressed(evt);
break;
case KeyEvent.KEY_RELEASED:
inputHandler.keyReleased(evt);
break;
}
}
// protected members
protected static String CENTER = "center";
protected static String RIGHT = "right";
protected static String BOTTOM = "bottom";
protected static JEditTextArea focusedComponent;
protected static Timer caretTimer;
protected TextAreaPainter painter;
protected JPopupMenu popup;
protected EventListenerList listenerList;
protected MutableCaretEvent caretEvent;
protected boolean caretBlinks;
protected boolean caretVisible;
protected boolean blink;
protected boolean editable;
protected int firstLine;
protected int visibleLines;
protected int electricScroll;
protected int horizontalOffset;
protected JScrollBar vertical;
protected JScrollBar horizontal;
protected boolean scrollBarsInitialized;
protected InputHandler inputHandler;
protected SyntaxDocument document;
protected DocumentHandler documentHandler;
protected Segment lineSegment;
protected int selectionStart;
protected int selectionStartLine;
protected int selectionEnd;
protected int selectionEndLine;
protected boolean biasLeft;
protected int bracketPosition;
protected int bracketLine;
protected int magicCaret;
protected boolean overwrite;
protected boolean rectSelect;
protected void fireCaretEvent()
{
Object[] listeners = listenerList.getListenerList();
for(int i = listeners.length - 2; i >= 0; i--)
{
if(listeners[i] == CaretListener.class)
{
((CaretListener)listeners[i+1]).caretUpdate(caretEvent);
}
}
}
protected void updateBracketHighlight(int newCaretPosition)
{
if(newCaretPosition == 0)
{
bracketPosition = bracketLine = -1;
return;
}
try
{
int offset = TextUtilities.findMatchingBracket(
document,newCaretPosition - 1);
if(offset != -1)
{
bracketLine = getLineOfOffset(offset);
bracketPosition = offset - getLineStartOffset(bracketLine);
return;
}
}
catch(BadLocationException bl)
{
bl.printStackTrace();
}
bracketLine = bracketPosition = -1;
}
protected void documentChanged(DocumentEvent evt)
{
DocumentEvent.ElementChange ch = evt.getChange(
document.getDefaultRootElement());
int count;
if(ch == null)
count = 0;
else
count = ch.getChildrenAdded().length -
ch.getChildrenRemoved().length;
int line = getLineOfOffset(evt.getOffset());
if(count == 0)
{
painter.invalidateLine(line);
}
// do magic stuff
else if(line < firstLine)
{
setFirstLine(firstLine + count);
}
// end of magic stuff
else
{
painter.invalidateLineRange(line,firstLine + visibleLines);
updateScrollBars();
}
}
class ScrollLayout implements LayoutManager
{
public void addLayoutComponent(String name, Component comp)
{
if(name.equals(CENTER))
center = comp;
else if(name.equals(RIGHT))
right = comp;
else if(name.equals(BOTTOM))
bottom = comp;
else if(name.equals(LEFT_OF_SCROLLBAR))
leftOfScrollBar.addElement(comp);
}
public void removeLayoutComponent(Component comp)
{
if(center == comp)
center = null;
if(right == comp)
right = null;
if(bottom == comp)
bottom = null;
else
leftOfScrollBar.removeElement(comp);
}
public Dimension preferredLayoutSize(Container parent)
{
Dimension dim = new Dimension();
Insets insets = getInsets();
dim.width = insets.left + insets.right;
dim.height = insets.top + insets.bottom;
Dimension centerPref = center.getPreferredSize();
dim.width += centerPref.width;
dim.height += centerPref.height;
Dimension rightPref = right.getPreferredSize();
dim.width += rightPref.width;
Dimension bottomPref = bottom.getPreferredSize();
dim.height += bottomPref.height;
return dim;
}
public Dimension minimumLayoutSize(Container parent)
{
Dimension dim = new Dimension();
Insets insets = getInsets();
dim.width = insets.left + insets.right;
dim.height = insets.top + insets.bottom;
Dimension centerPref = center.getMinimumSize();
dim.width += centerPref.width;
dim.height += centerPref.height;
Dimension rightPref = right.getMinimumSize();
dim.width += rightPref.width;
Dimension bottomPref = bottom.getMinimumSize();
dim.height += bottomPref.height;
return dim;
}
public void layoutContainer(Container parent)
{
Dimension size = parent.getSize();
Insets insets = parent.getInsets();
int itop = insets.top;
int ileft = insets.left;
int ibottom = insets.bottom;
int iright = insets.right;
int rightWidth = right.getPreferredSize().width;
int bottomHeight = bottom.getPreferredSize().height;
int centerWidth = size.width - rightWidth - ileft - iright;
int centerHeight = size.height - bottomHeight - itop - ibottom;
center.setBounds(
ileft,
itop,
centerWidth,
centerHeight);
right.setBounds(
ileft + centerWidth,
itop,
rightWidth,
centerHeight);
// Lay out all status components, in order
Enumeration status = leftOfScrollBar.elements();
while(status.hasMoreElements())
{
Component comp = (Component)status.nextElement();
Dimension dim = comp.getPreferredSize();
comp.setBounds(ileft,
itop + centerHeight,
dim.width,
bottomHeight);
ileft += dim.width;
}
bottom.setBounds(
ileft,
itop + centerHeight,
size.width - rightWidth - ileft - iright,
bottomHeight);
}
// private members
private Component center;
private Component right;
private Component bottom;
private Vector leftOfScrollBar = new Vector();
}
static class CaretBlinker implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
if(focusedComponent != null
&& focusedComponent.hasFocus())
focusedComponent.blinkCaret();
}
}
class MutableCaretEvent extends CaretEvent
{
MutableCaretEvent()
{
super(JEditTextArea.this);
}
public int getDot()
{
return getCaretPosition();
}
public int getMark()
{
return getMarkPosition();
}
}
class AdjustHandler implements AdjustmentListener
{
public void adjustmentValueChanged(final AdjustmentEvent evt)
{
if(!scrollBarsInitialized)
return;
// If this is not done, mousePressed events accumilate
// and the result is that scrolling doesn't stop after
// the mouse is released
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
if(evt.getAdjustable() == vertical)
setFirstLine(vertical.getValue());
else
setHorizontalOffset(-horizontal.getValue());
}
});
}
}
class ComponentHandler extends ComponentAdapter
{
public void componentResized(ComponentEvent evt)
{
recalculateVisibleLines();
scrollBarsInitialized = true;
}
}
class DocumentHandler implements DocumentListener
{
public void insertUpdate(DocumentEvent evt)
{
documentChanged(evt);
int offset = evt.getOffset();
int length = evt.getLength();
int newStart;
int newEnd;
if(selectionStart > offset || (selectionStart
== selectionEnd && selectionStart == offset))
newStart = selectionStart + length;
else
newStart = selectionStart;
if(selectionEnd >= offset)
newEnd = selectionEnd + length;
else
newEnd = selectionEnd;
select(newStart,newEnd);
}
public void removeUpdate(DocumentEvent evt)
{
documentChanged(evt);
int offset = evt.getOffset();
int length = evt.getLength();
int newStart;
int newEnd;
if(selectionStart > offset)
{
if(selectionStart > offset + length)
newStart = selectionStart - length;
else
newStart = offset;
}
else
newStart = selectionStart;
if(selectionEnd > offset)
{
if(selectionEnd > offset + length)
newEnd = selectionEnd - length;
else
newEnd = offset;
}
else
newEnd = selectionEnd;
select(newStart,newEnd);
}
public void changedUpdate(DocumentEvent evt)
{
}
}
class DragHandler implements MouseMotionListener
{
public void mouseDragged(MouseEvent evt)
{
if(popup != null && popup.isVisible())
return;
setSelectionRectangular((evt.getModifiers()
& InputEvent.CTRL_MASK) != 0);
select(getMarkPosition(),xyToOffset(evt.getX(),evt.getY()));
}
public void mouseMoved(MouseEvent evt) {}
}
class FocusHandler implements FocusListener
{
public void focusGained(FocusEvent evt)
{
setCaretVisible(true);
focusedComponent = JEditTextArea.this;
}
public void focusLost(FocusEvent evt)
{
setCaretVisible(false);
focusedComponent = null;
}
}
class MouseHandler extends MouseAdapter
{
public void mousePressed(MouseEvent evt)
{
requestFocus();
// Focus events not fired sometimes?
setCaretVisible(true);
focusedComponent = JEditTextArea.this;
if((evt.getModifiers() & InputEvent.BUTTON3_MASK) != 0
&& popup != null)
{
popup.show(painter,evt.getX(),evt.getY());
return;
}
int line = yToLine(evt.getY());
int offset = xToOffset(line,evt.getX());
int dot = getLineStartOffset(line) + offset;
switch(evt.getClickCount())
{
case 1:
doSingleClick(evt,line,offset,dot);
break;
case 2:
// It uses the bracket matching stuff, so
// it can throw a BLE
try
{
doDoubleClick(evt,line,offset,dot);
}
catch(BadLocationException bl)
{
bl.printStackTrace();
}
break;
case 3:
doTripleClick(evt,line,offset,dot);
break;
}
}
private void doSingleClick(MouseEvent evt, int line,
int offset, int dot)
{
if((evt.getModifiers() & InputEvent.SHIFT_MASK) != 0)
{
rectSelect = (evt.getModifiers() & InputEvent.CTRL_MASK) != 0;
select(getMarkPosition(),dot);
}
else
setCaretPosition(dot);
}
private void doDoubleClick(MouseEvent evt, int line,
int offset, int dot) throws BadLocationException
{
// Ignore empty lines
if(getLineLength(line) == 0)
return;
try
{
int bracket = TextUtilities.findMatchingBracket(
document,Math.max(0,dot - 1));
if(bracket != -1)
{
int mark = getMarkPosition();
// Hack
if(bracket > mark)
{
bracket++;
mark--;
}
select(mark,bracket);
return;
}
}
catch(BadLocationException bl)
{
bl.printStackTrace();
}
// Ok, it's not a bracket... select the word
String lineText = getLineText(line);
char ch = lineText.charAt(Math.max(0,offset - 1));
String noWordSep = (String)document.getProperty("noWordSep");
if(noWordSep == null)
noWordSep = "";
// If the user clicked on a non-letter char,
// we select the surrounding non-letters
boolean selectNoLetter = (!Character
.isLetterOrDigit(ch)
&& noWordSep.indexOf(ch) == -1);
int wordStart = 0;
for(int i = offset - 1; i >= 0; i--)
{
ch = lineText.charAt(i);
if(selectNoLetter ^ (!Character
.isLetterOrDigit(ch) &&
noWordSep.indexOf(ch) == -1))
{
wordStart = i + 1;
break;
}
}
int wordEnd = lineText.length();
for(int i = offset; i < lineText.length(); i++)
{
ch = lineText.charAt(i);
if(selectNoLetter ^ (!Character
.isLetterOrDigit(ch) &&
noWordSep.indexOf(ch) == -1))
{
wordEnd = i;
break;
}
}
int lineStart = getLineStartOffset(line);
select(lineStart + wordStart,lineStart + wordEnd);
/*
String lineText = getLineText(line);
String noWordSep = (String)document.getProperty("noWordSep");
int wordStart = TextUtilities.findWordStart(lineText,offset,noWordSep);
int wordEnd = TextUtilities.findWordEnd(lineText,offset,noWordSep);
int lineStart = getLineStartOffset(line);
select(lineStart + wordStart,lineStart + wordEnd);
*/
}
private void doTripleClick(MouseEvent evt, int line,
int offset, int dot)
{
select(getLineStartOffset(line),getLineEndOffset(line)-1);
}
}
class CaretUndo extends AbstractUndoableEdit
{
private int start;
private int end;
CaretUndo(int start, int end)
{
this.start = start;
this.end = end;
}
public boolean isSignificant()
{
return false;
}
public String getPresentationName()
{
return "caret move";
}
public void undo() throws CannotUndoException
{
super.undo();
select(start,end);
}
public void redo() throws CannotRedoException
{
super.redo();
select(start,end);
}
public boolean addEdit(UndoableEdit edit)
{
if(edit instanceof CaretUndo)
{
CaretUndo cedit = (CaretUndo)edit;
start = cedit.start;
end = cedit.end;
cedit.die();
return true;
}
else
return false;
}
}
static
{
caretTimer = new Timer(500,new CaretBlinker());
caretTimer.setInitialDelay(500);
caretTimer.start();
}
}
| Java |
package org.jedit.syntax;
/*
* JavaTokenMarker.java - Java token marker
* Copyright (C) 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
import javax.swing.text.Segment;
/**
* Java token marker.
*
* @author Slava Pestov
* @version $Id: JavaTokenMarker.java,v 1.5 1999/12/13 03:40:30 sp Exp $
*/
public class JavaTokenMarker extends CTokenMarker
{
public JavaTokenMarker()
{
super(false,getKeywords());
}
public static KeywordMap getKeywords()
{
if(javaKeywords == null)
{
javaKeywords = new KeywordMap(false);
javaKeywords.add("package",Token.KEYWORD2);
javaKeywords.add("import",Token.KEYWORD2);
javaKeywords.add("byte",Token.KEYWORD3);
javaKeywords.add("char",Token.KEYWORD3);
javaKeywords.add("short",Token.KEYWORD3);
javaKeywords.add("int",Token.KEYWORD3);
javaKeywords.add("long",Token.KEYWORD3);
javaKeywords.add("float",Token.KEYWORD3);
javaKeywords.add("double",Token.KEYWORD3);
javaKeywords.add("boolean",Token.KEYWORD3);
javaKeywords.add("void",Token.KEYWORD3);
javaKeywords.add("class",Token.KEYWORD3);
javaKeywords.add("interface",Token.KEYWORD3);
javaKeywords.add("abstract",Token.KEYWORD1);
javaKeywords.add("final",Token.KEYWORD1);
javaKeywords.add("private",Token.KEYWORD1);
javaKeywords.add("protected",Token.KEYWORD1);
javaKeywords.add("public",Token.KEYWORD1);
javaKeywords.add("static",Token.KEYWORD1);
javaKeywords.add("synchronized",Token.KEYWORD1);
javaKeywords.add("native",Token.KEYWORD1);
javaKeywords.add("volatile",Token.KEYWORD1);
javaKeywords.add("transient",Token.KEYWORD1);
javaKeywords.add("break",Token.KEYWORD1);
javaKeywords.add("case",Token.KEYWORD1);
javaKeywords.add("continue",Token.KEYWORD1);
javaKeywords.add("default",Token.KEYWORD1);
javaKeywords.add("do",Token.KEYWORD1);
javaKeywords.add("else",Token.KEYWORD1);
javaKeywords.add("for",Token.KEYWORD1);
javaKeywords.add("if",Token.KEYWORD1);
javaKeywords.add("instanceof",Token.KEYWORD1);
javaKeywords.add("new",Token.KEYWORD1);
javaKeywords.add("return",Token.KEYWORD1);
javaKeywords.add("switch",Token.KEYWORD1);
javaKeywords.add("while",Token.KEYWORD1);
javaKeywords.add("throw",Token.KEYWORD1);
javaKeywords.add("try",Token.KEYWORD1);
javaKeywords.add("catch",Token.KEYWORD1);
javaKeywords.add("extends",Token.KEYWORD1);
javaKeywords.add("finally",Token.KEYWORD1);
javaKeywords.add("implements",Token.KEYWORD1);
javaKeywords.add("throws",Token.KEYWORD1);
javaKeywords.add("this",Token.LITERAL2);
javaKeywords.add("null",Token.LITERAL2);
javaKeywords.add("super",Token.LITERAL2);
javaKeywords.add("true",Token.LITERAL2);
javaKeywords.add("false",Token.LITERAL2);
}
return javaKeywords;
}
// private members
private static KeywordMap javaKeywords;
}
| Java |
package org.jedit.syntax;
/*
* CTokenMarker.java - C token marker
* Copyright (C) 1998, 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
import javax.swing.text.Segment;
/**
* C token marker.
*
* @author Slava Pestov
* @version $Id: CTokenMarker.java,v 1.34 1999/12/13 03:40:29 sp Exp $
*/
public class CTokenMarker extends TokenMarker
{
public CTokenMarker()
{
this(true,getKeywords());
}
public CTokenMarker(boolean cpp, KeywordMap keywords)
{
this.cpp = cpp;
this.keywords = keywords;
}
public byte markTokensImpl(byte token, Segment line, int lineIndex)
{
char[] array = line.array;
int offset = line.offset;
lastOffset = offset;
lastKeyword = offset;
int length = line.count + offset;
boolean backslash = false;
loop: for(int i = offset; i < length; i++)
{
int i1 = (i+1);
char c = array[i];
if(c == '\\')
{
backslash = !backslash;
continue;
}
switch(token)
{
case Token.NULL:
switch(c)
{
case '#':
if(backslash)
backslash = false;
else if(cpp)
{
if(doKeyword(line,i,c))
break;
addToken(i - lastOffset,token);
addToken(length - i,Token.KEYWORD2);
lastOffset = lastKeyword = length;
break loop;
}
break;
case '"':
doKeyword(line,i,c);
if(backslash)
backslash = false;
else
{
addToken(i - lastOffset,token);
token = Token.LITERAL1;
lastOffset = lastKeyword = i;
}
break;
case '\'':
doKeyword(line,i,c);
if(backslash)
backslash = false;
else
{
addToken(i - lastOffset,token);
token = Token.LITERAL2;
lastOffset = lastKeyword = i;
}
break;
case ':':
if(lastKeyword == offset)
{
if(doKeyword(line,i,c))
break;
backslash = false;
addToken(i1 - lastOffset,Token.LABEL);
lastOffset = lastKeyword = i1;
}
else if(doKeyword(line,i,c))
break;
break;
case '/':
backslash = false;
doKeyword(line,i,c);
if(length - i > 1)
{
switch(array[i1])
{
case '*':
addToken(i - lastOffset,token);
lastOffset = lastKeyword = i;
if(length - i > 2 && array[i+2] == '*')
token = Token.COMMENT2;
else
token = Token.COMMENT1;
break;
case '/':
addToken(i - lastOffset,token);
addToken(length - i,Token.COMMENT1);
lastOffset = lastKeyword = length;
break loop;
}
}
break;
default:
backslash = false;
if(!Character.isLetterOrDigit(c)
&& c != '_')
doKeyword(line,i,c);
break;
}
break;
case Token.COMMENT1:
case Token.COMMENT2:
backslash = false;
if(c == '*' && length - i > 1)
{
if(array[i1] == '/')
{
i++;
addToken((i+1) - lastOffset,token);
token = Token.NULL;
lastOffset = lastKeyword = i+1;
}
}
break;
case Token.LITERAL1:
if(backslash)
backslash = false;
else if(c == '"')
{
addToken(i1 - lastOffset,token);
token = Token.NULL;
lastOffset = lastKeyword = i1;
}
break;
case Token.LITERAL2:
if(backslash)
backslash = false;
else if(c == '\'')
{
addToken(i1 - lastOffset,Token.LITERAL1);
token = Token.NULL;
lastOffset = lastKeyword = i1;
}
break;
default:
throw new InternalError("Invalid state: "
+ token);
}
}
if(token == Token.NULL)
doKeyword(line,length,'\0');
switch(token)
{
case Token.LITERAL1:
case Token.LITERAL2:
addToken(length - lastOffset,Token.INVALID);
token = Token.NULL;
break;
case Token.KEYWORD2:
addToken(length - lastOffset,token);
if(!backslash)
token = Token.NULL;
default:
addToken(length - lastOffset,token);
break;
}
return token;
}
public static KeywordMap getKeywords()
{
if(cKeywords == null)
{
cKeywords = new KeywordMap(false);
cKeywords.add("char",Token.KEYWORD3);
cKeywords.add("double",Token.KEYWORD3);
cKeywords.add("enum",Token.KEYWORD3);
cKeywords.add("float",Token.KEYWORD3);
cKeywords.add("int",Token.KEYWORD3);
cKeywords.add("long",Token.KEYWORD3);
cKeywords.add("short",Token.KEYWORD3);
cKeywords.add("signed",Token.KEYWORD3);
cKeywords.add("struct",Token.KEYWORD3);
cKeywords.add("typedef",Token.KEYWORD3);
cKeywords.add("union",Token.KEYWORD3);
cKeywords.add("unsigned",Token.KEYWORD3);
cKeywords.add("void",Token.KEYWORD3);
cKeywords.add("auto",Token.KEYWORD1);
cKeywords.add("const",Token.KEYWORD1);
cKeywords.add("extern",Token.KEYWORD1);
cKeywords.add("register",Token.KEYWORD1);
cKeywords.add("static",Token.KEYWORD1);
cKeywords.add("volatile",Token.KEYWORD1);
cKeywords.add("break",Token.KEYWORD1);
cKeywords.add("case",Token.KEYWORD1);
cKeywords.add("continue",Token.KEYWORD1);
cKeywords.add("default",Token.KEYWORD1);
cKeywords.add("do",Token.KEYWORD1);
cKeywords.add("else",Token.KEYWORD1);
cKeywords.add("for",Token.KEYWORD1);
cKeywords.add("goto",Token.KEYWORD1);
cKeywords.add("if",Token.KEYWORD1);
cKeywords.add("return",Token.KEYWORD1);
cKeywords.add("sizeof",Token.KEYWORD1);
cKeywords.add("switch",Token.KEYWORD1);
cKeywords.add("while",Token.KEYWORD1);
cKeywords.add("asm",Token.KEYWORD2);
cKeywords.add("asmlinkage",Token.KEYWORD2);
cKeywords.add("far",Token.KEYWORD2);
cKeywords.add("huge",Token.KEYWORD2);
cKeywords.add("inline",Token.KEYWORD2);
cKeywords.add("near",Token.KEYWORD2);
cKeywords.add("pascal",Token.KEYWORD2);
cKeywords.add("true",Token.LITERAL2);
cKeywords.add("false",Token.LITERAL2);
cKeywords.add("NULL",Token.LITERAL2);
}
return cKeywords;
}
// private members
private static KeywordMap cKeywords;
private boolean cpp;
private KeywordMap keywords;
private int lastOffset;
private int lastKeyword;
private boolean doKeyword(Segment line, int i, char c)
{
int i1 = i+1;
int len = i - lastKeyword;
byte id = keywords.lookup(line,lastKeyword,len);
if(id != Token.NULL)
{
if(lastKeyword != lastOffset)
addToken(lastKeyword - lastOffset,Token.NULL);
addToken(len,id);
lastOffset = i;
}
lastKeyword = i1;
return false;
}
}
| Java |
package org.jedit.syntax;
/*
* PropsTokenMarker.java - Java props/DOS INI token marker
* Copyright (C) 1998, 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
import javax.swing.text.Segment;
/**
* Java properties/DOS INI token marker.
*
* @author Slava Pestov
* @version $Id: PropsTokenMarker.java,v 1.9 1999/12/13 03:40:30 sp Exp $
*/
public class PropsTokenMarker extends TokenMarker
{
public static final byte VALUE = Token.INTERNAL_FIRST;
public byte markTokensImpl(byte token, Segment line, int lineIndex)
{
char[] array = line.array;
int offset = line.offset;
int lastOffset = offset;
int length = line.count + offset;
loop: for(int i = offset; i < length; i++)
{
int i1 = (i+1);
switch(token)
{
case Token.NULL:
switch(array[i])
{
case '#': case ';':
if(i == offset)
{
addToken(line.count,Token.COMMENT1);
lastOffset = length;
break loop;
}
break;
case '[':
if(i == offset)
{
addToken(i - lastOffset,token);
token = Token.KEYWORD2;
lastOffset = i;
}
break;
case '=':
addToken(i - lastOffset,Token.KEYWORD1);
token = VALUE;
lastOffset = i;
break;
}
break;
case Token.KEYWORD2:
if(array[i] == ']')
{
addToken(i1 - lastOffset,token);
token = Token.NULL;
lastOffset = i1;
}
break;
case VALUE:
break;
default:
throw new InternalError("Invalid state: "
+ token);
}
}
if(lastOffset != length)
addToken(length - lastOffset,Token.NULL);
return Token.NULL;
}
public boolean supportsMultilineTokens()
{
return false;
}
}
| Java |
package org.jedit.syntax;
/*
* XMLTokenMarker.java - XML token marker
* Copyright (C) 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
/**
* XML token marker.
*
* @author Slava Pestov
* @version $Id: XMLTokenMarker.java,v 1.2 1999/12/13 03:40:30 sp Exp $
*/
public class XMLTokenMarker extends HTMLTokenMarker
{
public XMLTokenMarker()
{
super(false);
}
}
| Java |
package org.jedit.syntax;
/*
* HTMLTokenMarker.java - HTML token marker
* Copyright (C) 1998, 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
import javax.swing.text.Segment;
/**
* HTML token marker.
*
* @author Slava Pestov
* @version $Id: HTMLTokenMarker.java,v 1.34 1999/12/13 03:40:29 sp Exp $
*/
public class HTMLTokenMarker extends TokenMarker
{
public static final byte JAVASCRIPT = Token.INTERNAL_FIRST;
public HTMLTokenMarker()
{
this(true);
}
public HTMLTokenMarker(boolean js)
{
this.js = js;
keywords = JavaScriptTokenMarker.getKeywords();
}
public byte markTokensImpl(byte token, Segment line, int lineIndex)
{
char[] array = line.array;
int offset = line.offset;
lastOffset = offset;
lastKeyword = offset;
int length = line.count + offset;
boolean backslash = false;
loop: for(int i = offset; i < length; i++)
{
int i1 = (i+1);
char c = array[i];
if(c == '\\')
{
backslash = !backslash;
continue;
}
switch(token)
{
case Token.NULL: // HTML text
backslash = false;
switch(c)
{
case '<':
addToken(i - lastOffset,token);
lastOffset = lastKeyword = i;
if(SyntaxUtilities.regionMatches(false,
line,i1,"!--"))
{
i += 3;
token = Token.COMMENT1;
}
else if(js && SyntaxUtilities.regionMatches(
true,line,i1,"script>"))
{
addToken(8,Token.KEYWORD1);
lastOffset = lastKeyword = (i += 8);
token = JAVASCRIPT;
}
else
{
token = Token.KEYWORD1;
}
break;
case '&':
addToken(i - lastOffset,token);
lastOffset = lastKeyword = i;
token = Token.KEYWORD2;
break;
}
break;
case Token.KEYWORD1: // Inside a tag
backslash = false;
if(c == '>')
{
addToken(i1 - lastOffset,token);
lastOffset = lastKeyword = i1;
token = Token.NULL;
}
break;
case Token.KEYWORD2: // Inside an entity
backslash = false;
if(c == ';')
{
addToken(i1 - lastOffset,token);
lastOffset = lastKeyword = i1;
token = Token.NULL;
break;
}
break;
case Token.COMMENT1: // Inside a comment
backslash = false;
if(SyntaxUtilities.regionMatches(false,line,i,"-->"))
{
addToken((i + 3) - lastOffset,token);
lastOffset = lastKeyword = i + 3;
token = Token.NULL;
}
break;
case JAVASCRIPT: // Inside a JavaScript
switch(c)
{
case '<':
backslash = false;
doKeyword(line,i,c);
if(SyntaxUtilities.regionMatches(true,
line,i1,"/script>"))
{
addToken(i - lastOffset,
Token.NULL);
addToken(9,Token.KEYWORD1);
lastOffset = lastKeyword = (i += 9);
token = Token.NULL;
}
break;
case '"':
if(backslash)
backslash = false;
else
{
doKeyword(line,i,c);
addToken(i - lastOffset,Token.NULL);
lastOffset = lastKeyword = i;
token = Token.LITERAL1;
}
break;
case '\'':
if(backslash)
backslash = false;
else
{
doKeyword(line,i,c);
addToken(i - lastOffset,Token.NULL);
lastOffset = lastKeyword = i;
token = Token.LITERAL2;
}
break;
case '/':
backslash = false;
doKeyword(line,i,c);
if(length - i > 1)
{
addToken(i - lastOffset,Token.NULL);
lastOffset = lastKeyword = i;
if(array[i1] == '/')
{
addToken(length - i,Token.COMMENT2);
lastOffset = lastKeyword = length;
break loop;
}
else if(array[i1] == '*')
{
token = Token.COMMENT2;
}
}
break;
default: backslash = false;
if(!Character.isLetterOrDigit(c)
&& c != '_')
doKeyword(line,i,c);
break;
}
break;
case Token.LITERAL1: // JavaScript "..."
if(backslash)
backslash = false;
else if(c == '"')
{
addToken(i1 - lastOffset,Token.LITERAL1);
lastOffset = lastKeyword = i1;
token = JAVASCRIPT;
}
break;
case Token.LITERAL2: // JavaScript '...'
if(backslash)
backslash = false;
else if(c == '\'')
{
addToken(i1 - lastOffset,Token.LITERAL1);
lastOffset = lastKeyword = i1;
token = JAVASCRIPT;
}
break;
case Token.COMMENT2: // Inside a JavaScript comment
backslash = false;
if(c == '*' && length - i > 1 && array[i1] == '/')
{
addToken((i+=2) - lastOffset,Token.COMMENT2);
lastOffset = lastKeyword = i;
token = JAVASCRIPT;
}
break;
default:
throw new InternalError("Invalid state: "
+ token);
}
}
switch(token)
{
case Token.LITERAL1:
case Token.LITERAL2:
addToken(length - lastOffset,Token.INVALID);
token = JAVASCRIPT;
break;
case Token.KEYWORD2:
addToken(length - lastOffset,Token.INVALID);
token = Token.NULL;
break;
case JAVASCRIPT:
doKeyword(line,length,'\0');
addToken(length - lastOffset,Token.NULL);
break;
default:
addToken(length - lastOffset,token);
break;
}
return token;
}
// private members
private KeywordMap keywords;
private boolean js;
private int lastOffset;
private int lastKeyword;
private boolean doKeyword(Segment line, int i, char c)
{
int i1 = i+1;
int len = i - lastKeyword;
byte id = keywords.lookup(line,lastKeyword,len);
if(id != Token.NULL)
{
if(lastKeyword != lastOffset)
addToken(lastKeyword - lastOffset,Token.NULL);
addToken(len,id);
lastOffset = i;
}
lastKeyword = i1;
return false;
}
}
| Java |
package org.jedit.syntax;
/*
* TextUtilities.java - Utility functions used by the text area classes
* Copyright (C) 1999 Slava Pestov
*
* You may use and modify this package for any purpose. Redistribution is
* permitted, in both source and binary form, provided that this notice
* remains intact in all source distributions of this package.
*/
import javax.swing.text.*;
/**
* Class with several utility functions used by the text area component.
* @author Slava Pestov
* @version $Id: TextUtilities.java,v 1.4 1999/12/13 03:40:30 sp Exp $
*/
public class TextUtilities
{
/**
* Returns the offset of the bracket matching the one at the
* specified offset of the document, or -1 if the bracket is
* unmatched (or if the character is not a bracket).
* @param doc The document
* @param offset The offset
* @exception BadLocationException If an out-of-bounds access
* was attempted on the document text
*/
public static int findMatchingBracket(Document doc, int offset)
throws BadLocationException
{
if(doc.getLength() == 0)
return -1;
char c = doc.getText(offset,1).charAt(0);
char cprime; // c` - corresponding character
boolean direction; // true = back, false = forward
switch(c)
{
case '(': cprime = ')'; direction = false; break;
case ')': cprime = '('; direction = true; break;
case '[': cprime = ']'; direction = false; break;
case ']': cprime = '['; direction = true; break;
case '{': cprime = '}'; direction = false; break;
case '}': cprime = '{'; direction = true; break;
default: return -1;
}
int count;
// How to merge these two cases is left as an exercise
// for the reader.
// Go back or forward
if(direction)
{
// Count is 1 initially because we have already
// `found' one closing bracket
count = 1;
// Get text[0,offset-1];
String text = doc.getText(0,offset);
// Scan backwards
for(int i = offset - 1; i >= 0; i--)
{
// If text[i] == c, we have found another
// closing bracket, therefore we will need
// two opening brackets to complete the
// match.
char x = text.charAt(i);
if(x == c)
count++;
// If text[i] == cprime, we have found a
// opening bracket, so we return i if
// --count == 0
else if(x == cprime)
{
if(--count == 0)
return i;
}
}
}
else
{
// Count is 1 initially because we have already
// `found' one opening bracket
count = 1;
// So we don't have to + 1 in every loop
offset++;
// Number of characters to check
int len = doc.getLength() - offset;
// Get text[offset+1,len];
String text = doc.getText(offset,len);
// Scan forwards
for(int i = 0; i < len; i++)
{
// If text[i] == c, we have found another
// opening bracket, therefore we will need
// two closing brackets to complete the
// match.
char x = text.charAt(i);
if(x == c)
count++;
// If text[i] == cprime, we have found an
// closing bracket, so we return i if
// --count == 0
else if(x == cprime)
{
if(--count == 0)
return i + offset;
}
}
}
// Nothing found
return -1;
}
/**
* Locates the start of the word at the specified position.
* @param line The text
* @param pos The position
*/
public static int findWordStart(String line, int pos, String noWordSep)
{
char ch = line.charAt(pos - 1);
if(noWordSep == null)
noWordSep = "";
boolean selectNoLetter = (!Character.isLetterOrDigit(ch)
&& noWordSep.indexOf(ch) == -1);
int wordStart = 0;
for(int i = pos - 1; i >= 0; i--)
{
ch = line.charAt(i);
if(selectNoLetter ^ (!Character.isLetterOrDigit(ch) &&
noWordSep.indexOf(ch) == -1))
{
wordStart = i + 1;
break;
}
}
return wordStart;
}
/**
* Locates the end of the word at the specified position.
* @param line The text
* @param pos The position
*/
public static int findWordEnd(String line, int pos, String noWordSep)
{
char ch = line.charAt(pos);
if(noWordSep == null)
noWordSep = "";
boolean selectNoLetter = (!Character.isLetterOrDigit(ch)
&& noWordSep.indexOf(ch) == -1);
int wordEnd = line.length();
for(int i = pos; i < line.length(); i++)
{
ch = line.charAt(i);
if(selectNoLetter ^ (!Character.isLetterOrDigit(ch) &&
noWordSep.indexOf(ch) == -1))
{
wordEnd = i;
break;
}
}
return wordEnd;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.