View Javadoc
1   /**
2    * This file Copyright (c) 2012-2018 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.ui.contentapp.browser;
35  
36  import info.magnolia.event.EventBus;
37  import info.magnolia.ui.actionbar.ActionbarPresenter;
38  import info.magnolia.ui.actionbar.definition.ActionbarDefinition;
39  import info.magnolia.ui.actionbar.definition.ActionbarGroupDefinition;
40  import info.magnolia.ui.actionbar.definition.ActionbarItemDefinition;
41  import info.magnolia.ui.actionbar.definition.ActionbarSectionDefinition;
42  import info.magnolia.ui.api.action.ActionDefinition;
43  import info.magnolia.ui.api.action.ActionExecutor;
44  import info.magnolia.ui.api.app.SubAppContext;
45  import info.magnolia.ui.api.app.SubAppEventBus;
46  import info.magnolia.ui.api.availability.AvailabilityChecker;
47  import info.magnolia.ui.api.availability.AvailabilityDefinition;
48  import info.magnolia.ui.api.event.AdmincentralEventBus;
49  import info.magnolia.ui.api.location.Location;
50  import info.magnolia.ui.api.location.LocationChangedEvent;
51  import info.magnolia.ui.contentapp.ContentSubAppView;
52  import info.magnolia.ui.framework.app.BaseSubApp;
53  import info.magnolia.ui.vaadin.actionbar.ActionPopup;
54  import info.magnolia.ui.vaadin.integration.contentconnector.ContentConnector;
55  import info.magnolia.ui.workbench.event.ItemRightClickedEvent;
56  import info.magnolia.ui.workbench.event.SearchEvent;
57  import info.magnolia.ui.workbench.event.SelectionChangedEvent;
58  import info.magnolia.ui.workbench.event.ViewTypeChangedEvent;
59  import info.magnolia.ui.workbench.search.SearchPresenterDefinition;
60  
61  import java.util.Arrays;
62  import java.util.Iterator;
63  import java.util.List;
64  import java.util.Set;
65  
66  import javax.inject.Inject;
67  import javax.inject.Named;
68  
69  import org.apache.commons.lang3.StringUtils;
70  import org.slf4j.Logger;
71  import org.slf4j.LoggerFactory;
72  
73  import com.vaadin.ui.MenuBar.MenuItem;
74  import com.vaadin.server.ExternalResource;
75  
76  /**
77   * Base implementation of a content subApp. A content subApp displays a collection of data represented inside a {@link info.magnolia.ui.workbench.ContentView} created by the {@link info.magnolia.ui.workbench.WorkbenchPresenter}.
78   *
79   * <pre>
80   *  <p>
81   *      This class Provides sensible implementation for services shared by all content subApps.
82   *      Out-of-the-box it will handle the following:
83   *  </p>
84   *
85   *  <ul>
86   *      <li>location updates when switching views, selecting items or performing searches: see {@link #locationChanged(Location)}
87   *      <li>restoring the browser app status when i.e. coming from a bookmark: see {@link #start(Location)}
88   *  </ul>
89   * In order to perform those tasks this class registers non-overridable handlers for the following events:
90   *  <ul>
91   *      <li> {@link SelectionChangedEvent}
92   *      <li> {@link ViewTypeChangedEvent}
93   *      <li> {@link SearchEvent}
94   *  </ul>
95   * Subclasses can augment the default behavior and perform additional tasks by overriding the following methods:
96   *  <ul>
97   *      <li>{@link #onSubAppStart()}
98   *      <li>{@link #locationChanged(Location)}
99   *      <li>{@link #updateActionbar(ActionbarPresenter)}
100  *  </ul>
101  * </pre>
102  *
103  * @see BrowserPresenter
104  * @see info.magnolia.ui.contentapp.ContentSubAppView
105  * @see info.magnolia.ui.contentapp.ContentApp
106  * @see BrowserLocation
107  */
108 public class BrowserSubApp extends BaseSubApp<ContentSubAppView> {
109 
110     private static final Logger log = LoggerFactory.getLogger(BrowserSubApp.class);
111 
112     private final BrowserPresenter browser;
113     private final EventBus subAppEventBus;
114     private ActionExecutor actionExecutor;
115     protected ContentConnector contentConnector;
116     private AvailabilityChecker checker;
117 
118     @Inject
119     public BrowserSubApp(ActionExecutor actionExecutor, final SubAppContext subAppContext, final ContentSubAppView view, final BrowserPresenter browser, final @Named(SubAppEventBus.NAME) EventBus subAppEventBus, @Named(AdmincentralEventBus.NAME) EventBus adminCentralEventBus, ContentConnector contentConnector, AvailabilityChecker checker) {
120         super(subAppContext, view);
121         this.checker = checker;
122         if (subAppContext == null || view == null || browser == null || subAppEventBus == null) {
123             throw new IllegalArgumentException("Constructor does not allow for null args. Found SubAppContext = " + subAppContext + ", ContentSubAppView = " + view + ", BrowserPresenter = " + browser + ", EventBus = " + subAppEventBus);
124         }
125         this.browser = browser;
126         this.subAppEventBus = subAppEventBus;
127         this.actionExecutor = actionExecutor;
128         this.contentConnector = contentConnector;
129 
130 
131         /**
132          * Would be clearer if we'd track {@link info.magnolia.ui.api.app.AppLifecycleEventType#FOCUSED},
133          * but it is not reliable enough (not fired in some essential cases, see issue MGNLUI-2988 for more details).
134          * @see <a href="http://jira.magnolia-cms.com/browse/MGNLUI-2988"/>
135          */
136         adminCentralEventBus.addHandler(LocationChangedEvent.class, new LocationChangedEvent.Handler() {
137             @Override
138             public void onLocationChanged(LocationChangedEvent event) {
139                 /**
140                  * If the new location actually points to this sub-app then we refresh it in order to avoid
141                  * synchronisation issues caused by the changes in the data-source that were not propagated to
142                  * underlying Vaadin containers of the browser.
143                  */
144                 if (event.getNewLocation().equals(getCurrentLocation())) {
145                         restoreBrowser(getCurrentLocation());
146                 }
147             }
148         });
149     }
150 
151     /**
152      * Performs some routine tasks needed by all content subapps before the view is displayed.
153      * The tasks are:
154      * <ul>
155      * <li>setting the current location
156      * <li>setting the browser view
157      * <li>restoring the browser status: see {@link #restoreBrowser(BrowserLocation)}
158      * <li>calling {@link #onSubAppStart()} a hook-up method subclasses can override to perform additional work.
159      * </ul>
160      */
161     @Override
162     public ContentSubAppView start(final Location location) {
163         BrowserLocation l = BrowserLocation.wrap(location);
164         super.start(l);
165         getView().setContentView(browser.start());
166         restoreBrowser(l);
167         registerSubAppEventsHandlers(subAppEventBus);
168 
169         return getView();
170     }
171 
172     /**
173      * Restores the browser status based on the information available in the location object. This is used e.g. when starting a subapp based on a
174      * bookmark. I.e. given a bookmark containing the following URI fragment
175      * <p>
176      * {@code
177      * #app:myapp:browser;/foo/bar:list
178      * }
179      * <p>
180      * this method will select the path <code>/foo/bar</code> in the workspace used by the app, set the view type as <code>list</code> and finally update the available actions.
181      * <p>
182      * In case of a search view the URI fragment will look similar to the following one {@code
183      * #app:myapp:browser;/:search:qux
184      * }
185      * <p>
186      * then this method will select the root path, set the view type as <code>search</code>, perform a search for "qux" in the workspace used by the app and finally update the available actions.
187      *
188      * @see BrowserSubApp#updateActionbar(info.magnolia.ui.actionbar.ActionbarPresenter)
189      * @see BrowserSubApp#start(Location)
190      * @see Location
191      */
192     protected void restoreBrowser(final BrowserLocation location) {
193         String path = location.getNodePath();
194         String viewType = location.getViewType();
195 
196         if (!getBrowser().hasViewType(viewType)) {
197             if (!StringUtils.isBlank(viewType)) {
198                 log.warn("Unknown view type [{}], returning to default view type.", viewType);
199             }
200             viewType = getBrowser().getDefaultViewType();
201             location.updateViewType(viewType);
202             getAppContext().updateSubAppLocation(getSubAppContext(), location);
203         }
204         String query = location.getQuery();
205 
206         Object itemId = contentConnector.getItemIdByUrlFragment(path);
207 
208         // MGNLUI-1475: item might have not been found if path doesn't exist
209         if (!contentConnector.canHandleItem(itemId)) {
210             itemId = contentConnector.getDefaultItemId();
211             BrowserLocation newLocation = getCurrentLocation();
212             newLocation.updateNodePath("/");
213             getAppContext().updateSubAppLocation(getSubAppContext(), newLocation);
214         }
215 
216         getBrowser().resync(Arrays.asList(itemId), viewType, query);
217         updateActionbar(getBrowser().getActionbarPresenter());
218     }
219 
220 
221     /**
222      * Show the actionPopup for the specified item at the specified coordinates.
223      */
224     public void showActionPopup(Object itemId, int x, int y) {
225 
226         // If there's no actionbar configured we don't want to show an empty action popup
227         BrowserSubAppDescriptor subAppDescriptor = (BrowserSubAppDescriptor) getSubAppContext().getSubAppDescriptor();
228         ActionbarDefinition actionbarDefinition = subAppDescriptor.getActionbar();
229         if (actionbarDefinition == null) {
230             return;
231         }
232 
233         ActionPopup actionPopup = browser.getView().getActionPopup();
234 
235         updateActionPopup(actionPopup);
236         actionPopup.open(x, y);
237     }
238 
239     /**
240      * Update the items in the actionPopup based on the selected item and the ActionPopup availability configuration.
241      * This method can be overriden to implement custom conditions diverging from {@link #updateActionbar(info.magnolia.ui.actionbar.ActionbarPresenter)}.
242      */
243     private void updateActionPopup(ActionPopup actionPopup) {
244 
245         actionPopup.removeItems();
246 
247         BrowserSubAppDescriptor subAppDescriptor = (BrowserSubAppDescriptor) getSubAppContext().getSubAppDescriptor();
248         ActionbarDefinition actionbarDefinition = subAppDescriptor.getActionbar();
249         if (actionbarDefinition == null) {
250             return;
251         }
252         List<ActionbarSectionDefinition> sections = actionbarDefinition.getSections();
253 
254         // Figure out which section to show, only one
255         ActionbarSectionDefinition sectionDefinition = getVisibleSection(sections);
256 
257         // If there no section matched the selection we just hide everything
258         if (sectionDefinition == null) {
259             return;
260         }
261 
262         // Evaluate availability of each action within the section
263         for (final Iterator<ActionbarGroupDefinition> groupDefinitionIterator = sectionDefinition.getGroups().iterator(); groupDefinitionIterator.hasNext();) {
264             final ActionbarGroupDefinition groupDefinition = groupDefinitionIterator.next();
265             for (ActionbarItemDefinition itemDefinition : groupDefinition.getItems()) {
266 
267                 final String actionName = itemDefinition.getName();
268                 final MenuItem menuItem = addActionPopupItem(subAppDescriptor, itemDefinition);
269                 ActionDefinition actionDefinition = actionExecutor.getActionDefinition(actionName);
270                 if (actionDefinition != null) {
271                     AvailabilityDefinition availability = actionDefinition.getAvailability();
272                     menuItem.setEnabled(checker.isAvailable(availability, browser.getSelectedItemIds()));
273                 }
274             }
275 
276             // Add group separator.
277             if (groupDefinitionIterator.hasNext()) {
278                 getBrowser().getView().getActionPopup().addSeparator();
279             }
280         }
281     }
282 
283     /**
284      * Add an additional menu item on the actionPopup.
285      */
286     private MenuItem addActionPopupItem(BrowserSubAppDescriptor subAppDescriptor, ActionbarItemDefinition itemDefinition) {
287         String actionName = itemDefinition.getName();
288 
289         ActionDefinition action = subAppDescriptor.getActions().get(actionName);
290         String label = action.getLabel();
291         String iconFontCode = ActionPopup.ICON_FONT_CODE + action.getIcon();
292         ExternalResource iconFontResource = new ExternalResource(iconFontCode);
293 
294         return getBrowser().getView().getActionPopup().addItem(label, iconFontResource, item -> getBrowser().onActionbarItemClicked(actionName));
295     }
296 
297     /**
298      * Update the items in the actionbar based on the selected item and the action availability configuration.
299      * This method can be overriden to implement custom conditions diverging from {@link #updateActionPopup(info.magnolia.ui.vaadin.actionbar.ActionPopup)}.
300      *
301      * @see #restoreBrowser(BrowserLocation)
302      * @see #locationChanged(Location)
303      * @see info.magnolia.ui.actionbar.ActionbarPresenter
304      */
305     public void updateActionbar(ActionbarPresenter actionbar) {
306 
307         BrowserSubAppDescriptor subAppDescriptor = (BrowserSubAppDescriptor) getSubAppContext().getSubAppDescriptor();
308         ActionbarDefinition actionbarDefinition = subAppDescriptor.getActionbar();
309         if (actionbarDefinition == null) {
310             return;
311         }
312         List<ActionbarSectionDefinition> sections = actionbarDefinition.getSections();
313         // Figure out which section to show, only one
314         ActionbarSectionDefinition sectionDefinition = getVisibleSection(sections);
315 
316         // Hide all other sections
317         for (ActionbarSectionDefinition section : sections) {
318             actionbar.hideSection(section.getName());
319         }
320 
321         if (sectionDefinition != null) {
322             // Show our section
323             actionbar.showSection(sectionDefinition.getName());
324 
325             // Evaluate availability of each action within the section
326             for (ActionbarGroupDefinition groupDefinition : sectionDefinition.getGroups()) {
327                 for (ActionbarItemDefinition itemDefinition : groupDefinition.getItems()) {
328 
329                     String actionName = itemDefinition.getName();
330                     ActionDefinition actionDefinition = actionExecutor.getActionDefinition(actionName);
331                     if (actionDefinition != null) {
332                         AvailabilityDefinition availability = actionDefinition.getAvailability();
333                         if (checker.isAvailable(availability, browser.getSelectedItemIds())) {
334                             actionbar.enable(actionName);
335                         } else {
336                             actionbar.disable(actionName);
337                         }
338                     } else {
339                         log.warn("Action bar expected an action named {}, but no such action is currently configured.", actionName);
340                     }
341                 }
342             }
343         }
344     }
345 
346     private ActionbarSectionDefinition getVisibleSection(List<ActionbarSectionDefinition> sections) {
347         for (ActionbarSectionDefinition section : sections) {
348             if (isSectionVisible(section))
349                 return section;
350         }
351         return null;
352     }
353 
354     private boolean isSectionVisible(ActionbarSectionDefinition section) {
355         return checker.isAvailable(section.getAvailability(), browser.getSelectedItemIds());
356     }
357 
358     protected final BrowserPresenter getBrowser() {
359         return browser;
360     }
361 
362     /**
363      * The default implementation selects the path in the current workspace and updates the available actions in the actionbar.
364      */
365     @Override
366     public void locationChanged(final Location location) {
367         super.locationChanged(location);
368         restoreBrowser(BrowserLocation.wrap(location));
369     }
370 
371     /**
372      * Wraps the current DefaultLocation in a {@link BrowserLocation}. Providing getter and setters for used parameters.
373      */
374     @Override
375     public BrowserLocation getCurrentLocation() {
376         return BrowserLocation.wrap(super.getCurrentLocation());
377     }
378 
379     /*
380      * Registers general purpose handlers for the following events:
381      * <ul>
382      * <li> {@link ItemSelectedEvent}
383      * <li> {@link ViewTypeChangedEvent}
384      * <li> {@link SearchEvent}
385      * </ul>
386      */
387     private void registerSubAppEventsHandlers(final EventBus subAppEventBus) {
388         final ActionbarPresenter actionbar = getBrowser().getActionbarPresenter();
389         subAppEventBus.addHandler(SelectionChangedEvent.class, new SelectionChangedEvent.Handler() {
390 
391             @Override
392             public void onSelectionChanged(SelectionChangedEvent event) {
393                 handleSelectionChange(event.getItemIds(), actionbar);
394             }
395         });
396 
397         subAppEventBus.addHandler(ItemRightClickedEvent.class, new ItemRightClickedEvent.Handler() {
398 
399             @Override
400             public void onItemRightClicked(ItemRightClickedEvent event) {
401                 showActionPopup(event.getItemId(), event.getClickX(), event.getClickY());
402             }
403         });
404 
405         subAppEventBus.addHandler(ViewTypeChangedEvent.class, new ViewTypeChangedEvent.Handler() {
406 
407             @Override
408             public void onViewChanged(ViewTypeChangedEvent event) {
409                 BrowserLocation location = getCurrentLocation();
410                 // remove search term from fragment when switching back
411                 if (location.getViewType().equals(SearchPresenterDefinition.VIEW_TYPE)
412                         && !event.getViewType().equals(SearchPresenterDefinition.VIEW_TYPE)) {
413                     location.updateQuery("");
414                 }
415                 location.updateViewType(event.getViewType());
416                 getAppContext().updateSubAppLocation(getSubAppContext(), location);
417                 updateActionbar(actionbar);
418             }
419         });
420 
421         subAppEventBus.addHandler(SearchEvent.class, new SearchEvent.Handler() {
422 
423             @Override
424             public void onSearch(SearchEvent event) {
425                 BrowserLocation location = getCurrentLocation();
426                 if (StringUtils.isNotBlank(event.getSearchExpression())) {
427                     location.updateViewType(SearchPresenterDefinition.VIEW_TYPE);
428                 }
429                 location.updateQuery(event.getSearchExpression());
430                 getAppContext().updateSubAppLocation(getSubAppContext(), location);
431                 updateActionbar(actionbar);
432             }
433         });
434     }
435 
436     private void handleSelectionChange(Set<Object> selectionIds, ActionbarPresenter actionbar) {
437         BrowserLocation location = getCurrentLocation();
438         applySelectionToLocation(location, selectionIds.isEmpty() ? contentConnector.getDefaultItemId() : selectionIds.iterator().next());
439         getAppContext().updateSubAppLocation(getSubAppContext(), location);
440         updateActionbar(actionbar);
441 
442     }
443 
444     protected void applySelectionToLocation(BrowserLocation location, Object selectedId) {
445         location.updateNodePath("");
446         if (!contentConnector.canHandleItem(selectedId)) {
447             // nothing is selected at the moment
448         } else {
449             location.updateNodePath(contentConnector.getItemUrlFragment(selectedId));
450         }
451     }
452 }