4 * i3 - an improved dynamic tiling window manager
6 * © 2009 Michael Stapelberg and contributors
8 * See file LICENSE for license information.
17 static iconv_t conversion_descriptor = 0;
18 static iconv_t conversion_descriptor2 = 0;
21 * Returns the input string, but converted from UCS-2 to UTF-8. Memory will be
22 * allocated, thus the caller has to free the output.
25 char *convert_ucs_to_utf8(char *input) {
26 size_t input_size = 2;
27 /* UTF-8 may consume up to 4 byte */
30 char *buffer = calloc(buffer_size, 1);
32 err(EXIT_FAILURE, "malloc() failed\n");
33 size_t output_size = buffer_size;
34 /* We need to use an additional pointer, because iconv() modifies it */
35 char *output = buffer;
37 /* We convert the input into UCS-2 big endian */
38 if (conversion_descriptor == 0) {
39 conversion_descriptor = iconv_open("UTF-8", "UCS-2BE");
40 if (conversion_descriptor == 0) {
41 fprintf(stderr, "error opening the conversion context\n");
46 /* Get the conversion descriptor back to original state */
47 iconv(conversion_descriptor, NULL, NULL, NULL, NULL);
49 /* Convert our text */
50 int rc = iconv(conversion_descriptor, (void*)&input, &input_size, &output, &output_size);
51 if (rc == (size_t)-1) {
52 perror("Converting to UCS-2 failed");
60 * Converts the given string to UCS-2 big endian for use with
61 * xcb_image_text_16(). The amount of real glyphs is stored in real_strlen,
62 * a buffer containing the UCS-2 encoded string (16 bit per glyph) is
63 * returned. It has to be freed when done.
66 char *convert_utf8_to_ucs2(char *input, int *real_strlen) {
67 size_t input_size = strlen(input) + 1;
68 /* UCS-2 consumes exactly two bytes for each glyph */
69 int buffer_size = input_size * 2;
71 char *buffer = malloc(buffer_size);
73 err(EXIT_FAILURE, "malloc() failed\n");
74 size_t output_size = buffer_size;
75 /* We need to use an additional pointer, because iconv() modifies it */
76 char *output = buffer;
78 /* We convert the input into UCS-2 big endian */
79 if (conversion_descriptor2 == 0) {
80 conversion_descriptor2 = iconv_open("UCS-2BE", "UTF-8");
81 if (conversion_descriptor2 == 0) {
82 fprintf(stderr, "error opening the conversion context\n");
87 /* Get the conversion descriptor back to original state */
88 iconv(conversion_descriptor2, NULL, NULL, NULL, NULL);
90 /* Convert our text */
91 int rc = iconv(conversion_descriptor2, (void*)&input, &input_size, &output, &output_size);
92 if (rc == (size_t)-1) {
93 perror("Converting to UCS-2 failed");
94 if (real_strlen != NULL)
99 if (real_strlen != NULL)
100 *real_strlen = ((buffer_size - output_size) / 2) - 1;