2 * libdpkg - Debian packaging suite library routines
3 * strwide.c - wide character string handling routines
5 * Copyright © 2004 Changwoo Ryu <cwryu@debian.org>
6 * Copyright © 2012-2013 Guillem Jover <guillem@debian.org>
8 * This is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
31 #include <dpkg/i18n.h>
32 #include <dpkg/dpkg.h>
33 #include <dpkg/string.h>
36 * Compute the screen width of a string.
38 * @param str The multibyte string.
40 * @return The width of the string.
43 str_width(const char *str)
48 const char *mbs = str;
52 len = strlen(str) + 1;
53 wcs = m_malloc(sizeof(wcs[0]) * len);
55 memset(&state, 0, sizeof(state));
57 res = mbsrtowcs(wcs, &mbs, len, &state);
58 if (res == (size_t)-1) {
59 #ifdef DPKG_UNIFORM_ENCODING
60 ohshit(_("cannot convert multibyte string '%s' "
61 "to a wide-character string"), str);
63 /* Cannot convert, fallback to ASCII method. */
69 width = wcswidth(wcs, res);
80 * Generate the crop values for a string given a maximum screen width.
82 * This function analyzes the string passed and computes the correct point
83 * where to crop the string, returning the amount of string and maximum
84 * bytes to use for padding for example.
86 * On NLS enabled builds, in addition the string will be cropped on any
89 * @param str The string to crop.
90 * @param max_width The max screen width to use.
91 * @param[out] crop The generated crop values for the string.
94 str_gen_crop(const char *str, int max_width, struct str_crop_info *crop)
102 str_bytes = strlen(str) + 1;
103 memset(&state, 0, sizeof(state));
110 mb_bytes = mbrtowc(&wc, str, str_bytes, &state);
111 if (mb_bytes == (size_t)-1 || mb_bytes == (size_t)-2) {
112 #ifdef DPKG_UNIFORM_ENCODING
113 ohshit(_("cannot convert multibyte sequence '%s' "
114 "to a wide character"), str);
116 /* Cannot convert, fallback to ASCII method. */
117 crop->str_bytes = crop->max_bytes = max_width;
124 wc_width = wcwidth(wc);
127 if (mbs_width + wc_width > max_width)
130 mbs_width += wc_width;
131 mbs_bytes += mb_bytes;
132 str_bytes -= mb_bytes;
136 crop->str_bytes = mbs_bytes;
137 crop->max_bytes = mbs_bytes + max_width - mbs_width;
139 crop->str_bytes = crop->max_bytes = max_width;