SWT StyledText getCaretOffset giving wrong line number - java

I'm trying to make the bullet of active line have a highlighted background. I'm using
int activeLine = styledText.getLineAtOffset(styledText.getCaretOffset());
To get the like that is currently active. This seems to work except when I hit enter and get a new line.
getCaretOffset returns 35 and getCharCount returns 36.
However, if I click on the last line (for now I call redraw() on clicks) the line highlights correctly and getCaretOffset returns 36.
Here is the relevant code
public void lineGetStyle(LineStyleEvent event) {
// Set the line number
int activeLine = styledText.getLineAtOffset(styledText.getCaretOffset());
System.out.println("Offset " + styledText.getCaretOffset() + " max " + styledText.getCharCount());
int currentLine = styledText.getLineAtOffset(event.lineOffset);
event.bulletIndex = currentLine;
// Set the style, 12 pixles wide for each digit
StyleRange style = new StyleRange();
style.metrics = new GlyphMetrics(0, 0, 36);
if (activeLine == currentLine) {
style.background = highlightedLine;
if (curActiveLine != activeLine){
System.out.println("ActiveLine " + activeLine + " old " + curActiveLine);
int redrawLine = curActiveLine;
curActiveLine = activeLine;
styledText.redraw(0, styledText.getLinePixel(redrawLine), 36, styledText.getLineHeight(),true);
}
}
style.foreground = mainBackground;
// Create and set the bullet
event.bullet = new Bullet(ST.BULLET_NUMBER, style);
event.styles = matchKeywords(event);
}

I just realized that you can set a CaretListener to get notifications for each move of the caret. By issuing the redraws from that it works great now.

Related

Checking if item lore contains contains string (loren.contains("§eSigned from "))

