ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
options/layout.c
Go to the documentation of this file.
1
8
9/* Storage capacities in elements; text buffers include the terminating NUL. */
10#define OPTIONS_LAYOUT_BUF_BUFFER_SIZE 256
11
12#include <ascii-chat/common.h>
13#include <ascii-chat/log/log.h>
17#include <stdio.h>
18#include <string.h>
19
20/* ============================================================================
21 * Colored Segment Printing
22 * ============================================================================
23 */
24
32static void layout_print_colored_segment(FILE *stream, const char *seg) {
33 if (!seg || !stream)
34 return;
35
36 // Just print the text as-is. All coloring is done in builder.c using
37 // colored_string() before passing to layout functions. Layout functions only
38 // handle positioning and wrapping.
39 fprintf(stream, "%s", seg);
40}
41
43static void layout_copy_segment(char *dst, size_t dst_size, const char *src,
44 size_t length) {
45 if (!dst || dst_size == 0)
46 return;
47
48 size_t copy_len = length < dst_size - 1 ? length : dst_size - 1;
49 if (src && copy_len > 0)
50 memcpy(dst, src, copy_len);
51 dst[copy_len] = '\0';
52}
53
54/* ============================================================================
55 * Wrapped Description Printing
56 * ============================================================================
57 */
58
65static int calculate_segment_display_width(const char *text, int len) {
66 if (!text || len <= 0)
67 return 0;
68
69 // Create a stripped version for width calculation
70 char *stripped = ansi_strip_escapes(text, len);
71 if (!stripped)
72 return 0;
73
74 // Calculate display width of stripped text
75 int width = utf8_display_width_n(stripped, strlen(stripped));
76 SAFE_FREE(stripped);
77
78 return width < 0 ? 0 : width;
79}
80
87static bool is_metadata_start(const char *p) {
88 if (!p || *p != '(')
89 return false;
90
91 // Strip ANSI codes to check the actual text
93 const char *src = p;
94 char *dst = buf;
95 int remaining = sizeof(buf) - 1;
96
97 // Copy up to 20 chars, stripping ANSI codes
98 int count = 0;
99 while (*src && count < 20 && remaining > 0) {
100 if (*src == '\x1b') {
101 // Skip ANSI escape sequence
102 src++;
103 while (*src && *src != 'm')
104 src++;
105 if (*src == 'm')
106 src++;
107 } else {
108 *dst++ = *src++;
109 remaining--;
110 count++;
111 }
112 }
113 *dst = '\0';
114
115 return strncmp(buf, "(default:", 9) == 0 || strncmp(buf, "(env:", 5) == 0;
116}
117
118void layout_print_wrapped_description(FILE *stream, const char *text,
119 int indent_width, int term_width,
120 int continuation_indent_extra) {
121 if (!text || !stream)
122 return;
123
124 // Default terminal width if not specified
125 if (term_width <= 0)
126 term_width = 80;
127
128 // Available width for text after indentation, capped at 130 for readability
129 // Account for continuation lines having extra indent, so reduce available
130 // width accordingly This allows the description column itself to be up to 130
131 // chars wide, starting from indent_width, for a max total line of
132 // indent_width + 130 (first line) or indent_width + continuation_indent_extra
133 // + 130 (continuation lines)
134 int available_width = term_width - indent_width - continuation_indent_extra;
135 if (available_width > 130)
136 available_width = 130;
137 if (available_width < 20)
138 available_width = 20;
139
140 const char *line_start = text;
141 const char *last_space = NULL;
142 const char *p = text;
143 bool inside_metadata = false;
144
145 while (*p) {
146 // Check for explicit newline
147 if (*p == '\n') {
148 // Print everything up to the newline
149 int text_len = (int)(p - line_start);
150 if (text_len > 0) {
151 char seg[BUFFER_SIZE_MEDIUM];
152 layout_copy_segment(seg, sizeof(seg), line_start, (size_t)text_len);
153 layout_print_colored_segment(stream, seg);
154 }
155
156 fprintf(stream, "\n");
157 if (*(p + 1)) {
158 // Continuation lines get extra indent if specified
159 int continuation_indent = indent_width + continuation_indent_extra;
160 for (int i = 0; i < continuation_indent; i++)
161 fprintf(stream, " ");
162 }
163 p++;
164 line_start = p;
165 last_space = NULL;
166 inside_metadata = false;
167 continue;
168 }
169
170 // Check for start of metadata blocks (must check before space tracking)
171 // Use helper that accounts for ANSI codes in the metadata
172 if (!inside_metadata && is_metadata_start(p)) {
173 inside_metadata = true;
174 }
175
176 // Check for end of metadata blocks - always exit on )
177 // We'll re-enter when we see the next metadata marker
178 if (inside_metadata && *p == ')') {
179 inside_metadata = false;
180 }
181
182 // Track spaces for word wrapping, including inside metadata blocks
183 // Prefer breaks before metadata blocks by updating last_space even if we
184 // already have one
185 if (*p == ' ') {
186 const char *next = p + 1;
187 while (*next == ' ')
188 next++;
189 // Track space as break point if it's before metadata or a normal space
190 // (not before parenthetical)
191 if (is_metadata_start(next) || !last_space || *next != '(') {
192 last_space = p;
193 }
194 }
195
196 // Decode UTF-8 character length
197 int char_bytes = utf8_next_char_bytes(p, strlen(p));
198
199 if (char_bytes <= 0) {
200 // Invalid UTF-8 or end of string, stop
201 break;
202 }
203
204 // Advance to next character first
205 p += char_bytes;
206
207 // Calculate actual display width from line_start to current position
208 // (excluding ANSI codes)
209 int actual_width =
210 calculate_segment_display_width(line_start, (int)(p - line_start));
211
212 // Check if we need to wrap
213 if (actual_width >= available_width && last_space &&
214 last_space > line_start) {
215 // Print text up to break point with colors applied
216 int text_len = (int)(last_space - line_start);
217 char seg[BUFFER_SIZE_MEDIUM];
218 layout_copy_segment(seg, sizeof(seg), line_start, (size_t)text_len);
219 layout_print_colored_segment(stream, seg);
220
221 fprintf(stream, "\n");
222 // Continuation lines get extra indent if specified
223 int continuation_indent = indent_width + continuation_indent_extra;
224 for (int i = 0; i < continuation_indent; i++)
225 fprintf(stream, " ");
226
227 p = last_space + 1;
228 line_start = p;
229 last_space = NULL;
230 continue;
231 }
232 }
233
234 // Print remaining text
235 if (p > line_start) {
236 char seg[BUFFER_SIZE_MEDIUM];
237 int text_len = (int)(p - line_start);
238 layout_copy_segment(seg, sizeof(seg), line_start, (size_t)text_len);
239 layout_print_colored_segment(stream, seg);
240 }
241}
242
243/* ============================================================================
244 * Two-Column Row Printing
245 * ============================================================================
246 */
247
248void layout_print_two_column_row(FILE *stream, const char *first_column,
249 const char *second_column, int first_col_len,
250 int term_width,
251 int continuation_indent_extra) {
252 if (!stream || !first_column || !second_column)
253 return;
254
255 // Strip ANSI escape codes before calculating display width
256 char *stripped = ansi_strip_escapes(first_column, strlen(first_column));
257
258 // Calculate actual display width of first column (accounts for UTF-8,
259 // excluding ANSI codes)
260 int display_width = utf8_display_width(stripped ? stripped : first_column);
261 if (display_width < 0)
262 display_width = first_col_len; // Fallback to provided value if available
263
264 SAFE_FREE(stripped);
265
266 // Use calculated first_col_len if provided (accounts for UTF-8 and ANSI
267 // codes), otherwise default to 35. The provided width respects both colored
268 // text and UTF-8 characters. Allow the first column to expand up to 60% of
269 // terminal width, but leave room for description.
270 int fixed_first_col_width = (first_col_len > 0) ? first_col_len : 35;
271 // Keep enough room for a useful description column. Letting the first
272 // column grow to 60% of a narrow terminal makes descriptions wrap one word
273 // at a time and stretches help vertically. Long option names are handled
274 // by the existing next-line fallback below.
275 const int minimum_description_width = 45;
276 int max_first_col_width = term_width - 2 - 2 - minimum_description_width;
277 if (max_first_col_width < 20)
278 max_first_col_width = 20;
279 if (fixed_first_col_width > max_first_col_width) {
280 fixed_first_col_width = max_first_col_width;
281 }
282
283 // Second column starts after first column (with 2 spaces padding)
284 // This allows descriptions to be quite wide for wrapping
285 int second_col_start = 2 + fixed_first_col_width + 2;
286
287 // At narrow terminal widths, force single-column layout
288 bool force_single_column = (term_width <= 90);
289
290 // Position where first column ends (including leading spaces)
291 int first_col_end = 2 + display_width;
292
293 // Check if first column fits within the fixed width
294 bool fits_in_first_column_width = (display_width <= fixed_first_col_width);
295
296 // If first column fits within its width and we're not forcing single column,
297 // try same-line layout
298 if (fits_in_first_column_width && !force_single_column) {
299 // Print first column
300 fprintf(stream, " %s", first_column);
301
302 // Pad to second column start position
303 int padding = second_col_start - first_col_end;
304 if (padding > 0) {
305 fprintf(stream, "%*s", padding, "");
306 } else {
307 fprintf(stream, " ");
308 }
309
310 // Print description with wrapping at second column position
311 layout_print_wrapped_description(stream, second_column, second_col_start,
312 term_width, continuation_indent_extra);
313 fprintf(stream, "\n");
314 } else if (force_single_column) {
315 // Terminal too narrow, put description on next line with indent
316 fprintf(stream, " %s\n", first_column);
317
318 // Only print description if it exists
319 if (second_column && second_column[0] != '\0') {
320 int description_indent = 4;
321 for (int i = 0; i < description_indent; i++)
322 fprintf(stream, " ");
323
324 layout_print_wrapped_description(stream, second_column,
325 description_indent, term_width,
326 continuation_indent_extra);
327 fprintf(stream, "\n");
328 }
329 } else {
330 // First column overflows its fixed width - bump description to next line
331 // Print first column as-is (it will overflow)
332 fprintf(stream, " %s\n", first_column);
333
334 // Only print description if it exists
335 if (second_column && second_column[0] != '\0') {
336 // Print description on next line at second column position, with wide
337 // wrapping
338 for (int i = 0; i < second_col_start; i++)
339 fprintf(stream, " ");
340 layout_print_wrapped_description(stream, second_column, second_col_start,
341 term_width, continuation_indent_extra);
342 fprintf(stream, "\n");
343 }
344 }
345}
ANSI escape sequence utilities and fast color code generation.
unsigned int width
Definition fft.c:24
char * ansi_strip_escapes(const char *input, size_t input_len)
When code needs to work with rgb error, it keeps r, g, b here instead of scattering it across globals...
Definition ansi.c:27
#define BUFFER_SIZE_MEDIUM
Medium buffer size (512 bytes).
#define SAFE_FREE(ptr)
int utf8_display_width_n(const char *str, size_t max_bytes)
Calculate terminal display width of a UTF-8 string up to byte limit.
Definition utf8.c:106
int display_width(const char *text)
Calculate the visible display width of text with ANSI escape codes.
int utf8_display_width(const char *str)
Calculate terminal display width of a UTF-8 string.
Definition utf8.c:102
int utf8_next_char_bytes(const char *str, size_t max_bytes)
Get byte length of next UTF-8 character.
Definition utf8.c:183
⚙️ Common definitions, error codes, macros, and types shared throughout the application
📝 Logging API with multiple log levels and terminal output control
#define OPTIONS_LAYOUT_BUF_BUFFER_SIZE
void layout_print_two_column_row(FILE *stream, const char *first_column, const char *second_column, int first_col_len, int term_width, int continuation_indent_extra)
Print two-column row with automatic wrapping.
void layout_print_wrapped_description(FILE *stream, const char *text, int indent_width, int term_width, int continuation_indent_extra)
Print text with wrapping and proper indentation.
Two-column layout helpers for help text and option formatting.
🔤 String Manipulation and Shell Escaping Utilities
🔤 UTF-8 Encoding and Decoding Utilities