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