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