Ejemplo n.º 1
0
/***********************************************************************
 *
 *  Procedure:
 *	HandleMapRequest - MapRequest event handler
 *
 ************************************************************************/
void HandleMapRequest()
{
  DBUG("HandleMapRequest","Routine Entered");

  HandleMapRequestKeepRaised(None);
}
Ejemplo n.º 2
0
/*
 * Copy a symlink.  This only happens if we're in "no derefence" mode,
 * in which we copy the links rather than the files that are pointed at.
 *
 * We always discard the destination file.  If it's a symlink already,
 * we want to throw it out and replace it.  If it's not a symlink, we
 * need to trash it so we can create one.
 */
static int copySymlink(const char* src, const char* dst, const struct stat* pSrcStat, unsigned int options)
{
    struct stat dstStat;
    char linkBuf[PATH_MAX+1];
    int statResult, nameLen;

    assert(options & COPY_NO_DEREFERENCE);
    DBUG(("--- copying symlink '%s' to '%s'\n", src, dst));

    /* NOTE: we use lstat() here */
    statResult = lstat(dst, &dstStat);
    if (statResult == 0 && !S_ISREG(dstStat.st_mode)
                         && !S_ISLNK(dstStat.st_mode)
						 )
    {
        fprintf(stderr,
            "acp: destination '%s' exists and is not regular or symlink\n",
            dst);
        return -1;
    }

    if (statResult == 0) {
        if (isSameFile(pSrcStat, &dstStat)) {
            fprintf(stderr, "acp: '%s' and '%s' are the same file\n",
                src, dst);
            return -1;
        }
        if (options & COPY_UPDATE_ONLY) {
            if (!isSourceNewer(pSrcStat, &dstStat)) {
                DBUG(("---  source is not newer: '%s'\n", src));
                printNotNewerMsg(src, dst, options);
                return 0;
            }
        }
    }

    /* extract the symlink contents */
    nameLen = readlink(src, linkBuf, sizeof(linkBuf)-1);
    if (nameLen <= 0) {
        fprintf(stderr, "acp: unable to read symlink '%s': %s\n",
            src, strerror(errno));
        return -1;
    }
    linkBuf[nameLen] = '\0';
    DBUG(("--- creating symlink file '%s' (--> %s)\n", dst, linkBuf));

    if (statResult == 0) {
        DBUG(("---  removing '%s'\n", dst));
        if (unlink(dst) != 0) {
            fprintf(stderr, "acp: unable to remove '%s': %s\n",
                dst, strerror(errno));
            return -1;
        }
    }

    if (symlink(linkBuf, dst) != 0) {
        fprintf(stderr, "acp: unable to create symlink '%s' [%s]: %s\n",
            dst, linkBuf, strerror(errno));
        return -1;
    }

    /*
     * There's no way to set the file date or access permissions, but
     * it is possible to set the owner.
     */
    if (options & COPY_PERMISSIONS) {
        if (lchown(dst, pSrcStat->st_uid, pSrcStat->st_gid) != 0)
            DBUG(("---  lchown failed: %s\n", strerror(errno)));
    }

    printCopyMsg(src, dst, options);

    return 0;
}
Ejemplo n.º 3
0
/*
 * Do the actual copy.  This is called recursively from copyDirectory().
 *
 * "dst" should only be a directory if "src" is also a directory.
 *
 * Returns 0 on success.
 */
