Example #1
0
int dlclose(void * handle)
{
    struct dlstatus * dls = handle;
    if (!isValidStatus(dls))
        return 1;
    if (dls->module == MAGIC_DYLIB_MOD)
    {
        warning("trying to close a .dylib!");
        error("dynamic libraries cannot be closed");
        // Code inside the PAL expects to be able to dlclose anything that
        // could be dlopen'd, so we return success here. It doesn't matter
        // that we don't do anything; the PAL doesn't require any action
        // as a result of this dlclose. Clients of the PAL can't call
        // dlclose() directly, so this isn't a concern.
        return 0;
    }
    if (!dls->module)
    {
        error("module already closed");
        return 1;
    }
    dls->refs--;
    if (!dls->refs)
    {
        unsigned long options = 0;
        void (*fini)(void);
        if ((fini = dlsymIntern(dls, "__fini",0)))
        {
            debug("calling _fini()");
            fini();
        }
        if (isFlagSet(dls->mode, RTLD_NODELETE))
            options |= NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED;
        if (!NSUnLinkModule(dls->module, options))
        {
            error("unable to unlink module");
            return 1;
        }
        dls->module = 0;
        /* Note: the dlstatus struct dls is neither removed from the list
         * nor is the memory it occupies freed. This shouldn't pose a 
         * problem in mostly all cases, though.
         */
    }
    return 0;
}
Example #2
0
static IPTR mLampDraw(struct IClass *cl, Object *obj, struct MUIP_Draw *msg)
{
    struct lampData *data = INST_DATA(cl,obj);
    IPTR            res;

    res = DoSuperMethodA(cl,obj,(APTR)msg);

    if(hasFlag(msg->flags, (MADF_DRAWOBJECT|MADF_DRAWUPDATE)))
    {
        WORD l, t, r, b;

        /* Don't ask or modify ! */

        l = _mleft(obj);
        r = _mright(obj);
        t = _mtop(obj)+(_mheight(obj)+data->delta)/2-1;
        b = t-data->delta;

        if (r-l>2)
        {
            l += 1;
            r -= 1;
        }

        if (b-t>2)
        {
            t += 1;
            b -= 1;
        }

        SetAPen(_rp(obj), MUIPEN(isFlagSet(data->flags, FLG_LampDisabled) ? data->disabled : data->enabled));
        RectFill(_rp(obj),l,t,r,b);

        SetAPen(_rp(obj),MUIPEN(data->detail));
        Move(_rp(obj),l,t);
        Draw(_rp(obj),r,t);
        Draw(_rp(obj),r,b);
        Draw(_rp(obj),l,b);
        Draw(_rp(obj),l,t);
    }

    return res;
}
Example #3
0
///
/// SetupDbgMalloc
// initialize the memory tracking framework
static void SetupDbgMalloc(void)
{
  ENTER();

  if(isFlagSet(debug_classes, DBC_MTRACK))
  {
    ULONG i;

    for(i = 0; i < ARRAY_SIZE(DbgMallocList); i++)
      NewList((struct List *)&DbgMallocList[i]);

    DbgMallocCount = 0;
    DbgUnsuitableFreeCount = 0;

    memset(&DbgMallocListSema, 0, sizeof(DbgMallocListSema));
    InitSemaphore(&DbgMallocListSema);
  }

  LEAVE();
}
Example #4
0
static void sbcFromRegA(struct gameboy * gameboy, uint8_t value)
{
	value += isFlagSet(gameboy, CARRY) ? 1 : 0;

	setFlag(gameboy, SUB, true);

	if (value > gameboy->cpu.a){
		setFlag(gameboy, ZERO, true);
	}
	else {
		setFlag(gameboy, ZERO, false);
	}

	if ((value & 0x0F) > (gameboy->cpu.a & 0x0F)){
		setFlag(gameboy, HALF_CARRY, true);
	}
	else {
		setFlag(gameboy, HALF_CARRY, false);
	}

	gameboy->cpu.a -= value;

}
Example #5
0
/*----------------------------*
 * Remove n chars from a line *
 *----------------------------*/
BOOL RemoveChars(LONG x, struct line_node *line, LONG length, struct InstData *data)
{
  ENTER();

  if(line->line.Styles != NULL)
  {
    if(*line->line.Styles != EOS)
    {
        UWORD start_style = GetStyle(x-1, line);
        UWORD end_style = GetStyle(x+length, line);
        ULONG c = 0, store;

      while(*(line->line.Styles+c) <= x)
        c += 2;

      if(start_style != end_style)
      {
        UWORD turn_off = start_style & ~end_style;
        UWORD turn_on  = end_style & ~start_style;

        if(isFlagSet(turn_off, BOLD))
        {
          *(line->line.Styles+c++) = x+1;
          *(line->line.Styles+c++) = ~BOLD;
        }
        if(isFlagSet(turn_off, ITALIC))
        {
          *(line->line.Styles+c++) = x+1;
          *(line->line.Styles+c++) = ~ITALIC;
        }
        if(isFlagSet(turn_off, UNDERLINE))
        {
          *(line->line.Styles+c++) = x+1;
          *(line->line.Styles+c++) = ~UNDERLINE;
        }
        if(isFlagSet(turn_on, BOLD))
        {
          *(line->line.Styles+c++) = x+1;
          *(line->line.Styles+c++) = BOLD;
        }
        if(isFlagSet(turn_on, ITALIC))
        {
          *(line->line.Styles+c++) = x+1;
          *(line->line.Styles+c++) = ITALIC;
        }
        if(isFlagSet(turn_on, UNDERLINE))
        {
          *(line->line.Styles+c++) = x+1;
          *(line->line.Styles+c++) = UNDERLINE;
        }
      }

      store = c;
      while(*(line->line.Styles+c) <= x+length+1)
        c += 2;

      while(*(line->line.Styles+c) != EOS)
      {
        *(line->line.Styles+store++) = *(line->line.Styles+c++)-length;
        *(line->line.Styles+store++) = *(line->line.Styles+c++);
      }
      *(line->line.Styles+store) = EOS;
    }
  }

  if(line->line.Colors != NULL)
  {
    if(*line->line.Colors != 0xffff)
    {
      UWORD start_color = x ? GetColor(x-1, line) : 0;
      UWORD end_color = GetColor(x+length, line);
      ULONG c = 0, store;

      while(*(line->line.Colors+c) <= x)
        c += 2;

      if(start_color != end_color)
      {
        *(line->line.Colors+c++) = x+1;
        *(line->line.Colors+c++) = end_color;
      }

      store = c;
      while(*(line->line.Colors+c) <= x+length+1)
        c += 2;

      while(*(line->line.Colors+c) != 0xffff)
      {
        *(line->line.Colors+store++) = *(line->line.Colors+c++)-length;
        *(line->line.Colors+store++) = *(line->line.Colors+c++);
      }
      *(line->line.Colors+store) = 0xffff;
    }
  }

  UpdateChange(x, line, length, NULL, NULL, data);

  RETURN(TRUE);
  return(TRUE);
}
Example #6
0
/* Save_FreqPlots_Gnuplot_Data()
 *
 * Saves frequency plots data to a file for gnuplot
 */
  void
Save_FreqPlots_Gnuplot_Data( char *filename )
{
  /* Abort if plot data not available */
  if( isFlagClear(FREQ_LOOP_DONE) )
    return;

  /* Used to calculate net gain */
  double Zr, Zo, Zi;

  /* Open gplot file, abort on error */
  FILE *fp = NULL;
  if( !Open_File(&fp, filename, "w") )
    return;

  /* Plot max gain vs frequency, if possible */
  if( isFlagSet(PLOT_GMAX) && isFlagSet(ENABLE_RDPAT) )
  {
    int nth, nph, idx, pol;
    gboolean no_fbr;

    double
      gmax,     /* Max gain buffer */
      netgain,  /* Viewer direction net gain buffer */
      gdir_phi, /* Direction in phi of gain */
      fbratio;  /* Front to back ratio */

    /* Find max gain and direction, F/B ratio */
    no_fbr = FALSE;
    netgain = 0;

    /* Polarization type and impedance */
    pol = calc_data.pol_type;
    Zo = calc_data.zo;

    /* Save data for all frequency steps that were used */
    fprintf( fp, _("# Gain and F/B Ratio vs Frequency\n") );
    for( idx = 0; idx <= calc_data.lastf; idx++ )
    {
      double fbdir;
      int fbidx, mgidx;

      /* Index to gtot buffer where max gain
       * occurs for given polarization type */
      mgidx = rad_pattern[idx].max_gain_idx[pol];

      /* Max gain for given polarization type */
      gmax = rad_pattern[idx].gtot[mgidx] +
        Polarization_Factor(pol, idx, mgidx);

      /* Net gain if selected */
      if( isFlagSet(PLOT_NETGAIN) )
      {
        Zr = impedance_data.zreal[idx];
        Zi = impedance_data.zimag[idx];
        netgain = gmax + 10*log10(4*Zr*Zo/(pow(Zr+Zo,2)+pow(Zi,2)));
      }

      /* Radiation angle/phi where max gain occurs */
      gdir_phi = rad_pattern[idx].max_gain_phi[pol];

      /* Find F/B direction in theta */
      fbdir = 180.0 - rad_pattern[idx].max_gain_tht[pol];
      if( fpat.dth == 0.0 )
        nth = 0;
      else
        nth = (int)( fbdir/fpat.dth + 0.5 );

      /* If the antenna is modelled over ground, then use the same
       * theta as the max gain direction, relying on phi alone to
       * take us to the back. Patch supplied by Rik van Riel AB1KW
       */
      if( (nth >= fpat.nth) || (nth < 0) )
      {
        fbdir = rad_pattern[idx].max_gain_tht[pol];
        if( fpat.dth == 0.0 )
          nth = 0;
        else
          nth = (int)( fbdir/fpat.dth + 0.5 );
      }

      /* Find F/B direction in phi */
      fbdir = gdir_phi + 180.0;
      if( fbdir >= 360.0 ) fbdir -= 360.0;
      nph = (int)( fbdir/fpat.dph + 0.5 );

      /* No F/B calc. possible if no phi step at +180 from max gain */
      if( (nph >= fpat.nph) || (nph < 0) )
        no_fbr = TRUE;

      /* Index to gtot buffer for gain in back direction */
      fbidx = nth + nph*fpat.nth;

      /* Front to back ratio */
      fbratio  = pow( 10.0, gmax / 10.0 );
      fbratio /= pow( 10.0,
          (rad_pattern[idx].gtot[fbidx] +
           Polarization_Factor(pol, idx, fbidx)) / 10.0 );
      fbratio = 10.0 * log10( fbratio );

      if( no_fbr && isFlagClear(PLOT_NETGAIN) ) /* Plot max gain only */
        fprintf( fp, "%13.6E %10.3E\n", save.freq[idx], gmax );
      else if( isFlagSet(PLOT_NETGAIN) ) /* Plot max gain and net gain */
        fprintf( fp, "%13.6E %10.3E %10.3E\n", save.freq[idx], gmax, netgain );
      else if( !no_fbr ) /* Plot max gain and F/B ratio */
        fprintf( fp, "%13.6E %10.3E %10.3E\n", save.freq[idx], gmax, fbratio );
    } /* for( idx = 0; idx < calc_data.lastf; idx++ ) */

    /* Plot gain direction in phi and theta */
    if( isFlagSet(PLOT_GAIN_DIR) )
    {
      fprintf( fp, "\n\n" );
      fprintf( fp, _("# Direction of gain in theta and phi\n") );
      for( idx = 0; idx < calc_data.lastf; idx++ )
      {
        double gdir_tht; /* Direction in theta of gain */

        /* Radiation angle/phi where max gain occurs */
        gdir_tht = 90.0 - rad_pattern[idx].max_gain_tht[pol];
        gdir_phi = rad_pattern[idx].max_gain_phi[pol];
        fprintf( fp, "%13.6E %10.3E %10.3E\n", save.freq[idx], gdir_tht, gdir_phi );
      } /* for( idx = 0; idx < calc_data.lastf; idx++ ) */
    } /* if( isFlagSet(PLOT_GAIN_DIR) ) */

    fprintf( fp, "\n\n" );
  } /* if( isFlagSet(PLOT_GMAX) && isFlagSet(ENABLE_RDPAT) ) */

  /* Plot VSWR vs freq */
  if( isFlagSet(PLOT_VSWR) )
  {
    int idx;
    double vswr, gamma;
    double zrpro2, zrmro2, zimag2;

    /* Calculate VSWR */
    fprintf( fp, _("# VSWR vs Frequency\n") );
    for(idx = 0; idx <= calc_data.lastf; idx++ )
    {
      zrpro2 = impedance_data.zreal[idx] + calc_data.zo;
      zrpro2 *= zrpro2;
      zrmro2 = impedance_data.zreal[idx] - calc_data.zo;
      zrmro2 *= zrmro2;
      zimag2 = impedance_data.zimag[idx] * impedance_data.zimag[idx];
      gamma = sqrt( (zrmro2 + zimag2)/(zrpro2 + zimag2) );
      vswr = (1+gamma)/(1-gamma);
      if( vswr > 10.0 ) vswr = 10.0;
      fprintf( fp, "%13.6E %10.3E\n", save.freq[idx], vswr );
    }

    fprintf( fp, "\n\n" );
  } /* if( isFlagSet(PLOT_VSWR) ) */

  /* Plot z-real and z-imag */
  if( isFlagSet(PLOT_ZREAL_ZIMAG) )
  {
    int idx;
    fprintf( fp, _("# Z real & Z imaginary vs Frequency\n") );
    for(idx = 0; idx <= calc_data.lastf; idx++ )
      fprintf( fp, "%13.6E %10.3E %10.3E\n",
          save.freq[idx], impedance_data.zreal[idx], impedance_data.zimag[idx] );

    fprintf( fp, "\n\n" );
  } /* if( isFlagSet(PLOT_ZREAL_ZIMAG) ) */

  /* Plot z-magn and z-phase */
  if( isFlagSet(PLOT_ZMAG_ZPHASE) )
  {
    int idx;
    fprintf( fp, _("# Z magnitude & Z phase vs Frequency\n") );
    for(idx = 0; idx <= calc_data.lastf; idx++ )
      fprintf( fp, "%13.6E %10.3E %10.3E\n",
          save.freq[idx], impedance_data.zmagn[idx], impedance_data.zphase[idx] );
  } /* if( isFlagSet(PLOT_ZREAL_ZIMAG) ) */

  fclose(fp);
} /* Save_FreqPlots_Gnuplot_Data() */
Example #7
0
/* Save_RadPattern_Gnuplot_Data()
 *
 * Saves radiation pattern data to a file for gnuplot
 */
  void
