/
AbstractHintProvider.java
539 lines (384 loc) · 15.9 KB
/
AbstractHintProvider.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
/*
* Copyright (C) 2010-2023 Structr GmbH
*
* This file is part of Structr <http://structr.org>.
*
* Structr is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Structr is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Structr. If not, see <http://www.gnu.org/licenses/>.
*/
package org.structr.autocomplete;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.structr.common.PropertyView;
import org.structr.common.error.FrameworkException;
import org.structr.core.GraphObject;
import org.structr.core.GraphObjectMap;
import org.structr.core.app.StructrApp;
import org.structr.core.entity.AbstractSchemaNode;
import org.structr.core.entity.SchemaMethod;
import org.structr.core.entity.SchemaProperty;
import org.structr.core.function.Functions;
import org.structr.core.function.KeywordHint;
import org.structr.core.function.ParseResult;
import org.structr.core.graph.NodeInterface;
import org.structr.core.property.*;
import org.structr.schema.SchemaHelper;
import org.structr.schema.SchemaHelper.Type;
import org.structr.schema.action.ActionContext;
import org.structr.schema.action.Function;
import org.structr.schema.action.Hint;
import org.structr.web.entity.dom.Content;
import org.structr.web.entity.dom.Content.ContentHandler;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.Map.Entry;
import java.util.logging.Level;
public abstract class AbstractHintProvider {
private static final Logger logger = LoggerFactory.getLogger(AbstractHintProvider.class);
private enum QueryType {
REST, Cypher, XPath, Function
}
public static final Property<String> displayText = new StringProperty("displayText");
public static final Property<String> className = new StringProperty("className");
public static final Property<String> text = new StringProperty("text");
public static final Property<GraphObject> from = new GenericProperty("from");
public static final Property<GraphObject> to = new GenericProperty("to");
public static final Property<Integer> line = new IntProperty("line");
public static final Property<Integer> ch = new IntProperty("ch");
protected abstract List<Hint> getAllHints(final ActionContext ionContext, final GraphObject currentNode, final String editorText, final ParseResult parseResult);
protected abstract String getFunctionName(final String sourceName);
protected final Comparator comparator = new HintComparator();
public static List<GraphObject> getHints(final ActionContext actionContext, final boolean isAutoscriptEnv, final GraphObject currentEntity, final String textBefore, final String textAfter, final int cursorLine, final int cursorPosition) {
String text = null;
// don't interpret invalid strings
if (textBefore != null && (textBefore.endsWith("''") || textBefore.endsWith("\"\""))) {
return Collections.EMPTY_LIST;
}
if (StringUtils.isBlank(textAfter) || textAfter.startsWith(" ") || textAfter.startsWith("\t") || textAfter.startsWith("\n") || textAfter.startsWith(";") || textAfter.startsWith(")")) {
if (isAutoscriptEnv || currentEntity instanceof SchemaMethod) {
// we can use the whole text here, the method will always contain script code and nothing else
// add ${ to be able to reuse code below
text = "${" + textBefore;
} else {
try {
final AutocompleteContentHandler handler = new AutocompleteContentHandler();
Content.renderContentWithScripts(textBefore, handler);
if (handler.inScript()) {
// we are inside of a scripting context
text = handler.getScript();
}
} catch (Throwable t) {
logger.error(ExceptionUtils.getStackTrace(t));
}
}
// handle text for autocompletion
if (text != null) {
if (text.startsWith("${{")) {
final JavascriptHintProvider provider = new JavascriptHintProvider();
final String source = text.substring(3);
return provider.getHints(actionContext, currentEntity, source, cursorLine, cursorPosition);
} else if (text.startsWith("${")) {
final PlaintextHintProvider provider = new PlaintextHintProvider();
final String source = text.substring(2);
return provider.getHints(actionContext, currentEntity, source, cursorLine, cursorPosition);
}
}
}
return Collections.EMPTY_LIST;
}
public List<GraphObject> getHints(final ActionContext actionContext, final GraphObject currentEntity, final String script, final int cursorLine, final int cursorPosition) {
final ParseResult parseResult = new ParseResult();
final List<Hint> allHints = getAllHints(actionContext, currentEntity, script, parseResult);
final List<GraphObject> hints = new LinkedList<>();
final String lastToken = parseResult.getLastToken();
final boolean unrestricted = lastToken.endsWith("(") || lastToken.endsWith(("."));
final int lastTokenLength = unrestricted ? 0 : lastToken.length();
int maxNameLength = 0;
for (final Hint hint : allHints) {
if (hint instanceof SeparatorHint) {
final GraphObjectMap item = new GraphObjectMap();
item.put(displayText, "");
item.put(className , "separator");
item.put(text, "");
hints.add(item);
} else if (!hint.isHidden()) {
final String functionName = getFunctionName(hint.getReplacement());
final String displayName = getFunctionName(hint.getDisplayName());
if ((unrestricted || displayName.startsWith(lastToken)) && ( (!script.endsWith(functionName)) || (script.endsWith(functionName) && hint instanceof Function) )) {
final GraphObjectMap item = new GraphObjectMap();
if (hint.mayModify()) {
item.put(text, displayName);
} else {
item.put(text, displayName);
}
item.put(displayText, displayName + " - " + textOrPlaceholder(hint.shortDescription()));
addPosition(item, hint, cursorLine, cursorPosition - lastTokenLength, cursorPosition);
if (displayName.length() > maxNameLength) {
maxNameLength = displayName.length();
}
hints.add(item);
}
}
}
alignHintDescriptions(hints, maxNameLength + 1);
return hints;
}
protected String visitReplacement(final String replacement) {
return replacement;
}
protected Hint createHint(final String name, final String description, final String replacement) {
final KeywordHint hint = new KeywordHint(name, description);
if (replacement != null) {
hint.setReplacement(replacement);
}
return hint;
}
protected void alignHintDescriptions(final List<GraphObject> hints, final int maxNameLength) {
// insert appropriate number of spaces into description to align function names
for (final GraphObject item : hints) {
final String text = item.getProperty(displayText);
final int pos = text.indexOf(" - ");
if (pos >= 0 && pos < maxNameLength) {
final StringBuilder buf = new StringBuilder(text);
buf.insert(pos, StringUtils.leftPad("", maxNameLength - pos));
// ignore exception, won't happen on a GraphObjectMap anyway
try { item.setProperty(displayText, buf.toString()); } catch (FrameworkException fex) {}
}
}
}
protected String textOrPlaceholder(final String source) {
if (StringUtils.isBlank(source)) {
return " (no description available yet)";
}
return source;
}
protected void handleJSExpression(final ActionContext actionContext, final GraphObject currentNode, final String expression, final List<Hint> hints, final ParseResult result) {
final String[] expressionParts = StringUtils.splitPreserveAllTokens(expression, ".(");
final List<String> tokens = Arrays.asList(expressionParts);
final int length = expressionParts.length;
if (length > 1) {
handleTokens(actionContext, tokens, currentNode, hints, result);
} else {
addAllHints(hints);
}
result.setExpression(expression);
}
protected void addAllHints(final List<Hint> hints) {
for (final Function<Object, Object> func : Functions.getFunctions()) {
hints.add(func);
}
// sort hints
Collections.sort(hints, comparator);
// add keywords
hints.add(0, createHint("this", "The current object", "this"));
hints.add(0, createHint("response", "The current response", "response"));
hints.add(0, createHint("request", "The current request", "request"));
hints.add(0, createHint("page", "The current page", "page"));
hints.add(0, createHint("me", "The current user", "me"));
hints.add(0, createHint("locale", "The current locale", "locale"));
hints.add(0, createHint("current", "The current details object", "current"));
}
protected void addNonempty(final List<String> list, final String string) {
if (StringUtils.isNotBlank(string)) {
list.add(string);
}
}
protected void addHintsForType(final ActionContext actionContext, final Class type, final List<Hint> hints, final ParseResult result) {
final List<Hint> methodHints = new LinkedList<>();
try {
// properties
final List<GraphObjectMap> typeInfo = SchemaHelper.getSchemaTypeInfo(actionContext.getSecurityContext(), type.getSimpleName(), type, PropertyView.All);
for (final GraphObjectMap property : typeInfo) {
final Map<String, Object> map = property.toMap();
final String name = (String)map.get("jsonName");
final String propertyType = (String)map.get("uiType");
final String className = (String)map.get("className");
final String declaringClass = (String)map.get("declaringClass");
// skip properties defined in NodeInterface class, except for name
if (NodeInterface.class.getSimpleName().equals(declaringClass) && !"name".equals(name)) {
continue;
}
// filter inherited properties (except name)
//if (!type.getSimpleName().equals(declaringClass) && !"name".equals(name)) {
// continue;
//}
hints.add(createHint(name, propertyType, name));
}
// methods go into their own collection, are sorted and the appended to the list
final Map<String, Method> methods = StructrApp.getConfiguration().getExportedMethodsForType(type);
for (final Entry<String, Method> entry : methods.entrySet()) {
final String name = entry.getKey();
methodHints.add(createHint(name + "()", "custom method", name));
}
Collections.sort(methodHints, comparator);
} catch (FrameworkException ex) {
java.util.logging.Logger.getLogger(JavascriptHintProvider.class.getName()).log(Level.SEVERE, null, ex);
}
Collections.sort(hints, comparator);
// add sorted method hints after the other hints
hints.addAll(methodHints);
}
protected boolean handleTokens(final ActionContext actionContext, final List<String> tokens, final GraphObject currentNode, final List<Hint> hints, final ParseResult result) {
List<String> tokenTypes = new LinkedList<>();
Class type = null;
for (final String token : tokens) {
switch (token) {
case "":
// last character in the expression is "."
tokenTypes.add("dot");
break;
case "$":
case "Structr":
tokenTypes.add("root");
break;
case "page":
tokenTypes.add("keyword");
type = StructrApp.getConfiguration().getNodeEntityClass("Page");
break;
case "me":
tokenTypes.add("keyword");
type = StructrApp.getConfiguration().getNodeEntityClass("User");
break;
case "current":
tokenTypes.add("keyword");
type = StructrApp.getConfiguration().getNodeEntityClass("AbstractNode");
break;
case "this":
if(currentNode instanceof SchemaMethod) {
final AbstractSchemaNode node = currentNode.getProperty(SchemaMethod.schemaNode);
if (node != null) {
tokenTypes.add("keyword");
type = StructrApp.getConfiguration().getNodeEntityClass(node.getClassName());
}
} else if (currentNode instanceof SchemaProperty && Type.Function.equals(((SchemaProperty)currentNode).getPropertyType())) {
final AbstractSchemaNode node = currentNode.getProperty(SchemaMethod.schemaNode);
if (node != null) {
tokenTypes.add("keyword");
type = StructrApp.getConfiguration().getNodeEntityClass(node.getClassName());
}
} else if (currentNode != null) {
tokenTypes.add("keyword");
type = StructrApp.getConfiguration().getNodeEntityClass(currentNode.getType());
}
break;
default:
// skip numbers
if (!StringUtils.isNumeric(token)) {
if (type != null) {
final String cleaned = token.replaceAll("[\\W\\d]+", "");
final PropertyKey key = StructrApp.key(type, cleaned, false);
if (key != null && key.relatedType() != null) {
tokenTypes.add("keyword");
type = key.relatedType();
} else {
tokenTypes.add(token);
}
} else {
tokenTypes.add(token);
}
}
break;
}
}
Collections.reverse(tokenTypes);
boolean requireValidPredecessor = false;
for (final String tokenType : tokenTypes) {
switch (tokenType) {
case "dot":
// if the last token of an expression is a dot, e.g. "this.owner.", the preceding keyword must be valid
requireValidPredecessor = true;
break;
case "root":
if (tokenTypes.size() < 3) {
addAllHints(hints);
return true;
}
break;
case "keyword":
if (type != null) {
addHintsForType(actionContext, type, hints, result);
return true;
}
break;
default:
final Function func = Functions.get(tokenType);
if (func != null) {
final List<Hint> contextHints = func.getContextHints(result.getLastToken());
if (contextHints != null) {
hints.addAll(contextHints);
Collections.sort(hints, comparator);
}
return true;
} else if (requireValidPredecessor) {
return false;
}
break;
}
}
return false;
}
// ----- private methods -----
private void addPosition(final GraphObjectMap item, final Hint hint, final int cursorLine, final int replaceFrom, final int replaceTo) {
final GraphObjectMap fromObject = new GraphObjectMap();
final GraphObjectMap toObject = new GraphObjectMap();
fromObject.put(line, cursorLine);
fromObject.put(ch, replaceFrom);
toObject.put(line, cursorLine);
toObject.put(ch, replaceTo);
item.put(from, fromObject);
item.put(to, toObject);
}
// ----- nested classes -----
protected static class HintComparator implements Comparator<Hint> {
@Override
public int compare(final Hint o1, final Hint o2) {
final boolean firstIsDynamic = o1.isDynamic();
final boolean secindIsDynamic = o2.isDynamic();
if (firstIsDynamic && !secindIsDynamic) {
return -1;
}
if (!firstIsDynamic && secindIsDynamic) {
return 1;
}
return o1.getName().compareTo(o2.getName());
}
}
protected static class AutocompleteContentHandler implements ContentHandler {
private boolean inScript = false;
private String scriptText = null;
@Override
public void handleScript(String script, final int row, final int column) throws FrameworkException, IOException {
inScript = false;
}
@Override
public void handleText(String text) throws FrameworkException {
}
@Override
public void handleIncompleteScript(String script) throws FrameworkException, IOException {
scriptText = script;
}
@Override
public void possibleStartOfScript(int row, int column) {
inScript = true;
}
public boolean inScript() {
return inScript;
}
public String getScript() {
return scriptText;
}
}
}