Initial commit from SVN.

This commit is contained in:
wcrisman
2014-05-30 10:31:51 -07:00
commit b45e56b890
1968 changed files with 370949 additions and 0 deletions

17
Snippets/.classpath Normal file
View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry combineaccessrules="false" kind="src" path="/Class File Services"/>
<classpathentry combineaccessrules="false" kind="src" path="/Orb"/>
<classpathentry combineaccessrules="false" kind="src" path="/Common"/>
<classpathentry combineaccessrules="false" kind="src" path="/SWT"/>
<classpathentry combineaccessrules="false" kind="src" path="/Foundation"/>
<classpathentry combineaccessrules="false" kind="src" path="/Foundation SWT"/>
<classpathentry kind="src" path=".apt_generated">
<attributes>
<attribute name="optional" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="bin"/>
</classpath>

BIN
Snippets/.keystore Normal file

Binary file not shown.

17
Snippets/.project Normal file
View File

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

3474
Snippets/regexSource.txt Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,85 @@
package com.de22.sql;
import java.io.File;
import com.common.debug.Debug;
import com.common.io.StreamSupport;
public class MsSqlToMySqlConstraintParser {
/**
* @param args
*/
public static void main(String[] args) {
try {
File inputFile = new File("c:/temp/script.sql");
File outputFile = new File("c:/temp/modified_script.sql");
String input = StreamSupport.readText(inputFile, "UTF8");
StringBuffer output = new StringBuffer(input.length());
StringBuffer alters = new StringBuffer(1000);
int nextTableIndex = 0;
int endTableIndex = 0;
String table;
input = input.replaceAll("\r\n", "\n");
while(nextTableIndex >= 0) {
nextTableIndex = input.indexOf("CREATE TABLE", endTableIndex == 0 ? 0 : endTableIndex + 1);
if(nextTableIndex > 0) {
//Ignore code that is commented out.//
if(input.lastIndexOf('\n', nextTableIndex) + 1 != input.lastIndexOf("--", nextTableIndex)) {
try {
//Write out the stuff above the table.//
output.append(input.substring(endTableIndex == 0 ? 0 : endTableIndex + 1, nextTableIndex));
} catch(StringIndexOutOfBoundsException e) {
Debug.log(e);
}
//Find the end of the table.//
endTableIndex = input.indexOf(';', nextTableIndex);
//Create a copy of the table text to work with.//
table = input.substring(nextTableIndex, endTableIndex + 1);
//Find the first constraint within the table.//
int firstConstraintIndex = table.indexOf("CONSTRAINT");
//If we found a constraint then cut out all the constraints from the table.//
if(firstConstraintIndex != -1) {
//Find the end of the constraints (will be the end of the table definition).//
int endParen = table.lastIndexOf(")");
String tableName = table.substring(13, table.indexOf('(') - 1);
//Create the alter statement.//
alters.append("ALTER TABLE ");
alters.append(tableName);
alters.append(" (\n ");
alters.append(table.substring(firstConstraintIndex, endParen));
alters.append(");\n\n");
try {
//Update the table to not include the constraints.//
table = table.substring(0, table.lastIndexOf(',', firstConstraintIndex)) + '\n' + table.substring(endParen);
} catch(StringIndexOutOfBoundsException e) {
Debug.log(e);
}
//Write the table to the ouptut.//
output.append(table);
}//if//
}//if//
else {
//Write out the stuff above the commented table.//
output.append(input.substring(endTableIndex == 0 ? 0 : endTableIndex + 1, nextTableIndex + 13));
//Update the end table index to ensure we don't end up in an infinate loop.//
endTableIndex = nextTableIndex + 13;
}//else//
}//if//
}//while//
output.append("\n");
output.append(alters.toString());
StreamSupport.writeText(output.toString(), outputFile, "UTF8");
}//try//
catch(Throwable e) {
Debug.log(e);
}//catch//
}//main()//
}//MsSqlToMySqlConstraintParser//

View File

@@ -0,0 +1,10 @@
package com.test;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
}//main()//
}//Main//

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,268 @@
package org.eclipse.swt.graphics;
import org.eclipse.swt.*;
import org.eclipse.swt.custom.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
import com.common.util.LiteHashMap;
import com.common.util.LiteList;
import com.common.util.optimized.IntObjectHashMap;
/**
* <pre>Attempt at writing an SWT document display that allows:
* word wrap or no word wrap
* document within document
* images with text wrap & attached to top, bottom, or text position (center, left, right align?)
* hyperlinks
* other controls (maybe just panel?)</pre>
*/
public class StyledDocument extends Canvas {
public static final int LEFT_WRAPPED = 0;
public static final int RIGHT_WRAPPED = 1;
public static final int UNWRAPPED = 2;
private int width = 0;
private String text = null;
private String[] paragraphs = null;
/** Assumes currently that the images are ordered first by paragraph #, then by VALIGN (TOP, then BOTTOM), then by HALIGN (HALIGN_LEFT, HALIGN_CENTER, HALIGN_RIGHT, HALIGN_LEFT_WRAPPED, then HALIGN_RIGHT_WRAPPED). */
private ParagraphContainer[] paragraphContainers = null;
/** Whether the metadata on the content has been reset, requiring a re-layout of the text. */
private boolean isReset = true;
private static class DocumentPart {
public TextLayout partLayout = null;
public int lineCount = 0;
}//DocumentPart//
private static class ComponentPart {
public Image image = null;
public Control control = null;
/** The orientation of the component part, either LEFT_WRAPPED, RIGHT_WRAPPED, or UNWRAPPED (if it is the top component). */
public int orientation = LEFT_WRAPPED;
public int leftPadding = 0;
public int rightPadding = 0;
public int topPadding = 0;
public int bottomPadding = 0;
/** Only used with wrapped parts. Determines how far from the preceeding component part or paragraph top before text starts wrapping and the component appears. */
public int offset = 0;
}//ComponentPart//
private static class ParagraphContainer {
/** A collection of TextLayout instances used in a previous rendering. */
public LiteList layouts = new LiteList(1, 10);
public ComponentPart top = null;
public LiteList left = null;
public LiteList right = null;
public void reset() {
for(int index = layouts.getSize() - 1; index >= 0; index--) {
((TextLayout) layouts.remove(index)).dispose();
}//for//
}//reset()//
}//ParagraphContainer//
/**
* StyledDocument constructor.
* @param parent
* @param style
*/
public StyledDocument(Composite parent, int style) {
super(parent, style);
addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
organize();
}
});
addControlListener(new ControlListener() {
public void controlResized(ControlEvent e) {
width = getSize().x;
reset();
}
public void controlMoved(ControlEvent e) {
}
});
}//StyledDocument()//
/**
*
*/
private void organize() {
//If the control has been reset then re-layout the text.//
if(isReset) {
//Iterate over the paragraphs, processing them one at a time.//
for(int paragraphIndex = 0; paragraphIndex < paragraphs.length; paragraphIndex++) {
String subText = paragraphs[paragraphIndex];
ParagraphContainer container = paragraphContainers[paragraphIndex];
if(container.left == null && container.right == null) {
TextLayout textLayout = new TextLayout(getDisplay());
textLayout.setText(subText);
container.layouts.add(textLayout);
}//if//
else {
ComponentPart nextLeft = null;
ComponentPart nextRight = null;
while(subText != null) {
TextLayout textLayout = new TextLayout(getDisplay());
int lineIndex = 0;
int height = 0;
Rectangle lineBounds;
textLayout.setText(subText);
textLayout.setWidth(width);
lineBounds = textLayout.getLineBounds(lineIndex);
height += lineBounds.height;
while(height)
textLayout.draw(e.gc, 0, 0);
}//while//
}//else//
}//for//
isReset = false;
}//if//
}//organize()//
/**
* Adds a control to the document.
* @param paragraphIndex The index of the paragraph the control is attached to.
* @param orientation The orientation of the control relative to the paragraph.
* @param control The control being added.
* @param topPadding The padding above the control that text will not exist in.
* @param rightPadding The padding right of the control that text will not exist in.
* @param bottomPadding The padding below the control that text will not exist in.
* @param leftPadding The padding left of the control that text will not exist in.
* @param offset The offset between the control and the previous control/image or top of the paragraph that text can exist within. This does not include padding, and is ignored if the orientation is UNWRAPPED.
*/
public void addControl(int paragraphIndex, int orientation, Control control, int topPadding, int rightPadding, int bottomPadding, int leftPadding, int offset) {
add(paragraphIndex, orientation, control, topPadding, rightPadding, bottomPadding, leftPadding, offset);
}//addControl()//
/**
* Adds an image to the document.
* @param paragraphIndex The index of the paragraph the image is attached to.
* @param orientation The orientation of the image relative to the paragraph.
* @param control The image being added.
* @param topPadding The padding above the image that text will not exist in.
* @param rightPadding The padding right of the image that text will not exist in.
* @param bottomPadding The padding below the image that text will not exist in.
* @param leftPadding The padding left of the image that text will not exist in.
* @param offset The offset between the image and the previous control/image or top of the paragraph that text can exist within. This does not include padding, and is ignored if the orientation is UNWRAPPED.
*/
public void addImage(int paragraphIndex, int orientation, Image image, int topPadding, int rightPadding, int bottomPadding, int leftPadding, int offset) {
add(paragraphIndex, orientation, image, topPadding, rightPadding, bottomPadding, leftPadding, offset);
}//addImage()//
private void add(int paragraphIndex, int orientation, Object controlOrImage, int topPadding, int rightPadding, int bottomPadding, int leftPadding, int offset) {
if(paragraphIndex >= 0 && paragraphIndex < paragraphContainers.length) {
ParagraphContainer container = paragraphContainers[paragraphIndex];
ComponentPart part = new ComponentPart();
if(controlOrImage instanceof Image) {
part.image = (Image) controlOrImage;
}//if//
else if(controlOrImage instanceof Control) {
part.control = (Control) controlOrImage;
}//else if//
part.topPadding = topPadding;
part.rightPadding = rightPadding;
part.bottomPadding = bottomPadding;
part.leftPadding = leftPadding;
switch(orientation) {
case UNWRAPPED: {
if(container.top == null) {
container.top = part;
}//if//
else {
throw new RuntimeException("Cannot have multiple top components.");
}//else//
break;
}//case//
case RIGHT_WRAPPED: {
if(container.right == null) {
container.right = new LiteList(3, 10);
}//if//
container.right.add(part);
break;
}//case//
case LEFT_WRAPPED: {
if(container.left == null) {
container.left = new LiteList(3, 10);
}//if//
container.left.add(part);
break;
}//case//
}//switch//
}//if//
else {
throw new IndexOutOfBoundsException();
}//else//
}//add()//
/**
* Sets the text, reseting the entire control.
* @param text The initial text for the control.
*/
public void setText(String text) {
text = text.replace("\r\n", "\n");
if(!text.equals(this.text)) {
this.text = text;
this.paragraphs = this.text.split("\n");
//TODO: Should we remove empty paragraphs?
//Cleanup old metadata.//
reset();
//Create a new metadata container.//
this.paragraphContainers = new ParagraphContainer[paragraphs.length];
//Setup new metadata.//
for(int index = 0; index < this.paragraphContainers.length; index++) {
this.paragraphContainers[index] = new ParagraphContainer();
}//for//
}//if//
}//setText()//
/**
* Resets the control by clearing any cached display data.
*/
public void reset() {
//Cleanup old metadata.//
if(this.paragraphContainers != null) {
for(int index = 0; index < this.paragraphContainers.length; index++) {
this.paragraphContainers[index].reset();
}//for//
}//if//
isReset = true;
}//reset()//
/* (non-Javadoc)
* @see org.eclipse.swt.widgets.Widget#dispose()
*/
public void dispose() {
reset();
super.dispose();
}//dispose()//
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
StyledDocument doc = null;
shell.setLayout(new FillLayout());
doc = new StyledDocument(shell, SWT.WRAP | SWT.BORDER);
shell.setSize(400, 400);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}//StyledDocument//

View File

@@ -0,0 +1,85 @@
package org.eclipse.swt.graphics;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
public class SwtBackgroundTextRenderTest {
/**
* @param args
*/
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
Composite doc = null;
shell.setLayout(new FillLayout());
doc = new Composite(shell, SWT.BORDER);
//Paints one line to an image which is mapped to the display. If the image is larger than the text then multiple images will be captured until all the text is mapped. Wrapping is performed manually.//
doc.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
TextLayout textLayout = new TextLayout(display);
String text = "A";
int offsets[][] = new int[2][text.length()];
int[] lineOffsets;
int characterOffset = 0;
int imageOffset = 0;
Rectangle bounds;
Image offlineImage;
GC gc;
int imageWidth = 100;
int outputX = 0;
int outputY = 0;
textLayout.setText(text);
bounds = textLayout.getBounds();
offlineImage = new Image(display, imageWidth, bounds.height);
gc = new GC(offlineImage);
textLayout.draw(gc, imageOffset, 0);
while(characterOffset < text.length()) {
int wordStartOffset = textLayout.getNextOffset(0, SWT.MOVEMENT_WORD_START);
int wordEndOffset = textLayout.getNextOffset(wordStartOffset, SWT.MOVEMENT_WORD_END);
//TODO: Determine whether to wrap the word to the next line.
if(wordStartOffset > imageWidth + imageOffset) {
}//if//
while(wordEndOffset > imageWidth + imageOffset) {
}//while//
}//while//
for(int index = 0; index < offsets[0].length; index++) {
offsets[0][index] = textLayout.getLocation(0, false).x;
offsets[1][index] = textLayout.getLocation(0, true).x;
}//for//
lineOffsets = textLayout.getLineOffsets();
textLayout.get
for(int index = 0, max = textLayout.getLineCount(); index < max; index++) {
textLayout.getL
}//for//
gc.dispose();
textLayout.dispose();
e.gc.drawImage(offlineImage, 0, 0);
}//paintControl()//
});
shell.setSize(400, 400);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}

View File

@@ -0,0 +1,82 @@
package snippets;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.CoolBar;
import org.eclipse.swt.widgets.CoolItem;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
/**
* Copyright Wynne Crisman 2006<p>
*/
public class Bindings {
/**
* Bindings constructor.
*/
public Bindings() {
super();
}
/**
* @param args
*/
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
CoolBar bar = new CoolBar(shell, SWT.BORDER);
for(int i=0; i<2; i++) {
CoolItem item = new CoolItem (bar, SWT.DROP_DOWN);
Button button = new Button (bar, SWT.PUSH);
button.setText ("Button " + i);
Point size = button.computeSize (SWT.DEFAULT, SWT.DEFAULT);
item.setPreferredSize (item.computeSize (size.x, size.y));
item.setControl (button);
}
bar.pack();
shell.open();
/*
<action>
<key code="a" modifiers="control | shift"
</action>
*/
shell.addKeyListener(new KeyListener() {
public void keyReleased(KeyEvent e) {
//int key = e.keyCode;
//int modifiers = e.stateMask;
//int a = SWT.MOD1;
//a = SWT.CONTROL;
//a = SWT.ALT;
//a = SWT.SHIFT;
}
public void keyPressed(KeyEvent e) {
}
});
shell.addMouseListener(new MouseListener() {
public void mouseUp(MouseEvent e) {
//int button = e.button;
//int modifiers = e.stateMask;
}
public void mouseDown(MouseEvent e) {
}
public void mouseDoubleClick(MouseEvent e) {
}
});
while (!shell.isDisposed ()) {
if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose ();
}
}

View File