Save_RadPattern_Gnuplot_Data( char *filename )
{
  int idx, npts; /* Number of points to plot */

  /* Scale factor ref, for normalizing field strength values */
  double dr;

  double
    fx, fy, fz, /* Co-ordinates of "free" end of field lines */
    fscale;     /* Scale factor for equalizing field line segments */

  FILE *fp = NULL;

  /* Draw near field pattern if possible */
  if( isFlagSet(ENABLE_NEAREH) && near_field.valid )
  {
    /* Open gplot file, abort on error */
    if( !Open_File(&fp, filename, "w") )
      return;

    /* Reference for scale factor used in
     * normalizing field strength values */
    if( fpat.near ) /* Spherical co-ordinates */
      dr = (double)fpat.dxnr;
    /* Rectangular co-ordinates */
    else dr = sqrt(
        (double)fpat.dxnr * (double)fpat.dxnr +
        (double)fpat.dynr * (double)fpat.dynr +
        (double)fpat.dznr * (double)fpat.dznr )/1.75;

    npts = fpat.nrx * fpat.nry * fpat.nrz;

    /*** Draw Near E Field ***/
    if( isFlagSet(DRAW_EFIELD) && (fpat.nfeh & NEAR_EFIELD) )
    {
      fprintf( fp, _("# Near E field\n") );
      /* Write e-field out to file [DJS] */
      for( idx = 0; idx < npts; idx++ )
      {
        fscale = dr / near_field.er[idx];
        fx = near_field.px[idx] + near_field.erx[idx] * fscale;
        fy = near_field.py[idx] + near_field.ery[idx] * fscale;
        fz = near_field.pz[idx] + near_field.erz[idx] * fscale;

        /* Print as x, y, z, dx, dy, dz for gnuplot */
        fprintf( fp, "%f %f %f %f %f %f\n",
            near_field.px[idx],
            near_field.py[idx],
            near_field.pz[idx],
            fx - near_field.px[idx],
            fy - near_field.py[idx],
            fz - near_field.pz[idx] );
      }
    } /* if( isFlagSet(DRAW_EFIELD) */

    /*** Draw Near H Field ***/
    if( isFlagSet(DRAW_HFIELD) && (fpat.nfeh & NEAR_HFIELD) )
    {
      fprintf( fp, _("# Near H field\n") );
      /* Write h-field out to file [DJS] */
      for( idx = 0; idx < npts; idx++ )
      {
        fscale = dr / near_field.hr[idx];
        fx = near_field.px[idx] + near_field.hrx[idx] * fscale;
        fy = near_field.py[idx] + near_field.hry[idx] * fscale;
        fz = near_field.pz[idx] + near_field.hrz[idx] * fscale;

        /* Print as x, y, z, dx, dy, dz for gnuplot */
        fprintf( fp, "%f %f %f %f %f %f\n",
            near_field.px[idx],
            near_field.py[idx],
            near_field.pz[idx],
            fx - near_field.px[idx],
            fy - near_field.py[idx],
            fz - near_field.pz[idx] );
      }
    } /* if( isFlagSet(DRAW_HFIELD) && (fpat.nfeh & NEAR_HFIELD) ) */

    /*** Draw Poynting Vector ***/
    if( isFlagSet(DRAW_POYNTING)  &&
        (fpat.nfeh & NEAR_EFIELD) &&
        (fpat.nfeh & NEAR_HFIELD) )
    {
      int ipv;
      static size_t mreq = 0;

      /* Co-ordinates of Poynting vectors */
      static double *pov_x = NULL, *pov_y = NULL;
      static double *pov_z = NULL, *pov_r = NULL;

      /* Range of Poynting vector values,
       * its max and min and log of max/min */
      static double pov_max = 0;

      /* Allocate on new near field matrix size */
      if( mreq != (size_t)npts * sizeof( double ) )
      {
        mreq = (size_t)npts * sizeof( double );
        mem_realloc( (void **)&pov_x, mreq, "in draw_radiation.c" );
        mem_realloc( (void **)&pov_y, mreq, "in draw_radiation.c" );
        mem_realloc( (void **)&pov_z, mreq, "in draw_radiation.c" );
        mem_realloc( (void **)&pov_r, mreq, "in draw_radiation.c" );
      }

      /* Calculate Poynting vector and its max and min */
      fprintf( fp, _("# Poynting Vector\n") );
      for( idx = 0; idx < npts; idx++ )
      {
        pov_max = 0;
        for( ipv = 0; ipv < npts; ipv++ )
        {
          pov_x[ipv] =
            near_field.ery[ipv] * near_field.hrz[ipv] -
            near_field.hry[ipv] * near_field.erz[ipv];
          pov_y[ipv] =
            near_field.erz[ipv] * near_field.hrx[ipv] -
            near_field.hrz[ipv] * near_field.erx[ipv];
          pov_z[ipv] =
            near_field.erx[ipv] * near_field.hry[ipv] -
            near_field.hrx[ipv] * near_field.ery[ipv];
          pov_r[ipv] = sqrt(
              pov_x[ipv] * pov_x[ipv] +
              pov_y[ipv] * pov_y[ipv] +
              pov_z[ipv] * pov_z[ipv] );
          if( pov_max < pov_r[ipv] )
            pov_max = pov_r[ipv];

        } /* for( ipv = 0; ipv < npts; ipv++ ) */

        /* Scale factor for each field point, to make
         * near field direction lines equal-sized */
        fscale = dr / pov_r[idx];

        /* Scaled field values are used to set one end of a
         * line segment that represents direction of field.
         * The other end is set by the field point co-ordinates */
        fx = near_field.px[idx] + pov_x[idx] * fscale;
        fy = near_field.py[idx] + pov_y[idx] * fscale;
        fz = near_field.pz[idx] + pov_z[idx] * fscale;

        /* Print as x, y, z, dx, dy, dz for gnuplot */
        fprintf( fp, "%f %f %f %f %f %f\n",
            near_field.px[idx],
            near_field.py[idx],
            near_field.pz[idx],
            fx - near_field.px[idx],
            fy - near_field.py[idx],
            fz - near_field.pz[idx] );
      } /* for( idx = 0; idx < npts; idx++ ) */

    } /* if( isFlagSet(DRAW_POYNTING) ) */
  } /* if( isFlagSet(ENABLE_NEAREH) && near_field.valid ) */

  /* Save radiation pattern data if possible */
  if( isFlagSet(ENABLE_RDPAT) && (calc_data.fstep >= 0) )
  {
    int
      nth,  /* Theta step count */
      nph;  /* Phi step count   */

    /* Frequency step and polarization type */
    int fstep = calc_data.fstep;

    /* Theta and phi angles defining a rad pattern point
     * and distance of its projection from xyz origin */
    double theta, phi, r;

    /* theta and phi step in rads */
    double dth = (double)fpat.dth * (double)TA;
    double dph = (double)fpat.dph * (double)TA;

    /* Open gplot file, abort on error */
    if( !Open_File(&fp, filename, "w") )
      return;
    fprintf( fp, _("# Radiation Pattern") );

    /* Distance of rdpattern point nearest to xyz origin */
    /*** Convert radiation pattern values
     * to points in 3d space in x,y,z axis ***/
    phi = (double)fpat.phis * (double)TA; /* In rads */

    /* Step phi angle */
    idx = 0;
    for( nph = 0; nph < fpat.nph; nph++ )
    {
      theta = (double)fpat.thets * (double)TA; /* In rads */

      /* Step theta angle */
      for( nth = 0; nth < fpat.nth; nth++ )
      {
        double x, y, z;

        /* Distance of pattern point from the xyz origin */
        r = Scale_Gain(
            rad_pattern[fstep].gtot[idx], fstep, idx );

        /* Distance of point's projection on xyz axis, from origin */
        z = r * cos(theta);
        r *= sin(theta);
        x = r * cos(phi);
        y = r * sin(phi);

        /* Print to file */
        fprintf( fp, "%10.3E %10.3E %10.3E\n", x, y, z );

        /* Step theta in rads */
        theta += dth;
        idx++;
      } /* for( nth = 0; nth < fpat.nth; nth++ ) */

      /* Step phi in rads */
      phi += dph;
    } /* for( nph = 0; nph < fpat.nph; nph++ ) */


  } /* if( isFlagSet(ENABLE_RDPAT) && (calc_data.fstep >= 0) ) */

  if( fp != NULL ) fclose(fp);
} /* Save_RadPattern_Gnuplot_Data() */
Example #8
0
//////////////////////////////////////////////////////////////////////////
// isAttached
BcBool ScnComponent::isAttached() const
{
	return isFlagSet( scnCF_ATTACHED );
}
Example #9
0
/// mSearch()
IPTR mSearch(UNUSED struct IClass *cl, Object *obj, struct MUIP_TextEditor_Search *msg)
{
  struct InstData *data = INST_DATA(cl, obj);
  STRPTR str = msg->SearchString;
  LONG len = strlen(str), step = 0;

  ENTER();

  if(len > 0 && len <= 120)
  {
    BYTE map[256];
    LONG (*StrCmp)(STRPTR, STRPTR, LONG);
    LONG cursor;
    struct line_node *line;

    // if the FromTop flag is set we start the search right from the top
    if(isFlagSet(msg->Flags, MUIF_TextEditor_Search_FromTop))
    {
      cursor = 0;
      line = GetFirstLine(&data->linelist);
    }
    else
    {
      cursor = data->CPos_X;
      line = data->actualline;
    }

    memset(map, len, 256);

    // if a casesensitive search is requested we use a different
    // compare function.
    if(isFlagSet(msg->Flags, MUIF_TextEditor_Search_CaseSensitive))
    {
      StrCmp = Native_strncmp;

      while(*str)
        map[(int)*str++] = step--;
    }
    else
    {
      StrCmp = Utility_strnicmp;
      while(*str)
      {
        map[ToLower(*str)] = step;
        map[ToUpper(*str++)] = step--;
      }
    }

    if(isFlagSet(msg->Flags, MUIF_TextEditor_Search_Backwards))
    {
//D(DBF_STARTUP, "MUIF_TextEditor_Search_Backwards  search=%s\n", msg->SearchString);
      if(Enabled(data))
        cursor -= len;

      while(line != NULL)
      {
        LONG lenTmp  = len;
        STRPTR contents = line->line.Contents + cursor - lenTmp+1;
        STRPTR lower = line->line.Contents;

        while(contents >= lower)
        {
//D(DBF_STARTUP, "MUIF_TextEditor_Search_Backwards  previous=%ld, contents=%s\n",line, contents);
          if(!StrCmp(contents, msg->SearchString, len))
          {
            LONG startx = contents - line->line.Contents;

//D(DBF_STARTUP, "MUIF_TextEditor_Search_Backwards found\n");

            SimpleMarkText(data, startx, line, startx+len, line);

            RETURN(TRUE);
            return TRUE;
          }
          contents -= 1;
          lenTmp += 1;
        }

        line = GetPrevLine(line);

        if(line != NULL)
          cursor = line->line.Length;
      }
    }
    else
    {
      while(line)
      {
        LONG skip;
        STRPTR contents = line->line.Contents + cursor + len-1;
        STRPTR upper = line->line.Contents + line->line.Length;

        while(contents < upper)
        {
          skip = map[(int)(*contents)];
          contents += skip;

          if(skip <= 0)
          {
            if(!StrCmp(contents, msg->SearchString, len))
            {
              LONG startx = contents - line->line.Contents;

              SimpleMarkText(data, startx, line, startx+len, line);

              RETURN(TRUE);
              return TRUE;
            }
            contents += len;
          }
        }

        cursor = 0;

        line = GetNextLine(line);
      }
    }

  }

  RETURN(FALSE);
  return FALSE;
}
Example #10
0
void ShaderBuildFromBuffer(Shader_t *shader)
{
  int i,n;
  int offset;
  int needsworldinv = LUX_FALSE;
  ShaderParam_t *parambrowse;
  // copy stages
  offset = 0;
  shader->numStages = l_SHDData.stagesColorInBuffer + l_SHDData.stagesTexGpuInBuffer;
  shader->stages = reszalloc(sizeof(ShaderStage_t*)*shader->numStages);
  shader->totalParams = reszalloc(sizeof(ShaderParam_t*)*shader->numTotalParams);

  // we will need manual matrix paramters
  shader->cgMode = l_SHDData.cgmode == -1 ? SHADER_PASSMODE_FIXEDARB : l_SHDData.cgmode;


  if (!(shader->shaderflag & SHADER_NOCOMPILE))
    l_SHDData.colorStage = 0;

  n = 0;
  for (i = 0; i < l_SHDData.stagesColorInBuffer + l_SHDData.stagesTexGpuInBuffer; i++){
    if (i == l_SHDData.colorStage && l_SHDData.stagesColorInBuffer)
      shader->stages[i]=l_SHDData.stagesColor;
    else{
      ShaderStage_t *stage =  l_SHDData.stagesTex[n];
      shader->stages[i]=stage;
      if (stage->paramListHead){
        lxListNode_forEach(stage->paramListHead,parambrowse)
          shader->totalParams[parambrowse->totalid] = parambrowse;
          needsworldinv |= ShaderParam_needsWorldInv(parambrowse);
        lxListNode_forEachEnd(stage->paramListHead,parambrowse);
      }
      if (stage->stagetype == SHADER_STAGE_TEX){
        if (stage->stageflag & (SHADER_EYELINMAP | SHADER_OBJLINMAP) && !stage->texgen){
          stage->stageflag &= ~(SHADER_EYELINMAP | SHADER_OBJLINMAP);
          stage->texgen = NULL;
          lprintf("WARNING shdload: no texgenplanes defined,%s\n",shader->resinfo.name);
        }
        if (stage->texgen){
          uchar legalcombos[] = { LUX_TRUE,LUX_TRUE,LUX_FALSE,LUX_FALSE,  // XY
                        LUX_TRUE,LUX_TRUE,LUX_TRUE,LUX_FALSE, // XYZ
                        LUX_TRUE,LUX_TRUE,LUX_FALSE,LUX_TRUE, // XYW
                        LUX_TRUE,LUX_TRUE,LUX_TRUE,LUX_TRUE}; // XYZW
          enum32  legalmodes[]  = { VID_TEXCOORD_TEXGEN_ST,
                        VID_TEXCOORD_TEXGEN_STR,
                        VID_TEXCOORD_TEXGEN_STQ,
                        VID_TEXCOORD_TEXGEN_STRQ};

          uint *pIn = (uint*)legalcombos;
          uint *pCur = (uint*)stage->texgen->enabledaxis;
          int c;

          for (c = 0; c < 4; c++,pIn++){
            if (*pIn == *pCur){
              stage->texgen->texgenmode = legalmodes[c];
              break;
            }
          }

          if (!stage->texgen){
            stage->texgen = NULL;
            stage->stageflag &= ~(SHADER_EYELINMAP | SHADER_OBJLINMAP);
            lprintf("WARNING shdload: illegal combination of texgenplanes defined,%s\n",shader->resinfo.name);
          }
        }
      }
      n++;
    }
  }

  if (needsworldinv)
    shader->shaderflag |= SHADER_NEEDINVMATRIX;


  // check if textured
  if (l_SHDData.stagesTexInBuffer)
    shader->shaderflag |= SHADER_TEXTURED;

  // nicer to work with, if first stage = color replace & second stage = tex modulate, we "encode" the modulate via vcolor flag
  if (  l_SHDData.stagesColorInBuffer && l_SHDData.stagesColor->blendmode == VID_REPLACE
    &&  l_SHDData.stagesTexInBuffer)
    for (i = 0; i < shader->numStages; i++){
      if (shader->stages[i]->stagetype == SHADER_STAGE_TEX ){
        if (shader->stages[i]->blendmode == VID_MODULATE && !(isFlagSet(shader->stages[i]->stageflag,SHADER_VCOLOR))){
          shader->stages[i]->blendmode = VID_REPLACE;
          shader->stages[i]->stageflag |= SHADER_VCOLOR | SHADER_VCOLOR_KEEP;
        }
        break;
      }
    }


  // if there is a bumpstage, we will remove lighting info from all other stages
  if (l_SHDData.bumpStage != -1){
    shader->shaderflag |= SHADER_TANGENTS;
    for (i= 0; i < shader->numStages; i++)
      shader->stages[i]->stageflag &= ~(SHADER_VCOLOR | SHADER_VCOLOR_KEEP);
  }
}
Example #11
0
static struct dlstatus * loadModule(const char * path, 
                    const struct stat * sbuf, int mode)
{
    NSObjectFileImage ofi = 0;
    NSObjectFileImageReturnCode ofirc;
    struct dlstatus * dls; 
    NSLinkEditErrors ler;
    int lerno;
    const char* errstr;
    const char* file;
    void (*init)(void);

    ofirc = NSCreateObjectFileImageFromFile(path, &ofi);
    switch (ofirc)
    {
        case NSObjectFileImageSuccess:
            break;
        case NSObjectFileImageInappropriateFile:
            if (isFlagSet(mode, RTLD_LOCAL))
            {
                warning("trying to open a .dylib with RTLD_LOCAL");
                error("unable to open this file with RTLD_LOCAL");
                return NULL;
            }                
            break;
        case NSObjectFileImageFailure:
            error("object file setup failure");
            return NULL;
        case NSObjectFileImageArch:
            error("no object for this architecture");
            return NULL;
        case NSObjectFileImageFormat:
            error("bad object file format");
            return NULL;
        case NSObjectFileImageAccess:
            error("can't read object file");
            return NULL;
        default:
            error("unknown error from NSCreateObjectFileImageFromFile()");
            return NULL;
    }
    dls = lookupStatus(sbuf);
    if (!dls) 
    {
        dls = allocStatus();
    }    
    if (!dls)
    {
        error("unable to allocate memory");
        return NULL;
    }
    dls->lib=0;
    if (ofirc == NSObjectFileImageInappropriateFile)
    {
        if ((dls->lib = NSAddImage(path, NSADDIMAGE_OPTION_RETURN_ON_ERROR)))
        {
            debug("Dynamic lib loaded at %ld",dls->lib);
            ofi = MAGIC_DYLIB_OFI;
            dls->module = MAGIC_DYLIB_MOD;
            ofirc = NSObjectFileImageSuccess;
        }
    }
    else 
    {
        /* Should change this to take care of RLTD_LAZY etc */
        dls->module = NSLinkModule(ofi, path,
                    NSLINKMODULE_OPTION_RETURN_ON_ERROR
                     | NSLINKMODULE_OPTION_PRIVATE
                    | NSLINKMODULE_OPTION_BINDNOW);
        NSDestroyObjectFileImage(ofi);
    }
    if (!dls->module)
    {
        NSLinkEditError(&ler,&lerno,&file,&errstr);            
        free(dls); 
        error(errstr);
        return NULL;
    }
    insertStatus(dls, sbuf);
    
    if ((init = dlsymIntern(dls, "__init",0)))
    {
        debug("calling _init()");
        init();
    }

    return dls;
}
Example #12
0
File: win.c Project: michalsc/AROS
static IPTR mGetPrefs(struct IClass *cl,Object *obj, struct MUIP_Win_GetPrefs *msg)
{
    struct data            *data = INST_DATA(cl,obj);
    struct URL_Prefs       *p;
    struct URL_BrowserNode *bn;
    struct URL_MailerNode  *mn;
    struct URL_FTPNode     *fn;
    ULONG                  mode, error = 0;

    /* get the openurl.library prefs */

    switch (msg->mode)
    {
        case MUIV_Win_GetPrefs_InUse:      mode = URL_GetPrefs_Mode_InUse;   break;
        case MUIV_Win_GetPrefs_LastSaveds: mode = URL_GetPrefs_Mode_Envarc;  break;
        case MUIV_Win_GetPrefs_Restore:    mode = URL_GetPrefs_Mode_Env;     break;
        case MUIV_Win_GetPrefs_Defaults:   mode = URL_GetPrefs_Mode_Default; break;
        default: return FALSE;
    }

    p = URL_GetPrefs(URL_GetPrefs_Mode,mode,TAG_DONE);
    if (!p) error = MSG_Err_NoPrefs;
    else if (p->up_Version!=PREFS_VERSION) error = MSG_Err_BadPrefs;

    if (error)
    {
        MUI_Request(_app(obj),NULL,0,getString(MSG_ErrReqTitle),
                                     getString(MSG_ErrReqGadget),
                                     getString(error),
                                     p ? p->up_Version : 0);

        if (p) URL_FreePrefsA(p,NULL);

        return FALSE;
    }

    /* Browsers */
    set(data->browserList,MUIA_List_Quiet,TRUE);
    DoMethod(data->browserList,MUIM_List_Clear);

    for (bn = (struct URL_BrowserNode *)p->up_BrowserList.mlh_Head;
         bn->ubn_Node.mln_Succ;
         bn = (struct URL_BrowserNode *)bn->ubn_Node.mln_Succ)
    {
        DoMethod(data->browserList,MUIM_List_InsertSingle,(IPTR)bn,MUIV_List_Insert_Bottom);
    }

    set(data->browserList,MUIA_List_Quiet,FALSE);

    /* Mailers */
    set(data->mailerList,MUIA_List_Quiet,TRUE);
    DoMethod(data->mailerList,MUIM_List_Clear);

    for (mn = (struct URL_MailerNode *)p->up_MailerList.mlh_Head;
         mn->umn_Node.mln_Succ;
         mn = (struct URL_MailerNode *)mn->umn_Node.mln_Succ)
    {
        DoMethod(data->mailerList,MUIM_List_InsertSingle,(IPTR)mn,MUIV_List_Insert_Bottom);
    }

    set(data->mailerList,MUIA_List_Quiet,FALSE);

    /* FTPs */
    set(data->FTPList,MUIA_List_Quiet,TRUE);
    DoMethod(data->FTPList,MUIM_List_Clear);

    for (fn = (struct URL_FTPNode *)p->up_FTPList.mlh_Head;
         fn->ufn_Node.mln_Succ;
         fn = (struct URL_FTPNode *)fn->ufn_Node.mln_Succ)
    {
        DoMethod(data->FTPList,MUIM_List_InsertSingle,(IPTR)fn,MUIV_List_Insert_Bottom);
    }

    set(data->FTPList,MUIA_List_Quiet,FALSE);

    /* Miscellaneous */
    set(data->prepend, MUIA_Selected, isFlagSet(p->up_Flags, UPF_PREPENDHTTP));
    set(data->mailto, MUIA_Selected, isFlagSet(p->up_Flags, UPF_DOMAILTO));
    set(data->useFTP, MUIA_Selected, isFlagSet(p->up_Flags, UPF_DOFTP));

    set(data->show, MUIA_Selected, p->up_DefShow);
    set(data->toFront, MUIA_Selected, p->up_DefBringToFront);
    set(data->newWin, MUIA_Selected, p->up_DefNewWindow);
    set(data->launch, MUIA_Selected, p->up_DefLaunch);

    /* Activate the first entry */
    DoSuperMethod(cl,obj,MUIM_MultiSet,MUIA_List_Active,MUIV_List_Active_Top,
        (IPTR)data->browserList,
        (IPTR)data->mailerList,
        (IPTR)data->FTPList,
        NULL);

    URL_FreePrefsA(p,NULL);

    return TRUE;
}
Example #13
0
/**
 * get IF-M PTS message (TNC)
 * return *msg (Network Byte Order)
 * TODO use RC core
 */
