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