@@ -0,0 +1,50 @@
package snippets;
import org.eclipse.swt.*;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.*;
/**
* Copyright Declarative Engineering LLC 2007<p>
*/
public class Combo1 {
public static void main (String [] args) {
Display display = new Display ();
Shell shell = new Shell (display);
shell.setLayout(new FillLayout(SWT.VERTICAL));
final Combo combo = new Combo(shell, 0);
combo.setItems (new String [] {"A", "B", "C"});
combo.setSize (200, 200);
Button button = new Button(shell, 0);
button.setText("Display Combo State");
button.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
System.out.println("Combo selection index: " + combo.getSelectionIndex() + " Text: " + combo.getText());
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
Button button2 = new Button(shell, 0);
button2.setText("Set Combo Text");
button2.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
combo.deselectAll();
combo.setText("A");
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
shell.pack ();
shell.open ();
while (!shell.isDisposed ()) {
if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose ();
}
}

View File

@@ -0,0 +1,38 @@
package snippets;
import org.eclipse.swt.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.widgets.*;
/**
* SWT snippit
*/
public class CoolBar1 {
/**
* CoolBar1 constructor.
*/
public CoolBar1() {
super();
}
public static void main (String [] args) {
Display display = new Display ();
Shell shell = new Shell (display);
CoolBar bar = new CoolBar (shell, SWT.BORDER);
for (int i=0; i<2; i++) {
CoolItem item = new CoolItem (bar, SWT.DROP_DOWN);
Button button = new Button (bar, SWT.PUSH);
button.setText ("Button " + i);
Point size = button.computeSize (SWT.DEFAULT, SWT.DEFAULT);
item.setPreferredSize (item.computeSize (size.x, size.y));
item.setControl (button);
}
bar.pack ();
shell.open ();
while (!shell.isDisposed ()) {
if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose ();
}
}

View File

@@ -0,0 +1,70 @@
package snippets;
import org.eclipse.swt.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.widgets.*;
import com.foundation.view.swt.layout.*;
/**
* SWT snippit
*/
public class CoolBar2 {
/**
* CoolBar2 constructor.
*/
public CoolBar2() {
super();
}
static int itemCount;
static CoolItem createItem(CoolBar coolBar, int count) {
ToolBar toolBar = new ToolBar(coolBar, SWT.FLAT);
for (int i = 0; i < count; i++) {
ToolItem item = new ToolItem(toolBar, SWT.PUSH);
item.setText(itemCount++ +"");
}
toolBar.pack();
Point size = toolBar.getSize();
CoolItem item = new CoolItem(coolBar, SWT.NONE);
item.setControl(toolBar);
Point preferred = item.computeSize(size.x, size.y);
item.setPreferredSize(preferred);
return item;
}
public static void main(String[] args) {
Display display = new Display();
final Shell shell = new Shell(display);
CoolBar coolBar = new CoolBar(shell, SWT.NONE);
createItem(coolBar, 3);
createItem(coolBar, 2);
createItem(coolBar, 3);
createItem(coolBar, 4);
int style = SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL;
Text text = new Text(shell, style);
FormLayout layout = new FormLayout();
shell.setLayout(layout);
FormData coolData = new FormData();
coolData.left = new FormAttachment(0);
coolData.right = new FormAttachment(100);
coolData.top = new FormAttachment(0);
coolBar.setLayoutData(coolData);
coolBar.addListener(SWT.Resize, new Listener() {
public void handleEvent(Event event) {
shell.layout();
}
});
FormData textData = new FormData();
textData.left = new FormAttachment(0);
textData.right = new FormAttachment(100);
textData.top = new FormAttachment(coolBar);
textData.bottom = new FormAttachment(100);
text.setLayoutData(textData);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
display.dispose();
}
}

View File

@@ -0,0 +1,104 @@
package snippets;
/*
* CoolBar example snippet: drop-down a chevron menu containing hidden tool items
*
* For a list of all SWT example snippets see
* http://www.eclipse.org/swt/snippets/
*/
import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import com.foundation.view.swt.layout.*;
/**
* SWT Snippit
*/
public class CoolBar3 {
static Display display;
static Shell shell;
static CoolBar coolBar;
static Menu chevronMenu = null;
/**
* CoolBar3 constructor.
*/
public CoolBar3() {
super();
}
public static void main (String [] args) {
display = new Display ();
shell = new Shell (display);
shell.setLayout(new GridLayout());
coolBar = new CoolBar(shell, SWT.FLAT | SWT.BORDER);
coolBar.setLayoutData(new GridData(GridData.FILL_BOTH));
ToolBar toolBar = new ToolBar(coolBar, SWT.FLAT | SWT.WRAP);
int minWidth = 0;
for (int j = 0; j < 5; j++) {
int width = 0;
ToolItem item = new ToolItem(toolBar, SWT.PUSH);
item.setText("B" + j);
width = item.getWidth();
/* find the width of the widest tool */
if (width > minWidth) minWidth = width;
}
CoolItem coolItem = new CoolItem(coolBar, SWT.DROP_DOWN);
coolItem.setControl(toolBar);
Point size = toolBar.computeSize(SWT.DEFAULT, SWT.DEFAULT);
Point coolSize = coolItem.computeSize (size.x, size.y);
coolItem.setMinimumSize(minWidth, coolSize.y);
coolItem.setPreferredSize(coolSize);
coolItem.setSize(coolSize);
coolItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
if (event.detail == SWT.ARROW) {
CoolItem item = (CoolItem) event.widget;
Rectangle itemBounds = item.getBounds ();
Point pt = coolBar.toDisplay(new Point(itemBounds.x, itemBounds.y));
itemBounds.x = pt.x;
itemBounds.y = pt.y;
ToolBar bar = (ToolBar) item.getControl ();
ToolItem[] tools = bar.getItems ();
int i = 0;
while (i < tools.length) {
Rectangle toolBounds = tools[i].getBounds ();
pt = bar.toDisplay(new Point(toolBounds.x, toolBounds.y));
toolBounds.x = pt.x;
toolBounds.y = pt.y;
/* Figure out the visible portion of the tool by looking at the
* intersection of the tool bounds with the cool item bounds. */
Rectangle intersection = itemBounds.intersection (toolBounds);
/* If the tool is not completely within the cool item bounds, then it
* is partially hidden, and all remaining tools are completely hidden. */
if (!intersection.equals (toolBounds)) break;
i++;
}
/* Create a menu with items for each of the completely hidden buttons. */
if (chevronMenu != null) chevronMenu.dispose();
chevronMenu = new Menu (coolBar);
for (int j = i; j < tools.length; j++) {
MenuItem menuItem = new MenuItem (chevronMenu, SWT.PUSH);
menuItem.setText (tools[j].getText());
}
/* Drop down the menu below the chevron, with the left edges aligned. */
pt = coolBar.toDisplay(new Point(event.x, event.y));
chevronMenu.setLocation (pt.x, pt.y);
chevronMenu.setVisible (true);
}
}
});
shell.pack();
shell.open ();
while (!shell.isDisposed ()) {
if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose ();
}
}

View File

@@ -0,0 +1,96 @@
package snippets;
import org.eclipse.swt.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.widgets.*;
import com.foundation.view.swt.layout.*;
/**
* SWT snippit
*/
public class CoolBarSimulation {
/**
* CoolBar2 constructor.
*/
public CoolBarSimulation() {
super();
}
static int itemCount;
static CoolItem createItem(CoolBar coolBar, int count) {
ToolBar toolBar = new ToolBar(coolBar, SWT.FLAT);
for (int i = 0; i < count; i++) {
ToolItem item = new ToolItem(toolBar, SWT.PUSH);
item.setText(itemCount++ +"");
}
toolBar.pack();
Point size = toolBar.getSize();
CoolItem item = new CoolItem(coolBar, SWT.NONE);
item.setControl(toolBar);
Point preferred = item.computeSize(size.x, size.y);
item.setPreferredSize(preferred);
return item;
}
public static void main(String[] args) {
Display display = new Display();
final Shell shell = new Shell(display);
CoolBar coolBar = new CoolBar(shell, SWT.NONE);
// CoolItem coolItem1 = new CoolItem(coolBar, 0);
ToolBar toolBar = new ToolBar(coolBar, SWT.FLAT);
//ToolItem toolItem1 = new ToolItem(toolBar, SWT.PUSH);
//ToolItem toolItem2 = new ToolItem(toolBar, SWT.CHECK);
//ToolItem toolItem3 = new ToolItem(toolBar, SWT.RADIO);
//ToolItem toolItem4 = new ToolItem(toolBar, SWT.RADIO);
//ToolItem toolItem5 = new ToolItem(toolBar, SWT.SEPARATOR);
//ToolItem toolItem6 = new ToolItem(toolBar, SWT.RADIO);
//ToolItem toolItem7 = new ToolItem(toolBar, SWT.RADIO);
// CoolItem coolItem2 = new CoolItem(coolBar, 0);
// Combo combo = new Combo(coolBar, SWT.BORDER);
Text text = new Text(shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
//Initialize//
shell.pack();
coolBar.addListener(SWT.Resize, new Listener() {
public void handleEvent(Event event) {
shell.layout(true, true);
}
});
//Refresh//
coolBar.setBackground(new Color(display, 136, 255, 153));
toolBar.setBackground(new Color(display, 136, 153, 255));
createItem(coolBar, 3);
createItem(coolBar, 2);
createItem(coolBar, 3);
createItem(coolBar, 4);
FormLayout layout = new FormLayout();
shell.setLayout(layout);
FormData coolData = new FormData();
coolData.left = new FormAttachment(0);
coolData.right = new FormAttachment(100);
coolData.top = new FormAttachment(0);
coolBar.setLayoutData(coolData);
FormData textData = new FormData();
textData.left = new FormAttachment(0);
textData.right = new FormAttachment(100);
textData.top = new FormAttachment(coolBar);
textData.bottom = new FormAttachment(100);
text.setLayoutData(textData);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
display.dispose();
}
}

View File

@@ -0,0 +1,112 @@
package snippets;
/*
* DateTime example snippet: create a DateTime calendar and a DateTime time.
*
* For a list of all SWT example snippets see
* http://www.eclipse.org/swt/snippets/
*/
import org.eclipse.swt.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
public class DateTime1 {
public static void main (String [] args) {
Display display = new Display ();
Shell shell = new Shell(display);
shell.setLayout(new RowLayout(SWT.VERTICAL));
Composite composite;
Label label;
DateTime calendar;
DateTime date;
DateTime time;
label = new Label(shell, 0);
label.setText("Short");
composite = new Composite(shell, SWT.BORDER);
composite.setLayout(new RowLayout(SWT.HORIZONTAL));
calendar = new DateTime(composite, SWT.CALENDAR | SWT.SHORT);
calendar.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
System.out.println("calendar date changed");
}
});
date = new DateTime(composite, SWT.DATE | SWT.SHORT);
date.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
System.out.println("date changed");
}
});
time = new DateTime(composite, SWT.TIME | SWT.SHORT);
time.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
System.out.println("time changed");
}
});
label = new Label(shell, 0);
label.setText("Medium");
composite = new Composite(shell, SWT.BORDER);
composite.setLayout(new RowLayout(SWT.HORIZONTAL));
calendar = new DateTime(composite, SWT.CALENDAR | SWT.MEDIUM);
calendar.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
System.out.println("calendar date changed");
}
});
date = new DateTime(composite, SWT.DATE | SWT.MEDIUM);
date.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
System.out.println("date changed");
}
});
time = new DateTime(composite, SWT.TIME | SWT.MEDIUM);
time.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
System.out.println("time changed");
}
});
label = new Label(shell, 0);
label.setText("Long");
composite = new Composite(shell, SWT.BORDER);
composite.setLayout(new RowLayout(SWT.HORIZONTAL));
calendar = new DateTime(composite, SWT.CALENDAR | SWT.LONG | SWT.BORDER);
calendar.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
System.out.println("calendar date changed");
}
});
date = new DateTime(composite, SWT.DATE | SWT.LONG | SWT.BORDER);
date.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
System.out.println("date changed");
}
});
time = new DateTime(composite, SWT.TIME | SWT.LONG | SWT.BORDER);
time.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
System.out.println("time changed");
}
});
shell.pack();
shell.open();
while(!shell.isDisposed()) {
if(!display.readAndDispatch()) display.sleep();
}
display.dispose();
}
}

View File

@@ -0,0 +1,46 @@
package snippets;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.Format;
import java.text.NumberFormat;
import java.util.Locale;
/**
* Copyright Declarative Engineering LLC 2008<p>
*/
public class FormatTest {
/**
* @param args
*/
public static void main(String[] args) {
Locale.setDefault(Locale.FRANCE);
BigDecimal number = new BigDecimal("-550235.23");
//DecimalFormat format = new DecimalFormat("<22>#.##;(<28>#.##)");
//DecimalFormat format = new DecimalFormat("$#.#<23>;($#.#<23>)");
DecimalFormat format = new DecimalFormat("$#.#;($#.#)");
//DecimalFormat format = (DecimalFormat) NumberFormat.getCurrencyInstance();
//format.setGroupingUsed(true);
System.out.println("Pattern (Local): " + format.toLocalizedPattern());
System.out.println("Pattern: " + format.toPattern());
System.out.println("Zero Digit: " + format.getDecimalFormatSymbols().getZeroDigit());
System.out.println("Decimal " + format.getDecimalFormatSymbols().getDecimalSeparator());
System.out.println("Monitary Decimal " + format.getDecimalFormatSymbols().getMonetaryDecimalSeparator());
System.out.println("Group Separator " + format.getDecimalFormatSymbols().getGroupingSeparator());
System.out.println("PerMill " + format.getDecimalFormatSymbols().getPerMill());
System.out.println("Positive Prefix: " + format.getPositivePrefix());
System.out.println("Positive Suffix: " + format.getPositiveSuffix());
System.out.println("Negative Prefix: " + format.getNegativePrefix());
System.out.println("Negative Suffix: " + format.getNegativeSuffix());
System.out.println("Is Monitary: " + (format.toLocalizedPattern().indexOf(format.getDecimalFormatSymbols().getCurrencySymbol()) != -1));
//System.out.println("Infinity " + format.getDecimalFormatSymbols().getInfinity());
System.out.println("Intl Currency: " + format.getDecimalFormatSymbols().getInternationalCurrencySymbol());
System.out.println("Currency: " + format.getDecimalFormatSymbols().getCurrencySymbol());
System.out.println(format.format(number));
System.exit(0);
}
}

View File