BYTE* getPtsTlvMessage(OPENPTS_CONTEXT *ctx, int type, int *len) {
    int i;
    OPENPTS_CONFIG *conf;
    UINT32 length = 0;  // endian of host
    BYTE * buf;
    int ptr;
    int rc;
    UINT16 nbou16;
    int fsize[MAX_RM_NUM];
    int fd[MAX_RM_NUM];
    int count[MAX_RM_NUM];
    struct stat st[MAX_RM_NUM];
    UINT32 num;

    DEBUG("writePtsTlvToSock - start\n");

    /* check */
    if (ctx == NULL) {
        LOG(LOG_ERR, "null input");
        return NULL;
    }
    conf = ctx->conf;
    if (conf == NULL) {
        LOG(LOG_ERR, "null input");
        return NULL;
    }

    /* init fd[] */
    for (i = 0; i < MAX_RM_NUM; i++) {
        fd[i] = -1;
    }

    /* TLV */
    *len = 0;

    switch (type) {
    /* Collector <-- Verifier Simple requests (no value)*/
    case REQUEST_TPM_PUBKEY:
    case REQUEST_INTEGRITY_REPORT:
    case REQUEST_RIMM_SET:
    case REQUEST_NEW_RIMM_SET:
    case VERIFICATION_RESULT:  // TODO
#ifdef CONFIG_AIDE
    case REQUEST_AIDE_DATABASE:
#endif
        buf = getTlvBuffer(type, 0);
        if (buf == NULL) {
            LOG(LOG_ERR, "getTlvBuffer() is null");
            goto error;
        }
        break;
    /* Collector <-> Verifier */
    case OPENPTS_CAPABILITIES:
    {
        length = sizeof(OPENPTS_IF_M_Capability);

        buf = getTlvBuffer(type, length);
        if (buf == NULL) {
            LOG(LOG_ERR, "getTlvBuffer() is null");
            goto error;
        }

        ptr = 12;
        /* Send versions */
        memcpy(&buf[ptr +  0], &ctx->conf->pts_flag, 4);
        memcpy(&buf[ptr +  4], &ctx->conf->tpm_version, 4);
        memcpy(&buf[ptr +  8], &ctx->conf->tss_version, 4);
        memcpy(&buf[ptr + 12], &ctx->conf->pts_version, 4);
        /* Send Platform UUID, ctx->uuid */
        memcpy(&buf[ptr + 16], ctx->conf->uuid->uuid, 16);

        /* Send RM UUID */
        if (ctx->conf->rm_uuid == NULL) {
            // TODO  verifier does not have Rm UUID. just send Verifier's UUID
            DEBUG("writePtsTlvToSock() RM uuid is NULL, => send platform UUID\n");
            memcpy(&buf[ptr + 32], ctx->conf->uuid->uuid, 16);
        } else if (ctx->conf->rm_uuid->uuid == NULL) {
            // TODO verifier?
            DEBUG("writePtsTlvToSock() RM uuid is NULL, => send platform UUID, file = %s\n",
                ctx->conf->rm_uuid->filename);

            memcpy(&buf[ptr + 32], ctx->conf->uuid->uuid, 16);
        } else {
            memcpy(&buf[ptr + 32], ctx->conf->rm_uuid->uuid, 16);
        }

        if (isFlagSet(ctx->conf->pts_flag[0], OPENPTS_FLAG0_NEWRM_EXIST) &&
            ctx->conf->newrm_uuid != NULL &&
            ctx->conf->newrm_uuid->uuid != NULL) {
            memcpy(&buf[ptr + 48], ctx->conf->newrm_uuid->uuid, 16);
        } else {
            DEBUG("New RM unavailable -> sending platform UUID");
            memcpy(&buf[ptr + 48], ctx->conf->uuid->uuid, 16);
        }

        break;
    }
    /* Collector --> Verifier (v0.2.5) */
    case OPENPTS_CAPABILITIES_025:
    {
        length = sizeof(OPENPTS_IF_M_Capability_025);

        buf = getTlvBuffer(OPENPTS_CAPABILITIES, length);  // v0.2.5
        if (buf == NULL) {
            LOG(LOG_ERR, "getTlvBuffer() is null");
            goto error;
        }

        ptr = 12;
        /* Send versions */
        memcpy(&buf[ptr +  0], &ctx->conf->pts_flag, 4);
        memcpy(&buf[ptr +  4], &ctx->conf->tpm_version, 4);
        memcpy(&buf[ptr +  8], &ctx->conf->tss_version, 4);
        memcpy(&buf[ptr + 12], &ctx->conf->pts_version, 4);
        /* Send Platform UUID, ctx->uuid */
        memcpy(&buf[ptr + 16], ctx->conf->uuid->uuid, 16);

        /* Send RM UUID */
        if (ctx->conf->rm_uuid == NULL) {
            // TODO  verifier does not have Rm UUID. just send Verifier's UUID
            DEBUG("writePtsTlvToSock() RM uuid is NULL, => send platform UUID\n");
            memcpy(&buf[ptr + 32], ctx->conf->uuid->uuid, 16);
        } else if (ctx->conf->rm_uuid->uuid == NULL) {
            // TODO verifier?
            DEBUG("writePtsTlvToSock() RM uuid is NULL, => send platform UUID, file = %s\n",
                ctx->conf->rm_uuid->filename);

            memcpy(&buf[ptr + 32], ctx->conf->uuid->uuid, 16);
        } else {
            memcpy(&buf[ptr + 32], ctx->conf->rm_uuid->uuid, 16);
        }
        break;
    }
    /* Collector --> Verifier */
    case TPM_PUBKEY:
    {
        if ((ctx->conf->pubkey != NULL) && (ctx->conf->pubkey_length > 0)) {
            /* PUB key exist */
            length = ctx->conf->pubkey_length;
            buf = getTlvBuffer(type, length);
            if (buf == NULL) {
                LOG(LOG_ERR, "getTlvBuffer() is null");
                goto error;
            }

            /* copy PUBKEY */
            memcpy(&buf[12], ctx->conf->pubkey, ctx->conf->pubkey_length);

        } else {
            /* PUB key is missing */
            LOG(LOG_ERR, "writePtsTlvToSock - PUBKEY blob is missing\n");
            ctx->ifm_errno = PTS_FATAL;
            ctx->ifm_strerror = smalloc_assert("Public key is missing");
            length = 0;
            goto error;
        }
        break;
    }

    /* Collector --> Verifier */
    case RIMM_SET:
    {
        /* open/read RM files */
        length = 4;  // for RM num
        for (i = 0; i < conf->rm_num; i++) {
            /* open */
            fd[i] = open(ctx->conf->rm_filename[i], O_RDONLY);
            if (fd[i] < 0) {
                // 20101124 SM must be a fullpath for Daemon
                LOG(LOG_ERR, "Can't open RM[%d] files, %s\n",
                    i, ctx->conf->rm_filename[i]);
                /* send Error massage */
                ctx->ifm_errno = PTS_FATAL;
                ctx->ifm_strerror =
                    smalloc_assert("Manifest not found, initialize the collector");
                goto error;
            }
            /* size */
            if (-1 == fstat(fd[i], &st[i])) {
                LOG(LOG_ERR, "fstat failed with errno %d\n", errno);
                goto error;
            }
            fsize[i] = st[i].st_size;
            length += 4 + fsize[i];
        }
        DEBUG_IFM("writePtsTlv - RIMM_SET, length = %d", length);

        buf = getTlvBuffer(type, length);
        if (buf == NULL) goto error;
        ptr = 12;

        // NUM of RM
        num = htonl(conf->rm_num);
        memcpy(&buf[ptr], (BYTE *)&num, 4);
        ptr += 4;

        for (i = 0; i< conf->rm_num; i++) {
            // length of RM[i]
            num = htonl(fsize[i]);
            // rc = wrapWrite(fdout, (BYTE *)&num, 4);
            memcpy(&buf[ptr], (BYTE *)&num, 4);
            ptr += 4;

            count[i] = copyfile(&buf[ptr], fd[i], fsize[i]);
            if (count[i] != fsize[i]) {
                LOG(LOG_ERR, "copyfile() faild %d != %d\n", count[i], fsize[i]);
            }

            /* close */
            close(fd[i]);
            fd[i] = -1;
            ptr += fsize[i];
            DEBUG_IFM("RM[%d] len = %d\n", i, count[i]);
        }
        break;
    }

    /* Collector --> Verifier */
    case NEW_RIMM_SET:
    {
        /* check */
        if (conf->newrm_num == 0) {
            /* New RM is missing => send Error massage */
            DEBUG_IFM("New RM is missing. send Error massage\n");
            ctx->ifm_errno = PTS_FATAL;
            ctx->ifm_strerror = smalloc_assert("New Manifest not found, check the collector");
            goto error;
        }

        /* setup TLV header  (2/2) */
        length = 16 + 4;  // UUID + num
        for (i = 0; i < conf->newrm_num; i++) {
            fd[i] = open(ctx->conf->newrm_filename[i], O_RDONLY);
            if (fd[i] < 0) {
                // 20101124 SM must be a fullpath for Daemon
                LOG(LOG_ERR, "Error RM file, %s not found\n", ctx->conf->newrm_filename[i]);
                /* send Error massage */
                ctx->ifm_errno = PTS_FATAL;
                ctx->ifm_strerror =
                    smalloc_assert("New Manifest file not found, check the collector");
                goto error;
            }
            /* check the size */
            if (-1 == fstat(fd[i], &st[i])) {
                LOG(LOG_ERR, "fstat failed with errno %d\n", errno);
                goto error;
            }
            fsize[i] = st[i].st_size;
            length += 4 + fsize[i];
        }


        DEBUG_IFM("writePtsTlv - NEW_RIMM_SET, length = %d", length);

        buf = getTlvBuffer(type, length);
        if (buf == NULL) {
            LOG(LOG_ERR, "getTlvBuffer() is null");
            goto error;
        }
        ptr = 12;


        // UUID
        memcpy(&buf[ptr], ctx->conf->newrm_uuid->uuid, 16);
        ptr += 16;

        // NUM of RM
        num = htonl(conf->newrm_num);
        memcpy(&buf[ptr], (BYTE *)&num, 4);
        ptr += 4;

        for (i = 0; i< conf->newrm_num; i++) {
            // length of RM[i]
            num = htonl(fsize[i]);
            memcpy(&buf[ptr], (BYTE *)&num, 4);
            ptr += 4;
            // RM[i] body
            count[i] = copyfile(&buf[ptr], fd[i], fsize[i]);
            /* close */
            close(fd[i]);
            fd[i] = -1;
            ptr += fsize[i];
            DEBUG_IFM("RM[%d] len = %d\n", i, count[i]);
        }
        break;
    }

    case NONCE:
    {
        length = ctx->nonce->nonce_length;
        buf = getTlvBuffer(type, length);
        if (buf == NULL) {
            LOG(LOG_ERR, "getTlvBuffer() is null");
            goto error;
        }
        memcpy(&buf[12], ctx->nonce->nonce, length);
        break;
    }

    case INTEGRITY_REPORT:
    {
        /* generate new IR, giving us a file descriptor corresponding
           to an already deleted file for added security - once the file
           gets closed you lose the IR! */
        rc = genIr(ctx, &fd[0]);
        if (rc != PTS_SUCCESS) {
            LOG(LOG_ERR, "writePtsTlvToSock - gen IR failed\n");
            /* send Error massage */
            ctx->ifm_errno = PTS_FATAL;
            ctx->ifm_strerror = smalloc_assert("Generation of IR failed");
            goto error;
        }

        /* check the IR size */
        if (-1 == fstat(fd[0], &st[0])) {
            LOG(LOG_ERR, "fstat failed with errno %d\n", errno);
            goto error;
        }
        fsize[0] = st[0].st_size;
        length = fsize[0];

        buf = getTlvBuffer(type, length);
        if (buf == NULL) {
            LOG(LOG_ERR, "getTlvBuffer() is null");
            goto error;
        }
        ptr = 12;

        if (-1 == lseek(fd[0], 0, SEEK_SET)) {
            LOG(LOG_ERR, "Could not seek to start of %s (fd '%d')\n", ctx->conf->ir_filename, fd[0]);
            goto error;
        }

        count[0] = copyfile(&buf[ptr], fd[0], fsize[0]);
        if (count[0] != fsize[0]) {
            LOG(LOG_ERR, "copyfile() faild %d != %d\n", count[0], fsize[0]);
        }

        /* close */
        close(fd[0]);
        fd[0] = -1;

        break;
    }

#ifdef CONFIG_AIDE
    case AIDE_DATABASE:  /* AIDE DATABASE: C -> V */
    {
        /* setup TLV header  (2/2) */
        /* body */
        if (ctx->conf->aide_database_filename == NULL) {
            // Test
            DEBUG("writePtsTlvToSock - Error AIDE DB file is not configured\n");
            ctx->ifm_errno = PTS_FATAL;
            ctx->ifm_strerror = smalloc_assert("AIDE DB file is not configured");
            goto error;
        } else {
            fd[0] = open(ctx->conf->aide_database_filename, O_RDONLY);
            if (fd[0] < 0) {
                /* AIDE file is missing, erorr */
                LOG(LOG_ERR, "writePtsTlvToSock - Error AIDE DB file, %s not found\n",
                    ctx->conf->aide_database_filename);
                /* send Error massage */
                ctx->ifm_errno = PTS_FATAL;
                ctx->ifm_strerror = smalloc_assert("AIDE file not found");
                goto error;
            } else {
                /* OK */
                if (-1 == fstat(fd[0], &st[0])) {
                    LOG(LOG_ERR, "fstat failed with errno %d\n", errno);
                    goto error;
                }
                fsize[0] = st[0].st_size;
                length = fsize[0];
            }
        }

        buf = getTlvBuffer(type, length);
        if (buf == NULL) {
            LOG(LOG_ERR, "getTlvBuffer() is null");
            goto error;
        }
        ptr = 12;


        if (length > 0) {
            // BODY1
            count[0] = copyfile(&buf[ptr], fd[0], fsize[0]);
            if (count[0] != fsize[0]) {
                LOG(LOG_ERR, "copyfile() faild %d != %d\n", count[0], fsize[0]);
            }

            /* close */
            close(fd[0]);
            fd[0] = -1;

            DEBUG_IFM("writePtsTlv - AIDE_DATABASE, file =  %s\n",
                ctx->conf->aide_database_filename);
            // DEBUG_IFM("AIDE DATABASE len = %d\n", count[0]);
        }
        DEBUG_IFM("writePtsTlv - AIDE_DATABASE, length = %d", length);
        break;
    }
#endif  // CONFIG_AIDE


    case DH_NONCE_PARAMETERS_REQUEST:  /* DH: Initiator -> Respondor */
    {
        /* setup TLV header  (2/2) */
        length = 4;
        buf = getTlvBuffer(type, length);
        if (buf == NULL) {
            goto error;
        }
        ptr = 12;

        /* Send DH Nonce */
        buf[0] = ctx->nonce->req->reserved;
        buf[1] = ctx->nonce->req->min_nonce_len;
        memcpy(&buf[ptr], buf, 2);
        ptr += 2;

        nbou16 = htons(ctx->nonce->req->dh_group_set);
        memcpy(&buf[ptr], (BYTE *)&nbou16, 2);
        ptr += 2;

        DEBUG_IFM("writePtsTlv - DH_NONCE_PARAMETERS_REQUEST, length = %d", length);
        break;
    }

    case DH_NONCE_PARAMETORS_RESPONSE:  /* DH: IRespondor -> Initiator */
    {
        /* setup TLV header  (2/2) */
        length =
            4 + 4 +
            ctx->nonce->respondor_nonce_length +
            ctx->nonce->pubkey_length;

        buf = getTlvBuffer(type, length);
        if (buf == NULL) {
            LOG(LOG_ERR, "getTlvBuffer() is null");
            goto error;
        }
        ptr = 12;

        /* Send DH param  */
        buf[0] = ctx->nonce->res->reserved[0];
        buf[1] = ctx->nonce->res->reserved[1];
        buf[2] = ctx->nonce->res->reserved[2];
        buf[3] = ctx->nonce->res->nonce_length;
        memcpy(&buf[ptr], buf, 4);
        ptr += 4;

        nbou16 = htons(ctx->nonce->res->selected_dh_group);
        memcpy(&buf[ptr], (BYTE *)&nbou16, 2);
        ptr += 2;

        nbou16 = htons(ctx->nonce->res->hash_alg_set);
        memcpy(&buf[ptr], (BYTE *)&nbou16, 2);
        ptr += 2;

        /* nonce */
        memcpy(
            &buf[ptr],
            ctx->nonce->respondor_nonce,
            ctx->nonce->respondor_nonce_length);
        ptr += ctx->nonce->respondor_nonce_length;

        /* send dh_respondor_public */
        memcpy(
            &buf[ptr],
            ctx->nonce->pubkey,
            ctx->nonce->pubkey_length);
        ptr += ctx->nonce->pubkey_length;

        DEBUG_IFM("writePtsTlv - DH_NONCE_PARAMETORS_RESPONSE, length = %d", length);
        break;
    }

    case DH_NONCE_FINISH: /* DH: Initiator -> Respondor */
    {
        /* setup TLV header  (2/2) */
        length =
            4 +
            ctx->nonce->initiator_nonce_length +
            ctx->nonce->pubkey_length;

        buf = getTlvBuffer(type, length);
        if (buf == NULL) {
            LOG(LOG_ERR, "getTlvBuffer() is null");
            goto error;
        }
        ptr = 12;

        /* Send IF-M TLV header */

        /* Send */
        buf[0] = ctx->nonce->fin->reserved = 0;
        buf[1] = ctx->nonce->fin->nonce_length = ctx->nonce->initiator_nonce_length;
        memcpy(&buf[ptr], (BYTE *)&buf, 2);
        ptr += 2;

        nbou16 = htons(ctx->nonce->fin->selected_hash_alg);
        memcpy(&buf[ptr], (BYTE *)&nbou16, 2);
        ptr += 2;

        /* send dh_initiator_pubkey */
        memcpy(&buf[ptr], ctx->nonce->pubkey, ctx->nonce->pubkey_length);
        ptr += ctx->nonce->pubkey_length;

        /* send dh_initiator_nonce */
        memcpy(
            &buf[ptr],
            ctx->nonce->initiator_nonce,
            ctx->nonce->initiator_nonce_length);
        ptr += ctx->nonce->initiator_nonce_length;

        DEBUG_IFM("writePtsTlv - DH_NONCE_FINISH, length = %d", length);
        break;
    }

    case OPENPTS_ERROR:
    {
        /* setup TLV header  (2/2) */
        // TODO
        if (ctx->ifm_strerror != NULL) {
            length = 4 + 4 + strlen(ctx->ifm_strerror);
        } else {
            length = 4 + 4 + 0;
        }

        buf = getTlvBuffer(type, length);
        if (buf == NULL) {
            LOG(LOG_ERR, "getTlvBuffer() is null");
            goto error;
        }
        ptr = 12;

        {
            UINT32 ifm_errno;
            UINT32 size = 0;
            UINT32 len = 0;
            /* send error code */
            ifm_errno = htonl(ctx->ifm_errno);
            memcpy(&buf[ptr], (BYTE *)&ifm_errno, 4);
            ptr += 4;

            /* send msg num */

            if (ctx->ifm_strerror != NULL) {
                len = strlen(ctx->ifm_strerror);
                size = htonl(len);
                memcpy(&buf[ptr], (BYTE *)&size, 4);
                ptr += 4;

                memcpy(&buf[ptr], (BYTE *)&ctx->ifm_strerror, len);
                ptr += len;
                /* free */
                xfree(ctx->ifm_strerror);
            } else {
                size = 0;
                memcpy(&buf[ptr], (BYTE *)&size, 4);
                ptr += 4;
            }
        }

        DEBUG_IFM("writePtsTlv - OPENPTS_ERROR, length = %d", length);
        break;
    }

    default:
        // BAD type
        LOG(LOG_ERR, "BAD IF-M OPENPTS MESSAGE TYPE, type=0x%x\n", type);
        return NULL;
    }

    DEBUG_IFM("IF-M message, type=0x%x, length=%d\n",
        type, length);
    DEBUG("writePtsTlvToSock - done\n");

    *len = 12 + length;
    return buf;

  error:
    /* close files*/
    for (i = 0; i < MAX_RM_NUM; i++) {
        if (fd[i] >= 0) close(fd[i]);
    }

    *len = 0;
    return NULL;
}
Example #14
0
///
/// US_LoadUsers
//  Loads user database from .users
static void US_LoadUsers(void)
{
  BOOL save = FALSE;
  FILE *fh;

  ENTER();

  // reset the user data
  memset(&G->Users, 0, sizeof(struct Users));
  G->Users.Num = 0;

  if((fh = fopen("PROGDIR:.users", "r")) != NULL)
  {
    char *buffer = NULL;
    size_t size = 0;
    BOOL hasmanager = FALSE;

    if(GetLine(&buffer, &size, fh) >= 3 && strncmp(buffer,"YUS", 3) == 0)
    {
      int ver = buffer[3] - '0';

      while(GetLine(&buffer, &size, fh) >= 0)
      {
        if(strncmp(buffer, "@USER", 5) == 0)
        {
          struct User *user = &G->Users.User[G->Users.Num];
          int flags;
          enum FType type;

          strlcpy(user->Name, Trim(&buffer[6]), sizeof(user->Name));
          GetLine(&buffer, &size, fh);
          strlcpy(user->MailDir, Trim(buffer), sizeof(user->MailDir));
          if(user->MailDir[0] == '\0')
          {
            strlcpy(user->MailDir, G->MA_MailDir, sizeof(user->MailDir));
            save = TRUE;
          }

          GetLine(&buffer, &size, fh);
          flags = atoi(Trim(buffer));
          user->Limited = isFlagSet(flags, UFLAG_LIMITED_USER);
          user->UseAddr = isFlagSet(flags, UFLAG_USE_GLOBAL_ADDRESSBOOK);
          user->UseDict = isFlagSet(flags, UFLAG_USE_GLOBAL_DICTIONARY);
          if(user->Limited == FALSE)
            hasmanager = TRUE;

          if(ver >= 2)
          {
            GetLine(&buffer, &size, fh);
            strlcpy(user->Password, Decrypt(buffer), sizeof(user->Password));
          }

          user->ID = GetUniqueID();
          G->Users.Num++;

          // check if the user's home directory exists
          if(ObtainFileInfo(user->MailDir, FI_TYPE, &type) == FALSE || type != FIT_DRAWER)
            ER_NewError(tr(MSG_ER_USER_DIR_MISSING), user->MailDir, user->Name);

          // skip all lines until we read the "@ENDUSER"
          while(GetLine(&buffer, &size, fh) >= 0)
          {
            if(strcmp(buffer, "@ENDUSER") == 0)
              break;
          }
        }
      }
    }

    fclose(fh);

    free(buffer);

    // if we found no user with manager privileges we give these privilege to the first user
    if(hasmanager == FALSE)
    {
      G->Users.User[0].Limited = FALSE;
      save = TRUE;
    }
  }

  // create a default user if none exists so far
  if(G->Users.Num == 0)
  {
    struct User *user = &G->Users.User[0];

    user->Name[0] = '\0';
    strlcpy(user->MailDir, G->MA_MailDir, sizeof(user->MailDir));
    user->Limited = FALSE;
    user->UseAddr = TRUE;
    user->UseDict = TRUE;
    user->ID = GetUniqueID();

    // there can only be one :)
    G->Users.Num = 1;
    save = TRUE;
  }

  // if the first user doesn't have a real name yet then copy over the name from the configuration
  if(G->Users.User[0].Name[0] == '\0')
  {
    struct UserIdentityNode *uin = GetUserIdentity(&C->userIdentityList, 0, TRUE);

    if(uin != NULL)
      strlcpy(G->Users.User[0].Name, uin->realname, sizeof(G->Users.User[0].Name));

    // if the first user still doesn't have a name then we use a fallback name
    if(G->Users.User[0].Name[0] == '\0')
      strlcpy(G->Users.User[0].Name, tr(MSG_USERNAME_FALLBACK), sizeof(G->Users.User[0].Name));

    // make sure our modifications are saved
    save = TRUE;
  }

  if(save == TRUE)
    US_SaveUsers();

  LEAVE();
}
Example #15
0
/*---------------------*
 * Split line into two *
 *---------------------*/
