Debian Codegraph @

src/utils/arrangement/dynamic.rs

raw symbols SCIP
1 use unicode_width::UnicodeWidthStr;
2
3 use super::{ColumnDisplayInfo, DisplayInfos, constraint, helper::*};
4 use crate::{Column, Table, style::*, utils::formatting::content_split::split_line};
5
6 /// Try to find the best fit for a given content and table_width
7 ///
8 /// 1. Determine the amount of available space after applying fixed columns, padding, and borders.
9 /// 2. Now that we know how much space we have to work with, we have to check again for
10 /// LowerBoundary constraints. If there are any columns that have a higher LowerBoundary, we have
11 /// to fix that column to this size.
12 /// 3. Check if there are any columns that require less space than the average remaining space for
13 /// the remaining columns. (This includes the MaxWidth constraint).
14 /// 4. Take those columns, fix their size and add the surplus in space to the remaining space.
15 /// 5. Repeat step 2-3 until no columns with smaller size than average remaining space are left.
16 /// 6. At this point, the remaining spaces is equally distributed between all columns. It get's a
17 /// little tricky now. Check the documentation of [optimize_space_after_split] for more
18 /// information.
19 /// 7. Divide the remaining space in relatively equal chunks.
20 ///
21 /// This breaks when:
22 ///
23 /// 1. A user assigns fixed sizes to a few columns, which are larger than the terminal when
24 /// combined.
25 /// 2. A user provides more than 100% column width across a few columns.
26 pub fn arrange(
27 table: &Table,
28 infos: &mut DisplayInfos,
29 table_width: usize,
30 max_content_widths: &[u16],
31 ) {
32 let visible_columns = count_visible_columns(&table.columns);
33
34 // Step 1
35 // Find out how much space there is left.
36 let mut remaining_width: usize =
37 available_content_width(table, infos, visible_columns, table_width);
38 let mut remaining_columns = count_remaining_columns(visible_columns, infos);
39
40 #[cfg(feature = "_debug")]
41 println!(
42 "dynamic::arrange: Table width: {table_width}, Start remaining width {remaining_width}"
43 );
44 #[cfg(feature = "_debug")]
45 println!("dynamic::arrange: Max content widths: {max_content_widths:#?}");
46
47 // Step 2.
48 //
49 // Iterate through all undecided columns and enforce LowerBoundary constraints, if they're
50 // bigger than the current average space.
51 if remaining_columns > 0 {
52 (remaining_width, remaining_columns) = enforce_lower_boundary_constraints(
53 table,
54 infos,
55 remaining_width,
56 remaining_columns,
57 visible_columns,
58 );
59 }
60
61 // Step 3-5.
62 // Find all columns that require less space than the average.
63 // Returns the remaining available width and the amount of remaining columns that need handling
64 let (mut remaining_width, mut remaining_columns) = find_columns_that_fit_into_average(
65 table,
66 infos,
67 remaining_width,
68 remaining_columns,
69 visible_columns,
70 max_content_widths,
71 );
72
73 #[cfg(feature = "_debug")]
74 {
75 println!("After less than average: {infos:#?}");
76 println!("Remaining width {remaining_width}, column {remaining_columns}");
77 }
78
79 // Step 6
80 // All remaining columns should get an equal amount of remaining space.
81 // However, we check if we can save some space after the content has been split.
82 //
83 // We only do this if there are remaining columns.
84 if remaining_columns > 0 {
85 // This is where Step 5 happens.
86 (remaining_width, remaining_columns) =
87 optimize_space_after_split(table, infos, remaining_width, remaining_columns);
88 }
89
90 #[cfg(feature = "_debug")]
91 {
92 println!("dynamic::arrange: After optimize: {infos:#?}",);
93 println!("dynamic::arrange: Remaining width {remaining_width}, column {remaining_columns}",);
94 }
95
96 // Early exit and one branch of Part 7.
97 //
98 // All columns have been successfully assigned a width.
99 // However, in case the user specified that the full terminal width should always be fully
100 // utilized, we have to equally distribute the remaining space across all columns.
101 if remaining_columns == 0 {
102 if remaining_width > 0 && matches!(table.arrangement, ContentArrangement::DynamicFullWidth)
103 {
104 use_full_width(infos, remaining_width);
105 #[cfg(feature = "_debug")]
106 println!("dynamic::arrange: After full width: {infos:#?}");
107 }
108 return;
109 }
110
111 // Step 7. Equally distribute the remaining_width to all remaining columns
112 // If we have less than one space per remaining column, give at least one space per column
113 if remaining_width < remaining_columns {
114 remaining_width = remaining_columns;
115 }
116
117 distribute_remaining_space(&table.columns, infos, remaining_width, remaining_columns);
118
119 #[cfg(feature = "_debug")]
120 println!("dynamic::arrange: After distribute: {infos:#?}");
121 }
122
123 /// Step 1
124 ///
125 /// This function calculates the amount of remaining space that can be distributed between
126 /// all remaining columns.
127 ///
128 /// Take the current terminal width and
129 /// - Subtract borders
130 /// - Subtract padding
131 /// - Subtract columns that already have a fixed width.
132 ///
133 /// This value is converted to a i32 to handle negative values in case we work with a very small
134 /// terminal.
135 fn available_content_width(
136 table: &Table,
137 infos: &DisplayInfos,
138 visible_columns: usize,
139 mut width: usize,
140 ) -> usize {
141 let border_count = count_border_columns(table, visible_columns);
142 width = width.saturating_sub(border_count);
143
144 // Subtract all paddings from the remaining width.
145 for column in table.columns.iter() {
146 if infos.contains_key(&column.index) {
147 continue;
148 }
149
150 // Remove the fixed padding for each column
151 let (left, right) = column.padding;
152 width = width.saturating_sub((left + right).into());
153 }
154
155 // Remove all already fixed sizes from the remaining_width.
156 for info in infos.values() {
157 if info.is_hidden {
158 continue;
159 }
160
161 width = width.saturating_sub(info.width().into());
162 }
163
164 width
165 }
166
167 /// Step 2-4
168 /// This function is part of the column width calculation process.
169 /// It checks if there are columns that take less space than there's currently available in average
170 /// for each column.
171 ///
172 /// The algorithm is a while loop with a nested for loop.
173 /// 1. We iterate over all columns and check if there are columns that take less space.
174 /// 2. If we find one or more such columns, we fix their width and add the surplus space to the
175 /// emaining space. Due to this step, the average space per column increased. Now some other
176 /// column might be fixed in width as well.
177 /// 3. Do step 1 and 2, as long as there are columns left and as long as we find columns that take
178 /// up less space than the current remaining average.
179 ///
180 /// Parameters:
181 /// - `table_width`: The absolute amount of available space.
182 /// - `remaining_width`: This is the amount of space that isn't yet reserved by any other column. We
183 /// need this to determine the average space each column has left. Any columns that needs less
184 /// than this average receives a fixed width. The leftover space can then be used for the other
185 /// columns.
186 /// - `visible_columns`: All visible columns that should be displayed.
187 ///
188 /// Returns:
189 /// `(remaining_width: usize, remaining_columns: u16)`
190 fn find_columns_that_fit_into_average(
191 table: &Table,
192 infos: &mut DisplayInfos,
193 mut remaining_width: usize,
194 mut remaining_columns: usize,
195 visible_columns: usize,
196 max_content_widths: &[u16],
197 ) -> (usize, usize) {
198 let mut found_smaller = true;
199 while found_smaller {
200 found_smaller = false;
201
202 // There are no columns left to check. Proceed to the next step
203 if remaining_columns == 0 {
204 break;
205 }
206
207 let mut average_space = remaining_width / remaining_columns;
208 // We have no space left, the terminal is either tiny or the other columns are huge.
209 if average_space == 0 {
210 break;
211 }
212
213 for column in table.columns.iter() {
214 // Ignore hidden columns
215 // We already checked this column, skip it
216 if infos.contains_key(&column.index) {
217 continue;
218 }
219
220 let max_column_width = max_content_widths[column.index];
221
222 // The column has a MaxWidth Constraint.
223 // we can fix the column to this max_width and mark it as checked if these
224 // two conditions are met:
225 // - The average remaining space is bigger then the MaxWidth constraint.
226 // - The actual max content of the column is bigger than the MaxWidth constraint.
227 if let Some(max_width) = constraint::max(table, &column.constraint, visible_columns) {
228 // Max/Min constraints always include padding!
229 let average_space_with_padding =
230 average_space + usize::from(column.padding_width());
231
232 let width_with_padding = max_column_width + column.padding_width();
233 // Check that both conditions mentioned above are met.
234 if usize::from(max_width) <= average_space_with_padding
235 && width_with_padding >= max_width
236 {
237 // Save the calculated info, this column has been handled.
238 let width = absolute_width_with_padding(column, max_width);
239 let info = ColumnDisplayInfo::new(column, width);
240 infos.insert(column.index, info);
241
242 #[cfg(feature = "_debug")]
243 println!(
244 "dynamic::find_columns_that_fit_into_average: Fixed column {} via MaxWidth constraint with size {}, as it's bigger than average {}",
245 column.index, width, average_space
246 );
247
248 // Continue with new recalculated width
249 remaining_width = remaining_width.saturating_sub(width.into());
250 remaining_columns -= 1;
251
252 if remaining_columns == 0 {
253 break;
254 }
255
256 average_space = remaining_width / remaining_columns;
257 found_smaller = true;
258 continue;
259 }
260 }
261
262 // The column has a smaller or equal max_content_width than the average space.
263 // Fix the width to max_content_width and mark it as checked
264 if usize::from(max_column_width) <= average_space {
265 let info = ColumnDisplayInfo::new(column, max_column_width);
266 infos.insert(column.index, info);
267
268 #[cfg(feature = "_debug")]
269 println!(
270 "dynamic::find_columns_that_fit_into_average: Fixed column {} with size {}, as it's smaller than average {}",
271 column.index, max_column_width, average_space
272 );
273
274 // Continue with new recalculated width
275 remaining_width = remaining_width.saturating_sub(max_column_width.into());
276 remaining_columns -= 1;
277 if remaining_columns == 0 {
278 break;
279 }
280
281 average_space = remaining_width / remaining_columns;
282 found_smaller = true;
283 }
284 }
285 }
286
287 (remaining_width, remaining_columns)
288 }
289
290 /// Step 5
291 ///
292 /// Determine, whether there are any columns that are allowed to occupy more width than the current
293 /// `average_space` via a [LowerBoundary] constraint.
294 ///
295 /// These columns will then get fixed to the width specified in the [LowerBoundary] constraint.
296 ///
297 /// I.e. if a column has to have at least 10 characters, but the average width left for a column is
298 /// only 6, we fix the column to this 10 character minimum!
299 fn enforce_lower_boundary_constraints(
300 table: &Table,
301 infos: &mut DisplayInfos,
302 mut remaining_width: usize,
303 mut remaining_columns: usize,
304 visible_columns: usize,
305 ) -> (usize, usize) {
306 let mut average_space = remaining_width / remaining_columns;
307
308 // We loop this as long as we found a lower boundary that fixed a column in place.
309 // Due to enforced lower boundaries, the `average_space` can shrink, which can result in
310 // further lower boundaries being triggered.
311 let mut try_again = true;
312 while try_again {
313 try_again = false;
314 for column in table.columns.iter() {
315 // Ignore hidden columns
316 // We already checked this column, skip it
317 if infos.contains_key(&column.index) {
318 continue;
319 }
320
321 // Check whether the column has a LowerBoundary constraint.
322 let Some(min_width) = constraint::min(table, &column.constraint, visible_columns)
323 else {
324 continue;
325 };
326
327 // Only proceed if the average spaces is smaller than the specified lower boundary.
328 if average_space >= min_width.into() {
329 continue;
330 }
331
332 // This column would get smaller than the specified lower boundary.
333 // Fix its width!!!
334 let width = absolute_width_with_padding(column, min_width);
335 let info = ColumnDisplayInfo::new(column, width);
336 infos.insert(column.index, info);
337
338 #[cfg(feature = "_debug")]
339 println!(
340 "dynamic::enforce_lower_boundary_constraints: Fixed column {} to min constraint width {}",
341 column.index, width
342 );
343
344 // Continue with new recalculated width
345 remaining_width = remaining_width.saturating_sub(width.into());
346 remaining_columns -= 1;
347 if remaining_columns == 0 {
348 break;
349 }
350
351 average_space = remaining_width / remaining_columns;
352 try_again = true;
353 }
354 }
355
356 (remaining_width, remaining_columns)
357 }
358
359 /// Step 5.
360 ///
361 /// Some Column's are too big and need to be split.
362 /// We're now going to simulate how this might look like.
363 /// The reason for this is the way we're splitting, which is to prefer a split at a delimiter.
364 /// This can lead to a column needing less space than it was initially assigned.
365 ///
366 /// Example:
367 /// A column is allowed to have a width of 10 characters.
368 /// A cell's content looks like this `sometest sometest`, which is 17 chars wide.
369 /// After splitting at the default delimiter (space), it looks like this:
370 /// ```text
371 /// sometest
372 /// sometest
373 /// ```
374 /// Even though the column required 17 spaces beforehand, it can now be shrunk to 8 chars width.
375 ///
376 /// By doing this for each column, we can save a lot of space in some edge-cases.
377 fn optimize_space_after_split(
378 table: &Table,
379 infos: &mut DisplayInfos,
380 mut remaining_width: usize,
381 mut remaining_columns: usize,
382 ) -> (usize, usize) {
383 let mut found_smaller = true;
384 // Calculate the average space that remains for each column.
385 let mut average_space = remaining_width / remaining_columns;
386
387 #[cfg(feature = "_debug")]
388 println!(
389 "dynamic::optimize_space_after_split: Start with average_space {}",
390 average_space
391 );
392
393 // Do this as long as we find a smaller column
394 while found_smaller {
395 found_smaller = false;
396 for column in table.columns.iter() {
397 // We already checked this column, skip it
398 if infos.contains_key(&column.index) {
399 continue;
400 }
401
402 let longest_line = longest_line_after_split(average_space, column, table);
403
404 #[cfg(feature = "_debug")]
405 println!(
406 "dynamic::optimize_space_after_split: Longest line after split for column {} is {}",
407 column.index, longest_line
408 );
409
410 // If there's a considerable amount of space left after splitting, we freeze the column
411 // and set its content width to the calculated post-split width.
412 let remaining_space = average_space.saturating_sub(longest_line);
413 if remaining_space >= 3 {
414 let info =
415 ColumnDisplayInfo::new(column, longest_line.try_into().unwrap_or(u16::MAX));
416 infos.insert(column.index, info);
417
418 remaining_width = remaining_width.saturating_sub(longest_line);
419 remaining_columns -= 1;
420 if remaining_columns == 0 {
421 break;
422 }
423
424 average_space = remaining_width / remaining_columns;
425
426 #[cfg(feature = "_debug")]
427 println!(
428 "dynamic::optimize_space_after_split: average_space is now {}",
429 average_space
430 );
431 found_smaller = true;
432 }
433 }
434 }
435
436 (remaining_width, remaining_columns)
437 }
438
439 /// Part of Step 5.
440 ///
441 /// This function simulates the split of a Column's content and returns the length of
442 /// the longest existing line after the split.
443 ///
444 /// A lot of this logic is duplicated from the [utils::format::format_row] function.
445 fn longest_line_after_split(average_space: usize, column: &Column, table: &Table) -> usize {
446 // Runtime variable that holds the longest found line length.
447 let mut longest = 0;
448
449 for cell in table.column_cells_with_header_iter(column.index) {
450 // Only look at rows that actually contain this cell.
451 let Some(cell) = cell else { continue };
452
453 let delimiter = delimiter(table, column, cell);
454
455 // Create a temporary ColumnDisplayInfo with the average space as width.
456 // That way we can simulate how the split text will look like.
457 let info = ColumnDisplayInfo::new(column, average_space.try_into().unwrap_or(u16::MAX));
458
459 // Iterate over each line and split it into multiple lines, if necessary.
460 // Newlines added by the user will be preserved.
461 for line in cell.content.iter() {
462 if line.width() > average_space {
463 let parts = split_line(line, &info, delimiter);
464
465 #[cfg(feature = "_debug")]
466 println!(
467 "dynamic::longest_line_after_split: Splitting line with width {}. Original:\n {}\nSplitted:\n {:?}",
468 line.width(),
469 line,
470 parts
471 );
472
473 parts
474 .iter()
475 .for_each(|part| longest = longest.max(part.len()));
476 } else {
477 longest = longest.max(line.len())
478 }
479 }
480 }
481
482 longest
483 }
484
485 /// Step 6 - First branch
486 ///
487 /// At this point of time, all columns have been assigned some kind of width!
488 /// The user wants to utilize the full width of the terminal and there's space left.
489 ///
490 /// Equally distribute the remaining space between all columns.
491 fn use_full_width(infos: &mut DisplayInfos, remaining_width: usize) {
492 let visible_columns = infos.iter().filter(|(_, info)| !info.is_hidden).count();
493
494 if visible_columns == 0 {
495 return;
496 }
497
498 // Calculate the amount of average remaining space per column.
499 // Since we do integer division, there is most likely a little bit of non equally-divisible
500 // space. We then try to distribute it as fair as possible (from left to right).
501 let average_space = remaining_width / visible_columns;
502 let mut excess = remaining_width - (average_space * visible_columns);
503
504 for (_, info) in infos.iter_mut() {
505 // Ignore hidden columns
506 if info.is_hidden {
507 continue;
508 }
509
510 // Distribute the non-divisible excess from left-to right until nothing is left.
511 let width = if excess > 0 {
512 excess -= 1;
513 (average_space + 1).try_into().unwrap_or(u16::MAX)
514 } else {
515 average_space.try_into().unwrap_or(u16::MAX)
516 };
517
518 info.content_width += width;
519 }
520 }
521
522 /// Step 6 - Second branch
523 ///
524 /// Not all columns have a determined width yet -> The content still doesn't fully fit into the
525 /// given width.
526 ///
527 /// This function now equally distributes the remaining width between the remaining columns.
528 fn distribute_remaining_space(
529 columns: &[Column],
530 infos: &mut DisplayInfos,
531 remaining_width: usize,
532 remaining_columns: usize,
533 ) {
534 // Calculate the amount of average remaining space per column.
535 // Since we do integer division, there is most likely a little bit of non equally-divisible
536 // space. We then try to distribute it as fair as possible (from left to right).
537 let average_space = remaining_width / remaining_columns;
538 let mut excess = remaining_width - (average_space * remaining_columns);
539
540 for column in columns.iter() {
541 // Ignore hidden columns
542 if infos.contains_key(&column.index) {
543 continue;
544 }
545
546 // Distribute the non-divisible excess from left-to right until nothing is left.
547 let width = if excess > 0 {
548 excess -= 1;
549 (average_space + 1).try_into().unwrap_or(u16::MAX)
550 } else {
551 average_space.try_into().unwrap_or(u16::MAX)
552 };
553
554 let info = ColumnDisplayInfo::new(column, width);
555 infos.insert(column.index, info);
556 }
557 }