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