BOOL SplitLine(LONG x, struct line_node *line, BOOL move_crsr, struct UserAction *buffer, struct InstData *data)
{
  struct line_node *newline;
  struct line_node *next;
  struct pos_info pos;
  LONG line_nr, lines;
  ULONG c;
  UWORD crsr_x = data->CPos_X;
  struct line_node *crsr_l = data->actualline;

  ENTER();

  OffsetToLines(x, line, &pos, data);
  lines = pos.lines;

  next = line->next;
  if((newline = AllocLine(data)) != NULL)
  {
    UWORD *styles = line->line.Styles;
    UWORD *newstyles = NULL;
    UWORD *colors = line->line.Colors;
    UWORD *newcolors = NULL;

    data->HasChanged = TRUE;
    Init_LineNode(newline, line, line->line.Contents+x, data);
    newline->line.Color = line->line.Color;
    newline->line.Flow = line->line.Flow;
    newline->line.Separator = line->line.Separator;
    if(buffer != NULL)
    {
      newline->line.Color = buffer->del.style;
      newline->line.Flow = buffer->del.flow;
      newline->line.Separator = buffer->del.separator;
    }

    if(styles != NULL)
    {
      LONG  style = 0;
      LONG  length = 0;
      UWORD *ostyles;

      while(*styles++ <= x+1)
      {
        if(*styles > 0xff)
          style &= *styles++;
        else
          style |= *styles++;
      }
      styles--;
      ostyles = styles;
      while(*(styles+length) != EOS)
        length += 2;
      length = (length*2) + 16;

      if((newstyles = MyAllocPooled(data->mypool, length)) != NULL)
      {
          UWORD *nstyles = newstyles;

        if(isFlagSet(style, BOLD))
        {
          *nstyles++ = 1;
          *nstyles++ = BOLD;
        }
        if(isFlagSet(style, ITALIC))
        {
          *nstyles++ = 1;
          *nstyles++ = ITALIC;
        }
        if(isFlagSet(style, UNDERLINE))
        {
          *nstyles++ = 1;
          *nstyles++ = UNDERLINE;
        }

        while(*styles != EOS)
        {
          *nstyles++ = (*styles++) - x;
          *nstyles++ = *styles++;
        }
        *nstyles = EOS;
      }

      if(isFlagSet(style, BOLD))
      {
        *ostyles++ = x+1;
        *ostyles++ = ~BOLD;
      }
      if(isFlagSet(style, ITALIC))
      {
        *ostyles++ = x+1;
        *ostyles++ = ~ITALIC;
      }
      if(isFlagSet(style, UNDERLINE))
      {
        *ostyles++ = x+1;
        *ostyles++ = ~UNDERLINE;
      }
      if(x != 0)
        ostyles = line->line.Styles;
      *ostyles = EOS;
    }
    newline->line.Styles = newstyles;

    if(colors != NULL)
    {
      UWORD color = GetColor(x, line);
      UWORD length = 0;
      UWORD *ocolors;

      while(*colors <= x+1)
      {
        colors += 2;
      }
      ocolors = colors;

      while(*(colors+length) != 0xffff)
        length += 2;
      length = (length*2) + 16;

      if((newcolors = MyAllocPooled(data->mypool, length)) != NULL)
      {
        UWORD *ncolors = newcolors;

        if(color && *colors-x != 1)
        {
          *ncolors++ = 1;
          *ncolors++ = color;
        }

        while(*colors != 0xffff)
        {
          *ncolors++ = (*colors++) - x;
          *ncolors++ = *colors++;
        }
        *ncolors = 0xffff;
      }
      if(x != 0)
        ocolors = line->line.Colors;
      *ocolors = 0xffff;
    }
    newline->line.Colors = newcolors;


    newline->next = next;
    if(next != NULL)
      next->previous = newline;

    *(line->line.Contents+x) = '\n';
    *(line->line.Contents+x+1) = '\0';
    line->line.Length = x+1;

/*------------------*/
    c = line->visual;
    line->visual = VisualHeight(line, data);
    CompressLine(line, data);

    line_nr = LineToVisual(line, data) + line->visual - 1;
    if(line_nr < 0)
      line_nr = 0;

    if(move_crsr)
    {
      data->CPos_X = 0;
      data->actualline = data->actualline->next;
    }

    if(x == 0)
    {
      line->line.Color = 0;
      line->line.Separator = 0;
      if(!(line->previous && line->previous->line.Flow == line->line.Flow))
      {
        line->line.Flow = MUIV_TextEditor_Flow_Left;
      }
      if(line_nr != data->maxlines)
      {
        data->totallines += 1;
        if(data->fastbackground)
        {
          if(line_nr)
          {
            ScrollDown(line_nr-1, 1, data);
            PrintLine(0, line, line_nr, FALSE, data);
          }
          else
          {
            ScrollDown(line_nr, 1, data);
          }
        }
        else  DumpText(data->visual_y+line_nr-1, line_nr-1, data->maxlines, TRUE, data);
      }
      else
      {
        data->visual_y++;
        data->totallines += 1;
        if(isFlagClear(data->flags, FLG_Quiet))
        {
          struct Hook *oldhook;

          oldhook = InstallLayerHook(data->rport->Layer, LAYERS_NOBACKFILL);
          ScrollRasterBF(data->rport, 0, data->height,
                    data->xpos, data->ypos,
                    data->xpos + data->innerwidth - 1, (data->ypos + ((data->maxlines-1) * data->height)) - 1);
          InstallLayerHook(data->rport->Layer, oldhook);

          PrintLine(0, line, data->maxlines-1, FALSE, data);
          if(!data->fastbackground)
          {
            DumpText(data->visual_y+data->maxlines-1, data->maxlines-1, data->maxlines, TRUE, data);
          }
        }
      }

      RETURN(TRUE);
      return(TRUE);
    }

    if(x == (LONG)(line->line.Length + newline->line.Length - 2))
    {
      data->totallines += 1;
      if(buffer == NULL)
      {
        line->next->line.Color = 0;
        line->next->line.Separator = 0;
      }
      SetCursor(crsr_x, crsr_l, FALSE, data);
      if(line_nr < data->maxlines)
      {
        if(data->fastbackground)
        {
          ScrollDown(line_nr, 1, data);
          if(line_nr+1 <= data->maxlines)
            PrintLine(0, line->next, line_nr+1, FALSE, data);
        }
        else  DumpText(data->visual_y+line_nr, line_nr, data->maxlines, TRUE, data);
      }

      RETURN(TRUE);
      return(TRUE);
    }
    x = line->line.Length;

    OffsetToLines(x-1, line, &pos, data);
    if(((ULONG)(line->visual + line->next->visual) >= c) && (line->visual == lines))
    {
      if((ULONG)(line->visual + line->next->visual) > c)
        data->totallines += 1;

      PrintLine(pos.bytes, line, line_nr, TRUE, data);

      if((line_nr+line->next->visual-1 < data->maxlines) && ((ULONG)(line->visual + line->next->visual) > c))
      {
        ScrollDown(line_nr+line->next->visual-1, 1, data);
      }
    }
    else
    {
      PrintLine((x-1)-pos.x, line, line_nr, TRUE, data);

      if((line_nr < data->maxlines) && ((ULONG)(line->visual + line->next->visual) < c))
      {
        data->totallines -= 1;
        ScrollUp(line_nr, 1, data);
      }
    }
/*------------------*/
    line = line->next;
    line_nr++;
    c = 0;
    while((c < line->line.Length) && (line_nr <= data->maxlines))
      c = c + PrintLine(c, line, line_nr++, TRUE, data);
  /* Her printes !HELE! den nye linie, burde optimeres! */

    RETURN(TRUE);
    return (TRUE);
  }
  else
  {
    RETURN(FALSE);
    return (FALSE);
  }
}
Example #16
0
static struct dlstatus *loadModule(const char *path, const struct stat *sbuf, int mode)
{
	NSObjectFileImage ofi = 0;
	NSObjectFileImageReturnCode ofirc;
	struct dlstatus *dls;
	NSLinkEditErrors ler;
	int lerno;
	const char *errstr;
	const char *file;
	void (*init) (void);
	ofirc = NSCreateObjectFileImageFromFile(path, &ofi);
	switch (ofirc)
	{
		case NSObjectFileImageSuccess:
			break;
		case NSObjectFileImageInappropriateFile:
			if (dyld_NSAddImage && dyld_NSIsSymbolNameDefinedInImage && dyld_NSLookupSymbolInImage)
			{	
				if (isFlagSet(mode, RTLD_LOCAL))
				{
					warning("trying to open a .dylib with RTLD_LOCAL");
					error("unable to open this file with RTLD_LOCAL");
					return NULL;
				}
			}
			else
			{
				error("opening this file is unsupported on this system");
				return NULL;
			}
			break;
		case NSObjectFileImageFailure:
			error("object file setup failure");
			return NULL;
		case NSObjectFileImageArch:
			error("no object for this architecture");
			return NULL;
		case NSObjectFileImageFormat:
			error("bad object file format");
			return NULL;
		case NSObjectFileImageAccess:
			error("can't read object file");
			return NULL;
		default:
			error("unknown error from NSCreateObjectFileImageFromFile()");
			return NULL;
	}
	dls = lookupStatus(sbuf);
	if (!dls)
	{
		dls = allocStatus();
	}
	if (!dls)
	{
		error("unable to allocate memory");
		return NULL;
	}
	dls->lib = 0;
	if (ofirc == NSObjectFileImageInappropriateFile)
	{
		if ((dls->lib = dyld_NSAddImage(path, NSADDIMAGE_OPTION_RETURN_ON_ERROR)))
		{
			debug("Dynamic lib loaded at %ld", dls->lib);
			ofi = MAGIC_DYLIB_OFI;
			dls->module = MAGIC_DYLIB_MOD;
			ofirc = NSObjectFileImageSuccess;
			/* Although it is possible with a bit of work to modify this so it works and
			   functions with RTLD_NOW, I don't deem it necessary at the moment */
		}
		if (!(dls->module))
		{
			NSLinkEditError(&ler, &lerno, &file, &errstr);
			if (!errstr || (!strlen(errstr)))
				error("Can't open this file type");
			else
				error(errstr);
			if ((dls->flags & DL_IN_LIST) == 0)
			{
				free(dls);
			}
			return NULL;
		}
	}
	else
	{
		dls->module = NSLinkModule(ofi, path,
								   NSLINKMODULE_OPTION_RETURN_ON_ERROR |
								   NSLINKMODULE_OPTION_PRIVATE |
								   (isFlagSet(mode, RTLD_NOW) ? NSLINKMODULE_OPTION_BINDNOW : 0));
		NSDestroyObjectFileImage(ofi);
		if (dls->module)
		{
			dls->lib = get_mach_header_from_NSModule(dls->module);
		}
	}
	if (!dls->module)
	{
		NSLinkEditError(&ler, &lerno, &file, &errstr);
		if ((dls->flags & DL_IN_LIST) == 0)
		{
			free(dls);
		}
		error(errstr);
		return NULL;
	}

