Ejemplo n.º 1
0
static void _CFAppendXMLEpilog(CFMutableStringRef str, CFXMLTreeRef tree) {
    CFXMLNodeTypeCode typeID = CFXMLNodeGetTypeCode(CFXMLTreeGetNode(tree));
    if (typeID == kCFXMLNodeTypeElement) {
        if (((CFXMLElementInfo *)CFXMLNodeGetInfoPtr(CFXMLTreeGetNode(tree)))->isEmpty) return;
        CFStringAppendFormat(str, NULL, CFSTR("</%@>"), CFXMLNodeGetString(CFXMLTreeGetNode(tree)));
    } else if (typeID == kCFXMLNodeTypeDocumentType) {
        CFIndex len = CFStringGetLength(str);
        if (CFStringHasSuffix(str, CFSTR(" ["))) {
            // There were no in-line DTD elements
            CFStringDelete(str, CFRangeMake(len-2, 2));
        } else {
            CFStringAppendCString(str, "]", kCFStringEncodingASCII);
        }
        CFStringAppendCString(str, ">", kCFStringEncodingASCII);
    }
}
void TestController::initializeInjectedBundlePath()
{
    CFStringRef exeContainerPath = CFURLCopyFileSystemPath(CFURLCreateCopyDeletingLastPathComponent(0, CFBundleCopyExecutableURL(CFBundleGetMainBundle())), kCFURLWindowsPathStyle);
    CFMutableStringRef bundlePath = CFStringCreateMutableCopy(0, 0, exeContainerPath);
    CFStringAppendCString(bundlePath, injectedBundleDLL, kCFStringEncodingWindowsLatin1);
    m_injectedBundlePath.adopt(WKStringCreateWithCFString(bundlePath));
}
Ejemplo n.º 3
0
static void appendExternalID(CFMutableStringRef str, CFXMLExternalID *extID) {
    if (extID->publicID) {
        CFStringAppendCString(str, " PUBLIC ", kCFStringEncodingASCII);
        appendQuotedString(str, extID->publicID);
        if (extID->systemID) {
            // Technically, for externalIDs, systemID must not be NULL.  However, by testing for a NULL systemID, we can use this to emit publicIDs, too.  REW, 2/15/2000
            CFStringAppendCString(str, " ", kCFStringEncodingASCII);
            appendQuotedString(str, CFURLGetString(extID->systemID));
        }
    } else if (extID->systemID) {
        CFStringAppendCString(str, " SYSTEM ", kCFStringEncodingASCII);
        appendQuotedString(str, CFURLGetString(extID->systemID));
    } else {
        // Should never get here
    }
}
Ejemplo n.º 4
0
//-----------------------------------------------------------------------------
//	C700::C700
//-----------------------------------------------------------------------------
C700::C700(AudioUnit component)
    : AUInstrumentBase(component, 0, 1)
    , mEfx(NULL)
{
    CreateElements();
    Globals()->UseIndexedParameters(kNumberOfParameters);

    mEfx = new C700Kernel();
    mEfx->SetPropertyNotifyFunc(PropertyNotifyFunc, this);
    mEfx->SetParameterSetFunc(ParameterSetFunc, this);

    //プリセット名テーブルを作成する
    mPresets = new AUPreset[NUM_PRESETS];
    for (int i = 0; i < NUM_PRESETS; ++i) {
        const char		*pname;
        pname = C700Kernel::GetPresetName(i);
        mPresets[i].presetNumber = i;
        CFMutableStringRef cfpname = CFStringCreateMutable(NULL, 64);
        mPresets[i].presetName = cfpname;
        CFStringAppendCString( cfpname, pname, kCFStringEncodingASCII );
    }

    //デフォルト値を設定する
    for ( int i=0; i<kNumberOfParameters; i++ ) {
        Globals()->SetParameter(i, C700Kernel::GetParameterDefault(i) );
    }

#if AU_DEBUG_DISPATCHER
    mDebugDispatcher = new AUDebugDispatcher(this);
#endif
}
Ejemplo n.º 5
0
__private_extern__
jstring newStringPlatform(JNIEnv *env, const char* str)
{
    jstring rv = NULL;
    CFMutableStringRef csref = CFStringCreateMutable(NULL, 0);
    if (csref == NULL) {
        JNU_ThrowOutOfMemoryError(env, "native heap");
    } else {
        CFStringAppendCString(csref, str, kCFStringEncodingUTF8);
        CFStringNormalize(csref, kCFStringNormalizationFormC);
        int clen = CFStringGetLength(csref);
        int ulen = (clen + 1) * 2;        // utf16 + zero padding
        char* chars = malloc(ulen);
        if (chars == NULL) {
            CFRelease(csref);
            JNU_ThrowOutOfMemoryError(env, "native heap");
        } else {
            if (CFStringGetCString(csref, chars, ulen, kCFStringEncodingUTF16)) {
                rv = (*env)->NewString(env, (jchar*)chars, clen);
            }
            free(chars);
            CFRelease(csref);
        }
    }
    return rv;
}
Ejemplo n.º 6
0
static void appendElementProlog(CFMutableStringRef str, CFXMLTreeRef tree) {
    const CFXMLElementInfo *data = (CFXMLElementInfo *)CFXMLNodeGetInfoPtr(CFXMLTreeGetNode(tree));
    CFStringAppendFormat(str, NULL, CFSTR("<%@"), CFXMLNodeGetString(CFXMLTreeGetNode(tree)));
    if (data->attributeOrder) {
        CFIndex i, c = CFArrayGetCount(data->attributeOrder);
        for (i = 0; i < c; i ++) {
            CFStringRef attr = (CFStringRef)CFArrayGetValueAtIndex(data->attributeOrder, i);
            CFStringRef value = (CFStringRef)CFDictionaryGetValue(data->attributes, attr);
            CFStringAppendFormat(str, NULL, CFSTR(" %@="), attr);
            appendQuotedString(str, value);
        }
    }
    if (data->isEmpty) {
        CFStringAppendCString(str, "/>", kCFStringEncodingASCII);
    } else {
        CFStringAppendCString(str, ">", kCFStringEncodingASCII);
    }
}
Ejemplo n.º 7
0
void TrackbarActionProcPtr (ControlRef theControl, ControlPartCode partCode)
{
    CvTrackbar * trackbar = icvTrackbarByHandle (theControl);

    if (trackbar == NULL)
    {
        fprintf(stderr,"Error getting trackbar\n");
        return;
    }
    else
    {
        int pos = GetControl32BitValue (theControl);
        if ( trackbar->data )
            *trackbar->data = pos;
        if ( trackbar->notify )
            trackbar->notify(pos);
        else if ( trackbar->notify2 )
            trackbar->notify2(pos, trackbar->userdata);

        //--------YV---------------------------
        CFStringEncoding encoding = kCFStringEncodingASCII;
        CFAllocatorRef alloc_default = kCFAllocatorDefault;  // = NULL;

        char valueinchar[20];
        sprintf(valueinchar, " (%d)",  *trackbar->data);

        // create an empty CFMutableString
        CFIndex maxLength = 256;
        CFMutableStringRef cfstring = CFStringCreateMutable(alloc_default,maxLength);

        // append some c strings into it.
        CFStringAppendCString(cfstring,trackbar->name,encoding);
        CFStringAppendCString(cfstring,valueinchar,encoding);

        SetControlData(trackbar->label, kControlEntireControl,kControlStaticTextCFStringTag, sizeof(cfstring), &cfstring);
        DrawControls(trackbar->parent->window);
        //-----------------------------------------
    }
}
Ejemplo n.º 8
0
std::string digidoc::util::File::decodeName(const std::string &localFileName)
{
    CFMutableStringRef ref = CFStringCreateMutable(0, 0);
    CFStringAppendCString(ref, localFileName.c_str(), kCFStringEncodingUTF8);
    CFStringNormalize(ref, kCFStringNormalizationFormC);

    char *composed = new char[localFileName.size() * 2];
    CFStringGetCString(ref, composed, localFileName.size() * 2, kCFStringEncodingUTF8);
    CFRelease(ref);

    std::string out(composed);
    delete [] composed;

    return out;
}
Ejemplo n.º 9
0
/**
 * Returns a new string in which each occurrence of @c stringToFind in @c subject has been replaced with @c replacement.
 *
 * @c stringToFind matches even if a different UTF-8 encoding or Unicode character decomposition is used.
 */
VuoText VuoText_replace(VuoText subject, VuoText stringToFind, VuoText replacement)
{
	CFMutableStringRef subjectCF = CFStringCreateMutable(NULL, 0);
	CFStringAppendCString(subjectCF, subject, kCFStringEncodingUTF8);
	CFStringRef stringToFindCF = CFStringCreateWithCString(NULL, stringToFind, kCFStringEncodingUTF8);
	CFStringRef replacementCF = CFStringCreateWithCString(NULL, replacement, kCFStringEncodingUTF8);

	CFStringFindAndReplace(subjectCF, stringToFindCF, replacementCF, CFRangeMake(0,CFStringGetLength(subjectCF)), kCFCompareNonliteral);

	VuoText replacedSubject = VuoText_makeFromMacString(subjectCF);
	CFRelease(replacementCF);
	CFRelease(stringToFindCF);
	CFRelease(subjectCF);

	return replacedSubject;
}
Ejemplo n.º 10
0
OSStatus SetVMPathFromApplicationDirectory() {
	CFBundleRef mainBundle;
	CFURLRef	bundleURL,bundleURLPrefix;
	CFStringRef filePath;

	CFMutableStringRef vmPathString;
	mainBundle = CFBundleGetMainBundle();   
	bundleURL = CFBundleCopyBundleURL(mainBundle);
	bundleURLPrefix = CFURLCreateCopyDeletingLastPathComponent(NULL,bundleURL);
	CFRelease(bundleURL);	
	filePath = CFURLCopyFileSystemPath (bundleURLPrefix, kCFURLPOSIXPathStyle);
	CFRelease(bundleURLPrefix);	
	vmPathString = CFStringCreateMutableCopy(NULL, 0, filePath);
	CFStringAppendCString(vmPathString, "/", kCFStringEncodingMacRoman);
	SetVMPathFromCFString(vmPathString);
	CFRelease(filePath);
	CFRelease(vmPathString);
	
	return 0;		
}
Ejemplo n.º 11
0
HP_HogMode::HP_HogMode(HP_Device* inDevice)
    :
    mToken(0),
    mDevice(inDevice),
    mPrefName(NULL),
    mOwner(-2)
{
    pthread_once(&sStaticInitializer, StaticInitializer);

    //	get our token
    mToken = sTokenMap->MapObject(this);

    //	construct the name of the preference
    mPrefName = CFStringCreateMutable(NULL, 0);
    ThrowIfNULL(mPrefName, CAException(kAudioHardwareUnspecifiedError), "HP_HogMode::HP_HogMode: couldn't allocate the pref name string");
    CFStringAppendCString((CFMutableStringRef)mPrefName, "com.apple.audio.CoreAudio.HogMode.Owner-", kCFStringEncodingASCII);
    CACFString theUID(inDevice->CopyDeviceUID());
    CFStringAppend((CFMutableStringRef)mPrefName, theUID.GetCFString());

    //	sign up for notifications
    CACFDistributedNotification::AddObserver((const void*)mToken, (CFNotificationCallback)ChangeNotification, mPrefName, 0);
}
Ejemplo n.º 12
0
    CFStringRef CFStringWithUTF8(const char* utf8) {
	CFMutableStringRef cfstr = CFStringCreateMutable(0, 0);
	CFStringAppendCString(cfstr, utf8, kCFStringEncodingUTF8);

	CFStringRef result;
	CFIndex len = CFStringGetLength(cfstr);
	CFIndex bufsize = len * sizeof(UInt16);
	UInt16* buf = new UInt16[len];

	CFStringGetBytes(cfstr, CFRangeMake(0, len), kCFStringEncodingUnicode, 0, false,
			 reinterpret_cast<UInt8*>(buf), bufsize, NULL);

	CFRelease(cfstr);

	for(int i = 0; i < len; ++ i) {
	    buf[i] = CFSwapInt16HostToBig(buf[i]);
	}

	result = CFStringCreateWithBytes(0, reinterpret_cast<UInt8*>(buf), bufsize, kCFStringEncodingUnicode, false);

	delete[] buf;
	
	return result;
    }
