Browse Source

Mass format based on eclipse build in formatting style.

svn changeset:2461/svn branch:trunk
tags/6.7.0.beta1
Jani Laakso 16 years ago
parent
commit
5ba28731e9
100 changed files with 5617 additions and 5321 deletions
  1. 18
    10
      src/com/itmill/toolkit/Application.java
  2. 84
    89
      src/com/itmill/toolkit/demo/CalendarDemo.java
  3. 1
    1
      src/com/itmill/toolkit/demo/FilterSelect.java
  4. 22
    27
      src/com/itmill/toolkit/demo/KeyboardShortcut.java
  5. 6
    6
      src/com/itmill/toolkit/demo/colorpicker/ColorPicker.java
  6. 11
    10
      src/com/itmill/toolkit/demo/colorpicker/ColorPickerApplication.java
  7. 13
    13
      src/com/itmill/toolkit/demo/colorpicker/gwt/client/WidgetSet.java
  8. 35
    27
      src/com/itmill/toolkit/demo/colorpicker/gwt/client/ui/GwtColorPicker.java
  9. 10
    10
      src/com/itmill/toolkit/demo/colorpicker/gwt/client/ui/ItkColorPicker.java
  10. 2
    2
      src/com/itmill/toolkit/demo/features/Feature.java
  11. 13
    13
      src/com/itmill/toolkit/demo/features/FeatureBrowser.java
  12. 6
    5
      src/com/itmill/toolkit/demo/features/FeatureDateField.java
  13. 1
    1
      src/com/itmill/toolkit/demo/features/FeaturesApplication.java
  14. 3
    3
      src/com/itmill/toolkit/demo/features/PropertyPanel.java
  15. 201
    201
      src/com/itmill/toolkit/demo/reservation/GoogleMap.java
  16. 245
    244
      src/com/itmill/toolkit/demo/reservation/ReservationApplication.java
  17. 1
    1
      src/com/itmill/toolkit/demo/reservation/ResourceNotAvailableException.java
  18. 86
    86
      src/com/itmill/toolkit/demo/reservation/ResourceSelectorPanel.java
  19. 468
    433
      src/com/itmill/toolkit/demo/reservation/SampleDB.java
  20. 18
    18
      src/com/itmill/toolkit/demo/reservation/gwt/client/WidgetSet.java
  21. 67
    66
      src/com/itmill/toolkit/demo/reservation/gwt/client/ui/IGoogleMap.java
  22. 134
    132
      src/com/itmill/toolkit/demo/util/SampleCalendarDatabase.java
  23. 5
    5
      src/com/itmill/toolkit/terminal/PaintTarget.java
  24. 9
    9
      src/com/itmill/toolkit/terminal/gwt/client/ApplicationConnection.java
  25. 51
    44
      src/com/itmill/toolkit/terminal/gwt/client/Caption.java
  26. 4
    4
      src/com/itmill/toolkit/terminal/gwt/client/CaptionWrapper.java
  27. 21
    14
      src/com/itmill/toolkit/terminal/gwt/client/DateLocale.java
  28. 234
    234
      src/com/itmill/toolkit/terminal/gwt/client/DateTimeService.java
  29. 19
    11
      src/com/itmill/toolkit/terminal/gwt/client/DebugConsole.java
  30. 208
    208
      src/com/itmill/toolkit/terminal/gwt/client/DefaultWidgetSet.java
  31. 2
    1
      src/com/itmill/toolkit/terminal/gwt/client/ErrorMessage.java
  32. 1
    1
      src/com/itmill/toolkit/terminal/gwt/client/LocaleNotLoadedException.java
  33. 103
    85
      src/com/itmill/toolkit/terminal/gwt/client/LocaleService.java
  34. 3
    3
      src/com/itmill/toolkit/terminal/gwt/client/NullConsole.java
  35. 17
    14
      src/com/itmill/toolkit/terminal/gwt/client/UIDL.java
  36. 4
    3
      src/com/itmill/toolkit/terminal/gwt/client/Util.java
  37. 14
    7
      src/com/itmill/toolkit/terminal/gwt/client/WidgetSet.java
  38. 102
    101
      src/com/itmill/toolkit/terminal/gwt/client/ui/CalendarEntry.java
  39. 347
    338
      src/com/itmill/toolkit/terminal/gwt/client/ui/CalendarPanel.java
  40. 17
    15
      src/com/itmill/toolkit/terminal/gwt/client/ui/ContextMenu.java
  41. 6
    6
      src/com/itmill/toolkit/terminal/gwt/client/ui/HorizontalSplitPanelImages.java
  42. 30
    26
      src/com/itmill/toolkit/terminal/gwt/client/ui/IButton.java
  43. 149
    149
      src/com/itmill/toolkit/terminal/gwt/client/ui/ICalendar.java
  44. 4
    4
      src/com/itmill/toolkit/terminal/gwt/client/ui/ICheckBox.java
  45. 5
    5
      src/com/itmill/toolkit/terminal/gwt/client/ui/ICustomComponent.java
  46. 27
    19
      src/com/itmill/toolkit/terminal/gwt/client/ui/ICustomLayout.java
  47. 61
    51
      src/com/itmill/toolkit/terminal/gwt/client/ui/IDateField.java
  48. 4
    4
      src/com/itmill/toolkit/terminal/gwt/client/ui/IDateFieldCalendar.java
  49. 18
    13
      src/com/itmill/toolkit/terminal/gwt/client/ui/IEmbedded.java
  50. 6
    3
      src/com/itmill/toolkit/terminal/gwt/client/ui/IExpandLayout.java
  51. 16
    15
      src/com/itmill/toolkit/terminal/gwt/client/ui/IFilterSelect.java
  52. 6
    7
      src/com/itmill/toolkit/terminal/gwt/client/ui/IForm.java
  53. 15
    15
      src/com/itmill/toolkit/terminal/gwt/client/ui/IFormLayout.java
  54. 17
    18
      src/com/itmill/toolkit/terminal/gwt/client/ui/IGridLayout.java
  55. 3
    3
      src/com/itmill/toolkit/terminal/gwt/client/ui/ILabel.java
  56. 29
    28
      src/com/itmill/toolkit/terminal/gwt/client/ui/ILink.java
  57. 20
    14
      src/com/itmill/toolkit/terminal/gwt/client/ui/IOptionGroup.java
  58. 50
    46
      src/com/itmill/toolkit/terminal/gwt/client/ui/IOptionGroupBase.java
  59. 52
    47
      src/com/itmill/toolkit/terminal/gwt/client/ui/IOrderedLayout.java
  60. 3
    3
      src/com/itmill/toolkit/terminal/gwt/client/ui/IOrderedLayoutHorizontal.java
  61. 3
    3
      src/com/itmill/toolkit/terminal/gwt/client/ui/IOrderedLayoutVertical.java
  62. 5
    5
      src/com/itmill/toolkit/terminal/gwt/client/ui/IPanel.java
  63. 3
    3
      src/com/itmill/toolkit/terminal/gwt/client/ui/IPasswordField.java
  64. 27
    25
      src/com/itmill/toolkit/terminal/gwt/client/ui/IPopupCalendar.java
  65. 9
    9
      src/com/itmill/toolkit/terminal/gwt/client/ui/IProgressIndicator.java
  66. 8
    8
      src/com/itmill/toolkit/terminal/gwt/client/ui/IScrollTable.java
  67. 21
    17
      src/com/itmill/toolkit/terminal/gwt/client/ui/ISelect.java
  68. 5
    6
      src/com/itmill/toolkit/terminal/gwt/client/ui/ISplitPanel.java
  69. 37
    33
      src/com/itmill/toolkit/terminal/gwt/client/ui/ITabsheet.java
  70. 80
    76
      src/com/itmill/toolkit/terminal/gwt/client/ui/ITabsheetPanel.java
  71. 5
    5
      src/com/itmill/toolkit/terminal/gwt/client/ui/ITextArea.java
  72. 21
    22
      src/com/itmill/toolkit/terminal/gwt/client/ui/ITextField.java
  73. 115
    79
      src/com/itmill/toolkit/terminal/gwt/client/ui/ITextualDate.java
  74. 42
    37
      src/com/itmill/toolkit/terminal/gwt/client/ui/ITwinColSelect.java
  75. 5
    5
      src/com/itmill/toolkit/terminal/gwt/client/ui/IUnknownComponent.java
  76. 2
    2
      src/com/itmill/toolkit/terminal/gwt/client/ui/IUpload.java
  77. 31
    29
      src/com/itmill/toolkit/terminal/gwt/client/ui/IView.java
  78. 12
    13
      src/com/itmill/toolkit/terminal/gwt/client/ui/IWindow.java
  79. 452
    431
      src/com/itmill/toolkit/terminal/gwt/client/ui/MenuBar.java
  80. 150
    136
      src/com/itmill/toolkit/terminal/gwt/client/ui/MenuItem.java
  81. 135
    116
      src/com/itmill/toolkit/terminal/gwt/client/ui/Time.java
  82. 10
    15
      src/com/itmill/toolkit/terminal/gwt/client/ui/TreeAction.java
  83. 5
    5
      src/com/itmill/toolkit/terminal/gwt/client/ui/VerticalSplitPanelImages.java
  84. 28
    27
      src/com/itmill/toolkit/terminal/gwt/client/util/DateLocale.java
  85. 61
    46
      src/com/itmill/toolkit/terminal/gwt/client/util/Pattern.java
  86. 24
    23
      src/com/itmill/toolkit/terminal/gwt/client/util/SimpleDateFormat.java
  87. 60
    48
      src/com/itmill/toolkit/terminal/gwt/client/util/SimpleDateParser.java
  88. 983
    983
      src/com/itmill/toolkit/terminal/gwt/server/ApplicationServlet.java
  89. 11
    21
      src/com/itmill/toolkit/terminal/gwt/server/CommunicationManager.java
  90. 29
    26
      src/com/itmill/toolkit/terminal/gwt/server/JsonPaintTarget.java
  91. 5
    5
      src/com/itmill/toolkit/terminal/gwt/server/Log.java
  92. 11
    8
      src/com/itmill/toolkit/terminal/gwt/server/WebApplicationContext.java
  93. 17
    11
      src/com/itmill/toolkit/terminal/gwt/server/WebBrowser.java
  94. 19
    15
      src/com/itmill/toolkit/tests/BasicRandomTest.java
  95. 8
    6
      src/com/itmill/toolkit/tests/RandomLayoutStress.java
  96. 3
    3
      src/com/itmill/toolkit/tests/TestBench.java
  97. 4
    4
      src/com/itmill/toolkit/tests/TestForApplicationLayoutThatUsesWholeBrosersSpace.java
  98. 26
    23
      src/com/itmill/toolkit/tests/TestForBasicApplicationLayout.java
  99. 18
    21
      src/com/itmill/toolkit/tests/TestForChildComponentRendering.java
  100. 0
    0
      src/com/itmill/toolkit/tests/TestForGridLayoutChildComponentRendering.java

+ 18
- 10
src/com/itmill/toolkit/Application.java View File

@@ -199,17 +199,23 @@ public abstract class Application implements URIHandler, Terminal.ErrorListener
* not running or it does not contain a window corresponding to the name.
* </p>
*
* <p>Since version 5.0 all windows can be referenced by their names in
* url <code>http://host:port/foo/bar/</code> where <code>http://host:port/foo/</code>
* is the application url as returned by getURL() and <code>bar</code> is the name
* of the window.</p>
* <p>
* Since version 5.0 all windows can be referenced by their names in url
* <code>http://host:port/foo/bar/</code> where
* <code>http://host:port/foo/</code> is the application url as returned
* by getURL() and <code>bar</code> is the name of the window.
* </p>
*
* <p>One should note that this method can, as a side effect create new windows
* if needed by the application. This can be achieved by overriding the default
* implementation.</p>
* <p>
* One should note that this method can, as a side effect create new windows
* if needed by the application. This can be achieved by overriding the
* default implementation.
* </p>
*
* <p>The method should return null if the window does not exists (and is not
* created as a side-effect) or if the application is not running anymore</p>.
* <p>
* The method should return null if the window does not exists (and is not
* created as a side-effect) or if the application is not running anymore
* </p>.
*
* @param name
* the name of the window.
@@ -303,7 +309,9 @@ public abstract class Application implements URIHandler, Terminal.ErrorListener
setMainWindow(window);
}

/** Send information to all listeners about new Windows associated with this application.
/**
* Send information to all listeners about new Windows associated with this
* application.
*
* @param window
*/

+ 84
- 89
src/com/itmill/toolkit/demo/CalendarDemo.java View File

@@ -23,96 +23,91 @@ import com.itmill.toolkit.ui.Window;
*/
public class CalendarDemo extends com.itmill.toolkit.Application {

// Database provided with sample data
private SampleCalendarDatabase sampleDatabase;

// The calendar UI component
private CalendarField from;
private CalendarField to;

/**
* Initialize Application. Demo components are added to main window.
*/
public void init() {
Window main = new Window("Calendar demo");
setMainWindow(main);
main.setLayout(new OrderedLayout(OrderedLayout.ORIENTATION_HORIZONTAL));

// set the application to use Corporate -theme
setTheme("corporate");

// create the calendar component and add to layout
from = new CalendarField();
main.addComponent(from);
from.setResolution(CalendarField.RESOLUTION_HOUR);
from.setImmediate(true);
to = new CalendarField();
main.addComponent(to);
to.setResolution(CalendarField.RESOLUTION_HOUR);
to.setEnabled(false);
to.setImmediate(true);

from.addListener(new ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
Date fd = (Date)from.getValue();
Date td = (Date)to.getValue();
if (fd == null) {
to.setValue(null);
to.setEnabled(false);
return;
} else {
to.setEnabled(true);
}
to.setMinimumDate(fd);
if (td == null||td.before(fd)) {
to.setValue(fd);
}
}
});


// initialize the sample database and set as calendar datasource
sampleDatabase = new SampleCalendarDatabase();
initCalendars();
// Don't allow dates before today
from.setMinimumDate(new Date());
}

/**
* Populates table component with all rows from calendar table.
*/
private void initCalendars() {
try {
QueryContainer qc = new QueryContainer("SELECT * FROM "
+ SampleCalendarDatabase.DB_TABLE_NAME, sampleDatabase
.getConnection());
from.setContainerDataSource(qc);
to.setContainerDataSource(qc);
} catch (SQLException e) {
e.printStackTrace();
// Database provided with sample data
private SampleCalendarDatabase sampleDatabase;

// The calendar UI component
private CalendarField from;
private CalendarField to;

/**
* Initialize Application. Demo components are added to main window.
*/
public void init() {
Window main = new Window("Calendar demo");
setMainWindow(main);

main.setLayout(new OrderedLayout(OrderedLayout.ORIENTATION_HORIZONTAL));

// set the application to use Corporate -theme
setTheme("corporate");

// create the calendar component and add to layout
from = new CalendarField();
main.addComponent(from);
from.setResolution(CalendarField.RESOLUTION_HOUR);
from.setImmediate(true);

to = new CalendarField();
main.addComponent(to);
to.setResolution(CalendarField.RESOLUTION_HOUR);
to.setEnabled(false);
to.setImmediate(true);

from.addListener(new ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
Date fd = (Date) from.getValue();
Date td = (Date) to.getValue();
if (fd == null) {
to.setValue(null);
to.setEnabled(false);
return;
} else {
to.setEnabled(true);
}
to.setMinimumDate(fd);
if (td == null || td.before(fd)) {
to.setValue(fd);
}
}
});

// initialize the sample database and set as calendar datasource
sampleDatabase = new SampleCalendarDatabase();
initCalendars();

// Don't allow dates before today
from.setMinimumDate(new Date());

}

// Calendar will use the first date property as start if you do not
// explicitly specify the property id. Our start -property will be the
// first one, so it's intentionally left out.
// Start is the only mandatory property, but you'll probably want to
// specify title as well.
from.setItemEndPropertyId(SampleCalendarDatabase.PROPERTY_ID_END);
from
.setItemTitlePropertyId(SampleCalendarDatabase.PROPERTY_ID_TITLE);
from
.setItemNotimePropertyId(SampleCalendarDatabase.PROPERTY_ID_NOTIME);
to.setItemEndPropertyId(SampleCalendarDatabase.PROPERTY_ID_END);
to
.setItemTitlePropertyId(SampleCalendarDatabase.PROPERTY_ID_TITLE);
to
.setItemNotimePropertyId(SampleCalendarDatabase.PROPERTY_ID_NOTIME);
}
/**
* Populates table component with all rows from calendar table.
*/
private void initCalendars() {
try {
QueryContainer qc = new QueryContainer("SELECT * FROM "
+ SampleCalendarDatabase.DB_TABLE_NAME, sampleDatabase
.getConnection());
from.setContainerDataSource(qc);
to.setContainerDataSource(qc);
} catch (SQLException e) {
e.printStackTrace();
}

// Calendar will use the first date property as start if you do not
// explicitly specify the property id. Our start -property will be the
// first one, so it's intentionally left out.
// Start is the only mandatory property, but you'll probably want to
// specify title as well.
from.setItemEndPropertyId(SampleCalendarDatabase.PROPERTY_ID_END);
from.setItemTitlePropertyId(SampleCalendarDatabase.PROPERTY_ID_TITLE);
from.setItemNotimePropertyId(SampleCalendarDatabase.PROPERTY_ID_NOTIME);

to.setItemEndPropertyId(SampleCalendarDatabase.PROPERTY_ID_END);
to.setItemTitlePropertyId(SampleCalendarDatabase.PROPERTY_ID_TITLE);
to.setItemNotimePropertyId(SampleCalendarDatabase.PROPERTY_ID_NOTIME);

}

}

+ 1
- 1
src/com/itmill/toolkit/demo/FilterSelect.java View File

@@ -47,7 +47,7 @@ public class FilterSelect extends com.itmill.toolkit.Application {
*/
Window main = new Window("Filter select demo");
setMainWindow(main);
setTheme("corporate");

// default filter

+ 22
- 27
src/com/itmill/toolkit/demo/KeyboardShortcut.java View File

@@ -12,7 +12,7 @@ import com.itmill.toolkit.ui.*;
*
*/
public class KeyboardShortcut extends com.itmill.toolkit.Application implements
Handler {
Handler {
private Window main;

private Button a;
@@ -26,21 +26,16 @@ Handler {
private AbstractField f;

Action[] actions = new Action[] {
new ShortcutAction("Button a action",
ShortcutAction.KeyCode.A, new int[] {
ShortcutAction.ModifierKey.CTRL,
ShortcutAction.ModifierKey.SHIFT }),
new ShortcutAction("Button z action",
ShortcutAction.KeyCode.Z, new int[] {
ShortcutAction.ModifierKey.CTRL,
ShortcutAction.ModifierKey.SHIFT }),
new ShortcutAction("Button x action",
ShortcutAction.KeyCode.X, new int[] {
ShortcutAction.ModifierKey.CTRL,
ShortcutAction.ModifierKey.SHIFT }),
new ShortcutAction("Restart ",
ShortcutAction.KeyCode.ESCAPE, null)
};
new ShortcutAction("Button a action", ShortcutAction.KeyCode.A,
new int[] { ShortcutAction.ModifierKey.CTRL,
ShortcutAction.ModifierKey.SHIFT }),
new ShortcutAction("Button z action", ShortcutAction.KeyCode.Z,
new int[] { ShortcutAction.ModifierKey.CTRL,
ShortcutAction.ModifierKey.SHIFT }),
new ShortcutAction("Button x action", ShortcutAction.KeyCode.X,
new int[] { ShortcutAction.ModifierKey.CTRL,
ShortcutAction.ModifierKey.SHIFT }),
new ShortcutAction("Restart ", ShortcutAction.KeyCode.ESCAPE, null) };

public void init() {

@@ -49,18 +44,18 @@ Handler {
setTheme("corporate");

main
.addComponent(new Label(
"<h3>Test application for shortcut actions</h3>"
+ "<p><b>Notes:</b><br />"
+ "<b>This feature is under development and it's API may still change.</b><br />"
+ "<b>If events do not work, <b>set focus to Textfield first.</b><br />"
+ "<b>Browsers may have reserved the keyboard combinations used in "
+ "this demo for other purposes.</b><br /></p>",
Label.CONTENT_XHTML));
.addComponent(new Label(
"<h3>Test application for shortcut actions</h3>"
+ "<p><b>Notes:</b><br />"
+ "<b>This feature is under development and it's API may still change.</b><br />"
+ "<b>If events do not work, <b>set focus to Textfield first.</b><br />"
+ "<b>Browsers may have reserved the keyboard combinations used in "
+ "this demo for other purposes.</b><br /></p>",
Label.CONTENT_XHTML));
main
.addComponent(new Label(
"ESC restarts program, ctrl-shift-a clicks A button, "
+ "ctrl-shift-z clicks Z button, ctrl-shift-x clicks X button"));
.addComponent(new Label(
"ESC restarts program, ctrl-shift-a clicks A button, "
+ "ctrl-shift-z clicks Z button, ctrl-shift-x clicks X button"));

// Restart button
close = new Button("restart", this, "close");

+ 6
- 6
src/com/itmill/toolkit/demo/colorpicker/ColorPicker.java View File

@@ -6,7 +6,7 @@ import com.itmill.toolkit.terminal.PaintTarget;
import com.itmill.toolkit.ui.*;

public class ColorPicker extends AbstractField {
public ColorPicker() {
super();
setValue(new String("white"));
@@ -21,12 +21,12 @@ public class ColorPicker extends AbstractField {
public String getTag() {
return "colorpicker";
}
/** Encode the property value of the field from RGB components. */
public void setColor(String newcolor) {
setValue(new String(newcolor));
}
/** Decode the property value of the field to RGB components. */
public String getColor() {
return (String) getValue();
@@ -36,16 +36,16 @@ public class ColorPicker extends AbstractField {
public void paintContent(PaintTarget target) throws PaintException {
// Superclass writes any common attributes in the paint target.
super.paintContent(target);
// Set any values as variables of the paint target.
target.addVariable(this, "colorname", getColor());
}
public void changeVariables(Object source, Map variables) {
// Sets the currently selected color
if (variables.containsKey("colorname") && !isReadOnly()) {
String newValue = (String) variables.get("colorname");
setValue(newValue,true);
setValue(newValue, true);
}
}
}

+ 11
- 10
src/com/itmill/toolkit/demo/colorpicker/ColorPickerApplication.java View File

@@ -6,36 +6,37 @@ import com.itmill.toolkit.ui.*;
import com.itmill.toolkit.ui.Button.ClickEvent;

/**
* Demonstration application that shows how to use a simple
* custom client-side GWT component, the ColorPicker.
* Demonstration application that shows how to use a simple custom client-side
* GWT component, the ColorPicker.
*/
public class ColorPickerApplication extends com.itmill.toolkit.Application {
Window main = new Window("Color Picker Demo");
/* The custom component. */
ColorPicker colorselector = new ColorPicker();
/* Another component. */
Label colorname;
public void init() {
setMainWindow(main);
setTheme("demo");
// Listen for value change events in the custom component,
// triggered when user clicks a button to select another color.
colorselector.addListener(new ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Provide some server-side feedback
colorname.setValue("Selected color: " + colorselector.getColor());
colorname.setValue("Selected color: "
+ colorselector.getColor());
}
});
main.addComponent(colorselector);
// Add another component to give feedback from server-side code
colorname = new Label("Selected color: "+colorselector.getColor());
colorname = new Label("Selected color: " + colorselector.getColor());
main.addComponent(colorname);
// Server-side manipulation of the component state
Button button = new Button("Set to white");
button.addListener(new Button.ClickListener() {

+ 13
- 13
src/com/itmill/toolkit/demo/colorpicker/gwt/client/WidgetSet.java View File

@@ -6,20 +6,20 @@ import com.itmill.toolkit.terminal.gwt.client.DefaultWidgetSet;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
public class WidgetSet extends DefaultWidgetSet {
public Widget createWidget(UIDL uidl) {
String className = resolveWidgetTypeName(uidl);
if ("com.itmill.toolkit.demo.colorpicker.gwt.client.ui.ItkColorPicker"
.equals(className))
return new ItkColorPicker();
public Widget createWidget(UIDL uidl) {
String className = resolveWidgetTypeName(uidl);
if ("com.itmill.toolkit.demo.colorpicker.gwt.client.ui.ItkColorPicker"
.equals(className))
return new ItkColorPicker();
return super.createWidget(uidl);
}
return super.createWidget(uidl);
}
protected String resolveWidgetTypeName(UIDL uidl) {
String tag = uidl.getTag();
if ("colorpicker".equals(tag))
return "com.itmill.toolkit.demo.colorpicker.gwt.client.ui.ItkColorPicker";
protected String resolveWidgetTypeName(UIDL uidl) {
String tag = uidl.getTag();
if ("colorpicker".equals(tag))
return "com.itmill.toolkit.demo.colorpicker.gwt.client.ui.ItkColorPicker";
return super.resolveWidgetTypeName(uidl);
}
return super.resolveWidgetTypeName(uidl);
}
}

+ 35
- 27
src/com/itmill/toolkit/demo/colorpicker/gwt/client/ui/GwtColorPicker.java View File

@@ -6,7 +6,7 @@ import com.google.gwt.user.client.ui.*;

/**
* A regular GWT component without integration with IT Mill Toolkit.
**/
*/
public class GwtColorPicker extends Composite implements ClickListener {

/** Currently selected color name to give client-side feedback to the user. */
@@ -14,44 +14,52 @@ public class GwtColorPicker extends Composite implements ClickListener {

public GwtColorPicker() {
// Create a 4x4 grid of buttons with names for 16 colors
Grid grid = new Grid(4,4);
String[] colors = new String[] {"aqua", "black", "blue", "fuchsia",
"gray", "green", "lime", "maroon", "navy", "olive",
"purple", "red", "silver", "teal", "white", "yellow"};
Grid grid = new Grid(4, 4);
String[] colors = new String[] { "aqua", "black", "blue", "fuchsia",
"gray", "green", "lime", "maroon", "navy", "olive", "purple",
"red", "silver", "teal", "white", "yellow" };
int colornum = 0;
for (int i=0; i<4; i++)
for (int j=0; j<4; j++, colornum++) {
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++, colornum++) {
// Create a button for each color
Button button = new Button(colors[colornum]);
button.addClickListener(this);
// Put the button in the Grid layout
grid.setWidget(i, j, button);

// Set the button background colors.
DOM.setStyleAttribute(button.getElement(), "background", colors[colornum]);
DOM.setStyleAttribute(button.getElement(), "background",
colors[colornum]);

// For dark colors, the button label must be in white.
if ("black navy maroon blue purple".indexOf(colors[colornum]) != -1)
DOM.setStyleAttribute(button.getElement(), "color", "white");
DOM
.setStyleAttribute(button.getElement(), "color",
"white");
}

// Create a panel with the color grid and currently selected color indicator
// Create a panel with the color grid and currently selected color
// indicator
HorizontalPanel panel = new HorizontalPanel();
panel.add(grid);
panel.add(currentcolor);

// Set the class of the color selection feedback box to allow CSS styling.
// Set the class of the color selection feedback box to allow CSS
// styling.
// We need to obtain the DOM element for the current color label.
// This assumes that the <td> element of the HorizontalPanel is
// the parent of the label element. Notice that the element has no parent
// the parent of the label element. Notice that the element has no
// parent
// before the widget has been added to the horizontal panel.
Element panelcell = DOM.getParent(currentcolor.getElement());
DOM.setElementProperty(panelcell, "className", "colorpicker-currentcolorbox");
Element panelcell = DOM.getParent(currentcolor.getElement());
DOM.setElementProperty(panelcell, "className",
"colorpicker-currentcolorbox");

// Set initial color. This will be overridden with the value read from server.
// Set initial color. This will be overridden with the value read from
// server.
setColor("white");
// Composite GWT widgets must call initWidget().
initWidget(panel);
}
@@ -60,21 +68,21 @@ public class GwtColorPicker extends Composite implements ClickListener {
public void onClick(Widget sender) {
// Use the button label as the color name to set
setColor(((Button) sender).getText());
}
}

/** Sets the currently selected color. */
public void setColor(String newcolor) {
// Give client-side feedback by changing the color name in the label
currentcolor.setText(newcolor);
currentcolor.setText(newcolor);

// Obtain the DOM elements. This assumes that the <td> element
// of the HorizontalPanel is the parent of the label element.
Element nameelement = currentcolor.getElement();
Element cell = DOM.getParent(nameelement);
// Obtain the DOM elements. This assumes that the <td> element
// of the HorizontalPanel is the parent of the label element.
Element nameelement = currentcolor.getElement();
Element cell = DOM.getParent(nameelement);

// Give feedback by changing the background color
DOM.setStyleAttribute(cell, "background", newcolor);
DOM.setStyleAttribute(nameelement, "background", newcolor);
// Give feedback by changing the background color
DOM.setStyleAttribute(cell, "background", newcolor);
DOM.setStyleAttribute(nameelement, "background", newcolor);
if ("black navy maroon blue purple".indexOf(newcolor) != -1)
DOM.setStyleAttribute(nameelement, "color", "white");
else

+ 10
- 10
src/com/itmill/toolkit/demo/colorpicker/gwt/client/ui/ItkColorPicker.java View File

@@ -16,13 +16,13 @@ public class ItkColorPicker extends GwtColorPicker implements Paintable {
ApplicationConnection client;

/**
* The constructor should first call super() to initialize the component
* and then handle any initialization relevant to IT Mill Toolkit.
**/
* The constructor should first call super() to initialize the component and
* then handle any initialization relevant to IT Mill Toolkit.
*/
public ItkColorPicker() {
// The superclass has a lot of relevant initialization
super();
// This method call of the Paintable interface sets the component
// style name in DOM tree
setStyleName(CLASSNAME);
@@ -40,11 +40,11 @@ public class ItkColorPicker extends GwtColorPicker implements Paintable {
// but don't let container manage caption etc.
if (client.updateComponent(this, uidl, false))
return;
// Save reference to server connection object to be able to send
// user interaction later
this.client = client;
// Save the UIDL identifier for the component
uidl_id = uidl.getId();

@@ -57,18 +57,18 @@ public class ItkColorPicker extends GwtColorPicker implements Paintable {
// Ignore if no change
if (newcolor.equals(currentcolor.getText()))
return;
// Let the original implementation to do whatever it needs to do
super.setColor(newcolor);

// Updating the state to the server can not be done before
// Updating the state to the server can not be done before
// the server connection is known, i.e., before updateFromUIDL()
// has been called.
if (uidl_id == null || client == null)
return;
return;

// Communicate the user interaction parameters to server. This call will
// initiate an AJAX request to the server.
client.updateVariable(uidl_id, "colorname", newcolor, true);
client.updateVariable(uidl_id, "colorname", newcolor, true);
}
}

+ 2
- 2
src/com/itmill/toolkit/demo/features/Feature.java View File

@@ -94,7 +94,7 @@ public abstract class Feature extends CustomComponent {
layout.addComponent(demo);

ts = new TabSheet();
ts.setWidth(100);
ts.setWidthUnits(TabSheet.UNITS_PERCENTAGE);
ts.setHeight(100);
@@ -159,7 +159,7 @@ public abstract class Feature extends CustomComponent {
public TabSheet getTabSheet() {
return ts;
}
/** Get the name of the image file that will be put on description page */
protected String getImage() {
return null;

+ 13
- 13
src/com/itmill/toolkit/demo/features/FeatureBrowser.java View File

@@ -83,7 +83,7 @@ public class FeatureBrowser extends CustomComponent implements
// Restart button
Button close = new Button("restart", getApplication(), "close");
close.setStyle("link");
mainlayout.addComponent(close,"restart");
mainlayout.addComponent(close, "restart");

// Test component
registerFeature("/Welcome", new IntroWelcome());
@@ -199,12 +199,12 @@ public class FeatureBrowser extends CustomComponent implements
if (feature != null) {
mainlayout.removeComponent(currentFeature);
mainlayout.removeComponent(currentFeature.getTabSheet());
mainlayout.addComponent(feature,"demo");
mainlayout.addComponent(feature.getTabSheet(),"tabsheet");
mainlayout.addComponent(feature, "demo");
mainlayout.addComponent(feature.getTabSheet(), "tabsheet");
currentFeature = feature;
properties = feature.getPropertyPanel();
if (properties != null) {
mainlayout.addComponent(properties,"properties");
mainlayout.addComponent(properties, "properties");
}
getWindow()
.setCaption(
@@ -233,17 +233,17 @@ public class FeatureBrowser extends CustomComponent implements

public void addComponent(Component c) {
// TODO Auto-generated method stub
}

public void addListener(ComponentAttachListener listener) {
// TODO Auto-generated method stub
}

public void addListener(ComponentDetachListener listener) {
// TODO Auto-generated method stub
}

public Iterator getComponentIterator() {
@@ -253,31 +253,31 @@ public class FeatureBrowser extends CustomComponent implements

public void moveComponentsFrom(ComponentContainer source) {
// TODO Auto-generated method stub
}

public void removeAllComponents() {
// TODO Auto-generated method stub
}

public void removeComponent(Component c) {
// TODO Auto-generated method stub
}

public void removeListener(ComponentAttachListener listener) {
// TODO Auto-generated method stub
}

public void removeListener(ComponentDetachListener listener) {
// TODO Auto-generated method stub
}

public void replaceComponent(Component oldComponent, Component newComponent) {
// TODO Auto-generated method stub
}
}

+ 6
- 5
src/com/itmill/toolkit/demo/features/FeatureDateField.java View File

@@ -45,7 +45,7 @@ public class FeatureDateField extends Feature {
static {
Locale[] locales = Locale.getAvailableLocales();
localeNames = new String[locales.length];
for (int i = 0; i < locales.length; i++)
for (int i = 0; i < locales.length; i++)
localeNames[i] = locales[i].getDisplayName();
}

@@ -64,11 +64,11 @@ public class FeatureDateField extends Feature {
DateField df = new DateField();
df.setValue(new java.util.Date());
l.addComponent(df);
// Properties
propertyPanel = new PropertyPanel(df);
Form ap = propertyPanel
.createBeanPropertySet(new String[] { "resolution", "locale" });
Form ap = propertyPanel.createBeanPropertySet(new String[] {
"resolution", "locale" });
ap.replaceWithSelect("resolution", new Object[] {
new Integer(DateField.RESOLUTION_YEAR),
new Integer(DateField.RESOLUTION_MONTH),
@@ -79,7 +79,8 @@ public class FeatureDateField extends Feature {
new Integer(DateField.RESOLUTION_MSEC) }, new Object[] {
"Year", "Month", "Day", "Hour", "Minute", "Second",
"Millisecond" });
ap.replaceWithSelect("locale", Locale.getAvailableLocales(), localeNames);
ap.replaceWithSelect("locale", Locale.getAvailableLocales(),
localeNames);
ap.getField("resolution").setValue(
new Integer(DateField.RESOLUTION_DAY));
ap.getField("locale").setValue(Locale.getDefault());

+ 1
- 1
src/com/itmill/toolkit/demo/features/FeaturesApplication.java View File

@@ -38,7 +38,7 @@ public class FeaturesApplication extends com.itmill.toolkit.Application {
setUser(new Long(System.currentTimeMillis()).toString());
Window main = new Window("IT Mill Toolkit Features Tour");
setMainWindow(main);
main.setLayout(new FeatureBrowser());
}


+ 3
- 3
src/com/itmill/toolkit/demo/features/PropertyPanel.java View File

@@ -76,7 +76,7 @@ public class PropertyPanel extends Panel implements Button.ClickListener,
setWidthUnits(Table.UNITS_PERCENTAGE);
setHeight(100);
setHeightUnits(Table.UNITS_PERCENTAGE);
// Target object
this.objectToConfigure = objectToConfigure;
config = new BeanItem(objectToConfigure);
@@ -111,8 +111,8 @@ public class PropertyPanel extends Panel implements Button.ClickListener,
allProperties.setWidth(100);
allProperties.setWidthUnits(Table.UNITS_PERCENTAGE);
// TODO Add as soon as supported
//allProperties.setHeight(100);
//allProperties.setHeightUnits(Table.UNITS_PERCENTAGE);
// allProperties.setHeight(100);
// allProperties.setHeightUnits(Table.UNITS_PERCENTAGE);
updatePropertyList();

}

+ 201
- 201
src/com/itmill/toolkit/demo/reservation/GoogleMap.java View File

@@ -14,206 +14,206 @@ import com.itmill.toolkit.terminal.Sizeable;
import com.itmill.toolkit.ui.AbstractComponent;
public class GoogleMap extends AbstractComponent implements Sizeable,
Container.Viewer {
private String TAG_MARKERS = "markers";
private String TAG_MARKER = "marker";
private int width = 400;
private int height = 300;
private int zoomLevel = 15;
private Point2D.Double mapCenter;
private Container dataSource;
private Object itemMarkerHtmlPropertyId = new Object();
private Object itemMarkerXPropertyId = new Object();
private Object itemMarkerYPropertyId = new Object();
public String getTag() {
return "googlemap";
}
public void paintContent(PaintTarget target) throws PaintException {
super.paintContent(target);
if (null != mapCenter) {
target.addAttribute("centerX", mapCenter.getX());
target.addAttribute("centerY", mapCenter.getY());
}
target.addAttribute("zoom", zoomLevel);
target.addAttribute("width", width);
target.addAttribute("height", height);
if (this.dataSource != null) {
target.startTag(TAG_MARKERS);
Collection itemIds = this.dataSource.getItemIds();
for (Iterator it = itemIds.iterator(); it.hasNext();) {
Object itemId = it.next();
Item item = this.dataSource.getItem(itemId);
Property p = item.getItemProperty(getItemMarkerXPropertyId());
Double x = (Double) (p != null ? p.getValue() : null);
p = item.getItemProperty(getItemMarkerYPropertyId());
Double y = (Double) (p != null ? p.getValue() : null);
if (x == null || y == null) {
continue;
Container.Viewer {
private String TAG_MARKERS = "markers";
private String TAG_MARKER = "marker";
private int width = 400;
private int height = 300;
private int zoomLevel = 15;
private Point2D.Double mapCenter;
private Container dataSource;
private Object itemMarkerHtmlPropertyId = new Object();
private Object itemMarkerXPropertyId = new Object();
private Object itemMarkerYPropertyId = new Object();
public String getTag() {
return "googlemap";
}
public void paintContent(PaintTarget target) throws PaintException {
super.paintContent(target);
if (null != mapCenter) {
target.addAttribute("centerX", mapCenter.getX());
target.addAttribute("centerY", mapCenter.getY());
}
target.addAttribute("zoom", zoomLevel);
target.addAttribute("width", width);
target.addAttribute("height", height);
if (this.dataSource != null) {
target.startTag(TAG_MARKERS);
Collection itemIds = this.dataSource.getItemIds();
for (Iterator it = itemIds.iterator(); it.hasNext();) {
Object itemId = it.next();
Item item = this.dataSource.getItem(itemId);
Property p = item.getItemProperty(getItemMarkerXPropertyId());
Double x = (Double) (p != null ? p.getValue() : null);
p = item.getItemProperty(getItemMarkerYPropertyId());
Double y = (Double) (p != null ? p.getValue() : null);
if (x == null || y == null) {
continue;
}
target.startTag(TAG_MARKER);
target.addAttribute("x", x.doubleValue());
target.addAttribute("y", y.doubleValue());
p = item.getItemProperty(getItemMarkerHtmlPropertyId());
String h = (String) (p != null ? p.getValue() : null);
target.addAttribute("html", h);
target.endTag(TAG_MARKER);
}
target.endTag(TAG_MARKERS);
}
target.startTag(TAG_MARKER);
target.addAttribute("x", x.doubleValue());
target.addAttribute("y", y.doubleValue());
p = item.getItemProperty(getItemMarkerHtmlPropertyId());
String h = (String) (p != null ? p.getValue() : null);
target.addAttribute("html", h);
target.endTag(TAG_MARKER);
}
target.endTag(TAG_MARKERS);
}
}
public void setZoomLevel(int zoomLevel) {
this.zoomLevel = zoomLevel;
requestRepaint();
}
public int getZoomLevel() {
return this.zoomLevel;
}
// Sizeable methods:
public int getHeight() {
return this.height;
}
public int getHeightUnits() {
return Sizeable.UNITS_PIXELS;
}
public int getWidth() {
return this.width;
}
public int getWidthUnits() {
return Sizeable.UNITS_PIXELS;
}
public void setHeight(int height) {
this.height = height;
requestRepaint();
}
public void setHeightUnits(int units) {
throw new UnsupportedOperationException();
}
public void setWidth(int width) {
this.width = width;
requestRepaint();
}
public void setWidthUnits(int units) {
throw new UnsupportedOperationException();
}
public void setMapCenter(Point2D.Double center) {
this.mapCenter = center;
}
public Point2D.Double getMapCenter() {
return this.mapCenter;
}
// Container.Viewer methods:
public Container getContainerDataSource() {
return this.dataSource;
}
public void setContainerDataSource(Container newDataSource) {
this.dataSource = newDataSource;
requestRepaint();
}
// Item methods
public Object getItemMarkerHtmlPropertyId() {
return itemMarkerHtmlPropertyId;
}
public void setItemMarkerHtmlPropertyId(Object itemMarkerHtmlPropertyId) {
this.itemMarkerHtmlPropertyId = itemMarkerHtmlPropertyId;
requestRepaint();
}
public Object getItemMarkerXPropertyId() {
return itemMarkerXPropertyId;
}
public void setItemMarkerXPropertyId(Object itemMarkerXPropertyId) {
this.itemMarkerXPropertyId = itemMarkerXPropertyId;
requestRepaint();
}
public Object getItemMarkerYPropertyId() {
return itemMarkerYPropertyId;
}
public void setItemMarkerYPropertyId(Object itemMarkerYPropertyId) {
this.itemMarkerYPropertyId = itemMarkerYPropertyId;
requestRepaint();
}
// Marker add
public Object addMarker(String html, Point2D.Double location) {
if (location == null) {
throw new IllegalArgumentException("Location must be non-null");
}
if (this.dataSource == null) {
initDataSource();
}
Object markerId = this.dataSource.addItem();
if (markerId == null) {
return null;
}
Item marker = this.dataSource.getItem(markerId);
Property p = marker.getItemProperty(getItemMarkerXPropertyId());
p.setValue(new Double(location.x));
p = marker.getItemProperty(getItemMarkerYPropertyId());
p.setValue(new Double(location.y));
p = marker.getItemProperty(getItemMarkerHtmlPropertyId());
p.setValue(html);
requestRepaint();
return markerId;
}
public void removeMarker(Object markerId) {
if (this.dataSource != null) {
this.dataSource.removeItem(markerId);
requestRepaint();
}
}
public Item getMarkerItem(Object markerId) {
if (this.dataSource != null) {
return this.dataSource.getItem(markerId);
} else {
return null;
}
}
// dataSource init helper:
private void initDataSource() {
this.dataSource = new IndexedContainer();
this.dataSource.addContainerProperty(this.itemMarkerHtmlPropertyId,
String.class, null);
this.dataSource.addContainerProperty(this.itemMarkerXPropertyId,
Double.class, new Double(0));
this.dataSource.addContainerProperty(this.itemMarkerYPropertyId,
Double.class, new Double(0));
}
public void clear() {
setContainerDataSource(null);
}
}
public void setZoomLevel(int zoomLevel) {
this.zoomLevel = zoomLevel;
requestRepaint();
}
public int getZoomLevel() {
return this.zoomLevel;
}
// Sizeable methods:
public int getHeight() {
return this.height;
}
public int getHeightUnits() {
return Sizeable.UNITS_PIXELS;
}
public int getWidth() {
return this.width;
}
public int getWidthUnits() {
return Sizeable.UNITS_PIXELS;
}
public void setHeight(int height) {
this.height = height;
requestRepaint();
}
public void setHeightUnits(int units) {
throw new UnsupportedOperationException();
}
public void setWidth(int width) {
this.width = width;
requestRepaint();
}
public void setWidthUnits(int units) {
throw new UnsupportedOperationException();
}
public void setMapCenter(Point2D.Double center) {
this.mapCenter = center;
}
public Point2D.Double getMapCenter() {
return this.mapCenter;
}
// Container.Viewer methods:
public Container getContainerDataSource() {
return this.dataSource;
}
public void setContainerDataSource(Container newDataSource) {
this.dataSource = newDataSource;
requestRepaint();
}
// Item methods
public Object getItemMarkerHtmlPropertyId() {
return itemMarkerHtmlPropertyId;
}
public void setItemMarkerHtmlPropertyId(Object itemMarkerHtmlPropertyId) {
this.itemMarkerHtmlPropertyId = itemMarkerHtmlPropertyId;
requestRepaint();
}
public Object getItemMarkerXPropertyId() {
return itemMarkerXPropertyId;
}
public void setItemMarkerXPropertyId(Object itemMarkerXPropertyId) {
this.itemMarkerXPropertyId = itemMarkerXPropertyId;
requestRepaint();
}
public Object getItemMarkerYPropertyId() {
return itemMarkerYPropertyId;
}
public void setItemMarkerYPropertyId(Object itemMarkerYPropertyId) {
this.itemMarkerYPropertyId = itemMarkerYPropertyId;
requestRepaint();
}
// Marker add
public Object addMarker(String html, Point2D.Double location) {
if (location == null) {
throw new IllegalArgumentException("Location must be non-null");
}
if (this.dataSource == null) {
initDataSource();
}
Object markerId = this.dataSource.addItem();
if (markerId == null) {
return null;
}
Item marker = this.dataSource.getItem(markerId);
Property p = marker.getItemProperty(getItemMarkerXPropertyId());
p.setValue(new Double(location.x));
p = marker.getItemProperty(getItemMarkerYPropertyId());
p.setValue(new Double(location.y));
p = marker.getItemProperty(getItemMarkerHtmlPropertyId());
p.setValue(html);
requestRepaint();
return markerId;
}
public void removeMarker(Object markerId) {
if (this.dataSource != null) {
this.dataSource.removeItem(markerId);
requestRepaint();
}
}
public Item getMarkerItem(Object markerId) {
if (this.dataSource != null) {
return this.dataSource.getItem(markerId);
} else {
return null;
}
}
// dataSource init helper:
private void initDataSource() {
this.dataSource = new IndexedContainer();
this.dataSource.addContainerProperty(this.itemMarkerHtmlPropertyId,
String.class, null);
this.dataSource.addContainerProperty(this.itemMarkerXPropertyId,
Double.class, new Double(0));
this.dataSource.addContainerProperty(this.itemMarkerYPropertyId,
Double.class, new Double(0));
}
public void clear() {
setContainerDataSource(null);
}
}

+ 245
- 244
src/com/itmill/toolkit/demo/reservation/ReservationApplication.java View File

@@ -25,259 +25,260 @@ import com.itmill.toolkit.ui.TabSheet.SelectedTabChangeEvent;
public class ReservationApplication extends Application {
private SampleDB db;
ResourceSelectorPanel resourcePanel;
private CalendarField reservedFrom;
private static final long DEFAULT_GAP_MILLIS = 3600000; // one hour
private long currentGapMillis = DEFAULT_GAP_MILLIS;
private CalendarField reservedTo;
private Label resourceName;
private Label statusLabel;
private TextField description;
private Button reservationButton;
private Table allTable;
private CalendarField allCalendar;
private GoogleMap map;
public void init() {
db = new SampleDB(true);
db.generateResources();
db.generateDemoUser();
Window mainWindow = new Window("Reservr");
setMainWindow(mainWindow);
setTheme("reservr");
TabSheet mainTabs = new TabSheet();
mainWindow.addComponent(mainTabs);
mainWindow.addComponent(new Button("close", this, "close"));
OrderedLayout reservationTab = new OrderedLayout();
mainTabs.addTab(reservationTab, "Make reservation", null);
resourcePanel = new ResourceSelectorPanel("Resources");
resourcePanel.setResourceContainer(db.getResources(null));
resourcePanel.addListener(
ResourceSelectorPanel.SelectedResourcesChangedEvent.class,
this, "selectedResourcesChanged");
reservationTab.addComponent(resourcePanel);
Panel reservationPanel = new Panel("Reservation", new OrderedLayout(
OrderedLayout.ORIENTATION_HORIZONTAL));
reservationTab.addComponent(reservationPanel);
OrderedLayout infoLayout = new OrderedLayout();
reservationPanel.addComponent(infoLayout);
resourceName = new Label("From the list above");
resourceName.setCaption("Choose resource");
infoLayout.addComponent(resourceName);
description = new TextField();
description.setColumns(55);
description.setRows(5);
infoLayout.addComponent(description);
reservationButton = new Button("Make reservation", this,
"makeReservation");
infoLayout.addComponent(reservationButton);
statusLabel = new Label();
infoLayout.addComponent(statusLabel);
map = new GoogleMap();
map.setWidth(360);
map.setHeight(270);
map.setItemMarkerHtmlPropertyId(SampleDB.Resource.PROPERTY_ID_NAME);
map.setItemMarkerXPropertyId(SampleDB.Resource.PROPERTY_ID_LOCATIONX);
map.setItemMarkerYPropertyId(SampleDB.Resource.PROPERTY_ID_LOCATIONY);
map.setContainerDataSource(db.getResources(null));
infoLayout.addComponent(map);
Calendar from = Calendar.getInstance();
reservedFrom = new CalendarField();
reservedFrom.setMinimumDate(from.getTime());
reservedFrom.setValue(from.getTime());
reservedFrom.setImmediate(true);
initCalendarFieldPropertyIds(reservedFrom);
reservationPanel.addComponent(reservedFrom);
Calendar to = Calendar.getInstance();
to.add(Calendar.MILLISECOND, (int)currentGapMillis);
reservedTo = new CalendarField();
reservedTo.setMinimumDate(from.getTime());
reservedTo.setValue(to.getTime());
reservedTo.setImmediate(true);
initCalendarFieldPropertyIds(reservedTo);
reservationPanel.addComponent(reservedTo);
reservedFrom.addListener(new ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
Date fd = (Date) reservedFrom.getValue();
if (fd == null) {
reservedTo.setValue(null);
reservedTo.setEnabled(false);
refreshSelectedResources();
return;
} else {
reservedTo.setEnabled(true);
}
reservedTo.setMinimumDate(fd);
private SampleDB db;
ResourceSelectorPanel resourcePanel;
private CalendarField reservedFrom;
private static final long DEFAULT_GAP_MILLIS = 3600000; // one hour
private long currentGapMillis = DEFAULT_GAP_MILLIS;
private CalendarField reservedTo;
private Label resourceName;
private Label statusLabel;
private TextField description;
private Button reservationButton;
private Table allTable;
private CalendarField allCalendar;
private GoogleMap map;
public void init() {
db = new SampleDB(true);
db.generateResources();
db.generateDemoUser();
Window mainWindow = new Window("Reservr");
setMainWindow(mainWindow);
setTheme("reservr");
TabSheet mainTabs = new TabSheet();
mainWindow.addComponent(mainTabs);
mainWindow.addComponent(new Button("close", this, "close"));
OrderedLayout reservationTab = new OrderedLayout();
mainTabs.addTab(reservationTab, "Make reservation", null);
resourcePanel = new ResourceSelectorPanel("Resources");
resourcePanel.setResourceContainer(db.getResources(null));
resourcePanel.addListener(
ResourceSelectorPanel.SelectedResourcesChangedEvent.class,
this, "selectedResourcesChanged");
reservationTab.addComponent(resourcePanel);
Panel reservationPanel = new Panel("Reservation", new OrderedLayout(
OrderedLayout.ORIENTATION_HORIZONTAL));
reservationTab.addComponent(reservationPanel);
OrderedLayout infoLayout = new OrderedLayout();
reservationPanel.addComponent(infoLayout);
resourceName = new Label("From the list above");
resourceName.setCaption("Choose resource");
infoLayout.addComponent(resourceName);
description = new TextField();
description.setColumns(55);
description.setRows(5);
infoLayout.addComponent(description);
reservationButton = new Button("Make reservation", this,
"makeReservation");
infoLayout.addComponent(reservationButton);
statusLabel = new Label();
infoLayout.addComponent(statusLabel);
map = new GoogleMap();
map.setWidth(360);
map.setHeight(270);
map.setItemMarkerHtmlPropertyId(SampleDB.Resource.PROPERTY_ID_NAME);
map.setItemMarkerXPropertyId(SampleDB.Resource.PROPERTY_ID_LOCATIONX);
map.setItemMarkerYPropertyId(SampleDB.Resource.PROPERTY_ID_LOCATIONY);
map.setContainerDataSource(db.getResources(null));
infoLayout.addComponent(map);
Calendar from = Calendar.getInstance();
reservedFrom = new CalendarField();
reservedFrom.setMinimumDate(from.getTime());
reservedFrom.setValue(from.getTime());
reservedFrom.setImmediate(true);
initCalendarFieldPropertyIds(reservedFrom);
reservationPanel.addComponent(reservedFrom);
Calendar to = Calendar.getInstance();
to.setTime(fd);
to.add(Calendar.MILLISECOND, (int)currentGapMillis);
to.add(Calendar.MILLISECOND, (int) currentGapMillis);
reservedTo = new CalendarField();
reservedTo.setMinimumDate(from.getTime());
reservedTo.setValue(to.getTime());
refreshSelectedResources();
resetStatus();
}
});
reservedTo.addListener(new ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
Date from = (Date) reservedFrom.getValue();
Date to = (Date) reservedTo.getValue();
currentGapMillis = to.getTime() - from.getTime();
if (currentGapMillis <= 0 ) {
Calendar t = Calendar.getInstance();
t.setTime(from);
t.add(Calendar.MILLISECOND, (int)DEFAULT_GAP_MILLIS);
reservedTo.setValue(t.getTime());
reservedTo.setImmediate(true);
initCalendarFieldPropertyIds(reservedTo);
reservationPanel.addComponent(reservedTo);
reservedFrom.addListener(new ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
Date fd = (Date) reservedFrom.getValue();
if (fd == null) {
reservedTo.setValue(null);
reservedTo.setEnabled(false);
refreshSelectedResources();
return;
} else {
reservedTo.setEnabled(true);
}
reservedTo.setMinimumDate(fd);
Calendar to = Calendar.getInstance();
to.setTime(fd);
to.add(Calendar.MILLISECOND, (int) currentGapMillis);
reservedTo.setValue(to.getTime());
refreshSelectedResources();
resetStatus();
}
});
reservedTo.addListener(new ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
Date from = (Date) reservedFrom.getValue();
Date to = (Date) reservedTo.getValue();
currentGapMillis = to.getTime() - from.getTime();
if (currentGapMillis <= 0) {
Calendar t = Calendar.getInstance();
t.setTime(from);
t.add(Calendar.MILLISECOND, (int) DEFAULT_GAP_MILLIS);
reservedTo.setValue(t.getTime());
}
refreshSelectedResources();
resetStatus();
}
});
OrderedLayout allLayout = new OrderedLayout(
OrderedLayout.ORIENTATION_HORIZONTAL);
allCalendar = new CalendarField();
initCalendarFieldPropertyIds(allCalendar);
allLayout.addComponent(allCalendar);
allTable = new Table();
allLayout.addComponent(allTable);
mainTabs.addTab(allLayout, "All reservations", null);
mainTabs.addListener(new TabSheet.SelectedTabChangeListener() {
public void selectedTabChange(SelectedTabChangeEvent event) {
refreshReservations();
}
});
refreshReservations();
}
public void makeReservation() {
try {
Item resource = getActiveResource();
if (resource != null) {
db.addReservation(resource, 0, (Date) reservedFrom.getValue(),
(Date) reservedTo.getValue(), (String) description
.getValue());
statusLabel.setCaption("Success!");
statusLabel
.setValue("You have reserved the resource for the selected period.");
}
} catch (ResourceNotAvailableException e) {
statusLabel.setCaption("Reservation failed");
statusLabel
.setValue("The selected resource was not available for the selected period.");
}
refreshSelectedResources();
resetStatus();
}
});
OrderedLayout allLayout = new OrderedLayout(
OrderedLayout.ORIENTATION_HORIZONTAL);
allCalendar = new CalendarField();
initCalendarFieldPropertyIds(allCalendar);
allLayout.addComponent(allCalendar);
allTable = new Table();
allLayout.addComponent(allTable);
mainTabs.addTab(allLayout, "All reservations", null);
mainTabs.addListener(new TabSheet.SelectedTabChangeListener() {
public void selectedTabChange(SelectedTabChangeEvent event) {
refreshReservations();
}
});
refreshReservations();
}
public void makeReservation() {
try {
Item resource = getActiveResource();
if (resource != null) {
db.addReservation(resource, 0, (Date) reservedFrom.getValue(),
(Date) reservedTo.getValue(), (String) description
.getValue());
statusLabel.setCaption("Success!");
statusLabel
.setValue("You have reserved the resource for the selected period.");
}
} catch (ResourceNotAvailableException e) {
statusLabel.setCaption("Reservation failed");
statusLabel
.setValue("The selected resource was not available for the selected period.");
}
refreshReservations();
}
private Item getActiveResource() throws ResourceNotAvailableException {
List rids = resourcePanel.getSelectedResources();
if (rids != null && rids.size() > 0) {
for (Iterator it = rids.iterator(); it.hasNext();) {
Item resource = (Item) it.next();
int id = ((Integer) resource.getItemProperty(
SampleDB.Resource.PROPERTY_ID_ID).getValue())
.intValue();
if (db.isAvailableResource(id, (Date) reservedFrom.getValue(),
(Date) reservedTo.getValue()))
return resource;
}
throw new ResourceNotAvailableException("No available resource");
} else {
return null;
private Item getActiveResource() throws ResourceNotAvailableException {
List rids = resourcePanel.getSelectedResources();
if (rids != null && rids.size() > 0) {
for (Iterator it = rids.iterator(); it.hasNext();) {
Item resource = (Item) it.next();
int id = ((Integer) resource.getItemProperty(
SampleDB.Resource.PROPERTY_ID_ID).getValue())
.intValue();
if (db.isAvailableResource(id, (Date) reservedFrom.getValue(),
(Date) reservedTo.getValue()))
return resource;
}
throw new ResourceNotAvailableException("No available resource");
} else {
return null;
}
}
}
private void refreshReservations() {
Container reservations = db.getReservations(resourcePanel
.getSelectedResources());
reservedFrom.setContainerDataSource(reservations);
reservedTo.setContainerDataSource(reservations);
refreshSelectedResources();
Container allReservations = db.getReservations(null);
allTable.setContainerDataSource(allReservations);
allCalendar.setContainerDataSource(allReservations);
}
private void refreshSelectedResources() {
Item resource = null;
try {
resource = getActiveResource();
} catch (ResourceNotAvailableException e) {
resourceName.setCaption("Not available");
resourceName.setValue("Please choose another time period or resource");
reservationButton.setEnabled(false);
return;
private void refreshReservations() {
Container reservations = db.getReservations(resourcePanel
.getSelectedResources());
reservedFrom.setContainerDataSource(reservations);
reservedTo.setContainerDataSource(reservations);
refreshSelectedResources();
Container allReservations = db.getReservations(null);
allTable.setContainerDataSource(allReservations);
allCalendar.setContainerDataSource(allReservations);
}
map.clear();
if (resource == null) {
resourceName.setCaption("Choose resource");
resourceName.setValue("from the list above");
reservationButton.setEnabled(false);
map.setContainerDataSource(db.getResources(null));
map.setZoomLevel(1);
} else {
LinkedList srs = resourcePanel.getSelectedResources();
for (Iterator it = srs.iterator(); it.hasNext();) {
resource = (Item)it.next();
String name = (String) resource.getItemProperty(
SampleDB.Resource.PROPERTY_ID_NAME).getValue();
String desc = (String) resource.getItemProperty(
SampleDB.Resource.PROPERTY_ID_DESCRIPTION).getValue();
resourceName.setCaption(name);
resourceName.setValue(desc);
Double x = (Double) resource.getItemProperty(
SampleDB.Resource.PROPERTY_ID_LOCATIONX).getValue();
Double y = (Double) resource.getItemProperty(
SampleDB.Resource.PROPERTY_ID_LOCATIONY).getValue();
if (x != null && y != null) {
map.addMarker(name + "<br/>" + desc, new Point2D.Double(x
.doubleValue(), y.doubleValue()));
private void refreshSelectedResources() {
Item resource = null;
try {
resource = getActiveResource();
} catch (ResourceNotAvailableException e) {
resourceName.setCaption("Not available");
resourceName
.setValue("Please choose another time period or resource");
reservationButton.setEnabled(false);
return;
}
}
map.setZoomLevel((srs.size()==1?16:9));
reservationButton.setEnabled(true);
map.clear();
if (resource == null) {
resourceName.setCaption("Choose resource");
resourceName.setValue("from the list above");
reservationButton.setEnabled(false);
map.setContainerDataSource(db.getResources(null));
map.setZoomLevel(1);
} else {
LinkedList srs = resourcePanel.getSelectedResources();
for (Iterator it = srs.iterator(); it.hasNext();) {
resource = (Item) it.next();
String name = (String) resource.getItemProperty(
SampleDB.Resource.PROPERTY_ID_NAME).getValue();
String desc = (String) resource.getItemProperty(
SampleDB.Resource.PROPERTY_ID_DESCRIPTION).getValue();
resourceName.setCaption(name);
resourceName.setValue(desc);
Double x = (Double) resource.getItemProperty(
SampleDB.Resource.PROPERTY_ID_LOCATIONX).getValue();
Double y = (Double) resource.getItemProperty(
SampleDB.Resource.PROPERTY_ID_LOCATIONY).getValue();
if (x != null && y != null) {
map.addMarker(name + "<br/>" + desc, new Point2D.Double(x
.doubleValue(), y.doubleValue()));
}
}
map.setZoomLevel((srs.size() == 1 ? 16 : 9));
reservationButton.setEnabled(true);
}
}
}
private void initCalendarFieldPropertyIds(CalendarField cal) {
cal
.setItemStartPropertyId(SampleDB.Reservation.PROPERTY_ID_RESERVED_FROM);
cal.setItemEndPropertyId(SampleDB.Reservation.PROPERTY_ID_RESERVED_TO);
cal.setItemTitlePropertyId(SampleDB.Resource.PROPERTY_ID_NAME);
cal
.setItemDescriptionPropertyId(SampleDB.Reservation.PROPERTY_ID_DESCRIPTION);
}
private void resetStatus() {
statusLabel.setCaption(null);
statusLabel.setValue(null);
}
public void selectedResourcesChanged(
ResourceSelectorPanel.SelectedResourcesChangedEvent event) {
refreshReservations();
resetStatus();
}
private void initCalendarFieldPropertyIds(CalendarField cal) {
cal
.setItemStartPropertyId(SampleDB.Reservation.PROPERTY_ID_RESERVED_FROM);
cal.setItemEndPropertyId(SampleDB.Reservation.PROPERTY_ID_RESERVED_TO);
cal.setItemTitlePropertyId(SampleDB.Resource.PROPERTY_ID_NAME);
cal
.setItemDescriptionPropertyId(SampleDB.Reservation.PROPERTY_ID_DESCRIPTION);
}
private void resetStatus() {
statusLabel.setCaption(null);
statusLabel.setValue(null);
}
public void selectedResourcesChanged(
ResourceSelectorPanel.SelectedResourcesChangedEvent event) {
refreshReservations();
resetStatus();
}
}

+ 1
- 1
src/com/itmill/toolkit/demo/reservation/ResourceNotAvailableException.java View File

@@ -2,6 +2,6 @@ package com.itmill.toolkit.demo.reservation;
public class ResourceNotAvailableException extends Exception {
public ResourceNotAvailableException(String message) {
super(message);
super(message);
}
}

+ 86
- 86
src/com/itmill/toolkit/demo/reservation/ResourceSelectorPanel.java View File

@@ -13,104 +13,104 @@ import com.itmill.toolkit.ui.Panel;
import com.itmill.toolkit.ui.Button.ClickEvent;
public class ResourceSelectorPanel extends Panel implements
Button.ClickListener {
private HashMap categoryLayouts = new HashMap();
private HashMap categoryResources = new HashMap();
Button.ClickListener {
private HashMap categoryLayouts = new HashMap();
private HashMap categoryResources = new HashMap();
private Container allResources;
private LinkedList selectedResources = null;
private Container allResources;
private LinkedList selectedResources = null;
public ResourceSelectorPanel(String caption) {
super(caption, new OrderedLayout(OrderedLayout.ORIENTATION_HORIZONTAL));
}
public ResourceSelectorPanel(String caption) {
super(caption, new OrderedLayout(OrderedLayout.ORIENTATION_HORIZONTAL));
}
public void setResourceContainer(Container resources) {
this.removeAllComponents();
categoryLayouts.clear();
categoryResources.clear();
if (resources != null && resources.size() > 0) {
for (Iterator it = resources.getItemIds().iterator(); it.hasNext();) {
Item resource = (Item) resources.getItem(it.next());
Integer id = (Integer) resource.getItemProperty(
SampleDB.Resource.PROPERTY_ID_ID).getValue();
String category = (String) resource.getItemProperty(
SampleDB.Resource.PROPERTY_ID_CATEGORY).getValue();
String name = (String) resource.getItemProperty(
SampleDB.Resource.PROPERTY_ID_NAME).getValue();
String description = (String) resource.getItemProperty(
SampleDB.Resource.PROPERTY_ID_DESCRIPTION).getValue();
Button rButton = new Button(name, this);
rButton.setStyle("link");
rButton.setDescription(description);
rButton.setData(resource);
Layout resourceLayout = (Layout) categoryLayouts.get(category);
LinkedList resourceList = (LinkedList) categoryResources
.get(category);
if (resourceLayout == null) {
resourceLayout = new OrderedLayout();
this.addComponent(resourceLayout);
categoryLayouts.put(category, resourceLayout);
resourceList = new LinkedList();
categoryResources.put(category, resourceList);
Button cButton = new Button(category + " (any)", this);
cButton.setStyle("important-link");
cButton.setData(category);
resourceLayout.addComponent(cButton);
public void setResourceContainer(Container resources) {
this.removeAllComponents();
categoryLayouts.clear();
categoryResources.clear();
if (resources != null && resources.size() > 0) {
for (Iterator it = resources.getItemIds().iterator(); it.hasNext();) {
Item resource = (Item) resources.getItem(it.next());
Integer id = (Integer) resource.getItemProperty(
SampleDB.Resource.PROPERTY_ID_ID).getValue();
String category = (String) resource.getItemProperty(
SampleDB.Resource.PROPERTY_ID_CATEGORY).getValue();
String name = (String) resource.getItemProperty(
SampleDB.Resource.PROPERTY_ID_NAME).getValue();
String description = (String) resource.getItemProperty(
SampleDB.Resource.PROPERTY_ID_DESCRIPTION).getValue();
Button rButton = new Button(name, this);
rButton.setStyle("link");
rButton.setDescription(description);
rButton.setData(resource);
Layout resourceLayout = (Layout) categoryLayouts.get(category);
LinkedList resourceList = (LinkedList) categoryResources
.get(category);
if (resourceLayout == null) {
resourceLayout = new OrderedLayout();
this.addComponent(resourceLayout);
categoryLayouts.put(category, resourceLayout);
resourceList = new LinkedList();
categoryResources.put(category, resourceList);
Button cButton = new Button(category + " (any)", this);
cButton.setStyle("important-link");
cButton.setData(category);
resourceLayout.addComponent(cButton);
}
resourceLayout.addComponent(rButton);
resourceList.add(resource);
}
}
resourceLayout.addComponent(rButton);
resourceList.add(resource);
}
}
}
private void setSelectedResources(LinkedList resources) {
selectedResources = resources;
fireEvent(new SelectedResourcesChangedEvent());
}
private void setSelectedResources(LinkedList resources) {
selectedResources = resources;
fireEvent(new SelectedResourcesChangedEvent());
}
public LinkedList getSelectedResources() {
return selectedResources;
}
public LinkedList getSelectedResources() {
return selectedResources;
}
public void buttonClick(ClickEvent event) {
Object source = event.getSource();
if (source instanceof Button) {
Object data = ((Button) source).getData();
String name = ((Button) source).getCaption();
resetStyles();
if (data instanceof Item) {
LinkedList rlist = new LinkedList();
rlist.add(data);
setSelectedResources(rlist);
} else {
String category = (String) data;
LinkedList resources = (LinkedList) categoryResources
.get(category);
setSelectedResources(resources);
}
((Button) source).setStyle("selected-link");
}
public void buttonClick(ClickEvent event) {
Object source = event.getSource();
if (source instanceof Button) {
Object data = ((Button) source).getData();
String name = ((Button) source).getCaption();
resetStyles();
if (data instanceof Item) {
LinkedList rlist = new LinkedList();
rlist.add(data);
setSelectedResources(rlist);
} else {
String category = (String) data;
LinkedList resources = (LinkedList) categoryResources
.get(category);
setSelectedResources(resources);
}
((Button)source).setStyle("selected-link");
}
}
private void resetStyles() {
for (Iterator it = categoryLayouts.values().iterator();it.hasNext();) {
Layout lo = (Layout)it.next();
for (Iterator bit = lo.getComponentIterator();bit.hasNext();) {
Button b = (Button)bit.next();
if (b.getData() instanceof Item) {
b.setStyle("link");
} else {
b.setStyle("important-link");
private void resetStyles() {
for (Iterator it = categoryLayouts.values().iterator(); it.hasNext();) {
Layout lo = (Layout) it.next();
for (Iterator bit = lo.getComponentIterator(); bit.hasNext();) {
Button b = (Button) bit.next();
if (b.getData() instanceof Item) {
b.setStyle("link");
} else {
b.setStyle("important-link");
}
}
}
}
}
}
public class SelectedResourcesChangedEvent extends Event {
public SelectedResourcesChangedEvent() {
super(ResourceSelectorPanel.this);
public class SelectedResourcesChangedEvent extends Event {
public SelectedResourcesChangedEvent() {
super(ResourceSelectorPanel.this);
}
}
}
}

+ 468
- 433
src/com/itmill/toolkit/demo/reservation/SampleDB.java View File

@@ -15,464 +15,499 @@ import com.itmill.toolkit.data.Item;
import com.itmill.toolkit.data.util.QueryContainer;

public class SampleDB {
public class User {
public static final String TABLE = "USER";
public static final String PROPERTY_ID_ID = TABLE + "_ID";
public static final String PROPERTY_ID_FULLNAME = TABLE + "_FULLNAME";
public static final String PROPERTY_ID_EMAIL = TABLE + "_EMAIL";
public static final String PROPERTY_ID_PASSWORD = TABLE + "_PASSWORD";
public static final String PROPERTY_ID_DELETED = TABLE + "_DELETED";
}

public class Resource {
public static final String TABLE = "RESOURCE";
public static final String PROPERTY_ID_ID = TABLE + "_ID";
public static final String PROPERTY_ID_NAME = TABLE + "_NAME";
public static final String PROPERTY_ID_DESCRIPTION = TABLE
+ "_DESCRIPTION";
public static final String PROPERTY_ID_LOCATIONX = TABLE
+ "_LOCATION_X";
public static final String PROPERTY_ID_LOCATIONY = TABLE
+ "_LOCATION_Y";
public static final String PROPERTY_ID_CATEGORY = TABLE + "_CATEGORY";
public static final String PROPERTY_ID_DELETED = TABLE + "_DELETED";
}

public class Reservation {
public static final String TABLE = "RESERVATION";
public static final String PROPERTY_ID_ID = TABLE + "_ID";
public static final String PROPERTY_ID_DESCRIPTION = TABLE
+ "_DESCRIPTION";
public static final String PROPERTY_ID_RESOURCE_ID = TABLE
+ "_RESOURCE_ID";
public static final String PROPERTY_ID_RESERVED_BY_ID = TABLE
+ "_RESERVED_BY_USER_ID";
public static final String PROPERTY_ID_RESERVED_FROM = TABLE
+ "_RESERVED_FROM";
public static final String PROPERTY_ID_RESERVED_TO = TABLE
+ "_RESERVED_TO";
}

// TODO -> param
private static final String DB_URL = "jdbc:hsqldb:file:reservation.db";

private static final String CREATE_TABLE_USER = "CREATE TABLE "
+ User.TABLE + " (" + " " + User.PROPERTY_ID_ID
+ " INTEGER IDENTITY" + ", " + User.PROPERTY_ID_FULLNAME
+ " VARCHAR(100) NOT NULL" + ", " + User.PROPERTY_ID_EMAIL
+ " VARCHAR(50) NOT NULL" + ", " + User.PROPERTY_ID_PASSWORD
+ " VARCHAR(20) NOT NULL" + ", " + User.PROPERTY_ID_DELETED
+ " BOOLEAN DEFAULT false NOT NULL" + ", UNIQUE("
+ User.PROPERTY_ID_FULLNAME + "), UNIQUE(" + User.PROPERTY_ID_EMAIL
+ ") )";
private static final String CREATE_TABLE_RESOURCE = "CREATE TABLE "
+ Resource.TABLE + " (" + " " + Resource.PROPERTY_ID_ID
+ " INTEGER IDENTITY" + ", " + Resource.PROPERTY_ID_NAME
+ " VARCHAR(30) NOT NULL" + ", " + Resource.PROPERTY_ID_DESCRIPTION
+ " VARCHAR(100)" + ", " + Resource.PROPERTY_ID_LOCATIONX
+ " DOUBLE" + ", " + Resource.PROPERTY_ID_LOCATIONY + " DOUBLE"
+ ", " + Resource.PROPERTY_ID_CATEGORY + " VARCHAR(30)" + ", "
+ Resource.PROPERTY_ID_DELETED + " BOOLEAN DEFAULT false NOT NULL"
+ ", UNIQUE(" + Resource.PROPERTY_ID_NAME + "))";
private static final String CREATE_TABLE_RESERVATION = "CREATE TABLE "
+ Reservation.TABLE + " (" + " " + Reservation.PROPERTY_ID_ID
+ " INTEGER IDENTITY" + ", " + Reservation.PROPERTY_ID_RESOURCE_ID
+ " INTEGER" + ", " + Reservation.PROPERTY_ID_RESERVED_BY_ID
+ " INTEGER" + ", " + Reservation.PROPERTY_ID_RESERVED_FROM
+ " TIMESTAMP NOT NULL" + ", "
+ Reservation.PROPERTY_ID_RESERVED_TO + " TIMESTAMP NOT NULL"
+ ", " + Reservation.PROPERTY_ID_DESCRIPTION + " VARCHAR(100)"
+ ", FOREIGN KEY (" + Reservation.PROPERTY_ID_RESOURCE_ID
+ ") REFERENCES " + Resource.TABLE + "(" + Resource.PROPERTY_ID_ID
+ "), FOREIGN KEY (" + Reservation.PROPERTY_ID_RESERVED_BY_ID
+ ") REFERENCES " + User.TABLE + "(" + User.PROPERTY_ID_ID + "))";

private Connection connection = null;

/**
* Create database.
*/
public SampleDB() {
this(false);
}

public SampleDB(boolean recreate) {
// connect to SQL database
connect();

if (recreate) {
dropTables();
public class User {
public static final String TABLE = "USER";
public static final String PROPERTY_ID_ID = TABLE + "_ID";
public static final String PROPERTY_ID_FULLNAME = TABLE + "_FULLNAME";
public static final String PROPERTY_ID_EMAIL = TABLE + "_EMAIL";
public static final String PROPERTY_ID_PASSWORD = TABLE + "_PASSWORD";
public static final String PROPERTY_ID_DELETED = TABLE + "_DELETED";
}

// initialize SQL database
createTables();
// test by executing sample JDBC query
testDatabase();
}
private void dropTables() {
try {
update("DROP TABLE " + Reservation.TABLE);
} catch (SQLException IGNORED) {
// IGNORED, assuming it was not there
public class Resource {
public static final String TABLE = "RESOURCE";
public static final String PROPERTY_ID_ID = TABLE + "_ID";
public static final String PROPERTY_ID_NAME = TABLE + "_NAME";
public static final String PROPERTY_ID_DESCRIPTION = TABLE
+ "_DESCRIPTION";
public static final String PROPERTY_ID_LOCATIONX = TABLE
+ "_LOCATION_X";
public static final String PROPERTY_ID_LOCATIONY = TABLE
+ "_LOCATION_Y";
public static final String PROPERTY_ID_CATEGORY = TABLE + "_CATEGORY";
public static final String PROPERTY_ID_DELETED = TABLE + "_DELETED";
}
try {
update("DROP TABLE " + Resource.TABLE);
} catch (SQLException IGNORED) {
// IGNORED, assuming it was not there

public class Reservation {
public static final String TABLE = "RESERVATION";
public static final String PROPERTY_ID_ID = TABLE + "_ID";
public static final String PROPERTY_ID_DESCRIPTION = TABLE
+ "_DESCRIPTION";
public static final String PROPERTY_ID_RESOURCE_ID = TABLE
+ "_RESOURCE_ID";
public static final String PROPERTY_ID_RESERVED_BY_ID = TABLE
+ "_RESERVED_BY_USER_ID";
public static final String PROPERTY_ID_RESERVED_FROM = TABLE
+ "_RESERVED_FROM";
public static final String PROPERTY_ID_RESERVED_TO = TABLE
+ "_RESERVED_TO";
}
try {
update("DROP TABLE " + User.TABLE);
} catch (SQLException IGNORED) {
// IGNORED, assuming it was not there

// TODO -> param
private static final String DB_URL = "jdbc:hsqldb:file:reservation.db";

private static final String CREATE_TABLE_USER = "CREATE TABLE "
+ User.TABLE + " (" + " " + User.PROPERTY_ID_ID
+ " INTEGER IDENTITY" + ", " + User.PROPERTY_ID_FULLNAME
+ " VARCHAR(100) NOT NULL" + ", " + User.PROPERTY_ID_EMAIL
+ " VARCHAR(50) NOT NULL" + ", " + User.PROPERTY_ID_PASSWORD
+ " VARCHAR(20) NOT NULL" + ", " + User.PROPERTY_ID_DELETED
+ " BOOLEAN DEFAULT false NOT NULL" + ", UNIQUE("
+ User.PROPERTY_ID_FULLNAME + "), UNIQUE(" + User.PROPERTY_ID_EMAIL
+ ") )";
private static final String CREATE_TABLE_RESOURCE = "CREATE TABLE "
+ Resource.TABLE + " (" + " " + Resource.PROPERTY_ID_ID
+ " INTEGER IDENTITY" + ", " + Resource.PROPERTY_ID_NAME
+ " VARCHAR(30) NOT NULL" + ", " + Resource.PROPERTY_ID_DESCRIPTION
+ " VARCHAR(100)" + ", " + Resource.PROPERTY_ID_LOCATIONX
+ " DOUBLE" + ", " + Resource.PROPERTY_ID_LOCATIONY + " DOUBLE"
+ ", " + Resource.PROPERTY_ID_CATEGORY + " VARCHAR(30)" + ", "
+ Resource.PROPERTY_ID_DELETED + " BOOLEAN DEFAULT false NOT NULL"
+ ", UNIQUE(" + Resource.PROPERTY_ID_NAME + "))";
private static final String CREATE_TABLE_RESERVATION = "CREATE TABLE "
+ Reservation.TABLE + " (" + " " + Reservation.PROPERTY_ID_ID
+ " INTEGER IDENTITY" + ", " + Reservation.PROPERTY_ID_RESOURCE_ID
+ " INTEGER" + ", " + Reservation.PROPERTY_ID_RESERVED_BY_ID
+ " INTEGER" + ", " + Reservation.PROPERTY_ID_RESERVED_FROM
+ " TIMESTAMP NOT NULL" + ", "
+ Reservation.PROPERTY_ID_RESERVED_TO + " TIMESTAMP NOT NULL"
+ ", " + Reservation.PROPERTY_ID_DESCRIPTION + " VARCHAR(100)"
+ ", FOREIGN KEY (" + Reservation.PROPERTY_ID_RESOURCE_ID
+ ") REFERENCES " + Resource.TABLE + "(" + Resource.PROPERTY_ID_ID
+ "), FOREIGN KEY (" + Reservation.PROPERTY_ID_RESERVED_BY_ID
+ ") REFERENCES " + User.TABLE + "(" + User.PROPERTY_ID_ID + "))";

private Connection connection = null;

/**
* Create database.
*/
public SampleDB() {
this(false);
}
}

/**
* Connect to SQL database. In this sample we use HSQLDB and an toolkit
* named database in implicitly created into system memory.
*
*/
private void connect() {
try {
Class.forName("org.hsqldb.jdbcDriver").newInstance();
connection = DriverManager.getConnection(DB_URL);
} catch (Exception e) {
throw new RuntimeException(e);

public SampleDB(boolean recreate) {
// connect to SQL database
connect();

if (recreate) {
dropTables();
}

// initialize SQL database
createTables();

// test by executing sample JDBC query
testDatabase();
}
}

/**
* use for SQL commands CREATE, DROP, INSERT and UPDATE
*
* @param expression
* @throws SQLException
*/
private void update(String expression) throws SQLException {
Statement st = null;
st = connection.createStatement();
int i = st.executeUpdate(expression);
if (i == -1) {
System.out.println("SampleDatabase error : " + expression);

private void dropTables() {
try {
update("DROP TABLE " + Reservation.TABLE);
} catch (SQLException IGNORED) {
// IGNORED, assuming it was not there
}
try {
update("DROP TABLE " + Resource.TABLE);
} catch (SQLException IGNORED) {
// IGNORED, assuming it was not there
}
try {
update("DROP TABLE " + User.TABLE);
} catch (SQLException IGNORED) {
// IGNORED, assuming it was not there
}
}
st.close();
}

/**
* Create test table and few rows. Issue note: using capitalized column
* names as HSQLDB returns column names in capitalized form with this demo.
*
*/
private void createTables() {
try {
String stmt = null;
stmt = CREATE_TABLE_RESOURCE;
update(stmt);
} catch (SQLException e) {
if (e.toString().indexOf("Table already exists") == -1)
throw new RuntimeException(e);

/**
* Connect to SQL database. In this sample we use HSQLDB and an toolkit
* named database in implicitly created into system memory.
*
*/
private void connect() {
try {
Class.forName("org.hsqldb.jdbcDriver").newInstance();
connection = DriverManager.getConnection(DB_URL);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
try {
String stmt = null;
stmt = CREATE_TABLE_USER;
update(stmt);
} catch (SQLException e) {
if (e.toString().indexOf("Table already exists") == -1)
throw new RuntimeException(e);

/**
* use for SQL commands CREATE, DROP, INSERT and UPDATE
*
* @param expression
* @throws SQLException
*/
private void update(String expression) throws SQLException {
Statement st = null;
st = connection.createStatement();
int i = st.executeUpdate(expression);
if (i == -1) {
System.out.println("SampleDatabase error : " + expression);
}
st.close();
}
try {
String stmt = null;
stmt = CREATE_TABLE_RESERVATION;
update(stmt);
} catch (SQLException e) {
if (e.toString().indexOf("Table already exists") == -1)
throw new RuntimeException(e);

/**
* Create test table and few rows. Issue note: using capitalized column
* names as HSQLDB returns column names in capitalized form with this demo.
*
*/
private void createTables() {
try {
String stmt = null;
stmt = CREATE_TABLE_RESOURCE;
update(stmt);
} catch (SQLException e) {
if (e.toString().indexOf("Table already exists") == -1)
throw new RuntimeException(e);
}
try {
String stmt = null;
stmt = CREATE_TABLE_USER;
update(stmt);
} catch (SQLException e) {
if (e.toString().indexOf("Table already exists") == -1)
throw new RuntimeException(e);
}
try {
String stmt = null;
stmt = CREATE_TABLE_RESERVATION;
update(stmt);
} catch (SQLException e) {
if (e.toString().indexOf("Table already exists") == -1)
throw new RuntimeException(e);
}
}
}

/**
* Test database connection with simple SELECT command.
*
*/
private String testDatabase() {
String result = null;
try {
Statement stmt = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM "
+ Resource.TABLE);
rs.next();
result = "rowcount for table test is " + rs.getObject(1).toString();
stmt.close();
} catch (SQLException e) {
throw new RuntimeException(e);

/**
* Test database connection with simple SELECT command.
*
*/
private String testDatabase() {
String result = null;
try {
Statement stmt = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM "
+ Resource.TABLE);
rs.next();
result = "rowcount for table test is " + rs.getObject(1).toString();
stmt.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
return result;
}
return result;
}

public Connection getConnection() {
return connection;
}

public Container getCategories() {
// TODO where deleted=?
String q = "SELECT DISTINCT(" + Resource.PROPERTY_ID_CATEGORY
+ ") FROM " + Resource.TABLE + " ORDER BY "
+ Resource.PROPERTY_ID_CATEGORY;
try {
return new QueryContainer(q, connection,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
} catch (SQLException e) {
throw new RuntimeException(e);

public Connection getConnection() {
return connection;
}

}
public Container getCategories() {
// TODO where deleted=?
String q = "SELECT DISTINCT(" + Resource.PROPERTY_ID_CATEGORY
+ ") FROM " + Resource.TABLE + " ORDER BY "
+ Resource.PROPERTY_ID_CATEGORY;
try {
return new QueryContainer(q, connection,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
} catch (SQLException e) {
throw new RuntimeException(e);
}

public Container getResources(String category) {
// TODO where deleted=?
String q = "SELECT * FROM " + Resource.TABLE;
if (category != null) {
q += " WHERE " + Resource.PROPERTY_ID_CATEGORY + "='" + category
+ "'"; // FIXME ->
// PreparedStatement!
}

try {
return new QueryContainer(q, connection,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
} catch (SQLException e) {
throw new RuntimeException(e);
}
public Container getResources(String category) {
// TODO where deleted=?
String q = "SELECT * FROM " + Resource.TABLE;
if (category != null) {
q += " WHERE " + Resource.PROPERTY_ID_CATEGORY + "='" + category
+ "'"; // FIXME ->
// PreparedStatement!
}

}

public Container getReservations(List resources) {
// TODO where reserved_by=?
// TODO where from=?
// TODO where to=?
// TODO where deleted=?
String q = "SELECT * FROM " + Reservation.TABLE + "," + Resource.TABLE;
q += " WHERE " + Reservation.PROPERTY_ID_RESOURCE_ID + "="
+ Resource.PROPERTY_ID_ID;
if (resources != null && resources.size() > 0) {
StringBuilder s = new StringBuilder();
for (Iterator it = resources.iterator(); it.hasNext();) {
if (s.length() > 0) {
s.append(",");
try {
return new QueryContainer(q, connection,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
} catch (SQLException e) {
throw new RuntimeException(e);
}
s.append(((Item) it.next())
.getItemProperty(Resource.PROPERTY_ID_ID));
}
q += " HAVING " + Reservation.PROPERTY_ID_RESOURCE_ID + " IN (" + s
+ ")";
}
q += " ORDER BY " + Reservation.PROPERTY_ID_RESERVED_FROM;
try {
QueryContainer qc = new QueryContainer(q, connection,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
if (qc.size() < 1) {
return null;
} else {
return qc;
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}

public void addReservation(Item resource, int reservedById,
Date reservedFrom, Date reservedTo, String description) {
if (reservedFrom.after(reservedTo)) {
Date tmp = reservedTo;
reservedTo = reservedFrom;
reservedFrom = tmp;

}
int resourceId = ((Integer) resource.getItemProperty(
Resource.PROPERTY_ID_ID).getValue()).intValue();
String q = "INSERT INTO " + Reservation.TABLE + " ("
+ Reservation.PROPERTY_ID_RESOURCE_ID + ","
+ Reservation.PROPERTY_ID_RESERVED_BY_ID + ","
+ Reservation.PROPERTY_ID_RESERVED_FROM + ","
+ Reservation.PROPERTY_ID_RESERVED_TO + ","
+ Reservation.PROPERTY_ID_DESCRIPTION + ")"
+ "VALUES (?,?,?,?,?)";
synchronized (DB_URL) {
try {
if (!isAvailableResource(resourceId, reservedFrom, reservedTo)) {
throw new ResourceNotAvailableException(
"The resource is not available at that time.");

public Container getReservations(List resources) {
// TODO where reserved_by=?
// TODO where from=?
// TODO where to=?
// TODO where deleted=?
String q = "SELECT * FROM " + Reservation.TABLE + "," + Resource.TABLE;
q += " WHERE " + Reservation.PROPERTY_ID_RESOURCE_ID + "="
+ Resource.PROPERTY_ID_ID;
if (resources != null && resources.size() > 0) {
StringBuilder s = new StringBuilder();
for (Iterator it = resources.iterator(); it.hasNext();) {
if (s.length() > 0) {
s.append(",");
}
s.append(((Item) it.next())
.getItemProperty(Resource.PROPERTY_ID_ID));
}
q += " HAVING " + Reservation.PROPERTY_ID_RESOURCE_ID + " IN (" + s
+ ")";
}
q += " ORDER BY " + Reservation.PROPERTY_ID_RESERVED_FROM;
try {
QueryContainer qc = new QueryContainer(q, connection,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
if (qc.size() < 1) {
return null;
} else {
return qc;
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
PreparedStatement p = connection.prepareStatement(q);
p.setInt(1, resourceId);
p.setInt(2, reservedById);
p.setTimestamp(3,
new java.sql.Timestamp(reservedFrom.getTime()));
p.setTimestamp(4, new java.sql.Timestamp(reservedTo.getTime()));
p.setString(5, description);
p.execute();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

public boolean isAvailableResource(int resourceId, Date reservedFrom,
Date reservedTo) {
// TODO where deleted=?
if (reservedFrom.after(reservedTo)) {
Date tmp = reservedTo;
reservedTo = reservedFrom;
reservedFrom = tmp;
}
String checkQ = "SELECT count(*) FROM " + Reservation.TABLE + " WHERE "
+ Reservation.PROPERTY_ID_RESOURCE_ID + "=? AND (("
+ Reservation.PROPERTY_ID_RESERVED_FROM + ">=? AND "
+ Reservation.PROPERTY_ID_RESERVED_FROM + "<=?) OR ("
+ Reservation.PROPERTY_ID_RESERVED_TO + ">=? AND "
+ Reservation.PROPERTY_ID_RESERVED_TO + "<=?) OR ("
+ Reservation.PROPERTY_ID_RESERVED_FROM + "<=? AND "
+ Reservation.PROPERTY_ID_RESERVED_TO + ">=?)" + ")";
try {
PreparedStatement p = connection.prepareStatement(checkQ);
p.setInt(1, resourceId);
p.setTimestamp(2, new java.sql.Timestamp(reservedFrom.getTime()));
p.setTimestamp(3, new java.sql.Timestamp(reservedTo.getTime()));
p.setTimestamp(4, new java.sql.Timestamp(reservedFrom.getTime()));
p.setTimestamp(5, new java.sql.Timestamp(reservedTo.getTime()));
p.setTimestamp(6, new java.sql.Timestamp(reservedFrom.getTime()));
p.setTimestamp(7, new java.sql.Timestamp(reservedTo.getTime()));
p.execute();
ResultSet rs = p.getResultSet();
if (rs.next() && rs.getInt(1) > 0) {
return false;
}
} catch (Exception e) {
throw new RuntimeException(e);

public void addReservation(Item resource, int reservedById,
Date reservedFrom, Date reservedTo, String description) {
if (reservedFrom.after(reservedTo)) {
Date tmp = reservedTo;
reservedTo = reservedFrom;
reservedFrom = tmp;
}
int resourceId = ((Integer) resource.getItemProperty(
Resource.PROPERTY_ID_ID).getValue()).intValue();
String q = "INSERT INTO " + Reservation.TABLE + " ("
+ Reservation.PROPERTY_ID_RESOURCE_ID + ","
+ Reservation.PROPERTY_ID_RESERVED_BY_ID + ","
+ Reservation.PROPERTY_ID_RESERVED_FROM + ","
+ Reservation.PROPERTY_ID_RESERVED_TO + ","
+ Reservation.PROPERTY_ID_DESCRIPTION + ")"
+ "VALUES (?,?,?,?,?)";
synchronized (DB_URL) {
try {
if (!isAvailableResource(resourceId, reservedFrom, reservedTo)) {
throw new ResourceNotAvailableException(
"The resource is not available at that time.");
}
PreparedStatement p = connection.prepareStatement(q);
p.setInt(1, resourceId);
p.setInt(2, reservedById);
p.setTimestamp(3,
new java.sql.Timestamp(reservedFrom.getTime()));
p.setTimestamp(4, new java.sql.Timestamp(reservedTo.getTime()));
p.setString(5, description);
p.execute();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
return true;
}

public Container getUsers() {
// TODO where deleted=?
String q = "SELECT * FROM " + User.TABLE + " ORDER BY "
+ User.PROPERTY_ID_FULLNAME;
try {
QueryContainer qc = new QueryContainer(q, connection,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
return qc;
} catch (SQLException e) {
throw new RuntimeException(e);

public boolean isAvailableResource(int resourceId, Date reservedFrom,
Date reservedTo) {
// TODO where deleted=?
if (reservedFrom.after(reservedTo)) {
Date tmp = reservedTo;
reservedTo = reservedFrom;
reservedFrom = tmp;
}
String checkQ = "SELECT count(*) FROM " + Reservation.TABLE + " WHERE "
+ Reservation.PROPERTY_ID_RESOURCE_ID + "=? AND (("
+ Reservation.PROPERTY_ID_RESERVED_FROM + ">=? AND "
+ Reservation.PROPERTY_ID_RESERVED_FROM + "<=?) OR ("
+ Reservation.PROPERTY_ID_RESERVED_TO + ">=? AND "
+ Reservation.PROPERTY_ID_RESERVED_TO + "<=?) OR ("
+ Reservation.PROPERTY_ID_RESERVED_FROM + "<=? AND "
+ Reservation.PROPERTY_ID_RESERVED_TO + ">=?)" + ")";
try {
PreparedStatement p = connection.prepareStatement(checkQ);
p.setInt(1, resourceId);
p.setTimestamp(2, new java.sql.Timestamp(reservedFrom.getTime()));
p.setTimestamp(3, new java.sql.Timestamp(reservedTo.getTime()));
p.setTimestamp(4, new java.sql.Timestamp(reservedFrom.getTime()));
p.setTimestamp(5, new java.sql.Timestamp(reservedTo.getTime()));
p.setTimestamp(6, new java.sql.Timestamp(reservedFrom.getTime()));
p.setTimestamp(7, new java.sql.Timestamp(reservedTo.getTime()));
p.execute();
ResultSet rs = p.getResultSet();
if (rs.next() && rs.getInt(1) > 0) {
return false;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return true;
}
}

public void generateResources() {
/*
* map.addMarker("Old Mill", new Point.Double(60.452224f,22.299929f));
* map.addMarker("ICT", new Point.Double(60.449007f,22.295508f));
* map.addMarker("DataCity", new Point.Double(60.448329f,22.295165f));
* map.addMarker("BioCity", new Point.Double(60.449451f,22.293105f));
* map.addMarker("PharmaCity", new Point.Double(60.44888f,22.292032f));
* map.addMarker("Intelligate", new Point.Double(60.450403f,22.29495f));
* map.addMarker("Paviljonki", new Point.Double(60.445408f,22.290831f));
* map.addMarker("Trivium", new Point.Double(60.44641962165445f,
* 22.301753170493f)); map.addMarker("Linja-auto asema", new
* Point.Double(60.457049f,22.267957f));
*/
/*
Object[][] resources = {
{ "IT Mill Toolkit Manual", "the manual", "Books", new Double(60.452224),new Double(22.299929)},
{ "IT Mill Toolkit for Dummies", "the hardcover version",
"Books", new Double(60.452224),new Double(22.299929) },
{ "Sony", "Old Sony video projector", "AV equipment", new Double(60.449007),new Double(22.295508) },
{ "Sanyo", "Brand new hd-ready video projector", "AV equipment", new Double(60.452224),new Double(22.299929) },
{ "Room 7", "Conference room in the lobby", "Conference rooms", new Double(60.449451),new Double(22.292032) },
{ "Nintendo Wii", "Teh uber fun", "Entertainment", new Double(60.445408),new Double(22.290831) },
{ "Playstation", "We don't actually have one", "Entertainment", new Double(60.44641962165445),new Double(22.301753170493) },
{ "Luokkahuone", "Classroom right next to IT Mill",
"Conference rooms", new Double(60.44888),new Double(22.292032) }
};
*/
Object[][] resources = {
// Turku
{ "01 Ford Mondeo", "w/ company logo", "Turku", new Double(60.510857),new Double(22.275424)},
{ "02 Citroen Jumper", "w/ company logo. 12m3 storage space.", "Turku", new Double(60.452171),new Double(22.2995)},
{ "03 Saab 93", "Cabriolet<br/>Keys from the rental desk.", "Turku", new Double(60.4507),new Double(22.295551)},
{ "04 Volvo S60", "Key from the rental desk.", "Turku", new Double(60.434722),new Double(22.224398)},
{ "05 Smart fourtwo", "Cabrio. Keys from infodesk.", "Turku", new Double(60.508970),new Double(22.264790)},
// Helsinki
{ "06 Smart fourtwo", "Cabrio. Keys from infodesk.", "Helsinki", new Double(60.17175),new Double(24.939029)},
{ "07 Smart fourtwo", "Cabrio. Keys from infodesk.", "Helsinki", new Double(60.17175),new Double(24.939029)},
{ "08 Smart fourtwo", "Cabrio. Keys from infodesk.", "Helsinki", new Double(60.166579),new Double(24.953899)},
{ "09 Volvo S60", "Keys from infodesk.", "Helsinki", new Double(60.317832),new Double(24.967289)},
{ "10 Saab 93", "Keys from infodesk.", "Helsinki", new Double(60.249193),new Double(25.045921)},
// Silicon Valley
{ "11 Ford Mustang", "Keys from Acme clerk.", "Silicon Valley", new Double(37.615853),new Double(-122.386384)},
{ "12 Ford Mondeo", "Keys from infodesk.", "Silicon Valley", new Double(37.365028),new Double(-121.922654)},
{ "13 Ford Mustang", "GT Cal Special. Keys from guard.", "Silicon Valley", new Double(37.403812),new Double(-121.977425)},
{ "14 Ford Mustang", "GT Cal Special. Keys from guard.", "Silicon Valley", new Double(37.403812),new Double(-121.977425)},
{ "15 Land Rover", "Keys from infodesk.", "Silicon Valley", new Double(37.365028),new Double(-121.922654)},
// Paris
{ "17 Peugeot 308", "Keys from infodesk.", "Paris", new Double(48.844756),new Double(2.372784)},
{ "18 Citroën C6", "Keys from rental desk.", "Paris", new Double(49.007253),new Double(2.545025)},
{ "19 Citroën C6", "Keys from infodesk.", "Paris", new Double(48.729061),new Double(2.368087)},
{ "20 Peugeot 308", "Keys from ticket sales.", "Paris", new Double(48.880931),new Double(2.356988)},
{ "21 Peugeot 308", "Keys from ticket sales.", "Paris", new Double(48.876479),new Double(2.358161)},
// STHLM
{ "22 Volvo S60", "Keys from infodesk.", "Stockholm", new Double(59.350414),new Double(18.106574)},
{ "23 Saab 93", "Keys from infodesk.", "Stockholm", new Double(59.355905),new Double(17.946784)},
{ "24 Smart fourtwo", "Keys from infodesk.", "Stockholm", new Double(59.315939),new Double(18.095904)},
{ "25 Smart fourtwo", "Keys from infodesk.", "Stockholm", new Double(59.330716),new Double(18.058702)},
// Boston
{ "26 Ford Mustang", "Keys from infodesk.", "Boston", new Double(42.366588),new Double(-71.020955)},
{ "27 Smart fourtwo", "Keys from infodesk.", "Boston", new Double(42.365419),new Double(-71.061748)},
{ "28 Volvo S60", "Keys from Seaport Hotel reception.", "Boston", new Double(42.34811),new Double(-71.041127)},
{ "29 Smart fourtwo", "Keys from Seaport Hotel reception.", "Boston", new Double(42.348072),new Double(-71.041315)},

};
String q = "INSERT INTO " + Resource.TABLE + "("
+ Resource.PROPERTY_ID_NAME + ","
+ Resource.PROPERTY_ID_DESCRIPTION + ","
+ Resource.PROPERTY_ID_CATEGORY + ","
+ Resource.PROPERTY_ID_LOCATIONX + ","
+ Resource.PROPERTY_ID_LOCATIONY
+ ")" + " VALUES (?,?,?,?,?)";
try {
PreparedStatement stmt = connection.prepareStatement(q);
for (int i = 0; i < resources.length; i++) {
int j=0;
stmt.setString(j+1, (String)resources[i][j++]);
stmt.setString(j+1, (String)resources[i][j++]);
stmt.setString(j+1, (String)resources[i][j++]);
stmt.setDouble(j+1, ((Double)resources[i][j++]).doubleValue());
stmt.setDouble(j+1, ((Double)resources[i][j++]).doubleValue());
stmt.execute();
}
} catch (SQLException e) {
throw new RuntimeException(e);

public Container getUsers() {
// TODO where deleted=?
String q = "SELECT * FROM " + User.TABLE + " ORDER BY "
+ User.PROPERTY_ID_FULLNAME;
try {
QueryContainer qc = new QueryContainer(q, connection,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
return qc;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}

public void generateDemoUser() {
String q = "INSERT INTO USER (" + User.PROPERTY_ID_FULLNAME + ","
+ User.PROPERTY_ID_EMAIL + "," + User.PROPERTY_ID_PASSWORD
+ ") VALUES (?,?,?)";
try {
PreparedStatement stmt = connection.prepareStatement(q);
stmt.setString(1, "Demo User");
stmt.setString(2, "demo.user@itmill.com");
stmt.setString(3, "demo");
stmt.execute();
} catch (SQLException e) {
throw new RuntimeException(e);

public void generateResources() {
/*
* map.addMarker("Old Mill", new Point.Double(60.452224f,22.299929f));
* map.addMarker("ICT", new Point.Double(60.449007f,22.295508f));
* map.addMarker("DataCity", new Point.Double(60.448329f,22.295165f));
* map.addMarker("BioCity", new Point.Double(60.449451f,22.293105f));
* map.addMarker("PharmaCity", new Point.Double(60.44888f,22.292032f));
* map.addMarker("Intelligate", new Point.Double(60.450403f,22.29495f));
* map.addMarker("Paviljonki", new Point.Double(60.445408f,22.290831f));
* map.addMarker("Trivium", new Point.Double(60.44641962165445f,
* 22.301753170493f)); map.addMarker("Linja-auto asema", new
* Point.Double(60.457049f,22.267957f));
*/
/*
* Object[][] resources = { { "IT Mill Toolkit Manual", "the manual",
* "Books", new Double(60.452224),new Double(22.299929)}, { "IT Mill
* Toolkit for Dummies", "the hardcover version", "Books", new
* Double(60.452224),new Double(22.299929) }, { "Sony", "Old Sony video
* projector", "AV equipment", new Double(60.449007),new
* Double(22.295508) }, { "Sanyo", "Brand new hd-ready video projector",
* "AV equipment", new Double(60.452224),new Double(22.299929) }, {
* "Room 7", "Conference room in the lobby", "Conference rooms", new
* Double(60.449451),new Double(22.292032) }, { "Nintendo Wii", "Teh
* uber fun", "Entertainment", new Double(60.445408),new
* Double(22.290831) }, { "Playstation", "We don't actually have one",
* "Entertainment", new Double(60.44641962165445),new
* Double(22.301753170493) }, { "Luokkahuone", "Classroom right next to
* IT Mill", "Conference rooms", new Double(60.44888),new
* Double(22.292032) } };
*/
Object[][] resources = {
// Turku
{ "01 Ford Mondeo", "w/ company logo", "Turku",
new Double(60.510857), new Double(22.275424) },
{ "02 Citroen Jumper", "w/ company logo. 12m3 storage space.",
"Turku", new Double(60.452171), new Double(22.2995) },
{ "03 Saab 93", "Cabriolet<br/>Keys from the rental desk.",
"Turku", new Double(60.4507), new Double(22.295551) },
{ "04 Volvo S60", "Key from the rental desk.", "Turku",
new Double(60.434722), new Double(22.224398) },
{ "05 Smart fourtwo", "Cabrio. Keys from infodesk.", "Turku",
new Double(60.508970), new Double(22.264790) },
// Helsinki
{ "06 Smart fourtwo", "Cabrio. Keys from infodesk.",
"Helsinki", new Double(60.17175), new Double(24.939029) },
{ "07 Smart fourtwo", "Cabrio. Keys from infodesk.",
"Helsinki", new Double(60.17175), new Double(24.939029) },
{ "08 Smart fourtwo", "Cabrio. Keys from infodesk.",
"Helsinki", new Double(60.166579),
new Double(24.953899) },
{ "09 Volvo S60", "Keys from infodesk.", "Helsinki",
new Double(60.317832), new Double(24.967289) },
{ "10 Saab 93", "Keys from infodesk.", "Helsinki",
new Double(60.249193), new Double(25.045921) },
// Silicon Valley
{ "11 Ford Mustang", "Keys from Acme clerk.", "Silicon Valley",
new Double(37.615853), new Double(-122.386384) },
{ "12 Ford Mondeo", "Keys from infodesk.", "Silicon Valley",
new Double(37.365028), new Double(-121.922654) },
{ "13 Ford Mustang", "GT Cal Special. Keys from guard.",
"Silicon Valley", new Double(37.403812),
new Double(-121.977425) },
{ "14 Ford Mustang", "GT Cal Special. Keys from guard.",
"Silicon Valley", new Double(37.403812),
new Double(-121.977425) },
{ "15 Land Rover", "Keys from infodesk.", "Silicon Valley",
new Double(37.365028), new Double(-121.922654) },
// Paris
{ "17 Peugeot 308", "Keys from infodesk.", "Paris",
new Double(48.844756), new Double(2.372784) },
{ "18 Citroën C6", "Keys from rental desk.", "Paris",
new Double(49.007253), new Double(2.545025) },
{ "19 Citroën C6", "Keys from infodesk.", "Paris",
new Double(48.729061), new Double(2.368087) },
{ "20 Peugeot 308", "Keys from ticket sales.", "Paris",
new Double(48.880931), new Double(2.356988) },
{ "21 Peugeot 308", "Keys from ticket sales.", "Paris",
new Double(48.876479), new Double(2.358161) },
// STHLM
{ "22 Volvo S60", "Keys from infodesk.", "Stockholm",
new Double(59.350414), new Double(18.106574) },
{ "23 Saab 93", "Keys from infodesk.", "Stockholm",
new Double(59.355905), new Double(17.946784) },
{ "24 Smart fourtwo", "Keys from infodesk.", "Stockholm",
new Double(59.315939), new Double(18.095904) },
{ "25 Smart fourtwo", "Keys from infodesk.", "Stockholm",
new Double(59.330716), new Double(18.058702) },
// Boston
{ "26 Ford Mustang", "Keys from infodesk.", "Boston",
new Double(42.366588), new Double(-71.020955) },
{ "27 Smart fourtwo", "Keys from infodesk.", "Boston",
new Double(42.365419), new Double(-71.061748) },
{ "28 Volvo S60", "Keys from Seaport Hotel reception.",
"Boston", new Double(42.34811), new Double(-71.041127) },
{ "29 Smart fourtwo", "Keys from Seaport Hotel reception.",
"Boston", new Double(42.348072), new Double(-71.041315) },

};

String q = "INSERT INTO " + Resource.TABLE + "("
+ Resource.PROPERTY_ID_NAME + ","
+ Resource.PROPERTY_ID_DESCRIPTION + ","
+ Resource.PROPERTY_ID_CATEGORY + ","
+ Resource.PROPERTY_ID_LOCATIONX + ","
+ Resource.PROPERTY_ID_LOCATIONY + ")" + " VALUES (?,?,?,?,?)";
try {
PreparedStatement stmt = connection.prepareStatement(q);
for (int i = 0; i < resources.length; i++) {
int j = 0;
stmt.setString(j + 1, (String) resources[i][j++]);
stmt.setString(j + 1, (String) resources[i][j++]);
stmt.setString(j + 1, (String) resources[i][j++]);
stmt.setDouble(j + 1, ((Double) resources[i][j++])
.doubleValue());
stmt.setDouble(j + 1, ((Double) resources[i][j++])
.doubleValue());
stmt.execute();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}

}
public void generateDemoUser() {
String q = "INSERT INTO USER (" + User.PROPERTY_ID_FULLNAME + ","
+ User.PROPERTY_ID_EMAIL + "," + User.PROPERTY_ID_PASSWORD
+ ") VALUES (?,?,?)";
try {
PreparedStatement stmt = connection.prepareStatement(q);
stmt.setString(1, "Demo User");
stmt.setString(2, "demo.user@itmill.com");
stmt.setString(3, "demo");
stmt.execute();
} catch (SQLException e) {
throw new RuntimeException(e);
}

}

}

+ 18
- 18
src/com/itmill/toolkit/demo/reservation/gwt/client/WidgetSet.java View File

@@ -7,28 +7,28 @@ import com.itmill.toolkit.terminal.gwt.client.DefaultWidgetSet;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
public class WidgetSet extends DefaultWidgetSet {
public Widget createWidget(UIDL uidl) {
String className = resolveWidgetTypeName(uidl);
if ("com.itmill.toolkit.terminal.gwt.client.ui.IGoogleMap"
.equals(className)) {
return new IGoogleMap();
public Widget createWidget(UIDL uidl) {
String className = resolveWidgetTypeName(uidl);
if ("com.itmill.toolkit.terminal.gwt.client.ui.IGoogleMap"
.equals(className)) {
return new IGoogleMap();
}
return super.createWidget(uidl);
}
return super.createWidget(uidl);
}
protected String resolveWidgetTypeName(UIDL uidl) {
protected String resolveWidgetTypeName(UIDL uidl) {
String tag = uidl.getTag();
if ("googlemap".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IGoogleMap";
}
String tag = uidl.getTag();
if ("googlemap".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IGoogleMap";
return super.resolveWidgetTypeName(uidl);
}
return super.resolveWidgetTypeName(uidl);
}
public boolean isCorrectImplementation(Widget currentWidget, UIDL uidl) {
return GWT.getTypeName(currentWidget).equals(
resolveWidgetTypeName(uidl));
}
public boolean isCorrectImplementation(Widget currentWidget, UIDL uidl) {
return GWT.getTypeName(currentWidget).equals(
resolveWidgetTypeName(uidl));
}
}

+ 67
- 66
src/com/itmill/toolkit/demo/reservation/gwt/client/ui/IGoogleMap.java View File

@@ -15,81 +15,82 @@ import com.mapitz.gwt.googleMaps.client.GMarkerEventManager;
public class IGoogleMap extends GMap2Widget implements Paintable {
public static final String CLASSNAME = "i-googlemap";
GMap2EventManager mapEventManager;
GMarkerEventManager markerEventManager;
GMap2 map;
public IGoogleMap() {
setStyleName(CLASSNAME);
mapEventManager = GMap2EventManager.getInstance();
map = this.getGmap();
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
map.clearOverlays();
GLatLng pos = null;
for (Iterator it = uidl.getChildIterator(); it.hasNext();) {
UIDL u = (UIDL) it.next();
if (u.getTag().equals("markers")) {
for (Iterator m = u.getChildIterator(); m.hasNext();) {
UIDL umarker = (UIDL) m.next();
String html = "<span>"+umarker.getStringAttribute("html")+"</span>";
double x = umarker.getDoubleAttribute("x");
double y = umarker.getDoubleAttribute("y");
pos = new GLatLng(x, y);
GMarker marker = new GMarker(pos);
map.addOverlay(marker);
if (html != null) {
addMarkerPopup(marker, html);
}
}
}
}
if (uidl.hasAttribute("width")) {
setWidth(""+uidl.getIntAttribute("width"));
}
if (uidl.hasAttribute("height")) {
setHeight(""+uidl.getIntAttribute("height"));
}
if (uidl.hasAttribute("zoom")) {
map.setZoom(uidl.getIntAttribute("zoom"));
}
if (uidl.hasAttribute("centerX") && uidl.hasAttribute("centerY")) {
GLatLng center = new GLatLng(uidl.getDoubleAttribute("centerX"),
uidl.getDoubleAttribute("centerY"));
map.setCenter(center);
} else if (pos!=null) {
// use last marker position
map.setCenter(pos);
}
public static final String CLASSNAME = "i-googlemap";
}
GMap2EventManager mapEventManager;
GMarkerEventManager markerEventManager;
GMap2 map;
private void addMarkerPopup(GMarker marker, String html) {
if (markerEventManager == null) {
markerEventManager = GMarkerEventManager.getInstance();
public IGoogleMap() {
setStyleName(CLASSNAME);
mapEventManager = GMap2EventManager.getInstance();
map = this.getGmap();
}
markerEventManager.addOnClickListener(marker, new MarkerEventListener(
html));
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
map.clearOverlays();
GLatLng pos = null;
for (Iterator it = uidl.getChildIterator(); it.hasNext();) {
UIDL u = (UIDL) it.next();
if (u.getTag().equals("markers")) {
}
private class MarkerEventListener implements GMarkerEventClickListener {
String html;
for (Iterator m = u.getChildIterator(); m.hasNext();) {
UIDL umarker = (UIDL) m.next();
String html = "<span>" + umarker.getStringAttribute("html")
+ "</span>";
double x = umarker.getDoubleAttribute("x");
double y = umarker.getDoubleAttribute("y");
pos = new GLatLng(x, y);
GMarker marker = new GMarker(pos);
map.addOverlay(marker);
if (html != null) {
addMarkerPopup(marker, html);
}
}
}
}
if (uidl.hasAttribute("width")) {
setWidth("" + uidl.getIntAttribute("width"));
}
if (uidl.hasAttribute("height")) {
setHeight("" + uidl.getIntAttribute("height"));
}
if (uidl.hasAttribute("zoom")) {
map.setZoom(uidl.getIntAttribute("zoom"));
}
if (uidl.hasAttribute("centerX") && uidl.hasAttribute("centerY")) {
GLatLng center = new GLatLng(uidl.getDoubleAttribute("centerX"),
uidl.getDoubleAttribute("centerY"));
map.setCenter(center);
} else if (pos != null) {
// use last marker position
map.setCenter(pos);
}
public MarkerEventListener(String html) {
this.html = html;
}
public void onClick(GMarker marker) {
marker.openInfoWindowHtml(html);
private void addMarkerPopup(GMarker marker, String html) {
if (markerEventManager == null) {
markerEventManager = GMarkerEventManager.getInstance();
}
markerEventManager.addOnClickListener(marker, new MarkerEventListener(
html));
}
public void onDblClick(GMarker marker) {
private class MarkerEventListener implements GMarkerEventClickListener {
String html;
public MarkerEventListener(String html) {
this.html = html;
}
public void onClick(GMarker marker) {
marker.openInfoWindowHtml(html);
}
public void onDblClick(GMarker marker) {
}
}
}
}

+ 134
- 132
src/com/itmill/toolkit/demo/util/SampleCalendarDatabase.java View File

@@ -19,144 +19,146 @@ import java.sql.Timestamp;
*/
public class SampleCalendarDatabase {

public static final int ENTRYCOUNT = 100;

public static final String DB_TABLE_NAME = "calendar";
public static final String PROPERTY_ID_START = "EVENTSTART";
public static final String PROPERTY_ID_END = "EVENTEND";
public static final String PROPERTY_ID_TITLE = "TITLE";
public static final String PROPERTY_ID_NOTIME = "NOTIME";
private Connection connection = null;

private static final String[] titles = new String[] { "Meeting", "Dentist",
"Haircut", "Bank", "Birthday", "Library", "Rent", "Acme test", "Party" };

/**
* Create temporary database.
*
*/
public SampleCalendarDatabase() {
// connect to SQL database
connect();

// initialize SQL database
createTables();

// test by executing sample JDBC query
testDatabase();
}

/**
* Creates sample table named employee and populates it with data.Use the
* specified database connection.
*
* @param connection
*/
public SampleCalendarDatabase(Connection connection) {
// initialize SQL database
createTables();

// test by executing sample JDBC query
testDatabase();
}

/**
* Connect to SQL database. In this sample we use HSQLDB and an toolkit
* named database in implicitly created into system memory.
*
*/
private void connect() {
// use memory-Only Database
String url = "jdbc:hsqldb:mem:toolkit";
try {
Class.forName("org.hsqldb.jdbcDriver").newInstance();
connection = DriverManager.getConnection(url, "sa", "");
} catch (Exception e) {
throw new RuntimeException(e);
public static final int ENTRYCOUNT = 100;

public static final String DB_TABLE_NAME = "calendar";
public static final String PROPERTY_ID_START = "EVENTSTART";
public static final String PROPERTY_ID_END = "EVENTEND";
public static final String PROPERTY_ID_TITLE = "TITLE";
public static final String PROPERTY_ID_NOTIME = "NOTIME";

private Connection connection = null;

private static final String[] titles = new String[] { "Meeting", "Dentist",
"Haircut", "Bank", "Birthday", "Library", "Rent", "Acme test",
"Party" };

/**
* Create temporary database.
*
*/
public SampleCalendarDatabase() {
// connect to SQL database
connect();

// initialize SQL database
createTables();

// test by executing sample JDBC query
testDatabase();
}

/**
* Creates sample table named employee and populates it with data.Use the
* specified database connection.
*
* @param connection
*/
public SampleCalendarDatabase(Connection connection) {
// initialize SQL database
createTables();

// test by executing sample JDBC query
testDatabase();
}
}

/**
* use for SQL commands CREATE, DROP, INSERT and UPDATE
*
* @param expression
* @throws SQLException
*/
public void update(String expression) throws SQLException {
Statement st = null;
st = connection.createStatement();
int i = st.executeUpdate(expression);
if (i == -1) {
System.out.println("SampleDatabase error : " + expression);

/**
* Connect to SQL database. In this sample we use HSQLDB and an toolkit
* named database in implicitly created into system memory.
*
*/
private void connect() {
// use memory-Only Database
String url = "jdbc:hsqldb:mem:toolkit";
try {
Class.forName("org.hsqldb.jdbcDriver").newInstance();
connection = DriverManager.getConnection(url, "sa", "");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
st.close();
}

/**
* Create test table and few rows. Issue note: using capitalized column
* names as HSQLDB returns column names in capitalized form with this demo.
*
*/
private void createTables() {
try {
String stmt = null;
stmt = "CREATE TABLE "+DB_TABLE_NAME+" ( ID INTEGER IDENTITY, TITLE VARCHAR(100), "
+ "EVENTSTART DATETIME, EVENTEND DATETIME, NOTIME BOOLEAN )";
update(stmt);
for (int j = 0; j < ENTRYCOUNT; j++) {
Timestamp start = new Timestamp(new java.util.Date().getTime());
start.setDate((int)((Math.random()-0.4) * 200));
start.setMinutes(0);
start.setHours(8+(int)Math.random()*12);
Timestamp end = new Timestamp(start.getTime());
if (Math.random()<0.7) {
long t = end.getTime();
long hour = 60 * 60 * 1000;
t = t + hour + (long)(Math.round(Math.random() * 3 * hour));
end.setTime(t);

/**
* use for SQL commands CREATE, DROP, INSERT and UPDATE
*
* @param expression
* @throws SQLException
*/
public void update(String expression) throws SQLException {
Statement st = null;
st = connection.createStatement();
int i = st.executeUpdate(expression);
if (i == -1) {
System.out.println("SampleDatabase error : " + expression);
}
st.close();
}

stmt = "INSERT INTO "+DB_TABLE_NAME+"(TITLE, EVENTSTART, EVENTEND, NOTIME) VALUES ("
+ "'"
+ titles[(int) (Math.round(Math.random() * (titles.length - 1)))]
+ "','"
+ start
+ "','"
+ end
+ "',"
+ (Math.random()>0.7)
+ ")";
update(stmt);
}
} catch (SQLException e) {
if (e.toString().indexOf("Table already exists") == -1)
throw new RuntimeException(e);
/**
* Create test table and few rows. Issue note: using capitalized column
* names as HSQLDB returns column names in capitalized form with this demo.
*
*/
private void createTables() {
try {
String stmt = null;
stmt = "CREATE TABLE "
+ DB_TABLE_NAME
+ " ( ID INTEGER IDENTITY, TITLE VARCHAR(100), "
+ "EVENTSTART DATETIME, EVENTEND DATETIME, NOTIME BOOLEAN )";
update(stmt);
for (int j = 0; j < ENTRYCOUNT; j++) {
Timestamp start = new Timestamp(new java.util.Date().getTime());
start.setDate((int) ((Math.random() - 0.4) * 200));
start.setMinutes(0);
start.setHours(8 + (int) Math.random() * 12);
Timestamp end = new Timestamp(start.getTime());
if (Math.random() < 0.7) {
long t = end.getTime();
long hour = 60 * 60 * 1000;
t = t + hour
+ (long) (Math.round(Math.random() * 3 * hour));
end.setTime(t);
}

stmt = "INSERT INTO "
+ DB_TABLE_NAME
+ "(TITLE, EVENTSTART, EVENTEND, NOTIME) VALUES ("
+ "'"
+ titles[(int) (Math.round(Math.random()
* (titles.length - 1)))] + "','" + start
+ "','" + end + "'," + (Math.random() > 0.7) + ")";
update(stmt);
}
} catch (SQLException e) {
if (e.toString().indexOf("Table already exists") == -1)
throw new RuntimeException(e);
}
}
}

/**
* Test database connection with simple SELECT command.
*
*/
private String testDatabase() {
String result = null;
try {
Statement stmt = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM "+DB_TABLE_NAME);
rs.next();
result = "rowcount for table test is " + rs.getObject(1).toString();
stmt.close();
} catch (SQLException e) {
throw new RuntimeException(e);

/**
* Test database connection with simple SELECT command.
*
*/
private String testDatabase() {
String result = null;
try {
Statement stmt = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM "
+ DB_TABLE_NAME);
rs.next();
result = "rowcount for table test is " + rs.getObject(1).toString();
stmt.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
return result;
}
return result;
}

public Connection getConnection() {
return connection;
}
public Connection getConnection() {
return connection;
}

}

+ 5
- 5
src/com/itmill/toolkit/terminal/PaintTarget.java View File

@@ -162,7 +162,7 @@ public interface PaintTarget {
* if the paint operation failed.
*/
public void addAttribute(String name, long value) throws PaintException;
/**
* Adds a float attribute to component. Atributes must be added before any
* content is written.
@@ -176,7 +176,7 @@ public interface PaintTarget {
* if the paint operation failed.
*/
public void addAttribute(String name, float value) throws PaintException;
/**
* Adds a double attribute to component. Atributes must be added before any
* content is written.
@@ -236,7 +236,7 @@ public interface PaintTarget {
*/
public void addVariable(VariableOwner owner, String name, int value)
throws PaintException;
/**
* Adds a long type variable.
*
@@ -252,7 +252,7 @@ public interface PaintTarget {
*/
public void addVariable(VariableOwner owner, String name, long value)
throws PaintException;
/**
* Adds a float type variable.
*
@@ -268,7 +268,7 @@ public interface PaintTarget {
*/
public void addVariable(VariableOwner owner, String name, float value)
throws PaintException;
/**
* Adds a double type variable.
*

+ 9
- 9
src/com/itmill/toolkit/terminal/gwt/client/ApplicationConnection.java View File

@@ -57,7 +57,7 @@ public class ApplicationConnection implements FocusListener {
}

makeUidlRequest("repaintAll=1");
// TODO remove hardcoded id name
view = new IView("itmtk-ajax-window");

@@ -74,14 +74,14 @@ public class ApplicationConnection implements FocusListener {
}-*/;

public native String getAppUri()/*-{
var u = $wnd.itmtk.appUri;
if (u.indexOf("/") != 0 && u.indexOf("http") != 0) u = "../../../" +u;
return u;
}-*/;
var u = $wnd.itmtk.appUri;
if (u.indexOf("/") != 0 && u.indexOf("http") != 0) u = "../../../" +u;
return u;
}-*/;

private native String getPathInfo()/*-{
return $wnd.itmtk.pathInfo;
}-*/;
return $wnd.itmtk.pathInfo;
}-*/;

private void makeUidlRequest(String requestData) {
console.log("Making UIDL Request with params: " + requestData);
@@ -198,8 +198,8 @@ public class ApplicationConnection implements FocusListener {

// Redirect browser
private static native void redirect(String url)/*-{
$wnd.location = url;
}-*/;
$wnd.location = url;
}-*/;

public void registerPaintable(String id, Paintable paintable) {
idToPaintable.put(id, paintable);

+ 51
- 44
src/com/itmill/toolkit/terminal/gwt/client/Caption.java View File

@@ -7,69 +7,72 @@ import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.PopupPanel;

public class Caption extends HTML {
public static final String CLASSNAME = "i-caption";

private Paintable owner;

private Element errorIndicatorElement;
private Element captionText;

private ErrorMessage errorMessage;
private PopupPanel errorContainer;
/* Caption must be attached to a Paintable */
private Caption(){};
public Caption(Paintable component) {
private Caption() {
};

public Caption(Paintable component) {
super();
owner = component;
setStyleName(CLASSNAME);
}
public void updateCaption(UIDL uidl) {
setVisible(!uidl.getBooleanAttribute("invisible"));
if(uidl.hasAttribute("error")) {
if (uidl.hasAttribute("error")) {
UIDL errorUidl = uidl.getErrors();
if(errorIndicatorElement == null) {
if (errorIndicatorElement == null) {
errorIndicatorElement = DOM.createDiv();
DOM.setElementProperty(errorIndicatorElement, "className", "i-errorindicator");
DOM.setElementProperty(errorIndicatorElement, "className",
"i-errorindicator");
DOM.insertChild(getElement(), errorIndicatorElement, 0);
}
if(errorMessage == null)
if (errorMessage == null)
errorMessage = new ErrorMessage();
errorMessage.updateFromUIDL(errorUidl);
} else if( errorIndicatorElement != null) {
} else if (errorIndicatorElement != null) {
DOM.setStyleAttribute(errorIndicatorElement, "display", "none");
}
if(uidl.hasAttribute("caption")) {
if(captionText == null) {

if (uidl.hasAttribute("caption")) {
if (captionText == null) {
captionText = DOM.createSpan();
DOM.appendChild(getElement(), captionText);
}
DOM.setInnerText(captionText, uidl.getStringAttribute("caption"));
}
if(uidl.hasAttribute("description")) {
if(captionText != null) {
DOM.setElementProperty(captionText, "title", uidl.getStringAttribute("description"));

if (uidl.hasAttribute("description")) {
if (captionText != null) {
DOM.setElementProperty(captionText, "title", uidl
.getStringAttribute("description"));
} else {
setTitle(uidl.getStringAttribute("description"));
}
}
}
public void onBrowserEvent(Event event) {
Element target= DOM.eventGetTarget(event);
if(errorIndicatorElement != null && DOM.compare(target, errorIndicatorElement)) {
Element target = DOM.eventGetTarget(event);
if (errorIndicatorElement != null
&& DOM.compare(target, errorIndicatorElement)) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEOVER:
showErrorMessage();
@@ -78,8 +81,8 @@ public class Caption extends HTML {
hideErrorMessage();
break;
case Event.ONCLICK:
ApplicationConnection.getConsole().
log(DOM.getInnerHTML(errorMessage.getElement()));
ApplicationConnection.getConsole().log(
DOM.getInnerHTML(errorMessage.getElement()));
default:
break;
}
@@ -87,39 +90,43 @@ public class Caption extends HTML {
}

private void hideErrorMessage() {
if(errorContainer != null) {
if (errorContainer != null) {
errorContainer.hide();
}
}

private void showErrorMessage() {
if(errorMessage != null) {
if(errorContainer == null) {
if (errorMessage != null) {
if (errorContainer == null) {
errorContainer = new PopupPanel();
errorContainer.setWidget(errorMessage);
}
errorContainer.setPopupPosition(
DOM.getAbsoluteLeft(errorIndicatorElement) +
2*DOM.getElementPropertyInt(errorIndicatorElement, "offsetHeight"),
DOM.getAbsoluteTop(errorIndicatorElement) +
2*DOM.getElementPropertyInt(errorIndicatorElement, "offsetHeight"));
errorContainer.setPopupPosition(DOM
.getAbsoluteLeft(errorIndicatorElement)
+ 2
* DOM.getElementPropertyInt(errorIndicatorElement,
"offsetHeight"), DOM
.getAbsoluteTop(errorIndicatorElement)
+ 2
* DOM.getElementPropertyInt(errorIndicatorElement,
"offsetHeight"));
errorContainer.show();
}
}

public static boolean isNeeded(UIDL uidl) {
if (uidl.getStringAttribute("caption") != null) return true;
if (uidl.getStringAttribute("caption") != null)
return true;
if (uidl.hasAttribute("error"))
return true;
// TODO Description ??
return false;
}
/**
* Returns Paintable for which this Caption
* belongs to.
* Returns Paintable for which this Caption belongs to.
*
* @return owner Widget
*/

+ 4
- 4
src/com/itmill/toolkit/terminal/gwt/client/CaptionWrapper.java View File

@@ -7,8 +7,8 @@ public class CaptionWrapper extends FlowPanel {

public static final String CLASSNAME = "i-captionwrapper";
Caption caption;
Paintable widget;
Paintable widget;
public CaptionWrapper(Paintable toBeWrapped) {
caption = new Caption(toBeWrapped);
add(caption);
@@ -16,12 +16,12 @@ public class CaptionWrapper extends FlowPanel {
add((Widget) widget);
setStyleName(CLASSNAME);
}
public void updateCaption(UIDL uidl) {
caption.updateCaption(uidl);
setVisible(!uidl.getBooleanAttribute("invisible"));
}
public Paintable getPaintable() {
return widget;
}

+ 21
- 14
src/com/itmill/toolkit/terminal/gwt/client/DateLocale.java View File

@@ -1,56 +1,63 @@
package com.itmill.toolkit.terminal.gwt.client;
public class DateLocale extends com.itmill.toolkit.terminal.gwt.client.util.DateLocale {
public class DateLocale extends
com.itmill.toolkit.terminal.gwt.client.util.DateLocale {
private static String locale;
public DateLocale() {
locale = LocaleService.getDefaultLocale();
}
public static void setLocale(String l) {
if(LocaleService.getAvailableLocales().contains(locale))
if (LocaleService.getAvailableLocales().contains(locale))
locale = l;
else // TODO redirect to console
System.out.println("Tried to use an unloaded locale \""+locale+"\". Using default in stead ("+locale+")");
else
// TODO redirect to console
System.out.println("Tried to use an unloaded locale \"" + locale
+ "\". Using default in stead (" + locale + ")");
}
public static String getAM() {
try {
return LocaleService.getAmPmStrings(locale)[0];
} catch (LocaleNotLoadedException e) {
// TODO redirect to console
System.out.println("Tried to use an unloaded locale \""+locale+"\".");
System.out.println("Tried to use an unloaded locale \"" + locale
+ "\".");
return "AM";
}
}
public static String getPM() {
try {
return LocaleService.getAmPmStrings(locale)[1];
} catch (LocaleNotLoadedException e) {
// TODO redirect to console
System.out.println("Tried to use an unloaded locale \""+locale+"\".");
System.out.println("Tried to use an unloaded locale \"" + locale
+ "\".");
return "PM";
}
}
public String[] getWEEKDAY_LONG() {
try {
return LocaleService.getDayNames(locale);
} catch (LocaleNotLoadedException e) {
// TODO redirect to console
System.out.println("Tried to use an unloaded locale \""+locale+"\".");
System.out.println("Tried to use an unloaded locale \"" + locale
+ "\".");
return null;
}
}
public String[] getWEEKDAY_SHORT() {
try {
return LocaleService.getShortDayNames(locale);
} catch (LocaleNotLoadedException e) {
// TODO redirect to console
System.out.println("Tried to use an unloaded locale \""+locale+"\".");
System.out.println("Tried to use an unloaded locale \"" + locale
+ "\".");
return null;
}
}

+ 234
- 234
src/com/itmill/toolkit/terminal/gwt/client/DateTimeService.java View File

@@ -12,239 +12,239 @@ import com.itmill.toolkit.terminal.gwt.client.ui.IDateField;
*
*/
public class DateTimeService {
public static int RESOLUTION_YEAR = 0;
public static int RESOLUTION_MONTH = 1;
public static int RESOLUTION_DAY = 2;
public static int RESOLUTION_HOUR = 3;
public static int RESOLUTION_MIN = 4;
public static int RESOLUTION_SEC = 5;
public static int RESOLUTION_MSEC = 6;
private String currentLocale;
private static int[] maxDaysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30,
31, 30, 31 };
/**
* Creates a new date time service with the application default locale.
*/
public DateTimeService() {
currentLocale = LocaleService.getDefaultLocale();
}
/**
* Creates a new date time service with a given locale.
*
* @param locale
* e.g. fi, en etc.
* @throws LocaleNotLoadedException
*/
public DateTimeService(String locale) throws LocaleNotLoadedException {
setLocale(locale);
}
public void setLocale(String locale) throws LocaleNotLoadedException {
if (LocaleService.getAvailableLocales().contains(locale))
currentLocale = locale;
else
throw new LocaleNotLoadedException(locale);
}
public String getLocale() {
return currentLocale;
}
public String getMonth(int month) {
try {
return LocaleService.getMonthNames(currentLocale)[month];
} catch (LocaleNotLoadedException e) {
// TODO redirect to console
System.out.println(e + ":" + e.getMessage());
}
return null;
}
public String getShortMonth(int month) {
try {
return LocaleService.getShortMonthNames(currentLocale)[month];
} catch (LocaleNotLoadedException e) {
// TODO redirect to console
System.out.println(e + ":" + e.getMessage());
}
return null;
}
public String getDay(int day) {
try {
return LocaleService.getDayNames(currentLocale)[day];
} catch (LocaleNotLoadedException e) {
// TODO redirect to console
System.out.println(e + ":" + e.getMessage());
}
return null;
}
public String getShortDay(int day) {
try {
return LocaleService.getShortDayNames(currentLocale)[day];
} catch (LocaleNotLoadedException e) {
// TODO redirect to console
System.out.println(e + ":" + e.getMessage());
}
return null;
}
public int getFirstDayOfWeek() {
try {
return LocaleService.getFirstDayOfWeek(currentLocale);
} catch (LocaleNotLoadedException e) {
// TODO redirect to console
System.out.println(e + ":" + e.getMessage());
}
return 0;
}
public boolean isTwelveHourClock() {
try {
return LocaleService.isTwelveHourClock(currentLocale);
} catch (LocaleNotLoadedException e) {
// TODO redirect to console
System.out.println(e + ":" + e.getMessage());
}
return false;
}
public String getClockDelimeter() {
try {
return LocaleService.getClockDelimiter(currentLocale);
} catch (LocaleNotLoadedException e) {
// TODO redirect to console
System.out.println(e + ":" + e.getMessage());
}
return ":";
}
public String[] getAmPmStrings() {
try {
return LocaleService.getAmPmStrings(currentLocale);
} catch (LocaleNotLoadedException e) {
// TODO redirect to console
System.out.println(e + ":" + e.getMessage());
}
String[] temp = new String[2];
temp[0] = "AM";
temp[1] = "PM";
return temp;
}
public int getStartWeekDay(Date date) {
Date dateForFirstOfThisMonth = new Date(date.getYear(),
date.getMonth(), 1);
int firstDay;
try {
firstDay = LocaleService.getFirstDayOfWeek(currentLocale);
} catch (LocaleNotLoadedException e) {
firstDay = 0;
// TODO redirect to console
System.out.println(e + ":" + e.getMessage());
}
int start = dateForFirstOfThisMonth.getDay() - firstDay;
if (start < 0)
start = 6;
return start;
}
public String getDateFormat() {
try {
return LocaleService.getDateFormat(currentLocale);
} catch (LocaleNotLoadedException e) {
// TODO redirect to console
System.out.println(e + ":" + e.getMessage());
}
return "M/d/yy";
}
public static int getNumberOfDaysInMonth(Date date) {
int month = date.getMonth();
if (month == 1 && true == isLeapYear(date))
return 29;
return maxDaysInMonth[month];
}
public static boolean isLeapYear(Date date) {
// Instantiate the date for 1st March of that year
Date firstMarch = new Date(date.getYear(), 2, 1);
// Go back 1 day
long firstMarchTime = firstMarch.getTime();
long lastDayTimeFeb = firstMarchTime - (24 * 60 * 60 * 1000); // NUM_MILLISECS_A_DAY
// Instantiate new Date with this time
Date febLastDay = new Date(lastDayTimeFeb);
// Check for date in this new instance
return (29 == febLastDay.getDate()) ? true : false;
}
public static boolean isSameDay(Date d1, Date d2) {
return (getDayInt(d1) == getDayInt(d2));
}
public static boolean isInRange(Date date, Date rangeStart, Date rangeEnd,
int resolution) {
Date s;
Date e;
if (rangeStart.after(rangeEnd)) {
s = rangeEnd;
e = rangeStart;
} else {
e = rangeEnd;
s = rangeStart;
}
long start = s.getYear()*10000000000l;
long end = e.getYear()*10000000000l;
long target = date.getYear()*10000000000l;
if (resolution == RESOLUTION_YEAR) {
return (start<=target&&end>=target);
}
start += s.getMonth() * 100000000;
end += e.getMonth() * 100000000;
target += date.getMonth() * 100000000;
if (resolution == RESOLUTION_MONTH) {
return (start<=target&&end>=target);
}
start += s.getDate() * 1000000;
end += e.getDate() * 1000000;
target += date.getDate() * 1000000;
if (resolution == RESOLUTION_DAY) {
return (start<=target&&end>=target);
}
start += s.getHours() * 10000;
end += e.getHours() * 10000;
target += date.getHours() * 10000;
if (resolution == RESOLUTION_HOUR) {
return (start<=target&&end>=target);
}
start += s.getMinutes() * 100;
end += e.getMinutes() * 100;
target += date.getMinutes() * 100;
if (resolution == RESOLUTION_MIN) {
return (start<=target&&end>=target);
}
start += s.getSeconds();
end += e.getSeconds();
target += date.getSeconds();
return (start<=target&&end>=target);
}
private static int getDayInt(Date date) {
int y = date.getYear();
int m = date.getMonth();
int d = date.getDate();
return ((y + 1900) * 10000 + m * 100 + d) * 1000000000;
}
public static int RESOLUTION_YEAR = 0;
public static int RESOLUTION_MONTH = 1;
public static int RESOLUTION_DAY = 2;
public static int RESOLUTION_HOUR = 3;
public static int RESOLUTION_MIN = 4;
public static int RESOLUTION_SEC = 5;
public static int RESOLUTION_MSEC = 6;
private String currentLocale;
private static int[] maxDaysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30,
31, 30, 31 };
/**
* Creates a new date time service with the application default locale.
*/
public DateTimeService() {
currentLocale = LocaleService.getDefaultLocale();
}
/**
* Creates a new date time service with a given locale.
*
* @param locale
* e.g. fi, en etc.
* @throws LocaleNotLoadedException
*/
public DateTimeService(String locale) throws LocaleNotLoadedException {
setLocale(locale);
}
public void setLocale(String locale) throws LocaleNotLoadedException {
if (LocaleService.getAvailableLocales().contains(locale))
currentLocale = locale;
else
throw new LocaleNotLoadedException(locale);
}
public String getLocale() {
return currentLocale;
}
public String getMonth(int month) {
try {
return LocaleService.getMonthNames(currentLocale)[month];
} catch (LocaleNotLoadedException e) {
// TODO redirect to console
System.out.println(e + ":" + e.getMessage());
}
return null;
}
public String getShortMonth(int month) {
try {
return LocaleService.getShortMonthNames(currentLocale)[month];
} catch (LocaleNotLoadedException e) {
// TODO redirect to console
System.out.println(e + ":" + e.getMessage());
}
return null;
}
public String getDay(int day) {
try {
return LocaleService.getDayNames(currentLocale)[day];
} catch (LocaleNotLoadedException e) {
// TODO redirect to console
System.out.println(e + ":" + e.getMessage());
}
return null;
}
public String getShortDay(int day) {
try {
return LocaleService.getShortDayNames(currentLocale)[day];
} catch (LocaleNotLoadedException e) {
// TODO redirect to console
System.out.println(e + ":" + e.getMessage());
}
return null;
}
public int getFirstDayOfWeek() {
try {
return LocaleService.getFirstDayOfWeek(currentLocale);
} catch (LocaleNotLoadedException e) {
// TODO redirect to console
System.out.println(e + ":" + e.getMessage());
}
return 0;
}
public boolean isTwelveHourClock() {
try {
return LocaleService.isTwelveHourClock(currentLocale);
} catch (LocaleNotLoadedException e) {
// TODO redirect to console
System.out.println(e + ":" + e.getMessage());
}
return false;
}
public String getClockDelimeter() {
try {
return LocaleService.getClockDelimiter(currentLocale);
} catch (LocaleNotLoadedException e) {
// TODO redirect to console
System.out.println(e + ":" + e.getMessage());
}
return ":";
}
public String[] getAmPmStrings() {
try {
return LocaleService.getAmPmStrings(currentLocale);
} catch (LocaleNotLoadedException e) {
// TODO redirect to console
System.out.println(e + ":" + e.getMessage());
}
String[] temp = new String[2];
temp[0] = "AM";
temp[1] = "PM";
return temp;
}
public int getStartWeekDay(Date date) {
Date dateForFirstOfThisMonth = new Date(date.getYear(),
date.getMonth(), 1);
int firstDay;
try {
firstDay = LocaleService.getFirstDayOfWeek(currentLocale);
} catch (LocaleNotLoadedException e) {
firstDay = 0;
// TODO redirect to console
System.out.println(e + ":" + e.getMessage());
}
int start = dateForFirstOfThisMonth.getDay() - firstDay;
if (start < 0)
start = 6;
return start;
}
public String getDateFormat() {
try {
return LocaleService.getDateFormat(currentLocale);
} catch (LocaleNotLoadedException e) {
// TODO redirect to console
System.out.println(e + ":" + e.getMessage());
}
return "M/d/yy";
}
public static int getNumberOfDaysInMonth(Date date) {
int month = date.getMonth();
if (month == 1 && true == isLeapYear(date))
return 29;
return maxDaysInMonth[month];
}
public static boolean isLeapYear(Date date) {
// Instantiate the date for 1st March of that year
Date firstMarch = new Date(date.getYear(), 2, 1);
// Go back 1 day
long firstMarchTime = firstMarch.getTime();
long lastDayTimeFeb = firstMarchTime - (24 * 60 * 60 * 1000); // NUM_MILLISECS_A_DAY
// Instantiate new Date with this time
Date febLastDay = new Date(lastDayTimeFeb);
// Check for date in this new instance
return (29 == febLastDay.getDate()) ? true : false;
}
public static boolean isSameDay(Date d1, Date d2) {
return (getDayInt(d1) == getDayInt(d2));
}
public static boolean isInRange(Date date, Date rangeStart, Date rangeEnd,
int resolution) {
Date s;
Date e;
if (rangeStart.after(rangeEnd)) {
s = rangeEnd;
e = rangeStart;
} else {
e = rangeEnd;
s = rangeStart;
}
long start = s.getYear() * 10000000000l;
long end = e.getYear() * 10000000000l;
long target = date.getYear() * 10000000000l;
if (resolution == RESOLUTION_YEAR) {
return (start <= target && end >= target);
}
start += s.getMonth() * 100000000;
end += e.getMonth() * 100000000;
target += date.getMonth() * 100000000;
if (resolution == RESOLUTION_MONTH) {
return (start <= target && end >= target);
}
start += s.getDate() * 1000000;
end += e.getDate() * 1000000;
target += date.getDate() * 1000000;
if (resolution == RESOLUTION_DAY) {
return (start <= target && end >= target);
}
start += s.getHours() * 10000;
end += e.getHours() * 10000;
target += date.getHours() * 10000;
if (resolution == RESOLUTION_HOUR) {
return (start <= target && end >= target);
}
start += s.getMinutes() * 100;
end += e.getMinutes() * 100;
target += date.getMinutes() * 100;
if (resolution == RESOLUTION_MIN) {
return (start <= target && end >= target);
}
start += s.getSeconds();
end += e.getSeconds();
target += date.getSeconds();
return (start <= target && end >= target);
}
private static int getDayInt(Date date) {
int y = date.getYear();
int m = date.getMonth();
int d = date.getDate();
return ((y + 1900) * 10000 + m * 100 + d) * 1000000000;
}
}

+ 19
- 11
src/com/itmill/toolkit/terminal/gwt/client/DebugConsole.java View File

@@ -10,7 +10,7 @@ import com.google.gwt.user.client.ui.ScrollPanel;
import com.itmill.toolkit.terminal.gwt.client.ui.IWindow;

public final class DebugConsole extends IWindow implements Console {
private Panel panel;

public DebugConsole() {
@@ -23,14 +23,17 @@ public final class DebugConsole extends IWindow implements Console {
minimize();
show();
}
private void minimize() {
// TODO stack to bottom (create window manager of some sort)
// TODO stack to bottom (create window manager of some sort)
setPixelSize(60, 60);
setPopupPosition(Window.getClientWidth() - 80, Window.getClientHeight() - 80);
setPopupPosition(Window.getClientWidth() - 80,
Window.getClientHeight() - 80);
}

/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see com.itmill.toolkit.terminal.gwt.client.Console#log(java.lang.String)
*/
public void log(String msg) {
@@ -38,7 +41,9 @@ public final class DebugConsole extends IWindow implements Console {
System.out.println(msg);
}

/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see com.itmill.toolkit.terminal.gwt.client.Console#error(java.lang.String)
*/
public void error(String msg) {
@@ -46,14 +51,18 @@ public final class DebugConsole extends IWindow implements Console {
System.out.println(msg);
}

/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see com.itmill.toolkit.terminal.gwt.client.Console#printObject(java.lang.Object)
*/
public void printObject(Object msg) {
panel.add((new Label(msg.toString())));
}
/* (non-Javadoc)

/*
* (non-Javadoc)
*
* @see com.itmill.toolkit.terminal.gwt.client.Console#dirUIDL(com.itmill.toolkit.terminal.gwt.client.UIDL)
*/
public void dirUIDL(UIDL u) {
@@ -63,6 +72,5 @@ public final class DebugConsole extends IWindow implements Console {
public void setSize(Event event, boolean updateVariables) {
super.setSize(event, false);
}

}

+ 208
- 208
src/com/itmill/toolkit/terminal/gwt/client/DefaultWidgetSet.java View File

@@ -40,223 +40,223 @@ import com.itmill.toolkit.terminal.gwt.client.ui.IWindow;

public class DefaultWidgetSet implements WidgetSet {

protected ApplicationConnection appConn;
protected ApplicationConnection appConn;

/**
* This is the entry point method.
*/
public void onModuleLoad() {
appConn = new ApplicationConnection(this);
}
/**
* This is the entry point method.
*/
public void onModuleLoad() {
appConn = new ApplicationConnection(this);
}

public Widget createWidget(UIDL uidl) {
public Widget createWidget(UIDL uidl) {

String className = resolveWidgetTypeName(uidl);
if ("com.itmill.toolkit.terminal.gwt.client.ui.ICheckBox"
.equals(className)) {
return new ICheckBox();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IButton"
.equals(className)) {
return new IButton();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IWindow"
.equals(className)) {
return new IWindow();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IOrderedLayoutVertical"
.equals(className)) {
return new IOrderedLayoutVertical();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IOrderedLayoutHorizontal"
.equals(className)) {
return new IOrderedLayoutHorizontal();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ILabel"
.equals(className)) {
return new ILabel();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ILink"
.equals(className)) {
return new ILink();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IGridLayout"
.equals(className)) {
return new IGridLayout();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ITree"
.equals(className)) {
return new ITree();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IOptionGroup"
.equals(className)) {
return new IOptionGroup();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ITwinColSelect"
.equals(className)) {
return new ITwinColSelect();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ISelect"
.equals(className)) {
return new ISelect();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IPanel"
.equals(className)) {
return new IPanel();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ITabsheet"
.equals(className)) {
return new ITabsheet();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IEmbedded"
.equals(className)) {
return new IEmbedded();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ICustomLayout"
.equals(className)) {
return new ICustomLayout();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ITextArea"
.equals(className)) {
return new ITextArea();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IPasswordField"
.equals(className)) {
return new IPasswordField();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ITextField"
.equals(className)) {
return new ITextField();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ITablePaging"
.equals(className)) {
return new ITablePaging();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IScrollTable"
.equals(className)) {
return new IScrollTable();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IDateFieldCalendar"
.equals(className)) {
return new IDateFieldCalendar();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ICalendar"
.equals(className)) {
return new ICalendar();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ITextualDate"
.equals(className)) {
return new ITextualDate();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IPopupCalendar"
.equals(className)) {
return new IPopupCalendar();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ISlider"
.equals(className)) {
return new ISlider();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IForm"
.equals(className)) {
return new IForm();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IFormLayout"
.equals(className)) {
return new IFormLayout();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IUpload"
.equals(className)) {
return new IUpload();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ISplitPanelHorizontal"
.equals(className)) {
return new ISplitPanelHorizontal();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ISplitPanelVertical"
.equals(className)) {
return new ISplitPanelVertical();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IFilterSelect"
.equals(className)) {
return new IFilterSelect();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IProgressIndicator"
.equals(className)) {
return new IProgressIndicator();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IExpandLayout"
.equals(className)) {
return new IExpandLayout();
}
return new IUnknownComponent();
String className = resolveWidgetTypeName(uidl);
if ("com.itmill.toolkit.terminal.gwt.client.ui.ICheckBox"
.equals(className)) {
return new ICheckBox();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IButton"
.equals(className)) {
return new IButton();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IWindow"
.equals(className)) {
return new IWindow();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IOrderedLayoutVertical"
.equals(className)) {
return new IOrderedLayoutVertical();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IOrderedLayoutHorizontal"
.equals(className)) {
return new IOrderedLayoutHorizontal();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ILabel"
.equals(className)) {
return new ILabel();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ILink"
.equals(className)) {
return new ILink();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IGridLayout"
.equals(className)) {
return new IGridLayout();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ITree"
.equals(className)) {
return new ITree();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IOptionGroup"
.equals(className)) {
return new IOptionGroup();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ITwinColSelect"
.equals(className)) {
return new ITwinColSelect();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ISelect"
.equals(className)) {
return new ISelect();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IPanel"
.equals(className)) {
return new IPanel();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ITabsheet"
.equals(className)) {
return new ITabsheet();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IEmbedded"
.equals(className)) {
return new IEmbedded();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ICustomLayout"
.equals(className)) {
return new ICustomLayout();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ITextArea"
.equals(className)) {
return new ITextArea();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IPasswordField"
.equals(className)) {
return new IPasswordField();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ITextField"
.equals(className)) {
return new ITextField();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ITablePaging"
.equals(className)) {
return new ITablePaging();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IScrollTable"
.equals(className)) {
return new IScrollTable();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IDateFieldCalendar"
.equals(className)) {
return new IDateFieldCalendar();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ICalendar"
.equals(className)) {
return new ICalendar();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ITextualDate"
.equals(className)) {
return new ITextualDate();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IPopupCalendar"
.equals(className)) {
return new IPopupCalendar();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ISlider"
.equals(className)) {
return new ISlider();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IForm"
.equals(className)) {
return new IForm();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IFormLayout"
.equals(className)) {
return new IFormLayout();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IUpload"
.equals(className)) {
return new IUpload();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ISplitPanelHorizontal"
.equals(className)) {
return new ISplitPanelHorizontal();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.ISplitPanelVertical"
.equals(className)) {
return new ISplitPanelVertical();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IFilterSelect"
.equals(className)) {
return new IFilterSelect();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IProgressIndicator"
.equals(className)) {
return new IProgressIndicator();
} else if ("com.itmill.toolkit.terminal.gwt.client.ui.IExpandLayout"
.equals(className)) {
return new IExpandLayout();
}

/*
* TODO: Class based impl, use when GWT supports return
* (Widget)GWT.create(resolveWidgetClass(uidl));
*/
}
return new IUnknownComponent();

protected String resolveWidgetTypeName(UIDL uidl) {
/*
* TODO: Class based impl, use when GWT supports return
* (Widget)GWT.create(resolveWidgetClass(uidl));
*/
}

String tag = uidl.getTag();
if ("button".equals(tag)) {
if ("switch".equals(uidl.getStringAttribute("type"))) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ICheckBox";
} else {
return "com.itmill.toolkit.terminal.gwt.client.ui.IButton";
}
} else if ("window".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IWindow";
} else if ("orderedlayout".equals(tag)) {
if ("horizontal".equals(uidl.getStringAttribute("orientation"))) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IOrderedLayoutHorizontal";
} else {
return "com.itmill.toolkit.terminal.gwt.client.ui.IOrderedLayoutVertical";
}
} else if ("label".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ILabel";
} else if ("link".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ILink";
} else if ("gridlayout".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IGridLayout";
} else if ("tree".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ITree";
} else if ("select".equals(tag)) {
if ("optiongroup".equals(uidl.getStringAttribute("style"))) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IOptionGroup";
} else if ("twincol".equals(uidl.getStringAttribute("style"))) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ITwinColSelect";
} else {
return "com.itmill.toolkit.terminal.gwt.client.ui.IFilterSelect";
}
} else if ("panel".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IPanel";
} else if ("tabsheet".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ITabsheet";
} else if ("embedded".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IEmbedded";
} else if ("customlayout".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ICustomLayout";
} else if ("textfield".equals(tag)) {
if (uidl.hasAttribute("multiline")) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ITextArea";
} else if (uidl.getBooleanAttribute("secret")) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IPasswordField";
} else {
return "com.itmill.toolkit.terminal.gwt.client.ui.ITextField";
}
} else if ("table".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IScrollTable";
} else if("pagingtable".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ITablePaging";
} else if ("datefield".equals(tag)) {
if (uidl.hasAttribute("style")) {
if ("calendar".equals(uidl.getStringAttribute("style"))) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ICalendar";
} else if ("text".equals(uidl.getStringAttribute("style"))) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ITextualDate";
protected String resolveWidgetTypeName(UIDL uidl) {

String tag = uidl.getTag();
if ("button".equals(tag)) {
if ("switch".equals(uidl.getStringAttribute("type"))) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ICheckBox";
} else {
return "com.itmill.toolkit.terminal.gwt.client.ui.IButton";
}
} else if ("window".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IWindow";
} else if ("orderedlayout".equals(tag)) {
if ("horizontal".equals(uidl.getStringAttribute("orientation"))) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IOrderedLayoutHorizontal";
} else {
return "com.itmill.toolkit.terminal.gwt.client.ui.IOrderedLayoutVertical";
}
} else if ("label".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ILabel";
} else if ("link".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ILink";
} else if ("gridlayout".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IGridLayout";
} else if ("tree".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ITree";
} else if ("select".equals(tag)) {
if ("optiongroup".equals(uidl.getStringAttribute("style"))) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IOptionGroup";
} else if ("twincol".equals(uidl.getStringAttribute("style"))) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ITwinColSelect";
} else {
return "com.itmill.toolkit.terminal.gwt.client.ui.IFilterSelect";
}
} else if ("panel".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IPanel";
} else if ("tabsheet".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ITabsheet";
} else if ("embedded".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IEmbedded";
} else if ("customlayout".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ICustomLayout";
} else if ("textfield".equals(tag)) {
if (uidl.hasAttribute("multiline")) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ITextArea";
} else if (uidl.getBooleanAttribute("secret")) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IPasswordField";
} else {
return "com.itmill.toolkit.terminal.gwt.client.ui.ITextField";
}
} else if ("table".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IScrollTable";
} else if ("pagingtable".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ITablePaging";
} else if ("datefield".equals(tag)) {
if (uidl.hasAttribute("style")) {
if ("calendar".equals(uidl.getStringAttribute("style"))) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ICalendar";
} else if ("text".equals(uidl.getStringAttribute("style"))) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ITextualDate";
}
} else {
return "com.itmill.toolkit.terminal.gwt.client.ui.IPopupCalendar";
}
} else if ("calendarfield".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ICalendar";
} else if ("slider".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ISlider";
} else if ("form".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IForm";
} else if ("formlayout".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IFormLayout";
} else if ("upload".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IUpload";
} else if ("hsplitpanel".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ISplitPanelHorizontal";
} else if ("vsplitpanel".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ISplitPanelVertical";
} else if ("progressindicator".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IProgressIndicator";
} else if ("expandlayout".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IExpandLayout";
}
} else {
return "com.itmill.toolkit.terminal.gwt.client.ui.IPopupCalendar";
}
} else if ("calendarfield".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ICalendar";
} else if ("slider".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ISlider";
} else if ("form".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IForm";
} else if ("formlayout".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IFormLayout";
} else if ("upload".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IUpload";
} else if ("hsplitpanel".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ISplitPanelHorizontal";
} else if ("vsplitpanel".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.ISplitPanelVertical";
} else if ("progressindicator".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IProgressIndicator";
} else if ("expandlayout".equals(tag)) {
return "com.itmill.toolkit.terminal.gwt.client.ui.IExpandLayout";
}

return "com.itmill.toolkit.terminal.gwt.client.ui.IUnknownComponent";
return "com.itmill.toolkit.terminal.gwt.client.ui.IUnknownComponent";

/*
* TODO: use class based impl when GWT supports it
*/
}
/*
* TODO: use class based impl when GWT supports it
*/
}

public boolean isCorrectImplementation(Widget currentWidget, UIDL uidl) {
return GWT.getTypeName(currentWidget).equals(
resolveWidgetTypeName(uidl));
}
public boolean isCorrectImplementation(Widget currentWidget, UIDL uidl) {
return GWT.getTypeName(currentWidget).equals(
resolveWidgetTypeName(uidl));
}

}

+ 2
- 1
src/com/itmill/toolkit/terminal/gwt/client/ErrorMessage.java View File

@@ -7,6 +7,7 @@ import com.google.gwt.user.client.ui.HTML;

public class ErrorMessage extends FlowPanel {
public static final String CLASSNAME = "i-error";

public ErrorMessage() {
super();
setStyleName(CLASSNAME);
@@ -14,7 +15,7 @@ public class ErrorMessage extends FlowPanel {

public void updateFromUIDL(UIDL uidl) {
clear();
for(Iterator it = uidl.getChildIterator();it.hasNext();) {
for (Iterator it = uidl.getChildIterator(); it.hasNext();) {
Object child = it.next();
if (child instanceof String) {
String errorMessage = (String) child;

+ 1
- 1
src/com/itmill/toolkit/terminal/gwt/client/LocaleNotLoadedException.java View File

@@ -1,7 +1,7 @@
package com.itmill.toolkit.terminal.gwt.client;
public class LocaleNotLoadedException extends Exception {
/**
* Serial generated by Eclipse.
*/

+ 103
- 85
src/com/itmill/toolkit/terminal/gwt/client/LocaleService.java View File

@@ -11,153 +11,171 @@ import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
/**
* Date / time etc. localisation service for all widgets.
* Caches all loaded locales as JSONObjects.
* Date / time etc. localisation service for all widgets. Caches all loaded
* locales as JSONObjects.
*
* @author IT Mill Ltd.
*
*
*/
public class LocaleService {
private static Map cache = new HashMap();
private static String defaultLocale;
public static void addLocale(JSONObject json) {
String key = ((JSONString)json.get("name")).stringValue();
if(cache.containsKey(key))
String key = ((JSONString) json.get("name")).stringValue();
if (cache.containsKey(key))
cache.remove(key);
cache.put(key, json);
if(cache.size()==1)
if (cache.size() == 1)
setDefaultLocale(key);
}
public static void setDefaultLocale(String locale) {
defaultLocale = locale;
}
public static String getDefaultLocale() {
return defaultLocale;
}
public static Set getAvailableLocales() {
return cache.keySet();
}
public static String[] getMonthNames(String locale) throws LocaleNotLoadedException {
if(cache.containsKey(locale)) {
public static String[] getMonthNames(String locale)
throws LocaleNotLoadedException {
if (cache.containsKey(locale)) {
JSONObject l = (JSONObject) cache.get(locale);
JSONArray mn = (JSONArray) l.get("mn");
String[] temp = new String[12];
temp[0] = ((JSONString)mn.get(0)).stringValue();
temp[1] = ((JSONString)mn.get(1)).stringValue();
temp[2] = ((JSONString)mn.get(2)).stringValue();
temp[3] = ((JSONString)mn.get(3)).stringValue();
temp[4] = ((JSONString)mn.get(4)).stringValue();
temp[5] = ((JSONString)mn.get(5)).stringValue();
temp[6] = ((JSONString)mn.get(6)).stringValue();
temp[7] = ((JSONString)mn.get(7)).stringValue();
temp[8] = ((JSONString)mn.get(8)).stringValue();
temp[9] = ((JSONString)mn.get(9)).stringValue();
temp[10] = ((JSONString)mn.get(10)).stringValue();
temp[11] = ((JSONString)mn.get(11)).stringValue();
temp[0] = ((JSONString) mn.get(0)).stringValue();
temp[1] = ((JSONString) mn.get(1)).stringValue();
temp[2] = ((JSONString) mn.get(2)).stringValue();
temp[3] = ((JSONString) mn.get(3)).stringValue();
temp[4] = ((JSONString) mn.get(4)).stringValue();
temp[5] = ((JSONString) mn.get(5)).stringValue();
temp[6] = ((JSONString) mn.get(6)).stringValue();
temp[7] = ((JSONString) mn.get(7)).stringValue();
temp[8] = ((JSONString) mn.get(8)).stringValue();
temp[9] = ((JSONString) mn.get(9)).stringValue();
temp[10] = ((JSONString) mn.get(10)).stringValue();
temp[11] = ((JSONString) mn.get(11)).stringValue();
return temp;
} else throw new LocaleNotLoadedException(locale);
} else
throw new LocaleNotLoadedException(locale);
}
public static String[] getShortMonthNames(String locale) throws LocaleNotLoadedException {
if(cache.containsKey(locale)) {
public static String[] getShortMonthNames(String locale)
throws LocaleNotLoadedException {
if (cache.containsKey(locale)) {
JSONObject l = (JSONObject) cache.get(locale);
JSONArray smn = (JSONArray) l.get("smn");
String[] temp = new String[12];
temp[0] = ((JSONString)smn.get(0)).stringValue();
temp[1] = ((JSONString)smn.get(1)).stringValue();
temp[2] = ((JSONString)smn.get(2)).stringValue();
temp[3] = ((JSONString)smn.get(3)).stringValue();
temp[4] = ((JSONString)smn.get(4)).stringValue();
temp[5] = ((JSONString)smn.get(5)).stringValue();
temp[6] = ((JSONString)smn.get(6)).stringValue();
temp[7] = ((JSONString)smn.get(7)).stringValue();
temp[8] = ((JSONString)smn.get(8)).stringValue();
temp[9] = ((JSONString)smn.get(9)).stringValue();
temp[10] = ((JSONString)smn.get(10)).stringValue();
temp[11] = ((JSONString)smn.get(11)).stringValue();
temp[0] = ((JSONString) smn.get(0)).stringValue();
temp[1] = ((JSONString) smn.get(1)).stringValue();
temp[2] = ((JSONString) smn.get(2)).stringValue();
temp[3] = ((JSONString) smn.get(3)).stringValue();
temp[4] = ((JSONString) smn.get(4)).stringValue();
temp[5] = ((JSONString) smn.get(5)).stringValue();
temp[6] = ((JSONString) smn.get(6)).stringValue();
temp[7] = ((JSONString) smn.get(7)).stringValue();
temp[8] = ((JSONString) smn.get(8)).stringValue();
temp[9] = ((JSONString) smn.get(9)).stringValue();
temp[10] = ((JSONString) smn.get(10)).stringValue();
temp[11] = ((JSONString) smn.get(11)).stringValue();
return temp;
} else throw new LocaleNotLoadedException(locale);
} else
throw new LocaleNotLoadedException(locale);
}
public static String[] getDayNames(String locale) throws LocaleNotLoadedException{
if(cache.containsKey(locale)) {
public static String[] getDayNames(String locale)
throws LocaleNotLoadedException {
if (cache.containsKey(locale)) {
JSONObject l = (JSONObject) cache.get(locale);
JSONArray dn = (JSONArray) l.get("dn");
String[] temp = new String[7];
temp[0] = ((JSONString)dn.get(0)).stringValue();
temp[1] = ((JSONString)dn.get(1)).stringValue();
temp[2] = ((JSONString)dn.get(2)).stringValue();
temp[3] = ((JSONString)dn.get(3)).stringValue();
temp[4] = ((JSONString)dn.get(4)).stringValue();
temp[5] = ((JSONString)dn.get(5)).stringValue();
temp[6] = ((JSONString)dn.get(6)).stringValue();
temp[0] = ((JSONString) dn.get(0)).stringValue();
temp[1] = ((JSONString) dn.get(1)).stringValue();
temp[2] = ((JSONString) dn.get(2)).stringValue();
temp[3] = ((JSONString) dn.get(3)).stringValue();
temp[4] = ((JSONString) dn.get(4)).stringValue();
temp[5] = ((JSONString) dn.get(5)).stringValue();
temp[6] = ((JSONString) dn.get(6)).stringValue();
return temp;
} else throw new LocaleNotLoadedException(locale);
} else
throw new LocaleNotLoadedException(locale);
}
public static String[] getShortDayNames(String locale) throws LocaleNotLoadedException {
if(cache.containsKey(locale)) {
public static String[] getShortDayNames(String locale)
throws LocaleNotLoadedException {
if (cache.containsKey(locale)) {
JSONObject l = (JSONObject) cache.get(locale);
JSONArray sdn = (JSONArray) l.get("sdn");
String[] temp = new String[7];
temp[0] = ((JSONString)sdn.get(0)).stringValue();
temp[1] = ((JSONString)sdn.get(1)).stringValue();
temp[2] = ((JSONString)sdn.get(2)).stringValue();
temp[3] = ((JSONString)sdn.get(3)).stringValue();
temp[4] = ((JSONString)sdn.get(4)).stringValue();
temp[5] = ((JSONString)sdn.get(5)).stringValue();
temp[6] = ((JSONString)sdn.get(6)).stringValue();
temp[0] = ((JSONString) sdn.get(0)).stringValue();
temp[1] = ((JSONString) sdn.get(1)).stringValue();
temp[2] = ((JSONString) sdn.get(2)).stringValue();
temp[3] = ((JSONString) sdn.get(3)).stringValue();
temp[4] = ((JSONString) sdn.get(4)).stringValue();
temp[5] = ((JSONString) sdn.get(5)).stringValue();
temp[6] = ((JSONString) sdn.get(6)).stringValue();
return temp;
} else throw new LocaleNotLoadedException(locale);
} else
throw new LocaleNotLoadedException(locale);
}
public static int getFirstDayOfWeek(String locale) throws LocaleNotLoadedException {
if(cache.containsKey(locale)) {
public static int getFirstDayOfWeek(String locale)
throws LocaleNotLoadedException {
if (cache.containsKey(locale)) {
JSONObject l = (JSONObject) cache.get(locale);
JSONNumber fdow = (JSONNumber) l.get("fdow");
return (int) fdow.getValue();
} else throw new LocaleNotLoadedException(locale);
} else
throw new LocaleNotLoadedException(locale);
}
public static String getDateFormat(String locale) throws LocaleNotLoadedException {
if(cache.containsKey(locale)) {
public static String getDateFormat(String locale)
throws LocaleNotLoadedException {
if (cache.containsKey(locale)) {
JSONObject l = (JSONObject) cache.get(locale);
JSONString df = (JSONString) l.get("df");
return df.stringValue();
} else throw new LocaleNotLoadedException(locale);
} else
throw new LocaleNotLoadedException(locale);
}
public static boolean isTwelveHourClock(String locale) throws LocaleNotLoadedException {
if(cache.containsKey(locale)) {
public static boolean isTwelveHourClock(String locale)
throws LocaleNotLoadedException {
if (cache.containsKey(locale)) {
JSONObject l = (JSONObject) cache.get(locale);
JSONBoolean thc = (JSONBoolean) l.get("thc");
return thc.booleanValue();
} else throw new LocaleNotLoadedException(locale);
} else
throw new LocaleNotLoadedException(locale);
}
public static String getClockDelimiter(String locale) throws LocaleNotLoadedException {
if(cache.containsKey(locale)) {
public static String getClockDelimiter(String locale)
throws LocaleNotLoadedException {
if (cache.containsKey(locale)) {
JSONObject l = (JSONObject) cache.get(locale);
JSONString hmd = (JSONString) l.get("hmd");
return hmd.stringValue();
} else throw new LocaleNotLoadedException(locale);
} else
throw new LocaleNotLoadedException(locale);
}
public static String[] getAmPmStrings(String locale) throws LocaleNotLoadedException {
if(cache.containsKey(locale)) {
public static String[] getAmPmStrings(String locale)
throws LocaleNotLoadedException {
if (cache.containsKey(locale)) {
JSONObject l = (JSONObject) cache.get(locale);
JSONArray ampm = (JSONArray) l.get("ampm");
String[] temp = new String[2];
temp[0] = ((JSONString)ampm.get(0)).stringValue();
temp[1] = ((JSONString)ampm.get(1)).stringValue();
temp[0] = ((JSONString) ampm.get(0)).stringValue();
temp[1] = ((JSONString) ampm.get(1)).stringValue();
return temp;
} else throw new LocaleNotLoadedException(locale);
} else
throw new LocaleNotLoadedException(locale);
}
}

+ 3
- 3
src/com/itmill/toolkit/terminal/gwt/client/NullConsole.java View File

@@ -1,9 +1,9 @@
package com.itmill.toolkit.terminal.gwt.client;

/**
* Client side console implementation for non-debug mode
* that discards all messages.
*
* Client side console implementation for non-debug mode that discards all
* messages.
*
*/
public class NullConsole implements Console {


+ 17
- 14
src/com/itmill/toolkit/terminal/gwt/client/UIDL.java View File

@@ -61,7 +61,7 @@ public class UIDL {
double num = ((JSONNumber) val).getValue();
return (long) num;
}
public float getFloatAttribute(String name) {
JSONValue val = ((JSONObject) json.get(1)).get(name);
if (val == null)
@@ -69,7 +69,7 @@ public class UIDL {
double num = ((JSONNumber) val).getValue();
return (float) num;
}
public double getDoubleAttribute(String name) {
JSONValue val = ((JSONObject) json.get(1)).get(name);
if (val == null)
@@ -84,7 +84,7 @@ public class UIDL {
return false;
return ((JSONBoolean) val).booleanValue();
}
public String[] getStringArrayAttribute(String name) {
JSONArray a = (JSONArray) ((JSONObject) json.get(1)).get(name);
String[] s = new String[a.size()];
@@ -176,7 +176,7 @@ public class UIDL {

};
}
public int getNumberOfChildren() {
return json.size() - 2;
}
@@ -188,8 +188,10 @@ public class UIDL {
String name = i.next().toString();
s += " " + name + "=";
JSONValue v = ((JSONObject) json.get(1)).get(name);
if (v.isString() != null) s += v;
else s += "\"" + v + "\"";
if (v.isString() != null)
s += v;
else
s += "\"" + v + "\"";
}

s += ">\n";
@@ -206,7 +208,7 @@ public class UIDL {
}

public String getChildrenAsXML() {
String s="";
String s = "";
Iterator i = getChildIterator();
while (i.hasNext()) {
Object c = i.next();
@@ -214,7 +216,7 @@ public class UIDL {
}
return s;
}
public UIDLBrowser print_r() {
return new UIDLBrowser();
}
@@ -305,12 +307,13 @@ public class UIDL {
throw new IllegalArgumentException("No variables defined in tag.");
return v;
}
public boolean hasVariable(String name) {
Object v = null;
try {
v = getVariableHash().get(name);
} catch(IllegalArgumentException e) {}
} catch (IllegalArgumentException e) {
}
return v != null;
}

@@ -334,14 +337,14 @@ public class UIDL {
throw new IllegalArgumentException("No such variable: " + name);
return (long) t.getValue();
}
public float getFloatVariable(String name) {
JSONNumber t = (JSONNumber) getVariableHash().get(name);
if (t == null)
throw new IllegalArgumentException("No such variable: " + name);
return (float) t.getValue();
}
public double getDoubleVariable(String name) {
JSONNumber t = (JSONNumber) getVariableHash().get(name);
if (t == null)
@@ -399,7 +402,7 @@ public class UIDL {

public String getXMLAsString() {
StringBuffer sb = new StringBuffer();
for(Iterator it = x.keySet().iterator(); it.hasNext();) {
for (Iterator it = x.keySet().iterator(); it.hasNext();) {
String tag = (String) it.next();
sb.append("<");
sb.append(tag);
@@ -414,7 +417,7 @@ public class UIDL {
}

public int getChidlCount() {
return json.size()-2;
return json.size() - 2;
}

public UIDL getErrors() {

+ 4
- 3
src/com/itmill/toolkit/terminal/gwt/client/Util.java View File

@@ -31,7 +31,7 @@ public class Util {
}
return false;
}-*/;
/**
* Nulls oncontextmenu function on given element. We need to manually clear
* context menu events due bad browsers memory leaks, since we GWT don't
@@ -44,8 +44,9 @@ public class Util {
}-*/;

/**
* Traverses recursively ancestors until ContainerResizedListener child widget is found.
* They will delegate it futher if needed.
* Traverses recursively ancestors until ContainerResizedListener child
* widget is found. They will delegate it futher if needed.
*
* @param container
*/
public static void runAnchestorsLayout(HasWidgets container) {

+ 14
- 7
src/com/itmill/toolkit/terminal/gwt/client/WidgetSet.java View File

@@ -5,18 +5,25 @@ import com.google.gwt.user.client.ui.Widget;

public interface WidgetSet extends EntryPoint {

/** Create an uninitialized component that best matches given UIDL.
/**
* Create an uninitialized component that best matches given UIDL.
*
* @param uidl UIDL to be painted with returned component.
* @return New uninitialized and unregistered component that can paint given UIDL.
* @param uidl
* UIDL to be painted with returned component.
* @return New uninitialized and unregistered component that can paint given
* UIDL.
*/
public Widget createWidget(UIDL uidl);

/** Test if the given component implementation conforms to UIDL.
/**
* Test if the given component implementation conforms to UIDL.
*
* @param currentWidget Current implementation of the component
* @param uidl UIDL to test against
* @return true iff createWidget would return a new component of the same class than currentWidget
* @param currentWidget
* Current implementation of the component
* @param uidl
* UIDL to test against
* @return true iff createWidget would return a new component of the same
* class than currentWidget
*/
public boolean isCorrectImplementation(Widget currentWidget, UIDL uidl);
}

+ 102
- 101
src/com/itmill/toolkit/terminal/gwt/client/ui/CalendarEntry.java View File

@@ -5,108 +5,109 @@ import java.util.Date;
import com.itmill.toolkit.terminal.gwt.client.DateTimeService;
public class CalendarEntry {
private Date start;
private Date end;
private String title;
private String description;
private boolean notime;
public CalendarEntry(Date start, Date end, String title, String description, boolean notime) {
if (notime) {
Date d = new Date(start.getTime());
d.setSeconds(0);
d.setMinutes(0);
this.start = d;
if (end != null) {
d = new Date(end.getTime());
d.setSeconds(0);
d.setMinutes(0);
this.end = d;
} else {
end = start;
}
} else {
this.start = start;
this.end = end;
private Date start;
private Date end;
private String title;
private String description;
private boolean notime;
public CalendarEntry(Date start, Date end, String title,
String description, boolean notime) {
if (notime) {
Date d = new Date(start.getTime());
d.setSeconds(0);
d.setMinutes(0);
this.start = d;
if (end != null) {
d = new Date(end.getTime());
d.setSeconds(0);
d.setMinutes(0);
this.end = d;
} else {
end = start;
}
} else {
this.start = start;
this.end = end;
}
this.title = title;
this.description = description;
this.notime = notime;
}
this.title = title;
this.description = description;
this.notime = notime;
}
public CalendarEntry(Date start, Date end, String title, String description) {
this(start, end, title, description, false);
}
public Date getStart() {
return start;
}
public void setStart(Date start) {
this.start = start;
}
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isNotime() {
return notime;
}
public void setNotime(boolean notime) {
this.notime = notime;
}
public String getStringForDate(Date d) {
// TODO format from DateTimeService
String s = "";
if (!notime) {
if (!DateTimeService.isSameDay(d, start)) {
s += (start.getYear() + 1900) + "." + (start.getMonth() + 1)
+ "." + start.getDate() + " ";
}
int i = start.getHours();
s += (i < 10 ? "0" : "") + i;
s += ":";
i = start.getMinutes();
s += (i < 10 ? "0" : "") + i;
if (!start.equals(end)) {
s += " - ";
if (!DateTimeService.isSameDay(start, end)) {
s += (end.getYear() + 1900) + "." + (end.getMonth() + 1) + "."
+ end.getDate() + " ";
}
i = end.getHours();
s += (i < 10 ? "0" : "") + i;
s += ":";
i = end.getMinutes();
s += (i < 10 ? "0" : "") + i;
}
s += " ";
public CalendarEntry(Date start, Date end, String title, String description) {
this(start, end, title, description, false);
}
public Date getStart() {
return start;
}
public void setStart(Date start) {
this.start = start;
}
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isNotime() {
return notime;
}
public void setNotime(boolean notime) {
this.notime = notime;
}
public String getStringForDate(Date d) {
// TODO format from DateTimeService
String s = "";
if (!notime) {
if (!DateTimeService.isSameDay(d, start)) {
s += (start.getYear() + 1900) + "." + (start.getMonth() + 1)
+ "." + start.getDate() + " ";
}
int i = start.getHours();
s += (i < 10 ? "0" : "") + i;
s += ":";
i = start.getMinutes();
s += (i < 10 ? "0" : "") + i;
if (!start.equals(end)) {
s += " - ";
if (!DateTimeService.isSameDay(start, end)) {
s += (end.getYear() + 1900) + "." + (end.getMonth() + 1)
+ "." + end.getDate() + " ";
}
i = end.getHours();
s += (i < 10 ? "0" : "") + i;
s += ":";
i = end.getMinutes();
s += (i < 10 ? "0" : "") + i;
}
s += " ";
}
s += title;
return s;
}
s += title;
return s;
}
}

+ 347
- 338
src/com/itmill/toolkit/terminal/gwt/client/ui/CalendarPanel.java View File

@@ -19,390 +19,399 @@ import com.itmill.toolkit.terminal.gwt.client.DateTimeService;
import com.itmill.toolkit.terminal.gwt.client.LocaleService;
public class CalendarPanel extends FlexTable implements MouseListener,
ClickListener {
private IDateField datefield;
private IEventButton prevYear;
private IEventButton nextYear;
private IEventButton prevMonth;
private IEventButton nextMonth;
private Time time;
private Date minDate = null;
private Date maxDate = null;
private CalendarEntrySource entrySource;
/* Needed to identify resolution changes */
private int resolution = IDateField.RESOLUTION_YEAR;
/* Needed to identify locale changes */
private String locale = LocaleService.getDefaultLocale();
public CalendarPanel(IDateField parent) {
datefield = parent;
setStyleName(datefield.CLASSNAME + "-calendarpanel");
// buildCalendar(true);
addTableListener(new DateClickListener(this));
}
public CalendarPanel(IDateField parent, Date min, Date max) {
datefield = parent;
setStyleName(datefield.CLASSNAME + "-calendarpanel");
// buildCalendar(true);
addTableListener(new DateClickListener(this));
}
private void buildCalendar(boolean forceRedraw) {
boolean needsMonth = datefield.getCurrentResolution() > IDateField.RESOLUTION_YEAR;
boolean needsBody = datefield.getCurrentResolution() >= IDateField.RESOLUTION_DAY;
boolean needsTime = datefield.getCurrentResolution() >= IDateField.RESOLUTION_HOUR;
buildCalendarHeader(forceRedraw, needsMonth);
clearCalendarBody(!needsBody);
if (needsBody)
buildCalendarBody();
if (needsTime)
buildTime(forceRedraw);
else if (time != null) {
remove(time);
time = null;
ClickListener {
private IDateField datefield;
private IEventButton prevYear;
private IEventButton nextYear;
private IEventButton prevMonth;
private IEventButton nextMonth;
private Time time;
private Date minDate = null;
private Date maxDate = null;
private CalendarEntrySource entrySource;
/* Needed to identify resolution changes */
private int resolution = IDateField.RESOLUTION_YEAR;
/* Needed to identify locale changes */
private String locale = LocaleService.getDefaultLocale();
public CalendarPanel(IDateField parent) {
datefield = parent;
setStyleName(datefield.CLASSNAME + "-calendarpanel");
// buildCalendar(true);
addTableListener(new DateClickListener(this));
}
}
private void clearCalendarBody(boolean remove) {
if (!remove) {
for (int row = 2; row < 8; row++) {
for (int col = 0; col < 7; col++) {
setHTML(row, col, "&nbsp;");
}
}
} else if (getRowCount() > 2) {
while (getRowCount() > 2)
removeRow(2);
public CalendarPanel(IDateField parent, Date min, Date max) {
datefield = parent;
setStyleName(datefield.CLASSNAME + "-calendarpanel");
// buildCalendar(true);
addTableListener(new DateClickListener(this));
}
}
private void buildCalendarHeader(boolean forceRedraw, boolean needsMonth) {
// Can't draw a calendar without a date :)
if (datefield.getCurrentDate() == null)
datefield.setCurrentDate(new Date());
if (forceRedraw) {
if (prevMonth == null) { // Only do once
prevYear = new IEventButton();
prevYear.setHTML("&laquo;");
nextYear = new IEventButton();
nextYear.setHTML("&raquo;");
prevYear.addMouseListener(this);
nextYear.addMouseListener(this);
prevYear.addClickListener(this);
nextYear.addClickListener(this);
setWidget(0, 0, prevYear);
setWidget(0, 4, nextYear);
if (needsMonth) {
prevMonth = new IEventButton();
prevMonth.setHTML("&lsaquo;");
nextMonth = new IEventButton();
nextMonth.setHTML("&rsaquo;");
prevMonth.addMouseListener(this);
nextMonth.addMouseListener(this);
prevMonth.addClickListener(this);
nextMonth.addClickListener(this);
setWidget(0, 3, nextMonth);
setWidget(0, 1, prevMonth);
}
getFlexCellFormatter().setColSpan(0, 2, 3);
} else if (!needsMonth) {
// Remove month traverse buttons
prevMonth.removeClickListener(this);
prevMonth.removeMouseListener(this);
nextMonth.removeClickListener(this);
nextMonth.removeMouseListener(this);
remove(prevMonth);
remove(nextMonth);
prevMonth = null;
nextMonth = null;
}
// Print weekday names
int firstDay = datefield.getDateTimeService().getFirstDayOfWeek();
for (int i = 0; i < 7; i++) {
int day = i + firstDay;
if (day > 6)
day = 0;
if (datefield.getCurrentResolution() > IDateField.RESOLUTION_MONTH)
setHTML(1, i, "<strong>"
+ datefield.getDateTimeService().getShortDay(day)
+ "</strong>");
else
setHTML(1, i, "");
}
private void buildCalendar(boolean forceRedraw) {
boolean needsMonth = datefield.getCurrentResolution() > IDateField.RESOLUTION_YEAR;
boolean needsBody = datefield.getCurrentResolution() >= IDateField.RESOLUTION_DAY;
boolean needsTime = datefield.getCurrentResolution() >= IDateField.RESOLUTION_HOUR;
buildCalendarHeader(forceRedraw, needsMonth);
clearCalendarBody(!needsBody);
if (needsBody)
buildCalendarBody();
if (needsTime)
buildTime(forceRedraw);
else if (time != null) {
remove(time);
time = null;
}
}
String monthName = needsMonth ? datefield.getDateTimeService()
.getMonth(datefield.getCurrentDate().getMonth()) : "";
int year = datefield.getCurrentDate().getYear() + 1900;
setHTML(0, 2, "<span class=\"" + datefield.CLASSNAME
+ "-calendarpanel-month\">" + monthName + " " + year
+ "</span>");
}
private void buildCalendarBody() {
Date date = datefield.getCurrentDate();
if (date == null)
date = new Date();
int startWeekDay = datefield.getDateTimeService().getStartWeekDay(date);
int numDays = DateTimeService.getNumberOfDaysInMonth(date);
int dayCount = 0;
Date today = new Date();
Date curr = new Date(date.getTime());
for (int row = 2; row < 8; row++) {
for (int col = 0; col < 7; col++) {
if (!(row == 2 && col < startWeekDay)) {
if (dayCount < numDays) {
int selectedDate = ++dayCount;
String title = "";
if (this.entrySource != null) {
curr.setDate(dayCount);
List entries = this.entrySource.getEntries(curr,
IDateField.RESOLUTION_DAY);
if (entries != null) {
for (Iterator it = entries.iterator(); it
.hasNext();) {
CalendarEntry entry = (CalendarEntry) it
.next();
title += (title.length() > 0 ? ", " : "")
+ entry.getStringForDate(curr);
private void clearCalendarBody(boolean remove) {
if (!remove) {
for (int row = 2; row < 8; row++) {
for (int col = 0; col < 7; col++) {
setHTML(row, col, "&nbsp;");
}
}
}
String baseclass = datefield.CLASSNAME
+ "-calendarpanel-day";
String cssClass = baseclass;
if (!isEnabledDate(curr)) {
cssClass += " " + baseclass + "-disabled";
} else if (getRowCount() > 2) {
while (getRowCount() > 2)
removeRow(2);
}
}
private void buildCalendarHeader(boolean forceRedraw, boolean needsMonth) {
// Can't draw a calendar without a date :)
if (datefield.getCurrentDate() == null)
datefield.setCurrentDate(new Date());
if (forceRedraw) {
if (prevMonth == null) { // Only do once
prevYear = new IEventButton();
prevYear.setHTML("&laquo;");
nextYear = new IEventButton();
nextYear.setHTML("&raquo;");
prevYear.addMouseListener(this);
nextYear.addMouseListener(this);
prevYear.addClickListener(this);
nextYear.addClickListener(this);
setWidget(0, 0, prevYear);
setWidget(0, 4, nextYear);
if (needsMonth) {
prevMonth = new IEventButton();
prevMonth.setHTML("&lsaquo;");
nextMonth = new IEventButton();
nextMonth.setHTML("&rsaquo;");
prevMonth.addMouseListener(this);
nextMonth.addMouseListener(this);
prevMonth.addClickListener(this);
nextMonth.addClickListener(this);
setWidget(0, 3, nextMonth);
setWidget(0, 1, prevMonth);
}
getFlexCellFormatter().setColSpan(0, 2, 3);
} else if (!needsMonth) {
// Remove month traverse buttons
prevMonth.removeClickListener(this);
prevMonth.removeMouseListener(this);
nextMonth.removeClickListener(this);
nextMonth.removeMouseListener(this);
remove(prevMonth);
remove(nextMonth);
prevMonth = null;
nextMonth = null;
}
if (date.getDate() == dayCount) {
cssClass += " " + baseclass + "-selected";
// Print weekday names
int firstDay = datefield.getDateTimeService().getFirstDayOfWeek();
for (int i = 0; i < 7; i++) {
int day = i + firstDay;
if (day > 6)
day = 0;
if (datefield.getCurrentResolution() > IDateField.RESOLUTION_MONTH)
setHTML(1, i, "<strong>"
+ datefield.getDateTimeService().getShortDay(day)
+ "</strong>");
else
setHTML(1, i, "");
}
if (today.getDate() == dayCount
&& today.getMonth() == date.getMonth()
&& today.getYear() == date.getYear()) {
cssClass += " " + baseclass + "-today";
}
String monthName = needsMonth ? datefield.getDateTimeService()
.getMonth(datefield.getCurrentDate().getMonth()) : "";
int year = datefield.getCurrentDate().getYear() + 1900;
setHTML(0, 2, "<span class=\"" + datefield.CLASSNAME
+ "-calendarpanel-month\">" + monthName + " " + year
+ "</span>");
}
private void buildCalendarBody() {
Date date = datefield.getCurrentDate();
if (date == null)
date = new Date();
int startWeekDay = datefield.getDateTimeService().getStartWeekDay(date);
int numDays = DateTimeService.getNumberOfDaysInMonth(date);
int dayCount = 0;
Date today = new Date();
Date curr = new Date(date.getTime());
for (int row = 2; row < 8; row++) {
for (int col = 0; col < 7; col++) {
if (!(row == 2 && col < startWeekDay)) {
if (dayCount < numDays) {
int selectedDate = ++dayCount;
String title = "";
if (this.entrySource != null) {
curr.setDate(dayCount);
List entries = this.entrySource.getEntries(curr,
IDateField.RESOLUTION_DAY);
if (entries != null) {
for (Iterator it = entries.iterator(); it
.hasNext();) {
CalendarEntry entry = (CalendarEntry) it
.next();
title += (title.length() > 0 ? ", " : "")
+ entry.getStringForDate(curr);
}
}
}
String baseclass = datefield.CLASSNAME
+ "-calendarpanel-day";
String cssClass = baseclass;
if (!isEnabledDate(curr)) {
cssClass += " " + baseclass + "-disabled";
}
if (date.getDate() == dayCount) {
cssClass += " " + baseclass + "-selected";
}
if (today.getDate() == dayCount
&& today.getMonth() == date.getMonth()
&& today.getYear() == date.getYear()) {
cssClass += " " + baseclass + "-today";
}
if (title.length() > 0)
cssClass += " " + baseclass + "-entry";
setHTML(row, col, "<span title=\"" + title
+ "\" class=\"" + cssClass + "\">"
+ selectedDate + "</span>");
} else {
break;
}
}
}
if (title.length() > 0)
cssClass += " " + baseclass + "-entry";
setHTML(row, col, "<span title=\"" + title
+ "\" class=\"" + cssClass + "\">"
+ selectedDate + "</span>");
} else {
break;
}
}
}
private void buildTime(boolean forceRedraw) {
if (time == null) {
time = new Time(datefield);
setText(8, 0, ""); // Add new row
getFlexCellFormatter().setColSpan(8, 0, 7);
setWidget(8, 0, time);
}
}
time.updateTime(forceRedraw);
}
}
private void buildTime(boolean forceRedraw) {
if (time == null) {
time = new Time(datefield);
setText(8, 0, ""); // Add new row
getFlexCellFormatter().setColSpan(8, 0, 7);
setWidget(8, 0, time);
/**
*
* @param forceRedraw
* Build all from scratch, in case of e.g. locale changes
*/
public void updateCalendar() {
// Locale and resolution changes force a complete redraw
buildCalendar(locale != datefield.getCurrentLocale()
|| resolution != datefield.getCurrentResolution());
if (datefield instanceof ITextualDate)
((ITextualDate) datefield).buildDate();
locale = datefield.getCurrentLocale();
resolution = datefield.getCurrentResolution();
}
time.updateTime(forceRedraw);
}
/**
*
* @param forceRedraw
* Build all from scratch, in case of e.g. locale changes
*/
public void updateCalendar() {
// Locale and resolution changes force a complete redraw
buildCalendar(locale != datefield.getCurrentLocale()
|| resolution != datefield.getCurrentResolution());
if (datefield instanceof ITextualDate)
((ITextualDate) datefield).buildDate();
locale = datefield.getCurrentLocale();
resolution = datefield.getCurrentResolution();
}
public void onClick(Widget sender) {
processClickEvent(sender);
}
private boolean isEnabledDate(Date date) {
if ((this.minDate != null && date.before(this.minDate))
|| (this.maxDate != null && date.after(this.maxDate))) {
return false;
public void onClick(Widget sender) {
processClickEvent(sender);
}
return true;
}
private void processClickEvent(Widget sender) {
if (!datefield.isEnabled() || datefield.isReadonly())
return;
if (sender == prevYear) {
datefield.getCurrentDate().setYear(datefield.getCurrentDate().getYear() - 1);
datefield.getClient().updateVariable(datefield.getId(), "year",
datefield.getCurrentDate().getYear() + 1900, datefield.isImmediate());
updateCalendar();
} else if (sender == nextYear) {
datefield.getCurrentDate().setYear(datefield.getCurrentDate().getYear() + 1);
datefield.getClient().updateVariable(datefield.getId(), "year",
datefield.getCurrentDate().getYear() + 1900, datefield.isImmediate());
updateCalendar();
} else if (sender == prevMonth) {
datefield.getCurrentDate().setMonth(datefield.getCurrentDate().getMonth() - 1);
datefield.getClient().updateVariable(datefield.getId(), "month",
datefield.getCurrentDate().getMonth() + 1, datefield.isImmediate());
updateCalendar();
} else if (sender == nextMonth) {
datefield.getCurrentDate().setMonth(datefield.getCurrentDate().getMonth() + 1);
datefield.getClient().updateVariable(datefield.getId(), "month",
datefield.getCurrentDate().getMonth() + 1, datefield.isImmediate());
updateCalendar();
private boolean isEnabledDate(Date date) {
if ((this.minDate != null && date.before(this.minDate))
|| (this.maxDate != null && date.after(this.maxDate))) {
return false;
}
return true;
}
}
private Timer timer;
private void processClickEvent(Widget sender) {
if (!datefield.isEnabled() || datefield.isReadonly())
return;
if (sender == prevYear) {
datefield.getCurrentDate().setYear(
datefield.getCurrentDate().getYear() - 1);
datefield.getClient().updateVariable(datefield.getId(), "year",
datefield.getCurrentDate().getYear() + 1900,
datefield.isImmediate());
updateCalendar();
} else if (sender == nextYear) {
datefield.getCurrentDate().setYear(
datefield.getCurrentDate().getYear() + 1);
datefield.getClient().updateVariable(datefield.getId(), "year",
datefield.getCurrentDate().getYear() + 1900,
datefield.isImmediate());
updateCalendar();
} else if (sender == prevMonth) {
datefield.getCurrentDate().setMonth(
datefield.getCurrentDate().getMonth() - 1);
datefield.getClient().updateVariable(datefield.getId(), "month",
datefield.getCurrentDate().getMonth() + 1,
datefield.isImmediate());
updateCalendar();
} else if (sender == nextMonth) {
datefield.getCurrentDate().setMonth(
datefield.getCurrentDate().getMonth() + 1);
datefield.getClient().updateVariable(datefield.getId(), "month",
datefield.getCurrentDate().getMonth() + 1,
datefield.isImmediate());
updateCalendar();
}
}
public void onMouseDown(final Widget sender, int x, int y) {
if (sender instanceof IEventButton) {
timer = new Timer() {
public void run() {
processClickEvent(sender);
private Timer timer;
public void onMouseDown(final Widget sender, int x, int y) {
if (sender instanceof IEventButton) {
timer = new Timer() {
public void run() {
processClickEvent(sender);
}
};
timer.scheduleRepeating(100);
}
};
timer.scheduleRepeating(100);
}
}
public void onMouseEnter(Widget sender) {
}
public void onMouseEnter(Widget sender) {
}
public void onMouseLeave(Widget sender) {
if (timer != null)
timer.cancel();
}
public void onMouseLeave(Widget sender) {
if (timer != null)
timer.cancel();
}
public void onMouseMove(Widget sender, int x, int y) {
}
public void onMouseMove(Widget sender, int x, int y) {
}
public void onMouseUp(Widget sender, int x, int y) {
if (timer != null)
timer.cancel();
}
public void onMouseUp(Widget sender, int x, int y) {
if (timer != null)
timer.cancel();
}
private class IEventButton extends IButton implements SourcesMouseEvents {
private class IEventButton extends IButton implements SourcesMouseEvents {
private MouseListenerCollection mouseListeners;
private MouseListenerCollection mouseListeners;
public IEventButton() {
super();
sinkEvents(Event.FOCUSEVENTS | Event.KEYEVENTS | Event.ONCLICK
| Event.MOUSEEVENTS);
}
public IEventButton() {
super();
sinkEvents(Event.FOCUSEVENTS | Event.KEYEVENTS | Event.ONCLICK
| Event.MOUSEEVENTS);
}
public void addMouseListener(MouseListener listener) {
if (mouseListeners == null) {
mouseListeners = new MouseListenerCollection();
}
mouseListeners.add(listener);
}
public void addMouseListener(MouseListener listener) {
if (mouseListeners == null) {
mouseListeners = new MouseListenerCollection();
}
mouseListeners.add(listener);
}
public void removeMouseListener(MouseListener listener) {
if (mouseListeners != null)
mouseListeners.remove(listener);
}
public void removeMouseListener(MouseListener listener) {
if (mouseListeners != null)
mouseListeners.remove(listener);
}
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
case Event.ONMOUSEUP:
case Event.ONMOUSEMOVE:
case Event.ONMOUSEOVER:
case Event.ONMOUSEOUT:
if (mouseListeners != null) {
mouseListeners.fireMouseEvent(this, event);
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
case Event.ONMOUSEUP:
case Event.ONMOUSEMOVE:
case Event.ONMOUSEOVER:
case Event.ONMOUSEOUT:
if (mouseListeners != null) {
mouseListeners.fireMouseEvent(this, event);
}
break;
}
}
break;
}
}
}
private class DateClickListener implements TableListener {
private class DateClickListener implements TableListener {
private CalendarPanel cal;
private CalendarPanel cal;
public DateClickListener(CalendarPanel panel) {
cal = panel;
}
public DateClickListener(CalendarPanel panel) {
cal = panel;
}
public void onCellClicked(SourcesTableEvents sender, int row, int col) {
if (sender != cal || row < 2 || row > 7 || !cal.datefield.isEnabled()
|| cal.datefield.isReadonly())
return;
public void onCellClicked(SourcesTableEvents sender, int row, int col) {
if (sender != cal || row < 2 || row > 7
|| !cal.datefield.isEnabled() || cal.datefield.isReadonly())
return;
String text = cal.getText(row, col);
if (text.equals(" "))
return;
String text = cal.getText(row, col);
if (text.equals(" "))
return;
Integer day = new Integer(text);
Integer day = new Integer(text);
Date newDate = new Date(cal.datefield.getCurrentDate().getTime());
newDate.setDate(day.intValue());
if (!isEnabledDate(newDate)) {
return;
}
cal.datefield.getCurrentDate().setTime(newDate.getTime());
cal.datefield.getClient().updateVariable(cal.datefield.getId(), "day",
cal.datefield.getCurrentDate().getDate(), cal.datefield.isImmediate());
Date newDate = new Date(cal.datefield.getCurrentDate().getTime());
newDate.setDate(day.intValue());
if (!isEnabledDate(newDate)) {
return;
}
cal.datefield.getCurrentDate().setTime(newDate.getTime());
cal.datefield.getClient().updateVariable(cal.datefield.getId(),
"day", cal.datefield.getCurrentDate().getDate(),
cal.datefield.isImmediate());
updateCalendar();
}
updateCalendar();
}
}
public void setLimits(Date min, Date max) {
if (min != null) {
Date d = new Date(min.getTime());
d.setHours(0);
d.setMinutes(0);
d.setSeconds(1);
this.minDate = d;
} else {
this.minDate = null;
}
if (max != null) {
Date d = new Date(max.getTime());
d.setHours(24);
d.setMinutes(59);
d.setSeconds(59);
this.maxDate = d;
} else {
this.maxDate = null;
public void setLimits(Date min, Date max) {
if (min != null) {
Date d = new Date(min.getTime());
d.setHours(0);
d.setMinutes(0);
d.setSeconds(1);
this.minDate = d;
} else {
this.minDate = null;
}
if (max != null) {
Date d = new Date(max.getTime());
d.setHours(24);
d.setMinutes(59);
d.setSeconds(59);
this.maxDate = d;
} else {
this.maxDate = null;
}
}
}
public void setCalendarEntrySource(CalendarEntrySource entrySource) {
this.entrySource = entrySource;
}
public void setCalendarEntrySource(CalendarEntrySource entrySource) {
this.entrySource = entrySource;
}
public CalendarEntrySource getCalendarEntrySource() {
return this.entrySource;
}
public CalendarEntrySource getCalendarEntrySource() {
return this.entrySource;
}
public interface CalendarEntrySource {
public List getEntries(Date date, int resolution);
}
public interface CalendarEntrySource {
public List getEntries(Date date, int resolution);
}
}

+ 17
- 15
src/com/itmill/toolkit/terminal/gwt/client/ui/ContextMenu.java View File

@@ -7,32 +7,33 @@ import com.google.gwt.user.client.ui.MenuItem;
import com.google.gwt.user.client.ui.PopupPanel;

public class ContextMenu extends PopupPanel {
private ActionOwner actionOwner;
private CMenuBar menu = new CMenuBar();
/**
* This method should be used only by Client object as
* only one per client should exists. Request an instance
* via client.getContextMenu();
* This method should be used only by Client object as only one per client
* should exists. Request an instance via client.getContextMenu();
*
* @param cli to be set as an owner of menu
* @param cli
* to be set as an owner of menu
*/
public ContextMenu() {
super(true);
setWidget(menu);
setStyleName("i-contextmenu");
}
/**
* Sets the element from which to build menu
*
* @param ao
*/
public void setActionOwner(ActionOwner ao) {
this.actionOwner = ao;
}
/**
* Shows context menu at given location.
*
@@ -46,12 +47,14 @@ public class ContextMenu extends PopupPanel {
Action a = actions[i];
menu.addItem(new MenuItem(a.getHTML(), true, a));
}
setPopupPosition(left, top);
show();
// fix position if "outside" screen
if(DOM.getElementPropertyInt(getElement(),"offsetWidth") + left > Window.getClientWidth()) {
left = Window.getClientWidth() - DOM.getElementPropertyInt(getElement(),"offsetWidth");
if (DOM.getElementPropertyInt(getElement(), "offsetWidth") + left > Window
.getClientWidth()) {
left = Window.getClientWidth()
- DOM.getElementPropertyInt(getElement(), "offsetWidth");
setPopupPosition(left, top);
}
}
@@ -62,9 +65,8 @@ public class ContextMenu extends PopupPanel {
}

/**
* Extend standard Gwt MenuBar to set proper settings and
* to override onPopupClosed method so that PopupPanel gets
* closed.
* Extend standard Gwt MenuBar to set proper settings and to override
* onPopupClosed method so that PopupPanel gets closed.
*/
class CMenuBar extends MenuBar {
public CMenuBar() {

+ 6
- 6
src/com/itmill/toolkit/terminal/gwt/client/ui/HorizontalSplitPanelImages.java View File

@@ -4,12 +4,12 @@ import com.google.gwt.user.client.ui.AbstractImagePrototype;
public interface HorizontalSplitPanelImages extends
com.google.gwt.user.client.ui.HorizontalSplitPanelImages {
/**
* An image representing the drag thumb.
*
* @gwt.resource com/itmill/toolkit/terminal/gwt/public/default/common/img/blank.gif
*/
* An image representing the drag thumb.
*
* @gwt.resource com/itmill/toolkit/terminal/gwt/public/default/common/img/blank.gif
*/
AbstractImagePrototype horizontalSplitPanelThumb();
}

+ 30
- 26
src/com/itmill/toolkit/terminal/gwt/client/ui/IButton.java View File

@@ -13,7 +13,7 @@ import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;

public class IButton extends Button implements Paintable {
public static final String CLASSNAME = "i-button";

String id;
@@ -23,9 +23,8 @@ public class IButton extends Button implements Paintable {
private Element errorIndicatorElement;

private ErrorMessage errorMessage;
private PopupPanel errorContainer;

private PopupPanel errorContainer;

public IButton() {
setStyleName(CLASSNAME);
@@ -52,32 +51,34 @@ public class IButton extends Button implements Paintable {

// Set text
setText(uidl.getStringAttribute("caption"));
if(uidl.hasAttribute("error")) {
if (uidl.hasAttribute("error")) {
UIDL errorUidl = uidl.getErrors();
if(errorIndicatorElement == null) {
if (errorIndicatorElement == null) {
errorIndicatorElement = DOM.createDiv();
DOM.setElementProperty(errorIndicatorElement, "className", "i-errorindicator");
DOM.setElementProperty(errorIndicatorElement, "className",
"i-errorindicator");
DOM.sinkEvents(errorIndicatorElement, Event.MOUSEEVENTS);
}
DOM.insertChild(getElement(), errorIndicatorElement, 0);
if(errorMessage == null)
if (errorMessage == null)
errorMessage = new ErrorMessage();
errorMessage.updateFromUIDL(errorUidl);
} else if( errorIndicatorElement != null) {
} else if (errorIndicatorElement != null) {
DOM.setStyleAttribute(errorIndicatorElement, "display", "none");
}
if(uidl.hasAttribute("description")) {
if (uidl.hasAttribute("description")) {
setTitle(uidl.getStringAttribute("description"));
}

}
public void onBrowserEvent(Event event) {
Element target= DOM.eventGetTarget(event);
if(errorIndicatorElement != null && DOM.compare(target, errorIndicatorElement)) {
Element target = DOM.eventGetTarget(event);
if (errorIndicatorElement != null
&& DOM.compare(target, errorIndicatorElement)) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEOVER:
showErrorMessage();
@@ -86,8 +87,8 @@ public class IButton extends Button implements Paintable {
hideErrorMessage();
break;
case Event.ONCLICK:
ApplicationConnection.getConsole().
log(DOM.getInnerHTML(errorMessage.getElement()));
ApplicationConnection.getConsole().log(
DOM.getInnerHTML(errorMessage.getElement()));
return;
default:
break;
@@ -97,25 +98,28 @@ public class IButton extends Button implements Paintable {
}

private void hideErrorMessage() {
if(errorContainer != null) {
if (errorContainer != null) {
errorContainer.hide();
}
}

private void showErrorMessage() {
if(errorMessage != null) {
if(errorContainer == null) {
if (errorMessage != null) {
if (errorContainer == null) {
errorContainer = new PopupPanel();
errorContainer.setWidget(errorMessage);
}
errorContainer.setPopupPosition(
DOM.getAbsoluteLeft(errorIndicatorElement) +
2*DOM.getElementPropertyInt(errorIndicatorElement, "offsetHeight"),
DOM.getAbsoluteTop(errorIndicatorElement) +
2*DOM.getElementPropertyInt(errorIndicatorElement, "offsetHeight"));
errorContainer.setPopupPosition(DOM
.getAbsoluteLeft(errorIndicatorElement)
+ 2
* DOM.getElementPropertyInt(errorIndicatorElement,
"offsetHeight"), DOM
.getAbsoluteTop(errorIndicatorElement)
+ 2
* DOM.getElementPropertyInt(errorIndicatorElement,
"offsetHeight"));
errorContainer.show();
}
}


}

+ 149
- 149
src/com/itmill/toolkit/terminal/gwt/client/ui/ICalendar.java View File

@@ -17,170 +17,170 @@ import com.itmill.toolkit.terminal.gwt.client.UIDL;
public class ICalendar extends IDateField {
private CalendarPanel calPanel;
private HTMLTable hourTable;
private EntrySource entrySource;
private TableListener ftListener = new HourTableListener();
private int realResolution = RESOLUTION_DAY;
private static final String CLASSNAME = IDateField.CLASSNAME
+ "-entrycalendar";
public ICalendar() {
super();
setStyleName(CLASSNAME);
calPanel = new CalendarPanel(this);
add(calPanel);
this.entrySource = new EntrySource();
calPanel.setCalendarEntrySource(this.entrySource);
calPanel.addTableListener(new TableListener() {
public void onCellClicked(SourcesTableEvents sender, int row,
int cell) {
buildDayView(date);
}
});
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
super.updateFromUIDL(uidl, client);
// We want to draw our own hour list
this.realResolution = currentResolution;
this.currentResolution = RESOLUTION_DAY;
if (uidl.hasAttribute("min")) {
String mins = uidl.getStringAttribute("min");
long min = (mins != null ? Long.parseLong(mins) : 0);
String maxs = uidl.getStringAttribute("max");
long max = (maxs != null ? Long.parseLong(maxs) : 0);
Date minDate = (min > 0 ? new Date(min) : null);
Date maxDate = (max > 0 ? new Date(max) : null);
calPanel.setLimits(minDate, maxDate);
private CalendarPanel calPanel;
private HTMLTable hourTable;
private EntrySource entrySource;
private TableListener ftListener = new HourTableListener();
private int realResolution = RESOLUTION_DAY;
private static final String CLASSNAME = IDateField.CLASSNAME
+ "-entrycalendar";
public ICalendar() {
super();
setStyleName(CLASSNAME);
calPanel = new CalendarPanel(this);
add(calPanel);
this.entrySource = new EntrySource();
calPanel.setCalendarEntrySource(this.entrySource);
calPanel.addTableListener(new TableListener() {
public void onCellClicked(SourcesTableEvents sender, int row,
int cell) {
buildDayView(date);
}
});
}
this.entrySource.clear();
for (Iterator cit = uidl.getChildIterator(); cit.hasNext();) {
UIDL child = (UIDL) cit.next();
if (child.getTag().equals("items")) {
for (Iterator iit = child.getChildIterator(); iit.hasNext();) {
UIDL item = (UIDL) iit.next();
this.entrySource.addItem(item);
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
super.updateFromUIDL(uidl, client);
// We want to draw our own hour list
this.realResolution = currentResolution;
this.currentResolution = RESOLUTION_DAY;
if (uidl.hasAttribute("min")) {
String mins = uidl.getStringAttribute("min");
long min = (mins != null ? Long.parseLong(mins) : 0);
String maxs = uidl.getStringAttribute("max");
long max = (maxs != null ? Long.parseLong(maxs) : 0);
Date minDate = (min > 0 ? new Date(min) : null);
Date maxDate = (max > 0 ? new Date(max) : null);
calPanel.setLimits(minDate, maxDate);
}
break;
}
}
calPanel.updateCalendar();
buildDayView(this.date);
}
protected void buildDayView(Date date) {
boolean firstRender = false;
if (this.hourTable == null) {
hourTable = new FlexTable();
firstRender = true;
hourTable.addTableListener(this.ftListener);
SimplePanel p = new SimplePanel();
p.add(hourTable);
p.setStyleName(CLASSNAME + "-hours");
this.calPanel.getFlexCellFormatter().setColSpan(8, 0, 7);
this.calPanel.setWidget(8, 0, p);
}
Date curr = new Date(date.getTime());
for (int i = 0; i < 24; i++) {
curr.setHours(i);
String style = (i % 2 == 0 ? "even" : "odd");
if (realResolution >= RESOLUTION_HOUR) {
if (this.date != null && this.date.getHours() == i) {
style = "selected";
this.entrySource.clear();
for (Iterator cit = uidl.getChildIterator(); cit.hasNext();) {
UIDL child = (UIDL) cit.next();
if (child.getTag().equals("items")) {
for (Iterator iit = child.getChildIterator(); iit.hasNext();) {
UIDL item = (UIDL) iit.next();
this.entrySource.addItem(item);
}
break;
}
}
}
hourTable.getRowFormatter().setStyleName(i,
CLASSNAME + "-row-" + style);
if (firstRender) {
String hstr = (i < 10 ? "0" : "") + i + ":00";
if (this.dts.isTwelveHourClock()) {
String ampm = (i < 12 ? "am" : "pm");
hstr = (i <= 12 ? i : i - 12) + ":00 " + ampm;
calPanel.updateCalendar();
buildDayView(this.date);
}
protected void buildDayView(Date date) {
boolean firstRender = false;
if (this.hourTable == null) {
hourTable = new FlexTable();
firstRender = true;
hourTable.addTableListener(this.ftListener);
SimplePanel p = new SimplePanel();
p.add(hourTable);
p.setStyleName(CLASSNAME + "-hours");
this.calPanel.getFlexCellFormatter().setColSpan(8, 0, 7);
this.calPanel.setWidget(8, 0, p);
}
hourTable.setHTML(i, 0, "<span>" + hstr + "</span>");
hourTable.getCellFormatter().setStyleName(i, 0,
CLASSNAME + "-time");
}
List entries = this.entrySource.getEntries(curr,
DateTimeService.RESOLUTION_HOUR);
String text = "";
if (entries != null) {
for (Iterator it = entries.iterator(); it.hasNext();) {
CalendarEntry entry = (CalendarEntry) it.next();
String title = entry.getTitle();
String desc = entry.getDescription();
text += (text == "" ? "" : ", ");
String e = "<span"
+ (desc != null ? " title=\"" + desc + "\"" : "")
+ ">";
e += (title != null ? title : "?");
e += "</span>";
text += e;
Date curr = new Date(date.getTime());
for (int i = 0; i < 24; i++) {
curr.setHours(i);
String style = (i % 2 == 0 ? "even" : "odd");
if (realResolution >= RESOLUTION_HOUR) {
if (this.date != null && this.date.getHours() == i) {
style = "selected";
}
}
hourTable.getRowFormatter().setStyleName(i,
CLASSNAME + "-row-" + style);
if (firstRender) {
String hstr = (i < 10 ? "0" : "") + i + ":00";
if (this.dts.isTwelveHourClock()) {
String ampm = (i < 12 ? "am" : "pm");
hstr = (i <= 12 ? i : i - 12) + ":00 " + ampm;
}
hourTable.setHTML(i, 0, "<span>" + hstr + "</span>");
hourTable.getCellFormatter().setStyleName(i, 0,
CLASSNAME + "-time");
}
List entries = this.entrySource.getEntries(curr,
DateTimeService.RESOLUTION_HOUR);
String text = "";
if (entries != null) {
for (Iterator it = entries.iterator(); it.hasNext();) {
CalendarEntry entry = (CalendarEntry) it.next();
String title = entry.getTitle();
String desc = entry.getDescription();
text += (text == "" ? "" : ", ");
String e = "<span"
+ (desc != null ? " title=\"" + desc + "\"" : "")
+ ">";
e += (title != null ? title : "?");
e += "</span>";
text += e;
}
}
hourTable.setHTML(i, 1, text);
hourTable.getCellFormatter().setStyleName(i, 1,
CLASSNAME + "-title");
}
}
hourTable.setHTML(i, 1, text);
hourTable.getCellFormatter().setStyleName(i, 1,
CLASSNAME + "-title");
}
}
private class HourTableListener implements TableListener {
private class HourTableListener implements TableListener {
public void onCellClicked(SourcesTableEvents sender, int row, int cell) {
if (realResolution < RESOLUTION_HOUR || date == null) {
return;
}
date.setHours(row);
client.updateVariable(id, "hour", row, immediate);
}
public void onCellClicked(SourcesTableEvents sender, int row, int cell) {
if (realResolution < RESOLUTION_HOUR || date == null) {
return;
}
date.setHours(row);
client.updateVariable(id, "hour", row, immediate);
}
}
private class EntrySource implements CalendarPanel.CalendarEntrySource {
private HashMap items = new HashMap();
public void addItem(UIDL item) {
Integer id = new Integer(item.getIntAttribute("id"));
long start = Long.parseLong(item.getStringAttribute("start"));
Date startDate = new Date(start);
long end = Long.parseLong(item.getStringAttribute("end"));
Date endDate = (end > 0 && end != start ? new Date(end) : new Date(
start));
String title = item.getStringAttribute("title");
String desc = item.getStringAttribute("description");
boolean notime = item.getBooleanAttribute("notime");
if (items.containsKey(id)) {
items.remove(id);
}
items.put(id, new CalendarEntry(startDate, endDate, title, desc,
notime));
}
private class EntrySource implements CalendarPanel.CalendarEntrySource {
private HashMap items = new HashMap();
public void addItem(UIDL item) {
Integer id = new Integer(item.getIntAttribute("id"));
long start = Long.parseLong(item.getStringAttribute("start"));
Date startDate = new Date(start);
long end = Long.parseLong(item.getStringAttribute("end"));
Date endDate = (end > 0 && end != start ? new Date(end) : new Date(
start));
String title = item.getStringAttribute("title");
String desc = item.getStringAttribute("description");
boolean notime = item.getBooleanAttribute("notime");
if (items.containsKey(id)) {
items.remove(id);
}
items.put(id, new CalendarEntry(startDate, endDate, title, desc,
notime));
}
public List getEntries(Date date, int resolution) {
ArrayList res = new ArrayList();
for (Iterator it = this.items.values().iterator(); it.hasNext();) {
CalendarEntry item = (CalendarEntry) it.next();
if (DateTimeService.isInRange(date, item.getStart(), item
.getEnd(), resolution)) {
res.add(item);
public List getEntries(Date date, int resolution) {
ArrayList res = new ArrayList();
for (Iterator it = this.items.values().iterator(); it.hasNext();) {
CalendarEntry item = (CalendarEntry) it.next();
if (DateTimeService.isInRange(date, item.getStart(), item
.getEnd(), resolution)) {
res.add(item);
}
}
return res;
}
}
return res;
}
public void clear() {
items.clear();
}
public void clear() {
items.clear();
}
}
}

+ 4
- 4
src/com/itmill/toolkit/terminal/gwt/client/ui/ICheckBox.java View File

@@ -6,9 +6,9 @@ import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;

public class ICheckBox extends com.google.gwt.user.client.ui.CheckBox
implements Paintable {
public class ICheckBox extends com.google.gwt.user.client.ui.CheckBox implements
Paintable {
public static final String CLASSNAME = "i-checkbox";

String id;
@@ -31,7 +31,7 @@ public class ICheckBox extends com.google.gwt.user.client.ui.CheckBox
}

public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
// Ensure correct implementation
if (client.updateComponent(this, uidl, false))
return;

+ 5
- 5
src/com/itmill/toolkit/terminal/gwt/client/ui/ICustomComponent.java View File

@@ -7,7 +7,7 @@ import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;

public class ICustomComponent extends SimplePanel implements Paintable {
private static final String CLASSNAME = "i-customcomponent";

public ICustomComponent() {
@@ -16,12 +16,12 @@ public class ICustomComponent extends SimplePanel implements Paintable {
}

public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
UIDL child = uidl.getChildUIDL(0);
if(child != null) {
if (child != null) {
Paintable p = (Paintable) client.getWidget(child);
if(p != getWidget()) {
if(getWidget() != null) {
if (p != getWidget()) {
if (getWidget() != null) {
client.unregisterPaintable((Paintable) getWidget());
clear();
}

+ 27
- 19
src/com/itmill/toolkit/terminal/gwt/client/ui/ICustomLayout.java View File

@@ -47,12 +47,14 @@ public class ICustomLayout extends ComplexPanel implements Paintable, Container
}

/**
* Sets widget to given location.
* Sets widget to given location.
*
* If location already contains a widget it will be removed.
*
* @param widget Widget to be set into location.
* @param location location name where widget will be added
* @param widget
* Widget to be set into location.
* @param location
* location name where widget will be added
*
* @throws IllegalArgumentException
* if no such location is found in the layout.
@@ -75,9 +77,9 @@ public class ICustomLayout extends ComplexPanel implements Paintable, Container
if (previous == widget)
return;
remove(previous);
// if template is missing add element in order
if(!hasTemplate())
if (!hasTemplate())
elem = getElement();

// Add widget to location
@@ -94,7 +96,7 @@ public class ICustomLayout extends ComplexPanel implements Paintable, Container

// Update PID
pid = uidl.getId();
if(!hasTemplate()) {
if (!hasTemplate()) {
// Update HTML template only once
initializeHTML(uidl, client);
}
@@ -114,7 +116,7 @@ public class ICustomLayout extends ComplexPanel implements Paintable, Container
}
}
}
// Evaluate scripts only once
if (scripts != null) {
eval(scripts);
@@ -128,9 +130,12 @@ public class ICustomLayout extends ComplexPanel implements Paintable, Container
String newTemplate = uidl.getStringAttribute("template");

// Get the HTML-template from client
String template = client.getResource("layouts/" + newTemplate + ".html");
String template = client
.getResource("layouts/" + newTemplate + ".html");
if (template == null) {
template = "<em>Layout file layouts/" + newTemplate + ".html is missing. Components will be drawn for debug purposes.</em>";
template = "<em>Layout file layouts/"
+ newTemplate
+ ".html is missing. Components will be drawn for debug purposes.</em>";
} else {
currentTemplate = newTemplate;
}
@@ -148,15 +153,16 @@ public class ICustomLayout extends ComplexPanel implements Paintable, Container
while (parent != null && !(parent instanceof IView))
parent = parent.getParent();
if (parent != null && ((IView) parent).getTheme() != null) {
prefixImgSrcs(getElement(), "../ITK-INF/themes/" + ((IView) parent).getTheme()
+ "/layouts/");
prefixImgSrcs(getElement(), "../ITK-INF/themes/"
+ ((IView) parent).getTheme() + "/layouts/");
} else {
throw(new IllegalStateException("Could not find IView; maybe updateFromUIDL() was called before attaching the widget?"));
throw (new IllegalStateException(
"Could not find IView; maybe updateFromUIDL() was called before attaching the widget?"));
}
}
private boolean hasTemplate() {
if(currentTemplate == null)
if (currentTemplate == null)
return false;
else
return true;
@@ -267,14 +273,15 @@ public class ICustomLayout extends ComplexPanel implements Paintable, Container
setWidget(to, location);
}

/** Does this layout contain given child*/
/** Does this layout contain given child */
public boolean hasChildComponent(Widget component) {
return locationToWidget.containsValue(component);
}

/** Update caption for given widget */
public void updateCaption(Paintable component, UIDL uidl) {
CaptionWrapper wrapper = (CaptionWrapper) widgetToCaptionWrapper.get(component);
CaptionWrapper wrapper = (CaptionWrapper) widgetToCaptionWrapper
.get(component);
if (Caption.isNeeded(uidl)) {
if (wrapper == null) {
String loc = getLocation((Widget) component);
@@ -285,10 +292,11 @@ public class ICustomLayout extends ComplexPanel implements Paintable, Container
}
wrapper.updateCaption(uidl);
} else {
if (wrapper != null) {
if (wrapper != null) {
String loc = getLocation((Widget) component);
super.remove(wrapper);
super.add((Widget) wrapper.getPaintable(), (Element) locationToElement.get(loc));
super.add((Widget) wrapper.getPaintable(),
(Element) locationToElement.get(loc));
widgetToCaptionWrapper.remove(component);
}
}
@@ -314,7 +322,7 @@ public class ICustomLayout extends ComplexPanel implements Paintable, Container
if (cw != null) {
widgetToCaptionWrapper.remove(w);
return super.remove(cw);
} else if(w != null)
} else if (w != null)
return super.remove(w);
return false;
}

+ 61
- 51
src/com/itmill/toolkit/terminal/gwt/client/ui/IDateField.java View File

@@ -12,13 +12,13 @@ import com.itmill.toolkit.terminal.gwt.client.UIDL;
public class IDateField extends FlowPanel implements Paintable {
public static final String CLASSNAME = "i-datefield";
String id;
ApplicationConnection client;
protected boolean immediate;
public static int RESOLUTION_YEAR = 0;
public static int RESOLUTION_MONTH = 1;
public static int RESOLUTION_DAY = 2;
@@ -26,24 +26,24 @@ public class IDateField extends FlowPanel implements Paintable {
public static int RESOLUTION_MIN = 4;
public static int RESOLUTION_SEC = 5;
public static int RESOLUTION_MSEC = 6;
protected int currentResolution = RESOLUTION_YEAR;
protected String currentLocale;
protected boolean readonly;
protected boolean enabled;
protected Date date = null;
protected DateTimeService dts;
public IDateField() {
setStyleName(CLASSNAME);
dts = new DateTimeService();
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
// Ensure correct implementation and let layout manage caption
if (client.updateComponent(this, uidl, true))
@@ -53,11 +53,11 @@ public class IDateField extends FlowPanel implements Paintable {
this.client = client;
this.id = uidl.getId();
this.immediate = uidl.getBooleanAttribute("immediate");
readonly = uidl.getBooleanAttribute("readonly");
enabled = !uidl.getBooleanAttribute("disabled");
if(uidl.hasAttribute("locale")) {
if (uidl.hasAttribute("locale")) {
String locale = uidl.getStringAttribute("locale");
try {
dts.setLocale(locale);
@@ -65,47 +65,57 @@ public class IDateField extends FlowPanel implements Paintable {
} catch (LocaleNotLoadedException e) {
currentLocale = dts.getLocale();
// TODO redirect this to console
System.out.println("Tried to use an unloaded locale \"" + locale + "\". Using default locale (" + currentLocale + ").");
System.out.println("Tried to use an unloaded locale \""
+ locale + "\". Using default locale (" + currentLocale
+ ").");
}
}
int newResolution;
if(uidl.hasVariable("msec"))
if (uidl.hasVariable("msec"))
newResolution = RESOLUTION_MSEC;
else if(uidl.hasVariable("sec"))
else if (uidl.hasVariable("sec"))
newResolution = RESOLUTION_SEC;
else if(uidl.hasVariable("min"))
else if (uidl.hasVariable("min"))
newResolution = RESOLUTION_MIN;
else if(uidl.hasVariable("hour"))
else if (uidl.hasVariable("hour"))
newResolution = RESOLUTION_HOUR;
else if(uidl.hasVariable("day"))
else if (uidl.hasVariable("day"))
newResolution = RESOLUTION_DAY;
else if(uidl.hasVariable("month"))
else if (uidl.hasVariable("month"))
newResolution = RESOLUTION_MONTH;
else
newResolution = RESOLUTION_YEAR;
currentResolution = newResolution;
int year = uidl.getIntVariable("year");
int month = (currentResolution >= RESOLUTION_MONTH)? uidl.getIntVariable("month") : -1;
int day = (currentResolution >= RESOLUTION_DAY)? uidl.getIntVariable("day") : -1;
int hour = (currentResolution >= RESOLUTION_HOUR)? uidl.getIntVariable("hour") : -1;
int min = (currentResolution >= RESOLUTION_MIN)? uidl.getIntVariable("min") : -1;
int sec = (currentResolution >= RESOLUTION_SEC)? uidl.getIntVariable("sec") : -1;
int msec = (currentResolution >= RESOLUTION_MSEC)? uidl.getIntVariable("msec") : -1;
int month = (currentResolution >= RESOLUTION_MONTH) ? uidl
.getIntVariable("month") : -1;
int day = (currentResolution >= RESOLUTION_DAY) ? uidl
.getIntVariable("day") : -1;
int hour = (currentResolution >= RESOLUTION_HOUR) ? uidl
.getIntVariable("hour") : -1;
int min = (currentResolution >= RESOLUTION_MIN) ? uidl
.getIntVariable("min") : -1;
int sec = (currentResolution >= RESOLUTION_SEC) ? uidl
.getIntVariable("sec") : -1;
int msec = (currentResolution >= RESOLUTION_MSEC) ? uidl
.getIntVariable("msec") : -1;
// Construct new date for this datefield (only if not null)
if(year > -1)
date = new Date((long) getTime(year, month, day, hour, min, sec, msec));
if (year > -1)
date = new Date((long) getTime(year, month, day, hour, min, sec,
msec));
}
/*
* We need this redundant native function because
* Java's Date object doesn't have a setMilliseconds method.
* We need this redundant native function because Java's Date object doesn't
* have a setMilliseconds method.
*/
private static native double getTime(int y, int m, int d, int h, int mi, int s, int ms) /*-{
private static native double getTime(int y, int m, int d, int h, int mi,
int s, int ms) /*-{
try {
var date = new Date();
if(y && y >= 0) date.setFullYear(y);
@@ -122,7 +132,7 @@ public class IDateField extends FlowPanel implements Paintable {
return (new Date()).getTime();
}
}-*/;
public int getMilliseconds() {
return (int) (date.getTime() - date.getTime() / 1000 * 1000);
}
@@ -132,50 +142,50 @@ public class IDateField extends FlowPanel implements Paintable {
}
public int getCurrentResolution() {
return currentResolution;
return currentResolution;
}
public void setCurrentResolution(int currentResolution) {
this.currentResolution = currentResolution;
this.currentResolution = currentResolution;
}
public String getCurrentLocale() {
return currentLocale;
return currentLocale;
}
public void setCurrentLocale(String currentLocale) {
this.currentLocale = currentLocale;
this.currentLocale = currentLocale;
}
public Date getCurrentDate() {
return date;
return date;
}
public void setCurrentDate(Date date) {
this.date = date;
this.date = date;
}
public boolean isImmediate() {
return immediate;
return immediate;
}
public boolean isReadonly() {
return readonly;
return readonly;
}
public boolean isEnabled() {
return enabled;
return enabled;
}
public DateTimeService getDateTimeService() {
return dts;
return dts;
}
public String getId() {
return id;
return id;
}
public ApplicationConnection getClient() {
return client;
return client;
}
}

+ 4
- 4
src/com/itmill/toolkit/terminal/gwt/client/ui/IDateFieldCalendar.java View File

@@ -4,16 +4,16 @@ import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
public class IDateFieldCalendar extends IDateField {
private CalendarPanel date;
public IDateFieldCalendar() {
super();
setStyleName(CLASSNAME+"-calendar");
setStyleName(CLASSNAME + "-calendar");
date = new CalendarPanel(this);
add(date);
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
super.updateFromUIDL(uidl, client);
date.updateCalendar();

+ 18
- 13
src/com/itmill/toolkit/terminal/gwt/client/ui/IEmbedded.java View File

@@ -8,20 +8,25 @@ import com.itmill.toolkit.terminal.gwt.client.UIDL;
public class IEmbedded extends HTML implements Paintable {

public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
if(client.updateComponent(this, uidl, true))
if (client.updateComponent(this, uidl, true))
return;
if(uidl.hasAttribute("type") && uidl.getStringAttribute("type").equals("image")) {
setHTML("<img src=\""+ uidl.getStringAttribute("src") +"\"/>");
} else if(uidl.hasAttribute("mimetype") &&
uidl.getStringAttribute("mimetype").equals("application/x-shockwave-flash")) {
String w = uidl.hasAttribute("width") ? uidl.getStringAttribute("width") : "100";
String h = uidl.hasAttribute("height") ? uidl.getStringAttribute("height") : "100";
setHTML("<object width=\""+w+"\" height=\""+h+"\"><param name=\"movie\" value=\""+
uidl.getStringAttribute("src") + "\"><embed src=\""+
uidl.getStringAttribute("src") + "\" width=\""+ w +
"\" height=\""+h+"\"></embed></object>");

if (uidl.hasAttribute("type")
&& uidl.getStringAttribute("type").equals("image")) {
setHTML("<img src=\"" + uidl.getStringAttribute("src") + "\"/>");
} else if (uidl.hasAttribute("mimetype")
&& uidl.getStringAttribute("mimetype").equals(
"application/x-shockwave-flash")) {
String w = uidl.hasAttribute("width") ? uidl
.getStringAttribute("width") : "100";
String h = uidl.hasAttribute("height") ? uidl
.getStringAttribute("height") : "100";

setHTML("<object width=\"" + w + "\" height=\"" + h
+ "\"><param name=\"movie\" value=\""
+ uidl.getStringAttribute("src") + "\"><embed src=\""
+ uidl.getStringAttribute("src") + "\" width=\"" + w
+ "\" height=\"" + h + "\"></embed></object>");
} else {
setText("Terminal don't know how ty handle this type of embed");
}

+ 6
- 3
src/com/itmill/toolkit/terminal/gwt/client/ui/IExpandLayout.java View File

@@ -130,8 +130,10 @@ public class IExpandLayout extends IOrderedLayout implements
Element expandedElement = DOM.getParent(expandedWidget.getElement());
// take expanded element temporarely out of flow to make container
// minimum sized
String origiginalPositioning = DOM.getStyleAttribute(expandedWidget.getElement(), "position");
DOM.setStyleAttribute(expandedWidget.getElement(), "position", "absolute");
String origiginalPositioning = DOM.getStyleAttribute(expandedWidget
.getElement(), "position");
DOM.setStyleAttribute(expandedWidget.getElement(), "position",
"absolute");
DOM.setStyleAttribute(expandedElement, "height", "");

// add temp element to make some measurements
@@ -150,7 +152,8 @@ public class IExpandLayout extends IOrderedLayout implements
// Component margins will bleed if overflow is not hidden
DOM.setStyleAttribute(expandedElement, "overflow", "hidden");

DOM.setStyleAttribute(expandedWidget.getElement(), "position", origiginalPositioning);
DOM.setStyleAttribute(expandedWidget.getElement(), "position",
origiginalPositioning);

DOM.removeChild(childContainer, meter);


+ 16
- 15
src/com/itmill/toolkit/terminal/gwt/client/ui/IFilterSelect.java View File

@@ -27,9 +27,8 @@ import com.itmill.toolkit.terminal.gwt.client.Util;

/**
*
* TODO needs major refactoring to be easily expandable
* TODO add new items
* TODO null selections
* TODO needs major refactoring to be easily expandable TODO add new items TODO
* null selections
*/
public class IFilterSelect extends Composite implements Paintable,
KeyboardListener, ClickListener {
@@ -164,7 +163,7 @@ public class IFilterSelect extends Composite implements Paintable,
if (index > -1)
menu.selectItem((MenuItem) menu.getItems().get(index));
else if (index == -1) {
if(currentPage > 0)
if (currentPage > 0)
filterOptions(currentPage - 1);
} else {
menu.selectItem((MenuItem) menu.getItems().get(
@@ -389,9 +388,9 @@ public class IFilterSelect extends Composite implements Paintable,
tb.setText(suggestion.getReplacementString());
currentSuggestion = suggestion;
}
// Collect captions so we can calculate minimum width for textarea
if(captions.length() > 0)
if (captions.length() > 0)
captions += "|";
captions += suggestion.getReplacementString();
}
@@ -401,23 +400,25 @@ public class IFilterSelect extends Composite implements Paintable,
totalSuggestions);
filtering = false;
}
// Calculate minumum textarea width
int minw = minWidth(captions);
if(Util.isIE()) {
if (Util.isIE()) {
Element spacer = DOM.createDiv();
DOM.setStyleAttribute(spacer, "width", minw+"px");
DOM.setStyleAttribute(spacer, "width", minw + "px");
DOM.setStyleAttribute(spacer, "height", "0");
DOM.setStyleAttribute(spacer, "overflow", "hidden");
DOM.appendChild(panel.getElement(), spacer);
} else {
DOM.setStyleAttribute(tb.getElement(), "minWidth", minw+"px");
DOM.setStyleAttribute(tb.getElement(), "minWidth", minw + "px");
}
// Set columns (width) is given
if(uidl.hasAttribute("cols"))
DOM.setStyleAttribute(getElement(), "width", uidl.getIntAttribute("cols")+"em");
if (uidl.hasAttribute("cols"))
DOM.setStyleAttribute(getElement(), "width", uidl
.getIntAttribute("cols")
+ "em");

}

public void onSuggestionSelected(FilterSelectSuggestion suggestion) {
@@ -504,7 +505,7 @@ public class IFilterSelect extends Composite implements Paintable,
tb.setFocus(true);
tb.selectAll();
}
/*
* Calculate minumum width for FilterSelect textarea
*/

+ 6
- 7
src/com/itmill/toolkit/terminal/gwt/client/ui/IForm.java View File

@@ -8,26 +8,25 @@ import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
public class IForm extends SimplePanel implements Paintable {
public static final String CLASSNAME = "i-form";
private Container lo;
private Container lo;
private ApplicationConnection client;
public IForm() {
super();
setStyleName(CLASSNAME);
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
this.client = client;
UIDL layoutUidl = uidl.getChildUIDL(0);
if(lo == null) {
if (lo == null) {
lo = (Container) client.getWidget(layoutUidl);
setWidget((Widget) lo);
}
lo.updateFromUIDL(layoutUidl, client);
}
}

+ 15
- 15
src/com/itmill/toolkit/terminal/gwt/client/ui/IFormLayout.java View File

@@ -15,35 +15,35 @@ import com.itmill.toolkit.terminal.gwt.client.UIDL;
* Two col Layout that places caption on left col and field on right col
*/
public class IFormLayout extends FlexTable implements Container {
HashMap componentToCaption = new HashMap();
private ApplicationConnection client;
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
this.client = client;
int i = 0;
for(Iterator it = uidl.getChildIterator();it.hasNext();i++) {
for (Iterator it = uidl.getChildIterator(); it.hasNext(); i++) {
prepareCell(i, 1);
UIDL childUidl = (UIDL) it.next();
Paintable p = (Paintable) client.getWidget(childUidl);
Caption c = (Caption) componentToCaption.get(p);
if(c == null) {
if (c == null) {
c = new Caption(p);
componentToCaption.put(p, c);
}
Paintable oldComponent = (Paintable) getWidget(i, 1);
if(oldComponent == null) {
setWidget(i,1,(Widget) p);
if (oldComponent == null) {
setWidget(i, 1, (Widget) p);
} else if (oldComponent != p) {
client.unregisterPaintable(oldComponent);
setWidget(i,1,(Widget) p);
setWidget(i, 1, (Widget) p);
}
setWidget(i,0,c);
setWidget(i, 0, c);
p.updateFromUIDL(childUidl, client);
}
i++;
while(getRowCount() > i) {
Paintable p = (Paintable) getWidget(i,1);
while (getRowCount() > i) {
Paintable p = (Paintable) getWidget(i, 1);
client.unregisterPaintable(p);
componentToCaption.remove(p);
removeRow(i);
@@ -56,11 +56,11 @@ public class IFormLayout extends FlexTable implements Container {

public void replaceChildComponent(Widget oldComponent, Widget newComponent) {
int i;
for(i = 0; i < getRowCount(); i++) {
if(oldComponent == getWidget(i, 1)) {
for (i = 0; i < getRowCount(); i++) {
if (oldComponent == getWidget(i, 1)) {
Caption newCap = new Caption((Paintable) newComponent);
setWidget(i,0,newCap);
setWidget(i,1,newComponent);
setWidget(i, 0, newCap);
setWidget(i, 1, newComponent);
client.unregisterPaintable((Paintable) oldComponent);
break;
}
@@ -69,7 +69,7 @@ public class IFormLayout extends FlexTable implements Container {

public void updateCaption(Paintable component, UIDL uidl) {
Caption c = (Caption) componentToCaption.get(component);
if(c != null)
if (c != null)
c.updateCaption(uidl);
}
}

+ 17
- 18
src/com/itmill/toolkit/terminal/gwt/client/ui/IGridLayout.java View File

@@ -13,11 +13,10 @@ import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;

public class IGridLayout extends FlexTable implements Paintable, Container {
/** Widget to captionwrapper map */
private HashMap widgetToCaptionWrapper = new HashMap();


public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
clear();
if (uidl.hasAttribute("caption"))
@@ -25,7 +24,7 @@ public class IGridLayout extends FlexTable implements Paintable, Container {
int row = 0, column = 0;

ArrayList detachdedPaintables = new ArrayList();
for (Iterator i = uidl.getChildIterator(); i.hasNext();) {
UIDL r = (UIDL) i.next();
if ("gr".equals(r.getTag())) {
@@ -38,58 +37,58 @@ public class IGridLayout extends FlexTable implements Paintable, Container {
int w;
if (c.hasAttribute("w")) {
w = c.getIntAttribute("w");
}
else
} else
w = 1;
((FlexCellFormatter) getCellFormatter())
.setColSpan(row, column, w);
((FlexCellFormatter) getCellFormatter()).setColSpan(
row, column, w);

UIDL u = c.getChildUIDL(0);
if (u != null) {
Widget child = client.getWidget(u);
prepareCell(row, column);
Widget oldChild = getWidget(row, column);
if(child != oldChild) {
if(oldChild != null) {
if (child != oldChild) {
if (oldChild != null) {
CaptionWrapper cw = (CaptionWrapper) oldChild;
detachdedPaintables.add(cw.getPaintable());
widgetToCaptionWrapper.remove(oldChild);
}
CaptionWrapper wrapper = new CaptionWrapper((Paintable) child);
CaptionWrapper wrapper = new CaptionWrapper(
(Paintable) child);
setWidget(row, column, wrapper);
widgetToCaptionWrapper.put(child, wrapper);
}
((Paintable) child).updateFromUIDL(u, client);
}
column += w -1;
column += w - 1;
}
}
}
}
// for loop detached widgets and unregister them unless they are
// attached (case of widget which is moved to another cell)
for(Iterator it = detachdedPaintables.iterator();it.hasNext();) {
for (Iterator it = detachdedPaintables.iterator(); it.hasNext();) {
Widget w = (Widget) it.next();
if(!w.isAttached())
if (!w.isAttached())
client.unregisterPaintable((Paintable) w);
}
}

public boolean hasChildComponent(Widget component) {
if(widgetToCaptionWrapper.containsKey(component))
if (widgetToCaptionWrapper.containsKey(component))
return true;
return false;
}

public void replaceChildComponent(Widget oldComponent, Widget newComponent) {
// TODO Auto-generated method stub
}

public void updateCaption(Paintable component, UIDL uidl) {
CaptionWrapper wrapper = (CaptionWrapper) widgetToCaptionWrapper.get(component);
CaptionWrapper wrapper = (CaptionWrapper) widgetToCaptionWrapper
.get(component);
wrapper.updateCaption(uidl);
}


+ 3
- 3
src/com/itmill/toolkit/terminal/gwt/client/ui/ILabel.java View File

@@ -6,14 +6,14 @@ import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;

public class ILabel extends HTML implements Paintable {
public static final String CLASSNAME = "i-label";
public ILabel() {
super();
setStyleName(CLASSNAME);
}
public ILabel(String text) {
super(text);
setStyleName(CLASSNAME);

+ 29
- 28
src/com/itmill/toolkit/terminal/gwt/client/ui/ILink.java View File

@@ -10,19 +10,19 @@ import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;

public class ILink extends HTML implements Paintable, ClickListener {
public static final String CLASSNAME = "i-link";
private static final int BORDER_STYLE_DEFAULT = 0;
private static final int BORDER_STYLE_MINIMAL = 1;
private static final int BORDER_STYLE_NONE = 2;
private String src;
private String target;
private int borderStyle = BORDER_STYLE_DEFAULT;
private boolean enabled;

private boolean readonly;
@@ -30,52 +30,53 @@ public class ILink extends HTML implements Paintable, ClickListener {
private int width;

private int height;
public ILink() {
super();
addClickListener(this);
setStyleName(CLASSNAME);
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {

enabled = uidl.hasAttribute("disabled") ? false : true;
readonly = uidl.hasAttribute("readonly") ? true : false;
if(uidl.hasAttribute("target"))
if (uidl.hasAttribute("target"))
target = uidl.getStringAttribute(target);
if(uidl.hasAttribute("src")) {
//TODO theme soure
if (uidl.hasAttribute("src")) {
// TODO theme soure
src = uidl.getStringAttribute("src");
}
if(uidl.hasAttribute("border")) {
if("none".equals(uidl.getStringAttribute("border")))
if (uidl.hasAttribute("border")) {
if ("none".equals(uidl.getStringAttribute("border")))
borderStyle = BORDER_STYLE_NONE;
else
borderStyle = BORDER_STYLE_MINIMAL;
} else {
borderStyle = BORDER_STYLE_DEFAULT;
}
height = uidl.hasAttribute("height") ? uidl.getIntAttribute("height") : -1;

height = uidl.hasAttribute("height") ? uidl.getIntAttribute("height")
: -1;
width = uidl.hasAttribute("width") ? uidl.getIntAttribute("width") : -1;
DOM.setInnerHTML(getElement(), uidl.getStringAttribute("caption"));
if(readonly)
if (readonly)
addStyleName("readonly");
else
removeStyleName("readonly");
if(enabled)
if (enabled)
addStyleName("enabled");
else
removeStyleName("enabled");
}

public void onClick(Widget sender) {
if(enabled && !readonly) {
if(target == null)
if (enabled && !readonly) {
if (target == null)
target = "_blank";
String features;
switch (borderStyle) {
@@ -89,17 +90,17 @@ public class ILink extends HTML implements Paintable, ClickListener {
features = "menubar=yes,location=yes,scrollbars=yes,status=yes";
break;
}
if(width > 0 || height > 0) {
if (width > 0 || height > 0) {
features += ",resizable=no";
if(width > 0)
if (width > 0)
features += ",width=" + width;
if(height > 0)
if (height > 0)
features += ",height=" + height;
} else {
features += ",resizable=yes";
features += ",resizable=yes";
}
Window.open(src, target, features);
}
}
}

+ 20
- 14
src/com/itmill/toolkit/terminal/gwt/client/ui/IOptionGroup.java View File

@@ -11,28 +11,28 @@ import com.google.gwt.user.client.ui.Widget;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
public class IOptionGroup extends IOptionGroupBase {
public static final String CLASSNAME = "i-select-optiongroup";
private Panel panel;
private Map optionsToKeys;
public IOptionGroup() {
super(CLASSNAME);
panel = (Panel) optionsContainer;
optionsToKeys = new HashMap();
}
/*
* Return true if no elements were changed, false otherwise.
*/
protected void buildOptions(UIDL uidl) {
panel.clear();
for(Iterator it = uidl.getChildIterator(); it.hasNext();) {
for (Iterator it = uidl.getChildIterator(); it.hasNext();) {
UIDL opUidl = (UIDL) it.next();
CheckBox op;
if(multiselect) {
if (multiselect) {
op = new ICheckBox();
op.setText(opUidl.getStringAttribute("caption"));
} else {
@@ -41,7 +41,8 @@ public class IOptionGroup extends IOptionGroupBase {
}
op.addStyleName(CLASSNAME_OPTION);
op.setChecked(opUidl.getBooleanAttribute("selected"));
op.setEnabled(!opUidl.getBooleanAttribute("disabled") && !readonly && !disabled);
op.setEnabled(!opUidl.getBooleanAttribute("disabled") && !readonly
&& !disabled);
op.addClickListener(this);
optionsToKeys.put(op, opUidl.getStringAttribute("key"));
panel.add(op);
@@ -51,16 +52,21 @@ public class IOptionGroup extends IOptionGroupBase {
protected Object[] getSelectedItems() {
return selectedKeys.toArray();
}
public void onClick(Widget sender) {
super.onClick(sender);
if(sender instanceof CheckBox) {
if (sender instanceof CheckBox) {
boolean selected = ((CheckBox) sender).isChecked();
String key = (String) optionsToKeys.get(sender);
if(!multiselect) selectedKeys.clear();
if(selected) selectedKeys.add(key);
else selectedKeys.remove(key);
client.updateVariable(id, "selected", getSelectedItems(), immediate);
if (!multiselect)
selectedKeys.clear();
if (selected)
selectedKeys.add(key);
else
selectedKeys.remove(key);
client
.updateVariable(id, "selected", getSelectedItems(),
immediate);
}
}

+ 50
- 46
src/com/itmill/toolkit/terminal/gwt/client/ui/IOptionGroupBase.java View File

@@ -13,40 +13,40 @@ import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
abstract class IOptionGroupBase extends Composite implements Paintable, ClickListener, ChangeListener, KeyboardListener {
abstract class IOptionGroupBase extends Composite implements Paintable,
ClickListener, ChangeListener, KeyboardListener {
public static final String CLASSNAME_OPTION = "i-select-option";
ApplicationConnection client;
String id;
protected boolean immediate;
protected Set selectedKeys;
protected boolean multiselect;
protected boolean disabled;
protected boolean readonly;
/**
* Widget holding the different options
* (e.g. ListBox or Panel for radio buttons)
* (optional, fallbacks to container Panel)
* Widget holding the different options (e.g. ListBox or Panel for radio
* buttons) (optional, fallbacks to container Panel)
*/
protected Widget optionsContainer;
/**
* Panel containing the component
*/
private Panel container;
private ITextField newItemField;
private IButton newItemButton;
public IOptionGroupBase(String classname) {
container = new FlowPanel();
initWidget(container);
@@ -55,36 +55,37 @@ abstract class IOptionGroupBase extends Composite implements Paintable, ClickLis
immediate = false;
multiselect = false;
}
/* Call this if you wish to specify your own container
* for the option elements (e.g. SELECT)
/*
* Call this if you wish to specify your own container for the option
* elements (e.g. SELECT)
*/
public IOptionGroupBase(Widget w, String classname) {
this(classname);
optionsContainer = w;
container.add(optionsContainer);
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
this.client = client;
this.id = uidl.getId();
if(client.updateComponent(this, uidl, true))
if (client.updateComponent(this, uidl, true))
return;
selectedKeys = uidl.getStringArrayVariableAsSet("selected");
readonly = uidl.getBooleanAttribute("readonly");
disabled = uidl.getBooleanAttribute("disabled");
multiselect = "multi".equals(uidl.getStringAttribute("selectmode"));
immediate = uidl.getBooleanAttribute("immediate");
UIDL ops = uidl.getChildUIDL(0);
buildOptions(ops);
if(uidl.getBooleanAttribute("allownewitem")) {
if(newItemField == null) {
if (uidl.getBooleanAttribute("allownewitem")) {
if (newItemField == null) {
newItemButton = new IButton();
newItemButton.setText("+");
newItemButton.addClickListener(this);
@@ -94,53 +95,56 @@ abstract class IOptionGroupBase extends Composite implements Paintable, ClickLis
}
newItemField.setEnabled(!disabled && !readonly);
newItemButton.setEnabled(!disabled && !readonly);
if(newItemField != null && newItemField.getParent() == container)
if (newItemField != null && newItemField.getParent() == container)
return;
container.add(newItemField);
container.add(newItemButton);
} else if(newItemField != null) {
} else if (newItemField != null) {
container.remove(newItemField);
container.remove(newItemButton);
}
}
public void onClick(Widget sender) {
if(sender == newItemButton && !newItemField.getText().equals("")) {
if (sender == newItemButton && !newItemField.getText().equals("")) {
client.updateVariable(id, "newitem", newItemField.getText(), true);
newItemField.setText("");
}
}
public void onChange(Widget sender) {
if(multiselect) {
client.updateVariable(id, "selected", getSelectedItems(), immediate);
if (multiselect) {
client
.updateVariable(id, "selected", getSelectedItems(),
immediate);
} else {
client.updateVariable(id, "selected", new String[] { "" + getSelectedItem()}, immediate);
client.updateVariable(id, "selected", new String[] { ""
+ getSelectedItem() }, immediate);
}
}
public void onKeyPress(Widget sender, char keyCode, int modifiers) {
if(sender == newItemField && keyCode==KeyboardListener.KEY_ENTER)
if (sender == newItemField && keyCode == KeyboardListener.KEY_ENTER)
newItemButton.click();
}
public void onKeyUp(Widget sender, char keyCode, int modifiers) {
// Ignore, subclasses may override
}
public void onKeyDown(Widget sender, char keyCode, int modifiers) {
// Ignore, subclasses may override
}
protected abstract void buildOptions(UIDL uidl);
protected abstract Object[] getSelectedItems();
protected Object getSelectedItem() {
Object[] sel = getSelectedItems();
if(sel.length > 0)
if (sel.length > 0)
return sel[0];
else
return null;

+ 52
- 47
src/com/itmill/toolkit/terminal/gwt/client/ui/IOrderedLayout.java View File

@@ -16,17 +16,18 @@ import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;

/**
* Abstract base class for ordered layouts.
* Use either vertical or horizontal subclass.
* Abstract base class for ordered layouts. Use either vertical or horizontal
* subclass.
*
* @author IT Mill Ltd
*/
public abstract class IOrderedLayout extends ComplexPanel implements Container {
public static final String CLASSNAME = "i-orderedlayout";

public static final int ORIENTATION_VERTICAL = 0;
public static final int ORIENTATION_HORIZONTAL = 1;
int orientationMode = ORIENTATION_VERTICAL;

protected HashMap componentToCaption = new HashMap();
@@ -34,8 +35,8 @@ public abstract class IOrderedLayout extends ComplexPanel implements Container {
protected ApplicationConnection client;

/**
* Contains reference to Element where Paintables are wrapped. For horizontal
* layout this is TR and for vertical DIV.
* Contains reference to Element where Paintables are wrapped. For
* horizontal layout this is TR and for vertical DIV.
*/
protected Element childContainer;

@@ -44,7 +45,7 @@ public abstract class IOrderedLayout extends ComplexPanel implements Container {
constructDOM();
setStyleName(CLASSNAME);
}
protected void constructDOM() {
switch (orientationMode) {
case ORIENTATION_HORIZONTAL:
@@ -62,11 +63,10 @@ public abstract class IOrderedLayout extends ComplexPanel implements Container {
}
}

public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
this.client = client;
// Ensure correct implementation
if (client.updateComponent(this, uidl, false))
return;
@@ -77,24 +77,24 @@ public abstract class IOrderedLayout extends ComplexPanel implements Container {
Widget child = client.getWidget(uidlForChild);
uidlWidgets.add(child);
}
ArrayList oldWidgets = getPaintables();
Iterator oldIt = oldWidgets.iterator();
Iterator newIt = uidlWidgets.iterator();
Iterator newUidl = uidl.getChildIterator();
Widget oldChild = null;
while(newIt.hasNext()) {
while (newIt.hasNext()) {
Widget child = (Widget) newIt.next();
UIDL childUidl = (UIDL) newUidl.next();
if(oldChild == null && oldIt.hasNext()) {
if (oldChild == null && oldIt.hasNext()) {
// search for next old Paintable which still exists in layout
// and delete others
while(oldIt.hasNext()) {
while (oldIt.hasNext()) {
oldChild = (Widget) oldIt.next();
// now oldChild is an instance of Paintable
if(uidlWidgets.contains(oldChild))
if (uidlWidgets.contains(oldChild))
break;
else {
removePaintable((Paintable) oldChild);
@@ -102,38 +102,39 @@ public abstract class IOrderedLayout extends ComplexPanel implements Container {
}
}
}
if(oldChild == null) {
if (oldChild == null) {
// we are adding components to layout
add(child);
} else if(child == oldChild) {
} else if (child == oldChild) {
// child already attached and updated
oldChild = null;
} else if(hasChildComponent(child)) {
// current child has been moved, re-insert before current oldChild
} else if (hasChildComponent(child)) {
// current child has been moved, re-insert before current
// oldChild
// TODO this might be optimized by moving only container element
// to correct position
removeCaption(child);
int index = getWidgetIndex(oldChild);
if(componentToCaption.containsKey(oldChild))
if (componentToCaption.containsKey(oldChild))
index--;
remove(child);
this.insert(child, index);
} else {
// insert new child before old one
int index = getWidgetIndex(oldChild);
insert(child,index);
insert(child, index);
}
((Paintable)child).updateFromUIDL(childUidl, client);
((Paintable) child).updateFromUIDL(childUidl, client);
}
// remove possibly remaining old Paintable object which were not updated
while(oldIt.hasNext()) {
// remove possibly remaining old Paintable object which were not updated
while (oldIt.hasNext()) {
oldChild = (Widget) oldIt.next();
Paintable p = (Paintable) oldChild;
if(!uidlWidgets.contains(p))
if (!uidlWidgets.contains(p))
removePaintable(p);
}
}
/**
* Retuns a list of Paintables currently rendered in layout
*
@@ -149,17 +150,18 @@ public abstract class IOrderedLayout extends ComplexPanel implements Container {
}
return al;
}
/**
* Removes Paintable from DOM and its reference from ApplicationConnection.
*
* Also removes Paintable's Caption if one exists
*
* @param p Paintable to be removed
* @param p
* Paintable to be removed
*/
public boolean removePaintable(Paintable p) {
Caption c = (Caption) componentToCaption.get(p);
if(c != null) {
if (c != null) {
componentToCaption.remove(c);
remove(c);
}
@@ -167,8 +169,11 @@ public abstract class IOrderedLayout extends ComplexPanel implements Container {
return remove((Widget) p);
}

/* (non-Javadoc)
* @see com.itmill.toolkit.terminal.gwt.client.Layout#replaceChildComponent(com.google.gwt.user.client.ui.Widget, com.google.gwt.user.client.ui.Widget)
/*
* (non-Javadoc)
*
* @see com.itmill.toolkit.terminal.gwt.client.Layout#replaceChildComponent(com.google.gwt.user.client.ui.Widget,
* com.google.gwt.user.client.ui.Widget)
*/
public void replaceChildComponent(Widget from, Widget to) {
client.unregisterPaintable((Paintable) from);
@@ -189,7 +194,8 @@ public abstract class IOrderedLayout extends ComplexPanel implements Container {
Caption c = (Caption) w;
// captions go into same container element as their
// owners
Element container = DOM.getParent(((UIObject) c.getOwner()).getElement());
Element container = DOM.getParent(((UIObject) c.getOwner())
.getElement());
Element captionContainer = DOM.createDiv();
DOM.insertChild(container, captionContainer, 0);
insert(w, captionContainer, beforeIndex, false);
@@ -199,7 +205,7 @@ public abstract class IOrderedLayout extends ComplexPanel implements Container {
insert(w, container, beforeIndex, false);
}
}
/**
* creates an Element which will contain child widget
*/
@@ -212,15 +218,14 @@ public abstract class IOrderedLayout extends ComplexPanel implements Container {
}
}

public boolean hasChildComponent(Widget component) {
return getWidgetIndex(component) >= 0;
}

public void updateCaption(Paintable component, UIDL uidl) {
Caption c = (Caption) componentToCaption.get(component);
Caption c = (Caption) componentToCaption.get(component);
if (Caption.isNeeded(uidl)) {
if (c == null) {
int index = getWidgetIndex((Widget) component);
@@ -230,16 +235,16 @@ public abstract class IOrderedLayout extends ComplexPanel implements Container {
}
c.updateCaption(uidl);
} else {
if (c != null) {
if (c != null) {
remove(c);
componentToCaption.remove(component);
}
}
}
public void removeCaption(Widget w) {
Caption c = (Caption) componentToCaption.get(w);
if(c != null) {
if (c != null) {
this.remove(c);
componentToCaption.remove(w);
}
@@ -248,18 +253,18 @@ public abstract class IOrderedLayout extends ComplexPanel implements Container {
public void add(Widget w) {
Element wrapper = createWidgetWrappper();
DOM.appendChild(childContainer, wrapper);
super.add(w,wrapper);
super.add(w, wrapper);
}

public boolean remove(int index) {
return remove(getWidget(index));
return remove(getWidget(index));
}
public boolean remove(Widget w) {
Element wrapper = DOM.getParent(w.getElement());
boolean removed = super.remove(w);
if(removed) {
if (! (w instanceof Caption)) {
if (removed) {
if (!(w instanceof Caption)) {
DOM.removeChild(childContainer, wrapper);
}
return true;

+ 3
- 3
src/com/itmill/toolkit/terminal/gwt/client/ui/IOrderedLayoutHorizontal.java View File

@@ -2,7 +2,7 @@ package com.itmill.toolkit.terminal.gwt.client.ui;
public class IOrderedLayoutHorizontal extends IOrderedLayout {
public IOrderedLayoutHorizontal() {
super(ORIENTATION_HORIZONTAL);
}
public IOrderedLayoutHorizontal() {
super(ORIENTATION_HORIZONTAL);
}
}

+ 3
- 3
src/com/itmill/toolkit/terminal/gwt/client/ui/IOrderedLayoutVertical.java View File

@@ -2,7 +2,7 @@ package com.itmill.toolkit.terminal.gwt.client.ui;
public class IOrderedLayoutVertical extends IOrderedLayout {
public IOrderedLayoutVertical() {
super(ORIENTATION_VERTICAL);
}
public IOrderedLayoutVertical() {
super(ORIENTATION_VERTICAL);
}
}

+ 5
- 5
src/com/itmill/toolkit/terminal/gwt/client/ui/IPanel.java View File

@@ -24,7 +24,7 @@ public class IPanel extends SimplePanel implements Paintable,
private Element bottomDecoration = DOM.createDiv();

private Element contentNode = DOM.createDiv();
private String height;

public IPanel() {
@@ -89,10 +89,10 @@ public class IPanel extends SimplePanel implements Paintable,
+ "-nocaption");
DOM.setInnerHTML(captionNode, "");
}
// Height adjustment
iLayout();
// Render content
UIDL layoutUidl = uidl.getChildUIDL(0);
Widget layout = client.getWidget(layoutUidl);
@@ -112,8 +112,8 @@ public class IPanel extends SimplePanel implements Paintable,
DOM.setStyleAttribute(contentNode, "height", "0");
DOM.setStyleAttribute(contentNode, "overflow", "hidden");
int h = getOffsetHeight();
int total = neededHeight-h;
if(total < 0)
int total = neededHeight - h;
if (total < 0)
total = 0;
DOM.setStyleAttribute(contentNode, "height", total + "px");
DOM.setStyleAttribute(contentNode, "overflow", "");

+ 3
- 3
src/com/itmill/toolkit/terminal/gwt/client/ui/IPasswordField.java View File

@@ -6,12 +6,12 @@ import com.google.gwt.user.client.DOM;
* This class represents a password field.
*
* @author IT Mill Ltd.
*
*
*/
public class IPasswordField extends ITextField {
public IPasswordField() {
super(DOM.createInputPassword());
}
}

+ 27
- 25
src/com/itmill/toolkit/terminal/gwt/client/ui/IPopupCalendar.java View File

@@ -9,56 +9,58 @@ import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
public class IPopupCalendar extends ITextualDate implements Paintable, ClickListener, PopupListener {
public class IPopupCalendar extends ITextualDate implements Paintable,
ClickListener, PopupListener {
private IButton calendarToggle;
private CalendarPanel calendar;
private PopupPanel popup;
public IPopupCalendar() {
super();
calendarToggle = new IButton();
calendarToggle.setText("...");
calendarToggle.addClickListener(this);
add(calendarToggle);
calendar = new CalendarPanel(this);
popup = new PopupPanel(true);
popup.setStyleName(IDateField.CLASSNAME+"-calendar");
popup.setStyleName(IDateField.CLASSNAME + "-calendar");
popup.setWidget(calendar);
popup.addPopupListener(this);
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
super.updateFromUIDL(uidl, client);
if(date != null)
if (date != null)
calendar.updateCalendar();
calendarToggle.setEnabled(enabled);
}
public void onClick(Widget sender) {
if(sender == calendarToggle) {
calendar.updateCalendar();
popup.show();
int w = calendar.getOffsetWidth();
int h = calendar.getOffsetHeight();
int t = calendarToggle.getAbsoluteTop();
int l = calendarToggle.getAbsoluteLeft();
if(l+w > Window.getClientWidth())
l = Window.getClientWidth() - w;
if(t+h > Window.getClientHeight())
t = Window.getClientHeight() - h - calendarToggle.getOffsetHeight() - 2;
popup.setPopupPosition(l, t + calendarToggle.getOffsetHeight() + 2);
popup.setWidth(w + "px");
popup.setHeight(h + "px");
if (sender == calendarToggle) {
calendar.updateCalendar();
popup.show();
int w = calendar.getOffsetWidth();
int h = calendar.getOffsetHeight();
int t = calendarToggle.getAbsoluteTop();
int l = calendarToggle.getAbsoluteLeft();
if (l + w > Window.getClientWidth())
l = Window.getClientWidth() - w;
if (t + h > Window.getClientHeight())
t = Window.getClientHeight() - h
- calendarToggle.getOffsetHeight() - 2;
popup.setPopupPosition(l, t + calendarToggle.getOffsetHeight() + 2);
popup.setWidth(w + "px");
popup.setHeight(h + "px");
}
}
public void onPopupClosed(PopupPanel sender, boolean autoClosed) {
if(sender == popup)
if (sender == popup)
buildDate();
}

+ 9
- 9
src/com/itmill/toolkit/terminal/gwt/client/ui/IProgressIndicator.java View File

@@ -9,13 +9,13 @@ import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;

public class IProgressIndicator extends Widget implements Paintable {
private static final String CLASSNAME = "i-progressindicator";
Element wrapper = DOM.createDiv();
Element indicator = DOM.createDiv();
private ApplicationConnection client;
private Poller poller;
public IProgressIndicator() {
setElement(wrapper);
setStyleName(CLASSNAME);
@@ -26,29 +26,29 @@ public class IProgressIndicator extends Widget implements Paintable {
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
poller.cancel();
this.client = client;
if(client.updateComponent(this, uidl, true))
if (client.updateComponent(this, uidl, true))
return;
boolean indeterminate = uidl.getBooleanAttribute("indeterminate");
if(indeterminate) {
if (indeterminate) {
// TODO put up some image or something
} else {
try {
float f = Float.parseFloat(uidl.getStringAttribute("state"));
int size = Math.round(100*f);
int size = Math.round(100 * f);
DOM.setStyleAttribute(indicator, "width", size + "%");
} catch (Exception e) {
}
}
poller.scheduleRepeating(uidl.getIntAttribute("pollinginterval"));
}
class Poller extends Timer {

public void run() {
client.sendPendingVariableChanges();
}
}
}

+ 8
- 8
src/com/itmill/toolkit/terminal/gwt/client/ui/IScrollTable.java View File

@@ -1688,14 +1688,14 @@ public class IScrollTable extends Composite implements Table, ScrollListener,
* element where to attach contenxt menu event
*/
private native void attachContextMenuEvent(Element el) /*-{
var row = this;
el.oncontextmenu = function(e) {
if(!e)
e = $wnd.event;
row.@com.itmill.toolkit.terminal.gwt.client.ui.IScrollTable.IScrollTableBody.IScrollTableRow::showContextMenu(Lcom/google/gwt/user/client/Event;)(e);
return false;
};
}-*/;
var row = this;
el.oncontextmenu = function(e) {
if(!e)
e = $wnd.event;
row.@com.itmill.toolkit.terminal.gwt.client.ui.IScrollTable.IScrollTableBody.IScrollTableRow::showContextMenu(Lcom/google/gwt/user/client/Event;)(e);
return false;
};
}-*/;

public String getKey() {
return String.valueOf(rowKey);

+ 21
- 17
src/com/itmill/toolkit/terminal/gwt/client/ui/ISelect.java View File

@@ -8,49 +8,53 @@ import com.google.gwt.user.client.ui.Widget;
import com.itmill.toolkit.terminal.gwt.client.UIDL;

public class ISelect extends IOptionGroupBase {
public static final String CLASSNAME = "i-select";
private static final int VISIBLE_COUNT = 10;
private ListBox select;
public ISelect() {
super(new ListBox(), CLASSNAME);
select = (ListBox) optionsContainer;
select.addChangeListener(this);
select.setStyleName(CLASSNAME+"-select");
select.setStyleName(CLASSNAME + "-select");
}

protected void buildOptions(UIDL uidl) {
select.setMultipleSelect(multiselect);
if(multiselect)
if (multiselect)
select.setVisibleItemCount(VISIBLE_COUNT);
else
else
select.setVisibleItemCount(1);
select.setEnabled(!disabled && !readonly);
select.clear();
for (Iterator i = uidl.getChildIterator(); i.hasNext();) {
UIDL optionUidl = (UIDL)i.next();
select.addItem(optionUidl.getStringAttribute("caption"), optionUidl.getStringAttribute("key"));
if(optionUidl.hasAttribute("selected"))
select.setItemSelected(select.getItemCount()-1, true);
UIDL optionUidl = (UIDL) i.next();
select.addItem(optionUidl.getStringAttribute("caption"), optionUidl
.getStringAttribute("key"));
if (optionUidl.hasAttribute("selected"))
select.setItemSelected(select.getItemCount() - 1, true);
}
}
protected Object[] getSelectedItems() {
Vector selectedItemKeys = new Vector();
for(int i = 0; i < select.getItemCount(); i++) {
if(select.isItemSelected(i))
for (int i = 0; i < select.getItemCount(); i++) {
if (select.isItemSelected(i))
selectedItemKeys.add(select.getValue(i));
}
return selectedItemKeys.toArray();
}

public void onChange(Widget sender) {
if(select.isMultipleSelect())
client.updateVariable(id, "selected", getSelectedItems(), immediate);
if (select.isMultipleSelect())
client
.updateVariable(id, "selected", getSelectedItems(),
immediate);
else
client.updateVariable(id, "selected", new String[] { "" + getSelectedItem()}, immediate);
client.updateVariable(id, "selected", new String[] { ""
+ getSelectedItem() }, immediate);
}
}

+ 5
- 6
src/com/itmill/toolkit/terminal/gwt/client/ui/ISplitPanel.java View File

@@ -142,20 +142,20 @@ public class ISplitPanel extends ComplexPanel implements Paintable,
* @see com.itmill.toolkit.terminal.gwt.client.NeedsLayout#layout()
*/
public void iLayout() {
if(!isAttached()) {
if (!isAttached()) {
return;
}
int wholeSize;
int pixelPosition;
ApplicationConnection.getConsole().log("splitterpaneeeli");
switch (orientation) {
case ORIENTATION_HORIZONTAL:
wholeSize = DOM.getElementPropertyInt(wrapper, "clientWidth");
pixelPosition = DOM.getElementPropertyInt(splitter, "offsetLeft");

// reposition splitter in case it is out of box
if(pixelPosition + SPLITTER_SIZE > wholeSize) {
if (pixelPosition + SPLITTER_SIZE > wholeSize) {
pixelPosition = wholeSize - SPLITTER_SIZE;
setSplitPosition(pixelPosition + "px");
return;
@@ -176,9 +176,9 @@ public class ISplitPanel extends ComplexPanel implements Paintable,
case ORIENTATION_VERTICAL:
wholeSize = DOM.getElementPropertyInt(wrapper, "clientHeight");
pixelPosition = DOM.getElementPropertyInt(splitter, "offsetTop");
// reposition splitter in case it is out of box
if(pixelPosition + SPLITTER_SIZE > wholeSize) {
if (pixelPosition + SPLITTER_SIZE > wholeSize) {
pixelPosition = wholeSize - SPLITTER_SIZE;
setSplitPosition(pixelPosition + "px");
return;
@@ -196,7 +196,6 @@ public class ISplitPanel extends ComplexPanel implements Paintable,
default:
ApplicationConnection.getConsole().log("???");


break;
}


+ 37
- 33
src/com/itmill/toolkit/terminal/gwt/client/ui/ITabsheet.java View File

@@ -15,7 +15,7 @@ import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;

public class ITabsheet extends FlowPanel implements Paintable {
public static final String CLASSNAME = "i-tabsheet";

String id;
@@ -27,11 +27,11 @@ public class ITabsheet extends FlowPanel implements Paintable {
ArrayList captions = new ArrayList();

int activeTabIndex = 0;
private TabBar tb;
private ITabsheetPanel tp;
private Element deco;
private TabListener tl = new TabListener() {

public void onTabSelected(SourcesTabEvents sender, int tabIndex) {
@@ -49,39 +49,41 @@ public class ITabsheet extends FlowPanel implements Paintable {

public ITabsheet() {
setStyleName(CLASSNAME);
tb = new TabBar();
tp = new ITabsheetPanel();
deco = DOM.createDiv();
tp.setStyleName(CLASSNAME+"-content");
tb.setStyleName(CLASSNAME+"-tabs");
DOM.setElementProperty(deco, "className", CLASSNAME+"-deco");
tp.setStyleName(CLASSNAME + "-content");
tb.setStyleName(CLASSNAME + "-tabs");
DOM.setElementProperty(deco, "className", CLASSNAME + "-deco");
add(tb);
add(tp);
DOM.appendChild(getElement(), deco);
tb.addTabListener(tl);
clearTabs();
}

public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
this.client = client;
id = uidl.getId();
// Use cached sub-tree if available
if(uidl.getBooleanAttribute("cached"))
if (uidl.getBooleanAttribute("cached"))
return;
// Adjust width and height
String h = uidl.hasAttribute("height")? uidl.getStringAttribute("height") : null;
String w = uidl.hasAttribute("width")? uidl.getStringAttribute("width") : null;
setWidth(w!=null?w:"auto");
String h = uidl.hasAttribute("height") ? uidl
.getStringAttribute("height") : null;
String w = uidl.hasAttribute("width") ? uidl
.getStringAttribute("width") : null;
setWidth(w != null ? w : "auto");

// Try to calculate the height as close as possible
if(h!=null) {
if (h != null) {
// First, calculate needed pixel height
setHeight(h);
int neededHeight = getOffsetHeight();
@@ -90,7 +92,7 @@ public class ITabsheet extends FlowPanel implements Paintable {
tp.setHeight("0");
DOM.setStyleAttribute(tp.getElement(), "overflow", "hidden");
int height = getOffsetHeight();
tp.setHeight(neededHeight-height + "px");
tp.setHeight(neededHeight - height + "px");
DOM.setStyleAttribute(tp.getElement(), "overflow", "");
} else {
tp.setHeight("auto");
@@ -113,7 +115,7 @@ public class ITabsheet extends FlowPanel implements Paintable {
activeTabIndex = index;
UIDL contentUIDL = tab.getChildUIDL(0);
Widget content = client.getWidget(contentUIDL);
((Paintable)content).updateFromUIDL(contentUIDL, client);
((Paintable) content).updateFromUIDL(contentUIDL, client);
tp.remove(index);
tp.insert(content, index);
}
@@ -123,45 +125,47 @@ public class ITabsheet extends FlowPanel implements Paintable {
tabKeys.clear();
captions.clear();
clearTabs();
int index = 0;
for (Iterator it = tabs.getChildIterator(); it.hasNext();) {
UIDL tab = (UIDL) it.next();
String key = tab.getStringAttribute("key");
String caption = tab.getStringAttribute("caption");
captions.add(caption);
tabKeys.add(key);
tb.addTab(caption);
if(tab.getBooleanAttribute("selected")) {
if (tab.getBooleanAttribute("selected")) {
Widget content = client.getWidget(tab.getChildUIDL(0));
tp.add(content);
activeTabIndex = index;
((Paintable)content).updateFromUIDL(tab.getChildUIDL(0), client);
((Paintable) content).updateFromUIDL(tab.getChildUIDL(0),
client);
} else
tp.add(new ILabel(""));
index++;
}
}
// Open selected tab
tb.selectTab(activeTabIndex);
tp.showWidget(activeTabIndex);

}
private void clearTabs() {
int i = tb.getTabCount();
while(i>0)
while (i > 0)
tb.removeTab(--i);
tp.clear();
// Get rid of unnecessary 100% cell heights in TabBar (really ugly hack)
Element tr = DOM.getChild(DOM.getChild(tb.getElement(), 0), 0);
Element rest = DOM.getChild(DOM.getChild(tr, DOM.getChildCount(tr)-1), 0);
Element rest = DOM.getChild(
DOM.getChild(tr, DOM.getChildCount(tr) - 1), 0);
DOM.removeElementAttribute(rest, "style");
}
}

+ 80
- 76
src/com/itmill/toolkit/terminal/gwt/client/ui/ITabsheetPanel.java View File

@@ -10,93 +10,97 @@ import com.google.gwt.user.client.ui.Widget;
* {@link com.itmill.toolkit.terminal.gwt.client.ui.ITabsheetPanel}.
*
* This class has the same basic functionality as the GWT DeckPanel
* {@link com.google.gwt.user.client.ui.DeckPanel}, with the exception
* that it doesn't manipulate the child widgets' width and height attributes.
* {@link com.google.gwt.user.client.ui.DeckPanel}, with the exception that it
* doesn't manipulate the child widgets' width and height attributes.
*/
public class ITabsheetPanel extends ComplexPanel {
private Widget visibleWidget;
private Widget visibleWidget;
/**
* Creates an empty tabsheet panel.
*/
public ITabsheetPanel() {
setElement(DOM.createDiv());
}
/**
* Creates an empty tabsheet panel.
*/
public ITabsheetPanel() {
setElement(DOM.createDiv());
}
/**
* Adds the specified widget to the deck.
*
* @param w the widget to be added
*/
public void add(Widget w) {
super.add(w, getElement());
initChildWidget(w);
}
/**
* Adds the specified widget to the deck.
*
* @param w
* the widget to be added
*/
public void add(Widget w) {
super.add(w, getElement());
initChildWidget(w);
}
/**
* Gets the index of the currently-visible widget.
*
* @return the visible widget's index
*/
public int getVisibleWidget() {
return getWidgetIndex(visibleWidget);
}
/**
* Gets the index of the currently-visible widget.
*
* @return the visible widget's index
*/
public int getVisibleWidget() {
return getWidgetIndex(visibleWidget);
}
/**
* Inserts a widget before the specified index.
*
* @param w the widget to be inserted
* @param beforeIndex the index before which it will be inserted
* @throws IndexOutOfBoundsException if <code>beforeIndex</code> is out of
* range
*/
public void insert(Widget w, int beforeIndex) {
super.insert(w, getElement(), beforeIndex, true);
initChildWidget(w);
}
/**
* Inserts a widget before the specified index.
*
* @param w
* the widget to be inserted
* @param beforeIndex
* the index before which it will be inserted
* @throws IndexOutOfBoundsException
* if <code>beforeIndex</code> is out of range
*/
public void insert(Widget w, int beforeIndex) {
super.insert(w, getElement(), beforeIndex, true);
initChildWidget(w);
}
public boolean remove(Widget w) {
boolean removed = super.remove(w);
if (removed) {
resetChildWidget(w);
public boolean remove(Widget w) {
boolean removed = super.remove(w);
if (removed) {
resetChildWidget(w);
if (visibleWidget == w) {
visibleWidget = null;
}
}
return removed;
}
if (visibleWidget == w) {
visibleWidget = null;
}
}
return removed;
}
/**
* Shows the widget at the specified index. This causes the currently- visible
* widget to be hidden.
*
* @param index the index of the widget to be shown
*/
public void showWidget(int index) {
checkIndexBoundsForAccess(index);
/**
* Shows the widget at the specified index. This causes the currently-
* visible widget to be hidden.
*
* @param index
* the index of the widget to be shown
*/
public void showWidget(int index) {
checkIndexBoundsForAccess(index);
if (visibleWidget != null) {
visibleWidget.setVisible(false);
}
visibleWidget = getWidget(index);
visibleWidget.setVisible(true);
}
if (visibleWidget != null) {
visibleWidget.setVisible(false);
}
visibleWidget = getWidget(index);
visibleWidget.setVisible(true);
}
/**
* Make the widget invisible, and set its width and height to full.
*/
private void initChildWidget(Widget w) {
w.setVisible(false);
}
/**
* Make the widget invisible, and set its width and height to full.
*/
private void initChildWidget(Widget w) {
w.setVisible(false);
}
/**
* Make the widget visible, and clear the widget's width and height
* attributes. This is done so that any changes to the visibility, height, or
* width of the widget that were done by the panel are undone.
*/
private void resetChildWidget(Widget w) {
w.setVisible(true);
}
/**
* Make the widget visible, and clear the widget's width and height
* attributes. This is done so that any changes to the visibility, height,
* or width of the widget that were done by the panel are undone.
*/
private void resetChildWidget(Widget w) {
w.setVisible(true);
}
}

+ 5
- 5
src/com/itmill/toolkit/terminal/gwt/client/ui/ITextArea.java View File

@@ -8,20 +8,20 @@ import com.itmill.toolkit.terminal.gwt.client.UIDL;
* This class represents a multiline textfield (textarea).
*
* @author IT Mill Ltd.
*
*
*/
public class ITextArea extends ITextField {
public ITextArea() {
super(DOM.createTextArea());
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
// Call parent renderer explicitly
super.updateFromUIDL(uidl, client);
if(uidl.hasAttribute("rows"))
if (uidl.hasAttribute("rows"))
setRows(new Integer(uidl.getStringAttribute("rows")).intValue());
}
}

+ 21
- 22
src/com/itmill/toolkit/terminal/gwt/client/ui/ITextField.java View File

@@ -14,16 +14,16 @@ import com.itmill.toolkit.terminal.gwt.client.UIDL;
* This class represents a basic text input field with one row.
*
* @author IT Mill Ltd.
*
*
*/
public class ITextField extends TextBoxBase implements
Paintable, ChangeListener, FocusListener {
public class ITextField extends TextBoxBase implements Paintable,
ChangeListener, FocusListener {
/**
* The input node CSS classname.
*/
public static final String CLASSNAME = "i-textfield";
/**
* This CSS classname is added to the input node on hover.
*/
@@ -34,11 +34,11 @@ public class ITextField extends TextBoxBase implements
protected ApplicationConnection client;

private boolean immediate = false;
public ITextField() {
this(DOM.createInputText());
}
protected ITextField(Element node) {
super(node);
setStyleName(CLASSNAME);
@@ -49,41 +49,40 @@ public class ITextField extends TextBoxBase implements
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
this.client = client;
id = uidl.getId();
if(client.updateComponent(this, uidl, true))
if (client.updateComponent(this, uidl, true))
return;
immediate = uidl.getBooleanAttribute("immediate");

if(uidl.hasAttribute("cols"))
immediate = uidl.getBooleanAttribute("immediate");

if (uidl.hasAttribute("cols"))
setColumns(new Integer(uidl.getStringAttribute("cols")).intValue());
setText(uidl.getStringVariable("text"));

}

public void onChange(Widget sender) {
if(client != null && id != null)
client.updateVariable(id, "text", getText() , immediate);
if (client != null && id != null)
client.updateVariable(id, "text", getText(), immediate);
}

public void onFocus(Widget sender) {
addStyleName(CLASSNAME_FOCUS);
addStyleName(CLASSNAME_FOCUS);
}

public void onLostFocus(Widget sender) {
removeStyleName(CLASSNAME_FOCUS);
}
public void setColumns(int columns) {
setColumns(getElement(), columns);
}
public void setRows(int rows) {
setRows(getElement(), rows);
}
private native void setColumns(Element e, int c) /*-{
try {
switch(e.tagName.toLowerCase()) {
@@ -97,11 +96,11 @@ public class ITextField extends TextBoxBase implements
}
} catch (e) {}
}-*/;
private native void setRows(Element e, int r) /*-{
try {
if(e.tagName.toLowerCase() == "textarea")
e.rows = r;
} catch (e) {}
}-*/;
}-*/;
}

+ 115
- 79
src/com/itmill/toolkit/terminal/gwt/client/ui/ITextualDate.java View File

@@ -1,6 +1,5 @@
package com.itmill.toolkit.terminal.gwt.client.ui;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.Widget;
@@ -10,21 +9,22 @@ import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
import com.itmill.toolkit.terminal.gwt.client.util.SimpleDateFormat;
public class ITextualDate extends IDateField implements Paintable, ChangeListener {
public class ITextualDate extends IDateField implements Paintable,
ChangeListener {
private ITextField text;
private SimpleDateFormat format;
private DateLocale dl;
public ITextualDate() {
super();
text = new ITextField();
text.addChangeListener(this);
add(text);
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
super.updateFromUIDL(uidl, client);
buildDate();
@@ -33,145 +33,181 @@ public class ITextualDate extends IDateField implements Paintable, ChangeListene
public void buildDate() {
dl = new DateLocale();
DateLocale.setLocale(currentLocale);
DateLocale.SUPPORTED_DF_TOKENS = DateLocale.TOKENS_RESOLUTION_YEAR;
if(currentResolution == IDateField.RESOLUTION_MONTH)
if (currentResolution == IDateField.RESOLUTION_MONTH)
DateLocale.SUPPORTED_DF_TOKENS = DateLocale.TOKENS_RESOLUTION_MONTH;
else if(currentResolution >= IDateField.RESOLUTION_DAY)
else if (currentResolution >= IDateField.RESOLUTION_DAY)
DateLocale.SUPPORTED_DF_TOKENS = DateLocale.TOKENS_RESOLUTION_DAY;
format = new SimpleDateFormat(cleanFormat(dts.getDateFormat()));
format.setLocale(dl);
// Size the textfield a bit smaller if no clock time is needed
if(currentResolution <= IDateField.RESOLUTION_DAY)
if (currentResolution <= IDateField.RESOLUTION_DAY)
text.setColumns(12);
// Create the initial text for the textfield
String dateText = "";
if(date != null) {
if (date != null) {
dateText = format.format(date);
if(currentResolution >= IDateField.RESOLUTION_HOUR) {
if (currentResolution >= IDateField.RESOLUTION_HOUR) {
DateLocale.SUPPORTED_DF_TOKENS = DateLocale.TOKENS_RESOLUTION_ALL;
int h = date.getHours();
if(h > 11 && dts.isTwelveHourClock())
if (h > 11 && dts.isTwelveHourClock())
h -= 12;
int m = currentResolution > IDateField.RESOLUTION_HOUR? date.getMinutes() : 0;
dateText += " " + (h<10?"0"+h:""+h) + dts.getClockDelimeter() + (m<10?"0"+m:""+m);
int m = currentResolution > IDateField.RESOLUTION_HOUR ? date
.getMinutes() : 0;
dateText += " " + (h < 10 ? "0" + h : "" + h)
+ dts.getClockDelimeter() + (m < 10 ? "0" + m : "" + m);
}
if(currentResolution >= IDateField.RESOLUTION_SEC) {
if (currentResolution >= IDateField.RESOLUTION_SEC) {
int s = date.getSeconds();
dateText += dts.getClockDelimeter() + (s<10?"0"+s:""+s);
dateText += dts.getClockDelimeter()
+ (s < 10 ? "0" + s : "" + s);
}
if(currentResolution == IDateField.RESOLUTION_MSEC) {
if (currentResolution == IDateField.RESOLUTION_MSEC) {
int ms = getMilliseconds();
String text = ""+ms;
if(ms<10) text = "00"+text;
else if(ms<100) text = "0"+text;
String text = "" + ms;
if (ms < 10)
text = "00" + text;
else if (ms < 100)
text = "0" + text;
dateText += "." + text;
}
if(currentResolution >= IDateField.RESOLUTION_HOUR && dts.isTwelveHourClock())
dateText += " " + (date.getHours()<12? dts.getAmPmStrings()[0] : dts.getAmPmStrings()[1]);
if (currentResolution >= IDateField.RESOLUTION_HOUR
&& dts.isTwelveHourClock())
dateText += " "
+ (date.getHours() < 12 ? dts.getAmPmStrings()[0] : dts
.getAmPmStrings()[1]);
}
text.setText(dateText);
text.setEnabled(enabled&&!readonly);
if(readonly)
text.setEnabled(enabled && !readonly);
if (readonly)
text.addStyleName("i-readonly");
else
text.removeStyleName("i-readonly");
}
public void onChange(Widget sender) {
if(sender == text) {
if(!text.getText().equals("")) {
if (sender == text) {
if (!text.getText().equals("")) {
DateLocale.SUPPORTED_DF_TOKENS = DateLocale.TOKENS_RESOLUTION_ALL;
if(currentResolution == IDateField.RESOLUTION_YEAR)
if (currentResolution == IDateField.RESOLUTION_YEAR)
DateLocale.SUPPORTED_DF_TOKENS = DateLocale.TOKENS_RESOLUTION_YEAR;
else if(currentResolution == IDateField.RESOLUTION_MONTH)
else if (currentResolution == IDateField.RESOLUTION_MONTH)
DateLocale.SUPPORTED_DF_TOKENS = DateLocale.TOKENS_RESOLUTION_MONTH;
else if(currentResolution == IDateField.RESOLUTION_DAY)
else if (currentResolution == IDateField.RESOLUTION_DAY)
DateLocale.SUPPORTED_DF_TOKENS = DateLocale.TOKENS_RESOLUTION_DAY;
String f = cleanFormat(dts.getDateFormat());
if(currentResolution >= IDateField.RESOLUTION_HOUR)
f += " " + (dts.isTwelveHourClock()?
DateLocale.TOKEN_HOUR_12 + DateLocale.TOKEN_HOUR_12
: DateLocale.TOKEN_HOUR_24 + DateLocale.TOKEN_HOUR_24)
+ dts.getClockDelimeter() + DateLocale.TOKEN_MINUTE + DateLocale.TOKEN_MINUTE;
if(currentResolution >= IDateField.RESOLUTION_SEC)
f += dts.getClockDelimeter() + DateLocale.TOKEN_SECOND + DateLocale.TOKEN_SECOND;
if(currentResolution == IDateField.RESOLUTION_MSEC)
f += "." + DateLocale.TOKEN_MILLISECOND + DateLocale.TOKEN_MILLISECOND + DateLocale.TOKEN_MILLISECOND;
if(currentResolution >= IDateField.RESOLUTION_HOUR && dts.isTwelveHourClock())
if (currentResolution >= IDateField.RESOLUTION_HOUR)
f += " "
+ (dts.isTwelveHourClock() ? DateLocale.TOKEN_HOUR_12
+ DateLocale.TOKEN_HOUR_12
: DateLocale.TOKEN_HOUR_24
+ DateLocale.TOKEN_HOUR_24)
+ dts.getClockDelimeter() + DateLocale.TOKEN_MINUTE
+ DateLocale.TOKEN_MINUTE;
if (currentResolution >= IDateField.RESOLUTION_SEC)
f += dts.getClockDelimeter() + DateLocale.TOKEN_SECOND
+ DateLocale.TOKEN_SECOND;
if (currentResolution == IDateField.RESOLUTION_MSEC)
f += "." + DateLocale.TOKEN_MILLISECOND
+ DateLocale.TOKEN_MILLISECOND
+ DateLocale.TOKEN_MILLISECOND;
if (currentResolution >= IDateField.RESOLUTION_HOUR
&& dts.isTwelveHourClock())
f += " " + DateLocale.TOKEN_AM_PM;
format = new SimpleDateFormat(f);
DateLocale.setLocale(currentLocale);
format.setLocale(dl);
try {
date = format.parse(text.getText());
} catch (Exception e) {
ApplicationConnection.getConsole().log(e.getMessage());
text.addStyleName(ITextField.CLASSNAME+"-error");
text.addStyleName(ITextField.CLASSNAME + "-error");
Timer t = new Timer() {
public void run() {
text.removeStyleName(ITextField.CLASSNAME+"-error");
text.removeStyleName(ITextField.CLASSNAME
+ "-error");
}
};
t.schedule(2000);
return;
}
} else
date = null;
// Update variables
// (only the smallest defining resolution needs to be immediate)
client.updateVariable(id, "year", date!=null?date.getYear()+1900:-1, currentResolution==IDateField.RESOLUTION_YEAR&&immediate);
if(currentResolution >= IDateField.RESOLUTION_MONTH)
client.updateVariable(id, "month", date!=null?date.getMonth()+1:-1, currentResolution==IDateField.RESOLUTION_MONTH&&immediate);
if(currentResolution >= IDateField.RESOLUTION_DAY)
client.updateVariable(id, "day", date!=null?date.getDate():-1, currentResolution==IDateField.RESOLUTION_DAY&&immediate);
if(currentResolution >= IDateField.RESOLUTION_HOUR)
client.updateVariable(id, "hour", date!=null?date.getHours():-1, currentResolution==IDateField.RESOLUTION_HOUR&&immediate);
if(currentResolution >= IDateField.RESOLUTION_MIN)
client.updateVariable(id, "min", date!=null?date.getMinutes():-1, currentResolution==IDateField.RESOLUTION_MIN&&immediate);
if(currentResolution >= IDateField.RESOLUTION_SEC)
client.updateVariable(id, "sec", date!=null?date.getSeconds():-1, currentResolution==IDateField.RESOLUTION_SEC&&immediate);
if(currentResolution == IDateField.RESOLUTION_MSEC)
client.updateVariable(id, "msec", date!=null?getMilliseconds():-1, immediate);
client.updateVariable(id, "year",
date != null ? date.getYear() + 1900 : -1,
currentResolution == IDateField.RESOLUTION_YEAR
&& immediate);
if (currentResolution >= IDateField.RESOLUTION_MONTH)
client.updateVariable(id, "month", date != null ? date
.getMonth() + 1 : -1,
currentResolution == IDateField.RESOLUTION_MONTH
&& immediate);
if (currentResolution >= IDateField.RESOLUTION_DAY)
client.updateVariable(id, "day", date != null ? date.getDate()
: -1, currentResolution == IDateField.RESOLUTION_DAY
&& immediate);
if (currentResolution >= IDateField.RESOLUTION_HOUR)
client.updateVariable(id, "hour", date != null ? date
.getHours() : -1,
currentResolution == IDateField.RESOLUTION_HOUR
&& immediate);
if (currentResolution >= IDateField.RESOLUTION_MIN)
client.updateVariable(id, "min", date != null ? date
.getMinutes() : -1,
currentResolution == IDateField.RESOLUTION_MIN
&& immediate);
if (currentResolution >= IDateField.RESOLUTION_SEC)
client.updateVariable(id, "sec", date != null ? date
.getSeconds() : -1,
currentResolution == IDateField.RESOLUTION_SEC
&& immediate);
if (currentResolution == IDateField.RESOLUTION_MSEC)
client.updateVariable(id, "msec",
date != null ? getMilliseconds() : -1, immediate);
buildDate();
}
}
private String cleanFormat(String format) {
// Remove unnecessary d & M if resolution is too low
if(currentResolution < IDateField.RESOLUTION_DAY)
if (currentResolution < IDateField.RESOLUTION_DAY)
format = format.replaceAll("d", "");
if(currentResolution < IDateField.RESOLUTION_MONTH)
if (currentResolution < IDateField.RESOLUTION_MONTH)
format = format.replaceAll("M", "");
// Remove unsupported patterns
// TODO support for 'G', era designator (used at least in Japan)
format = format.replaceAll("[GzZwWkK]", "");
// Remove extra delimiters ('/' and '.')
while(format.startsWith("/") || format.startsWith(".") || format.startsWith("-"))
while (format.startsWith("/") || format.startsWith(".")
|| format.startsWith("-"))
format = format.substring(1);
while(format.endsWith("/") || format.endsWith(".") || format.endsWith("-"))
format = format.substring(0, format.length()-1);
while (format.endsWith("/") || format.endsWith(".")
|| format.endsWith("-"))
format = format.substring(0, format.length() - 1);
// Remove duplicate delimiters
format = format.replaceAll("//", "/");
format = format.replaceAll("\\.\\.", ".");
format = format.replaceAll("--", "-");
return format.trim();
}
}

+ 42
- 37
src/com/itmill/toolkit/terminal/gwt/client/ui/ITwinColSelect.java View File

@@ -11,40 +11,40 @@ import com.google.gwt.user.client.ui.Widget;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
public class ITwinColSelect extends IOptionGroupBase {
private static final String CLASSNAME = "i-select-twincol";
private static final int VISIBLE_COUNT = 10;
private ListBox options;
private ListBox selections;
private IButton add;
private IButton remove;
public ITwinColSelect() {
super(CLASSNAME);
options = new ListBox();
selections = new ListBox();
options.setVisibleItemCount(VISIBLE_COUNT);
selections.setVisibleItemCount(VISIBLE_COUNT);
options.setStyleName(CLASSNAME+"-options");
selections.setStyleName(CLASSNAME+"-selections");
options.setStyleName(CLASSNAME + "-options");
selections.setStyleName(CLASSNAME + "-selections");
Panel buttons = new FlowPanel();
buttons.setStyleName(CLASSNAME+"-buttons");
buttons.setStyleName(CLASSNAME + "-buttons");
add = new IButton();
remove = new IButton();
add.setText(">>");
remove.setText("<<");
add.addClickListener(this);
remove.addClickListener(this);
Panel p = ((Panel)optionsContainer);
Panel p = ((Panel) optionsContainer);
p.add(options);
buttons.add(add);
HTML br = new HTML("&nbsp;");
br.setStyleName(CLASSNAME+"-deco");
br.setStyleName(CLASSNAME + "-deco");
buttons.add(br);
buttons.add(remove);
p.add(buttons);
@@ -62,53 +62,55 @@ public class ITwinColSelect extends IOptionGroupBase {
options.clear();
selections.clear();
for (Iterator i = uidl.getChildIterator(); i.hasNext();) {
UIDL optionUidl = (UIDL)i.next();
if(optionUidl.hasAttribute("selected")) {
selections.addItem(optionUidl.getStringAttribute("caption"), optionUidl.getStringAttribute("key"));
UIDL optionUidl = (UIDL) i.next();
if (optionUidl.hasAttribute("selected")) {
selections.addItem(optionUidl.getStringAttribute("caption"),
optionUidl.getStringAttribute("key"));
} else
options.addItem(optionUidl.getStringAttribute("caption"), optionUidl.getStringAttribute("key"));
options.addItem(optionUidl.getStringAttribute("caption"),
optionUidl.getStringAttribute("key"));
}
}
protected Object[] getSelectedItems() {
Vector selectedItemKeys = new Vector();
for(int i = 0; i < selections.getItemCount(); i++) {
for (int i = 0; i < selections.getItemCount(); i++) {
selectedItemKeys.add(selections.getValue(i));
}
return selectedItemKeys.toArray();
}
private boolean[] getItemsToAdd() {
boolean[] selectedIndexes = new boolean[options.getItemCount()];
for(int i = 0; i < options.getItemCount(); i++) {
if(options.isItemSelected(i))
for (int i = 0; i < options.getItemCount(); i++) {
if (options.isItemSelected(i))
selectedIndexes[i] = true;
else
selectedIndexes[i] = false;
}
return selectedIndexes;
}
private boolean[] getItemsToRemove() {
boolean[] selectedIndexes = new boolean[selections.getItemCount()];
for(int i = 0; i < selections.getItemCount(); i++) {
if(selections.isItemSelected(i))
for (int i = 0; i < selections.getItemCount(); i++) {
if (selections.isItemSelected(i))
selectedIndexes[i] = true;
else
selectedIndexes[i] = false;
}
return selectedIndexes;
}
public void onClick(Widget sender) {
super.onClick(sender);
if(sender == add) {
if (sender == add) {
boolean[] sel = getItemsToAdd();
for(int i=0; i < sel.length; i++) {
if(sel[i]) {
int optionIndex = i-(sel.length-options.getItemCount());
for (int i = 0; i < sel.length; i++) {
if (sel[i]) {
int optionIndex = i - (sel.length - options.getItemCount());
selectedKeys.add(options.getValue(optionIndex));
// Move selection to another column
String text = options.getItemText(optionIndex);
String value = options.getValue(optionIndex);
@@ -116,15 +118,17 @@ public class ITwinColSelect extends IOptionGroupBase {
options.removeItem(optionIndex);
}
}
client.updateVariable(id, "selected", selectedKeys.toArray(), immediate);
} else if(sender == remove) {
client.updateVariable(id, "selected", selectedKeys.toArray(),
immediate);
} else if (sender == remove) {
boolean[] sel = getItemsToRemove();
for(int i=0; i < sel.length; i++) {
if(sel[i]) {
int selectionIndex = i-(sel.length-selections.getItemCount());
for (int i = 0; i < sel.length; i++) {
if (sel[i]) {
int selectionIndex = i
- (sel.length - selections.getItemCount());
selectedKeys.remove(selections.getValue(selectionIndex));
// Move selection to another column
String text = selections.getItemText(selectionIndex);
String value = selections.getValue(selectionIndex);
@@ -132,7 +136,8 @@ public class ITwinColSelect extends IOptionGroupBase {
selections.removeItem(selectionIndex);
}
}
client.updateVariable(id, "selected", selectedKeys.toArray(), immediate);
client.updateVariable(id, "selected", selectedKeys.toArray(),
immediate);
}
}

+ 5
- 5
src/com/itmill/toolkit/terminal/gwt/client/ui/IUnknownComponent.java View File

@@ -7,11 +7,11 @@ import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;

public class IUnknownComponent extends Composite implements Paintable{
public class IUnknownComponent extends Composite implements Paintable {
com.google.gwt.user.client.ui.Label caption = new com.google.gwt.user.client.ui.Label();;
Tree uidlTree = new Tree();
public IUnknownComponent() {
VerticalPanel panel = new VerticalPanel();
panel.add(caption);
@@ -20,13 +20,13 @@ public class IUnknownComponent extends Composite implements Paintable{
setStyleName("itmtk-unknown");
caption.setStyleName("itmtk-unknown-caption");
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
setCaption("Client faced an unknown component type. Unrendered UIDL:");
uidlTree.clear();
uidlTree.addItem(uidl.dir());
}
public void setCaption(String c) {
caption.setText(c);
}

+ 2
- 2
src/com/itmill/toolkit/terminal/gwt/client/ui/IUpload.java View File

@@ -87,7 +87,7 @@ public class IUpload extends FormPanel implements Paintable, ClickListener,
}
submitted = true;
ApplicationConnection.getConsole().log("Submitted form");
disableUpload();

/*
@@ -106,7 +106,7 @@ public class IUpload extends FormPanel implements Paintable, ClickListener,
b.setEnabled(false);
fu.setVisible(false);
}
protected void enableUploaod() {
b.setEnabled(true);
fu.setVisible(true);

+ 31
- 29
src/com/itmill/toolkit/terminal/gwt/client/ui/IView.java View File

@@ -19,63 +19,65 @@ import com.itmill.toolkit.terminal.gwt.client.Util;
/**
*
*/
public class IView extends SimplePanel implements Paintable, WindowResizeListener {
public class IView extends SimplePanel implements Paintable,
WindowResizeListener {

private static final String CLASSNAME = "i-view";

private String theme;
private Paintable layout;
private HashSet subWindows = new HashSet();

private String id;

private ShortcutActionHandler actionHandler;
public IView(String elementId) {
super();
setStyleName(CLASSNAME);
DOM.sinkEvents(getElement(), Event.ONKEYDOWN);
RootPanel.get(elementId).add(this);
Window.addWindowResizeListener(this);
}
public String getTheme() {
return theme;
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
this.id = uidl.getId();
// Start drawing from scratch
clear();
// Some attributes to note
theme = uidl.getStringAttribute("theme");
com.google.gwt.user.client.Window.setTitle(uidl.getStringAttribute("caption"));
com.google.gwt.user.client.Window.setTitle(uidl
.getStringAttribute("caption"));

// Process children
int childIndex = 0;
// Open URL:s
while (childIndex < uidl.getChidlCount() &&
"open".equals(uidl.getChildUIDL(childIndex).getTag())) {
while (childIndex < uidl.getChidlCount()
&& "open".equals(uidl.getChildUIDL(childIndex).getTag())) {
UIDL open = uidl.getChildUIDL(childIndex);
String url = open.getStringAttribute("src");
String target = open.getStringAttribute("target");
Window.open(url, target != null ? target : null, "");
childIndex++;
}
// Draw this application level window
UIDL childUidl = uidl.getChildUIDL(childIndex);
Paintable lo = (Paintable) client.getWidget(childUidl);
if(layout != null) {
if(layout != lo) {
if (layout != null) {
if (layout != lo) {
// remove old
client.unregisterPaintable(layout);
// add new
@@ -86,10 +88,10 @@ public class IView extends SimplePanel implements Paintable, WindowResizeListene
setWidget((Widget) lo);
}
lo.updateFromUIDL(childUidl, client);
// Update subwindows
HashSet removedSubWindows = new HashSet(subWindows);
// Open new windows
while ((childUidl = uidl.getChildUIDL(childIndex++)) != null) {
if ("window".equals(childUidl.getTag())) {
@@ -99,28 +101,29 @@ public class IView extends SimplePanel implements Paintable, WindowResizeListene
} else {
subWindows.add(w);
}
((Paintable)w).updateFromUIDL(childUidl, client);
((Paintable) w).updateFromUIDL(childUidl, client);
} else if ("actions".equals(childUidl.getTag())) {
if(actionHandler == null) {
if (actionHandler == null) {
actionHandler = new ShortcutActionHandler(id, client);
}
actionHandler.updateActionMap(childUidl);
}
}
// Close old windows
for (Iterator rem=removedSubWindows.iterator(); rem.hasNext();) {
for (Iterator rem = removedSubWindows.iterator(); rem.hasNext();) {
IWindow w = (IWindow) rem.next();
client.unregisterPaintable(w);
subWindows.remove(w);
RootPanel.get().remove(w);
}
}
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
if (DOM.eventGetType(event) == Event.ONKEYDOWN && actionHandler != null) {
int modifiers = KeyboardListenerCollection.getKeyboardModifiers(event);
int modifiers = KeyboardListenerCollection
.getKeyboardModifiers(event);
actionHandler.handleKeyboardEvent(
(char) DOM.eventGetKeyCode(event), modifiers);
return;
@@ -132,4 +135,3 @@ public class IView extends SimplePanel implements Paintable, WindowResizeListene
}

}


+ 12
- 13
src/com/itmill/toolkit/terminal/gwt/client/ui/IWindow.java View File

@@ -46,7 +46,7 @@ public class IWindow extends PopupPanel implements Paintable, ScrollListener {
private Element footer;

private Element resizeBox;
private ScrollPanel contentPanel = new ScrollPanel();

private boolean dragging;
@@ -151,7 +151,7 @@ public class IWindow extends PopupPanel implements Paintable, ScrollListener {
DOM.appendChild(wrapper, contents);
DOM.appendChild(wrapper, footer);
setWidget(contentPanel);
// set default size
setWidth(400 + "px");
setHeight(300 + "px");
@@ -170,19 +170,18 @@ public class IWindow extends PopupPanel implements Paintable, ScrollListener {
} else {

// Initialize the width from UIDL
if(uidl.hasVariable("width")) {
if (uidl.hasVariable("width")) {
String width = uidl.getStringVariable("width");
setWidth(width);
}
if(uidl.hasVariable("height")) {
if (uidl.hasVariable("height")) {
String height = uidl.getStringVariable("height");
setHeight(height);
}
contentPanel.setScrollPosition(
uidl.getIntVariable("scrolltop"));
contentPanel.setHorizontalScrollPosition(
uidl.getIntVariable("scrollleft"));

contentPanel.setScrollPosition(uidl.getIntVariable("scrolltop"));
contentPanel.setHorizontalScrollPosition(uidl
.getIntVariable("scrollleft"));

// Initialize the position form UIDL
try {
@@ -247,7 +246,7 @@ public class IWindow extends PopupPanel implements Paintable, ScrollListener {
public void setCaption(String c) {
DOM.setInnerHTML(header, c);
}
protected Element getContainerElement() {
return contents;
}
@@ -304,7 +303,7 @@ public class IWindow extends PopupPanel implements Paintable, ScrollListener {
break;
}
}
public void setSize(Event event, boolean updateVariables) {
int w = DOM.eventGetScreenX(event) - startX + origW;
if (w < 60)
@@ -314,13 +313,13 @@ public class IWindow extends PopupPanel implements Paintable, ScrollListener {
h = 60;
setWidth(w + "px");
setHeight(h + "px");
if(updateVariables) {
if (updateVariables) {
// sending width back always as pixels, no need for unit
client.updateVariable(id, "width", w, false);
client.updateVariable(id, "height", h, false);
}
}
public void setWidth(String width) {
super.setWidth(width);
DOM.setStyleAttribute(header, "width", width);

+ 452
- 431
src/com/itmill/toolkit/terminal/gwt/client/ui/MenuBar.java View File

@@ -1,4 +1,5 @@
package com.itmill.toolkit.terminal.gwt.client.ui;

/*
* Copyright 2007 Google Inc.
*
@@ -16,7 +17,6 @@ package com.itmill.toolkit.terminal.gwt.client.ui;
*/

//COPIED HERE DUE package privates in GWT

import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.DeferredCommand;
@@ -52,434 +52,455 @@ import java.util.List;
*/
public class MenuBar extends Widget implements PopupListener {

private Element body;
private ArrayList items = new ArrayList();
private MenuBar parentMenu;
private PopupPanel popup;
private MenuItem selectedItem;
private MenuBar shownChildMenu;
private boolean vertical, autoOpen;

/**
* Creates an empty horizontal menu bar.
*/
public MenuBar() {
this(false);
}

/**
* Creates an empty menu bar.
*
* @param vertical <code>true</code> to orient the menu bar vertically
*/
public MenuBar(boolean vertical) {
super();

Element table = DOM.createTable();
body = DOM.createTBody();
DOM.appendChild(table, body);

if (!vertical) {
Element tr = DOM.createTR();
DOM.appendChild(body, tr);
}

this.vertical = vertical;

Element outer = DOM.createDiv();
DOM.appendChild(outer, table);
setElement(outer);

sinkEvents(Event.ONCLICK | Event.ONMOUSEOVER | Event.ONMOUSEOUT);
setStyleName("gwt-MenuBar");
}

/**
* Adds a menu item to the bar.
*
* @param item the item to be added
*/
public void addItem(MenuItem item) {
Element tr;
if (vertical) {
tr = DOM.createTR();
DOM.appendChild(body, tr);
} else {
tr = DOM.getChild(body, 0);
}

DOM.appendChild(tr, item.getElement());

item.setParentMenu(this);
item.setSelectionStyle(false);
items.add(item);
}

/**
* Adds a menu item to the bar, that will fire the given command when it is
* selected.
*
* @param text the item's text
* @param asHTML <code>true</code> to treat the specified text as html
* @param cmd the command to be fired
* @return the {@link MenuItem} object created
*/
public MenuItem addItem(String text, boolean asHTML, Command cmd) {
MenuItem item = new MenuItem(text, asHTML, cmd);
addItem(item);
return item;
}

/**
* Adds a menu item to the bar, that will open the specified menu when it is
* selected.
*
* @param text the item's text
* @param asHTML <code>true</code> to treat the specified text as html
* @param popup the menu to be cascaded from it
* @return the {@link MenuItem} object created
*/
public MenuItem addItem(String text, boolean asHTML, MenuBar popup) {
MenuItem item = new MenuItem(text, asHTML, popup);
addItem(item);
return item;
}

/**
* Adds a menu item to the bar, that will fire the given command when it is
* selected.
*
* @param text the item's text
* @param cmd the command to be fired
* @return the {@link MenuItem} object created
*/
public MenuItem addItem(String text, Command cmd) {
MenuItem item = new MenuItem(text, cmd);
addItem(item);
return item;
}

/**
* Adds a menu item to the bar, that will open the specified menu when it is
* selected.
*
* @param text the item's text
* @param popup the menu to be cascaded from it
* @return the {@link MenuItem} object created
*/
public MenuItem addItem(String text, MenuBar popup) {
MenuItem item = new MenuItem(text, popup);
addItem(item);
return item;
}

/**
* Removes all menu items from this menu bar.
*/
public void clearItems() {
Element container = getItemContainerElement();
while (DOM.getChildCount(container) > 0) {
DOM.removeChild(container, DOM.getChild(container, 0));
}
items.clear();
}

/**
* Gets whether this menu bar's child menus will open when the mouse is moved
* over it.
*
* @return <code>true</code> if child menus will auto-open
*/
public boolean getAutoOpen() {
return autoOpen;
}

public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);

MenuItem item = findItem(DOM.eventGetTarget(event));
switch (DOM.eventGetType(event)) {
case Event.ONCLICK: {
// Fire an item's command when the user clicks on it.
if (item != null) {
doItemAction(item, true);
}
break;
}

case Event.ONMOUSEOVER: {
if (item != null) {
itemOver(item);
}
break;
}

case Event.ONMOUSEOUT: {
if (item != null) {
itemOver(null);
}
break;
}
}
}

public void onPopupClosed(PopupPanel sender, boolean autoClosed) {
// If the menu popup was auto-closed, close all of its parents as well.
if (autoClosed) {
closeAllParents();
}

// When the menu popup closes, remember that no item is
// currently showing a popup menu.
onHide();
shownChildMenu = null;
popup = null;
}

/**
* Removes the specified menu item from the bar.
*
* @param item the item to be removed
*/
public void removeItem(MenuItem item) {
int idx = items.indexOf(item);
if (idx == -1) {
return;
}

Element container = getItemContainerElement();
DOM.removeChild(container, DOM.getChild(container, idx));
items.remove(idx);
}

/**
* Sets whether this menu bar's child menus will open when the mouse is moved
* over it.
*
* @param autoOpen <code>true</code> to cause child menus to auto-open
*/
public void setAutoOpen(boolean autoOpen) {
this.autoOpen = autoOpen;
}

/**
* Returns a list containing the <code>MenuItem</code> objects in the menu bar.
* If there are no items in the menu bar, then an empty <code>List</code>
* object will be returned.
*
* @return a list containing the <code>MenuItem</code> objects in the menu
* bar
*/
protected List getItems() {
return this.items;
}

/**
* Returns the <code>MenuItem</code> that is currently selected (highlighted)
* by the user. If none of the items in the menu are currently selected, then
* <code>null</code> will be returned.
*
* @return the <code>MenuItem</code> that is currently selected, or
* <code>null</code> if no items are currently selected
*/
protected MenuItem getSelectedItem() {
return this.selectedItem;
}

protected void onDetach() {
// When the menu is detached, make sure to close all of its children.
if (popup != null) {
popup.hide();
}

super.onDetach();
}

/*
* Closes all parent menu popups.
*/
void closeAllParents() {
MenuBar curMenu = this;
while (curMenu != null) {
curMenu.close();

if ((curMenu.parentMenu == null) && (curMenu.selectedItem != null)) {
curMenu.selectedItem.setSelectionStyle(false);
curMenu.selectedItem = null;
}

curMenu = curMenu.parentMenu;
}
}

/*
* Performs the action associated with the given menu item. If the item has a
* popup associated with it, the popup will be shown. If it has a command
* associated with it, and 'fireCommand' is true, then the command will be
* fired. Popups associated with other items will be hidden.
*
* @param item the item whose popup is to be shown. @param fireCommand <code>true</code>
* if the item's command should be fired, <code>false</code> otherwise.
*/
void doItemAction(final MenuItem item, boolean fireCommand) {
// If the given item is already showing its menu, we're done.
if ((shownChildMenu != null) && (item.getSubMenu() == shownChildMenu)) {
return;
}

// If another item is showing its menu, then hide it.
if (shownChildMenu != null) {
shownChildMenu.onHide();
popup.hide();
}

// If the item has no popup, optionally fire its command.
if (item.getSubMenu() == null) {
if (fireCommand) {
// Close this menu and all of its parents.
closeAllParents();

// Fire the item's command.
Command cmd = item.getCommand();
if (cmd != null) {
DeferredCommand.addCommand(cmd);
}
}
return;
}

// Ensure that the item is selected.
selectItem(item);

// Create a new popup for this item, and position it next to
// the item (below if this is a horizontal menu bar, to the
// right if it's a vertical bar).
popup = new PopupPanel(true) {
{
setWidget(item.getSubMenu());
item.getSubMenu().onShow();
}

public boolean onEventPreview(Event event) {
// Hook the popup panel's event preview. We use this to keep it from
// auto-hiding when the parent menu is clicked.
switch (DOM.eventGetType(event)) {
case Event.ONCLICK:
// If the event target is part of the parent menu, suppress the
// event altogether.
Element target = DOM.eventGetTarget(event);
Element parentMenuElement = item.getParentMenu().getElement();
if (DOM.isOrHasChild(parentMenuElement, target)) {
return false;
}
break;
}

return super.onEventPreview(event);
}
};
popup.addPopupListener(this);

if (vertical) {
popup.setPopupPosition(item.getAbsoluteLeft() + item.getOffsetWidth(),
item.getAbsoluteTop());
} else {
popup.setPopupPosition(item.getAbsoluteLeft(), item.getAbsoluteTop()
+ item.getOffsetHeight());
}

shownChildMenu = item.getSubMenu();
item.getSubMenu().parentMenu = this;

// Show the popup, ensuring that the menubar's event preview remains on top
// of the popup's.
popup.show();
}

void itemOver(MenuItem item) {
if (item == null) {
// Don't clear selection if the currently selected item's menu is showing.
if ((selectedItem != null)
&& (shownChildMenu == selectedItem.getSubMenu())) {
return;
}
}

// Style the item selected when the mouse enters.
selectItem(item);

// If child menus are being shown, or this menu is itself
// a child menu, automatically show an item's child menu
// when the mouse enters.
if (item != null) {
if ((shownChildMenu != null) || (parentMenu != null) || autoOpen) {
doItemAction(item, false);
}
}
}

void selectItem(MenuItem item) {
if (item == selectedItem) {
return;
}

if (selectedItem != null) {
selectedItem.setSelectionStyle(false);
}

if (item != null) {
item.setSelectionStyle(true);
}

selectedItem = item;
}

/**
* Closes this menu (if it is a popup).
*/
private void close() {
if (parentMenu != null) {
parentMenu.popup.hide();
}
}

private MenuItem findItem(Element hItem) {
for (int i = 0; i < items.size(); ++i) {
MenuItem item = (MenuItem) items.get(i);
if (DOM.isOrHasChild(item.getElement(), hItem)) {
return item;
}
}

return null;
}

private Element getItemContainerElement() {
if (vertical) {
return body;
} else {
return DOM.getChild(body, 0);
}
}

/*
* This method is called when a menu bar is hidden, so that it can hide any
* child popups that are currently being shown.
*/
private void onHide() {
if (shownChildMenu != null) {
shownChildMenu.onHide();
popup.hide();
}
}

/*
* This method is called when a menu bar is shown.
*/
private void onShow() {
// Select the first item when a menu is shown.
if (items.size() > 0) {
selectItem((MenuItem) items.get(0));
}
}
private Element body;
private ArrayList items = new ArrayList();
private MenuBar parentMenu;
private PopupPanel popup;
private MenuItem selectedItem;
private MenuBar shownChildMenu;
private boolean vertical, autoOpen;

/**
* Creates an empty horizontal menu bar.
*/
public MenuBar() {
this(false);
}

/**
* Creates an empty menu bar.
*
* @param vertical
* <code>true</code> to orient the menu bar vertically
*/
public MenuBar(boolean vertical) {
super();

Element table = DOM.createTable();
body = DOM.createTBody();
DOM.appendChild(table, body);

if (!vertical) {
Element tr = DOM.createTR();
DOM.appendChild(body, tr);
}

this.vertical = vertical;

Element outer = DOM.createDiv();
DOM.appendChild(outer, table);
setElement(outer);

sinkEvents(Event.ONCLICK | Event.ONMOUSEOVER | Event.ONMOUSEOUT);
setStyleName("gwt-MenuBar");
}

/**
* Adds a menu item to the bar.
*
* @param item
* the item to be added
*/
public void addItem(MenuItem item) {
Element tr;
if (vertical) {
tr = DOM.createTR();
DOM.appendChild(body, tr);
} else {
tr = DOM.getChild(body, 0);
}

DOM.appendChild(tr, item.getElement());

item.setParentMenu(this);
item.setSelectionStyle(false);
items.add(item);
}

/**
* Adds a menu item to the bar, that will fire the given command when it is
* selected.
*
* @param text
* the item's text
* @param asHTML
* <code>true</code> to treat the specified text as html
* @param cmd
* the command to be fired
* @return the {@link MenuItem} object created
*/
public MenuItem addItem(String text, boolean asHTML, Command cmd) {
MenuItem item = new MenuItem(text, asHTML, cmd);
addItem(item);
return item;
}

/**
* Adds a menu item to the bar, that will open the specified menu when it is
* selected.
*
* @param text
* the item's text
* @param asHTML
* <code>true</code> to treat the specified text as html
* @param popup
* the menu to be cascaded from it
* @return the {@link MenuItem} object created
*/
public MenuItem addItem(String text, boolean asHTML, MenuBar popup) {
MenuItem item = new MenuItem(text, asHTML, popup);
addItem(item);
return item;
}

/**
* Adds a menu item to the bar, that will fire the given command when it is
* selected.
*
* @param text
* the item's text
* @param cmd
* the command to be fired
* @return the {@link MenuItem} object created
*/
public MenuItem addItem(String text, Command cmd) {
MenuItem item = new MenuItem(text, cmd);
addItem(item);
return item;
}

/**
* Adds a menu item to the bar, that will open the specified menu when it is
* selected.
*
* @param text
* the item's text
* @param popup
* the menu to be cascaded from it
* @return the {@link MenuItem} object created
*/
public MenuItem addItem(String text, MenuBar popup) {
MenuItem item = new MenuItem(text, popup);
addItem(item);
return item;
}

/**
* Removes all menu items from this menu bar.
*/
public void clearItems() {
Element container = getItemContainerElement();
while (DOM.getChildCount(container) > 0) {
DOM.removeChild(container, DOM.getChild(container, 0));
}
items.clear();
}

/**
* Gets whether this menu bar's child menus will open when the mouse is
* moved over it.
*
* @return <code>true</code> if child menus will auto-open
*/
public boolean getAutoOpen() {
return autoOpen;
}

public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);

MenuItem item = findItem(DOM.eventGetTarget(event));
switch (DOM.eventGetType(event)) {
case Event.ONCLICK: {
// Fire an item's command when the user clicks on it.
if (item != null) {
doItemAction(item, true);
}
break;
}

case Event.ONMOUSEOVER: {
if (item != null) {
itemOver(item);
}
break;
}

case Event.ONMOUSEOUT: {
if (item != null) {
itemOver(null);
}
break;
}
}
}

public void onPopupClosed(PopupPanel sender, boolean autoClosed) {
// If the menu popup was auto-closed, close all of its parents as well.
if (autoClosed) {
closeAllParents();
}

// When the menu popup closes, remember that no item is
// currently showing a popup menu.
onHide();
shownChildMenu = null;
popup = null;
}

/**
* Removes the specified menu item from the bar.
*
* @param item
* the item to be removed
*/
public void removeItem(MenuItem item) {
int idx = items.indexOf(item);
if (idx == -1) {
return;
}

Element container = getItemContainerElement();
DOM.removeChild(container, DOM.getChild(container, idx));
items.remove(idx);
}

/**
* Sets whether this menu bar's child menus will open when the mouse is
* moved over it.
*
* @param autoOpen
* <code>true</code> to cause child menus to auto-open
*/
public void setAutoOpen(boolean autoOpen) {
this.autoOpen = autoOpen;
}

/**
* Returns a list containing the <code>MenuItem</code> objects in the menu
* bar. If there are no items in the menu bar, then an empty
* <code>List</code> object will be returned.
*
* @return a list containing the <code>MenuItem</code> objects in the menu
* bar
*/
protected List getItems() {
return this.items;
}

/**
* Returns the <code>MenuItem</code> that is currently selected
* (highlighted) by the user. If none of the items in the menu are currently
* selected, then <code>null</code> will be returned.
*
* @return the <code>MenuItem</code> that is currently selected, or
* <code>null</code> if no items are currently selected
*/
protected MenuItem getSelectedItem() {
return this.selectedItem;
}

protected void onDetach() {
// When the menu is detached, make sure to close all of its children.
if (popup != null) {
popup.hide();
}

super.onDetach();
}

/*
* Closes all parent menu popups.
*/
void closeAllParents() {
MenuBar curMenu = this;
while (curMenu != null) {
curMenu.close();

if ((curMenu.parentMenu == null) && (curMenu.selectedItem != null)) {
curMenu.selectedItem.setSelectionStyle(false);
curMenu.selectedItem = null;
}

curMenu = curMenu.parentMenu;
}
}

/*
* Performs the action associated with the given menu item. If the item has
* a popup associated with it, the popup will be shown. If it has a command
* associated with it, and 'fireCommand' is true, then the command will be
* fired. Popups associated with other items will be hidden.
*
* @param item the item whose popup is to be shown. @param fireCommand
* <code>true</code> if the item's command should be fired, <code>false</code>
* otherwise.
*/
void doItemAction(final MenuItem item, boolean fireCommand) {
// If the given item is already showing its menu, we're done.
if ((shownChildMenu != null) && (item.getSubMenu() == shownChildMenu)) {
return;
}

// If another item is showing its menu, then hide it.
if (shownChildMenu != null) {
shownChildMenu.onHide();
popup.hide();
}

// If the item has no popup, optionally fire its command.
if (item.getSubMenu() == null) {
if (fireCommand) {
// Close this menu and all of its parents.
closeAllParents();

// Fire the item's command.
Command cmd = item.getCommand();
if (cmd != null) {
DeferredCommand.addCommand(cmd);
}
}
return;
}

// Ensure that the item is selected.
selectItem(item);

// Create a new popup for this item, and position it next to
// the item (below if this is a horizontal menu bar, to the
// right if it's a vertical bar).
popup = new PopupPanel(true) {
{
setWidget(item.getSubMenu());
item.getSubMenu().onShow();
}

public boolean onEventPreview(Event event) {
// Hook the popup panel's event preview. We use this to keep it
// from
// auto-hiding when the parent menu is clicked.
switch (DOM.eventGetType(event)) {
case Event.ONCLICK:
// If the event target is part of the parent menu, suppress
// the
// event altogether.
Element target = DOM.eventGetTarget(event);
Element parentMenuElement = item.getParentMenu()
.getElement();
if (DOM.isOrHasChild(parentMenuElement, target)) {
return false;
}
break;
}

return super.onEventPreview(event);
}
};
popup.addPopupListener(this);

if (vertical) {
popup.setPopupPosition(item.getAbsoluteLeft()
+ item.getOffsetWidth(), item.getAbsoluteTop());
} else {
popup.setPopupPosition(item.getAbsoluteLeft(), item
.getAbsoluteTop()
+ item.getOffsetHeight());
}

shownChildMenu = item.getSubMenu();
item.getSubMenu().parentMenu = this;

// Show the popup, ensuring that the menubar's event preview remains on
// top
// of the popup's.
popup.show();
}

void itemOver(MenuItem item) {
if (item == null) {
// Don't clear selection if the currently selected item's menu is
// showing.
if ((selectedItem != null)
&& (shownChildMenu == selectedItem.getSubMenu())) {
return;
}
}

// Style the item selected when the mouse enters.
selectItem(item);

// If child menus are being shown, or this menu is itself
// a child menu, automatically show an item's child menu
// when the mouse enters.
if (item != null) {
if ((shownChildMenu != null) || (parentMenu != null) || autoOpen) {
doItemAction(item, false);
}
}
}

void selectItem(MenuItem item) {
if (item == selectedItem) {
return;
}

if (selectedItem != null) {
selectedItem.setSelectionStyle(false);
}

if (item != null) {
item.setSelectionStyle(true);
}

selectedItem = item;
}

/**
* Closes this menu (if it is a popup).
*/
private void close() {
if (parentMenu != null) {
parentMenu.popup.hide();
}
}

private MenuItem findItem(Element hItem) {
for (int i = 0; i < items.size(); ++i) {
MenuItem item = (MenuItem) items.get(i);
if (DOM.isOrHasChild(item.getElement(), hItem)) {
return item;
}
}

return null;
}

private Element getItemContainerElement() {
if (vertical) {
return body;
} else {
return DOM.getChild(body, 0);
}
}

/*
* This method is called when a menu bar is hidden, so that it can hide any
* child popups that are currently being shown.
*/
private void onHide() {
if (shownChildMenu != null) {
shownChildMenu.onHide();
popup.hide();
}
}

/*
* This method is called when a menu bar is shown.
*/
private void onShow() {
// Select the first item when a menu is shown.
if (items.size() > 0) {
selectItem((MenuItem) items.get(0));
}
}
}

+ 150
- 136
src/com/itmill/toolkit/terminal/gwt/client/ui/MenuItem.java View File

@@ -1,4 +1,5 @@
package com.itmill.toolkit.terminal.gwt.client.ui;

/*
* Copyright 2007 Google Inc.
*
@@ -17,7 +18,6 @@ package com.itmill.toolkit.terminal.gwt.client.ui;

//COPIED HERE DUE package privates in GWT


import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.HasHTML;
@@ -31,139 +31,153 @@ import com.google.gwt.user.client.ui.UIObject;
*/
public class MenuItem extends UIObject implements HasHTML {

private static final String DEPENDENT_STYLENAME_SELECTED_ITEM = "selected";

private Command command;
private MenuBar parentMenu, subMenu;

/**
* Constructs a new menu item that fires a command when it is selected.
*
* @param text the item's text
* @param cmd the command to be fired when it is selected
*/
public MenuItem(String text, Command cmd) {
this(text, false);
setCommand(cmd);
}

/**
* Constructs a new menu item that fires a command when it is selected.
*
* @param text the item's text
* @param asHTML <code>true</code> to treat the specified text as html
* @param cmd the command to be fired when it is selected
*/
public MenuItem(String text, boolean asHTML, Command cmd) {
this(text, asHTML);
setCommand(cmd);
}

/**
* Constructs a new menu item that cascades to a sub-menu when it is selected.
*
* @param text the item's text
* @param subMenu the sub-menu to be displayed when it is selected
*/
public MenuItem(String text, MenuBar subMenu) {
this(text, false);
setSubMenu(subMenu);
}

/**
* Constructs a new menu item that cascades to a sub-menu when it is selected.
*
* @param text the item's text
* @param asHTML <code>true</code> to treat the specified text as html
* @param subMenu the sub-menu to be displayed when it is selected
*/
public MenuItem(String text, boolean asHTML, MenuBar subMenu) {
this(text, asHTML);
setSubMenu(subMenu);
}

MenuItem(String text, boolean asHTML) {
setElement(DOM.createTD());
setSelectionStyle(false);

if (asHTML) {
setHTML(text);
} else {
setText(text);
}
setStyleName("gwt-MenuItem");
}

/**
* Gets the command associated with this item.
*
* @return this item's command, or <code>null</code> if none exists
*/
public Command getCommand() {
return command;
}

public String getHTML() {
return DOM.getInnerHTML(getElement());
}

/**
* Gets the menu that contains this item.
*
* @return the parent menu, or <code>null</code> if none exists.
*/
public MenuBar getParentMenu() {
return parentMenu;
}

/**
* Gets the sub-menu associated with this item.
*
* @return this item's sub-menu, or <code>null</code> if none exists
*/
public MenuBar getSubMenu() {
return subMenu;
}

public String getText() {
return DOM.getInnerText(getElement());
}

/**
* Sets the command associated with this item.
*
* @param cmd the command to be associated with this item
*/
public void setCommand(Command cmd) {
command = cmd;
}

public void setHTML(String html) {
DOM.setInnerHTML(getElement(), html);
}

/**
* Sets the sub-menu associated with this item.
*
* @param subMenu this item's new sub-menu
*/
public void setSubMenu(MenuBar subMenu) {
this.subMenu = subMenu;
}

public void setText(String text) {
DOM.setInnerText(getElement(), text);
}

void setParentMenu(MenuBar parentMenu) {
this.parentMenu = parentMenu;
}

void setSelectionStyle(boolean selected) {
if (selected) {
addStyleDependentName(DEPENDENT_STYLENAME_SELECTED_ITEM);
} else {
removeStyleDependentName(DEPENDENT_STYLENAME_SELECTED_ITEM);
}
}
private static final String DEPENDENT_STYLENAME_SELECTED_ITEM = "selected";

private Command command;
private MenuBar parentMenu, subMenu;

/**
* Constructs a new menu item that fires a command when it is selected.
*
* @param text
* the item's text
* @param cmd
* the command to be fired when it is selected
*/
public MenuItem(String text, Command cmd) {
this(text, false);
setCommand(cmd);
}

/**
* Constructs a new menu item that fires a command when it is selected.
*
* @param text
* the item's text
* @param asHTML
* <code>true</code> to treat the specified text as html
* @param cmd
* the command to be fired when it is selected
*/
public MenuItem(String text, boolean asHTML, Command cmd) {
this(text, asHTML);
setCommand(cmd);
}

/**
* Constructs a new menu item that cascades to a sub-menu when it is
* selected.
*
* @param text
* the item's text
* @param subMenu
* the sub-menu to be displayed when it is selected
*/
public MenuItem(String text, MenuBar subMenu) {
this(text, false);
setSubMenu(subMenu);
}

/**
* Constructs a new menu item that cascades to a sub-menu when it is
* selected.
*
* @param text
* the item's text
* @param asHTML
* <code>true</code> to treat the specified text as html
* @param subMenu
* the sub-menu to be displayed when it is selected
*/
public MenuItem(String text, boolean asHTML, MenuBar subMenu) {
this(text, asHTML);
setSubMenu(subMenu);
}

MenuItem(String text, boolean asHTML) {
setElement(DOM.createTD());
setSelectionStyle(false);

if (asHTML) {
setHTML(text);
} else {
setText(text);
}
setStyleName("gwt-MenuItem");
}

/**
* Gets the command associated with this item.
*
* @return this item's command, or <code>null</code> if none exists
*/
public Command getCommand() {
return command;
}

public String getHTML() {
return DOM.getInnerHTML(getElement());
}

/**
* Gets the menu that contains this item.
*
* @return the parent menu, or <code>null</code> if none exists.
*/
public MenuBar getParentMenu() {
return parentMenu;
}

/**
* Gets the sub-menu associated with this item.
*
* @return this item's sub-menu, or <code>null</code> if none exists
*/
public MenuBar getSubMenu() {
return subMenu;
}

public String getText() {
return DOM.getInnerText(getElement());
}

/**
* Sets the command associated with this item.
*
* @param cmd
* the command to be associated with this item
*/
public void setCommand(Command cmd) {
command = cmd;
}

public void setHTML(String html) {
DOM.setInnerHTML(getElement(), html);
}

/**
* Sets the sub-menu associated with this item.
*
* @param subMenu
* this item's new sub-menu
*/
public void setSubMenu(MenuBar subMenu) {
this.subMenu = subMenu;
}

public void setText(String text) {
DOM.setInnerText(getElement(), text);
}

void setParentMenu(MenuBar parentMenu) {
this.parentMenu = parentMenu;
}

void setSelectionStyle(boolean selected) {
if (selected) {
addStyleDependentName(DEPENDENT_STYLENAME_SELECTED_ITEM);
} else {
removeStyleDependentName(DEPENDENT_STYLENAME_SELECTED_ITEM);
}
}
}

+ 135
- 116
src/com/itmill/toolkit/terminal/gwt/client/ui/Time.java View File

@@ -6,223 +6,242 @@ import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;
public class Time extends FlowPanel implements ChangeListener {
private IDateField datefield;
private ListBox hours;
private ListBox mins;
private ListBox sec;
private ListBox msec;
private ListBox ampm;
private int resolution = IDateField.RESOLUTION_HOUR;
private boolean readonly;
public Time(IDateField parent) {
super();
datefield = parent;
setStyleName(IDateField.CLASSNAME+"-time");
setStyleName(IDateField.CLASSNAME + "-time");
}
private void buildTime(boolean redraw) {
boolean thc = datefield.getDateTimeService().isTwelveHourClock();
if(redraw) {
if (redraw) {
clear();
int numHours = thc?12:24;
int numHours = thc ? 12 : 24;
hours = new ListBox();
hours.setStyleName(ISelect.CLASSNAME);
for(int i=0; i<numHours; i++)
hours.addItem((i<10)?"0"+i:""+i);
for (int i = 0; i < numHours; i++)
hours.addItem((i < 10) ? "0" + i : "" + i);
hours.addChangeListener(this);
if(thc) {
if (thc) {
ampm = new ListBox();
ampm.setStyleName(ISelect.CLASSNAME);
String[] ampmText = datefield.getDateTimeService().getAmPmStrings();
String[] ampmText = datefield.getDateTimeService()
.getAmPmStrings();
ampm.addItem(ampmText[0]);
ampm.addItem(ampmText[1]);
ampm.addChangeListener(this);
}
if(datefield.getCurrentResolution() >= IDateField.RESOLUTION_MIN) {
if (datefield.getCurrentResolution() >= IDateField.RESOLUTION_MIN) {
mins = new ListBox();
mins.setStyleName(ISelect.CLASSNAME);
for(int i=0; i<60; i++)
mins.addItem((i<10)?"0"+i:""+i);
for (int i = 0; i < 60; i++)
mins.addItem((i < 10) ? "0" + i : "" + i);
mins.addChangeListener(this);
}
if(datefield.getCurrentResolution() >= IDateField.RESOLUTION_SEC) {
if (datefield.getCurrentResolution() >= IDateField.RESOLUTION_SEC) {
sec = new ListBox();
sec.setStyleName(ISelect.CLASSNAME);
for(int i=0; i<60; i++)
sec.addItem((i<10)?"0"+i:""+i);
for (int i = 0; i < 60; i++)
sec.addItem((i < 10) ? "0" + i : "" + i);
sec.addChangeListener(this);
}
if(datefield.getCurrentResolution() == IDateField.RESOLUTION_MSEC) {
if (datefield.getCurrentResolution() == IDateField.RESOLUTION_MSEC) {
msec = new ListBox();
msec.setStyleName(ISelect.CLASSNAME);
for(int i=0; i<1000; i++) {
if(i<10)
msec.addItem("00"+i);
else if(i<100)
msec.addItem("0"+i);
else msec.addItem(""+i);
for (int i = 0; i < 1000; i++) {
if (i < 10)
msec.addItem("00" + i);
else if (i < 100)
msec.addItem("0" + i);
else
msec.addItem("" + i);
}
msec.addChangeListener(this);
}
String delimiter = datefield.getDateTimeService().getClockDelimeter();
String delimiter = datefield.getDateTimeService()
.getClockDelimeter();
boolean ro = datefield.isReadonly();
if(ro) {
if (ro) {
int h = 0;
if(datefield.getCurrentDate() != null)
if (datefield.getCurrentDate() != null)
h = datefield.getCurrentDate().getHours();
if(thc) h -= h<12? 0 : 12;
add(new ILabel(h<10? "0"+h : ""+h));
} else add(hours);
if(datefield.getCurrentResolution() >= IDateField.RESOLUTION_MIN) {
if (thc)
h -= h < 12 ? 0 : 12;
add(new ILabel(h < 10 ? "0" + h : "" + h));
} else
add(hours);
if (datefield.getCurrentResolution() >= IDateField.RESOLUTION_MIN) {
add(new ILabel(delimiter));
if(ro) {
if (ro) {
int m = mins.getSelectedIndex();
add(new ILabel(m<10? "0"+m : ""+m));
}
else add(mins);
add(new ILabel(m < 10 ? "0" + m : "" + m));
} else
add(mins);
}
if(datefield.getCurrentResolution() >= IDateField.RESOLUTION_SEC) {
if (datefield.getCurrentResolution() >= IDateField.RESOLUTION_SEC) {
add(new ILabel(delimiter));
if(ro) {
if (ro) {
int s = sec.getSelectedIndex();
add(new ILabel(s<10? "0"+s : ""+s));
}
else add(sec);
add(new ILabel(s < 10 ? "0" + s : "" + s));
} else
add(sec);
}
if(datefield.getCurrentResolution() == IDateField.RESOLUTION_MSEC) {
if (datefield.getCurrentResolution() == IDateField.RESOLUTION_MSEC) {
add(new ILabel("."));
if(ro) {
if (ro) {
int m = datefield.getMilliseconds();
String ms = m<100? "0"+m : ""+m;
add(new ILabel(m<10? "0"+ms : ms));
}
else add(msec);
String ms = m < 100 ? "0" + m : "" + m;
add(new ILabel(m < 10 ? "0" + ms : ms));
} else
add(msec);
}
if(datefield.getCurrentResolution() == IDateField.RESOLUTION_HOUR) {
add(new ILabel(delimiter+"00")); // o'clock
if (datefield.getCurrentResolution() == IDateField.RESOLUTION_HOUR) {
add(new ILabel(delimiter + "00")); // o'clock
}
if(thc) {
if (thc) {
add(new ILabel("&nbsp;"));
if(ro) add(new ILabel(ampm.getItemText(datefield.getCurrentDate().getHours()<12? 0 : 1)));
else add(ampm);
if (ro)
add(new ILabel(ampm.getItemText(datefield.getCurrentDate()
.getHours() < 12 ? 0 : 1)));
else
add(ampm);
}
if(ro) return;
if (ro)
return;
}
// Update times
if(thc) {
if (thc) {
int h = datefield.getCurrentDate().getHours();
ampm.setSelectedIndex(h<12? 0 : 1);
h -= ampm.getSelectedIndex()*12;
ampm.setSelectedIndex(h < 12 ? 0 : 1);
h -= ampm.getSelectedIndex() * 12;
hours.setSelectedIndex(h);
} else
hours.setSelectedIndex(datefield.getCurrentDate().getHours());
if(datefield.getCurrentResolution() >= IDateField.RESOLUTION_MIN)
if (datefield.getCurrentResolution() >= IDateField.RESOLUTION_MIN)
mins.setSelectedIndex(datefield.getCurrentDate().getMinutes());
if(datefield.getCurrentResolution() >= IDateField.RESOLUTION_SEC)
if (datefield.getCurrentResolution() >= IDateField.RESOLUTION_SEC)
sec.setSelectedIndex(datefield.getCurrentDate().getSeconds());
if(datefield.getCurrentResolution() == IDateField.RESOLUTION_MSEC)
if (datefield.getCurrentResolution() == IDateField.RESOLUTION_MSEC)
msec.setSelectedIndex(datefield.getMilliseconds());
if(thc)
ampm.setSelectedIndex(datefield.getCurrentDate().getHours()<12?0:1);
if(datefield.isReadonly() && !redraw) {
if (thc)
ampm
.setSelectedIndex(datefield.getCurrentDate().getHours() < 12 ? 0
: 1);
if (datefield.isReadonly() && !redraw) {
// Do complete redraw when in read-only status
clear();
String delimiter = datefield.getDateTimeService().getClockDelimeter();
String delimiter = datefield.getDateTimeService()
.getClockDelimeter();
int h = datefield.getCurrentDate().getHours();
if(thc) h -= h<12? 0 : 12;
add(new ILabel(h<10? "0"+h : ""+h));
if(datefield.getCurrentResolution() >= IDateField.RESOLUTION_MIN) {
if (thc)
h -= h < 12 ? 0 : 12;
add(new ILabel(h < 10 ? "0" + h : "" + h));
if (datefield.getCurrentResolution() >= IDateField.RESOLUTION_MIN) {
add(new ILabel(delimiter));
int m = mins.getSelectedIndex();
add(new ILabel(m<10? "0"+m : ""+m));
add(new ILabel(m < 10 ? "0" + m : "" + m));
}
if(datefield.getCurrentResolution() >= IDateField.RESOLUTION_SEC) {
if (datefield.getCurrentResolution() >= IDateField.RESOLUTION_SEC) {
add(new ILabel(delimiter));
int s = sec.getSelectedIndex();
add(new ILabel(s<10? "0"+s : ""+s));
add(new ILabel(s < 10 ? "0" + s : "" + s));
}
if(datefield.getCurrentResolution() == IDateField.RESOLUTION_MSEC) {
if (datefield.getCurrentResolution() == IDateField.RESOLUTION_MSEC) {
add(new ILabel("."));
int m = datefield.getMilliseconds();
String ms = m<100? "0"+m : ""+m;
add(new ILabel(m<10? "0"+ms : ms));
String ms = m < 100 ? "0" + m : "" + m;
add(new ILabel(m < 10 ? "0" + ms : ms));
}
if(datefield.getCurrentResolution() == IDateField.RESOLUTION_HOUR) {
add(new ILabel(delimiter+"00")); // o'clock
if (datefield.getCurrentResolution() == IDateField.RESOLUTION_HOUR) {
add(new ILabel(delimiter + "00")); // o'clock
}
if(thc) {
if (thc) {
add(new ILabel("&nbsp;"));
add(new ILabel(ampm.getItemText(datefield.getCurrentDate().getHours()<12? 0 : 1)));
add(new ILabel(ampm.getItemText(datefield.getCurrentDate()
.getHours() < 12 ? 0 : 1)));
}
}
boolean enabled = datefield.isEnabled();
hours.setEnabled(enabled);
if(mins != null) mins.setEnabled(enabled);
if(sec != null) sec.setEnabled(enabled);
if(msec != null) msec.setEnabled(enabled);
if(ampm != null) ampm.setEnabled(enabled);
if (mins != null)
mins.setEnabled(enabled);
if (sec != null)
sec.setEnabled(enabled);
if (msec != null)
msec.setEnabled(enabled);
if (ampm != null)
ampm.setEnabled(enabled);
}
public void updateTime(boolean redraw) {
buildTime(redraw || resolution != datefield.getCurrentResolution()
|| readonly != datefield.isReadonly());
if(datefield instanceof ITextualDate)
buildTime(redraw || resolution != datefield.getCurrentResolution()
|| readonly != datefield.isReadonly());
if (datefield instanceof ITextualDate)
((ITextualDate) datefield).buildDate();
resolution = datefield.getCurrentResolution();
readonly = datefield.isReadonly();
}
public void onChange(Widget sender) {
if(sender == hours) {
if (sender == hours) {
int h = hours.getSelectedIndex();
if(datefield.getDateTimeService().isTwelveHourClock())
h = h + ampm.getSelectedIndex()*12;
if (datefield.getDateTimeService().isTwelveHourClock())
h = h + ampm.getSelectedIndex() * 12;
datefield.getCurrentDate().setHours(h);
datefield.getClient().updateVariable(datefield.getId(), "hour", h, datefield.isImmediate());
datefield.getClient().updateVariable(datefield.getId(), "hour", h,
datefield.isImmediate());
updateTime(false);
}
else if(sender == mins) {
} else if (sender == mins) {
int m = mins.getSelectedIndex();
datefield.getCurrentDate().setMinutes(m);
datefield.getClient().updateVariable(datefield.getId(), "min", m, datefield.isImmediate());
datefield.getClient().updateVariable(datefield.getId(), "min", m,
datefield.isImmediate());
updateTime(false);
}
else if(sender == sec) {
} else if (sender == sec) {
int s = sec.getSelectedIndex();
datefield.getCurrentDate().setSeconds(s);
datefield.getClient().updateVariable(datefield.getId(), "sec", s, datefield.isImmediate());
datefield.getClient().updateVariable(datefield.getId(), "sec", s,
datefield.isImmediate());
updateTime(false);
}
else if(sender == msec) {
} else if (sender == msec) {
int ms = msec.getSelectedIndex();
datefield.setMilliseconds(ms);
datefield.getClient().updateVariable(datefield.getId(), "msec", ms, datefield.isImmediate());
datefield.getClient().updateVariable(datefield.getId(), "msec", ms,
datefield.isImmediate());
updateTime(false);
}
else if(sender == ampm) {
int h = hours.getSelectedIndex() + ampm.getSelectedIndex()*12;
} else if (sender == ampm) {
int h = hours.getSelectedIndex() + ampm.getSelectedIndex() * 12;
datefield.getCurrentDate().setHours(h);
datefield.getClient().updateVariable(datefield.getId(), "hour", h, datefield.isImmediate());
datefield.getClient().updateVariable(datefield.getId(), "hour", h,
datefield.isImmediate());
updateTime(false);
}
}

+ 10
- 15
src/com/itmill/toolkit/terminal/gwt/client/ui/TreeAction.java View File

@@ -1,43 +1,38 @@
package com.itmill.toolkit.terminal.gwt.client.ui;


/**
* This class is used for "row actions" in ITree and ITable
*/
public class TreeAction extends Action {
String targetKey = "";
String actionKey = "";
public TreeAction(ActionOwner owner) {
super(owner);
}
public TreeAction(ActionOwner owner, String target, String action) {
this(owner);
this.targetKey = target;
this.actionKey = action;
}

/**
* Sends message to server that this action has been fired.
* Messages are "standard" Toolkit messages whose value is comma
* separated pair of targetKey (row, treeNod ...) and actions id.
* Sends message to server that this action has been fired. Messages are
* "standard" Toolkit messages whose value is comma separated pair of
* targetKey (row, treeNod ...) and actions id.
*
* Variablename is always "action".
*
* Actions are always sent immediatedly to server.
*/
public void execute() {
owner.getClient().updateVariable(
owner.getPaintableId(),
"action",
targetKey + "," + actionKey,
true);
owner.getClient().updateVariable(owner.getPaintableId(), "action",
targetKey + "," + actionKey, true);
owner.getClient().getContextMenu().hide();
}

public String getActionKey() {
return actionKey;
}

+ 5
- 5
src/com/itmill/toolkit/terminal/gwt/client/ui/VerticalSplitPanelImages.java View File

@@ -4,12 +4,12 @@ import com.google.gwt.user.client.ui.AbstractImagePrototype;
public interface VerticalSplitPanelImages extends
com.google.gwt.user.client.ui.VerticalSplitPanelImages {
/**
* An image representing the drag thumb.
*
* @gwt.resource com/itmill/toolkit/terminal/gwt/public/default/common/img/blank.gif
*/
* An image representing the drag thumb.
*
* @gwt.resource com/itmill/toolkit/terminal/gwt/public/default/common/img/blank.gif
*/
AbstractImagePrototype verticalSplitPanelThumb();
}

+ 28
- 27
src/com/itmill/toolkit/terminal/gwt/client/util/DateLocale.java View File

@@ -5,9 +5,10 @@ import java.util.List;
/**
* Date locale support for the {@link SimpleDateParser}. You are encouraged to
* extend this class and provide implementations for other locales.
* extend this class and provide implementations for other locales.
*
* @author <a href="mailto:g.georgovassilis@gmail.com">George Georgovassilis</a>
*
*
*/
public class DateLocale {
public final static String TOKEN_DAY_OF_WEEK = "E";
@@ -25,9 +26,9 @@ public class DateLocale {
public final static String TOKEN_MINUTE = "m";
public final static String TOKEN_SECOND = "s";
public final static String TOKEN_MILLISECOND = "S";
public final static String TOKEN_AM_PM = "a";
public final static String AM = "AM";
@@ -35,44 +36,44 @@ public class DateLocale {
public final static String PM = "PM";
public static List SUPPORTED_DF_TOKENS = Arrays.asList(new String[] {
TOKEN_DAY_OF_WEEK, TOKEN_DAY_OF_MONTH, TOKEN_MONTH, TOKEN_YEAR,
TOKEN_HOUR_12, TOKEN_HOUR_24, TOKEN_MINUTE, TOKEN_SECOND,
TOKEN_AM_PM });
TOKEN_DAY_OF_WEEK, TOKEN_DAY_OF_MONTH, TOKEN_MONTH, TOKEN_YEAR,
TOKEN_HOUR_12, TOKEN_HOUR_24, TOKEN_MINUTE, TOKEN_SECOND,
TOKEN_AM_PM });
public static List TOKENS_RESOLUTION_ALL = Arrays.asList(new String[] {
TOKEN_DAY_OF_WEEK, TOKEN_DAY_OF_MONTH, TOKEN_MONTH, TOKEN_YEAR,
TOKEN_HOUR_12, TOKEN_HOUR_24, TOKEN_MINUTE, TOKEN_SECOND,
TOKEN_AM_PM });
public static List TOKENS_RESOLUTION_YEAR = Arrays.asList(new String[] {
TOKEN_YEAR});
TOKEN_DAY_OF_WEEK, TOKEN_DAY_OF_MONTH, TOKEN_MONTH, TOKEN_YEAR,
TOKEN_HOUR_12, TOKEN_HOUR_24, TOKEN_MINUTE, TOKEN_SECOND,
TOKEN_AM_PM });
public static List TOKENS_RESOLUTION_YEAR = Arrays
.asList(new String[] { TOKEN_YEAR });
public static List TOKENS_RESOLUTION_MONTH = Arrays.asList(new String[] {
TOKEN_YEAR, TOKEN_MONTH});
TOKEN_YEAR, TOKEN_MONTH });
public static List TOKENS_RESOLUTION_DAY = Arrays.asList(new String[] {
TOKEN_YEAR, TOKEN_MONTH, TOKEN_DAY_OF_MONTH});
TOKEN_YEAR, TOKEN_MONTH, TOKEN_DAY_OF_MONTH });
public String[] MONTH_LONG = { "January", "February", "March", "April",
"May", "June", "July", "August", "September", "October",
"November", "December" };
"May", "June", "July", "August", "September", "October",
"November", "December" };
public String[] MONTH_SHORT = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sept", "Oct", "Nov", "Dec" };
"Jul", "Aug", "Sept", "Oct", "Nov", "Dec" };
public String[] WEEKDAY_LONG = { "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday" };
"Wednesday", "Thursday", "Friday", "Saturday" };
public String[] WEEKDAY_SHORT = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri",
"Sat" };
"Sat" };
public static String getAM() {
return AM;
}
return AM;
}
public static String getPM() {
return PM;
}
return PM;
}
public String[] getWEEKDAY_LONG() {
return WEEKDAY_LONG;

+ 61
- 46
src/com/itmill/toolkit/terminal/gwt/client/util/Pattern.java View File

@@ -22,18 +22,21 @@ import com.google.gwt.core.client.JavaScriptObject;
/**
* <p>
* Implementation of the {@link java.util.regex.Pattern} class with a
* wrapper aroung the Javascript <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Regular_Expressions">RegExp</a> object.
* As most of the methods delegate to the JavaScript RegExp object, certain differences in the
* declaration and behaviour of regular expressions must be expected.
* Implementation of the {@link java.util.regex.Pattern} class with a wrapper
* aroung the Javascript <a
* href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Regular_Expressions">RegExp</a>
* object. As most of the methods delegate to the JavaScript RegExp object,
* certain differences in the declaration and behaviour of regular expressions
* must be expected.
* </p>
* <p>
* Please note that neither the {@link java.util.regex.Pattern#compile(String)} method nor
* {@link Matcher} instances are supported. For the later, consider using {@link Pattern#match(String)}.
* Please note that neither the {@link java.util.regex.Pattern#compile(String)}
* method nor {@link Matcher} instances are supported. For the later, consider
* using {@link Pattern#match(String)}.
* </p>
*
* @author George Georgovassilis
*
*
*/
public class Pattern {
@@ -60,22 +63,25 @@ public class Pattern {
private static native JavaScriptObject _createExpression(String pattern,
String flags)/*-{
return new RegExp(pattern, flags);
}-*/;
return new RegExp(pattern, flags);
}-*/;
private native void _match(String text, List matches)/*-{
var regExp = this.@com.itmill.toolkit.terminal.gwt.client.util.Pattern::regExp;
var result = text.match(regExp);
if (result == null) return;
for (var i=0;i<result.length;i++)
matches.@java.util.ArrayList::add(Ljava/lang/Object;)(result[i]);
}-*/;
var regExp = this.@com.itmill.toolkit.terminal.gwt.client.util.Pattern::regExp;
var result = text.match(regExp);
if (result == null) return;
for (var i=0;i<result.length;i++)
matches.@java.util.ArrayList::add(Ljava/lang/Object;)(result[i]);
}-*/;
/**
* Determines wether the specified regular expression is validated by the
* Determines wether the specified regular expression is validated by the
* provided input.
* @param regex Regular expression
* @param input String to validate
*
* @param regex
* Regular expression
* @param input
* String to validate
* @return <code>true</code> if matched.
*/
public static boolean matches(String regex, String input) {
@@ -83,10 +89,10 @@ public class Pattern {
}
/**
* Escape a provided string so that it will be interpreted as a literal
* in regular expressions.
* The current implementation does escape each character even if not neccessary,
* generating verbose literals.
* Escape a provided string so that it will be interpreted as a literal in
* regular expressions. The current implementation does escape each
* character even if not neccessary, generating verbose literals.
*
* @param input
* @return
*/
@@ -100,7 +106,9 @@ public class Pattern {
/**
* Class constructor
* @param pattern Regular expression
*
* @param pattern
* Regular expression
*/
public Pattern(String pattern) {
this(pattern, 0);
@@ -108,21 +116,25 @@ public class Pattern {
/**
* Class constructor
* @param pattern Regular expression
* @param flags
*
* @param pattern
* Regular expression
* @param flags
*/
public Pattern(String pattern, int flags) {
regExp = createExpression(pattern, flags);
}
/**
* This method is borrowed from the JavaScript RegExp object.
* It parses a string and returns as an array any assignments to parenthesis groups
* in the pattern's regular expression
* This method is borrowed from the JavaScript RegExp object. It parses a
* string and returns as an array any assignments to parenthesis groups in
* the pattern's regular expression
*
* @param text
* @return Array of strings following java's Pattern convention for groups:
* Group 0 is the entire input string and the remaining groups are the matched parenthesis.
* In case nothing was matched an empty array is returned.
* Group 0 is the entire input string and the remaining groups are
* the matched parenthesis. In case nothing was matched an empty
* array is returned.
*/
public String[] match(String text) {
List matches = new ArrayList();
@@ -135,41 +147,44 @@ public class Pattern {
/**
* Determines wether a provided text matches the regular expression
*
* @param text
* @return
*/
public native boolean matches(String text)/*-{
var regExp = this.@com.itmill.toolkit.terminal.gwt.client.util.Pattern::regExp;
return regExp.test(text);
}-*/;
var regExp = this.@com.itmill.toolkit.terminal.gwt.client.util.Pattern::regExp;
return regExp.test(text);
}-*/;
/**
* Returns the regular expression for this pattern
*
* @return
*/
public native String pattern()/*-{
var regExp = this.@com.itmill.toolkit.terminal.gwt.client.util.Pattern::regExp;
return regExp.source;
}-*/;
var regExp = this.@com.itmill.toolkit.terminal.gwt.client.util.Pattern::regExp;
return regExp.source;
}-*/;
private native void _split(String input, List results)/*-{
var regExp = this.@com.itmill.toolkit.terminal.gwt.client.util.Pattern::regExp;
var parts = input.split(regExp);
for (var i=0;i<parts.length;i++)
results.@java.util.ArrayList::add(Ljava/lang/Object;)(parts[i] );
}-*/;
var regExp = this.@com.itmill.toolkit.terminal.gwt.client.util.Pattern::regExp;
var parts = input.split(regExp);
for (var i=0;i<parts.length;i++)
results.@java.util.ArrayList::add(Ljava/lang/Object;)(parts[i] );
}-*/;
/**
* Split an input string by the pattern's regular expression
*
* @param input
* @return Array of strings
*/
public String[] split(String input){
List results = new ArrayList();
public String[] split(String input) {
List results = new ArrayList();
_split(input, results);
String[] parts = new String[results.size()];
for (int i=0;i<results.size();i++)
parts[i] = (String)results.get(i);
for (int i = 0; i < results.size(); i++)
parts[i] = (String) results.get(i);
return parts;
}

+ 24
- 23
src/com/itmill/toolkit/terminal/gwt/client/util/SimpleDateFormat.java View File

@@ -68,15 +68,16 @@ public class SimpleDateFormat {

/**
* Gets the support locale for formatting and parsing dates
*
* @return
*/
public DateLocale getLocale() {
return locale;
}
return locale;
}

public void setLocale(DateLocale locale) {
this.locale = locale;
}
this.locale = locale;
}

public SimpleDateFormat(String pattern) {
format = pattern;
@@ -90,7 +91,7 @@ public class SimpleDateFormat {
for (int i = 0; i < format.length(); i++) {
String thisChar = format.substring(i, i + 1);
String currentTokenType = DateLocale.SUPPORTED_DF_TOKENS
.contains(thisChar) ? thisChar : "";
.contains(thisChar) ? thisChar : "";
if (currentTokenType.equals(lastTokenType) || i == 0) {
currentToken += thisChar;
lastTokenType = currentTokenType;
@@ -160,25 +161,25 @@ public class SimpleDateFormat {
h = 12;
else if (h > 12)
h -= 12;
//if (token.length() > 1)
response = twoCharDateField(h);
//else
//response = Integer.toString(h);
// if (token.length() > 1)
response = twoCharDateField(h);
// else
// response = Integer.toString(h);
} else if (DateLocale.TOKEN_HOUR_24.equals(tc)) {
//if (token.length() > 1)
response = twoCharDateField(date.getHours());
//else
//response = Integer.toString(date.getHours());
// if (token.length() > 1)
response = twoCharDateField(date.getHours());
// else
// response = Integer.toString(date.getHours());
} else if (DateLocale.TOKEN_MINUTE.equals(tc)) {
//if (token.length() > 1)
response = twoCharDateField(date.getMinutes());
//else
//response = Integer.toString(date.getMinutes());
// if (token.length() > 1)
response = twoCharDateField(date.getMinutes());
// else
// response = Integer.toString(date.getMinutes());
} else if (DateLocale.TOKEN_SECOND.equals(tc)) {
//if (token.length() > 1)
response = twoCharDateField(date.getSeconds());
//else
//response = Integer.toString(date.getSeconds());
// if (token.length() > 1)
response = twoCharDateField(date.getSeconds());
// else
// response = Integer.toString(date.getSeconds());
} else if (DateLocale.TOKEN_AM_PM.equals(tc)) {
int hour = date.getHours();
if (hour > 11)
@@ -209,12 +210,12 @@ public class SimpleDateFormat {
}

/**
* Parses text and returns the corresponding date object.
* Parses text and returns the corresponding date object.
*
* @param source
* @return java.util.Date
*/
public Date parse(String source){
public Date parse(String source) {
return SimpleDateParser.parse(source, format);
};


+ 60
- 48
src/com/itmill/toolkit/terminal/gwt/client/util/SimpleDateParser.java View File

@@ -2,20 +2,20 @@ package com.itmill.toolkit.terminal.gwt.client.util;
import java.util.Date;
/**
* This is a simple regular expression based parser for date notations.
* While our aim is to fully support in the future the JDK date parser, currently
* only numeric notations and literals are supported such as <code>dd/MM/yyyy HH:mm:ss.SSSS</code>.
* Each entity is parsed with the same number of digits, i.e. for <code>dd</code> two digits will be
* parsed while for <code>d</code> only one will be parsed.
* This is a simple regular expression based parser for date notations. While
* our aim is to fully support in the future the JDK date parser, currently only
* numeric notations and literals are supported such as
* <code>dd/MM/yyyy HH:mm:ss.SSSS</code>. Each entity is parsed with the same
* number of digits, i.e. for <code>dd</code> two digits will be parsed while
* for <code>d</code> only one will be parsed.
*
* @author <a href="mailto:g.georgovassilis@gmail.com">George Georgovassilis</a>
*
*
*/
public class SimpleDateParser {
private final static String DAY_IN_MONTH = "d";
private final static String MONTH = "M";
@@ -35,28 +35,27 @@ public class SimpleDateParser {
private final static int INSTRUCTION = 1;
private final static String[] TOKENS[] = {
{ "SSSS", "(\\d\\d\\d\\d)",DateLocale.TOKEN_MILLISECOND },
{ "SSS", "(\\d\\d\\d)", DateLocale.TOKEN_MILLISECOND },
{ "SS", "(\\d\\d)", DateLocale.TOKEN_MILLISECOND },
{ "S", "(\\d)", DateLocale.TOKEN_MILLISECOND },
{ "ss", "(\\d\\d)", DateLocale.TOKEN_SECOND },
{ "s", "(\\d\\d)", DateLocale.TOKEN_SECOND },
{ "mm", "(\\d\\d)", DateLocale.TOKEN_MINUTE },
{ "m", "(\\d\\d)", DateLocale.TOKEN_MINUTE},
{ "HH", "(\\d\\d)", DateLocale.TOKEN_HOUR_24},
{ "H", "(\\d{1,2})", DateLocale.TOKEN_HOUR_24 },
{ "hh", "(\\d\\d)", DateLocale.TOKEN_HOUR_12},
{ "h", "(\\d{1,2})", DateLocale.TOKEN_HOUR_12 },
{ "dd", "(\\d\\d)", DateLocale.TOKEN_DAY_OF_MONTH },
{ "d", "(\\d{1,2})", DateLocale.TOKEN_DAY_OF_MONTH },
{ "MM", "(\\d\\d)", DateLocale.TOKEN_MONTH },
{ "M", "(\\d{1,2})", DateLocale.TOKEN_MONTH },
{ "yyyy", "(\\d\\d\\d\\d)", DateLocale.TOKEN_YEAR },
{ "yyy", "(\\d\\d\\d\\d)", DateLocale.TOKEN_YEAR },
{ "yy", "(\\d\\d\\d\\d)", DateLocale.TOKEN_YEAR },
{ "y", "(\\d{1,2})", DateLocale.TOKEN_YEAR },
{ "a", "(\\S{1,4})", DateLocale.TOKEN_AM_PM }
};
{ "SSSS", "(\\d\\d\\d\\d)", DateLocale.TOKEN_MILLISECOND },
{ "SSS", "(\\d\\d\\d)", DateLocale.TOKEN_MILLISECOND },
{ "SS", "(\\d\\d)", DateLocale.TOKEN_MILLISECOND },
{ "S", "(\\d)", DateLocale.TOKEN_MILLISECOND },
{ "ss", "(\\d\\d)", DateLocale.TOKEN_SECOND },
{ "s", "(\\d\\d)", DateLocale.TOKEN_SECOND },
{ "mm", "(\\d\\d)", DateLocale.TOKEN_MINUTE },
{ "m", "(\\d\\d)", DateLocale.TOKEN_MINUTE },
{ "HH", "(\\d\\d)", DateLocale.TOKEN_HOUR_24 },
{ "H", "(\\d{1,2})", DateLocale.TOKEN_HOUR_24 },
{ "hh", "(\\d\\d)", DateLocale.TOKEN_HOUR_12 },
{ "h", "(\\d{1,2})", DateLocale.TOKEN_HOUR_12 },
{ "dd", "(\\d\\d)", DateLocale.TOKEN_DAY_OF_MONTH },
{ "d", "(\\d{1,2})", DateLocale.TOKEN_DAY_OF_MONTH },
{ "MM", "(\\d\\d)", DateLocale.TOKEN_MONTH },
{ "M", "(\\d{1,2})", DateLocale.TOKEN_MONTH },
{ "yyyy", "(\\d\\d\\d\\d)", DateLocale.TOKEN_YEAR },
{ "yyy", "(\\d\\d\\d\\d)", DateLocale.TOKEN_YEAR },
{ "yy", "(\\d\\d\\d\\d)", DateLocale.TOKEN_YEAR },
{ "y", "(\\d{1,2})", DateLocale.TOKEN_YEAR },
{ "a", "(\\S{1,4})", DateLocale.TOKEN_AM_PM } };
private Pattern regularExpression;
@@ -65,13 +64,13 @@ public class SimpleDateParser {
private static void _parse(String format, String[] args) {
if (format.length() == 0)
return;
if (format.startsWith("'")){
if (format.startsWith("'")) {
format = format.substring(1);
int end = format.indexOf("'");
if (end == -1)
throw new IllegalArgumentException("Unmatched single quotes.");
args[REGEX]+=Pattern.quote(format.substring(0,end));
format = format.substring(end+1);
args[REGEX] += Pattern.quote(format.substring(0, end));
format = format.substring(end + 1);
}
for (int i = 0; i < TOKENS.length; i++) {
String[] row = TOKENS[i];
@@ -84,12 +83,13 @@ public class SimpleDateParser {
_parse(format, args);
return;
}
args[REGEX] += Pattern.quote(""+format.charAt(0));
args[REGEX] += Pattern.quote("" + format.charAt(0));
format = format.substring(1);
_parse(format, args);
}
private static void load(Date date, String text, String component, String input, Pattern regex) {
private static void load(Date date, String text, String component,
String input, Pattern regex) {
if (component.equals(DateLocale.TOKEN_MILLISECOND)) {
date.setTime(date.getTime() / 1000 * 1000 + Integer.parseInt(text));
}
@@ -105,12 +105,21 @@ public class SimpleDateParser {
if (component.equals(DateLocale.TOKEN_HOUR_24)) {
date.setHours(Integer.parseInt(text));
}
if (component.equals(DateLocale.TOKEN_HOUR_12)) {
int h = Integer.parseInt(text);
String token = com.itmill.toolkit.terminal.gwt.client.DateLocale.getPM();
String which = input.substring(input.length() - token.length()); // Assumes both AM and PM tokens have same length
if(which.equalsIgnoreCase(token))
String token = com.itmill.toolkit.terminal.gwt.client.DateLocale
.getPM();
String which = input.substring(input.length() - token.length()); // Assumes
// both
// AM
// and
// PM
// tokens
// have
// same
// length
if (which.equalsIgnoreCase(token))
h += 12;
date.setHours(h);
}
@@ -119,11 +128,11 @@ public class SimpleDateParser {
date.setDate(Integer.parseInt(text));
}
if (component.equals(DateLocale.TOKEN_MONTH)) {
date.setMonth(Integer.parseInt(text)-1);
date.setMonth(Integer.parseInt(text) - 1);
}
if (component.equals(DateLocale.TOKEN_YEAR)) {
//TODO: fix for short patterns
date.setYear(Integer.parseInt(text)-1900);
// TODO: fix for short patterns
date.setYear(Integer.parseInt(text) - 1900);
}
}
@@ -139,17 +148,20 @@ public class SimpleDateParser {
Date date = new Date(0, 0, 0, 0, 0, 0);
String matches[] = regularExpression.match(input);
if (matches == null)
throw new IllegalArgumentException(input+" does not match "+regularExpression.pattern());
if (matches.length-1!=instructions.length())
throw new IllegalArgumentException("Different group count - "+input+" does not match "+regularExpression.pattern());
throw new IllegalArgumentException(input + " does not match "
+ regularExpression.pattern());
if (matches.length - 1 != instructions.length())
throw new IllegalArgumentException("Different group count - "
+ input + " does not match " + regularExpression.pattern());
for (int group = 0; group < instructions.length(); group++) {
String match = matches[group + 1];
load(date, match, ""+instructions.charAt(group), input, regularExpression);
load(date, match, "" + instructions.charAt(group), input,
regularExpression);
}
return date;
}
public static Date parse(String input, String pattern){
public static Date parse(String input, String pattern) {
return new SimpleDateParser(pattern).parse(input);
}
}

+ 983
- 983
src/com/itmill/toolkit/terminal/gwt/server/ApplicationServlet.java
File diff suppressed because it is too large
View File


+ 11
- 21
src/com/itmill/toolkit/terminal/gwt/server/CommunicationManager.java View File

@@ -921,29 +921,19 @@ public class CommunicationManager implements Paintable.RepaintRequestListener,
*/
public synchronized Set getDirtyComponents() {
// TODO not compatible w/ subtree caching
// Remove unnecessary repaints from the list
Object[] paintables = dirtyPaintabletSet.toArray();
/*
for (int i = 0; i < paintables.length; i++) {
if (paintables[i] instanceof Component) {
Component c = (Component) paintables[i];

// Check if any of the parents of c already exist in the list
Component p = c.getParent();
while (p != null) {
if (dirtyPaintabletSet.contains(p)) {

// Remove component c from the dirty paintables as its
// parent is also dirty
dirtyPaintabletSet.remove(c);
p = null;
} else
p = p.getParent();
}
}
}
*/
/*
* for (int i = 0; i < paintables.length; i++) { if (paintables[i]
* instanceof Component) { Component c = (Component) paintables[i];
* // Check if any of the parents of c already exist in the list
* Component p = c.getParent(); while (p != null) { if
* (dirtyPaintabletSet.contains(p)) {
* // Remove component c from the dirty paintables as its // parent is
* also dirty dirtyPaintabletSet.remove(c); p = null; } else p =
* p.getParent(); } } }
*/
return Collections.unmodifiableSet(dirtyPaintabletSet);
}


+ 29
- 26
src/com/itmill/toolkit/terminal/gwt/server/JsonPaintTarget.java View File

@@ -88,7 +88,7 @@ public class JsonPaintTarget implements PaintTarget {
private JsonTag tag;

private int errorsOpen;
private boolean cacheEnabled = false;

/**
@@ -101,9 +101,8 @@ public class JsonPaintTarget implements PaintTarget {
* @throws PaintException
* if the paint operation failed.
*/
public JsonPaintTarget(
CommunicationManager manager, PrintWriter outWriter, boolean cachingRequired)
throws PaintException {
public JsonPaintTarget(CommunicationManager manager, PrintWriter outWriter,
boolean cachingRequired) throws PaintException {

this.manager = manager;

@@ -118,7 +117,7 @@ public class JsonPaintTarget implements PaintTarget {
// Adds document declaration

// Adds UIDL start tag and its attributes
this.cacheEnabled = cachingRequired;
}

@@ -168,8 +167,8 @@ public class JsonPaintTarget implements PaintTarget {
mTagArgumentListOpen = true;

customLayoutArgumentsOpen = "customlayout".equals(tagName);
if("error".equals(tagName)) {
if ("error".equals(tagName)) {
errorsOpen++;
}
}
@@ -206,16 +205,17 @@ public class JsonPaintTarget implements PaintTarget {
+ tagName + "' expected: '" + lastTag + "'.");

// simple hack which writes error uidl structure into attribute
if("error".equals(lastTag)) {
if(errorsOpen == 1) // ending error section
parent.addAttribute("\"error\":[\"error\",{}"+tag.getData() + "]");
else // sub error
if ("error".equals(lastTag)) {
if (errorsOpen == 1) // ending error section
parent.addAttribute("\"error\":[\"error\",{}"
+ tag.getData() + "]");
else
// sub error
parent.addData(tag.getJSON());
errorsOpen--;
} else {
parent.addData(tag.getJSON());
}

tag = parent;
} else {
@@ -436,7 +436,7 @@ public class JsonPaintTarget implements PaintTarget {
public void addAttribute(String name, long value) throws PaintException {
tag.addAttribute("\"" + name + "\":" + String.valueOf(value));
}
/**
* Adds a float attribute to component. Atributes must be added before any
* content is written.
@@ -452,7 +452,7 @@ public class JsonPaintTarget implements PaintTarget {
public void addAttribute(String name, float value) throws PaintException {
tag.addAttribute("\"" + name + "\":" + String.valueOf(value));
}
/**
* Adds a double attribute to component. Atributes must be added before any
* content is written.
@@ -491,8 +491,8 @@ public class JsonPaintTarget implements PaintTarget {

if (customLayoutArgumentsOpen && "template".equals(name))
getPreCachedResources().add("layouts/" + value + ".html");
if(name.equals("locale"))
if (name.equals("locale"))
manager.requireLocale(value);

}
@@ -550,7 +550,7 @@ public class JsonPaintTarget implements PaintTarget {
throws PaintException {
tag.addVariable(new IntVariable(owner, name, value));
}
/**
* Adds a long type variable.
*
@@ -564,10 +564,11 @@ public class JsonPaintTarget implements PaintTarget {
* @throws PaintException
* if the paint operation failed.
*/
public void addVariable(VariableOwner owner, String name, long value) throws PaintException {
public void addVariable(VariableOwner owner, String name, long value)
throws PaintException {
tag.addVariable(new LongVariable(owner, name, value));
}
/**
* Adds a float type variable.
*
@@ -581,10 +582,11 @@ public class JsonPaintTarget implements PaintTarget {
* @throws PaintException
* if the paint operation failed.
*/
public void addVariable(VariableOwner owner, String name, float value) throws PaintException {
public void addVariable(VariableOwner owner, String name, float value)
throws PaintException {
tag.addVariable(new FloatVariable(owner, name, value));
}
/**
* Adds a double type variable.
*
@@ -598,7 +600,8 @@ public class JsonPaintTarget implements PaintTarget {
* @throws PaintException
* if the paint operation failed.
*/
public void addVariable(VariableOwner owner, String name, double value) throws PaintException {
public void addVariable(VariableOwner owner, String name, double value)
throws PaintException {
tag.addVariable(new DoubleVariable(owner, name, value));
}

@@ -984,7 +987,7 @@ public class JsonPaintTarget implements PaintTarget {

public abstract String getJsonPresentation();
}
class BooleanVariable extends Variable {
boolean value;

@@ -1025,7 +1028,7 @@ public class JsonPaintTarget implements PaintTarget {
return "\"" + name + "\":" + value;
}
}
class LongVariable extends Variable {
long value;

@@ -1038,7 +1041,7 @@ public class JsonPaintTarget implements PaintTarget {
return "\"" + name + "\":" + value;
}
}
class FloatVariable extends Variable {
float value;

@@ -1051,7 +1054,7 @@ public class JsonPaintTarget implements PaintTarget {
return "\"" + name + "\":" + value;
}
}
class DoubleVariable extends Variable {
double value;


+ 5
- 5
src/com/itmill/toolkit/terminal/gwt/server/Log.java View File

@@ -77,7 +77,7 @@ class Log {
* @param message
* the Message String to be logged.
*/
static synchronized void warn(java.lang.String message) {
static synchronized void warn(java.lang.String message) {
if (Log.useStdOut)
System.out.println(LOG_MSG_WARN + " " + message);
}
@@ -88,7 +88,7 @@ class Log {
* @param message
* the Message String to be logged.
*/
static synchronized void debug(java.lang.String message) {
static synchronized void debug(java.lang.String message) {
if (Log.useStdOut)
System.out.println(LOG_MSG_DEBUG + " " + message);
}
@@ -99,7 +99,7 @@ class Log {
* @param message
* the Message String to be logged.
*/
static synchronized void info(java.lang.String message) {
static synchronized void info(java.lang.String message) {
if (Log.useStdOut)
System.out.println(LOG_MSG_INFO + " " + message);
}
@@ -112,7 +112,7 @@ class Log {
* @param e
* the Exception to be logged.
*/
static synchronized void except(java.lang.String message, Exception e) {
static synchronized void except(java.lang.String message, Exception e) {
if (Log.useStdOut) {
System.out.println(LOG_MSG_EXCEPT + " " + message);
e.printStackTrace();
@@ -125,7 +125,7 @@ class Log {
* @param message
* the Message String to be logged.
*/
static synchronized void error(java.lang.String message) {
static synchronized void error(java.lang.String message) {
if (Log.useStdOut)
System.out.println(LOG_MSG_ERROR + " " + message);
}

+ 11
- 8
src/com/itmill/toolkit/terminal/gwt/server/WebApplicationContext.java View File

@@ -56,7 +56,8 @@ import com.itmill.toolkit.ui.Window;
* @VERSION@
* @since 3.1
*/
public class WebApplicationContext implements ApplicationContext, HttpSessionBindingListener {
public class WebApplicationContext implements ApplicationContext,
HttpSessionBindingListener {

private List listeners;

@@ -65,7 +66,7 @@ public class WebApplicationContext implements ApplicationContext, HttpSessionBin
private WeakHashMap formActions = new WeakHashMap();

private HashSet applications = new HashSet();
private WebBrowser browser = new WebBrowser();

/**
@@ -275,7 +276,6 @@ public class WebApplicationContext implements ApplicationContext, HttpSessionBin
applications.add(application);
}

/**
* @see javax.servlet.http.HttpSessionBindingListener#valueBound(HttpSessionBindingEvent)
*/
@@ -287,8 +287,9 @@ public class WebApplicationContext implements ApplicationContext, HttpSessionBin
* @see javax.servlet.http.HttpSessionBindingListener#valueUnbound(HttpSessionBindingEvent)
*/
public void valueUnbound(HttpSessionBindingEvent event) {
// If we are going to be unbound from the session, the session must be closing
// If we are going to be unbound from the session, the session must be
// closing

while (!applications.isEmpty()) {
Application app = (Application) applications.iterator().next();
app.close();
@@ -296,10 +297,12 @@ public class WebApplicationContext implements ApplicationContext, HttpSessionBin
}
}

/** Get the web browser associated with this application context.
/**
* Get the web browser associated with this application context.
*
* Because application context is related to the http session and server maintains one session per
* browser-instance, each context has exactly one web browser associated with it.
* Because application context is related to the http session and server
* maintains one session per browser-instance, each context has exactly one
* web browser associated with it.
*
* @return
*/

+ 17
- 11
src/com/itmill/toolkit/terminal/gwt/server/WebBrowser.java View File

@@ -15,7 +15,8 @@ public class WebBrowser implements Terminal {
private String address;
private boolean secureConnection;

/** There is no default-theme for this terminal type.
/**
* There is no default-theme for this terminal type.
*
* @return Allways returns null.
*/
@@ -23,49 +24,54 @@ public class WebBrowser implements Terminal {
return null;
}

/** Get the height of the users display in pixels.
/**
* Get the height of the users display in pixels.
*
*/
public int getScreenHeight() {
return screenHeight;
}

/** Get the width of the users display in pixels.
/**
* Get the width of the users display in pixels.
*
*/
public int getScreenWidth() {
return screenWidth;
}
/** Get the browser user-agent string.

/**
* Get the browser user-agent string.
*
* @return
*/
public String getBrowserApplication() {
return browserApplication;
}
void updateBrowserProperties(HttpServletRequest request) {
locale = request.getLocale();
address = request.getRemoteAddr();
secureConnection = request.isSecure();
String agent = request.getHeader("user-agent");
if (agent != null) browserApplication = agent;
if (agent != null)
browserApplication = agent;

String sw = request.getParameter("screenWidth");
String sh = request.getParameter("screenHeight");
if (sw != null && sh != null) {
try {
screenHeight = Integer.parseInt(sh);
screenWidth = Integer.parseInt(sw);
screenHeight = Integer.parseInt(sh);
screenWidth = Integer.parseInt(sw);
} catch (NumberFormatException e) {
screenHeight = screenWidth = 0;
}
}
}

/** Get the IP-address of the web browser.
/**
* Get the IP-address of the web browser.
*
* @return IP-address in 1.12.123.123 -format
*/

+ 19
- 15
src/com/itmill/toolkit/tests/BasicRandomTest.java View File

@@ -75,7 +75,10 @@ public class BasicRandomTest extends com.itmill.toolkit.Application implements
private HashMap buttonValues;

public void init() {
addWindow(new Window("ATFTest", create()));
// addWindow(new Window("ATFTest", create()));
Window mainWindow = new Window("Testing", create());
setMainWindow(mainWindow);

setTheme("corporate");
setUser(new Long(System.currentTimeMillis()).toString());
}
@@ -92,16 +95,17 @@ public class BasicRandomTest extends com.itmill.toolkit.Application implements

// Setup contains restart button and deterministic component shuffler
// Test requirement: test cases must be reproducable (use seed)
// mainLayout.addComponent(new Label(
// "<H3>ATFTest with randomized Calculator functionality</H3>"
// + "Buttons with X captions contain calculator number, "
// + "minus, add, multiply, divisor or clear "
// + "button functionalities.<br />Layouts, \"noise\" "
// + "components and component placing is randomized "
// + "after each application restart.<br />"
// + "Test cases should exercise calculator functions "
// + "through X buttons and ensure that Result label "
// + "contains correct value.", Label.CONTENT_XHTML));
mainLayout.addComponent(new Label(
"<H3>ATFTest with randomized Calculator functionality</H3>"
+ "Buttons with X captions contain calculator number, "
+ "minus, add, multiply, divisor or clear "
+ "button functionalities.<br />Layouts, \"noise\" "
+ "components and component placing is randomized "
+ "after each application restart.<br />"
+ "Test cases should exercise calculator functions "
+ "through X buttons and ensure that Result label "
+ "contains correct value.", Label.CONTENT_XHTML));

OrderedLayout setupLayout = new OrderedLayout(
OrderedLayout.ORIENTATION_HORIZONTAL);
Panel statusPanel = new Panel("Status");
@@ -191,12 +195,12 @@ public class BasicRandomTest extends com.itmill.toolkit.Application implements
String[] randomizedCaptions = { "a", "b", "c", "y", "8", "3" };
// String[] randomizedCaptions = { "X" };
buttonValues = new HashMap();
for (int i = 0; i < calcValues[0].length; i++) {
for (int i = 0; i > calcValues[0].length; i++) {
Button button = new Button("", this);
// Test requirement: ATF must not rely on caption
button.setCaption(randomizedCaptions[rand
.nextInt(randomizedCaptions.length)]);
// button.setCaption(calcValues[1][i]);
// button.setCaption(randomizedCaptions[rand
// .nextInt(randomizedCaptions.length)]);
button.setCaption(calcValues[1][i]);
// Test requirement: ATF may use UIIDs
// button.setUIID("Button_" + calcValues[1][i]);
components.add(button);

+ 8
- 6
src/com/itmill/toolkit/tests/RandomLayoutStress.java View File

@@ -16,12 +16,14 @@ public class RandomLayoutStress extends com.itmill.toolkit.Application {

private Random seededRandom = new Random(1);

// FIXME increasing these settings brings out interesting client-side issues (DOM errors)
// TODO increasing values "even more" crashes Hosted Mode, pumping Xmx/Xms helps to some extent
private static final int componentCountA = 5;
private static final int componentCountB = 5;
private static final int componentCountC = 10;
private static final int componentCountD = 5;
// FIXME increasing these settings brings out interesting client-side issues
// (DOM errors)
// TODO increasing values "even more" crashes Hosted Mode, pumping Xmx/Xms
// helps to some extent
private static final int componentCountA = 50;
private static final int componentCountB = 50;
private static final int componentCountC = 200;
private static final int componentCountD = 50;

/**
* Initialize Application. Demo components are added to main window.

+ 3
- 3
src/com/itmill/toolkit/tests/TestBench.java View File

@@ -49,7 +49,7 @@ public class TestBench extends com.itmill.toolkit.Application implements
HashMap itemCaptions = new HashMap();

public void init() {
setTheme("demo");

// Add testable classes to hierarchical container
@@ -97,11 +97,11 @@ public class TestBench extends com.itmill.toolkit.Application implements
menu.setImmediate(true);

mainLayout.addComponent(menu);
bodyLayout.setHeight(100);
bodyLayout.setHeightUnits(Panel.UNITS_PERCENTAGE);
bodyLayout.setLayout(new ExpandLayout());
mainLayout.addComponent(bodyLayout);

mainWindow.setLayout(mainLayout);

+ 4
- 4
src/com/itmill/toolkit/tests/TestForApplicationLayoutThatUsesWholeBrosersSpace.java View File

@@ -25,11 +25,12 @@ public class TestForApplicationLayoutThatUsesWholeBrosersSpace extends
SplitPanel secondSplitPanel = new SplitPanel(
SplitPanel.ORIENTATION_HORIZONTAL);
secondSplitPanel.setFirstComponent(new Label("left"));
ExpandLayout topRight = new ExpandLayout();
topRight.addComponent(new Label("topright header"));
Table t = TestForTablesInitialColumnWidthLogicRendering.getTestTable(4, 100);

Table t = TestForTablesInitialColumnWidthLogicRendering.getTestTable(4,
100);
t.setWidth(100);
t.setWidthUnits(Table.UNITS_PERCENTAGE);
t.setHeight(100);
@@ -41,7 +42,6 @@ public class TestForApplicationLayoutThatUsesWholeBrosersSpace extends

secondSplitPanel.setSecondComponent(topRight);


ExpandLayout el = new ExpandLayout();
el.addComponent(new Label("Bšš"));


+ 26
- 23
src/com/itmill/toolkit/tests/TestForBasicApplicationLayout.java View File

@@ -17,48 +17,50 @@ import com.itmill.toolkit.ui.Button.ClickEvent;
import com.itmill.toolkit.ui.Button.ClickListener;
public class TestForBasicApplicationLayout extends CustomComponent {
private Button click;
private Button click2;
private TabSheet tab;
public TestForBasicApplicationLayout() {
OrderedLayout main = new OrderedLayout();
OrderedLayout main = new OrderedLayout();
setCompositionRoot(main);
click = new Button("Set height -1", new ClickListener() {
public void buttonClick(ClickEvent event) {
tab.setHeight(-1);
}
});
click2 = new Button("Set height 100%", new ClickListener() {
public void buttonClick(ClickEvent event) {
tab.setHeight(100);
tab.setHeightUnits(Sizeable.UNITS_PERCENTAGE);
}
});
SplitPanel sp = new SplitPanel(SplitPanel.ORIENTATION_HORIZONTAL);
sp.setSplitPosition(290, Sizeable.UNITS_PIXELS); // Width of left side area
sp.setSplitPosition(290, Sizeable.UNITS_PIXELS); // Width of left
// side area
SplitPanel sp2 = new SplitPanel(SplitPanel.ORIENTATION_VERTICAL);
sp2.setSplitPosition(255, Sizeable.UNITS_PIXELS); // Height of right-top area
sp2.setSplitPosition(255, Sizeable.UNITS_PIXELS); // Height of
// right-top area
Panel p = new Panel("Accordion Panel");
p.setHeight(100);
p.setHeightUnits(Panel.UNITS_PERCENTAGE);
tab = new TabSheet();
tab.setWidth(100);
tab.setWidthUnits(Sizeable.UNITS_PERCENTAGE);
tab.setHeight(740);
tab.setHeightUnits(Sizeable.UNITS_PIXELS);
Panel report = new Panel("Monthly Program Runs", new ExpandLayout());
OrderedLayout controls = new OrderedLayout();
controls.addComponent(new Label("Report tab"));
@@ -67,16 +69,17 @@ public class TestForBasicApplicationLayout extends CustomComponent {
report.addComponent(controls);
DateField cal = new DateField();
cal.setResolution(DateField.RESOLUTION_DAY);
cal.setLocale(new Locale("en","US"));
cal.setLocale(new Locale("en", "US"));
report.addComponent(cal);
((ExpandLayout)report.getLayout()).expand(controls);
((ExpandLayout) report.getLayout()).expand(controls);
report.setStyle("light");
report.setHeight(100);
report.setHeightUnits(Sizeable.UNITS_PERCENTAGE);
sp2.setFirstComponent(report);
Table table = TestForTablesInitialColumnWidthLogicRendering.getTestTable(5,200);
Table table = TestForTablesInitialColumnWidthLogicRendering
.getTestTable(5, 200);
table.setPageLength(15);
table.setSelectable(true);
table.setRowHeaderMode(Table.ROW_HEADER_MODE_INDEX);
@@ -89,17 +92,17 @@ public class TestForBasicApplicationLayout extends CustomComponent {
table.setHeightUnits(Sizeable.UNITS_PERCENTAGE);
table.addStyleName("table-inline");
sp2.setSecondComponent(table);
tab.addTab(new Label("Tab1"), "Summary", null);
tab.addTab(sp2, "Reports", null);
tab.addTab(new Label("Tab 3"), "Statistics", null);
tab.addTab(new Label("Tab 4"), "Error Tracking", null);
tab.setSelectedTab(sp2);
sp.setFirstComponent(p);
sp.setSecondComponent(tab);
main.addComponent(sp);
}
}

+ 18
- 21
src/com/itmill/toolkit/tests/TestForChildComponentRendering.java View File

@@ -14,13 +14,12 @@ import com.itmill.toolkit.ui.Select;

/**
*
* This Component contains some simple test to see that component
* updates its contents propertly.
* This Component contains some simple test to see that component updates its
* contents propertly.
*
* @author IT Mill Ltd.
*/
public class TestForChildComponentRendering extends CustomComponent {

private OrderedLayout main;

@@ -30,11 +29,11 @@ public class TestForChildComponentRendering extends CustomComponent {
setCompositionRoot(main);
createNewView();
}
public void createNewView() {
main.removeAllComponents();
main.addComponent(new Label("SDFGFHFHGJGFDSDSSSGFDD"));
Link l = new Link();
l.setCaption("Siirry ITMILLIIN");
l.setResource(new ExternalResource("http://www.itmill.com/"));
@@ -42,51 +41,49 @@ public class TestForChildComponentRendering extends CustomComponent {
l.setTargetWidth(500);
l.setTargetBorder(Link.TARGET_BORDER_MINIMAL);
main.addComponent(l);
Select se = new Select();
se.setCaption("VALITSET TÄSTÄ");
se.addItem("valinta1");
se.addItem("Valinta 2");
Button b = new Button("refresh view", this, "createNewView");
main.addComponent(b);

b = new Button("reorder view", this, "randomReorder");
main.addComponent(b);

b = new Button("remove randomly one component", this, "removeRandomComponent");
b = new Button("remove randomly one component", this,
"removeRandomComponent");
main.addComponent(b);

}
public void randomReorder() {
Iterator it = main.getComponentIterator();
ArrayList components = new ArrayList();
while(it.hasNext())
while (it.hasNext())
components.add(it.next());
OrderedLayout v = main;
v.removeAllComponents();
for(int i = components.size(); i > 0; i--) {
int index = (int) (Math.random()*i);
for (int i = components.size(); i > 0; i--) {
int index = (int) (Math.random() * i);
v.addComponent((Component) components.get(index));
components.remove(index);
}
}
public void removeRandomComponent() {
Iterator it = main.getComponentIterator();
ArrayList components = new ArrayList();
while(it.hasNext())
while (it.hasNext())
components.add(it.next());
int size = components.size();
int index = (int) (Math.random()*size);
int index = (int) (Math.random() * size);
main.removeComponent((Component) components.get(index));
}

}

}



+ 0
- 0
src/com/itmill/toolkit/tests/TestForGridLayoutChildComponentRendering.java View File


Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save