Change OpenButton nomenclature to NavigationButton.
[online-glom:gwt-glom.git] / src / main / java / org / glom / web / client / activity / DetailsActivity.java
1 /*
2  * Copyright (C) 2011 Openismus GmbH
3  *
4  * This file is part of GWT-Glom.
5  *
6  * GWT-Glom is free software: you can redistribute it and/or modify it
7  * under the terms of the GNU Lesser General Public License as published by the
8  * Free Software Foundation, either version 3 of the License, or (at your
9  * option) any later version.
10  *
11  * GWT-Glom is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
14  * for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License
17  * along with GWT-Glom.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 package org.glom.web.client.activity;
21
22 import java.util.ArrayList;
23
24 import org.glom.web.client.ClientFactory;
25 import org.glom.web.client.OnlineGlomServiceAsync;
26 import org.glom.web.client.Utils;
27 import org.glom.web.client.event.TableChangeEvent;
28 import org.glom.web.client.event.TableChangeEventHandler;
29 import org.glom.web.client.place.DetailsPlace;
30 import org.glom.web.client.place.DocumentSelectionPlace;
31 import org.glom.web.client.ui.DetailsView;
32 import org.glom.web.client.ui.cell.NavigationButtonCell;
33 import org.glom.web.client.ui.details.DetailsCell;
34 import org.glom.web.client.ui.details.Portal;
35 import org.glom.web.client.ui.details.RelatedListTable;
36 import org.glom.web.shared.DataItem;
37 import org.glom.web.shared.DetailsLayoutAndData;
38 import org.glom.web.shared.NavigationRecord;
39 import org.glom.web.shared.TypedDataItem;
40 import org.glom.web.shared.layout.LayoutGroup;
41 import org.glom.web.shared.layout.LayoutItemField;
42 import org.glom.web.shared.layout.LayoutItemPortal;
43
44 import com.google.gwt.activity.shared.AbstractActivity;
45 import com.google.gwt.cell.client.ValueUpdater;
46 import com.google.gwt.core.client.GWT;
47 import com.google.gwt.dom.client.Element;
48 import com.google.gwt.dom.client.NativeEvent;
49 import com.google.gwt.event.dom.client.ClickEvent;
50 import com.google.gwt.event.dom.client.ClickHandler;
51 import com.google.gwt.event.shared.EventBus;
52 import com.google.gwt.place.shared.Place;
53 import com.google.gwt.user.client.rpc.AsyncCallback;
54 import com.google.gwt.user.client.ui.AcceptsOneWidget;
55
56 /**
57  * @author Ben Konrath <ben@bagu.org>
58  */
59 public class DetailsActivity extends AbstractActivity implements DetailsView.Presenter {
60         /*
61          * Cell renderer for the related list open buttons. Normally this wouldn't be in an Activity class but since it's
62          * making a call to the server it makes sense for it to be here.
63          */
64         private class RelatedListNavigationButtonCell extends NavigationButtonCell {
65
66                 private String relationshipName;
67
68                 public RelatedListNavigationButtonCell(String relationshipName) {
69                         this.relationshipName = relationshipName;
70                 }
71
72                 /*
73                  * (non-Javadoc)
74                  * 
75                  * @see com.google.gwt.cell.client.ButtonCell#onEnterKeyDown(com.google.gwt.cell.client.Cell.Context,
76                  * com.google.gwt.dom.client.Element, java.lang.String, com.google.gwt.dom.client.NativeEvent,
77                  * com.google.gwt.cell.client.ValueUpdater)
78                  */
79                 @Override
80                 protected void onEnterKeyDown(Context context, Element parent, String value, NativeEvent event,
81                                 ValueUpdater<String> valueUpdater) {
82                         AsyncCallback<NavigationRecord> callback = new AsyncCallback<NavigationRecord>() {
83                                 public void onFailure(Throwable caught) {
84                                         // TODO: create a way to notify users of asynchronous callback failures
85                                         GWT.log("AsyncCallback Failed: OnlineGlomService.getSuitableRecordToViewDetails()");
86                                 }
87
88                                 @Override
89                                 public void onSuccess(NavigationRecord result) {
90                                         processNavgiation(result.getTableName(), result.getPrimaryKeyValue());
91                                 }
92
93                         };
94                         OnlineGlomServiceAsync.Util.getInstance().getSuitableRecordToViewDetails(documentID, tableName,
95                                         relationshipName, (TypedDataItem) context.getKey(), callback);
96                 }
97         }
98
99         private final String documentID;
100         private final String tableName;
101         private TypedDataItem primaryKeyValue;
102         private final ClientFactory clientFactory;
103         private final DetailsView detailsView;
104         ArrayList<DetailsCell> detailsCells;
105         ArrayList<Portal> portals;
106
107         public DetailsActivity(DetailsPlace place, ClientFactory clientFactory) {
108                 this.documentID = place.getDocumentID();
109                 this.tableName = place.getTableName();
110                 this.primaryKeyValue = place.getPrimaryKeyValue();
111                 this.clientFactory = clientFactory;
112                 detailsView = clientFactory.getDetailsView();
113         }
114
115         /*
116          * (non-Javadoc)
117          * 
118          * @see com.google.gwt.activity.shared.Activity#start(com.google.gwt.user.client.ui.AcceptsOneWidget,
119          * com.google.gwt.event.shared.EventBus)
120          */
121         @Override
122         public void start(AcceptsOneWidget panel, EventBus eventBus) {
123                 // register this class as the presenter
124                 detailsView.setPresenter(this);
125
126                 // TODO here's where we should check for database authentication - see ListActivity.start() for how to do this
127
128                 // set the change handler for the table selection widget
129                 eventBus.addHandler(TableChangeEvent.TYPE, new TableChangeEventHandler() {
130                         @Override
131                         public void onTableChange(final TableChangeEvent event) {
132                                 // note the empty primary key item
133                                 goTo(new DetailsPlace(documentID, event.getNewTableName(), new TypedDataItem()));
134                         }
135                 });
136
137                 // get the layout and data for the DetailsView
138                 AsyncCallback<DetailsLayoutAndData> callback = new AsyncCallback<DetailsLayoutAndData>() {
139                         public void onFailure(Throwable caught) {
140                                 // TODO: create a way to notify users of asynchronous callback failures
141                                 GWT.log("AsyncCallback Failed: OnlineGlomService.getDetailsLayoutAndData()");
142                         }
143
144                         @Override
145                         public void onSuccess(DetailsLayoutAndData result) {
146                                 if (result == null) {
147                                         // The result is null only when the documentID was not found. There's nothing to display without the
148                                         // documentID.
149                                         goTo(new DocumentSelectionPlace());
150                                 } else {
151                                         // create the layout and set the data
152                                         createLayout(result.getLayout());
153                                         setData(result.getData());
154                                 }
155                         }
156
157                 };
158                 OnlineGlomServiceAsync.Util.getInstance().getDetailsLayoutAndData(documentID, tableName, primaryKeyValue,
159                                 callback);
160
161                 // indicate that the view is ready to be displayed
162                 panel.setWidget(detailsView.asWidget());
163         }
164
165         /*
166          * Create the layout.
167          */
168         private void createLayout(ArrayList<LayoutGroup> layout) {
169                 // add the groups
170                 for (LayoutGroup layoutGroup : layout) {
171                         detailsView.addGroup(layoutGroup);
172                 }
173
174                 // save references to the DetailsCells and the Portals
175                 detailsCells = detailsView.getCells();
176                 portals = detailsView.getPortals();
177
178                 // Setup click handlers for the navigation buttons
179                 for (final DetailsCell detailsCell : detailsCells) {
180                         final LayoutItemField layoutItemField = detailsCell.getLayoutItemField();
181                         if (layoutItemField.getAddNavigation()) {
182                                 detailsCell.setOpenButtonClickHandler(new ClickHandler() {
183                                         @Override
184                                         public void onClick(ClickEvent event) {
185                                                 TypedDataItem primaryKeyItem = Utils.getTypedDataItem(layoutItemField.getType(),
186                                                                 detailsCell.getData());
187                                                 processNavgiation(layoutItemField.getNavigationTableName(), primaryKeyItem);
188
189                                         }
190                                 });
191                         }
192                 }
193
194         }
195
196         /*
197          * Set the data.
198          */
199         private void setData(DataItem[] data) {
200
201                 if (data == null)
202                         return;
203
204                 // TODO create proper client side logging
205                 if (data.length != detailsCells.size())
206                         GWT.log("Warning: The number of data items doesn't match the number of data detailsCells.");
207
208                 for (int i = 0; i < Math.min(detailsCells.size(), data.length); i++) {
209                         DetailsCell detailsCell = detailsCells.get(i);
210                         if (data[i] != null) {
211
212                                 // set the DatailsItem
213                                 detailsCell.setData(data[i]);
214
215                                 // see if there are any related lists that need to be setup
216                                 for (Portal portal : portals) {
217                                         LayoutItemField layoutItemField = detailsCell.getLayoutItemField();
218                                         LayoutItemPortal layoutItemPortal = portal.getLayoutItem();
219
220                                         if (layoutItemField.getName().equals(layoutItemPortal.getFromField())) {
221                                                 if (data[i] == null)
222                                                         continue;
223
224                                                 TypedDataItem foreignKeyValue = Utils.getTypedDataItem(layoutItemField.getType(), data[i]);
225
226                                                 RelatedListTable relatedListTable = new RelatedListTable(documentID, layoutItemPortal,
227                                                                 foreignKeyValue, new RelatedListNavigationButtonCell(layoutItemPortal.getName()));
228
229                                                 if (!layoutItemPortal.getAddNavigation()
230                                                                 || layoutItemPortal.getNavigationType() == LayoutItemPortal.NavigationType.NAVIGATION_NONE) {
231                                                         relatedListTable.hideNavigationButtons();
232                                                 }
233                                                 portal.setContents(relatedListTable);
234
235                                                 setRowCountForRelatedListTable(relatedListTable, layoutItemPortal.getName(), foreignKeyValue);
236                                         }
237                                 }
238                         }
239                 }
240         }
241
242         private void refreshData() {
243
244                 // get the data for the DetailsView
245                 AsyncCallback<DataItem[]> callback = new AsyncCallback<DataItem[]>() {
246                         public void onFailure(Throwable caught) {
247                                 // TODO: create a way to notify users of asynchronous callback failures
248                                 GWT.log("AsyncCallback Failed: OnlineGlomService.getDetailsData()");
249                         }
250
251                         @Override
252                         public void onSuccess(DataItem[] result) {
253                                 setData(result);
254                         }
255                 };
256
257                 OnlineGlomServiceAsync.Util.getInstance().getDetailsData(documentID, tableName, primaryKeyValue, callback);
258
259         }
260
261         // sets the row count for the related list table
262         private void setRowCountForRelatedListTable(final RelatedListTable relatedListTable, String relationshipName,
263                         TypedDataItem foreignKeyValue) {
264                 AsyncCallback<Integer> callback = new AsyncCallback<Integer>() {
265                         public void onFailure(Throwable caught) {
266                                 // TODO: create a way to notify users of asynchronous callback failures
267                                 GWT.log("AsyncCallback Failed: OnlineGlomService.getRelatedListRowCount()");
268                         }
269
270                         @Override
271                         public void onSuccess(Integer result) {
272                                 if (result.intValue() <= relatedListTable.getMinNumVisibleRows()) {
273                                         // Set the table row count to the minimum row count if the data row count is less than or equal to
274                                         // the minimum row count. This ensures that data with fewer rows than the minimum will not create
275                                         // indexes in the underlying CellTable that will override the rendering of the empty rows.
276                                         relatedListTable.setRowCount(relatedListTable.getMinNumVisibleRows());
277                                 } else {
278                                         // Set the table row count to the data row count if it's larger than the minimum number of rows
279                                         // visible.
280                                         relatedListTable.setRowCount(result.intValue());
281                                 }
282                         }
283                 };
284
285                 OnlineGlomServiceAsync.Util.getInstance().getRelatedListRowCount(documentID, tableName, relationshipName,
286                                 foreignKeyValue, callback);
287         }
288
289         /*
290          * Process a navigation by either doing: nothing if the navigation isn't valid, refreshing the data for the current
291          * table with a new primary key, or going to a new table with a new primary key.
292          */
293         private void processNavgiation(String navigationTableName, TypedDataItem navigationPrimaryKeyValue) {
294
295                 // Ensure the new table name is valid.
296                 String newTableName;
297                 if (navigationTableName != null && !navigationTableName.isEmpty()) {
298                         newTableName = navigationTableName;
299                 } else {
300                         newTableName = tableName;
301                 }
302
303                 // Only process the navigation if there's a valid primary key value.
304                 if (navigationPrimaryKeyValue != null && !navigationPrimaryKeyValue.isEmpty()) {
305                         if (!newTableName.equals(tableName)) {
306                                 // Go to a new DetailsPlace because the table name has changed.
307                                 goTo(new DetailsPlace(documentID, newTableName, navigationPrimaryKeyValue));
308                         } else {
309                                 // Refresh the details view with the new primary because the table name has not changed.
310                                 primaryKeyValue = navigationPrimaryKeyValue;
311                                 refreshData();
312                         }
313                 } else {
314                         // TODO notify the user that navigation isn't possible.
315                         // This is what Glom displays:
316                         // Frame_Glom::show_ok_dialog(_("No Corresponding Record Exists"),
317                         // _("No record with this value exists. Therefore navigation to the related record is not possible."),
318                         // *window, Gtk::MESSAGE_WARNING);
319                         // TODO: Make it more clear to the user exactly what record, what field, and what value, we are talking
320                         // about.
321                 }
322         }
323
324         /*
325          * (non-Javadoc)
326          * 
327          * @see com.google.gwt.activity.shared.Activity#onCancel()
328          */
329         @Override
330         public void onCancel() {
331                 detailsView.clear();
332         }
333
334         /*
335          * (non-Javadoc)
336          * 
337          * @see com.google.gwt.activity.shared.Activity#onStop()
338          */
339         @Override
340         public void onStop() {
341                 detailsView.clear();
342         }
343
344         /*
345          * (non-Javadoc)
346          * 
347          * @see org.glom.web.client.ui.DetailsView.Presenter#goTo(com.google.gwt.place.shared.Place)
348          */
349         @Override
350         public void goTo(Place place) {
351                 clientFactory.getPlaceController().goTo(place);
352         }
353
354 }