static int copyFileRecursive(const char* src, const char* dst, bool isCmdLine, unsigned int options)
{
    char* srcExe = NULL;
    char* dstExe = NULL;
    char* dstDir = NULL;
    struct stat srcStat;
    int retVal = 0;
    int statResult, statErrno;

    /*
     * Stat the source file.  If it doesn't exist, fail.
     */
    if (options & COPY_NO_DEREFERENCE)
        statResult = lstat(src, &srcStat);
    else
        statResult = stat(src, &srcStat);
    statErrno = errno;        /* preserve across .exe attempt */

#ifdef WIN32_EXE
    /*
     * Here's the interesting part.  Under Cygwin, if you have a file
     * called "foo.exe", stat("foo", ...) will succeed, but open("foo", ...)
     * will fail.  We need to figure out what its name is supposed to be
     * so we can create the correct destination file.
     *
     * If we don't have the "-e" flag set, we want "acp foo bar" to fail,
     * not automatically find "foo.exe".  That way, if we really were
     * trying to copy "foo", it doesn't grab something we don't want.
     */
    if (isCmdLine && statResult == 0) {
        int tmpFd;
        tmpFd = open(src, O_RDONLY | O_BINARY, 0);
        if (tmpFd < 0) {
            statResult = -1;
            statErrno = ENOENT;
        } else {
            (void) close(tmpFd);
        }
    }

    /*
     * If we didn't find the file, try it again with ".exe".
     */
    if (isCmdLine && statResult < 0 && statErrno == ENOENT && (options & COPY_TRY_EXE)) {
        srcExe = malloc(strlen(src) + 4 +1);
        strcpy(srcExe, src);
        strcat(srcExe, ".exe");

        if (options & COPY_NO_DEREFERENCE)
            statResult = lstat(srcExe, &srcStat);
        else
            statResult = stat(srcExe, &srcStat);

        if (statResult == 0 && !S_ISREG(srcStat.st_mode))
            statResult = -1;        /* fail, use original statErrno below */

        if (statResult == 0) {
            /* found a .exe, copy that instead */
            dstExe = malloc(strlen(dst) + 4 +1);
            strcpy(dstExe, dst);
            strcat(dstExe, ".exe");

            src = srcExe;
            dst = dstExe;
        } else {
            DBUG(("---  couldn't find '%s' either\n", srcExe));
        }
    }
#endif
    if (statResult < 0) {
        if (statErrno == ENOENT)
            fprintf(stderr, "acp: file '%s' does not exist\n", src);
        else
            fprintf(stderr, "acp: unable to stat '%s': %s\n",
                src, strerror(statErrno));
        retVal = -1;
        goto bail;
    }

    /*
     * If "src" is a directory, ignore it if "recursive" isn't set.
     *
     * We want to create "dst" as a directory (or verify that it already
     * exists as a directory), and then copy its contents.
     */
    if (S_ISDIR(srcStat.st_mode)) {
        if (!(options & COPY_RECURSIVE)) {
            fprintf(stderr, "acp: omitting directory '%s'\n", src);
        } else {
            retVal = copyDirectory(src, dst, &srcStat, options);
        }
#ifdef HAVE_SYMLINKS
    } else if (S_ISLNK(srcStat.st_mode)) {
        retVal = copySymlink(src, dst, &srcStat, options);
#endif		
    } else if (S_ISREG(srcStat.st_mode)) {
        retVal = copyRegular(src, dst, &srcStat, options);
    } else {
        fprintf(stderr, "acp: skipping unusual file '%s' (mode=0%o)\n",
            src, srcStat.st_mode);
        retVal = -1;
    }

bail:
    free(srcExe);
    free(dstExe);
    free(dstDir);
    return retVal;
}
Ejemplo n.º 4
0
static void
add_weight(fz_weights *weights, int j, int i, fz_scale_filter *filter,
	float x, float F, float G, int src_w, float dst_w)
{
	float dist = j - x + 0.5f - ((i + 0.5f)*dst_w/src_w);
	float f;
	int min, len, index, weight;

	dist *= G;
	if (dist < 0)
		dist = -dist;
	f = filter->fn(filter, dist)*F;
	weight = (int)(256*f+0.5f);

	/* Ensure i is in range */
	if (i < 0)
	{
		i = 0;
		return;
	}
	else if (i >= src_w)
	{
		i = src_w-1;
		return;
	}
	if (weight == 0)
	{
		/* We add a fudge factor here to allow for extreme downscales
		 * where all the weights round to 0. Ensure that at least one
		 * (arbitrarily the first one) is non zero. */
		if (weights->new_line && f > 0)
			weight = 1;
		else
			return;
	}

	DBUG(("add_weight[%d][%d] = %d(%g) dist=%g\n",j,i,weight,f,dist));

	/* Move j from patch_l...patch_l+patch_w range to 0..patch_w range */
	j -= weights->patch_l;
	if (weights->new_line)
	{
		/* New line */
		weights->new_line = 0;
		index = weights->index[j]; /* row pointer */
		weights->index[index] = i; /* min */
		weights->index[index+1] = 0; /* len */
	}
	index = weights->index[j];
	min = weights->index[index++];
	len = weights->index[index++];
	while (i < min)
	{
		/* This only happens in rare cases, but we need to insert
		 * one earlier. In exceedingly rare cases we may need to
		 * insert more than one earlier. */
		int k;

		for (k = len; k > 0; k--)
		{
			weights->index[index+k] = weights->index[index+k-1];
		}
		weights->index[index] = 0;
		min--;
		len++;
		weights->index[index-2] = min;
		weights->index[index-1] = len;
	}
	if (i-min >= len)
	{
		/* The usual case */
		while (i-min >= ++len)
		{
			weights->index[index+len-1] = 0;
		}
		assert(len-1 == i-min);
		weights->index[index+i-min] = weight;
		weights->index[index-1] = len;
		assert(len <= weights->max_len);
	}
	else
	{
		/* Infrequent case */
		weights->index[index+i-min] += weight;
	}
}
std::unique_ptr<TwoPhaseFlowWithPrhoMaterialProperties>
createTwoPhaseFlowPrhoMaterialProperties(
    BaseLib::ConfigTree const& config,
    boost::optional<MeshLib::PropertyVector<int> const&> material_ids,
    std::vector<std::unique_ptr<ParameterBase>> const& parameters)
{
    DBUG("Reading material properties of two-phase flow process.");

    //! \ogs_file_param{prj__processes__process__TWOPHASE_FLOW_PRHO__material_property__fluid}
    auto const& fluid_config = config.getConfigSubtree("fluid");

    // Get fluid properties
    //! \ogs_file_param{prj__processes__process__TWOPHASE_FLOW_PRHO__material_property__liquid_density}
    auto const& rho_conf = fluid_config.getConfigSubtree("liquid_density");
    auto _liquid_density =
        MaterialLib::Fluid::createFluidDensityModel(rho_conf);
    //! \ogs_file_param{prj__processes__process__TWOPHASE_FLOW_PRHO__material_property__gas_density}
    auto const& rho_gas_conf = fluid_config.getConfigSubtree("gas_density");
    auto _gas_density =
        MaterialLib::Fluid::createFluidDensityModel(rho_gas_conf);
    //! \ogs_file_param{prj__processes__process__TWOPHASE_FLOW_PRHO__material_property__liquid_viscosity}
    auto const& mu_conf = fluid_config.getConfigSubtree("liquid_viscosity");
    auto _viscosity = MaterialLib::Fluid::createViscosityModel(mu_conf);
    //! \ogs_file_param{prj__processes__process__TWOPHASE_FLOW_PRHO__material_property__gas_viscosity}
    auto const& mu_gas_conf = fluid_config.getConfigSubtree("gas_viscosity");
    auto _gas_viscosity = MaterialLib::Fluid::createViscosityModel(mu_gas_conf);

    // Get porous properties
    std::vector<int> mat_ids;
    std::vector<int> mat_krel_ids;
    std::vector<std::unique_ptr<MaterialLib::PorousMedium::Permeability>>
        _intrinsic_permeability_models;
    std::vector<std::unique_ptr<MaterialLib::PorousMedium::Porosity>>
        _porosity_models;
    std::vector<std::unique_ptr<MaterialLib::PorousMedium::Storage>>
        _storage_models;
    std::vector<
        std::unique_ptr<MaterialLib::PorousMedium::CapillaryPressureSaturation>>
        _capillary_pressure_models;
    std::vector<
        std::unique_ptr<MaterialLib::PorousMedium::RelativePermeability>>
        _relative_permeability_models;

    //! \ogs_file_param{prj__processes__process__TWOPHASE_FLOW_PRHO__material_property__porous_medium}
    auto const& poro_config = config.getConfigSubtree("porous_medium");
    //! \ogs_file_param{prj__processes__process__TWOPHASE_FLOW_PRHO__material_property__porous_medium__porous_medium}
    for (auto const& conf : poro_config.getConfigSubtreeList("porous_medium"))
    {
        //! \ogs_file_attr{prj__processes__process__TWOPHASE_FLOW_PRHO__material_property__porous_medium__porous_medium__id}
        auto const id = conf.getConfigAttributeOptional<int>("id");
        mat_ids.push_back(*id);

        //! \ogs_file_param{prj__processes__process__TWOPHASE_FLOW_PRHO__material_property__porous_medium__porous_medium__permeability}
        auto const& permeability_conf = conf.getConfigSubtree("permeability");
        _intrinsic_permeability_models.emplace_back(
            MaterialLib::PorousMedium::createPermeabilityModel(
                permeability_conf, parameters));

        //! \ogs_file_param{prj__processes__process__TWOPHASE_FLOW_PRHO__material_property__porous_medium__porous_medium__porosity}
        auto const& porosity_conf = conf.getConfigSubtree("porosity");
        auto n = MaterialLib::PorousMedium::createPorosityModel(porosity_conf,
                                                                parameters);
        _porosity_models.emplace_back(std::move(n));

        //! \ogs_file_param{prj__processes__process__TWOPHASE_FLOW_PRHO__material_property__porous_medium__porous_medium__storage}
        auto const& storage_conf = conf.getConfigSubtree("storage");
        auto beta = MaterialLib::PorousMedium::createStorageModel(storage_conf);
        _storage_models.emplace_back(std::move(beta));

        auto const& capillary_pressure_conf =
            //! \ogs_file_param{prj__processes__process__TWOPHASE_FLOW_PRHO__material_property__porous_medium__porous_medium__capillary_pressure}
            conf.getConfigSubtree("capillary_pressure");
        auto pc = MaterialLib::PorousMedium::createCapillaryPressureModel(
            capillary_pressure_conf);
        _capillary_pressure_models.emplace_back(std::move(pc));

        auto const& krel_config =
            //! \ogs_file_param{prj__processes__process__TWOPHASE_FLOW_PRHO__material_property__porous_medium__porous_medium__relative_permeability}
            conf.getConfigSubtree("relative_permeability");
        for (
            auto const& krel_conf :
            //! \ogs_file_param{prj__processes__process__TWOPHASE_FLOW_PRHO__material_property__porous_medium__porous_medium__relative_permeability__relative_permeability}
            krel_config.getConfigSubtreeList("relative_permeability"))
        {
            auto const krel_id =
                //! \ogs_file_attr{prj__processes__process__TWOPHASE_FLOW_PRHO__material_property__porous_medium__porous_medium__relative_permeability__relative_permeability__id}
                krel_conf.getConfigAttributeOptional<int>("id");
            mat_krel_ids.push_back(*krel_id);
            auto krel_n =
                MaterialLib::PorousMedium::createRelativePermeabilityModel(
                    krel_conf);
            _relative_permeability_models.emplace_back(std::move(krel_n));
        }
        BaseLib::reorderVector(_relative_permeability_models, mat_krel_ids);
    }

    BaseLib::reorderVector(_intrinsic_permeability_models, mat_ids);
    BaseLib::reorderVector(_porosity_models, mat_ids);
    BaseLib::reorderVector(_storage_models, mat_ids);

    return std::make_unique<TwoPhaseFlowWithPrhoMaterialProperties>(
        material_ids, std::move(_liquid_density), std::move(_viscosity),
        std::move(_gas_density), std::move(_gas_viscosity),
        std::move(_intrinsic_permeability_models), std::move(_porosity_models),
        std::move(_storage_models), std::move(_capillary_pressure_models),
        std::move(_relative_permeability_models));
}
Ejemplo n.º 6
0
void TESProcess::initializeConcreteProcess(
    NumLib::LocalToGlobalIndexMap const& dof_table,
    MeshLib::Mesh const& mesh, unsigned const integration_order)
{
    DBUG("Create global assembler.");
    _global_assembler.reset(new GlobalAssembler(dof_table));

    ProcessLib::createLocalAssemblers<TESLocalAssembler>(
        mesh.getDimension(), mesh.getElements(), dof_table, integration_order,
        _local_assemblers, _assembly_params);

    // TODO move the two data members somewhere else.
    // for extrapolation of secondary variables
    std::vector<std::unique_ptr<MeshLib::MeshSubsets>>
        all_mesh_subsets_single_component;
    all_mesh_subsets_single_component.emplace_back(
        new MeshLib::MeshSubsets(this->_mesh_subset_all_nodes.get()));
    _local_to_global_index_map_single_component.reset(
        new NumLib::LocalToGlobalIndexMap(
            std::move(all_mesh_subsets_single_component),
            // by location order is needed for output
            NumLib::ComponentOrder::BY_LOCATION));

    {
        auto const& l = *_local_to_global_index_map_single_component;
        _extrapolator.reset(new ExtrapolatorImplementation(
            MathLib::MatrixSpecifications(l.dofSizeWithoutGhosts(),
                                          l.dofSizeWithoutGhosts(),
                                          &l.getGhostIndices(),
                                          nullptr),
            l));
    }

    // secondary variables
    auto add2nd = [&](std::string const& var_name, unsigned const n_components,
                      SecondaryVariableFunctions&& fcts) {
        this->_secondary_variables.addSecondaryVariable(var_name, n_components,
                                                        std::move(fcts));
    };
    auto makeEx =
        [&](TESIntPtVariables var) -> SecondaryVariableFunctions {
        return ProcessLib::makeExtrapolator(var, *_extrapolator,
                                            _local_assemblers);
    };

    add2nd("solid_density", 1, makeEx(TESIntPtVariables::SOLID_DENSITY));
    add2nd("reaction_rate", 1, makeEx(TESIntPtVariables::REACTION_RATE));
    add2nd("velocity_x", 1, makeEx(TESIntPtVariables::VELOCITY_X));
    if (mesh.getDimension() >= 2)
        add2nd("velocity_y", 1, makeEx(TESIntPtVariables::VELOCITY_Y));
    if (mesh.getDimension() >= 3)
        add2nd("velocity_z", 1, makeEx(TESIntPtVariables::VELOCITY_Z));

    add2nd("loading", 1, makeEx(TESIntPtVariables::LOADING));
    add2nd("reaction_damping_factor", 1,
           makeEx(TESIntPtVariables::REACTION_DAMPING_FACTOR));

    namespace PH = std::placeholders;
    using Self = TESProcess;

    add2nd("vapour_partial_pressure", 1,
           {std::bind(&Self::computeVapourPartialPressure, this, PH::_1, PH::_2,
                      PH::_3),
            nullptr});
    add2nd("relative_humidity", 1, {std::bind(&Self::computeRelativeHumidity,
                                              this, PH::_1, PH::_2, PH::_3),
                                    nullptr});
    add2nd("equilibrium_loading", 1,
           {std::bind(&Self::computeEquilibriumLoading, this, PH::_1, PH::_2,
                      PH::_3),
            nullptr});
}
Ejemplo n.º 7
0
/************************************************************************************
** Extract capabilities info from each device.
*/
static BOOL CALLBACK Pa_EnumProc(LPGUID lpGUID,
                                 LPCTSTR lpszDesc,
                                 LPCTSTR lpszDrvName,
                                 LPVOID lpContext )
{
    HRESULT    hr;
    LPDIRECTSOUND          lpDirectSound;
#if SUPPORT_AUDIO_CAPTURE
    LPDIRECTSOUNDCAPTURE   lpDirectSoundCapture;
#endif /* SUPPORT_AUDIO_CAPTURE */
    int        isInput  = (int) lpContext;  /* Passed from Pa_CountDevices() */
    internalPortAudioDevice *pad;

    if( sDeviceIndex >= sNumDevices )
    {
        sEnumerationError = paInternalError;
        return FALSE;
    }
    pad = &sDevices[sDeviceIndex];
    /* Copy GUID to static array. Set pointer. */
    if( lpGUID == NULL )
    {
        pad->pad_lpGUID = NULL;
    }
    else
    {
        memcpy( &pad->pad_GUID, lpGUID, sizeof(GUID) );
        pad->pad_lpGUID = &pad->pad_GUID;
    }
    pad->pad_Info.sampleRates = pad->pad_SampleRates;  /* Point to array. */
    /* Allocate room for descriptive name. */
    if( lpszDesc != NULL )
    {
        int len = strlen(lpszDesc);
        pad->pad_Info.name = (char *)malloc( len+1 );
        if( pad->pad_Info.name == NULL )
        {
            sEnumerationError = paInsufficientMemory;
            return FALSE;
        }
        memcpy( (void *) pad->pad_Info.name, lpszDesc, len+1 );
    }
#if SUPPORT_AUDIO_CAPTURE
    if( isInput )
    {
        /********** Input ******************************/
        DSCCAPS     caps;
        if( lpGUID == NULL ) sDefaultInputDeviceID = sDeviceIndex;
        hr = DirectSoundCaptureCreate(  lpGUID, &lpDirectSoundCapture,   NULL );
        if( hr != DS_OK )
        {
            pad->pad_Info.maxInputChannels = 0;
            DBUG(("Cannot create Capture for %s. Result = 0x%x\n", lpszDesc, hr ));
        }
        else
        {
            /* Query device characteristics. */
            caps.dwSize = sizeof(caps);
            IDirectSoundCapture_GetCaps( lpDirectSoundCapture, &caps );
            /* printf("caps.dwFormats = 0x%x\n", caps.dwFormats ); */
            pad->pad_Info.maxInputChannels = caps.dwChannels;
            /* Determine sample rates from flags. */
            if( caps.dwChannels == 2 )
            {
                int index = 0;
                if( caps.dwFormats & WAVE_FORMAT_1S16) pad->pad_SampleRates[index++] = 11025.0;
                if( caps.dwFormats & WAVE_FORMAT_2S16) pad->pad_SampleRates[index++] = 22050.0;
                if( caps.dwFormats & WAVE_FORMAT_4S16) pad->pad_SampleRates[index++] = 44100.0;
                pad->pad_Info.numSampleRates = index;
            }
            else if( caps.dwChannels == 1 )
            {
                int index = 0;
                if( caps.dwFormats & WAVE_FORMAT_1M16) pad->pad_SampleRates[index++] = 11025.0;
                if( caps.dwFormats & WAVE_FORMAT_2M16) pad->pad_SampleRates[index++] = 22050.0;
                if( caps.dwFormats & WAVE_FORMAT_4M16) pad->pad_SampleRates[index++] = 44100.0;
                pad->pad_Info.numSampleRates = index;
            }
            else pad->pad_Info.numSampleRates = 0;
            IDirectSoundCapture_Release( lpDirectSoundCapture );
        }
    }
    else
#endif /* SUPPORT_AUDIO_CAPTURE */

    {
        /********** Output ******************************/
        DSCAPS     caps;
        if( lpGUID == NULL ) sDefaultOutputDeviceID = sDeviceIndex;
        /* Create interfaces for each object. */
        hr = DirectSoundCreate(  lpGUID, &lpDirectSound,   NULL );
        if( hr != DS_OK )
        {
            pad->pad_Info.maxOutputChannels = 0;
            DBUG(("Cannot create dsound for %s. Result = 0x%x\n", lpszDesc, hr ));
        }
        else
        {
            /* Query device characteristics. */
            caps.dwSize = sizeof(caps);
            IDirectSound_GetCaps( lpDirectSound, &caps );
            pad->pad_Info.maxOutputChannels = ( caps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1;
            /* Get sample rates. */
            pad->pad_SampleRates[0] = (double) caps.dwMinSecondarySampleRate;
            pad->pad_SampleRates[1] = (double) caps.dwMaxSecondarySampleRate;
            if( caps.dwFlags & DSCAPS_CONTINUOUSRATE ) pad->pad_Info.numSampleRates = -1;
            else if( caps.dwMinSecondarySampleRate == caps.dwMaxSecondarySampleRate )
            {
                if( caps.dwMinSecondarySampleRate == 0 )
                {
                    /*
                    ** On my Thinkpad 380Z, DirectSoundV6 returns min-max=0 !!
                    ** But it supports continuous sampling.
                    ** So fake range of rates, and hope it really supports it.
                    */
                    pad->pad_SampleRates[0] = 11025.0f;
                    pad->pad_SampleRates[1] = 48000.0f;
                    pad->pad_Info.numSampleRates = -1; /* continuous range */

                    DBUG(("PA - Reported rates both zero. Setting to fake values for device #%d\n", sDeviceIndex ));
                }
                else
                {
                    pad->pad_Info.numSampleRates = 1;
                }
            }
            else if( (caps.dwMinSecondarySampleRate < 1000.0) && (caps.dwMaxSecondarySampleRate > 50000.0) )
            {
                /* The EWS88MT drivers lie, lie, lie. The say they only support two rates, 100 & 100000.
                ** But we know that they really support a range of rates!
                ** So when we see a ridiculous set of rates, assume it is a range.
                */
                pad->pad_Info.numSampleRates = -1;
                DBUG(("PA - Sample rate range used instead of two odd values for device #%d\n", sDeviceIndex ));
            }
            else pad->pad_Info.numSampleRates = 2;
            IDirectSound_Release( lpDirectSound );
        }
    }
    pad->pad_Info.nativeSampleFormats = paInt16;
    sDeviceIndex++;
    return( TRUE );
}
Ejemplo n.º 8
0
/*********************************************************************
 * Try to open the named device.
 * If it opens, try to set various rates and formats and fill in
 * the device info structure.
 */
PaError Pa_QueryDevice( const char *deviceName, internalPortAudioDevice *pad )
{
    int result = paHostError;
    int tempDevHandle;
    int numChannels, maxNumChannels;
    int numSampleRates;
    int sampleRate;
    int numRatesToTry;
    int ratesToTry[9] = {96000, 48000, 44100, 32000, 24000, 22050, 16000, 11025, 8000};
    int i;
    audio_info_t solaris_info;
    audio_device_t device_info;

    /* douglas:
     we have to do this querying in a slightly different order. apparently
     some sound cards will give you different info based on their settins.
     e.g. a card might give you stereo at 22kHz but only mono at 44kHz.
     the correct order for OSS is: format, channels, sample rate

    */
	/*
	 to check a device for it's capabilities, it's probably better to use the
	 equivalent "-ctl"-descriptor - MR
	*/
    char devname[strlen(deviceName) + 4];
    snprintf(devname,(strlen(deviceName) + 4),"%sctl",deviceName);

    if ((tempDevHandle = open(devname, O_WRONLY|O_NONBLOCK))  == -1 )
    {
        DBUG(("Pa_QueryDevice: could not open %s\n", deviceName ));
        return paHostError;
    }

    /*  Ask OSS what formats are supported by the hardware. */
    pad->pad_Info.nativeSampleFormats = 0;
    AUDIO_INITINFO(&solaris_info);

    /* SAM 12/31/01: Sparc native does mulaw, alaw and PCM.
       I think PCM is signed. */

    for (i = 8; i <= 32; i += 8) {
      solaris_info.play.precision = i;
      solaris_info.play.encoding = AUDIO_ENCODING_LINEAR;
      /* If there are no errors, add the format. */
      if (ioctl(tempDevHandle, AUDIO_SETINFO, &solaris_info) > -1) {
	switch (i) {
	case 8:
	  pad->pad_Info.nativeSampleFormats |= paInt8;
	  break;
	case 16:
	  pad->pad_Info.nativeSampleFormats |= paInt16;
	  break;
	case 24:
	  pad->pad_Info.nativeSampleFormats |= paInt24;
	  break;
	case 32:
	  pad->pad_Info.nativeSampleFormats |= paInt32;
	  break;
	}
      }
    }

    maxNumChannels = 0;
    for( numChannels = 1; numChannels <= 16; numChannels++ )
      {
	int temp = numChannels;
	DBUG(("Pa_QueryDevice: use SNDCTL_DSP_CHANNELS, numChannels = %d\n", numChannels ))
	  AUDIO_INITINFO(&solaris_info);
	solaris_info.play.channels = temp;
	if (ioctl(tempDevHandle, AUDIO_SETINFO, &solaris_info) < 0)
	  {
	    /* ioctl() failed so bail out if we already have stereo */
	    if( numChannels > 2 ) break;
	  }
	else
	  {
	    /* ioctl() worked but bail out if it does not support numChannels.
	     * We don't want to leave gaps in the numChannels supported.
	     */
	    if( (numChannels > 2) && (temp != numChannels) ) break;
	    DBUG(("Pa_QueryDevice: temp = %d\n", temp ))
	      if( temp > maxNumChannels ) maxNumChannels = temp; /* Save maximum. */
	  }
      }

    pad->pad_Info.maxOutputChannels = maxNumChannels;
    DBUG(("Pa_QueryDevice: maxNumChannels = %d\n", maxNumChannels))

    /* FIXME - for now, assume maxInputChannels = maxOutputChannels.
     *    Eventually do separate queries for O_WRONLY and O_RDONLY
    */
    pad->pad_Info.maxInputChannels = pad->pad_Info.maxOutputChannels;

    DBUG(("Pa_QueryDevice: maxInputChannels = %d\n",
          pad->pad_Info.maxInputChannels))


    /* Determine available sample rates by trying each one and seeing result.
     */
    numSampleRates = 0;

    AUDIO_INITINFO(&solaris_info);

    numRatesToTry = sizeof(ratesToTry)/sizeof(int);
    for (i = 0; i < numRatesToTry; i++)
    {
        sampleRate = ratesToTry[i];

	solaris_info.play.sample_rate = sampleRate; /* AS: We opened for Write, so set play */
        if (ioctl(tempDevHandle, AUDIO_SETINFO, &solaris_info) >= 0 ) /* PLB20010817 */
        {
            if (sampleRate == ratesToTry[i])
            {
                DBUG(("Pa_QueryDevice: got sample rate: %d\n", sampleRate))
                pad->pad_SampleRates[numSampleRates] = (float)ratesToTry[i];
                numSampleRates++;
            }
        }
    }

    DBUG(("Pa_QueryDevice: final numSampleRates = %d\n", numSampleRates))
    if (numSampleRates==0)   /* HP20010922 */
    {
        ERR_RPT(("Pa_QueryDevice: no supported sample rate (or SNDCTL_DSP_SPEED ioctl call failed).\n" ));
        goto error;
    }

    pad->pad_Info.numSampleRates = numSampleRates;
    pad->pad_Info.sampleRates = pad->pad_SampleRates;

    /* query for the device name instead of using the filesystem-device - MR */
	if (ioctl(tempDevHandle, AUDIO_GETDEV, &device_info) == -1) {
      pad->pad_Info.name = deviceName;
    } else {
      char *pt = (char *)PaHost_AllocateFastMemory(strlen(device_info.name));
      strcpy(pt, device_info.name);
      pad->pad_Info.name = pt;
    }

    result = paNoError;

error:
    /* We MUST close the handle here or we won't be able to reopen it later!!!  */
    close(tempDevHandle);

    return result;
}
Ejemplo n.º 9
0
void PythonBoundaryCondition::getEssentialBCValues(
    const double t, GlobalVector const& x,
    NumLib::IndexValueVector<GlobalIndexType>& bc_values) const
{
    FlushStdoutGuard guard(_flush_stdout);
    (void)guard;

    auto const nodes = _bc_data.boundary_mesh.getNodes();

    auto const& bulk_node_ids_map =
        *_bc_data.boundary_mesh.getProperties().getPropertyVector<std::size_t>(
            "bulk_node_ids");

    bc_values.ids.clear();
    bc_values.values.clear();

    bc_values.ids.reserve(_bc_data.boundary_mesh.getNumberOfNodes());
    bc_values.values.reserve(_bc_data.boundary_mesh.getNumberOfNodes());

    std::vector<double> primary_variables;

    for (auto const* node : _bc_data.boundary_mesh.getNodes())
    {
        auto const boundary_node_id = node->getID();
        auto const bulk_node_id = bulk_node_ids_map[boundary_node_id];

        // gather primary variable values
        primary_variables.clear();
        auto const num_var = _dof_table_boundary->getNumberOfVariables();
        for (int var = 0; var < num_var; ++var)
        {
            auto const num_comp =
                _dof_table_boundary->getNumberOfVariableComponents(var);
            for (int comp = 0; comp < num_comp; ++comp)
            {
                MeshLib::Location loc{_bc_data.bulk_mesh_id,
                                      MeshLib::MeshItemType::Node,
                                      bulk_node_id};
                auto const dof_idx =
                    _bc_data.dof_table_bulk.getGlobalIndex(loc, var, comp);

                if (dof_idx == NumLib::MeshComponentMap::nop)
                {
                    // TODO extend Python BC to mixed FEM ansatz functions
                    OGS_FATAL(
                        "No d.o.f. found for (node=%d, var=%d, comp=%d).  "
                        "That might be due to the use of mixed FEM ansatz "
                        "functions, which is currently not supported by "
                        "the implementation of Python BCs. That excludes, "
                        "e.g., the HM process.",
                        bulk_node_id, var, comp);
                }

                primary_variables.push_back(x[dof_idx]);
            }
        }

        auto* xs = nodes[boundary_node_id]->getCoords();  // TODO DDC problems?
        auto pair_flag_value = _bc_data.bc_object->getDirichletBCValue(
            t, {xs[0], xs[1], xs[2]}, boundary_node_id, primary_variables);
        if (!_bc_data.bc_object->isOverriddenEssential())
        {
            DBUG(
                "Method `getDirichletBCValue' not overridden in Python "
                "script.");
            return;
        }

        if (!pair_flag_value.first)
            continue;

        MeshLib::Location l(_bc_data.bulk_mesh_id, MeshLib::MeshItemType::Node,
                            bulk_node_id);
        const auto dof_idx = _bc_data.dof_table_bulk.getGlobalIndex(
            l, _bc_data.global_component_id);
        if (dof_idx == NumLib::MeshComponentMap::nop)
            OGS_FATAL(
                "Logic error. This error should already have occured while "
                "gathering primary variables. Something nasty is going on!");

        // For the DDC approach (e.g. with PETSc option), the negative
        // index of g_idx means that the entry by that index is a ghost
        // one, which should be dropped. Especially for PETSc routines
        // MatZeroRows and MatZeroRowsColumns, which are called to apply
        // the Dirichlet BC, the negative index is not accepted like
        // other matrix or vector PETSc routines. Therefore, the
        // following if-condition is applied.
        if (dof_idx >= 0)
        {
            bc_values.ids.emplace_back(dof_idx);
            bc_values.values.emplace_back(pair_flag_value.second);
        }
    }
}
Ejemplo n.º 10
0
void VRPN_CALLBACK SpaceNavigatorClient::_handleAnalogs(void*, vrpn_ANALOGCB analogData)
{
    // read data from the analog axes
    // range [0, 1]
    // set some values to 0 due to mode

    // normal mode (translation and rotation)
    if(_spacenavigator->_mode == TRANSROT)
    {
        if(_spacenavigator->_dominating)
        {
            double max = analogData.channel[0];
            int index = 0;
            for(int i = 1; i < 6; i++)
                if(abs(analogData.channel[i]) > abs(max))
                {
                    index = i;
                    max = analogData.channel[i];
                }
            _spacenavigator->x = _spacenavigator->y = _spacenavigator->z =
                                     _spacenavigator->rx =
                                         _spacenavigator->
                                         ry = _spacenavigator->rz = 0;
            switch(index)
            {
            case 0:
                _spacenavigator->x = max  * _spacenavigator->_invertAxes[0];
                break;
            case 2:
                _spacenavigator->y = max  * _spacenavigator->_invertAxes[1];
                break;
            case 1:
                _spacenavigator->z = max  * _spacenavigator->_invertAxes[2];
                break;
            case 3:
                _spacenavigator->rx = max  * _spacenavigator->_invertAxes[3];
                break;
            case 5:
                _spacenavigator->ry = max  * _spacenavigator->_invertAxes[4];
                break;
            case 4:
                _spacenavigator->rz = max  * _spacenavigator->_invertAxes[5];
                break;
            }
        }
        else
        {
            _spacenavigator->x = analogData.channel[0] *
                                 _spacenavigator->_invertAxes[0];
            _spacenavigator->y = analogData.channel[2] *
                                 _spacenavigator->_invertAxes[1];
            _spacenavigator->z = analogData.channel[1] *
                                 _spacenavigator->_invertAxes[2];
            _spacenavigator->rx = analogData.channel[3] *
                                  _spacenavigator->_invertAxes[3];
            _spacenavigator->ry = analogData.channel[5] *
                                  _spacenavigator->_invertAxes[4];
            _spacenavigator->rz = analogData.channel[4] *
                                  _spacenavigator->_invertAxes[5];
        }
    }

    // translation only mode
    else if(_spacenavigator->_mode == TRANS)
    {
        if(_spacenavigator->_dominating)
        {
            double max = analogData.channel[0];
            int index = 0;
            for(int i = 1; i < 3; i++)
                if(abs(analogData.channel[i]) > abs(max))
                {
                    index = i;
                    max = analogData.channel[i];
                }
            _spacenavigator->x = _spacenavigator->y = _spacenavigator->z =
                                     _spacenavigator->rx =
                                         _spacenavigator->
                                         ry = _spacenavigator->rz = 0;
            switch(index)
            {
            case 0:
                _spacenavigator->x = max  * _spacenavigator->_invertAxes[0];
                break;
            case 2:
                _spacenavigator->y = max  * _spacenavigator->_invertAxes[1];
                break;
            case 1:
                _spacenavigator->z = max  * _spacenavigator->_invertAxes[2];
                break;
            }
        }
        else
        {
            _spacenavigator->x = analogData.channel[0] *
                                 _spacenavigator->_invertAxes[0];
            _spacenavigator->y = analogData.channel[2] *
                                 _spacenavigator->_invertAxes[1];
            _spacenavigator->z = analogData.channel[1] *
                                 _spacenavigator->_invertAxes[2];
            _spacenavigator->rx = _spacenavigator->ry = _spacenavigator->rz = 0;
        }
    }

    // rotation only mode
    else if(_spacenavigator->_mode == ROT)
    {
        if(_spacenavigator->_dominating)
        {
            double max = analogData.channel[3];
            int index = 3;
            for(int i = 4; i < 6; i++)
                if(abs(analogData.channel[i]) > abs(max))
                {
                    index = i;
                    max = analogData.channel[i];
                }
            _spacenavigator->x = _spacenavigator->y = _spacenavigator->z =
                                     _spacenavigator->rx =
                                         _spacenavigator->
                                         ry = _spacenavigator->rz = 0;
            switch(index)
            {
            case 3:
                _spacenavigator->rx = max  * _spacenavigator->_invertAxes[3];
                break;
            case 5:
                _spacenavigator->ry = max  * _spacenavigator->_invertAxes[4];
                break;
            case 4:
                _spacenavigator->rz = max  * _spacenavigator->_invertAxes[5];
                break;
            }
        }
        else
        {
            _spacenavigator->rx = analogData.channel[3] *
                                  _spacenavigator->_invertAxes[3];
            _spacenavigator->ry = analogData.channel[5] *
                                  _spacenavigator->_invertAxes[4];
            _spacenavigator->rz = analogData.channel[4] *
                                  _spacenavigator->_invertAxes[5];
            _spacenavigator->x = _spacenavigator->y = _spacenavigator->z = 0;
        }
    }

    // swap axes if the z-axis is the up axis
    if(_spacenavigator->_upAxis == Z)
    {
        double temp = _spacenavigator->y;
        _spacenavigator->y = _spacenavigator->z;
        _spacenavigator->z = temp;

        temp = _spacenavigator->ry;
        _spacenavigator->ry = _spacenavigator->rz;
        _spacenavigator->rz = temp;
    }

    _spacenavigator->_unconsumedData = true;

#ifdef SPACENAVIGATOR_DEBUG_OUTPUT
    DBUG("Translation: { %f, %f, %f }", _spacenavigator->x, _spacenavigator->y, _spacenavigator->z);
    DBUG("Rotation: { %f, %f, %f }", _spacenavigator->rx, _spacenavigator->ry, _spacenavigator->rz);
#endif     // SPACENAVIGATOR_DEBUG_OUTPUT
}
Ejemplo n.º 11
0
void *thrKVdata(void *Tptr) {
	_adapt_::adaptThreadSQ *aTsqptr;
	void *ptr;
	aMsg *aM;
	int ret, ret2, i;
	int rcount = 0;
	aMsgType aMtype;
	int datasize;
	KVdata *KVdataptr;
	char *keyptr, *valptr;
	char tmpbuf2[8];
	int totalsize;
	int y;
	struct timespec ts;
	int size;
	int tot, count, newcount, start;

	if (sigignore(SIGPIPE) == -1) {
		perror("failed to ignore SIGPIPE; sigaction");
		exit(1);
	}

	aTsqptr = (_adapt_::adaptThreadSQ *) Tptr;
	Thread_SetAffinity(aTsqptr->threadIndex % 2);

	ALERT(
			ALOG_INFO, "KVDATA:Start:threadId(%p)sharedQ(%p)Type(%d)Q(%p)", aTsqptr->threadId, aTsqptr->aTSQptr, aTsqptr->type, aTsqptr->aTSQptr->Q);

	while (true) {

		aM = (aMsg *) aTsqptr->aTSQptr->aTSQgetMsg();
		DBUG((ALOG_TMSG|ALOG_KVDATA|ALOG_ALERT),
				"KVdata:GetMsg(%p)Type:%d", aM, aM->type);
		assert( aM->type == KVDATA);

		// DBUG(ALOG_DALL, "KVdata:fd:%d ctype:%d key:%s keylen:%d hashval:%u", aM->aC->cSockFd,aM->ctype,aM->key,aM->keylen,aM->hashval);

		// DBUG(ALOG_DALL, "KVdata:fd:%d ctype:%d key:%s ", aM->aC->cSockFd,aM->ctype,aM->key);

		switch (aM->ctype) {

		case ACACHED_CMD_SET:

			datasize = sizeof(KVdata) + aM->HdrIN.aMsgHdrIN.keylen + aM->IN.KVdataSet.vallen + 2;
			ptr = malloc(datasize);
			memset(ptr, 0x0, datasize);
			INFO(ALOG_MEM, "KVDATA:SET:MALLOC:%p", ptr);
			KVdataptr = (KVdata *) ptr;
			DBUG((ALOG_KVDATA|ALOG_ALERT),
					"KVDATA:SET:sizeofkvdata:%d keylen:%d datalen:%d +2 total:%d ptr(%p)data(%p)", sizeof(KVdata), aM->HdrIN.aMsgHdrIN.keylen, aM->IN.KVdataSet.vallen, datasize, ptr, &(KVdataptr->data));

			KVdataptr->keylen = aM->HdrIN.aMsgHdrIN.keylen;
			KVdataptr->vallen = aM->IN.KVdataSet.vallen;

			keyptr = (char *) &(KVdataptr->data);
			valptr = keyptr + KVdataptr->keylen;
			memcpy(keyptr, aM->HdrIN.aMsgHdrIN.key, KVdataptr->keylen);
			DBUG((ALOG_KVDATA|ALOG_MEM),
					"KVDATA:SET:FREE:Bodyptr:%p", aM->HdrIN.cmdptr);
			memcpy(valptr, aM->HdrIN.cmdptr, KVdataptr->vallen);
			// free cmdptr here
			free(aM->HdrIN.cmdptr);
			aM->HdrIN.cmdptr = NULL;

			//hexdump((char *)ptr,datasize,"KVDATA:SET:STORE",0);
			ret = SGAptr->ahashtableptr->set(aM->HdrIN.aMsgHdrIN.hashval,
					KVdataptr);
			//ALERT(ALOG_ALERT, "INDEX is %d\n",ACONN_IOVREPLYINDEX(aM->aC) );

			//pthread_spin_lock(&(aM->aC->spinlock));
			ret2 = atomicIncrGetAdd(&(ACONN_IOVREPLYINDEX(aM->aC)));
			strncpy(tmpbuf2, "STORED\r\n", 8);
			size = aM->aC->AddIOVReply(tmpbuf2, 8, true, ret2);
			ret2++;
			//y = __sync_val_compare_and_swap(&(aM->aC->windexlast), 0, 0) ;

			ret = aM->aC->WriteAllOnceIMM(0, 1);

			//pthread_spin_unlock(&(aM->aC->spinlock));

			if (ret != 8)
				ALERT(
						ALOG_ALERT, "KVDATA:SET:WriteData:writing STORED...fd:%d expecting return:8 got:%d errno:%d", aM->aC->cSockFd, ret, errno);

			if (!__sync_bool_compare_and_swap(&(aM->aC->Busy), 1, 0)) {
				ALERT(
						ALOG_ALERT, "KVDATA:SET:!!!:CONN(%p)NOT ABLE TO SWAP CONN BUSY val:%d", aM->aC, __sync_val_compare_and_swap(&(aM->aC->Busy), 99, 99));
			}

			aM->aC->windexlast = 0;
			aM->aC->totalsize = 0;
			aM->aC->iovReply.iovIndex = 0;
			aM->aC->replyCount = 0;
			aM->aC->writingflag = 0;

			if (aM->aC->PendingCmdQ->empty() == false) {
				aM->aC->CheckPendingCmdQ();
			}

			//sched_yield();

			rcount = aM->aC->Revoke();
			DBUG(ALOG_KVDATA,
					"KVDATA:CMD_SET:rcount:%d set add ret:%d ", rcount, ret);
			aMtype = SUCCESS;
			//post to client port
			aM->Init(aMtype, aM->aC, aM->ctype);
			//DBUG((ALOG_TMSG|ALOG_KVDATA),"KVdata:SET:Post Client(%p)type(%d)ctype(%d)",aM,aM->type, aM->ctype);
			//SGAptr->aTSQGClient->aTSQputMsg(aM) ; //post msg to Client SQ
			SGAptr->aMsgRelease(aM);
			DBUG(ALOG_INTERNAL,
					"CLIENT:MSG:Released(%p)FreeQ size(%d)BusyQ size(%d)", aM, SGAptr->aFBSQGaMsg->FreeQ->Q->size(), SGAptr->aFBSQGaMsg->BusyQ->Q->size());

			break;

		case ACACHED_CMD_GETS:

			ret = SGAptr->ahashtableptr->get(&(aM->HdrIN.aMsgHdrIN));
			if (ret < 0) {
				aM->aC->aerrtype = AERR_TYPE_APP_GETS;
				ALERT(
						(ALOG_TERR|ALOG_ALERT), "GET COMMAND KEY:%s len:%d NOT FOUND", aM->HdrIN.aMsgHdrIN.key, aM->HdrIN.aMsgHdrIN.keylen);
				snprintf(aM->OUT.ErrBuf, MAX_ERRBUF_LEN - 1,
						"CLIENT_ERROR NOT FOUND \r\n");
				rcount = aM->aC->Revoke();
				//aMtype = ERROR ;
				fprintf(stderr, "NOT FOUND!!!!\n");
				//atomicIncrAddGet(&(aM->aC->replyCount)) ;

			} else {
				KVdataptr = aM->HdrIN.aMsgHdrIN.KVdataptr;
				aM->aC->QReply(KVdataptr, aM->HdrIN.aMsgHdrIN.key);
				rcount = aM->aC->Revoke();
				//atomicIncrAddGet(&(aM->aC->replyCount)) ;

				DBUG(ALOG_TCONC, "KVDATA:conn revoke rcount:%d", rcount);
				DBUG(ALOG_KVDATA,
						"KVDATA:connection pending:%d reqcount:%d", aM->aC->IsconcPending(), aM->aC->reqCount);
			}
			atomicIncrAddGet(&(aM->aC->replyCount));

			if (!aM->aC->IsconcPending()) {

				// check if request == reply
				if ((ret = __sync_val_compare_and_swap(&(aM->aC->replyCount),
						aM->aC->reqCount, 0)) == aM->aC->reqCount) {
					DBUG(ALOG_KVDATA,
							"KVDATA:Replycount SWAP SUCESSFULL ret:%d", ret);
					aM->aC->reqCount = 0;

					ret2 = atomicIncrGetAdd(&(ACONN_IOVREPLYINDEX(aM->aC)));
					strncpy(tmpbuf2, "END\r\n", 5);
					size = aM->aC->AddIOVReply(tmpbuf2, 5, true, ret2);
					totalsize = __sync_add_and_fetch(&(aM->aC->totalsize),
							size);

					DBUG(ALOG_MEM, "KVDATA:aC(%p)index:%d", aM->aC, ret2);
					ret2++;
					// reset  here , as after recieving data, client will send next req
					ACONN_IOVREPLYINDEX(aM->aC) = 0;

					//ret = aM->aC->WriteAll(ret2);
					y = __sync_val_compare_and_swap(&(aM->aC->windexlast), 0,
							0);
					// z = __sync_val_compare_and_swap(&(aM->aC->writingflag), 110, 110) ;

					while (__sync_val_compare_and_swap(&(aM->aC->writingflag),
							111, 111)) {
						ALERT(
								ALOG_ALERT, "KVDATA:ALERT:WriteALL:Writing Flag is SET");
						sched_yield();
						ts.tv_sec = 0;
						ts.tv_nsec = 100000;
						nanosleep(&ts, NULL);
					}

					while (true) {
						for (i = y; i < ret2; i++) {
							if (ISSET_AC_IOVREPLY_DESC(aM->aC,i,AC_IOVREPLY_DESC_WRITTEN)== false ) {
								//newindex = i;
								ALERT((ALOG_TCONN|ALOG_TCONC), "KVDATA(%p)ALERT>>>not iov_written index:%d", aM->aC,i);
								break;
							}
						}
						if ( i == ret2) break;
						ALERT(ALOG_ALERT, "KVDATA:ALERT:Waiting for all desc writes");
						//sched_yield();
						ts.tv_sec = 1;
						ts.tv_nsec = 1000;
						nanosleep (&ts, NULL);

					}

					DBUG((ALOG_TCONN|ALOG_TCONC),
							"KVDATA:CONN(%p)WriteALLonce:before totalsize:%d windex:%d ", aM->aC, totalsize, y);
					aM->aC->writingflag = 0;

					//  int aConn::WriteIOVReply(int start, int count)

					count = ret2 - y;
					start = y;
					tot = 0;
					do {
						if (count > IOV_MAX) {
							newcount = IOV_MAX;
							count = count - IOV_MAX;
						} else {
							newcount = count;
						}
						ret = aM->aC->WriteAllOnce(start, newcount);
						tot = tot + ret;
						start = start + newcount;
						DBUG(ALOG_INFO,
								"KVDATA:WriteAllOnce:A:Expecting:%d Got:%d errno:%d", totalsize, tot, errno);

					} while (ret > 0 && newcount >= IOV_MAX);

					if (tot != totalsize) {
						ALERT(
								ALOG_INFO, "KVDATA:WriteAllOnce:TOTALSIZE FINAL:%d Expecting:%d Got:%d errno:%d", __sync_val_compare_and_swap(&(aM->aC->totalsize),0,0), totalsize, tot, errno);
					}
					//ret = aM->aC->WriteIOVReply(y, ret2-y,true);

					totalsize = __sync_val_compare_and_swap(
							&(aM->aC->totalsize), 0, 0);
					DBUG(ALOG_ALERT,
							"KVDATA:conn(%p)FINAL totalsize:%d", aM->aC, totalsize);

					aM->aC->windexlast = 0;
					aM->aC->totalsize = 0;
					aM->aC->iovReply.iovIndex = 0;
					aM->aC->replyCount = 0;
					aM->aC->writingflag = 0;

					for (i = 0; i < ret2; i++) {
						if (ISSET_AC_IOVREPLY_DESC(aM->aC,i,AC_IOVREPLY_DESC_MALLOC)) {
							DBUG(ALOG_MEM,"free:%p i:%d",aM->aC->iovReply.iovec[i].iov_base,i);
							//free(aM->aC->iovReply.iovec[i].iov_base);
							//free(ACONN_IOVREPLY_IOVECBASE2(aM->aC,i));
						}
						ACONN_IOVREPLY_IOVECBASE(aM->aC,i)= NULL;
						ACONN_IOVREPLY_IOVECBASE2(aM->aC,i)= NULL;
						ACONN_IOVREPLY_IOVECLEN(aM->aC,i)= 0;
						ACONN_IOVREPLY_BASEOFFSET(aM->aC,i)= 0;
						ACONN_IOVREPLY_ALLOCSIZE(aM->aC,i)= 0;
						//ACONN_IOVREQ_DESC(aM->aC,i).reset();
						ACONN_IOVREPLY_DESC(aM->aC,i).reset();

					}

					DBUG(ALOG_TCONC,
							"KVDATA:conn revoke bef END/r/n rcount:%d totalsize:%d ret:%d iovcount:%d "
							"reqCount:%d replyCount:%d", rcount, aM->aC->totalsize, ret, ret2, aM->aC->reqCount, aM->aC->replyCount);
					//ret = aM->aC->WriteData("END\r\n",5);
					//printf("return from write data:%d", ret);
					//	SGAptr->aSQGFreebusySQ->aSQprintall("Check freebusy rcount",PrintGFreebusySQ);

					atomicSet(&(aM->aC->conWatchSent));

					if (!__sync_bool_compare_and_swap(&(aM->aC->Busy), 1, 0)) {
						ALERT(
								ALOG_ALERT, "KVDATA:GETS:!!!:CONN(%p)NOT ABLE TO SWAP CONN BUSY val:%d ptr(%p)", aM->aC, __sync_val_compare_and_swap(&(aM->aC->Busy), 99, 99), &(aM->aC->Busy));
					}
					//aM->aC->Post2KVdataTSQ(NULL);
					if (aM->aC->PendingCmdQ->empty() == false) {
						aM->aC->CheckPendingCmdQ();
					}

				} else {
					DBUG(ALOG_KVDATA, "KVDATA:SWAP NOT SUCESSFULL ret:%d", ret);

				}

				//DBUG(ALOG_DALL, "KVDATA:CMD_GET:rcount:%d write returned:%d expecting:%d buf:%s", rcount,ret,);
			}

			aMtype = SUCCESS;
			//post to client port
			aM->Init(aMtype, aM->aC, aM->ctype);
			//INFO(ALOG_TMSG,"KVdata:GETS:Post Client(%p)type(%d)ctype(%d)",aM,aM->type, aM->ctype);
			//SGAptr->aTSQGClient->aTSQputMsg(aM) ; //post msg to Client SQ
			SGAptr->aMsgRelease(aM);
			DBUG(ALOG_INTERNAL,
					"CLIENT:MSG:Released(%p)FreeQ size(%d)BusyQ size(%d)", aM, SGAptr->aFBSQGaMsg->FreeQ->Q->size(), SGAptr->aFBSQGaMsg->BusyQ->Q->size());

			break;

		default:
			DBUG(ALOG_DALL, "ERROR::KVdata:::INVALID CMD:%d", aM->ctype);
			break;
		}

	}
	// thread never returns
	//pthread_exit((void*) t);
	return NULL;
}
Ejemplo n.º 12
0
int aConn::Post2KVdataTSQ(void *ptr) {
	int KVdatathrindex;
	int bucket;
	aMsg *aM = (aMsg *) ptr;
	aMsg *aM1;

	//DBUG(ALOG_TCONN, "CONN(%p)BUSY val:%d BEFORE  QUEING MSG(%p)",this,__sync_val_compare_and_swap(&(this->Busy), 9999,9999),aM);

	if (__sync_bool_compare_and_swap(&(this->Busy), 0, 1)) {

		DBUG(ALOG_TCONN,
				"CONN(%p)Post2KVDATA:BUSY SET TO 1 val:%d ptr(%p) ", this, __sync_val_compare_and_swap(&(this->Busy), 99,99), &(this->Busy));
		// check if pending messages on aC
		aM1 = (aMsg *) this->PendingCmdQ->aSQget();
		if (aM1) {
			DBUG(ALOG_TCONN, "CONN(%p)got PendingCmdQ msg(%p)", this, aM1);
			if (ptr) {
				this->PendingCmdQ->aSQput(aM);
			}
			aM = aM1;
		}

		if (aM) {
			if (aM->aC->cmd.ctype == ACACHED_CMD_GETS) {
				this->Post2KVdataGets(aM);
			} else if (aM->aC->cmd.ctype == ACACHED_CMD_QUIT) {
				closeConnection(aM->aC->cSockFd, aM->aC->commRead_wptr);
				if (!__sync_bool_compare_and_swap(&(this->Busy), 1, 0)) {
					ALERT(
							ALOG_ALERT, "CONN(%p)CMD:QUIT NOT ABLE TO SWAP CONN BUSY val:%d", this, __sync_val_compare_and_swap(&(this->Busy), 99, 99));
				}
				SGAptr->aMsgRelease(aM);
			} else {

				// cmd will be SET
				bucket = aM->HdrIN.aMsgHdrIN.hashval & SGAptr->hashmask;
				if (bucket <= SGAptr->hashsize / SGAptr->numCores) {
					KVdatathrindex = 0;
				} else {
					KVdatathrindex = 1;
				}

				DBUG(ALOG_ALERT, "KV index:%d", KVdatathrindex);
				//printf("posting to kvdata val:%d\n",__sync_val_compare_and_swap(&(this->Busy), 99,99) );
				SGAptr->aTSQGKVdata[KVdatathrindex]->aTSQputMsg(aM);
			}

		} else {
			if (!__sync_bool_compare_and_swap(&(this->Busy), 1, 0)) {
				ALERT(
						ALOG_ALERT, "CONN(%p)NOT ABLE TO SWAP CONN BUSY val:%d", this, __sync_val_compare_and_swap(&(this->Busy), 99, 99));
			}

		}

	} else {
		DBUG(ALOG_TCONN,
				"CONN(%p)BUSY val:%d QUEING MSG(%p)CMD:%d", this, __sync_val_compare_and_swap(&(this->Busy), 99,99), aM, aM->aC->cmd.ctype);
		//queue to connection list
		this->PendingCmdQ->aSQput(aM);
		DBUG(ALOG_TCONN,
				"CONN(%p)BUSY val:%d AFTER QUEING MSG(%p)", this, __sync_val_compare_and_swap(&(this->Busy), 99,99), aM);

	}

	return 0;
}
Ejemplo n.º 13
0
/***********************************************************************
 *
 *  Procedure:
 *	HandleUnmapNotify - UnmapNotify event handler
 *
 ************************************************************************/
void HandleUnmapNotify()
{
  int dstx, dsty;
  Window dumwin;
  XEvent dummy;
  extern FvwmWindow *colormap_win;
  int    weMustUnmap;

  DBUG("HandleUnmapNotify","Routine Entered");

  /*
   * Don't ignore events as described below.
   */
  if((Event.xunmap.event != Event.xunmap.window) &&
     (Event.xunmap.event != Scr.Root || !Event.xunmap.send_event))
    {
      return;
    }

  /*
   * The July 27, 1988 ICCCM spec states that a client wishing to switch
   * to WithdrawnState should send a synthetic UnmapNotify with the
   * event field set to (pseudo-)root, in case the window is already
   * unmapped (which is the case for fvwm for IconicState).  Unfortunately,
   * we looked for the FvwmContext using that field, so try the window
   * field also.
   */
  weMustUnmap = 0;
  if (!Tmp_win)
    {
      Event.xany.window = Event.xunmap.window;
      weMustUnmap = 1;
      if (XFindContext(dpy, Event.xany.window,
		       FvwmContext, (caddr_t *)&Tmp_win) == XCNOENT)
	Tmp_win = NULL;
    }

  if(!Tmp_win)
    return;

  if(weMustUnmap)
    XUnmapWindow(dpy, Event.xunmap.window);

  if(Tmp_win ==  Scr.Hilite)
    Scr.Hilite = NULL;

  if(Scr.PreviousFocus == Tmp_win)
    Scr.PreviousFocus = NULL;

  if((Tmp_win == Scr.Focus)&&(Tmp_win->flags & ClickToFocus))
    {
      if(Tmp_win->next)
	{
	  HandleHardFocus(Tmp_win->next);
	}
      else
	SetFocus(Scr.NoFocusWin,NULL,1);
    }

  if(Scr.Focus == Tmp_win)
    SetFocus(Scr.NoFocusWin,NULL,1);

  if(Tmp_win == Scr.pushed_window)
    Scr.pushed_window = NULL;

  if(Tmp_win == colormap_win)
    colormap_win = NULL;

  if ((!(Tmp_win->flags & MAPPED)&&!(Tmp_win->flags&ICONIFIED)))
    {
      return;
    }

  MyXGrabServer(dpy);

  if(XCheckTypedWindowEvent (dpy, Event.xunmap.window, DestroyNotify,&dummy))
    {
      Destroy(Tmp_win);
      MyXUngrabServer (dpy);
      return;
    }

  /*
   * The program may have unmapped the client window, from either
   * NormalState or IconicState.  Handle the transition to WithdrawnState.
   *
   * We need to reparent the window back to the root (so that fvwm exiting
   * won't cause it to get mapped) and then throw away all state (pretend
   * that we've received a DestroyNotify).
   */
  if (XTranslateCoordinates (dpy, Event.xunmap.window, Scr.Root,
			     0, 0, &dstx, &dsty, &dumwin))
    {
      XEvent ev;
      Bool reparented;

      reparented = XCheckTypedWindowEvent (dpy, Event.xunmap.window,
					   ReparentNotify, &ev);
      SetMapStateProp (Tmp_win, WithdrawnState);
      if (reparented)
	{
	  if (Tmp_win->old_bw)
	    XSetWindowBorderWidth (dpy, Event.xunmap.window, Tmp_win->old_bw);
	  if((!(Tmp_win->flags & SUPPRESSICON))&&
	     (Tmp_win->wmhints && (Tmp_win->wmhints->flags & IconWindowHint)))
	    XUnmapWindow (dpy, Tmp_win->wmhints->icon_window);
	}
      else
	{
	  RestoreWithdrawnLocation (Tmp_win,False);
	}
      XRemoveFromSaveSet (dpy, Event.xunmap.window);
      XSelectInput (dpy, Event.xunmap.window, NoEventMask);
      Destroy(Tmp_win);		/* do not need to mash event before */
      /*
       * Flush any pending events for the window.
       */
      /* Bzzt! it could be about to re-map */
/*      while(XCheckWindowEvent(dpy, Event.xunmap.window,
			      StructureNotifyMask | PropertyChangeMask |
			      ColormapChangeMask | VisibilityChangeMask |
			      EnterWindowMask | LeaveWindowMask, &dummy));
      */
    } /* else window no longer exists and we'll get a destroy notify */
  MyXUngrabServer(dpy);

  XFlush (dpy);
}
Ejemplo n.º 14
0
/***********************************************************************
 *
 *  Procedure:
 *	HandleMapNotify - MapNotify event handler
 *
 ***********************************************************************/
void HandleMapNotify()
{
  Boolean       OnThisPage    =  False;

  DBUG("HandleMapNotify","Routine Entered");

  if (!Tmp_win)
    {
      if((Event.xmap.override_redirect == True)&&
	 (Event.xmap.window != Scr.NoFocusWin))
	{
	  XSelectInput(dpy,Event.xmap.window,FocusChangeMask);
	  Scr.UnknownWinFocused = Event.xmap.window;
	}
      return;
    }

  /* Except for identifying over-ride redirect window mappings, we
   * don't need or want windows associated with the sunstructurenotifymask */
  if(Event.xmap.event != Event.xmap.window)
    return;

  /*
      Make sure at least part of window is on this page
      before giving it focus...
  */
  if ( (Tmp_win->Desk == Scr.CurrentDesk) &&
       ( ((Tmp_win->frame_x + Tmp_win->frame_width) >= 0 &&
          Tmp_win->frame_x < Scr.MyDisplayWidth) &&
         ((Tmp_win->frame_y + Tmp_win->frame_height) >= 0 &&
          Tmp_win->frame_y < Scr.MyDisplayHeight)
       )
     )
    {
      OnThisPage  =  True;
    }

  /*
   * Need to do the grab to avoid race condition of having server send
   * MapNotify to client before the frame gets mapped; this is bad because
   * the client would think that the window has a chance of being viewable
   * when it really isn't.
   */
  MyXGrabServer (dpy);
  if (Tmp_win->icon_w)
    XUnmapWindow(dpy, Tmp_win->icon_w);
  if(Tmp_win->icon_pixmap_w != None)
    XUnmapWindow(dpy, Tmp_win->icon_pixmap_w);
  XMapSubwindows(dpy, Tmp_win->frame);

  if(Tmp_win->Desk == Scr.CurrentDesk)
    {
      XMapWindow(dpy, Tmp_win->frame);
    }

  if(Tmp_win->flags & ICONIFIED)
    BroadcastPacket(M_DEICONIFY, 3,
                    Tmp_win->w, Tmp_win->frame, (unsigned long)Tmp_win);
  else
    BroadcastPacket(M_MAP, 3,
                    Tmp_win->w,Tmp_win->frame, (unsigned long)Tmp_win);

  if((Tmp_win->flags & ClickToFocus)&&
     ((!Scr.Focus)||(Scr.Focus->flags & ClickToFocus)))
    {
      if (OnThisPage)
        {
          SetFocus(Tmp_win->w,Tmp_win,1);
        }
    }
  if((!(Tmp_win->flags &(BORDER|TITLE)))&&(Tmp_win->boundary_width <2))
    {
      SetBorder(Tmp_win,False,True,True,Tmp_win->frame);
    }
  XSync(dpy,0);
  MyXUngrabServer (dpy);
  XFlush (dpy);
  Tmp_win->flags |= MAPPED;
  Tmp_win->flags &= ~MAP_PENDING;
  Tmp_win->flags &= ~ICONIFIED;
  Tmp_win->flags &= ~ICON_UNMAPPED;
  KeepOnTop();
}
Ejemplo n.º 15
0
ProcessVariable::ProcessVariable(
    BaseLib::ConfigTree const& config,
    MeshLib::Mesh& mesh,
    std::vector<std::unique_ptr<MeshLib::Mesh>> const& meshes,
    std::vector<std::unique_ptr<ParameterBase>> const& parameters)
    :  //! \ogs_file_param{prj__process_variables__process_variable__name}
      _name(config.getConfigParameter<std::string>("name")),
      _mesh(mesh),
      //! \ogs_file_param{prj__process_variables__process_variable__components}
      _n_components(config.getConfigParameter<int>("components")),
      //! \ogs_file_param{prj__process_variables__process_variable__order}
      _shapefunction_order(config.getConfigParameter<unsigned>("order")),
      _initial_condition(findParameter<double>(
          //! \ogs_file_param{prj__process_variables__process_variable__initial_condition}
          config.getConfigParameter<std::string>("initial_condition"),
          parameters, _n_components))
{
    DBUG("Constructing process variable %s", _name.c_str());

    if (_shapefunction_order < 1 || 2 < _shapefunction_order)
        OGS_FATAL("The given shape function order %d is not supported", _shapefunction_order);

    // Boundary conditions
    //! \ogs_file_param{prj__process_variables__process_variable__boundary_conditions}
    if (auto bcs_config = config.getConfigSubtreeOptional("boundary_conditions"))
    {
        for (auto bc_config :
             //! \ogs_file_param{prj__process_variables__process_variable__boundary_conditions__boundary_condition}
             bcs_config->getConfigSubtreeList("boundary_condition"))
        {
            auto const& mesh = findMeshInConfig(bc_config, meshes);
            auto component_id =
                //! \ogs_file_param{prj__process_variables__process_variable__boundary_conditions__boundary_condition__component}
                bc_config.getConfigParameterOptional<int>("component");

            if (!component_id && _n_components == 1)
                // default value for single component vars.
                component_id = 0;

            _bc_configs.emplace_back(std::move(bc_config), mesh, component_id);
        }
    } else {
        INFO("No boundary conditions found.");
    }

    // Source terms
    //! \ogs_file_param{prj__process_variables__process_variable__source_terms}
    if (auto sts_config = config.getConfigSubtreeOptional("source_terms"))
    {
        for (auto st_config :
             //! \ogs_file_param{prj__process_variables__process_variable__source_terms__source_term}
             sts_config->getConfigSubtreeList("source_term"))
        {
            MeshLib::Mesh const& mesh = findMeshInConfig(st_config, meshes);
            auto component_id =
                //! \ogs_file_param{prj__process_variables__process_variable__source_terms__source_term__component}
                st_config.getConfigParameterOptional<int>("component");

            if (!component_id && _n_components == 1)
                // default value for single component vars.
                component_id = 0;

            _source_term_configs.emplace_back(std::move(st_config), mesh,
                                              component_id);
        }
    } else {
        INFO("No source terms found.");
    }
}
Ejemplo n.º 16
0
/*
 * Extract all of the records from the archive, pulling out and displaying
 * comment threads.
 *
 * The "bulk extract" call doesn't deal with comments.  Since we want to
 * show them while we're extracting the files, we have to manually find
 * and extract them.
 */
static NuError ExtractAllRecords(NulibState* pState, NuArchive* pArchive)
{
    NuError err;
    const NuRecord* pRecord;
    const NuThread* pThread;
    NuRecordIdx recordIdx;
    NuAttr numRecords;
    int idx, threadIdx;

    DBUG(("--- doing manual extract\n"));
    Assert(NState_GetCommand(pState) == kCommandExtract);   /* no "-p" here */

    err = NuGetAttr(pArchive, kNuAttrNumRecords, &numRecords);
    for (idx = 0; idx < (int) numRecords; idx++) {
        err = NuGetRecordIdxByPosition(pArchive, idx, &recordIdx);
        if (err != kNuErrNone) {
            fprintf(stderr, "ERROR: couldn't get record #%d (err=%d)\n",
                idx, err);
            goto bail;
        }

        err = NuGetRecord(pArchive, recordIdx, &pRecord);
        if (err != kNuErrNone) {
            fprintf(stderr, "ERROR: unable to get recordIdx %u\n", recordIdx);
            goto bail;
        }

        /* do we want to extract this record? */
        if (!IsSpecified(pState, pRecord))
            continue;
        NState_IncMatchCount(pState);

        /*
         * Look for a comment thread.
         */
        for (threadIdx = 0; (uint32_t)threadIdx < pRecord->recTotalThreads;
            threadIdx++)
        {
            pThread = NuGetThread(pRecord, threadIdx);
            Assert(pThread != NULL);

            if (NuGetThreadID(pThread) == kNuThreadIDComment &&
                pThread->actualThreadEOF > 0)
            {
                UNICHAR* filenameUNI = CopyMORToUNI(pRecord->filenameMOR);
                printf("----- '%s':\n", filenameUNI);
                free(filenameUNI);
                err = NuExtractThread(pArchive, pThread->threadIdx,
                        NState_GetCommentSink(pState));
                if (err != kNuErrNone) {
                    printf("[comment extraction failed, continuing\n");
                } else {
                    printf("\n-----\n");
                }
            }
        }

        /* extract the record, using the usual mechanisms */
        err = NuExtractRecord(pArchive, recordIdx);
        if (err != kNuErrNone)
            goto bail;
    }

bail:
    return err;
}
std::unique_ptr<LiquidFlowMaterialProperties>
createLiquidFlowMaterialProperties(
    BaseLib::ConfigTree const& config,
    std::vector<std::unique_ptr<ParameterBase>> const& parameters,
    bool const has_material_ids,
    MeshLib::PropertyVector<int> const& material_ids)
{
    DBUG("Reading material properties of liquid flow process.");

    //! \ogs_file_param{prj__processes__process__LIQUID_FLOW__material_property__fluid}
    auto const& fluid_config = config.getConfigSubtree("fluid");
    auto fluid_properties =
        MaterialLib::Fluid::createFluidProperties(fluid_config);

    // Get porous properties
    std::vector<std::unique_ptr<MaterialLib::PorousMedium::Permeability>>
        intrinsic_permeability_models;
    std::vector<std::unique_ptr<MaterialLib::PorousMedium::Porosity>>
        porosity_models;
    std::vector<std::unique_ptr<MaterialLib::PorousMedium::Storage>>
        storage_models;

    std::vector<int> mat_ids;
    auto const& porous_medium_configs =
        //! \ogs_file_param{prj__processes__process__LIQUID_FLOW__material_property__porous_medium}
        config.getConfigSubtree("porous_medium");
    for (
        auto const& porous_medium_config :
        //! \ogs_file_param{prj__processes__process__LIQUID_FLOW__material_property__porous_medium__porous_medium}
        porous_medium_configs.getConfigSubtreeList("porous_medium"))
    {
        //! \ogs_file_attr{prj__processes__process__LIQUID_FLOW__material_property__porous_medium__porous_medium__id}
        auto const id = porous_medium_config.getConfigAttribute<int>("id");
        mat_ids.push_back(id);

        auto const& permeability_config =
            //! \ogs_file_param{prj__processes__process__LIQUID_FLOW__material_property__porous_medium__porous_medium__permeability}
            porous_medium_config.getConfigSubtree("permeability");
        intrinsic_permeability_models.emplace_back(
            MaterialLib::PorousMedium::createPermeabilityModel(
                permeability_config, parameters));

        auto const& porosity_config =
            //! \ogs_file_param{prj__processes__process__LIQUID_FLOW__material_property__porous_medium__porous_medium__porosity}
            porous_medium_config.getConfigSubtree("porosity");
        auto n = MaterialLib::PorousMedium::createPorosityModel(porosity_config,
                                                                parameters);
        porosity_models.emplace_back(std::move(n));

        auto const& storage_config =
            //! \ogs_file_param{prj__processes__process__LIQUID_FLOW__material_property__porous_medium__porous_medium__storage}
            porous_medium_config.getConfigSubtree("storage");
        auto beta =
            MaterialLib::PorousMedium::createStorageModel(storage_config);
        storage_models.emplace_back(std::move(beta));
    }

    BaseLib::reorderVector(intrinsic_permeability_models, mat_ids);
    BaseLib::reorderVector(porosity_models, mat_ids);
    BaseLib::reorderVector(storage_models, mat_ids);

    return std::make_unique<LiquidFlowMaterialProperties>(
        std::move(fluid_properties), std::move(intrinsic_permeability_models),
        std::move(porosity_models), std::move(storage_models), has_material_ids,
        material_ids);
}
/* sets the value of the given property and waits for the change to 
   be acknowledged, and returns the final value, which is not guaranteed
   by this function to be the same as the desired value. Obviously, this
   function can only be used for data whose input and output are the
   same size and format, and their size and format are known in advance.*/
PaError AudioDeviceSetPropertyNowAndWaitForChange(
    AudioDeviceID inDevice,
    UInt32 inChannel, 
    Boolean isInput, 
    AudioDevicePropertyID inPropertyID,
    UInt32 inPropertyDataSize, 
    const void *inPropertyData,
    void *outPropertyData )
{
   OSStatus macErr;
   int unixErr;
   MutexAndBool mab;
   UInt32 outPropertyDataSize = inPropertyDataSize;

   /* First, see if it already has that value. If so, return. */
   macErr = AudioDeviceGetProperty( inDevice, inChannel,
                                 isInput, inPropertyID, 
                                 &outPropertyDataSize, outPropertyData );
   if( macErr )
      goto failMac2;
   if( inPropertyDataSize!=outPropertyDataSize )
      return paInternalError;
   if( 0==memcmp( outPropertyData, inPropertyData, outPropertyDataSize ) )
      return paNoError;

   /* setup and lock mutex */
   mab.once = FALSE;
   unixErr = pthread_mutex_init( &mab.mutex, NULL );
   if( unixErr )
      goto failUnix2;
   unixErr = pthread_mutex_lock( &mab.mutex );
   if( unixErr )
      goto failUnix;

   /* add property listener */
   macErr = AudioDeviceAddPropertyListener( inDevice, inChannel, isInput,
                                   inPropertyID, propertyProc,
                                   &mab ); 
   if( macErr )
      goto failMac;
   /* set property */
   macErr  = AudioDeviceSetProperty( inDevice, NULL, inChannel,
                                 isInput, inPropertyID,
                                 inPropertyDataSize, inPropertyData );
   if( macErr ) {
      /* we couldn't set the property, so we'll just unlock the mutex
         and move on. */
      pthread_mutex_unlock( &mab.mutex );
   }

   /* wait for property to change */                      
   unixErr = pthread_mutex_lock( &mab.mutex );
   if( unixErr )
      goto failUnix;

   /* now read the property back out */
   macErr = AudioDeviceGetProperty( inDevice, inChannel,
                                 isInput, inPropertyID, 
                                 &outPropertyDataSize, outPropertyData );
   if( macErr )
      goto failMac;
   /* cleanup */
   AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput,
                                      inPropertyID, propertyProc );
   unixErr = pthread_mutex_unlock( &mab.mutex );
   if( unixErr )
      goto failUnix2;
   unixErr = pthread_mutex_destroy( &mab.mutex );
   if( unixErr )
      goto failUnix2;

   return paNoError;

 failUnix:
   pthread_mutex_destroy( &mab.mutex );
   AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput,
                                      inPropertyID, propertyProc );

 failUnix2:
   DBUG( ("Error #%d while setting a device property: %s\n", unixErr, strerror( unixErr ) ) );
   return paUnanticipatedHostError;

 failMac:
   pthread_mutex_destroy( &mab.mutex );
   AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput,
                                      inPropertyID, propertyProc );
 failMac2:
   return ERR( macErr );
}
Ejemplo n.º 19
0
TESProcess::TESProcess(
    MeshLib::Mesh& mesh,
    Process::NonlinearSolver& nonlinear_solver,
    std::unique_ptr<Process::TimeDiscretization>&&
        time_discretization,
    std::vector<std::reference_wrapper<ProcessVariable>>&& process_variables,
    SecondaryVariableCollection&& secondary_variables,
    ProcessOutput&& process_output,
    const BaseLib::ConfigTree& config)
    : Process(
          mesh, nonlinear_solver, std::move(time_discretization),
          std::move(process_variables), std::move(secondary_variables),
          std::move(process_output))
{
    DBUG("Create TESProcess.");

    // physical parameters for local assembly
    {
        std::vector<std::pair<std::string, double*>> params{
            {"fluid_specific_heat_source",
             &_assembly_params.fluid_specific_heat_source},
            {"fluid_specific_isobaric_heat_capacity", &_assembly_params.cpG},
            {"solid_specific_heat_source",
             &_assembly_params.solid_specific_heat_source},
            {"solid_heat_conductivity", &_assembly_params.solid_heat_cond},
            {"solid_specific_isobaric_heat_capacity", &_assembly_params.cpS},
            {"tortuosity", &_assembly_params.tortuosity},
            {"diffusion_coefficient",
             &_assembly_params.diffusion_coefficient_component},
            {"porosity", &_assembly_params.poro},
            {"solid_density_dry", &_assembly_params.rho_SR_dry},
            {"solid_density_initial", &_assembly_params.initial_solid_density}};

        for (auto const& p : params)
        {
            if (auto const par = config.getConfigParameterOptional<double>(p.first))
            {
                DBUG("setting parameter `%s' to value `%g'", p.first.c_str(),
                     *par);
                *p.second = *par;
            }
        }
    }

    // characteristic values of primary variables
    {
        std::vector<std::pair<std::string, Trafo*>> const params{
            {"characteristic_pressure", &_assembly_params.trafo_p},
            {"characteristic_temperature", &_assembly_params.trafo_T},
            {"characteristic_vapour_mass_fraction", &_assembly_params.trafo_x}};

        for (auto const& p : params)
        {
            if (auto const par = config.getConfigParameterOptional<double>(p.first))
            {
                INFO("setting parameter `%s' to value `%g'", p.first.c_str(),
                     *par);
                *p.second = Trafo{*par};
            }
        }
    }

    // permeability
    if (auto par =
            config.getConfigParameterOptional<double>("solid_hydraulic_permeability"))
    {
        DBUG(
            "setting parameter `solid_hydraulic_permeability' to isotropic "
            "value `%g'",
            *par);
        const auto dim = mesh.getDimension();
        _assembly_params.solid_perm_tensor =
            Eigen::MatrixXd::Identity(dim, dim) * (*par);
    }

    // reactive system
    _assembly_params.react_sys = Adsorption::AdsorptionReaction::newInstance(
        config.getConfigSubtree("reactive_system"));

    // debug output
    if (auto const param =
            config.getConfigParameterOptional<bool>("output_element_matrices"))
    {
        DBUG("output_element_matrices: %s", (*param) ? "true" : "false");

        _assembly_params.output_element_matrices = *param;
    }

    // TODO somewhere else
    /*
    if (auto const param =
    config.getConfigParameterOptional<bool>("output_global_matrix"))
    {
        DBUG("output_global_matrix: %s", (*param) ? "true" : "false");

        this->_process_output.output_global_matrix = *param;
    }
    */
}
/*
 * Translates MacOS generated errors into PaErrors
 */
