Text justification: tests (WIP) + code (WIP)
[fanfix.git] / src / be / nikiroo / utils / StringJustifier.java
CommitLineData
cc3e7291
NR
1/*
2 * This file was taken from:
3 * Jexer - Java Text User Interface
4 *
5 * The MIT License (MIT)
6 *
7 * Copyright (C) 2017 Kevin Lamonte
8 *
9 * Permission is hereby granted, free of charge, to any person obtaining a
10 * copy of this software and associated documentation files (the "Software"),
11 * to deal in the Software without restriction, including without limitation
12 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
13 * and/or sell copies of the Software, and to permit persons to whom the
14 * Software is furnished to do so, subject to the following conditions:
15 *
16 * The above copyright notice and this permission notice shall be included in
17 * all copies or substantial portions of the Software.
18 *
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25 * DEALINGS IN THE SOFTWARE.
26 *
27 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
28 * @version 1
29 */
30package be.nikiroo.utils;
31
32import java.util.LinkedList;
33import java.util.List;
34
35/**
36 * StringJustifier contains methods to convert one or more long lines of strings
37 * into justified text paragraphs.
38 */
39class StringJustifier {
6a493e05
NR
40 /**
41 * Process the given text into a list of left-justified lines of a given
42 * max-width.
43 *
44 * @param data
45 * the text to justify
46 * @param width
47 * the maximum width of a line
48 *
49 * @return the list of justified lines
50 */
771c4ba4
NR
51 static List<String> left(final String data, final int width) {
52 List<String> lines = new LinkedList<String>();
6a493e05 53
771c4ba4
NR
54 for (String dataLine : data.split("\n")) {
55 String line = rightTrim(dataLine.replace("\t", " "));
cc3e7291 56
771c4ba4
NR
57 if (width > 0 && line.length() > width) {
58 while (line.length() > 0) {
59 int i = Math.min(line.length(), width - 1); // -1 for "-"
cc3e7291 60
771c4ba4
NR
61 boolean needDash = true;
62 // find the best space if any and if needed
63 int prevSpace = 0;
64 if (i < line.length()) {
65 prevSpace = -1;
66 int space = line.indexOf(' ');
cc3e7291 67
771c4ba4
NR
68 while (space > -1 && space <= i) {
69 prevSpace = space;
70 space = line.indexOf(' ', space + 1);
cc3e7291 71 }
771c4ba4
NR
72
73 if (prevSpace > 0) {
74 i = prevSpace;
75 needDash = false;
76 }
77 }
78 //
79
80 // no dash before space/dash
81 if ((i + 1) < line.length()) {
82 char car = line.charAt(i);
83 char nextCar = line.charAt(i + 1);
84 if (nextCar == ' ' || car == '-' || nextCar == '-') {
85 needDash = false;
cc3e7291 86 }
cc3e7291 87 }
771c4ba4
NR
88
89 // if the space freed by the removed dash allows it, or if
90 // it is the last char, add the next char
91 if (!needDash || i >= line.length() - 1) {
92 int checkI = Math.min(i + 1, line.length());
93 if (checkI == i || checkI <= width) {
94 needDash = false;
95 i = checkI;
96 }
97 }
98
99 // no dash before parenthesis (but cannot add one more
100 // after)
101 if ((i + 1) < line.length()) {
102 char car = line.charAt(i + 1);
103 if (car == '(' || car == ')') {
104 needDash = false;
105 }
106 }
107
108 if (needDash) {
109 lines.add(rightTrim(line.substring(0, i)) + "-");
cc3e7291 110 } else {
771c4ba4 111 lines.add(rightTrim(line.substring(0, i)));
cc3e7291 112 }
cc3e7291 113
771c4ba4
NR
114 // full trim (remove spaces when cutting)
115 line = line.substring(i).trim();
116 }
cc3e7291 117 } else {
771c4ba4 118 lines.add(line);
cc3e7291 119 }
771c4ba4 120 }
cc3e7291 121
771c4ba4 122 return lines;
cc3e7291
NR
123 }
124
125 /**
126 * Right-justify a string into a list of lines.
127 *
128 * @param str
129 * the string
130 * @param n
131 * the maximum number of characters in a line
132 * @return the list of lines
133 */
134 static List<String> right(final String str, final int n) {
135 List<String> result = new LinkedList<String>();
136
137 /*
138 * Same as left(), but preceed each line with spaces to make it n chars
139 * long.
140 */
141 List<String> lines = left(str, n);
142 for (String line : lines) {
143 StringBuilder sb = new StringBuilder();
144 for (int i = 0; i < n - line.length(); i++) {
145 sb.append(' ');
146 }
147 sb.append(line);
148 result.add(sb.toString());
149 }
150
151 return result;
152 }
153
154 /**
155 * Center a string into a list of lines.
156 *
157 * @param str
158 * the string
159 * @param n
160 * the maximum number of characters in a line
161 * @return the list of lines
162 */
163 static List<String> center(final String str, final int n) {
164 List<String> result = new LinkedList<String>();
165
166 /*
167 * Same as left(), but preceed/succeed each line with spaces to make it
168 * n chars long.
169 */
170 List<String> lines = left(str, n);
171 for (String line : lines) {
172 StringBuilder sb = new StringBuilder();
173 int l = (n - line.length()) / 2;
174 int r = n - line.length() - l;
175 for (int i = 0; i < l; i++) {
176 sb.append(' ');
177 }
178 sb.append(line);
179 for (int i = 0; i < r; i++) {
180 sb.append(' ');
181 }
182 result.add(sb.toString());
183 }
184
185 return result;
186 }
187
188 /**
189 * Fully-justify a string into a list of lines.
190 *
191 * @param str
192 * the string
193 * @param n
194 * the maximum number of characters in a line
195 * @return the list of lines
196 */
197 static List<String> full(final String str, final int n) {
198 List<String> result = new LinkedList<String>();
199
200 /*
201 * Same as left(), but insert spaces between words to make each line n
202 * chars long. The "algorithm" here is pretty dumb: it performs a split
203 * on space and then re-inserts multiples of n between words.
204 */
205 List<String> lines = left(str, n);
206 for (int lineI = 0; lineI < lines.size() - 1; lineI++) {
207 String line = lines.get(lineI);
208 String[] words = line.split(" ");
209 if (words.length > 1) {
210 int charCount = 0;
211 for (int i = 0; i < words.length; i++) {
212 charCount += words[i].length();
213 }
214 int spaceCount = n - charCount;
215 int q = spaceCount / (words.length - 1);
216 int r = spaceCount % (words.length - 1);
217 StringBuilder sb = new StringBuilder();
218 for (int i = 0; i < words.length - 1; i++) {
219 sb.append(words[i]);
220 for (int j = 0; j < q; j++) {
221 sb.append(' ');
222 }
223 if (r > 0) {
224 sb.append(' ');
225 r--;
226 }
227 }
228 for (int j = 0; j < r; j++) {
229 sb.append(' ');
230 }
231 sb.append(words[words.length - 1]);
232 result.add(sb.toString());
233 } else {
234 result.add(line);
235 }
236 }
237 if (lines.size() > 0) {
238 result.add(lines.get(lines.size() - 1));
239 }
240
241 return result;
242 }
771c4ba4
NR
243
244 /**
245 * Trim the given {@link String} on the right only.
246 *
247 * @param data
248 * the source {@link String}
249 * @return the right-trimmed String or Empty if it was NULL
250 */
251 static private String rightTrim(String data) {
252 if (data == null)
253 return "";
254
255 return ("|" + data).trim().substring(1);
256 }
cc3e7291 257}