@@ -0,0 +1,57 @@
package snippets;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.*;
/**
* Copyright Wynne Crisman 2006<p>
*/
public class GlobalListener implements Listener {
/**
* GlobalListener constructor.
*/
private GlobalListener() {
super();
}
/**
* @param args
*/
public static void main(String[] args) {
GlobalListener listener = new GlobalListener();
Display display = new Display();
Shell shell = new Shell(display);
CoolBar bar = new CoolBar(shell, SWT.BORDER);
for(int i=0; i<2; i++) {
CoolItem item = new CoolItem (bar, SWT.DROP_DOWN);
Button button = new Button (bar, SWT.PUSH);
button.setText ("Button " + i);
Point size = button.computeSize (SWT.DEFAULT, SWT.DEFAULT);
item.setPreferredSize (item.computeSize (size.x, size.y));
item.setControl (button);
}
bar.pack();
shell.open();
display.addListener(SWT.MouseDoubleClick, listener);
display.addListener(SWT.MouseDown, listener);
display.addFilter(SWT.MouseMove, listener);
display.addListener(SWT.MouseUp, listener);
display.addListener(SWT.MouseWheel, listener);
display.addListener(SWT.KeyDown, listener);
display.addListener(SWT.KeyUp, listener);
while (!shell.isDisposed ()) {
if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose ();
}
public void handleEvent(Event event) {
System.out.println("Event Handled @ " + System.currentTimeMillis());
}
}

View File

@@ -0,0 +1,75 @@
package snippets;
import org.eclipse.swt.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.widgets.*;
/**
* Copyright Declarative Engineering LLC 2007<p>
*/
public class ScrollComposite {
/**
* @param args
*/
public static void main(String[] args) {
Display display = new Display ();
final Shell shell = new Shell (display, SWT.SHELL_TRIM | SWT.H_SCROLL | SWT.V_SCROLL);
final Composite composite = new Composite (shell, SWT.BORDER);
composite.setSize (700, 600);
final Color red = display.getSystemColor (SWT.COLOR_RED);
composite.addPaintListener (new PaintListener() {
public void paintControl (PaintEvent e) {
e.gc.setBackground (red);
e.gc.fillOval (5, 5, 690, 590);
}
});
final ScrollBar hBar = shell.getHorizontalBar ();
hBar.addListener (SWT.Selection, new Listener () {
public void handleEvent (Event e) {
Point location = composite.getLocation ();
location.x = -hBar.getSelection ();
composite.setLocation (location);
}
});
final ScrollBar vBar = shell.getVerticalBar ();
vBar.addListener (SWT.Selection, new Listener () {
public void handleEvent (Event e) {
Point location = composite.getLocation ();
location.y = -vBar.getSelection ();
composite.setLocation (location);
}
});
shell.addListener (SWT.Resize, new Listener () {
public void handleEvent (Event e) {
Point size = composite.getSize ();
Rectangle rect = shell.getClientArea ();
hBar.setMaximum (size.x);
vBar.setMaximum (size.y);
hBar.setThumb (Math.min (size.x, rect.width));
vBar.setThumb (Math.min (size.y, rect.height));
int hPage = size.x - rect.width;
int vPage = size.y - rect.height;
int hSelection = hBar.getSelection ();
int vSelection = vBar.getSelection ();
Point location = composite.getLocation ();
if (hSelection >= hPage) {
if (hPage <= 0) hSelection = 0;
location.x = -hSelection;
}
if (vSelection >= vPage) {
if (vPage <= 0) vSelection = 0;
location.y = -vSelection;
}
composite.setLocation (location);
}
});
shell.open ();
while (!shell.isDisposed()) {
if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose ();
}
}

View File

@@ -0,0 +1,142 @@
package snippets;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
import com.foundation.view.JefGradient;
/**
* Copyright Declarative Engineering LLC 2007<p>
*/
public class ScrolledControls {
/**
* @param args
*/
public static void main(String[] args) {
Display display = new Display();
final Shell shell = new Shell(display, SWT.SHELL_TRIM);
FillLayout shellLayout = new FillLayout();
shellLayout.marginHeight = 10;
shellLayout.marginWidth = 10;
shell.setLayout(shellLayout);
final Canvas outer = new Canvas(shell, SWT.V_SCROLL);
outer.setBackground(display.getSystemColor(SWT.COLOR_GREEN));
outer.getVerticalBar().setVisible(false);
outer.setBackgroundMode(SWT.INHERIT_FORCE);
outer.addListener(SWT.Resize, new Listener() {
public void handleEvent(Event event) {
Image image = null;
Rectangle clientArea = outer instanceof Composite ? ((Composite) outer).getClientArea() : outer.getBounds();
Display display = outer.getDisplay();
Color c1 = display.getSystemColor(SWT.COLOR_BLUE);
Color c2 = display.getSystemColor(SWT.COLOR_RED);
Pattern pattern = new Pattern(display, 0, 0, clientArea.width, clientArea.height, c1, 100, c2, 255);
GC gc;
image = new Image(display, Math.max(1, clientArea.width), Math.max(1, clientArea.height));
gc = new GC(image);
//Force the x/y values to zero since getBounds uses them to provide the upper left point of the control.//
clientArea.x = 0;
clientArea.y = 0;
clientArea.width = Math.max(1, clientArea.width);
clientArea.height = Math.max(1, clientArea.height);
gc.setBackgroundPattern(pattern);
gc.fillRectangle(clientArea);
gc.dispose();
pattern.dispose();
//Dispose of the old gradient background image.//
if(outer.getBackgroundImage() != null) {
outer.getBackgroundImage().dispose();
}//if//
outer.setBackgroundImage(image);
}//handleEvent()//
});
final Canvas inner = new Canvas(outer, SWT.DOUBLE_BUFFERED);
GridLayout innerLayout = new GridLayout(2, false);
innerLayout.horizontalSpacing = 6;
innerLayout.verticalSpacing = 4;
innerLayout.marginHeight = 4;
innerLayout.marginWidth = 4;
inner.setLayout(innerLayout);
for(int i = 0; i < 40; i++) {
Label label = new Label(inner, 0);
Text text = new Text(inner, SWT.BORDER);
GridData labelLayoutData = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
GridData textLayoutData = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
label.setLayoutData(labelLayoutData);
text.setLayoutData(textLayoutData);
label.setText("Text Field " + i);
text.setText("Contents of text field " + i);
}//for//
outer.addListener(SWT.Resize, new Listener() {
public void handleEvent(Event event) {
int increment = 30;
Rectangle bounds = inner.getBounds();
Rectangle clientArea = outer.getClientArea();
ScrollBar vBar = outer.getVerticalBar();
//Check to see if we should show a vertical scroll bar.//
if(bounds.height <= clientArea.height) {
vBar.setVisible(false);
bounds.y = 0;
}//if//
else {
int range = bounds.height - clientArea.height;
if(bounds.y < -range) {
bounds.y = -range;
}//if//
vBar.setVisible(true);
vBar.setPageIncrement(clientArea.height);
vBar.setIncrement(increment);
vBar.setMinimum(0);
vBar.setMaximum(range);
vBar.setSelection(-bounds.y);
}//else//
bounds.width = clientArea.width;
inner.setBounds(bounds);
}//handleEvent()//
});
outer.getVerticalBar().addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
Point location = inner.getLocation();
int offset = -(outer.getVerticalBar().getSelection() + location.y);
Point size = inner.getSize();
//location.y = -getSwtComposite().getVerticalBar().getSelection();
//getSwtParent()SwtUtilities.setRedraw(, false);
//getSwtParent().setLocation(location);
//getSwtParent()SwtUtilities.setRedraw(, true);
outer.scroll(0, offset, 0, 0, size.x, size.y, true);
outer.update();
}//handleEvent()//
});
inner.pack();
shell.setSize(400, 300);
shell.open();
while(!shell.isDisposed()) {
if(!display.readAndDispatch())
display.sleep();
}
display.dispose();
System.exit(0);
}
}

View File

