Exemple #1
0
/*
 *  This is the CGI process wrapper.  It will open and redirect stdin
 *  and stdout to stdIn and stdOut.  It converts argv to an argc, argv
 *  pair to pass to the user entry. It initializes the task environment
 *  with envp strings.  Then it will call the user entry.
 */
static void vxWebsCgiEntry(void *entryAddr(int argc, char_t **argv),
				char_t **argp, char_t **envp, char_t *stdIn, char_t *stdOut)
{
	char_t  **p;
	int     argc, taskId, fdin, fdout;

/*
 *  Open the stdIn and stdOut files and redirect stdin and stdout
 *  to them.
 */
	taskId = taskIdSelf();
	if ((fdout = gopen(stdOut, O_RDWR | O_CREAT, 0666)) < 0 &&
			(fdout = creat(stdOut, O_RDWR)) < 0) {
		exit(0);
	}
	ioTaskStdSet(taskId, 1, fdout);

	if ((fdin = gopen(stdIn, O_RDONLY | O_CREAT, 0666)) < 0 &&
			(fdin = creat(stdIn, O_RDWR)) < 0) {
		printf("content-type: text/html\n\n"
				"Can not create CGI stdin to %s\n", stdIn);
		gclose(fdout);
		exit (0);
	}
	ioTaskStdSet(taskId, 0, fdin);

/*
 *  Count the number of entries in argv
 */
	for (argc = 0, p = argp; p != NULL && *p != NULL; p++, argc++) {
	}

/*
 *  Create a private envirnonment and copy the envp strings to it.
 */
	if (envPrivateCreate(taskId, -1) != OK) {
		printf("content-type: text/html\n\n"
			"Can not create CGI environment space\n");
		gclose(fdin);
		gclose(fdout);
		exit (0);
	}
	for (p = envp; p != NULL && *p != NULL; p++) {
		putenv(*p);
	}

/*
 *  Call the user entry.
 */
	(*entryAddr)(argc, argp);

/*
 *  The user code should return here for cleanup.
 */

	envPrivateDestroy(taskId);
	gclose(fdin);
	gclose(fdout);
	exit(0);
}
Exemple #2
0
int main()
{
     char linebuf[MAXTEXT], name[NAMESIZE];
     FILE *infile[MERGEORDER];
     FILE *outfile;
     char *lineptr[MAXPTR];
     int nlines, t, outlow, outhigh, mergelow, mergehigh;

     outlow = 1;
     mergelow = outlow + N;
     mergehigh = mergelow-1;
     for (;;) {
          /*
           * Read chunks from stdin and write to files outlow...outhigh.
           */
          for (outhigh = outlow; outhigh < outlow+N; outhigh++) {
               t = gtext(lineptr, MAXPTR, linebuf, MAXTEXT, &nlines, stdin);
               qsort(lineptr, nlines, sizeof(lineptr[0]), qcmpstr);
               outfile = makefile(outhigh);
               ptext(lineptr, nlines, outfile);
               fclose(outfile);
               if (t == EOF)
                    break;
          }
          if (outhigh >= outlow+N)
               outhigh--;

          /*
           * Merge files outlow...outhigh to mergehigh.
           */
          gopen(infile, outlow, outhigh);
          ++mergehigh;
          outfile = makefile(mergehigh);
          merge(infile, outhigh-outlow+1, outfile);
          fclose(outfile);

          /*
           * If the merge group is full, merge them to outlow and exchange
           * merge group and sorting group.
           */
          if (mergehigh-mergelow+1 >= N) {
               gopen(infile, mergelow, mergehigh);
               outfile = makefile(outlow);
               merge(infile, mergehigh-mergelow+1, outfile);
               fclose(outfile);
               swap(&outlow, &mergelow);
               mergehigh = mergelow;
          }
          if (t == EOF)
               break;
     }

     gopen(infile, mergelow, mergehigh);
     merge(infile, mergehigh-mergelow+1, stdout);
     gopen(infile, 1, 2*N);
     gremove(infile, 1, 2*N);
     return 0;
}
Exemple #3
0
int main()
{
  int win, win2, win3;
  double t = 0, h = 2 * M_PI / 100, quit = 0, run = 1;
  double clr2 = 0, clr3 = 0;
  double r[6] = { 0 };

  param_set prms = { &win, &win2, &win3, &F, &D, &B, &t, &h,
    &clr2, &clr3, &run, r
  };
  e_ctrl ctrls[] = {
    {"Force", &F, 0.1, &init, &prms},
    {"Dumping", &D, 0.01, &init, &prms},
    {"Nonlinear", &B, 0.1, &init, &prms},
    {"_Clear Phase", &clr2, 0, NULL, NULL},
    {"_Clear Poincare", &clr3, 0, NULL, NULL},
    {"_Run", &run, 0, NULL, NULL},
    {"_Quit", &quit, 0, NULL, NULL},
  };
  int cwin;
  cwin = init_ctrls(ctrls, 7);

  win = gopen(2 * WD + 2 * MG, HT);
  win2 = gopen(WD + MG, HT);
  win3 = gopen(WD + MG, HT);
  window(win, 0, -HT / 2, 2 * WD + 2 * MG, HT / 2 - 1);
  window(win2, -(MG + WD) / 2, -HT / 2, (WD + MG) / 2 - 1, HT / 2 - 1);
  window(win3, -(MG + WD) / 2, -HT / 2, (WD + MG) / 2 - 1, HT / 2 - 1);
  winname(win2, "Phase chart");
  winname(win3, "Poincare chart");
  layer(win, 0, 1);
  layer(win2, 0, 1);
  layer(win3, 0, 1);
  gsetbgcolor(win, ECTRL_BGCOLOR);
  gsetbgcolor(win2, ECTRL_FGCOLOR);
  gsetbgcolor(win3, ECTRL_FGCOLOR);
  newcolor(win, ECTRL_FGCOLOR);
  newcolor(win2, ECTRL_BGCOLOR);
  newcolor(win3, "red3");
  gclr(win2);
  gclr(win3);
  gsetnonblock(ENABLE);

  while (!quit) {
    int iscwin, type, button;
    double wx, wy;
    iscwin = ggetxpress(&type, &button, &wx, &wy);
    display_ctrls(cwin, ctrls, 7, wx, wy, iscwin, type, button);
    if (run) {
      rk4fixv6(duffing, t, r, h);
      t += h;
      draw(&prms);
    }
    msleep(5);
  }
  gcloseall();
  return 0;
}
Exemple #4
0
int websPageOpen(webs_t wp, char_t *lpath, char_t *path, int mode, int perm)
{
#if defined(WIN32)
	errno_t	error;
#endif
	a_assert(websValid(wp));
#ifdef WEBS_PAGE_ROM
	return websRomPageOpen(wp, path, mode, perm);
#elif defined(WIN32)
	error = _sopen_s(&(wp->docfd), lpath, mode, _SH_DENYNO, _S_IREAD);
	return (wp->docfd = gopen(lpath, mode, _S_IREAD));
#else
	return (wp->docfd = gopen(lpath, mode, perm));
#endif /* WEBS_PAGE_ROM */
}
Exemple #5
0
int
InitScreen()
{
	char	*sb_dev, *driver;
	
	printnbits();

	sb_dev = getenv("SB_OUTDEV");   
	if(!sb_dev) sb_dev = getenv("OUTDEV");   
	if(!sb_dev) sb_dev = "/dev/crt1";

	driver = getenv("SB_OUTDRIVER");
	if(!driver) driver = getenv("OUTDRIVER");
	if (!driver ) driver = "hp98731";
	
	fildes = gopen(sb_dev,OUTDEV,driver,INIT|INT_XFORM);
	interior_style(fildes,INT_SOLID,FALSE);
	
	intvdc_extent(fildes,0,0,SIZE, SIZE);
	mapping_mode(fildes,FALSE);
	
	drawing_mode(fildes,6);	  /* xor mode */
	
	clear_control(fildes, CLEAR_VIEWPORT);
	fill_color(fildes, 1.0, 1.0, 1.0);
	
	return(fildes);
}
Exemple #6
0
//--------------------------------メイン--------------------------------------
int main(void){
  int seed;
  
  //ランダム関数設定
  printf("適当に何か入力してreturnを押してください >> ");
  scanf("%d", &seed);
  srand(seed);  
  
  //落ちてくる物体の初期値設定
  syoki_buttai();
    
  //画面表示
  win=gopen(400, 500);
  winname(win, "DODGE GAME");
  
  STA();//スタート画面 
  if(ggetevent(&type, &code, &s, &t)==win){//入力待ち
    if(code==0x073){// sキーを入力した場合
      game();
    }
    else if(code == 0x075){// fキーを押した場合
      return 0;
    }
  }
  return 0;
}
Exemple #7
0
/* Open pseudo tty interface and (in due course create a symlink
   to be /dev/gnokii etc. ) */
