1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package org.nuiton.jrst.legacy.directive;
24
25 import org.nuiton.jrst.JRSTDirective;
26 import org.nuiton.jrst.legacy.JRSTLexer;
27 import static org.nuiton.jrst.legacy.ReStructuredText.IMAGE;
28 import static org.nuiton.jrst.legacy.ReStructuredText.SUBSTITUTION_DEFINITION;
29 import org.dom4j.DocumentHelper;
30 import org.dom4j.Element;
31 import org.dom4j.Node;
32
33 import java.util.regex.Matcher;
34 import java.util.regex.Pattern;
35
36
37
38
39
40
41
42
43
44
45
46
47
48 public class ImageDirective implements JRSTDirective {
49
50 protected static final String SCALE = "scale";
51 protected static final String WIDTH = "width";
52 protected static final String HEIGHT = "height";
53
54
55
56
57
58
59 @Override
60 public Node parse(Element e) {
61 Element result = DocumentHelper.createElement(IMAGE);
62
63 if (e.getParent() != null
64 && SUBSTITUTION_DEFINITION.equals(e.getParent().getName())) {
65 String ref = e.getParent().attributeValue("name");
66 result.addAttribute("alt", ref);
67 }
68 result.addAttribute("uri", e.attributeValue(JRSTLexer.DIRECTIVE_VALUE));
69
70 Pattern arg = Pattern.compile(":([^:]+):\\s*(.*)");
71 String[] lines = e.getText().split("\n");
72 for (String l : lines) {
73 Matcher matcher = arg.matcher(l.trim());
74 if (matcher.matches()) {
75 String name = matcher.group(1);
76 String value = matcher.group(2);
77 if (SCALE.equalsIgnoreCase(name)) {
78 if (!result.asXML().matches(".*" + WIDTH + "=\".*\".*")) {
79 result.addAttribute(WIDTH, value + (value.matches(".*%") ? "" : "%"));
80 }
81 if (!result.asXML().matches(".*" + HEIGHT + "=\".*\".*")) {
82 result.addAttribute(HEIGHT, value + (value.matches(".*%") ? "" : "%"));
83 }
84 }
85 result.addAttribute(name, value);
86 }
87 }
88 return result;
89 }
90
91 }