@@ -0,0 +1,440 @@
package snippets;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
import org.eclipse.swt.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import com.common.debug.Debug;
public class StyledTextCurrency {
public static boolean disableFocusSelection = false;
public static DecimalFormat defaultFormat = (DecimalFormat) NumberFormat.getCurrencyInstance(Locale.US);
public static boolean ignoreModifyEvents = false;
public static Text text = null;
public static String originalText = "";
public static Character decimal = null;
public static Character groupingSeparator = null;
public static Character minusSign = null;
public static String exponentSeparator = null;
private static boolean useNull = true;
static {
decimal = new Character(defaultFormat.getDecimalFormatSymbols().getDecimalSeparator());
groupingSeparator = new Character(defaultFormat.getDecimalFormatSymbols().getGroupingSeparator());
minusSign = new Character(defaultFormat.getDecimalFormatSymbols().getMinusSign());
//exponentSeparator = defaultFormat.getDecimalFormatSymbols().getExponentSeparator();
Debug.log("getDecimalSeparator " + defaultFormat.getDecimalFormatSymbols().getDecimalSeparator());
Debug.log("getCurrencySymbol " + defaultFormat.getDecimalFormatSymbols().getCurrencySymbol());
//Debug.log("getExponentSeparator " + defaultFormat.getDecimalFormatSymbols().getExponentSeparator());
Debug.log("getInfinity " + defaultFormat.getDecimalFormatSymbols().getInfinity());
Debug.log("getInternationalCurrencySymbol " + defaultFormat.getDecimalFormatSymbols().getInternationalCurrencySymbol());
Debug.log("getNaN " + defaultFormat.getDecimalFormatSymbols().getNaN());
Debug.log("getDigit " + defaultFormat.getDecimalFormatSymbols().getDigit());
Debug.log("getGroupingSeparator " + defaultFormat.getDecimalFormatSymbols().getGroupingSeparator());
Debug.log("getMinusSign " + defaultFormat.getDecimalFormatSymbols().getMinusSign());
Debug.log("getMonetaryDecimalSeparator " + defaultFormat.getDecimalFormatSymbols().getMonetaryDecimalSeparator());
Debug.log("getPatternSeparator " + defaultFormat.getDecimalFormatSymbols().getPatternSeparator());
Debug.log("getPercent " + defaultFormat.getDecimalFormatSymbols().getPercent());
Debug.log("getPerMill " + defaultFormat.getDecimalFormatSymbols().getPerMill());
Debug.log("getZeroDigit " + defaultFormat.getDecimalFormatSymbols().getZeroDigit());
Debug.log(NumberFormat.getIntegerInstance().getClass().getName());
}//static//
public static void main(String [] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout(1, false));
text = new Text(shell, SWT.SINGLE | SWT.BORDER);
text.setLayoutData(new GridData(150, -1));
text.setText(defaultFormat.format(1213.90));
text.addVerifyListener(new VerifyListener() {
public void verifyText(VerifyEvent event) {
if(!ignoreModifyEvents) {
Number newNumber;
String newText = text.getText();
StringBuffer numberOnly = new StringBuffer(newText.length());
boolean decimalFound = false;
boolean digitFound = false;
boolean negativePrefix = newText.startsWith(defaultFormat.getNegativePrefix());
boolean negativeSuffix = newText.endsWith(defaultFormat.getNegativeSuffix());
boolean positivePrefix = newText.startsWith(defaultFormat.getPositivePrefix());
boolean positiveSuffix = newText.endsWith(defaultFormat.getPositiveSuffix());
int exponentIndex;
String exponentText = null;
//Replace any positive or negative prefix and/or suffix with a minus sign prefix or no prefix to make number detection simpler.//
if(negativePrefix) {
newText = minusSign + newText.substring(negativePrefix ? defaultFormat.getNegativePrefix().length() : 0, newText.length() - (negativeSuffix ? defaultFormat.getNegativeSuffix().length() : 0) - (negativePrefix ? defaultFormat.getNegativePrefix().length() : 0));
}//if//
else if(positivePrefix) {
newText = newText.substring(positivePrefix ? defaultFormat.getPositivePrefix().length() : 0, newText.length() - (positiveSuffix ? defaultFormat.getPositiveSuffix().length() : 0) - (positivePrefix ? defaultFormat.getPositivePrefix().length() : 0));
}//else if//
//NOTE: It is assumed that formatting will either always show the exponent text or never show it, thus no need to identify the user typing a partial exponent separator.//
//NOTE: This may require some testing to get right.//
//Separate the exponent portion of the number.//
if((exponentIndex = newText.indexOf(exponentSeparator)) != -1) {
exponentText = newText.substring(exponentIndex + exponentSeparator.length());
newText = newText.substring(0, exponentIndex);
}//if//
//Identify the actual number sans formatting.//
for(int index = 0; index < newText.length(); index++) {
char ch = newText.charAt(index);
boolean isDecimal = ch == decimal.charValue();
//Gather the characters that make up the number and ignore all other characters.//
if(((ch >= '0') && (ch <= '9')) || ((!digitFound) && (ch == minusSign.charValue())) || (isDecimal && !decimalFound)) {
if(ch == minusSign.charValue()) {
numberOnly.append('-');
}//if//
else {
numberOnly.append(ch);
}//else//
if(isDecimal) {
decimalFound = true;
}//if//
digitFound = true;
}//if//
}//for//
if(exponentText != null) {
digitFound = false;
numberOnly.append('e');
//Identify the actual number sans formatting.//
for(int index = 0; index < exponentText.length(); index++) {
char ch = exponentText.charAt(index);
//Gather the characters that make up the number and ignore all other characters.//
if(((ch >= '0') && (ch <= '9')) || ((!digitFound) && (ch == minusSign.charValue()))) {
if(ch == minusSign.charValue()) {
numberOnly.append('-');
}//if//
else {
numberOnly.append(ch);
}//else//
digitFound = true;
}//if//
}//for//
}//if//
try {
//Ignore the case where a negative number without digits has been typed, or nothing has been typed.//
if(!((numberOnly.length() == 0) || ((numberOnly.length() == 1) && (numberOnly.charAt(0) == '-')))) {
if((newNumber = Double.valueOf(numberOnly.toString())) == null) {
event.doit = false;
}//if//
else {
defaultFormat.format(newNumber);
}//else//
}//if//
}//try//
catch(Throwable e) {
Debug.log(e);
event.doit = false;
}//catch//
}//if//
}//verifyText()//
});
text.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent event) {
if(!ignoreModifyEvents) {
formatText(false);
}//if//
}
});
text.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
//TODO: If the text is not properly formatted then we should default the value. This could be the case if the user has removed the value or typed just a negative sign.
formatText(true);
}
public void focusGained(FocusEvent e) {
if(!disableFocusSelection) {
text.getDisplay().asyncExec(new Runnable() {
public void run() {
text.selectAll();
}
});
}//if//
}
});
text.getShell().addShellListener(new ShellListener() {
public void shellIconified(ShellEvent e) {
}
public void shellDeiconified(ShellEvent e) {
}
public void shellDeactivated(ShellEvent e) {
disableFocusSelection = true;
}
public void shellActivated(ShellEvent e) {
text.getDisplay().asyncExec(new Runnable() {
public void run() {
disableFocusSelection = false;
}
});
}
public void shellClosed(ShellEvent e) {
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
display.dispose();
}
public static Number extractNumber() {
int caretPosition = text.getCaretPosition();
int newCaretPosition = caretPosition;
Number newNumber = null;
String newText = text.getText();
StringBuffer numberOnly = new StringBuffer(newText.length());
boolean decimalFound = false;
boolean digitFound = false;
boolean negativePrefix = newText.startsWith(defaultFormat.getNegativePrefix());
boolean negativeSuffix = newText.endsWith(defaultFormat.getNegativeSuffix());
boolean positivePrefix = newText.startsWith(defaultFormat.getPositivePrefix());
boolean positiveSuffix = newText.endsWith(defaultFormat.getPositiveSuffix());
int exponentIndex;
String exponentText = null;
//Replace any positive or negative prefix and/or suffix with a minus sign prefix or no prefix to make number detection simpler.//
if(negativePrefix) {
newText = minusSign + newText.substring(negativePrefix ? defaultFormat.getNegativePrefix().length() : 0, newText.length() - (negativeSuffix ? defaultFormat.getNegativeSuffix().length() : 0) - (negativePrefix ? defaultFormat.getNegativePrefix().length() : 0));
}//if//
else if(positivePrefix) {
newText = newText.substring(positivePrefix ? defaultFormat.getPositivePrefix().length() : 0, newText.length() - (positiveSuffix ? defaultFormat.getPositiveSuffix().length() : 0) - (positivePrefix ? defaultFormat.getPositivePrefix().length() : 0));
}//else if//
//NOTE: It is assumed that formatting will either always show the exponent text or never show it, thus no need to identify the user typing a partial exponent separator.//
//NOTE: This may require some testing to get right.//
//Separate the exponent portion of the number.//
if((exponentIndex = newText.indexOf(exponentSeparator)) != -1) {
exponentText = newText.substring(exponentIndex + exponentSeparator.length());
newText = newText.substring(0, exponentIndex);
}//if//
//Identify the actual number sans formatting.//
for(int index = 0; index < newText.length(); index++) {
char ch = newText.charAt(index);
boolean isDecimal = ch == decimal.charValue();
//Gather the characters that make up the number and ignore all other characters.//
if(((ch >= '0') && (ch <= '9')) || ((!digitFound) && (ch == minusSign.charValue())) || (isDecimal && !decimalFound)) {
if(ch == minusSign.charValue()) {
numberOnly.append('-');
}//if//
else {
numberOnly.append(ch);
}//else//
if(isDecimal) {
decimalFound = true;
}//if//
digitFound = true;
}//if//
else if(index < caretPosition) {
newCaretPosition--;
}//else if//
}//for//
if(exponentText != null) {
digitFound = false;
numberOnly.append('e');
//Identify the actual number sans formatting.//
for(int index = 0; index < exponentText.length(); index++) {
char ch = exponentText.charAt(index);
//Gather the characters that make up the number and ignore all other characters.//
if(((ch >= '0') && (ch <= '9')) || ((!digitFound) && (ch == minusSign.charValue()))) {
if(ch == minusSign.charValue()) {
numberOnly.append('-');
}//if//
else {
numberOnly.append(ch);
}//else//
digitFound = true;
}//if//
else if(numberOnly.length() + index + exponentSeparator.length() < caretPosition) {
newCaretPosition--;
}//else if//
}//for//
}//if//
//Ignore the case where a negative number without digits has been typed, or nothing has been typed.//
if(!((numberOnly.length() == 0) || ((numberOnly.length() == 1) && (numberOnly.charAt(0) == '-')))) {
try {
newNumber = Double.valueOf(numberOnly.toString());
}//try//
catch(Throwable e) {
Debug.log(e);
newNumber = new Double(0);
}//catch//
}//if//
else {
if(useNull) {
newNumber = null;
}//if//
else {
newNumber = new Double(0);
}//else//
}//else if//
return newNumber;
}//extractNumber()//
public static void formatText(boolean force) {
int caretPosition = text.getCaretPosition();
int newCaretPosition = caretPosition;
Number newNumber = null;
StringBuffer buffer = new StringBuffer(text.getText());
String newText = text.getText();
StringBuffer numberOnly = new StringBuffer(newText.length());
boolean decimalFound = false;
boolean digitFound = false;
boolean negativePrefix = newText.startsWith(defaultFormat.getNegativePrefix());
boolean negativeSuffix = newText.endsWith(defaultFormat.getNegativeSuffix());
boolean positivePrefix = newText.startsWith(defaultFormat.getPositivePrefix());
boolean positiveSuffix = newText.endsWith(defaultFormat.getPositiveSuffix());
int exponentIndex;
String exponentText = null;
//Replace any positive or negative prefix and/or suffix with a minus sign prefix or no prefix to make number detection simpler.//
if(negativePrefix) {
newText = minusSign + newText.substring(negativePrefix ? defaultFormat.getNegativePrefix().length() : 0, newText.length() - (negativeSuffix ? defaultFormat.getNegativeSuffix().length() : 0) - (negativePrefix ? defaultFormat.getNegativePrefix().length() : 0));
}//if//
else if(positivePrefix) {
newText = newText.substring(positivePrefix ? defaultFormat.getPositivePrefix().length() : 0, newText.length() - (positiveSuffix ? defaultFormat.getPositiveSuffix().length() : 0) - (positivePrefix ? defaultFormat.getPositivePrefix().length() : 0));
}//else if//
//NOTE: It is assumed that formatting will either always show the exponent text or never show it, thus no need to identify the user typing a partial exponent separator.//
//NOTE: This may require some testing to get right.//
//Separate the exponent portion of the number.//
if((exponentIndex = newText.indexOf(exponentSeparator)) != -1) {
exponentText = newText.substring(exponentIndex + exponentSeparator.length());
newText = newText.substring(0, exponentIndex);
}//if//
//Identify the actual number sans formatting.//
for(int index = 0; index < newText.length(); index++) {
char ch = newText.charAt(index);
boolean isDecimal = ch == decimal.charValue();
//Gather the characters that make up the number and ignore all other characters.//
if(((ch >= '0') && (ch <= '9')) || ((!digitFound) && (ch == minusSign.charValue())) || (isDecimal && !decimalFound)) {
if(ch == minusSign.charValue()) {
numberOnly.append('-');
}//if//
else {
numberOnly.append(ch);
}//else//
if(isDecimal) {
decimalFound = true;
}//if//
digitFound = true;
}//if//
else if(index < caretPosition) {
newCaretPosition--;
}//else if//
}//for//
if(exponentText != null) {
digitFound = false;
numberOnly.append('e');
//Identify the actual number sans formatting.//
for(int index = 0; index < exponentText.length(); index++) {
char ch = exponentText.charAt(index);
//Gather the characters that make up the number and ignore all other characters.//
if(((ch >= '0') && (ch <= '9')) || ((!digitFound) && (ch == minusSign.charValue()))) {
if(ch == minusSign.charValue()) {
numberOnly.append('-');
}//if//
else {
numberOnly.append(ch);
}//else//
digitFound = true;
}//if//
else if(numberOnly.length() + index + exponentSeparator.length() < caretPosition) {
newCaretPosition--;
}//else if//
}//for//
}//if//
//Ignore the case where a negative number without digits has been typed, or nothing has been typed.//
if(!((numberOnly.length() == 0) || ((numberOnly.length() == 1) && (numberOnly.charAt(0) == '-')))) {
try {
ignoreModifyEvents = true;
newNumber = Double.valueOf(numberOnly.toString());
//newNumber = defaultFormat.parse(text.getText());
text.setText(defaultFormat.format(newNumber));
newText = text.getText();
for(int index = 0; index < newCaretPosition; index++) {
if(newCaretPosition < newText.length()) {
char ch = newText.charAt(index);
if(((ch < '0') || (ch > '9')) && (ch != decimal.charValue())) {
newCaretPosition++;
}//if//
}//if//
}//for//
}//if//
catch(Throwable e) {
Debug.log(e);
//Reset to the original text.//
buffer.setLength(0);
buffer.append(originalText);
newCaretPosition = caretPosition;
}//catch//
finally {
ignoreModifyEvents = false;
}//finally//
text.setSelection(newCaretPosition);
originalText = text.getText();
}//if//
else if(force) {
if(useNull) {
try {
ignoreModifyEvents = true;
text.setText("");
}//try//
finally {
ignoreModifyEvents = false;
}//finally//
}//if//
else {
try {
ignoreModifyEvents = true;
text.setText(defaultFormat.format(new Integer(0)));
}//try//
finally {
ignoreModifyEvents = false;
}//finally//
}//else//
}//else if//
}//formatText()//
}

View File

@@ -0,0 +1,93 @@
package snippets;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Currency;
import java.util.Locale;
import org.eclipse.swt.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import com.common.debug.Debug;
public class TextCurrency {
public static boolean disableFocusSelection = false;
//public static Currency currency = Currency.getInstance(Locale.US);
public static NumberFormat defaultFormat = NumberFormat.getCurrencyInstance(Locale.US);
public static boolean ignoreModifyEvents = false;
public static Text text = null;
public static void main(String [] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout(1, false));
text = new Text(shell, SWT.SINGLE | SWT.BORDER);
text.setLayoutData(new GridData(150, -1));
text.setText(defaultFormat.format(123));
text.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent event) {
if(!ignoreModifyEvents) {
int caretPosition = text.getCaretPosition();
Number newNumber = null;
try {
ignoreModifyEvents = true;
newNumber = defaultFormat.parse(text.getText());
text.setText(defaultFormat.format(newNumber));
}//if//
catch(ParseException e) {
Debug.log(e);
//Reset text.
}//catch//
finally {
ignoreModifyEvents = false;
}//finally//
text.setSelection(caretPosition);
}//if//
}
});
text.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
}
public void focusGained(FocusEvent e) {
if(!disableFocusSelection) {
text.getDisplay().asyncExec(new Runnable() {
public void run() {
text.selectAll();
}
});
}//if//
}
});
text.getShell().addShellListener(new ShellListener() {
public void shellIconified(ShellEvent e) {
}
public void shellDeiconified(ShellEvent e) {
}
public void shellDeactivated(ShellEvent e) {
disableFocusSelection = true;
}
public void shellActivated(ShellEvent e) {
text.getDisplay().asyncExec(new Runnable() {
public void run() {
disableFocusSelection = false;
}
});
}
public void shellClosed(ShellEvent e) {
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
display.dispose();
}
}

View File

@@ -0,0 +1,48 @@
package snippets;
import org.eclipse.swt.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.events.*;
public class TextSearch {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout(2, false));
final Text text = new Text(shell, SWT.SEARCH | SWT.CANCEL);
Image image = null;
if ((text.getStyle() & SWT.CANCEL) == 0) {
image = new Image (display, TextSearch.class.getResourceAsStream("cancel.gif"));
ToolBar toolBar = new ToolBar (shell, SWT.FLAT);
ToolItem item = new ToolItem (toolBar, SWT.PUSH);
item.setImage (image);
item.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
text.setText("");
System.out.println("Search cancelled");
}
});
}
text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
text.setText("Search text");
text.addSelectionListener(new SelectionAdapter() {
public void widgetDefaultSelected(SelectionEvent e) {
if (e.detail == SWT.CANCEL) {
System.out.println("Search cancelled");
} else {
System.out.println("Searching for: " + text.getText() + "...");
}
}
});
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
if (image != null) image.dispose();
display.dispose();
}
}

View File

@@ -0,0 +1,70 @@
package snippets;
import org.eclipse.swt.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
public class TextSelectAll {
public static boolean disableFocusSelection = false;
public static void main(String [] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout(1, false));
Text text1 = new Text(shell, SWT.MULTI | SWT.WRAP);
text1.setLayoutData(new GridData(150, 50));
text1.setText("Tab will traverse out from here.");
text1.addTraverseListener(new TraverseListener() {
public void keyTraversed(TraverseEvent e) {
if (e.detail == SWT.TRAVERSE_TAB_NEXT || e.detail == SWT.TRAVERSE_TAB_PREVIOUS) {
e.doit = true;
}
}
});
final Text text2 = new Text(shell, SWT.SINGLE | SWT.BORDER);
text2.setLayoutData(new GridData(150, -1));
text2.setText("123");
text2.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
}
public void focusGained(FocusEvent e) {
if(!disableFocusSelection) {
text2.getDisplay().asyncExec(new Runnable() {
public void run() {
text2.selectAll();
}
});
}//if//
}
});
text2.getShell().addShellListener(new ShellListener() {
public void shellIconified(ShellEvent e) {
}
public void shellDeiconified(ShellEvent e) {
}
public void shellDeactivated(ShellEvent e) {
disableFocusSelection = true;
}
public void shellActivated(ShellEvent e) {
text2.getDisplay().asyncExec(new Runnable() {
public void run() {
disableFocusSelection = false;
}
});
}
public void shellClosed(ShellEvent e) {
}
});
shell.setTabList(new Control[] {text1, text2});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
display.dispose();
}
}

View File

@@ -0,0 +1,120 @@
package snippets;
import org.eclipse.swt.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import com.common.util.StringSupport;
public class TextTraverseAndHexOuput {
public static boolean disableFocusSelection = false;
public static final int CUSTOM_EVENT_TYPE = 1000;
public static void main(String [] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout(1, false));
//shell.setBounds(10,10,200,200);
Text text1 = new Text(shell, SWT.MULTI | SWT.WRAP);
//text1.setBounds(10,10,150,50);
text1.setLayoutData(new GridData(150, 50));
text1.setText("Tab will traverse out from here.");
text1.addKeyListener(new KeyListener() {
public void keyReleased(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
System.out.println(StringSupport.toHexString(StringSupport.toUtf8Bytes(new String(new char[] {(char) ((e.stateMask >> 8) & 0xFF), (char) (e.stateMask & 0xFF)}))));
System.out.println(StringSupport.toHexString(StringSupport.toUtf8Bytes(new String(new char[] {(char) ((e.keyCode >> 8) & 0xFF), (char) (e.keyCode & 0xFF)}))));
System.out.println(StringSupport.toHexString(StringSupport.toUtf8Bytes(new String(new char[] {(char) ((e.character >> 8) & 0xFF), (char) (e.character & 0xFF)}))));
}
});
text1.addTraverseListener(new TraverseListener() {
public void keyTraversed(TraverseEvent e) {
if (e.detail == SWT.TRAVERSE_TAB_NEXT || e.detail == SWT.TRAVERSE_TAB_PREVIOUS) {
e.doit = true;
}
}
});
Text text2 = new Text(shell, SWT.MULTI | SWT.WRAP);
//text2.setBounds(10,100,150,50);
text2.setLayoutData(new GridData(150, 50));
text2.setText("But Tab will NOT traverse out from here (Ctrl+Tab will).");
final Text text3 = new Text(shell, SWT.SINGLE | SWT.BORDER);
//text3.setBounds(10,300,150,50);
text3.setLayoutData(new GridData(150, -1));
text3.setText("123");
text3.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
System.out.println("Focus Lost");
}
public void focusGained(FocusEvent e) {
//Event event = new Event();
//event.type = CUSTOM_EVENT_TYPE;
//event.widget = text3;
//event.item = text3;
System.out.println("Focus Gained");
//postFocusClick = false;
//text3.getDisplay().post(event);
if(!disableFocusSelection) {
text3.getDisplay().asyncExec(new Runnable() {
public void run() {
System.out.println("Runnable");
//postFocusClick = true;
text3.selectAll();
}
});
}//if//
}
});
text3.getShell().addShellListener(new ShellListener() {
public void shellIconified(ShellEvent e) {
System.out.println("Iconified");
}
public void shellDeiconified(ShellEvent e) {
System.out.println("Deiconified");
}
public void shellDeactivated(ShellEvent e) {
System.out.println("Deactivated");
disableFocusSelection = true;
}
public void shellActivated(ShellEvent e) {
System.out.println("Activated");
text3.getDisplay().asyncExec(new Runnable() {
public void run() {
System.out.println("Runnable2");
disableFocusSelection = false;
}
});
}
public void shellClosed(ShellEvent e) {
}
});
text3.addMouseListener(new MouseListener() {
public void mouseUp(MouseEvent e) {
}
public void mouseDown(MouseEvent e) {
System.out.println("Mouse Down");
//if(!postFocusClick) {
// postFocusClick = true;
// text3.selectAll();
//}
}
public void mouseDoubleClick(MouseEvent e) {
}
});
shell.setTabList(new Control[] {text1, text3});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
display.dispose();
}
}

View File

@@ -0,0 +1,45 @@
package snippets;
/*
* ToolBar example snippet: create a flat tool bar (images)
*
* For a list of all SWT example snippets see
* http://www.eclipse.org/swt/snippets/
*/
import org.eclipse.swt.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.widgets.*;
/**
* SWT snippit
*/
public class ToolBar1 {
/**
* ToolBar1 constructor.
*/
public ToolBar1() {
super();
}
public static void main (String [] args) {
Display display = new Display();
Image image = new Image (display, 16, 16);
Color color = display.getSystemColor (SWT.COLOR_RED);
GC gc = new GC (image);
gc.setBackground (color);
gc.fillRectangle (image.getBounds ());
gc.dispose ();
Shell shell = new Shell (display);
ToolBar toolBar = new ToolBar (shell, SWT.FLAT | SWT.BORDER);
for (int i=0; i<12; i++) {
ToolItem item = new ToolItem (toolBar, SWT.DROP_DOWN);
item.setImage (image);
}
toolBar.pack ();
shell.open ();
while (!shell.isDisposed()) {
if (!display.readAndDispatch ()) display.sleep ();
}
image.dispose ();
display.dispose ();
}
}

