1/****************************************************************************
2 * Copyright (c) 2005-2006,2007 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#include <term_entry.h>
39
40MODULE_ID("$Id: trim_sgr0.c,v 1.8 2007/04/07 17:14:11 tom Exp $")
41
42#undef CUR
43#define CUR tp->
44
45#define CSI       233
46#define ESC       033		/* ^[ */
47#define L_BRACK   '['
48
49static char *
50set_attribute_9(TERMTYPE *tp, int flag)
51{
52    const char *result;
53
54    if ((result = tparm(set_attributes, 0, 0, 0, 0, 0, 0, 0, 0, flag)) == 0)
55	result = "";
56    return strdup(result);
57}
58
59static int
60is_csi(const char *s)
61{
62    if (UChar(s[0]) == CSI)
63	return 1;
64    else if (s[0] == ESC && s[1] == L_BRACK)
65	return 2;
66    return 0;
67}
68
69static char *
70skip_zero(char *s)
71{
72    if (s[0] == '0') {
73	if (s[1] == ';')
74	    s += 2;
75	else if (isalpha(UChar(s[1])))
76	    s += 1;
77    }
78    return s;
79}
80
81static const char *
82skip_delay(const char *s)
83{
84    if (s[0] == '$' && s[1] == '<') {
85	s += 2;
86	while (isdigit(UChar(*s)) || *s == '/')
87	    ++s;
88	if (*s == '>')
89	    ++s;
90    }
91    return s;
92}
93
94/*
95 * Improve similar_sgr a little by moving the attr-string from the beginning
96 * to the end of the s-string.
97 */
98static bool
99rewrite_sgr(char *s, char *attr)
100{
101    if (PRESENT(s)) {
102	if (PRESENT(attr)) {
103	    unsigned len_s = strlen(s);
104	    unsigned len_a = strlen(attr);
105
106	    if (len_s > len_a && !strncmp(attr, s, len_a)) {
107		unsigned n;
108		TR(TRACE_DATABASE, ("rewrite:\n\t%s", s));
109		for (n = 0; n < len_s - len_a; ++n) {
110		    s[n] = s[n + len_a];
111		}
112		strcpy(s + n, attr);
113		TR(TRACE_DATABASE, ("to:\n\t%s", s));
114	    }
115	}
116	return TRUE;
117    }
118    return FALSE;		/* oops */
119}
120
121static bool
122similar_sgr(char *a, char *b)
123{
124    bool result = FALSE;
125    int csi_a = is_csi(a);
126    int csi_b = is_csi(b);
127    unsigned len_a;
128    unsigned len_b;
129
130    TR(TRACE_DATABASE, ("similar_sgr:\n\t%s\n\t%s",
131			_nc_visbuf2(1, a),
132			_nc_visbuf2(2, b)));
133    if (csi_a != 0 && csi_b != 0 && csi_a == csi_b) {
134	a += csi_a;
135	b += csi_b;
136	if (*a != *b) {
137	    a = skip_zero(a);
138	    b = skip_zero(b);
139	}
140    }
141    len_a = strlen(a);
142    len_b = strlen(b);
143    if (len_a && len_b) {
144	if (len_a > len_b)
145	    result = (strncmp(a, b, len_b) == 0);
146	else
147	    result = (strncmp(a, b, len_a) == 0);
148    }
149    TR(TRACE_DATABASE, ("...similar_sgr: %d\n\t%s\n\t%s", result,
150			_nc_visbuf2(1, a),
151			_nc_visbuf2(2, b)));
152    return result;
153}
154
155static unsigned
156chop_out(char *string, unsigned i, unsigned j)
157{
158    TR(TRACE_DATABASE, ("chop_out %d..%d from %s", i, j, _nc_visbuf(string)));
159    while (string[j] != '\0') {
160	string[i++] = string[j++];
161    }
162    string[i] = '\0';
163    return i;
164}
165
166/*
167 * Compare, ignoring delays.  Some of the delay values are inconsistent, and
168 * we do not want to be stopped by that.
169 *
170 * Returns the number of chars from 'full' that we matched.  If any mismatch
171 * occurs, return zero.
172 */
173static int
174compare_part(const char *part, const char *full)
175{
176    const char *next_part;
177    const char *next_full;
178    int used_full = 0;
179    int used_delay = 0;
180
181    while (*part != 0) {
182	if (*part != *full) {
183	    used_full = 0;
184	    break;
185	}
186
187	/*
188	 * Adjust the return-value to allow the rare case of
189	 *      string<delay>string
190	 * to remove the whole piece.  The most common case is a delay at the
191	 * end of the string.  The adjusted string will retain the delay, which
192	 * is conservative.
193	 */
194	if (used_delay != 0) {
195	    used_full += used_delay;
196	    used_delay = 0;
197	}
198	if (*part == '$' && *full == '$') {
199	    next_part = skip_delay(part);
200	    next_full = skip_delay(full);
201	    if (next_part != part && next_full != full) {
202		used_delay += (next_full - full);
203		full = next_full;
204		part = next_part;
205		continue;
206	    }
207	}
208	++used_full;
209	++part;
210	++full;
211    }
212    return used_full;
213}
214
215/*
216 * While 'sgr0' is the "same" as termcap 'me', there is a compatibility issue.
217 * The sgr/sgr0 capabilities include setting/clearing alternate character set
218 * mode.  A termcap application cannot use sgr, so sgr0 strings that reset
219 * alternate character set mode will be misinterpreted.  Here, we remove those
220 * from the more common ISO/ANSI/VT100 entries, which have sgr0 agreeing with
221 * sgr.
222 *
223 * This function returns the modified sgr0 if it can be modified, a null if
224 * an error occurs, or the original sgr0 if no change is needed.
225 */
226NCURSES_EXPORT(char *)
227_nc_trim_sgr0(TERMTYPE *tp)
228{
229    char *result = exit_attribute_mode;
230
231    T((T_CALLED("_nc_trim_sgr0()")));
232
233    if (PRESENT(exit_attribute_mode)
234	&& PRESENT(set_attributes)) {
235	bool found = FALSE;
236	char *on = set_attribute_9(tp, 1);
237	char *off = set_attribute_9(tp, 0);
238	char *end = strdup(exit_attribute_mode);
239	char *tmp;
240	size_t i, j, k;
241
242	TR(TRACE_DATABASE, ("checking if we can trim sgr0 based on sgr"));
243	TR(TRACE_DATABASE, ("sgr0       %s", _nc_visbuf(end)));
244	TR(TRACE_DATABASE, ("sgr(9:off) %s", _nc_visbuf(off)));
245	TR(TRACE_DATABASE, ("sgr(9:on)  %s", _nc_visbuf(on)));
246
247	if (!rewrite_sgr(on, enter_alt_charset_mode)
248	    || !rewrite_sgr(off, exit_alt_charset_mode)
249	    || !rewrite_sgr(end, exit_alt_charset_mode)) {
250	    FreeIfNeeded(off);
251	} else if (similar_sgr(off, end)
252		   && !similar_sgr(off, on)) {
253	    TR(TRACE_DATABASE, ("adjusting sgr(9:off) : %s", _nc_visbuf(off)));
254	    result = off;
255	    /*
256	     * If rmacs is a substring of sgr(0), remove that chunk.
257	     */
258	    if (exit_alt_charset_mode != 0) {
259		TR(TRACE_DATABASE, ("scan for rmacs %s", _nc_visbuf(exit_alt_charset_mode)));
260		j = strlen(off);
261		k = strlen(exit_alt_charset_mode);
262		if (j > k) {
263		    for (i = 0; i <= (j - k); ++i) {
264			int k2 = compare_part(exit_alt_charset_mode, off + i);
265			if (k2 != 0) {
266			    found = TRUE;
267			    chop_out(off, i, i + k2);
268			    break;
269			}
270		    }
271		}
272	    }
273	    /*
274	     * SGR 10 would reset to normal font.
275	     */
276	    if (!found) {
277		if ((i = is_csi(off)) != 0
278		    && off[strlen(off) - 1] == 'm') {
279		    TR(TRACE_DATABASE, ("looking for SGR 10 in %s",
280					_nc_visbuf(off)));
281		    tmp = skip_zero(off + i);
282		    if (tmp[0] == '1'
283			&& skip_zero(tmp + 1) != tmp + 1) {
284			i = tmp - off;
285			if (off[i - 1] == ';')
286			    i--;
287			j = skip_zero(tmp + 1) - off;
288			i = chop_out(off, i, j);
289			found = TRUE;
290		    }
291		}
292	    }
293	    if (!found
294		&& (tmp = strstr(end, off)) != 0
295		&& strcmp(end, off) != 0) {
296		i = tmp - end;
297		j = strlen(off);
298		tmp = strdup(end);
299		chop_out(tmp, i, j);
300		free(off);
301		result = tmp;
302	    }
303	    TR(TRACE_DATABASE, ("...adjusted sgr0 : %s", _nc_visbuf(result)));
304	    if (!strcmp(result, exit_attribute_mode)) {
305		TR(TRACE_DATABASE, ("...same result, discard"));
306		free(result);
307		result = exit_attribute_mode;
308	    }
309	} else {
310	    /*
311	     * Either the sgr does not reference alternate character set,
312	     * or it is incorrect.  That's too hard to decide right now.
313	     */
314	    free(off);
315	}
316	FreeIfNeeded(end);
317	FreeIfNeeded(on);
318    } else {
319	/*
320	 * Possibly some applications are confused if sgr0 contains rmacs,
321	 * but that would be a different bug report -TD
322	 */
323    }
324
325    returnPtr(result);
326}
327