#include <sys/cdefs.h>
#ifndef lint
__RCSID("$NetBSD: ins_wch.c,v 1.21 2024/12/23 02:58:03 blymn Exp $");
#endif
#include <string.h>
#include <stdlib.h>
#include "curses.h"
#include "curses_private.h"
int
ins_wch(const cchar_t *wch)
{
return wins_wch(stdscr, wch);
}
int
mvins_wch(int y, int x, const cchar_t *wch)
{
return mvwins_wch(stdscr, y, x, wch);
}
int
mvwins_wch(WINDOW *win, int y, int x, const cchar_t *wch)
{
if (wmove(win, y, x) == ERR)
return ERR;
return wins_wch(win, wch);
}
int
wins_wch(WINDOW *win, const cchar_t *wch)
{
__LDATA *start, *temp1, *temp2;
__LINE *lnp;
int cw, pcw, x, y, sx, ex, newx, i;
nschar_t *np, *tnp;
wchar_t ws[] = L" ";
if (__predict_false(win == NULL))
return ERR;
if (!wch)
return OK;
cw = wcwidth(wch->vals[0]);
__CTRACE(__CTRACE_INPUT, "wins_wch: wcwidth %d\n", cw);
if (cw < 0)
cw = 1;
if (!cw)
return wadd_wch( win, wch );
x = win->curx;
y = win->cury;
__CTRACE(__CTRACE_INPUT, "wins_wch: (%d,%d)\n", y, x);
switch (wch->vals[0]) {
case L'\b':
if (--x < 0)
x = 0;
win->curx = x;
return OK;
case L'\r':
win->curx = 0;
return OK;
case L'\n':
wclrtoeol(win);
if (y == win->scr_b) {
if (!(win->flags & __SCROLLOK))
return ERR;
scroll(win);
}
return OK;
case L'\t':
if (wins_nwstr(win, ws, min(win->maxx - x,
TABSIZE - (x % TABSIZE))) == ERR)
return ERR;
return OK;
}
x = win->curx;
y = win->cury;
lnp = win->alines[y];
start = &win->alines[y]->line[x];
sx = x;
pcw = start->wcols;
if (pcw < 0) {
start += pcw;
sx += pcw;
}
if (cw > win->maxx - sx)
return ERR;
lnp->flags |= __ISDIRTY;
newx = sx + win->ch_off;
if (newx < *lnp->firstchp)
*lnp->firstchp = newx;
__CTRACE(__CTRACE_INPUT, "wins_wch: shift all characters\n");
temp1 = &win->alines[y]->line[win->maxx - 1];
temp2 = temp1 - cw;
pcw = (temp2 + 1)->wcols;
if (pcw < 0) {
__CTRACE(__CTRACE_INPUT, "wins_wch: clear EOL\n");
temp2 += pcw;
while (temp1 > temp2 + cw) {
np = temp1->nsp;
if (np) {
while (np) {
tnp = np->next;
free(np);
np = tnp;
}
temp1->nsp = NULL;
}
temp1->ch = win->bch;
if (_cursesi_copy_nsp(win->bnsp, temp1) == ERR)
return ERR;
temp1->attr = win->battr;
temp1->wcols = 1;
temp1--;
}
}
while (temp2 >= start) {
(void)memcpy(temp1, temp2, sizeof(__LDATA));
temp1--, temp2--;
}
start->nsp = NULL;
start->ch = wch->vals[0];
start->attr = wch->attributes & WA_ATTRIBUTES;
start->wcols = cw;
if (wch->elements > 1) {
for (i = 1; i < wch->elements; i++) {
np = malloc(sizeof(nschar_t));
if (!np)
return ERR;
np->ch = wch->vals[i];
np->next = start->nsp;
start->nsp = np;
}
}
__CTRACE(__CTRACE_INPUT, "wins_wch: insert (%x,%x,%p)\n",
start->ch, start->attr, start->nsp);
temp1 = start + 1;
ex = x + 1;
while (ex - x < cw) {
temp1->ch = wch->vals[0];
temp1->wcols = x - ex;
temp1->nsp = NULL;
temp1->cflags |= CA_CONTINUATION;
ex++, temp1++;
}
newx = win->maxx - 1 + win->ch_off;
if (newx > *lnp->lastchp)
*lnp->lastchp = newx;
__touchline(win, y, sx, (int)win->maxx - 1);
__sync(win);
return OK;
}