static int VM_PtySetup(const char *bindir)
{
	char mgnokiidev[200];

	if (UseSTDIO) {
		PtyRDFD = STDIN_FILENO;
		PtyWRFD = STDOUT_FILENO;
		return (0);
	}

	if (bindir) {
		strncpy(mgnokiidev, bindir, sizeof(mgnokiidev));
		strncat(mgnokiidev, "/", sizeof(mgnokiidev) - strlen(mgnokiidev));
	} else {
		mgnokiidev[0] = 0;
	}

	strncat(mgnokiidev, "mgnokiidev", sizeof(mgnokiidev) - strlen(mgnokiidev));

	if (access(mgnokiidev, X_OK) != 0) {
		fprintf(stderr, _("Cannot access %s, check the bindir in your config file!\n"), mgnokiidev);
		exit(1);
	}

	PtyRDFD = gopen(mgnokiidev);

	if (PtyRDFD < 0) {
		fprintf (stderr, _("Couldn't open pty!\n"));
		return(-1);
	}
	PtyWRFD = PtyRDFD;

	return (0);
}
Exemple #8
0
int main()
{
    time_t time_now ;
    int win ;
    char d0[8],d1[8],d2[8],d3[8], t0[16] ;

    gsetinitialattributes(ENABLE,DOCK_APPLICATION) ;
    win = gopen(56,56) ;
    layer(win,0,1) ;
    while(1){
	time(&time_now) ;
	sscanf(ctime(&time_now),"%s %s %s %s %s\n",d0,d1,d2,t0,d3) ;
	gclr(win) ;
	newrgbcolor(win,0xff,0xff,0xff) ;
	drawstr(win,4,1, 8 ,0,"%s %s %s",d0,d1,d2) ;
	drawstr(win,4,46, 10 ,0,"%s",t0) ;
	gputimage(win,0,10,Ppmimage,PPM_WIDTH,PPM_HEIGHT,0) ;
	newrgbcolor(win,0x40,0x40,0x40) ;
	moveto(win,0,0) ;
	lineto(win,0,55) ;
	lineto(win,55,55) ;
	newrgbcolor(win,0xe7,0xe7,0xe7) ;
	lineto(win,55,0) ;
	lineto(win,0,0) ;
	copylayer(win,1,0) ;
	msleep(200) ;
    }
    gcloseall() ;
    return(0) ;
}
Exemple #9
0
//=================================================================================
void bTrack::writeBinnedProf(const char *fname){
	if(fProfile==0) fProfile=new FloatArray();
	fProfile->init(NA);
	name=strdup(fname);
	char pfil[4096];
	readInputTrack(makeFileName(pfil,trackPath,name));

	//================================================= Normalize

	errStatus="WriteBinnedProfile";
	//============================ calculate min, max, average, std deviation
//	for(int i=0; i<profileLength; i++){
//		float x=fProfile->get(i);
////		if(trackType==BED_TRACK){
////			if(x == 0) fProfile->set(i,x=NA);
////		}
////		if(x!=NA) fProfile->set(i,x*1000);
//	}

	char wfil[4096];
	makeFileName(pfil,trackPath,name);

	char *s=strrchr(pfil,'/'); if(s==0) s=wfil;
	s=strrchr(s,'.'); if(s) *s=0;
	sprintf(wfil,"%s_%i.bgr",pfil,binSize);

	FILE *f=gopen(wfil,"w");
	fprintf(f,"track type=bedGraph name=\"%s\" description=\"Binned track. Binsize=%i\"\n",name, binSize);
	writeBedGr(f,fProfile, NA,  NA);

	fclose(f);
}
Exemple #10
0
int main()
{
    int win ;
    time_t time_now ;
    char d0[8],d1[8],d2[8],d3[8], t0[16] ;

    /* open a graphic window */
    win = gopen(FONTSIZE*24/2+4,FONTSIZE+4) ;
    /* set name of window */
    winname(win,"Simple Clock") ;
    /* configure layer */
    layer(win,0,1) ;
    /* display time... */
    while(1){
        time(&time_now) ;
        sscanf(ctime(&time_now),"%s %s %s %s %s",d0,d1,d2,t0,d3) ;
	gclr(win) ;
	drawstr(win,2,2,FONTSIZE,0,"%s %s %s %s %s",d0,d1,d2,t0,d3) ;
	copylayer(win,1,0) ;
	msleep(200) ;
    }
    /* close a graphic window */
    gclose(win) ;

    return(0) ;
}
Exemple #11
0
static void memLeaks() 
{
	int		fd;

	if ((fd = gopen(T("leak.txt"), O_CREAT | O_TRUNC | O_WRONLY, 0666)) >= 0) {
		bstats(fd, printMemStats);
		close(fd);
	}
}
Exemple #12
0
char_t *ejEvalFile(int eid, char_t *path, char_t **emsg)
{
	gstat_t sbuf;
	ej_t	*ep;
	char_t	*script, *rs;
	char	*fileBuf;
	int		fd;

	a_assert(path && *path);

	if (emsg) {
		*emsg = NULL;
	}

	if ((ep = ejPtr(eid)) == NULL) {
		return NULL;
	}

	if ((fd = gopen(path, O_RDONLY | O_BINARY, 0666)) < 0) {
		ejError(ep, T("Bad handle %d"), eid);
		return NULL;
	}
	
	if (gstat(path, &sbuf) < 0) {
		gclose(fd);
		ejError(ep, T("Cant stat %s"), path);
		return NULL;
	}
	
	if ((fileBuf = balloc(B_L, sbuf.st_size + 1)) == NULL) {
		gclose(fd);
		ejError(ep, T("Cant malloc %d"), sbuf.st_size);
		return NULL;
	}
	
	if (gread(fd, fileBuf, sbuf.st_size) != (int)sbuf.st_size) {
		gclose(fd);
		bfree(B_L, fileBuf);
		ejError(ep, T("Error reading %s"), path);
		return NULL;
	}
	
	fileBuf[sbuf.st_size] = '\0';
	gclose(fd);

	if ((script = ballocAscToUni(fileBuf, sbuf.st_size)) == NULL) {
		bfree(B_L, fileBuf);
		ejError(ep, T("Cant malloc %d"), sbuf.st_size + 1);
		return NULL;
	}
	bfree(B_L, fileBuf);

	rs = ejEvalBlock(eid, script, emsg);

	bfree(B_L, script);
	return rs;
}
Exemple #13
0
int main(int argc, char **argv)
{
  int win, win2;
  double quit = 0, run = 1, t = 0, h = 0.05;
  double x0 = -40, IR = R / 3;

  param_set prms = { &win, &win2, &x0, &IR, &h, &run, &quit };
  e_ctrl ctrls[] = {
    {"Step", &h, 0.01, NULL, NULL},
    {"X0", &x0, 1, &init, &prms},
    {"Inner radius", &IR, 1, &init, &prms},
    {"_Run", &run, 0, NULL, NULL},
    {"_Quit", &quit, 0, NULL, NULL}
  };
  int cwin;
  cwin = init_ctrls(ctrls, 5);

  srand48(time(NULL));
  win = gopen(2 * R, 2 * R);
  win2 = gopen(2 * R, R);
  window(win, -R, -R, R - 1, R - 1);
  gsetbgcolor(win, WCOLOR);
  gsetbgcolor(win2, ECTRL_FGCOLOR);
  newcolor(win, ECTRL_FGCOLOR);
  layer(win, 0, 1);
  layer(win2, 0, 1);
  gsetnonblock(ENABLE);
  init(&prms);
  run = 1;
  while (!quit) {
    int iscwin, type, button;
    double wx, wy;
    iscwin = ggetxpress(&type, &button, &wx, &wy);
    display_ctrls(cwin, ctrls, 5, wx, wy, iscwin, type, button);
    if (run) {
      step(&prms);
      draw(&prms);
      t += h;
    }
    msleep(40);
  }
  gcloseall();
  return 0;
}
Exemple #14
0
int websPageOpen(webs_t wp, char_t *lpath, char_t *path, int mode, int perm)
{
	a_assert(websValid(wp));

#ifdef WEBS_PAGE_ROM
	return websRomPageOpen(wp, path, mode, perm);
#else
	return (wp->docfd = gopen(lpath, mode, perm));
#endif /* WEBS_PAGE_ROM */
}
Exemple #15
0
void open_files(char *name)
{
    char name1[200],name2[200],name4[200];
    int oflag;

    oflag=O_CREAT | O_TRUNC | O_WRONLY;

    if(NO_OUTPUT_FILE)return;

    if(CALC_VOLUME_ONLY)return;

    strcpy(Gfilename,name);
    strcpy(name4,name);
    strcat(name4,"_1st.poly");

    if(DIFF_LEVEL_FILES)return;

    strcpy(name1,name);
    strcat(name1,".poly");
    strcpy(name2,name);
    strcat(name2,"_untiled.poly");

    strcpy(poly_file_name, name1);

#ifdef i860
    if((Tiled_fd=gopen(name1,oflag,M_LOG,0644))==-1) file_open_error(name1);
    if((Untiled_fd=gopen(name2,oflag,M_LOG,0644))==-1)file_open_error(name2);
#else

    Tiled_fd = fopen(name1,"w");
    if (Tiled_fd == 0) file_open_error(name1);

    Untiled_fd = fopen(name1,"w");
    if (Untiled_fd == 0) file_open_error(name2);

    if(STORE_1ST_PASS)
    {
        if((Debug_fd = fopen(name4, "w"))==0) file_open_error(name1);
    }
#endif
}
Exemple #16
0
/*********************************************************************************************************
** 函数名称: memLeaks
** 功能描述: 测试内存泄露
** 输 入  : NONE
** 输 出  : NONE
** 全局变量:
** 调用模块:
*********************************************************************************************************/
static int memLeaks(int argc, char *argv[])
{
    int fd;

    if (argc < 2) {
        bstats(STDOUT_FILENO, printMemStats);
        return 0;
    } else if ((fd = gopen(T(argv[1]), O_CREAT | O_TRUNC | O_WRONLY, 0644)) >= 0) {
        bstats(fd, printMemStats);
        gclose(fd);
    }

    return 0;
}
Exemple #17
0
void smooth(const char *fname){
	outLC=1;
	initOutLC();
	int l=profileLength;
	bTrack *tr=new bTrack(fname);

	for(int i=0,k=0; i<l; i+=wProfStep,k++){
		double d;
		d=100.*k/(l/wProfStep);
		if(k%10000 ==0) verb("\nSmooother: %4.1f%% (%6i/%i) ",d,k,l/wProfStep);
		else if(k%1000 ==0) verb(".");
		double *pr1=tr->getProfile(i,0);		// decode the first profile. Decoder uses hasCompl and complFg flags and combines profiles
		if(smoothProf==0) getMem(smoothProf,profWithFlanksLength+10, "storeCorrTrack");
		if(smTmp==0)      getMem(smTmp,profWithFlanksLength+10, "storeCorrTrack");
		kern->fftx(pr1,0);
		calcSmoothProfile(&(kern->fx),0, 0);	// calculate smooth ptrofile c=\int f*\rho
		addLCProf(LCorrelation.re,i);
	}
	char pfil[4096],wfil[4096];
	makeFileName(pfil,trackPath,fname);

	char *s=strrchr(pfil,'/'); if(s==0) s=wfil;
	s=strrchr(s,'.'); if(s) *s=0;
	sprintf(wfil,"%s_sm.bgr",pfil);

	//================ normalize
	double tt=0,ee=0,dd=0,nn=0;
	for(int i=0; i<l; i++) {
		double x=lcProfile->get(i);
		ee+=x; nn++; dd+=x*x;
	}
	tt=ee; ee/=nn; dd=dd/nn-ee*ee; dd=sqrt(dd);

	for(int i=0; i<l; i++) {
		double x=lcProfile->get(i);
		if(smoothZ){if((x-ee)/dd < smoothZ) x=0;}
		else	   {x=x*tr->total/tt/binSize;}
		lcProfile->set(i,x);
	}

	FILE *f=gopen(wfil,"w");
	char b[4096]; strcpy(b,fname);
	s=strrchr(b,'.'); if(s) *s=0;
	s=strchr(b,'/'); if(s==0) s=b;
	fprintf(f,"track type=bedGraph name=\"%s_Sm\" description=\"Smoothed track. Width=%.0f\"\n",s, kernelSigma);
	verb("\n Write Smooth profile...\n");
	writeBedGr(f,lcProfile, NA,  NA);
	verb("   Done\n");
}
Exemple #18
0
int main()
{
  int win;
  double angle = 30, ratio = 5, run = 0, reset = 0, quit = 0;
  double t = 0, h = 0.1;
  double sx, sy, bx, by;

  param_set prms = {
    &win, &angle, &ratio, &t, &h, &run, &reset,
    &sx, &sy, &bx, &by
  };

  e_ctrl ctrls[] = {
    {"Angle", &angle, 1, &init, &prms},
    {"Ratio M/m", &ratio, 1, &init, &prms},
    {"Step", &h, 0.01, &init, &prms},
    {"_Run", &run, 0, NULL, NULL},
    {"_Reset", &reset, 0, &init, &prms},
    {"_Quit", &quit, 0, NULL, NULL}
  };
  int cwin;
  cwin = init_ctrls(ctrls, 6);

  win = gopen(WD, HT);
  layer(win, 0, 1);
  gsetbgcolor(win, ECTRL_BGCOLOR);
  newcolor(win, ECTRL_BGCOLOR);
  init(&prms);
  gsetnonblock(ENABLE);

  while (!quit) {
    int iscwin, type, button;
    double wx, wy;
    iscwin = ggetxpress(&type, &button, &wx, &wy);
    display_ctrls(cwin, ctrls, 6, wx, wy, iscwin, type, button);
    if (run) {
      t += h;
      step(&prms);
      draw(&prms);
      if (by < 0)
	run = 0;
    }
    msleep(40);
  }
  gcloseall();

  return 0;
}
Exemple #19
0
int main()
{
    int win;
    int cnt;
    float x_cen = X_CEN;
    float y_cen = Y_CEN;

    win = gopen(WIDTH,HEIGHT);

    puts("Move your mouse cursor on the window :-)");

    /* レイヤの設定をする */
    layer(win, 0,1);
    /* ノンブロックモードにする */
    gsetnonblock(ENABLE);

    cnt = 0;
    while ( 1 ) {
	int win_ev;	/* イベントのあったウィンドゥ番号 */
	int type, b;	/* イベントのタイプ,ボタン */
	float r, x, y;
	win_ev = ggetevent(&type,&b,&x,&y) ;
	if ( win_ev == win ) {
	    if ( type == MotionNotify ){
		x_cen = x;
		y_cen = y;
	    }
	    else if ( type == ButtonPress ) {
		break;
	    }
	}
	else {
	    int i;
	    if ( CNT_MAX <= cnt ) cnt = 0;
	    gclr(win);
	    for ( i=0 ; i < 4 ; i++ ) {
		r = pow((cnt+i*(CNT_MAX/4)) % CNT_MAX, 2)/DIV;
		drawcirc(win,x_cen,y_cen,r,r);
	    }
	    copylayer(win, 1,0);
	    msleep(20);
	    cnt++;
	}
    }
    gclose(win);

    return(0);
}
Exemple #20
0
int main(int argc, char **argv)
{
  int win;
  double chbg = 0, quit = 0;
  double order = 8, rt = 0.8, ra = 15, rnd = 0.1;
  int bgcolor_r = 0x036 - 48, bgcolor_g = 0x064 - 48, bgcolor_b =
      0x088 - 48;

  param_set prms = {
    &win, &order, &rt, &ra, &rnd, &chbg,
    &bgcolor_r, &bgcolor_g, &bgcolor_b
  };

  e_ctrl ctrls[] = {
    {"Order", &order, 1, &remake_all, &prms},
    {"Ratio", &rt, 0.01, &remake_all, &prms},
    {"Angle", &ra, 1, &remake_all, &prms},
    {"Randomness", &rnd, 0.01, &remake_all, &prms},
    {"_Change bgcolor", &chbg, 0, &change_bgcolor, &prms},
    {"_Quit", &quit, 0, NULL, NULL},
  };

  int cwin;
  cwin = init_ctrls(ctrls, 6);

  srand48(time(NULL));
  win = gopen(L, L);
  window(win, -L / 2, 0, L / 2 - 1, L - 1);
  winname(win, "Snow falls on fractal tree");
  layer(win, 0, 1);
  remake_all(&prms);
  gsetnonblock(ENABLE);

  while (!quit) {
    int type, button, iscwin;
    double wx, wy;
    if (order > 11)
      order = 12;
    iscwin = ggetxpress(&type, &button, &wx, &wy);
    display_ctrls(cwin, ctrls, 6, wx, wy, iscwin, type, button);
    draw(win, prms.snowx, prms.snowy, MAXSNOW);
    msleep(40);
  }
  gcloseall();
  return 0;
}
Exemple #21
0
int main(int argc, char **argv)
{
  int win;
  double angle = 10, run = 0, reset = 0, quit = 0;
  double t = 0, h = 0.0001;
  param_set prms = {&win, &angle, &t, &run, &reset};

  e_ctrl ctrls[] = {
    {"Initial Angle", &angle, 1, &init, &prms},
    {"_Run", &run, 0, NULL, NULL},
    {"_Reset", &reset, 0, &init, &prms},
    {"_Quit", &quit, 0, NULL, NULL}
  };
  int cwin;
  cwin = init_ctrls(ctrls, 4);

  gsetinitialbgcolor(ECTRL_BGCOLOR);
  win = gopen(WD, HT);
  newlinewidth(win, 6);
  window(win, -WD/2, -MG, WD/2, HT-MG);
  layer(win, 0, 1);
  init(&prms);
  gsetnonblock(ENABLE);

  while (!quit) {
    int iscwin, type, button;
    double wx, wy;
    iscwin = ggetxpress(&type, &button, &wx, &wy);
    display_ctrls(cwin, ctrls, 4, wx, wy, iscwin, type, button);
    if (run) {
      rk4fixv6(rod, t, prms.r, h);
      t += h;
      if ((int)(t*RH) % (RH/100) == 0 ) {
        draw(&prms); msleep(10);
      }
      if (prms.r[0] >= M_PI/2) {
         run = 0;
         post(&prms);
      }
    }
  }
  gcloseall();

  return 0;
}
Exemple #22
0
int main(int argc, char *argv[])
{
  int win;
  double R = 2 * L / 3, r_inc = 10, run = 0, reset = 0, quit = 0;
  double agg_prob = 1, mid, src_r = 0, new_r = 1, rem_r = 0;

  param_set prms = { &win, &R, &agg_prob, &r_inc, &run, &reset,
    &mid, &src_r, &new_r, &rem_r
  };

  e_ctrl ctrls[] = {
    {"Size", &R, dR, &init, &prms},
    {"Aggr. prob.", &agg_prob, 0.1, &init, &prms},
    {"Radius Inc.", &r_inc, 1, &init, &prms},
    {"_Run", &run, 0, NULL, NULL},
    {"_Reset", &reset, 0, &init, &prms},
    {"_Quit", &quit, 0, NULL, NULL}
  };
  int cwin;
  cwin = init_ctrls(ctrls, 6);

  srand48(time(NULL));
  win = gopen(L, L);
  gsetnonblock(ENABLE);
  init(&prms);

  while (!quit) {
    int iscwin, type, button;
    double wx, wy;
    iscwin = ggetxpress(&type, &button, &wx, &wy);
    display_ctrls(cwin, ctrls, 6, wx, wy, iscwin, type, button);
    if (run)
      draw(&prms);
  }
  gcloseall();
  return 0;
}
Exemple #23
0
int main()
{
  int win, i, j, k, m, key = 0;
  int arp[5] = { 0, 3, 1, 4, 2 }, ars[7] = {
  0, 5, 3, 1, 6, 4, 2};
  double pentagon[3][5], septagon[3][7], parab[3][144], y;

  win = gopen(L, L);
  window(win, -L / 2, -L / 2, L / 2, L / 2);
  gsetbgcolor(win, ECTRL_BGCOLOR);
  newcolor(win, ECTRL_FGCOLOR);
  winname(win, "e_3d demo");
  layer(win, 0, 1);
  gsetnonblock(ENABLE);
  i = j = m = 0;

  for (i = 0; i < 144; i++) {
    y = L/(2*144.0)*i;
    parab[0][i] = 0;
    parab[1][i] = -y;
    parab[2][i] = 0.02*y*(L/2 - y);
  }

  while (key != 'q') {
    g3dsetangle(torad(40 * (1.5 + sin(j * 2 * M_PI / 30))),
		i * 2 * M_PI / 144);
    gclr(win);

    for (k = 0; k < 5; k++) {
      pentagon[0][k] =
	  L / 6 * cos(arp[k] * 2 * M_PI / 5 + m * 2 * M_PI / 50) + L / 5;
      pentagon[1][k] =
	  L / 6 * sin(arp[k] * 2 * M_PI / 5 + m * 2 * M_PI / 50) + L / 5;
      pentagon[2][k] = 0;
    }
    for (k = 0; k < 7; k++) {
      septagon[0][k] =
	  L / 6 * cos(ars[k] * 2 * M_PI / 7 + 2 * m * 2 * M_PI / 50) -
	  L / 5;
      septagon[1][k] = 0;
      septagon[2][k] =
	  L / 6 * sin(ars[k] * 2 * M_PI / 7 + 2 * m * 2 * M_PI / 50) +
	  L / 5;
    }
    newcolor(win, "lightsteelblue");
    newlinestyle(win, LineOnOffDash);
    for(k = 0; k < 6; k++) {
      drawline3d(win, -L/10*k, 0, 0,  -L/10*k, -L/2, 0);
      drawline3d(win, 0, -L/10*k, 0,  -L/2, -L/10*k, 0);
    }
    newlinestyle(win, LineSolid);
    newcolor(win, "red4");
    fillpoly3d(win, pentagon[0], pentagon[1], pentagon[2], 5, 0);
    newcolor(win, "green4");
    fillpoly3d(win, septagon[0], septagon[1], septagon[2], 7, 0);
    newcolor(win, ECTRL_FGCOLOR);
    drawarrow3d(win, 0, 0, 0, 0, 0, L / 3, 10, 6, 12);
    drawarrow3d(win, 0, 0, 0, 0, L / 3, 0, 10, 6, 12);
    drawarrow3d(win, 0, 0, 0, L / 3, 0, 0, 10, 6, 12);
    newcolor(win, "gold3");
    drawstr3d(win, 0, 0, L/3+10, FONTSET, 0, "z¼´");
    drawlines3d(win, parab[0], parab[1], parab[2], 144);
    y = L/(2*36.0)*(i%36);
    putimg24m3d(win, 0 - 6 *(-sin(_phi) - cos(_th)*cos(_phi)), 
                     -y - 6*(cos(_phi) - cos(_th)*sin(_phi)), 
                0.02*y*(L/2 - y) -6*sin(_th), 12, 12, Xpm_image_stone6);
    copylayer(win, 1, 0);
    i++;
    i %= 144;
    j++;
    j %= 30;
    m++;
    m %= 50;
    msleep(40);
    key = ggetch();
  }
  gcloseall();
  return 0;
}
Exemple #24
0
int main()
{
    int i,j,key,sl=0,wl=1 ;
    int shape_i = 11, shape_j = 4 ;
    float f=MRATIO_F ;
    float x,y,zx,zy,z,ph,ms_w,ms_h ;
    float zran=(ZMAX-ZMIN) ;
    float zcen=(ZMAX+ZMIN)/2.0 ;
    color_prms cl = {
	EGGX_COLOR_BEGIN,			/* カラーパターン */
	CP_CONTRAST | CP_BRIGHTNESS | CP_GAMMA,	/* フラグ */
	1.0,					/* コントラスト */
	0.0,					/* ブライトネス*/
	1.0,					/* γ */
    } ;
    int win ;
    int cl_r,cl_g,cl_b ;

    win=gopen(WINWIDTH,WINHEIGHT) ;	/* ウィンドゥのタイトル */
    /* 座標系を変更する */
    coordinate(win, 0,0, XMIN,YMIN, 
	       WINWIDTH/(XMAX-XMIN), WINHEIGHT/(YMAX-YMIN)) ;
    layer(win,sl,wl) ;

    puts("【キーボードでの操作方法】") ;
    puts("'PageUp','PageDown'  … 質量比変更") ;
    puts("'c','C'              … カラーパターン") ;
    puts("'↑','↓','←','→'  … カラー調整") ;
    puts("'[',']'              … コントラスト") ;
    puts("'{','}'              … ブライトネス") ;
    puts("'<','>'              … γ補正") ;
    puts("'s'                  … 画像を保存") ;
    puts("'q','Esc'            … 終了") ;

    ms_w=(float)(XMAX-XMIN)/XSAMPLES ;	/* メッシュ1個分のサイズ */
    ms_h=(float)(YMAX-YMIN)/YSAMPLES ;

    do{
	/* ウィンドゥのタイトル */
	winname(win,"ロッシュワールド('s'キーで画像save) f=%g zcen=%g zran=%g",
		f,zcen,zran) ;
	for( i=0 ; i<XSAMPLES ; i++ ){	/* ポテンシャルを色で表現 */
	    x=XMIN+ms_w*i ;
	    for( j=0 ; j<YSAMPLES ; j++ ){
		y=YMIN+ms_h*j ;
		ph=get_phi(x+ms_w/2.0,y+ms_w/2.0,f) ;
		generatecolor(&cl,zcen-zran/2,zcen+zran/2,ph,
			      &cl_r,&cl_g,&cl_b) ;
		newrgbcolor(win,cl_r,cl_g,cl_b) ;
		fillrect(win,x,y,ms_w*1.5,ms_h*1.5) ;
	    }
	}
	newpen(win,1) ;
	for( i=0 ; i<XSAMPLES ; i++ ){	/* テスト粒子に働く力を矢印で表現 */
	    x=XMIN+ms_w*(i+0.5) ;
	    for( j=0 ; j<YSAMPLES ; j++ ){
		y=YMIN+ms_h*(j+0.5) ;
		zx=get_fx(x,y,f) ;
		zy=get_fy(x,y,f) ;
		zx *= VXSCALE ;
		zy *= VYSCALE ;
		z=sqrt(zx*zx+zy*zy) ;
		if( z <= VCARMAX ){
		    drawarrow(win,x-zx,y-zy,x+zx,y+zy,0.3,0.2,
			      shape_i*10+shape_j) ;
		}
	    }
	}
	sl ^= 1 ;				/* XORをとってレイヤを切替 */
	wl ^= 1 ;
	layer( win,sl,wl ) ;
	key=ggetch() ;				/* キー入力があるまで待つ */
	if( key == 0x002 ) f += 0.1 ;		/* PageUp */
	else if( key == 0x006 ) f -= 0.1 ;	/* PageDown */
	else if( key == 0x01e ) zcen += 0.1 ;	/* ↑ */
	else if( key == 0x01f ) zcen -= 0.1 ;	/* ↓ */
	else if( key == 0x01c ) zran += 0.1 ;	/* → */
	else if( key == 0x01d ) zran -= 0.1 ;	/* ← */
	else if( key == 'i' ) {
	    shape_i += 1 ;
	    if ( 12 < shape_i ) shape_i = 10 ;
	}
	else if( key == 'j' ) {
	    shape_j += 1 ;
	    if ( 7 < shape_j ) shape_j = 1 ;
	}
	else if( key == 'c' ){			/* 'c','C'キーでカラーパターン変更 */
	    cl.colormode++ ;
	    if( EGGX_COLOR_BEGIN+EGGX_COLOR_NUM <= cl.colormode )
		cl.colormode=EGGX_COLOR_BEGIN ;
	}
	else if( key == 'C' ){
	    cl.colormode-- ;
	    if( cl.colormode < EGGX_COLOR_BEGIN )
		cl.colormode=EGGX_COLOR_BEGIN+EGGX_COLOR_NUM-1 ;
	}
	else if( key == '[' ){			/* '[',']'でコントラスト変更 */
	    cl.contrast += 0.05 ;
	    if( 1 < cl.contrast ) cl.contrast = 1 ;
	}
	else if( key == ']' ){
	    cl.contrast -= 0.05 ;
	    if( cl.contrast < 0 ) cl.contrast = 0 ;
	}
	else if( key == '{' ){			/* '{','}'でブライトネス変更 */
	    cl.brightness += 0.05 ;
	    if( 1 < cl.brightness ) cl.brightness = 1 ;
	}
	else if( key == '}' ){
	    cl.brightness -= 0.05 ;
	    if( cl.brightness < 0 ) cl.brightness = 0 ;
	}
	else if( key == '<' ){			/* '<','>'でγ変更 */
	    cl.gamma += 0.025 ;
	}
	else if( key == '>' ){
	    cl.gamma -= 0.025 ;
	    if( cl.gamma <= 0 ) cl.gamma = 0.025 ;
	}
	else if( key == 's' ){			/* 's'キーで保存 */
#ifdef USE_NETPBM
	    saveimg( win,sl,XMIN,YMIN,XMAX,YMAX,
		     "pnmtops -noturn -dpi 72 -equalpixels -psfilter -flate -ascii85",256,
		     "roche_f=%g.eps",f) ;
	    printf("画像を保存: filename='roche_f=%g.eps'\n",f) ;
#else
#ifdef USE_IMAGEMAGICK
	    saveimg( win,sl,XMIN,YMIN,XMAX,YMAX,"convert",256,
		     "roche_f=%g.png",f) ;
	    printf("画像を保存: filename='roche_f=%g.png'\n",f) ;
#else
	    saveimg( win,sl,XMIN,YMIN,XMAX,YMAX,"",256,
		     "roche_f=%g.ppm",f) ;
	    printf("画像を保存: filename='roche_f=%g.ppm'\n",f) ;
#endif
#endif
	}
	if( f < 0 ) f=0 ;
	if( zran < 0 ) zran=0.1 ;
    } while( key != 0x01b && key != 'q' ) ;	/* ESCキーか 'q'キーで終了 */

    gcloseall() ;
    return(0) ;
}
Exemple #25
0
static int compile( char_t* fileList, char_t* prefix )
{
    gstat_t			sbuf;
    FILE*			lp;
    time_t			now;
    char_t			file[FNAMESIZE];
    char_t*			cp, *sl;
    char			buf[512];
    unsigned char*	p;
    int				j, i, len, fd, nFile;

    /*
     *	Open list of files
     */
    if ( ( lp = fopen( fileList, "r" ) ) == NULL )
    {
        fprintf( stderr, "Can't open file list %s\n", fileList );
        return -1;
    }

    time( &now );
    fprintf( stdout, "/*\n * webrom.c -- Compiled Web Pages\n *\n" );
    fprintf( stdout, " * Compiled by GoAhead WebCompile: %s */\n\n",
             gctime( &now ) );
    fprintf( stdout, "#include \"wsIntrn.h\"\n\n" );
    fprintf( stdout, "#ifndef WEBS_PAGE_ROM\n" );
    fprintf( stdout, "websRomPageIndexType websRomPageIndex[] = {\n" );
    fprintf( stdout, "    { 0, 0, 0 },\n};\n" );
    fprintf( stdout, "#else\n" );
    /*
     *	Open each input file and compile each web page
     */
    nFile = 0;

    while ( fgets( file, sizeof( file ), lp ) != NULL )
    {
        if ( ( p = strchr( file, '\n' ) ) || ( p = strchr( file, '\r' ) ) )
        {
            *p = '\0';
        }

        if ( *file == '\0' )
        {
            continue;
        }

        if ( gstat( file, &sbuf ) == 0 && sbuf.st_mode & S_IFDIR )
        {
            continue;
        }

        if ( ( fd = gopen( file, O_RDONLY | O_BINARY ) ) < 0 )
        {
            fprintf( stderr, "Can't open file %s\n", file );
            return -1;
        }

        fprintf( stdout, "static unsigned char page_%d[] = {\n", nFile );

        while ( ( len = read( fd, buf, sizeof( buf ) ) ) > 0 )
        {
            p = buf;

            for ( i = 0; i < len; )
            {
                fprintf( stdout, "    " );

                for ( j = 0; p < &buf[len] && j < 16; j++, p++ )
                {
                    fprintf( stdout, "%3d,", *p );
                }

                i += j;
                fprintf( stdout, "\n" );
            }
        }

        fprintf( stdout, "    0 };\n\n" );
        close( fd );
        nFile++;
    }

    fclose( lp );
    /*
     *	Now output the page index
     */
    fprintf( stdout, "websRomPageIndexType websRomPageIndex[] = {\n" );

    if ( ( lp = fopen( fileList, "r" ) ) == NULL )
    {
        fprintf( stderr, "Can't open file list %s\n", fileList );
        return -1;
    }

    nFile = 0;

    while ( fgets( file, sizeof( file ), lp ) != NULL )
    {
        if ( ( p = strchr( file, '\n' ) ) || ( p = strchr( file, '\r' ) ) )
        {
            *p = '\0';
        }

        if ( *file == '\0' )
        {
            continue;
        }

        /*
         *		Remove the prefix and add a leading "/" when we print the path
         */
        if ( strncmp( file, prefix, gstrlen( prefix ) ) == 0 )
        {
            cp = &file[gstrlen( prefix )];
        }

        else
        {
            cp = file;
        }

        while ( ( sl = strchr( file, '\\' ) ) != NULL )
        {
            *sl = '/';
        }

        if ( *cp == '/' )
        {
            cp++;
        }

        if ( gstat( file, &sbuf ) == 0 && sbuf.st_mode & S_IFDIR )
        {
            fprintf( stdout, "    { T(\"/%s\"), 0, 0 },\n", cp );
            continue;
        }

        fprintf( stdout, "    { T(\"/%s\"), page_%d, %d },\n", cp, nFile,
                 sbuf.st_size );
        nFile++;
    }

    fclose( lp );
    fprintf( stdout, "    { 0, 0, 0 },\n" );
    fprintf( stdout, "};\n" );
    fprintf( stdout, "#endif /* WEBS_PAGE_ROM */\n" );
    fclose( lp );
    fflush( stdout );
    return 0;
}
Exemple #26
0
void Confounder(){
	bTrack *confdr=new bTrack();
	if(confFile==0) confFile=strdup("confounder");
	confdr->trackType=BED_GRAPH;
	confdr->hasCompl=0;
	confdr->name=confFile;
	confdr->initProfile();
	VectorX v=VectorX();
	VectorX cnf=VectorX();
	FILE *f;
	char b[4096];
	for(int i=0; i<nfiles; i++){
		cnf.v[i]=eVectors->get(i,0);
	}
	verb("\n");
	if(verbose) {verb("confounder: "); cnf.print(stdout);}

	double min=1.e+100, max=-1.e+100, e=0;
	int nn=0;
	int na0=0;
	verb("Make Confounder...\n");
	for(int i=0; i<profileLength; i++){
		if(i%1000000 ==0) verb("%5.1f%%\r",1.*i/profileLength*100);
		v.get(i);
		if(v.v[0]==NA) na0++;
		double w=v.scalar(cnf);
		if(w==NA){
			fProfile->set(i,w);
			continue;
		}
		fProfile->set(i,w);	//finProfile will divide by bisize
		e+=w; nn++;
		if(w<min) min=w;
		if(w>max) max=w;
	}
	verb("\n");
	e/=nn;
	if(e < 0){
		min=1.e+100; max=-1.e+100; e=0;
		for(int i=0; i<profileLength; i++){
			double w=fProfile->get(i);
			if(w==NA) continue;
			fProfile->set(i,(w=-w));
			e+=w;
			if(w<min) min=w;
			if(w>max) max=w;
		}
	}
	//================================================ Norm
	confdr->finProfile();
	//=================================================== Write wig
	makeFileName(b,trackPath, confFile, BGR_EXT);
	f=gopen(b,"wt");
	fprintf(f,"track type=bedGraph name=\"%s\" ", confFile);
	fprintf(f,"description=\"confounder\" \n");
	for(int i=0; i<nfiles; i++){
		fprintf(f,"#%s\n",files[i].fname);
	}
	verb("Write confounder profile...\n");

	writeBedGr(f,fProfile);
	verb("\n");
	fclose(f);

	confdr->writeProfilePrm();
	confdr->writeByteProfile();
	del(fProfile); fProfile=0;
	del(confdr);
}
Exemple #27
0
int main( int argc, char *argv[] )
{
    int ret = 1;
    int win_main, win_zoom, zoom_factor = 2;
    double p_x = -1, p_y = -1;
    unsigned char *zoom_buf = NULL;
    unsigned char *img_buf = NULL;
    int img_width, img_height, img_msk;
    int crosshairs = 1;

    if ( argc < 2 ) {
	fprintf(stderr,"[USAGE]\n");
	fprintf(stderr,"%s filename.png\n",argv[0]);
	return 1;
    }

    /* zoom ウィンドゥ用の画像バッファ */
    zoom_buf = (unsigned char *)malloc(ZOOMWN_WIDTH * ZOOMWN_HEIGHT * 4);
    if ( zoom_buf == NULL ) goto quit;

    //img_buf = readimage(NULL,argv[1],&img_width,&img_height,&img_msk);
    //img_buf = readimage("xbmtopbm",argv[1],&img_width,&img_height,&img_msk);
#ifdef USE_IMAGEMAGICK
    img_buf = readimage("convert",argv[1],&img_width,&img_height,&img_msk);
#else
    img_buf = readimage("pngtopnm",argv[1],&img_width,&img_height,&img_msk);
#endif
    if ( img_buf == NULL ) {
	fprintf(stderr,"ERROR: cannot read file\n");
	goto quit;
    }
    printf("mask value = %d\n",img_msk);

    /* 属性設定(左上を原点にする) */
    gsetinitialattributes(DISABLE, BOTTOM_LEFT_ORIGIN);
    /* ウィンドゥのオープン */
    win_zoom = gopen(ZOOMWN_WIDTH*2, ZOOMWN_HEIGHT);
    win_main = gopen(img_width, img_height);
    layer(win_zoom,0,1);

    /* メインウィンドゥへの画像の転送 */
    gclr(win_main);
    gputimage(win_main, 0,0, img_buf, img_width, img_height, img_msk);

    /* カーソル描画のために,XOR での描画functionに設定 */
    newgcfunction(win_main, GXxor);
    newcolor(win_main, "red");

#if 0	/* 保存のテスト */
    //writeimage(img_buf,img_width,img_height,img_msk,"pnmtopng",256,"hoge.png");
    //writeimage(img_buf,img_width,img_height,img_msk,NULL,256,"hoge.pam");
    gsaveimage( win_main,0,0,0,1999,1999,"pnmtopng",256,"capt0.png");
    {
	int im_w, im_h;
	unsigned char *im = ggetimage(win_main,0,0,0,1999,1999,&im_w,&im_h);
	writeimage(im_w,im_h,im,0,"pnmtopng",256,"capt.png");
	if ( im != NULL ) free(im);
    }
#endif

    /* メインループ */
    while ( 1 ) {
	int win_ev, type, b;
	int needs_redraw = 0;
	double x, y;
	win_ev = ggetevent(&type,&b,&x,&y) ;
	if ( type == EnterNotify ) {
	    fprintf(stderr,"event type = EnterNotify wid=%d\n",win_ev);
	}
	else if ( type == LeaveNotify ) {
	    fprintf(stderr,"event type = LeaveNotify wid=%d\n",win_ev);
	}
	else {
	    fprintf(stderr,"event type = %d wid=%d\n",type,win_ev);
	}
	if ( win_ev == win_main ) {
	    if ( type == MotionNotify || 
		 type == EnterNotify || type == LeaveNotify ) {
		if ( type == LeaveNotify ) {
		    x = -32000;  y = -32000;
		}
		if ( crosshairs ) {
		    /* crosshairs カーソルを消す */
		    drawline(win_main, 0,p_y, img_width,p_y);
		    drawline(win_main, p_x,0, p_x,img_height);
		    /* crosshairs カーソルを表示する */
		    drawline(win_main, 0,y, img_width,y);
		    drawline(win_main, x,0, x,img_height);
		}
		needs_redraw = 1;
		p_x = x;
		p_y = y;
	    }
	    else if ( type == ButtonPress ) {
		if ( b == 1 ) zoom_factor++;
		else if ( b == 3 ) zoom_factor--;
		needs_redraw = 1;
	    }
	}
	if ( type == KeyPress ) {
	    if ( b == 'q' ) goto quit;
	    else if ( b == '>' || b == '+' ) zoom_factor++;
	    else if ( b == '<' || b == '-' ) zoom_factor--;
	    else if ( b == ' ' ) {
		if ( crosshairs ) {
		    /* crosshairs カーソルを消す */
		    drawline(win_main, 0,p_y, img_width,p_y);
		    drawline(win_main, p_x,0, p_x,img_height);
		    crosshairs = 0;
		}
		else {
		    /* crosshairs カーソルを表示する */
		    drawline(win_main, 0,p_y, img_width,p_y);
		    drawline(win_main, p_x,0, p_x,img_height);
		    crosshairs = 1;
		}
	    }
	    needs_redraw = 1;
	}
	if ( needs_redraw ) {
	    if ( zoom_factor < 2 ) zoom_factor = 2;
	    else if ( 32 < zoom_factor ) zoom_factor = 32;
	    get_zoom_image(img_width, img_height,
			   img_buf, p_x, p_y, zoom_factor,
			   ZOOMWN_WIDTH, ZOOMWN_HEIGHT, zoom_buf);
	    gclr(win_zoom);
	    /* 普通のコピー */
	    newgcfunction(win_zoom, GXcopy);
	    gputimage(win_zoom, 0, 0, 
		      zoom_buf, ZOOMWN_WIDTH, ZOOMWN_HEIGHT, img_msk);
	    /* 反転コピー */
	    newgcfunction(win_zoom, GXcopyInverted);
	    gputarea(win_zoom, ZOOMWN_WIDTH, 0, 
		     win_zoom,1, 0,0,ZOOMWN_WIDTH-1, ZOOMWN_HEIGHT-1);
	    /* ズームウィンドゥで,文字列を反転描画する */
	    newgcfunction(win_zoom, GXinvert);
	    drawstr(win_zoom,2,14,14,0,
		    "%dx zoom pos=(%g,%g)\n",zoom_factor,p_x,p_y);
	    copylayer(win_zoom,1,0);
	}
    }

    ret = 0;
 quit:
    gcloseall();
    if ( img_buf != NULL ) free(img_buf);
    if ( zoom_buf != NULL ) free(zoom_buf);
    return ret;
}
Exemple #28
0
int dbSave(int did, char_t *filename, int flags)
{
    int			row, column, nColumns, nRows, fd, rc;
    int			*colTypes, *pRow, nRet, tid;
    char_t		*path, *tmpFile, *tmpNum;
    char_t		**colNames;
    dbTable_t	*pTable;

    trace(5, T("DB: About to save database to file\n"));

    a_assert(dbMaxTables > 0);

    /*
     *	First write to a temporary file, then switch around later.
     */
    fmtAlloc(&tmpFile, FNAMESIZE, T("%s/data.tmp"), basicGetProductDir());
    if ((fd = gopen(tmpFile,
                    O_CREAT | O_TRUNC | O_WRONLY | O_BINARY, 0666)) < 0) {
        trace(1, T("WARNING: Failed to open file %s\n"), tmpFile);
        bfree(B_L, tmpFile);
        return -1;
    }

    nRet = 0;

    for (tid = 0; (tid < dbMaxTables) && (nRet != -1); tid++) {
        pTable = dbListTables[tid];

        if (pTable) {
            /*
             *			Print the TABLE=tableName directive to the file
             */
            rc = dbWriteKeyValue(fd, KEYWORD_TABLE, pTable->name);

            nColumns = pTable->nColumns;
            nRows = pTable->nRows;

            for (row = 0; (row < nRows) && (nRet == 0); row++) {
                pRow = pTable->rows[row];
                /*
                 *				if row is NULL, the row has been deleted, so don't
                 *				write it out.
                 */
                if ((pRow == NULL) || (pRow[0] == '\0') ||
                        (*(char_t *)(pRow[0]) == '\0')) {
                    continue;
                }
                /*
                 *				Print the ROW=rowNumber directive to the file
                 */
                fmtAlloc(&tmpNum, 20, T("%d"), row);
                rc = dbWriteKeyValue(fd, KEYWORD_ROW, tmpNum);
                bfreeSafe(B_L, tmpNum);

                colNames = pTable->columnNames;
                colTypes = pTable->columnTypes;
                /*
                 *				Print the key-value pairs (COLUMN=value) for data cells
                 */
                for (column = 0; (column < nColumns) && (rc >= 0);
                        column++, colNames++, colTypes++) {
                    if (*colTypes == T_STRING) {
                        rc = dbWriteKeyValue(fd, *colNames,
                                             (char_t *)(pRow[column]));
                    } else {
                        fmtAlloc(&tmpNum, 20, T("%d"), pRow[column]);
                        rc = dbWriteKeyValue(fd, *colNames, tmpNum);
                        bfreeSafe(B_L, tmpNum);
                    }
                }

                if (rc < 0) {
                    trace(1, T("WARNING: Failed to write to file %s\n"),
                          tmpFile);
                    nRet = -1;
                }
            }
        }
    }

    gclose(fd);

    /*
     *	Replace the existing file with the temporary file, if no errors
     */
    if (nRet == 0) {
        fmtAlloc(&path, FNAMESIZE, T("%s/%s"), basicGetProductDir(), filename);

        gunlink(path);
        if (grename(tmpFile, path) != 0) {
            trace(1, T("WARNING: Failed to rename %s to %s\n"), tmpFile, path);
            nRet = -1;
        }

        bfree(B_L, path);
    }

    bfree(B_L, tmpFile);

    return nRet;
}
Exemple #29
0
/*
 *	Process a form request. Returns 1 always to indicate it handled the URL
 */