static PaError PaMacCore_SetError(OSStatus error, int line, int isError)
{
    /*FIXME: still need to handle possible ComponentResult values.*/
    /*       unfortunately, they don't seem to be documented anywhere.*/
    PaError result;
    const char *errorType; 
    const char *errorText;
    
    switch (error) {
    case kAudioHardwareNoError:
        return paNoError;
    case kAudioHardwareNotRunningError:
        errorText = "Audio Hardware Not Running";
        result = paInternalError; break;
    case kAudioHardwareUnspecifiedError: 
        errorText = "Unspecified Audio Hardware Error";
        result = paInternalError; break;
    case kAudioHardwareUnknownPropertyError:
        errorText = "Audio Hardware: Unknown Property";
        result = paInternalError; break;
    case kAudioHardwareBadPropertySizeError:
        errorText = "Audio Hardware: Bad Property Size";
        result = paInternalError; break;
    case kAudioHardwareIllegalOperationError: 
        errorText = "Audio Hardware: Illegal Operation";
        result = paInternalError; break;
    case kAudioHardwareBadDeviceError:
        errorText = "Audio Hardware: Bad Device";
        result = paInvalidDevice; break;
    case kAudioHardwareBadStreamError:
        errorText = "Audio Hardware: BadStream";
        result = paBadStreamPtr; break;
    case kAudioHardwareUnsupportedOperationError:
        errorText = "Audio Hardware: Unsupported Operation";
        result = paInternalError; break;
    case kAudioDeviceUnsupportedFormatError:
        errorText = "Audio Device: Unsupported Format";
        result = paSampleFormatNotSupported; break;
    case kAudioDevicePermissionsError:
        errorText = "Audio Device: Permissions Error";
        result = paDeviceUnavailable; break;
    /* Audio Unit Errors: http://developer.apple.com/documentation/MusicAudio/Reference/CoreAudio/audio_units/chapter_5_section_3.html */
    case kAudioUnitErr_InvalidProperty:
        errorText = "Audio Unit: Invalid Property";
        result = paInternalError; break;
    case kAudioUnitErr_InvalidParameter:
        errorText = "Audio Unit: Invalid Parameter";
        result = paInternalError; break;
    case kAudioUnitErr_NoConnection:
        errorText = "Audio Unit: No Connection";
        result = paInternalError; break;
    case kAudioUnitErr_FailedInitialization:
        errorText = "Audio Unit: Initialization Failed";
        result = paInternalError; break;
    case kAudioUnitErr_TooManyFramesToProcess:
        errorText = "Audio Unit: Too Many Frames";
        result = paInternalError; break;
    case kAudioUnitErr_IllegalInstrument:
        errorText = "Audio Unit: Illegal Instrument";
        result = paInternalError; break;
    case kAudioUnitErr_InstrumentTypeNotFound:
        errorText = "Audio Unit: Instrument Type Not Found";
        result = paInternalError; break;
    case kAudioUnitErr_InvalidFile:
        errorText = "Audio Unit: Invalid File";
        result = paInternalError; break;
    case kAudioUnitErr_UnknownFileType:
        errorText = "Audio Unit: Unknown File Type";
        result = paInternalError; break;
    case kAudioUnitErr_FileNotSpecified:
        errorText = "Audio Unit: File Not Specified";
        result = paInternalError; break;
    case kAudioUnitErr_FormatNotSupported:
        errorText = "Audio Unit: Format Not Supported";
        result = paInternalError; break;
    case kAudioUnitErr_Uninitialized:
        errorText = "Audio Unit: Unitialized";
        result = paInternalError; break;
    case kAudioUnitErr_InvalidScope:
        errorText = "Audio Unit: Invalid Scope";
        result = paInternalError; break;
    case kAudioUnitErr_PropertyNotWritable:
        errorText = "Audio Unit: PropertyNotWritable";
        result = paInternalError; break;
    case kAudioUnitErr_InvalidPropertyValue:
        errorText = "Audio Unit: Invalid Property Value";
        result = paInternalError; break;
    case kAudioUnitErr_PropertyNotInUse:
        errorText = "Audio Unit: Property Not In Use";
        result = paInternalError; break;
    case kAudioUnitErr_Initialized:
        errorText = "Audio Unit: Initialized";
        result = paInternalError; break;
    case kAudioUnitErr_InvalidOfflineRender:
        errorText = "Audio Unit: Invalid Offline Render";
        result = paInternalError; break;
    case kAudioUnitErr_Unauthorized:
        errorText = "Audio Unit: Unauthorized";
        result = paInternalError; break;
    case kAudioUnitErr_CannotDoInCurrentContext:
        errorText = "Audio Unit: cannot do in current context";
        result = paInternalError; break;
    default:
        errorText = "Unknown Error";
        result = paInternalError;
    }

    if (isError)
        errorType = "Error";
    else
        errorType = "Warning";

    if ((int)error < -99999 || (int)error > 99999)
        DBUG(("%s on line %d: err='%4s', msg='%s'\n", errorType, line, (const char *)&error, errorText));
    else
        DBUG(("%s on line %d: err=%d, 0x%x, msg='%s'\n", errorType, line, (int)error, (unsigned)error, errorText));

    PaUtil_SetLastHostErrorInfo( paCoreAudio, error, errorText );

    return result;
}
Ejemplo n.º 21
0
PaError PaHost_OpenStream( internalPortAudioStream   *past )
{
    HRESULT          hr;
    PaError          result = paNoError;
    PaHostSoundControl *pahsc;
    int              numBytes, maxChannels;
    unsigned int     minNumBuffers;
    internalPortAudioDevice *pad;
    DSoundWrapper   *dsw;
    /* Allocate and initialize host data. */
    pahsc = (PaHostSoundControl *) PaHost_AllocateFastMemory(sizeof(PaHostSoundControl)); /* MEM */
    if( pahsc == NULL )
    {
        result = paInsufficientMemory;
        goto error;
    }
    memset( pahsc, 0, sizeof(PaHostSoundControl) );
    past->past_DeviceData = (void *) pahsc;
    pahsc->pahsc_TimerID = 0;
    dsw = &pahsc->pahsc_DSoundWrapper;
    DSW_Init( dsw );
    /* Allocate native buffer. */
    maxChannels = ( past->past_NumOutputChannels > past->past_NumInputChannels ) ?
                  past->past_NumOutputChannels : past->past_NumInputChannels;
    pahsc->pahsc_BytesPerBuffer = past->past_FramesPerUserBuffer * maxChannels * sizeof(short);
    if( maxChannels > 0 )
    {
        pahsc->pahsc_NativeBuffer = (short *) PaHost_AllocateFastMemory(pahsc->pahsc_BytesPerBuffer); /* MEM */
        if( pahsc->pahsc_NativeBuffer == NULL )
        {
            result = paInsufficientMemory;
            goto error;
        }
    }
    else
    {
        result = paInvalidChannelCount;
        goto error;
    }

    DBUG(("PaHost_OpenStream: pahsc_MinFramesPerHostBuffer = %d\n", pahsc->pahsc_MinFramesPerHostBuffer ));
    minNumBuffers = Pa_GetMinNumBuffers( past->past_FramesPerUserBuffer, past->past_SampleRate );
    past->past_NumUserBuffers = ( minNumBuffers > past->past_NumUserBuffers ) ? minNumBuffers : past->past_NumUserBuffers;
    numBytes = pahsc->pahsc_BytesPerBuffer * past->past_NumUserBuffers;
    if( numBytes < DSBSIZE_MIN )
    {
        result = paBufferTooSmall;
        goto error;
    }
    if( numBytes > DSBSIZE_MAX )
    {
        result = paBufferTooBig;
        goto error;
    }
    pahsc->pahsc_FramesPerDSBuffer = past->past_FramesPerUserBuffer * past->past_NumUserBuffers;
    {
        int msecLatency = (int) ((pahsc->pahsc_FramesPerDSBuffer * 1000) / past->past_SampleRate);
        PRINT(("PortAudio on DirectSound - Latency = %d frames, %d msec\n", pahsc->pahsc_FramesPerDSBuffer, msecLatency ));
    }
    /* ------------------ OUTPUT */
    if( (past->past_OutputDeviceID >= 0) && (past->past_NumOutputChannels > 0) )
    {
        DBUG(("PaHost_OpenStream: deviceID = 0x%x\n", past->past_OutputDeviceID));
        pad = Pa_GetInternalDevice( past->past_OutputDeviceID );
        hr = DirectSoundCreate( pad->pad_lpGUID, &dsw->dsw_pDirectSound,   NULL );
        /* If this fails, then try each output device until we find one that works. */
        if( hr != DS_OK )
        {
            int i;
            ERR_RPT(("Creation of requested Audio Output device '%s' failed.\n",
                     ((pad->pad_lpGUID == NULL) ? "Default" : pad->pad_Info.name) ));
            for( i=0; i<Pa_CountDevices(); i++ )
            {
                pad = Pa_GetInternalDevice( i );
                if( pad->pad_Info.maxOutputChannels >= past->past_NumOutputChannels )
                {
                    DBUG(("Try device '%s' instead.\n", pad->pad_Info.name ));
                    hr = DirectSoundCreate( pad->pad_lpGUID, &dsw->dsw_pDirectSound,   NULL );
                    if( hr == DS_OK )
                    {
                        ERR_RPT(("Using device '%s' instead.\n", pad->pad_Info.name ));
                        break;
                    }
                }
            }
        }
        if( hr != DS_OK )
        {
            ERR_RPT(("PortAudio: DirectSoundCreate() failed!\n"));
            result = paHostError;
            sPaHostError = hr;
            goto error;
        }
        hr = DSW_InitOutputBuffer( dsw,
                                   (unsigned long) (past->past_SampleRate + 0.5),
                                   past->past_NumOutputChannels, numBytes );
        DBUG(("DSW_InitOutputBuffer() returns %x\n", hr));
        if( hr != DS_OK )
        {
            result = paHostError;
            sPaHostError = hr;
            goto error;
        }
        past->past_FrameCount = pahsc->pahsc_DSoundWrapper.dsw_FramesWritten;
    }
#if SUPPORT_AUDIO_CAPTURE
    /* ------------------ INPUT */
    if( (past->past_InputDeviceID >= 0) && (past->past_NumInputChannels > 0) )
    {
        pad = Pa_GetInternalDevice( past->past_InputDeviceID );
        hr = DirectSoundCaptureCreate( pad->pad_lpGUID, &dsw->dsw_pDirectSoundCapture,   NULL );
        /* If this fails, then try each input device until we find one that works. */
        if( hr != DS_OK )
        {
            int i;
            ERR_RPT(("Creation of requested Audio Capture device '%s' failed.\n",
                     ((pad->pad_lpGUID == NULL) ? "Default" : pad->pad_Info.name) ));
            for( i=0; i<Pa_CountDevices(); i++ )
            {
                pad = Pa_GetInternalDevice( i );
                if( pad->pad_Info.maxInputChannels >= past->past_NumInputChannels )
                {
                    PRINT(("Try device '%s' instead.\n", pad->pad_Info.name ));
                    hr = DirectSoundCaptureCreate( pad->pad_lpGUID, &dsw->dsw_pDirectSoundCapture,   NULL );
                    if( hr == DS_OK ) break;
                }
            }
        }
        if( hr != DS_OK )
        {
            ERR_RPT(("PortAudio: DirectSoundCaptureCreate() failed!\n"));
            result = paHostError;
            sPaHostError = hr;
            goto error;
        }
        hr = DSW_InitInputBuffer( dsw,
                                  (unsigned long) (past->past_SampleRate + 0.5),
                                  past->past_NumInputChannels, numBytes );
        DBUG(("DSW_InitInputBuffer() returns %x\n", hr));
        if( hr != DS_OK )
        {
            ERR_RPT(("PortAudio: DSW_InitInputBuffer() returns %x\n", hr));
            result = paHostError;
            sPaHostError = hr;
            goto error;
        }
    }
#endif /* SUPPORT_AUDIO_CAPTURE */
    /* Calculate scalar used in CPULoad calculation. */
    {
        LARGE_INTEGER frequency;
        if( QueryPerformanceFrequency( &frequency ) == 0 )
        {
            pahsc->pahsc_InverseTicksPerUserBuffer = 0.0;
        }
        else
        {
            pahsc->pahsc_InverseTicksPerUserBuffer = past->past_SampleRate /
                    ( (double)frequency.QuadPart * past->past_FramesPerUserBuffer );
            DBUG(("pahsc_InverseTicksPerUserBuffer = %g\n", pahsc->pahsc_InverseTicksPerUserBuffer ));
        }
    }
    return result;
error:
    PaHost_CloseStream( past );
    return result;
}
Ejemplo n.º 22
0
std::unique_ptr<Process> createLiquidFlowProcess(
    MeshLib::Mesh& mesh,
    std::unique_ptr<ProcessLib::AbstractJacobianAssembler>&& jacobian_assembler,
    std::vector<ProcessVariable> const& variables,
    std::vector<std::unique_ptr<ParameterBase>> const& parameters,
    unsigned const integration_order,
    BaseLib::ConfigTree const& config)
{
    //! \ogs_file_param{process__type}
    config.checkConfigParameter("type", "LIQUID_FLOW");

    DBUG("Create LiquidFlowProcess.");

    // Process variable.
    auto process_variables = findProcessVariables(
        variables, config,
        {//! \ogs_file_param_special{process__LIQUID_FLOW__process_variables__process_variable}
         "process_variable"});

    SecondaryVariableCollection secondary_variables;

    NumLib::NamedFunctionCaller named_function_caller({"LiquidFlow_pressure"});

    ProcessLib::parseSecondaryVariables(config, secondary_variables,
                                        named_function_caller);

    // Get the gravity vector for the Darcy velocity
    //! \ogs_file_param{process__LIQUID_FLOW__darcy_gravity}
    auto const& darcy_g_config = config.getConfigSubtree("darcy_gravity");
    const int gravity_axis_id_input =
        //! \ogs_file_param_special{process__LIQUID_FLOW__darcy_gravity_axis_id}
        darcy_g_config.getConfigParameter<int>("axis_id");
    assert(gravity_axis_id_input < static_cast<int>(mesh.getDimension()));
    const double g =
        //! \ogs_file_param_special{process__LIQUID_FLOW__darcy_gravity_g}
        darcy_g_config.getConfigParameter<double>("g");
    assert(g >= 0.);
    const int gravity_axis_id = (g == 0.) ? -1 : gravity_axis_id_input;

    //! \ogs_file_param{process__LIQUID_FLOW__material_property}
    auto const& mat_config = config.getConfigSubtree("material_property");

    auto const& mat_ids =
        mesh.getProperties().getPropertyVector<int>("MaterialIDs");
    if (mat_ids)
    {
        INFO("The liquid flow is in heterogeneous porous media.");
        const bool has_material_ids = true;
        return std::unique_ptr<Process>{new LiquidFlowProcess{
            mesh, std::move(jacobian_assembler), parameters, integration_order,
            std::move(process_variables), std::move(secondary_variables),
            std::move(named_function_caller), *mat_ids, has_material_ids,
            gravity_axis_id, g, mat_config}};
    }
    else
    {
        INFO("The liquid flow is in homogeneous porous media.");

        MeshLib::Properties dummy_property;
        // For a reference argument of LiquidFlowProcess(...).
        auto const& dummy_property_vector =
            dummy_property.createNewPropertyVector<int>(
                "MaterialIDs", MeshLib::MeshItemType::Cell, 1);

        // Since dummy_property_vector is only visible in this function,
        // the following constant, has_material_ids, is employed to indicate
        // that material_ids does not exist.
        const bool has_material_ids = false;

        return std::unique_ptr<Process>{new LiquidFlowProcess{
            mesh, std::move(jacobian_assembler), parameters, integration_order,
            std::move(process_variables), std::move(secondary_variables),
            std::move(named_function_caller), *dummy_property_vector,
            has_material_ids, gravity_axis_id, g, mat_config}};
    }
}
Ejemplo n.º 23
0
/*********************************************************************
 * Try to open the named device.
 * If it opens, try to set various rates and formats and fill in 
 * the device info structure.
 */
