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