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