	insertStatus(dls, sbuf);
	dls = reference(dls, mode);
	if ((init = dlsymIntern(dls, "__init", 0)))
	{
		debug("calling _init()");
		init();
	}
	return dls;
}
Example #17
0
ULONG loadPrefs(ULONG mode)
{
    struct URL_Prefs       *p;
    ULONG                  error = 0;

    /* get the openurl.library prefs */
/*    switch(mode)
    {
        case MUIV_Win_GetPrefs_InUse:      mode = URL_GetPrefs_Mode_InUse;   break;
        case MUIV_Win_GetPrefs_LastSaveds: mode = URL_GetPrefs_Mode_Envarc;  break;
        case MUIV_Win_GetPrefs_Restore:    mode = URL_GetPrefs_Mode_Env;     break;
        case MUIV_Win_GetPrefs_Defaults:   mode = URL_GetPrefs_Mode_Default; break;
        default: return FALSE;
    }
*/
    p = IOpenURL->URL_GetPrefs(URL_GetPrefs_Mode,mode,TAG_DONE);
    if (!p) error = MSG_Err_NoPrefs;
    else if (p->up_Version!=PREFS_VERSION) error = MSG_Err_BadPrefs;

    if (error)
    {
        RA_Request(NULL,0,getString(MSG_ErrReqTitle),
                          getString(MSG_ErrReqGadget),
                          getString(error),
                          p ? p->up_Version : 0);

        if (p) IOpenURL->URL_FreePrefsA(p,NULL);

        return FALSE;
    }

    /* Browsers */
	gadset(GAD(OBJ_LBROWSER_BROW), window, LISTBROWSER_Labels, ~0);
    updateBrowserList(&list_Brow, p->up_BrowserList);
	gadset(GAD(OBJ_LBROWSER_BROW), window, LISTBROWSER_Labels, &list_Brow, LISTBROWSER_AutoFit, TRUE);

    /* Mailers */
    gadset(GAD(OBJ_LBROWSER_MAIL), window, LISTBROWSER_Labels, ~0, TAG_DONE);
    updateMailerList(&list_Mail, p->up_MailerList);
    gadset(GAD(OBJ_LBROWSER_MAIL), window, LISTBROWSER_Labels, &list_Mail, LISTBROWSER_AutoFit, TRUE);

    /* FTPs */
	gadset(GAD(OBJ_LBROWSER_FTP), window, LISTBROWSER_Labels, ~0, TAG_DONE);
    updateFTPList(&list_FTPs, p->up_FTPList);
	gadset(GAD(OBJ_LBROWSER_FTP), window, LISTBROWSER_Labels, &list_FTPs, LISTBROWSER_AutoFit, TRUE);

    /* Miscellaneous */
    gadset(GAD(OBJ_PREPEND), window, GA_Selected, isFlagSet(p->up_Flags, UPF_PREPENDHTTP));
    gadset(GAD(OBJ_SEND_MAILTO), window, GA_Selected, isFlagSet(p->up_Flags, UPF_DOMAILTO));
    gadset(GAD(OBJ_SEND_FTP), window, GA_Selected, isFlagSet(p->up_Flags, UPF_DOFTP));

    gadset(GAD(OBJ_UNICONIFY), window, GA_Selected, p->up_DefShow);
    gadset(GAD(OBJ_BRING), window, GA_Selected, p->up_DefBringToFront);
    gadset(GAD(OBJ_OPEN), window, GA_Selected, p->up_DefNewWindow);
    gadset(GAD(OBJ_LAUNCH), window, GA_Selected, p->up_DefLaunch);

    /* free the preferences */
    IOpenURL->URL_FreePrefsA(p,NULL);

    return TRUE;
}
Example #18
0
/* Main program */
  int
