#include "config.h"
#include <sys/types.h>
#include <sys/queue.h>
#include <sys/time.h>
#include <bitstring.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "common.h"
#include "../vi/vi.h"
int
screen_init(GS *gp, SCR *orig, SCR **spp)
{
SCR *sp;
size_t len;
*spp = NULL;
CALLOC_RET(orig, sp, 1, sizeof(SCR));
*spp = sp;
sp->id = ++gp->id;
sp->refcnt = 1;
sp->gp = gp;
sp->ccnt = 2;
TAILQ_INIT(&sp->tiq);
if (orig == NULL) {
sp->searchdir = NOTSET;
} else {
if (orig->alt_name != NULL &&
(sp->alt_name = strdup(orig->alt_name)) == NULL)
goto mem;
if (F_ISSET(orig, SC_AT_SET)) {
F_SET(sp, SC_AT_SET);
sp->at_lbuf = orig->at_lbuf;
}
sp->searchdir = orig->searchdir == NOTSET ? NOTSET : FORWARD;
if (orig->re != NULL && (sp->re =
v_strdup(sp, orig->re, orig->re_len)) == NULL)
goto mem;
sp->re_len = orig->re_len;
if (orig->subre != NULL && (sp->subre =
v_strdup(sp, orig->subre, orig->subre_len)) == NULL)
goto mem;
sp->subre_len = orig->subre_len;
if (orig->repl != NULL && (sp->repl =
v_strdup(sp, orig->repl, orig->repl_len)) == NULL)
goto mem;
sp->repl_len = orig->repl_len;
if (orig->newl_len) {
len = orig->newl_len * sizeof(size_t);
MALLOC(sp, sp->newl, len);
if (sp->newl == NULL) {
mem: msgq(orig, M_SYSERR, NULL);
goto err;
}
sp->newl_len = orig->newl_len;
sp->newl_cnt = orig->newl_cnt;
memcpy(sp->newl, orig->newl, len);
}
if (opts_copy(orig, sp))
goto err;
F_SET(sp, F_ISSET(orig, SC_EX | SC_VI));
}
if (ex_screen_copy(orig, sp))
goto err;
if (v_screen_copy(orig, sp))
goto err;
*spp = sp;
return (0);
err: screen_end(sp);
return (1);
}
int
screen_end(SCR *sp)
{
int rval;
SCR *tsp;
if (--sp->refcnt != 0)
return (0);
TAILQ_FOREACH(tsp, &sp->gp->dq, q) {
if (tsp == sp) {
TAILQ_REMOVE(&sp->gp->dq, sp, q);
break;
}
}
TAILQ_FOREACH(tsp, &sp->gp->hq, q) {
if (tsp == sp) {
TAILQ_REMOVE(&sp->gp->hq, sp, q);
break;
}
}
F_CLR(sp, SC_SCR_EX | SC_SCR_VI);
rval = 0;
if (v_screen_end(sp))
rval = 1;
if (ex_screen_end(sp))
rval = 1;
{ char **ap;
if (!F_ISSET(sp, SC_ARGNOFREE) && sp->argv != NULL) {
for (ap = sp->argv; *ap != NULL; ++ap)
free(*ap);
free(sp->argv);
}
}
if (TAILQ_FIRST(&sp->tiq) != NULL)
text_lfree(&sp->tiq);
free(sp->alt_name);
free(sp->re);
if (F_ISSET(sp, SC_RE_SEARCH))
regfree(&sp->re_c);
free(sp->subre);
if (F_ISSET(sp, SC_RE_SUBST))
regfree(&sp->subre_c);
free(sp->repl);
free(sp->newl);
opts_free(sp);
free(sp);
return (rval);
}
SCR *
screen_next(SCR *sp)
{
GS *gp;
SCR *next;
gp = sp->gp;
TAILQ_FOREACH(next, &gp->dq, q)
if (next != sp)
return (next);
if (!TAILQ_EMPTY(&gp->hq)) {
next = TAILQ_FIRST(&gp->hq);
TAILQ_REMOVE(&gp->hq, next, q);
TAILQ_INSERT_HEAD(&gp->dq, next, q);
return (next);
}
return (NULL);
}