View File

@@ -0,0 +1,67 @@
package snippets;
/*
* ToolBar example snippet: create tool bar (normal, hot and disabled images)
*
* For a list of all SWT example snippets see
* http://www.eclipse.org/swt/snippets/
*/
import org.eclipse.swt.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.widgets.*;
/**
* SWT snippit
*/
public class ToolBar2 {
/**
* ToolBar2 constructor.
*/
public ToolBar2() {
super();
}
public static void main (String [] args) {
Display display = new Display ();
Shell shell = new Shell (display);
Image image = new Image (display, 20, 20);
Color color = display.getSystemColor (SWT.COLOR_BLUE);
GC gc = new GC (image);
gc.setBackground (color);
gc.fillRectangle (image.getBounds ());
gc.dispose ();
Image disabledImage = new Image (display, 20, 20);
color = display.getSystemColor (SWT.COLOR_GREEN);
gc = new GC (disabledImage);
gc.setBackground (color);
gc.fillRectangle (disabledImage.getBounds ());
gc.dispose ();
Image hotImage = new Image (display, 20, 20);
color = display.getSystemColor (SWT.COLOR_RED);
gc = new GC (hotImage);
gc.setBackground (color);
gc.fillRectangle (hotImage.getBounds ());
gc.dispose ();
ToolBar bar = new ToolBar (shell, SWT.BORDER | SWT.FLAT);
bar.setSize (200, 32);
for (int i=0; i<12; i++) {
ToolItem item = new ToolItem (bar, 0);
item.setImage (image);
item.setDisabledImage (disabledImage);
item.setHotImage (hotImage);
if (i % 3 == 0) item.setEnabled (false);
}
shell.open ();
while (!shell.isDisposed ()) {
if (!display.readAndDispatch ()) display.sleep ();
}
image.dispose ();
disabledImage.dispose ();
hotImage.dispose ();
display.dispose ();
}
}

View File

@@ -0,0 +1,53 @@
package snippets;
/*
* ToolBar example snippet: place a drop down menu in a tool bar
*
* For a list of all SWT example snippets see
* http://www.eclipse.org/swt/snippets/
*/
import org.eclipse.swt.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.widgets.*;
/**
* SWT snippit
*/
public class ToolBar3 {
/**
* ToolBar3 constructor.
*/
public ToolBar3() {
super();
}
public static void main (String [] args) {
final Display display = new Display ();
final Shell shell = new Shell (display);
final ToolBar toolBar = new ToolBar (shell, SWT.NONE);
final Menu menu = new Menu (shell, SWT.POP_UP);
for (int i=0; i<8; i++) {
MenuItem item = new MenuItem (menu, SWT.PUSH);
item.setText ("Item " + i);
}
final ToolItem item = new ToolItem (toolBar, SWT.DROP_DOWN);
item.addListener (SWT.Selection, new Listener () {
public void handleEvent (Event event) {
if (event.detail == SWT.ARROW) {
Rectangle rect = item.getBounds ();
Point pt = new Point (rect.x, rect.y + rect.height);
pt = toolBar.toDisplay (pt);
menu.setLocation (pt.x, pt.y);
menu.setVisible (true);
}
}
});
toolBar.pack ();
shell.pack ();
shell.open ();
while (!shell.isDisposed ()) {
if (!display.readAndDispatch ()) display.sleep ();
}
menu.dispose ();
display.dispose ();
}
}

View File

