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