Skip to content
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
22 changes: 22 additions & 0 deletions src/util/files.c
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,28 @@ char *path_for_fd(int fd) {
return realpath(fdpath, NULL);
}

int infer_is_text_plain_utf8(const char *file_path) {
/* Infer if the file is valid UTF-8 text */
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return 0;
}
if (pid == 0) {
int devnull = open("/dev/null", O_WRONLY);
dup2(devnull, STDOUT_FILENO);
dup2(devnull, STDERR_FILENO);
execlp("iconv", "iconv", "-f", "utf-8", "-t", "utf-8", file_path, NULL);
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can potentially switch this to use iconv(3) instead or some other UTF-8 validity check.

exit(1);
}

int wstatus;
wait(&wstatus);

/* A successful conversion will return zero */
return WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0;
}

char *infer_mime_type_from_contents(const char *file_path) {
/* Spawn xdg-mime query filetype */
int pipefd[2];
Expand Down
1 change: 1 addition & 0 deletions src/util/files.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
#define UTIL_FILES_H

int create_anonymous_file(void);
int infer_is_text_plain_utf8(const char *file_path);

void trim_trailing_newline(const char *file_path);

Expand Down
3 changes: 2 additions & 1 deletion src/wl-copy.c
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,8 @@ int main(int argc, argv_t argv) {
if (options.mime_type != NULL) {
source_offer(copy_action->source, options.mime_type);
}
if (options.mime_type == NULL || mime_type_is_text(options.mime_type)) {
if (options.mime_type == NULL || mime_type_is_text(options.mime_type)
|| infer_is_text_plain_utf8(copy_action->file_to_copy)) {
/* Offer a few generic plain text formats */
source_offer(copy_action->source, text_plain);
source_offer(copy_action->source, text_plain_utf8);
Expand Down