@@ -0,0 +1,51 @@
package snippets;
/*
* ToolBar example snippet: place a combo box in a tool bar
*
* For a list of all SWT example snippets see
* http://www.eclipse.org/swt/snippets/
*/
import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;
/**
* SWT Snippit
*/
public class ToolBar4 {
/**
* ToolBar4 constructor.
*/
public ToolBar4() {
super();
}
public static void main (String [] args) {
Display display = new Display ();
Shell shell = new Shell (display);
ToolBar bar = new ToolBar (shell, SWT.BORDER);
for (int i=0; i<4; i++) {
ToolItem item = new ToolItem (bar, SWT.DROP_DOWN);
item.setText ("Item " + i);
}
ToolItem sep = new ToolItem (bar, SWT.SEPARATOR);
int start = bar.getItemCount ();
for (int i=start; i<start+4; i++) {
ToolItem item = new ToolItem (bar, 0);
item.setText ("Item " + i);
}
Combo combo = new Combo (bar, SWT.READ_ONLY);
for (int i=0; i<4; i++) {
combo.add ("Item " + i);
}
combo.pack ();
sep.setWidth (combo.getSize ().x);
sep.setControl (combo);
bar.pack ();
shell.pack ();
shell.open ();
while (!shell.isDisposed ()) {
if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose ();
}
}

View File

@@ -0,0 +1,157 @@
package snippets;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TreeEditor;
import org.eclipse.swt.events.TreeEvent;
import org.eclipse.swt.events.TreeListener;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/**
* A sample tree table which is a modification of the eclipse snippet 170.
*
* Demonstrates: the size of the open/close icon bug. Setting the width/height variables below to low values makes the open/close graphics
* impossibly small, and the activation rectangle is not over the graphic (it is in fact to the right of the graphic, just to the left of
* the image attached to the row/first column.
*
* Demonstrates: the user opens a node and there is a delay before data is given to the display.
* During the delay we don't want the UI to become non-reponsive, so we thread the collection of the data.
* For some reason the threading causes the buttons to be displayed incorrectly.
* Any change in size of the view results in the correct display.
*/
public class TreeTable {
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
int width = 4;
int height = 4;
final Image image = new Image(display, width, height);
final Image image2 = new Image(display, width * 2, height * 2);
GC imageGc = new GC(image);
imageGc.setLineWidth(3);
imageGc.drawLine(0, 0, width, height);
imageGc.dispose();
imageGc = new GC(image2);
imageGc.setLineWidth(3);
imageGc.drawLine(0, 0, width * 2, height * 2);
imageGc.dispose();
final Tree tree = new Tree(shell, SWT.FULL_SELECTION | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
tree.setHeaderVisible(true);
TreeColumn column1 = new TreeColumn(tree, SWT.LEFT);
column1.setText("Column 1");
column1.setWidth(130);
//column1.setImage(image);
TreeColumn column2 = new TreeColumn(tree, SWT.CENTER);
column2.setText("Column 2");
column2.setWidth(130);
TreeColumn column3 = new TreeColumn(tree, SWT.RIGHT);
column3.setText("Column 3");
column3.setWidth(130);
for(int i = 0; i < 4; i++) {
TreeItem item = new TreeItem(tree, SWT.NONE);
item.setText(new String[] {"item " + i, "abc", "defghi"});
item.setImage(new Image[] {image2, null, image});
item.setData(Boolean.TRUE);
TreeEditor editor = new TreeEditor(tree);
Button control = new Button(tree, SWT.PUSH);
editor.setEditor(control, item, 1);
control.setText("...");
editor.grabHorizontal = true;
editor.grabVertical = true;
editor.minimumWidth = 30;
editor.minimumHeight = 17;
TreeItem subItem = new TreeItem(item, SWT.NONE);
subItem.setText(new String[] {"", "", ""});
}
tree.addListener(SWT.MeasureItem, new Listener() {
public void handleEvent(Event event) {
switch(event.type) {
case SWT.MeasureItem: {
TreeItem item = (TreeItem) event.item;
event.height = 60;
break;
}//case//
}//switch//
}//handleEvent()//
});
tree.addTreeListener(new TreeListener() {
public void treeExpanded(TreeEvent e) {
final TreeItem item = (TreeItem) e.item;
if((item.getData() != null) && (((Boolean) item.getData()).booleanValue() == true)) {
//Things that were irrelevant to the problem.
//e.doit = false;
//item.setExpanded(false);
//tree.setEnabled(false);
//treeSwtUtilities.setRedraw(, false);
item.setData(Boolean.FALSE);
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(400);
} catch(InterruptedException e) {
}
display.syncExec(new Runnable() {
public void run() {
TreeItem[] oldItems = item.getItems();
for(int index = 0; index < oldItems.length; index++) {
oldItems[index].dispose();
}
for(int j = 0; j < 4; j++) {
TreeItem subItem = new TreeItem(item, SWT.NONE);
subItem.setText(new String[] {"subitem " + j, "jklmnop", "qrs"});
}
TreeItem topItem = tree.getTopItem();
//shellSwtUtilities.setRedraw(, false);
tree.pack();
shell.layout(true, true);
tree.setTopItem(topItem);
//shellSwtUtilities.setRedraw(, true);
shell.redraw();
//Things that were irrelevant to the problem.
//item.setExpanded(true);
//tree.setEnabled(true);
//treeSwtUtilities.setRedraw(, true);
/* Some things I tried to force a refresh...
tree.layout(true, true);
tree.redraw();
tree.update();
*/
}
});
}
}).start();
}
}
public void treeCollapsed(TreeEvent e) {
}
});
shell.pack();
Rectangle bounds = shell.getBounds();
bounds.height += 100;
shell.setBounds(bounds);
shell.open();
while(!shell.isDisposed()) {
if(!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}

View File

@@ -0,0 +1,446 @@
package snippets;
import com.common.security.Random;
public class VarIntTest {
/**
* @param args
*/
public static void main(String[] args) {
{
long original = 8536407376162401424L;
byte[] buffer = new byte[100];
// int count = writeLong(original, buffer, 0);
// long result = readLong(buffer, 0);
int count = writeLongReverse(original, buffer, 0);
long result = readLongReverse(buffer, 0);
System.out.println("Original: " + original);
System.out.println(" Result: " + result);
System.out.println("Size: " + count);
System.exit(0);
}
//Uses a most significant first orientation.//
//Rotates the sign bit to become the right most bit in the sequence.//
// boolean ok = true;
// long original = 0;
//
// while(ok) {
// byte[] buffer = new byte[100];
// int count = writeLongReverse(original, buffer, 0);
// long result = readLongReverse(buffer, 0);
//
//// System.out.println("Original: " + original);
//// System.out.println("Result: " + result);
//// System.out.println("Size: " + count);
// ok = original == result;
// original -= 1;
// ok &= original != 0;
//
// if(!ok) {
// System.out.println("Original: " + original);
// System.out.println("Result: " + result);
// System.out.println("Size: " + count);
// }
// }
for(int index = 0; index < 1000000; index++) {
long original = new Random().nextLong();
byte[] buffer = new byte[100];
int count = writeLongReverse(original, buffer, 0);
long result = readLongReverse(buffer, 0);
// System.out.println("Original: " + original);
// System.out.println("Result: " + result);
// System.out.println("Size: " + count);
boolean ok = original == result;
if(!ok) {
System.out.println("Original: " + original);
System.out.println("Result: " + result);
System.out.println("Size: " + count);
}
}
}
public static int write(int value, byte[] buffer, int offset) {
int nextByte;
int nextIndex = offset;
boolean hasWritten = false;
//Write it.//
if(value < 0) {
value = (~value << 1) | 0x01;
}//if//
else {
value <<= 1;
}//else//
nextByte = value >>> 28; //Last 4 bits.//
if(nextByte != 0) {
nextByte |= 0x80;
buffer[nextIndex++] = (byte) nextByte;
hasWritten = true;
}//if//
nextByte = (value >>> 21) & 0x7F;
if(nextByte != 0 || hasWritten) {
nextByte |= 0x80;
buffer[nextIndex++] = (byte) nextByte;
hasWritten = true;
}//if//
nextByte = (value >>> 14) & 0x7F;
if(nextByte != 0 || hasWritten) {
nextByte |= 0x80;
buffer[nextIndex++] = (byte) nextByte;
hasWritten = true;
}//if//
nextByte = (value >>> 7) & 0x7F;
if(nextByte != 0 || hasWritten) {
nextByte |= 0x80;
buffer[nextIndex++] = (byte) nextByte;
}//if//
nextByte = value & 0x7F;
buffer[nextIndex++] = (byte) nextByte;
return nextIndex - offset;
}
public static int writeReverse(int value, byte[] buffer, int offset) {
int nextByte;
int nextIndex = offset;
//Write it.//
if(value < 0) {
value = (~value << 1) | 0x01;
}//if//
else {
value <<= 1;
}//else//
nextByte = value & 0x7F;
if((value & 0xFFFFFF80) != 0) {
buffer[nextIndex++] = (byte) (nextByte | 0x80);
nextByte = (value >>> 7) & 0x7F;
if((value & 0xFFFFC000) != 0) {
buffer[nextIndex++] = (byte) (nextByte | 0x80);
nextByte = (value >>> 14) & 0x7F;
if((value & 0xFFE00000) != 0) {
buffer[nextIndex++] = (byte) (nextByte | 0x80);
nextByte = (value >>> 21) & 0x7F;
if((value & 0xF0000000) != 0) {
buffer[nextIndex++] = (byte) (nextByte | 0x80);
nextByte = value >>> 28; //Last 4 bits.//
}//if//
}//if//
}//if//
}//if//
buffer[nextIndex++] = (byte) nextByte;
return nextIndex - offset;
}
public static int read(byte[] buffer, int offset) {
boolean hasMore = true;
int result = 0;
while(hasMore) {
int nextByte = buffer[offset++];
result = (result << 7) | (nextByte & 0x7F);
hasMore = (nextByte & 0x80) > 0;
}//while//
//Flip the negative bit around to become the most significant bit.//
if((result & 0x01) == 1) {
result = ~(result >>> 1);
}//if//
else {
result >>>= 1;
}//else//
return result;
}//read()//
public static int readReverse(byte[] buffer, int offset) {
int result = 0;
int nextByte;
nextByte = buffer[offset++];
result = nextByte & 0x7F;
if((nextByte & 0x80) != 0) {
nextByte = buffer[offset++];
result |= ((nextByte & 0x7F) << 7);
if((nextByte & 0x80) != 0) {
nextByte = buffer[offset++];
result |= ((nextByte & 0x7F) << 14);
if((nextByte & 0x80) != 0) {
nextByte = buffer[offset++];
result |= ((nextByte & 0x7F) << 21);
if((nextByte & 0x80) != 0) {
nextByte = buffer[offset++];
result |= ((nextByte & 0x7F) << 28);
}//if//
}//if//
}//if//
}//if//
//Flip the negative bit around to become the most significant bit.//
if((result & 0x01) == 1) {
result = ~(result >>> 1);
}//if//
else {
result >>>= 1;
}//else//
return result;
}
public static int writeLong(long value, byte[] buffer, int offset) {
int nextByte;
int nextIndex = offset;
boolean hasWritten = false;
//Write it.//
if(value < 0) {
value = (~value << 1) | 0x01;
}//if//
else {
value <<= 1;
}//else//
nextByte = (int) (value >>> 63); //Last 1 bits.//
if(nextByte != 0) {
nextByte |= 0x80;
buffer[nextIndex++] = (byte) nextByte;
hasWritten = true;
}//if//
nextByte = (int) ((value >>> 56) & 0x7F);
if(nextByte != 0 || hasWritten) {
nextByte |= 0x80;
buffer[nextIndex++] = (byte) nextByte;
hasWritten = true;
}//if//
nextByte = (int) ((value >>> 49) & 0x7F);
if(nextByte != 0 || hasWritten) {
nextByte |= 0x80;
buffer[nextIndex++] = (byte) nextByte;
hasWritten = true;
}//if//
nextByte = (int) ((value >>> 42) & 0x7F);
if(nextByte != 0 || hasWritten) {
nextByte |= 0x80;
buffer[nextIndex++] = (byte) nextByte;
hasWritten = true;
}//if//
nextByte = (int) ((value >>> 35) & 0x7F);
if(nextByte != 0 || hasWritten) {
nextByte |= 0x80;
buffer[nextIndex++] = (byte) nextByte;
hasWritten = true;
}//if//
nextByte = (int) ((value >>> 28) & 0x7F);
if(nextByte != 0 || hasWritten) {
nextByte |= 0x80;
buffer[nextIndex++] = (byte) nextByte;
hasWritten = true;
}//if//
nextByte = (int) ((value >>> 21) & 0x7F);
if(nextByte != 0 || hasWritten) {
nextByte |= 0x80;
buffer[nextIndex++] = (byte) nextByte;
hasWritten = true;
}//if//
nextByte = (int) ((value >>> 14) & 0x7F);
if(nextByte != 0 || hasWritten) {
nextByte |= 0x80;
buffer[nextIndex++] = (byte) nextByte;
hasWritten = true;
}//if//
nextByte = (int) ((value >>> 7) & 0x7F);
if(nextByte != 0 || hasWritten) {
nextByte |= 0x80;
buffer[nextIndex++] = (byte) nextByte;
}//if//
nextByte = (int) (value & 0x7F);
buffer[nextIndex++] = (byte) nextByte;
return nextIndex - offset;
}
public static int writeLongReverse(long value, byte[] buffer, int offset) {
int nextByte;
int nextIndex = offset;
//Write it.//
if(value < 0) {
value = (~value << 1) | 0x01;
}//if//
else {
value <<= 1;
}//else//
nextByte = (int) (value & 0x7F);
if((value & 0xFFFFFFFFFFFFFF80L) != 0) {
buffer[nextIndex++] = (byte) (nextByte | 0x80);
nextByte = (int) ((value >>> 7) & 0x7F);
if((value & 0xFFFFFFFFFFFFC000L) != 0) {
buffer[nextIndex++] = (byte) (nextByte | 0x80);
nextByte = (int) ((value >>> 14) & 0x7F);
if((value & 0xFFFFFFFFFFE00000L) != 0) {
buffer[nextIndex++] = (byte) (nextByte | 0x80);
nextByte = (int) ((value >>> 21) & 0x7F);
if((value & 0xFFFFFFFFF0000000L) != 0) {
buffer[nextIndex++] = (byte) (nextByte | 0x80);
nextByte = (int) ((value >>> 28) & 0x7F);
if((value & 0xFFFFFFF800000000L) != 0) {
buffer[nextIndex++] = (byte) (nextByte | 0x80);
nextByte = (int) ((value >>> 35) & 0x7F);
if((value & 0xFFFFFC0000000000L) != 0) {
buffer[nextIndex++] = (byte) (nextByte | 0x80);
nextByte = (int) ((value >>> 42) & 0x7F);
if((value & 0xFFFE000000000000L) != 0) {
buffer[nextIndex++] = (byte) (nextByte | 0x80);
nextByte = (int) ((value >>> 49) & 0x7F);
if((value & 0xFF00000000000000L) != 0) {
buffer[nextIndex++] = (byte) (nextByte | 0x80);
nextByte = (int) ((value >>> 56) & 0x7F);
if((value & 0x8000000000000000L) != 0) {
buffer[nextIndex++] = (byte) (nextByte | 0x80);
nextByte = (int) (value >>> 63); //Last 1 bit.//
}//if//
}//if//
}//if//
}//if//
}//if//
}//if//
}//if//
}//if//
}//if//
buffer[nextIndex++] = (byte) nextByte;
return nextIndex - offset;
}
public static long readLong(byte[] buffer, int offset) {
boolean hasMore = true;
long result = 0;
while(hasMore) {
long nextByte = buffer[offset++];
result = (result << 7) | (nextByte & 0x7F);
hasMore = (nextByte & 0x80) > 0;
}//while//
//Flip the negative bit around to become the most significant bit.//
if((result & 0x01) == 1) {
result = ~(result >>> 1);
}//if//
else {
result >>>= 1;
}//else//
return result;
}//read()//
public static long readLongReverse(byte[] buffer, int offset) {
long result = 0;
long nextByte;
nextByte = buffer[offset++];
result = nextByte & 0x7F;
if((nextByte & 0x80) != 0) {
nextByte = buffer[offset++];
result |= ((nextByte & 0x7F) << 7);
if((nextByte & 0x80) != 0) {
nextByte = buffer[offset++];
result |= ((nextByte & 0x7F) << 14);
if((nextByte & 0x80) != 0) {
nextByte = buffer[offset++];
result |= ((nextByte & 0x7F) << 21);
if((nextByte & 0x80) != 0) {
nextByte = buffer[offset++];
result |= ((nextByte & 0x7F) << 28);
if((nextByte & 0x80) != 0) {
nextByte = buffer[offset++];
result |= ((nextByte & 0x7F) << 35);
if((nextByte & 0x80) != 0) {
nextByte = buffer[offset++];
result |= ((nextByte & 0x7F) << 42);
if((nextByte & 0x80) != 0) {
nextByte = buffer[offset++];
result |= ((nextByte & 0x7F) << 49);
if((nextByte & 0x80) != 0) {
nextByte = buffer[offset++];
result |= ((nextByte & 0x7F) << 56);
if((nextByte & 0x80) != 0) {
nextByte = buffer[offset++];
result |= ((nextByte & 0x01) << 63);
}//if//
}//if//
}//if//
}//if//
}//if//
}//if//
}//if//
}//if//
}//if//
//Flip the negative bit around to become the most significant bit.//
if((result & 0x01) == 1) {
result = ~(result >>> 1);
}//if//
else {
result >>>= 1;
}//else//
return result;
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 367 B

View File

@@ -0,0 +1,33 @@
package snippets.orb;
import com.common.orb.Orb;
import com.de22.orb.Address;
import com.de22.orb.development.OrbClassLoader;
import com.de22.orb.optional.*;
/**
* Copyright Declarative Engineering LLC 2008<p>
*/
public class ClientTest {
/**
* @param args
*/
public static void main(String[] args) {
Orb.setOrbWrapper(new CommonOrbWrapper(new OrbClassLoader(), null, null));
try {
Object socketIdentifier = Orb.openSocket("Socket", new SocketOptions(new Address("zeeri:8444"), null, null));
IData data = (IData) Orb.lookup("Data", socketIdentifier);
while(true) {
System.out.println(data.getData());
System.out.println(data.getBigData());
}//while//
}
catch(Throwable e) {
e.printStackTrace();
}
System.exit(0);
}
}

View File

@@ -0,0 +1,27 @@
package snippets.orb;
/**
* Copyright Declarative Engineering LLC 2008<p>
*/
public class Data implements IData {
/* (non-Javadoc)
* @see snippets.orb.IData#getData()
*/
public String getData() {
return "The brown fox jumped over the red moon.";
}
/* (non-Javadoc)
* @see snippets.orb.IData#getBigData()
*/
public String getBigData() {
StringBuffer bigData = new StringBuffer(120000);
String data = getData();
int count = 120000 / data.length();
while(count-- > 0) {
bigData.append(data);
}
return bigData.toString();
}
}

View File

@@ -0,0 +1,9 @@
package snippets.orb;
/**
* Copyright Declarative Engineering LLC 2008<p>
*/
public interface IData {
public String getData();
public String getBigData();
}

View File

@@ -0,0 +1,27 @@
package snippets.orb;
import com.common.orb.Orb;
import com.de22.orb.Address;
import com.de22.orb.development.OrbClassLoader;
import com.de22.orb.optional.*;
import com.de22.orb.security.SslSecurityProvider;
/**
* Copyright Declarative Engineering LLC 2008<p>
*/
public class ServerTest {
/**
* @param args
*/
public static void main(String[] args) {
Orb.setOrbWrapper(new CommonOrbWrapper(new OrbClassLoader(), null, null));
Orb.bind(Orb.getProxy(new Data(), IData.class), "Data", null);
try {
Orb.openServerSocket("ServerSocket", new ServerSocketOptions(new Address("zeeri:8444"), new Address("zeeri:8444"), new SocketOptions(), null, 360000, 20000, new SslSecurityProvider("TLS", "./.keystore", "123456", "abcdefg")));
}
catch(Throwable e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,150 @@
package snippets.regex;
import java.io.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import com.common.io.StreamSupport;
/**
* A simple regex tester that takes a regex string and a file path (2 parameters) and outputs any matches.
*
* <p><pre>
Regex Notes:
Meta Characters in Java regex: ([{\^-$|]})?*+
To use a meta character as a normal character place a '\' in front of it, or place it between '\Q' (starts a quote) and '\E' (ends a quote). (All ' characters in this info should be omitted in the pattern.)
[abc] == a, b, or c matches
[^abc] == any character other than a, b, or c matches
[a-zA-Z] == any character (a through z) small or large case matches
[a-d[m-p]] == [a-dm-p] == a through d, or m through p matches (UNION)
[a-z&&[def]] == [def] == d, e, or f matches (INTERSECTION)
[bcr]at == b, c, or r followed by 'a' and then 't' matches (bat, cat, rat)
. == any character at all matches (may or may not match line terminators)
\d == [^\D] == any digit matches
\s == [^\S] == any whitespace character matches (\t, \n, \x0B, \f, \r)
\w == [a-zA-Z_0-9] == [^\W] any word character matches
--== Quantifiers ==--
x? == matches x once or not at all
x* == matches x zero or more times
x+ == matches x one or more times
x{n} == matches x exactly n times
x{n,} == matches x at least n or more times
x{n,m} == matches x at least n but not more than m times
(abc)* or (abc){n,m} == matches the text inside the braces using the following quantifier
The above quantifiers are all "greedy" meaning they start by trying to consume the whole input string before slowly narrowing down until a match is found (the biggest possible match is found).
Placing a '?' after the quantifier makes it "reluctant" meaning that a match is found by trying to consume as little as possible until a match is found (the smallest possible match is found).
Placing a '+' after the quantifier makes it "possessive" meaning that the whole input string is consumed and either a match is found or it fails.
--== Groups ==--
(abc) == is a group that matches a followed by b followed by c
(abc)(123) == has two groups that match abc then 123 (group #1 is abc and group #2 is 123)
(abc)\1 == has one group that matches abc followed by another abc (the \1 references the group number to replace the \# with)
--== Boundary ==--
^ == the beginning of a line
$ == the end of a line
\b == [^\B] == a word boundary (eg: \bdog\b has a match for "the dog" but not "thedog")
\A == beginning of the input
\G == end of the previous match (note: "dogdog" matches "dogdogdog" only once - the first occurance, so \G is not needed to ensure that there aren't two matches in this case)
\Z == end of the input except for any final terminator
\z == end of the input
--== Flags ==--
(?i) == use case insensitive matching (CASE_INSENSITIVE)
(?x) == allow comments and ignore whitespace (allows you to break down your pattern for easier reading) - comments start with # and go to the end of the line (COMMENTS)
(?s) == allows '.' to match everything including line terminators (DOTALL)
(?m) == allows '^' and '$' to match just before and just after (respectively) line terminators and the end of the input, not just the end of the input (MULTILINE)
(?u) == enables unicode case folding (UNICODE_CASE)
(?d) == enables unix line mode where ONLY '\n' is recognized in the behavior of '.', '^', and '$' (UNIX_LINES)
* </pre></p>
*/
public class RegexTestHarness {
public static void main(String[] args) {
try {
// Pattern pattern = Pattern.compile(args[0]);
// Matcher matcher = pattern.matcher(StreamSupport.readText(new File(args[1]), "UTF8"));
// boolean found = false;
//
// while(matcher.find()) {
// System.out.println("Found the text: '" + matcher.group() + "' at (" + matcher.start() + "," + matcher.end() + ").");
// found = true;
// }//while//
//
// if(!found) {
// System.out.println("No matches found.");
// }//if//
Pattern pattern = Pattern.compile("(?s)(/\\*)(.)*?(\\*/)");
Matcher matcher = pattern.matcher(StreamSupport.readText(new File(args[1]), "UTF8"));
boolean found = false;
while(matcher.find()) {
String comment = matcher.group();
Pattern commentStartPattern = Pattern.compile("/\\*[\\*\\s]*?");
Pattern commentEndPattern = Pattern.compile("[\\*\\s]*?\\*/");
Pattern commentLineStartPattern = Pattern.compile("(?m)^[\\*\\s]*");
Pattern commentLineEndPattern = Pattern.compile("(?m)\\s*$");
Matcher commentMatcher = null;
//Strip the comment characters from the comment so we just have the block of text.//
commentMatcher = commentStartPattern.matcher(comment);
comment = commentMatcher.replaceFirst("");
commentMatcher = commentEndPattern.matcher(comment);
comment = commentMatcher.replaceFirst("");
commentMatcher = commentLineStartPattern.matcher(comment);
comment = commentMatcher.replaceAll("");
commentMatcher = commentLineEndPattern.matcher(comment);
comment = commentMatcher.replaceAll("");
//comment = comment.replaceAll("(?m)^", " * ");
System.out.println("Found the text: '" + matcher.group() + "' at (" + matcher.start() + "," + matcher.end() + ").");
System.out.println("Converted the comment to: '" + comment + "'.");
found = true;
Pattern p = Pattern.compile("results will ensue\\.</b></p>\\r\\n@param");
Matcher m = p.matcher(comment);
if(m.find()) {
System.out.println("Found match.");
}
else {
System.out.println("No match.");
}
}//while//
if(!found) {
System.out.println("No matches found.");
}//if//
// Pattern pattern = Pattern.compile("results will ensue");
// Matcher matcher = pattern.matcher("Notifies the longest blocked thread that it can run again.\n" +
//"<p><b>Warning: This method actually calls wait on the calling thread's Thread object. If used, the application may not use thread objects for calling wait/notify/notifyAll otherwise unexpected results will ensue.</b></p>\n" +
//"@param object The object whose monitor the waiting thread to be unblocked will have waited on.");
// boolean found = false;
//
// while(matcher.find()) {
// System.out.println("Found match");
// found = true;
// }//while//
//
// if(!found) {
// System.out.println("No matches found.");
// }//if//
// Pattern pattern = Pattern.compile("(?m)^([ \\t\\x0B])*\\*\\1*(Copyright)\\1*((Declarative Engineering LLC)?(Software Zealot)?(Wynne Crisman)?)\\1*(\\d+)\\1*([,\\- ]\\1*(\\d+))?\\1*(<p>)?\\1*");
// Matcher matcher = pattern.matcher("/*\n * Copyright Declarative Engineering LLC 2005,2009<p>\n */");
// boolean found = false;
//
// while(matcher.find()) {
// System.out.println("Found the text: '" + matcher.group() + "' at (" + matcher.start() + "," + matcher.end() + ").");
// System.out.println("Start Year: " + matcher.group(7) + " End Year: " + matcher.group(9));
// found = true;
// }//while//
//
// if(!found) {
// System.out.println("No matches found.");
// }//if//
}//try//
catch(Throwable e) {
e.printStackTrace();
}//catch//
}//main()//
}//RegexTestHarness//

View File

@@ -0,0 +1,156 @@
package snippets.ssl;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
/**
* Copyright Declarative Engineering LLC 2008<p>
*/
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
try {
String protocol = "TLS";
String keyStorePath = "./.keystore";
String keyStorePassword = "123456";
String keyPassword = "abcdefg";
KeyStore keyStore = KeyStore.getInstance("JKS");
KeyManagerFactory keyManagerFactory;
int inputSize = 20;
byte[] input = new byte[inputSize];
for(int index = 0; index < inputSize; index++) {
input[index] = (byte) index;
}//for//
keyStore.load(new FileInputStream(keyStorePath), keyStorePassword.toCharArray());
keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(keyStore, keyPassword.toCharArray());
SSLContext serverSslContext = SSLContext.getInstance(protocol);
serverSslContext.init(keyManagerFactory.getKeyManagers(), null, null);
SSLContext clientSslContext = SSLContext.getInstance(protocol);
System.out.println("TrustManager algorithm: " + TrustManagerFactory.getDefaultAlgorithm());
clientSslContext.init(null, new X509TrustManager[] {new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
}}, null);
SSLEngine serverEngine = serverSslContext.createSSLEngine();
serverEngine.setUseClientMode(false);
SSLEngine clientEngine = clientSslContext.createSSLEngine();
clientEngine.setUseClientMode(true);
serverEngine.beginHandshake();
clientEngine.beginHandshake();
String[] supportedCipherSuites = serverEngine.getSupportedCipherSuites();
System.out.println("Supported Cipher Suites:");
for(int index = 0; index < supportedCipherSuites.length; index++) {
if(index != 0) {
System.out.print(", ");
}
System.out.print(supportedCipherSuites[index]);
}
System.out.println();
String[] supportedProtocols = serverEngine.getSupportedProtocols();
System.out.println("Supported Protocols:");
for(int index = 0; index < supportedProtocols.length; index++) {
if(index != 0) {
System.out.print(", ");
}
System.out.print(supportedProtocols[index]);
}
System.out.println();
serverEngine.setWantClientAuth(false);
clientEngine.setWantClientAuth(false);
serverEngine.setNeedClientAuth(false);
clientEngine.setNeedClientAuth(false);
while(serverEngine.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING && clientEngine.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
if(serverEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_TASK) {
System.out.println("Server running task.");
serverEngine.getDelegatedTask().run();
}//if//
else if(clientEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_TASK) {
System.out.println("Client running task.");
clientEngine.getDelegatedTask().run();
}//else if//
else if(serverEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_WRAP) {
ByteBuffer handshake = ByteBuffer.allocate(serverEngine.getSession().getPacketBufferSize());
ByteBuffer decrypted = ByteBuffer.allocate(clientEngine.getSession().getApplicationBufferSize());
System.out.println("Server wrapping handshake data.");
serverEngine.wrap(ByteBuffer.allocate(0), handshake);
handshake.flip();
while(clientEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_UNWRAP && handshake.hasRemaining()) {
System.out.println("Client unwrapping handshake data.");
clientEngine.unwrap(handshake, decrypted);
}//while//
}//else if//
else if(clientEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_WRAP) {
ByteBuffer handshake = ByteBuffer.allocate(clientEngine.getSession().getPacketBufferSize());
ByteBuffer decrypted = ByteBuffer.allocate(serverEngine.getSession().getApplicationBufferSize());
System.out.println("Client wrapping handshake data.");
clientEngine.wrap(ByteBuffer.allocate(0), handshake);
handshake.flip();
while(serverEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_UNWRAP && handshake.hasRemaining()) {
System.out.println("Server unwrapping handshake data.");
serverEngine.unwrap(handshake, decrypted);
}//while//
}//else if//
else {
System.out.println("Unexpected state.");
}//else//
}//while//
{
ByteBuffer encrypted = ByteBuffer.allocate(clientEngine.getSession().getPacketBufferSize());
ByteBuffer decrypted = ByteBuffer.allocate(serverEngine.getSession().getApplicationBufferSize());
decrypted.put(input);
decrypted.flip();
clientEngine.wrap(decrypted, encrypted);
System.out.println("Encrypted position: " + encrypted.position());
System.out.println("Encrypted limit: " + encrypted.limit());
decrypted.clear();
encrypted.flip();
serverEngine.unwrap(encrypted, decrypted);
System.out.println("Decrypted position: " + decrypted.position());
System.out.println("Decrypted limit: " + decrypted.limit());
decrypted.flip();
while(decrypted.hasRemaining()) {
System.out.print(decrypted.get() + " ");
}//while//
}
}//try//
catch(Throwable e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,258 @@
package snippets.swt;
import java.awt.EventQueue;
import java.io.File;
import java.util.Date;
import javax.swing.*;
import javax.swing.table.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.awt.SWT_AWT;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
public class AWT {
static class FileTableModel extends AbstractTableModel {
File[] files;
String[] columnsName = {"Name", "Size", "Date Modified"};
public FileTableModel (File[] files) {
this.files = files;
}
public int getColumnCount () {
return columnsName.length;
}
public Class getColumnClass (int col) {
if (col == 1) return Long.class;
if (col == 2) return Date.class;
return String.class;
}
public int getRowCount () {
return files == null ? 0 : files.length;
}
public Object getValueAt (int row, int col) {
if (col == 0) return files[row].getName();
if (col == 1) return new Long(files[row].length());
if (col == 2) return new Date(files[row].lastModified());
return "";
}
public String getColumnName (int col) {
return columnsName[col];
}
}
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("SWT and Swing/AWT Example");
Listener exitListener = new Listener() {
public void handleEvent(Event e) {
MessageBox dialog = new MessageBox(shell, SWT.OK | SWT.CANCEL | SWT.ICON_QUESTION);
dialog.setText("Question");
dialog.setMessage("Exit?");
if (e.type == SWT.Close) e.doit = false;
if (dialog.open() != SWT.OK) return;
shell.dispose();
}
};
Listener aboutListener = new Listener() {
public void handleEvent(Event e) {
final Shell s = new Shell(shell, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
s.setText("About");
GridLayout layout = new GridLayout(1, false);
layout.verticalSpacing = 20;
layout.marginHeight = layout.marginWidth = 10;
s.setLayout(layout);
Label label = new Label(s, SWT.NONE);
label.setText("SWT and AWT Example.");
Button button = new Button(s, SWT.PUSH);
button.setText("OK");
GridData data = new GridData();
data.horizontalAlignment = GridData.CENTER;
button.setLayoutData(data);
button.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
s.dispose();
}
});
s.pack();
Rectangle parentBounds = shell.getBounds();
Rectangle bounds = s.getBounds();
int x = parentBounds.x + (parentBounds.width - bounds.width) / 2;
int y = parentBounds.y + (parentBounds.height - bounds.height) / 2;
s.setLocation(x, y);
s.open();
while (!s.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
}
};
shell.addListener(SWT.Close, exitListener);
Menu mb = new Menu(shell, SWT.BAR);
MenuItem fileItem = new MenuItem(mb, SWT.CASCADE);
fileItem.setText("&File");
Menu fileMenu = new Menu(shell, SWT.DROP_DOWN);
fileItem.setMenu(fileMenu);
MenuItem exitItem = new MenuItem(fileMenu, SWT.PUSH);
exitItem.setText("&Exit\tCtrl+X");
exitItem.setAccelerator(SWT.CONTROL + 'X');
exitItem.addListener(SWT.Selection, exitListener);
MenuItem aboutItem = new MenuItem(fileMenu, SWT.PUSH);
aboutItem.setText("&About\tCtrl+A");
aboutItem.setAccelerator(SWT.CONTROL + 'A');
aboutItem.addListener(SWT.Selection, aboutListener);
shell.setMenuBar(mb);
RGB color = shell.getBackground().getRGB();
Label separator1 = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
Label locationLb = new Label(shell, SWT.NONE);
locationLb.setText("Location:");
Composite locationComp = new Composite(shell, SWT.EMBEDDED);
ToolBar toolBar = new ToolBar(shell, SWT.FLAT);
ToolItem exitToolItem = new ToolItem(toolBar, SWT.PUSH);
exitToolItem.setText("&Exit");
exitToolItem.addListener(SWT.Selection, exitListener);
ToolItem aboutToolItem = new ToolItem(toolBar, SWT.PUSH);
aboutToolItem.setText("&About");
aboutToolItem.addListener(SWT.Selection, aboutListener);
Label separator2 = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
final Composite comp = new Composite(shell, SWT.NONE);
final Tree fileTree = new Tree(comp, SWT.SINGLE | SWT.BORDER);
Sash sash = new Sash(comp, SWT.VERTICAL);
Composite tableComp = new Composite(comp, SWT.EMBEDDED);
Label separator3 = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
Composite statusComp = new Composite(shell, SWT.EMBEDDED);
java.awt.Frame locationFrame = SWT_AWT.new_Frame(locationComp);
final java.awt.TextField locationText = new java.awt.TextField();
locationFrame.add(locationText);
java.awt.Frame fileTableFrame = SWT_AWT.new_Frame(tableComp);
java.awt.Panel panel = new java.awt.Panel(new java.awt.BorderLayout());
fileTableFrame.add(panel);
final JTable fileTable = new JTable(new FileTableModel(null));
fileTable.setDoubleBuffered(true);
fileTable.setShowGrid(false);
fileTable.createDefaultColumnsFromModel();
JScrollPane scrollPane = new JScrollPane(fileTable);
panel.add(scrollPane);
java.awt.Frame statusFrame = SWT_AWT.new_Frame(statusComp);
statusFrame.setBackground(new java.awt.Color(color.red, color.green, color.blue));
final java.awt.Label statusLabel = new java.awt.Label();
statusFrame.add(statusLabel);
statusLabel.setText("Select a file");
sash.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
if (e.detail == SWT.DRAG) return;
GridData data = (GridData)fileTree.getLayoutData();
Rectangle trim = fileTree.computeTrim(0, 0, 0, 0);
data.widthHint = e.x - trim.width;
comp.layout();
}
});
File[] roots = File.listRoots();
for (int i = 0; i < roots.length; i++) {
File file = roots[i];
TreeItem treeItem = new TreeItem(fileTree, SWT.NONE);
treeItem.setText(file.getAbsolutePath());
treeItem.setData(file);
new TreeItem(treeItem, SWT.NONE);
}
fileTree.addListener(SWT.Expand, new Listener() {
public void handleEvent(Event e) {
TreeItem item = (TreeItem)e.item;
if (item == null) return;
if (item.getItemCount() == 1) {
TreeItem firstItem = item.getItems()[0];
if (firstItem.getData() != null) return;
firstItem.dispose();
} else {
return;
}
File root = (File)item.getData();
File[] files = root.listFiles();
if (files == null) return;
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isDirectory()) {
TreeItem treeItem = new TreeItem(item, SWT.NONE);
treeItem.setText(file.getName());
treeItem.setData(file);
new TreeItem(treeItem, SWT.NONE);
}
}
}
});
fileTree.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
TreeItem item = (TreeItem)e.item;
if (item == null) return;
final File root = (File)item.getData();
EventQueue.invokeLater(new Runnable() {
public void run() {
statusLabel.setText(root.getAbsolutePath());
locationText.setText(root.getAbsolutePath());
fileTable.setModel(new FileTableModel(root.listFiles()));
}
});
}
});
GridLayout layout = new GridLayout(4, false);
layout.marginWidth = layout.marginHeight = 0;
layout.horizontalSpacing = layout.verticalSpacing = 1;
shell.setLayout(layout);
GridData data;
data = new GridData(GridData.FILL_HORIZONTAL);
data.horizontalSpan = 4;
separator1.setLayoutData(data);
data = new GridData();
data.horizontalSpan = 1;
data.horizontalIndent = 10;
locationLb.setLayoutData(data);
data = new GridData(GridData.FILL_HORIZONTAL);
data.horizontalSpan = 2;
data.heightHint = locationText.getPreferredSize().height;
locationComp.setLayoutData(data);
data = new GridData(GridData.FILL_HORIZONTAL);
data.horizontalSpan = 1;
toolBar.setLayoutData(data);
data = new GridData(GridData.FILL_HORIZONTAL);
data.horizontalSpan = 4;
separator2.setLayoutData(data);
data = new GridData(GridData.FILL_BOTH);
data.horizontalSpan = 4;
comp.setLayoutData(data);
data = new GridData(GridData.FILL_HORIZONTAL);
data.horizontalSpan = 4;
separator3.setLayoutData(data);
data = new GridData(GridData.FILL_HORIZONTAL);
data.horizontalSpan = 4;
data.heightHint = statusLabel.getPreferredSize().height;
statusComp.setLayoutData(data);
layout = new GridLayout(3, false);
layout.marginWidth = layout.marginHeight = 0;
layout.horizontalSpacing = layout.verticalSpacing = 1;
comp.setLayout(layout);
data = new GridData(GridData.FILL_VERTICAL);
data.widthHint = 200;
fileTree.setLayoutData(data);
data = new GridData(GridData.FILL_VERTICAL);
sash.setLayoutData(data);
data = new GridData(GridData.FILL_BOTH);
tableComp.setLayoutData(data);
shell.open();
while(!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
display.dispose();
}
}

