1 /****************************************************************************
2  * Copyright (c) 2005-2010,2012 Free Software Foundation, Inc.              *
3  *                                                                          *
4  * Permission is hereby granted, free of charge, to any person obtaining a  *
5  * copy of this software and associated documentation files (the            *
6  * "Software"), to deal in the Software without restriction, including      *
7  * without limitation the rights to use, copy, modify, merge, publish,      *
8  * distribute, distribute with modifications, sublicense, and/or sell       *
9  * copies of the Software, and to permit persons to whom the Software is    *
10  * furnished to do so, subject to the following conditions:                 *
11  *                                                                          *
12  * The above copyright notice and this permission notice shall be included  *
13  * in all copies or substantial portions of the Software.                   *
14  *                                                                          *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
16  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
17  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
18  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
19  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
20  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
21  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
22  *                                                                          *
23  * Except as contained in this notice, the name(s) of the above copyright   *
24  * holders shall not be used in advertising or otherwise to promote the     *
25  * sale, use or other dealings in this Software without prior written       *
26  * authorization.                                                           *
27  ****************************************************************************/
28 
29 /****************************************************************************
30  *  Author: Thomas Dickey                                                   *
31  ****************************************************************************/
32 
33 #include <curses.priv.h>
34 
35 #include <ctype.h>
36 
37 #include <tic.h>
38 
39 MODULE_ID("$Id: trim_sgr0.c,v 1.15 2012/12/15 20:57:17 tom Exp $")
40 
41 #undef CUR
42 #define CUR tp->
43 
44 #define CSI       233
45 #define ESC       033		/* ^[ */
46 #define L_BRACK   '['
47 
48 static char *
49 set_attribute_9(TERMTYPE *tp, int flag)
50 {
51     const char *value;
52     char *result;
53 
54     value = tparm(set_attributes, 0, 0, 0, 0, 0, 0, 0, 0, flag);
55     if (PRESENT(value))
56 	result = strdup(value);
57     else
58 	result = 0;
59     return result;
60 }
61 
62 static int
63 is_csi(const char *s)
64 {
65     int result = 0;
66     if (s != 0) {
67 	if (UChar(s[0]) == CSI)
68 	    result = 1;
69 	else if (s[0] == ESC && s[1] == L_BRACK)
70 	    result = 2;
71     }
72     return result;
73 }
74 
75 static char *
76 skip_zero(char *s)
77 {
78     if (s[0] == '0') {
79 	if (s[1] == ';')
80 	    s += 2;
81 	else if (isalpha(UChar(s[1])))
82 	    s += 1;
83     }
84     return s;
85 }
86 
87 static const char *
88 skip_delay(const char *s)
89 {
90     if (s[0] == '$' && s[1] == '<') {
91 	s += 2;
92 	while (isdigit(UChar(*s)) || *s == '/')
93 	    ++s;
94 	if (*s == '>')
95 	    ++s;
96     }
97     return s;
98 }
99 
100 /*
101  * Improve similar_sgr a little by moving the attr-string from the beginning
102  * to the end of the s-string.
103  */
104 static bool
105 rewrite_sgr(char *s, char *attr)
106 {
107     if (s != 0) {
108 	if (PRESENT(attr)) {
109 	    size_t len_s = strlen(s);
110 	    size_t len_a = strlen(attr);
111 
112 	    if (len_s > len_a && !strncmp(attr, s, len_a)) {
113 		unsigned n;
114 		TR(TRACE_DATABASE, ("rewrite:\n\t%s", s));
115 		for (n = 0; n < len_s - len_a; ++n) {
116 		    s[n] = s[n + len_a];
117 		}
118 		_nc_STRCPY(s + n, attr, strlen(s) + 1);
119 		TR(TRACE_DATABASE, ("to:\n\t%s", s));
120 	    }
121 	}
122 	return TRUE;
123     }
124     return FALSE;		/* oops */
125 }
126 
127 static bool
128 similar_sgr(char *a, char *b)
129 {
130     bool result = FALSE;
131     if (a != 0 && b != 0) {
132 	int csi_a = is_csi(a);
133 	int csi_b = is_csi(b);
134 	size_t len_a;
135 	size_t len_b;
136 
137 	TR(TRACE_DATABASE, ("similar_sgr:\n\t%s\n\t%s",
138 			    _nc_visbuf2(1, a),
139 			    _nc_visbuf2(2, b)));
140 	if (csi_a != 0 && csi_b != 0 && csi_a == csi_b) {
141 	    a += csi_a;
142 	    b += csi_b;
143 	    if (*a != *b) {
144 		a = skip_zero(a);
145 		b = skip_zero(b);
146 	    }
147 	}
148 	len_a = strlen(a);
149 	len_b = strlen(b);
150 	if (len_a && len_b) {
151 	    if (len_a > len_b)
152 		result = (strncmp(a, b, len_b) == 0);
153 	    else
154 		result = (strncmp(a, b, len_a) == 0);
155 	}
156 	TR(TRACE_DATABASE, ("...similar_sgr: %d\n\t%s\n\t%s", result,
157 			    _nc_visbuf2(1, a),
158 			    _nc_visbuf2(2, b)));
159     }
160     return result;
161 }
162 
163 static unsigned
164 chop_out(char *string, unsigned i, unsigned j)
165 {
166     TR(TRACE_DATABASE, ("chop_out %d..%d from %s", i, j, _nc_visbuf(string)));
167     while (string[j] != '\0') {
168 	string[i++] = string[j++];
169     }
170     string[i] = '\0';
171     return i;
172 }
173 
174 /*
175  * Compare, ignoring delays.  Some of the delay values are inconsistent, and
176  * we do not want to be stopped by that.
177  *
178  * Returns the number of chars from 'full' that we matched.  If any mismatch
179  * occurs, return zero.
180  */
181 static unsigned
182 compare_part(const char *part, const char *full)
183 {
184     const char *next_part;
185     const char *next_full;
186     unsigned used_full = 0;
187     unsigned used_delay = 0;
188 
189     while (*part != 0) {
190 	if (*part != *full) {
191 	    used_full = 0;
192 	    break;
193 	}
194 
195 	/*
196 	 * Adjust the return-value to allow the rare case of
197 	 *      string<delay>string
198 	 * to remove the whole piece.  The most common case is a delay at the
199 	 * end of the string.  The adjusted string will retain the delay, which
200 	 * is conservative.
201 	 */
202 	if (used_delay != 0) {
203 	    used_full += used_delay;
204 	    used_delay = 0;
205 	}
206 	if (*part == '$' && *full == '$') {
207 	    next_part = skip_delay(part);
208 	    next_full = skip_delay(full);
209 	    if (next_part != part && next_full != full) {
210 		used_delay += (unsigned) (next_full - full);
211 		full = next_full;
212 		part = next_part;
213 		continue;
214 	    }
215 	}
216 	++used_full;
217 	++part;
218 	++full;
219     }
220     return used_full;
221 }
222 
223 /*
224  * While 'sgr0' is the "same" as termcap 'me', there is a compatibility issue.
225  * The sgr/sgr0 capabilities include setting/clearing alternate character set
226  * mode.  A termcap application cannot use sgr, so sgr0 strings that reset
227  * alternate character set mode will be misinterpreted.  Here, we remove those
228  * from the more common ISO/ANSI/VT100 entries, which have sgr0 agreeing with
229  * sgr.
230  *
231  * This function returns the modified sgr0 if it can be modified, a null if
232  * an error occurs, or the original sgr0 if no change is needed.
233  */
234 NCURSES_EXPORT(char *)
235 _nc_trim_sgr0(TERMTYPE *tp)
236 {
237     char *result = exit_attribute_mode;
238 
239     T((T_CALLED("_nc_trim_sgr0()")));
240 
241     if (PRESENT(exit_attribute_mode)
242 	&& PRESENT(set_attributes)) {
243 	bool found = FALSE;
244 	char *on = set_attribute_9(tp, 1);
245 	char *off = set_attribute_9(tp, 0);
246 	char *end = strdup(exit_attribute_mode);
247 	char *tmp;
248 	size_t i, j, k;
249 
250 	TR(TRACE_DATABASE, ("checking if we can trim sgr0 based on sgr"));
251 	TR(TRACE_DATABASE, ("sgr0       %s", _nc_visbuf(end)));
252 	TR(TRACE_DATABASE, ("sgr(9:off) %s", _nc_visbuf(off)));
253 	TR(TRACE_DATABASE, ("sgr(9:on)  %s", _nc_visbuf(on)));
254 
255 	if (!rewrite_sgr(on, enter_alt_charset_mode)
256 	    || !rewrite_sgr(off, exit_alt_charset_mode)
257 	    || !rewrite_sgr(end, exit_alt_charset_mode)) {
258 	    FreeIfNeeded(off);
259 	} else if (similar_sgr(off, end)
260 		   && !similar_sgr(off, on)) {
261 	    TR(TRACE_DATABASE, ("adjusting sgr(9:off) : %s", _nc_visbuf(off)));
262 	    result = off;
263 	    /*
264 	     * If rmacs is a substring of sgr(0), remove that chunk.
265 	     */
266 	    if (exit_alt_charset_mode != 0) {
267 		TR(TRACE_DATABASE, ("scan for rmacs %s", _nc_visbuf(exit_alt_charset_mode)));
268 		j = strlen(off);
269 		k = strlen(exit_alt_charset_mode);
270 		if (j > k) {
271 		    for (i = 0; i <= (j - k); ++i) {
272 			unsigned k2 = compare_part(exit_alt_charset_mode,
273 						   off + i);
274 			if (k2 != 0) {
275 			    found = TRUE;
276 			    chop_out(off, (unsigned) i, (unsigned) (i + k2));
277 			    break;
278 			}
279 		    }
280 		}
281 	    }
282 	    /*
283 	     * SGR 10 would reset to normal font.
284 	     */
285 	    if (!found) {
286 		if ((i = (size_t) is_csi(off)) != 0
287 		    && off[strlen(off) - 1] == 'm') {
288 		    TR(TRACE_DATABASE, ("looking for SGR 10 in %s",
289 					_nc_visbuf(off)));
290 		    tmp = skip_zero(off + i);
291 		    if (tmp[0] == '1'
292 			&& skip_zero(tmp + 1) != tmp + 1) {
293 			i = (size_t) (tmp - off);
294 			if (off[i - 1] == ';')
295 			    i--;
296 			j = (size_t) (skip_zero(tmp + 1) - off);
297 			(void) chop_out(off, (unsigned) i, (unsigned) j);
298 			found = TRUE;
299 		    }
300 		}
301 	    }
302 	    if (!found
303 		&& (tmp = strstr(end, off)) != 0
304 		&& strcmp(end, off) != 0) {
305 		i = (size_t) (tmp - end);
306 		j = strlen(off);
307 		tmp = strdup(end);
308 		chop_out(tmp, (unsigned) i, (unsigned) j);
309 		free(off);
310 		result = tmp;
311 	    }
312 	    TR(TRACE_DATABASE, ("...adjusted sgr0 : %s", _nc_visbuf(result)));
313 	    if (!strcmp(result, exit_attribute_mode)) {
314 		TR(TRACE_DATABASE, ("...same result, discard"));
315 		free(result);
316 		result = exit_attribute_mode;
317 	    }
318 	} else {
319 	    /*
320 	     * Either the sgr does not reference alternate character set,
321 	     * or it is incorrect.  That's too hard to decide right now.
322 	     */
323 	    free(off);
324 	}
325 	FreeIfNeeded(end);
326 	FreeIfNeeded(on);
327     } else {
328 	/*
329 	 * Possibly some applications are confused if sgr0 contains rmacs,
330 	 * but that would be a different bug report -TD
331 	 */
332     }
333 
334     returnPtr(result);
335 }
336