static PaError Pa_QueryDevice( const char *deviceName, internalPortAudioDevice *pad )
{
    int result = paHostError;
    int tempDevHandle;
    int numChannels, maxNumChannels;
    int format;
    int numSampleRates;
    int sampleRate;
    int numRatesToTry;
    int ratesToTry[9] = {96000, 48000, 44100, 32000, 24000, 22050, 16000, 11025, 8000};
    int i;

    /* douglas:
     we have to do this querying in a slightly different order. apparently
     some sound cards will give you different info based on their settins. 
     e.g. a card might give you stereo at 22kHz but only mono at 44kHz.
     the correct order for OSS is: format, channels, sample rate
     
    */
    if ( (tempDevHandle = open(deviceName,O_WRONLY|O_NONBLOCK))  == -1 )
    {
        DBUG(("Pa_QueryDevice: could not open %s\n", deviceName ));
        return paHostError;
    }

    /*  Ask OSS what formats are supported by the hardware. */
    pad->pad_Info.nativeSampleFormats = 0;
    if (ioctl(tempDevHandle, SNDCTL_DSP_GETFMTS, &format) == -1)
    {
        ERR_RPT(("Pa_QueryDevice: could not get format info\n" ));
        goto error;
    }
    if( format & AFMT_U8 )     pad->pad_Info.nativeSampleFormats |= paUInt8;
    if( format & AFMT_S16_NE ) pad->pad_Info.nativeSampleFormats |= paInt16;

    /* Negotiate for the maximum number of channels for this device. PLB20010927
     * Consider up to 16 as the upper number of channels.
     * Variable numChannels should contain the actual upper limit after the call.
     * Thanks to John Lazzaro and Heiko Purnhagen for suggestions.
     */
    maxNumChannels = 0;
    for( numChannels = 1; numChannels <= 16; numChannels++ )
    {
        int temp = numChannels;
        DBUG(("Pa_QueryDevice: use SNDCTL_DSP_CHANNELS, numChannels = %d\n", numChannels ))
        if(ioctl(tempDevHandle, SNDCTL_DSP_CHANNELS, &temp) < 0 )
        {
            /* ioctl() failed so bail out if we already have stereo */
            if( numChannels > 2 ) break;
        }
        else
        {
            /* ioctl() worked but bail out if it does not support numChannels.
             * We don't want to leave gaps in the numChannels supported.
             */
            if( (numChannels > 2) && (temp != numChannels) ) break;
            DBUG(("Pa_QueryDevice: temp = %d\n", temp ))
            if( temp > maxNumChannels ) maxNumChannels = temp; /* Save maximum. */
        }
    }

    /* The above negotiation may fail for an old driver so try this older technique. */
    if( maxNumChannels < 1 )
    {
        int stereo = 1;
        if(ioctl(tempDevHandle, SNDCTL_DSP_STEREO, &stereo) < 0)
        {
            maxNumChannels = 1;
        }
        else
        {
            maxNumChannels = (stereo) ? 2 : 1;
        }
        DBUG(("Pa_QueryDevice: use SNDCTL_DSP_STEREO, maxNumChannels = %d\n", maxNumChannels ))
    }
static fz_weights *
make_weights(fz_context *ctx, int src_w, float x, float dst_w, fz_scale_filter *filter, int vertical, int dst_w_int, int patch_l, int patch_r, int n, int flip, fz_scale_cache *cache)
{
	fz_weights *weights;
	float F, G;
	float window;
	int j;

	if (cache)
	{
		if (cache->src_w == src_w && cache->x == x && cache->dst_w == dst_w &&
			cache->filter == filter && cache->vertical == vertical &&
			cache->dst_w_int == dst_w_int &&
			cache->patch_l == patch_l && cache->patch_r == patch_r &&
			cache->n == n && cache->flip == flip)
		{
			return cache->weights;
		}
		cache->src_w = src_w;
		cache->x = x;
		cache->dst_w = dst_w;
		cache->filter = filter;
		cache->vertical = vertical;
		cache->dst_w_int = dst_w_int;
		cache->patch_l = patch_l;
		cache->patch_r = patch_r;
		cache->n = n;
		cache->flip = flip;
		fz_free(ctx, cache->weights);
		cache->weights = NULL;
	}

	if (dst_w < src_w)
	{
		/* Scaling down */
		F = dst_w / src_w;
		G = 1;
	}
	else
	{
		/* Scaling up */
		F = 1;
		G = src_w / dst_w;
	}
	window = filter->width / F;
	DBUG(("make_weights src_w=%d x=%g dst_w=%g patch_l=%d patch_r=%d F=%g window=%g\n", src_w, x, dst_w, patch_l, patch_r, F, window));
	weights	= new_weights(ctx, filter, src_w, dst_w, patch_r-patch_l, n, flip, patch_l);
	if (!weights)
		return NULL;
	for (j = patch_l; j < patch_r; j++)
	{
		/* find the position of the centre of dst[j] in src space */
		float centre = (j - x + 0.5f)*src_w/dst_w - 0.5f;
		int l, r;
		l = ceilf(centre - window);
		r = floorf(centre + window);
		DBUG(("%d: centre=%g l=%d r=%d\n", j, centre, l, r));
		init_weights(weights, j);
		for (; l <= r; l++)
		{
			add_weight(weights, j, l, filter, x, F, G, src_w, dst_w);
		}
		check_weights(weights, j, dst_w_int, x, dst_w);
		if (vertical)
		{
			reorder_weights(weights, j, src_w);
		}
	}
	weights->count++; /* weights->count = dst_w_int now */
	if (cache)
	{
		cache->weights = weights;
	}
	return weights;
}
Ejemplo n.º 25
0
/*
 * Copy a regular file.  If the destination file exists and is not a
 * regular file, we fail.  However, we use stat() rather than lstat(),
 * because it's okay to write through a symlink (the noDereference stuff
 * only applies to the source file).
 *
 * If the file doesn't exist, create it.  If it does exist, truncate it.
 */
static int copyRegular(const char* src, const char* dst, const struct stat* pSrcStat, unsigned int options)
{
    struct stat dstStat;
    int srcFd, dstFd, statResult, copyResult;

    DBUG(("--- copying regular '%s' to '%s'\n", src, dst));

    statResult = stat(dst, &dstStat);
    if (statResult == 0 && !S_ISREG(dstStat.st_mode)) {
        fprintf(stderr,
            "acp: destination '%s' exists and is not regular file\n",
            dst);
        return -1;
    } else if (statResult != 0 && errno != ENOENT) {
        fprintf(stderr, "acp: unable to stat destination '%s'\n", dst);
        return -1;
    }

    if (statResult == 0) {
        if (isSameFile(pSrcStat, &dstStat)) {
            fprintf(stderr, "acp: '%s' and '%s' are the same file\n",
                src, dst);
            return -1;
        }
        if (options & COPY_UPDATE_ONLY) {
            if (!isSourceNewer(pSrcStat, &dstStat)) {
                DBUG(("---  source is not newer: '%s'\n", src));
                printNotNewerMsg(src, dst, options);
                return 0;
            }
        }
    }

    /* open src */
    srcFd = open(src, O_RDONLY | O_BINARY, 0);
    if (srcFd < 0) {
        fprintf(stderr, "acp: unable to open '%s': %s\n", src, strerror(errno));
        return -1;
    }

    /* open dest with O_CREAT | O_TRUNC */
    DBUG(("---  opening '%s'\n", dst));
    dstFd = open(dst, O_CREAT | O_TRUNC | O_WRONLY | O_BINARY, 0644);

    if (dstFd < 0) {
        if (errno == ENOENT) {
            /* this happens if the target directory doesn't exist */
            fprintf(stderr,
                "acp: cannot create '%s': %s\n", dst, strerror(errno));
            (void) close(srcFd);
            return -1;
        }

        /* if "force" is set, try removing the destination file and retry */
        if (options & COPY_FORCE) {
            if (unlink(dst) != 0) {
#ifdef HAVE_MS_C_RUNTIME
				/* MSVCRT.DLL unlink will fail with EACCESS if the file is set read-only */
				/* so try to change its mode, and unlink again                           */
				if (errno == EACCESS) {
					if (chmod(dst, S_IWRITE|S_IREAD) == 0 && unlink(dst) == 0)
						goto Open_File;
				}
#endif		
                fprintf(stderr, "acp: unable to remove '%s': %s\n",
                    dst, strerror(errno));
                (void) close(srcFd);
                return -1;
            }
#ifdef HAVE_MS_C_RUNTIME
        Open_File:
#endif			
            dstFd = open(dst, O_CREAT | O_TRUNC | O_WRONLY | O_BINARY, 0644);
        }
    }
    if (dstFd < 0) {
        fprintf(stderr, "acp: unable to open '%s': %s\n",
            dst, strerror(errno));
        (void) close(srcFd);
        return -1;
    }

    copyResult = copyFileContents(dst, dstFd, src, srcFd);

    (void) close(srcFd);
    (void) close(dstFd);
    if (copyResult != 0)
        return -1;

#ifdef MACOSX_RSRC
    {
        char* srcRsrcName = NULL;
        char* dstRsrcName = NULL;
        struct stat rsrcStat;

        srcRsrcName = malloc(strlen(src) + 5 + 1);
        strcpy(srcRsrcName, src);
        strcat(srcRsrcName, "/rsrc");

        dstRsrcName = malloc(strlen(dst) + 5 + 1);
        strcpy(dstRsrcName, dst);
        strcat(dstRsrcName, "/rsrc");

        if (stat(srcRsrcName, &rsrcStat) == 0 && rsrcStat.st_size > 0) {
            DBUG(("---  RSRC: %s --> %s\n", srcRsrcName, dstRsrcName));

            srcFd = open(srcRsrcName, O_RDONLY);
            dstFd = open(dstRsrcName, O_TRUNC | O_WRONLY, 0);
            copyResult = -1;
            if (srcFd >= 0 && dstFd >= 0) {
                copyResult = copyFileContents(dstRsrcName, dstFd,
                    srcRsrcName, srcFd);
                (void) close(srcFd);
                (void) close(dstFd);
            }

            if (copyResult != 0)
                return -1;
        }

        free(srcRsrcName);
        free(dstRsrcName);
    }
#endif

    setPermissions(dst, pSrcStat, options);

    printCopyMsg(src, dst, options);

    return 0;
}
Ejemplo n.º 26
0
struct template_chunk *
template_chunk_new(const char *entity)
{
  static const struct {
    enum crab_chunk_type type;
    const char *name;
  } entities[] = {
  { crab_uri,             "crab.uri" },
  { crab_url,             "crab.url" },
  { crab_startup_time,    "crab.startup.time" },
  { crab_user_agent,      "crab.user.agent" },
  { crab_network_id,      "crab.network.id" },
  { crab_contact_address, "crab.contact.address" },
  
  { crab_rusage_utime,    "crab.rusage.utime" },
  { crab_rusage_stime,    "crab.rusage.stime" },
  { crab_rusage_utime_percent,    "crab.rusage.utime.percent" },
  { crab_rusage_stime_percent,    "crab.rusage.stime.percent" },
  { crab_rusage_maxrss,   "crab.rusage.maxrss" },
  { crab_rusage_ixrss,    "crab.rusage.ixrss" },
  { crab_rusage_idrss,    "crab.rusage.idrss" },
  { crab_rusage_isrss,    "crab.rusage.isrss" },
  { crab_rusage_minflt,   "crab.rusage.minflt" },
  { crab_rusage_majflt,   "crab.rusage.majflt" },
  { crab_rusage_nswap,    "crab.rusage.nswap" },
  { crab_rusage_inblock,  "crab.rusage.inblock" },
  { crab_rusage_oublock,  "crab.rusage.oublock" },
  { crab_rusage_msgsnd,   "crab.rusage.msgsnd" },
  { crab_rusage_msgrcv,   "crab.rusage.msgrcv" },
  { crab_rusage_nsignals, "crab.rusage.nsignals" },
  { crab_rusage_nvcsw,    "crab.rusage.nvcsw" },
  { crab_rusage_nivcsw,   "crab.rusage.nivcsw" },
  
  { crab_stats_total_updates,           "crab.stats.total.updates" },
  { crab_stats_total_updates_ip,        "crab.stats.total.updates.ip" },
  { crab_stats_total_updates_url,       "crab.stats.total.updates.url" },
  { crab_stats_total_requests,          "crab.stats.total.requests" },
  { crab_stats_total_requests_base,     "crab.stats.total.requests.base" },
  { crab_stats_total_requests_data,     "crab.stats.total.requests.data" },
  { crab_stats_total_requests_get,      "crab.stats.total.requests.get" },
  { crab_stats_total_requests_hostfile, "crab.stats.total.requests.hostfile" },
  { crab_stats_total_requests_urlfile,  "crab.stats.total.requests.urlfile" },
  { crab_stats_total_requests_ping,     "crab.stats.total.requests.ping" },
  { crab_stats_total_requests_statfile, "crab.stats.total.requests.statfile" },
  { crab_stats_total_accepts,           "crab.stats.total.accepts" },
  { crab_stats_total_blocked,           "crab.stats.total.blocked" },
  { crab_stats_total_errors,            "crab.stats.total.errors" },
  { crab_stats_total_http_400s,         "crab.stats.total.http_400s" },
  { crab_stats_total_http_404s,         "crab.stats.total.http_404s" },
  { crab_stats_total_too_early,         "crab.stats.total.too_early" },
  { crab_stats_total_rx,                "crab.stats.total.rx" },
  { crab_stats_total_tx,                "crab.stats.total.tx" },
  
  { crab_stats_hourly_updates,           "crab.stats.hourly.updates" },
  { crab_stats_hourly_updates_ip,        "crab.stats.hourly.updates.ip" },
  { crab_stats_hourly_updates_url,       "crab.stats.hourly.updates.url" },
  { crab_stats_hourly_requests,          "crab.stats.hourly.requests" },
  { crab_stats_hourly_requests_base,     "crab.stats.hourly.requests.base" },
  { crab_stats_hourly_requests_data,     "crab.stats.hourly.requests.data" },
  { crab_stats_hourly_requests_get,      "crab.stats.hourly.requests.get" },
  { crab_stats_hourly_requests_hostfile, "crab.stats.hourly.requests.hostfile"},
  { crab_stats_hourly_requests_urlfile,  "crab.stats.hourly.requests.urlfile" },
  { crab_stats_hourly_requests_ping,     "crab.stats.hourly.requests.ping" },
  { crab_stats_hourly_requests_statfile, "crab.stats.hourly.requests.statfile"},
  { crab_stats_hourly_accepts,           "crab.stats.hourly.accepts" },
  { crab_stats_hourly_blocked,           "crab.stats.hourly.blocked" },
  { crab_stats_hourly_errors,            "crab.stats.hourly.errors" },
  { crab_stats_hourly_http_400s,         "crab.stats.hourly.http_400s" },
  { crab_stats_hourly_http_404s,         "crab.stats.hourly.http_404s" },
  { crab_stats_hourly_too_early,         "crab.stats.hourly.too_early" },
  { crab_stats_hourly_rx,                "crab.stats.hourly.rx" },
  { crab_stats_hourly_tx,                "crab.stats.hourly.tx" },
  };
  size_t i;
  
  RUNTIME_ASSERT(entity != NULL);
  
  for (i = 0; i < ARRAY_LEN(entities); i++) {
    struct template_chunk *chunk;
    
    if (0 != strcmp(entity, entities[i].name)) {
      continue;
    }
    
    chunk = calloc(1, sizeof *chunk);
    if (chunk) {
      chunk->buf = NULL;
      chunk->size = 0;
      chunk->type = entities[i].type;
#if 0
      DBUG("Added template chunk \"%s\"", entities[i].name);
#endif
    }
    return chunk;
  }

  if (0 == strncmp(entity, "crab", sizeof "crab" - 1)) {
    WARN("No such entity \"%s\"", entity);
  } else {
#if 0
    DBUG("No such entity \"%s\"", entity);
#endif
  }
  return NULL;
}
Ejemplo n.º 27
0
/*
 * Copy the contents of one directory to another.  Both "src" and "dst"
 * must be directories.  We will create "dst" if it does not exist.
 */
int copyDirectory(const char* src, const char* dst, const struct stat* pSrcStat, unsigned int options)
{
    int retVal = 0;
    struct stat dstStat;
    DIR* dir;
    int cc, statResult;

    DBUG(("--- copy dir '%s' to '%s'\n", src, dst));

    statResult = stat(dst, &dstStat);
    if (statResult == 0 && !S_ISDIR(dstStat.st_mode)) {
        fprintf(stderr,
            "acp: destination '%s' exists and is not a directory\n", dst);
        return -1;
    } else if (statResult != 0 && errno != ENOENT) {
        fprintf(stderr, "acp: unable to stat destination '%s'\n", dst);
        return -1;
    }

    if (statResult == 0) {
        if (isSameFile(pSrcStat, &dstStat)) {
            fprintf(stderr,
                "acp: cannot copy directory into itself ('%s' and '%s')\n",
                src, dst);
            return -1;
        }
    } else {
        DBUG(("---  creating dir '%s'\n", dst));
        cc = mkdir(dst, 0755);
        if (cc != 0) {
            fprintf(stderr, "acp: unable to create directory '%s': %s\n",
                dst, strerror(errno));
            return -1;
        }

        /* only print on mkdir */
        printCopyMsg(src, dst, options);
    }

    /*
     * Open the directory, and plow through its contents.
     */
    dir = opendir(src);
    if (dir == NULL) {
        fprintf(stderr, "acp: unable to open directory '%s': %s\n",
            src, strerror(errno));
        return -1;
    }

    while (1) {
        struct dirent* ent;
        char* srcFile;
        char* dstFile;
        int srcLen, dstLen, nameLen;

        ent = readdir(dir);
        if (ent == NULL)
            break;

        if (strcmp(ent->d_name, ".") == 0 ||
            strcmp(ent->d_name, "..") == 0)
        {
            continue;
        }

        nameLen = strlen(ent->d_name);
        srcLen = strlen(src);
        dstLen = strlen(dst);

        srcFile = malloc(srcLen +1 + nameLen +1);
        memcpy(srcFile, src, srcLen);
        srcFile[srcLen] = FSSEP;
        memcpy(srcFile + srcLen+1, ent->d_name, nameLen +1);

        dstFile = malloc(dstLen +1 + nameLen +1);
        memcpy(dstFile, dst, dstLen);
        dstFile[dstLen] = FSSEP;
        memcpy(dstFile + dstLen+1, ent->d_name, nameLen +1);

        if (copyFileRecursive(srcFile, dstFile, false, options) != 0)
            retVal = -1;        /* note failure and keep going */

        free(srcFile);
        free(dstFile);
    }
    closedir(dir);

    setPermissions(dst, pSrcStat, options);

    return retVal;
}
Ejemplo n.º 28
0
template_t *
template_load(const char *filename)
{
  struct template_chunk *chunk;
  FILE *f;
  char *buf = NULL, *q;
  size_t buf_len, line;
  template_t *tpl = NULL;
  int c;
  char entity[128], *e = NULL;

  RUNTIME_ASSERT(filename != NULL);
  f = safer_fopen(filename, SAFER_FOPEN_RD);
  if (!f) {
    WARN("could not open \"%s\": %s", filename, compat_strerror(errno));
    goto failure;
  }

  tpl = calloc(1, sizeof *tpl);
  if (!tpl) {
    CRIT("Out of memory");
    goto failure;
  }
  tpl->chunks = NULL;
  
  buf_len = 4096;
  buf = calloc(1, buf_len);
  if (!buf) {
    CRIT("Out of memory");
    goto failure;
  }
  
  for (line = 1; /* NOTHING */; line++) {
    char *p;
    
    p = fgets(buf, buf_len, f);
    if (!p) {
      if (!ferror(f))
        break;

      CRIT("fgets() failed: %s", compat_strerror(errno));
      goto failure;
    }

    q = strchr(buf, '\n');
    if (!q) {
      CRIT("Line too long or unterminated: \"%s\"", buf);
      goto failure;
    }
    while (isspace((unsigned char) *q)) {
      *q = '\0';
      if (q == buf)
        break;
      q--;
    }
    
    if (q == buf && *q == '\0')
      break;

    if (line == 1 && 0 == strncmp(buf, "HTTP/", sizeof "HTTP/" - 1)) {
      uint64_t code;
      char *endptr;
      int error;
      struct http_response hres;
      size_t size;
      snode_t *sn;

      p = strchr(buf, ' ');
      if (!p) {
        WARN("Invalid HTTP response: \"%s\"", buf);
        goto failure;
      }
      
      p = skip_spaces(p);
      code = parse_uint64(p, &endptr, 10, &error);
      if (code < 100 || code > 999) {
        WARN("Invalid HTTP result code: \"%s\"", buf);
        goto failure;
      }
      p = skip_spaces(endptr);

      hres.code = code;
      size = sizeof hres.msg;
      append_string(hres.msg, &size, p);
      RUNTIME_ASSERT(hres.msg == (char *) &hres);
      chunk = template_raw_chunk_new(chunk_http_response,
                (char *) &hres, sizeof hres);

      if (NULL == (sn = snode_new(chunk))) {
        CRIT("snode_new() failed");
        goto failure;
      }
      tpl->chunks = snode_prepend(tpl->chunks, sn);
    } else {
      size_t len;
      snode_t *sn;

      if (!isalpha((unsigned char) buf[0]) || NULL == strchr(buf, ':')) {
        WARN("Invalid HTTP header: \"%s\"", buf);
        goto failure;
      }

      for (p = buf; (c = (unsigned char) *p) != ':'; ++p)
        if (!isalpha(c) && c != '-') {
          WARN("Invalid character HTTP in header name: \"%s\"", buf);
          goto failure;
        }
      
      len = strlen(buf) + 1;
      chunk = template_raw_chunk_new(chunk_http_header, buf, len);
      if (NULL == (sn = snode_new(chunk))) {
        CRIT("snode_new() failed");
        goto failure;
      }
      tpl->chunks = snode_prepend(tpl->chunks, sn);
    }
  }

  if (feof(f)) {
    tpl->chunks = snode_reverse(tpl->chunks);
    return tpl;
  }
  
  q = buf;
  e = NULL;
  
  for (;;) {
    c = fgetc(f);
    if (c == EOF) {
      if (!ferror(f))
        break;
      
      CRIT("fgetc() failed: %s", compat_strerror(errno));
      goto failure;
    }
    
    if ((size_t) (q - buf) >= buf_len) {
      char *n;
      
      buf_len += 4096;
      n = realloc(buf, buf_len);
      if (!n) {
        CRIT("Out of memory");
        goto failure;
      }
      q = &n[q - buf];
      buf = n;
    }
    *q++ = c;

    if (c == ';' && e != NULL) {
      RUNTIME_ASSERT(e >= entity && e < &entity[sizeof entity]);
      *e = '\0';
      
      chunk = template_chunk_new(entity);
      if (chunk) {
        struct template_chunk *data;
        size_t data_len;
        snode_t *sn;
     
        data_len = (q - buf) - strlen(entity) - 2;
        RUNTIME_ASSERT(data_len <= INT_MAX);
        if (data_len > 0) {
          data = template_raw_chunk_new(chunk_data, buf, data_len);
          if (NULL == (sn = snode_new(data))) {
            CRIT("snode_new() failed");
            goto failure;
          }
          tpl->chunks = snode_prepend(tpl->chunks, sn);
      
          buf_len = 4096;
          buf = calloc(1, buf_len);
          if (!buf) {
            CRIT("Out of memory");
            goto failure;
          }
        }
        q = buf;
    
        if (NULL == (sn = snode_new(chunk))) {
          CRIT("snode_new() failed");
          goto failure;
        }
        tpl->chunks = snode_prepend(tpl->chunks, sn);
      }

      e = NULL;
    }
    
    if (e) {
      bool b = isalnum(c) || c == '.' || c == '_';
      
      if (b && e < &entity[sizeof entity - 1]) {
        *e++ = c;
      } else {
        e = NULL;
      }
    }
    
    if (c == '&') {
      e = entity;
    }
  }
  fclose(f);
  f = NULL;

  if (q != buf) {
    snode_t *sn;

    chunk = template_raw_chunk_new(chunk_data, buf, q - buf);
    if (NULL == (sn = snode_new(chunk))) {
      CRIT("snode_new() failed");
      goto failure;
    }
    tpl->chunks = snode_prepend(tpl->chunks, sn);
  }
  DO_FREE(buf);
 
  tpl->chunks = snode_reverse(tpl->chunks);
  
#if 0
  {
    size_t n = 0;
    
    snode_t *sn = tpl->chunks;
    while (sn) {
      struct gwc_data_chunk *data = sn->ptr;
      DBUG("data->type=%d; data->buf=%p; data->size=%d",
          (int) data->type, data->buf, (int) data->size);
      sn = sn->next;
      n += data->size;
    }
    
    DBUG("n=%d", (int) n);
  }
#endif
  
  return tpl;

failure:

  CRIT("Loading data template from \"%s\" failed.", filename);

  if (f) {
    fclose(f);
    f = NULL;
  }
  DO_FREE(buf);
  if (tpl) {
    while (tpl->chunks != NULL) {
      snode_t *sn = tpl->chunks->next;
    
      DO_FREE(tpl->chunks);
      tpl->chunks = sn;
    }
    DO_FREE(tpl);
  }
  return NULL;
}
Ejemplo n.º 29
0
/*
 * Something failed, and the user may want to choose how to handle it.
 * Invoked as a callback.
 */
NuResult ErrorHandler(NuArchive* pArchive, void* vErrorStatus)
{
    const NuErrorStatus* pErrorStatus = vErrorStatus;
    NulibState* pState;
    NuResult result;

    Assert(pArchive != NULL);
    (void) NuGetExtraData(pArchive, (void**) &pState);
    Assert(pState != NULL);

    /* default action is to abort the current operation */
    result = kNuAbort;

    /*
     * When extracting, the error handler callback gets invoked for several
     * different problems because we might want to rename the file.  Also,
     * because extractions are done with "bulk" calls, returning an
     * individual error message would be meaningless.
     *
     * When adding files, the NuAddFile and NuAddRecord calls can return
     * immediate, specific results for a single add.  The only reasons for
     * calling here are to decide if an existing record should be replaced
     * or not (without even an option to rename), or to decide what to do
     * when the NuFlush call runs into a problem while adding a file.
     */
    if (pErrorStatus->operation == kNuOpExtract) {
        if (pErrorStatus->err == kNuErrFileExists) {
            result = HandleReplaceExisting(pState, pArchive, pErrorStatus);
        } else if (pErrorStatus->err == kNuErrNotNewer) {
            /* if we were expecting this, it's okay */
            if (NState_GetModFreshen(pState) || NState_GetModUpdate(pState)) {
                printf("\rSKIP\n");
                result = kNuSkip;
            } else {
                DBUG(("WEIRD one\n"));
            }
        } else if (pErrorStatus->err == kNuErrDuplicateNotFound) {
            /* if we were expecting this, it's okay */
            if (NState_GetModFreshen(pState)) {
                printf("\rSKIP\n");
                result = kNuSkip;
            } else {
                DBUG(("WEIRD two\n"));
            }
        }
    } else if (pErrorStatus->operation == kNuOpAdd) {
        if (pErrorStatus->err == kNuErrRecordExists) {
            /* if they want to update or freshen, don't hassle them */
            if (NState_GetModFreshen(pState) || NState_GetModUpdate(pState))
                result = kNuOverwrite;
            else
                result = HandleReplaceExisting(pState, pArchive, pErrorStatus);
        } else if (pErrorStatus->err == kNuErrFileNotFound) {
            /* file was specified with NuAdd but removed during NuFlush */
            result = HandleAddNotFound(pState, pArchive, pErrorStatus);
        }
    } else if (pErrorStatus->operation == kNuOpTest) {
        if (pErrorStatus->err == kNuErrBadMHCRC ||
            pErrorStatus->err == kNuErrBadRHCRC ||
            pErrorStatus->err == kNuErrBadThreadCRC ||
            pErrorStatus->err == kNuErrBadDataCRC)
        {
            result = HandleBadCRC(pState, pArchive, pErrorStatus);
        }
    }

    return result;
}
Ejemplo n.º 30
0
/***********************************************************************
 *
 *  Procedure:
 *	HandleDestroyNotify - DestroyNotify event handler
 *
 ***********************************************************************/
void HandleDestroyNotify()
{
  DBUG("HandleDestroyNotify","Routine Entered");

  Destroy(Tmp_win);
}