View File

@@ -0,0 +1,104 @@
package snippets.swt;
import org.eclipse.swt.*;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Pattern;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.*;
/**
* Copyright Declarative Engineering LLC 2009<p>
*/
public class BackgroundGradient {
public static final int HORIZONTAL = 0;
public static final int VERTICAL = 1;
public static final int DIAGONAL = 2;
public static final int REVERSE_DIAGONAL = 3;
static Image image = null;
/**
* @param args
*/
public static void main(String[] args) {
final Display display = new Display ();
Shell shell = new Shell (display);
Button button = new Button(shell, 0); //SWT.INHERIT_FORCE | SWT.NO_BACKGROUND
final Control control = shell; //Allow test to use other controls for the background testing.//
FillLayout layout = new FillLayout();
layout.marginHeight = 30;
layout.marginWidth = 30;
button.setText("HELLO");
shell.setLayout(layout);
//shell.setSize(100, 100);
shell.pack();
// shell.addListener(SWT.Paint, new Listener () {
// public void handleEvent (Event e) {
// GC gc = e.gc;
// Rectangle clientArea = control instanceof Composite ? ((Composite) control).getClientArea() : control.getBounds();
//
// if(clientArea.width > 0 && clientArea.height > 0) {
// Color c1 = display.getSystemColor(SWT.COLOR_RED);
// Color c2 = display.getSystemColor(SWT.COLOR_BLUE);
// int startAlpha = 100;
// int endAlpha = 200;
// int direction = REVERSE_DIAGONAL;
// Pattern pattern = new Pattern(display, (direction == REVERSE_DIAGONAL ? clientArea.width : 0), 0, (direction == VERTICAL ? 1 : direction == REVERSE_DIAGONAL ? 0 : clientArea.width), (direction == HORIZONTAL ? 1 : clientArea.height), c1, startAlpha, c2, endAlpha);
//
// //Force the x/y values to zero since getBounds uses them to provide the upper left point of the control.//
// clientArea.x = 0;
// clientArea.y = 0;
// gc.setBackgroundPattern(pattern);
// gc.fillRectangle(clientArea);
//
// pattern.dispose();
// }//if//
// }
// });
Listener listener;
shell.addListener(SWT.Resize, listener = new Listener () {
public void handleEvent (Event e) {
Rectangle clientArea = control instanceof Composite ? ((Composite) control).getClientArea() : control.getBounds();
if(clientArea.width > 0 && clientArea.height > 0) {
Color c1 = display.getSystemColor(SWT.COLOR_RED);
Color c2 = display.getSystemColor(SWT.COLOR_BLUE);
int startAlpha = 100;
int endAlpha = 200;
int direction = REVERSE_DIAGONAL;
Pattern pattern = new Pattern(display, (direction == REVERSE_DIAGONAL ? clientArea.width : 0), 0, (direction == VERTICAL ? 1 : direction == REVERSE_DIAGONAL ? 0 : clientArea.width), (direction == HORIZONTAL ? 1 : clientArea.height), c1, startAlpha, c2, endAlpha);
if(image != null) {
image.dispose();
}//if//
image = new Image(display, clientArea.width, clientArea.height);
GC gc = new GC(image);
//Force the x/y values to zero since getBounds uses them to provide the upper left point of the control.//
clientArea.x = 0;
clientArea.y = 0;
gc.setBackgroundPattern(pattern);
gc.fillRectangle(clientArea);
control.setBackgroundImage(image);
//image.dispose();
pattern.dispose();
}//if//
else if(image != null) {
image.dispose();
control.setBackgroundImage(null);
}//else if//
}
});
listener.handleEvent(null);
shell.open ();
while (!shell.isDisposed()) {
if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose ();
}
}

View File

@@ -0,0 +1,65 @@
package snippets.swt;
import org.eclipse.swt.*;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Pattern;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.*;
/**
* Copyright Declarative Engineering LLC 2009<p>
*/
public class GridLayoutBugDemo {
/**
* @param args
*/
public static void main(String[] args) {
final Display display = new Display ();
final Shell shell = new Shell (display);
Composite c = new Composite(shell, 0);
Composite c2 = new Composite(c, 0);
Link l1 = new Link(c2, 0);
Link l2 = new Link(c2, 0);
Link l3 = new Link(c2, 0);
Table b1 = new Table(c, SWT.BORDER);
FillLayout fillLayout;
RowLayout rowLayout;
GridData data;
shell.setVisible(false);
shell.setLayoutDeferred(true);
shell.setLayout(fillLayout = new FillLayout());
fillLayout.marginHeight = 3;
fillLayout.marginWidth = 3;
c.setLayout(new GridLayout(1, false));
c2.setLayoutData(new GridData(SWT.FILL, SWT.END, true, false));
c2.setLayout(rowLayout = new RowLayout(SWT.HORIZONTAL));
rowLayout.wrap = false;
rowLayout.pack = true;
rowLayout.spacing = 10;
l1.setText("<a>Link1</a>");
l2.setText("<a>Link2</a>");
l3.setText("<a>Link3</a>");
b1.setLayoutData(data = new GridData(SWT.FILL, SWT.FILL, true, true));
data.heightHint = 200;
data.widthHint = 200;
data.minimumHeight = 200;
data.minimumWidth = 200;
shell.setLayoutDeferred(false);
shell.layout(true, true);
shell.pack(true);
shell.setVisible(true);
while(!shell.isDisposed()) {
if(!display.readAndDispatch()) display.sleep();
}
display.dispose();
}
}

View File

@@ -0,0 +1,49 @@
package snippets.swt;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
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.widgets.Text;
import com.foundation.view.swt.layout.GridData;
import com.foundation.view.swt.layout.GridLayout;
public class SashTest {
/**
* @param args
*/
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
SashForm sashForm = new SashForm(shell, SWT.VERTICAL);
Color red = display.getSystemColor(SWT.COLOR_RED);
Color blue = display.getSystemColor(SWT.COLOR_BLUE);
Color green = display.getSystemColor(SWT.COLOR_GREEN);
Composite c1 = new Composite(sashForm, 0);
Composite c2 = new Composite(sashForm, 0);
Composite c3 = new Composite(sashForm, 0);
shell.setLayout(new FillLayout());
sashForm.setWeights(new int[] {30, 20, 70});
c1.setBackground(red);
c2.setBackground(blue);
c3.setBackground(green);
shell.setSize(400, 400);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}

View File

@@ -0,0 +1,119 @@
package snippets.swt;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.PaintObjectEvent;
import org.eclipse.swt.custom.PaintObjectListener;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.GlyphMetrics;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class StyledTextAndControls {
static StyledText styledText;
static String text =
"This snippet shows how to embed widgets in a StyledText.\n"+
"Here is one: \uFFFC, and here is another: \uFFFC.";
static int[] offsets;
static Control[] controls;
static int MARGIN = 5;
static void addControl(Control control, int offset) {
StyleRange style = new StyleRange ();
style.start = offset;
style.length = 1;
control.pack();
Rectangle rect = control.getBounds();
int ascent = 2*rect.height/3;
int descent = rect.height - ascent;
style.metrics = new GlyphMetrics(ascent + MARGIN, descent + MARGIN, rect.width + 2*MARGIN);
styledText.setStyleRange(style);
}
public static void main(String[] args) {
final Display display = new Display();
Font font = new Font(display, "Tahoma", 32, SWT.NORMAL);
final Shell shell = new Shell(display);
shell.setLayout(new GridLayout());
styledText = new StyledText(shell, SWT.WRAP | SWT.BORDER);
styledText.setFont(font);
styledText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
styledText.setText(text);
controls = new Control[2];
Button button = new Button(styledText, SWT.PUSH);
button.setText("Button 1");
controls[0] = button;
Combo combo = new Combo(styledText, SWT.NONE);
combo.add("item 1");
combo.add("another item");
controls[1] = combo;
offsets = new int[controls.length];
int lastOffset = 0;
for (int i = 0; i < controls.length; i++) {
int offset = text.indexOf("\uFFFC", lastOffset);
offsets[i] = offset;
addControl(controls[i], offsets[i]);
lastOffset = offset + 1;
}
// use a verify listener to keep the offsets up to date
styledText.addVerifyListener(new VerifyListener() {
public void verifyText(VerifyEvent e) {
int start = e.start;
int replaceCharCount = e.end - e.start;
int newCharCount = e.text.length();
for (int i = 0; i < offsets.length; i++) {
int offset = offsets[i];
if (start <= offset && offset < start + replaceCharCount) {
// this widget is being deleted from the text
if (controls[i] != null && !controls[i].isDisposed()) {
controls[i].dispose();
controls[i] = null;
}
offset = -1;
}
if (offset != -1 && offset >= start) offset += newCharCount - replaceCharCount;
offsets[i] = offset;
}
}
});
// reposition widgets on paint event
styledText.addPaintObjectListener(new PaintObjectListener() {
public void paintObject(PaintObjectEvent event) {
StyleRange style = event.style;
int start = style.start;
for (int i = 0; i < offsets.length; i++) {
int offset = offsets[i];
if (start == offset) {
Point pt = controls[i].getSize();
int x = event.x + MARGIN;
int y = event.y + event.ascent - 2*pt.y/3;
controls[i].setLocation(x, y);
break;
}
}
}
});
shell.setSize(400, 400);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
font.dispose();
display.dispose();
}
}

View File

@@ -0,0 +1,134 @@
package snippets.swt;
import org.eclipse.swt.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.custom.*;
public class StyledTextAndImages {
static StyledText styledText;
static String text =
"This snippet shows how to embed images in a StyledText.\n"+
"Here is one: \uFFFC, and here is another: \uFFFC."+
"Use the add button to add an image from your filesystem to the StyledText at the current caret offset.";
static Image[] images;
static int[] offsets;
static void addImage(Image image, int offset) {
StyleRange style = new StyleRange ();
style.start = offset;
style.length = 1;
Rectangle rect = image.getBounds();
style.metrics = new GlyphMetrics(rect.height, 0, rect.width);
styledText.setStyleRange(style);
}
public static void main(String [] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new GridLayout());
styledText = new StyledText(shell, SWT.WRAP | SWT.BORDER);
styledText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
styledText.setText(text);
images = new Image[] {
display.getSystemImage(SWT.ICON_QUESTION),
display.getSystemImage(SWT.ICON_INFORMATION),
};
offsets = new int[images.length];
int lastOffset = 0;
for (int i = 0; i < images.length; i++) {
int offset = text.indexOf("\uFFFC", lastOffset);
offsets[i] = offset;
addImage(images[i], offset);
lastOffset = offset + 1;
}
// use a verify listener to keep the offsets up to date
styledText.addVerifyListener(new VerifyListener() {
public void verifyText(VerifyEvent e) {
int start = e.start;
int replaceCharCount = e.end - e.start;
int newCharCount = e.text.length();
for (int i = 0; i < offsets.length; i++) {
int offset = offsets[i];
if (start <= offset && offset < start + replaceCharCount) {
// this image is being deleted from the text
if (images[i] != null && !images[i].isDisposed()) {
images[i].dispose();
images[i] = null;
}
offset = -1;
}
if (offset != -1 && offset >= start) offset += newCharCount - replaceCharCount;
offsets[i] = offset;
}
}
});
styledText.addPaintObjectListener(new PaintObjectListener() {
public void paintObject(PaintObjectEvent event) {
GC gc = event.gc;
StyleRange style = event.style;
int start = style.start;
for (int i = 0; i < offsets.length; i++) {
int offset = offsets[i];
if (start == offset) {
Image image = images[i];
int x = event.x;
int y = event.y + event.ascent - style.metrics.ascent;
gc.drawImage(image, x, y);
}
}
}
});
Button button = new Button (shell, SWT.PUSH);
button.setText("Add Image");
button.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));
button.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
FileDialog dialog = new FileDialog(shell);
String filename = dialog.open();
if (filename != null) {
try {
Image image = new Image(display, filename);
int offset = styledText.getCaretOffset();
styledText.replaceTextRange(offset, 0, "\uFFFC");
int index = 0;
while (index < offsets.length) {
if (offsets[index] == -1 && images[index] == null) break;
index++;
}
if (index == offsets.length) {
int[] tmpOffsets = new int[index + 1];
System.arraycopy(offsets, 0, tmpOffsets, 0, offsets.length);
offsets = tmpOffsets;
Image[] tmpImages = new Image[index + 1];
System.arraycopy(images, 0, tmpImages, 0, images.length);
images = tmpImages;
}
offsets[index] = offset;
images[index] = image;
addImage(image, offset);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
shell.setSize(400, 400);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
for (int i = 0; i < images.length; i++) {
Image image = images[i];
if (image != null && !image.isDisposed()) {
image.dispose();
}
}
display.dispose();
}
}

