Receive tabbed area from Argeo Commons.
[gpl/argeo-suite.git] / core / org.argeo.suite.ui / src / org / argeo / suite / ui / SuiteApp.java
1 package org.argeo.suite.ui;
2
3 import static org.argeo.cms.ui.CmsView.CMS_VIEW_UID_PROPERTY;
4
5 import java.util.Collections;
6 import java.util.HashMap;
7 import java.util.HashSet;
8 import java.util.List;
9 import java.util.Locale;
10 import java.util.Map;
11 import java.util.Set;
12 import java.util.TreeMap;
13 import java.util.TreeSet;
14
15 import javax.jcr.Node;
16 import javax.jcr.RepositoryException;
17 import javax.jcr.Session;
18 import javax.jcr.nodetype.NodeType;
19 import javax.naming.InvalidNameException;
20 import javax.naming.ldap.LdapName;
21
22 import org.apache.commons.logging.Log;
23 import org.apache.commons.logging.LogFactory;
24 import org.argeo.api.NodeUtils;
25 import org.argeo.cms.CmsUserManager;
26 import org.argeo.cms.LocaleUtils;
27 import org.argeo.cms.auth.CmsSession;
28 import org.argeo.cms.ui.AbstractCmsApp;
29 import org.argeo.cms.ui.CmsTheme;
30 import org.argeo.cms.ui.CmsUiProvider;
31 import org.argeo.cms.ui.CmsView;
32 import org.argeo.cms.ui.dialogs.CmsFeedback;
33 import org.argeo.cms.ui.util.CmsUiUtils;
34 import org.argeo.eclipse.ui.specific.UiContext;
35 import org.argeo.entity.EntityConstants;
36 import org.argeo.entity.EntityNames;
37 import org.argeo.entity.EntityType;
38 import org.argeo.jcr.Jcr;
39 import org.argeo.suite.RankedObject;
40 import org.argeo.suite.SuiteUtils;
41 import org.argeo.util.LangUtils;
42 import org.eclipse.swt.SWT;
43 import org.eclipse.swt.widgets.Composite;
44 import org.osgi.framework.Constants;
45 import org.osgi.service.event.Event;
46 import org.osgi.service.event.EventHandler;
47 import org.osgi.service.useradmin.User;
48
49 /** The Argeo Suite App. */
50 public class SuiteApp extends AbstractCmsApp implements EventHandler {
51         private final static Log log = LogFactory.getLog(SuiteApp.class);
52
53         public final static String PUBLIC_BASE_PATH_PROPERTY = "publicBasePath";
54         public final static String DEFAULT_UI_NAME_PROPERTY = "defaultUiName";
55         public final static String DEFAULT_THEME_ID_PROPERTY = "defaultThemeId";
56
57         private String publicBasePath = null;
58
59         private String pidPrefix;
60         private String headerPid;
61         private String leadPanePid;
62         private String loginScreenPid;
63 //      private String DASHBOARD_PID = pidPrefix + "dashboard";
64 //      private String RECENT_ITEMS_PID = pidPrefix + "recentItems";
65
66         private String defaultUiName = "app";
67         private String defaultThemeId = "org.argeo.suite.theme.default";
68
69         private Map<String, RankedObject<CmsUiProvider>> uiProvidersByPid = Collections.synchronizedMap(new HashMap<>());
70         private Map<String, RankedObject<CmsUiProvider>> uiProvidersByType = Collections.synchronizedMap(new HashMap<>());
71         private Map<String, RankedObject<SuiteLayer>> layersByPid = Collections.synchronizedSortedMap(new TreeMap<>());
72         private Map<String, RankedObject<SuiteLayer>> layersByType = Collections.synchronizedSortedMap(new TreeMap<>());
73
74         private CmsUserManager cmsUserManager;
75
76         // TODO make more optimal or via CmsSession/CmsView
77         private Map<String, SuiteUi> managedUis = new HashMap<>();
78
79 //      private CmsUiProvider headerPart = null;
80
81         public void init(Map<String, Object> properties) {
82                 if (log.isDebugEnabled())
83                         log.info("Argeo Suite App started");
84
85                 if (properties.containsKey(DEFAULT_UI_NAME_PROPERTY))
86                         defaultUiName = LangUtils.get(properties, DEFAULT_UI_NAME_PROPERTY);
87                 if (properties.containsKey(DEFAULT_THEME_ID_PROPERTY))
88                         defaultThemeId = LangUtils.get(properties, DEFAULT_THEME_ID_PROPERTY);
89                 publicBasePath = LangUtils.get(properties, PUBLIC_BASE_PATH_PROPERTY);
90
91                 if (properties.containsKey(Constants.SERVICE_PID)) {
92                         String servicePid = properties.get(Constants.SERVICE_PID).toString();
93                         if (servicePid.endsWith(".app")) {
94                                 pidPrefix = servicePid.substring(0, servicePid.length() - "app".length());
95                         }
96                 }
97
98                 if (pidPrefix == null)
99                         throw new IllegalArgumentException("PID prefix must be set.");
100
101                 headerPid = pidPrefix + "header";
102                 leadPanePid = pidPrefix + "leadPane";
103                 loginScreenPid = pidPrefix + "loginScreen";
104         }
105
106         public void destroy(Map<String, Object> properties) {
107                 for (SuiteUi ui : managedUis.values())
108                         if (!ui.isDisposed())
109                                 ui.dispose();
110                 if (log.isDebugEnabled())
111                         log.info("Argeo Suite App stopped");
112
113         }
114
115         @Override
116         public Set<String> getUiNames() {
117                 HashSet<String> uiNames = new HashSet<>();
118                 uiNames.add(defaultUiName);
119                 return uiNames;
120         }
121
122         @Override
123         public Composite initUi(Composite parent) {
124                 String uiName = parent.getData(UI_NAME_PROPERTY) != null ? parent.getData(UI_NAME_PROPERTY).toString() : null;
125                 CmsView cmsView = CmsView.getCmsView(parent);
126                 if (cmsView == null)
127                         throw new IllegalStateException("No CMS view is registered.");
128                 CmsTheme theme = getTheme(uiName);
129                 if (theme != null)
130                         CmsTheme.registerCmsTheme(parent.getShell(), theme);
131                 SuiteUi argeoSuiteUi = new SuiteUi(parent, SWT.INHERIT_DEFAULT);
132                 String uid = cmsView.getUid();
133                 managedUis.put(uid, argeoSuiteUi);
134                 argeoSuiteUi.addDisposeListener((e) -> {
135                         managedUis.remove(uid);
136                         if (log.isDebugEnabled())
137                                 log.debug("Suite UI " + uid + " has been disposed.");
138                 });
139                 return argeoSuiteUi;
140         }
141
142         @Override
143         public String getThemeId(String uiName) {
144                 return defaultThemeId;
145         }
146
147         @Override
148         public void refreshUi(Composite parent, String state) {
149                 try {
150                         Node context = null;
151                         SuiteUi ui = (SuiteUi) parent;
152                         CmsView cmsView = CmsView.getCmsView(parent);
153                         if (cmsView.isAnonymous() && publicBasePath == null) {// internal app, must login
154                                 ui.logout();
155                                 refreshPart(findUiProvider(headerPid), ui.getHeader(), context);
156                                 ui.refreshBelowHeader(false);
157                                 refreshPart(findUiProvider(loginScreenPid), ui.getBelowHeader(), context);
158                                 ui.layout(true, true);
159                         } else {
160                                 CmsSession cmsSession = cmsView.getCmsSession();
161                                 if (ui.getUserDir() == null) {
162                                         if (cmsView.isAnonymous()) {
163                                                 assert publicBasePath != null;
164                                                 ui.initSessions(getRepository(), publicBasePath);
165                                         } else {
166                                                 Session adminSession = null;
167                                                 try {
168                                                         adminSession = NodeUtils.openDataAdminSession(getRepository(), null);
169                                                         Node userDir = SuiteUtils.getOrCreateCmsSessionNode(adminSession, cmsSession);
170                                                         ui.initSessions(getRepository(), userDir.getPath());
171                                                 } finally {
172                                                         Jcr.logout(adminSession);
173                                                 }
174                                         }
175                                 }
176                                 initLocale(cmsSession);
177                                 context = stateToNode(ui, state);
178                                 if (context == null)
179                                         context = ui.getUserDir();
180
181                                 refreshPart(findUiProvider(headerPid), ui.getHeader(), context);
182                                 ui.refreshBelowHeader(true);
183                                 for (String key : layersByPid.keySet()) {
184                                         SuiteLayer layer = layersByPid.get(key).get();
185                                         ui.addLayer(key, layer);
186                                 }
187                                 refreshPart(findUiProvider(leadPanePid), ui.getLeadPane(), context);
188                                 ui.layout(true, true);
189                                 setState(parent, state);
190                         }
191                 } catch (Exception e) {
192                         CmsFeedback.show("Unexpected exception", e);
193                 }
194         }
195
196         private void initLocale(CmsSession cmsSession) {
197                 if (cmsSession == null)
198                         return;
199                 Locale locale = cmsSession.getLocale();
200                 UiContext.setLocale(locale);
201                 LocaleUtils.setThreadLocale(locale);
202
203         }
204
205         private void refreshPart(CmsUiProvider uiProvider, Composite part, Node context) {
206                 CmsUiUtils.clear(part);
207                 uiProvider.createUiPart(part, context);
208         }
209
210         private CmsUiProvider findUiProvider(String pid) {
211                 if (!uiProvidersByPid.containsKey(pid))
212                         throw new IllegalArgumentException("No UI provider registered as " + pid);
213                 return uiProvidersByPid.get(pid).get();
214         }
215
216         private <T> T findByType(Map<String, RankedObject<T>> byType, Node context) {
217                 if (context == null)
218                         throw new IllegalArgumentException("A node should be provided");
219                 try {
220                         // mixins
221                         Set<String> types = new TreeSet<>();
222                         for (NodeType nodeType : context.getMixinNodeTypes()) {
223                                 String typeName = nodeType.getName();
224                                 if (byType.containsKey(typeName)) {
225                                         types.add(typeName);
226                                 }
227                         }
228                         // primary node type
229                         {
230                                 NodeType nodeType = context.getPrimaryNodeType();
231                                 String typeName = nodeType.getName();
232                                 if (byType.containsKey(typeName)) {
233                                         types.add(typeName);
234                                 }
235                                 for (NodeType mixin : nodeType.getDeclaredSupertypes()) {
236                                         if (byType.containsKey(mixin.getName())) {
237                                                 types.add(mixin.getName());
238                                         }
239                                 }
240                         }
241                         // entity type
242                         if (context.isNodeType(EntityType.entity.get())) {
243                                 if (context.hasProperty(EntityNames.ENTITY_TYPE)) {
244                                         String typeName = context.getProperty(EntityNames.ENTITY_TYPE).getString();
245                                         if (byType.containsKey(typeName)) {
246                                                 types.add(typeName);
247                                         }
248                                 }
249                         }
250
251 //                      if (context.getPath().equals("/")) {// root node
252 //                              types.add("nt:folder");
253 //                      }
254                         if (NodeUtils.isUserHome(context) && byType.containsKey("nt:folder")) {// home node
255                                 types.add("nt:folder");
256                         }
257
258                         if (types.size() == 0)
259                                 throw new IllegalArgumentException("No type found for " + context);
260                         String type = types.iterator().next();
261                         if (!byType.containsKey(type))
262                                 throw new IllegalArgumentException("No component found for " + context + " with type " + type);
263                         return byType.get(type).get();
264                 } catch (RepositoryException e) {
265                         throw new IllegalStateException(e);
266                 }
267         }
268
269         @Override
270         public void setState(Composite parent, String state) {
271                 if (state == null || state.equals("~"))
272                         return;
273                 if (!state.startsWith("/") && !state.equals("~")) {
274                         if (parent instanceof SuiteUi) {
275                                 SuiteUi ui = (SuiteUi) parent;
276                                 String currentLayerId = ui.getCurrentLayerId();
277                                 if (state.equals(currentLayerId))
278                                         return; // does nothing
279                                 else {
280                                         Map<String, Object> properties = new HashMap<>();
281                                         properties.put(SuiteEvent.LAYER, state);
282                                         ui.getCmsView().sendEvent(SuiteEvent.switchLayer.topic(), properties);
283                                 }
284                         }
285                         return;
286                 }
287                 SuiteUi suiteUi = (SuiteUi) parent;
288                 Node node = stateToNode(suiteUi, state);
289                 if (node == null) {
290                         suiteUi.getCmsView().navigateTo("~");
291                 } else {
292                         suiteUi.getCmsView().sendEvent(SuiteEvent.switchLayer.topic(), SuiteEvent.eventProperties(node));
293                         suiteUi.getCmsView().sendEvent(SuiteEvent.refreshPart.topic(), SuiteEvent.eventProperties(node));
294                 }
295         }
296
297         private String nodeToState(Node node) {
298                 return '/' + Jcr.getWorkspaceName(node) + Jcr.getPath(node);
299         }
300
301         private Node stateToNode(SuiteUi suiteUi, String state) {
302                 if (suiteUi == null)
303                         return null;
304                 if (state == null || !state.startsWith("/"))
305                         return null;
306
307                 String path = state.substring(1);
308                 String workspace;
309                 if (path.equals("")) {
310                         workspace = null;
311                         path = "/";
312                 } else {
313                         int index = path.indexOf('/');
314                         if (index == 0) {
315                                 log.error("Cannot interpret " + state);
316 //                              cmsView.navigateTo("~");
317                                 return null;
318                         } else if (index > 0) {
319                                 workspace = path.substring(0, index);
320                                 path = path.substring(index);
321                         } else {// index<0, assuming root node
322                                 workspace = path;
323                                 path = "/";
324                         }
325                 }
326                 Session session = suiteUi.getSession(workspace);
327                 if (session == null)
328                         return null;
329                 Node node = Jcr.getNode(session, path);
330                 return node;
331         }
332
333         /*
334          * Events management
335          */
336
337         @Override
338         public void handleEvent(Event event) {
339
340                 // Specific UI related events
341                 SuiteUi ui = getRelatedUi(event);
342                 if (ui == null)
343                         return;
344                 try {
345 //                      String currentLayerId = ui.getCurrentLayerId();
346 //                      SuiteLayer currentLayer = currentLayerId != null ? layersByPid.get(currentLayerId).get() : null;
347                         if (SuiteUiUtils.isTopic(event, SuiteEvent.refreshPart)) {
348                                 Node node = getNode(ui, event);
349                                 if (node == null)
350                                         return;
351                                 CmsUiProvider uiProvider = findByType(uiProvidersByType, node);
352                                 SuiteLayer layer = findByType(layersByType, node);
353                                 ui.switchToLayer(layer, node);
354                                 ui.getCmsView().runAs(() -> layer.view(uiProvider, ui.getCurrentWorkArea(), node));
355                                 ui.getCmsView().stateChanged(nodeToState(node), Jcr.getTitle(node));
356                         } else if (SuiteUiUtils.isTopic(event, SuiteEvent.openNewPart)) {
357                                 Node node = getNode(ui, event);
358                                 if (node == null)
359                                         return;
360                                 CmsUiProvider uiProvider = findByType(uiProvidersByType, node);
361                                 SuiteLayer layer = findByType(layersByType, node);
362                                 ui.switchToLayer(layer, node);
363                                 ui.getCmsView().runAs(() -> layer.open(uiProvider, ui.getCurrentWorkArea(), node));
364                                 ui.getCmsView().stateChanged(nodeToState(node), Jcr.getTitle(node));
365                         } else if (SuiteUiUtils.isTopic(event, SuiteEvent.switchLayer)) {
366                                 String layerId = get(event, SuiteEvent.LAYER);
367                                 if (layerId != null) {
368 //                                      ui.switchToLayer(layerId, ui.getUserDir());
369                                         ui.getCmsView().runAs(() -> ui.switchToLayer(layerId, ui.getUserDir()));
370                                         ui.getCmsView().navigateTo(layerId);
371                                 } else {
372                                         Node node = getNode(ui, event);
373                                         if (node != null) {
374                                                 SuiteLayer layer = findByType(layersByType, node);
375                                                 ui.getCmsView().runAs(() -> ui.switchToLayer(layer, node));
376                                         }
377                                 }
378                         }
379                 } catch (Exception e) {
380                         log.error("Cannot handle event " + event, e);
381 //                      CmsView.getCmsView(ui).exception(e);
382                 }
383
384         }
385
386         private Node getNode(SuiteUi ui, Event event) {
387                 String nodePath = get(event, SuiteEvent.NODE_PATH);
388                 String workspaceName = get(event, SuiteEvent.WORKSPACE);
389                 Session session = ui.getSession(workspaceName);
390                 Node node;
391                 if (nodePath == null) {
392                         // look for a user
393                         String username = get(event, SuiteEvent.USERNAME);
394                         if (username == null)
395                                 return null;
396                         User user = cmsUserManager.getUser(username);
397                         if (user == null)
398                                 return null;
399                         LdapName userDn;
400                         try {
401                                 userDn = new LdapName(user.getName());
402                         } catch (InvalidNameException e) {
403                                 throw new IllegalArgumentException("Badly formatted username", e);
404                         }
405                         String userNodePath = SuiteUtils.getUserNodePath(userDn);
406                         if (Jcr.itemExists(session, userNodePath))
407                                 node = Jcr.getNode(session, userNodePath);
408                         else {
409                                 Session adminSession = null;
410                                 try {
411                                         adminSession = NodeUtils.openDataAdminSession(getRepository(), workspaceName);
412                                         SuiteUtils.getOrCreateUserNode(adminSession, userDn);
413                                 } finally {
414                                         Jcr.logout(adminSession);
415                                 }
416                                 node = Jcr.getNode(session, userNodePath);
417                         }
418                 } else {
419                         node = Jcr.getNode(session, nodePath);
420                 }
421                 return node;
422         }
423
424         private SuiteUi getRelatedUi(Event event) {
425                 return managedUis.get(get(event, CMS_VIEW_UID_PROPERTY));
426         }
427
428         public static String get(Event event, String key) {
429                 Object value = event.getProperty(key);
430                 if (value == null)
431                         return null;
432 //                      throw new IllegalArgumentException("Property " + key + " must be set");
433                 return value.toString();
434
435         }
436
437         /*
438          * Dependency injection.
439          */
440
441         public void addUiProvider(CmsUiProvider uiProvider, Map<String, Object> properties) {
442                 if (properties.containsKey(Constants.SERVICE_PID)) {
443                         String pid = (String) properties.get(Constants.SERVICE_PID);
444                         RankedObject.putIfHigherRank(uiProvidersByPid, pid, uiProvider, properties);
445                 }
446                 if (properties.containsKey(EntityConstants.TYPE)) {
447                         List<String> types = LangUtils.toStringList(properties.get(EntityConstants.TYPE));
448                         for (String type : types)
449                                 RankedObject.putIfHigherRank(uiProvidersByType, type, uiProvider, properties);
450                 }
451         }
452
453         public void removeUiProvider(CmsUiProvider uiProvider, Map<String, Object> properties) {
454                 if (properties.containsKey(Constants.SERVICE_PID)) {
455                         String pid = (String) properties.get(Constants.SERVICE_PID);
456                         if (uiProvidersByPid.containsKey(pid)) {
457                                 if (uiProvidersByPid.get(pid).equals(new RankedObject<CmsUiProvider>(uiProvider, properties))) {
458                                         uiProvidersByPid.remove(pid);
459                                 }
460                         }
461                 }
462                 if (properties.containsKey(EntityConstants.TYPE)) {
463                         List<String> types = LangUtils.toStringList(properties.get(EntityConstants.TYPE));
464                         for (String type : types) {
465                                 if (uiProvidersByType.containsKey(type)) {
466                                         if (uiProvidersByType.get(type).equals(new RankedObject<CmsUiProvider>(uiProvider, properties))) {
467                                                 uiProvidersByType.remove(type);
468                                         }
469                                 }
470                         }
471                 }
472         }
473
474         public void addLayer(SuiteLayer layer, Map<String, Object> properties) {
475                 if (properties.containsKey(Constants.SERVICE_PID)) {
476                         String pid = (String) properties.get(Constants.SERVICE_PID);
477                         RankedObject.putIfHigherRank(layersByPid, pid, layer, properties);
478                 }
479                 if (properties.containsKey(EntityConstants.TYPE)) {
480                         List<String> types = LangUtils.toStringList(properties.get(EntityConstants.TYPE));
481                         for (String type : types)
482                                 RankedObject.putIfHigherRank(layersByType, type, layer, properties);
483                 }
484         }
485
486         public void removeLayer(SuiteLayer layer, Map<String, Object> properties) {
487                 if (properties.containsKey(Constants.SERVICE_PID)) {
488                         String pid = (String) properties.get(Constants.SERVICE_PID);
489                         if (layersByPid.containsKey(pid)) {
490                                 if (layersByPid.get(pid).equals(new RankedObject<SuiteLayer>(layer, properties))) {
491                                         layersByPid.remove(pid);
492                                 }
493                         }
494                 }
495                 if (properties.containsKey(EntityConstants.TYPE)) {
496                         List<String> types = LangUtils.toStringList(properties.get(EntityConstants.TYPE));
497                         for (String type : types) {
498                                 if (layersByType.containsKey(type)) {
499                                         if (layersByType.get(type).equals(new RankedObject<CmsUiProvider>(layer, properties))) {
500                                                 layersByType.remove(type);
501                                         }
502                                 }
503                         }
504                 }
505         }
506
507         public void setCmsUserManager(CmsUserManager cmsUserManager) {
508                 this.cmsUserManager = cmsUserManager;
509         }
510
511 }