I only want to check for:
if (lore.contains("§eSigned of ")) {
but it doesn't get that it does contain "§eSigned of "
I wrote a Minecraft Command /sign you can add a lore to an item ("Signed of playerrank | playername").
Then i wanted to add an /unsign command to remove this lore.
ItemStack is = p.getItemInHand();
ItemMeta im = is.getItemMeta();
List<String> lore = im.hasLore() ? im.getLore() : new ArrayList<String>();
if (lore.contains("§eSigned of " + getChatName(p))) { // this line is important!
for (int i = 0; i < 3; i++) {
int size = lore.size();
lore.remove(size - 1);
}
im.setLore(lore);
is.setItemMeta(im);
p.setItemInHand(is);
sendMessage(p, "§aThis item is no longer signed");
} else {
sendMessage(p, "§aThis item is not signed!");
}
return CommandResult.None;
Everything works fine until you e.g. change your name. than you can't remove the sign because getChatName(p) has changed.
To fix this i only want to check
if (lore.contains("§eSigned of ")) {
but than it doesn't get it and returns false. (it says lore does not contain "§eSigned of ")
I tried a lot but it only works with the string "§eSigned of " and getChatName(p).
As the documentation "contains" searches for the specific string so it should work as I thought right?
Add:
getChatName(p) returns the rank of the player and the playername like: "Member | domi"
sendMessage(p, "") sends a simple message in the Minecraft chat
The problem you run into is that contains(String) looks for a matching string. What you search for is a check if any string in the list starts with "§eSigned of ".
I would suggest adding a function isSignedItem like this:
private boolean isSignedItem(List<String> lore) {
for (String st : lore)
if (st.startsWith("§eSigned of "))
return true;
return false;
}
and then to use this function to check if the item is signed or not:
[...]
List<String> lore = im.hasLore() ? im.getLore() : new ArrayList<String>();
if (isSignedItem(lore)) { // this line is important!
for (int i = 0; i < 3; i++) {
int size = lore.size();
lore.remove(size - 1);
}
[...]

Vaadin TextField action at every key pressed

In Vaadin 7 there are no KeyListener in TextField only on EnterKey press.
I'm looking for an add-on which contains a SuperImmediateTextField but compatible with Vaadin 7.
I use Vaadin version 7.1.8
You can use TextChangeListener.
For example:
// Text field with maximum length
final TextField tf = new TextField("My Eventful Field");
tf.setValue("Initial content");
tf.setMaxLength(20);
// Counter for input length
final Label counter = new Label();
counter.setValue(tf.getValue().length() +
" of " + tf.getMaxLength());
// Display the current length interactively in the counter
tf.addTextChangeListener(new TextChangeListener() {
public void textChange(TextChangeEvent event) {
int len = event.getText().length();
counter.setValue(len + " of " + tf.getMaxLength());
}
});
// The lazy mode is actually the default
tf.setTextChangeEventMode(TextChangeEventMode.LAZY);

read IRC data correctly in Processing

I am trying to read IRC and pull data from individual IRC messages in Processing. You can see the code (also with twitter library, ignore that) and I need some pointers on how I can pull the data out in the format of Nick:Message so it can be displayed in a visualization.
//Twitter
import twitter4j.conf.*;
import twitter4j.*;
import twitter4j.auth.*;
import twitter4j.api.*;
import java.util.*;
// Import the net libraries
import processing.net.*;
// Declare a client
Client client;
Twitter twitter;
String searchString = "god";
List<Status> tweets;
String server = "irc.twitch.tv";
String nick = "NugShow";
//String user = "simple_bot";
int port = 6667;
String channel = "#nugshow";
String password = "xx";
String in = "butt";
String checkFor;
//bools
Boolean isLive = false;
int privMsgIndex;
int atIndex;
String playerSubstring;
// The channel which the bot will joString channel = "#irchacks";
int currentTweet;
void setup()
{
size(800,600);
frameRate(60);
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("xx");
cb.setOAuthConsumerSecret("xx");
cb.setOAuthAccessToken("xx");
cb.setOAuthAccessTokenSecret("xx");
TwitterFactory tf = new TwitterFactory(cb.build());
twitter = tf.getInstance();
getNewTweets();
currentTweet = 0;
thread("refreshTweets");
thread("loopChat");
connectToServer();
//IRC
}
void draw()
{
if (client.available() > 0) {
String in = client.readString();
println(in);
}
if (isLive == false){
if (client.available() > 0) {
}
} else {
}
/*
fill(0, 40);
rect(0, 0, width, height);
currentTweet = currentTweet + 1;
if (currentTweet >= tweets.size())
{
currentTweet = 0;
}
Status status = tweets.get(currentTweet);
fill(200);
text(status.getText(), random(width), random(height), 300, 200);
delay(100);
*/
}
void joinChannel() {
String in = client.readString();
client.write( "JOIN " + channel + "\n\r" );
client.clear();
in = client.readString();
println(in);
if (in != null){
//println("Recieved data");
println(in);
//String inString = myClient.readStringUntil("");
isLive = true;
println(isLive);
}
}
void connectToServer()
{
client = new Client(this, server , 6667);
client.write( "PASS " + password + "\n\r" );
println(password + " sent!");
client.write( "NICK " + nick + "\n\r" );
println(nick + " sent!");
joinChannel();
}
void getNewTweets()
{
try
{
Query query = new Query(searchString);
QueryResult result = twitter.search(query);
tweets = result.getTweets();
}
catch (TwitterException te)
{
System.out.println("Failed to search tweets: " + te.getMessage());
System.exit(-1);
}
}
void refreshTweets()
{
while (true)
{
getNewTweets();
println("Updated Tweets");
delay(30000);
}
}
void loopChat()
{
while (true)
{
if (privMsgIndex != 0){
println(privMsgIndex);
//privMsgIndex = privMsgIndex - 15;
atIndex = in.indexOf("#");
println(atIndex);
//atIndex = atIndex + 1;
playerSubstring = in.substring(atIndex, privMsgIndex);
println(playerSubstring);
} else {
println("looped");
}
delay(300);
client.clear();
in = null;
}
}
void keyPressed()
{
}
void tweet()
{
try
{
Status status = twitter.updateStatus("This is a tweet sent from Processing!");
System.out.println("Status updated to [" + status.getText() + "].");
}
catch (TwitterException te)
{
System.out.println("Error: "+ te.getMessage());
}
}
The chat commands look like this: :nugshow!nugshow#nugshow.testserver.local PRIVMSG #nugshow :dddd where nugshow is the username, #nugshow is the channel, and dddd is the message. I need to get it into the format of nugshow: dddd.
there is a lot of header information that I'm not sure how to strip out of client.recieved buffer as well, it looks like this:
:testserver.local 001 nugshow :Welcome, GLHF!
:testserver.local 002 nugshow :Your host is testserver.local
:testserver.local 003 nugshow :This server is rather new
:testserver.local 004 nugshow :-
:testserver.local 375 nugshow :-
:testserver.local 372 nugshow :You are in a maze of twisty passages, all alike.
:testserver.local 376 nugshow :>
:nugshow!nugshow#nugshow.testserver.local JOIN #nugshow
:nugshow.testserver.local 353 nugshow = #nugshow :nugshow
:nugshow.testserver.local 366 nugshow #nugshow :End of /NAMES list
:jtv!jtv#jtv.testserver.local PRIVMSG nugshow :HISTORYEND nugshow
I would not recommend regex here. At least not if you want to be able to catch all types of IRC messages. The key is to look at the message code to know what you can actually get out of the message. As I'm also writing an IRC-client (just for giggles) I have some notes for you.
Be sure to answer any PINGs that the server sends you so you don't get kicked off. As the PING is sent with an identifier, you need to catch that and send it back. A simple way to do this is to check the last line that was sent from the server and substring it.
String line = inputStream.readLine();
if(line.substring(0,4).equals("PING")){
send("PONG " + line.substring(5)); // Assume you have some send-function.
}
This will make sure you don't get kicked off and can proceed to actually stay on a server.
As I mentioned, I do not recommend using regex for this as it would become a RegEx-of-doom. So, what I have done is to just split the line you get and put all the results in a String array.
String[] arr = line.split(" ");
As you know by your own message line you have posted, the IRC protocol separates things with spaces. So splitting at spaces in not all that shabby (we'll get how to deal with actual text in a bit).
The basic structure that is always the same (as far as I can tell) in messages is PREFIX COMMAND PARAM PARAM/TRAILING. So what does this mean? The PREFIX is where the message was sent from. Example ":user!user#host.com". The COMMAND is what the line actually is. You are looking for PRIVMSG here, but there are many, many, others that you might want to take care of. Like JOIN, PART, QUIT, 332 (current topic), 353 (nicks in channel, 404 (unable to send to channel), etc. etc. The PARAM and PARAM/TRAILING will all depend on the COMMAND.
So, what do we gain from splitting at spaces? This:
arr[0] = :user!user#host.com
arr[1] = COMMAND
arr[2] = PARAM
arr[3 onwards] = rest
We can now easily manage every command in it's own needed way.
Without further delay, lets get to your actual question, the PRIVMSG.
I will use this string: ":Chewtoy!chewtoy#stackoverflow.com PRIVMSG #stackoverflow :Ty: I saw your question and thought I should give you an answer."
After doing a split at the spaces, we get the array
arr[0] = :Chewtoy!chewtoy#stackoverflow.com
arr[1] = PRIVMSG
arr[2] = #stackoverflow
arr[3] = :Ty:
arr[4] = I
arr[5] = saw
...
As you can see, everything from 3 and onwards is the message you want. 0-2 is stuff that you need to be able to know who sent what where. My code for getting all this looks like this:
String[] arr = receivedLine.split(" ");
if(arr[1].equals("PRIVMSG")){
String[] usr = arr[0].split(!"); // Get the user, which is in usr[0]. Host in usr[1]
StringBuilder msg = new StringBuilder();
for(int i=3; i<arr.length; i++){ // We know the message starts at arr[3], so start counting from that.
msg.append(arr[i] + " ");
}
String chan = "";
if(arr[2].substring(0,1).equals("#")){ // We need to differentiate between sending to channel and sending a PM. The only difference in this is where the text is sent.
chan = arr[2];
} else{
chan = usr[0].substring(1); // substring(1) because we want Chewtoy, not :Chewtoy
}
// The result here will be:
// <#stackoverflow> Chewtoy: Ty: I saw your question and thought I should give you an answer.
sendItAllToWhereYouWantIt("<" + chan +"> " + usr[0].substring(1) + ": " + msg.substring(1));
}
Hope that helps.

Loop through a ThreadGroup - please help me debugging

I try hard to find the problem in this Java code, but I can't find it - can you help me?
I hope the code I provide is enough, but I will post more if necessary.
Further I apologize, I didn't make a minimal example.
game.getGroupPlayers().list();
MoverThread[] playerThread = game.getPlayers();
System.out.println(playerThread.length);
for (int i = 0; i < playerThread.length; i++) {
try {
System.out.println(i + " -> " +playerThread[i].toString());
returnString += playerThread[i].toString() + "\n";
} catch(NullPointerException e) {
System.out.println("Problem at i = " + i);
e.printStackTrace();
}
game.getGroupPlayers().list();
}
sometimes gives me the following output:
java.lang.ThreadGroup[name=Players,maxpri=10]
Player-0: 113
Player-1: 277
Player-2: 0
3
0 -> Player-0: 113
1 -> Player-1: 277
Problem at i = 2
java.lang.NullPointerException
at Referee.goalFound(Referee.java:70)
at DebugTestReferee.goalFound(DebugTestReferee.java:42)
at Player.checkGoal(Player.java:61)
at Player.run(Player.java:94)
at java.lang.Thread.run(Thread.java:636)
java.lang.ThreadGroup[name=Players,maxpri=10]
Player-0: 113
Player-1: 277
Player-2: 0
[edit]
here's the source of getPlayers()
/*
* post returns the games players as an array
*/
public MoverThread[] getPlayers() {
synchronized(movers) {
MoverThread[] playerList = new MoverThread[players.activeCount()];
players.enumerate(playerList);
return playerList;
}
}
[edit]
here's how players is generated
private ThreadGroup movers;
private ThreadGroup players;
private ThreadGroup ghosts;
private Observer observer;
/*
* constructor
*/
public Game(Maze maze, Referee referee) {
this.maze = maze;
this.referee = referee;
threadList = new ArrayList<MoverThread>();
movers = new ThreadGroup("Movers");
players = new ThreadGroup(movers, "Players");
ghosts = new ThreadGroup(movers, "Ghosts");
observer = null;
}
[edit]
Here's how I call the method that generates the problem:
/*
* post checks if the players thread was interrupted - if not if hostfield pretends to be a goal the game gets stopped and referee is called to perform "goal-found-actions"
*/
private void checkGoal() {
if (!getThread().isInterrupted()) {
synchronized(getGame().getMovers()) {
if (!getThread().isInterrupted()) {
if (getHostField().isGoal()) {
Field goal = getHostField();
getGame().getReferee().goalFound(this, goal);
getGame().setGameOver();
}
}
}
}
}
and here's the whole goalFound()
/*
* post action to be performed if a player finds a goal
* print some information
*/
public void goalFound(Player player, Field at) {
//FIXME get the Bug!!!
String returnString = "Game over - player " + player.getName() + " found a goal on (" + at.getPos()[0] + ", " + at.getPos()[1] + ")!\n";
game.getGroupPlayers().list();
MoverThread[] playerThread = game.getPlayers();
System.out.println(playerThread.length);
for (int i = 0; i < playerThread.length; i++) {
try {
System.out.println(i + " -> " +playerThread[i].toString());
returnString += playerThread[i].toString() + "\n";
} catch(NullPointerException e) {
System.out.println("Problem at i = " + i);
e.printStackTrace();
}
}
game.getGroupPlayers().list();
returnString += game.mazeString();
System.out.println(returnString);
}
There isn't a nice way of enumerating the Threads of a ThreadGroup. It's a well known terrible design.
Between calling ThreadGroup.activeCount and ThreadGroup.enumerate(Thread[]), threads may have started or died. The best you can do is add a fudge factor the activeCount when allocating the array. If the returned value matches the array length, then you may have missed some and should repeat with a larger array size (probably a factor larger, rather than just adding a constant). When successful, you will need to trim your array appropriately (or treat it as such).
game.getPlayers(); is returning MoverThread[] with length 3, but the third one is null.
I found a solution - or maybe more a workaround...
Beside using ThreadGroups I store my threads in an ArrayList aswell (maybe a Vector would be even better, but I'm fine with the ArrayList).
I don't know why, but when I try to call all Threads in the ThreadGroup it often happens that some Threads are left out. However, with the ArrayList it works fine.
Would be interesting why ThreadGroups don't work as supposed and what we need them for in this case.

Can anyone help with a java problem regarding record stores?

I have this code. And basically this returns the correct data without the town qualities. When I add the town qualities the method returns nothing, not even the orginal data that it has been and I dont know why. Can anyone see a problem?
protected void listRecords() {
mListForm.deleteAll(); // clear the form
try {
RecordStore rs = RecordStore.openRecordStore("Details", true);
RecordEnumeration re = rs.enumerateRecords(null, new RecordSorter(), false);
while (re.hasNextElement()) {
byte [] recordBuffer = re.nextRecord();
String record = new String(recordBuffer);
// extract the name and the age from the record
int endOfName = record.indexOf(";");
int endOfDesc = record.indexOf(";" , endOfName + 1);
int endOfTown = record.indexOf (";", endOfDesc + 1);
String name = record.substring(0, endOfName);
String desc = record.substring(endOfName + 1, endOfDesc);
String town = record.substring(endOfDesc +1, endOfTown);
mListForm.append(name + " aged: "+ desc + " " + town);
}
rs.closeRecordStore();
}
catch(Exception e){
mAlertConfirmDetailsSaved.setString("Couldn't read details");
System.err.println("Error accessing database");
}
mDisplay.setCurrent(mListForm);
}
Have you tried running it in the debugger? Is the exception happening? Are the three semicolons present in the record? Is there a limit on mDisplay's string size? When setCurrent is called, is the mListForm correct?
In other words, what have you done so far and where is it definitely right, and where does it become wrong?

Categories

Resources