View File

@@ -0,0 +1,75 @@
package snippets.swt;
import org.eclipse.swt.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/**
* Copyright Declarative Engineering LLC 2009<p>
*/
public class TableRowImage {
/**
* @param args
*/
public static void main(String[] args) {
Display display = new Display();
final Image image = display.getSystemImage(SWT.ICON_INFORMATION);
Shell shell = new Shell(display);
shell.setText("Images on the right side of the TableItem");
shell.setLayout(new FillLayout ());
Table table = new Table(shell, SWT.MULTI | SWT.FULL_SELECTION);
table.setHeaderVisible(true);
table.setLinesVisible(true);
int columnCount = 3;
for (int i=0; i<columnCount; i++) {
TableColumn column = new TableColumn(table, SWT.NONE);
column.setText("Column " + i);
}
int itemCount = 8;
for(int i = 0; i < itemCount; i++) {
TableItem item = new TableItem(table, SWT.NONE);
item.setText(new String[] {"item "+i+" a", "item "+i+" b", "item "+i+" c"});
}
/*
* NOTE: MeasureItem, PaintItem and EraseItem are called repeatedly.
* Therefore, it is critical for performance that these methods be
* as efficient as possible.
*/
Listener paintListener = new Listener() {
public void handleEvent(Event event) {
switch(event.type) {
case SWT.MeasureItem: {
Rectangle rect = image.getBounds();
event.width += rect.width;
event.height = Math.max(event.height, rect.height + 2);
break;
}
case SWT.PaintItem: {
int x = event.x + event.width;
Rectangle rect = image.getBounds();
int offset = Math.max(0, (event.height - rect.height) / 2);
event.gc.drawImage(image, x, event.y + offset);
break;
}
}
}
};
table.addListener(SWT.MeasureItem, paintListener);
table.addListener(SWT.PaintItem, paintListener);
for(int i = 0; i < columnCount; i++) {
table.getColumn(i).pack();
}
shell.setSize(500, 200);
shell.open();
while(!shell.isDisposed ()) {
if(!display.readAndDispatch()) display.sleep();
}
if(image != null) image.dispose();
display.dispose();
}
}

View File

@@ -0,0 +1,48 @@
package snippets.swt;
import org.eclipse.swt.*;
//import org.eclipse.swt.layout.*;
import com.foundation.view.swt.layout.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.custom.*;
public class TextHideAndColor {
static Text text;
public static void main(String [] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
GridLayout shellLayout = new GridLayout();
GridData layoutData = null;
Color red = display.getSystemColor(SWT.COLOR_RED);
shell.setLayout(shellLayout);
text = new Text(shell, SWT.BORDER | SWT.READ_ONLY);
text.setVisible(false);
layoutData = new GridData(SWT.FILL, SWT.CENTER, true, false);
text.setLayoutData(layoutData);
text.setForeground(null);
text.setText("10");
//text.setForeground(red);
Button button = new Button(shell, SWT.PUSH);
button.setText("Toggle Visibility");
button.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, false));
button.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
text.setVisible(!text.getVisible());
shell.layout();
}
});
shell.setSize(400, 400);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}

View File

@@ -0,0 +1,48 @@
package snippets.swt;
import org.eclipse.swt.*;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Pattern;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.*;
/**
* Copyright Declarative Engineering LLC 2009<p>
*/
public class Timer {
public static final int HORIZONTAL = 0;
public static final int VERTICAL = 1;
public static final int DIAGONAL = 2;
public static final int REVERSE_DIAGONAL = 3;
static Image image = null;
/**
* @param args
*/
public static void main(String[] args) {
final Display display = new Display ();
final Shell shell = new Shell (display);
shell.setSize(100, 100);
shell.open();
Runnable runnable = new Runnable() {
int counter = 1;
public void run() {
counter++;
shell.setBackground(display.getSystemColor(counter % 2 == 0 ? SWT.COLOR_BLUE : SWT.COLOR_RED));
}//run()//
};
display.timerExec(5000, runnable);
display.timerExec(10000, runnable);
display.timerExec(15000, runnable);
while(!shell.isDisposed()) {
if(!display.readAndDispatch()) display.sleep();
}
display.dispose ();
}
}

View File

@@ -0,0 +1,32 @@
package snippets.util;
import com.common.comparison.Comparator;
import com.common.util.LiteList;
import com.common.util.optimized.ObjectLongHashMap;
public class ObjectLongHashMapTest {
/**
* @param args
*/
public static void main(String[] args) {
ObjectLongHashMap map = new ObjectLongHashMap(10, Comparator.getIdentityComparator());
LiteList added = new LiteList(500, 1000);
int max = 1000;
for(int index = 0; index < max; index++) {
Object o = "Test " + index;
map.put(o, (long) index);
added.add(o);
}//for//
for(int index = 0; index < max; index++) {
String s = (String) added.get(index);
//long l = Long.parseLong(s.substring(s.lastIndexOf(' ')));
if(!map.containsKey(s)) {
System.out.println("error: " + index);
}//if//
}//for//
}
}

View File

@@ -0,0 +1,29 @@
package snippets.zip;
import java.io.File;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class ZipFileTest {
/**
* Runs a simple test of what java's zip code finds in the zip file.
* @param args Only one arg expected, the path to the zip to test with.
*/
public static void main(String[] args) {
File zipFile = new File(args[0]);
try {
ZipFile zip = new ZipFile(zipFile);
for(Enumeration entries = zip.entries(); entries.hasMoreElements();) {
ZipEntry next = (ZipEntry) entries.nextElement();
System.out.println("Entry: " + next.getName());
}//for//
}//try//
catch(Throwable e) {
e.printStackTrace();
}//catch//
}//main()//
}//ZipFileTest//