Ejemplo n.º 13
0
void GourceSettings::importGourceSettings(ConfFile& conffile, ConfSection* gource_settings) {

    setGourceDefaults();

    if(gource_settings == 0) gource_settings = conffile.getSection(default_section_name);

    if(gource_settings == 0) {
        gource_settings = conffile.addSection("gource");
    }

    ConfEntry* entry = 0;

    //hide flags

    std::vector<std::string> hide_fields;

    if((entry = gource_settings->getEntry("hide")) != 0) {

        if(!entry->hasValue()) conffile.missingValueException(entry);

        std::string hide_string = entry->getString();

        size_t sep;
        while((sep = hide_string.find(",")) != std::string::npos) {

            if(sep == 0 && hide_string.size()==1) break;

            if(sep == 0) {
                hide_string = hide_string.substr(sep+1, hide_string.size()-1);
                continue;
            }

            std::string hide_field  = hide_string.substr(0, sep);
            hide_fields.push_back(hide_field);
            hide_string = hide_string.substr(sep+1, hide_string.size()-1);
        }

        if(hide_string.size() > 0 && hide_string != ",") hide_fields.push_back(hide_string);

        //validate field list

        for(std::vector<std::string>::iterator it = hide_fields.begin(); it != hide_fields.end(); it++) {
            std::string hide_field = (*it);

            if(   hide_field != "date"
               && hide_field != "users"
               && hide_field != "tree"
               && hide_field != "files"
               && hide_field != "usernames"
               && hide_field != "filenames"
               && hide_field != "dirnames"
               && hide_field != "bloom"
               && hide_field != "progress"
               && hide_field != "mouse"
               && hide_field != "root") {
                std::string unknown_hide_option = std::string("unknown option hide ") + hide_field;
                conffile.entryException(entry, unknown_hide_option);
            }
        }
    }

    //check hide booleans
    for(std::map<std::string,std::string>::iterator it = arg_types.begin(); it != arg_types.end(); it++) {
        if(it->first.find("hide-") == 0 && it->second == "bool") {

            if(gource_settings->getBool(it->first)) {
                std::string hide_field = it->first.substr(5, it->first.size()-5);
                hide_fields.push_back(hide_field);
            }
        }
    }

    if(hide_fields.size()>0) {

        for(std::vector<std::string>::iterator it = hide_fields.begin(); it != hide_fields.end(); it++) {
            std::string hidestr = (*it);

                if(hidestr == "date")       hide_date      = true;
            else if(hidestr == "users")     hide_users     = true;
            else if(hidestr == "tree")      hide_tree      = true;
            else if(hidestr == "files")     hide_files     = true;
            else if(hidestr == "usernames") hide_usernames = true;
            else if(hidestr == "filenames") hide_filenames = true;
            else if(hidestr == "dirnames")  hide_dirnames  = true;
            else if(hidestr == "bloom")     hide_bloom     = true;
            else if(hidestr == "progress")  hide_progress  = true;
            else if(hidestr == "root")      hide_root      = true;
            else if(hidestr == "mouse")     {
                hide_mouse     = true;
                hide_progress  = true;
            }
        }
    }

    if((entry = gource_settings->getEntry("date-format")) != 0) {

        if(!entry->hasValue()) conffile.missingValueException(entry);

        date_format = entry->getString();
    }

    if(gource_settings->getBool("disable-auto-rotate")) {
        disable_auto_rotate=true;
    }

    if(gource_settings->getBool("disable-auto-skip")) {
        auto_skip_seconds = -1.0;
    }

    if(gource_settings->getBool("loop")) {
        loop = true;
    }

    if((entry = gource_settings->getEntry("git-branch")) != 0) {

        if(!entry->hasValue()) conffile.missingValueException(entry);

        git_branch = entry->getString();
    }

    if(gource_settings->getBool("colour-images")) {
        colour_user_images = true;
    }

    if((entry = gource_settings->getEntry("crop")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify crop (vertical,horizontal)");

        std::string crop = entry->getString();

        if(crop == "vertical") {
            crop_vertical = true;
        } else if (crop == "horizontal") {
            crop_horizontal = true;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("log-format")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify log-format (format)");

        log_format = entry->getString();

        if(log_format == "cvs") {
            conffile.entryException(entry, "please use either 'cvs2cl' or 'cvs-exp'");
        }

        if(   log_format != "git"
           && log_format != "cvs-exp"
           && log_format != "cvs2cl"
           && log_format != "svn"
           && log_format != "custom"
           && log_format != "hg"
           && log_format != "bzr"
           && log_format != "apache") {

            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("default-user-image")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify default-user-image (image path)");

        default_user_image = entry->getString();
    }

    if((entry = gource_settings->getEntry("user-image-dir")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-image-dir (directory)");

        user_image_dir = entry->getString();

        //append slash
        if(user_image_dir[user_image_dir.size()-1] != '/') {
            user_image_dir += std::string("/");
        }

        //get jpg and png images in dir
        DIR *dp;
        struct dirent *dirp;

        user_image_map.clear();

        if((dp = opendir(gGourceSettings.user_image_dir.c_str())) != 0) {

            while ((dirp = readdir(dp)) != 0) {
                std::string dirfile = std::string(dirp->d_name);

                size_t extpos = 0;

                if(   (extpos=dirfile.rfind(".jpg"))  == std::string::npos
                && (extpos=dirfile.rfind(".jpeg")) == std::string::npos
                && (extpos=dirfile.rfind(".png"))  == std::string::npos) continue;


                std::string image_path = gGourceSettings.user_image_dir + dirfile;
                std::string name       = dirfile.substr(0,extpos);

#ifdef __APPLE__
                CFMutableStringRef help = CFStringCreateMutable(kCFAllocatorDefault, 0);
                CFStringAppendCString(help, name.c_str(), kCFStringEncodingUTF8);
                CFStringNormalize(help, kCFStringNormalizationFormC);
                char data[4096];
                CFStringGetCString(help,
                                   data,
                                   sizeof(data),
                                   kCFStringEncodingUTF8);
                name = data;
#endif

                debugLog("%s => %s", name.c_str(), image_path.c_str());

                user_image_map[name] = image_path;
            }

            closedir(dp);
        }
    }

    if((entry = gource_settings->getEntry("caption-file")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption file (filename)");

        caption_file = entry->getString();
    }

    if((entry = gource_settings->getEntry("caption-duration")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption duration (seconds)");

        caption_duration = entry->getFloat();

        if(caption_duration <= 0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("caption-size")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption size");

        caption_size = entry->getInt();

        if(caption_size<1 || caption_size>100) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("caption-offset")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption offset");

        caption_offset = entry->getInt();
    }

    if((entry = gource_settings->getEntry("caption-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            caption_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            caption_colour = vec3(r,g,b);
            caption_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("bloom-intensity")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify bloom-intensity (float)");

        bloom_intensity = entry->getFloat();

        if(bloom_intensity<=0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("bloom-multiplier")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify bloom-multiplier (float)");

        bloom_multiplier = entry->getFloat();

        if(bloom_multiplier<=0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("elasticity")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify elasticity (float)");

        elasticity = entry->getFloat();

        if(elasticity<=0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("font-size")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify font size");

        font_size = entry->getInt();

        if(font_size<1 || font_size>100) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("hash-seed")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify hash seed (integer)");

        gStringHashSeed = entry->getInt();
    }

    if((entry = gource_settings->getEntry("font-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify font colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            font_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            font_colour = vec3(r,g,b);
            font_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("background-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify background colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            background_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            background_colour = vec3(r,g,b);
            background_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("highlight-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify highlight colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            highlight_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            highlight_colour = vec3(r,g,b);
            highlight_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("selection-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify selection colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            selection_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            selection_colour = vec3(r,g,b);
            selection_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("dir-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify dir colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            dir_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            dir_colour = vec3(r,g,b);
            dir_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("background-image")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify background image (image path)");

        background_image = entry->getString();
    }

    if((entry = gource_settings->getEntry("title")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify title");

        title = entry->getString();
    }

    if((entry = gource_settings->getEntry("logo")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify logo (image path)");

        logo = entry->getString();
    }

    if((entry = gource_settings->getEntry("logo-offset")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify logo-offset (XxY)");

        std::string logo_offset_str = entry->getString();

        int posx = 0;
        int posy = 0;

        if(parseRectangle(logo_offset_str, posx, posy)) {
            logo_offset = vec2(posx, posy);
        } else {
            conffile.invalidValueException(entry);
        }

    }

    if((entry = gource_settings->getEntry("seconds-per-day")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify seconds-per-day (seconds)");

        float seconds_per_day = entry->getFloat();

        if(seconds_per_day<=0.0f) {
            conffile.invalidValueException(entry);
        }

        // convert seconds-per-day to days-per-second
        days_per_second = 1.0 / seconds_per_day;
    }

    if((entry = gource_settings->getEntry("auto-skip-seconds")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify auto-skip-seconds (seconds)");

        auto_skip_seconds = entry->getFloat();

        if(auto_skip_seconds <= 0.0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("file-idle-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify file-idle-time (seconds)");

        std::string file_idle_str = entry->getString();

        file_idle_time = (float) atoi(file_idle_str.c_str());

        if(file_idle_time<0.0f || (file_idle_time == 0.0f && file_idle_str[0] != '0') ) {
            conffile.invalidValueException(entry);
        }
        if(file_idle_time==0.0f) {
            file_idle_time = 86400.0f;
        }
    }

    if((entry = gource_settings->getEntry("user-idle-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-idle-time (seconds)");

        user_idle_time = entry->getFloat();

        if(user_idle_time < 0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("time-scale")) != 0) {

        if(!entry->hasValue())
            conffile.entryException(entry, "specify time-scale (scale)");

        time_scale = entry->getFloat();

        if(time_scale <= 0.0f || time_scale > 4.0f) {
            conffile.entryException(entry, "time-scale outside of range 0.0 - 4.0");
        }
    }

    if((entry = gource_settings->getEntry("start-position")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify start-position (float,random)");

        if(entry->getString() == "random") {
            srand(time(0));
            start_position = (rand() % 1000) / 1000.0f;
        } else {
            start_position = entry->getFloat();

            if(start_position<=0.0 || start_position>=1.0) {
                conffile.entryException(entry, "start-position outside of range 0.0 - 1.0 (non-inclusive)");
            }
        }
    }

    if((entry = gource_settings->getEntry("stop-position")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify stop-position (float)");

        stop_position = entry->getFloat();

        if(stop_position<=0.0 || stop_position>1.0) {
            conffile.entryException(entry, "stop-position outside of range 0.0 - 1.0 (inclusive)");
        }
    }

    if((entry = gource_settings->getEntry("stop-at-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify stop-at-time (seconds)");

        stop_at_time = entry->getFloat();

        if(stop_at_time <= 0.0) {
            conffile.invalidValueException(entry);
        }
    }

    if(gource_settings->getBool("key")) {
        show_key = true;
    }

    if(gource_settings->getBool("ffp")) {
        ffp = true;
    }

    if(gource_settings->getBool("realtime")) {
        days_per_second = 1.0 / 86400.0;
    }

    if(gource_settings->getBool("dont-stop")) {
        dont_stop = true;
    }

    if(gource_settings->getBool("stop-at-end")) {
        stop_at_end = true;
    }

    //NOTE: this no longer does anything
    if(gource_settings->getBool("stop-on-idle")) {
        stop_on_idle = true;
    }

    if((entry = gource_settings->getEntry("max-files")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify max-files (number)");

        max_files = entry->getInt();

        if( max_files<0 || (max_files == 0 && entry->getString() != "0") ) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("max-file-lag")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify max-file-lag (seconds)");

        max_file_lag = entry->getFloat();

        if(max_file_lag==0.0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("user-friction")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-friction (seconds)");

        user_friction = entry->getFloat();

        if(user_friction<=0.0) {
            conffile.invalidValueException(entry);
        }

        user_friction = 1.0 / user_friction;
    }

    if((entry = gource_settings->getEntry("user-scale")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-scale (scale)");

        user_scale = entry->getFloat();

        if(user_scale<=0.0 || user_scale>100.0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("max-user-speed")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify max-user-speed (units)");

        max_user_speed = entry->getFloat();

        if(max_user_speed<=0) {
            conffile.invalidValueException(entry);
        }
    }

    if(   gource_settings->getBool("highlight-users")
       || gource_settings->getBool("highlight-all-users")) {
        highlight_all_users = true;
    }

    if(gource_settings->getBool("highlight-dirs")) {
        highlight_dirs = true;
    }

    if((entry = gource_settings->getEntry("camera-mode")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify camera-mode (overview,track)");

        camera_mode = entry->getString();

        if(camera_mode != "overview" && camera_mode != "track") {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("padding")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify padding (float)");

        padding = entry->getFloat();

        if(padding <= 0.0f || padding >= 2.0f) {
            conffile.invalidValueException(entry);
        }
    }

    // multi-value entries

    if((entry = gource_settings->getEntry("highlight-user")) != 0) {

        ConfEntryList* highlight_user_entries = gource_settings->getEntries("highlight-user");

        for(ConfEntryList::iterator it = highlight_user_entries->begin(); it != highlight_user_entries->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify highlight-user (user)");

            highlight_users.push_back(entry->getString());
        }
    }

    if((entry = gource_settings->getEntry("follow-user")) != 0) {

        ConfEntryList* follow_user_entries = gource_settings->getEntries("follow-user");

        for(ConfEntryList::iterator it = follow_user_entries->begin(); it != follow_user_entries->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify follow-user (user)");

            follow_users.push_back(entry->getString());
        }
    }

    if(gource_settings->getBool("file-extensions")) {
        file_extensions=true;
    }

    if((entry = gource_settings->getEntry("file-filter")) != 0) {

        ConfEntryList* filters = gource_settings->getEntries("file-filter");

        for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify file-filter (regex)");

            std::string filter_string = entry->getString();

            Regex* r = new Regex(filter_string, 1);

            if(!r->isValid()) {
                delete r;
                conffile.entryException(entry, "invalid file-filter regular expression");
            }

            file_filters.push_back(r);
        }
    }

    if((entry = gource_settings->getEntry("user-filter")) != 0) {

        ConfEntryList* filters = gource_settings->getEntries("user-filter");

        for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify user-filter (regex)");

            std::string filter_string = entry->getString();

            Regex* r = new Regex(filter_string, 1);

            if(!r->isValid()) {
                delete r;
                conffile.entryException(entry, "invalid user-filter regular expression");
            }

            user_filters.push_back(r);
        }
    }

    //validate path
    if(gource_settings->hasValue("path")) {
        path = gource_settings->getString("path");
        default_path = false;
    }

    if(path == "-") {

        if(log_format.size() == 0) {
            throw ConfFileException("log-format required when reading from STDIN", "", 0);
        }

#ifdef _WIN32
        DWORD available_bytes;
        HANDLE stdin_handle = GetStdHandle(STD_INPUT_HANDLE);

        while(PeekNamedPipe(stdin_handle, 0, 0, 0,
            &available_bytes, 0) && available_bytes==0 && !std::cin.fail()) {
            SDL_Delay(100);
        }
#else
        while(std::cin.peek() == EOF && !std::cin.fail()) SDL_Delay(100);
#endif

        std::cin.clear();
    }

    //remove trailing slash and check if path is a directory
    if(path.size() &&
    (path[path.size()-1] == '\\' || path[path.size()-1] == '/')) {
        path = path.substr(0,path.size()-1);
    }

#ifdef _WIN32
    //on windows, pre-open console window if we think this is a directory the
    //user is trying to open, as system() commands will create a console window
    //if there isn't one anyway.

    bool isdir = false;

    if(path.size()>0) {
        struct stat fileinfo;
        int rc = stat(path.c_str(), &fileinfo);

        if(rc==0 && fileinfo.st_mode & S_IFDIR) isdir = true;
    }

    if(path.size()==0 || isdir) {
        SDLAppCreateWindowsConsole();
    }
#endif
}
Ejemplo n.º 14
0
CFStringRef
SMBCreateNetBIOSName(CFStringRef proposedName)
{
    CFMutableStringRef  composedName;
    CFStringEncoding    codepage;
    CFIndex		    nconverted = 0;
    CFIndex		    nused = 0;

    uint8_t		    name_buffer[NetBIOS_NAME_LEN];

    if (proposedName == NULL) {
        return NULL;
    }

    codepage = getPrefsCodePage();

    composedName = CFStringCreateMutableCopy(kCFAllocatorDefault,
                   0, proposedName);
    if (!composedName) {
        return NULL;
    }
    CFStringTrimWhitespace(composedName);
    CFStringUppercase(composedName, CFLocaleGetSystem());

    nconverted = CFStringGetBytes(composedName,
                                  CFRangeMake(0,
                                          MIN((CFIndex)sizeof(name_buffer), CFStringGetLength(composedName))),
                                  codepage, 0 /* loss byte */, false /* no BOM */,
                                  name_buffer, sizeof(name_buffer), &nused);

    /* We expect the conversion above to always succeed, given that we
     * tried to remove anything that might not convert to a code page.
     */
    if (nconverted == 0) {
        char buf[256];

        buf[0] = '\0';
        CFStringGetCString(composedName, buf, sizeof(buf), kCFStringEncodingUTF8);
        SMBLogInfo("failed to compose a NetBIOS name string from '%s'",
                   ASL_LEVEL_DEBUG, buf);

        CFRelease(composedName);
        return NULL;
    }

    CFRelease(composedName);

    /* Null terminate for the benefit of CFStringCreate. Be careful to be
     * no more that 15 bytes, since the last byte is reserved for the name
     * type.
     */
    name_buffer[MIN(nused, (CFIndex)sizeof(name_buffer) - 1)] = '\0';

    composedName = CFStringCreateMutable(kCFAllocatorDefault,
                                         NetBIOS_NAME_LEN);
    if (composedName == NULL) {
        return NULL;
    }

    CFStringAppendCString(composedName, (const char *)name_buffer, codepage);
    return composedName;
}
Ejemplo n.º 15
0
Archivo: parse_url.c Proyecto: aosm/smb
/*
 * Check to make sure we have the correct user name and share. If we already have
 * both a username and share name then we are done, otherwise get the latest stuff.
 */
static void UpdateDictionaryWithUserAndShare(struct smb_ctx *ctx, CFMutableDictionaryRef mutableDict)
{
	CFStringRef DomainWrkgrp = NULL;
	CFStringRef Username = NULL;
	CFStringRef share = NULL;
	CFMutableStringRef path = NULL;
	
	Username = CFDictionaryGetValue(mutableDict, kNetFSUserNameKey);
	share = CFDictionaryGetValue(mutableDict, kNetFSPathKey);
	
	/* Everything we need is in the dictionary */
	if (share && Username) 
		return;
	
	/* Add the user name, if we have one */
	if (ctx->ct_setup.ioc_user[0]) {
		Username = CFStringCreateWithCString(NULL, ctx->ct_setup.ioc_user, kCFStringEncodingUTF8);
		if (ctx->ct_setup.ioc_domain[0])	/* They gave us a domain add it */
			DomainWrkgrp = CFStringCreateWithCString(NULL, ctx->ct_setup.ioc_domain, kCFStringEncodingUTF8);

		/* 
		 * We have a domain name so combined it with the user name. We now test 
		 * to make sure we have a username. Having a domain without a username 
		 * makes no sense, so don't return either.
		 */
		if (DomainWrkgrp && Username && CFStringGetLength(Username)) {
			CFMutableStringRef tempString = CFStringCreateMutableCopy(NULL, 0, DomainWrkgrp);
			
			if (tempString) {
				CFStringAppend(tempString, CFSTR("\\"));
				CFStringAppend(tempString, Username);
				CFRelease(Username);
				Username = tempString;
			}
		}
		if (DomainWrkgrp) {
			CFRelease(DomainWrkgrp);
		}
		if (Username)
		{
			CFDictionarySetValue (mutableDict, kNetFSUserNameKey, Username);
			CFRelease(Username);				
		}	
	}
	/* if we have a share then we are done */
	if (share || !ctx->ct_origshare)
		return;
	
	path = CFStringCreateMutable(NULL, 1024);
	/* Should never happen, but just to be safe */
	if (!path)
		return;
	
	CFStringAppendCString(path, ctx->ct_origshare, kCFStringEncodingUTF8);
	/* Add the path if we have one */
	if (ctx->mountPath) {
		CFStringAppend(path, CFSTR("/"));
		CFStringAppend(path, ctx->mountPath);		
	}
	CFDictionarySetValue (mutableDict, kNetFSPathKey, path);
	CFRelease(path);
}
Ejemplo n.º 16
0
void growl_init(void)
{

	struct Growl_Delegate * delegateObject;

	CFStringRef applicationName;
	CFStringRef identifierString;
	CFDataRef icon = NULL;
	CFMutableStringRef iconPath = CFStringCreateMutable(kCFAllocatorDefault, 0);
 	char *home = getenv( "HOME" );
	
	applicationName = CFSTR("growl-irssi");
	identifierString = NULL;

	CFStringAppendCString(iconPath, home, kCFStringEncodingUTF8);
	CFStringAppend(iconPath, CFSTR("/.irssi/irssi.icns"));
	
	icon = (CFDataRef)copyIconData(iconPath);
	
	CFSafeRelease(iconPath);
	// Can't register console app growl without icon data so don't even try
	g_return_if_fail(icon != NULL);
	
	CFStringRef name = NOTIFICATION_NAME;
	CFArrayRef defaultAndAllNotifications = CFArrayCreate(kCFAllocatorDefault, (const void **)&name, 1, &kCFTypeArrayCallBacks);
	CFTypeRef registerKeys[4] = {
		GROWL_APP_NAME,
		GROWL_NOTIFICATIONS_ALL,
		GROWL_NOTIFICATIONS_DEFAULT,
		GROWL_APP_ICON,
		// GROWL_APP_ID
	};
	CFTypeRef registerValues[4] = {
		applicationName,
		defaultAndAllNotifications,
		defaultAndAllNotifications,
		icon
	};
	
	CFDictionaryRef registerInfo = CFDictionaryCreate(kCFAllocatorDefault, registerKeys, registerValues, 4, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
	
	delegateObject = (struct Growl_Delegate *)calloc(1, sizeof(struct Growl_Delegate));
	delegateObject->applicationName = CFSTR("growl-irssi");
	delegateObject->registrationDictionary = registerInfo;
	delegateObject->applicationIconData = icon;
	
	
	Growl_SetDelegate(delegateObject);


	CFRelease(defaultAndAllNotifications);
	CFRelease(icon);
	CFRelease(applicationName);

	// Setup irssi
	signal_add_last("message private", (SIGNAL_FUNC) message_incoming);
	signal_add_last("message public", (SIGNAL_FUNC) message_public);
	command_bind("growlhelp", NULL, (SIGNAL_FUNC) command_helpgrowl);
	command_bind("helpgrowl", NULL, (SIGNAL_FUNC) command_helpgrowl);
	// Growl_NotifyWithTitleDescriptionNameIconPriorityStickyClickContext(CFSTR("growl-irssi"), CFSTR("Plugin successfully loaded."), NOTIFICATION_NAME, NULL,	0, FALSE, NULL);

	printtext(NULL, NULL, MSGLEVEL_CLIENTNOTICE,
		"Growl Support successfully loaded\n"
		"Try /helpgrowl or /growlhelp for a short command overview");

	module_register("growl", "core");	
}
Ejemplo n.º 17
0
static CFDictionaryRef __DAMountMapCreate1( CFAllocatorRef allocator, struct fstab * fs )
{
    CFMutableDictionaryRef map = NULL;

    if ( strcmp( fs->fs_type, FSTAB_SW ) )
    {
        char * idAsCString = fs->fs_spec;

        strsep( &idAsCString, "=" );

        if ( idAsCString )
        {
            CFStringRef idAsString;

            idAsString = CFStringCreateWithCString( kCFAllocatorDefault, idAsCString, kCFStringEncodingUTF8 );

            if ( idAsString )
            {
                CFTypeRef id = NULL;

                if ( strcmp( fs->fs_spec, "UUID" ) == 0 )
                {
                    id = ___CFUUIDCreateFromString( kCFAllocatorDefault, idAsString );
                }
                else if ( strcmp( fs->fs_spec, "LABEL" ) == 0 )
                {
                    id = CFRetain( idAsString );
                }
                else if ( strcmp( fs->fs_spec, "DEVICE" ) == 0 )
                {
                    id = ___CFDictionaryCreateFromXMLString( kCFAllocatorDefault, idAsString );
                }

                if ( id )
                {
                    map = CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks );

                    if ( map )
                    {
                        CFMutableStringRef options;

                        options = CFStringCreateMutable( kCFAllocatorDefault, 0 );

                        if ( options )
                        {
                            char *       argument  = NULL;
                            char *       arguments = fs->fs_mntops;
                            CFBooleanRef automatic = NULL;

                            while ( ( argument = strsep( &arguments, "," ) ) )
                            {
                                if ( strcmp( argument, "auto" ) == 0 )
                                {
                                    automatic = kCFBooleanTrue;
                                }
                                else if ( strcmp( argument, "noauto" ) == 0 )
                                {
                                    automatic = kCFBooleanFalse;
                                }
                                else
                                {
                                    CFStringAppendCString( options, argument, kCFStringEncodingUTF8 );    
                                    CFStringAppendCString( options, ",", kCFStringEncodingUTF8 );
                                }
                            }

                            if ( automatic )
                            {
                                CFDictionarySetValue( map, kDAMountMapMountAutomaticKey, automatic );
                            }

                            if ( CFStringGetLength( options ) )
                            {
                                CFStringTrim( options, CFSTR( "," ) );

                                CFDictionarySetValue( map, kDAMountMapMountOptionsKey, options );
                            }

                            CFRelease( options );
                        }

                        if ( strcmp( fs->fs_file, "none" ) )
                        {
                            CFURLRef path;

                            path = CFURLCreateFromFileSystemRepresentation( kCFAllocatorDefault, ( void * ) fs->fs_file, strlen( fs->fs_file ), TRUE );

                            if ( path )
                            {
                                CFDictionarySetValue( map, kDAMountMapMountPathKey, path );

                                CFRelease( path );
                            }
                        }

                        if ( strcmp( fs->fs_vfstype, "auto" ) )
                        {
                            CFStringRef kind;

                            kind = CFStringCreateWithCString( kCFAllocatorDefault, fs->fs_vfstype, kCFStringEncodingUTF8 );

                            if ( kind )
                            {
                                CFDictionarySetValue( map, kDAMountMapProbeKindKey, kind );

                                CFRelease( kind );
                            }
                        }

                        CFDictionarySetValue( map, kDAMountMapProbeIDKey, id );
                    }

                    CFRelease( id );
                }

                CFRelease( idAsString );
            }
        }
    }

    return map;
}
Ejemplo n.º 18
0
/* 
   Parses command line options for the VM options, properties,
   main class, and main class args and returns them in the VMLaunchOptions
   structure.
*/
VMLaunchOptions * NewVMLaunchOptions(int argc, const char **currentArg) 
{
    int ArgIndex = 0; 
    
    /* The following Strings are used to convert the command line -cp to -Djava.class.path= */
    CFStringRef classPathOption = CFSTR("-cp");
    CFStringRef classPathDefine = CFSTR("-Djava.class.path=");

    /* vmOptionsCFArrayRef will temporarly hold a list of VM options and properties to be passed in when
       creating the JVM
    */
    CFMutableArrayRef vmOptionsCFArrayRef = CFArrayCreateMutable(NULL,0,&kCFTypeArrayCallBacks);
    
    /* mainArgsCFArrayRef will temporarly hold a list of arguments to be passed to the main method of the
       main class
    */
    CFMutableArrayRef mainArgsCFArrayRef = CFArrayCreateMutable(NULL,0,&kCFTypeArrayCallBacks);

    /* Allocated the structure that will be used to return the launch options */
    VMLaunchOptions * vmLaunchOptions = malloc(sizeof(VMLaunchOptions));
    
    /* Start with the first arg, not the path to the tool */
    ArgIndex++;
    currentArg++;
    
    /* JVM options start with - */
    while(ArgIndex < argc && **currentArg == '-') {
        CFMutableStringRef option = CFStringCreateMutable(NULL, 0);
        CFStringAppendCString(option, *currentArg, kCFStringEncodingUTF8);
        
        /* If the option string is '-cp', replace it with '-Djava.class.path=' and append
            then next option which contains the actuall class path.
        */
        CFRange rangeToSearch = CFRangeMake(0,CFStringGetLength(option));
        if (CFStringFindAndReplace(option, classPathOption, classPathDefine, rangeToSearch, kCFCompareAnchored) != 0) {
            /* So the option was -cp, and we replaced it with -Djava.class.path= */
            /* Now append the next option which is the actuall class path */
            currentArg++;
            ArgIndex++;        
            if (ArgIndex < argc) {
                CFStringAppendCString(option, *currentArg, kCFStringEncodingUTF8);
            } else {
                /* We shouldn't reach here unless the last arg was -cp */
                fprintf(stderr, "[JavaAppLauncher Error] Error parsing class path.\n");
                /* Release the option CFString heresince the break; statement is going */
                /* to skip the release in this loop */
                CFRelease(option);
                break;
            }
        }

        /* Add this to our list of JVM options */
        CFArrayAppendValue(vmOptionsCFArrayRef,option);
        /* When an object is added to a CFArray the array retains a reference to it, this means */
        /* we need to release the object so that the memory will be freed when we release the CFArray. */
        CFRelease(option);

        /* On to the next one */
        currentArg++;
        ArgIndex++;        
    }
    
    /* Now we know how many JVM options there are and they are all in a CFArray of CFStrings. */
    vmLaunchOptions->nOptions = CFArrayGetCount(vmOptionsCFArrayRef);
    /* We only need to do this if there are options */
    if ( vmLaunchOptions->nOptions > 0) {
        int index;
        /* Allocate some memory for the array of JavaVMOptions */
        JavaVMOption * option = malloc(vmLaunchOptions->nOptions*sizeof(JavaVMOption));
        vmLaunchOptions->options = option;

        /* Itterate over each option adding it to the JavaVMOptions array */
        for(index = 0;index < vmLaunchOptions->nOptions; index++, option++) {
            /* Allocate enough memory for each optionString char* to hold the max possible lengh a UTF8 */
            /* encoded copy of the string would require */
            CFStringRef optionStringRef = (CFStringRef)CFArrayGetValueAtIndex(vmOptionsCFArrayRef,index);
            CFIndex optionStringSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(optionStringRef), kCFStringEncodingUTF8);
            option->extraInfo = NULL;
            option->optionString = malloc(optionStringSize+1);
            /* Now copy the option into the the optionString char* buffer in a UTF8 encoding */
            if (!CFStringGetCString(optionStringRef, (char *)option->optionString, optionStringSize, kCFStringEncodingUTF8)) {
                fprintf(stderr, "[JavaAppLauncher Error] Error parsing JVM options.\n");
                exit(-1);
            }
        }
        
    } else {
        vmLaunchOptions->options = NULL;
    }

    /* Now we know how many args for main there are and they are all in a CFArray of CFStrings. */
    vmLaunchOptions->numberOfArgs = CFArrayGetCount(mainArgsCFArrayRef);
    /* We only need to do this if there are args */
    if ( vmLaunchOptions->numberOfArgs > 0) {
        int index;
        char ** arg;
        /* Allocate some memory for the array of char *'s */
        vmLaunchOptions->args = malloc(vmLaunchOptions->numberOfArgs*sizeof(char *));
                
        for(index = 0, arg = vmLaunchOptions->args;index < vmLaunchOptions->numberOfArgs; index++, arg++)
        {
            /* Allocate enough memory for each arg char* to hold the max possible lengh a UTF8 */
            /* encoded copy of the string would require */
            CFStringRef argStringRef = (CFStringRef)CFArrayGetValueAtIndex(mainArgsCFArrayRef,index);
            CFIndex argStringSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(argStringRef), kCFStringEncodingUTF8);
            *arg = (char*)malloc(argStringSize+1);
            /* Now copy the arg into the the args char* buffer in a UTF8 encoding */
            if (!CFStringGetCString(argStringRef, *arg, argStringSize, kCFStringEncodingUTF8)) {
                fprintf(stderr, "[JavaAppLauncher Error] Error parsing args.\n");
                exit(-1);
            }
        }
        
    } else {
        vmLaunchOptions->args = NULL;
    }    
    /* Free the Array's holding our options and args */
    /* Releaseing an array also releases its references to the objects it contains */
    CFRelease(vmOptionsCFArrayRef);
    CFRelease(mainArgsCFArrayRef);
    return vmLaunchOptions;
}
Ejemplo n.º 19
0
static void target_setprefix(CFMutableStringRef inputstr, bool israw) {
    CFStringAppendCString(inputstr, israw ? "r" : "x", kCFStringEncodingUTF8);
}
Ejemplo n.º 20
0
/* Although named "prolog", for leafs of the tree, this is the only XML generation function called.  This is why Comments, Processing Instructions, etc. generate their XML during this function.  REW, 2/11/2000 */
static void _CFAppendXMLProlog(CFMutableStringRef str, const CFXMLTreeRef tree) {
    switch (CFXMLNodeGetTypeCode(CFXMLTreeGetNode(tree))) {
        case kCFXMLNodeTypeDocument:
            break;
        case kCFXMLNodeTypeElement:
            appendElementProlog(str, tree);
            break;
        case kCFXMLNodeTypeAttribute:
            // Should never be encountered
            break;
        case kCFXMLNodeTypeProcessingInstruction: {
            CFXMLProcessingInstructionInfo *data = (CFXMLProcessingInstructionInfo *)CFXMLNodeGetInfoPtr(CFXMLTreeGetNode(tree));
            if (data->dataString) {
                CFStringAppendFormat(str, NULL, CFSTR("<?%@ %@?>"), CFXMLNodeGetString(CFXMLTreeGetNode(tree)), data->dataString);
            } else {
                CFStringAppendFormat(str, NULL, CFSTR("<?%@?>"), CFXMLNodeGetString(CFXMLTreeGetNode(tree)));
            }
            break;
        }
        case kCFXMLNodeTypeComment:
            CFStringAppendFormat(str, NULL, CFSTR("<!--%@-->"), CFXMLNodeGetString(CFXMLTreeGetNode(tree)));
            break;
        case kCFXMLNodeTypeText:
            CFStringAppend(str, CFXMLNodeGetString(CFXMLTreeGetNode(tree)));
            break;
        case kCFXMLNodeTypeCDATASection:
            CFStringAppendFormat(str, NULL, CFSTR("<![CDATA[%@]]>"), CFXMLNodeGetString(CFXMLTreeGetNode(tree)));
            break;
        case kCFXMLNodeTypeDocumentFragment:
            break;
        case kCFXMLNodeTypeEntity: {
            CFXMLEntityInfo *data = (CFXMLEntityInfo *)CFXMLNodeGetInfoPtr(CFXMLTreeGetNode(tree));
            CFStringAppendCString(str, "<!ENTITY ", kCFStringEncodingASCII);
            if (data->entityType == kCFXMLEntityTypeParameter) {
                CFStringAppend(str, CFSTR("% "));
            }
            CFStringAppend(str, CFXMLNodeGetString(CFXMLTreeGetNode(tree)));
            CFStringAppend(str, CFSTR(" "));
            if (data->replacementText) {
                appendQuotedString(str, data->replacementText);
                CFStringAppendCString(str, ">", kCFStringEncodingASCII);
            } else {
                appendExternalID(str, &(data->entityID));
                if (data->notationName) {
                    CFStringAppendFormat(str, NULL, CFSTR(" NDATA %@"), data->notationName);
                }
                CFStringAppendCString(str, ">", kCFStringEncodingASCII);
            }
                break;
        }
        case kCFXMLNodeTypeEntityReference:
        {
            CFXMLEntityTypeCode entityType = ((CFXMLEntityReferenceInfo *)CFXMLNodeGetInfoPtr(CFXMLTreeGetNode(tree)))->entityType;
            if (entityType == kCFXMLEntityTypeParameter) {
                CFStringAppendFormat(str, NULL, CFSTR("%%%@;"), CFXMLNodeGetString(CFXMLTreeGetNode(tree)));
            } else {
                CFStringAppendFormat(str, NULL, CFSTR("&%@;"), CFXMLNodeGetString(CFXMLTreeGetNode(tree)));
            }
            break;
        }
        case kCFXMLNodeTypeDocumentType:
            CFStringAppendCString(str, "<!DOCTYPE ", kCFStringEncodingASCII);
            CFStringAppend(str, CFXMLNodeGetString(CFXMLTreeGetNode(tree)));
            if (CFXMLNodeGetInfoPtr(CFXMLTreeGetNode(tree))) {
                CFXMLExternalID *extID = &((CFXMLDocumentTypeInfo *)CFXMLNodeGetInfoPtr(CFXMLTreeGetNode(tree)))->externalID;
                appendExternalID(str, extID);
            }
                CFStringAppendCString(str, " [", kCFStringEncodingASCII);
            break;
        case kCFXMLNodeTypeWhitespace:
            CFStringAppend(str, CFXMLNodeGetString(CFXMLTreeGetNode(tree)));
            break;
        case kCFXMLNodeTypeNotation: {
            CFXMLNotationInfo *data = (CFXMLNotationInfo *)CFXMLNodeGetInfoPtr(CFXMLTreeGetNode(tree));
            CFStringAppendFormat(str, NULL, CFSTR("<!NOTATION %@ "), CFXMLNodeGetString(CFXMLTreeGetNode(tree)));
            appendExternalID(str, &(data->externalID));
                CFStringAppendCString(str, ">", kCFStringEncodingASCII);
            break;
        }
        case kCFXMLNodeTypeElementTypeDeclaration:
            CFStringAppendFormat(str, NULL, CFSTR("<!ELEMENT %@ %@>"), CFXMLNodeGetString(CFXMLTreeGetNode(tree)), ((CFXMLElementTypeDeclarationInfo *)CFXMLNodeGetInfoPtr(CFXMLTreeGetNode(tree)))->contentDescription);
            break;
        case kCFXMLNodeTypeAttributeListDeclaration: {
            CFXMLAttributeListDeclarationInfo *attListData = (CFXMLAttributeListDeclarationInfo *)CFXMLNodeGetInfoPtr(CFXMLTreeGetNode(tree));
            CFIndex idx;
            CFStringAppendCString(str, "<!ATTLIST ", kCFStringEncodingASCII);
            CFStringAppend(str, CFXMLNodeGetString(CFXMLTreeGetNode(tree)));
            for (idx = 0; idx < attListData->numberOfAttributes; idx ++) {
                CFXMLAttributeDeclarationInfo *attr = &(attListData->attributes[idx]);
                CFStringAppendFormat(str, NULL, CFSTR("\n\t%@ %@ %@"), attr->attributeName, attr->typeString, attr->defaultString);
            }
            CFStringAppendCString(str, ">", kCFStringEncodingASCII);
            break;
        }
        default:
            CFAssert1(false, __kCFLogAssertion, "Encountered unexpected XMLDataTypeID %d", CFXMLNodeGetTypeCode(CFXMLTreeGetNode(tree)));
    }
}
Ejemplo n.º 21
0
int main(int argc, char * argv[]) {
    signal(SIGINT, sigint_handler);

    bool israw = false;
    bool readstdin = false;
    char* code = NULL;
    bool usecolors = true;

    int ch;
    while ((ch = getopt(argc, argv, "nirc:t:sh")) != -1) {
        switch (ch) {
            case 'n': usecolors = false; break;
            case 'i': break;
            case 'r': israw = true; break;
            case 'c': code = optarg; break;
            case 't': recvTimeout = strtod(optarg, NULL); break;
            case 's': readstdin = true; break;
            case 'h': case '?': default:
                usage(argv[0]);
        }
    }

    if (optind != argc) usage(argv[0]);

    argc -= optind;
    argv += optind;

    CFMessagePortRef port = CFMessagePortCreateRemote(NULL, CFSTR("Hammerspoon"));

    if (!port) {
        fprintf(stderr, "error: can't access Hammerspoon; is it running with the ipc module loaded?\n");
        return 1;
    }

    CFMutableStringRef str = CFStringCreateMutable(NULL, 0);

    if (readstdin) {
        target_setprefix(str, israw);

        char buffer[BUFSIZ];
        while (fgets(buffer, BUFSIZ, stdin))
            CFStringAppendCString(str, buffer, kCFStringEncodingUTF8);

        if (ferror(stdin)) {
            perror("error reading from stdin.");
            exit(3);
        }

        target_send(port, str);
    }
    else if (code) {
        target_setprefix(str, israw);
        CFStringAppendCString(str, code, kCFStringEncodingUTF8);
        target_send(port, str);
    }
    else {
        if (usecolors)
            setupcolors();

        printf("%sHammerspoon interactive prompt.%s\n", COLOR_INITIAL, COLOR_RESET);

        while (1) {
            printf("\n%s", COLOR_INPUT);
            char* input = readline("> ");
            printf("%s", COLOR_RESET);
            if (!input) { printf("\n") ; exit(0); }
            add_history(input);

            if (!CFMessagePortIsValid(port)) {
                fprintf(stderr, "%sMessage port has become invalid.  Attempting to re-establish.%s\n", COLOR_INITIAL, COLOR_RESET);
                port = CFMessagePortCreateRemote(NULL, CFSTR("Hammerspoon"));
                if (!port) {
                    fprintf(stderr, "error: can't access Hammerspoon; is it running?\n");
                    exit(1);
                }

            }

            target_setprefix(str, israw);
            CFStringAppendCString(str, input, kCFStringEncodingUTF8);
            target_send(port, str);
            CFStringDelete(str, CFRangeMake(0, CFStringGetLength(str)));

            free(input);
        }
    }

    return 0;
}
int main(int argc, char **argv)
{
	bool quiet = false;
	bool doPause = false;
	
	int arg;
	while ((arg = getopt(argc, argv, "pqh")) != -1) {
		switch (arg) {
			case 'q':
				quiet = true;
				break;
			case 'p':
				doPause = true;
				break;
			case 'h':
				usage(argv);
		}
	}
	if(optind != argc) {
		usage(argv);
	}
	
	testStartBanner("certLabelTest", argc, argv);
	
	CSSM_CL_HANDLE	clHand = clStartup();
	CSSM_CSP_HANDLE cspHand = cspStartup();
	
	/* create a key pair */
	CSSM_RETURN crtn;
	CSSM_KEY pubKey;
	CSSM_KEY privKey;
	
	crtn = cspGenKeyPair(cspHand, KEY_ALG, 
		"someLabel", 8,
		KEY_SIZE,
		&pubKey, CSSM_FALSE, CSSM_KEYUSE_ANY, CSSM_KEYBLOB_RAW_FORMAT_NONE,
		&privKey, CSSM_FALSE, CSSM_KEYUSE_ANY, CSSM_KEYBLOB_RAW_FORMAT_NONE, 
		CSSM_FALSE);
	if(crtn) {
		printf("***Error generating RSA key pair. Aborting.\n");
		exit(1);
	}
	
	/* common params, reused for each test */
	notBefore = CB_BuildX509Time(0);
	notAfter = CB_BuildX509Time(100000);
	
	/* 
	 * Grind thru test cases.
	 */
	int ourRtn;
	
	/* very basic */
	ourRtn = doTest("simple ASCII common name", quiet, 
		cspHand, clHand, &privKey, &pubKey,
		"Simple Name", strlen("Simple Name"), BER_TAG_PRINTABLE_STRING, &CSSMOID_CommonName,
		NULL, 0, BER_TAG_UNKNOWN, NULL, 
		CFSTR("Simple Name"), true);
	if(ourRtn) {
		exit(1);
	}
	
	/* test concatentation of description */
	ourRtn = doTest("ASCII common name plus ASCII description", quiet, 
		cspHand, clHand, &privKey, &pubKey,
		"Simple Name", strlen("Simple Name"), BER_TAG_PRINTABLE_STRING, &CSSMOID_CommonName,
		"Description", strlen("Description"), BER_TAG_PRINTABLE_STRING, &CSSMOID_Description, 
		CFSTR("Simple Name (Description)"), false);
	if(ourRtn) {
		exit(1);
	}

	/* basic, specifying UTF8 (should be same as PRINTABLE) */
	ourRtn = doTest("simple UTF8 common name", quiet, 
		cspHand, clHand, &privKey, &pubKey,
		"Simple Name", strlen("Simple Name"), BER_TAG_PKIX_UTF8_STRING, &CSSMOID_CommonName,
		NULL, 0, BER_TAG_UNKNOWN, NULL, 
		CFSTR("Simple Name"), true);
	if(ourRtn) {
		exit(1);
	}

	/* label from org name instead of common name */
	ourRtn = doTest("label from OrgName", quiet, 
		cspHand, clHand, &privKey, &pubKey,
		"Simple Name", strlen("Simple Name"), BER_TAG_PRINTABLE_STRING, &CSSMOID_OrganizationName,
		NULL, 0, BER_TAG_UNKNOWN, NULL, 
		CFSTR("Simple Name"), false);
	if(ourRtn) {
		exit(1);
	}

	/* label from orgUnit name instead of common name */
	ourRtn = doTest("label from OrgUnit", quiet, 
		cspHand, clHand, &privKey, &pubKey,
		"Simple Name", strlen("Simple Name"), BER_TAG_PRINTABLE_STRING, &CSSMOID_OrganizationalUnitName,
		NULL, 0, BER_TAG_UNKNOWN, NULL, 
		CFSTR("Simple Name"), false);
	if(ourRtn) {
		exit(1);
	}

	/* label from orgUnit name, description is ignored (it's only used if the 
	 * label comes from CommonName) */
	ourRtn = doTest("label from OrgUnit, description is ignored", quiet, 
		cspHand, clHand, &privKey, &pubKey,
		"Simple Name", strlen("Simple Name"), BER_TAG_PRINTABLE_STRING, &CSSMOID_OrganizationalUnitName,
		"Description", strlen("Description"), BER_TAG_PRINTABLE_STRING, &CSSMOID_Description, 
		CFSTR("Simple Name"), false);
	if(ourRtn) {
		exit(1);
	}

	/* Radar 3529689: T61/Teletex, ISOLatin encoding, commonName only */
	CFStringRef t61Str = CFStringCreateWithBytes(NULL, JurgenPetersen, sizeof(JurgenPetersen),
				kCFStringEncodingISOLatin1, true);
	ourRtn = doTest("T61/Teletex name from Radar 3529689", quiet, 
		cspHand, clHand, &privKey, &pubKey,
		JurgenPetersen, sizeof(JurgenPetersen), BER_TAG_TELETEX_STRING, &CSSMOID_CommonName,
		NULL, 0, BER_TAG_UNKNOWN, NULL, 
		t61Str, true);
	if(ourRtn) {
		exit(1);
	}
	
	/* Now convert that ISOLatin into Unicode and try with that */
	CFDataRef unicodeStr = CFStringCreateExternalRepresentation(NULL, t61Str,
			kCFStringEncodingUnicode, 0);
	if(unicodeStr == NULL) {
		printf("***Error converting to Unicode\n");
		exit(1);
	}
	ourRtn = doTest("Unicode CommonName", quiet, 
		cspHand, clHand, &privKey, &pubKey,
		CFDataGetBytePtr(unicodeStr), CFDataGetLength(unicodeStr), 
				BER_TAG_PKIX_BMP_STRING, &CSSMOID_CommonName,
		NULL, 0, BER_TAG_UNKNOWN, NULL, 
		t61Str, true);
	if(ourRtn) {
		exit(1);
	}
	CFRelease(unicodeStr);
	
	/* Mix up ISOLatin Common Name and ASCII Description to ensure that the encodings
	 * of the two components are handled separately */
	CFMutableStringRef combo = CFStringCreateMutable(NULL, 0);
	CFStringAppend(combo, t61Str);
	CFStringAppendCString(combo, " (Description)", kCFStringEncodingASCII);
	ourRtn = doTest("ISOLatin Common Name and ASCII Description", quiet, 
		cspHand, clHand, &privKey, &pubKey,
		JurgenPetersen, sizeof(JurgenPetersen), BER_TAG_TELETEX_STRING, &CSSMOID_CommonName,
		"Description", strlen("Description"), BER_TAG_PRINTABLE_STRING, &CSSMOID_Description, 
		combo, false);
	if(ourRtn) {
		exit(1);
	}
	CFRelease(combo);
	CFRelease(t61Str);
				
	if(doPause) {
		fpurge(stdin);
		printf("Pausing for leaks testing; CR to continue: ");
		getchar();
	}
	if(!quiet) {
		printf("...success\n");
	}
	return 0;
}
Ejemplo n.º 23
0
static kern_return_t
IOFindPlugIns( io_service_t service,
               CFUUIDRef pluginType,
               CFArrayRef * factories, CFArrayRef * plists )
{
    CFURLRef		url;
    CFPlugInRef		onePlugin;
    CFBundleRef		bundle;
    CFDictionaryRef	plist;
    CFDictionaryRef	matching;
    CFDictionaryRef	pluginTypes;
    CFMutableStringRef	path;
    LookUUIDContext	context;
    CFStringRef		pluginName;
    boolean_t		matches;
    kern_return_t	kr = kIOReturnSuccess;
    
    // -- loadables
    onePlugin 		= NULL;
    pluginName		= NULL;
    path 		= NULL;
    url 		= NULL;

    do {

        pluginTypes = IORegistryEntryCreateCFProperty( service, CFSTR(kIOCFPlugInTypesKey),
                                            kCFAllocatorDefault, kNilOptions );
        if( !pluginTypes )
            continue;

        // look up UUID key this way - otherwise string case matters
//        CFShow( pluginTypes );
        context.key = pluginType;
        context.result = 0;
        CFDictionaryApplyFunction( pluginTypes, &_IOGetWithUUIDKey, &context);
        pluginName = (CFStringRef) context.result;
        if( !pluginName)
            continue;

        path = CFStringCreateMutable( kCFAllocatorDefault, 0 );
        if( !path)
            continue;
        CFStringAppendCString(path,
                            "/System/Library/Extensions/",
                            kCFStringEncodingMacRoman);
        CFStringAppend(path, pluginName);
        url = CFURLCreateWithFileSystemPath(NULL, path,
                        kCFURLPOSIXPathStyle, TRUE);
        if( !url)
            continue;

        onePlugin = CFPlugInCreate(NULL, url);

    } while( false );

//    if (pluginName && (!onePlugin))
//        printf("Could not create CFPluginRef.\n");

    if( url)
        CFRelease( url );
    if( path)
        CFRelease( path );
    if( pluginTypes )
        CFRelease( pluginTypes );
    // --

    if( onePlugin
        && (bundle = CFPlugInGetBundle(onePlugin))
        && (plist = CFBundleGetInfoDictionary(bundle))
        && (matching = (CFDictionaryRef)
            CFDictionaryGetValue(plist, CFSTR("Personality")))) {

        kr = IOServiceMatchPropertyTable( service, matching, &matches);
        if( kr != kIOReturnSuccess)
            matches = FALSE;
    } else
        matches = TRUE;

    if( matches) {
        if( onePlugin)
            *factories = CFPlugInFindFactoriesForPlugInTypeInPlugIn(pluginType, onePlugin);
        else
            *factories = 0;//CFPlugInFindFactoriesForPlugInType(pluginType);
    } else
        *factories = 0;

    *plists = 0;

    return( kr );
}
Ejemplo n.º 24
0
void GourceSettings::importGourceSettings(ConfFile& conffile, ConfSection* gource_settings) {

    setGourceDefaults();

    if(gource_settings == 0) gource_settings = conffile.getSection(default_section_name);

    if(gource_settings == 0) {
        gource_settings = conffile.addSection("gource");
    }

    ConfEntry* entry = 0;

    //hide flags

    std::vector<std::string> hide_fields;

    if((entry = gource_settings->getEntry("hide")) != 0) {

        if(!entry->hasValue()) conffile.missingValueException(entry);

        std::string hide_string = entry->getString();

        size_t sep;
        while((sep = hide_string.find(",")) != std::string::npos) {

            if(sep == 0 && hide_string.size()==1) break;

            if(sep == 0) {
                hide_string = hide_string.substr(sep+1, hide_string.size()-1);
                continue;
            }

            std::string hide_field  = hide_string.substr(0, sep);
            hide_fields.push_back(hide_field);
            hide_string = hide_string.substr(sep+1, hide_string.size()-1);
        }

        if(hide_string.size() > 0 && hide_string != ",") hide_fields.push_back(hide_string);

        //validate field list

        for(std::vector<std::string>::iterator it = hide_fields.begin(); it != hide_fields.end(); it++) {
            std::string hide_field = (*it);

            if(   hide_field != "date"
               && hide_field != "users"
               && hide_field != "tree"
               && hide_field != "files"
               && hide_field != "usernames"
               && hide_field != "filenames"
               && hide_field != "dirnames"
               && hide_field != "bloom"
               && hide_field != "progress"
               && hide_field != "mouse"
               && hide_field != "root") {
                std::string unknown_hide_option = std::string("unknown option hide ") + hide_field;
                conffile.entryException(entry, unknown_hide_option);
            }
        }
    }

    //check hide booleans
    for(std::map<std::string,std::string>::iterator it = arg_types.begin(); it != arg_types.end(); it++) {
        if(it->first.find("hide-") == 0 && it->second == "bool") {

            if(gource_settings->getBool(it->first)) {
                std::string hide_field = it->first.substr(5, it->first.size()-5);
                hide_fields.push_back(hide_field);
            }
        }
    }

    if(hide_fields.size()>0) {

        for(std::vector<std::string>::iterator it = hide_fields.begin(); it != hide_fields.end(); it++) {
            std::string hidestr = (*it);

                if(hidestr == "date")       hide_date      = true;
            else if(hidestr == "users")     hide_users     = true;
            else if(hidestr == "tree")      hide_tree      = true;
            else if(hidestr == "files")     hide_files     = true;
            else if(hidestr == "usernames") hide_usernames = true;
            else if(hidestr == "filenames") hide_filenames = true;
            else if(hidestr == "dirnames")  hide_dirnames  = true;
            else if(hidestr == "bloom")     hide_bloom     = true;
            else if(hidestr == "progress")  hide_progress  = true;
            else if(hidestr == "root")      hide_root      = true;
            else if(hidestr == "mouse")     {
                hide_mouse     = true;
                hide_progress  = true;
            }
        }
    }

    if((entry = gource_settings->getEntry("date-format")) != 0) {

        if(!entry->hasValue()) conffile.missingValueException(entry);

        date_format = entry->getString();
    }

    if(gource_settings->getBool("disable-auto-rotate")) {
        disable_auto_rotate=true;
    }

    if(gource_settings->getBool("disable-auto-skip")) {
        auto_skip_seconds = -1.0;
    }

    if(gource_settings->getBool("loop")) {
        loop = true;
    }

    if((entry = gource_settings->getEntry("git-branch")) != 0) {

        if(!entry->hasValue()) conffile.missingValueException(entry);

        Regex branch_regex("^(?!-)[/\\w.,;_=+{}\\[\\]-]+$");

        std::string branch = entry->getString();

        if(branch_regex.match(branch)) {
            git_branch = branch;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if(gource_settings->getBool("colour-images")) {
        colour_user_images = true;
    }

    if((entry = gource_settings->getEntry("crop")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify crop (vertical,horizontal)");

        std::string crop = entry->getString();

        if(crop == "vertical") {
            crop_vertical = true;
        } else if (crop == "horizontal") {
            crop_horizontal = true;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("log-format")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify log-format (format)");

        log_format = entry->getString();

        if(log_format == "cvs") {
            conffile.entryException(entry, "please use either 'cvs2cl' or 'cvs-exp'");
        }

        if(   log_format != "git"
           && log_format != "cvs-exp"
           && log_format != "cvs2cl"
           && log_format != "svn"
           && log_format != "custom"
           && log_format != "hg"
           && log_format != "bzr"
           && log_format != "apache") {

            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("default-user-image")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify default-user-image (image path)");

        default_user_image = entry->getString();
    }

    if((entry = gource_settings->getEntry("user-image-dir")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-image-dir (directory)");

        user_image_dir = entry->getString();

        //append slash
        if(user_image_dir[user_image_dir.size()-1] != '/') {
            user_image_dir += std::string("/");
        }

        user_image_map.clear();

        boost::filesystem::path image_dir_path(user_image_dir);

        if(!is_directory(image_dir_path)) {
             conffile.entryException(entry, "specified user-image-dir is not a directory");
        }

        std::vector<boost::filesystem::path> image_dir_files;

        try {
            copy(boost::filesystem::directory_iterator(image_dir_path), boost::filesystem::directory_iterator(), back_inserter(image_dir_files));
        } catch(const boost::filesystem::filesystem_error& exception) {
             conffile.entryException(entry, "error reading specified user-image-dir");
        }

        for(boost::filesystem::path& p : image_dir_files) {

            std::string dirfile;

#ifdef _WIN32
            std::wstring dirfile_16 = p.filename().wstring();
            utf8::utf16to8(dirfile_16.begin(), dirfile_16.end(), back_inserter(dirfile));
#else
            dirfile = p.filename().string();
#endif
            std::string file_ext = extension(p);
            boost::algorithm::to_lower(file_ext);

            if(file_ext != ".jpg" && file_ext != ".jpeg" && file_ext != ".png") continue;

            std::string image_path = gGourceSettings.user_image_dir + dirfile;
            std::string name       = dirfile.substr(0,dirfile.size() - file_ext.size());

#ifdef __APPLE__
                CFMutableStringRef help = CFStringCreateMutable(kCFAllocatorDefault, 0);
                CFStringAppendCString(help, name.c_str(), kCFStringEncodingUTF8);
                CFStringNormalize(help, kCFStringNormalizationFormC);
                char data[4096];
                CFStringGetCString(help,
                                   data,
                                   sizeof(data),
                                   kCFStringEncodingUTF8);
                name = data;
#endif

            debugLog("%s => %s", name.c_str(), image_path.c_str());

            user_image_map[name] = image_path;
        }
    }

    if((entry = gource_settings->getEntry("caption-file")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption file (filename)");

        caption_file = entry->getString();

        if(!boost::filesystem::exists(caption_file)) {
            conffile.entryException(entry, "caption file not found");
        }
    }

    if((entry = gource_settings->getEntry("caption-duration")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption duration (seconds)");

        caption_duration = entry->getFloat();

        if(caption_duration <= 0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("caption-size")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption size");

        caption_size = entry->getInt();

        if(caption_size<1 || caption_size>100) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("caption-offset")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption offset");

        caption_offset = entry->getInt();
    }

    if((entry = gource_settings->getEntry("caption-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            caption_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            caption_colour = vec3(r,g,b);
            caption_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("filename-colour")) != 0) {
        if(!entry->hasValue()) conffile.entryException(entry, "specify filename colour (FFFFFF)");

	int r,g,b;

	std::string colstring = entry->getString();

	if(entry->isVec3()) {
	    filename_colour = entry->getVec3();
	} else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            filename_colour = vec3(r,g,b);
            filename_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("filename-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify duration to keep files on screen (float)");

        filename_time = entry->getFloat();

        if(filename_time<2.0f) {
            conffile.entryException(entry, "filename-time must be >= 2.0");
        }
    }

    if((entry = gource_settings->getEntry("bloom-intensity")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify bloom-intensity (float)");

        bloom_intensity = entry->getFloat();

        if(bloom_intensity<=0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("bloom-multiplier")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify bloom-multiplier (float)");

        bloom_multiplier = entry->getFloat();

        if(bloom_multiplier<=0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("elasticity")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify elasticity (float)");

        elasticity = entry->getFloat();

        if(elasticity<=0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("font-size")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify font size");

        font_size = entry->getInt();

        if(font_size<1 || font_size>100) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("hash-seed")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify hash seed (integer)");

        gStringHashSeed = entry->getInt();
    }

    if((entry = gource_settings->getEntry("font-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify font colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            font_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            font_colour = vec3(r,g,b);
            font_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("background-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify background colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            background_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            background_colour = vec3(r,g,b);
            background_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("highlight-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify highlight colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            highlight_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            highlight_colour = vec3(r,g,b);
            highlight_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("selection-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify selection colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            selection_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            selection_colour = vec3(r,g,b);
            selection_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("dir-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify dir colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            dir_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            dir_colour = vec3(r,g,b);
            dir_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("background-image")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify background image (image path)");

        background_image = entry->getString();
    }

    if((entry = gource_settings->getEntry("title")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify title");

        title = entry->getString();
    }

    if((entry = gource_settings->getEntry("logo")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify logo (image path)");

        logo = entry->getString();
    }

    if((entry = gource_settings->getEntry("logo-offset")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify logo-offset (XxY)");

        std::string logo_offset_str = entry->getString();

        int posx = 0;
        int posy = 0;

        if(parseRectangle(logo_offset_str, posx, posy)) {
            logo_offset = vec2(posx, posy);
        } else {
            conffile.invalidValueException(entry);
        }

    }

    if((entry = gource_settings->getEntry("seconds-per-day")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify seconds-per-day (seconds)");

        float seconds_per_day = entry->getFloat();

        if(seconds_per_day<=0.0f) {
            conffile.invalidValueException(entry);
        }

        // convert seconds-per-day to days-per-second
        days_per_second = 1.0 / seconds_per_day;
    }

    if((entry = gource_settings->getEntry("auto-skip-seconds")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify auto-skip-seconds (seconds)");

        auto_skip_seconds = entry->getFloat();

        if(auto_skip_seconds <= 0.0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("file-idle-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify file-idle-time (seconds)");

        std::string file_idle_str = entry->getString();

        file_idle_time = (float) atoi(file_idle_str.c_str());

        if(file_idle_time<0.0f || (file_idle_time == 0.0f && file_idle_str[0] != '0') ) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("user-idle-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-idle-time (seconds)");

        user_idle_time = entry->getFloat();

        if(user_idle_time < 0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("time-scale")) != 0) {

        if(!entry->hasValue())
            conffile.entryException(entry, "specify time-scale (scale)");

        time_scale = entry->getFloat();

        if(time_scale <= 0.0f || time_scale > 4.0f) {
            conffile.entryException(entry, "time-scale outside of range 0.0 - 4.0");
        }
    }

    if((entry = gource_settings->getEntry("start-date")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify start-date (YYYY-MM-DD hh:mm:ss)");

        std::string start_date_string = entry->getString();

        if(parseDateTime(start_date_string, start_timestamp)) {

            char datestr[256];
            strftime(datestr, 256, "%Y-%m-%d", localtime ( &start_timestamp ));
            start_date = datestr;

        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("stop-date")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify stop-date (YYYY-MM-DD hh:mm:ss)");

        std::string end_date_string = entry->getString();

        if(parseDateTime(end_date_string, stop_timestamp)) {

            struct tm * timeinfo;
            timeinfo = localtime ( &stop_timestamp );

            time_t stop_timestamp_rounded = stop_timestamp;

            if(timeinfo->tm_hour > 0 || timeinfo->tm_min > 0 || timeinfo->tm_sec > 0) {
                stop_timestamp_rounded += 60*60*24;
            }

            char datestr[256];
            strftime(datestr, 256, "%Y-%m-%d", localtime ( &stop_timestamp_rounded ));
            stop_date = datestr;

        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("start-position")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify start-position (float,random)");

        if(entry->getString() == "random") {
            srand(time(0));
            start_position = (rand() % 1000) / 1000.0f;
        } else {
            start_position = entry->getFloat();

            if(start_position<=0.0 || start_position>=1.0) {
                conffile.entryException(entry, "start-position outside of range 0.0 - 1.0 (non-inclusive)");
            }
        }
    }

    if((entry = gource_settings->getEntry("stop-position")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify stop-position (float)");

        stop_position = entry->getFloat();

        if(stop_position<=0.0 || stop_position>1.0) {
            conffile.entryException(entry, "stop-position outside of range 0.0 - 1.0 (inclusive)");
        }
    }

    if((entry = gource_settings->getEntry("stop-at-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify stop-at-time (seconds)");

        stop_at_time = entry->getFloat();

        if(stop_at_time <= 0.0) {
            conffile.invalidValueException(entry);
        }
    }

    if(gource_settings->getBool("key")) {
        show_key = true;
    }

    if(gource_settings->getBool("ffp")) {
        ffp = true;
    }

    if(gource_settings->getBool("realtime")) {
        days_per_second = 1.0 / 86400.0;
    }

    if(gource_settings->getBool("no-time-travel")) {
        no_time_travel = true;
    }

    if(gource_settings->getBool("dont-stop")) {
        dont_stop = true;
    }

    if(gource_settings->getBool("stop-at-end")) {
        stop_at_end = true;
    }

    //NOTE: this no longer does anything
    if(gource_settings->getBool("stop-on-idle")) {
        stop_on_idle = true;
    }

    if((entry = gource_settings->getEntry("max-files")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify max-files (number)");

        max_files = entry->getInt();

        if( max_files<0 || (max_files == 0 && entry->getString() != "0") ) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("max-file-lag")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify max-file-lag (seconds)");

        max_file_lag = entry->getFloat();

        if(max_file_lag==0.0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("user-friction")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-friction (seconds)");

        user_friction = entry->getFloat();

        if(user_friction<=0.0) {
            conffile.invalidValueException(entry);
        }

        user_friction = 1.0 / user_friction;
    }

    if((entry = gource_settings->getEntry("user-scale")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-scale (scale)");

        user_scale = entry->getFloat();

        if(user_scale<=0.0 || user_scale>100.0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("max-user-speed")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify max-user-speed (units)");

        max_user_speed = entry->getFloat();

        if(max_user_speed<=0) {
            conffile.invalidValueException(entry);
        }
    }

    if(   gource_settings->getBool("highlight-users")
       || gource_settings->getBool("highlight-all-users")) {
        highlight_all_users = true;
    }

    if(gource_settings->getBool("highlight-dirs")) {
        highlight_dirs = true;
    }

    if((entry = gource_settings->getEntry("camera-mode")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify camera-mode (overview,track)");

        camera_mode = entry->getString();

        if(camera_mode != "overview" && camera_mode != "track") {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("padding")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify padding (float)");

        padding = entry->getFloat();

        if(padding <= 0.0f || padding >= 2.0f) {
            conffile.invalidValueException(entry);
        }
    }

    // multi-value entries

    if((entry = gource_settings->getEntry("highlight-user")) != 0) {

        ConfEntryList* highlight_user_entries = gource_settings->getEntries("highlight-user");

        for(ConfEntryList::iterator it = highlight_user_entries->begin(); it != highlight_user_entries->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify highlight-user (user)");

            highlight_users.push_back(entry->getString());
        }
    }

    if((entry = gource_settings->getEntry("follow-user")) != 0) {

        ConfEntryList* follow_user_entries = gource_settings->getEntries("follow-user");

        for(ConfEntryList::iterator it = follow_user_entries->begin(); it != follow_user_entries->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify follow-user (user)");

            follow_users.push_back(entry->getString());
        }
    }

    if(gource_settings->getBool("file-extensions")) {
        file_extensions=true;
    }

    if(gource_settings->getBool("file-extension-fallback")) {
        file_extension_fallback=true;
    }

    if((entry = gource_settings->getEntry("file-filter")) != 0) {

        ConfEntryList* filters = gource_settings->getEntries("file-filter");

        for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify file-filter (regex)");

            std::string filter_string = entry->getString();

            Regex* r = new Regex(filter_string, 1);

            if(!r->isValid()) {
                delete r;
                conffile.entryException(entry, "invalid file-filter regular expression");
            }

            file_filters.push_back(r);
        }
    }

    if((entry = gource_settings->getEntry("file-show-filter")) != 0) {

        ConfEntryList* filters = gource_settings->getEntries("file-show-filter");

        for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify file-show-filter (regex)");

            std::string filter_string = entry->getString();

            Regex* r = new Regex(filter_string, 1);

            if(!r->isValid()) {
                delete r;
                conffile.entryException(entry, "invalid file-show-filter regular expression");
            }

            file_show_filters.push_back(r);
        }
    }

    if((entry = gource_settings->getEntry("user-filter")) != 0) {

        ConfEntryList* filters = gource_settings->getEntries("user-filter");

        for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify user-filter (regex)");

            std::string filter_string = entry->getString();

            Regex* r = new Regex(filter_string, 1);

            if(!r->isValid()) {
                delete r;
                conffile.entryException(entry, "invalid user-filter regular expression");
            }

            user_filters.push_back(r);
        }
    }

    if((entry = gource_settings->getEntry("user-show-filter")) != 0) {

        ConfEntryList* filters = gource_settings->getEntries("user-show-filter");

        for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify user-show-filter (regex)");

            std::string filter_string = entry->getString();

            Regex* r = new Regex(filter_string, 1);

            if(!r->isValid()) {
                delete r;
                conffile.entryException(entry, "invalid user-show-filter regular expression");
            }

            user_show_filters.push_back(r);
        }
    }

    if((entry = gource_settings->getEntry("dir-name-depth")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify dir-name-depth (depth)");

        dir_name_depth = entry->getInt();

        if(dir_name_depth <= 0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("dir-name-position")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify dir-name-position (float)");

        dir_name_position = entry->getFloat();

        if(dir_name_position < 0.1f || dir_name_position > 1.0f) {
            conffile.entryException(entry, "dir-name-position outside of range 0.1 - 1.0 (inclusive)");
        }
    }

    //validate path
    if(gource_settings->hasValue("path")) {
        path = gource_settings->getString("path");
        default_path = false;
    }

    if(path == "-") {

        if(log_format.size() == 0) {
            throw ConfFileException("log-format required when reading from STDIN", "", 0);
        }

#ifdef _WIN32
        DWORD available_bytes;
        HANDLE stdin_handle = GetStdHandle(STD_INPUT_HANDLE);

        while(PeekNamedPipe(stdin_handle, 0, 0, 0,
            &available_bytes, 0) && available_bytes==0 && !std::cin.fail()) {
            SDL_Delay(100);
        }
#else
        while(std::cin.peek() == EOF && !std::cin.fail()) SDL_Delay(100);
#endif

        std::cin.clear();

    } else if(!path.empty() && path != ".") {

        //remove trailing slash
        if(path[path.size()-1] == '\\' || path[path.size()-1] == '/') {
            path.resize(path.size()-1);
        }

        // check path exists
        if(!boost::filesystem::exists(path)) {
            throw ConfFileException(str(boost::format("'%s' does not appear to be a valid file or directory") % path), "", 0);
        }
    }
}
Ejemplo n.º 25
0
int main(int argc, const char *argv[]) {
    // http://developer.apple.com/library/IOs/#documentation/CoreFoundation/Conceptual/CFStrings/Articles/MutableStrings.html
    int i;
    CFMutableStringRef args = CFStringCreateMutable(NULL, 0);
    CFStringEncoding encoding = CFStringGetSystemEncoding();
    CFStringAppend(args, CFSTR("starting screenresolution argv="));
    for (i = 0 ; i < argc ; i++) {
        CFStringAppendCString(args, argv[i], encoding);
        // If I were so motivated, I'd probably use CFStringAppendFormat
        CFStringAppend(args, CFSTR(" "));
    }
    // This has security implications.  Will look at that later
    NSLog(CFSTR("%@"), args);
    unsigned int exitcode = 0;

    if (argc > 1) {
        int d;
        int keepgoing = 1;
        CGError rc;
        uint32_t displayCount = 0;
        uint32_t activeDisplayCount = 0;
        CGDirectDisplayID *activeDisplays = NULL;

        rc = CGGetActiveDisplayList(0, NULL, &activeDisplayCount);
        if (rc != kCGErrorSuccess) {
            NSLog(CFSTR("%s"), "Error: failed to get list of active displays");
            return 1;
        }
        // Allocate storage for the next CGGetActiveDisplayList call
        activeDisplays = (CGDirectDisplayID *) malloc(activeDisplayCount * sizeof(CGDirectDisplayID));
        if (activeDisplays == NULL) {
            NSLog(CFSTR("s"), "Error: could not allocate memory for display list");
            return 1;
        }
        rc = CGGetActiveDisplayList(activeDisplayCount, activeDisplays, &displayCount);
        if (rc != kCGErrorSuccess) {
            NSLog(CFSTR("%s"), "Error: failed to get list of active displays");
            return 1;
        }

        // This loop should probably be in another function.
        for (d = 0; d < displayCount && keepgoing; d++) {
            if (strcmp(argv[1], "get") == 0) {
                if (!listCurrentMode(activeDisplays[d], d)) {
                    exitcode++;
                }
            } else if (strcmp(argv[1], "list") == 0) {
                if (!listAvailableModes(activeDisplays[d], d)) {
                    exitcode++;
                }
            } else if (strcmp(argv[1], "set") == 0) {
                if (d < (argc - 2)) {
                    if (strcmp(argv[d+2], "skip") == 0 && d < (argc - 2)) {
                        printf("Skipping display %d\n", d);
                    } else {
                        struct config newConfig;
                        if (parseStringConfig(argv[d + 2], &newConfig)) {
                            if (!configureDisplay(activeDisplays[d], &newConfig, d)) {
                                exitcode++;
                            }
                        } else {
                            exitcode++;
                        }
                    }
                }
            } else if (strcmp(argv[1], "-version") == 0) {
                printf("screenresolution version %s\nLicensed under GPLv2\n", VERSION);
                keepgoing = 0;
            } else {
                NSLog(CFSTR("I'm sorry %s. I'm afraid I can't do that"), getlogin());
                exitcode++;
                keepgoing = 0;
            }
        }
        free(activeDisplays);
        activeDisplays = NULL;
    } else {
        NSLog(CFSTR("%s"), "Incorrect command line");
        exitcode++;
    }
    return exitcode > 0;
}
static
CFArrayRef _SecIdentityCopyPossiblePaths(
    CFStringRef name)
{
    // utility function to build and return an array of possible paths for the given name.
    // if name is not a URL, this returns a single-element array.
    // if name is a URL, the array may contain 1..N elements, one for each level of the path hierarchy.

    CFMutableArrayRef names = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
    if (!name) {
        return names;
    }
    CFIndex oldLength = CFStringGetLength(name);
    CFArrayAppendValue(names, name);

    CFURLRef url = CFURLCreateWithString(NULL, name, NULL);
    if (url) {
		if (CFURLCanBeDecomposed(url)) {
			// first, remove the query portion of this URL, if any
			CFStringRef qs = CFURLCopyQueryString(url, NULL);
			if (qs) {
				CFMutableStringRef newName = CFStringCreateMutableCopy(NULL, oldLength, name);
				if (newName) {
					CFIndex qsLength = CFStringGetLength(qs) + 1; // include the '?'
					CFStringDelete(newName, CFRangeMake(oldLength-qsLength, qsLength));
					CFRelease(url);
					url = CFURLCreateWithString(NULL, newName, NULL);
					CFArraySetValueAtIndex(names, 0, newName);
					CFRelease(newName);
				}
				CFRelease(qs);
			}
			// now add an entry for each level of the path
			while (url) {
				CFURLRef parent = CFURLCreateCopyDeletingLastPathComponent(NULL, url);
				if (parent) {
					CFStringRef parentURLString = CFURLGetString(parent);
					if (parentURLString) {
						CFIndex newLength = CFStringGetLength(parentURLString);
						// check that string length has decreased as expected; for file URLs,
						// CFURLCreateCopyDeletingLastPathComponent can insert './' or '../'
						if ((newLength >= oldLength) || (!CFStringHasPrefix(name, parentURLString))) {
							CFRelease(parent);
							CFRelease(url);
							break;
						}
						oldLength = newLength;
						CFArrayAppendValue(names, parentURLString);
					}
				}
				CFRelease(url);
				url = parent;
			}
		}
		else {
			CFRelease(url);
		}
	}
	// finally, add wildcard entries for each subdomain
	url = CFURLCreateWithString(NULL, name, NULL);
	if (url) {
		if (CFURLCanBeDecomposed(url)) {
			CFStringRef netLocString = CFURLCopyNetLocation(url);
			if (netLocString) {
				// first strip off port number, if present
				CFStringRef tmpLocString = netLocString;
				CFArrayRef hostnameArray = CFStringCreateArrayBySeparatingStrings(NULL, netLocString, CFSTR(":"));
				tmpLocString = (CFStringRef)CFRetain((CFStringRef)CFArrayGetValueAtIndex(hostnameArray, 0));
				CFRelease(netLocString);
				CFRelease(hostnameArray);
				netLocString = tmpLocString;
				// split remaining string into domain components
				hostnameArray = CFStringCreateArrayBySeparatingStrings(NULL, netLocString, CFSTR("."));
				CFIndex subdomainCount = CFArrayGetCount(hostnameArray);
				CFIndex i = 0;
				while (++i < subdomainCount) {
					CFIndex j = i;
					CFMutableStringRef wildcardString = CFStringCreateMutable(NULL, 0);
					if (wildcardString) {
						CFStringAppendCString(wildcardString, "*", kCFStringEncodingUTF8);
						while (j < subdomainCount) {
							CFStringRef domainString = (CFStringRef)CFArrayGetValueAtIndex(hostnameArray, j++);
							if (CFStringGetLength(domainString) > 0) {
								CFStringAppendCString(wildcardString, ".", kCFStringEncodingUTF8);
								CFStringAppend(wildcardString, domainString);
							}
						}
						if (CFStringGetLength(wildcardString) > 1) {
							CFArrayAppendValue(names, wildcardString);
						}
						CFRelease(wildcardString);
					}
				}
				CFRelease(hostnameArray);
				CFRelease(netLocString);
			}
		}
		CFRelease(url);
	}

    return names;
}
Ejemplo n.º 27
0
void stringManipulation(void) {
   
   CFMutableStringRef strChange;
   CFStringRef strOuter, find, replace, find2, replace2, find3, replace3, bigger, smaller, result;
   CFComparisonResult comp;
   CFLocaleRef curLocale;
   Boolean isHyphenationSupported = false;
   
   show(CFSTR("------------------String Manipulations---------------"));

   // Create a simple immutable string from a Pascal string and convert it to Unicode
   strOuter = CFStringCreateWithCString(NULL, "Hello Cruel World", kCFStringEncodingASCII);
   strChange = CFStringCreateMutableCopy(NULL, CFStringGetLength(strOuter), strOuter);
   find = CFStringCreateWithCString(NULL, "Cruel", kCFStringEncodingASCII);
   replace = CFStringCreateWithCString(NULL, "Cool", kCFStringEncodingASCII);
   find2 = CFStringCreateWithCString(NULL, "Keep", kCFStringEncodingASCII);
   replace2 = CFStringCreateWithCString(NULL, "Be", kCFStringEncodingASCII);
   find3 = CFStringCreateWithCString(NULL, "Change.", kCFStringEncodingASCII);
   replace3 = CFStringCreateWithCString(NULL, "Ball.", kCFStringEncodingASCII);

   bigger  = CFStringCreateWithCString(NULL, "version 2.5", kCFStringEncodingASCII);
   smaller = CFStringCreateWithCString(NULL, "version 2.0", kCFStringEncodingASCII);

   show(CFSTR("String Outer       : %@"), strOuter);
   show(CFSTR("String Find        : %@"), find);
   show(CFSTR("String Replace     : %@"), replace);
   
   CFStringFindAndReplace(strChange, find, replace, CFRangeMake(0, CFStringGetLength(strChange)), 0);
   
   show(CFSTR("Replaced           : %@"), strChange);
   
   CFStringAppendCString(strChange, "!  Keep the change.", kCFStringEncodingASCII);
   
   show(CFSTR("Appended           : %@"), strChange);
   
   curLocale = CFLocaleCopyCurrent ();

   isHyphenationSupported = CFStringIsHyphenationAvailableForLocale(curLocale);
   show(CFSTR("Is Hyphenation supported for this locale? %@"), ((isHyphenationSupported) ? CFSTR ("Yes") : CFSTR("No")));

   CFStringUppercase(strChange, curLocale);
   
   show(CFSTR("Upper Cased        : %@"), strChange);
   
   CFStringLowercase(strChange, curLocale);
   
   show(CFSTR("Lower Cased        : %@"), strChange);
   
   CFStringCapitalize(strChange, curLocale);
   
   show(CFSTR("Capitalized        : %@"), strChange);

   CFStringUppercase(strChange, curLocale);
   
   show(CFSTR("Up Cased (again)   : %@"), strChange);

   CFStringFindAndReplace(strChange, find2, replace2, CFRangeMake(0, CFStringGetLength(strChange)), 0);

   show(CFSTR("Replaced?          : %@"), strChange);
   
   CFStringFindAndReplace(strChange, find2, replace2, CFRangeMake(0, CFStringGetLength(strChange)), kCFCompareCaseInsensitive);
   
   show(CFSTR("Case insensitive   : %@"), strChange);
   
   CFStringCapitalize(strChange, curLocale);
   
   show(CFSTR("Capitalized        : %@"), strChange);

   CFStringFindAndReplace(strChange, replace2, find2, CFRangeMake(0, CFStringGetLength(strChange)), kCFCompareAnchored);
   
   show(CFSTR("Should Be Unchanged: %@"), strChange);

   CFStringFindAndReplace(strChange, find3, replace3, CFRangeMake(0, CFStringGetLength(strChange)), kCFCompareAnchored|kCFCompareBackwards);
   
   show(CFSTR("Should Be Changed  : %@"), strChange);
   
   show(CFSTR("Which is bigger %@ or %@?"), bigger, smaller);
   
   comp = CFStringCompare(bigger, smaller, 0);   
   result = (comp == kCFCompareGreaterThan) ? bigger : smaller;   
   show(CFSTR("Base Compare Says  : %@"), result);

   comp = CFStringCompare(bigger, smaller, kCFCompareNumerically);
   result = (comp == kCFCompareGreaterThan) ? bigger : smaller;   
   show(CFSTR("Numerical Compare  : %@"), result);

   CFRelease(curLocale);
   CFRelease(replace);
   CFRelease(find);
   CFRelease(replace2);   
   CFRelease(find2);
   CFRelease(replace3);   
   CFRelease(find3);
   CFRelease(bigger);   
   CFRelease(smaller);
   CFRelease(strChange);
}
Ejemplo n.º 28
0
CFArrayRef createTracks()
{
	CFMutableArrayRef		trackArray = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
	char 					path[PATH_MAX];
	int						pathLen;
	
	/* Prompt the user to pick a folder of AIFF's to burn. */
	promptForFolder(NULL,"~/Music", path, PATH_MAX);
	pathLen = strlen(path);
	
	// Remove trailing slashes, if any.
	if (pathLen>0 && path[pathLen-1] == '/') pathLen--;
	
	// Open the directory.
	DIR	*dirfd = opendir((const char*)path);
	if (dirfd == NULL) return 0;
	
	while (1)
	{
		CFMutableStringRef	fileStr;
		CFStringRef			aStr;
		AIFFFileInfo*		info;
		char				filepath[PATH_MAX];
		DRRefConCallbacks	callbacks;
		CFMutableDictionaryRef	properties;
		
		/* Get the next child.  This is threadsafe, because the struct dirent* is
		   not global; it's actually pointing to a buffer that was malloc'ed
		   inside the DIR structure. */
		struct dirent *childPtr = readdir(dirfd);
		if (childPtr == NULL) break;
		int	nameLength = childPtr->d_namlen;
		char *name = childPtr->d_name;
		
		if (childPtr->d_type == DT_DIR)
			continue;
			
		/* Skip "." and ".." entries, and AppleDouble "._" entries which 
		   we treat as one file. */
		if (name[0] == '.' && (nameLength == 1 || name[1] == '_' || (name[1] == '.' && nameLength == 2)))
			continue;
		
		/* skip all non-AIFF files by looking at the extension. */
		if (strncmp(".aiff", &name[nameLength-5], 5) != 0 && strncmp(".aif", &name[nameLength-4], 4) != 0)
			continue;
		
		aStr = CFStringCreateWithCString(kCFAllocatorDefault, path, kCFStringEncodingUTF8);
		fileStr = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, aStr);
		CFRelease(aStr);
		CFStringAppendCString(fileStr, "/", kCFStringEncodingUTF8);
		CFStringAppendCString(fileStr, name, kCFStringEncodingUTF8);
			
		/* parse out the file information and construct an information structure 
		   to hold this info for use when we start the burn and start producing data. */
		CFStringGetCString(fileStr, filepath, PATH_MAX, kCFStringEncodingUTF8);
		info = parseFile(filepath);
		
		/* Create the properties dictionary describing this track. */
		properties = createAudioTrackProperties(((info->dataEnd - info->dataStart) / (info->sampleBytes * info->numChannels) * 4) / 2352);
		
		/* Add the file path for this file to the track properties. This will 
		   be used by the producer callback later. */
		CFDictionarySetValue(properties, CFSTR("kTrackSourceFilePath"), fileStr);
		CFRelease(fileStr);
		
		/* Create a track that is described by properties and whose data is 
		   produced by sampleTrackProducerCallback */
		DRTrackRef track = DRTrackCreate(properties, sampleTrackProducerCallback);
		
		/* stuff the info structure pointer into the refCon of the track object. Each object in
		   DiscRecording has a refCon associated with it. */
		callbacks.version = 0;
		callbacks.retain = NULL;
		callbacks.release = trackRefConDestructor;	/* we just need to destroy it when the track is released */
		DRSetRefCon(track, info, &callbacks);
		
		/* Put the track into the array for burning */
		CFArrayAppendValue(trackArray, track);
		CFRelease(properties);
		CFRelease(track);
	}
	
	closedir(dirfd);
	
	
	if (CFArrayGetCount(trackArray) == 0)
	{
		printf("No AIFF files were located!  Aborting.\n");
		exit(1);
	}
	
	return trackArray;
}