Merge branch 'subtree'
[fanfix.git] / src / be / nikiroo / utils / StringJustifier.java
... / ...
CommitLineData
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 *
30 * I added some changes to integrate it here.
31 * @author Niki
32 */
33package be.nikiroo.utils;
34
35import java.util.LinkedList;
36import java.util.List;
37
38/**
39 * StringJustifier contains methods to convert one or more long lines of strings
40 * into justified text paragraphs.
41 */
42class StringJustifier {
43 /**
44 * Process the given text into a list of left-justified lines of a given
45 * max-width.
46 *
47 * @param data
48 * the text to justify
49 * @param width
50 * the maximum width of a line
51 *
52 * @return the list of justified lines
53 */
54 static List<String> left(final String data, final int width) {
55 return left(data, width, false);
56 }
57
58 /**
59 * Right-justify a string into a list of lines.
60 *
61 * @param str
62 * the string
63 * @param n
64 * the maximum number of characters in a line
65 * @return the list of lines
66 */
67 static List<String> right(final String str, final int n) {
68 List<String> result = new LinkedList<String>();
69
70 /*
71 * Same as left(), but preceed each line with spaces to make it n chars
72 * long.
73 */
74 List<String> lines = left(str, n);
75 for (String line : lines) {
76 StringBuilder sb = new StringBuilder();
77 for (int i = 0; i < n - line.length(); i++) {
78 sb.append(' ');
79 }
80 sb.append(line);
81 result.add(sb.toString());
82 }
83
84 return result;
85 }
86
87 /**
88 * Center a string into a list of lines.
89 *
90 * @param str
91 * the string
92 * @param n
93 * the maximum number of characters in a line
94 * @return the list of lines
95 */
96 static List<String> center(final String str, final int n) {
97 List<String> result = new LinkedList<String>();
98
99 /*
100 * Same as left(), but preceed/succeed each line with spaces to make it
101 * n chars long.
102 */
103 List<String> lines = left(str, n);
104 for (String line : lines) {
105 StringBuilder sb = new StringBuilder();
106 int l = (n - line.length()) / 2;
107 int r = n - line.length() - l;
108 for (int i = 0; i < l; i++) {
109 sb.append(' ');
110 }
111 sb.append(line);
112 for (int i = 0; i < r; i++) {
113 sb.append(' ');
114 }
115 result.add(sb.toString());
116 }
117
118 return result;
119 }
120
121 /**
122 * Fully-justify a string into a list of lines.
123 *
124 * @param str
125 * the string
126 * @param n
127 * the maximum number of characters in a line
128 * @return the list of lines
129 */
130 static List<String> full(final String str, final int n) {
131 List<String> result = new LinkedList<String>();
132
133 /*
134 * Same as left(true), but insert spaces between words to make each line
135 * n chars long. The "algorithm" here is pretty dumb: it performs a
136 * split on space and then re-inserts multiples of n between words.
137 */
138 List<String> lines = left(str, n, true);
139 for (int lineI = 0; lineI < lines.size() - 1; lineI++) {
140 String line = lines.get(lineI);
141 String[] words = line.split(" ");
142 if (words.length > 1) {
143 int charCount = 0;
144 for (int i = 0; i < words.length; i++) {
145 charCount += words[i].length();
146 }
147 int spaceCount = n - charCount;
148 int q = spaceCount / (words.length - 1);
149 int r = spaceCount % (words.length - 1);
150 StringBuilder sb = new StringBuilder();
151 for (int i = 0; i < words.length - 1; i++) {
152 sb.append(words[i]);
153 for (int j = 0; j < q; j++) {
154 sb.append(' ');
155 }
156 if (r > 0) {
157 sb.append(' ');
158 r--;
159 }
160 }
161 for (int j = 0; j < r; j++) {
162 sb.append(' ');
163 }
164 sb.append(words[words.length - 1]);
165 result.add(sb.toString());
166 } else {
167 result.add(line);
168 }
169 }
170 if (lines.size() > 0) {
171 result.add(lines.get(lines.size() - 1));
172 }
173
174 return result;
175 }
176
177 /**
178 * Process the given text into a list of left-justified lines of a given
179 * max-width.
180 *
181 * @param data
182 * the text to justify
183 * @param width
184 * the maximum width of a line
185 * @param minTwoWords
186 * use 2 words per line minimum if the text allows it
187 *
188 * @return the list of justified lines
189 */
190 static private List<String> left(final String data, final int width,
191 boolean minTwoWords) {
192 List<String> lines = new LinkedList<String>();
193
194 for (String dataLine : data.split("\n")) {
195 String line = rightTrim(dataLine.replace("\t", " "));
196
197 if (width > 0 && line.length() > width) {
198 while (line.length() > 0) {
199 int i = Math.min(line.length(), width - 1); // -1 for "-"
200
201 boolean needDash = true;
202 // find the best space if any and if needed
203 int prevSpace = 0;
204 if (i < line.length()) {
205 prevSpace = -1;
206 int space = line.indexOf(' ');
207 int numOfSpaces = 0;
208
209 while (space > -1 && space <= i) {
210 prevSpace = space;
211 space = line.indexOf(' ', space + 1);
212 numOfSpaces++;
213 }
214
215 if (prevSpace > 0 && (!minTwoWords || numOfSpaces >= 2)) {
216 i = prevSpace;
217 needDash = false;
218 }
219 }
220 //
221
222 // no dash before space/dash
223 if ((i + 1) < line.length()) {
224 char car = line.charAt(i);
225 char nextCar = line.charAt(i + 1);
226 if (car == ' ' || car == '-' || nextCar == ' ') {
227 needDash = false;
228 } else if (i > 0) {
229 char prevCar = line.charAt(i - 1);
230 if (prevCar == ' ' || prevCar == '-') {
231 needDash = false;
232 i--;
233 }
234 }
235 }
236
237 // if the space freed by the removed dash allows it, or if
238 // it is the last char, add the next char
239 if (!needDash || i >= line.length() - 1) {
240 int checkI = Math.min(i + 1, line.length());
241 if (checkI == i || checkI <= width) {
242 needDash = false;
243 i = checkI;
244 }
245 }
246
247 // no dash before parenthesis (but cannot add one more
248 // after)
249 if ((i + 1) < line.length()) {
250 char nextCar = line.charAt(i + 1);
251 if (nextCar == '(' || nextCar == ')') {
252 needDash = false;
253 }
254 }
255
256 if (needDash) {
257 lines.add(rightTrim(line.substring(0, i)) + "-");
258 } else {
259 lines.add(rightTrim(line.substring(0, i)));
260 }
261
262 // full trim (remove spaces when cutting)
263 line = line.substring(i).trim();
264 }
265 } else {
266 lines.add(line);
267 }
268 }
269
270 return lines;
271 }
272
273 /**
274 * Trim the given {@link String} on the right only.
275 *
276 * @param data
277 * the source {@link String}
278 * @return the right-trimmed String or Empty if it was NULL
279 */
280 static private String rightTrim(String data) {
281 if (data == null)
282 return "";
283
284 return ("|" + data).trim().substring(1);
285 }
286}