chiark / gitweb /
Remove .cvsignore files from git repo.
[chiark-tcl.git] / base / scriptinv.c
1 /*
2  * base code for various Tcl extensions
3  * Copyright 2006-2012 Ian Jackson
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this library; if not, see <http://www.gnu.org/licenses/>.
17  */
18
19 #include "chiark-tcl-base.h"
20
21 void cht_scriptinv_init(ScriptToInvoke *si) {
22   si->ipq= 0;
23   si->script= 0;
24   si->xargs= 0;
25 }
26
27 void cht_scriptinv_cancel(ScriptToInvoke *si) {
28   if (si->script) { Tcl_DecrRefCount(si->script); si->script= 0; }
29   if (si->xargs) { Tcl_DecrRefCount(si->xargs); si->xargs= 0; }
30   si->ipq= 0;
31 }
32
33 int cht_scriptinv_set(ScriptToInvoke *si, Tcl_Interp *ip,
34                   Tcl_Obj *newscript, Tcl_Obj *xargs) {
35   int rc, xlength;
36   
37   cht_scriptinv_cancel(si);
38   if (!newscript) return 0;
39
40   rc= Tcl_ListObjLength(ip, newscript, &si->llen);  if (rc) return rc;
41   Tcl_IncrRefCount(newscript);
42
43   if (xargs) {
44     rc= Tcl_ListObjLength(ip, xargs, &xlength);  if (rc) return rc;
45     Tcl_IncrRefCount(xargs);
46     assert(si->llen < INT_MAX/2 && xlength < INT_MAX/2);
47     si->llen += xlength;
48   }
49
50   si->script= newscript;
51   si->xargs= xargs;
52   si->ipq= ip;
53   return 0;
54 }  
55   
56 int cht_scriptinv_invoke_fg(ScriptToInvoke *si, int argc,
57                             Tcl_Obj *const *argv) {
58   Tcl_Obj *invoke=0;
59   int i, rc;
60
61   if (!si->ipq) return TCL_OK;
62
63   for (i=0; i<argc; i++) Tcl_IncrRefCount(argv[i]);
64
65   invoke= Tcl_DuplicateObj(si->script);
66   Tcl_IncrRefCount(invoke);
67
68   if (si->xargs) {
69     rc= Tcl_ListObjAppendList(si->ipq, invoke, si->xargs);
70     if (rc) goto x_rc;
71   }
72
73   rc= Tcl_ListObjReplace(si->ipq, invoke,si->llen,0, argc,argv);
74   if (rc) goto x_rc;
75
76   rc= Tcl_EvalObjEx(si->ipq, invoke, TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
77   if (rc) goto x_rc;
78
79   rc= 0;
80   
81 x_rc:
82   for (i=0; i<argc; i++) Tcl_DecrRefCount(argv[i]);
83   if (invoke) Tcl_DecrRefCount(invoke);
84   return rc;
85 }
86
87 void cht_scriptinv_invoke(ScriptToInvoke *si, int argc, Tcl_Obj *const *argv) {
88   int rc;
89   rc= cht_scriptinv_invoke_fg(si, argc, argv);
90   if (rc) Tcl_BackgroundError(si->ipq);
91 }