int websCgiHandler(webs_t wp, char_t *urlPrefix, char_t *webDir, int arg, 
		char_t *url, char_t *path, char_t* query)
{
	cgiRec		*cgip;
	sym_t		*s;
	char_t		cgiBuf[FNAMESIZE], *stdIn, *stdOut, cwd[FNAMESIZE];
	char_t		*cp, *cgiName, *cgiPath, **argp, **envp, **ep;
	int			n, envpsize, argpsize, pHandle, cid;
	a_assert(websValid(wp));
	a_assert(url && *url);
	a_assert(path && *path == '/');
	websStats.cgiHits++;
/*
 *	Extract the form name and then build the full path name.  The form
 *	name will follow the first '/' in path.
 */
	gstrncpy(cgiBuf, path, TSZ(cgiBuf));
	if ((cgiName = gstrchr(&cgiBuf[1], '/')) == NULL) {
		websError(wp, 200, T("Missing CGI name"));
		return 1;
	}
	cgiName++;
	if ((cp = gstrchr(cgiName, '/')) != NULL) {
		*cp = '\0';
	}
	fmtAlloc(&cgiPath, FNAMESIZE, T("%s/%s/%s"), websGetDefaultDir(),
		CGI_BIN, cgiName);
#ifndef VXWORKS
/*
 *	See if the file exists and is executable.  If not error out.
 *	Don't do this step for VxWorks, since the module may already
 *	be part of the OS image, rather than in the file system.
 */
	{
		gstat_t		sbuf;
		if (gstat(cgiPath, &sbuf) != 0 || (sbuf.st_mode & S_IFREG) == 0) {
			websError(wp, 200, T("CGI process file does not exist"));
			bfree(B_L, cgiPath);
			return 1;
		}
#if (defined (WIN) || defined (CE))
		if (gstrstr(cgiPath, T(".exe")) == NULL &&
			gstrstr(cgiPath, T(".bat")) == NULL) {
#elif (defined (NW))
			if (gstrstr(cgiPath, T(".nlm")) == NULL) {
#else
		if (gaccess(cgiPath, X_OK) != 0) {
#endif /* WIN || CE */
			websError(wp, 200, T("CGI process file is not executable"));
			bfree(B_L, cgiPath);
			return 1;
		}
	}
#endif /* ! VXWORKS */

         
/*
 *	Get the CWD for resetting after launching the child process CGI
 */
	ggetcwd(cwd, FNAMESIZE);
/*
 *	Retrieve the directory of the child process CGI
 */
	if ((cp = gstrrchr(cgiPath, '/')) != NULL) {
		*cp = '\0';
		gchdir(cgiPath);
		*cp = '/';
	}

/*
 *	Build command line arguments.  Only used if there is no non-encoded
 *	= character.  This is indicative of a ISINDEX query.  POST separators
 *	are & and others are +.  argp will point to a balloc'd array of 
 *	pointers.  Each pointer will point to substring within the
 *	query string.  This array of string pointers is how the spawn or 
 *	exec routines expect command line arguments to be passed.  Since 
 *	we don't know ahead of time how many individual items there are in
 *	the query string, the for loop includes logic to grow the array 
 *	size via brealloc.
 */

	argpsize = 10;
	argp = balloc(B_L, argpsize * sizeof(char_t *));
	*argp = cgiPath;

	n = 1;
	if (gstrchr(query, '=') == NULL) {

		websDecodeUrl(query, query, gstrlen(query));
		for (cp = gstrtok(query, T(" ")); cp != NULL; ) {
			*(argp+n) = cp;
			n++;

			if (n >= argpsize) {
				argpsize *= 2;
				argp = brealloc(B_L, argp, argpsize * sizeof(char_t *));

			}
			cp = gstrtok(NULL, T(" "));

		}
	}
	*(argp+n) = NULL;

/*
 *	Add all CGI variables to the environment strings to be passed
 *	to the spawned CGI process.  This includes a few we don't 
 *	already have in the symbol table, plus all those that are in
 *	the cgiVars symbol table.  envp will point to a balloc'd array of 
 *	pointers.  Each pointer will point to a balloc'd string containing
 *	the keyword value pair in the form keyword=value.  Since we don't
 *	know ahead of time how many environment strings there will be the
 *	for loop includes logic to grow the array size via brealloc.
 */

	envpsize = WEBS_SYM_INIT;
	envp = balloc(B_L, envpsize * sizeof(char_t *));
	n = 0;
	fmtAlloc(envp+n, FNAMESIZE, T("%s=%s"),T("PATH_TRANSLATED"), cgiPath);
	n++;
	fmtAlloc(envp+n, FNAMESIZE, T("%s=%s/%s"),T("SCRIPT_NAME"),
		CGI_BIN, cgiName);
	n++;
	fmtAlloc(envp+n, FNAMESIZE, T("%s=%s"),T("REMOTE_USER"), wp->userName);
	n++;
	fmtAlloc(envp+n, FNAMESIZE, T("%s=%s"),T("AUTH_TYPE"), wp->authType);

	n++;
	for (s = symFirst(wp->cgiVars); s != NULL; s = symNext(wp->cgiVars)) {

		if (s->content.valid && s->content.type == string &&
			gstrcmp(s->name.value.string, T("REMOTE_HOST")) != 0 &&
			gstrcmp(s->name.value.string, T("HTTP_AUTHORIZATION")) != 0) {
			fmtAlloc(envp+n, FNAMESIZE, T("%s=%s"), s->name.value.string,
				s->content.value.string);

			n++;
			if (n >= envpsize) {

				envpsize *= 2;
				envp = brealloc(B_L, envp, envpsize * sizeof(char_t *));
			}
		}
	}


	if (wp->flags & WEBS_CGI_UPLOAD){
		// set filename into enviornment variables 
		fmtAlloc(envp+n, FNAMESIZE, T("%s=%s"), T("UPLOAD_FILENAME"), wp->cgiStdin);
		n++;
	}


	*(envp+n) = NULL;
/*
 *	Create temporary file name(s) for the child's stdin and stdout.
 *	For POST data the stdin temp file (and name) should already exist.
 */

	if (wp->cgiStdin == NULL) {
		wp->cgiStdin = websGetCgiCommName(wp);
	} 
	stdIn = wp->cgiStdin;
	stdOut = websGetCgiCommName(wp);

/*
 *	Now launch the process.  If not successful, do the cleanup of resources.
 *	If successful, the cleanup will be done after the process completes.
 */
	if ((pHandle = websLaunchCgiProc(cgiPath, argp, envp, stdIn, stdOut)) 
		== -1) {
		websError(wp, 200, T("failed to spawn CGI task"));
		for (ep = envp; *ep != NULL; ep++) {
			bfreeSafe(B_L, *ep);
		}
		bfreeSafe(B_L, cgiPath);
		bfreeSafe(B_L, argp);
		bfreeSafe(B_L, envp);
		bfreeSafe(B_L, stdOut);
	} else {
/*
 *		If the spawn was successful, put this wp on a queue to be
 *		checked for completion.
 */
		cid = hAllocEntry((void***) &cgiList, &cgiMax, sizeof(cgiRec));
		cgip = cgiList[cid];
		cgip->handle = pHandle;
		cgip->stdIn = stdIn;
		cgip->stdOut = stdOut;
		cgip->cgiPath = cgiPath;
		cgip->argp = argp;
		cgip->envp = envp;
		cgip->wp = wp;
		cgip->fplacemark = 0;
		websTimeoutCancel(wp);
	}
/*
 *	Restore the current working directory after spawning child CGI
 */
 	gchdir(cwd);
	return 1;
}



/******************************************************************************/
/*
 *	Any entry in the cgiList need to be checked to see if it has
 */
void websCgiGatherOutput (cgiRec *cgip)
{
	gstat_t	sbuf;
	char_t	cgiBuf[FNAMESIZE];
	if ((gstat(cgip->stdOut, &sbuf) == 0) && 
		(sbuf.st_size > cgip->fplacemark)) {
		int fdout;
		fdout = gopen(cgip->stdOut, O_RDONLY | O_BINARY, 0444 );
/*
 *		Check to see if any data is available in the
 *		output file and send its contents to the socket.
 */
		if (fdout >= 0) {
			webs_t	wp = cgip->wp;
			int		nRead;
/*
 *			Write the HTTP header on our first pass
 */
			if (cgip->fplacemark == 0) {
				websWrite(wp, T("HTTP/1.0 200 OK\r\n"));
			}
			glseek(fdout, cgip->fplacemark, SEEK_SET);
			while ((nRead = gread(fdout, cgiBuf, FNAMESIZE)) > 0) {
				websWriteBlock(wp, cgiBuf, nRead);
				cgip->fplacemark += nRead;
			}
			gclose(fdout);
		}
	}
}


/******************************************************************************/
/*
 *	Any entry in the cgiList need to be checked to see if it has
 *	completed, and if so, process its output and clean up.
 */
void websCgiCleanup()
{
	cgiRec	*cgip;
	webs_t	wp;
	char_t	**ep;
	int		cid, nTries;
	for (cid = 0; cid < cgiMax; cid++) {
		if ((cgip = cgiList[cid]) != NULL) {
			int exit_status;
			wp = cgip->wp;
			websCgiGatherOutput (cgip);
			if ( websCheckCgiProc(cgip->handle, &exit_status) == 0) {
/*
 *				We get here if the CGI process has terminated.  Clean up.
 */
				nTries = 0;
/*				
 *				Make sure we didn't miss something during a task switch.
 *				Maximum wait is 100 times 10 msecs (1 second).
 */
				while ((cgip->fplacemark == 0) && (nTries < 100)) {
					websCgiGatherOutput(cgip);
/*					
 *					There are some cases when we detect app exit 
 *					before the file is ready. 
 */
					if (cgip->fplacemark == 0) {
#ifdef WIN
						Sleep(10);
#endif /* WIN*/
					}
					nTries++;
				}
				if (cgip->fplacemark == 0) {
					websError(wp, 200, T("CGI generated no output"));
				} else {
					websDone(wp, 200);
				}
/*
 *				Remove the temporary re-direction files
 */
				gunlink(cgip->stdIn);
				gunlink(cgip->stdOut);
/*
 *				Free all the memory buffers pointed to by cgip.
 *				The stdin file name (wp->cgiStdin) gets freed as
 *				part of websFree().
 */
				cgiMax = hFree((void***) &cgiList, cid);
				for (ep = cgip->envp; ep != NULL && *ep != NULL; ep++) {
					bfreeSafe(B_L, *ep);
				}
				bfreeSafe(B_L, cgip->cgiPath);
				bfreeSafe(B_L, cgip->argp);
				bfreeSafe(B_L, cgip->envp);
				bfreeSafe(B_L, cgip->stdOut);
				bfreeSafe(B_L, cgip);
#if 0 //DAVIDM - we do not want this, netflash does it for us
				if(wp->has_firmware_upload_clean){
					if (WIFEXITED(exit_status) && WEXITSTATUS(exit_status) != 0)
						return;
					sync();
					doSystem("sleep 3 && reboot &");
				}
#endif
			}
		}
	}
}
Exemple #30
0
int dbLoad(int did, char_t *filename, int flags)
{
    gstat_t		sbuf;
    char_t		*buf, *keyword, *value, *path, *ptr;
    char_t		*tablename;
    int			fd, tid, row;
    dbTable_t	*pTable;

    a_assert(did >= 0);

    fmtAlloc(&path, FNAMESIZE, T("%s/%s"), basicGetProductDir(), filename);
    trace(4, T("DB: About to read data file <%s>\n"), path);

    if (gstat(path, &sbuf) < 0) {
        trace(3, T("DB: Failed to stat persistent data file.\n"));
        bfree(B_L, path);
        return -1;
    }

    fd = gopen(path, O_RDONLY | O_BINARY, 0666);
    bfree(B_L, path);

    if (fd < 0) {
        trace(3, T("DB: No persistent data file present.\n"));
        return -1;
    }

    if (sbuf.st_size <= 0) {
        trace(3, T("DB: Persistent data file is empty.\n"));
        gclose(fd);
        return -1;
    }
    /*
     *	Read entire file into temporary buffer
     */
    buf = balloc(B_L, sbuf.st_size + 1);
#ifdef CE
    if (readAscToUni(fd, &buf, sbuf.st_size) != (int)sbuf.st_size) {
#else
    if (gread(fd, buf, sbuf.st_size) != (int)sbuf.st_size) {
#endif
        trace(3, T("DB: Persistent data read failed.\n"));
        bfree(B_L, buf);
        gclose(fd);
        return -1;
    }

    gclose(fd);
    *(buf + sbuf.st_size) = '\0';

    row = -1;
    tid = -1;
    pTable = NULL;
    ptr = gstrtok(buf, T("\n"));
    tablename = NULL;

    do {
        if (crack(ptr, &keyword, &value) < 0) {
            trace(5, T("DB: Failed to crack line %s\n"), ptr);
            continue;
        }

        a_assert(keyword && *keyword);

        if (gstrcmp(keyword, KEYWORD_TABLE) == 0) {
            /*
             *			Table name found, check to see if it's registered
             */
            if (tablename) {
                bfree(B_L, tablename);
            }

            tablename = bstrdup(B_L, value);
            tid = dbGetTableId(did, tablename);

            if (tid >= 0) {
                pTable = dbListTables[tid];
            } else {
                pTable = NULL;
            }

        } else if (gstrcmp(keyword, KEYWORD_ROW) == 0) {
            /*
             *			Row/Record indicator found, add a new row to table
             */
            if (tid >= 0) {
                int nRows = dbGetTableNrow(did, tablename);

                if (dbSetTableNrow(did, tablename, nRows + 1) == 0) {
                    row = nRows;
                }
            }

        } else if (row != -1) {
            /*
             *			some other data found, assume it's a COLUMN=value
             */
            int nColumn = GetColumnIndex(tid, keyword);

            if ((nColumn >= 0) && (pTable != NULL)) {
                int nColumnType = pTable->columnTypes[nColumn];
                if (nColumnType == T_STRING) {
                    dbWriteStr(did, tablename, keyword, row, value);
                } else {
                    dbWriteInt(did, tablename, keyword, row, gstrtoi(value));
                }
            }
        }
    } while ((ptr = gstrtok(NULL, T("\n"))) != NULL);

    if (tablename) {
        bfree(B_L, tablename);
    }

    bfree(B_L, buf);

    return 0;
}

/******************************************************************************/
/*
 *	Return a table id given the table name
 */

int dbGetTableId(int did, char_t *tablename)
{
    int			tid;
    dbTable_t	*pTable;

    a_assert(tablename);

    for (tid = 0; (tid < dbMaxTables); tid++) {
        if ((pTable = dbListTables[tid]) != NULL) {
            if (gstrcmp(tablename, pTable->name) == 0) {
                return tid;
            }
        }
    }

    return -1;
}