earlier mirror fix only got the additive changes; here are the subtractives.
git-svn-id: https://google-web-toolkit.googlecode.com/svn/trunk@8267 8db76d5a-ed1c-0410-87a9-c151d255dfc7
diff --git a/bikeshed/src/com/google/gwt/app/client/ListBoxPlacePickerView.java b/bikeshed/src/com/google/gwt/app/client/ListBoxPlacePickerView.java
deleted file mode 100644
index 204d0ea..0000000
--- a/bikeshed/src/com/google/gwt/app/client/ListBoxPlacePickerView.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.app.client;
-
-import com.google.gwt.app.place.Place;
-import com.google.gwt.app.place.PlacePickerView;
-import com.google.gwt.event.logical.shared.ValueChangeEvent;
-import com.google.gwt.event.logical.shared.ValueChangeHandler;
-import com.google.gwt.event.shared.HandlerRegistration;
-import com.google.gwt.user.client.ui.ValueListBox;
-
-/**
- * Hacky ValueListBox based implementation of PlacePickerView, to be replaced by
- * new data widget, or at least something less ugly.
- *
- * @param <P> the type of places listed
- */
-public class ListBoxPlacePickerView<P extends Place> extends ValueListBox<P>
- implements PlacePickerView<P> {
- private HandlerRegistration handlerRegistration;
-
- /**
- * @return this view
- */
- public ListBoxPlacePickerView<P> asWidget() {
- return this;
- }
-
- /**
- * Set the listener.
- */
- public void setListener(final PlacePickerView.Listener<P> listener) {
- if (handlerRegistration != null) {
- handlerRegistration.removeHandler();
- handlerRegistration = null;
- }
-
- handlerRegistration = addValueChangeHandler(new ValueChangeHandler<P>() {
- public void onValueChange(ValueChangeEvent<P> event) {
- listener.placePicked(event.getValue());
- }
- });
- }
-}
diff --git a/bikeshed/src/com/google/gwt/app/util/DateTimeFormatRenderer.java b/bikeshed/src/com/google/gwt/app/util/DateTimeFormatRenderer.java
deleted file mode 100644
index 7abc353..0000000
--- a/bikeshed/src/com/google/gwt/app/util/DateTimeFormatRenderer.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.app.util;
-
-import com.google.gwt.i18n.client.DateTimeFormat;
-import com.google.gwt.i18n.client.TimeZone;
-
-import java.util.Date;
-
-/**
- * Renders {@link Date} objects with a {@link DateTimeFormat}.
- */
-public class DateTimeFormatRenderer implements Renderer<Date> {
- private final DateTimeFormat format;
- private final TimeZone timeZone;
-
- public DateTimeFormatRenderer(DateTimeFormat format) {
- this(format, null);
- }
-
- public DateTimeFormatRenderer(DateTimeFormat format, TimeZone timeZone) {
- this.format = format;
- this.timeZone = timeZone;
- }
-
- public String render(Date object) {
- return timeZone == null ? format.format(object) : format.format(object,
- timeZone);
- }
-}
diff --git a/bikeshed/src/com/google/gwt/app/util/IsWidget.java b/bikeshed/src/com/google/gwt/app/util/IsWidget.java
deleted file mode 100644
index d2f2d1d..0000000
--- a/bikeshed/src/com/google/gwt/app/util/IsWidget.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.app.util;
-
-import com.google.gwt.user.client.ui.Widget;
-
-/**
- * Extended by View interfaces that are likely to be implemented by Widgets.
- * Provides access to that widget, if it exists, without compromising the
- * ability to provide mock view instance in JRE unit tests.
- */
-public interface IsWidget {
- Widget asWidget();
-}
diff --git a/bikeshed/src/com/google/gwt/app/util/PassthroughRenderer.java b/bikeshed/src/com/google/gwt/app/util/PassthroughRenderer.java
deleted file mode 100644
index 118088c..0000000
--- a/bikeshed/src/com/google/gwt/app/util/PassthroughRenderer.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.app.util;
-
-/**
- * A no-op renderer.
- */
-public class PassthroughRenderer implements Renderer<String> {
-
- private static PassthroughRenderer INSTANCE;
-
- /**
- * @return the instance of the no-op renderer
- */
- public static Renderer<String> instance() {
- if (INSTANCE == null) {
- INSTANCE = new PassthroughRenderer();
- }
- return INSTANCE;
- }
-
- protected PassthroughRenderer() {
- }
-
- public String render(String object) {
- return object;
- }
-
-}
diff --git a/bikeshed/src/com/google/gwt/app/util/Renderer.java b/bikeshed/src/com/google/gwt/app/util/Renderer.java
deleted file mode 100644
index 12de40e..0000000
--- a/bikeshed/src/com/google/gwt/app/util/Renderer.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.app.util;
-
-/**
- * An object that can render other objects of a particular type into plain-text
- * form.
- * <p>
- * TODO: steal the slightly richer version from Guava
- *
- * @param <T> the type to render
- */
-public interface Renderer<T> {
- /**
- * Renders {@code object} as plain text.
- */
- String render(T object);
-}
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/List.gwt.xml b/bikeshed/src/com/google/gwt/bikeshed/list/List.gwt.xml
deleted file mode 100644
index a1ff279..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/List.gwt.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<!--
- Copyright 2010 Google Inc.
-
- Licensed under the Apache License, Version 2.0 (the "License"); you may not
- use this file except in compliance with the License. You may obtain a copy of
- the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- License for the specific language governing permissions and limitations under
- the License.
--->
-<module>
- <inherits name='com.google.gwt.user.User'/>
- <inherits name='com.google.gwt.cell.Cell'/>
- <source path="shared" />
- <source path="client" />
-</module>
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/client/AbstractPager.java b/bikeshed/src/com/google/gwt/bikeshed/list/client/AbstractPager.java
deleted file mode 100644
index c0db17f..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/client/AbstractPager.java
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.bikeshed.list.client;
-
-import com.google.gwt.user.client.ui.Composite;
-import com.google.gwt.view.client.PagingListView;
-import com.google.gwt.view.client.PagingListView.Pager;
-
-/**
- * An abstract pager that exposes many methods useful for paging.
- *
- * @param <T> the type of the PagingListView being controlled
- */
-public abstract class AbstractPager<T> extends Composite implements Pager<T> {
-
- /**
- * If true, all operations should be limited to the data size.
- */
- private boolean isRangeLimited;
-
- /**
- * The {@link PagingListView} being paged.
- */
- private final PagingListView<T> view;
-
- public AbstractPager(PagingListView<T> view) {
- this.view = view;
- view.setPager(this);
- }
-
- /**
- * Go to the first page.
- */
- public void firstPage() {
- setPage(0);
- }
-
- /**
- * Get the current page index.
- *
- * Since the page start index can be set to any value, its possible to be
- * between pages. In this case, the return value is the number of times
- * {@link #previousPage()} can be called.
- *
- * @return the page index
- */
- public int getPage() {
- int pageSize = view.getPageSize();
- return (view.getPageStart() + pageSize - 1) / pageSize;
- }
-
- /**
- * Get the number of pages based on the data size.
- *
- * @return the page count
- */
- public int getPageCount() {
- int pageSize = view.getPageSize();
- return (view.getDataSize() + pageSize - 1) / pageSize;
- }
-
- /**
- * Get the {@link PagingListView} being paged.
- *
- * @return the {@link PagingListView}
- */
- public PagingListView<T> getPagingListView() {
- return view;
- }
-
- /**
- * Returns true if there is enough data such that a call to
- * {@link #nextPage()} will succeed in moving the starting point of the table
- * forward.
- */
- public boolean hasNextPage() {
- return view.getPageStart() + view.getPageSize() < view.getDataSize();
- }
-
- /**
- * Returns true if there is enough data such that the specified page is within
- * range.
- */
- public boolean hasPage(int index) {
- return view.getPageSize() * index < view.getDataSize();
- }
-
- /**
- * Returns true if there is enough data such that a call to
- * {@link #previousPage()} will succeed in moving the starting point of the
- * table backward.
- */
- public boolean hasPreviousPage() {
- return view.getPageStart() > 0 && view.getDataSize() > 0;
- }
-
- /**
- * Check if the page should be limited to the actual data size.
- *
- * @return true if the range is limited to the data size
- */
- public boolean isRangeLimited() {
- return isRangeLimited;
- }
-
- /**
- * Go to the last page.
- */
- public void lastPage() {
- setPage(getPageCount() - 1);
- }
-
- /**
- * Set the page start to the last index that will still show a full page.
- */
- public void lastPageStart() {
- setPageStart(view.getDataSize() - view.getPageSize());
- }
-
- /**
- * Advance the starting row by 'pageSize' rows.
- */
- public void nextPage() {
- setPageStart(view.getPageStart() + view.getPageSize());
- }
-
- public void onRangeOrSizeChanged(PagingListView<T> listView) {
- if (isRangeLimited) {
- setPageStart(view.getPageStart());
- }
- }
-
- /**
- * Move the starting row back by 'pageSize' rows.
- */
- public void previousPage() {
- setPageStart(view.getPageStart() - view.getPageSize());
- }
-
- /**
- * Go to a specific page.
- *
- * @param index the page index
- */
- public void setPage(int index) {
- if (!isRangeLimited || hasPage(index)) {
- // We don't use the local version of setPageStart because the user
- // probably wants to use absolute page indexes.
- view.setPageStart(view.getPageSize() * index);
- }
- }
-
- /**
- * Set the page start index.
- *
- * @param index the index
- */
- public void setPageStart(int index) {
- if (isRangeLimited) {
- index = Math.min(index, view.getDataSize() - view.getPageSize());
- }
- index = Math.max(0, index);
- view.setPageStart(index);
- }
-
- /**
- * Set whether or not the page range should be limited to the actual data
- * size. If true, all operations will adjust so that there is always data
- * visible on the page.
- *
- * @param isRangeLimited
- */
- public void setRangeLimited(boolean isRangeLimited) {
- this.isRangeLimited = isRangeLimited;
- }
-}
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/client/CellList.css b/bikeshed/src/com/google/gwt/bikeshed/list/client/CellList.css
deleted file mode 100644
index c0864fa..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/client/CellList.css
+++ /dev/null
@@ -1,15 +0,0 @@
-.evenItem {
-
-}
-
-.oddItem {
-
-}
-
-@sprite .selectedItem {
- gwt-image: 'cellListSelectedBackground';
- background-color: #628cd5;
- color: white;
- height: auto;
- overflow: auto;
-}
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/client/CellList.java b/bikeshed/src/com/google/gwt/bikeshed/list/client/CellList.java
deleted file mode 100644
index 68db2c8..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/client/CellList.java
+++ /dev/null
@@ -1,272 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.bikeshed.list.client;
-
-import com.google.gwt.bikeshed.list.client.impl.CellListImpl;
-import com.google.gwt.cell.client.Cell;
-import com.google.gwt.cell.client.ValueUpdater;
-import com.google.gwt.core.client.GWT;
-import com.google.gwt.dom.client.DivElement;
-import com.google.gwt.dom.client.Document;
-import com.google.gwt.dom.client.Element;
-import com.google.gwt.dom.client.Style.Display;
-import com.google.gwt.resources.client.ClientBundle;
-import com.google.gwt.resources.client.CssResource;
-import com.google.gwt.resources.client.ImageResource;
-import com.google.gwt.resources.client.ImageResource.ImageOptions;
-import com.google.gwt.resources.client.ImageResource.RepeatStyle;
-import com.google.gwt.user.client.Event;
-import com.google.gwt.user.client.ui.Widget;
-import com.google.gwt.view.client.PagingListView;
-import com.google.gwt.view.client.Range;
-import com.google.gwt.view.client.SelectionModel;
-
-import java.util.List;
-
-/**
- * A single column list of cells.
- *
- * @param <T> the data type of list items
- */
-public class CellList<T> extends Widget implements PagingListView<T> {
-
- /**
- * The default page size.
- */
- private static final int DEFAULT_PAGE_SIZE = 25;
-
- /**
- * Styles used by this widget.
- */
- public static interface Style extends CssResource {
-
- /**
- * Applied to even items.
- */
- String evenItem();
-
- /**
- * Applied to odd items.
- */
- String oddItem();
-
- /**
- * Applied to selected items.
- */
- String selectedItem();
- }
-
- /**
- * A ClientBundle that provides images for this widget.
- */
- public static interface Resources extends ClientBundle {
-
- /**
- * The background used for selected items.
- */
- @ImageOptions(repeatStyle = RepeatStyle.Horizontal)
- ImageResource cellListSelectedBackground();
-
- /**
- * The styles used in this widget.
- */
- @Source("CellList.css")
- Style cellListStyle();
- }
-
- private static Resources DEFAULT_RESOURCES;
-
- private static Resources getDefaultResources() {
- if (DEFAULT_RESOURCES == null) {
- DEFAULT_RESOURCES = GWT.create(Resources.class);
- }
- return DEFAULT_RESOURCES;
- }
-
- private final Cell<T> cell;
- private final Element emptyMessageElem;
- private final CellListImpl<T> impl;
- private final Style style;
- private ValueUpdater<T> valueUpdater;
-
- /**
- * Construct a new {@link CellList}.
- *
- * @param cell the cell used to render each item
- */
- public CellList(final Cell<T> cell) {
- this(cell, getDefaultResources());
- }
-
- /**
- * Construct a new {@link CellList} with the specified {@link Resources}.
- *
- * @param cell the cell used to render each item
- * @param resources the resources used for this widget
- */
- // TODO(jlabanca): Should cell support ViewData?
- public CellList(final Cell<T> cell, Resources resources) {
- this.cell = cell;
- this.style = resources.cellListStyle();
- this.style.ensureInjected();
-
- // Create the DOM hierarchy.
- Element childContainer = Document.get().createDivElement();
-
- emptyMessageElem = Document.get().createDivElement();
- emptyMessageElem.setInnerHTML("<i>no data</i>");
- showOrHide(emptyMessageElem, false);
-
- // TODO: find some way for cells to communicate what they're interested in.
- DivElement outerDiv = Document.get().createDivElement();
- outerDiv.appendChild(childContainer);
- outerDiv.appendChild(emptyMessageElem);
- setElement(outerDiv);
- sinkEvents(Event.ONCLICK | Event.ONCHANGE | Event.MOUSEEVENTS);
-
- // Create the implementation.
- impl = new CellListImpl<T>(this, DEFAULT_PAGE_SIZE, childContainer) {
-
- @Override
- protected boolean dependsOnSelection() {
- return cell.dependsOnSelection();
- }
-
- @Override
- protected void emitHtml(StringBuilder sb, List<T> values, int start,
- SelectionModel<? super T> selectionModel) {
- int length = values.size();
- int end = start + length;
- for (int i = start; i < end; i++) {
- T value = values.get(i - start);
- boolean isSelected = selectionModel == null ? false
- : selectionModel.isSelected(value);
- sb.append("<div __idx='").append(i).append("'");
- sb.append(" class='");
- sb.append(i % 2 == 0 ? style.evenItem() : style.oddItem());
- if (isSelected) {
- sb.append(" ").append(style.selectedItem());
- }
- sb.append("'>");
- cell.render(value, null, sb);
- sb.append("</div>");
- }
- }
-
- @Override
- protected void onSizeChanged() {
- super.onSizeChanged();
- showOrHide(emptyMessageElem, impl.getDataSize() == 0);
- }
-
- @Override
- protected void setSelected(Element elem, boolean selected) {
- setStyleName(elem, style.selectedItem(), selected);
- }
- };
- }
-
- public int getDataSize() {
- return impl.getDataSize();
- }
-
- public int getPageSize() {
- return impl.getPageSize();
- }
-
- public int getPageStart() {
- return impl.getPageStart();
- }
-
- public Range getRange() {
- return impl.getRange();
- }
-
- @Override
- public void onBrowserEvent(Event event) {
- super.onBrowserEvent(event);
-
- // Forward the event to the cell.
- Element target = event.getEventTarget().cast();
- String idxString = "";
- while ((target != null)
- && ((idxString = target.getAttribute("__idx")).length() == 0)) {
- target = target.getParentElement();
- }
- if (idxString.length() > 0) {
- int idx = Integer.parseInt(idxString);
- T value = impl.getData().get(idx - impl.getPageStart());
- cell.onBrowserEvent(target, value, null, event, valueUpdater);
- if (event.getTypeInt() == Event.ONMOUSEDOWN && !cell.consumesEvents()) {
- SelectionModel<? super T> selectionModel = impl.getSelectionModel();
- if (selectionModel != null) {
- selectionModel.setSelected(value, true);
- }
- }
- }
- }
-
- public void setData(int start, int length, List<T> values) {
- impl.setData(values, start);
- }
-
- public void setDataSize(int size, boolean isExact) {
- impl.setDataSize(size);
- }
-
- public void setDelegate(Delegate<T> delegate) {
- impl.setDelegate(delegate);
- }
-
- public void setPager(Pager<T> pager) {
- impl.setPager(pager);
- }
-
- public void setPageSize(int pageSize) {
- impl.setPageSize(pageSize);
- }
-
- public void setPageStart(int pageStart) {
- impl.setPageStart(pageStart);
- }
-
- public void setSelectionModel(final SelectionModel<? super T> selectionModel) {
- impl.setSelectionModel(selectionModel, true);
- }
-
- /**
- * Set the value updater to use when cells modify items.
- *
- * @param valueUpdater the {@link ValueUpdater}
- */
- public void setValueUpdater(ValueUpdater<T> valueUpdater) {
- this.valueUpdater = valueUpdater;
- }
-
- /**
- * Show or hide an element.
- *
- * @param element the element
- * @param show true to show, false to hide
- */
- private void showOrHide(Element element, boolean show) {
- if (show) {
- element.getStyle().clearDisplay();
- } else {
- element.getStyle().setDisplay(Display.NONE);
- }
- }
-}
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/client/CellTable.css b/bikeshed/src/com/google/gwt/bikeshed/list/client/CellTable.css
deleted file mode 100644
index aa7f4df..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/client/CellTable.css
+++ /dev/null
@@ -1,63 +0,0 @@
-.cellTable {
- border: 1px solid #88b0f2;
-}
-
-.firstColumn {
-
-}
-
-@sprite .footer {
- gwt-image: 'cellTableFooterBackground';
- background-color: #b4d0f8;
- border-top: 1px solid #88b0f2;
- border-left: 1px solid #88b0f2;
- border-right: 1px solid #eef;
- padding: 5px 20px;
- text-align: left;
- color: #4b4a4a;
- text-shadow: #ddf 1px 1px 0
-}
-
-@sprite .header {
- gwt-image: 'cellTableHeaderBackground';
- background-color: #b4d0f8;
- border-bottom: 1px solid #88b0f2;
- border-left: 1px solid #88b0f2;
- border-right: 1px solid #eef;
- padding: 0px 20px;
- text-align: left;
- color: #4b4a4a;
- text-shadow: #ddf 1px 1px 0;
-}
-
-.cell {
- padding: 4px 10px;
-}
-
-.firstColumnFooter {
- border-left: 0px;
-}
-
-.firstColumnHeader {
- border-left: 0px;
-}
-
-.evenRow {
- background-color: #ffffff;
-}
-
-.oddRow {
- background-color: #eef4fb;
-}
-
-.hoveredRow {
- background-color: #88b0f2;
-}
-
-@sprite .selectedRow {
- gwt-image: 'cellTableSelectedBackground';
- background-color: #628cd5;
- color: white;
- height: auto;
- overflow: auto;
-}
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/client/CellTable.java b/bikeshed/src/com/google/gwt/bikeshed/list/client/CellTable.java
deleted file mode 100644
index b36022d..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/client/CellTable.java
+++ /dev/null
@@ -1,618 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.bikeshed.list.client;
-
-import com.google.gwt.bikeshed.list.client.impl.CellListImpl;
-import com.google.gwt.core.client.GWT;
-import com.google.gwt.dom.client.Document;
-import com.google.gwt.dom.client.Element;
-import com.google.gwt.dom.client.EventTarget;
-import com.google.gwt.dom.client.TableCellElement;
-import com.google.gwt.dom.client.TableElement;
-import com.google.gwt.dom.client.TableRowElement;
-import com.google.gwt.dom.client.TableSectionElement;
-import com.google.gwt.resources.client.ClientBundle;
-import com.google.gwt.resources.client.CssResource;
-import com.google.gwt.resources.client.ImageResource;
-import com.google.gwt.resources.client.ImageResource.ImageOptions;
-import com.google.gwt.resources.client.ImageResource.RepeatStyle;
-import com.google.gwt.user.client.Event;
-import com.google.gwt.user.client.ui.Widget;
-import com.google.gwt.view.client.PagingListView;
-import com.google.gwt.view.client.ProvidesKey;
-import com.google.gwt.view.client.Range;
-import com.google.gwt.view.client.SelectionModel;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * A list view that supports paging and columns.
- *
- * @param <T> the data type of each row
- */
-public class CellTable<T> extends Widget implements PagingListView<T> {
-
- /**
- * The default page size.
- */
- private static final int DEFAULT_PAGESIZE = 15;
-
- /**
- * Styles used by this widget.
- */
- public static interface Style extends CssResource {
-
- /**
- * Applied to every cell.
- */
- String cell();
-
- /**
- * Applied to the table.
- */
- String cellTable();
-
- /**
- * Applied to even rows.
- */
- String evenRow();
-
- /**
- * Applied to the first column.
- */
- String firstColumn();
-
- /**
- * Applied to the first column footers.
- */
- String firstColumnFooter();
-
- /**
- * Applied to the first column headers.
- */
- String firstColumnHeader();
-
- /**
- * Applied to footers cells.
- */
- String footer();
-
- /**
- * Applied to headers cells.
- */
- String header();
-
- /**
- * Applied to the hovered row.
- */
- String hoveredRow();
-
- /**
- * Applied to odd rows.
- */
- String oddRow();
-
- /**
- * Applied to selected rows.
- */
- String selectedRow();
- }
-
- /**
- * A ClientBundle that provides images for this widget.
- */
- public static interface Resources extends ClientBundle {
-
- /**
- * The background used for header cells.
- */
- @ImageOptions(repeatStyle = RepeatStyle.Horizontal)
- ImageResource cellTableHeaderBackground();
-
- /**
- * The background used for footer cells.
- */
- @Source("cellTableHeaderBackground.png")
- @ImageOptions(repeatStyle = RepeatStyle.Horizontal)
- ImageResource cellTableFooterBackground();
-
- /**
- * The background used for selected cells.
- */
- @Source("cellListSelectedBackground.png")
- @ImageOptions(repeatStyle = RepeatStyle.Horizontal)
- ImageResource cellTableSelectedBackground();
-
- /**
- * The styles used in this widget.
- */
- @Source("CellTable.css")
- Style cellTableStyle();
- }
-
- private static Resources DEFAULT_RESOURCES;
-
- private static Resources getDefaultResources() {
- if (DEFAULT_RESOURCES == null) {
- DEFAULT_RESOURCES = GWT.create(Resources.class);
- }
- return DEFAULT_RESOURCES;
- }
-
- private List<Column<T, ?>> columns = new ArrayList<Column<T, ?>>();
- private List<Header<?>> footers = new ArrayList<Header<?>>();
- private List<Header<?>> headers = new ArrayList<Header<?>>();
-
- /**
- * Set to true when the footer is stale.
- */
- private boolean headersStale;
-
- private TableRowElement hoveringRow;
- private final CellListImpl<T> impl;
-
- /**
- * If null, each T will be used as its own key.
- */
- private ProvidesKey<T> providesKey;
-
- /**
- * If true, enable selection via the mouse.
- */
- private boolean isSelectionEnabled;
-
- private final Style style;
- private final TableElement table;
- private final TableSectionElement tbody;
- private final TableSectionElement tfoot;
- private TableSectionElement thead;
-
- /**
- * Constructs a table with a default page size of 15.
- */
- public CellTable() {
- this(DEFAULT_PAGESIZE);
- }
-
- /**
- * Constructs a table with the given page size.
- *
- * @param pageSize the page size
- */
- public CellTable(final int pageSize) {
- this(pageSize, getDefaultResources());
- }
-
- /**
- * Constructs a table with the given page size with the specified
- * {@link Resources}.
- *
- * @param pageSize the page size
- * @param resources the resources to use for this widget
- */
- public CellTable(final int pageSize, Resources resources) {
- this.style = resources.cellTableStyle();
- this.style.ensureInjected();
-
- setElement(table = Document.get().createTableElement());
- table.setCellSpacing(0);
- thead = table.createTHead();
- table.appendChild(tbody = Document.get().createTBodyElement());
- tfoot = table.createTFoot();
- setStyleName(this.style.cellTable());
-
- // Create the implementation.
- this.impl = new CellListImpl<T>(this, pageSize, tbody) {
-
- private final TableElement tmpElem = Document.get().createTableElement();
-
- @Override
- public void setData(List<T> values, int start) {
- createHeadersAndFooters();
- super.setData(values, start);
- }
-
- @Override
- protected Element convertToElements(String html) {
- tmpElem.setInnerHTML("<tbody>" + html + "</tbody>");
- return tmpElem.getTBodies().getItem(0);
- }
-
- @Override
- protected boolean dependsOnSelection() {
- for (Column<T, ?> column : columns) {
- if (column.dependsOnSelection()) {
- return true;
- }
- }
- return false;
- }
-
- @Override
- protected void emitHtml(StringBuilder sb, List<T> values, int start,
- SelectionModel<? super T> selectionModel) {
- int length = values.size();
- int end = start + length;
- for (int i = start; i < end; i++) {
- T value = values.get(i - start);
- boolean isSelected = (selectionModel == null || value == null)
- ? false : selectionModel.isSelected(value);
- sb.append("<tr __idx='").append(i).append("'");
- sb.append(" class='");
- sb.append(i % 2 == 0 ? style.evenRow() : style.oddRow());
- if (isSelected) {
- sb.append(" ").append(style.selectedRow());
- }
- sb.append("'>");
- boolean first = true;
- for (Column<T, ?> column : columns) {
- // TODO(jlabanca): How do we sink ONFOCUS and ONBLUR?
- sb.append("<td class='").append(style.cell());
- if (first) {
- first = false;
- sb.append(" ").append(style.firstColumn());
- }
- sb.append("'>");
- if (value != null) {
- column.render(value, sb);
- }
- sb.append("</td>");
- }
- sb.append("</tr>");
- }
- }
-
- @Override
- protected void setSelected(Element elem, boolean selected) {
- setStyleName(elem, style.selectedRow(), selected);
- }
-
- @Override
- protected void updateSelection() {
- // Refresh headers.
- for (Header<?> header : headers) {
- if (header != null && header.dependsOnSelection()) {
- createHeaders(false);
- break;
- }
- }
-
- // Refresh footers.
- for (Header<?> footer : footers) {
- if (footer != null && footer.dependsOnSelection()) {
- createHeaders(true);
- break;
- }
- }
-
- // Update data.
- super.updateSelection();
- }
- };
-
- setPageSize(pageSize);
-
- // TODO: Total hack. It would almost definitely be preferable to sink only
- // those events actually needed by cells.
- sinkEvents(Event.ONCLICK | Event.MOUSEEVENTS | Event.KEYEVENTS
- | Event.ONCHANGE | Event.FOCUSEVENTS);
- }
-
- /**
- * Adds a column to the table.
- */
- public void addColumn(Column<T, ?> col) {
- addColumn(col, (Header<?>) null, (Header<?>) null);
- }
-
- /**
- * Adds a column to the table with an associated header.
- */
- public void addColumn(Column<T, ?> col, Header<?> header) {
- addColumn(col, header, null);
- }
-
- /**
- * Adds a column to the table with an associated header and footer.
- */
- public void addColumn(Column<T, ?> col, Header<?> header, Header<?> footer) {
- headers.add(header);
- footers.add(footer);
- columns.add(col);
- headersStale = true;
- refresh();
- }
-
- /**
- * Adds a column to the table with an associated String header.
- */
- public void addColumn(Column<T, ?> col, String headerString) {
- addColumn(col, new TextHeader(headerString), null);
- }
-
- /**
- * Adds a column to the table with an associated String header and footer.
- */
- public void addColumn(Column<T, ?> col, String headerString,
- String footerString) {
- addColumn(col, new TextHeader(headerString), new TextHeader(footerString));
- }
-
- // TODO: remove(Column)
-
- public int getBodyHeight() {
- int height = getClientHeight(tbody);
- return height;
- }
-
- public int getDataSize() {
- return impl.getDataSize();
- }
-
- public T getDisplayedItem(int indexOnPage) {
- if (indexOnPage < 0 || indexOnPage >= getNumDisplayedItems()) {
- throw new IndexOutOfBoundsException("indexOnPage = " + indexOnPage);
- }
- return impl.getData().get(indexOnPage);
- }
-
- public List<T> getDisplayedItems() {
- return new ArrayList<T>(impl.getData());
- }
-
- public int getHeaderHeight() {
- int height = getClientHeight(thead);
- return height;
- }
-
- public int getNumDisplayedItems() {
- return impl.getDisplayedItemCount();
- }
-
- public int getPageSize() {
- return impl.getPageSize();
- }
-
- public int getPageStart() {
- return impl.getPageStart();
- }
-
- public ProvidesKey<T> getProvidesKey() {
- return providesKey;
- }
-
- public Range getRange() {
- return impl.getRange();
- }
-
- public int getSize() {
- return impl.getDataSize();
- }
-
- /**
- * Check whether or not mouse selection is enabled.
- *
- * @return true if enabled, false if disabled
- */
- public boolean isSelectionEnabled() {
- return isSelectionEnabled;
- }
-
- @Override
- public void onBrowserEvent(Event event) {
- super.onBrowserEvent(event);
-
- // Find the cell where the event occurred.
- EventTarget eventTarget = event.getEventTarget();
- TableCellElement cell = null;
- if (eventTarget != null && Element.is(eventTarget)) {
- cell = findNearestParentCell(Element.as(eventTarget));
- }
- if (cell == null) {
- return;
- }
-
- // Forward the event to the associated header, footer, or column.
- TableRowElement tr = TableRowElement.as(cell.getParentElement());
- TableSectionElement section = TableSectionElement.as(tr.getParentElement());
- int col = cell.getCellIndex();
- if (section == thead) {
- Header<?> header = headers.get(col);
- if (header != null) {
- header.onBrowserEvent(cell, event);
- }
- } else if (section == tfoot) {
- Header<?> footer = footers.get(col);
- if (footer != null) {
- footer.onBrowserEvent(cell, event);
- }
- } else if (section == tbody) {
- int row = tr.getSectionRowIndex();
-
- if (event.getType().equals("mouseover")) {
- if (hoveringRow != null) {
- hoveringRow.removeClassName(style.hoveredRow());
- }
- hoveringRow = tr;
- tr.addClassName(style.hoveredRow());
- } else if (event.getType().equals("mouseout")) {
- hoveringRow = null;
- tr.removeClassName(style.hoveredRow());
- }
-
- T value = impl.getData().get(row);
- Column<T, ?> column = columns.get(col);
- column.onBrowserEvent(cell, impl.getPageStart() + row, value, event,
- providesKey);
-
- // Update selection.
- if (isSelectionEnabled && event.getTypeInt() == Event.ONMOUSEDOWN) {
- SelectionModel<? super T> selectionModel = impl.getSelectionModel();
- if (selectionModel != null) {
- selectionModel.setSelected(value, true);
- }
- }
- }
- }
-
- /**
- * Redraw the table using the existing data.
- */
- public void redraw() {
- impl.redraw();
- }
-
- /**
- * Redraw the table, requesting data from the delegate.
- */
- public void refresh() {
- impl.refresh();
- }
-
- public void refreshFooters() {
- createHeaders(true);
- }
-
- public void refreshHeaders() {
- createHeaders(false);
- }
-
- public void setData(int start, int length, List<T> values) {
- impl.setData(values, start);
- }
-
- public void setDataSize(int size, boolean isExact) {
- impl.setDataSize(size);
- }
-
- public void setDelegate(Delegate<T> delegate) {
- impl.setDelegate(delegate);
- }
-
- public void setPager(PagingListView.Pager<T> pager) {
- impl.setPager(pager);
- }
-
- /**
- * Set the number of rows per page and refresh the table.
- *
- * @param pageSize the page size
- *
- * @throw {@link IllegalArgumentException} if pageSize is negative or 0
- */
- public void setPageSize(int pageSize) {
- impl.setPageSize(pageSize);
- }
-
- /**
- * Set the starting index of the current visible page. The actual page start
- * will be clamped in the range [0, getSize() - 1].
- *
- * @param pageStart the index of the row that should appear at the start of
- * the page
- */
- public void setPageStart(int pageStart) {
- impl.setPageStart(pageStart);
- }
-
- /**
- * Sets the {@link ProvidesKey} instance that will be used to generate keys
- * for each record object as needed.
- *
- * @param providesKey an instance of {@link ProvidesKey} used to generate keys
- * for record objects.
- */
- // TODO - when is this valid? Do we rehash column view data if it changes?
- public void setProvidesKey(ProvidesKey<T> providesKey) {
- this.providesKey = providesKey;
- }
-
- /**
- * Enable mouse and keyboard selection.
- *
- * @param isSelectionEnabled true to enable, false to disable
- */
- public void setSelectionEnabled(boolean isSelectionEnabled) {
- this.isSelectionEnabled = isSelectionEnabled;
- }
-
- public void setSelectionModel(SelectionModel<? super T> selectionModel) {
- impl.setSelectionModel(selectionModel, true);
- }
-
- /**
- * Render the header of footer.
- *
- * @param isFooter true if this is the footer table, false if the header table
- */
- private void createHeaders(boolean isFooter) {
- List<Header<?>> theHeaders = isFooter ? footers : headers;
- TableSectionElement section = isFooter ? tfoot : thead;
- String className = isFooter ? style.footer() : style.header();
-
- boolean hasHeader = false;
- StringBuilder sb = new StringBuilder();
- sb.append("<tr>");
- boolean first = true;
- for (Header<?> header : theHeaders) {
- sb.append("<th class='").append(className);
- if (first) {
- first = false;
- sb.append(" ");
- sb.append(isFooter ? style.firstColumnFooter()
- : style.firstColumnHeader());
- }
- sb.append("'>");
- if (header != null) {
- hasHeader = true;
- header.render(sb);
- }
- sb.append("</th>");
- }
- sb.append("</tr>");
-
- section.setInnerHTML(sb.toString());
-
- // If the section isn't used, hide it.
- setVisible(section, hasHeader);
- }
-
- private void createHeadersAndFooters() {
- if (headersStale) {
- headersStale = false;
- createHeaders(false);
- createHeaders(true);
- }
- }
-
- private TableCellElement findNearestParentCell(Element elem) {
- while ((elem != null) && (elem != table)) {
- // TODO: We need is() implementations in all Element subclasses.
- // This would allow us to use TableCellElement.is() -- much cleaner.
- String tagName = elem.getTagName();
- if ("td".equalsIgnoreCase(tagName) || "th".equalsIgnoreCase(tagName)) {
- return elem.cast();
- }
- elem = elem.getParentElement();
- }
- return null;
- }
-
- private native int getClientHeight(Element element) /*-{
- return element.clientHeight;
- }-*/;
-}
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/client/Column.java b/bikeshed/src/com/google/gwt/bikeshed/list/client/Column.java
deleted file mode 100644
index 089c005..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/client/Column.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.bikeshed.list.client;
-
-import com.google.gwt.cell.client.Cell;
-import com.google.gwt.cell.client.FieldUpdater;
-import com.google.gwt.cell.client.HasCell;
-import com.google.gwt.cell.client.ValueUpdater;
-import com.google.gwt.dom.client.Element;
-import com.google.gwt.dom.client.NativeEvent;
-import com.google.gwt.view.client.HasViewData;
-import com.google.gwt.view.client.ProvidesKey;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * A representation of a column in a table. The column may maintain view data
- * for each cell on demand. New view data, if needed, is created by the cell's
- * onBrowserEvent method, stored in the Column, and passed to future calls to
- * Cell's {@link Cell#onBrowserEvent} and @link{Cell#render} methods.
- *
- * @param <T> the row type
- * @param <C> the column type
- */
-// TODO - when can we get rid of a view data object?
-// TODO - should viewData implement some interface? (e.g., with
-// commit/rollback/dispose)
-// TODO - have a ViewDataColumn superclass / SimpleColumn subclass
-public abstract class Column<T, C> implements HasViewData, HasCell<T, C> {
-
- protected final Cell<C> cell;
-
- protected FieldUpdater<T, C> fieldUpdater;
-
- protected Map<Object, Object> viewDataMap = new HashMap<Object, Object>();
-
- public Column(Cell<C> cell) {
- this.cell = cell;
- }
-
- public boolean consumesEvents() {
- return cell.consumesEvents();
- }
-
- /**
- * Returns true if the contents of the column may depend on the current state
- * of the selection model associated with the table that is displaying this
- * column. The default implementation returns false.
- */
- public boolean dependsOnSelection() {
- return false;
- }
-
- public Cell<C> getCell() {
- return cell;
- }
-
- public FieldUpdater<T, C> getFieldUpdater() {
- return fieldUpdater;
- }
-
- public abstract C getValue(T object);
-
- public Object getViewData(Object key) {
- return viewDataMap.get(key);
- }
-
- /**
- * @param providesKey an instance of ProvidesKey<T>, or null if the record
- * object should act as its own key.
- */
- public void onBrowserEvent(Element elem, final int index, final T object,
- NativeEvent event, ProvidesKey<T> providesKey) {
- Object key = providesKey == null ? object : providesKey.getKey(object);
- Object viewData = viewDataMap.get(key);
- Object newViewData = cell.onBrowserEvent(elem, getValue(object), viewData,
- event, fieldUpdater == null ? null : new ValueUpdater<C>() {
- public void update(C value) {
- fieldUpdater.update(index, object, value);
- }
- });
- if (newViewData != viewData) {
- viewDataMap.put(key, newViewData);
- }
- }
-
- public void render(T object, StringBuilder sb) {
- cell.render(getValue(object), viewDataMap.get(object), sb);
- }
-
- public void setFieldUpdater(FieldUpdater<T, C> fieldUpdater) {
- this.fieldUpdater = fieldUpdater;
- }
-
- public void setViewData(Object key, Object viewData) {
- viewDataMap.put(key, viewData);
- }
-}
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/client/Header.java b/bikeshed/src/com/google/gwt/bikeshed/list/client/Header.java
deleted file mode 100644
index 7183768..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/client/Header.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.bikeshed.list.client;
-
-import com.google.gwt.cell.client.Cell;
-import com.google.gwt.cell.client.ValueUpdater;
-import com.google.gwt.dom.client.Element;
-import com.google.gwt.dom.client.NativeEvent;
-
-/**
- * A table column header or footer.
- *
- * @param <H> the {#link Cell} type
- */
-public abstract class Header<H> {
-
- private final Cell<H> cell;
-
- private ValueUpdater<H> updater;
-
- public Header(Cell<H> cell) {
- this.cell = cell;
- }
-
- public boolean dependsOnSelection() {
- return false;
- }
-
- public abstract H getValue();
-
- public void onBrowserEvent(Element elem, NativeEvent event) {
- cell.onBrowserEvent(elem, getValue(), null, event, updater);
- }
-
- public void render(StringBuilder sb) {
- cell.render(getValue(), null, sb);
- }
-
- public void setUpdater(ValueUpdater<H> updater) {
- this.updater = updater;
- }
-}
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/client/IdentityColumn.java b/bikeshed/src/com/google/gwt/bikeshed/list/client/IdentityColumn.java
deleted file mode 100644
index c70f600..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/client/IdentityColumn.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.bikeshed.list.client;
-
-import com.google.gwt.cell.client.Cell;
-
-/**
- * A passthrough column, useful for giving cells access to the entire row
- * object.
- *
- * @param <T> the row type
- */
-public class IdentityColumn<T> extends Column<T, T> {
-
- /**
- * @param cell
- */
- public IdentityColumn(Cell<T> cell) {
- super(cell);
- }
-
- @Override
- public T getValue(T object) {
- return object;
- }
-}
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/client/PageSizePager.java b/bikeshed/src/com/google/gwt/bikeshed/list/client/PageSizePager.java
deleted file mode 100644
index b4ae081..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/client/PageSizePager.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.bikeshed.list.client;
-
-import com.google.gwt.event.dom.client.ClickEvent;
-import com.google.gwt.event.dom.client.ClickHandler;
-import com.google.gwt.user.client.ui.Anchor;
-import com.google.gwt.user.client.ui.Composite;
-import com.google.gwt.user.client.ui.FlexTable;
-import com.google.gwt.view.client.PagingListView;
-import com.google.gwt.view.client.PagingListView.Pager;
-
-/**
- * A simple {@link Pager} that controls the page size.
- *
- * @param <T> the data type of list items
- */
-public class PageSizePager<T> extends Composite implements Pager<T> {
-
- /**
- * The increment by which to grow or shrink the page size.
- */
- private final int increment;
-
- /**
- * The main layout widget.
- */
- private final FlexTable layout = new FlexTable();
-
- // TODO(jlabanca): I18N button text.
- private final Anchor showMoreButton = new Anchor("Show More");
- private final Anchor showLessButton = new Anchor("Show Less");
-
- public PageSizePager(final PagingListView<T> listView, final int increment) {
- this.increment = increment;
- initWidget(layout);
- layout.setCellPadding(0);
- layout.setCellSpacing(0);
-
- // Show more button.
- showMoreButton.addClickHandler(new ClickHandler() {
- public void onClick(ClickEvent event) {
- int pageSize = Math.min(listView.getPageSize() + increment,
- listView.getDataSize());
- listView.setPageSize(pageSize);
- }
- });
- showLessButton.addClickHandler(new ClickHandler() {
- public void onClick(ClickEvent event) {
- int pageSize = Math.max(listView.getPageSize() - increment, increment);
- listView.setPageSize(pageSize);
- }
- });
-
- // Add the buttons to the pager.
- layout.setWidget(0, 0, showLessButton);
- layout.setText(0, 1, " | ");
- layout.setWidget(0, 2, showMoreButton);
-
- // Update the button state.
- listView.setPager(this);
- onRangeOrSizeChanged(listView);
- }
-
- public void onRangeOrSizeChanged(PagingListView<T> listView) {
- // Assumes a page start index of 0.
- boolean hasLess = listView.getPageSize() > increment;
- boolean hasMore = listView.getPageSize() < listView.getDataSize();
- showLessButton.setVisible(hasLess);
- showMoreButton.setVisible(hasMore);
- layout.setText(0, 1, (hasLess && hasMore) ? " | " : "");
- }
-}
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/client/SimplePager.css b/bikeshed/src/com/google/gwt/bikeshed/list/client/SimplePager.css
deleted file mode 100644
index 82bf184..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/client/SimplePager.css
+++ /dev/null
@@ -1,14 +0,0 @@
-.pageDetails {
- padding: 4px 8px;
- text-align: center;
-}
-
-.button {
- padding: 4px;
- cursor: pointer;
- cursor: hand;
-}
-
-.disabledButton {
- cursor: default;
-}
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/client/SimplePager.java b/bikeshed/src/com/google/gwt/bikeshed/list/client/SimplePager.java
deleted file mode 100644
index 9e06cfb..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/client/SimplePager.java
+++ /dev/null
@@ -1,305 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.bikeshed.list.client;
-
-import com.google.gwt.core.client.GWT;
-import com.google.gwt.event.dom.client.ClickEvent;
-import com.google.gwt.event.dom.client.ClickHandler;
-import com.google.gwt.resources.client.ClientBundle;
-import com.google.gwt.resources.client.CssResource;
-import com.google.gwt.resources.client.ImageResource;
-import com.google.gwt.user.client.ui.HasVerticalAlignment;
-import com.google.gwt.user.client.ui.HorizontalPanel;
-import com.google.gwt.user.client.ui.Image;
-import com.google.gwt.user.client.ui.Label;
-import com.google.gwt.view.client.PagingListView;
-
-/**
- * A pager for controlling a {@link PagingListView} that only supports simple
- * page navigation.
- *
- * @param <T> the type of the PagingListView being controlled
- */
-public class SimplePager<T> extends AbstractPager<T> {
-
- /**
- * The location of the text relative to the paging buttons.
- */
- public static enum TextLocation {
- LEFT, RIGHT, CENTER;
- }
-
- /**
- * A ClientBundle that provides images for this widget.
- */
- public static interface Resources extends ClientBundle {
-
- /**
- * The image used to go to the first page.
- */
- ImageResource simplePagerFirstPage();
-
- /**
- * The disabled first page image.
- */
- ImageResource simplePagerFirstPageDisabled();
-
- /**
- * The image used to go to the last page.
- */
- ImageResource simplePagerLastPage();
-
- /**
- * The disabled last page image.
- */
- ImageResource simplePagerLastPageDisabled();
-
- /**
- * The image used to go to the next page.
- */
- ImageResource simplePagerNextPage();
-
- /**
- * The disabled next page image.
- */
- ImageResource simplePagerNextPageDisabled();
-
- /**
- * The image used to go to the previous page.
- */
- ImageResource simplePagerPreviousPage();
-
- /**
- * The disabled previous page image.
- */
- ImageResource simplePagerPreviousPageDisabled();
-
- /**
- * The styles used in this widget.
- */
- @Source("SimplePager.css")
- Style simplePagerStyle();
- }
-
- /**
- * Styles used by this widget.
- */
- public static interface Style extends CssResource {
-
- /**
- * Applied to buttons.
- */
- String button();
-
- /**
- * Applied to disabled buttons.
- */
- String disabledButton();
-
- /**
- * Applied to the details text.
- */
- String pageDetails();
- }
-
- private static Resources DEFAULT_RESOURCES;
-
- private static Resources getDefaultResources() {
- if (DEFAULT_RESOURCES == null) {
- DEFAULT_RESOURCES = GWT.create(Resources.class);
- }
- return DEFAULT_RESOURCES;
- }
-
- private final Image firstPage;
- private final Label label = new Label();
- private final Image lastPage;
-
- /**
- * Set to true when the next and last buttons are disabled.
- */
- private boolean nextDisabled;
-
- private final Image nextPage;
-
- /**
- * Set to true when the prev and first buttons are disabled.
- */
- private boolean prevDisabled;
-
- private final Image prevPage;
-
- /**
- * The {@link Resources} used by this widget.
- */
- private final Resources resources;
-
- /**
- * The {@link Style} used by this widget.
- */
- private final Style style;
-
- /**
- * Construct a {@link SimplePager}.
- *
- * @param view the {@link PagingListView} to page
- */
- public SimplePager(PagingListView<T> view) {
- this(view, TextLocation.CENTER);
- }
-
- /**
- * Construct a {@link SimplePager} with the specified text location.
- *
- * @param view the {@link PagingListView} to page
- * @param location the location of the text relative to the buttons
- */
- public SimplePager(PagingListView<T> view, TextLocation location) {
- this(view, location, getDefaultResources());
- }
-
- /**
- * Construct a {@link SimplePager} with the specified resources.
- *
- * @param view the {@link PagingListView} to page
- * @param location the location of the text relative to the buttons
- * @param resources the {@link Resources} to use
- */
- public SimplePager(PagingListView<T> view, TextLocation location,
- Resources resources) {
- super(view);
- this.resources = resources;
- this.style = resources.simplePagerStyle();
- this.style.ensureInjected();
-
- // Create the buttons.
- firstPage = new Image(resources.simplePagerFirstPage());
- lastPage = new Image(resources.simplePagerLastPage());
- nextPage = new Image(resources.simplePagerNextPage());
- prevPage = new Image(resources.simplePagerPreviousPage());
-
- // Add handlers.
- firstPage.addClickHandler(new ClickHandler() {
- public void onClick(ClickEvent event) {
- firstPage();
- }
- });
- lastPage.addClickHandler(new ClickHandler() {
- public void onClick(ClickEvent event) {
- lastPage();
- }
- });
- nextPage.addClickHandler(new ClickHandler() {
- public void onClick(ClickEvent event) {
- nextPage();
- }
- });
- prevPage.addClickHandler(new ClickHandler() {
- public void onClick(ClickEvent event) {
- previousPage();
- }
- });
-
- // Construct the widget.
- HorizontalPanel layout = new HorizontalPanel();
- layout.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
- initWidget(layout);
- if (location == TextLocation.RIGHT) {
- layout.add(label);
- }
- layout.add(firstPage);
- layout.add(prevPage);
- if (location == TextLocation.CENTER) {
- layout.add(label);
- }
- layout.add(nextPage);
- layout.add(lastPage);
- if (location == TextLocation.LEFT) {
- layout.add(label);
- }
-
- // Add style names to the cells.
- firstPage.getElement().getParentElement().addClassName(style.button());
- prevPage.getElement().getParentElement().addClassName(style.button());
- label.getElement().getParentElement().addClassName(style.pageDetails());
- nextPage.getElement().getParentElement().addClassName(style.button());
- lastPage.getElement().getParentElement().addClassName(style.button());
- }
-
- @Override
- public void onRangeOrSizeChanged(PagingListView<T> listView) {
- super.onRangeOrSizeChanged(listView);
- label.setText(createText());
-
- // Update the prev and first buttons.
- boolean hasPrev = hasPreviousPage();
- if (hasPrev && prevDisabled) {
- prevDisabled = false;
- firstPage.setResource(resources.simplePagerFirstPage());
- prevPage.setResource(resources.simplePagerPreviousPage());
- firstPage.getElement().getParentElement().removeClassName(
- style.disabledButton());
- prevPage.getElement().getParentElement().removeClassName(
- style.disabledButton());
- } else if (!hasPrev && !prevDisabled) {
- prevDisabled = true;
- firstPage.setResource(resources.simplePagerFirstPageDisabled());
- prevPage.setResource(resources.simplePagerPreviousPageDisabled());
- firstPage.getElement().getParentElement().addClassName(
- style.disabledButton());
- prevPage.getElement().getParentElement().addClassName(
- style.disabledButton());
- }
-
- // Update the next and last buttons.
- if (isRangeLimited()) {
- boolean hasNext = hasNextPage();
- if (hasNext && nextDisabled) {
- nextDisabled = false;
- nextPage.setResource(resources.simplePagerNextPage());
- lastPage.setResource(resources.simplePagerLastPage());
- nextPage.getElement().getParentElement().removeClassName(
- style.disabledButton());
- lastPage.getElement().getParentElement().removeClassName(
- style.disabledButton());
- } else if (!hasNext && !nextDisabled) {
- nextDisabled = true;
- nextPage.setResource(resources.simplePagerNextPageDisabled());
- lastPage.setResource(resources.simplePagerLastPageDisabled());
- nextPage.getElement().getParentElement().addClassName(
- style.disabledButton());
- lastPage.getElement().getParentElement().addClassName(
- style.disabledButton());
- }
- }
- }
-
- /**
- * Get the text to display in the pager that reflects the state of the pager.
- *
- * @return the text
- */
- protected String createText() {
- // Default text is 1 based.
- PagingListView<T> view = getPagingListView();
- int pageStart = view.getPageStart() + 1;
- int pageSize = view.getPageSize();
- int dataSize = view.getDataSize();
- int endIndex = Math.min(dataSize, pageStart + pageSize - 1);
- endIndex = Math.max(pageStart, endIndex);
- return pageStart + "-" + endIndex + " of " + dataSize;
- }
-}
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/client/TextColumn.java b/bikeshed/src/com/google/gwt/bikeshed/list/client/TextColumn.java
deleted file mode 100644
index a799fec..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/client/TextColumn.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.bikeshed.list.client;
-
-import com.google.gwt.cell.client.TextCell;
-
-/**
- * A column that displays its contents with a {@link TextCell} and does not make
- * use of view data.
- *
- * @param <T> the row type
- */
-public abstract class TextColumn<T> extends Column<T, String> {
-
- public TextColumn() {
- super(new TextCell());
- }
-}
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/client/TextHeader.java b/bikeshed/src/com/google/gwt/bikeshed/list/client/TextHeader.java
deleted file mode 100644
index 222129d..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/client/TextHeader.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.bikeshed.list.client;
-
-import com.google.gwt.cell.client.TextCell;
-
-/**
- * A Header containing String data rendered by a TextCell.
- */
-public class TextHeader extends Header<String> {
-
- private String text;
-
- public TextHeader(String text) {
- super(new TextCell());
- this.text = text;
- }
-
- @Override
- public String getValue() {
- return text;
- }
-}
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/client/cellListSelectedBackground.png b/bikeshed/src/com/google/gwt/bikeshed/list/client/cellListSelectedBackground.png
deleted file mode 100644
index 108ea3f..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/client/cellListSelectedBackground.png
+++ /dev/null
Binary files differ
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/client/cellTableHeaderBackground.png b/bikeshed/src/com/google/gwt/bikeshed/list/client/cellTableHeaderBackground.png
deleted file mode 100644
index dab5a96..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/client/cellTableHeaderBackground.png
+++ /dev/null
Binary files differ
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/client/impl/CellListImpl.java b/bikeshed/src/com/google/gwt/bikeshed/list/client/impl/CellListImpl.java
deleted file mode 100644
index 1394532..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/client/impl/CellListImpl.java
+++ /dev/null
@@ -1,534 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.bikeshed.list.client.impl;
-
-import com.google.gwt.core.client.Scheduler;
-import com.google.gwt.dom.client.Document;
-import com.google.gwt.dom.client.Element;
-import com.google.gwt.event.shared.HandlerRegistration;
-import com.google.gwt.view.client.PagingListView;
-import com.google.gwt.view.client.Range;
-import com.google.gwt.view.client.SelectionModel;
-import com.google.gwt.view.client.AbstractListViewAdapter.DefaultRange;
-import com.google.gwt.view.client.ListView.Delegate;
-import com.google.gwt.view.client.PagingListView.Pager;
-import com.google.gwt.view.client.SelectionModel.SelectionChangeEvent;
-import com.google.gwt.view.client.SelectionModel.SelectionChangeHandler;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * Implementation of {@link com.google.gwt.bikeshed.list.client.CellList}. This
- * class is subject to change or deletion. Do not rely on this class.
- *
- * @param <T> the data type of items in the list
- */
-public abstract class CellListImpl<T> {
-
- /**
- * The Element that holds the rendered child items.
- */
- private final Element childContainer;
-
- /**
- * The local cache of data in the view. The 0th index in the list corresponds
- * to the data at pageStart.
- */
- private final List<T> data = new ArrayList<T>();
-
- private int dataSize;
-
- /**
- * A boolean indicating whether or not the data size has ever been set. If the
- * data size has never been set, then we will always pass it along to the
- * view.
- */
- private boolean dataSizeInitialized;
-
- private Delegate<T> delegate;
- private final PagingListView<T> listView;
- private Pager<T> pager;
-
- /**
- * The number of elements to show on the page.
- */
- private int pageSize;
-
- /**
- * The start index of the current page.
- */
- private int pageStart = 0;
-
- /**
- * Set to true when the page start changes, and we need to do a full refresh.
- */
- private boolean pageStartChanged;
-
- /**
- * Indicates whether or not a redraw is scheduled.
- */
- private boolean redrawScheduled;
-
- /**
- * The command used to refresh or redraw the page. If both are scheduled, the
- * refresh will take priority.
- */
- private final Scheduler.ScheduledCommand refreshCommand = new Scheduler.ScheduledCommand() {
- public void execute() {
- // We clear the variables before making the refresh/redraw call so another
- // refresh/redraw can be scheduled synchronously.
- boolean wasRefreshScheduled = refreshScheduled;
- boolean wasRedrawScheduled = redrawScheduled;
- refreshScheduled = false;
- redrawScheduled = false;
- if (wasRefreshScheduled && delegate != null) {
- // Refresh takes priority over redraw.
- delegate.onRangeChanged(listView);
- } else if (wasRedrawScheduled) {
- setData(data, pageStart);
- }
- }
- };
-
- /**
- * Indicates whether or not a refresh is scheduled.
- */
- private boolean refreshScheduled;
-
- private HandlerRegistration selectionHandler;
-
- /**
- * A local cache of the currently selected rows. We cannot track selected keys
- * instead because we might end up in an inconsistent state where we render a
- * subset of a list with duplicate values, styling a value in the subset but
- * not styling the duplicate value outside of the subset.
- */
- private final Set<Integer> selectedRows = new HashSet<Integer>();
-
- private SelectionModel<? super T> selectionModel;
-
- /**
- * The temporary element use to convert HTML to DOM.
- */
- private final Element tmpElem;
-
- public CellListImpl(PagingListView<T> listView, int pageSize,
- Element childContainer) {
- this.childContainer = childContainer;
- this.listView = listView;
- this.pageSize = pageSize;
- tmpElem = Document.get().createDivElement();
- }
-
- /**
- * Get the list of data within the current range. The data may not be
- * complete.
- *
- * @return the list of data
- */
- public List<T> getData() {
- return data;
- }
-
- /**
- * Get the overall data size.
- *
- * @return the data size
- */
- public int getDataSize() {
- return dataSize;
- }
-
- /**
- * Get the number of items that are within the current page and data range.
- *
- * @return the number of displayed items
- */
- public int getDisplayedItemCount() {
- return Math.min(pageSize, dataSize - pageStart);
- }
-
- /**
- * @return the page size
- */
- public int getPageSize() {
- return pageSize;
- }
-
- /**
- * @return the start index of the current page (inclusive)
- */
- public int getPageStart() {
- return pageStart;
- }
-
- /**
- * @return the range of data being displayed
- */
- public Range getRange() {
- return new DefaultRange(pageStart, pageSize);
- }
-
- public SelectionModel<? super T> getSelectionModel() {
- return selectionModel;
- }
-
- /**
- * Redraw the list with the current data.
- */
- public void redraw() {
- scheduleRefresh(true);
- }
-
- /**
- * Request data from the delegate.
- */
- public void refresh() {
- scheduleRefresh(false);
- }
-
- /**
- * Set the data in the list.
- *
- * @param values the new data
- * @param valuesStart the start index of the values
- */
- public void setData(List<T> values, int valuesStart) {
- int valuesLength = values.size();
- int valuesEnd = valuesStart + valuesLength;
-
- // Calculate the bounded start (inclusive) and end index (exclusive).
- int pageEnd = pageStart + pageSize;
- int boundedStart = Math.max(valuesStart, pageStart);
- int boundedEnd = Math.min(valuesEnd, pageEnd);
- if (boundedStart >= boundedEnd) {
- // The data is out of range for the current page.
- return;
- }
-
- // The data size must be at least as large as the data.
- if (valuesEnd > dataSize) {
- dataSize = valuesEnd;
- onSizeChanged();
- }
-
- // Create placeholders up to the specified index.
- int lastCacheIndex = pageStart + data.size();
- while (lastCacheIndex < boundedStart) {
- data.add(null);
- lastCacheIndex++;
- }
-
- // Insert the new values into the data array.
- for (int i = boundedStart; i < boundedEnd; i++) {
- T value = values.get(i - valuesStart);
- int dataIndex = i - pageStart;
- if (dataIndex < data.size()) {
- data.set(dataIndex, value);
- } else {
- data.add(value);
- }
-
- // Update our local cache of selected rows.
- if (selectionModel != null) {
- if (value != null && selectionModel.isSelected(value)) {
- selectedRows.add(i);
- } else {
- selectedRows.remove(i);
- }
- }
- }
-
- // Construct a run of elements within the range of the data and the page.
- boundedStart = pageStartChanged ? pageStart : boundedStart;
- List<T> boundedValues = data.subList(boundedStart - pageStart, boundedEnd
- - pageStart);
- int boundedSize = boundedValues.size();
- StringBuilder sb = new StringBuilder();
- emitHtml(sb, boundedValues, boundedStart, selectionModel);
-
- // Replace the DOM elements with the new rendered cells.
- int childCount = childContainer.getChildCount();
- if (boundedStart == pageStart
- && (boundedSize >= childCount || boundedSize >= getDisplayedItemCount())) {
- childContainer.setInnerHTML(sb.toString());
- } else {
- Element container = convertToElements(sb.toString());
- Element toReplace = null;
- int realStart = boundedStart - pageStart;
- if (realStart < childCount) {
- toReplace = childContainer.getChild(realStart).cast();
- }
- for (int i = boundedStart; i < boundedEnd; i++) {
- if (toReplace == null) {
- // The child will be removed from tmpElem, so always use index 0.
- childContainer.appendChild(container.getChild(0));
- } else {
- Element nextSibling = toReplace.getNextSiblingElement();
- childContainer.replaceChild(container.getChild(0), toReplace);
- toReplace = nextSibling;
- }
- }
- }
-
- // Reset the pageStartChanged boolean.
- pageStartChanged = false;
- }
-
- /**
- * Set the overall size of the list.
- *
- * @param size the overall size
- */
- public void setDataSize(int size) {
- if (dataSizeInitialized && size == this.dataSize) {
- return;
- }
- dataSizeInitialized = true;
- this.dataSize = size;
- updateDataAndView();
- onSizeChanged();
- }
-
- public void setDelegate(Delegate<T> delegate) {
- this.delegate = delegate;
- }
-
- public void setPager(PagingListView.Pager<T> pager) {
- this.pager = pager;
- }
-
- /**
- * Set the number of items to show on each page.
- *
- * @param pageSize the page size
- */
- public void setPageSize(int pageSize) {
- if (pageSize == this.pageSize) {
- return;
- }
- this.pageSize = pageSize;
- updateDataAndView();
- onSizeChanged();
- refresh();
- }
-
- /**
- * Set the start index of the range.
- *
- * @param pageStart the start index
- */
- public void setPageStart(int pageStart) {
- if (pageStart == this.pageStart) {
- return;
- } else if (pageStart > this.pageStart) {
- if (data.size() > pageStart - this.pageStart) {
- // Remove the data we no longer need.
- for (int i = this.pageStart; i < pageStart; i++) {
- data.remove(0);
- }
- } else {
- // We have no overlapping data, so just clear it.
- data.clear();
- }
- } else {
- if ((data.size() > 0) && (this.pageStart - pageStart < pageSize)) {
- // Insert null data at the beginning.
- for (int i = pageStart; i < this.pageStart; i++) {
- data.add(0, null);
- }
- } else {
- // We have no overlapping data, so just clear it.
- data.clear();
- }
- }
-
- // Update the start index.
- this.pageStart = pageStart;
- this.pageStartChanged = true;
- updateDataAndView();
- onSizeChanged();
-
- // Refresh the view with the data that is currently available.
- setData(data, pageStart);
-
- // Send a request for new data in the range.
- refresh();
- }
-
- /**
- * Set the {@link SelectionModel}, optionally triggering an update.
- *
- * @param selectionModel the new {@link SelectionModel}
- * @param updateSelection true to update selection
- */
- public void setSelectionModel(final SelectionModel<? super T> selectionModel,
- boolean updateSelection) {
- // Remove the old selection model.
- if (selectionHandler != null) {
- selectionHandler.removeHandler();
- selectionHandler = null;
- }
-
- // Set the new selection model.
- this.selectionModel = selectionModel;
- if (selectionModel != null) {
- selectionHandler = selectionModel.addSelectionChangeHandler(new SelectionChangeHandler() {
- public void onSelectionChange(SelectionChangeEvent event) {
- updateSelection();
- }
- });
- }
-
- // Update the current selection state based on the new model.
- if (updateSelection) {
- updateSelection();
- }
- }
-
- /**
- * Convert the specified HTML into DOM elements and return the parent of the
- * DOM elements.
- *
- * @param html the HTML to convert
- * @return the parent element
- */
- protected Element convertToElements(String html) {
- tmpElem.setInnerHTML(html);
- return tmpElem;
- }
-
- /**
- * Check whether or not the cells in the list depend on the selection state.
- *
- * @return true if cells depend on selection, false if not
- */
- protected abstract boolean dependsOnSelection();
-
- /**
- * Construct the HTML that represents the list of items.
- *
- * @param sb the {@link StringBuilder} to build into
- * @param values the values to render
- * @param start the start index
- * @param selectionModel the {@link SelectionModel}
- */
- protected abstract void emitHtml(StringBuilder sb, List<T> values, int start,
- SelectionModel<? super T> selectionModel);
-
- /**
- * Called when pageStart, pageSize, or data size changes.
- */
- protected void onSizeChanged() {
- // Inform the pager about a change in page start, page size, or data size
- if (pager != null) {
- pager.onRangeOrSizeChanged(listView);
- }
- }
-
- /**
- * Remove the last element from the list.
- */
- protected void removeLastItem() {
- childContainer.getLastChild().removeFromParent();
- }
-
- /**
- * Mark an element as selected or unselected. This is called when a cells
- * selection state changes, but the cell does not depend on selection.
- *
- * @param elem the element to modify
- * @param selected true if selected, false if not
- */
- protected abstract void setSelected(Element elem, boolean selected);
-
- /**
- * Update the table based on the current selection.
- */
- protected void updateSelection() {
- // Determine if our selection states are stale.
- boolean dependsOnSelection = dependsOnSelection();
- boolean refreshRequired = false;
- Element cellElem = childContainer.getFirstChildElement();
- int row = pageStart;
- for (T value : data) {
- boolean selected = selectionModel == null ? false
- : selectionModel.isSelected(value);
- if (selected != selectedRows.contains(row)) {
- refreshRequired = true;
- if (selected) {
- selectedRows.add(row);
- } else {
- selectedRows.remove(row);
- }
- if (!dependsOnSelection) {
- // The cell doesn't depend on selection, so we only need to update the
- // style.
- setSelected(cellElem, selected);
- }
- }
- cellElem = cellElem.getNextSiblingElement();
- row++;
- }
-
- // Refresh the entire list if needed.
- if (refreshRequired && dependsOnSelection) {
- setData(data, pageStart);
- }
- }
-
- /**
- * Schedule a redraw or refresh.
- *
- * @param redrawOnly if true, only schedule a redraw
- */
- private void scheduleRefresh(boolean redrawOnly) {
- if (!refreshScheduled && !redrawScheduled) {
- Scheduler.get().scheduleDeferred(refreshCommand);
- }
- if (redrawOnly) {
- redrawScheduled = true;
- } else {
- refreshScheduled = true;
- }
- }
-
- /**
- * Ensure that the data and the view are in a consistent state.
- */
- private void updateDataAndView() {
- // Update the data size.
- int expectedLastIndex = Math.max(0,
- Math.min(pageSize, dataSize - pageStart));
- int lastIndex = data.size() - 1;
- while (lastIndex >= expectedLastIndex) {
- data.remove(lastIndex);
- selectedRows.remove(lastIndex + pageStart);
- lastIndex--;
- }
-
- // Update the DOM.
- int expectedChildCount = data.size();
- int childCount = childContainer.getChildCount();
- while (childCount > expectedChildCount) {
- removeLastItem();
- childCount--;
- }
- }
-}
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/client/simplePagerFirstPage.png b/bikeshed/src/com/google/gwt/bikeshed/list/client/simplePagerFirstPage.png
deleted file mode 100644
index 13a2ba2..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/client/simplePagerFirstPage.png
+++ /dev/null
Binary files differ
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/client/simplePagerFirstPageDisabled.png b/bikeshed/src/com/google/gwt/bikeshed/list/client/simplePagerFirstPageDisabled.png
deleted file mode 100644
index 645d305..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/client/simplePagerFirstPageDisabled.png
+++ /dev/null
Binary files differ
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/client/simplePagerLastPage.png b/bikeshed/src/com/google/gwt/bikeshed/list/client/simplePagerLastPage.png
deleted file mode 100644
index db4f865..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/client/simplePagerLastPage.png
+++ /dev/null
Binary files differ
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/client/simplePagerLastPageDisabled.png b/bikeshed/src/com/google/gwt/bikeshed/list/client/simplePagerLastPageDisabled.png
deleted file mode 100644
index 72cea52..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/client/simplePagerLastPageDisabled.png
+++ /dev/null
Binary files differ
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/client/simplePagerNextPage.png b/bikeshed/src/com/google/gwt/bikeshed/list/client/simplePagerNextPage.png
deleted file mode 100644
index a0879b6..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/client/simplePagerNextPage.png
+++ /dev/null
Binary files differ
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/client/simplePagerNextPageDisabled.png b/bikeshed/src/com/google/gwt/bikeshed/list/client/simplePagerNextPageDisabled.png
deleted file mode 100644
index 9f40e91..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/client/simplePagerNextPageDisabled.png
+++ /dev/null
Binary files differ
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/client/simplePagerPreviousPage.png b/bikeshed/src/com/google/gwt/bikeshed/list/client/simplePagerPreviousPage.png
deleted file mode 100644
index d4f15a1..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/client/simplePagerPreviousPage.png
+++ /dev/null
Binary files differ
diff --git a/bikeshed/src/com/google/gwt/bikeshed/list/client/simplePagerPreviousPageDisabled.png b/bikeshed/src/com/google/gwt/bikeshed/list/client/simplePagerPreviousPageDisabled.png
deleted file mode 100644
index aca6318..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/list/client/simplePagerPreviousPageDisabled.png
+++ /dev/null
Binary files differ
diff --git a/bikeshed/src/com/google/gwt/bikeshed/tree/Tree.gwt.xml b/bikeshed/src/com/google/gwt/bikeshed/tree/Tree.gwt.xml
deleted file mode 100644
index 8b19a59..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/tree/Tree.gwt.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<!--
- Copyright 2010 Google Inc.
-
- Licensed under the Apache License, Version 2.0 (the "License"); you may not
- use this file except in compliance with the License. You may obtain a copy of
- the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- License for the specific language governing permissions and limitations under
- the License.
--->
-<module>
- <inherits name='com.google.gwt.user.User'/>
- <inherits name='com.google.gwt.cell.Cell'/>
- <inherits name='com.google.gwt.bikeshed.list.List'/>
- <source path="shared" />
- <source path="client" />
-</module>
diff --git a/bikeshed/src/com/google/gwt/bikeshed/tree/client/CellBrowser.css b/bikeshed/src/com/google/gwt/bikeshed/tree/client/CellBrowser.css
deleted file mode 100644
index 6c44ae6..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/tree/client/CellBrowser.css
+++ /dev/null
@@ -1,27 +0,0 @@
-.column {
-
-}
-
-.firstColumn {
-
-}
-
-.item {
- padding: 8px;
-}
-
-@sprite .openItem {
- gwt-image: 'cellBrowserOpenBackground';
- background-color: #7b7b7b;
- color: white;
- height: auto;
- overflow: auto;
-}
-
-@sprite .selectedItem {
- gwt-image: 'cellBrowserSelectedBackground';
- background-color: #628cd5;
- color: white;
- height: auto;
- overflow: auto;
-}
diff --git a/bikeshed/src/com/google/gwt/bikeshed/tree/client/CellBrowser.java b/bikeshed/src/com/google/gwt/bikeshed/tree/client/CellBrowser.java
deleted file mode 100644
index 6ec1b5d..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/tree/client/CellBrowser.java
+++ /dev/null
@@ -1,792 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.bikeshed.tree.client;
-
-import com.google.gwt.animation.client.Animation;
-import com.google.gwt.bikeshed.list.client.CellList;
-import com.google.gwt.bikeshed.list.client.PageSizePager;
-import com.google.gwt.cell.client.AbstractCell;
-import com.google.gwt.cell.client.Cell;
-import com.google.gwt.cell.client.ValueUpdater;
-import com.google.gwt.core.client.GWT;
-import com.google.gwt.dom.client.Document;
-import com.google.gwt.dom.client.Element;
-import com.google.gwt.dom.client.NativeEvent;
-import com.google.gwt.dom.client.Style.Overflow;
-import com.google.gwt.dom.client.Style.Position;
-import com.google.gwt.dom.client.Style.Unit;
-import com.google.gwt.dom.client.Style.Visibility;
-import com.google.gwt.resources.client.ClientBundle;
-import com.google.gwt.resources.client.CssResource;
-import com.google.gwt.resources.client.ImageResource;
-import com.google.gwt.resources.client.ImageResource.ImageOptions;
-import com.google.gwt.resources.client.ImageResource.RepeatStyle;
-import com.google.gwt.user.client.DOM;
-import com.google.gwt.user.client.Event;
-import com.google.gwt.user.client.ui.Composite;
-import com.google.gwt.user.client.ui.FlowPanel;
-import com.google.gwt.user.client.ui.HasAnimation;
-import com.google.gwt.user.client.ui.ProvidesResize;
-import com.google.gwt.user.client.ui.RequiresResize;
-import com.google.gwt.user.client.ui.ScrollPanel;
-import com.google.gwt.user.client.ui.SplitLayoutPanel;
-import com.google.gwt.user.client.ui.Widget;
-import com.google.gwt.view.client.ListView;
-import com.google.gwt.view.client.PagingListView;
-import com.google.gwt.view.client.ProvidesKey;
-import com.google.gwt.view.client.Range;
-import com.google.gwt.view.client.SelectionModel;
-import com.google.gwt.view.client.TreeViewModel;
-import com.google.gwt.view.client.PagingListView.Pager;
-import com.google.gwt.view.client.TreeViewModel.NodeInfo;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * A "browsable" view of a tree in which only a single node per level may be
- * open at one time.
- */
-public class CellBrowser extends Composite implements ProvidesResize,
- RequiresResize, HasAnimation {
-
- /**
- * A ClientBundle that provides images for this widget.
- */
- public static interface Resources extends ClientBundle {
-
- /**
- * An image indicating a closed branch.
- */
- ImageResource cellBrowserClosed();
-
- /**
- * An image indicating an open branch.
- */
- ImageResource cellBrowserOpen();
-
- /**
- * The background used for open items.
- */
- @ImageOptions(repeatStyle = RepeatStyle.Horizontal)
- ImageResource cellBrowserOpenBackground();
-
- /**
- * The background used for selected items.
- */
- @Source("../../list/client/cellListSelectedBackground.png")
- @ImageOptions(repeatStyle = RepeatStyle.Horizontal)
- ImageResource cellBrowserSelectedBackground();
-
- /**
- * The styles used in this widget.
- */
- @Source("CellBrowser.css")
- Style cellBrowserStyle();
- }
-
- /**
- * Styles used by this widget.
- */
- public static interface Style extends CssResource {
-
- /**
- * Applied to all columns.
- */
- String column();
-
- /**
- * Applied to the first column.
- */
- String firstColumn();
-
- /**
- * Applied to all list items.
- */
- String item();
-
- /***
- * Applied to open items.
- */
- String openItem();
-
- /***
- * Applied to selected items.
- */
- String selectedItem();
- }
-
- /**
- * We override the Resources in {@link CellList} so that the styles in
- * {@link CellList} don't conflict with the styles in {@link CellBrowser}.
- */
- static interface CellListResources extends CellList.Resources {
- @Source("CellBrowserOverride.css")
- CellList.Style cellListStyle();
- }
-
- /**
- * A wrapper around a cell that adds an open button.
- *
- * @param <C> the data type of the cell
- */
- private class CellDecorator<C> extends AbstractCell<C> {
-
- /**
- * The cell used to render the inner contents.
- */
- private final Cell<C> cell;
-
- /**
- * The level of this list view.
- */
- private final int level;
-
- /**
- * The key of the currently open item.
- */
- private Object openKey;
-
- /**
- * The key provider for the node.
- */
- private final ProvidesKey<C> providesKey;
-
- /**
- * The selection model for the node.
- */
- private final SelectionModel<? super C> selectionModel;
-
- /**
- * Construct a new {@link CellDecorator}.
- *
- * @param nodeInfo the {@link NodeInfo} associated with the cell
- * @param level the level of items rendered by this decorator
- */
- public CellDecorator(NodeInfo<C> nodeInfo, int level) {
- this.cell = nodeInfo.getCell();
- this.level = level;
- this.providesKey = nodeInfo.getProvidesKey();
- this.selectionModel = nodeInfo.getSelectionModel();
- }
-
- @Override
- public boolean consumesEvents() {
- return cell.consumesEvents();
- }
-
- @Override
- public boolean dependsOnSelection() {
- return cell.dependsOnSelection();
- }
-
- @Override
- public Object onBrowserEvent(Element parent, C value, Object viewData,
- NativeEvent event, ValueUpdater<C> valueUpdater) {
-
- // Fire the event to the inner cell.
- viewData = cell.onBrowserEvent(getCellParent(parent), value, viewData,
- event, valueUpdater);
-
- // Open child nodes.
- if (Event.getTypeInt(event.getType()) == Event.ONMOUSEDOWN) {
- trimToLevel(level);
-
- // Remove style from currently open item.
- Element curOpenItem = Document.get().getElementById(getOpenId());
- if (curOpenItem != null) {
- setElementOpenState(curOpenItem.getParentElement(), false);
- }
- openKey = null;
-
- // Save the key of the new open item and update the Element.
- if (!viewModel.isLeaf(value)) {
- NodeInfo<?> nodeInfo = viewModel.getNodeInfo(value);
- if (nodeInfo != null) {
- openKey = providesKey.getKey(value);
- setElementOpenState(parent, true);
- appendTreeNode(nodeInfo);
- }
- }
- }
-
- return viewData;
- }
-
- @Override
- public void render(C value, Object viewData, StringBuilder sb) {
- boolean isOpen = (openKey == null) ? false
- : openKey.equals(providesKey.getKey(value));
- boolean isSelected = (selectionModel == null) ? false
- : selectionModel.isSelected(value);
- sb.append("<div style='position:relative;padding-right:");
- sb.append(imageWidth);
- sb.append("px;'");
- sb.append(" class='").append(style.item());
- if (isOpen) {
- sb.append(" ").append(style.openItem());
- }
- if (isSelected) {
- sb.append(" ").append(style.selectedItem());
- }
- sb.append("'");
- if (isOpen) {
- sb.append(" id='").append(getOpenId()).append("'");
- }
- sb.append(">");
- if (isOpen) {
- sb.append(openImageHtml);
- } else if (viewModel.isLeaf(value)) {
- sb.append(LEAF_IMAGE);
- } else {
- sb.append(closedImageHtml);
- }
- sb.append("<div>");
- cell.render(value, viewData, sb);
- sb.append("</div></div>");
- }
-
- @Override
- public void setValue(Element parent, C value, Object viewData) {
- cell.setValue(getCellParent(parent), value, viewData);
- }
-
- /**
- * Get the parent element of the decorated cell.
- *
- * @param parent the parent of this cell
- * @return the decorated cell's parent
- */
- private Element getCellParent(Element parent) {
- return parent.getFirstChildElement().getChild(1).cast();
- }
-
- /**
- * Get the image element of the decorated cell.
- *
- * @param parent the parent of this cell
- * @return the image element
- */
- private Element getImageElement(Element parent) {
- return parent.getFirstChildElement().getFirstChildElement();
- }
-
- /**
- * Get the ID of the open element.
- *
- * @return the ID
- */
- private String getOpenId() {
- return uniqueId + "-" + level;
- }
-
- /**
- * Replace the image element of a cell and update the styles associated with
- * the open state.
- *
- * @param parent the parent element of the cell
- * @param open true if open, false if closed
- */
- private void setElementOpenState(Element parent, boolean open) {
- // Update the style name and ID.
- Element wrapper = parent.getFirstChildElement();
- if (open) {
- wrapper.addClassName(style.openItem());
- wrapper.setId(getOpenId());
- } else {
- wrapper.removeClassName(style.openItem());
- wrapper.setId("");
- }
-
- // Replace the image element.
- String html = open ? openImageHtml : closedImageHtml;
- Element tmp = Document.get().createDivElement();
- tmp.setInnerHTML(html);
- Element imageElem = tmp.getFirstChildElement();
- Element oldImg = getImageElement(parent);
- wrapper.replaceChild(imageElem, oldImg);
- }
- }
-
- /**
- * The animation used to scroll to the newly added list view.
- */
- private class ScrollAnimation extends Animation {
-
- /**
- * The starting scroll position.
- */
- private int startScrollLeft;
-
- /**
- * The ending scroll position.
- */
- private int targetScrollLeft;
-
- @Override
- protected void onComplete() {
- getElement().setScrollLeft(targetScrollLeft);
- }
-
- @Override
- protected void onUpdate(double progress) {
- int diff = targetScrollLeft - startScrollLeft;
- getElement().setScrollLeft(startScrollLeft + (int) (diff * progress));
- }
-
- void scrollToEnd() {
- Element elem = getElement();
- targetScrollLeft = elem.getScrollWidth() - elem.getClientWidth();
-
- if (isAnimationEnabled()) {
- // Animate the scrolling.
- startScrollLeft = elem.getScrollLeft();
- run(250);
- } else {
- // Scroll instantly.
- onComplete();
- }
- }
- }
-
- /**
- * A node in the tree.
- *
- * @param <C> the data type of the children of the node
- */
- private class TreeNode<C> {
- private CellDecorator<C> cell;
- private ListView<C> listView;
- private NodeInfo<C> nodeInfo;
- private Widget widget;
-
- /**
- * Construct a new {@link TreeNode}.
- *
- * @param nodeInfo the nodeInfo for the children nodes
- * @param listView the list view assocated with the node
- * @param widget the widget that represents the list view
- */
- public TreeNode(NodeInfo<C> nodeInfo, ListView<C> listView,
- CellDecorator<C> cell, Widget widget) {
- this.cell = cell;
- this.listView = listView;
- this.nodeInfo = nodeInfo;
- this.widget = widget;
- }
-
- /**
- * Get the {@link CellDecorator} used to render the node.
- *
- * @return the cell decorator
- */
- public CellDecorator<C> getCell() {
- return cell;
- }
-
- /**
- * Unregister the list view and remove it from the widget.
- */
- void cleanup() {
- listView.setSelectionModel(null);
- nodeInfo.unsetView();
- getSplitLayoutPanel().remove(widget);
- }
- }
-
- /**
- * The element used in place of an image when a node has no children.
- */
- private static final String LEAF_IMAGE = "<div style='position:absolute;display:none;'></div>";
-
- private static Resources DEFAULT_RESOURCES;
-
- /**
- * The override styles used in {@link CellList}.
- */
- private static CellListResources cellListResource;
-
- /**
- * Get the {@link CellList.Resources} overrides.
- */
- private static CellListResources getCellListResources() {
- if (cellListResource == null) {
- cellListResource = GWT.create(CellListResources.class);
- }
- return cellListResource;
- }
-
- private static Resources getDefaultResources() {
- if (DEFAULT_RESOURCES == null) {
- DEFAULT_RESOURCES = GWT.create(Resources.class);
- }
- return DEFAULT_RESOURCES;
- }
-
- /**
- * The animation used for scrolling.
- */
- private final ScrollAnimation animation = new ScrollAnimation();
-
- /**
- * The default width of new columns.
- */
- private int defaultWidth = 200;
-
- /**
- * The HTML used to generate the closed image.
- */
- private final String closedImageHtml;
-
- /**
- * The unique ID assigned to this tree widget.
- */
- private final String uniqueId = Document.get().createUniqueId();
-
- /**
- * A boolean indicating whether or not animations are enabled.
- */
- private boolean isAnimationEnabled;
-
- /**
- * The minimum width of new columns.
- */
- private int minWidth;
-
- /**
- * The maximum width of the open and closed images.
- */
- private final int imageWidth;
-
- /**
- * The HTML used to generate the open image.
- */
- private final String openImageHtml;
-
- /**
- * The styles used by this widget.
- */
- private final Style style;
-
- /**
- * The element used to maintain the scrollbar when columns are removed.
- */
- private Element scrollLock;
-
- /**
- * The visible {@link TreeNode}.
- */
- private final List<TreeNode<?>> treeNodes = new ArrayList<TreeNode<?>>();
-
- /**
- * The {@link TreeViewModel} that backs the tree.
- */
- private final TreeViewModel viewModel;
-
- /**
- * Construct a new {@link CellBrowser}.
- *
- * @param <T> the type of data in the root node
- * @param viewModel the {@link TreeViewModel} that backs the tree
- * @param rootValue the hidden root value of the tree
- */
- public <T> CellBrowser(TreeViewModel viewModel, T rootValue) {
- this(viewModel, rootValue, getDefaultResources());
- }
-
- /**
- * Construct a new {@link CellBrowser} with the specified {@link Resources}.
- *
- * @param <T> the type of data in the root node
- * @param viewModel the {@link TreeViewModel} that backs the tree
- * @param rootValue the hidden root value of the tree
- * @param resources the {@link Resources} used for images
- */
- public <T> CellBrowser(TreeViewModel viewModel, T rootValue,
- Resources resources) {
- this.viewModel = viewModel;
- this.style = resources.cellBrowserStyle();
- this.style.ensureInjected();
- initWidget(new SplitLayoutPanel());
- getElement().getStyle().setOverflow(Overflow.AUTO);
- setStyleName("gwt-SideBySideTreeView");
-
- // Initialize the open and close images strings.
- ImageResource treeOpen = resources.cellBrowserOpen();
- ImageResource treeClosed = resources.cellBrowserClosed();
- openImageHtml = getImageHtml(treeOpen);
- closedImageHtml = getImageHtml(treeClosed);
- imageWidth = Math.max(treeOpen.getWidth(), treeClosed.getWidth());
- minWidth = imageWidth + 20;
-
- // Add a placeholder to maintain the scroll width.
- scrollLock = Document.get().createDivElement();
- scrollLock.getStyle().setPosition(Position.ABSOLUTE);
- scrollLock.getStyle().setVisibility(Visibility.HIDDEN);
- scrollLock.getStyle().setZIndex(-32767);
- scrollLock.getStyle().setBackgroundColor("red");
- scrollLock.getStyle().setTop(0, Unit.PX);
- scrollLock.getStyle().setLeft(0, Unit.PX);
- scrollLock.getStyle().setHeight(1, Unit.PX);
- scrollLock.getStyle().setWidth(1, Unit.PX);
- getElement().appendChild(scrollLock);
-
- // Associate the first ListView with the rootValue.
- appendTreeNode(viewModel.getNodeInfo(rootValue));
-
- // Catch scroll events.
- sinkEvents(Event.ONSCROLL);
- }
-
- /**
- * Get the default width of new columns.
- *
- * @return the default width in pixels
- */
- public int getDefaultColumnWidth() {
- return defaultWidth;
- }
-
- /**
- * Get the minimum width of columns.
- *
- * @return the minimum width in pixels
- */
- public int getMinimumColumnWidth() {
- return minWidth;
- }
-
- public boolean isAnimationEnabled() {
- return isAnimationEnabled;
- }
-
- @Override
- public void onBrowserEvent(Event event) {
- switch (DOM.eventGetType(event)) {
- case Event.ONSCROLL:
- // Shorten the scroll bar is possible.
- adjustScrollLock();
- break;
- }
- super.onBrowserEvent(event);
- }
-
- public void onResize() {
- getSplitLayoutPanel().onResize();
- }
-
- public void setAnimationEnabled(boolean enable) {
- this.isAnimationEnabled = enable;
- }
-
- /**
- * Set the default width of new columns.
- *
- * @param width the default width in pixels
- */
- public void setDefaultColumnWidth(int width) {
- this.defaultWidth = width;
- }
-
- /**
- * Set the minimum width of columns.
- *
- * @param minWidth the minimum width in pixels
- */
- public void setMinimumColumnWidth(int minWidth) {
- this.minWidth = minWidth;
- }
-
- /**
- * Create a Pager to control the list view. The {@link ListView} must extend
- * {@link Widget}.
- *
- * @param <C> the item type in the list view
- * @param listView the list view to add paging too
- * @return the {@link Pager}
- */
- protected <C> Pager<C> createPager(PagingListView<C> listView) {
- return new PageSizePager<C>(listView, listView.getPageSize());
- }
-
- /**
- * Create a {@link PagingListView} that will display items. The
- * {@link PagingListView} must extend {@link Widget}.
- *
- * @param <C> the item type in the list view
- * @param nodeInfo the node info with child data
- * @param cell the cell to use in the list view
- * @return the {@link ListView}
- */
- protected <C> PagingListView<C> createPagingListView(NodeInfo<C> nodeInfo,
- Cell<C> cell) {
- CellList<C> pagingListView = new CellList<C>(cell, getCellListResources());
- pagingListView.setValueUpdater(nodeInfo.getValueUpdater());
- return pagingListView;
- }
-
- /**
- * Adjust the size of the scroll lock element based on the new position of the
- * scroll bar.
- */
- private void adjustScrollLock() {
- int scrollLeft = getElement().getScrollLeft();
- if (scrollLeft > 0) {
- int clientWidth = getElement().getClientWidth();
- scrollLock.getStyle().setWidth(scrollLeft + clientWidth, Unit.PX);
- } else {
- scrollLock.getStyle().setWidth(1.0, Unit.PX);
- }
- }
-
- /**
- * Create a new {@link TreeNode} and append it to the end of the LayoutPanel.
- *
- * @param <C> the data type of the children
- * @param nodeInfo the info about the node
- */
- private <C> void appendTreeNode(final NodeInfo<C> nodeInfo) {
- // Create the list view.
- final int level = treeNodes.size();
- final CellDecorator<C> cell = new CellDecorator<C>(nodeInfo, level);
- final PagingListView<C> listView = createPagingListView(nodeInfo, cell);
- assert (listView instanceof Widget) : "createPagingListView() must return a widget";
-
- // Create a pager and wrap the components in a scrollable container.
- ScrollPanel scrollable = new ScrollPanel();
- final Pager<C> pager = createPager(listView);
- if (pager != null) {
- assert (pager instanceof Widget) : "createPager() must return a widget";
- FlowPanel flowPanel = new FlowPanel();
- flowPanel.add((Widget) listView);
- flowPanel.add((Widget) pager);
- scrollable.setWidget(flowPanel);
- } else {
- scrollable.setWidget((Widget) listView);
- }
- scrollable.setStyleName(style.column());
- if (level == 0) {
- scrollable.addStyleName(style.firstColumn());
- }
-
- // Create a delegate list view so we can trap data changes.
- ListView<C> listViewDelegate = new ListView<C>() {
- public Range getRange() {
- return listView.getRange();
- }
-
- public void setData(int start, int length, List<C> values) {
- // Trim to the current level if the open node no longer exists.
- TreeNode<?> node = treeNodes.get(level);
- Object openKey = node.getCell().openKey;
- if (openKey != null) {
- boolean stillExists = false;
- ProvidesKey<C> keyProvider = nodeInfo.getProvidesKey();
- for (C value : values) {
- if (openKey.equals(keyProvider.getKey(value))) {
- stillExists = true;
- break;
- }
- }
- if (!stillExists) {
- trimToLevel(level);
- }
- }
-
- // Refresh the list.
- listView.setData(start, length, values);
- }
-
- public void setDataSize(int size, boolean isExact) {
- listView.setDataSize(size, isExact);
- }
-
- public void setDelegate(Delegate<C> delegate) {
- listView.setDelegate(delegate);
- }
-
- public void setSelectionModel(SelectionModel<? super C> selectionModel) {
- listView.setSelectionModel(selectionModel);
- }
- };
-
- // Create a TreeNode.
- TreeNode<C> treeNode = new TreeNode<C>(nodeInfo, listViewDelegate, cell,
- scrollable);
- treeNodes.add(treeNode);
-
- // Attach the view to the selection model and node info.
- listView.setSelectionModel(nodeInfo.getSelectionModel());
- nodeInfo.setView(listViewDelegate);
-
- // Add the ListView to the LayoutPanel.
- SplitLayoutPanel splitPanel = getSplitLayoutPanel();
- splitPanel.insertWest(scrollable, defaultWidth, null);
- splitPanel.setWidgetMinSize(scrollable, minWidth);
- splitPanel.forceLayout();
-
- // Scroll to the right.
- animation.scrollToEnd();
- }
-
- /**
- * Get the HTML representation of an image.
- *
- * @param res the {@link ImageResource} to render as HTML
- * @return the rendered HTML
- */
- private String getImageHtml(ImageResource res) {
- // Add the position and dimensions.
- StringBuilder sb = new StringBuilder();
- sb.append("<div style=\"position:absolute;right:0px;top:0px;height:100%;");
- sb.append("width:").append(res.getWidth()).append("px;");
-
- // Add the background, vertically centered.
- sb.append("background:url('").append(res.getURL()).append("') ");
- sb.append("no-repeat scroll center center transparent;");
-
- // Close the div and return.
- sb.append("\"></div>");
- return sb.toString();
- }
-
- /**
- * Get the {@link SplitLayoutPanel} used to lay out the views.
- *
- * @return the {@link SplitLayoutPanel}
- */
- private SplitLayoutPanel getSplitLayoutPanel() {
- return (SplitLayoutPanel) getWidget();
- }
-
- /**
- * Reduce the number of {@link ListView}s down to the specified level.
- *
- * @param level the level to trim to
- */
- private void trimToLevel(int level) {
- // Add a placeholder to maintain the same scroll width.
- adjustScrollLock();
-
- // Remove the listViews that are no longer needed.
- int curLevel = treeNodes.size() - 1;
- while (curLevel > level) {
- TreeNode<?> removed = treeNodes.remove(curLevel);
- removed.cleanup();
- curLevel--;
- }
- }
-}
diff --git a/bikeshed/src/com/google/gwt/bikeshed/tree/client/CellBrowserOverride.css b/bikeshed/src/com/google/gwt/bikeshed/tree/client/CellBrowserOverride.css
deleted file mode 100644
index 3793a83..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/tree/client/CellBrowserOverride.css
+++ /dev/null
@@ -1,15 +0,0 @@
-/**
- * The following overrides are used by CellBrowser to disable the styles used
- * in CellList.
- */
-.evenItem {
-
-}
-
-.oddItem {
-
-}
-
-.selectedItem {
-
-}
diff --git a/bikeshed/src/com/google/gwt/bikeshed/tree/client/CellTree.css b/bikeshed/src/com/google/gwt/bikeshed/tree/client/CellTree.css
deleted file mode 100644
index be6f2f9..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/tree/client/CellTree.css
+++ /dev/null
@@ -1,28 +0,0 @@
-.emptyMessage {
- padding-left: 16px;
- font-style: italic;
-}
-
-.item {
- padding: 4px 3px;
-}
-
-.itemImage {
- top: 2px !important;
-}
-
-.openItem {
-}
-
-@sprite .selectedItem {
- gwt-image: 'cellTreeSelectedBackground';
- background-color: #628cd5;
- color: white;
- height: auto;
- overflow: auto;
-}
-
-.showMoreButton {
- padding-left: 16px;
- outline: none;
-}
diff --git a/bikeshed/src/com/google/gwt/bikeshed/tree/client/CellTree.java b/bikeshed/src/com/google/gwt/bikeshed/tree/client/CellTree.java
deleted file mode 100644
index 7a53fc6..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/tree/client/CellTree.java
+++ /dev/null
@@ -1,631 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.bikeshed.tree.client;
-
-import com.google.gwt.animation.client.Animation;
-import com.google.gwt.core.client.GWT;
-import com.google.gwt.dom.client.Element;
-import com.google.gwt.dom.client.Style.Display;
-import com.google.gwt.dom.client.Style.Position;
-import com.google.gwt.dom.client.Style.Unit;
-import com.google.gwt.resources.client.ClientBundle;
-import com.google.gwt.resources.client.CssResource;
-import com.google.gwt.resources.client.ImageResource;
-import com.google.gwt.resources.client.ImageResource.ImageOptions;
-import com.google.gwt.resources.client.ImageResource.RepeatStyle;
-import com.google.gwt.user.client.Event;
-import com.google.gwt.user.client.ui.Composite;
-import com.google.gwt.user.client.ui.HasAnimation;
-import com.google.gwt.user.client.ui.SimplePanel;
-import com.google.gwt.view.client.TreeViewModel;
-
-import java.util.ArrayList;
-
-/**
- * A view of a tree.
- */
-public class CellTree extends Composite implements HasAnimation {
-
- /**
- * A node animation.
- */
- public abstract static class NodeAnimation extends Animation {
-
- /**
- * The default animation delay in milliseconds.
- */
- private static final int DEFAULT_ANIMATION_DURATION = 450;
-
- /**
- * The duration of the animation.
- */
- private int duration = DEFAULT_ANIMATION_DURATION;
-
- NodeAnimation() {
- }
-
- public int getDuration() {
- return duration;
- }
-
- public void setDuration(int duration) {
- this.duration = duration;
- }
-
- /**
- * Animate a tree node into its new state.
- *
- * @param node the node to animate
- * @param isAnimationEnabled true to animate
- */
- abstract void animate(CellTreeNodeView<?> node, boolean isAnimationEnabled);
- }
-
- /**
- * A ClientBundle that provides images for this widget.
- */
- public static interface Resources extends ClientBundle {
-
- /**
- * An image indicating a closed branch.
- */
- ImageResource cellTreeClosedItem();
-
- /**
- * An image indicating that a node is loading.
- */
- ImageResource cellTreeLoading();
-
- /**
- * An image indicating an open branch.
- */
- ImageResource cellTreeOpenItem();
-
- /**
- * The background used for selected items.
- */
- @Source("../../list/client/cellListSelectedBackground.png")
- @ImageOptions(repeatStyle = RepeatStyle.Horizontal)
- ImageResource cellTreeSelectedBackground();
-
- /**
- * The styles used in this widget.
- */
- @Source("CellTree.css")
- Style cellTreeStyle();
- }
-
- /**
- * A {@link NodeAnimation} that reveals the contents of child nodes.
- */
- public static class RevealAnimation extends NodeAnimation {
-
- /**
- * Create a new {@link RevealAnimation}.
- *
- * @return the new animation
- */
- public static RevealAnimation create() {
- return new RevealAnimation();
- }
-
- /**
- * The container that holds the content, includind the children.
- */
- Element contentContainer;
-
- /**
- * The target height when opening, the start height when closing.
- */
- int height;
-
- /**
- * True if the node is opening, false if closing.
- */
- boolean opening;
-
- /**
- * The container that holds the child container.
- */
- private Element animFrame;
-
- /**
- * The container that holds the children.
- */
- private Element childContainer;
-
- /**
- * Not instantiable.
- */
- private RevealAnimation() {
- }
-
- @Override
- protected void onComplete() {
- cleanup();
- }
-
- @Override
- protected void onStart() {
- if (opening) {
- animFrame.getStyle().setHeight(1.0, Unit.PX);
- animFrame.getStyle().clearDisplay();
- height = contentContainer.getScrollHeight();
- } else {
- height = contentContainer.getOffsetHeight();
- }
- }
-
- @Override
- protected void onUpdate(double progress) {
- if (opening) {
- double curHeight = progress * height;
- animFrame.getStyle().setHeight(curHeight, Unit.PX);
- } else {
- double curHeight = (1.0 - progress) * height;
- animFrame.getStyle().setHeight(curHeight, Unit.PX);
- }
- }
-
- /**
- * Animate a {@link CellTreeNodeView} into its new state.
- *
- * @param node the {@link CellTreeNodeView} to animate
- * @param isAnimationEnabled true to animate
- */
- @Override
- void animate(CellTreeNodeView<?> node, boolean isAnimationEnabled) {
- // Cancel any pending animations.
- cancel();
-
- // Initialize the fields.
- this.opening = node.isOpen();
- animFrame = node.ensureAnimationFrame();
- contentContainer = node.ensureContentContainer();
- childContainer = node.ensureChildContainer();
-
- if (isAnimationEnabled) {
- // Animated.
- int duration = getDuration();
- int childCount = childContainer.getChildCount();
- if (childCount < 4) {
- // Reduce the duration if there are less than four items or it will
- // look really slow.
- duration = (int) ((childCount / 4.0) * duration);
- }
- run(duration);
- } else {
- // Non animated.
- cleanup();
- }
- }
-
- /**
- * Put the node back into a clean state and clear fields.
- */
- private void cleanup() {
- if (opening) {
- animFrame.getStyle().clearDisplay();
- } else {
- animFrame.getStyle().setDisplay(Display.NONE);
- childContainer.setInnerHTML("");
- }
- animFrame.getStyle().clearHeight();
- this.contentContainer = null;
- this.childContainer = null;
- this.animFrame = null;
- }
- }
-
- /**
- * A {@link NodeAnimation} that slides children into view.
- */
- public static class SlideAnimation extends RevealAnimation {
- /**
- * Create a new {@link RevealAnimation}.
- *
- * @return the new animation
- */
- public static SlideAnimation create() {
- return new SlideAnimation();
- }
-
- /**
- * Not instantiable.
- */
- private SlideAnimation() {
- }
-
- @Override
- protected void onComplete() {
- contentContainer.getStyle().clearPosition();
- contentContainer.getStyle().clearTop();
- contentContainer.getStyle().clearWidth();
- super.onComplete();
- }
-
- @Override
- protected void onStart() {
- super.onStart();
- if (opening) {
- contentContainer.getStyle().setTop(-height, Unit.PX);
- } else {
- contentContainer.getStyle().setTop(0, Unit.PX);
- }
- contentContainer.getStyle().setPosition(Position.RELATIVE);
- }
-
- @Override
- protected void onUpdate(double progress) {
- super.onUpdate(progress);
- if (opening) {
- double curTop = (1.0 - progress) * -height;
- contentContainer.getStyle().setTop(curTop, Unit.PX);
- } else {
- double curTop = progress * -height;
- contentContainer.getStyle().setTop(curTop, Unit.PX);
- }
- }
- }
-
- /**
- * Styles used by this widget.
- */
- public static interface Style extends CssResource {
-
- /**
- * Applied to the empty message.
- */
- String emptyMessage();
-
- /**
- * Applied to tree items.
- */
- String item();
-
- /**
- * Applied to open/close icon.
- */
- String itemImage();
-
- /**
- * Applied to open tree items.
- */
- String openItem();
-
- /**
- * Applied to selected tree items.
- */
- String selectedItem();
-
- /**
- * Applied to the show more button.
- */
- String showMoreButton();
- }
-
- /**
- * The default number of children to show under a tree node.
- */
- private static final int DEFAULT_LIST_SIZE = 25;
-
- private static Resources DEFAULT_RESOURCES;
-
- private static Resources getDefaultResources() {
- if (DEFAULT_RESOURCES == null) {
- DEFAULT_RESOURCES = GWT.create(Resources.class);
- }
- return DEFAULT_RESOURCES;
- }
-
- /**
- * The animation.
- */
- private NodeAnimation animation;
-
- /**
- * The HTML used to generate the closed image.
- */
- private final String closedImageHtml;
-
- /**
- * The default number of children to display under each node.
- */
- private int defaultNodeSize = DEFAULT_LIST_SIZE;
-
- /**
- * The maximum width of the open and closed images.
- */
- private final int imageWidth;
-
- /**
- * Indicates whether or not animations are enabled.
- */
- private boolean isAnimationEnabled;
-
- /**
- * The HTML used to generate the loading image.
- */
- private final String loadingImageHtml;
-
- /**
- * The HTML used to generate the open image.
- */
- private final String openImageHtml;
-
- /**
- * The hidden root node in the tree.
- */
- private final CellTreeNodeView<?> rootNode;
-
- /**
- * The styles used by this widget.
- */
- private final Style style;
-
- /**
- * The {@link TreeViewModel} that backs the tree.
- */
- private final TreeViewModel viewModel;
-
- /**
- * Construct a new {@link CellTree}.
- *
- * @param <T> the type of data in the root node
- * @param viewModel the {@link TreeViewModel} that backs the tree
- * @param rootValue the hidden root value of the tree
- */
- public <T> CellTree(TreeViewModel viewModel, T rootValue) {
- this(viewModel, rootValue, getDefaultResources());
- }
-
- /**
- * Construct a new {@link CellTree}.
- *
- * @param <T> the type of data in the root node
- * @param viewModel the {@link TreeViewModel} that backs the tree
- * @param rootValue the hidden root value of the tree
- * @param resources the resources used to render the tree
- */
- public <T> CellTree(TreeViewModel viewModel, T rootValue,
- Resources resources) {
- this.viewModel = viewModel;
- this.style = resources.cellTreeStyle();
- this.style.ensureInjected();
- initWidget(new SimplePanel());
- setStyleName("gwt-StandardTreeView");
-
- // Initialize the open and close images strings.
- ImageResource treeOpen = resources.cellTreeOpenItem();
- ImageResource treeClosed = resources.cellTreeClosedItem();
- ImageResource treeLoading = resources.cellTreeLoading();
- openImageHtml = getImageHtml(treeOpen);
- closedImageHtml = getImageHtml(treeClosed);
- loadingImageHtml = getImageHtml(treeLoading);
- imageWidth = Math.max(Math.max(treeOpen.getWidth(), treeClosed.getWidth()),
- treeLoading.getWidth());
-
- // We use one animation for the entire tree.
- setAnimation(SlideAnimation.create());
-
- // Add event handlers.
- sinkEvents(Event.ONCLICK | Event.ONCHANGE | Event.MOUSEEVENTS);
-
- // Associate a view with the item.
- CellTreeNodeView<T> root = new CellTreeNodeView<T>(this, null, null,
- getElement(), rootValue);
- rootNode = root;
- root.setOpen(true);
- }
-
- /**
- * Get the animation used to open and close nodes in this tree if animations
- * are enabled.
- *
- * @return the animation
- * @see #isAnimationEnabled()
- */
- public NodeAnimation getAnimation() {
- return animation;
- }
-
- /**
- * Get the default maximum number of children to display under each tree node.
- *
- * @return the default node size
- */
- public int getDefaultNodeSize() {
- return defaultNodeSize;
- }
-
- public TreeViewModel getTreeViewModel() {
- return viewModel;
- }
-
- public boolean isAnimationEnabled() {
- return isAnimationEnabled;
- }
-
- @Override
- public void onBrowserEvent(Event event) {
- super.onBrowserEvent(event);
-
- Element target = event.getEventTarget().cast();
-
- ArrayList<Element> chain = new ArrayList<Element>();
- collectElementChain(chain, getElement(), target);
-
- CellTreeNodeView<?> nodeView = findItemByChain(chain, 0, rootNode);
- if (nodeView != null && nodeView != rootNode) {
- if ("click".equals(event.getType())) {
- // Open the node when the open image is clicked.
- Element showMoreElem = nodeView.getShowMoreElement();
- if (nodeView.getImageElement().isOrHasChild(target)) {
- nodeView.setOpen(!nodeView.isOpen());
- return;
- } else if (showMoreElem != null && showMoreElem.isOrHasChild(target)) {
- nodeView.showMore();
- return;
- }
- }
-
- // Forward the event to the cell.
- if (nodeView.getCellParent().isOrHasChild(target)) {
- boolean consumesEvent = nodeView.fireEventToCell(event);
- if (!consumesEvent && "click".equals(event.getType())) {
- nodeView.select();
- }
- }
- }
- }
-
- /**
- * Set the animation used to open and close nodes in this tree. You must call
- * {@link #setAnimationEnabled(boolean)} to enable or disable animation.
- *
- * @param animation a {@link NodeAnimation}
- * @see #setAnimationEnabled(boolean)
- */
- public void setAnimation(NodeAnimation animation) {
- assert animation != null : "animation cannot be null";
- this.animation = animation;
- }
-
- public void setAnimationEnabled(boolean enable) {
- this.isAnimationEnabled = enable;
- if (!enable && animation != null) {
- animation.cancel();
- }
- }
-
- /**
- * Set the default number of children to display beneath each child node. If
- * more nodes are available, a button will appear at the end of the list
- * allowing the user to show more items. Changing this value will not affect
- * tree nodes that are already open.
- *
- * @param defaultNodeSize the max
- */
- public void setDefaultNodeSize(int defaultNodeSize) {
- this.defaultNodeSize = defaultNodeSize;
- }
-
- /**
- * @return the HTML to render the closed image.
- */
- String getClosedImageHtml() {
- return closedImageHtml;
- }
-
- /**
- * Get the width required for the images.
- *
- * @return the maximum width required for images.
- */
- int getImageWidth() {
- return imageWidth;
- }
-
- /**
- * @return the HTML to render the loading image.
- */
- String getLoadingImageHtml() {
- return loadingImageHtml;
- }
-
- /**
- * @return the HTML to render the open image.
- */
- String getOpenImageHtml() {
- return openImageHtml;
- }
-
- /**
- * @return the Style used by the tree
- */
- Style getStyle() {
- return style;
- }
-
- /**
- * Animate the current state of a {@link CellTreeNodeView} in this tree.
- *
- * @param node the node to animate
- */
- void maybeAnimateTreeNode(CellTreeNodeView<?> node) {
- if (animation != null) {
- animation.animate(node, node.consumeAnimate() && isAnimationEnabled());
- }
- }
-
- /**
- * Collects parents going up the element tree, terminated at the tree root.
- */
- private void collectElementChain(ArrayList<Element> chain, Element hRoot,
- Element hElem) {
- if ((hElem == null) || (hElem == hRoot)) {
- return;
- }
-
- collectElementChain(chain, hRoot, hElem.getParentElement());
- chain.add(hElem);
- }
-
- private CellTreeNodeView<?> findItemByChain(ArrayList<Element> chain,
- int idx, CellTreeNodeView<?> parent) {
- if (idx == chain.size()) {
- return parent;
- }
-
- Element hCurElem = chain.get(idx);
- for (int i = 0, n = parent.getChildCount(); i < n; ++i) {
- CellTreeNodeView<?> child = parent.getChildNode(i);
- if (child.getElement() == hCurElem) {
- CellTreeNodeView<?> retItem = findItemByChain(chain, idx + 1, child);
- if (retItem == null) {
- return child;
- }
- return retItem;
- }
- }
-
- return findItemByChain(chain, idx + 1, parent);
- }
-
- /**
- * Get the HTML representation of an image.
- *
- * @param res the {@link ImageResource} to render as HTML
- * @return the rendered HTML
- */
- private String getImageHtml(ImageResource res) {
- StringBuilder sb = new StringBuilder();
- sb.append("<div class='").append(style.itemImage()).append("' ");
-
- // Add the position and dimensions.
- sb.append("style=\"position:absolute;left:0px;top:0px;");
- sb.append("height:").append(res.getHeight()).append("px;");
- sb.append("width:").append(res.getWidth()).append("px;");
-
- // Add the background, vertically centered.
- sb.append("background:url('").append(res.getURL()).append("') ");
- sb.append("no-repeat scroll center center transparent;");
-
- // Close the div and return.
- sb.append("\"></div>");
- return sb.toString();
- }
-}
diff --git a/bikeshed/src/com/google/gwt/bikeshed/tree/client/CellTreeNodeView.java b/bikeshed/src/com/google/gwt/bikeshed/tree/client/CellTreeNodeView.java
deleted file mode 100644
index 1b35306..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/tree/client/CellTreeNodeView.java
+++ /dev/null
@@ -1,698 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.bikeshed.tree.client;
-
-import com.google.gwt.bikeshed.list.client.impl.CellListImpl;
-import com.google.gwt.cell.client.Cell;
-import com.google.gwt.dom.client.AnchorElement;
-import com.google.gwt.dom.client.Document;
-import com.google.gwt.dom.client.Element;
-import com.google.gwt.dom.client.NativeEvent;
-import com.google.gwt.dom.client.Style.Display;
-import com.google.gwt.dom.client.Style.Overflow;
-import com.google.gwt.dom.client.Style.Position;
-import com.google.gwt.user.client.ui.UIObject;
-import com.google.gwt.view.client.TreeViewModel;
-import com.google.gwt.view.client.PagingListView;
-import com.google.gwt.view.client.ProvidesKey;
-import com.google.gwt.view.client.Range;
-import com.google.gwt.view.client.SelectionModel;
-import com.google.gwt.view.client.TreeViewModel.NodeInfo;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * A view of a tree node.
- *
- * @param <T> the type that this view contains
- */
-class CellTreeNodeView<T> extends UIObject {
-
- /**
- * The element used in place of an image when a node has no children.
- */
- private static final String LEAF_IMAGE = "<div style='position:absolute;display:none;'></div>";
-
- /**
- * Returns the element that parents the cell contents of the node.
- *
- * @param nodeElem the element that represents the node
- * @return the cell parent within the node
- */
- private static Element getCellParent(Element nodeElem) {
- return nodeElem.getChild(1).cast();
- }
-
- /**
- * Show or hide an element.
- *
- * @param element the element to show or hide
- * @param show true to show, false to hide
- */
- private static void showOrHide(Element element, boolean show) {
- if (show) {
- element.getStyle().clearDisplay();
- } else {
- element.getStyle().setDisplay(Display.NONE);
- }
- }
-
- /**
- * The {@link com.google.gwt.view.client.ListView ListView} used to
- * show children.
- *
- * @param <C> the child item type
- */
- private static class NodeListView<C> implements PagingListView<C> {
-
- private final int defaultPageSize;
- private final CellListImpl<C> impl;
- private CellTreeNodeView<?> nodeView;
- private Map<Object, CellTreeNodeView<?>> savedViews;
-
- public NodeListView(final NodeInfo<C> nodeInfo,
- final CellTreeNodeView<?> nodeView, int pageSize) {
- this.defaultPageSize = pageSize;
- this.nodeView = nodeView;
-
- final Cell<C> cell = nodeInfo.getCell();
- impl = new CellListImpl<C>(this, pageSize,
- nodeView.ensureChildContainer()) {
-
- @Override
- public void setData(List<C> values, int start) {
- nodeView.updateImage(false);
-
- // Ensure that we have a children array.
- if (nodeView.children == null) {
- nodeView.children = new ArrayList<CellTreeNodeView<?>>();
- }
-
- // Construct a map of former child views based on their value keys.
- int len = values.size();
- int end = start + len;
- int childCount = nodeView.getChildCount();
- Map<Object, CellTreeNodeView<?>> openNodes = new HashMap<Object, CellTreeNodeView<?>>();
- for (int i = start; i < end && i < childCount; i++) {
- CellTreeNodeView<?> child = nodeView.getChildNode(i);
- // Ignore child nodes that are closed.
- if (child.isOpen()) {
- openNodes.put(child.getValueKey(), child);
- }
- }
-
- // Hide the child container so we can animate it.
- if (nodeView.tree.isAnimationEnabled()) {
- nodeView.ensureAnimationFrame().getStyle().setDisplay(Display.NONE);
- }
-
- // Trim the saved views down to the children that still exists.
- ProvidesKey<C> providesKey = nodeInfo.getProvidesKey();
- savedViews = new HashMap<Object, CellTreeNodeView<?>>();
- for (C childValue : values) {
- // Remove any child elements that correspond to prior children
- // so the call to setInnerHtml will not destroy them
- Object key = providesKey.getKey(childValue);
- CellTreeNodeView<?> savedView = openNodes.remove(key);
- if (savedView != null) {
- savedView.ensureAnimationFrame().removeFromParent();
- savedViews.put(key, savedView);
- }
- }
-
- // Create the new cells.
- super.setData(values, start);
-
- // Create the child TreeNodeViews from the new elements.
- Element childElem = nodeView.ensureChildContainer().getFirstChildElement();
- for (int i = start; i < end; i++) {
- C childValue = values.get(i - start);
- CellTreeNodeView<C> child = nodeView.createTreeNodeView(nodeInfo,
- childElem, childValue, null);
- CellTreeNodeView<?> savedChild = savedViews.remove(providesKey.getKey(childValue));
- // Copy the saved child's state into the new child
- if (savedChild != null) {
- child.animationFrame = savedChild.animationFrame;
- child.contentContainer = savedChild.contentContainer;
- child.childContainer = savedChild.childContainer;
- child.children = savedChild.children;
- child.emptyMessageElem = savedChild.emptyMessageElem;
- child.nodeInfo = savedChild.nodeInfo;
- child.nodeInfoLoaded = savedChild.nodeInfoLoaded;
- child.open = savedChild.open;
- child.showMoreElem = savedChild.showMoreElem;
-
- // Swap the node view in the child. We reuse the same NodeListView
- // so that we don't have to unset and register a new view with the
- // NodeInfo.
- savedChild.listView.setNodeView(child);
-
- // Copy the child container element to the new child
- child.getElement().appendChild(savedChild.ensureAnimationFrame());
- }
-
- if (childCount > i) {
- if (savedChild == null) {
- // Cleanup the child node if we aren't going to reuse it.
- nodeView.children.get(i).cleanup();
- }
- nodeView.children.set(i, child);
- } else {
- nodeView.children.add(child);
- }
- childElem = childElem.getNextSiblingElement();
- }
-
- // Clear temporary state.
- savedViews = null;
-
- // Animate the child container open.
- if (nodeView.tree.isAnimationEnabled()) {
- nodeView.tree.maybeAnimateTreeNode(nodeView);
- }
- }
-
- @Override
- protected boolean dependsOnSelection() {
- return cell.dependsOnSelection();
- }
-
- @Override
- protected void emitHtml(StringBuilder sb, List<C> values, int start,
- SelectionModel<? super C> selectionModel) {
- String selectedStyle = nodeView.tree.getStyle().selectedItem();
- String itemStyle = nodeView.tree.getStyle().item();
- String openStyle = nodeView.tree.getStyle().openItem();
-
- ProvidesKey<C> providesKey = nodeInfo.getProvidesKey();
- TreeViewModel model = nodeView.tree.getTreeViewModel();
- int imageWidth = nodeView.tree.getImageWidth();
- for (C value : values) {
- Object key = providesKey.getKey(value);
- boolean isOpen = savedViews.containsKey(key);
- sb.append("<div style='position:relative;padding-left:");
- sb.append(imageWidth).append("px'>");
- if (isOpen) {
- sb.append(nodeView.tree.getOpenImageHtml());
- } else if (model.isLeaf(value)) {
- sb.append(LEAF_IMAGE);
- } else {
- sb.append(nodeView.tree.getClosedImageHtml());
- }
- sb.append("<div class='").append(itemStyle);
- if (isOpen) {
- sb.append(" ").append(openStyle);
- }
- if (selectionModel != null && selectionModel.isSelected(value)) {
- sb.append(" ").append(selectedStyle);
- }
- sb.append("'>");
- cell.render(value, null, sb);
- sb.append("</div></div>");
- }
- }
-
- @Override
- protected void removeLastItem() {
- CellTreeNodeView<?> child = nodeView.children.remove(nodeView.children.size() - 1);
- child.cleanup();
- super.removeLastItem();
- }
-
- @Override
- protected void setSelected(Element elem, boolean selected) {
- setStyleName(getCellParent(elem),
- nodeView.tree.getStyle().selectedItem(), selected);
- }
- };
-
- // Use a pager to update buttons.
- impl.setPager(new Pager<C>() {
- public void onRangeOrSizeChanged(PagingListView<C> listView) {
- // Assumes a page start of 0.
- int dataSize = impl.getDataSize();
- showOrHide(nodeView.showMoreElem, dataSize > impl.getPageSize());
- if (dataSize == 0) {
- showOrHide(nodeView.emptyMessageElem, true);
- nodeView.updateImage(false);
- } else {
- showOrHide(nodeView.emptyMessageElem, false);
- }
- }
- });
- }
-
- /**
- * Cleanup this node view.
- */
- public void cleanup() {
- impl.setSelectionModel(null, false);
- }
-
- public int getDataSize() {
- return impl.getDataSize();
- }
-
- public int getDefaultPageSize() {
- return defaultPageSize;
- }
-
- public int getPageSize() {
- return impl.getPageSize();
- }
-
- public int getPageStart() {
- return impl.getPageStart();
- }
-
- public Range getRange() {
- return impl.getRange();
- }
-
- public void setData(int start, int length, List<C> values) {
- impl.setData(values, start);
- }
-
- public void setDataSize(int size, boolean isExact) {
- impl.setDataSize(size);
- }
-
- public void setDelegate(Delegate<C> delegate) {
- impl.setDelegate(delegate);
- }
-
- public void setPager(Pager<C> pager) {
- impl.setPager(pager);
- }
-
- public void setPageSize(int pageSize) {
- impl.setPageSize(pageSize);
- }
-
- public void setPageStart(int pageStart) {
- impl.setPageStart(pageStart);
- }
-
- public void setSelectionModel(final SelectionModel<? super C> selectionModel) {
- impl.setSelectionModel(selectionModel, true);
- }
-
- /**
- * Assign this {@link PagingListView} to a new {@link CellTreeNodeView}.
- *
- * @param nodeView the new node view
- */
- private void setNodeView(CellTreeNodeView<?> nodeView) {
- this.nodeView.listView = null;
- this.nodeView = nodeView;
- nodeView.listView = this;
- }
- }
-
- /**
- * True during the time a node should be animated.
- */
- private boolean animate;
-
- /**
- * A reference to the element that is used to animate nodes. Parent of the
- * contentContainer.
- */
- private Element animationFrame;
-
- /**
- * A reference to the element that contains the children. Parent to the actual
- * child nodes.
- */
- private Element childContainer;
-
- /**
- * A list of child views.
- */
- private List<CellTreeNodeView<?>> children;
-
- /**
- * A reference to the element that contains all content. Parent of the
- * childContainer and the show/hide elements.
- */
- private Element contentContainer;
-
- /**
- * The element used when there are no children to display.
- */
- private Element emptyMessageElem;
-
- /**
- * The list view used to display the nodes.
- */
- private NodeListView<?> listView;
-
- /**
- * The info about children of this node.
- */
- private NodeInfo<?> nodeInfo;
-
- /**
- * Indicates whether or not we've loaded the node info.
- */
- private boolean nodeInfoLoaded;
-
- /**
- * Indicates whether or not this node is open.
- */
- private boolean open;
-
- /**
- * The parent {@link CellTreeNodeView}.
- */
- private final CellTreeNodeView<?> parentNode;
-
- /**
- * The {@link NodeInfo} of the parent node.
- */
- private final NodeInfo<T> parentNodeInfo;
-
- /**
- * The element used to display more children.
- */
- private AnchorElement showMoreElem;
-
- /**
- * The {@link CellTree} that this node belongs to.
- */
- private final CellTree tree;
-
- /**
- * This node's value.
- */
- private T value;
-
- /**
- * Construct a {@link CellTreeNodeView}.
- *
- * @param tree the parent {@link CellTreeNodeView}
- * @param parent the parent {@link CellTreeNodeView}
- * @param parentNodeInfo the {@link NodeInfo} of the parent
- * @param elem the outer element of this {@link CellTreeNodeView}
- * @param value the value of this node
- */
- CellTreeNodeView(final CellTree tree, final CellTreeNodeView<?> parent,
- NodeInfo<T> parentNodeInfo, Element elem, T value) {
- this.tree = tree;
- this.parentNode = parent;
- this.parentNodeInfo = parentNodeInfo;
- this.value = value;
- setElement(elem);
- }
-
- public int getChildCount() {
- return children == null ? 0 : children.size();
- }
-
- public CellTreeNodeView<?> getChildNode(int childIndex) {
- return children.get(childIndex);
- }
-
- /**
- * Check whether or not this node is open.
- *
- * @return true if open, false if closed
- */
- public boolean isOpen() {
- return open;
- }
-
- /**
- * Select this node.
- */
- public void select() {
- SelectionModel<? super T> selectionModel = parentNodeInfo.getSelectionModel();
- if (selectionModel != null) {
- selectionModel.setSelected(value, true);
- }
- }
-
- /**
- * Sets whether this item's children are displayed.
- *
- * @param open whether the item is open
- */
- public void setOpen(boolean open) {
- // Early out.
- if (this.open == open) {
- return;
- }
-
- this.animate = true;
- this.open = open;
- if (open) {
- if (!nodeInfoLoaded) {
- nodeInfoLoaded = true;
- nodeInfo = tree.getTreeViewModel().getNodeInfo(value);
- }
-
- // If we don't have any nodeInfo, we must be a leaf node.
- if (nodeInfo != null) {
- // Add a loading message.
- ensureChildContainer();
- showOrHide(showMoreElem, false);
- showOrHide(emptyMessageElem, false);
- if (!isRootNode()) {
- setStyleName(getCellParent(), tree.getStyle().openItem(), true);
- }
- ensureAnimationFrame().getStyle().setProperty("display", "");
- updateImage(true);
- onOpen(nodeInfo);
- }
- } else {
- if (!isRootNode()) {
- setStyleName(getCellParent(), tree.getStyle().openItem(), false);
- }
- cleanup();
- tree.maybeAnimateTreeNode(this);
- updateImage(false);
- }
- }
-
- /**
- * Unregister the list handler and destroy all child nodes.
- */
- protected void cleanup() {
- // Unregister the list handler.
- if (listView != null) {
- listView.cleanup();
- nodeInfo.unsetView();
- listView = null;
- }
-
- // Recursively kill children.
- if (children != null) {
- for (CellTreeNodeView<?> child : children) {
- child.cleanup();
- }
- children = null;
- }
- }
-
- protected boolean consumeAnimate() {
- boolean hasAnimate = animate;
- animate = false;
- return hasAnimate;
- }
-
- /**
- * Returns an instance of TreeNodeView of the same subclass as the calling
- * object.
- *
- * @param <C> the data type of the node's children
- * @param nodeInfo a NodeInfo object describing the child nodes
- * @param childElem the DOM element used to parent the new TreeNodeView
- * @param childValue the child's value
- * @param viewData view data associated with the node
- * @return a TreeNodeView of suitable type
- */
- protected <C> CellTreeNodeView<C> createTreeNodeView(NodeInfo<C> nodeInfo,
- Element childElem, C childValue, Object viewData) {
- return new CellTreeNodeView<C>(tree, this, nodeInfo, childElem, childValue);
- }
-
- /**
- * Fire an event to the {@link com.google.gwt.cell.client.AbstractCell}.
- *
- * @param event the native event
- * @return true if the cell consumes the event, false if not
- */
- protected boolean fireEventToCell(NativeEvent event) {
- if (parentNodeInfo != null) {
- Element cellParent = getCellParent();
- Cell<T> parentCell = parentNodeInfo.getCell();
- parentCell.onBrowserEvent(cellParent, value, null, event,
- parentNodeInfo.getValueUpdater());
- return parentCell.consumesEvents();
- }
- return false;
- }
-
- /**
- * Returns the element that parents the cell contents of this node.
- */
- protected Element getCellParent() {
- return getCellParent(getElement());
- }
-
- /**
- * Returns the element corresponding to the open/close image.
- *
- * @return the open/close image element
- */
- protected Element getImageElement() {
- return getElement().getFirstChildElement();
- }
-
- /**
- * Returns the key for the value of this node using the parent's
- * implementation of NodeInfo.getKey().
- */
- protected Object getValueKey() {
- return parentNodeInfo.getProvidesKey().getKey(value);
- }
-
- /**
- * Set up the node when it is opened.
- *
- * @param nodeInfo the {@link NodeInfo} that provides information about the
- * child values
- * @param <C> the child data type of the node
- */
- protected <C> void onOpen(final NodeInfo<C> nodeInfo) {
- NodeListView<C> view = new NodeListView<C>(nodeInfo, this,
- tree.getDefaultNodeSize());
- listView = view;
- view.setSelectionModel(nodeInfo.getSelectionModel());
- nodeInfo.setView(view);
- }
-
- /**
- * Ensure that the animation frame exists and return it.
- *
- * @return the animation frame
- */
- Element ensureAnimationFrame() {
- if (animationFrame == null) {
- animationFrame = Document.get().createDivElement();
- animationFrame.getStyle().setPosition(Position.RELATIVE);
- animationFrame.getStyle().setOverflow(Overflow.HIDDEN);
- animationFrame.setId("animFrame");
- getElement().appendChild(animationFrame);
- }
- return animationFrame;
- }
-
- /**
- * Ensure that the child container exists and return it.
- *
- * @return the child container
- */
- Element ensureChildContainer() {
- if (childContainer == null) {
- childContainer = Document.get().createDivElement();
- ensureContentContainer().insertFirst(childContainer);
- }
- return childContainer;
- }
-
- /**
- * Ensure that the content container exists and return it.
- *
- * @return the content container
- */
- Element ensureContentContainer() {
- if (contentContainer == null) {
- contentContainer = Document.get().createDivElement();
- ensureAnimationFrame().appendChild(contentContainer);
-
- // TODO(jlabanca): I18N no data string.
- emptyMessageElem = Document.get().createDivElement();
- emptyMessageElem.setInnerHTML("no data");
- setStyleName(emptyMessageElem, tree.getStyle().emptyMessage(), true);
- showOrHide(emptyMessageElem, false);
- contentContainer.appendChild(emptyMessageElem);
-
- showMoreElem = Document.get().createAnchorElement();
- showMoreElem.setHref("javascript:;");
- showMoreElem.setInnerText("Show more");
- setStyleName(showMoreElem, tree.getStyle().showMoreButton(), true);
- showOrHide(showMoreElem, false);
- contentContainer.appendChild(showMoreElem);
- }
- return contentContainer;
- }
-
- Element getShowMoreElement() {
- return showMoreElem;
- }
-
- void showFewer() {
- int defaultPageSize = listView.getDefaultPageSize();
- int maxSize = Math.max(defaultPageSize, listView.impl.getPageSize()
- - defaultPageSize);
- listView.impl.setPageSize(maxSize);
- }
-
- void showMore() {
- listView.impl.setPageSize(listView.impl.getPageSize()
- + listView.getDefaultPageSize());
- }
-
- /**
- * Check if this node is a root node.
- *
- * @return true if a root node
- */
- private boolean isRootNode() {
- return parentNode == null;
- }
-
- /**
- * Update the image based on the current state.
- *
- * @param isLoading true if still loading data
- */
- private void updateImage(boolean isLoading) {
- // Early out if this is a root node.
- if (isRootNode()) {
- return;
- }
-
- // Replace the image element with a new one.
- String html = tree.getClosedImageHtml();
- if (open) {
- html = isLoading ? tree.getLoadingImageHtml() : tree.getOpenImageHtml();
- }
- if (nodeInfoLoaded && nodeInfo == null) {
- html = LEAF_IMAGE;
- }
- Element tmp = Document.get().createDivElement();
- tmp.setInnerHTML(html);
- Element imageElem = tmp.getFirstChildElement();
-
- Element oldImg = getImageElement();
- oldImg.getParentElement().replaceChild(imageElem, oldImg);
- }
-}
diff --git a/bikeshed/src/com/google/gwt/bikeshed/tree/client/cellBrowserClosed.gif b/bikeshed/src/com/google/gwt/bikeshed/tree/client/cellBrowserClosed.gif
deleted file mode 100644
index 6e9a180..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/tree/client/cellBrowserClosed.gif
+++ /dev/null
Binary files differ
diff --git a/bikeshed/src/com/google/gwt/bikeshed/tree/client/cellBrowserOpen.gif b/bikeshed/src/com/google/gwt/bikeshed/tree/client/cellBrowserOpen.gif
deleted file mode 100644
index b891d9d..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/tree/client/cellBrowserOpen.gif
+++ /dev/null
Binary files differ
diff --git a/bikeshed/src/com/google/gwt/bikeshed/tree/client/cellBrowserOpenBackground.png b/bikeshed/src/com/google/gwt/bikeshed/tree/client/cellBrowserOpenBackground.png
deleted file mode 100644
index 1cbce6f..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/tree/client/cellBrowserOpenBackground.png
+++ /dev/null
Binary files differ
diff --git a/bikeshed/src/com/google/gwt/bikeshed/tree/client/cellTreeClosedItem.gif b/bikeshed/src/com/google/gwt/bikeshed/tree/client/cellTreeClosedItem.gif
deleted file mode 100644
index 7bda586..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/tree/client/cellTreeClosedItem.gif
+++ /dev/null
Binary files differ
diff --git a/bikeshed/src/com/google/gwt/bikeshed/tree/client/cellTreeLoading.gif b/bikeshed/src/com/google/gwt/bikeshed/tree/client/cellTreeLoading.gif
deleted file mode 100644
index c5fedc3..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/tree/client/cellTreeLoading.gif
+++ /dev/null
Binary files differ
diff --git a/bikeshed/src/com/google/gwt/bikeshed/tree/client/cellTreeOpenItem.gif b/bikeshed/src/com/google/gwt/bikeshed/tree/client/cellTreeOpenItem.gif
deleted file mode 100644
index 0fcf791..0000000
--- a/bikeshed/src/com/google/gwt/bikeshed/tree/client/cellTreeOpenItem.gif
+++ /dev/null
Binary files differ
diff --git a/bikeshed/src/com/google/gwt/requestfactory/shared/SyncResult.java b/bikeshed/src/com/google/gwt/requestfactory/shared/SyncResult.java
deleted file mode 100644
index 9af5329..0000000
--- a/bikeshed/src/com/google/gwt/requestfactory/shared/SyncResult.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.requestfactory.shared;
-
-import com.google.gwt.valuestore.shared.Record;
-
-import java.util.Map;
-
-/**
- * Result per record of a SyncRequest.
- */
-public interface SyncResult {
- boolean hasViolations();
-
- Record getRecord();
-
- Map<String, String> getViolations();
-}
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/StocksCommon.gwt.xml b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/StocksCommon.gwt.xml
deleted file mode 100644
index 394d1d2..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/StocksCommon.gwt.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 0.0.999//EN" "http://google-web-toolkit.googlecode.com/svn/tags/0.0.999/distro-source/core/src/gwt-module.dtd">
-<module>
- <inherits name='com.google.gwt.user.User'/>
- <inherits name='com.google.gwt.sample.bikeshed.style.Style'/>
- <inherits name='com.google.gwt.regexp.RegExp'/>
- <inherits name='com.google.gwt.bikeshed.list.List'/>
- <inherits name='com.google.gwt.bikeshed.tree.Tree'/>
-
- <source path='client'/>
- <source path='shared'/>
-</module>
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/StocksDesktop.gwt.xml b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/StocksDesktop.gwt.xml
deleted file mode 100644
index 6977c58..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/StocksDesktop.gwt.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 0.0.999//EN" "http://google-web-toolkit.googlecode.com/svn/tags/0.0.999/distro-source/core/src/gwt-module.dtd">
-<module rename-to='stocksdesktop'>
- <inherits name='com.google.gwt.sample.bikeshed.stocks.StocksCommon'/>
- <entry-point class='com.google.gwt.sample.bikeshed.stocks.client.StocksDesktop'/>
-</module>
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/StocksMobile.gwt.xml b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/StocksMobile.gwt.xml
deleted file mode 100644
index c6cfbcd..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/StocksMobile.gwt.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 0.0.999//EN" "http://google-web-toolkit.googlecode.com/svn/tags/0.0.999/distro-source/core/src/gwt-module.dtd">
-<module rename-to='stocksmobile'>
- <inherits name='com.google.gwt.sample.bikeshed.stocks.StocksCommon'/>
- <entry-point class='com.google.gwt.sample.bikeshed.stocks.client.StocksMobile'/>
-</module>
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/BuySellPopup.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/BuySellPopup.java
deleted file mode 100644
index 9fb028f..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/BuySellPopup.java
+++ /dev/null
@@ -1,188 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.client;
-
-import com.google.gwt.event.dom.client.ClickEvent;
-import com.google.gwt.event.dom.client.ClickHandler;
-import com.google.gwt.event.dom.client.KeyUpEvent;
-import com.google.gwt.event.dom.client.KeyUpHandler;
-import com.google.gwt.i18n.client.NumberFormat;
-import com.google.gwt.sample.bikeshed.stocks.shared.StockQuote;
-import com.google.gwt.sample.bikeshed.stocks.shared.Transaction;
-import com.google.gwt.user.client.Command;
-import com.google.gwt.user.client.DeferredCommand;
-import com.google.gwt.user.client.Window;
-import com.google.gwt.user.client.ui.Button;
-import com.google.gwt.user.client.ui.DialogBox;
-import com.google.gwt.user.client.ui.FlexTable;
-import com.google.gwt.user.client.ui.TextBox;
-
-/**
- * A popup used for purchasing stock.
- */
-public class BuySellPopup extends DialogBox {
-
- // Row numbers for popup fields
- private static final int TICKER = 0;
- private static final int NAME = 1;
- private static final int PRICE = 2;
- private static final int MAX_QUANTITY = 3;
- private static final int QUANTITY = 4;
- private static final int TOTAL = 5;
- private static final int AVAILABLE = 6;
- private static final int BUTTONS = 7;
-
- private int cash;
-
- /**
- * True if we are buying, false if hiding.
- */
- private boolean isBuying;
-
- /**
- * The table used for layout.
- */
- private FlexTable layout = new FlexTable();
-
- /**
- * The button used to buy or sell.
- */
- private Button opButton;
-
- /**
- * The box used to change the quantity.
- */
- private TextBox quantityBox = new TextBox();
-
- private StockQuote quote;
-
- /**
- * The last transaction.
- */
- private Transaction transaction;
-
- public BuySellPopup() {
- super(false, true);
- setGlassEnabled(true);
- setWidget(layout);
-
- layout.setHTML(TICKER, 0, "<b>Ticker:</b>");
- layout.setHTML(NAME, 0, "<b>Name:</b>");
- layout.setHTML(PRICE, 0, "<b>Price:</b>");
- layout.setHTML(MAX_QUANTITY, 0, "<b>Max Quantity:</b>");
- layout.setHTML(QUANTITY, 0, "<b>Quantity:</b>");
- layout.setWidget(QUANTITY, 1, quantityBox);
- layout.setHTML(TOTAL, 0, "<b>Total:</b>");
- layout.setHTML(AVAILABLE, 0, "<b>Available:</b>");
-
- // Update total price when the quantity changes.
- quantityBox.addKeyUpHandler(new KeyUpHandler() {
- public void onKeyUp(KeyUpEvent event) {
- try {
- String text = quantityBox.getText();
- int quantity = text.length() == 0 ? 0 : Integer.parseInt(text);
- double totalPrice = quantity * quote.getPrice() / 100.0;
- layout.setText(TOTAL, 1, NumberFormat.getCurrencyFormat("USD").format(
- totalPrice));
- } catch (NumberFormatException e) {
- layout.setText(TOTAL, 1, "Invalid quantity");
- }
- }
- });
-
- // Buy Button.
- opButton = new Button("", new ClickHandler() {
- public void onClick(ClickEvent event) {
- try {
- int quantity = Integer.parseInt(quantityBox.getText());
- transaction = new Transaction(isBuying, quote.getTicker(), quantity);
- hide();
- } catch (NumberFormatException e) {
- Window.alert("You must enter a valid quantity");
- }
- }
- });
- layout.setWidget(BUTTONS, 0, opButton);
-
- // Cancel Button.
- Button cancelButton = new Button("Cancel", new ClickHandler() {
- public void onClick(ClickEvent event) {
- hide();
- }
- });
- layout.setWidget(BUTTONS, 1, cancelButton);
- }
-
- public StockQuote getStockQuote() {
- return quote;
- }
-
- /**
- * Get the last transaction.
- *
- * @return the last transaction, or null if canceled
- */
- public Transaction getTransaction() {
- return transaction;
- }
-
- /**
- * Set the available cash.
- *
- * @param cash the available cash
- */
- public void setAvailableCash(int cash) {
- // TODO: Bind the available cash field.
- this.cash = cash;
- layout.setText(AVAILABLE, 1, NumberFormat.getCurrencyFormat("USD").format(cash / 100.0));
- }
-
- /**
- * Set the current {@link StockQuote}.
- *
- * @param quote the stock quote to buy
- * @param isBuying true if buying the stock
- */
- public void setStockQuote(StockQuote quote, boolean isBuying) {
- this.quote = quote;
- String op = isBuying ? "Buy" : "Sell";
- setText(op + " " + quote.getTicker() + " (" + quote.getName() + ")");
- layout.setText(TICKER, 1, quote.getTicker());
- layout.setText(NAME, 1, quote.getName());
- layout.setText(PRICE, 1, quote.getDisplayPrice());
- if (isBuying) {
- layout.setText(MAX_QUANTITY, 1, "" + cash / quote.getPrice());
- } else {
- layout.setText(MAX_QUANTITY, 1, "" + quote.getSharesOwned());
- }
- layout.setText(TOTAL, 1, NumberFormat.getCurrencyFormat("USD").format(0.0));
- quantityBox.setText("0");
- opButton.setText(op);
- this.isBuying = isBuying;
- transaction = null;
- }
-
- @Override
- protected void onLoad() {
- super.onLoad();
- DeferredCommand.addCommand(new Command() {
- public void execute() {
- quantityBox.selectAll();
- quantityBox.setFocus(true);
- }
- });
- }
-}
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/ChangeCell.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/ChangeCell.java
deleted file mode 100644
index 79dd6b7..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/ChangeCell.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.client;
-
-import com.google.gwt.cell.client.AbstractCell;
-
-/**
- * A cell that represents a
- * {@link com.google.gwt.sample.bikeshed.stocks.shared.StockQuote StockQuote}.
- */
-public class ChangeCell extends AbstractCell<String> {
-
- @Override
- public void render(String value, Object viewData, StringBuilder sb) {
- if (value == null || value.length() == 0) {
- return;
- }
- sb.append("<span style=\"color:");
- if (value.charAt(0) == '-') {
- sb.append("red\">");
- } else {
- sb.append("green\">");
- }
- sb.append(value);
- sb.append("</span>");
- }
-}
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/Columns.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/Columns.java
deleted file mode 100644
index 9667b2b..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/Columns.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.client;
-
-import com.google.gwt.bikeshed.list.client.Column;
-import com.google.gwt.cell.client.ButtonCell;
-import com.google.gwt.cell.client.CheckboxCell;
-import com.google.gwt.cell.client.CurrencyCell;
-import com.google.gwt.cell.client.TextCell;
-import com.google.gwt.sample.bikeshed.stocks.shared.StockQuote;
-import com.google.gwt.sample.bikeshed.stocks.shared.Transaction;
-
-/**
- * Column definitions for the stock demo.
- */
-public class Columns {
-
- static Column<StockQuote, String> buyColumn = new Column<StockQuote, String>(
- new ButtonCell()) {
- @Override
- public String getValue(StockQuote object) {
- return "Buy";
- }
- };
-
- static Column<StockQuote, String> changeColumn = new Column<StockQuote, String>(
- new ChangeCell()) {
- @Override
- public String getValue(StockQuote object) {
- return object.getChange();
- }
- };
-
- static Column<StockQuote, Integer> dollarsColumn = new Column<StockQuote, Integer>(
- new CurrencyCell()) {
- @Override
- public Integer getValue(StockQuote object) {
- return object.getPrice() * object.getSharesOwned();
- }
- };
-
- static Column<StockQuote, Boolean> favoriteColumn = new Column<StockQuote, Boolean>(
- new CheckboxCell()) {
- @Override
- public Boolean getValue(StockQuote object) {
- return object.isFavorite();
- }
- };
-
- // TODO - use an ellipsis cell
- static HighlightingTextCell nameCell = new HighlightingTextCell();
-
- static Column<StockQuote, String> nameColumn = new Column<StockQuote, String>(
- nameCell) {
- @Override
- public String getValue(StockQuote object) {
- return object.getName();
- }
- };
-
- static Column<StockQuote, Integer> priceColumn = new Column<StockQuote, Integer>(
- new CurrencyCell()) {
- @Override
- public Integer getValue(StockQuote object) {
- return object.getPrice();
- }
- };
-
- static Column<StockQuote, Integer> profitLossColumn = new Column<StockQuote, Integer>(
- new ProfitLossCell()) {
- @Override
- public Integer getValue(StockQuote object) {
- return object.getValue() - object.getTotalPaid();
- }
- };
-
- static Column<StockQuote, String> sellColumn = new Column<StockQuote, String>(
- new ButtonCell()) {
- @Override
- public String getValue(StockQuote object) {
- return "Sell";
- }
- };
-
- static TextCell textCell = new TextCell();
-
- static Column<StockQuote, String> sharesColumn =
- new Column<StockQuote, String>(textCell) {
- @Override
- public String getValue(StockQuote object) {
- return "" + object.getSharesOwned();
- }
- };
-
- static Column<Transaction, String> subtotalColumn =
- new Column<Transaction, String>(textCell) {
- @Override
- public String getValue(Transaction object) {
- int price = object.getActualPrice() * object.getQuantity();
- return (object.isBuy() ? " (" : " ")
- + StocksDesktop.getFormattedPrice(price) + (object.isBuy() ? ")" : "");
- }
- };
-
- static Column<StockQuote, String> tickerColumn =
- new Column<StockQuote, String>(textCell) {
- @Override
- public String getValue(StockQuote object) {
- return object.getTicker();
- }
- };
-
- static Column<Transaction, String> transactionColumn =
- new Column<Transaction, String>(textCell) {
- @Override
- public String getValue(Transaction object) {
- return object.toString();
- }
- };
-}
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/FavoritesWidget.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/FavoritesWidget.java
deleted file mode 100644
index 811be2a..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/FavoritesWidget.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.client;
-
-import com.google.gwt.bikeshed.list.client.CellTable;
-import com.google.gwt.core.client.GWT;
-import com.google.gwt.sample.bikeshed.stocks.shared.StockQuote;
-import com.google.gwt.uibinder.client.UiBinder;
-import com.google.gwt.uibinder.client.UiFactory;
-import com.google.gwt.uibinder.client.UiField;
-import com.google.gwt.user.client.ui.Composite;
-import com.google.gwt.user.client.ui.Widget;
-import com.google.gwt.view.client.AbstractListViewAdapter;
-
-/**
- * Widget for favorite stocks.
- */
-public class FavoritesWidget extends Composite {
-
- interface Binder extends UiBinder<Widget, FavoritesWidget> { }
- private static final Binder binder = GWT.create(Binder.class);
-
- @UiField CellTable<StockQuote> table;
-
- private final AbstractListViewAdapter<StockQuote> adapter;
-
- public FavoritesWidget(AbstractListViewAdapter<StockQuote> adapter) {
- this.adapter = adapter;
- initWidget(binder.createAndBindUi(this));
-
- table.addColumn(Columns.tickerColumn, "ticker");
- table.addColumn(Columns.priceColumn, "price");
- table.addColumn(Columns.changeColumn, "change");
- table.addColumn(Columns.sharesColumn, "shares");
- table.addColumn(Columns.dollarsColumn, "value");
- table.addColumn(Columns.profitLossColumn, "profit/loss");
- table.addColumn(Columns.buyColumn);
- table.addColumn(Columns.sellColumn);
- }
-
- @UiFactory
- CellTable<StockQuote> createTable() {
- CellTable<StockQuote> view = new CellTable<StockQuote>(10);
- adapter.addView(view);
- return view;
- }
-}
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/FavoritesWidget.ui.xml b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/FavoritesWidget.ui.xml
deleted file mode 100644
index 837443c..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/FavoritesWidget.ui.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<ui:UiBinder
- xmlns:ui='urn:ui:com.google.gwt.uibinder'
- xmlns:g='urn:import:com.google.gwt.user.client.ui'
- xmlns:l='urn:import:com.google.gwt.bikeshed.list.client'
- xmlns:t='urn:import:com.google.gwt.bikeshed.tree.client'
- xmlns:s='urn:import:com.google.gwt.sample.bikeshed.stocks.client'>
-
- <ui:with field='styles'
- type='com.google.gwt.sample.bikeshed.style.client.Styles'/>
-
- <g:DockLayoutPanel unit='EM'>
- <g:north size='2'>
- <g:Label styleName='{styles.common.headerLeft}'>Portfolio / Favorites</g:Label>
- </g:north>
-
- <g:center>
- <g:ScrollPanel>
- <l:CellTable ui:field='table' styleName='{styles.common.table}'/>
- </g:ScrollPanel>
- </g:center>
- </g:DockLayoutPanel>
-</ui:UiBinder>
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/HighlightingTextCell.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/HighlightingTextCell.java
deleted file mode 100644
index 3acd2c7..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/HighlightingTextCell.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.client;
-
-import com.google.gwt.cell.client.AbstractCell;
-import com.google.gwt.regexp.shared.MatchResult;
-import com.google.gwt.regexp.shared.RegExp;
-
-/**
- * A {@link AbstractCell} used to render text, with portions matching a given
- * regular expression highlighted.
- */
-public class HighlightingTextCell extends AbstractCell<String> {
-
- private RegExp highlightRegex;
-
- @Override
- public void render(String value, Object viewData, StringBuilder sb) {
- // sb.append("<div style='overflow:hidden; white-space:nowrap; text-overflow:ellipsis;'>");
- sb.append("<div>");
- if (highlightRegex == null) {
- sb.append(value);
- sb.append("</div>");
- return;
- }
-
- int fromIndex = 0;
- int length = value.length();
- MatchResult result;
- highlightRegex.setLastIndex(0);
- while (fromIndex < length) {
- // Find the next match of the highlight regex
- result = highlightRegex.exec(value);
- if (result == null) {
- // No more matches
- break;
- }
- int index = result.getIndex();
- String match = result.getGroup(0);
-
- // Append the characters leading up to the match
- sb.append(value.substring(fromIndex, index));
- // Append the match in boldface
- sb.append("<b>");
- sb.append(match);
- sb.append("</b>");
- // Skip past the matched string
- fromIndex = index + match.length();
- highlightRegex.setLastIndex(fromIndex);
- }
- // Append the tail of the string
- if (fromIndex < length) {
- sb.append(value.substring(fromIndex));
- }
- sb.append("</div>");
- }
-
- public void setHighlightRegex(String highlightText) {
- if (highlightText != null && highlightText.length() > 0) {
- highlightRegex = RegExp.compile(highlightText, "gi");
- } else {
- highlightRegex = null;
- }
- }
-}
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/PlayerScoresWidget.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/PlayerScoresWidget.java
deleted file mode 100644
index af75791..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/PlayerScoresWidget.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.client;
-
-import com.google.gwt.bikeshed.list.client.CellList;
-import com.google.gwt.cell.client.AbstractCell;
-import com.google.gwt.core.client.GWT;
-import com.google.gwt.sample.bikeshed.stocks.shared.PlayerInfo;
-import com.google.gwt.uibinder.client.UiBinder;
-import com.google.gwt.uibinder.client.UiFactory;
-import com.google.gwt.uibinder.client.UiField;
-import com.google.gwt.user.client.ui.Composite;
-import com.google.gwt.user.client.ui.Widget;
-import com.google.gwt.view.client.AbstractListViewAdapter;
-
-import java.util.List;
-
-/**
- * Widget to display player scores.
- */
-public class PlayerScoresWidget extends Composite {
-
- interface Binder extends UiBinder<Widget, PlayerScoresWidget> {
- }
-
- private static final Binder binder = GWT.create(Binder.class);
-
- /**
- * A {@link AbstractCell} that displays the status of a single player.
- */
- private static final class PlayerInfoCell extends AbstractCell<PlayerInfo> {
- @Override
- public void render(PlayerInfo value, Object viewData, StringBuilder sb) {
- sb.append("<div class='playerScoreBox'>");
- sb.append("<b>Name: </b>");
- sb.append(value.getDisplayName());
- sb.append("<br><b>Net Worth: </b>");
- sb.append(StocksDesktop.getFormattedPrice(value.getNetWorth()));
- sb.append("<br><b>Cash: </b>");
- sb.append(StocksDesktop.getFormattedPrice(value.getCash()));
-
- List<String> status = value.getStatus();
- if (status != null) {
- for (String s : status) {
- sb.append("<br>");
- sb.append(s);
- }
- }
- sb.append("</div>");
- }
- }
-
- @UiField
- CellList<PlayerInfo> cellList;
-
- private final AbstractListViewAdapter<PlayerInfo> adapter;
-
- public PlayerScoresWidget(AbstractListViewAdapter<PlayerInfo> adapter) {
- this.adapter = adapter;
- initWidget(binder.createAndBindUi(this));
- }
-
- @UiFactory
- CellList<PlayerInfo> createCellList() {
- CellList<PlayerInfo> view = new CellList<PlayerInfo>(new PlayerInfoCell());
- adapter.addView(view);
- return view;
- }
-}
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/PlayerScoresWidget.ui.xml b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/PlayerScoresWidget.ui.xml
deleted file mode 100644
index 317e725..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/PlayerScoresWidget.ui.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<ui:UiBinder
- xmlns:ui='urn:ui:com.google.gwt.uibinder'
- xmlns:g='urn:import:com.google.gwt.user.client.ui'
- xmlns:l='urn:import:com.google.gwt.bikeshed.list.client'
- xmlns:t='urn:import:com.google.gwt.bikeshed.tree.client'
- xmlns:s='urn:import:com.google.gwt.sample.bikeshed.stocks.client'>
-
- <ui:with field='styles'
- type='com.google.gwt.sample.bikeshed.style.client.Styles'/>
-
- <g:DockLayoutPanel unit='EM'>
- <g:north size='2'>
- <g:Label styleName='{styles.common.header}'>Player Status</g:Label>
- </g:north>
-
- <g:center>
- <g:ScrollPanel styleName="{styles.common.padded}">
- <l:CellList ui:field='cellList'/>
- </g:ScrollPanel>
- </g:center>
- </g:DockLayoutPanel>
-</ui:UiBinder>
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/ProfitLossCell.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/ProfitLossCell.java
deleted file mode 100644
index bec3746..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/ProfitLossCell.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.client;
-
-import com.google.gwt.cell.client.AbstractCell;
-
-/**
- * A {@link AbstractCell} used to render profit and loss. Positive values are shown in
- * green with a "+" sign and negative values are shown in red with a "-" sign.
- */
-public class ProfitLossCell extends AbstractCell<Integer> {
-
- @Override
- public void render(Integer priceDelta, Object viewData, StringBuilder sb) {
- boolean negative = priceDelta < 0;
- if (negative) {
- priceDelta = -priceDelta;
- }
- int dollars = priceDelta / 100;
- int cents = priceDelta % 100;
-
- sb.append("<span style=\"color:");
- if (priceDelta == 0) {
- sb.append("green\"> ");
- } else if (negative) {
- sb.append("red\">-");
- } else {
- sb.append("green\">+");
- }
- sb.append("$");
- sb.append(dollars);
- sb.append('.');
- if (cents < 10) {
- sb.append('0');
- }
- sb.append(cents);
- sb.append("</span>");
- }
-}
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StockQueryWidget.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StockQueryWidget.java
deleted file mode 100644
index 5b7564f..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StockQueryWidget.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.client;
-
-import com.google.gwt.bikeshed.list.client.CellTable;
-import com.google.gwt.core.client.GWT;
-import com.google.gwt.event.dom.client.KeyUpEvent;
-import com.google.gwt.event.dom.client.KeyUpHandler;
-import com.google.gwt.sample.bikeshed.stocks.shared.StockQuote;
-import com.google.gwt.uibinder.client.UiBinder;
-import com.google.gwt.uibinder.client.UiFactory;
-import com.google.gwt.uibinder.client.UiField;
-import com.google.gwt.user.client.Timer;
-import com.google.gwt.user.client.ui.Composite;
-import com.google.gwt.user.client.ui.TextBox;
-import com.google.gwt.user.client.ui.Widget;
-import com.google.gwt.view.client.AbstractListViewAdapter;
-
-/**
- * A widget containing a search box and a results table.
- */
-public class StockQueryWidget extends Composite {
-
- interface Binder extends UiBinder<Widget, StockQueryWidget> { }
- private static final Binder binder = GWT.create(Binder.class);
-
- @UiField CellTable<StockQuote> table;
- @UiField TextBox queryField = new TextBox();
-
- private final AbstractListViewAdapter<StockQuote> adapter;
-
- public StockQueryWidget(AbstractListViewAdapter<StockQuote> adapter, final Updater updater) {
- this.adapter = adapter;
- initWidget(binder.createAndBindUi(this));
-
- table.addColumn(Columns.favoriteColumn);
- table.addColumn(Columns.tickerColumn, "ticker");
- table.addColumn(Columns.nameColumn, "name");
- table.addColumn(Columns.changeColumn, "change");
- table.addColumn(Columns.priceColumn, "price");
- table.addColumn(Columns.buyColumn);
-
- // Focus the cursor on the name field when the app loads
- queryField.setFocus(true);
- queryField.selectAll();
- queryField.setText("G");
-
- // Add a handler to send the name to the server
- final Timer requestTimer = new Timer() {
- @Override
- public void run() {
- updater.update();
- }
- };
- queryField.addKeyUpHandler(new KeyUpHandler() {
- public void onKeyUp(KeyUpEvent event) {
- Columns.nameCell.setHighlightRegex(getSearchQuery());
- // Delay the request until the user stops typing.
- requestTimer.schedule(250);
- }
- });
- }
-
- public String getSearchQuery() {
- return normalize(queryField.getText());
- }
-
- @UiFactory
- CellTable<StockQuote> createTable() {
- CellTable<StockQuote> view = new CellTable<StockQuote>(10);
- adapter.addView(view);
- return view;
- }
-
- private String normalize(String input) {
- String output = input;
- output = output.replaceAll("\\|+", " ");
- output = output.replaceAll("^[\\| ]+", "");
- output = output.replaceAll("[\\| ]+$", "");
- output = output.replaceAll("[ ]+", "|");
- return output;
- }
-}
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StockQueryWidget.ui.xml b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StockQueryWidget.ui.xml
deleted file mode 100644
index 671a925..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StockQueryWidget.ui.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<ui:UiBinder
- xmlns:ui='urn:ui:com.google.gwt.uibinder'
- xmlns:g='urn:import:com.google.gwt.user.client.ui'
- xmlns:l='urn:import:com.google.gwt.bikeshed.list.client'
- xmlns:t='urn:import:com.google.gwt.bikeshed.tree.client'
- xmlns:s='urn:import:com.google.gwt.sample.bikeshed.stocks.client'>
-
- <ui:with field='styles'
- type='com.google.gwt.sample.bikeshed.style.client.Styles'/>
-
- <g:DockLayoutPanel unit='EM'>
- <g:north size='2'>
- <g:HTMLPanel>
- <span class='{styles.common.headerLeft}'>Enter query:</span>
- <g:TextBox ui:field='queryField'/>
- </g:HTMLPanel>
- </g:north>
-
- <g:center>
- <g:ScrollPanel>
- <l:CellTable ui:field='table' styleName='{styles.common.table}'/>
- </g:ScrollPanel>
- </g:center>
- </g:DockLayoutPanel>
-</ui:UiBinder>
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StockQuoteCell.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StockQuoteCell.java
deleted file mode 100644
index c84dde4..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StockQuoteCell.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.client;
-
-import com.google.gwt.cell.client.AbstractCell;
-import com.google.gwt.sample.bikeshed.stocks.shared.StockQuote;
-
-/**
- * A cell that represents a {@link StockQuote}.
- */
-public class StockQuoteCell extends AbstractCell<StockQuote> {
-
- @Override
- public void render(StockQuote value, Object viewData, StringBuilder sb) {
- sb.append(value.getTicker() + " (" + value.getName() + "): "
- + value.getDisplayPrice());
- }
-}
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StockService.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StockService.java
deleted file mode 100644
index 98c11eb..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StockService.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.client;
-
-import com.google.gwt.sample.bikeshed.stocks.shared.StockRequest;
-import com.google.gwt.sample.bikeshed.stocks.shared.StockResponse;
-import com.google.gwt.sample.bikeshed.stocks.shared.Transaction;
-import com.google.gwt.user.client.rpc.RemoteService;
-import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
-import com.google.gwt.view.client.Range;
-
-/**
- * The client side stub for the RPC service.
- */
-@RemoteServiceRelativePath("stock")
-public interface StockService extends RemoteService {
-
- StockResponse getStockQuotes(StockRequest request)
- throws IllegalArgumentException;
-
- StockResponse addFavorite(String ticker, Range favoritesRange);
-
- StockResponse removeFavorite(String ticker, Range favoritesRange);
-
- Transaction transact(Transaction transaction) throws IllegalArgumentException;
-}
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StockServiceAsync.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StockServiceAsync.java
deleted file mode 100644
index 9cb5963..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StockServiceAsync.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.client;
-
-import com.google.gwt.sample.bikeshed.stocks.shared.StockRequest;
-import com.google.gwt.sample.bikeshed.stocks.shared.StockResponse;
-import com.google.gwt.sample.bikeshed.stocks.shared.Transaction;
-import com.google.gwt.user.client.rpc.AsyncCallback;
-import com.google.gwt.view.client.Range;
-
-/**
- * The async counterpart of <code>DataService</code>.
- */
-public interface StockServiceAsync {
- void getStockQuotes(StockRequest request,
- AsyncCallback<StockResponse> callback);
-
- void addFavorite(String ticker, Range favoritesRange, AsyncCallback<StockResponse> callback);
-
- void removeFavorite(String ticker, Range favoritesRange, AsyncCallback<StockResponse> callback);
-
- void transact(Transaction transaction, AsyncCallback<Transaction> callback);
-}
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StocksDesktop.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StocksDesktop.java
deleted file mode 100644
index ae11b8c..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StocksDesktop.java
+++ /dev/null
@@ -1,399 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.client;
-
-import com.google.gwt.bikeshed.tree.client.CellBrowser;
-import com.google.gwt.cell.client.FieldUpdater;
-import com.google.gwt.core.client.EntryPoint;
-import com.google.gwt.core.client.GWT;
-import com.google.gwt.event.logical.shared.CloseEvent;
-import com.google.gwt.event.logical.shared.CloseHandler;
-import com.google.gwt.i18n.client.NumberFormat;
-import com.google.gwt.sample.bikeshed.stocks.client.TransactionTreeViewModel.SectorListViewAdapter;
-import com.google.gwt.sample.bikeshed.stocks.shared.PlayerInfo;
-import com.google.gwt.sample.bikeshed.stocks.shared.StockQuote;
-import com.google.gwt.sample.bikeshed.stocks.shared.StockQuoteList;
-import com.google.gwt.sample.bikeshed.stocks.shared.StockRequest;
-import com.google.gwt.sample.bikeshed.stocks.shared.StockResponse;
-import com.google.gwt.sample.bikeshed.stocks.shared.Transaction;
-import com.google.gwt.uibinder.client.UiBinder;
-import com.google.gwt.uibinder.client.UiFactory;
-import com.google.gwt.uibinder.client.UiField;
-import com.google.gwt.user.client.Timer;
-import com.google.gwt.user.client.Window;
-import com.google.gwt.user.client.rpc.AsyncCallback;
-import com.google.gwt.user.client.ui.Label;
-import com.google.gwt.user.client.ui.PopupPanel;
-import com.google.gwt.user.client.ui.RootLayoutPanel;
-import com.google.gwt.user.client.ui.Widget;
-import com.google.gwt.view.client.AsyncListViewAdapter;
-import com.google.gwt.view.client.ListView;
-import com.google.gwt.view.client.ListViewAdapter;
-import com.google.gwt.view.client.Range;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Desktop client for the stocks demo.
- */
-public class StocksDesktop implements EntryPoint, Updater {
-
- interface Binder extends UiBinder<Widget, StocksDesktop> {
- }
-
- private static final Binder binder = GWT.create(Binder.class);
-
- /**
- * The delay between updates in milliseconds.
- */
- private static final int UPDATE_DELAY = 5000;
-
- static String getFormattedPrice(int price) {
- return NumberFormat.getCurrencyFormat("USD").format(price / 100.0);
- }
-
- @UiField
- Label cashLabel;
-
- @UiField
- FavoritesWidget favoritesWidget;
- @UiField
- Label netWorthLabel;
- @UiField
- PlayerScoresWidget playerScoresWidget;
- @UiField
- StockQueryWidget queryWidget;
- @UiField
- CellBrowser transactionTree;
-
- /**
- * The popup used to purchase stock.
- */
- private BuySellPopup buySellPopup = new BuySellPopup();
- private final StockServiceAsync dataService = GWT.create(StockService.class);
-
- private AsyncListViewAdapter<StockQuote> favoritesListViewAdapter;
- private AsyncListViewAdapter<PlayerInfo> playerScoresListViewAdapter;
- private AsyncListViewAdapter<StockQuote> searchListViewAdapter;
- private Map<String, ListViewAdapter<Transaction>> transactionListViewAdaptersByTicker = new HashMap<String, ListViewAdapter<Transaction>>();
- private ListViewAdapter<Transaction> transactionListViewAdapter;
- private List<Transaction> transactions;
-
- private TransactionTreeViewModel treeModel;
-
- /**
- * The timer used to update the stock quotes.
- */
- private Timer updateTimer = new Timer() {
- @Override
- public void run() {
- update();
- }
- };
-
- public void buy(StockQuote stockQuote) {
- buySellPopup.setStockQuote(stockQuote, true);
- buySellPopup.center();
- }
-
- /**
- * This is the entry point method.
- */
- public void onModuleLoad() {
- // Create the various models. Do this before binding the UI, because some
- // of the UiFactories need the models to instantiate their widgets.
- searchListViewAdapter = new AsyncListViewAdapter<StockQuote>() {
- @Override
- protected void onRangeChanged(ListView<StockQuote> view) {
- update();
- }
- };
- searchListViewAdapter.setKeyProvider(StockQuote.KEY_PROVIDER);
-
- favoritesListViewAdapter = new AsyncListViewAdapter<StockQuote>() {
- @Override
- protected void onRangeChanged(ListView<StockQuote> view) {
- update();
- }
- };
- favoritesListViewAdapter.setKeyProvider(StockQuote.KEY_PROVIDER);
-
- playerScoresListViewAdapter = new AsyncListViewAdapter<PlayerInfo>() {
- @Override
- protected void onRangeChanged(ListView<PlayerInfo> view) {
- }
- };
-
- treeModel = new TransactionTreeViewModel(this, favoritesListViewAdapter,
- transactionListViewAdaptersByTicker);
-
- transactionListViewAdapter = new ListViewAdapter<Transaction>();
- transactions = transactionListViewAdapter.getList();
-
- // Now create the UI.
- RootLayoutPanel.get().add(binder.createAndBindUi(this));
-
- // Hook up handlers to columns and the buy/sell popup.
- Columns.favoriteColumn.setFieldUpdater(new FieldUpdater<StockQuote, Boolean>() {
- public void update(int index, StockQuote object, Boolean value) {
- setFavorite(object.getTicker(), value);
- }
- });
-
- Columns.buyColumn.setFieldUpdater(new FieldUpdater<StockQuote, String>() {
- public void update(int index, StockQuote quote, String value) {
- buy(quote);
- }
- });
-
- Columns.sellColumn.setFieldUpdater(new FieldUpdater<StockQuote, String>() {
- public void update(int index, StockQuote quote, String value) {
- sell(quote);
- }
- });
-
- buySellPopup.addCloseHandler(new CloseHandler<PopupPanel>() {
- public void onClose(CloseEvent<PopupPanel> event) {
- Transaction t = buySellPopup.getTransaction();
- if (t != null) {
- transact(t);
- }
- }
- });
-
- update();
- }
-
- /**
- * Process the {@link StockResponse} from the server.
- *
- * @param response the stock response
- */
- public void processStockResponse(StockResponse response) {
- // Update the search list if the query has not changed.
- StockQuoteList searchResults = response.getSearchResults();
- String searchQuery = queryWidget.getSearchQuery();
- if (searchQuery != null && searchQuery.equals(response.getSearchQuery())) {
- searchListViewAdapter.updateDataSize(response.getNumSearchResults(), true);
- searchListViewAdapter.updateViewData(searchResults.getStartIndex(),
- searchResults.size(), searchResults);
- }
-
- // Update the favorites list.
- updateFavorites(response);
- updateSector(response);
- updatePlayerScores(response);
-
- // Update available cash.
- int cash = response.getCash();
- int netWorth = response.getNetWorth();
- cashLabel.setText(getFormattedPrice(cash));
- netWorthLabel.setText(getFormattedPrice(netWorth));
- buySellPopup.setAvailableCash(cash);
-
- // Restart the update timer.
- updateTimer.schedule(UPDATE_DELAY);
- }
-
- public void sell(StockQuote stockQuote) {
- buySellPopup.setStockQuote(stockQuote, false);
- buySellPopup.center();
- }
-
- /**
- * Set or unset a ticker symbol as a 'favorite'.
- *
- * @param ticker the ticker symbol
- * @param favorite if true, make the stock a favorite
- */
- public void setFavorite(String ticker, boolean favorite) {
- if (favorite) {
- dataService.addFavorite(ticker, favoritesListViewAdapter.getRanges()[0],
- new AsyncCallback<StockResponse>() {
- public void onFailure(Throwable caught) {
- handleRpcError(caught, "Error adding favorite");
- }
-
- public void onSuccess(StockResponse response) {
- updateFavorites(response);
- updatePlayerScores(response);
- }
- });
- } else {
- dataService.removeFavorite(ticker,
- favoritesListViewAdapter.getRanges()[0],
- new AsyncCallback<StockResponse>() {
- public void onFailure(Throwable caught) {
- handleRpcError(caught, "Error removing favorite");
- }
-
- public void onSuccess(StockResponse response) {
- updateFavorites(response);
- updatePlayerScores(response);
- }
- });
- }
- }
-
- public void transact(Transaction t) {
- dataService.transact(t, new AsyncCallback<Transaction>() {
- public void onFailure(Throwable caught) {
- Window.alert("Error: " + caught.getMessage());
- }
-
- public void onSuccess(Transaction result) {
- recordTransaction(result);
- update();
- }
-
- /**
- * Update transactions (list of all transactions), transactionTickers (set
- * of all tickers involved in transactions), and transactionsByTicker (map
- * from ticker to lists of transactions for that ticker).
- */
- private void recordTransaction(Transaction result) {
- transactions.add(0, result);
- String ticker = result.getTicker();
-
- // Update the next level of the transaction tree
- // for the given ticker
- ListViewAdapter<Transaction> t = transactionListViewAdaptersByTicker.get(ticker);
- if (t == null) {
- t = new ListViewAdapter<Transaction>();
- transactionListViewAdaptersByTicker.put(ticker, t);
- }
- t.getList().add(result);
- }
- });
- }
-
- /**
- * Request data from the server using the last query string.
- */
- public void update() {
- if (queryWidget == null) {
- return;
- }
-
- updateTimer.cancel();
-
- Range[] searchRanges = searchListViewAdapter.getRanges();
- Range[] favoritesRanges = favoritesListViewAdapter.getRanges();
-
- SectorListViewAdapter sectorListViewAdapter = treeModel.getSectorListViewAdapter();
- Range[] sectorRanges = sectorListViewAdapter == null ? null
- : sectorListViewAdapter.getRanges();
-
- if (searchRanges == null || searchRanges.length == 0
- || favoritesRanges == null || favoritesRanges.length == 0) {
- return;
- }
-
- String searchQuery = queryWidget.getSearchQuery();
-
- StockRequest request = new StockRequest(searchQuery,
- sectorListViewAdapter != null ? sectorListViewAdapter.getSector()
- : null, searchRanges[0], favoritesRanges[0], sectorRanges != null
- && sectorRanges.length > 0 ? sectorRanges[0] : null);
- dataService.getStockQuotes(request, new AsyncCallback<StockResponse>() {
- public void onFailure(Throwable caught) {
- if (handleRpcError(caught, null)) {
- updateTimer.schedule(UPDATE_DELAY);
- }
- }
-
- public void onSuccess(StockResponse result) {
- processStockResponse(result);
- }
- });
- }
-
- @UiFactory
- FavoritesWidget createFavoritesWidget() {
- return new FavoritesWidget(favoritesListViewAdapter);
- }
-
- @UiFactory
- PlayerScoresWidget createPlayerScoresWidget() {
- return new PlayerScoresWidget(playerScoresListViewAdapter);
- }
-
- @UiFactory
- StockQueryWidget createQueryWidget() {
- return new StockQueryWidget(searchListViewAdapter, this);
- }
-
- @UiFactory
- CellBrowser createTransactionTree() {
- CellBrowser treeView = new CellBrowser(treeModel, null);
- treeView.setAnimationEnabled(true);
- return treeView;
- }
-
- /**
- * Display a message to the user when an RPC call fails.
- *
- * @param caught the exception
- * @param displayMessage the message to display to the user, or null to
- * display a default message
- * @return true if recoverable, false if not
- */
- private boolean handleRpcError(Throwable caught, String displayMessage) {
- String message = caught.getMessage();
- if (message.contains("Not logged in")) {
- // Force the user to login.
- Window.Location.reload();
- return false;
- }
-
- if (displayMessage == null) {
- displayMessage = "ERROR: " + caught.getMessage();
- }
- Window.alert(displayMessage);
- return true;
- }
-
- private void updateFavorites(StockResponse response) {
- // Update the favorites list.
- StockQuoteList favorites = response.getFavorites();
- favoritesListViewAdapter.updateDataSize(response.getNumFavorites(), true);
- favoritesListViewAdapter.updateViewData(favorites.getStartIndex(),
- favorites.size(), favorites);
- }
-
- private void updatePlayerScores(StockResponse response) {
- // Update the player scores.
- List<PlayerInfo> playerScores = response.getPlayers();
- int numPlayers = playerScores.size();
- playerScoresListViewAdapter.updateDataSize(numPlayers, true);
- playerScoresListViewAdapter.updateViewData(0, numPlayers, playerScores);
- }
-
- private void updateSector(StockResponse response) {
- // Update the sector list.
- StockQuoteList sectorList = response.getSector();
- if (sectorList != null) {
- SectorListViewAdapter sectorListViewAdapter = treeModel.getSectorListViewAdapter();
- if (sectorListViewAdapter != null) {
- sectorListViewAdapter.updateDataSize(response.getNumSector(), true);
- sectorListViewAdapter.updateViewData(sectorList.getStartIndex(),
- sectorList.size(), sectorList);
- }
- }
- }
-}
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StocksDesktop.ui.xml b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StocksDesktop.ui.xml
deleted file mode 100644
index 2e0cca6..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StocksDesktop.ui.xml
+++ /dev/null
@@ -1,54 +0,0 @@
-<ui:UiBinder
- xmlns:ui='urn:ui:com.google.gwt.uibinder'
- xmlns:g='urn:import:com.google.gwt.user.client.ui'
- xmlns:l='urn:import:com.google.gwt.bikeshed.list.client'
- xmlns:t='urn:import:com.google.gwt.bikeshed.tree.client'
- xmlns:s='urn:import:com.google.gwt.sample.bikeshed.stocks.client'>
-
- <ui:with field='styles'
- type='com.google.gwt.sample.bikeshed.style.client.Styles'/>
-
- <g:DockLayoutPanel unit='EM'>
- <g:north size='4'>
- <g:HTML styleName='{styles.common.headerMain}'>Day Trader</g:HTML>
- </g:north>
-
- <g:west size='16'>
- <g:DockLayoutPanel unit='EM'>
- <g:north size='12'>
- <g:HTMLPanel styleName='{styles.common.box}'>
- <div class='{styles.common.header}'>Your Stats</div>
- <table>
- <tr><td>Available cash:</td><td><g:InlineLabel ui:field='cashLabel'/></td></tr>
- <tr><td>Net worth:</td><td><g:InlineLabel ui:field='netWorthLabel'/></td></tr>
- </table>
- </g:HTMLPanel>
- </g:north>
-
- <g:center>
- <s:PlayerScoresWidget styleName='{styles.common.box}' ui:field='playerScoresWidget'/>
- </g:center>
- </g:DockLayoutPanel>
- </g:west>
-
- <g:north size="18">
- <g:LayoutPanel styleName='{styles.common.box}'>
- <g:layer>
- <t:CellBrowser ui:field='transactionTree'/>
- </g:layer>
- </g:LayoutPanel>
- </g:north>
-
- <g:center>
- <g:DockLayoutPanel unit='PCT'>
- <g:west size="50">
- <s:StockQueryWidget styleName='{styles.common.box}' ui:field='queryWidget'/>
- </g:west>
-
- <g:center>
- <s:FavoritesWidget styleName='{styles.common.box}' ui:field='favoritesWidget'/>
- </g:center>
- </g:DockLayoutPanel>
- </g:center>
- </g:DockLayoutPanel>
-</ui:UiBinder>
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StocksMobile.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StocksMobile.java
deleted file mode 100644
index 77e23ee..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StocksMobile.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.client;
-
-import com.google.gwt.bikeshed.list.client.CellTable;
-import com.google.gwt.core.client.GWT;
-import com.google.gwt.i18n.client.NumberFormat;
-import com.google.gwt.sample.bikeshed.stocks.shared.StockQuote;
-import com.google.gwt.sample.bikeshed.stocks.shared.StockQuoteList;
-import com.google.gwt.sample.bikeshed.stocks.shared.StockRequest;
-import com.google.gwt.sample.bikeshed.stocks.shared.StockResponse;
-import com.google.gwt.uibinder.client.UiBinder;
-import com.google.gwt.uibinder.client.UiFactory;
-import com.google.gwt.uibinder.client.UiField;
-import com.google.gwt.user.client.Timer;
-import com.google.gwt.user.client.Window;
-import com.google.gwt.user.client.rpc.AsyncCallback;
-import com.google.gwt.user.client.ui.RootPanel;
-import com.google.gwt.user.client.ui.Widget;
-import com.google.gwt.view.client.AsyncListViewAdapter;
-import com.google.gwt.view.client.ListView;
-import com.google.gwt.view.client.Range;
-
-/**
- * Mobile client for the stocks demo.
- */
-public class StocksMobile {
-
- interface Binder extends UiBinder<Widget, StocksMobile> {
- }
-
- private static final Binder binder = GWT.create(Binder.class);
-
- /**
- * The delay between updates in milliseconds.
- */
- private static final int UPDATE_DELAY = 5000;
-
- static String getFormattedPrice(int price) {
- return NumberFormat.getCurrencyFormat("USD").format(price / 100.0);
- }
-
- @UiField CellTable<StockQuote> table;
- private final StockServiceAsync dataService = GWT.create(StockService.class);
- private AsyncListViewAdapter<StockQuote> favoritesListViewAdapter;
-
- /**
- * The timer used to update the stock quotes.
- */
- private Timer updateTimer = new Timer() {
- @Override
- public void run() {
- update();
- }
- };
-
- /**
- * This is the entry point method.
- */
- public void onModuleLoad() {
- // Create the various models. Do this before binding the UI, because some
- // of the UiFactories need the models to instantiate their widgets.
- favoritesListViewAdapter = new AsyncListViewAdapter<StockQuote>() {
- @Override
- protected void onRangeChanged(ListView<StockQuote> view) {
- update();
- }
- };
- favoritesListViewAdapter.setKeyProvider(StockQuote.KEY_PROVIDER);
-
- // Now create the UI.
- RootPanel.get().add(binder.createAndBindUi(this));
- update();
- }
-
- /**
- * Process the {@link StockResponse} from the server.
- *
- * @param response the stock response
- */
- public void processStockResponse(StockResponse response) {
- // Update the favorites list.
- updateFavorites(response);
-
- // Restart the update timer.
- updateTimer.schedule(UPDATE_DELAY);
- }
-
- public void update() {
- Range[] favoritesRanges = favoritesListViewAdapter.getRanges();
-
- StockRequest request = new StockRequest("TODO", null, null,
- favoritesRanges[0], null);
-
- dataService.getStockQuotes(request, new AsyncCallback<StockResponse>() {
- public void onFailure(Throwable caught) {
- if (handleRpcError(caught, null)) {
- updateTimer.schedule(UPDATE_DELAY);
- }
- }
-
- public void onSuccess(StockResponse result) {
- processStockResponse(result);
- }
- });
- }
-
- @UiFactory
- CellTable<StockQuote> createFavoritesWidget() {
- CellTable<StockQuote> favorite = new CellTable<StockQuote>(10);
- favoritesListViewAdapter.addView(favorite);
-
- favorite.addColumn(Columns.tickerColumn, "ticker");
- favorite.addColumn(Columns.priceColumn, "price");
- favorite.addColumn(Columns.changeColumn, "change");
- favorite.addColumn(Columns.sharesColumn, "shares");
- favorite.addColumn(Columns.dollarsColumn, "value");
- favorite.addColumn(Columns.profitLossColumn, "profit/loss");
-
- return favorite;
- }
-
- /**
- * Display a message to the user when an RPC call fails.
- *
- * @param caught the exception
- * @param displayMessage the message to display to the user, or null to
- * display a default message
- * @return true if recoverable, false if not
- */
- private boolean handleRpcError(Throwable caught, String displayMessage) {
- String message = caught.getMessage();
- if (message.contains("Not logged in")) {
- // Force the user to login.
- Window.Location.reload();
- return false;
- }
-
- if (displayMessage == null) {
- displayMessage = "ERROR: " + caught.getMessage();
- }
- Window.alert(displayMessage);
- return true;
- }
-
- private void updateFavorites(StockResponse response) {
- // Update the favorites list.
- StockQuoteList favorites = response.getFavorites();
- favoritesListViewAdapter.updateDataSize(response.getNumFavorites(), true);
- favoritesListViewAdapter.updateViewData(favorites.getStartIndex(),
- favorites.size(), favorites);
- }
-}
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StocksMobile.ui.xml b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StocksMobile.ui.xml
deleted file mode 100644
index 9786f59..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/StocksMobile.ui.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<ui:UiBinder
- xmlns:ui='urn:ui:com.google.gwt.uibinder'
- xmlns:g='urn:import:com.google.gwt.user.client.ui'
- xmlns:l='urn:import:com.google.gwt.bikeshed.list.client'
- xmlns:t='urn:import:com.google.gwt.bikeshed.tree.client'
- xmlns:s='urn:import:com.google.gwt.sample.bikeshed.stocks.client'>
-
- <ui:with field='styles'
- type='com.google.gwt.sample.bikeshed.style.client.Styles'/>
-
- <g:HTMLPanel>
- <div styleName='{styles.common.headerLeft}'>Portfolio / Favorites</div>
- <l:CellTable ui:field='table' styleName='{styles.common.table}'/>
- </g:HTMLPanel>
-</ui:UiBinder>
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/TransactionTreeViewModel.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/TransactionTreeViewModel.java
deleted file mode 100644
index efaaff7..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/TransactionTreeViewModel.java
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.client;
-
-import com.google.gwt.cell.client.ButtonCell;
-import com.google.gwt.cell.client.AbstractCell;
-import com.google.gwt.cell.client.Cell;
-import com.google.gwt.cell.client.TextCell;
-import com.google.gwt.cell.client.ValueUpdater;
-import com.google.gwt.sample.bikeshed.stocks.shared.StockQuote;
-import com.google.gwt.sample.bikeshed.stocks.shared.Transaction;
-import com.google.gwt.view.client.AbstractListViewAdapter;
-import com.google.gwt.view.client.AsyncListViewAdapter;
-import com.google.gwt.view.client.TreeViewModel;
-import com.google.gwt.view.client.ListView;
-import com.google.gwt.view.client.ListViewAdapter;
-import com.google.gwt.view.client.ProvidesKey;
-import com.google.gwt.view.client.SingleSelectionModel;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * A TreeViewModel for a tree with a hidden root node of null, a first level
- * containing ticker symbol Strings, and a second level containing Transactions.
- */
-class TransactionTreeViewModel implements TreeViewModel {
-
- class SectorListViewAdapter extends AsyncListViewAdapter<StockQuote> {
-
- String sector;
-
- public SectorListViewAdapter(String sector) {
- this.sector = sector;
- setKeyProvider(StockQuote.KEY_PROVIDER);
- }
-
- public String getSector() {
- return sector;
- }
-
- @Override
- protected void onRangeChanged(ListView<StockQuote> view) {
- updater.update();
- }
- }
-
- /**
- * A {@link AbstractCell} used to render a {@link StockQuote}.
- */
- private static final Cell<StockQuote> STOCK_QUOTE_CELL = new AbstractCell<StockQuote>() {
- @Override
- public void render(StockQuote value, Object viewData, StringBuilder sb) {
- sb.append(value.getTicker() + " - " + value.getDisplayPrice());
- }
- };
-
- /**
- * A {@link AbstractCell} used to render a {@link Transaction}.
- */
- private static final Cell<Transaction> TRANSACTION_CELL = new AbstractCell<Transaction>() {
- @Override
- public void render(Transaction value, Object viewData, StringBuilder sb) {
- sb.append(value.toString());
- }
- };
-
- /**
- * The last {@link StockQuote} that was opened.
- */
- private StockQuote lastStockQuote;
-
- /**
- * The last Sector that was opened.
- */
- private String lastSector;
-
- private Map<String, SectorListViewAdapter> sectorListViewAdapters = new HashMap<String, SectorListViewAdapter>();
- private AbstractListViewAdapter<StockQuote> stockQuoteListViewAdapter;
- private ListViewAdapter<String> topLevelListViewAdapter = new ListViewAdapter<String>();
- private SingleSelectionModel<Object> selectionModel = new SingleSelectionModel<Object>();
-
- private Map<String, ListViewAdapter<Transaction>> transactionListViewAdaptersByTicker;
-
- private Updater updater;
-
- public TransactionTreeViewModel(
- Updater updater,
- AbstractListViewAdapter<StockQuote> stockQuoteListViewAdapter,
- Map<String, ListViewAdapter<Transaction>> transactionListViewAdaptersByTicker) {
- this.selectionModel.setKeyProvider(new ProvidesKey<Object>() {
- public Object getKey(Object item) {
- if (item instanceof StockQuote) {
- return StockQuote.KEY_PROVIDER.getKey((StockQuote) item);
- } else {
- return item;
- }
- }
- });
- this.updater = updater;
- this.stockQuoteListViewAdapter = stockQuoteListViewAdapter;
-
- // Setup the sector list.
- List<String> topLevelList = topLevelListViewAdapter.getList();
- topLevelList.add("Favorites");
- topLevelList.add("Dow Jones Industrials");
- topLevelList.add("S&P 500");
- this.transactionListViewAdaptersByTicker = transactionListViewAdaptersByTicker;
- }
-
- public <T> NodeInfo<?> getNodeInfo(T value) {
- if (value == null) {
- // Return list of sectors.
- return new TreeViewModel.DefaultNodeInfo<String>(topLevelListViewAdapter,
- new TextCell(), selectionModel, null);
- } else if ("Favorites".equals(value)) {
- // Return favorites.
- return new TreeViewModel.DefaultNodeInfo<StockQuote>(
- stockQuoteListViewAdapter, STOCK_QUOTE_CELL, selectionModel, null);
- } else if ("History".equals(value)) {
- // Return history of the current stock quote.
- String ticker = lastStockQuote.getTicker();
- ListViewAdapter<Transaction> adapter = transactionListViewAdaptersByTicker.get(ticker);
- if (adapter == null) {
- adapter = new ListViewAdapter<Transaction>();
- transactionListViewAdaptersByTicker.put(ticker, adapter);
- }
- return new TreeViewModel.DefaultNodeInfo<Transaction>(adapter,
- TRANSACTION_CELL, selectionModel, null);
- } else if ("Actions".equals(value)) {
- // Return the actions for the current stock quote.
- ListViewAdapter<String> adapter = new ListViewAdapter<String>();
- List<String> list = adapter.getList();
- list.add("Buy");
- list.add("Sell");
- return new TreeViewModel.DefaultNodeInfo<String>(adapter,
- new ButtonCell(), selectionModel,
- new ValueUpdater<String>() {
- public void update(String value) {
- if ("Buy".equals(value)) {
- updater.buy(lastStockQuote);
- } else {
- updater.sell(lastStockQuote);
- }
- }
- });
- } else if (value instanceof String) {
- // Return the stocks for a given sector.
- lastSector = (String) value;
- SectorListViewAdapter adapter = new SectorListViewAdapter(lastSector);
- sectorListViewAdapters.put(lastSector, adapter);
- return new TreeViewModel.DefaultNodeInfo<StockQuote>(adapter,
- STOCK_QUOTE_CELL, selectionModel, null);
- } else if (value instanceof StockQuote) {
- // Return the submenu for a stock quote.
- lastStockQuote = (StockQuote) value;
- ListViewAdapter<String> adapter = new ListViewAdapter<String>();
- List<String> list = adapter.getList();
- list.add("Actions");
- list.add("History");
- return new TreeViewModel.DefaultNodeInfo<String>(adapter,
- new TextCell(), selectionModel, null);
- }
-
- throw new IllegalArgumentException(value.toString());
- }
-
- /**
- * Get the {@link SectorListViewAdapter} for the last selected sector.
- *
- * @return the {@link SectorListViewAdapter}
- */
- public SectorListViewAdapter getSectorListViewAdapter() {
- return lastSector == null ? null : sectorListViewAdapters.get(lastSector);
- }
-
- public boolean isLeaf(Object value) {
- if (value instanceof Transaction || "Buy".equals(value)
- || "Sell".equals(value)) {
- return true;
- }
-
- return false;
- }
-}
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/Updater.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/Updater.java
deleted file mode 100644
index 56d7fb6..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/client/Updater.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.client;
-
-import com.google.gwt.sample.bikeshed.stocks.shared.StockQuote;
-
-/**
- * Bridge between StocksDesktop and StockQueryWidget.
- */
-public interface Updater {
-
- void buy(StockQuote stock);
-
- void sell(StockQuote stock);
-
- /**
- * Update the widget.
- *
- * TODO - refactor this
- */
- void update();
-}
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/server/GoogleFinance.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/server/GoogleFinance.java
deleted file mode 100644
index 3a82b37..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/server/GoogleFinance.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.server;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.Map;
-import java.util.Scanner;
-import java.util.Set;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * A class to perform queries against the Google Finance server.
- */
-public class GoogleFinance {
-
- private static final Pattern DATA_PATTERN =
- Pattern.compile("\"([^\"]*)\"\\s*:\\s*\"([^\"]*)\"");
-
- private static final Pattern QUOTE_PATTERN = Pattern.compile("\\{[^\\}]*\\}");
-
- public static void queryServer(Set<String> symbolsInRange,
- Map<String, StockServiceImpl.Quote> quotes) {
- // Build the URL string.
- StringBuilder sb = new StringBuilder(
- "http://www.google.com/finance/info?client=ig&q=");
- boolean first = true;
- for (String symbol : symbolsInRange) {
- if (!first) {
- sb.append(',');
- }
- sb.append(symbol);
- first = false;
- }
-
- // Send the request.
- String content = "";
- try {
- String urlString = sb.toString();
- URL url = new URL(urlString);
- InputStream urlInputStream = url.openStream();
- Scanner contentScanner = new Scanner(urlInputStream, "UTF-8");
- if (contentScanner.hasNextLine()) {
- // See http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html
- content = contentScanner.useDelimiter("\\A").next();
- }
-
- // System.out.println(content);
- } catch (MalformedURLException mue) {
- System.err.println(mue);
- } catch (IOException ioe) {
- System.err.println(ioe);
- }
-
- Matcher matcher = QUOTE_PATTERN.matcher(content);
- while (matcher.find()) {
- String group = matcher.group();
-
- String symbol = null;
- String dprice = null;
- String change = null;
-
- Matcher dataMatcher = DATA_PATTERN.matcher(group);
- while (dataMatcher.find()) {
- String tag = dataMatcher.group(1);
- String data = dataMatcher.group(2);
- if (tag.equals("t")) {
- symbol = data;
- } else if (tag.equals("l_cur")) {
- dprice = data;
- } else if (tag.equals("c")) {
- change = data;
- }
- }
-
- if (symbol != null && dprice != null && change != null) {
- try {
- int price = (int) (Double.parseDouble(dprice) * 100);
-
- // Cache the quote (will be good for 5 seconds)
- quotes.put(symbol, new StockServiceImpl.Quote(price, change));
- } catch (NumberFormatException e) {
- System.out.println("Bad price " + dprice + " for symbol " + symbol);
- }
- }
- }
- }
-
-}
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/server/PlayerStatus.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/server/PlayerStatus.java
deleted file mode 100644
index 4bdf912..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/server/PlayerStatus.java
+++ /dev/null
@@ -1,221 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.server;
-
-import com.google.gwt.sample.bikeshed.stocks.shared.PlayerInfo;
-
-import java.util.HashMap;
-import java.util.TreeSet;
-import java.util.regex.Pattern;
-
-/**
- * Game state for a single player.
- */
-public class PlayerStatus extends PlayerInfo {
-
- /**
- * An impossible stock ticker.
- */
- private static final String IMPOSSIBLE_TICKER_SYMBOL = "XXXXXXXXXX";
-
- /**
- * This players favorite stocks.
- */
- private TreeSet<String> favorites = new TreeSet<String>();
-
- /**
- * A precompiled version of the favorites query.
- */
- private Pattern favoritesPattern;
-
- /**
- * The query used to retrieve favorites.
- */
- private String favoritesQuery;
-
- /**
- * The number of shares owned for each symbol.
- */
- private HashMap<String, Integer> sharesOwnedBySymbol = new HashMap<String, Integer>();
-
- /**
- * The total amount paid for each symbol.
- */
- private HashMap<String, Double> averagePriceBySymbol = new HashMap<String, Double>();
-
- public PlayerStatus(String name) {
- super(name);
- generateFavoritesQuery();
- }
-
- /**
- * Add a stock to the favorites list.
- *
- * @param ticker the stock ticker
- */
- public void addFavorite(String ticker) {
- favorites.add(ticker);
- generateFavoritesQuery();
- }
-
- /**
- * Purchase stock.
- *
- * @param ticker the stock ticker
- * @param quantity the number of shares to buy
- * @param price the price of the stock
- * @throws IllegalArgumentException if the stock cannot be purchased
- */
- public void buy(String ticker, int quantity, int price)
- throws IllegalArgumentException {
- // Verify that the player can afford the stock.
- int cash = getCash();
- int totalPrice = price * quantity;
- if (cash < totalPrice) {
- throw new IllegalArgumentException("You cannot afford that much stock");
- }
-
- // Update the number of shares owned.
- int current = getSharesOwned(ticker);
- double averagePrice = getAveragePrice(ticker);
- double totalPaid = averagePrice * current + totalPrice;
-
- // Update case and shares owned
- current += quantity;
- setCash(cash - totalPrice);
- sharesOwnedBySymbol.put(ticker, current);
-
- // Update average price
- averagePrice = totalPaid / current;
- averagePriceBySymbol.put(ticker, averagePrice);
-
- // Add this stock to the favorites list.
- addFavorite(ticker);
- }
-
- /**
- * Returns the total cost of the currently owned shared, using an average cost
- * basis method.
- *
- * @param ticker the stock ticker
- */
- public int getAverageCostBasis(String ticker) {
- return (int) (Math.round(getAveragePrice(ticker) * getSharesOwned(ticker)));
- }
-
- public double getAveragePrice(String ticker) {
- Double current = averagePriceBySymbol.get(ticker);
- return current == null ? 0.0 : current;
- }
-
- /**
- * Get this players favorite pattern.
- *
- * @return the pattern
- */
- public Pattern getFavoritesPattern() {
- return favoritesPattern;
- }
-
- /**
- * Get this players favorite query.
- *
- * @return the query
- */
- public String getFavoritesQuery() {
- return favoritesQuery;
- }
-
- /**
- * Get the number of shares owned for a given stock.
- *
- * @param ticker the stock ticker
- * @return the number of shares owned
- */
- public int getSharesOwned(String ticker) {
- Integer current = sharesOwnedBySymbol.get(ticker);
- return current == null ? 0 : current;
- }
-
- /**
- * Check if the stock ticker is in the favorites list.
- *
- * @param ticker the stock sticker
- * @return true if a favorite, false if not
- */
- public boolean isFavorite(String ticker) {
- return favorites.contains(ticker);
- }
-
- /**
- * Remove a stock from the favorites list.
- *
- * @param ticker the stock ticker
- */
- public void removeFavorite(String ticker) {
- favorites.remove(ticker);
- generateFavoritesQuery();
- }
-
- /**
- * Sell stock.
- *
- * @param ticker the stock ticker
- * @param quantity the number of shares to sell
- * @param price the price of the stock
- * @throws IllegalArgumentException if the stock cannot be sold
- */
- public void sell(String ticker, int quantity, int price)
- throws IllegalArgumentException {
- // Verify that the player has enough stock to sell.
- int current = sharesOwnedBySymbol.get(ticker);
- if (quantity > current) {
- throw new IllegalArgumentException(
- "You cannot sell more stock than you own");
- }
-
- // Perform the transaction.
- int totalPrice = price * quantity;
- setCash(getCash() + totalPrice);
-
- current -= quantity;
- sharesOwnedBySymbol.put(ticker, current);
-
- if (current == 0) {
- sharesOwnedBySymbol.remove(ticker);
- averagePriceBySymbol.remove(ticker);
- removeFavorite(ticker);
- }
- }
-
- @Override
- public void setStockValue(int value) {
- super.setStockValue(value);
- }
-
- /**
- * Regenerate the favorites query.
- */
- private void generateFavoritesQuery() {
- StringBuilder sb = new StringBuilder(IMPOSSIBLE_TICKER_SYMBOL);
- for (String ticker : favorites) {
- sb.append('|');
- sb.append(ticker);
- }
- favoritesQuery = sb.toString();
- favoritesPattern = Pattern.compile(favoritesQuery);
- }
-}
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/server/StockServiceImpl.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/server/StockServiceImpl.java
deleted file mode 100644
index a22fcb4..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/server/StockServiceImpl.java
+++ /dev/null
@@ -1,489 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.server;
-
-import com.google.appengine.api.users.User;
-import com.google.appengine.api.users.UserService;
-import com.google.appengine.api.users.UserServiceFactory;
-import com.google.gwt.sample.bikeshed.stocks.client.StockService;
-import com.google.gwt.sample.bikeshed.stocks.shared.PlayerInfo;
-import com.google.gwt.sample.bikeshed.stocks.shared.StockQuote;
-import com.google.gwt.sample.bikeshed.stocks.shared.StockQuoteList;
-import com.google.gwt.sample.bikeshed.stocks.shared.StockRequest;
-import com.google.gwt.sample.bikeshed.stocks.shared.StockResponse;
-import com.google.gwt.sample.bikeshed.stocks.shared.Transaction;
-import com.google.gwt.user.server.rpc.RemoteServiceServlet;
-import com.google.gwt.view.client.Range;
-import com.google.gwt.view.client.AbstractListViewAdapter.DefaultRange;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
-import java.util.SortedSet;
-import java.util.TreeSet;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.regex.PatternSyntaxException;
-
-/**
- * The server side implementation of the RPC service.
- */
-@SuppressWarnings("serial")
-public class StockServiceImpl extends RemoteServiceServlet implements
- StockService {
-
- static class Quote {
- String change;
- long createdTime;
- int price;
-
- public Quote(int price, String change) {
- this.price = price;
- this.change = change;
- this.createdTime = System.currentTimeMillis();
- }
-
- public String getChange() {
- return change;
- }
-
- public long getCreatedTime() {
- return createdTime;
- }
-
- public int getPrice() {
- return price;
- }
- }
-
- /**
- * The result of a query to the remote service that provides stock quotes.
- */
- private static class Result {
- int numRows;
- StockQuoteList quotes;
-
- public Result(StockQuoteList quotes, int numRows) {
- this.quotes = quotes;
- this.numRows = numRows;
- }
- }
-
- private static final int MAX_RESULTS_TO_RETURN = 10000;
-
- private static final Map<String, Quote> QUOTES = new HashMap<String, Quote>();
-
- private static final HashMap<String,Pattern> sectorPatterns =
- new HashMap<String,Pattern>();
-
- private static final HashMap<String,String> sectorQueries =
- new HashMap<String,String>();
-
- static {
- sectorQueries.put("DOW JONES INDUSTRIALS",
- "AA|AXP|BA|BAC|CAT|CSCO|CVX|DD|DIS|GE|HD|HPQ|IBM|INTC|JNJ|JPM|KFT|KO|" +
- "MCD|MMM|MRK|MSFT|PFE|PG|T|TRV|UTX|VZ|WMT|XOM");
- sectorQueries.put("S&P 500",
- "A|AA|AAPL|ABC|ABT|ACS|ADBE|ADI|ADM|ADP|ADSK|AEE|AEP|AES|AET|AFL|AGN|" +
- "AIG|AIV|AIZ|AKAM|AKS|ALL|ALTR|AMAT|AMD|AMGN|AMP|AMT|AMZN|AN|ANF|AON|" +
- "APA|APC|APD|APOL|ASH|ATI|AVB|AVP|AVY|AXP|AYE|AZO|BA|BAC|BAX|BBBY|" +
- "BBT|BBY|BCR|BDK|BDX|BEN|BF.B|BHI|BIG|BIIB|BJS|BK|BLL|BMC|BMS|BMY|" +
- "BRCM|BRK.B|BSX|BTU|BXP|C|CA|CAG|CAH|CAM|CAT|CB|CBE|CBG|CBS|CCE|CCL|" +
- "CEG|CELG|CEPH|CF|CFN|CHK|CHRW|CI|CINF|CL|CLF|CLX|CMA|CMCSA|CME|CMI|" +
- "CMS|CNP|CNX|COF|COG|COH|COL|COP|COST|CPB|CPWR|CRM|CSC|CSCO|CSX|CTAS|" +
- "CTL|CTSH|CTXS|CVH|CVS|CVX|D|DD|DE|DELL|DF|DFS|DGX|DHI|DHR|DIS|DNB|" +
- "DNR|DO|DOV|DOW|DPS|DRI|DTE|DTV|DUK|DV|DVA|DVN|EBAY|ECL|ED|EFX|EIX|" +
- "EK|EL|EMC|EMN|EMR|EOG|EP|EQR|EQT|ERTS|ESRX|ETFC|ETN|ETR|EXC|EXPD|" +
- "EXPE|F|FAST|FCX|FDO|FDX|FE|FHN|FII|FIS|FISV|FITB|FLIR|FLR|FLS|FMC|" +
- "FO|FPL|FRX|FSLR|FTI|FTR|GAS|GCI|GD|GE|GENZ|GILD|GIS|GLW|GME|GNW|" +
- "GOOG|GPC|GPS|GR|GS|GT|GWW|HAL|HAR|HAS|HBAN|HCBK|HCN|HCP|HD|HES|HIG|" +
- "HNZ|HOG|HON|HOT|HPQ|HRB|HRL|HRS|HSP|HST|HSY|HUM|IBM|ICE|IFF|IGT|" +
- "INTC|INTU|IP|IPG|IRM|ISRG|ITT|ITW|IVZ|JBL|JCI|JCP|JDSU|JEC|JNJ|JNPR|" +
- "JNS|JPM|JWN|K|KEY|KFT|KG|KIM|KLAC|KMB|KO|KR|KSS|L|LEG|LEN|LH|LIFE|" +
- "LLL|LLTC|LLY|LM|LMT|LNC|LO|LOW|LSI|LTD|LUK|LUV|LXK|M|MA|MAR|MAS|MAT|" +
- "MCD|MCHP|MCK|MCO|MDP|MDT|MEE|MET|MFE|MHP|MHS|MI|MIL|MJN|MKC|MMC|MMM|" +
- "MO|MOLX|MON|MOT|MRK|MRO|MS|MSFT|MTB|MU|MUR|MWV|MWW|MXB|MYL|NBL|NBR|" +
- "NDAQ|NEM|NI|NKE|NOC|NOV|NOVL|NSC|NSM|NTAP|NTRS|NU|NUE|NVDA|NVLS|NWL|" +
- "NWSA|NYT|NYX|ODP|OI|OMC|ORCL|ORLY|OXY|PAYX|PBCT|PBG|PBI|PCAR|PCG|" +
- "PCL|PCP|PCS|PDCO|PEG|PEP|PFE|PFG|PG|PGN|PGR|PH|PHM|PKI|PLD|PLL|PM|" +
- "PNC|PNW|POM|PPG|PPL|PRU|PSA|PTV|PWR|PX|PXD|Q|QCOM|QLGC|R|RAI|RDC|RF|" +
- "RHI|RHT|RL|ROK|ROP|ROST|RRC|RRD|RSG|RSH|RTN|RX|S|SAI|SBUX|SCG|SCHW|" +
- "SE|SEE|SHLD|SHW|SIAL|SII|SJM|SLB|SLE|SLM|SNA|SNDK|SNI|SO|SPG|SPLS|" +
- "SRCL|SRE|STI|STJ|STR|STT|STZ|SUN|SVU|SWK|SWN|SWY|SYK|SYMC|SYY|T|TAP|" +
- "TDC|TE|TEG|TER|TGT|THC|TIE|TIF|TJX|TLAB|TMK|TMO|TROW|TRV|TSN|TSO|" +
- "TSS|TWC|TWX|TXN|TXT|UNH|UNM|UNP|UPS|USB|UTX|V|VAR|VFC|VIAb|VLO|VMC|" +
- "VNO|VRSN|VTR|VZ|WAG|WAT|WDC|WEC|WFC|WFMI|WFR|WHR|WIN|WLP|WM|WMB|WMT|" +
- "WPI|WPO|WU|WY|WYN|WYNN|X|XEL|XL|XLNX|XOM|XRAY|XRX|XTO|YHOO|YUM|ZION|" +
- "ZMH");
-
- // Precompile each regex
- for (Map.Entry<String, String> entry : sectorQueries.entrySet()) {
- sectorPatterns.put(entry.getKey(), compile(entry.getValue()));
- }
- }
-
- private static Pattern compile(String query) {
- try {
- return Pattern.compile(query);
- } catch (PatternSyntaxException e) {
- return null;
- }
- }
-
- /**
- * A mapping of usernames to {@link PlayerStatus}.
- */
- private Map<String, PlayerStatus> players =
- new HashMap<String, PlayerStatus>();
-
- public StockResponse addFavorite(String ticker, Range favoritesRange) {
- PlayerStatus player = ensurePlayer();
- player.addFavorite(ticker);
- Result favorites = queryFavorites(favoritesRange);
- player.addStatus(player.getDisplayName() + " added " + ticker
- + " to favorites");
- return createStockResponse(player, null, null, favorites, null, null);
- }
-
- public Result getSectorQuotes(String sector, Range sectorRange) {
- sector = sector.toUpperCase();
- String sectorQuery = sectorQueries.get(sector);
- if (sectorQuery == null) {
- return null;
- }
- Pattern sectorPattern = sectorPatterns.get(sector);
- return queryTickerRegex(sectorPattern, sectorRange);
- }
-
- public StockResponse getStockQuotes(StockRequest request)
- throws IllegalArgumentException {
-
- String query = request.getSearchQuery();
- if (query == null || query.length() == 0) {
- query = ".*";
- }
- Range searchRange = request.getSearchRange();
- Range favoritesRange = request.getFavoritesRange();
- Range sectorRange = request.getSectorRange();
-
- PlayerStatus player = ensurePlayer();
- Result searchResults = searchRange != null ?
- getSearchQuotes(query, searchRange) : null;
- Result favorites = queryFavorites(favoritesRange);
- String sectorName = request.getSector();
- Result sector = sectorRange != null ? getSectorQuotes(sectorName,
- sectorRange) : null;
-
- return createStockResponse(player, request.getSearchQuery(), searchResults,
- favorites, sectorName, sector);
- }
-
- public StockResponse removeFavorite(String ticker, Range favoritesRange) {
- PlayerStatus player = ensurePlayer();
- player.removeFavorite(ticker);
- Result favorites = queryFavorites(favoritesRange);
- player.addStatus(player.getDisplayName() + " removed " + ticker
- + " from favorites");
- return createStockResponse(player, null, null, favorites, null, null);
- }
-
- public Transaction transact(Transaction transaction)
- throws IllegalArgumentException {
- // Get the current stock price.
- String ticker = transaction.getTicker();
- if (ticker == null || ticker.length() < 0) {
- throw new IllegalArgumentException("Stock could not be found");
- }
-
- Result result = queryExactTicker(ticker);
- if (result.numRows != 1 || result.quotes.size() != 1) {
- throw new IllegalArgumentException("Could not resolve stock ticker");
- }
- StockQuote quote = result.quotes.get(0);
-
- // Perform the transaction with the user.
- int quantity = transaction.getQuantity();
- int price = quote.getPrice();
-
- PlayerStatus player = ensurePlayer();
- if (transaction.isBuy()) {
- player.buy(ticker, quantity, price);
- player.addStatus(player.getDisplayName() + " bought " + quantity +
- " share" + ((quantity == 1) ? "" : "s") + " of " + ticker);
- } else {
- player.sell(ticker, quantity, price);
- player.addStatus(player.getDisplayName() + " sold " + quantity +
- " share" + ((quantity == 1) ? "" : "s") + " of " + ticker);
- }
-
- return new Transaction(transaction.isBuy(), ticker, quantity, price);
- }
-
- /**
- * Create a stock response, updating the current user's net worth.
- *
- * @param player the player info
- * @param searchQuery the original search query
- * @param searchResults the search results
- * @param favorites the users favorites
- * @param sectorName the name of the sector
- * @param sectorResults the sector results
- * @return a {@link StockResponse}
- */
- private StockResponse createStockResponse(PlayerStatus player,
- String searchQuery, Result searchResults, Result favorites,
- String sectorName, Result sectorResults) {
- // Default to no search results.
- if (searchResults == null) {
- searchResults = new Result(null, 0);
- }
-
- // Default to no sector results.
- if (sectorResults == null) {
- sectorResults = new Result(null, 0);
- }
-
- // Store the new stock value.
- player.setStockValue(favorites.quotes.getValue());
-
- // Create a stock response.
- List<PlayerInfo> playerInfo = new ArrayList<PlayerInfo>();
- for (PlayerStatus curPlayer : players.values()) {
- playerInfo.add(curPlayer.copy());
- }
- Collections.sort(playerInfo, new Comparator<PlayerInfo>() {
- public int compare(PlayerInfo o1, PlayerInfo o2) {
- // Reverse sort so top player is first.
- return o2.getNetWorth() - o1.getNetWorth();
- }
- });
- StockResponse response = new StockResponse(player.copy(), searchQuery,
- searchResults.quotes, favorites.quotes, sectorName != null ? sectorName
- : null, sectorResults.quotes, searchResults.numRows,
- favorites.numRows, sectorResults.numRows, playerInfo);
-
- return response;
- }
-
- /**
- * Ensure that a {@link PlayerStatus} for the current player exists and return
- * it.
- *
- * @return the {@link PlayerStatus} for the current player
- */
- private PlayerStatus ensurePlayer() {
- UserService userService = UserServiceFactory.getUserService();
- User user = userService.getCurrentUser();
- String userId = user.getUserId();
- PlayerStatus player = players.get(userId);
- if (player == null) {
- player = new PlayerStatus(user.getNickname());
- players.put(userId, player);
- }
- return player;
- }
-
- private Result getQuotes(SortedSet<String> symbols, Range range) {
- int start = range.getStart();
- int end = Math.min(start + range.getLength(), symbols.size());
-
- if (end <= start) {
- return new Result(new StockQuoteList(0), 0);
- }
-
- // Get the symbols that are in range.
- SortedSet<String> symbolsInRange = new TreeSet<String>();
- int idx = 0;
- for (String symbol : symbols) {
- if (idx >= start && idx < end) {
- symbolsInRange.add(symbol);
- }
- idx++;
- }
-
- // If we already have a price that is less than 5 seconds old,
- // don't re-request the data from the server
-
- SortedSet<String> symbolsToQuery = new TreeSet<String>();
- long now = System.currentTimeMillis();
- for (String symbol : symbolsInRange) {
- Quote quote = QUOTES.get(symbol);
- if (quote == null || now - quote.getCreatedTime() >= 5000) {
- symbolsToQuery.add(symbol);
- // System.out.println("retrieving new value of " + symbol);
- } else {
- // System.out.println("Using cached value of " + symbol + " (" + (now -
- // quote.getCreatedTime()) + "ms old)");
- }
- }
-
- if (symbolsToQuery.size() > 0) {
- GoogleFinance.queryServer(symbolsToQuery, QUOTES);
- }
-
- // Create and return a StockQuoteList containing the quotes
- StockQuoteList toRet = new StockQuoteList(start);
- for (String symbol : symbolsInRange) {
- Quote quote = QUOTES.get(symbol);
-
- if (quote == null) {
- System.out.println("Bad symbol " + symbol);
- } else {
- String name = Stocks.companyNamesBySymbol.get(symbol);
- PlayerStatus player = ensurePlayer();
- Integer sharesOwned = player.getSharesOwned(symbol);
- boolean favorite = player.isFavorite(symbol);
- int totalPaid = player.getAverageCostBasis(symbol);
-
- toRet.add(new StockQuote(symbol, name, quote.getPrice(),
- quote.getChange(),
- sharesOwned == null ? 0 : sharesOwned.intValue(), favorite,
- totalPaid));
- }
- }
-
- return new Result(toRet, symbols.size());
- }
-
- // If a query is alpha-only ([A-Za-z]+), return stocks for which:
- // 1a) a prefix of the ticker symbol matches the query
- // 2) any substring of the stock name matches the query
- //
- // If a query is non-alpha, consider it as a regex and return stocks for
- // which:
- // 1b) any portion of the stock symbol matches the regex
- // 2) any portion of the stock name matches the regex
- private Result getSearchQuotes(String query, Range searchRange) {
- SortedSet<String> symbols = new TreeSet<String>();
-
- boolean queryIsAlpha = true;
- for (int i = 0; i < query.length(); i++) {
- char c = query.charAt(i);
- if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z')) {
- queryIsAlpha = false;
- break;
- }
- }
-
- // Canonicalize case
- query = query.toUpperCase(Locale.US);
-
- // (1a)
- if (queryIsAlpha) {
- getTickersByPrefix(query, symbols);
- }
-
- // Use Unicode case-insensitive matching, allow matching of a substring
- Pattern pattern = compile("(?iu).*(" + query + ").*");
- if (pattern != null) {
- // (1b)
- if (!queryIsAlpha) {
- getTickersBySymbolRegex(pattern, symbols);
- }
-
- // (2)
- if (query.length() > 2) {
- getTickersByNameRegex(pattern, symbols);
- }
- }
-
- return getQuotes(symbols, searchRange);
- }
-
- // Assume pattern is upper case
- private void getTickersByNameRegex(Pattern pattern, Set<String> tickers) {
- if (pattern == null) {
- return;
- }
-
- for (Map.Entry<String, String> entry : Stocks.companyNamesBySymbol.entrySet()) {
- if (tickers.size() >= MAX_RESULTS_TO_RETURN) {
- return;
- }
-
- if (match(entry.getValue(), pattern)) {
- tickers.add(entry.getKey());
- }
- }
- }
-
- // Assume prefix is upper case
- private void getTickersByPrefix(String prefix, Set<String> tickers) {
- if (prefix == null || prefix.length() == 0) {
- return;
- }
-
- for (String ticker : Stocks.stockTickers) {
- if (tickers.size() >= MAX_RESULTS_TO_RETURN) {
- break;
- }
-
- if (ticker.startsWith(prefix)) {
- tickers.add(ticker);
- }
- }
- }
-
- // Assume pattern is upper case
- private void getTickersBySymbolRegex(Pattern pattern, Set<String> tickers) {
- if (pattern == null) {
- return;
- }
-
- for (String ticker : Stocks.stockTickers) {
- if (tickers.size() >= MAX_RESULTS_TO_RETURN) {
- return;
- }
- if (match(ticker, pattern)) {
- tickers.add(ticker);
- }
- }
- }
-
- private boolean match(String symbol, Pattern pattern) {
- Matcher m = pattern.matcher(symbol);
- return m.matches();
- }
-
- private Result queryExactTicker(String ticker) {
- SortedSet<String> symbols = new TreeSet<String>();
- symbols.add(ticker);
- return getQuotes(symbols, new DefaultRange(0, 1));
- }
-
- private Result queryFavorites(Range favoritesRange) {
- PlayerStatus player = ensurePlayer();
- SortedSet<String> symbols = new TreeSet<String>();
-
- Pattern favoritesPattern = player.getFavoritesPattern();
- if (favoritesPattern != null) {
- getTickersBySymbolRegex(favoritesPattern, symbols);
- }
-
- return getQuotes(symbols, favoritesRange);
- }
-
- private Result queryTickerRegex(Pattern pattern, Range range) {
- SortedSet<String> symbols = new TreeSet<String>();
- getTickersBySymbolRegex(pattern, symbols);
- return getQuotes(symbols, range);
- }
-}
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/server/Stocks.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/server/Stocks.java
deleted file mode 100644
index f06e9dd..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/server/Stocks.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.server;
-
-import java.io.BufferedReader;
-import java.io.FileReader;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.TreeSet;
-
-/**
- * A list of NYSE and NASDAQ stocks (note: this is a snapshot plus some
- * corrections, not a definitive list). Stocks are listed in the file
- * symbols.txt, which contains a series of lines of the form:
- *
- * <ticker> <name>
- */
-public class Stocks {
-
- public static final List<String> SYMBOLS = new ArrayList<String>();
-
- public static final HashMap<String, String> companyNamesBySymbol =
- new HashMap<String, String>();
-
- public static final TreeSet<String> stockTickers = new TreeSet<String>();
-
- static {
- try {
- BufferedReader reader = new BufferedReader(new FileReader("symbols.txt"));
- String s;
- while ((s = reader.readLine()) != null) {
- int index = s.indexOf(' ');
- String symbol = s.substring(0, index).trim();
- String name = s.substring(index + 1).trim();
- SYMBOLS.add(symbol);
- SYMBOLS.add(name);
- }
- reader.close();
- } catch (IOException e) {
- }
-
- int num = SYMBOLS.size();
- for (int i = 0; i < num - 1; i += 2) {
- String symbol = SYMBOLS.get(i);
- String companyName = SYMBOLS.get(i + 1);
- stockTickers.add(symbol);
- companyNamesBySymbol.put(symbol, companyName);
- }
- }
-}
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/shared/PlayerInfo.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/shared/PlayerInfo.java
deleted file mode 100644
index de593d0..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/shared/PlayerInfo.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.shared;
-
-import java.io.Serializable;
-import java.util.LinkedList;
-import java.util.List;
-
-/**
- * Information about a single player.
- */
-public class PlayerInfo implements Serializable {
-
- private static final int MAX_STATUS = 5;
-
- /**
- * The initial amount of cash that the player starts with, in cents.
- */
- private static final int INITIAL_CASH = 10000 * 100;
-
- /**
- * The net worth of the player in cents.
- */
- private int cash = INITIAL_CASH;
-
- /**
- * The players name.
- */
- private String name;
-
- private LinkedList<String> status;
-
- /**
- * The net worth of the player in cents.
- */
- private int stockValue;
-
- public PlayerInfo(String name) {
- this.name = name;
- }
-
- /**
- * Visible for RPC.
- */
- PlayerInfo() {
- }
-
- public void addStatus(String message) {
- if (status == null) {
- status = new LinkedList<String>();
- }
- status.add(message);
- if (status.size() > MAX_STATUS) {
- status.removeFirst();
- }
- }
-
- public PlayerInfo copy() {
- PlayerInfo copy = new PlayerInfo(name);
- copy.setCash(cash);
- copy.setStockValue(stockValue);
- copy.setStatus(status);
- return copy;
- }
-
- /**
- * Get the player's current cash amount.
- *
- * @return the cash amount
- */
- public int getCash() {
- return cash;
- }
-
- /**
- * Get the player's display name, which excludes domain information.
- *
- * @return the display name of the player.
- */
- public String getDisplayName() {
- String displayName = name;
- int domain = displayName.indexOf('@');
- if (domain > 0) {
- displayName = displayName.substring(0, domain);
- }
- return displayName;
- }
-
- /**
- * Get the player's name.
- *
- * @return the name of the player.
- */
- public String getName() {
- return name;
- }
-
- /**
- * Get the players net worth, including cash and stock value.
- *
- * @return the net worth in cents
- */
- public int getNetWorth() {
- return cash + stockValue;
- }
-
- public List<String> getStatus() {
- return status;
- }
-
- /**
- * Get the value of this player's stock.
- *
- * @return the value of the stock in cents
- */
- public int getStockValue() {
- return stockValue;
- }
-
- /**
- * Set the amount of cash that the user has.
- *
- * @param cash the user's cash in cents
- */
- protected void setCash(int cash) {
- this.cash = cash;
- }
-
- /**
- * Set the value of this player's stock.
- *
- * @param value the stock value in cents
- */
- protected void setStockValue(int value) {
- this.stockValue = value;
- }
-
- private void setStatus(List<String> status) {
- this.status = status == null ? null : new LinkedList<String>(status);
- }
-}
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/shared/StockQuote.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/shared/StockQuote.java
deleted file mode 100644
index 51451cc..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/shared/StockQuote.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.shared;
-
-import com.google.gwt.view.client.ProvidesKey;
-
-import java.io.Serializable;
-
-/**
- * A single stock quote.
- */
-public class StockQuote implements Serializable {
-
- /**
- * Provides the key for {@link StockQuote}.
- */
- public static final ProvidesKey<StockQuote> KEY_PROVIDER = new ProvidesKey<StockQuote>() {
- public Object getKey(StockQuote item) {
- return item.getTicker();
- }
- };
-
- private boolean favorite;
- private String name;
- private int price;
- private String change;
- private String ticker;
- private int sharesOwned;
- private int totalPaid; // Total amount paid for all share, int pennies
-
- /**
- * Construct a new {@link StockQuote}.
- *
- * @param ticker the ticket symbol
- * @param name the company name
- * @param price the price in pennies
- * @param sharesOwned the number of shares owned by the player
- * @param favorite true if the stock is in the player's favorites
- */
- public StockQuote(String ticker, String name, int price, String change, int sharesOwned,
- boolean favorite, int totalPaid) {
- this.ticker = ticker;
- this.name = name;
- this.price = price;
- this.change = change;
- this.sharesOwned = sharesOwned;
- this.favorite = favorite;
- this.totalPaid = totalPaid;
- }
-
- /**
- * Used for RPC.
- */
- StockQuote() {
- }
-
- public String getChange() {
- return change;
- }
-
- public String getDisplayPrice() {
- int dollars = getPrice() / 100;
- int cents = getPrice() % 100;
-
- StringBuilder sb = new StringBuilder();
- sb.append("$ ");
- sb.append(dollars);
- sb.append('.');
- if (cents < 10) {
- sb.append('0');
- }
- sb.append(cents);
- return sb.toString();
- }
-
- public String getName() {
- return name;
- }
-
- public int getPrice() {
- return price;
- }
-
- public int getSharesOwned() {
- return sharesOwned;
- }
-
- public String getTicker() {
- return ticker;
- }
-
- public int getTotalPaid() {
- return totalPaid;
- }
-
- public int getValue() {
- return price * sharesOwned;
- }
-
- public boolean isFavorite() {
- return favorite;
- }
-
- @Override
- public String toString() {
- return "StockQuote [ticker=" + ticker + ", name=\"" + name + "\", price="
- + price + ", favorite=" + favorite
- + ", totalPaid=" + totalPaid + "]";
- }
-}
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/shared/StockQuoteList.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/shared/StockQuoteList.java
deleted file mode 100644
index 93b69e2..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/shared/StockQuoteList.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.shared;
-
-import java.util.ArrayList;
-
-/**
- * A list of {@link StockQuote} that knows its start index in the global list of
- * results.
- */
-public class StockQuoteList extends ArrayList<StockQuote> {
-
- private int start;
-
- public StockQuoteList(int start) {
- this.start = start;
- }
-
- /**
- * Used by RPC.
- */
- StockQuoteList() {
- }
-
- public int getStartIndex() {
- return start;
- }
-
- /**
- * Returns the sum of stock prices times shares owned, in pennies.
- */
- public int getValue() {
- int value = 0;
- for (StockQuote q : this) {
- value += q.getPrice() * q.getSharesOwned();
- }
- return value;
- }
-}
-
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/shared/StockRequest.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/shared/StockRequest.java
deleted file mode 100644
index 0f8fa9f..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/shared/StockRequest.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.shared;
-
-import com.google.gwt.view.client.Range;
-
-import java.io.Serializable;
-
-/**
- * A request for new stock data.
- */
-public class StockRequest implements Serializable {
-
- Range favoritesRange;
- String searchQuery;
- Range searchRange;
- String sector;
- Range sectorRange;
-
- public StockRequest(String searchQuery, String sector, Range searchRange,
- Range favoritesRange, Range sectorRange) {
- this.searchQuery = searchQuery;
- this.sector = sector;
- this.searchRange = searchRange;
- this.favoritesRange = favoritesRange;
- this.sectorRange = sectorRange;
- }
-
- /**
- * Used by RPC.
- */
- StockRequest() {
- }
-
- public Range getFavoritesRange() {
- return favoritesRange;
- }
-
- public String getSearchQuery() {
- return searchQuery;
- }
-
- public Range getSearchRange() {
- return searchRange;
- }
-
- public String getSector() {
- return sector;
- }
-
- public Range getSectorRange() {
- return sectorRange;
- }
-}
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/shared/StockResponse.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/shared/StockResponse.java
deleted file mode 100644
index 4405945..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/shared/StockResponse.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.shared;
-
-import java.io.Serializable;
-import java.util.List;
-
-/**
- * A response to a request for stock data.
- */
-public class StockResponse implements Serializable {
-
- /**
- * The amount of available cash in pennies.
- */
- private String searchQuery;
- private StockQuoteList favorites;
- private int numFavorites;
- private int numSearchResults;
- private int numSector;
- private StockQuoteList searchResults;
- private StockQuoteList sector;
- private String sectorName;
- private PlayerInfo player;
- private List<PlayerInfo> playerInfo;
-
- public StockResponse(PlayerInfo player, String searchQuery,
- StockQuoteList searchResults, StockQuoteList favorites,
- String sectorName, StockQuoteList sector, int numSearchResults,
- int numFavorites, int numSector, List<PlayerInfo> playerInfo) {
- this.player = player;
- this.searchQuery = searchQuery;
- this.searchResults = searchResults;
- this.favorites = favorites;
- this.sectorName = sectorName;
- this.sector = sector;
- this.numSearchResults = numSearchResults;
- this.numFavorites = numFavorites;
- this.numSector = numSector;
- this.playerInfo = playerInfo;
- }
-
- /**
- * Used for RPC.
- */
- StockResponse() {
- }
-
- public int getCash() {
- return player.getCash();
- }
-
- public StockQuoteList getFavorites() {
- return favorites;
- }
-
- /**
- * The sum of cash available and portfolio value.
- */
- public int getNetWorth() {
- return player.getNetWorth();
- }
-
- public int getNumFavorites() {
- return numFavorites;
- }
-
- public int getNumSearchResults() {
- return numSearchResults;
- }
-
- public int getNumSector() {
- return numSector;
- }
-
- /**
- * Get the list of all players and their scores.
- *
- * @return the ordered list of all players
- */
- public List<PlayerInfo> getPlayers() {
- return playerInfo;
- }
-
- public String getSearchQuery() {
- return searchQuery;
- }
-
- public StockQuoteList getSearchResults() {
- return searchResults;
- }
-
- public StockQuoteList getSector() {
- return sector;
- }
-
- public String getSectorName() {
- return sectorName;
- }
-}
diff --git a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/shared/Transaction.java b/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/shared/Transaction.java
deleted file mode 100644
index 66d0433..0000000
--- a/bikeshed/src/com/google/gwt/sample/bikeshed/stocks/shared/Transaction.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.bikeshed.stocks.shared;
-
-import com.google.gwt.i18n.client.NumberFormat;
-
-import java.io.Serializable;
-
-/**
- * The buy or sell transaction.
- */
-public class Transaction implements Serializable {
-
- private int actualPrice; // in pennies
-
- /**
- * True if a buy transaction, false if a sell transaction.
- */
- private boolean isBuy;
-
- private int quantity;
- private String ticker;
-
- public Transaction(boolean isBuy, String ticker, int quantity) {
- this(isBuy, ticker, quantity, -1);
- }
-
- public Transaction(boolean isBuy, String ticker, int quantity,
- int actualPrice) {
- super();
- this.isBuy = isBuy;
- this.ticker = ticker;
- this.quantity = quantity;
- this.actualPrice = actualPrice;
- }
-
- Transaction() {
- }
-
- public int getActualPrice() {
- return actualPrice;
- }
-
- public int getQuantity() {
- return quantity;
- }
-
- public String getTicker() {
- return ticker;
- }
-
- public boolean isBuy() {
- return isBuy;
- }
-
- @Override
- public String toString() {
- String op = isBuy ? "Bought" : "Sold";
- if (actualPrice == -1) {
- return op + " " + quantity + " shares of " + ticker;
- } else {
- return op + " " + quantity + " shares of " + ticker + " at " +
- NumberFormat.getCurrencyFormat("USD").format(actualPrice / 100.0);
- }
- }
-}
diff --git a/bikeshed/src/com/google/gwt/sample/expenses/server/ExpensesDataServlet.java b/bikeshed/src/com/google/gwt/sample/expenses/server/ExpensesDataServlet.java
deleted file mode 100644
index 4c50d4d..0000000
--- a/bikeshed/src/com/google/gwt/sample/expenses/server/ExpensesDataServlet.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.sample.expenses.server;
-
-import com.google.gwt.requestfactory.server.RequestFactoryServlet;
-import com.google.gwt.sample.expenses.server.domain.Employee;
-import com.google.gwt.sample.expenses.server.domain.Expense;
-import com.google.gwt.sample.expenses.server.domain.Report;
-
-import java.util.Date;
-import java.util.Random;
-
-/**
- * Dwindling interim servlet that calls our mock storage backend directly
- * instead of reflectively. Should soon vanish completely.
- */
-@SuppressWarnings("serial")
-public class ExpensesDataServlet extends RequestFactoryServlet {
-
- // Must be in sync with DESCRIPTIONS
- private static final String[] CATEGORIES = {
- "Dining", "Dining", "Dining", "Lodging", "Lodging",
- "Local Transportation", "Local Transportation", "Local Transportation",
- "Air Travel", "Air Travel", "Office Supplies", "Office Supplies",
- "Office Supplies", "Office Supplies",};
-
- private static final String[] DEPARTMENTS = {
- "Sales", "Marketing", "Engineering", "Operations"};
-
- // Must be in sync with CATEGORIES
- private static final String[] DESCRIPTIONS = {
- "Breakfast", "Lunch", "Dinner", "Hotel", "Bed & Breakfast", "Train fare",
- "Taxi fare", "Bus ticket", "Flight from ATL to SFO",
- "Flight from SFO to ATL", "Paperclips", "Stapler", "Scissors", "Paste",};
-
- private static final String[] FIRST_NAMES = {
- "Amy", "Bob", "Catherine", "Dave", "Earl", "Flin", "George", "Harriot",
- "Ingrid", "John", "Katy", "Leo", "Mike", "Nancy", "Owen", "Paul",
- "Reece", "Sally", "Terry", "Val", "Wes", "Xavier", "Zack"};
-
- private static final String[] LAST_NAMES = {
- "Awesome", "Bravo", "Cool", "Fantastic", "Great", "Happy",
- "Ignoranomous", "Krazy", "Luminous", "Magnanimous", "Outstanding",
- "Perfect", "Radical", "Stellar", "Terrific", "Wonderful"};
-
- private static final String[] NOTES = {
- // Some entries do not have notes.
- "", "Need approval by Monday", "Show me the money",
- "Please bill to the Widgets project", "High priority", "Review A.S.A.P."};
-
- private static final String[] PURPOSES = {
- "Spending lots of money", "Team building diamond cutting offsite",
- "Visit to Istanbul", "ISDN modem for telecommuting", "Sushi offsite",
- "Baseball card research", "Potato chip cooking offsite",
- "Money laundering", "Donut day"};
-
- Random rand = new Random();
-
- @Override
- protected void initDb() {
- long size = Employee.countEmployees();
- if (size > 1) {
- return;
- }
-
- // Initialize the database.
- for (int i = 0; i < 100; i++) {
- addEmployee();
- }
- }
-
- /**
- * Add a randomly generated employee.
- */
- private void addEmployee() {
- Employee abc = new Employee();
- String firstName = nextValue(FIRST_NAMES);
- String lastName = nextValue(LAST_NAMES);
- String username = (firstName.charAt(0) + lastName).toLowerCase();
- abc.setUserName(username);
- abc.setDisplayName(firstName + " " + lastName);
- abc.setDepartment(nextValue(DEPARTMENTS));
- abc.persist();
-
- addReports(abc.getId());
- }
-
- private void addExpenses(Long reportId) {
- int num = rand.nextInt(5) + 1;
- for (int i = 0; i < num; i++) {
- int index = rand.nextInt(DESCRIPTIONS.length);
- Expense detail = new Expense();
- detail.setReportId(reportId);
- detail.setDescription(DESCRIPTIONS[index]);
- detail.setDate(getDate());
- detail.setAmount(rand.nextInt(25000) / 100.0);
- detail.setCategory(CATEGORIES[index]);
- detail.setApproval("");
- detail.setReasonDenied("");
- detail.persist();
- }
- }
-
- /**
- * Add a randomly generated report.
- *
- * @param employeeId the id of the employee who created the report
- */
- private void addReports(Long employeeId) {
- // Add 1-20 expense reports.
- int reportCount = 1 + rand.nextInt(20);
- for (int i = 0; i < reportCount; i++) {
- Report report = new Report();
- report.setCreated(getDate());
- report.setReporterKey(employeeId);
- report.setPurpose(nextValue(PURPOSES));
- report.setNotes(nextValue(NOTES));
- report.persist();
-
- addExpenses(report.getId());
- }
- }
-
- private Date getDate() {
- long now = new Date().getTime();
- // Go back up to 90 days from the current date
- long dateOffset = rand.nextInt(60 * 60 * 24 * 90) * 1000L;
- return new Date(now - dateOffset);
- }
-
- /**
- * Get the next random value from an array.
- *
- * @param array the array
- * @return a random value from the array
- */
- private String nextValue(String[] array) {
- return array[rand.nextInt(array.length)];
- }
-}
diff --git a/bikeshed/src/com/google/gwt/valuestore/ui/AbstractRecordEditActivity.java b/bikeshed/src/com/google/gwt/valuestore/ui/AbstractRecordEditActivity.java
deleted file mode 100644
index 9599af6..0000000
--- a/bikeshed/src/com/google/gwt/valuestore/ui/AbstractRecordEditActivity.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.valuestore.ui;
-
-import com.google.gwt.app.place.Activity;
-import com.google.gwt.requestfactory.shared.Receiver;
-import com.google.gwt.requestfactory.shared.RequestFactory;
-import com.google.gwt.requestfactory.shared.SyncResult;
-import com.google.gwt.user.client.Window;
-import com.google.gwt.valuestore.shared.DeltaValueStore;
-import com.google.gwt.valuestore.shared.Record;
-import com.google.gwt.valuestore.shared.Value;
-
-import java.util.Set;
-
-/**
- * Abstract activity for editing a record.
- *
- * @param <R> the type of Record being edited
- */
-public abstract class AbstractRecordEditActivity<R extends Record> implements
- Activity, RecordEditView.Delegate {
-
- private final RecordEditView<R> view;
- private final String id;
- private DeltaValueStore deltas;
- private final RequestFactory requests;
- private boolean dead = false;
-
- public AbstractRecordEditActivity(RecordEditView<R> view, String id,
- RequestFactory requests) {
- this.view = view;
- this.id = id;
- this.requests = requests;
- this.deltas = requests.getValueStore().spawnDeltaView();
- view.setDelegate(this);
- view.setDeltaValueStore(deltas);
- }
-
- public void cancelClicked() {
- if (willStop()) {
- exit();
- }
- }
-
- public void onCancel() {
- this.dead = true;
- }
-
- public void onStop() {
- this.dead = true;
- }
-
- public void saveClicked() {
- if (deltas.isChanged()) {
- view.setEnabled(false);
-
- final DeltaValueStore toCommit = deltas;
- deltas = null;
-
- Receiver<Set<SyncResult>> receiver = new Receiver<Set<SyncResult>>() {
- public void onSuccess(Set<SyncResult> response) {
- if (dead) {
- return;
- }
- boolean hasViolations = false;
- for (SyncResult syncResult : response) {
- if (syncResult.getRecord().getId().equals(id)) {
- if (syncResult.hasViolations()) {
- hasViolations = true;
- view.showErrors(syncResult.getViolations());
- }
- }
- }
- if (!hasViolations) {
- exit();
- } else {
- deltas = toCommit;
- deltas.clearUsed();
- view.setEnabled(true);
- deltas.clearUsed();
- }
- }
-
- };
- requests.syncRequest(toCommit).to(receiver).fire();
- }
- }
-
- public void start(final Display display) {
- Receiver<R> callback = new Receiver<R>() {
- public void onSuccess(R record) {
- if (dead) {
- return;
- }
- view.setEnabled(true);
- view.setValue(record);
- view.showErrors(null);
- display.showActivityWidget(view);
- }
- };
-
- fireFindRequest(Value.of(id), callback);
- }
-
- public boolean willStop() {
- return deltas == null || !deltas.isChanged()
- || Window.confirm("Are you sure you want to abandon your changes?");
- }
-
- /**
- * Called when the user has clicked Cancel or has successfully saved.
- */
- protected abstract void exit();
-
- /**
- * Called to fetch the details of the edited record.
- */
- protected abstract void fireFindRequest(Value<String> id, Receiver<R> callback);
-
- protected String getId() {
- return id;
- }
-
-}
diff --git a/bikeshed/src/com/google/gwt/valuestore/ui/AbstractRecordListActivity.java b/bikeshed/src/com/google/gwt/valuestore/ui/AbstractRecordListActivity.java
deleted file mode 100644
index 126da5c..0000000
--- a/bikeshed/src/com/google/gwt/valuestore/ui/AbstractRecordListActivity.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.google.gwt.valuestore.ui;
-
-import com.google.gwt.app.place.Activity;
-import com.google.gwt.requestfactory.shared.Receiver;
-import com.google.gwt.requestfactory.shared.RecordListRequest;
-import com.google.gwt.valuestore.shared.Record;
-import com.google.gwt.view.client.ListView;
-import com.google.gwt.view.client.Range;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Abstract activity for requesting and displaying a list of {@Record}.
- * <p>
- * Subclasses must:
- *
- * <ul>
- * <li>implement a method for creating request objects
- * <li>provide a {@link RecordListView}
- * <li>respond to "show" and "edit" requests
- * </ul>
- *
- * Only the properties required by the view will be requested.
- *
- * @param <R> the type of {@link Record} listed
- */
-public abstract class AbstractRecordListActivity<R extends Record> implements
- Activity, RecordListView.Delegate<R> {
- private final Map<String, Integer> recordToRow = new HashMap<String, Integer>();
-
- private RecordListView<R> view;
- private Display display;
-
- public AbstractRecordListActivity(RecordListView<R> view) {
- this.view = view;
- view.setDelegate(this);
- }
-
- public RecordListView<R> getView() {
- return view;
- }
-
- public void onCancel() {
- onStop();
- }
-
- /**
- * Called by the table as it needs data.
- */
- public void onRangeChanged(ListView<R> listView) {
- final Range range = listView.getRange();
-
- final Receiver<List<R>> callback = new Receiver<List<R>>() {
- public void onSuccess(List<R> values) {
- recordToRow.clear();
- for (int i = 0, r = range.getStart(); i < values.size(); i++, r++) {
- recordToRow.put(values.get(i).getId(), r);
- }
- getView().setData(range.getStart(), range.getLength(), values);
- if (display != null) {
- display.showActivityWidget(getView());
- }
- }
- };
-
- createRangeRequest(range).forProperties(getView().getProperties()).to(
- callback).fire();
- }
-
- public void onStop() {
- view.setDelegate((RecordListView.Delegate<R>) null);
- }
-
- public void start(Display display) {
- this.display = display;
- init();
- }
-
- public void update(R record) {
- // TODO Must handle delete, new
- Integer row = recordToRow.get(record.getId());
- getView().setData(row, 1, Collections.singletonList(record));
- }
-
- public boolean willStop() {
- return true;
- }
-
- protected abstract RecordListRequest<R> createRangeRequest(Range range);
-
- protected abstract void fireCountRequest(Receiver<Long> callback);
-
- private void init() {
- fireCountRequest(new Receiver<Long>() {
- public void onSuccess(Long response) {
- getView().setDataSize(response.intValue(), true);
- onRangeChanged(view);
- }
- });
- }
-}
diff --git a/bikeshed/war/Stocks.html b/bikeshed/war/Stocks.html
deleted file mode 100644
index 0c01bb1..0000000
--- a/bikeshed/war/Stocks.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<!doctype html>
-<html>
- <head>
- <meta http-equiv="content-type" content="text/html; charset=UTF-8">
- <title>Stock Game Sample</title>
- <script type="text/javascript" language="javascript" src="stocksdesktop/stocksdesktop.nocache.js"></script>
- </head>
-
- <body>
- <iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe>
- <noscript>
- <div style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif">
- Your web browser must have JavaScript enabled
- in order for this application to display correctly.
- </div>
- </noscript>
- </body>
-</html>
diff --git a/bikeshed/war/StocksMobile.html b/bikeshed/war/StocksMobile.html
deleted file mode 100644
index c9173d7..0000000
--- a/bikeshed/war/StocksMobile.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<!doctype html>
-<html>
- <head>
- <meta http-equiv="content-type" content="text/html; charset=UTF-8">
- <title>Stock Game Sample</title>
- <script type="text/javascript" language="javascript" src="stocksmobile/stocksmobile.nocache.js"></script>
- </head>
-
- <body>
- <iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe>
- <noscript>
- <div style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif">
- Your web browser must have JavaScript enabled
- in order for this application to display correctly.
- </div>
- </noscript>
- </body>
-</html>