MiniDevil As beautiful as a shell
drawing_text.c
Go to the documentation of this file.
1 /* ************************************************************************** */
2 /* */
3 /* ::: :::::::: */
4 /* drawing_text.c :+: :+: :+: */
5 /* +:+ +:+ +:+ */
6 /* By: baelgadi <baelgadi@student.42.fr> +#+ +:+ +#+ */
7 /* +#+#+#+#+#+ +#+ */
8 /* Created: 2026/02/17 17:49:05 by zotaj-di #+# #+# */
9 /* Updated: 2026/03/04 03:31:20 by baelgadi ### ########.fr */
10 /* */
11 /* ************************************************************************** */
12 
13 #include "minishell_ui.h"
14 
21 static int utf8_byte_len(unsigned char c)
22 {
23  if (c >= 0xF0)
24  return (4);
25  if (c >= 0xE0)
26  return (3);
27  if (c >= 0xC0)
28  return (2);
29  return (1);
30 }
31 
42 char *truncate_line(const char *line, int max_width)
43 {
44  static char buf[BUF_SIZE];
45  int i;
46  int visual_w;
47  int char_len;
48 
49  if (!line)
50  return ("");
51  ft_memset(buf, 0, sizeof(buf));
52  i = 0;
53  visual_w = 0;
54  while (line[i] && visual_w < max_width)
55  {
56  char_len = utf8_byte_len((unsigned char)line[i]);
57  if (i + char_len > BUF_SIZE - 1)
58  break ;
59  ft_memcpy(buf + i, line + i, char_len);
60  i += char_len;
61  visual_w++;
62  }
63  buf[i] = '\0';
64  return (buf);
65 }
66 
75 int visual_strlen(const char *s)
76 {
77  int len;
78 
79  len = 0;
80  while (*s)
81  {
82  if ((unsigned char)*s >= 0xF0)
83  len += 2;
84  else
85  len++;
86  s += utf8_byte_len((unsigned char)*s);
87  }
88  return (len);
89 }
static int utf8_byte_len(unsigned char c)
Return the length in bytes of an UTF-8 character.
Definition: drawing_text.c:21
char * truncate_line(const char *line, int max_width)
Copy up to max_width visible characters into a static buffer.
Definition: drawing_text.c:42
int visual_strlen(const char *s)
Calculate the visual display width of a UTF-8 string in terminal cols.
Definition: drawing_text.c:75
UI mode structures, macros & function prototypes.
#define BUF_SIZE
Definition: minishell_ui.h:86