main(void)
{
  /* TLE source file */
  char tle_file[] = "./rax.txt";

  /* Observer's geodetic co-ordinates.      */
  /* Lat North, Lon East in rads, Alt in km */
  geodetic_t obs_geodetic = {0.7368, -1.4615, 0.251, 0.0};

  /* Two-line Orbital Elements for the satellite */
  tle_t tle ;

  /* Zero vector for initializations */
  vector_t zero_vector = {0,0,0,0};

  /* Satellite position and velocity vectors */
  vector_t vel = zero_vector;
  vector_t pos = zero_vector;
  /* Satellite Az, El, Range, Range rate */
  vector_t obs_set;

  /* Solar ECI position vector  */
  vector_t solar_vector = zero_vector;
  /* Solar observed azi and ele vector  */
  vector_t solar_set;

  /* Calendar date and time (UTC) */
  struct tm utc;

  /* Satellite's predicted geodetic position */
  geodetic_t sat_geodetic;

  double
	tsince,            /* Time since epoch (in minutes) */
	jul_epoch,         /* Julian date of epoch          */
	jul_utc,           /* Julian UTC date               */
	eclipse_depth = 0, /* Depth of satellite eclipse    */
	/* Satellite's observed position, range, range rate */
	sat_azi, sat_ele, sat_range, sat_range_rate,
	/* Satellites geodetic position and velocity */
	sat_lat, sat_lon, sat_alt, sat_vel,
	/* Solar azimuth and elevation */
	sun_azi, sun_ele;

  /* Used for storing function return codes */
  int flg;

  char
	ephem[5],       /* Ephemeris in use string  */
	sat_status[12]; /* Satellite eclipse status */


  /* Input one (first!) TLE set from file */
  flg = Input_Tle_Set(tle_file, &tle);

  /* Abort if file open fails */
  if( flg == -1 )
  {
	printf(" File open failed - Exiting!\n");
	exit(-1);
  }

  /* Print satellite name and TLE read status */
  printf(" %s: ", tle.sat_name);
  if( flg == -2 )
  {
	printf("TLE set bad - Exiting!\n");
	exit(-2);
  }
  else
	printf("TLE set good - Happy Tracking!\n");

  /* Printout of tle set data for tests if needed */
  /*  printf("\n %s %s %i  %i  %i\n"
	  " %14f %10f %8f %8f\n"
	  " %8f %8f %9f %8f %8f %12f\n",
	  tle.sat_name, tle.idesg, tle.catnr, tle.elset, tle.revnum,
	  tle.epoch, tle.xndt2o, tle.xndd6o, tle.bstar,
	  tle.xincl, tle.xnodeo, tle.eo, tle.omegao, tle.xmo, tle.xno);
   */

  /** !Clear all flags! **/
  /* Before calling a different ephemeris  */
  /* or changing the TLE set, flow control */
  /* flags must be cleared in main().      */
  ClearFlag(ALL_FLAGS);

  /** Select ephemeris type **/
  /* Will set or clear the DEEP_SPACE_EPHEM_FLAG       */
  /* depending on the TLE parameters of the satellite. */
  /* It will also pre-process tle members for the      */
  /* ephemeris functions SGP4 or SDP4 so this function */
  /* must be called each time a new tle set is used    */
  select_ephemeris(&tle);

  do  /* Loop */
  {
	/* Get UTC calendar and convert to Julian */
	UTC_Calendar_Now(&utc);
	jul_utc = Julian_Date(&utc);

	/* Convert satellite's epoch time to Julian  */
	/* and calculate time since epoch in minutes */
	jul_epoch = Julian_Date_of_Epoch(tle.epoch);
	tsince = (jul_utc - jul_epoch) * xmnpda;

	/* Copy the ephemeris type in use to ephem string */
	if( isFlagSet(DEEP_SPACE_EPHEM_FLAG) )
	  strcpy(ephem,"SDP4");
	else
	  strcpy(ephem,"SGP4");

	/* Call NORAD routines according to deep-space flag */
	if( isFlagSet(DEEP_SPACE_EPHEM_FLAG) )
	  SDP4(tsince, &tle, &pos, &vel);
	else
	  SGP4(tsince, &tle, &pos, &vel);

	/* Scale position and velocity vectors to km and km/sec */
	Convert_Sat_State( &pos, &vel );

	/* Calculate velocity of satellite */
	Magnitude( &vel );
	sat_vel = vel.w;

	/** All angles in rads. Distance in km. Velocity in km/s **/
	/* Calculate satellite Azi, Ele, Range and Range-rate */
	Calculate_Obs(jul_utc, &pos, &vel, &obs_geodetic, &obs_set);

	/* Calculate satellite Lat North, Lon East and Alt. */
	Calculate_LatLonAlt(jul_utc, &pos, &sat_geodetic);

	/* Calculate solar position and satellite eclipse depth */
	/* Also set or clear the satellite eclipsed flag accordingly */
	Calculate_Solar_Position(jul_utc, &solar_vector);
	Calculate_Obs(jul_utc,&solar_vector,&zero_vector,&obs_geodetic,&solar_set);

	if( Sat_Eclipsed(&pos, &solar_vector, &eclipse_depth) )
	  SetFlag( SAT_ECLIPSED_FLAG );
	else
	  ClearFlag( SAT_ECLIPSED_FLAG );

	/* Copy a satellite eclipse status string in sat_status */
	if( isFlagSet( SAT_ECLIPSED_FLAG ) )
	  strcpy( sat_status, "Eclipsed" );
	else
	  strcpy( sat_status, "In Sunlight" );

	/* Convert and print satellite and solar data */
	sat_azi = Degrees(obs_set.x);
	sat_ele = Degrees(obs_set.y);
	sat_range = obs_set.z;
	sat_range_rate = obs_set.w;
	sat_lat = Degrees(sat_geodetic.lat);
	sat_lon = Degrees(sat_geodetic.lon);
	sat_alt = sat_geodetic.alt;

	sun_azi = Degrees(solar_set.x);
	sun_ele = Degrees(solar_set.y);

	printf("\n Date: %02d/%02d/%04d UTC: %02d:%02d:%02d  Ephemeris: %s"
		"\n Azi=%6.1f Ele=%6.1f Range=%8.1f Range Rate=%6.2f"
		"\n Lat=%6.1f Lon=%6.1f  Alt=%8.1f  Vel=%8.3f"
		"\n Stellite Status: %s - Depth: %2.3f"
		"\n Sun Azi=%6.1f Sun Ele=%6.1f\n",
		utc.tm_mday, utc.tm_mon, utc.tm_year,
		utc.tm_hour, utc.tm_min, utc.tm_sec, ephem,
		sat_azi, sat_ele, sat_range, sat_range_rate,
		sat_lat, sat_lon, sat_alt, sat_vel,
		sat_status, eclipse_depth,
		sun_azi, sun_ele);

	sleep(1);
  }  /* End of do */
  while( 1 ); /* This stops Compaq ccc 'unreachcode' warning! */

  return(0);
} /* End of main() */
Example #19
0
void Draw_Mesh_simple(Mesh_t *mesh)
{
  int meshtype = mesh->meshtype;

  LUX_DEBUGASSERT(mesh);

  if (!mesh->numVertices)
    return;

  // draw mesh
  if (meshtype != MESH_DL){
    int n;
    ushort  *pointtri;
    uint  *pointtriI;
    uint  offsetTri;
    uint  vertexoffset;
    GLenum  rendertype = mesh->primtype;
    GLenum  indicestype = mesh->index16 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;

    LUX_DEBUGASSERT(!(mesh->meshtype == MESH_VBO && !mesh->vid.vbo));

    if (mesh->vid.ibo){
      pointtri  = NULL;
      pointtriI = NULL;
      offsetTri  = mesh->vid.ibooffset;
    }
    else{
      offsetTri = 0;
      pointtri  = mesh->indicesData16;
      pointtriI = mesh->indicesData32;
    }
    vidBindBufferIndex(mesh->vid.ibo);

    vertexoffset = mesh->vid.vbo ? mesh->vid.vbooffset : 0;


    // feed vertex attribs
    {
      int t;
      Mesh_setStandardAttribsGL(mesh,
        !(g_VID.state.renderflag & RENDER_NOVERTEXCOLOR),
        g_VID.drawsetup.lightCnt || g_VID.drawsetup.setnormals);

      for (t = 0; t < VID_MAX_TEXTURE_UNITS; t++){
        if (g_VID.state.texcoords[t].type < 0){
          Mesh_setTexCoordGL(mesh,t,g_VID.state.texcoords[t].channel);
        }
      }

      if (g_VID.drawsetup.attribs.needed & (1<<VERTEX_ATTRIB_TANGENT)){
        Mesh_setTangentGL(mesh);
      }
    }

    if (mesh->vid.ibo || mesh->indicesData){
      if (mesh->numGroups < 2){
        if (GLEW_EXT_draw_range_elements)
          glDrawRangeElementsEXT(rendertype,mesh->indexMin + vertexoffset,mesh->indexMax + vertexoffset, USED_INDICES(mesh->numIndices),  indicestype ,mesh->index16 ? (void*)(&pointtri[offsetTri]) : (void*)(&pointtriI[offsetTri]));
        else
          glDrawElements(rendertype, USED_INDICES(mesh->numIndices),  indicestype, mesh->index16 ? (void*)(&pointtri[offsetTri]) : (void*)(&pointtriI[offsetTri]));
      }
      else {
        for (n = 0; n < mesh->numGroups; n++){
          if (GLEW_EXT_draw_range_elements)
            glDrawRangeElementsEXT(rendertype,mesh->indexMin + vertexoffset,mesh->indexMax + vertexoffset, USED_INDICES(mesh->indicesGroupLength[n]),  indicestype ,mesh->index16 ? (void*)(&pointtri[offsetTri]) : (void*)(&pointtriI[offsetTri]));
          else
            glDrawElements(rendertype, USED_INDICES(mesh->indicesGroupLength[n]),  indicestype, mesh->index16 ? (void*)(&pointtri[offsetTri]) : (void*)(&pointtriI[offsetTri]));

          offsetTri += mesh->indicesGroupLength[n];
        }
      }
    }
    else{
      glDrawArrays(rendertype,vertexoffset,mesh->numVertices);
    }
  }
  else{
    vidBindBufferArray(NULL);
    vidBindBufferIndex(NULL);
    if (g_VID.gpuvendor == VID_VENDOR_ATI)
      if((g_VID.drawsetup.lightCnt || g_VID.drawsetup.setnormals) && (mesh->vertextype == VERTEX_32_NRM || mesh->vertextype == VERTEX_64_TEX4 || mesh->vertextype == VERTEX_64_SKIN || mesh->vertextype == VERTEX_32_FN))
        glEnableClientState(GL_NORMAL_ARRAY);
      else
        glDisableClientState(GL_NORMAL_ARRAY);

    glCallList(mesh->vid.glID);
    g_VID.state.activeTex = -1;
    g_VID.state.activeClientTex = -1;

    LUX_DEBUGASSERT(!glIsEnabled(GL_COLOR_ARRAY)==isFlagSet(g_VID.state.renderflag,RENDER_NOVERTEXCOLOR));

    //if (!glIsEnabled(GL_COLOR_ARRAY)) g_VID.state.renderflag |= RENDER_NOVERTEXCOLOR;
    //else                g_VID.state.renderflag &= ~RENDER_NOVERTEXCOLOR;

    vidResetPointer();
  }


#if 0
  glEnableClientState(GL_VERTEX_ARRAY);
  vidResetPointer();
  vidResetBuffers();
#endif

}
Example #20
0
IPTR Get(struct IClass *cl, Object *obj, struct opGet *msg)
{
  struct InstData *data = (struct InstData *)INST_DATA(cl, obj);
  IPTR ti_Data;

  switch(msg->opg_AttrID)
  {
    case MUIA_Font:
      ti_Data = (IPTR)(data->Font ? data->Font : muiAreaData(obj)->mad_Font);
    break;

    case MUIA_ControlChar:
      ti_Data = (IPTR)data->CtrlChar;
    break;

    case MUIA_String_AttachedList:
      ti_Data = (IPTR)data->ForwardObject;
    break;

    case MUIA_String_BufferPos:
      ti_Data = (IPTR)data->BufferPos;
    break;

    case MUIA_String_Acknowledge:
    case MUIA_String_Contents:
      ti_Data = (IPTR)data->Contents;
    break;

    case MUIA_String_DisplayPos:
      ti_Data = (IPTR)data->DisplayPos;
    break;

    case MUIA_String_Format:
      ti_Data = (IPTR)data->Alignment;
    break;

    case MUIA_String_Integer:
      StrToLong(data->Contents, (ULONG *)&ti_Data);
    break;

    case MUIA_String_MaxLen:
      ti_Data = (IPTR)data->MaxLength;
    break;

    case MUIA_String_Reject:
      ti_Data = (IPTR)data->Reject;
    break;

    case MUIA_String_Secret:
      ti_Data = isFlagSet(data->Flags, FLG_Secret) ? TRUE : FALSE;
    break;

    case MUIA_String_EditHook:
      ti_Data = (IPTR)data->EditHook;
    break;

    case MUIA_String_AdvanceOnCR:
      ti_Data = isFlagSet(data->Flags, FLG_AdvanceOnCr) ? TRUE : FALSE;
    break;

    case MUIA_BetterString_KeyUpFocus:
      ti_Data = (IPTR)data->KeyUpFocus;
    break;

    case MUIA_BetterString_KeyDownFocus:
      ti_Data = (IPTR)data->KeyDownFocus;
    break;

    case MUIA_BetterString_SelectSize:
      ti_Data = isFlagSet(data->Flags, FLG_BlockEnabled) ? data->BlockStop-data->BlockStart : 0;
    break;

    case MUIA_BetterString_StayActive:
      ti_Data = isFlagSet(data->Flags, FLG_StayActive) ? TRUE : FALSE;
    break;

    case MUIA_BetterString_NoInput:
      ti_Data = isFlagSet(data->Flags, FLG_NoInput) ? TRUE : FALSE;
    break;

    case MUIA_BetterString_InactiveContents:
      ti_Data = (IPTR)data->InactiveContents;
    break;

    case MUIA_BetterString_NoShortcuts:
      ti_Data = isFlagSet(data->Flags, FLG_NoShortcuts) ? TRUE : FALSE;
    break;

    case MUIA_BetterString_SelectOnActive:
    {
      if((data->SelectOnActive == TRUE && isFlagClear(data->Flags, FLG_ForceSelectOff)) ||
         isFlagSet(data->Flags, FLG_ForceSelectOn))
      {
         ti_Data = TRUE;
      }
      else
         ti_Data = FALSE;
    }
    break;

    case MUIA_Version:
      ti_Data = LIB_VERSION;
    break;

    case MUIA_Revision:
      ti_Data = LIB_REVISION;
    break;

    default:
      return DoSuperMethodA(cl, obj, (Msg)msg);
    break;
  }

  *msg->opg_Storage = ti_Data;

  return TRUE;
}