Skip to content

file_contents: Handle utf-8 characters #411

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions include/i3status.h
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ extern char *pct_mark;

#define BEGINS_WITH(haystack, needle) (strncmp(haystack, needle, strlen(needle)) == 0)
#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(x, y) ((x) < (y) ? (x) : (y))

#define DEFAULT_SINK_INDEX UINT32_MAX
#define COMPOSE_VOLUME_MUTE(vol, mute) ((vol) | ((mute) ? (1 << 30) : 0))
Expand Down
35 changes: 30 additions & 5 deletions src/print_file_contents.c
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,44 @@ static void *scalloc(size_t size) {

void print_file_contents(yajl_gen json_gen, char *buffer, const char *title, const char *path, const char *format, const char *format_bad, const int max_chars) {
const char *walk = format;
/* Each utf-8 character is a maximum of 4 bytes */
const int max_bytes = 4 * max_chars;
char *outwalk = buffer;
char *buf = scalloc(max_chars * sizeof(char) + 1);
char *buf = scalloc(max_bytes * sizeof(char) + 1);

int n = -1;
int fd = open(path, O_RDONLY);

INSTANCE(path);

if (fd > -1) {
n = read(fd, buf, max_chars);
if (n != -1) {
buf[n] = '\0';
read(fd, buf, max_bytes);

int i = 0;
int actual_chars = 0;
while (i < max_bytes) {
const unsigned char c = buf[i];

if (c == 0) {
break;
}
/* Count utf-8 characters, by only inspecting the first byte,
* skipping the rest. For reference see:
* https://tools.ietf.org/html/rfc3629#page-4 */
if (c < 128 /* 0xxxxxxx */) {
i++;
} else if (c < 0xe0 /* 110xxxxx */) {
i += 2;
} else if (c < 0xf0 /* 1110xxxx */) {
i += 3;
} else if (c < 0xf5 /* 11110xxx */) {
i += 4;
}
if (++actual_chars >= max_chars) {
buf[min(i, max_bytes)] = '\0';
break;
}
}

(void)close(fd);
START_COLOR("color_good");
} else if (errno != 0) {
Expand Down