[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [Newsgroup Home]
[news.eclipse.platform.swt] Why would introducing Thread.sleep(5000) prevent the Shell from being displayed?

Hi All,

This is my 2nd little attempts to use SWT and it's working out OK except for the following issue. Apologies in advance for a long message (but I moved all the code samples to the bottom)...

I am trying to write a screen-saver that would double as an RSS reader.

I create a shell, populate it with the StyledText widget (which will contain the text) and get the news stories from Reuters RSS URL (using Rome library).

Then I do a little for loop over all the stories and display their titles/texts with a 5 sec pause in between. Now, there comes my problem. If I comment out the line that effectively sleeps for 5 sec after each story, everything works: namely, the shell window appears, and text gets rendered on it for all the stories. If I uncomment the sleep line, the shell never appears, although the correct debug output goes into the console every 5 sec.

Here's the sleep line:

   try { Thread.sleep(5000); } catch (InterruptedException ie) {}

Below are sections of my code. First there is the main class, ImgFeedSS. Notice the line in createContents() method:

   f.display2(font, shell, st);

The code for that method is displayed at the bottom.

Thanks, Kirill

======================== code below =========================

Here's the main class, ImgFeedSS:

package net.kirillka.rssss;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.PaletteData;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.custom.StyledText;

public class ImgFeedSS
{
	private Properties props = null;

/**
* The application entry point
* * @param args the command line arguments
*/
public static void main(String[] args) throws InterruptedException
{
new ImgFeedSS().run();
}


/**
* Constructor */
public ImgFeedSS()
{
props = new Properties();
try {
props.load(new FileInputStream(Constants.propertiesFile));
}
catch (FileNotFoundException e)
{
System.out.println("File " + Constants.propertiesFile + " not found. Using defaults.");
}
catch (IOException e)
{
System.out.println("Could not read file " + Constants.propertiesFile + ". Using defaults.");
}

// Overwrite default values
//if (props.containsKey("rssss.output.dir")) { Constants.outputDir = props.getProperty("rssss.output.dir"); } //if (props.containsKey("rssss.output.prefix")) { Constants.outputPrefix = props.getProperty("rssss.output.prefix"); }
if (props.containsKey("rssss.debug")) { Constants.DEBUG = new Boolean(props.getProperty("rssss.debug")).booleanValue(); }
}


/**
* Runs the application
*/
public void run() throws InterruptedException
{
final Display display = new Display();
final Shell shell = new Shell(display, SWT.NO_TRIM | SWT.ON_TOP); // Shell must be created with style SWT.NO_TRIM
createContents(display, shell);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch()) { display.sleep(); }
}
display.dispose();
}



/**
* Creates the window contents
* * @param shell the parent shell
*/
private void createContents(Display display, Shell shell) throws InterruptedException
{
/**
* Black out the shell and make it fill up the whole display */
//Browser browser = new Browser(shell, SWT.NONE);
shell.setBackground(display.getSystemColor(SWT.COLOR_BLACK));
Rectangle r = shell.getDisplay().getPrimaryMonitor().getBounds();
shell.setSize(r.width, r.height);
shell.setLocation(1000, 0); // for debugging
//shell.setLocation(0, 0); //shell.forceActive(); // i thought this is necessary to have it on top, but the Shell constructor takes care of that
//shell.forceFocus(); // i thought this is necessary to catch keyboard events, but they get caught anyways


/**
* create a cursor with a transparent image and hide it forever (until we exit)
*/
Color white = display.getSystemColor(SWT.COLOR_WHITE);
Color black = display.getSystemColor(SWT.COLOR_BLACK);
PaletteData palette = new PaletteData(new RGB[] { white.getRGB(), black.getRGB() });
ImageData sourceData = new ImageData(16, 16, 1, palette);
sourceData.transparentPixel = 0;
Cursor cursor = new Cursor(display, sourceData, 0, 0);
shell.setCursor(cursor);

/**
* Show feed results onscreen
*/
StyledText st = new StyledText(shell, SWT.BORDER | SWT.WRAP | SWT.READ_ONLY); // | SWT.V_SCROLL);
st.setBounds(0, 0, shell.getSize().x, shell.getSize().y);
st.setBackground(display.getSystemColor(SWT.COLOR_RED));
st.setForeground(display.getSystemColor(SWT.COLOR_YELLOW));
Font font = new Font(display,"Arial",16,SWT.NORMAL);
st.setFont(font);


FeedFactory factory = new FeedFactory();
HtmlFeed f = (HtmlFeed) factory.build(Constants.feedUrlString);
f.display2(font, shell, st);

/**
* exit screen-saver whenever any key is pressed
*/
st.addListener(SWT.KeyDown, new Listener() {
public void handleEvent(Event e)
{
System.exit(0);
}
});


/**
* exit screen-saver whenever mouse is double-clicked
*/
st.addListener(SWT.MouseDoubleClick, new Listener() {
public void handleEvent(Event e)
{
System.exit(0);
}
});
}


}


