*** empty log message ***
[dana/urxvt.git] / src / screen.C
1 /*--------------------------------*-C-*--------------------------------------*
2  * File:        screen.C
3  *---------------------------------------------------------------------------*
4  *
5  * Copyright (c) 1997-2001 Geoff Wing <gcw@pobox.com>
6  * Copyright (c) 2003-2004 Marc Lehmann <pcg@goof.com>
7  *
8  * This program 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.
12  *
13  * This program 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.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  *--------------------------------------------------------------------------*/
22
23 /*
24  * This file handles _all_ screen updates and selections
25  */
26
27 #include "../config.h"          /* NECESSARY */
28 #include "rxvt.h"               /* NECESSARY */
29
30 #include <X11/Xmd.h>            /* get the typedef for CARD32 */
31
32 #include <inttypes.h>
33 #include <wchar.h>
34
35 #include "salloc.C" // HACK, should be a seperate compile!
36
37 inline void fill_text (text_t *start, text_t value, int len)
38 {
39   while (len--)
40     *start++ = value;
41 }
42
43 /* ------------------------------------------------------------------------- */
44 #define PROP_SIZE               16384
45 #define TABSIZE                 8       /* default tab size */
46
47 /* ------------------------------------------------------------------------- *
48  *             GENERAL SCREEN AND SELECTION UPDATE ROUTINES                  *
49  * ------------------------------------------------------------------------- */
50 #define ZERO_SCROLLBACK()                                              \
51     if (options & Opt_scrollTtyOutput)                                 \
52         TermWin.view_start = 0
53 #define CLEAR_SELECTION()                                              \
54     selection.beg.row = selection.beg.col                              \
55         = selection.end.row = selection.end.col = 0
56 #define CLEAR_ALL_SELECTION()                                          \
57     selection.beg.row = selection.beg.col                              \
58         = selection.mark.row = selection.mark.col                      \
59         = selection.end.row = selection.end.col = 0
60
61 #define ROW_AND_COL_IS_AFTER(A, B, C, D)                               \
62     (((A) > (C)) || (((A) == (C)) && ((B) > (D))))
63 #define ROW_AND_COL_IS_BEFORE(A, B, C, D)                              \
64     (((A) < (C)) || (((A) == (C)) && ((B) < (D))))
65 #define ROW_AND_COL_IN_ROW_AFTER(A, B, C, D)                           \
66     (((A) == (C)) && ((B) > (D)))
67 #define ROW_AND_COL_IN_ROW_AT_OR_AFTER(A, B, C, D)                     \
68     (((A) == (C)) && ((B) >= (D)))
69 #define ROW_AND_COL_IN_ROW_BEFORE(A, B, C, D)                          \
70     (((A) == (C)) && ((B) < (D)))
71 #define ROW_AND_COL_IN_ROW_AT_OR_BEFORE(A, B, C, D)                    \
72     (((A) == (C)) && ((B) <= (D)))
73
74 /* these must be row_col_t */
75 #define ROWCOL_IS_AFTER(X, Y)                                          \
76     ROW_AND_COL_IS_AFTER ((X).row, (X).col, (Y).row, (Y).col)
77 #define ROWCOL_IS_BEFORE(X, Y)                                         \
78     ROW_AND_COL_IS_BEFORE ((X).row, (X).col, (Y).row, (Y).col)
79 #define ROWCOL_IN_ROW_AFTER(X, Y)                                      \
80     ROW_AND_COL_IN_ROW_AFTER ((X).row, (X).col, (Y).row, (Y).col)
81 #define ROWCOL_IN_ROW_BEFORE(X, Y)                                     \
82     ROW_AND_COL_IN_ROW_BEFORE ((X).row, (X).col, (Y).row, (Y).col)
83 #define ROWCOL_IN_ROW_AT_OR_AFTER(X, Y)                                \
84     ROW_AND_COL_IN_ROW_AT_OR_AFTER ((X).row, (X).col, (Y).row, (Y).col)
85 #define ROWCOL_IN_ROW_AT_OR_BEFORE(X, Y)                               \
86     ROW_AND_COL_IN_ROW_AT_OR_BEFORE ((X).row, (X).col, (Y).row, (Y).col)
87
88 /*
89  * CLEAR_ROWS : clear <num> rows starting from row <row>
90  * CLEAR_CHARS: clear <num> chars starting from pixel position <x,y>
91  * ERASE_ROWS : set <num> rows starting from row <row> to the foreground colour
92  */
93 #define drawBuffer      TermWin.vt
94
95 #define CLEAR_ROWS(row, num)                                           \
96     if (TermWin.mapped)                                                \
97         XClearArea (display->display, drawBuffer, 0,                   \
98                     Row2Pixel (row), (unsigned int)TermWin.width,      \
99                     (unsigned int)Height2Pixel (num), False)
100
101 #define CLEAR_CHARS(x, y, num)                                         \
102     if (TermWin.mapped)                                                \
103         XClearArea (display->display, drawBuffer, x, y,                \
104                     (unsigned int)Width2Pixel (num),                   \
105                     (unsigned int)Height2Pixel (1), False)
106
107 #define ERASE_ROWS(row, num)                                           \
108     XFillRectangle (display->display, drawBuffer, TermWin.gc,          \
109                     0, Row2Pixel (row),                                \
110                     (unsigned int)TermWin.width,                       \
111                     (unsigned int)Height2Pixel (num))
112
113 /* ------------------------------------------------------------------------- *
114  *                        SCREEN `COMMON' ROUTINES                           *
115  * ------------------------------------------------------------------------- */
116
117 /* Fill part/all of a line with blanks. */
118 void
119 rxvt_term::scr_blank_line (text_t *et, rend_t *er, unsigned int width, rend_t efs)
120 {
121   efs &= ~RS_baseattrMask;
122   efs = SET_FONT (efs, FONTSET (efs)->find_font (' '));
123
124   while (width--)
125     {
126       *et++ = ' ';
127       *er++ = efs;
128     }
129 }
130
131 /* ------------------------------------------------------------------------- */
132 /* Fill a full line with blanks - make sure it is allocated first */
133 void
134 rxvt_term::scr_blank_screen_mem (text_t **tp, rend_t **rp, unsigned int row, rend_t efs)
135 {
136 #ifdef DEBUG_STRICT
137   assert ((tp[row] && rp[row]) || (tp[row] == NULL && rp[row] == NULL));
138 #endif
139   if (tp[row] == NULL)
140     {
141       tp[row] = (text_t *)talloc->alloc ();
142       rp[row] = (rend_t *)ralloc->alloc ();
143     }
144
145   scr_blank_line (tp[row], rp[row], TermWin.ncol, efs);
146 }
147
148 /* ------------------------------------------------------------------------- *
149  *                          SCREEN INITIALISATION                            *
150  * ------------------------------------------------------------------------- */
151 void
152 rxvt_term::scr_reset ()
153 {
154   unsigned int ncol, nrow, total_rows, prev_total_rows;
155   unsigned int p, q;
156   int k;
157   rend_t setrstyle;
158
159 #if ENABLE_OVERLAY
160   scr_overlay_off ();
161 #endif
162
163   TermWin.view_start = 0;
164   num_scr = 0;
165
166   if (TermWin.ncol == 0)
167     TermWin.ncol = 80;
168
169   if (TermWin.nrow == 0)
170     TermWin.nrow = 24;
171
172   ncol = TermWin.ncol;
173   nrow = TermWin.nrow;
174
175   if (ncol == prev_ncol && nrow == prev_nrow)
176     return;
177
178   // we need at least two lines for wrapping to work correctly
179   if (nrow + TermWin.saveLines < 2)
180     {
181       TermWin.saveLines++;
182       prev_nrow--;
183       TermWin.nscrolled++;
184     }
185
186   want_refresh = 1;
187
188   prev_total_rows = prev_nrow + TermWin.saveLines;
189   total_rows = nrow + TermWin.saveLines;
190
191   screen.tscroll = 0;
192   screen.bscroll = nrow - 1;
193
194   if (!talloc)
195     {
196       talloc = new rxvt_salloc (ncol * sizeof (text_t));
197       ralloc = new rxvt_salloc (ncol * sizeof (rend_t));
198     }
199
200   if (!screen.text)
201     {
202       /*
203        * first time called so just malloc everything: don't rely on realloc
204        * Note: this is still needed so that all the scrollback lines are NULL
205        */
206       screen.text = (text_t **)rxvt_calloc (total_rows, sizeof (text_t *));
207       buf_text = (text_t **)rxvt_calloc (total_rows, sizeof (text_t *));
208       drawn_text = (text_t **)rxvt_calloc (nrow, sizeof (text_t *));
209       swap.text = (text_t **)rxvt_calloc (nrow, sizeof (text_t *));
210
211       screen.tlen = (int16_t *)rxvt_calloc (total_rows, sizeof (int16_t));
212       swap.tlen = (int16_t *)rxvt_calloc (nrow, sizeof (int16_t));
213
214       screen.rend = (rend_t **)rxvt_calloc (total_rows, sizeof (rend_t *));
215       buf_rend = (rend_t **)rxvt_calloc (total_rows, sizeof (rend_t *));
216       drawn_rend = (rend_t **)rxvt_calloc (nrow, sizeof (rend_t *));
217       swap.rend = (rend_t **)rxvt_calloc (nrow, sizeof (rend_t *));
218
219       for (p = 0; p < nrow; p++)
220         {
221           q = p + TermWin.saveLines;
222           scr_blank_screen_mem (screen.text, screen.rend, q, DEFAULT_RSTYLE);
223           scr_blank_screen_mem (swap.text, swap.rend, p, DEFAULT_RSTYLE);
224           screen.tlen[q] = swap.tlen[p] = 0;
225           scr_blank_screen_mem (drawn_text, drawn_rend, p, DEFAULT_RSTYLE);
226         }
227
228       memset (charsets, 'B', sizeof (charsets));
229       TermWin.nscrolled = 0;       /* no saved lines */
230       rstyle = DEFAULT_RSTYLE;
231       screen.flags = Screen_DefaultFlags;
232       screen.cur.row = screen.cur.col = 0;
233       screen.charset = 0;
234       current_screen = PRIMARY;
235       scr_cursor (SAVE);
236
237 #if NSCREENS
238       swap.flags = Screen_DefaultFlags;
239       swap.cur.row = swap.cur.col = 0;
240       swap.charset = 0;
241       current_screen = SECONDARY;
242       scr_cursor (SAVE);
243       current_screen = PRIMARY;
244 #endif
245
246       selection.text = NULL;
247       selection.len = 0;
248       selection.op = SELECTION_CLEAR;
249       selection.screen = PRIMARY;
250       selection.clicks = 0;
251       CLEAR_ALL_SELECTION ();
252       rvideo = 0;
253     }
254   else
255     {
256       /*
257        * add or delete rows as appropriate
258        */
259       setrstyle = DEFAULT_RSTYLE;
260
261       if (nrow < prev_nrow)
262         {
263           /* delete rows */
264           k = min (TermWin.nscrolled, prev_nrow - nrow);
265           scr_scroll_text (0, (int)prev_nrow - 1, k, 1);
266
267           for (p = nrow; p < prev_nrow; p++)
268             {
269               q = p + TermWin.saveLines;
270
271               if (screen.text[q])
272                 {
273 #ifdef DEBUG_STRICT
274                   assert (screen.rend[q]);
275 #endif
276                   talloc->free (screen.text[q]);
277                   ralloc->free (screen.rend[q]);
278                 }
279
280               if (swap.text[p])
281                 {
282 #ifdef DEBUG_STRICT
283                   assert (swap.rend[p]);
284 #endif
285                   talloc->free (swap.text[p]);
286                   ralloc->free (swap.rend[p]);
287                 }
288
289 #ifdef DEBUG_STRICT
290               assert (drawn_text[p] && drawn_rend[p]);
291 #endif
292               talloc->free (drawn_text[p]);
293               ralloc->free (drawn_rend[p]);
294             }
295
296           /* we have fewer rows so fix up cursor position */
297           MIN_IT (screen.cur.row, (int32_t)nrow - 1);
298           MIN_IT (swap.cur.row, (int32_t)nrow - 1);
299
300           scr_reset_realloc (); /* realloc _last_ */
301         }
302       else if (nrow > prev_nrow)
303         {
304           /* add rows */
305           scr_reset_realloc (); /* realloc _first_ */
306
307           TermWin.ncol = prev_ncol; // save b/c scr_blank_screen_mem uses this
308
309           k = min (TermWin.nscrolled, nrow - prev_nrow);
310
311           for (p = prev_total_rows; p < total_rows; p++)
312             {
313               screen.tlen[p] = 0;
314               screen.text[p] = NULL;
315               screen.rend[p] = NULL;
316             }
317
318           for (p = prev_total_rows; p < total_rows - k; p++)
319             scr_blank_screen_mem (screen.text, screen.rend, p, setrstyle);
320
321           for (p = prev_nrow; p < nrow; p++)
322             {
323               swap.tlen[p] = 0;
324               swap.text[p] = NULL;
325               swap.rend[p] = NULL;
326               drawn_text[p] = NULL;
327               drawn_rend[p] = NULL;
328               scr_blank_screen_mem (swap.text,  swap.rend,  p, setrstyle);
329               scr_blank_screen_mem (drawn_text, drawn_rend, p, setrstyle);
330             }
331
332           if (k > 0)
333             {
334               scr_scroll_text (0, (int)nrow - 1, -k, 1);
335               screen.cur.row += k;
336               screen.s_cur.row += k;
337               TermWin.nscrolled -= k;
338             }
339 #ifdef DEBUG_STRICT
340           assert (screen.cur.row < TermWin.nrow);
341           assert (swap.cur.row < TermWin.nrow);
342 #else                           /* drive with your eyes closed */
343
344           MIN_IT (screen.cur.row, nrow - 1);
345           MIN_IT (swap.cur.row, nrow - 1);
346 #endif
347           TermWin.ncol =  ncol; // save b/c scr_blank_screen_mem uses this
348         }
349
350       /* resize columns */
351       if (ncol != prev_ncol)
352         {
353           rxvt_salloc *ta = new rxvt_salloc (ncol * sizeof (text_t));
354           rxvt_salloc *ra = new rxvt_salloc (ncol * sizeof (rend_t));
355
356           for (p = 0; p < total_rows; p++)
357             {
358               if (screen.text[p])
359                 {
360                   screen.text[p] = (text_t *)ta->alloc (screen.text[p], prev_ncol * sizeof (text_t));
361                   screen.rend[p] = (rend_t *)ra->alloc (screen.rend[p], prev_ncol * sizeof (rend_t));
362
363                   MIN_IT (screen.tlen[p], (int16_t)ncol);
364
365                   if (ncol > prev_ncol)
366                     scr_blank_line (&screen.text[p][prev_ncol],
367                                     &screen.rend[p][prev_ncol],
368                                     ncol - prev_ncol, setrstyle);
369                 }
370             }
371
372           for (p = 0; p < nrow; p++)
373             {
374               drawn_text[p] = (text_t *)ta->alloc (drawn_text[p], prev_ncol * sizeof (text_t));
375               drawn_rend[p] = (rend_t *)ra->alloc (drawn_rend[p], prev_ncol * sizeof (rend_t));
376
377               if (ncol > prev_ncol)
378                 scr_blank_line (&drawn_text[p][prev_ncol],
379                                 &drawn_rend[p][prev_ncol],
380                                 ncol - prev_ncol, setrstyle);
381
382               if (swap.text[p])
383                 {
384                   swap.text[p] = (text_t *)ta->alloc (swap.text[p], prev_ncol * sizeof (text_t));
385                   swap.rend[p] = (rend_t *)ra->alloc (swap.rend[p], prev_ncol * sizeof (rend_t));
386
387                   MIN_IT (swap.tlen[p], (int16_t)ncol);
388
389                   if (ncol > prev_ncol)
390                     scr_blank_line (&swap.text[p][prev_ncol],
391                                     &swap.rend[p][prev_ncol],
392                                     ncol - prev_ncol, setrstyle);
393                 }
394
395             }
396
397           MIN_IT (screen.cur.col, (int16_t)ncol - 1);
398           MIN_IT (swap.cur.col, (int16_t)ncol - 1);
399
400           delete talloc; talloc = ta;
401           delete ralloc; ralloc = ra;
402         }
403
404       if (tabs)
405         free (tabs);
406     }
407
408   prev_nrow = nrow;
409   prev_ncol = ncol;
410
411   tabs = (char *)rxvt_malloc (ncol * sizeof (char));
412
413   for (p = 0; p < ncol; p++)
414     tabs[p] = (p % TABSIZE == 0) ? 1 : 0;
415
416   tt_winch ();
417 }
418
419 void
420 rxvt_term::scr_reset_realloc ()
421 {
422   unsigned int total_rows, nrow;
423
424   nrow = TermWin.nrow;
425   total_rows = nrow + TermWin.saveLines;
426   /* *INDENT-OFF* */
427   screen.text = (text_t **)rxvt_realloc (screen.text, total_rows * sizeof (text_t *));
428   buf_text    = (text_t **)rxvt_realloc (buf_text   , total_rows * sizeof (text_t *));
429   drawn_text  = (text_t **)rxvt_realloc (drawn_text , nrow       * sizeof (text_t *));
430   swap.text   = (text_t **)rxvt_realloc (swap.text  , nrow       * sizeof (text_t *));
431
432   screen.tlen = (int16_t *)rxvt_realloc (screen.tlen, total_rows * sizeof (int16_t));
433   swap.tlen   = (int16_t *)rxvt_realloc (swap.tlen  , total_rows * sizeof (int16_t));
434
435   screen.rend = (rend_t **)rxvt_realloc (screen.rend, total_rows * sizeof (rend_t *));
436   buf_rend    = (rend_t **)rxvt_realloc (buf_rend   , total_rows * sizeof (rend_t *));
437   drawn_rend  = (rend_t **)rxvt_realloc (drawn_rend , nrow       * sizeof (rend_t *));
438   swap.rend   = (rend_t **)rxvt_realloc (swap.rend  , nrow       * sizeof (rend_t *));
439   /* *INDENT-ON* */
440 }
441
442 /* ------------------------------------------------------------------------- */
443 /*
444  * Free everything.  That way malloc debugging can find leakage.
445  */
446 void
447 rxvt_term::scr_release ()
448 {
449   unsigned int total_rows;
450   int i;
451
452   total_rows = TermWin.nrow + TermWin.saveLines;
453
454   delete talloc; talloc = 0;
455   delete ralloc; ralloc = 0;
456
457   free (screen.text);
458   free (screen.tlen);
459   free (screen.rend);
460   free (drawn_text);
461   free (drawn_rend);
462   free (swap.text);
463   free (swap.tlen);
464   free (swap.rend);
465   free (buf_text);
466   free (buf_rend);
467   free (tabs);
468
469   /* NULL these so if anything tries to use them, we'll know about it */
470   screen.text = drawn_text = swap.text = NULL;
471   screen.rend = drawn_rend = swap.rend = NULL;
472   screen.tlen = swap.tlen = NULL;
473   buf_text = NULL;
474   buf_rend = NULL;
475   tabs = NULL;
476 }
477
478 /* ------------------------------------------------------------------------- */
479 /*
480  * Hard reset
481  */
482 void
483 rxvt_term::scr_poweron ()
484 {
485   scr_release ();
486   prev_nrow = prev_ncol = 0;
487   scr_reset ();
488
489   scr_clear (true);
490   scr_refresh (SLOW_REFRESH);
491 }
492
493 /* ------------------------------------------------------------------------- *
494  *                         PROCESS SCREEN COMMANDS                           *
495  * ------------------------------------------------------------------------- */
496 /*
497  * Save and Restore cursor
498  * XTERM_SEQ: Save cursor   : ESC 7
499  * XTERM_SEQ: Restore cursor: ESC 8
500  */
501 void
502 rxvt_term::scr_cursor (int mode)
503 {
504   screen_t *s;
505
506 #if NSCREENS && !defined(NO_SECONDARY_SCREEN_CURSOR)
507   if (current_screen == SECONDARY)
508     s = &swap;
509   else
510 #endif
511     s = &screen;
512
513   switch (mode)
514     {
515       case SAVE:
516         s->s_cur.row = screen.cur.row;
517         s->s_cur.col = screen.cur.col;
518         s->s_rstyle = rstyle;
519         s->s_charset = screen.charset;
520         s->s_charset_char = charsets[screen.charset];
521         break;
522
523       case RESTORE:
524         want_refresh = 1;
525         screen.cur.row = s->s_cur.row;
526         screen.cur.col = s->s_cur.col;
527         screen.flags &= ~Screen_WrapNext;
528         rstyle = s->s_rstyle;
529         screen.charset = s->s_charset;
530         charsets[screen.charset] = s->s_charset_char;
531         set_font_style ();
532         break;
533     }
534
535   /* boundary check in case screen size changed between SAVE and RESTORE */
536   MIN_IT (s->cur.row, TermWin.nrow - 1);
537   MIN_IT (s->cur.col, TermWin.ncol - 1);
538 #ifdef DEBUG_STRICT
539   assert (s->cur.row >= 0);
540   assert (s->cur.col >= 0);
541 #else                           /* drive with your eyes closed */
542   MAX_IT (s->cur.row, 0);
543   MAX_IT (s->cur.col, 0);
544 #endif
545 }
546
547 /* ------------------------------------------------------------------------- */
548 /*
549  * Swap between primary and secondary screens
550  * XTERM_SEQ: Primary screen  : ESC [ ? 4 7 h
551  * XTERM_SEQ: Secondary screen: ESC [ ? 4 7 l
552  */
553 int
554 rxvt_term::scr_change_screen (int scrn)
555 {
556   int i;
557 #if NSCREENS
558   int offset;
559 #endif
560
561   want_refresh = 1;
562
563   TermWin.view_start = 0;
564
565   if (current_screen == scrn)
566     return scrn;
567
568   selection_check (2);        /* check for boundary cross */
569
570   SWAP_IT (current_screen, scrn, int);
571
572   SWAP_IT (screen.cur.row, swap.cur.row, int16_t);
573   SWAP_IT (screen.cur.col, swap.cur.col, int16_t);
574 # ifdef DEBUG_STRICT
575   assert (screen.cur.row >= 0 && screen.cur.row < prev_nrow);
576   assert (screen.cur.col >= 0 && screen.cur.col < prev_ncol);
577 # else                          /* drive with your eyes closed */
578   MAX_IT (screen.cur.row, 0);
579   MIN_IT (screen.cur.row, (int32_t)prev_nrow - 1);
580   MAX_IT (screen.cur.col, 0);
581   MIN_IT (screen.cur.col, (int32_t)prev_ncol - 1);
582 # endif
583
584 #if NSCREENS
585   if (options & Opt_secondaryScreen)
586     {
587       num_scr = 0;
588       offset = TermWin.saveLines;
589
590       for (i = prev_nrow; i--;)
591         {
592           SWAP_IT (screen.text[i + offset], swap.text[i], text_t *);
593           SWAP_IT (screen.tlen[i + offset], swap.tlen[i], int16_t);
594           SWAP_IT (screen.rend[i + offset], swap.rend[i], rend_t *);
595         }
596
597       SWAP_IT (screen.charset, swap.charset, int16_t);
598       SWAP_IT (screen.flags, swap.flags, int);
599       screen.flags |= Screen_VisibleCursor;
600       swap.flags |= Screen_VisibleCursor;
601     }
602   else
603 #endif
604     if (options & Opt_secondaryScroll)
605       //if (current_screen == PRIMARY)
606         scr_scroll_text (0, prev_nrow - 1, prev_nrow, 0);
607
608   return scrn;
609 }
610
611 // clear WrapNext indicator, solidifying position on next line
612 void
613 rxvt_term::scr_do_wrap ()
614 {
615   if (!(screen.flags & Screen_WrapNext))
616     return;
617
618   screen.flags &= ~Screen_WrapNext;
619
620   screen.cur.col = 0;
621
622   if (screen.cur.row == screen.bscroll)
623     scr_scroll_text (screen.tscroll, screen.bscroll, 1, 0);
624   else if (screen.cur.row < TermWin.nrow - 1)
625     screen.cur.row++;
626 }
627
628 /* ------------------------------------------------------------------------- */
629 /*
630  * Change the colour for following text
631  */
632 void
633 rxvt_term::scr_color (unsigned int color, int fgbg)
634 {
635   if (color > maxTermCOLOR)
636     color = fgbg;
637
638   if (fgbg == Color_fg)
639     rstyle = SET_FGCOLOR (rstyle, color);
640   else
641     rstyle = SET_BGCOLOR (rstyle, color);
642 }
643
644 /* ------------------------------------------------------------------------- */
645 /*
646  * Change the rendition style for following text
647  */
648 void
649 rxvt_term::scr_rendition (int set, int style)
650   {
651     if (set)
652       rstyle |= style;
653     else if (style == ~RS_None)
654       rstyle = DEFAULT_RSTYLE;
655     else
656       rstyle &= ~style;
657   }
658
659 /* ------------------------------------------------------------------------- */
660 /*
661  * Scroll text between <row1> and <row2> inclusive, by <count> lines
662  * count positive ==> scroll up
663  * count negative ==> scroll down
664  * spec == 0 for normal routines
665  */
666 int
667 rxvt_term::scr_scroll_text (int row1, int row2, int count, int spec)
668 {
669   int i, j;
670   long nscrolled;
671
672   if (count == 0 || (row1 > row2))
673     return 0;
674
675   want_refresh = 1;
676
677   if (row1 == 0 && count > 0
678       && (current_screen == PRIMARY || options & Opt_secondaryScroll))
679     {
680       nscrolled = (long)TermWin.nscrolled + (long)count;
681
682       if (nscrolled > (long)TermWin.saveLines)
683         TermWin.nscrolled = TermWin.saveLines;
684       else
685         TermWin.nscrolled = (unsigned int)nscrolled;
686
687       if ((options & Opt_scrollWithBuffer)
688           && TermWin.view_start != 0
689           && TermWin.view_start != TermWin.saveLines)
690         scr_page (UP, count);
691     }
692   else if (!spec)
693     row1 += TermWin.saveLines;
694
695   row2 += TermWin.saveLines;
696
697   if (selection.op && current_screen == selection.screen)
698     {
699       i = selection.beg.row + TermWin.saveLines;
700       j = selection.end.row + TermWin.saveLines;
701       if ((i < row1 && j > row1)
702           || (i < row2 && j > row2)
703           || (i - count < row1 && i >= row1)
704           || (i - count > row2 && i <= row2)
705           || (j - count < row1 && j >= row1)
706           || (j - count > row2 && j <= row2))
707         {
708           CLEAR_ALL_SELECTION ();
709           selection.op = SELECTION_CLEAR;  /* XXX: too aggressive? */
710         }
711       else if (j >= row1 && j <= row2)
712         {
713           /* move selected region too */
714           selection.beg.row -= count;
715           selection.end.row -= count;
716           selection.mark.row -= count;
717         }
718     }
719
720   selection_check (0);        /* _after_ TermWin.nscrolled update */
721
722   num_scr += count;
723   j = count;
724
725   if (count < 0)
726     count = -count;
727
728   i = row2 - row1 + 1;
729   MIN_IT (count, i);
730
731   if (j > 0)
732     {
733       /* A: scroll up */
734
735       /* A1: Copy lines that will get clobbered by the rotation */
736       memcpy (buf_text, screen.text + row1, count * sizeof (text_t *));
737       memcpy (buf_rend, screen.rend + row1, count * sizeof (rend_t *));
738
739       /* A2: Rotate lines */
740       i = row2 - row1 - count + 1;
741       memmove (screen.tlen + row1, screen.tlen + row1 + count, i * sizeof (int16_t));
742       memmove (screen.text + row1, screen.text + row1 + count, i * sizeof (text_t *));
743       memmove (screen.rend + row1, screen.rend + row1 + count, i * sizeof (rend_t *));
744
745       j = row2 - count + 1, i = count;
746     }
747   else /* if (j < 0) */
748     {
749       /* B: scroll down */
750
751       /* B1: Copy lines that will get clobbered by the rotation */
752       for (i = 0, j = row2; i < count; i++, j--)
753         {
754           buf_text[i] = screen.text[j];
755           buf_rend[i] = screen.rend[j];
756         }
757
758       /* B2: Rotate lines */
759       for (j = row2, i = j - count; i >= row1; i--, j--)
760         {
761           screen.tlen[j] = screen.tlen[i];
762           screen.text[j] = screen.text[i];
763           screen.rend[j] = screen.rend[i];
764         }
765
766       j = row1, i = count;
767       count = -count;
768     }
769
770   /* C: Resurrect lines */
771   memset (screen.tlen + j, 0, i * sizeof (int16_t));
772   memcpy (screen.text + j, buf_text, i * sizeof (text_t *));
773   memcpy (screen.rend + j, buf_rend, i * sizeof (text_t *));
774   if (!spec) /* line length may not equal TermWin.ncol */
775     for (; i--; j++)
776       scr_blank_screen_mem (screen.text, screen.rend, (unsigned int)j, rstyle);
777
778   return count;
779 }
780
781 /* ------------------------------------------------------------------------- */
782 /*
783  * Add text given in <str> of length <len> to screen struct
784  */
785 void
786 rxvt_term::scr_add_lines (const unicode_t *str, int nlines, int len)
787 {
788   unsigned char checksel;
789   unicode_t c;
790   int i, row, last_col;
791   text_t *stp;
792   rend_t *srp;
793
794   if (len <= 0)               /* sanity */
795     return;
796
797   want_refresh = 1;
798   ZERO_SCROLLBACK ();
799   last_col = TermWin.ncol;
800
801   if (nlines > 0)
802     {
803       nlines += screen.cur.row - screen.bscroll;
804       if ((nlines > 0)
805           && (screen.tscroll == 0)
806           && (screen.bscroll == (TermWin.nrow - 1)))
807         {
808           /* _at least_ this many lines need to be scrolled */
809           scr_scroll_text (screen.tscroll, screen.bscroll, nlines, 0);
810           screen.cur.row -= nlines;
811         }
812     }
813
814 #ifdef DEBUG_STRICT
815   assert (screen.cur.col < last_col);
816   assert ((screen.cur.row < TermWin.nrow)
817           && (screen.cur.row >= - (int32_t)TermWin.nscrolled));
818 #else                           /* drive with your eyes closed */
819   MIN_IT (screen.cur.col, last_col - 1);
820   MIN_IT (screen.cur.row, (int32_t)TermWin.nrow - 1);
821   MAX_IT (screen.cur.row, - (int32_t)TermWin.nscrolled);
822 #endif
823   row = screen.cur.row + TermWin.saveLines;
824
825   checksel = selection.op && current_screen == selection.screen ? 1 : 0;
826
827   stp = screen.text[row];
828   srp = screen.rend[row];
829
830   while (len--)
831     {
832       c = *str++;
833
834       if (c < 0x20)
835         switch (c)
836           {
837             case C0_HT:
838               scr_tab (1, true);
839               continue;
840
841             case C0_LF:
842               if (screen.tlen[row] != -1)      /* XXX: think about this */
843                 MAX_IT (screen.tlen[row], screen.cur.col);
844
845               screen.flags &= ~Screen_WrapNext;
846
847               if (screen.cur.row == screen.bscroll)
848                 scr_scroll_text (screen.tscroll, screen.bscroll, 1, 0);
849               else if (screen.cur.row < (TermWin.nrow - 1))
850                 row = (++screen.cur.row) + TermWin.saveLines;
851
852               stp = screen.text[row];  /* _must_ refresh */
853               srp = screen.rend[row];  /* _must_ refresh */
854               continue;
855
856             case C0_CR:
857               if (screen.tlen[row] != -1)      /* XXX: think about this */
858                 MAX_IT (screen.tlen[row], screen.cur.col);
859
860               screen.flags &= ~Screen_WrapNext;
861               screen.cur.col = 0;
862               continue;
863           }
864
865       if (checksel            /* see if we're writing within selection */
866           && !ROWCOL_IS_BEFORE (screen.cur, selection.beg)
867           && ROWCOL_IS_BEFORE (screen.cur, selection.end))
868         {
869           checksel = 0;
870           /*
871            * If we wrote anywhere in the selected area, kill the selection
872            * XXX: should we kill the mark too?  Possibly, but maybe that
873            *      should be a similar check.
874            */
875           CLEAR_SELECTION ();
876         }
877
878       if (screen.flags & Screen_WrapNext)
879         {
880           screen.tlen[row] = -1;
881
882           scr_do_wrap (); row = screen.cur.row + TermWin.saveLines;
883
884           stp = screen.text[row];  /* _must_ refresh */
885           srp = screen.rend[row];  /* _must_ refresh */
886         }
887
888       // rely on wcwidth to tell us the character width, at least for non-latin1
889       // do wcwidth before further replacements, as wcwidth says that line-drawing
890       // characters have width -1 (DOH!) on GNU/Linux sometimes.
891       int width = c < 0x100 ? 1 : wcwidth (c);
892
893       if (charsets[screen.charset] == '0') // DEC SPECIAL
894         {
895           // vt100 special graphics and line drawing
896           // 5f-7e standard vt100
897           // 40-5e rxvt extension for extra curses acs chars
898           static uint16_t vt100_0[63] = { // 40 .. 7e
899             0x0000, 0x2191, 0x2193, 0x2192, 0x2190, 0x2588, 0x259a, 0x2603, // 40-47 hi mr. snowman!
900             0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, // 48-4f
901             0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, // 50-57
902             0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0020, // 58-5f
903             0x25c6, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0, 0x00b1, // 60-67
904             0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c, 0x23ba, // 68-6f
905             0x23bb, 0x2500, 0x23bc, 0x23bd, 0x251c, 0x2524, 0x2534, 0x252c, // 70-77
906             0x2502, 0x2264, 0x2265, 0x03c0, 0x2260, 0x00a3, 0x00b7,         // 78-7e
907           };
908
909           if (c >= 0x40 && c <= 0x7e && vt100_0[c - 0x40])
910             {
911               c = vt100_0[c - 0x40];
912               width = 1;
913             }
914         }
915
916       if (screen.flags & Screen_Insert)
917         scr_insdel_chars (width, INSERT);
918
919       if (width != 0)
920         {
921           // some utf-8 decoders decode surrogate characters.
922           if (0xd800 <= c && c <= 0xdfff)
923             c = 0xfffd;
924
925 #if !UNICODE_3
926           // trim characters we can't store directly :(
927           if (c >= 0x10000)
928 # if ENABLE_COMBINING
929             c = rxvt_composite.compose (c); // map to lower 16 bits
930 # else
931             c = 0xfffd;
932 # endif
933 #endif
934
935           // nuke the character at this position, if required
936           if (stp[screen.cur.col] == NOCHAR
937               || (screen.cur.col < TermWin.ncol - 1
938                   && stp[screen.cur.col + 1] == NOCHAR))
939             {
940               int col = screen.cur.col;
941
942               // find begin
943               while (col > 0 && stp[col] == NOCHAR)
944                 col--;
945
946               rend_t rend = SET_FONT (srp[col], FONTSET (srp[col])->find_font (' '));
947
948               // found begin, nuke
949               do {
950                 stp[col] = ' ';
951                 srp[col] = rend;
952                 col++;
953               } while (col < TermWin.ncol && stp[col] == NOCHAR);
954             }
955
956           rend_t rend = SET_FONT (rstyle, FONTSET (rstyle)->find_font (c));
957
958           do
959             {
960               stp[screen.cur.col] = c;
961               srp[screen.cur.col] = rend;
962
963               if (screen.cur.col < last_col - 1)
964                 screen.cur.col++;
965               else
966                 {
967                   screen.tlen[row] = last_col;
968                   if (screen.flags & Screen_Autowrap)
969                     screen.flags |= Screen_WrapNext;
970                   break;
971                 }
972
973               c = NOCHAR;
974             }
975           while (--width > 0);
976
977           // pad with spaces when overwriting wide character with smaller one
978           if (!width)
979             for (int c = screen.cur.col; c < last_col && stp[c] == NOCHAR; c++)
980               {
981                 stp[c] = ' ';
982                 srp[c] = rend;
983               }
984         }
985       else if (width == 0)
986         {
987 #if ENABLE_COMBINING
988           // handle combining characters
989           // we just tag the accent on the previous on-screen character.
990           // this is arguably not correct, but also arguably not wrong.
991           // we don't handle double-width characters nicely yet.
992
993           text_t *tp;
994           rend_t *rp;
995
996           if (screen.cur.col > 0)
997             {
998               tp = stp + screen.cur.col - 1;
999               rp = srp + screen.cur.col - 1;
1000
1001               while (*tp == NOCHAR && tp > stp)
1002                 tp--, rp--;
1003             }
1004           else if (screen.cur.row > 0
1005                    && screen.tlen [screen.cur.row - 1 + TermWin.saveLines] == -1)
1006             {
1007               int line = screen.cur.row - 1 + TermWin.saveLines;
1008
1009               tp = screen.text[line] + last_col - 1;
1010               rp = screen.rend[line] + last_col - 1;
1011
1012               while (*tp == NOCHAR && tp > screen.text[line])
1013                 tp--, rp--;
1014             }
1015           else
1016             continue;
1017
1018           // first try to find a precomposed character
1019           unicode_t n = rxvt_compose (*tp, c);
1020           if (n == NOCHAR)
1021             n = rxvt_composite.compose (*tp, c);
1022
1023           *tp = n;
1024           *rp = SET_FONT (*rp, FONTSET (*rp)->find_font (*tp));
1025 #endif
1026         }
1027     }
1028
1029   if (screen.tlen[row] != -1)      /* XXX: think about this */
1030     MAX_IT (screen.tlen[row], screen.cur.col);
1031
1032 #ifdef DEBUG_STRICT
1033   assert (screen.cur.row >= 0);
1034 #else                           /* drive with your eyes closed */
1035   MAX_IT (screen.cur.row, 0);
1036 #endif
1037 }
1038
1039 /* ------------------------------------------------------------------------- */
1040 /*
1041  * Process Backspace.  Move back the cursor back a position, wrap if have to
1042  * XTERM_SEQ: CTRL-H
1043  */
1044 void
1045 rxvt_term::scr_backspace ()
1046 {
1047   want_refresh = 1;
1048
1049   if (screen.cur.col == 0)
1050     {
1051       if (screen.cur.row > 0)
1052         {
1053 #ifdef TERMCAP_HAS_BW
1054           screen.cur.col = TermWin.ncol - 1;
1055           screen.cur.row--;
1056           return;
1057 #endif
1058         }
1059     }
1060   else if (!(screen.flags & Screen_WrapNext))
1061     scr_gotorc (0, -1, RELATIVE);
1062
1063   screen.flags &= ~Screen_WrapNext;
1064 }
1065
1066 /* ------------------------------------------------------------------------- */
1067 /*
1068  * Process Horizontal Tab
1069  * count: +ve = forward; -ve = backwards
1070  * XTERM_SEQ: CTRL-I
1071  */
1072 void
1073 rxvt_term::scr_tab (int count, bool ht)
1074 {
1075   int i, x;
1076
1077   want_refresh = 1;
1078   i = x = screen.cur.col;
1079
1080   if (count == 0)
1081     return;
1082   else if (count > 0)
1083     {
1084       int row = TermWin.saveLines + screen.cur.row;
1085       text_t *tp = screen.text[row];
1086       rend_t *rp = screen.rend[row];
1087       rend_t base_rend = rp[i];
1088       ht &= tp[i] == ' ';
1089
1090       for (; ++i < TermWin.ncol; )
1091         if (tabs[i])
1092           {
1093             x = i;
1094             if (!--count)
1095               break;
1096           }
1097         else 
1098           ht &= tp[i] == ' '
1099                 && RS_SAME (rp[i], base_rend);
1100
1101       if (count)
1102         x = TermWin.ncol - 1;
1103
1104       // store horizontal tab commands as characters inside the text
1105       // buffer so they can be selected and pasted.
1106       if (ht && options & Opt_pastableTabs)
1107         {
1108           base_rend = SET_FONT (base_rend, 0);
1109
1110           if (screen.tlen[row] != -1)      /* XXX: think about this */
1111             MAX_IT (screen.tlen[row], x);
1112
1113           i = screen.cur.col;
1114
1115           tp[i] = '\t';
1116           rp[i] = base_rend;
1117
1118           while (++i < x)
1119             {
1120               tp[i] = NOCHAR;
1121               rp[i] = base_rend;
1122             }
1123         }
1124     }
1125   else /* if (count < 0) */
1126     {
1127       for (; --i >= 0; )
1128         if (tabs[i])
1129           {
1130             x = i;
1131             if (!++count)
1132               break;
1133           }
1134
1135       if (count)
1136         x = 0;
1137     }
1138
1139   if (x != screen.cur.col)
1140     scr_gotorc (0, x, R_RELATIVE);
1141 }
1142
1143 /* ------------------------------------------------------------------------- */
1144 /*
1145  * Process DEC Back Index
1146  * XTERM_SEQ: ESC 6
1147  * Move cursor left in row.  If we're at the left boundary, shift everything
1148  * in that row right.  Clear left column.
1149  */
1150 #if ENABLE_FRILLS
1151 void
1152 rxvt_term::scr_backindex ()
1153 {
1154   if (screen.cur.col > 0)
1155     scr_gotorc (0, -1, R_RELATIVE | C_RELATIVE);
1156   else
1157     {
1158       if (screen.tlen[screen.cur.row + TermWin.saveLines] == 0)
1159         return;             /* um, yeah? */
1160
1161       scr_insdel_chars (1, INSERT);
1162     }
1163 }
1164 #endif
1165 /* ------------------------------------------------------------------------- */
1166 /*
1167  * Process DEC Forward Index
1168  * XTERM_SEQ: ESC 9
1169  * Move cursor right in row.  If we're at the right boundary, shift everything
1170  * in that row left.  Clear right column.
1171  */
1172 #if ENABLE_FRILLS
1173 void
1174 rxvt_term::scr_forwardindex ()
1175 {
1176   int             row;
1177
1178   if (screen.cur.col < TermWin.ncol - 1)
1179     scr_gotorc (0, 1, R_RELATIVE | C_RELATIVE);
1180   else
1181     {
1182       row = screen.cur.row + TermWin.saveLines;
1183
1184       if (screen.tlen[row] == 0)
1185         return;             /* um, yeah? */
1186       else if (screen.tlen[row] == -1)
1187         screen.tlen[row] = TermWin.ncol;
1188
1189       scr_gotorc (0, 0, R_RELATIVE);
1190       scr_insdel_chars (1, DELETE);
1191       scr_gotorc (0, TermWin.ncol - 1, R_RELATIVE);
1192     }
1193 }
1194 #endif
1195
1196 /* ------------------------------------------------------------------------- */
1197 /*
1198  * Goto Row/Column
1199  */
1200 void
1201 rxvt_term::scr_gotorc (int row, int col, int relative)
1202 {
1203   want_refresh = 1;
1204   ZERO_SCROLLBACK ();
1205
1206   screen.cur.col = relative & C_RELATIVE ? screen.cur.col + col : col;
1207   MAX_IT (screen.cur.col, 0);
1208   MIN_IT (screen.cur.col, (int32_t)TermWin.ncol - 1);
1209
1210   screen.flags &= ~Screen_WrapNext;
1211
1212   if (relative & R_RELATIVE)
1213     {
1214       if (row > 0)
1215         {
1216           if (screen.cur.row <= screen.bscroll
1217               && (screen.cur.row + row) > screen.bscroll)
1218             screen.cur.row = screen.bscroll;
1219           else
1220             screen.cur.row += row;
1221         }
1222       else if (row < 0)
1223         {
1224           if (screen.cur.row >= screen.tscroll
1225               && (screen.cur.row + row) < screen.tscroll)
1226             screen.cur.row = screen.tscroll;
1227           else
1228             screen.cur.row += row;
1229         }
1230     }
1231   else
1232     {
1233       if (screen.flags & Screen_Relative)
1234         {        /* relative origin mode */
1235           screen.cur.row = row + screen.tscroll;
1236           MIN_IT (screen.cur.row, screen.bscroll);
1237         }
1238       else
1239         screen.cur.row = row;
1240     }
1241
1242   MAX_IT (screen.cur.row, 0);
1243   MIN_IT (screen.cur.row, (int32_t)TermWin.nrow - 1);
1244 }
1245
1246 /* ------------------------------------------------------------------------- */
1247 /*
1248  * direction should be UP or DN
1249  */
1250 void
1251 rxvt_term::scr_index (enum page_dirn direction)
1252 {
1253   int dirn;
1254
1255   want_refresh = 1;
1256   ZERO_SCROLLBACK ();
1257
1258   dirn = ((direction == UP) ? 1 : -1);
1259
1260   screen.flags &= ~Screen_WrapNext;
1261
1262   if ((screen.cur.row == screen.bscroll && direction == UP)
1263       || (screen.cur.row == screen.tscroll && direction == DN))
1264     scr_scroll_text (screen.tscroll, screen.bscroll, dirn, 0);
1265   else
1266     screen.cur.row += dirn;
1267
1268   MAX_IT (screen.cur.row, 0);
1269   MIN_IT (screen.cur.row, (int32_t)TermWin.nrow - 1);
1270   selection_check (0);
1271 }
1272
1273 /* ------------------------------------------------------------------------- */
1274 /*
1275  * Erase part or whole of a line
1276  * XTERM_SEQ: Clear line to right: ESC [ 0 K
1277  * XTERM_SEQ: Clear line to left : ESC [ 1 K
1278  * XTERM_SEQ: Clear whole line   : ESC [ 2 K
1279  */
1280 void
1281 rxvt_term::scr_erase_line (int mode)
1282 {
1283   unsigned int row, col, num;
1284
1285   want_refresh = 1;
1286   ZERO_SCROLLBACK ();
1287
1288   selection_check (1);
1289
1290   row = TermWin.saveLines + screen.cur.row;
1291   switch (mode)
1292     {
1293       case 0:                     /* erase to end of line */
1294         col = screen.cur.col;
1295         num = TermWin.ncol - col;
1296         MIN_IT (screen.tlen[row], (int16_t)col);
1297         if (ROWCOL_IN_ROW_AT_OR_AFTER (selection.beg, screen.cur)
1298             || ROWCOL_IN_ROW_AT_OR_AFTER (selection.end, screen.cur))
1299           CLEAR_SELECTION ();
1300         break;
1301       case 1:                     /* erase to beginning of line */
1302         col = 0;
1303         num = screen.cur.col + 1;
1304         if (ROWCOL_IN_ROW_AT_OR_BEFORE (selection.beg, screen.cur)
1305             || ROWCOL_IN_ROW_AT_OR_BEFORE (selection.end, screen.cur))
1306           CLEAR_SELECTION ();
1307         break;
1308       case 2:                     /* erase whole line */
1309         col = 0;
1310         num = TermWin.ncol;
1311         screen.tlen[row] = 0;
1312         if (selection.beg.row <= screen.cur.row
1313             && selection.end.row >= screen.cur.row)
1314           CLEAR_SELECTION ();
1315         break;
1316       default:
1317         return;
1318     }
1319
1320   if (screen.text[row])
1321     scr_blank_line (&screen.text[row][col], &screen.rend[row][col], num, rstyle);
1322   else
1323     scr_blank_screen_mem (screen.text, screen.rend, row, rstyle);
1324 }
1325
1326 /* ------------------------------------------------------------------------- */
1327 /*
1328  * Erase part of whole of the screen
1329  * XTERM_SEQ: Clear screen after cursor : ESC [ 0 J
1330  * XTERM_SEQ: Clear screen before cursor: ESC [ 1 J
1331  * XTERM_SEQ: Clear whole screen        : ESC [ 2 J
1332  */
1333 void
1334 rxvt_term::scr_erase_screen (int mode)
1335 {
1336   int num;
1337   int32_t row, row_offset;
1338   rend_t ren;
1339   XGCValues gcvalue;
1340
1341   want_refresh = 1;
1342   ZERO_SCROLLBACK ();
1343
1344   row_offset = (int32_t)TermWin.saveLines;
1345
1346   switch (mode)
1347     {
1348       case 0:                     /* erase to end of screen */
1349         selection_check (1);
1350         scr_erase_line (0);
1351         row = screen.cur.row + 1;    /* possible OOB */
1352         num = TermWin.nrow - row;
1353         break;
1354       case 1:                     /* erase to beginning of screen */
1355         selection_check (3);
1356         scr_erase_line (1);
1357         row = 0;
1358         num = screen.cur.row;
1359         break;
1360       case 2:                     /* erase whole screen */
1361         selection_check (3);
1362         row = 0;
1363         num = TermWin.nrow;
1364         break;
1365       default:
1366         return;
1367     }
1368
1369   if (selection.op && current_screen == selection.screen
1370       && ((selection.beg.row >= row && selection.beg.row <= row + num)
1371           || (selection.end.row >= row
1372               && selection.end.row <= row + num)))
1373     CLEAR_SELECTION ();
1374
1375   if (row >= TermWin.nrow) /* Out Of Bounds */
1376     return;
1377
1378   MIN_IT (num, (TermWin.nrow - row));
1379
1380   if (rstyle & (RS_RVid | RS_Uline))
1381     ren = (rend_t) ~RS_None;
1382   else if (GET_BASEBG (rstyle) == Color_bg)
1383     {
1384       ren = DEFAULT_RSTYLE;
1385       CLEAR_ROWS (row, num);
1386     }
1387   else
1388     {
1389       ren = rstyle & (RS_fgMask | RS_bgMask);
1390       gcvalue.foreground = pix_colors[GET_BGCOLOR (rstyle)];
1391       XChangeGC (display->display, TermWin.gc, GCForeground, &gcvalue);
1392       ERASE_ROWS (row, num);
1393       gcvalue.foreground = pix_colors[Color_fg];
1394       XChangeGC (display->display, TermWin.gc, GCForeground, &gcvalue);
1395     }
1396
1397   for (; num--; row++)
1398     {
1399       scr_blank_screen_mem (screen.text, screen.rend, (unsigned int) (row + row_offset), rstyle);
1400       screen.tlen[row + row_offset] = 0;
1401       scr_blank_line (drawn_text[row], drawn_rend[row], (unsigned int)TermWin.ncol, ren);
1402     }
1403 }
1404
1405 /* ------------------------------------------------------------------------- */
1406 /*
1407  * Fill the screen with `E's
1408  * XTERM_SEQ: Screen Alignment Test: ESC # 8
1409  */
1410 void
1411 rxvt_term::scr_E ()
1412 {
1413   int             i, j, k;
1414   rend_t         *r1, fs;
1415
1416   want_refresh = 1;
1417   ZERO_SCROLLBACK ();
1418
1419   num_scr_allow = 0;
1420   selection_check (3);
1421
1422   fs = SET_FONT (rstyle, FONTSET (rstyle)->find_font ('E'));
1423   for (k = TermWin.saveLines, i = TermWin.nrow; i--; k++)
1424     {
1425       screen.tlen[k] = TermWin.ncol;    /* make the `E's selectable */
1426       fill_text (screen.text[k], 'E', TermWin.ncol);
1427       for (r1 = screen.rend[k], j = TermWin.ncol; j--; )
1428         *r1++ = fs;
1429     }
1430 }
1431
1432 /* ------------------------------------------------------------------------- */
1433 /*
1434  * Insert/Delete <count> lines
1435  */
1436 void
1437 rxvt_term::scr_insdel_lines (int count, int insdel)
1438 {
1439   int end;
1440
1441   ZERO_SCROLLBACK ();
1442
1443   selection_check (1);
1444
1445   if (screen.cur.row > screen.bscroll)
1446     return;
1447
1448   end = screen.bscroll - screen.cur.row + 1;
1449   if (count > end)
1450     {
1451       if (insdel == DELETE)
1452         return;
1453       else if (insdel == INSERT)
1454         count = end;
1455     }
1456
1457   scr_do_wrap ();
1458
1459   scr_scroll_text (screen.cur.row, screen.bscroll, insdel * count, 0);
1460 }
1461
1462 /* ------------------------------------------------------------------------- */
1463 /*
1464  * Insert/Delete <count> characters from the current position
1465  */
1466 void
1467 rxvt_term::scr_insdel_chars (int count, int insdel)
1468 {
1469   int col, row;
1470   rend_t tr;
1471   text_t *stp;
1472   rend_t *srp;
1473   int16_t *slp;
1474
1475   want_refresh = 1;
1476   ZERO_SCROLLBACK ();
1477
1478   if (count <= 0)
1479     return;
1480
1481   scr_do_wrap ();
1482
1483   selection_check (1);
1484   MIN_IT (count, (TermWin.ncol - screen.cur.col));
1485
1486   row = screen.cur.row + TermWin.saveLines;
1487
1488   stp = screen.text[row];
1489   srp = screen.rend[row];
1490   slp = &screen.tlen[row];
1491
1492   switch (insdel)
1493     {
1494       case INSERT:
1495         for (col = TermWin.ncol - 1; (col - count) >= screen.cur.col; col--)
1496           {
1497             stp[col] = stp[col - count];
1498             srp[col] = srp[col - count];
1499           }
1500
1501         if (*slp != -1)
1502           {
1503             *slp += count;
1504             MIN_IT (*slp, TermWin.ncol);
1505           }
1506
1507         if (selection.op && current_screen == selection.screen
1508             && ROWCOL_IN_ROW_AT_OR_AFTER (selection.beg, screen.cur))
1509           {
1510             if (selection.end.row != screen.cur.row
1511                 || (selection.end.col + count >= TermWin.ncol))
1512               CLEAR_SELECTION ();
1513             else
1514               {              /* shift selection */
1515                 selection.beg.col  += count;
1516                 selection.mark.col += count; /* XXX: yes? */
1517                 selection.end.col  += count;
1518               }
1519           }
1520
1521         scr_blank_line (&stp[screen.cur.col], &srp[screen.cur.col],
1522                         (unsigned int)count, rstyle);
1523         break;
1524
1525       case ERASE:
1526         screen.cur.col += count;     /* don't worry if > TermWin.ncol */
1527         selection_check (1);
1528         screen.cur.col -= count;
1529         scr_blank_line (&stp[screen.cur.col], &srp[screen.cur.col],
1530                         (unsigned int)count, rstyle);
1531         break;
1532
1533       case DELETE:
1534         tr = srp[TermWin.ncol - 1] & (RS_fgMask | RS_bgMask | RS_baseattrMask);
1535
1536         for (col = screen.cur.col; (col + count) < TermWin.ncol; col++)
1537           {
1538             stp[col] = stp[col + count];
1539             srp[col] = srp[col + count];
1540           }
1541
1542         scr_blank_line (&stp[TermWin.ncol - count], &srp[TermWin.ncol - count],
1543                         (unsigned int)count, tr);
1544
1545         if (*slp == -1) /* break line continuation */
1546           *slp = TermWin.ncol;
1547         
1548         *slp -= count;
1549         MAX_IT (*slp, 0);
1550
1551         if (selection.op && current_screen == selection.screen
1552             && ROWCOL_IN_ROW_AT_OR_AFTER (selection.beg, screen.cur))
1553           {
1554             if (selection.end.row != screen.cur.row
1555                 || (screen.cur.col >= selection.beg.col - count)
1556                 || selection.end.col >= TermWin.ncol)
1557               CLEAR_SELECTION ();
1558             else
1559               {
1560                 /* shift selection */
1561                 selection.beg.col  -= count;
1562                 selection.mark.col -= count; /* XXX: yes? */
1563                 selection.end.col  -= count;
1564               }
1565           }
1566
1567         break;
1568     }
1569 }
1570
1571 /* ------------------------------------------------------------------------- */
1572 /*
1573  * Set the scrolling region
1574  * XTERM_SEQ: Set region <top> - <bot> inclusive: ESC [ <top> ; <bot> r
1575  */
1576 void
1577 rxvt_term::scr_scroll_region (int top, int bot)
1578 {
1579   MAX_IT (top, 0);
1580   MIN_IT (bot, (int)TermWin.nrow - 1);
1581
1582   if (top > bot)
1583     return;
1584
1585   screen.tscroll = top;
1586   screen.bscroll = bot;
1587   scr_gotorc (0, 0, 0);
1588 }
1589
1590 /* ------------------------------------------------------------------------- */
1591 /*
1592  * Make the cursor visible/invisible
1593  * XTERM_SEQ: Make cursor visible  : ESC [ ? 25 h
1594  * XTERM_SEQ: Make cursor invisible: ESC [ ? 25 l
1595  */
1596 void
1597 rxvt_term::scr_cursor_visible (int mode)
1598 {
1599   want_refresh = 1;
1600
1601   if (mode)
1602     screen.flags |= Screen_VisibleCursor;
1603   else
1604     screen.flags &= ~Screen_VisibleCursor;
1605 }
1606
1607 /* ------------------------------------------------------------------------- */
1608 /*
1609  * Set/unset automatic wrapping
1610  * XTERM_SEQ: Set Wraparound  : ESC [ ? 7 h
1611  * XTERM_SEQ: Unset Wraparound: ESC [ ? 7 l
1612  */
1613 void
1614 rxvt_term::scr_autowrap (int mode)
1615 {
1616   if (mode)
1617     screen.flags |= Screen_Autowrap;
1618   else
1619     screen.flags &= ~(Screen_Autowrap | Screen_WrapNext);
1620 }
1621
1622 /* ------------------------------------------------------------------------- */
1623 /*
1624  * Set/unset margin origin mode
1625  * Absolute mode: line numbers are counted relative to top margin of screen
1626  *      and the cursor can be moved outside the scrolling region.
1627  * Relative mode: line numbers are relative to top margin of scrolling region
1628  *      and the cursor cannot be moved outside.
1629  * XTERM_SEQ: Set Absolute: ESC [ ? 6 h
1630  * XTERM_SEQ: Set Relative: ESC [ ? 6 l
1631  */
1632 void
1633 rxvt_term::scr_relative_origin (int mode)
1634 {
1635   if (mode)
1636     screen.flags |= Screen_Relative;
1637   else
1638     screen.flags &= ~Screen_Relative;
1639
1640   scr_gotorc (0, 0, 0);
1641 }
1642
1643 /* ------------------------------------------------------------------------- */
1644 /*
1645  * Set insert/replace mode
1646  * XTERM_SEQ: Set Insert mode : ESC [ ? 4 h
1647  * XTERM_SEQ: Set Replace mode: ESC [ ? 4 l
1648  */
1649 void
1650 rxvt_term::scr_insert_mode (int mode)
1651 {
1652   if (mode)
1653     screen.flags |= Screen_Insert;
1654   else
1655     screen.flags &= ~Screen_Insert;
1656 }
1657
1658 /* ------------------------------------------------------------------------- */
1659 /*
1660  * Set/Unset tabs
1661  * XTERM_SEQ: Set tab at current column  : ESC H
1662  * XTERM_SEQ: Clear tab at current column: ESC [ 0 g
1663  * XTERM_SEQ: Clear all tabs             : ESC [ 3 g
1664  */
1665 void
1666 rxvt_term::scr_set_tab (int mode)
1667 {
1668   if (mode < 0)
1669     memset (tabs, 0, TermWin.ncol * sizeof (char));
1670   else if (screen.cur.col < TermWin.ncol)
1671     tabs[screen.cur.col] = (mode ? 1 : 0);
1672 }
1673
1674 /* ------------------------------------------------------------------------- */
1675 /*
1676  * Set reverse/normal video
1677  * XTERM_SEQ: Reverse video: ESC [ ? 5 h
1678  * XTERM_SEQ: Normal video : ESC [ ? 5 l
1679  */
1680 void
1681 rxvt_term::scr_rvideo_mode (int mode)
1682 {
1683   XGCValues gcvalue;
1684
1685   if (rvideo != mode)
1686     {
1687       rvideo = mode;
1688       SWAP_IT (pix_colors[Color_fg], pix_colors[Color_bg], rxvt_color);
1689 #if XPM_BACKGROUND
1690       if (bgPixmap.pixmap == None)
1691 #endif
1692 #if TRANSPARENT
1693         if (! (options & Opt_transparent) || am_transparent == 0)
1694 #endif
1695           XSetWindowBackground (display->display, TermWin.vt,
1696                                pix_colors[Color_bg]);
1697
1698       gcvalue.foreground = pix_colors[Color_fg];
1699       gcvalue.background = pix_colors[Color_bg];
1700       XChangeGC (display->display, TermWin.gc, GCBackground | GCForeground,
1701                 &gcvalue);
1702       scr_clear ();
1703       scr_touch (true);
1704     }
1705 }
1706
1707 /* ------------------------------------------------------------------------- */
1708 /*
1709  * Report current cursor position
1710  * XTERM_SEQ: Report position: ESC [ 6 n
1711  */
1712 void
1713 rxvt_term::scr_report_position ()
1714 {
1715   tt_printf ("\033[%d;%dR", screen.cur.row + 1, screen.cur.col + 1);
1716 }
1717 \f
1718 /* ------------------------------------------------------------------------- *
1719  *                                  FONTS                                    *
1720  * ------------------------------------------------------------------------- */
1721
1722 /*
1723  * Set font style
1724  */
1725 void
1726 rxvt_term::set_font_style ()
1727 {
1728   switch (charsets[screen.charset])
1729     {
1730       case '0':                   /* DEC Special Character & Line Drawing Set */
1731         break;
1732       case 'A':                   /* United Kingdom (UK) */
1733         break;
1734       case 'B':                   /* United States (USASCII) */
1735         break;
1736       case '<':                   /* Multinational character set */
1737         break;
1738       case '5':                   /* Finnish character set */
1739         break;
1740       case 'C':                   /* Finnish character set */
1741         break;
1742       case 'K':                   /* German character set */
1743         break;
1744     }
1745 }
1746
1747 /* ------------------------------------------------------------------------- */
1748 /*
1749  * Choose a font
1750  * XTERM_SEQ: Invoke G0 character set: CTRL-O
1751  * XTERM_SEQ: Invoke G1 character set: CTRL-N
1752  * XTERM_SEQ: Invoke G2 character set: ESC N
1753  * XTERM_SEQ: Invoke G3 character set: ESC O
1754  */
1755 void
1756 rxvt_term::scr_charset_choose (int set)
1757 {
1758   screen.charset = set;
1759   set_font_style ();
1760 }
1761
1762 /* ------------------------------------------------------------------------- */
1763 /*
1764  * Set a font
1765  * XTERM_SEQ: Set G0 character set: ESC ( <C>
1766  * XTERM_SEQ: Set G1 character set: ESC ) <C>
1767  * XTERM_SEQ: Set G2 character set: ESC * <C>
1768  * XTERM_SEQ: Set G3 character set: ESC + <C>
1769  * See set_font_style for possible values for <C>
1770  */
1771 void
1772 rxvt_term::scr_charset_set (int set, unsigned int ch)
1773 {
1774   charsets[set] = (unsigned char)ch;
1775   set_font_style ();
1776 }
1777
1778 \f
1779 /* ------------------------------------------------------------------------- *
1780  *                        MAJOR SCREEN MANIPULATION                          *
1781  * ------------------------------------------------------------------------- */
1782
1783 /*
1784  * refresh matching text.
1785  */
1786 bool
1787 rxvt_term::scr_refresh_rend (rend_t mask, rend_t value)
1788 {
1789   bool found = false;
1790
1791   for (int i = 0; i < TermWin.nrow; i++)
1792     {
1793       int col = 0;
1794       rend_t *drp = drawn_rend [i];
1795
1796       for (; col < TermWin.ncol; col++, drp++)
1797         if ((*drp & mask) == value)
1798           {
1799             found = true;
1800             *drp = ~value;
1801           }
1802     }
1803
1804   return found;
1805 }
1806
1807 /*
1808  * Refresh an area
1809  */
1810 enum {
1811   PART_BEG = 0,
1812   PART_END,
1813   RC_COUNT
1814 };
1815
1816 void
1817 rxvt_term::scr_expose (int x, int y, int width, int height, bool refresh)
1818 {
1819   int i;
1820   row_col_t rc[RC_COUNT];
1821
1822   if (drawn_text == NULL)  /* sanity check */
1823     return;
1824
1825 #ifndef NO_SLOW_LINK_SUPPORT
1826   if (refresh_type == FAST_REFRESH && !display->is_local)
1827     {
1828       y = 0;
1829       height = TermWin.height;
1830     }
1831 #endif
1832
1833 #ifdef DEBUG_STRICT
1834   x = max (x, 0);
1835   x = min (x, (int)TermWin.width);
1836   y = max (y, 0);
1837   y = min (y, (int)TermWin.height);
1838 #endif
1839
1840   /* round down */
1841   rc[PART_BEG].col = Pixel2Col (x);
1842   rc[PART_BEG].row = Pixel2Row (y);
1843   /* round up */
1844   rc[PART_END].col = Pixel2Width (x + width + TermWin.fwidth - 1);
1845   rc[PART_END].row = Pixel2Row (y + height + TermWin.fheight - 1);
1846
1847   /* sanity checks */
1848   for (i = PART_BEG; i < RC_COUNT; i++)
1849     {
1850       MIN_IT (rc[i].col, TermWin.ncol - 1);
1851       MIN_IT (rc[i].row, TermWin.nrow - 1);
1852     }
1853
1854   for (i = rc[PART_BEG].row; i <= rc[PART_END].row; i++)
1855     fill_text (&drawn_text[i][rc[PART_BEG].col], 0, rc[PART_END].col - rc[PART_BEG].col + 1);
1856
1857   if (refresh)
1858     scr_refresh (SLOW_REFRESH);
1859 }
1860
1861 /* ------------------------------------------------------------------------- */
1862 /*
1863  * Refresh the entire screen
1864  */
1865 void
1866 rxvt_term::scr_touch (bool refresh)
1867 {
1868   scr_expose (0, 0, TermWin.width, TermWin.height, refresh);
1869 }
1870
1871 /* ------------------------------------------------------------------------- */
1872 /*
1873  * Move the display so that the line represented by scrollbar value Y is at
1874  * the top of the screen
1875  */
1876 int
1877 rxvt_term::scr_move_to (int y, int len)
1878 {
1879   long p = 0;
1880   unsigned int oldviewstart;
1881
1882   oldviewstart = TermWin.view_start;
1883
1884   if (y < len)
1885     {
1886       p = (TermWin.nrow + TermWin.nscrolled) * (len - y) / len;
1887       p -= (long) (TermWin.nrow - 1);
1888       p = max (p, 0);
1889     }
1890
1891   TermWin.view_start = (unsigned int)min (p, TermWin.nscrolled);
1892
1893   return scr_changeview (oldviewstart);
1894 }
1895
1896 /* ------------------------------------------------------------------------- */
1897 /*
1898  * Page the screen up/down nlines
1899  * direction should be UP or DN
1900  */
1901 int
1902 rxvt_term::scr_page (enum page_dirn direction, int nlines)
1903 {
1904   int n;
1905   unsigned int oldviewstart;
1906
1907 #ifdef DEBUG_STRICT
1908   assert ((nlines >= 0) && (nlines <= TermWin.nrow));
1909 #endif
1910   oldviewstart = TermWin.view_start;
1911   if (direction == UP)
1912     {
1913       n = TermWin.view_start + nlines;
1914       TermWin.view_start = min (n, TermWin.nscrolled);
1915     }
1916   else
1917     {
1918       n = TermWin.view_start - nlines;
1919       TermWin.view_start = max (n, 0);
1920     }
1921   return scr_changeview (oldviewstart);
1922 }
1923
1924 int
1925 rxvt_term::scr_changeview (unsigned int oldviewstart)
1926 {
1927   if (TermWin.view_start != oldviewstart)
1928     {
1929       want_refresh = 1;
1930       num_scr -= (TermWin.view_start - oldviewstart);
1931     }
1932
1933   return (int) (TermWin.view_start - oldviewstart);
1934 }
1935
1936 /* ------------------------------------------------------------------------- */
1937 void
1938 rxvt_term::scr_bell ()
1939 {
1940 #ifndef NO_BELL
1941 # ifndef NO_MAPALERT
1942 #  ifdef MAPALERT_OPTION
1943   if (options & Opt_mapAlert)
1944 #  endif
1945     XMapWindow (display->display, TermWin.parent[0]);
1946 # endif
1947   if (options & Opt_visualBell)
1948     {
1949       scr_rvideo_mode (!rvideo); /* refresh also done */
1950       scr_rvideo_mode (!rvideo); /* refresh also done */
1951     }
1952   else
1953     XBell (display->display, 0);
1954 #endif
1955 }
1956
1957 /* ------------------------------------------------------------------------- */
1958 /* ARGSUSED */
1959 void
1960 rxvt_term::scr_printscreen (int fullhist)
1961 {
1962 #ifdef PRINTPIPE
1963   int i, r1, nrows, row_offset;
1964   FILE *fd;
1965
1966   if ((fd = popen_printer ()) == NULL)
1967     return;
1968
1969   nrows = TermWin.nrow;
1970   row_offset = TermWin.saveLines;
1971
1972   if (!fullhist)
1973     row_offset -= TermWin.view_start;
1974   else
1975     {
1976       nrows += TermWin.nscrolled;
1977       row_offset -= TermWin.nscrolled;
1978     }
1979
1980   wctomb (0, 0);
1981
1982   for (r1 = 0; r1 < nrows; r1++)
1983     {
1984       text_t *tp = screen.text[r1 + row_offset];
1985       int len = screen.tlen[r1 + row_offset];
1986
1987       for (i = len >= 0 ? len : TermWin.ncol - 1; i--; )
1988         {
1989           char mb[MB_LEN_MAX];
1990           text_t t = *tp++;
1991           if (t == NOCHAR)
1992             continue;
1993
1994           len = wctomb (mb, t);
1995
1996           if (len <= 0)
1997             {
1998               mb[0] = ' ';
1999               len = 1;
2000             }
2001
2002           fwrite (mb, 1, len, fd);
2003         }
2004
2005       fputc ('\n', fd);
2006     }
2007
2008   pclose_printer (fd);
2009 #endif
2010 }
2011
2012 /* ------------------------------------------------------------------------- */
2013 /*
2014  * Refresh the screen
2015  * drawn_text/drawn_rend contain the screen information before the update.
2016  * screen.text/screen.rend contain what the screen will change to.
2017  */
2018
2019 #define FONT_WIDTH(X, Y)                                                \
2020     (X)->per_char[ (Y) - (X)->min_char_or_byte2].width
2021 #define FONT_RBEAR(X, Y)                                                \
2022     (X)->per_char[ (Y) - (X)->min_char_or_byte2].rbearing
2023 #define FONT_LBEAR(X, Y)                                                \
2024     (X)->per_char[ (Y) - (X)->min_char_or_byte2].lbearing
2025 #define IS_FONT_CHAR(X, Y)                                              \
2026     ((Y) >= (X)->min_char_or_byte2 && (Y) <= (X)->max_char_or_byte2)
2027
2028 void
2029 rxvt_term::scr_refresh (unsigned char refresh_type)
2030 {
2031   unsigned char must_clear, /* use draw_string not draw_image_string     */
2032                 showcursor; /* show the cursor                           */
2033   int16_t col, row,   /* column/row we're processing               */
2034           ocrow;      /* old cursor row                            */
2035   int i,              /* tmp                                       */
2036   row_offset;         /* basic offset in screen structure          */
2037 #ifndef NO_CURSORCOLOR
2038   rend_t cc1;         /* store colours at cursor position (s)      */
2039 #endif
2040   rend_t *crp;        // cursor rendition pointer
2041
2042   want_refresh = 0;        /* screen is current */
2043
2044   if (refresh_type == NO_REFRESH || !TermWin.mapped)
2045     return;
2046
2047   /*
2048    * A: set up vars
2049    */
2050   must_clear = 0;
2051   refresh_count = 0;
2052
2053   row_offset = TermWin.saveLines - TermWin.view_start;
2054
2055 #if XPM_BACKGROUND
2056   must_clear |= (bgPixmap.pixmap != None);
2057 #endif
2058 #if TRANSPARENT
2059   must_clear |= ((options & Opt_transparent) && am_transparent);
2060 #endif
2061   ocrow = oldcursor.row; /* is there an old outline cursor on screen? */
2062
2063   /*
2064    * B: reverse any characters which are selected
2065    */
2066   scr_reverse_selection ();
2067
2068   /*
2069    * C: set the cursor character (s)
2070    */
2071   {
2072     unsigned char setoldcursor;
2073     rend_t ccol1,  /* Cursor colour       */
2074            ccol2;  /* Cursor colour2      */
2075
2076     showcursor = (screen.flags & Screen_VisibleCursor);
2077 #ifdef CURSOR_BLINK
2078     if (hidden_cursor)
2079       showcursor = 0;
2080 #endif
2081
2082     if (showcursor)
2083       {
2084         int col = screen.cur.col;
2085
2086         while (col && screen.text[screen.cur.row + TermWin.saveLines][col] == NOCHAR)
2087           col--;
2088
2089         crp = &screen.rend[screen.cur.row + TermWin.saveLines][col];
2090
2091         if (showcursor && TermWin.focus)
2092           {
2093             *crp ^= RS_RVid;
2094 #ifndef NO_CURSORCOLOR
2095             cc1 = *crp & (RS_fgMask | RS_bgMask);
2096             if (ISSET_PIXCOLOR (Color_cursor))
2097               ccol1 = Color_cursor;
2098             else
2099 #ifdef CURSOR_COLOR_IS_RENDITION_COLOR
2100               ccol1 = GET_FGCOLOR (rstyle);
2101 #else
2102               ccol1 = Color_fg;
2103 #endif
2104             if (ISSET_PIXCOLOR (Color_cursor2))
2105               ccol2 = Color_cursor2;
2106             else
2107 #ifdef CURSOR_COLOR_IS_RENDITION_COLOR
2108               ccol2 = GET_BGCOLOR (rstyle);
2109 #else
2110               ccol2 = Color_bg;
2111 #endif
2112             *crp = SET_FGCOLOR (*crp, ccol1);
2113             *crp = SET_BGCOLOR (*crp, ccol2);
2114 #endif
2115           }
2116       }
2117
2118     /* make sure no outline cursor is left around */
2119     setoldcursor = 0;
2120     if (ocrow != -1)
2121       {
2122         if (screen.cur.row + TermWin.view_start != ocrow
2123             || screen.cur.col != oldcursor.col)
2124           {
2125             if (ocrow < TermWin.nrow
2126                 && oldcursor.col < TermWin.ncol)
2127               drawn_rend[ocrow][oldcursor.col] ^= (RS_RVid | RS_Uline);
2128
2129             if (TermWin.focus || !showcursor)
2130               oldcursor.row = -1;
2131             else
2132               setoldcursor = 1;
2133           }
2134       }
2135     else if (!TermWin.focus)
2136       setoldcursor = 1;
2137
2138     if (setoldcursor)
2139       {
2140         if (screen.cur.row + TermWin.view_start >= TermWin.nrow)
2141           oldcursor.row = -1;
2142         else
2143           {
2144             oldcursor.row = screen.cur.row + TermWin.view_start;
2145             oldcursor.col = screen.cur.col;
2146           }
2147       }
2148   }
2149
2150 #if ENABLE_OVERLAY
2151   scr_swap_overlay ();
2152 #endif
2153
2154   rend_t *drp, *srp;  /* drawn-rend-pointer, screen-rend-pointer   */
2155   text_t *dtp, *stp;  /* drawn-text-pointer, screen-text-pointer   */
2156
2157 #ifndef NO_SLOW_LINK_SUPPORT
2158   /*
2159    * D: CopyArea pass - very useful for slower links
2160    *    This has been deliberately kept simple.
2161    */
2162   i = num_scr;
2163   if (!display->is_local
2164       && refresh_type == FAST_REFRESH && num_scr_allow && i
2165       && abs (i) < TermWin.nrow && !must_clear)
2166     {
2167       int16_t nits;
2168       int j;
2169       int len, wlen;
2170
2171       j = TermWin.nrow;
2172       wlen = len = -1;
2173       row = i > 0 ? 0 : j - 1;
2174       for (; j-- >= 0; row += (i > 0 ? 1 : -1))
2175         {
2176           if (row + i >= 0 && row + i < TermWin.nrow && row + i != ocrow)
2177             {
2178               text_t *stp  = screen.text[row + row_offset];
2179               rend_t *srp  = screen.rend[row + row_offset];
2180               text_t *dtp  = drawn_text[row];
2181               text_t *dtp2 = drawn_text[row + i];
2182               rend_t *drp  = drawn_rend[row];
2183               rend_t *drp2 = drawn_rend[row + i];
2184
2185               for (nits = 0, col = TermWin.ncol; col--; )
2186                 if (stp[col] != dtp2[col] || srp[col] != drp2[col])
2187                   nits--;
2188                 else if (stp[col] != dtp[col] || srp[col] != drp[col])
2189                   nits++;
2190
2191               if (nits > 8) /* XXX: arbitrary choice */
2192                 {
2193                   for (col = TermWin.ncol; col--; )
2194                     {
2195                       *dtp++ = *dtp2++;
2196                       *drp++ = *drp2++;
2197                     }
2198
2199                   if (len == -1)
2200                     len = row;
2201
2202                   wlen = row;
2203                   continue;
2204                 }
2205             }
2206
2207           if (len != -1)
2208             {
2209               /* also comes here at end if needed because of >= above */
2210               if (wlen < len)
2211                 SWAP_IT (wlen, len, int);
2212
2213               XCopyArea (display->display, TermWin.vt, TermWin.vt,
2214                          TermWin.gc, 0, Row2Pixel (len + i),
2215                          (unsigned int)TermWin_TotalWidth (),
2216                          (unsigned int)Height2Pixel (wlen - len + 1),
2217                          0, Row2Pixel (len));
2218               len = -1;
2219             }
2220         }
2221     }
2222 #endif
2223
2224   /*
2225    * E: main pass across every character
2226    */
2227   for (row = 0; row < TermWin.nrow; row++)
2228     {
2229       text_t *stp = screen.text[row + row_offset];
2230       rend_t *srp = screen.rend[row + row_offset];
2231       text_t *dtp = drawn_text[row];
2232       rend_t *drp = drawn_rend[row];
2233
2234       /*
2235        * E2: OK, now the real pass
2236        */
2237       int ypixel = (int)Row2Pixel (row);
2238
2239       for (col = 0; col < TermWin.ncol; col++)
2240         {
2241           /* compare new text with old - if exactly the same then continue */
2242           if (stp[col] == dtp[col]    /* Must match characters to skip. */
2243               && (RS_SAME (srp[col], drp[col])    /* Either rendition the same or   */
2244                   || (stp[col] == ' ' /* space w/ no background change  */
2245                       && GET_BGATTR (srp[col]) == GET_BGATTR (drp[col]))))
2246             continue;
2247
2248           // redraw one or more characters
2249
2250           // seek to the beginning of wide characters
2251           while (stp[col] == NOCHAR && col > 0)
2252             --col;
2253
2254           rend_t rend = srp[col];     /* screen rendition (target rendtion) */
2255           text_t *text = stp + col;
2256           int count = 1;
2257
2258           dtp[col] = stp[col];
2259           drp[col] = rend;
2260
2261           int xpixel = Col2Pixel (col);
2262
2263           for (i = 0; ++col < TermWin.ncol; )
2264             {
2265               if (stp[col] == NOCHAR)
2266                 {
2267                   dtp[col] = stp[col];
2268                   drp[col] = rend;
2269                   count++;
2270                   i++;
2271
2272                   continue;
2273                 }
2274
2275               if (!RS_SAME (rend, srp[col]))
2276                 break;
2277
2278               count++;
2279
2280               if (stp[col] != dtp[col]
2281                   || !RS_SAME (srp[col], drp[col]))
2282                 {
2283                   if (must_clear && (i++ > count / 2))
2284                     break;
2285
2286                   dtp[col] = stp[col];
2287                   drp[col] = rend;
2288                   i = 0;
2289                 }
2290               else if (must_clear || (stp[col] != ' ' && ++i >= 16))
2291                 break;
2292             }
2293
2294           col--;      /* went one too far.  move back */
2295           count -= i; /* dump any matching trailing chars */
2296
2297           // sometimes we optimize away the trailing NOCHAR's, add them back
2298           while (i && text[count] == NOCHAR)
2299             count++, i--;
2300
2301 #if ENABLE_STYLES
2302           // force redraw after "careful" characters to avoid pixel droppings
2303           if (srp[col] & RS_Careful && col < TermWin.ncol - 1 && 0)
2304             drp[col + 1] = ~srp[col + 1];
2305
2306           // include previous careful character(s) if possible, looks nicer (best effort...)
2307           while (text > stp
2308               && srp[text - stp - 1] & RS_Careful
2309               && RS_SAME (rend, srp[text - stp - 1]))
2310             text--, count++, xpixel -= TermWin.fwidth;
2311 #endif
2312
2313           /*
2314            * Determine the attributes for the string
2315            */
2316           int fore = GET_FGCOLOR (rend); // desired foreground
2317           int back = GET_BGCOLOR (rend); // desired background
2318
2319           // only do special processing if ana attributes are set, which is rare
2320           if (rend & (RS_Bold | RS_Italic | RS_Uline | RS_RVid | RS_Blink))
2321             {
2322               bool invert = rend & RS_RVid;
2323
2324 #ifndef NO_BOLD_UNDERLINE_REVERSE
2325               if (rend & RS_Bold
2326                   && fore == Color_fg)
2327                 {
2328                   if (ISSET_PIXCOLOR (Color_BD))
2329                     fore = Color_BD;
2330 # if !ENABLE_STYLES
2331                   else
2332                     invert = !invert;
2333 # endif
2334                 }
2335
2336               if (rend & RS_Italic
2337                   && fore == Color_fg)
2338                 {
2339                   if (ISSET_PIXCOLOR (Color_IT))
2340                     fore = Color_IT;
2341 # if !ENABLE_STYLES
2342                   else
2343                     invert = !invert;
2344 # endif
2345                 }
2346
2347               if (rend & RS_Uline && ISSET_PIXCOLOR (Color_UL))
2348                 fore = Color_UL;
2349 #endif
2350
2351               if (invert)
2352                 {
2353                   SWAP_IT (fore, back, int);
2354
2355 #ifndef NO_BOLD_UNDERLINE_REVERSE
2356                   if (ISSET_PIXCOLOR (Color_RV))
2357                     back = Color_RV;
2358 #endif
2359                 }
2360
2361 #ifdef TEXT_BLINK
2362               if (rend & RS_Blink && (back == Color_bg || fore == Color_bg))
2363                 {
2364                   if (!text_blink_ev.active)
2365                     {
2366                       text_blink_ev.start (NOW + TEXT_BLINK_INTERVAL);
2367                       hidden_text = 0;
2368                     }
2369                   else if (hidden_text)
2370                     fore = back;
2371                 }
2372 #endif
2373             }
2374
2375           /*
2376            * Actually do the drawing of the string here
2377            */
2378           rxvt_font *font = (*TermWin.fontset[GET_STYLE (rend)])[GET_FONT (rend)];
2379
2380           if (back == fore)
2381             font->clear_rect (*TermWin.drawable, xpixel, ypixel,
2382                               TermWin.fwidth * count, TermWin.fheight,
2383                               back);
2384           else if (back == Color_bg)
2385             {
2386               if (must_clear)
2387                 {
2388                   CLEAR_CHARS (xpixel, ypixel, count);
2389
2390                   for (i = 0; i < count; i++) /* don't draw empty strings */
2391                     if (text[i] != ' ')
2392                       {
2393                         font->draw (*TermWin.drawable, xpixel, ypixel, text, count, fore, -1);
2394                         break;
2395                       }
2396                 }
2397               else
2398                 font->draw (*TermWin.drawable, xpixel, ypixel, text, count, fore, Color_bg);
2399             }
2400           else
2401             font->draw (*TermWin.drawable, xpixel, ypixel, text, count, fore, back);
2402
2403           if (rend & RS_Uline && font->descent > 1 && fore != back)
2404             {
2405               XSetForeground (display->display, TermWin.gc, pix_colors[fore]);
2406               XDrawLine (display->display, drawBuffer, TermWin.gc,
2407                          xpixel, ypixel + font->ascent + 1,
2408                          xpixel + Width2Pixel (count) - 1, ypixel + font->ascent + 1);
2409             }
2410         }                     /* for (col....) */
2411     }                         /* for (row....) */
2412
2413 #if ENABLE_OVERLAY
2414   scr_swap_overlay ();
2415 #endif
2416
2417   /*
2418    * G: cleanup cursor and display outline cursor if necessary
2419    */
2420   if (showcursor)
2421     {
2422       if (TermWin.focus)
2423         {
2424           *crp ^= RS_RVid;
2425 #ifndef NO_CURSORCOLOR
2426           *crp = (*crp & ~ (RS_fgMask | RS_bgMask)) | cc1;
2427 #endif
2428         }
2429       else if (oldcursor.row >= 0)
2430         {
2431 #ifndef NO_CURSORCOLOR
2432           if (ISSET_PIXCOLOR (Color_cursor))
2433             XSetForeground (display->display, TermWin.gc, pix_colors[Color_cursor]);
2434 #endif
2435           int cursorwidth = 1;
2436           while (oldcursor.col + cursorwidth < TermWin.ncol
2437                  && drawn_text[oldcursor.row][oldcursor.col + cursorwidth] == NOCHAR)
2438             cursorwidth++;
2439
2440           XDrawRectangle (display->display, drawBuffer, TermWin.gc,
2441                           Col2Pixel (oldcursor.col),
2442                           Row2Pixel (oldcursor.row),
2443                           (unsigned int) (Width2Pixel (cursorwidth) - 1),
2444                           (unsigned int) (Height2Pixel (1) - TermWin.lineSpace - 1));
2445         }
2446     }
2447
2448   /*
2449    * H: cleanup selection
2450    */
2451   scr_reverse_selection ();
2452
2453   if (refresh_type & SMOOTH_REFRESH)
2454     XFlush (display->display);
2455
2456   num_scr = 0;
2457   num_scr_allow = 1;
2458 }
2459
2460 void
2461 rxvt_term::scr_remap_chars (text_t *tp, rend_t *rp)
2462 {
2463   if (!rp || !tp)
2464     return;
2465
2466   for (int i = TermWin.ncol; i; i--, rp++, tp++)
2467     *rp = SET_FONT (*rp, FONTSET (*rp)->find_font (*tp));
2468 }
2469
2470 void
2471 rxvt_term::scr_remap_chars ()
2472 {
2473   for (int i = TermWin.nrow + TermWin.saveLines; i--; )
2474     scr_remap_chars (screen.text[i], screen.rend[i]);
2475
2476   for (int i = TermWin.nrow; i--; )
2477     {
2478       scr_remap_chars (drawn_text[i], drawn_rend[i]);
2479       scr_remap_chars (swap.text[i], swap.rend[i]);
2480     }
2481 }
2482
2483 void
2484 rxvt_term::scr_recolour ()
2485 {
2486   if (1
2487 #if TRANSPARENT
2488       && !am_transparent
2489 #endif
2490 #if XPM_BACKGROUND
2491       && !bgPixmap.pixmap
2492 #endif
2493       )
2494     {
2495       XSetWindowBackground (display->display, TermWin.parent[0], pix_colors[Color_border]);
2496       XClearWindow (display->display, TermWin.parent[0]);
2497       XSetWindowBackground (display->display, TermWin.vt, pix_colors[Color_bg]);
2498 #if HAVE_SCROLLBARS
2499       if (scrollBar.win)
2500         {
2501           XSetWindowBackground (display->display, scrollBar.win, pix_colors[Color_border]);
2502           scrollBar.setIdle ();
2503           scrollbar_show (0);
2504         }
2505 #endif
2506     }
2507
2508   scr_clear ();
2509   scr_touch (true);
2510   want_refresh = 1;
2511 }
2512
2513 /* ------------------------------------------------------------------------- */
2514 void
2515 rxvt_term::scr_clear (bool really)
2516 {
2517   if (!TermWin.mapped)
2518     return;
2519
2520   num_scr_allow = 0;
2521   want_refresh = 1;
2522
2523 #if TRANSPARENT
2524   if ((options & Opt_transparent) && (am_pixmap_trans == 0))
2525     {
2526       int i;
2527
2528       if (!(options & Opt_transparent_all))
2529         i = 0;
2530       else
2531         i = (int) (sizeof (TermWin.parent) / sizeof (Window));
2532
2533       while (i--)
2534         if (TermWin.parent[i] != None)
2535           XClearWindow (display->display, TermWin.parent[i]);
2536     }
2537 #endif
2538
2539   if (really)
2540     XClearWindow (display->display, TermWin.vt);
2541 }
2542
2543 /* ------------------------------------------------------------------------- */
2544 void
2545 rxvt_term::scr_reverse_selection ()
2546 {
2547   if (selection.op && current_screen == selection.screen)
2548     {
2549       int end_row = TermWin.saveLines - TermWin.view_start;
2550       int i = selection.beg.row + TermWin.saveLines;
2551       int col, row = selection.end.row + TermWin.saveLines;
2552       rend_t *srp;
2553
2554 #if ENABLE_FRILLS
2555       if (selection.rect)
2556         {
2557           end_row += TermWin.nrow;
2558
2559           for (; i <= row && i <= end_row; i++)
2560             for (srp = screen.rend[i], col = selection.beg.col; col < selection.end.col; col++)
2561               srp[col] ^= RS_RVid;
2562         }
2563       else
2564 #endif
2565         {
2566           if (i >= end_row)
2567             col = selection.beg.col;
2568           else
2569             {
2570               col = 0;
2571               i = end_row;
2572             }
2573
2574           end_row += TermWin.nrow;
2575
2576           for (; i < row && i < end_row; i++, col = 0)
2577             for (srp = screen.rend[i]; col < TermWin.ncol; col++)
2578               srp[col] ^= RS_RVid;
2579
2580           if (i == row && i < end_row)
2581             for (srp = screen.rend[i]; col < selection.end.col; col++)
2582               srp[col] ^= RS_RVid;
2583         }
2584     }
2585 }
2586
2587 /* ------------------------------------------------------------------------- */
2588 /*
2589  * Dump the whole scrollback and screen to the passed filedescriptor.  The
2590  * invoking routine must close the fd.
2591  */
2592 #if 0
2593 void
2594 rxvt_term::scr_dump (int fd)
2595 {
2596   int             row, wrote;
2597   unsigned int    width, towrite;
2598   char            r1[] = "\n";
2599
2600   for (row = TermWin.saveLines - TermWin.nscrolled;
2601        row < TermWin.saveLines + TermWin.nrow - 1; row++)
2602     {
2603       width = screen.tlen[row] >= 0 ? screen.tlen[row]
2604               : TermWin.ncol;
2605       for (towrite = width; towrite; towrite -= wrote)
2606         {
2607           wrote = write (fd, & (screen.text[row][width - towrite]),
2608                         towrite);
2609           if (wrote < 0)
2610             return;         /* XXX: death, no report */
2611         }
2612       if (screen.tlen[row] >= 0)
2613         if (write (fd, r1, 1) <= 0)
2614           return; /* XXX: death, no report */
2615     }
2616 }
2617 #endif
2618 \f
2619 /* ------------------------------------------------------------------------- *
2620  *                           CHARACTER SELECTION                             *
2621  * ------------------------------------------------------------------------- */
2622
2623 /*
2624  * -TermWin.nscrolled <= (selection row) <= TermWin.nrow - 1
2625  */
2626 void
2627 rxvt_term::selection_check (int check_more)
2628 {
2629   row_col_t pos;
2630
2631   if (!selection.op)
2632     return;
2633
2634   pos.row = pos.col = 0;
2635   if ((selection.beg.row < - (int32_t)TermWin.nscrolled)
2636       || (selection.beg.row >= TermWin.nrow)
2637       || (selection.mark.row < - (int32_t)TermWin.nscrolled)
2638       || (selection.mark.row >= TermWin.nrow)
2639       || (selection.end.row < - (int32_t)TermWin.nscrolled)
2640       || (selection.end.row >= TermWin.nrow)
2641       || (check_more == 1
2642           && current_screen == selection.screen
2643           && !ROWCOL_IS_BEFORE (screen.cur, selection.beg)
2644           && ROWCOL_IS_BEFORE (screen.cur, selection.end))
2645       || (check_more == 2
2646           && ROWCOL_IS_BEFORE (selection.beg, pos)
2647           && ROWCOL_IS_AFTER (selection.end, pos))
2648       || (check_more == 3
2649           && ROWCOL_IS_AFTER (selection.end, pos))
2650       || (check_more == 4     /* screen width change */
2651           && (selection.beg.row != selection.end.row
2652               || selection.end.col > TermWin.ncol)))
2653     CLEAR_SELECTION ();
2654 }
2655
2656 /* ------------------------------------------------------------------------- */
2657 /*
2658  * Paste a selection direct to the command fd
2659  */
2660 void
2661 rxvt_term::paste (const unsigned char *data, unsigned int len)
2662 {
2663   unsigned int i, j, n;
2664   unsigned char *ds = (unsigned char *)rxvt_malloc (PROP_SIZE);
2665
2666   /* convert normal newline chars into common keyboard Return key sequence */
2667   for (i = 0; i < len; i += PROP_SIZE)
2668     {
2669       n = min (len - i, PROP_SIZE);
2670       memcpy (ds, data + i, n);
2671
2672       for (j = 0; j < n; j++)
2673         if (ds[j] == C0_LF)
2674           ds[j] = C0_CR;
2675
2676       tt_write (ds, (int)n);
2677     }
2678
2679   free (ds);
2680 }
2681
2682 /* ------------------------------------------------------------------------- */
2683 /*
2684  * Respond to a notification that a primary selection has been sent
2685  * EXT: SelectionNotify
2686  */
2687 int
2688 rxvt_term::selection_paste (Window win, Atom prop, bool delete_prop)
2689 {
2690   long nread = 0;
2691   unsigned long bytes_after;
2692   XTextProperty ct;
2693
2694   if (prop == None)         /* check for failed XConvertSelection */
2695     {
2696       if ((selection_type & Sel_CompoundText))
2697         {
2698           int selnum = selection_type & Sel_whereMask;
2699
2700           selection_type = 0;
2701           if (selnum != Sel_direct)
2702             selection_request_other (XA_STRING, selnum);
2703         }
2704
2705       if ((selection_type & Sel_UTF8String))
2706         {
2707           int selnum = selection_type & Sel_whereMask;
2708
2709           selection_type = Sel_CompoundText;
2710           if (selnum != Sel_direct)
2711             selection_request_other (xa[XA_COMPOUND_TEXT], selnum);
2712           else
2713             selection_type = 0;
2714         }
2715
2716       return 0;
2717     }
2718
2719   for (;;)
2720     {
2721       if (XGetWindowProperty (display->display, win, prop, (long) (nread / 4),
2722                               (long) (PROP_SIZE / 4), delete_prop,
2723                               AnyPropertyType, &ct.encoding, &ct.format,
2724                               &ct.nitems, &bytes_after,
2725                               &ct.value) != Success)
2726         break;
2727
2728       if (ct.encoding == 0)
2729         break;
2730
2731       if (ct.encoding == xa[XA_INCR])
2732         {
2733           // INCR selection, start handshake
2734           XDeleteProperty (display->display, win, prop);
2735           selection_wait = Sel_incr;
2736           incr_ev.start (NOW + 10);
2737           break;
2738         }
2739
2740       if (ct.value == NULL)
2741         continue;
2742
2743       if (ct.nitems == 0)
2744         {
2745           if (selection_wait == Sel_normal && nread == 0
2746               && (win != display->root || prop != XA_CUT_BUFFER0)) // avoid recursion
2747             {
2748               /*
2749                * pass through again trying CUT_BUFFER0 if we've come from
2750                * XConvertSelection () but nothing was presented
2751                */
2752               selection_paste (display->root, XA_CUT_BUFFER0, False);
2753             }
2754
2755           nread = -1;         /* discount any previous stuff */
2756           break;
2757         }
2758
2759       nread += ct.nitems;
2760
2761       char **cl;
2762       int cr;
2763
2764 #if ENABLE_FRILLS
2765       // xlib is horribly broken with respect to UTF8_STRING, and nobody cares to fix it
2766       // so recode it manually
2767       if (ct.encoding == xa[XA_UTF8_STRING])
2768         {
2769           wchar_t *w = rxvt_utf8towcs ((const char *)ct.value, ct.nitems);
2770           char *s = rxvt_wcstombs (w);
2771
2772           // TODO: strlen == only the first element will be converted. well...
2773           paste ((unsigned char *)s, strlen (s));
2774
2775           free (s);
2776           free (w);
2777         }
2778       else
2779 #endif
2780       if (XmbTextPropertyToTextList (display->display, &ct, &cl, &cr) >= 0 && cl)
2781         {
2782           for (int i = 0; i < cr; i++)
2783             paste ((unsigned char *)cl[i], strlen (cl[i]));
2784
2785           XFreeStringList (cl);
2786         }
2787       else
2788         paste (ct.value, ct.nitems);
2789
2790       if (bytes_after == 0)
2791         break;
2792
2793       XFree (ct.value);
2794     }
2795
2796   if (ct.value)
2797     XFree (ct.value);
2798
2799   if (selection_wait == Sel_normal)
2800     selection_wait = Sel_none;
2801
2802   return (int)nread;
2803 }
2804
2805 void
2806 rxvt_term::incr_cb (time_watcher &w)
2807 {
2808   selection_wait = Sel_none;
2809
2810   rxvt_warn ("data loss: timeout on INCR selection paste, ignoring.\n");
2811 }
2812
2813 /*
2814  * INCR support originally provided by Paul Sheer <psheer@obsidian.co.za>
2815  */
2816 void
2817 rxvt_term::selection_property (Window win, Atom prop)
2818 {
2819   if (prop == None || selection_wait != Sel_incr)
2820     return;
2821
2822   if (selection_paste (win, prop, 1) > 0)
2823     incr_ev.start (NOW + 10);
2824   else
2825     {
2826       selection_wait = Sel_none;
2827       incr_ev.stop ();
2828     }
2829 }
2830
2831 /* ------------------------------------------------------------------------- */
2832 /*
2833  * Request the current selection: 
2834  * Order: > internal selection if available
2835  *        > PRIMARY, SECONDARY, CLIPBOARD if ownership is claimed (+)
2836  *        > CUT_BUFFER0
2837  * (+) if ownership is claimed but property is empty, rxvt_selection_paste ()
2838  *     will auto fallback to CUT_BUFFER0
2839  * EXT: button 2 release
2840  */
2841 void
2842 rxvt_term::selection_request (Time tm, int x, int y)
2843 {
2844   if (x < 0 || x >= TermWin.width || y < 0 || y >= TermWin.height)
2845     return;                 /* outside window */
2846
2847   if (selection.text)
2848     { /* internal selection */
2849       char *str = rxvt_wcstombs (selection.text, selection.len);
2850       paste ((unsigned char *)str, strlen (str));
2851       free (str);
2852       return;
2853     }
2854   else
2855     {
2856       int i;
2857
2858       selection_request_time = tm;
2859       selection_wait = Sel_normal;
2860
2861       for (i = Sel_Primary; i <= Sel_Clipboard; i++)
2862         {
2863 #if X_HAVE_UTF8_STRING
2864           selection_type = Sel_UTF8String;
2865           if (selection_request_other (xa[XA_UTF8_STRING], i))
2866             return;
2867 #else
2868           selection_type = Sel_CompoundText;
2869           if (selection_request_other (xa[XA_COMPOUND_TEXT], i))
2870             return;
2871 #endif
2872         }
2873     }
2874
2875   selection_wait = Sel_none;       /* don't loop in rxvt_selection_paste () */
2876   selection_paste (display->root, XA_CUT_BUFFER0, False);
2877 }
2878
2879 int
2880 rxvt_term::selection_request_other (Atom target, int selnum)
2881 {
2882   Atom sel;
2883 #ifdef DEBUG_SELECT
2884   char *debug_xa_names[] = { "PRIMARY", "SECONDARY", "CLIPBOARD" };
2885 #endif
2886
2887   selection_type |= selnum;
2888
2889   if (selnum == Sel_Primary)
2890     sel = XA_PRIMARY;
2891   else if (selnum == Sel_Secondary)
2892     sel = XA_SECONDARY;
2893   else
2894     sel = xa[XA_CLIPBOARD];
2895
2896   if (XGetSelectionOwner (display->display, sel) != None)
2897     {
2898       XConvertSelection (display->display, sel, target, xa[XA_VT_SELECTION],
2899                          TermWin.vt, selection_request_time);
2900       return 1;
2901     }
2902
2903   return 0;
2904 }
2905
2906 /* ------------------------------------------------------------------------- */
2907 /*
2908  * Clear all selected text
2909  * EXT: SelectionClear
2910  */
2911 void
2912 rxvt_term::selection_clear ()
2913 {
2914   want_refresh = 1;
2915   free (selection.text);
2916   selection.text = NULL;
2917   selection.len = 0;
2918   CLEAR_SELECTION ();
2919
2920   if (display->selection_owner == this)
2921     display->selection_owner = 0;
2922 }
2923
2924 /* ------------------------------------------------------------------------- */
2925 /*
2926  * Copy a selection into the cut buffer
2927  * EXT: button 1 or 3 release
2928  */
2929 void
2930 rxvt_term::selection_make (Time tm)
2931 {
2932   int i, col, end_col, row, end_row;
2933   wchar_t *new_selection_text;
2934   text_t *t;
2935
2936   switch (selection.op)
2937     {
2938       case SELECTION_CONT:
2939         break;
2940       case SELECTION_INIT:
2941         CLEAR_SELECTION ();
2942         /* FALLTHROUGH */
2943       case SELECTION_BEGIN:
2944         selection.op = SELECTION_DONE;
2945         /* FALLTHROUGH */
2946       default:
2947         return;
2948     }
2949
2950   selection.op = SELECTION_DONE;
2951
2952   if (selection.clicks == 4)
2953     return;                 /* nothing selected, go away */
2954
2955   i = (selection.end.row - selection.beg.row + 1) * (TermWin.ncol + 1);
2956   new_selection_text = (wchar_t *)rxvt_malloc ((i + 4) * sizeof (wchar_t));
2957
2958   col = selection.beg.col;
2959   row = selection.beg.row + TermWin.saveLines;
2960   end_row = selection.end.row + TermWin.saveLines;
2961   int ofs = 0;
2962   int extra = 0;
2963
2964   for (; row <= end_row; row++, col = 0)
2965     {
2966       end_col = screen.tlen[row];
2967
2968 #if ENABLE_FRILLS
2969       if (selection.rect)
2970         {
2971           col = selection.beg.col;
2972           end_col = TermWin.ncol + 1;
2973         }
2974 #endif
2975
2976       MAX_IT (col, 0);
2977
2978       if (end_col == -1)
2979         end_col = TermWin.ncol;
2980
2981       if (row == end_row || selection.rect)
2982         MIN_IT (end_col, selection.end.col);
2983
2984       t = &screen.text[row][col];
2985       for (; col < end_col; col++)
2986         {
2987           if (*t == NOCHAR)
2988             t++;
2989 #if ENABLE_COMBINING
2990           else if (IS_COMPOSE (*t))
2991             {
2992               int len = rxvt_composite.expand (*t, 0);
2993
2994               extra -= (len - 1);
2995
2996               if (extra < 0)
2997                 {
2998                   extra += i;
2999                   i += i;
3000                   new_selection_text = (wchar_t *)rxvt_realloc (new_selection_text, (i + 4) * sizeof (wchar_t));
3001                 }
3002
3003               ofs += rxvt_composite.expand (*t++, new_selection_text + ofs);
3004             }
3005 #endif
3006           else
3007             new_selection_text[ofs++] = *t++;
3008         }
3009
3010       if (screen.tlen[row] != -1 && row != end_row)
3011         new_selection_text[ofs++] = C0_LF;
3012     }
3013
3014   if (end_col != selection.end.col)
3015     new_selection_text[ofs++] = C0_LF;
3016
3017   new_selection_text[ofs] = 0;
3018
3019   if (ofs == 0)
3020     {
3021       free (new_selection_text);
3022       return;
3023     }
3024
3025   free (selection.text);
3026
3027   // we usually allocate much more than necessary, so realloc it smaller again
3028   selection.len = ofs;
3029   selection.text = (wchar_t *)rxvt_realloc (new_selection_text, (ofs + 1) * sizeof (wchar_t));
3030
3031   XSetSelectionOwner (display->display, XA_PRIMARY, TermWin.vt, tm);
3032   if (XGetSelectionOwner (display->display, XA_PRIMARY) == TermWin.vt)
3033     display->set_selection_owner (this);
3034   else
3035     rxvt_warn ("can't get primary selection, ignoring.\n");
3036
3037 #if 0
3038   XTextProperty ct;
3039
3040   if (XwcTextListToTextProperty (display->display, &selection.text, 1, XStringStyle, &ct) >= 0)
3041     {
3042       set_string_property (XA_CUT_BUFFER0, ct.value, ct.nitems);
3043       XFree (ct.value);
3044     }
3045 #endif
3046
3047   selection_time = tm;
3048 }
3049
3050 /* ------------------------------------------------------------------------- */
3051 /*
3052  * Mark or select text based upon number of clicks: 1, 2, or 3
3053  * EXT: button 1 press
3054  */
3055 void
3056 rxvt_term::selection_click (int clicks, int x, int y)
3057 {
3058   clicks = ((clicks - 1) % 3) + 1;
3059   selection.clicks = clicks;       /* save clicks so extend will work */
3060
3061   selection_start_colrow (Pixel2Col (x), Pixel2Row (y));
3062
3063   if (clicks == 2 || clicks == 3)
3064     selection_extend_colrow (selection.mark.col,
3065                              selection.mark.row + TermWin.view_start,
3066                              0, /* button 3     */
3067                              1, /* button press */
3068                              0);        /* click change */
3069 }
3070
3071 /* ------------------------------------------------------------------------- */
3072 /*
3073  * Mark a selection at the specified col/row
3074  */
3075 void
3076 rxvt_term::selection_start_colrow (int col, int row)
3077 {
3078   want_refresh = 1;
3079   selection.mark.col = col;
3080   selection.mark.row = row - TermWin.view_start;
3081
3082   MAX_IT (selection.mark.row, - (int32_t)TermWin.nscrolled);
3083   MIN_IT (selection.mark.row, (int32_t)TermWin.nrow - 1);
3084   MAX_IT (selection.mark.col, 0);
3085   MIN_IT (selection.mark.col, (int32_t)TermWin.ncol - 1);
3086
3087   while (selection.mark.col > 0
3088          && screen.text[selection.mark.row + TermWin.saveLines][selection.mark.col] == NOCHAR)
3089     --selection.mark.col;
3090   
3091   if (selection.op)
3092     {      /* clear the old selection */
3093       selection.beg.row = selection.end.row = selection.mark.row;
3094       selection.beg.col = selection.end.col = selection.mark.col;
3095     }
3096
3097   selection.op = SELECTION_INIT;
3098   selection.screen = current_screen;
3099 }
3100
3101 /* ------------------------------------------------------------------------- */
3102 /*
3103  * Word select: select text for 2 clicks
3104  * We now only find out the boundary in one direction
3105  */
3106
3107 /* what do we want: spaces/tabs are delimiters or cutchars or non-cutchars */
3108 #define DELIMIT_TEXT(x)                 \
3109     (unicode::is_space (x) ? 2 : (x) <= 0xff && !!strchr (rs[Rs_cutchars], (x)))
3110 #define DELIMIT_REND(x)        1
3111
3112 void
3113 rxvt_term::selection_delimit_word (enum page_dirn dirn, const row_col_t *mark, row_col_t *ret)
3114 {
3115   int col, row, dirnadd, tcol, trow, w1, w2;
3116   row_col_t bound;
3117   text_t *stp;
3118   rend_t *srp;
3119
3120   if (dirn == UP)
3121     {
3122       bound.row = TermWin.saveLines - TermWin.nscrolled - 1;
3123       bound.col = 0;
3124       dirnadd = -1;
3125     }
3126   else
3127     {
3128       bound.row = TermWin.saveLines + TermWin.nrow;
3129       bound.col = TermWin.ncol - 1;
3130       dirnadd = 1;
3131     }
3132
3133   row = mark->row + TermWin.saveLines;
3134   col = mark->col;
3135   MAX_IT (col, 0);
3136   /* find the edge of a word */
3137   stp = &screen.text[row][col];
3138   w1 = DELIMIT_TEXT (*stp);
3139
3140   srp = &screen.rend[row][col];
3141   w2 = DELIMIT_REND (*srp);
3142
3143   for (;;)
3144     {
3145       for (; col != bound.col; col += dirnadd)
3146         {
3147           stp += dirnadd;
3148           srp += dirnadd;
3149
3150           if (*stp == NOCHAR)
3151             continue;
3152
3153           if (DELIMIT_TEXT (*stp) != w1)
3154             break;
3155           if (DELIMIT_REND (*srp) != w2)
3156             break;
3157         }
3158
3159       if ((col == bound.col) && (row != bound.row))
3160         {
3161           if (screen.tlen[ (row - (dirn == UP ? 1 : 0))] == -1)
3162             {
3163               trow = row + dirnadd;
3164               tcol = dirn == UP ? TermWin.ncol - 1 : 0;
3165
3166               if (screen.text[trow] == NULL)
3167                 break;
3168
3169               stp = & (screen.text[trow][tcol]);
3170               srp = & (screen.rend[trow][tcol]);
3171
3172               if (DELIMIT_TEXT (*stp) != w1 || DELIMIT_REND (*srp) != w2)
3173                 break;
3174
3175               row = trow;
3176               col = tcol;
3177               continue;
3178             }
3179         }
3180       break;
3181     }
3182
3183 Old_Word_Selection_You_Die:
3184   if (dirn == DN)
3185     col++;                  /* put us on one past the end */
3186
3187   /* Poke the values back in */
3188   ret->row = row - TermWin.saveLines;
3189   ret->col = col;
3190 }
3191
3192 /* ------------------------------------------------------------------------- */
3193 /*
3194  * Extend the selection to the specified x/y pixel location
3195  * EXT: button 3 press; button 1 or 3 drag
3196  * flag == 0 ==> button 1
3197  * flag == 1 ==> button 3 press
3198  * flag == 2 ==> button 3 motion
3199  */
3200 void
3201 rxvt_term::selection_extend (int x, int y, int flag)
3202 {
3203   int col, row;
3204
3205   col = Pixel2Col (x);
3206   row = Pixel2Row (y);
3207   MAX_IT (row, 0);
3208   MIN_IT (row, (int)TermWin.nrow - 1);
3209   MAX_IT (col, 0);
3210   MIN_IT (col, (int)TermWin.ncol);
3211
3212   /*
3213   * If we're selecting characters (single click) then we must check first
3214   * if we are at the same place as the original mark.  If we are then
3215   * select nothing.  Otherwise, if we're to the right of the mark, you have to
3216   * be _past_ a character for it to be selected.
3217   */
3218   if (((selection.clicks % 3) == 1) && !flag
3219       && (col == selection.mark.col
3220           && (row == selection.mark.row + TermWin.view_start)))
3221     {
3222       /* select nothing */
3223       selection.beg.row = selection.end.row = 0;
3224       selection.beg.col = selection.end.col = 0;
3225       selection.clicks = 4;
3226       want_refresh = 1;
3227       return;
3228     }
3229
3230   if (selection.clicks == 4)
3231     selection.clicks = 1;
3232
3233   selection_extend_colrow (col, row, !!flag,  /* ? button 3      */
3234                            flag == 1 ? 1 : 0,     /* ? button press  */
3235                            0);    /* no click change */
3236 }
3237
3238 /* ------------------------------------------------------------------------- */
3239 /*
3240  * Extend the selection to the specified col/row
3241  */
3242 void
3243 rxvt_term::selection_extend_colrow (int32_t col, int32_t row, int button3, int buttonpress, int clickchange)
3244 {
3245   int16_t ncol = TermWin.ncol;
3246   int end_col;
3247   row_col_t pos;
3248   enum {
3249     LEFT, RIGHT
3250   } closeto = RIGHT;
3251
3252   want_refresh = 1;
3253
3254   switch (selection.op)
3255     {
3256       case SELECTION_INIT:
3257         CLEAR_SELECTION ();
3258         selection.op = SELECTION_BEGIN;
3259         /* FALLTHROUGH */
3260       case SELECTION_BEGIN:
3261         if (row != selection.mark.row || col != selection.mark.col
3262             || (!button3 && buttonpress))
3263           selection.op = SELECTION_CONT;
3264         break;
3265       case SELECTION_DONE:
3266         selection.op = SELECTION_CONT;
3267         /* FALLTHROUGH */
3268       case SELECTION_CONT:
3269         break;
3270       case SELECTION_CLEAR:
3271         selection_start_colrow (col, row);
3272         /* FALLTHROUGH */
3273       default:
3274         return;
3275     }
3276
3277   if (selection.beg.col == selection.end.col
3278       && selection.beg.col != selection.mark.col
3279       && selection.beg.row == selection.end.row
3280       && selection.beg.row != selection.mark.row)
3281     {
3282       selection.beg.col = selection.end.col = selection.mark.col;
3283       selection.beg.row = selection.end.row = selection.mark.row;
3284     }
3285
3286   pos.col = col;
3287   pos.row = row;
3288
3289   pos.row -= TermWin.view_start;   /* adjust for scroll */
3290
3291   /*
3292    * This is mainly xterm style selection with a couple of differences, mainly
3293    * in the way button3 drag extension works.
3294    * We're either doing: button1 drag; button3 press; or button3 drag
3295    *  a) button1 drag : select around a midpoint/word/line - that point/word/line
3296    *     is always at the left/right edge of the selection.
3297    *  b) button3 press: extend/contract character/word/line at whichever edge of
3298    *     the selection we are closest to.
3299    *  c) button3 drag : extend/contract character/word/line - we select around
3300    *     a point/word/line which is either the start or end of the selection
3301    *     and it was decided by whichever point/word/line was `fixed' at the
3302    *     time of the most recent button3 press
3303    */
3304   if (button3 && buttonpress)
3305     { /* button3 press */
3306       /*
3307        * first determine which edge of the selection we are closest to
3308        */
3309       if (ROWCOL_IS_BEFORE (pos, selection.beg)
3310           || (!ROWCOL_IS_AFTER (pos, selection.end)
3311               && (((pos.col - selection.beg.col)
3312                    + ((pos.row - selection.beg.row) * ncol))
3313                   < ((selection.end.col - pos.col)
3314                      + ((selection.end.row - pos.row) * ncol)))))
3315         closeto = LEFT;
3316
3317       if (closeto == LEFT)
3318         {
3319           selection.beg.row = pos.row;
3320           selection.beg.col = pos.col;
3321           selection.mark.row = selection.end.row;
3322           selection.mark.col = selection.end.col - (selection.clicks == 2);
3323         }
3324       else
3325         {
3326           selection.end.row = pos.row;
3327           selection.end.col = pos.col;
3328           selection.mark.row = selection.beg.row;
3329           selection.mark.col = selection.beg.col;
3330         }
3331     }
3332   else
3333     { /* button1 drag or button3 drag */
3334       if (ROWCOL_IS_AFTER (selection.mark, pos))
3335         {
3336           if (selection.mark.row == selection.end.row
3337               && selection.mark.col == selection.end.col
3338               && clickchange
3339               && selection.clicks == 2)
3340             selection.mark.col--;
3341
3342           selection.beg.row = pos.row;
3343           selection.beg.col = pos.col;
3344           selection.end.row = selection.mark.row;
3345           selection.end.col = selection.mark.col + (selection.clicks == 2);
3346         }
3347       else
3348         {
3349           selection.beg.row = selection.mark.row;
3350           selection.beg.col = selection.mark.col;
3351           selection.end.row = pos.row;
3352           selection.end.col = pos.col;
3353         }
3354     }
3355
3356   if (selection.clicks == 1)
3357     {
3358       end_col = screen.tlen[selection.beg.row + TermWin.saveLines];
3359
3360       if (selection.beg.col > end_col
3361           && end_col != -1
3362 #if ENABLE_FRILLS
3363           && !selection.rect
3364 #endif
3365          )
3366         selection.beg.col = ncol;
3367
3368       end_col = screen.tlen[selection.end.row + TermWin.saveLines];
3369
3370       if (
3371           selection.end.col > end_col
3372           && end_col != -1
3373 #if ENABLE_FRILLS
3374           && !selection.rect
3375 #endif
3376          )
3377         selection.end.col = ncol;
3378     }
3379   else if (selection.clicks == 2)
3380     {
3381       if (ROWCOL_IS_AFTER (selection.end, selection.beg))
3382         selection.end.col--;
3383
3384       selection_delimit_word (UP, &selection.beg, &selection.beg);
3385       selection_delimit_word (DN, &selection.end, &selection.end);
3386     }
3387   else if (selection.clicks == 3)
3388     {
3389 #if ENABLE_FRILLS
3390       if ((options & Opt_tripleclickwords))
3391         {
3392           int end_row;
3393
3394           selection_delimit_word (UP, &selection.beg, &selection.beg);
3395           end_row = screen.tlen[selection.mark.row + TermWin.saveLines];
3396
3397           for (end_row = selection.mark.row; end_row < TermWin.nrow; end_row++)
3398             {
3399               end_col = screen.tlen[end_row + TermWin.saveLines];
3400
3401               if (end_col != -1)
3402                 {
3403                   selection.end.row = end_row;
3404                   selection.end.col = end_col;
3405                   selection_remove_trailing_spaces ();
3406                   break;
3407                 }
3408             }
3409         }
3410       else
3411 #endif
3412         {
3413           if (ROWCOL_IS_AFTER (selection.mark, selection.beg))
3414             selection.mark.col++;
3415
3416           selection.beg.col = 0;
3417           selection.end.col = ncol;
3418         }
3419     }
3420
3421   if (button3 && buttonpress)
3422     { /* mark may need to be changed */
3423       if (closeto == LEFT)
3424         {
3425           selection.mark.row = selection.end.row;
3426           selection.mark.col = selection.end.col - (selection.clicks == 2);
3427         }
3428       else
3429         {
3430           selection.mark.row = selection.beg.row;
3431           selection.mark.col = selection.beg.col;
3432         }
3433     }
3434
3435 #if ENABLE_FRILLS
3436   if (selection.rect && selection.beg.col > selection.end.col)
3437     SWAP_IT (selection.beg.col, selection.end.col, int);
3438 #endif
3439 }
3440
3441 #if ENABLE_FRILLS
3442 void
3443 rxvt_term::selection_remove_trailing_spaces ()
3444 {
3445   int32_t end_col, end_row;
3446   text_t *stp;
3447
3448   end_col = selection.end.col;
3449   end_row = selection.end.row;
3450
3451   for ( ; end_row >= selection.beg.row; )
3452     {
3453       stp = screen.text[end_row + TermWin.saveLines];
3454
3455       while (--end_col >= 0)
3456         {
3457           if (stp[end_col] != ' '
3458               && stp[end_col] != '\t'
3459               && stp[end_col] != NOCHAR)
3460             break;
3461         }
3462
3463       if (end_col >= 0
3464           || screen.tlen[end_row - 1 + TermWin.saveLines] != -1)
3465         {
3466           selection.end.col = end_col + 1;
3467           selection.end.row = end_row;
3468           break;
3469         }
3470
3471       end_row--;
3472       end_col = TermWin.ncol;
3473     }
3474
3475   if (selection.mark.row > selection.end.row)
3476     {
3477       selection.mark.row = selection.end.row;
3478       selection.mark.col = selection.end.col;
3479     }
3480   else if (selection.mark.row == selection.end.row
3481            && selection.mark.col > selection.end.col)
3482     selection.mark.col = selection.end.col;
3483 }
3484 #endif
3485
3486 /* ------------------------------------------------------------------------- */
3487 /*
3488  * Double click on button 3 when already selected
3489  * EXT: button 3 double click
3490  */
3491 void
3492 rxvt_term::selection_rotate (int x, int y)
3493 {
3494   selection.clicks = selection.clicks % 3 + 1;
3495   selection_extend_colrow (Pixel2Col (x), Pixel2Row (y), 1, 0, 1);
3496 }
3497
3498 /* ------------------------------------------------------------------------- */
3499 /*
3500  * Respond to a request for our current selection
3501  * EXT: SelectionRequest
3502  */
3503 void
3504 rxvt_term::selection_send (const XSelectionRequestEvent &rq)
3505 {
3506   XSelectionEvent ev;
3507
3508   ev.type = SelectionNotify;
3509   ev.property = None;
3510   ev.display = rq.display;
3511   ev.requestor = rq.requestor;
3512   ev.selection = rq.selection;
3513   ev.target = rq.target;
3514   ev.time = rq.time;
3515
3516   if (rq.target == xa[XA_TARGETS])
3517     {
3518       Atom target_list[6];
3519       Atom *target = target_list;
3520
3521       *target++ = xa[XA_TARGETS];
3522       *target++ = xa[XA_TIMESTAMP];
3523       *target++ = XA_STRING;
3524       *target++ = xa[XA_TEXT];
3525       *target++ = xa[XA_COMPOUND_TEXT];
3526 #if X_HAVE_UTF8_STRING
3527       *target++ = xa[XA_UTF8_STRING];
3528 #endif
3529
3530       XChangeProperty (display->display, rq.requestor, rq.property, XA_ATOM,
3531                        32, PropModeReplace,
3532                        (unsigned char *)target_list, target - target_list);
3533       ev.property = rq.property;
3534     }
3535 #if TODO // TODO
3536   else if (rq.target == xa[XA_MULTIPLE])
3537     {
3538       /* TODO: Handle MULTIPLE */
3539     }
3540 #endif
3541   else if (rq.target == xa[XA_TIMESTAMP] && selection.text)
3542     {
3543       XChangeProperty (display->display, rq.requestor, rq.property, rq.target,
3544                        32, PropModeReplace, (unsigned char *)&selection_time, 1);
3545       ev.property = rq.property;
3546     }
3547   else if (rq.target == XA_STRING
3548            || rq.target == xa[XA_TEXT]
3549            || rq.target == xa[XA_COMPOUND_TEXT]
3550            || rq.target == xa[XA_UTF8_STRING]
3551           )
3552     {
3553       XTextProperty ct;
3554       Atom target = rq.target;
3555       short freect = 0;
3556       int selectlen;
3557       wchar_t *cl;
3558       enum {
3559         enc_string        = XStringStyle,
3560         enc_text          = XStdICCTextStyle,
3561         enc_compound_text = XCompoundTextStyle,
3562 #ifdef X_HAVE_UTF8_STRING
3563         enc_utf8          = XUTF8StringStyle,
3564 #else
3565         enc_utf8          = -1,
3566 #endif
3567       } style;
3568
3569       if (target == XA_STRING)
3570         // we actually don't do XA_STRING, but who cares, as i18n clients
3571         // will ask for another format anyways.
3572         style = enc_string;
3573       else if (target == xa[XA_TEXT])
3574         style = enc_text;
3575       else if (target == xa[XA_COMPOUND_TEXT])
3576         style = enc_compound_text;
3577 #if ENABLE_FRILLS
3578       else if (target == xa[XA_UTF8_STRING])
3579         style = enc_utf8;
3580 #endif
3581       else
3582         {
3583           target = xa[XA_COMPOUND_TEXT];
3584           style = enc_compound_text;
3585         }
3586
3587       if (selection.text)
3588         {
3589           cl = selection.text;
3590           selectlen = selection.len;
3591         }
3592       else
3593         {
3594           cl = L"";
3595           selectlen = 0;
3596         }
3597
3598 #if ENABLE_FRILLS
3599       // xlib is horribly broken with respect to UTF8_STRING, and nobody cares to fix it
3600       // so recode it manually
3601       if (style == enc_utf8)
3602         {
3603           freect = 1;
3604           ct.encoding = target;
3605           ct.format = 8;
3606           ct.value = (unsigned char *)rxvt_wcstoutf8 (cl, selectlen);
3607           ct.nitems = strlen ((char *)ct.value);
3608         }
3609       else
3610 #endif
3611       if (XwcTextListToTextProperty (display->display, &cl, 1, (XICCEncodingStyle) style, &ct) >= 0)
3612         freect = 1;
3613       else
3614         {
3615           /* if we failed to convert then send it raw */
3616           ct.value = (unsigned char *)cl;
3617           ct.nitems = selectlen;
3618           ct.encoding = target;
3619         }
3620
3621       XChangeProperty (display->display, rq.requestor, rq.property,
3622                        ct.encoding, 8, PropModeReplace,
3623                        ct.value, (int)ct.nitems);
3624       ev.property = rq.property;
3625
3626       if (freect)
3627         XFree (ct.value);
3628     }
3629
3630   XSendEvent (display->display, rq.requestor, False, 0L, (XEvent *)&ev);
3631 }
3632 \f
3633 /* ------------------------------------------------------------------------- *
3634  *                              MOUSE ROUTINES                               *
3635  * ------------------------------------------------------------------------- */
3636
3637 /*
3638  * return col/row values corresponding to x/y pixel values
3639  */
3640 void
3641 rxvt_term::pixel_position (int *x, int *y)
3642 {
3643   *x = Pixel2Col (*x);
3644   /* MAX_IT (*x, 0); MIN_IT (*x, (int)TermWin.ncol - 1); */
3645   *y = Pixel2Row (*y);
3646   /* MAX_IT (*y, 0); MIN_IT (*y, (int)TermWin.nrow - 1); */
3647 }
3648
3649 /* ------------------------------------------------------------------------- */
3650 #ifdef USE_XIM
3651 void
3652 rxvt_term::im_set_position (XPoint &pos)
3653 {
3654   XWindowAttributes xwa;
3655
3656   XGetWindowAttributes (display->display, TermWin.vt, &xwa);
3657
3658   pos.x = xwa.x + Col2Pixel    (screen.cur.col);
3659   pos.y = xwa.y + Height2Pixel (screen.cur.row) + TermWin.fbase;
3660 }
3661 #endif
3662
3663 #if ENABLE_OVERLAY
3664 void
3665 rxvt_term::scr_overlay_new (int x, int y, int w, int h)
3666 {
3667   if (TermWin.nrow < 3 || TermWin.ncol < 3)
3668     return;
3669
3670   want_refresh = 1;
3671
3672   scr_overlay_off ();
3673
3674   if (x < 0) x = TermWin.ncol - w;
3675   if (y < 0) y = TermWin.nrow - h;
3676
3677   // make space for border
3678   w += 2; MIN_IT (w, TermWin.ncol);
3679   h += 2; MIN_IT (h, TermWin.nrow);
3680
3681   x -= 1; MAX_IT (x, 0);
3682   y -= 1; MAX_IT (y, 0);
3683
3684   MIN_IT (x, TermWin.ncol - w);
3685   MIN_IT (y, TermWin.nrow - h);
3686
3687   ov_x = x; ov_y = y;
3688   ov_w = w; ov_h = h;
3689
3690   ov_text = new text_t *[h];
3691   ov_rend = new rend_t *[h];
3692
3693   for (y = 0; y < h; y++)
3694     {
3695       text_t *tp = ov_text[y] = new text_t[w];
3696       rend_t *rp = ov_rend[y] = new rend_t[w];
3697
3698       text_t t0, t1, t2;
3699       rend_t r = OVERLAY_RSTYLE;
3700
3701       if (y == 0)
3702         t0 = 0x2554, t1 = 0x2550, t2 = 0x2557;
3703       else if (y < h - 1)
3704         t0 = 0x2551, t1 = 0x0020, t2 = 0x2551;
3705       else
3706         t0 = 0x255a, t1 = 0x2550, t2 = 0x255d;
3707
3708       *tp++ = t0;
3709       *rp++ = r;
3710
3711       for (x = w - 2; x > 0; --x)
3712         {
3713           *tp++ = t1;
3714           *rp++ = r;
3715         }
3716
3717       *tp = t2;
3718       *rp = r;
3719     }
3720 }
3721
3722 void
3723 rxvt_term::scr_overlay_off ()
3724 {
3725   if (!ov_text)
3726     return;
3727
3728   want_refresh = 1;
3729
3730   for (int y = 0; y < ov_h; y++)
3731     {
3732       delete [] ov_text[y];
3733       delete [] ov_rend[y];
3734     }
3735
3736   delete [] ov_text; ov_text = 0;
3737   delete [] ov_rend; ov_rend = 0;
3738 }
3739
3740 void
3741 rxvt_term::scr_overlay_set (int x, int y, text_t text, rend_t rend)
3742 {
3743   if (!ov_text || x >= ov_w - 2 || y >= ov_h - 2)
3744     return;
3745
3746   x++, y++;
3747
3748   ov_text[y][x] = text;
3749   ov_rend[y][x] = rend;
3750 }
3751
3752 void
3753 rxvt_term::scr_overlay_set (int x, int y, const char *s)
3754 {
3755   while (*s)
3756     scr_overlay_set (x++, y, *s++);
3757 }
3758
3759 void
3760 rxvt_term::scr_swap_overlay ()
3761 {
3762   if (!ov_text)
3763     return;
3764
3765   int row_offset = ov_y + TermWin.saveLines - TermWin.view_start;
3766
3767   // swap screen mem with overlay
3768   for (int y = ov_h; y--; )
3769     {
3770       text_t *t1 = ov_text[y];
3771       rend_t *r1 = ov_rend[y];
3772
3773       text_t *t2 = screen.text[y + row_offset] + ov_x;
3774       rend_t *r2 = screen.rend[y + row_offset] + ov_x;
3775
3776       for (int x = ov_w; x--; )
3777         {
3778           text_t t = *t1; *t1++ = *t2; *t2++ = t;
3779           rend_t r = *r1; *r1++ = *r2; *r2++ = SET_FONT (r, FONTSET (r)->find_font (t));
3780         }
3781     }
3782 }
3783
3784 #endif
3785 /* ------------------------------------------------------------------------- */