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