Here's display2() and a couple of helper functions. Note that this is work in progress and a lot of irregularities in the code for now (hopefully :) ..


public void display2(final Font font, final Shell s, final StyledText st) throws InterruptedException
{
System.out.println("HtmlFeed.display2 (using StyledText):");
final SyndFeed sf = super.getSf();


String text = ""; System.out.println("HtmlFeed.display2: before the loop");
for (Object fe : sf.getEntries())
{
//get title and text of the entry
SyndContent title = ((SyndEntry)fe).getTitleEx();
SyndContent content = (SyndContent) ((SyndEntry)fe).getDescription(); //use description field
System.out.println("HtmlFeed.display2: title: " + title);

if (content == null) // if it's empty, use content # 1
{
content = (SyndContent) ((SyndEntry)fe).getContents().get(0);
}

if (content == null) // if that's empty - return {
System.out.println("Skipping: " + fe);
continue; // nothing to display. next loop item, please
}
else // content not null, we go on!
{
text = htmlToText(content.getValue());
if (Constants.DEBUG) { System.out.println(text); }
text = layout2(font, s.getDisplay(), text, s);
text = title.getValue() + "\n" + text + "\n\n";
System.out.println("HtmlFeed.display2: text: " + text);
st.append("\n\n\n" + text);
// pause a few sec
Thread.sleep(5000);
// Commenting out the sleep line below makes the shell window reappear - no idea why
//try { Thread.sleep(5000); } catch (InterruptedException ie) {}
st.invokeAction(ST.PAGE_DOWN);
}
}
System.out.println("All the news that fit to print - all done!");
}


private String layout2(Font f, Display d, String t, Shell s)
{
if (Constants.DEBUG) { System.out.println("Full text: [" + t + "]"); }
if (Constants.DEBUG) { System.out.println("Full text length: [" + t.length() + "]"); }
StringBuffer b = new StringBuffer();
Rectangle monitor = d.getBounds();
int lineWidth = getLineLength2(s, monitor, f); // compute the length of line

int pos = 0; // position of the last space in a given line
int curr = 0; // current position
String line = "";
while(curr + lineWidth <= t.length()) // read all lines but the last one (which can be incomplete)
{
line = t.substring(curr, curr + lineWidth); // get the next lineWidth characters into line var
if (Constants.DEBUG) { System.out.println("Raw Line: [" + line + "]"); }
pos = line.lastIndexOf(" "); // position of last space in the line var
if (Constants.DEBUG) { System.out.println("Last index of space: " + pos); }
line = line.substring(0, pos); // correct the line variable
if (Constants.DEBUG) { System.out.println("Corrected Line: [" + line + "]"); }
b.append(line);
b.append("\n");
if (Constants.DEBUG) { System.out.println("Buffer b is now:\n" + b.toString()); }
curr = curr + line.length() + 1;
}

// read the last (possibly short) line
line = t.substring(curr); // get the remainder of t into line var
if (Constants.DEBUG) { System.out.println("Last (short?) Line: [" + line + "]"); }
b.append(line);
b.append("\n\n");
if (Constants.DEBUG) { System.out.println("Buffer b is now:\n" + b.toString()); }


		return b.toString();
	}

private int getLineLength2(Shell sh, Rectangle r, Font f)
{
String s = "a";
sh.setFont(f);
GC gc = new GC(sh);
while(gc.textExtent(s).x < r.width)
{
s += "a"; // increment test string
}
if (Constants.DEBUG) { System.out.println("Line length is " + (s.length()-1)); }
return s.length()-1;
}