String QualifiedName::toString() const { String local = localName(); if (hasPrefix()) return prefix() + ":" + local; return local; }
char OSISLemma::processText(std::string &text, const SWKey *key, const SWModule *module) { (void) key; (void) module; std::string token; bool intoken = false; const std::string orig = text; const char * from = orig.c_str(); if (!option) { for (text = ""; *from; ++from) { if (*from == '<') { intoken = true; token = ""; continue; } if (*from == '>') { // process tokens intoken = false; if (hasPrefix(token, "w ")) { // Word XMLTag wtag(token.c_str()); int count = wtag.getAttributePartCount("lemma", ' '); for (int i = 0; i < count; i++) { std::string a = wtag.getAttribute("lemma", i, ' '); auto const prefixPos(a.find(':')); if (prefixPos == std::string::npos || (prefixPos >= sizeof("lemma.") - 1u && std::strncmp(a.c_str(), "lemma.", sizeof("lemma.") - 1u))) { // remove attribute part wtag.setAttribute("lemma", 0, i, ' '); i--; count--; } } token = wtag; trimString(token); // drop <> token.erase(0u, 1u); token.pop_back(); } // keep token in text text.push_back('<'); text.append(token); text.push_back('>'); continue; } if (intoken) { token += *from; } else { text.push_back(*from); } } } return 0; }
String QualifiedName::toString() const { if (!hasPrefix()) return localName(); return prefix().string() + ':' + localName().string(); }
static void removeFile(std::string const & name) { if ( hasPrefix(name,"file://") ) { std::string const fn = name.substr(strlen("file://")); remove(fn.c_str()); } else if ( hasPrefix(name,"mem:") ) { std::string const fn = name.substr(strlen("mem:")); MemoryFileContainer::eraseEntry(fn); } else { remove(name.c_str()); } }
bool Path::removePrefix(const Path &prefix) { if (hasPrefix(prefix)) { _components.erase(_components.begin(), _components.begin() + prefix.size()); return true; } return false; }
bool Path::replacePrefix(const Path &old_prefix, const Path &new_prefix) { if (hasPrefix(old_prefix)) { removePrefix(old_prefix); _components.insert(_components.begin(), new_prefix.begin(), new_prefix.end()); return true; } return false; }
void ControlFile::setPrefix(const char *prefix) { if (prefix && !hasPrefix() && _prefix) { char buf[_maxPrefix + 1]; sprintf(buf, "%.*s\n", _maxPrefix - 1, prefix); memcpy(_prefix, buf, strlen(buf)); msync(_mapBase, pageAlign(1), MS_ASYNC | MS_INVALIDATE); } }
bool hasPrefix(const TrieNode* root, const string prefix,int idx){ int k = prefix[idx] - 'a'; if(root->childNode[k]){ if(idx == prefix.length() - 1){ return true; } else{ return hasPrefix(root->childNode[k], prefix, idx+1); } } return false; }
bool findAndRenamePrefix(const std::vector<std::string>& files, const std::string& oldPrefix, const std::string& newPrefix) { const size_t oldPrefixLen = oldPrefix.length(); for (std::string file : files) { logPrintf("Considering %s\n", file.c_str()); if (hasPrefix(file, oldPrefix)) { std::string newName = PayloadPath + newPrefix + file.substr(oldPrefixLen); file = PayloadPath + file; logPrintf("%s -> %s", file.c_str(), newName.c_str()); if (std::rename(file.c_str(), newName.c_str()) != 0) { std::perror((std::string("Could not rename ") + newName).c_str()); } } } return true; }
char OSISXlit::processText(std::string &text, const SWKey *key, const SWModule *module) { (void) key; (void) module; std::string token; bool intoken = false; const std::string orig = text; const char * from = orig.c_str(); if (!option) { for (text = ""; *from; ++from) { if (*from == '<') { intoken = true; token = ""; continue; } if (*from == '>') { // process tokens intoken = false; if (hasPrefix(token, "w ")) { // Word XMLTag wtag(token.c_str()); if (!wtag.attribute("xlit").empty()) { wtag.eraseAttribute("xlit"); token = wtag.toString(); trimString(token); // drop <> token.erase(0u, 1u); token.pop_back(); } } // keep token in text text.push_back('<'); text.append(token); text.push_back('>'); continue; } if (intoken) { token += *from; } else { text.push_back(*from); } } } return 0; }
char OSISEnum::processText(std::string &text, const SWKey *key, const SWModule *module) { (void) key; (void) module; if (!option) { std::string result; std::string token; bool inToken = false; for (auto const & c : text) { if (c == '<') { inToken = true; } else if (c == '>') { // Process token: inToken = false; if (hasPrefix(token, "w ")) { // Word XMLTag wtag(token.c_str()); if (!wtag.attribute("n").empty()) { wtag.eraseAttribute("n"); token = wtag.toString(); trimString(token); result.append(token); } else { // Keep original token in text: result.push_back('<'); result.append(token); result.push_back('>'); } } else { // Keep original token in text: result.push_back('<'); result.append(token); result.push_back('>'); } token.clear(); } else { (inToken ? token : result).push_back(c); } } text = std::move(result); } return 0; }
bool String::hasPrefix(const String &x) const { return hasPrefix(x.c_str()); }
TokenType getNextToken(const util::FastInsertVector<string_view>& lines, size_t* line, size_t* offset, const string_view& whole, Location& pos, Token* out, bool crlf) { bool flag = true; if(*line == lines.size()) { out->loc = pos; out->type = TokenType::EndOfFile; return TokenType::EndOfFile; } string_view stream = lines[*line].substr(*offset); if(stream.empty()) { out->loc = pos; out->type = TokenType::EndOfFile; return TokenType::EndOfFile; } size_t read = 0; size_t unicodeLength = 0; // first eat all whitespace skipWhitespace(stream, pos, offset); Token& tok = *out; tok.loc = pos; tok.type = TokenType::Invalid; // check compound symbols first. if(hasPrefix(stream, "//")) { tok.type = TokenType::Comment; // stream = stream.substr(0, 0); (*line)++; pos.line++; pos.col = 0; (*offset) = 0; // don't assign lines[line] = stream, since over here we've changed 'line' to be the next one. flag = false; tok.text = ""; } else if(hasPrefix(stream, "==")) { tok.type = TokenType::EqualsTo; tok.text = "=="; read = 2; } else if(hasPrefix(stream, ">=")) { tok.type = TokenType::GreaterEquals; tok.text = ">="; read = 2; } else if(hasPrefix(stream, "<=")) { tok.type = TokenType::LessThanEquals; tok.text = "<="; read = 2; } else if(hasPrefix(stream, "!=")) { tok.type = TokenType::NotEquals; tok.text = "!="; read = 2; } else if(hasPrefix(stream, "||")) { tok.type = TokenType::LogicalOr; tok.text = "||"; read = 2; } else if(hasPrefix(stream, "&&")) { tok.type = TokenType::LogicalAnd; tok.text = "&&"; read = 2; } else if(hasPrefix(stream, "<-")) { tok.type = TokenType::LeftArrow; tok.text = "<-"; read = 2; } else if(hasPrefix(stream, "->")) { tok.type = TokenType::RightArrow; tok.text = "->"; read = 2; } else if(hasPrefix(stream, "<=")) { tok.type = TokenType::FatLeftArrow; tok.text = "<="; read = 2; } else if(hasPrefix(stream, "=>")) { tok.type = TokenType::FatRightArrow; tok.text = "=>"; read = 2; } else if(hasPrefix(stream, "++")) { tok.type = TokenType::DoublePlus; tok.text = "++"; read = 2; } else if(hasPrefix(stream, "--")) { tok.type = TokenType::DoubleMinus; tok.text = "--"; read = 2; } else if(hasPrefix(stream, "+=")) { tok.type = TokenType::PlusEq; tok.text = "+="; read = 2; } else if(hasPrefix(stream, "-=")) { tok.type = TokenType::MinusEq; tok.text = "-="; read = 2; } else if(hasPrefix(stream, "*=")) { tok.type = TokenType::MultiplyEq; tok.text = "*="; read = 2; } else if(hasPrefix(stream, "/=")) { tok.type = TokenType::DivideEq; tok.text = "/="; read = 2; } else if(hasPrefix(stream, "%=")) { tok.type = TokenType::ModEq; tok.text = "%="; read = 2; } else if(hasPrefix(stream, "&=")) { tok.type = TokenType::AmpersandEq; tok.text = "&="; read = 2; } else if(hasPrefix(stream, "|=")) { tok.type = TokenType::PipeEq; tok.text = "|="; read = 2; } else if(hasPrefix(stream, "^=")) { tok.type = TokenType::CaretEq; tok.text = "^="; read = 2; } else if(hasPrefix(stream, "::")) { tok.type = TokenType::DoubleColon; tok.text = "::"; read = 2; } else if(hasPrefix(stream, "...")) { tok.type = TokenType::Ellipsis; tok.text = "..."; read = 3; } else if(hasPrefix(stream, "..<")) { tok.type = TokenType::HalfOpenEllipsis; tok.text = "..<"; read = 3; } else if(hasPrefix(stream, "/*")) { int currentNest = 1; // support nested, so basically we have to loop until we find either a /* or a */ stream.remove_prefix(2); (*offset) += 2; pos.col += 2; Location opening = pos; Location curpos = pos; size_t k = 0; while(currentNest > 0) { // we can do this, because we know the closing token (*/) is 2 chars long // so if we have 1 char left, gg. if(k + 1 == stream.size() || stream[k] == '\n') { if(*line + 1 == lines.size()) error(opening, "expected closing */ (reached EOF), for block comment started here:"); // else, get the next line. // also note: if we're in this loop, we're inside a block comment. // since the ending token cannot be split across lines, we know that this last char // must also be part of the comment. hence, just skip over it. k = 0; curpos.line++; curpos.col = 0; (*offset) = 0; (*line)++; stream = lines[*line]; continue; } if(stream[k] == '/' && stream[k + 1] == '*') currentNest++, k++, curpos.col++, opening = curpos; else if(stream[k] == '*' && stream[k + 1] == '/') currentNest--, k++, curpos.col++; k++; curpos.col++; } if(currentNest != 0) error(opening, "expected closing */ (reached EOF), for block comment started here:"); pos = curpos; // don't actually store the text, because it's pointless and memory-wasting // tok.text = "/* I used to be a comment like you, until I took a memory-leak to the knee. */"; tok.type = TokenType::Comment; tok.text = ""; read = k; } else if(hasPrefix(stream, "*/")) { unexpected(tok.loc, "'*/'"); } // attrs else if(hasPrefix(stream, "@nomangle")) { tok.type = TokenType::Attr_NoMangle; tok.text = "@nomangle"; read = 9; } else if(hasPrefix(stream, "@entry")) { tok.type = TokenType::Attr_EntryFn; tok.text = "@entry"; read = 6; } else if(hasPrefix(stream, "@raw")) { tok.type = TokenType::Attr_Raw; tok.text = "@raw"; read = 4; } else if(hasPrefix(stream, "@operator")) { tok.type = TokenType::Attr_Operator; tok.text = "@operator"; read = 9; } // unicode stuff else if(hasPrefix(stream, "ƒ")) { tok.type = TokenType::Func; read = std::string("ƒ").length(); tok.text = "ƒ"; unicodeLength = 1; } else if(hasPrefix(stream, "fi")) { tok.type = TokenType::ForeignFunc; read = std::string("fi").length(); tok.text = "fi"; unicodeLength = 1; } else if(hasPrefix(stream, "÷")) { tok.type = TokenType::Divide; read = std::string("÷").length(); tok.text = "÷"; unicodeLength = 1; } else if(hasPrefix(stream, "≠")) { tok.type = TokenType::NotEquals; read = std::string("≠").length(); tok.text = "≠"; unicodeLength = 1; } else if(hasPrefix(stream, "≤")) { tok.type = TokenType::LessThanEquals; read = std::string("≤").length(); tok.text = "≤"; unicodeLength = 1; } else if(hasPrefix(stream, "≥")) { tok.type = TokenType::GreaterEquals; read = std::string("≥").length(); tok.text = "≥"; unicodeLength = 1; } // note some special-casing is needed to differentiate between unary +/- and binary +/- // cases where we want binary: // ...) + 3 // ...] + 3 // ident + 3 // number + 3 // string + 3 // so in every other case we want unary +/-. // note: this dumb '<=255' thing is because windows likes to assert useless things. else if((!stream.empty() && ((stream[0] >= 1 && (int) stream[0] <= 255 && isdigit(stream[0])) || shouldConsiderUnaryLiteral(stream, pos))) /* handle cases like '+ 3' or '- 14' (ie. space between sign and number) */ && ((isdigit(stream[0]) ? true : false) || (stream.size() > 1 && isdigit(stream[1])))) { // copy it. auto tmp = stream; if(tmp.find('-') == 0 || tmp.find('+') == 0) tmp.remove_prefix(1); int base = 10; if(tmp.find("0x") == 0 || tmp.find("0X") == 0) base = 16, tmp.remove_prefix(2); else if(tmp.find("0b") == 0 || tmp.find("0B") == 0) base = 2, tmp.remove_prefix(2); // find that shit auto end = std::find_if_not(tmp.begin(), tmp.end(), [base](const char& c) -> bool { if(base == 10) return isdigit(c); if(base == 16) return isdigit(c) || (toupper(c) >= 'A' && toupper(c) <= 'F'); else return (c == '0' || c == '1'); }); tmp.remove_prefix((end - tmp.begin())); // check if we have 'e' or 'E' bool hadExp = false; if(tmp.size() > 0 && (tmp[0] == 'e' || tmp[0] == 'E')) { if(base != 10) error("exponential form is supported with neither hexadecimal nor binary literals"); // find that shit auto next = std::find_if_not(tmp.begin() + 1, tmp.end(), isdigit); // this does the 'e' as well. tmp.remove_prefix(next - tmp.begin()); hadExp = true; } size_t didRead = stream.size() - tmp.size(); auto post = stream.substr(didRead); if(!post.empty() && post[0] == '.') { if(base != 10) error("invalid floating point literal; only valid in base 10"); else if(hadExp) error("invalid floating point literal; decimal point cannot occur after the exponent ('e' or 'E')."); // if the previous token was a '.' as well, then we're doing some tuple access // eg. x.0.1 (we would be at '0', having a period both ahead and behind us) // if the next token is not a number, then same thing, eg. // x.0.z, where the first tuple element of 'x' is a struct or something. // so -- lex a floating point *iff* the previous token was not '.', and the next token is a digit. if(prevType != TokenType::Period && post.size() > 1 && isdigit(post[1])) { // yes, parse a floating point post.remove_prefix(1), didRead++; while(post.size() > 0 && isdigit(post.front())) post.remove_prefix(1), didRead++; // ok. } else { // no, just return the integer token. // (which we do below, so just do nothing here) } } tok.text = stream.substr(0, didRead); tok.type = TokenType::Number; tok.loc.len = didRead; read = didRead; } else if(!stream.empty() && (stream[0] == '_' || utf8iscategory(stream.data(), stream.size(), UTF8_CATEGORY_LETTER) > 0)) { // get as many letters as possible first size_t identLength = utf8iscategory(stream.data(), stream.size(), UTF8_CATEGORY_LETTER | UTF8_CATEGORY_PUNCTUATION_CONNECTOR | UTF8_CATEGORY_NUMBER); read = identLength; tok.text = stream.substr(0, identLength); initKeywordMap(); if(auto it = keywordMap.find(tok.text); it != keywordMap.end()) tok.type = it->second; else
int main(int argc, char *argv[]) { const char *filename = getFilename(argv[0]); std::string target, compilerCommand; splitCompilerName(filename, &target, &compilerCommand); std::string compilerBaseDir = getBaseDir(compilerCommand); if (compilerBaseDir.size() && compilerBaseDir[compilerBaseDir.size() - 1] != '/') { compilerBaseDir += '/'; } compilerCommand = compilerBaseDir + "bin/" + compilerCommand; // Determine SDK and deployment settings. const char *sdkPath = getenvd("IOS_SDK", IOS_SDK_DEFAULT); const char *iOSMinVer = getenvd("IPHONEOS_DEPLOYMENT_TARGET", IOS_MIN_VER_DEFAULT); unsetenv("IPHONEOS_DEPLOYMENT_TARGET"); std::string iOSMinVerParam = "-miphoneos-version-min="; iOSMinVerParam += iOSMinVer; // Set default archtitecture based on minimum iOS version. int major = -1, minor = -1; if (sscanf(iOSMinVer, "%d.%d", &major, &minor) != 2) { abort(); } // armv6 devices only support up to iOS 4.2.1. If we deploy for such an // old version, we default that architecture. const char *arch; if (major <= 4) { arch = "armv6"; } else { arch = "armv7"; } // Make sure all program binaries created are automatically signed. std::string codesign = target + "-codesign_allocate"; setenv("CODESIGN_ALLOCATE", codesign.c_str(), 1); setenv("IOS_FAKE_CODE_SIGN", "1", 1); // Setup environment for proper execution. std::string newLdLibraryPath = compilerBaseDir; newLdLibraryPath += "lib"; char *ldLibraryPath = getenv(LIBRARY_PATH); if (ldLibraryPath && *ldLibraryPath) { newLdLibraryPath += ':'; newLdLibraryPath += ldLibraryPath; } setenv(LIBRARY_PATH, newLdLibraryPath.c_str(), 1); // Setup command line arguments for compiler. char **params = (char **)malloc(sizeof(char *) * (argc + 9)); bool hasArch = false; bool hasIPhoneOSVersionMin = false; for (int i = 1; i < argc; ++i) { if (hasPrefix(argv[i], "-arch")) { hasArch = true; break; } else if (hasPrefix(argv[i], "-miphoneos-version-min")) { hasIPhoneOSVersionMin = true; break; } } int param = 0; #define ADD_PARAM(x) params[param++] = strdup((x)) ADD_PARAM(compilerCommand.c_str()); ADD_PARAM("-target"); ADD_PARAM(target.c_str()); if (!hasArch) { ADD_PARAM("-arch"); ADD_PARAM(arch); } ADD_PARAM("-isysroot"); ADD_PARAM(sdkPath); if (!hasIPhoneOSVersionMin) { ADD_PARAM(iOSMinVerParam.c_str()); } ADD_PARAM("-mlinker-version=" LINKER_VERSION); #undef ADD_PARAM for (int i = 1; i < argc; ++i) { params[param++] = argv[i]; } params[param] = 0; execvp(compilerCommand.c_str(), params); abort(); }
void ElemLiteralResult::execute(StylesheetExecutionContext& executionContext) const { const XalanDOMString& theElementName = getElementName(); executionContext.startElement(c_wstr(theElementName)); ElemUse::execute(executionContext); const NamespacesHandler& theNamespacesHandler = getNamespacesHandler(); theNamespacesHandler.outputResultNamespaces(executionContext); if (hasPrefix() == false) { // OK, let's check to make sure we don't have to change the default namespace... const XalanDOMString* const theCurrentDefaultNamespace = executionContext.getResultNamespaceForPrefix(s_emptyString); if (theCurrentDefaultNamespace != 0) { const XalanDOMString* const theElementDefaultNamespace = theNamespacesHandler.getNamespace(s_emptyString); if (theElementDefaultNamespace == 0) { // There was no default namespace, so we have to turn the // current one off. executionContext.addResultAttribute(DOMServices::s_XMLNamespace, s_emptyString); } else if (equals(*theCurrentDefaultNamespace, *theElementDefaultNamespace) == false) { executionContext.addResultAttribute(DOMServices::s_XMLNamespace, *theElementDefaultNamespace); } } } if(m_avtsCount > 0) { StylesheetExecutionContext::GetAndReleaseCachedString theGuard(executionContext); XalanDOMString& theStringedValue = theGuard.get(); for(unsigned int i = 0; i < m_avtsCount; ++i) { const AVT* const avt = m_avts[i]; const XalanDOMString& theName = avt->getName(); avt->evaluate(theStringedValue, *this, executionContext); executionContext.addResultAttribute(theName, theStringedValue); theStringedValue.clear(); } } executeChildren(executionContext); executionContext.endElement(c_wstr(theElementName)); }
void ElemLiteralResult::init( StylesheetConstructionContext& constructionContext, Stylesheet& stylesheetTree, const XalanDOMChar* name, const AttributeListType& atts) { assert(name != 0); hasPrefix(indexOf(name, XalanUnicode::charColon) < length(name) ? true : false); const unsigned int nAttrs = atts.getLength(); // This over-allocates, but we probably won't waste that much space. m_avts = constructionContext.allocateAVTPointerVector(nAttrs); assert(m_avts != 0); const StylesheetConstructionContext::GetAndReleaseCachedString theGuard(constructionContext); XalanDOMString& theBuffer = theGuard.get(); for(unsigned int i = 0; i < nAttrs; i++) { const XalanDOMChar* const aname = atts.getName(i); bool needToProcess = true; const XalanDOMString::size_type indexOfNSSep = indexOf(aname, XalanUnicode::charColon); const XalanDOMString::size_type len = length(aname); if(indexOfNSSep < len) { substring(aname, theBuffer, 0, indexOfNSSep); if(!equals(theBuffer, DOMServices::s_XMLNamespace)) { const XalanDOMString* const ns = getNamespaceForPrefixInternal(theBuffer); if(ns == 0) { constructionContext.error( XalanMessageLoader::getMessage(XalanMessages::UndeclaredNamespacePrefix_1Param, theBuffer), 0, this); } else if(equals(*ns, stylesheetTree.getXSLTNamespaceURI())) { theBuffer.assign(aname + indexOfNSSep + 1, len - (indexOfNSSep + 1)); if(processPrefixControl(constructionContext, stylesheetTree, theBuffer, atts.getValue(i)) == true) { needToProcess = false; } else if (equals(theBuffer, Constants::ATTRNAME_VERSION) == true) { const XalanDOMChar* const value = atts.getValue(i); stylesheetTree.setXSLTVerDeclared(DoubleSupport::toDouble(value)); } } } else { // don't process namespace decls needToProcess = false; } } if(needToProcess == true) { processSpaceAttr(aname, atts, i, constructionContext); // Add xmlns attribute(except xmlns:xsl), xml:space, etc... // Ignore anything with xsl:xxx if(! processUseAttributeSets(constructionContext, aname, atts, i) && isAttrOK(aname, atts, i, constructionContext)) { m_avts[m_avtsCount++] = constructionContext.createAVT(getLocator(), aname, atts.getValue(i), *this); } } } }
int main(int argc, char *argv[]) { if (argc != 3) { printf("Usage: convbdf [input] [fontname]\n"); return 1; } std::ifstream in(argv[1]); std::string line; std::getline(in, line); if (in.fail() || in.eof()) error("Premature end of file"); int verMajor, verMinor; if (sscanf(line.c_str(), "STARTFONT %d.%d", &verMajor, &verMinor) != 2) error("File '%s' is no BDF file", argv[1]); if (verMajor != 2 || (verMinor != 1 && verMinor != 2)) error("File '%s' does not use a supported BDF version (%d.%d)", argv[1], verMajor, verMinor); std::string fontName; std::string copyright; BdfFont font; memset(&font, 0, sizeof(font)); font.ascent = -1; font.defaultCharacter = -1; int charsProcessed = 0, charsAvailable = 0, descent = -1; while (true) { std::getline(in, line); if (in.fail() || in.eof()) error("Premature end of file"); if (hasPrefix(line, "SIZE ")) { // Ignore } else if (hasPrefix(line, "FONT ")) { fontName = line.substr(5); } else if (hasPrefix(line, "COPYRIGHT ")) { copyright = line.substr(10); } else if (hasPrefix(line, "COMMENT ")) { // Ignore } else if (hasPrefix(line, "FONTBOUNDINGBOX ")) { if (sscanf(line.c_str(), "FONTBOUNDINGBOX %d %d %d %d", &font.defaultBox.width, &font.defaultBox.height, &font.defaultBox.xOffset, &font.defaultBox.yOffset) != 4) error("Invalid FONTBOUNDINGBOX"); } else if (hasPrefix(line, "CHARS ")) { if (sscanf(line.c_str(), "CHARS %d", &charsAvailable) != 1) error("Invalid CHARS"); font.numCharacters = 256; font.bitmaps = new unsigned char *[font.numCharacters]; memset(font.bitmaps, 0, sizeof(unsigned char *) * font.numCharacters); font.advances = new unsigned char[font.numCharacters]; font.boxes = new BdfBoundingBox[font.numCharacters]; } else if (hasPrefix(line, "FONT_ASCENT ")) { if (sscanf(line.c_str(), "FONT_ASCENT %d", &font.ascent) != 1) error("Invalid FONT_ASCENT"); } else if (hasPrefix(line, "FONT_DESCENT ")) { if (sscanf(line.c_str(), "FONT_DESCENT %d", &descent) != 1) error("Invalid FONT_ASCENT"); } else if (hasPrefix(line, "DEFAULT_CHAR ")) { if (sscanf(line.c_str(), "DEFAULT_CHAR %d", &font.defaultCharacter) != 1) error("Invalid DEFAULT_CHAR"); } else if (hasPrefix(line, "STARTCHAR ")) { ++charsProcessed; if (charsProcessed > charsAvailable) error("Too many characters defined (only %d specified, but %d existing already)", charsAvailable, charsProcessed); bool hasWidth = false, hasBitmap = false; int encoding = -1; int xAdvance; unsigned char *bitmap = 0; BdfBoundingBox bbox = font.defaultBox; while (true) { std::getline(in, line); if (in.fail() || in.eof()) error("Premature end of file"); if (hasPrefix(line, "ENCODING ")) { if (sscanf(line.c_str(), "ENCODING %d", &encoding) != 1) error("Invalid ENCODING"); } else if (hasPrefix(line, "DWIDTH ")) { int yAdvance; if (sscanf(line.c_str(), "DWIDTH %d %d", &xAdvance, &yAdvance) != 2) error("Invalid DWIDTH"); if (yAdvance != 0) error("Character %d uses a DWIDTH y advance of %d", encoding, yAdvance); if (xAdvance < 0) error("Character %d has a negative x advance", encoding); if (xAdvance > font.maxAdvance) font.maxAdvance = xAdvance; hasWidth = true; } else if (hasPrefix(line, "BBX" )) { if (sscanf(line.c_str(), "BBX %d %d %d %d", &bbox.width, &bbox.height, &bbox.xOffset, &bbox.yOffset) != 4) error("Invalid BBX"); } else if (line == "BITMAP") { hasBitmap = true; const size_t bytesPerRow = ((bbox.width + 7) / 8); // Since we do not load all characters, we only create a // buffer for the ones we actually load. if (encoding < font.numCharacters) bitmap = new unsigned char[bbox.height * bytesPerRow]; for (int i = 0; i < bbox.height; ++i) { std::getline(in, line); if (in.fail() || in.eof()) error("Premature end of file"); if (line.size() != bytesPerRow * 2) error("Glyph bitmap line too short"); if (!bitmap) continue; for (size_t j = 0; j < bytesPerRow; ++j) { unsigned char nibble1 = line[j * 2 + 0]; hexToInt(nibble1); unsigned char nibble2 = line[j * 2 + 1]; hexToInt(nibble2); bitmap[i * bytesPerRow + j] = (nibble1 << 4) | nibble2; } } } else if (line == "ENDCHAR") { if (encoding == -1 || !hasWidth || !hasBitmap) error("Character not completly defined"); if (encoding < font.numCharacters) { font.advances[encoding] = xAdvance; font.boxes[encoding] = bbox; font.bitmaps[encoding] = bitmap; } break; } } } else if (line == "ENDFONT") { break; } else { // Silently ignore other declarations //warning("Unsupported declaration: \"%s\"", line.c_str()); } } if (font.ascent < 0) error("No ascent specified"); if (descent < 0) error("No descent specified"); font.height = font.ascent + descent; int firstCharacter = font.numCharacters; int lastCharacter = -1; bool hasFixedBBox = true; bool hasFixedAdvance = true; for (int i = 0; i < font.numCharacters; ++i) { if (!font.bitmaps[i]) continue; if (i < firstCharacter) firstCharacter = i; if (i > lastCharacter) lastCharacter = i; if (font.advances[i] != font.maxAdvance) hasFixedAdvance = false; const BdfBoundingBox &bbox = font.boxes[i]; if (bbox.width != font.defaultBox.width || bbox.height != font.defaultBox.height || bbox.xOffset != font.defaultBox.xOffset || bbox.yOffset != font.defaultBox.yOffset) hasFixedBBox = false; } if (lastCharacter == -1) error("No glyphs found"); // Free the advance table, in case all glyphs use the same advance if (hasFixedAdvance) { delete[] font.advances; font.advances = 0; } // Free the box table, in case all glyphs use the same box if (hasFixedBBox) { delete[] font.boxes; font.boxes = 0; } // Adapt for the fact that we never use encoding 0. if (font.defaultCharacter < firstCharacter || font.defaultCharacter > lastCharacter) font.defaultCharacter = -1; font.firstCharacter = firstCharacter; charsAvailable = lastCharacter - firstCharacter + 1; // Try to compact the tables if (charsAvailable < font.numCharacters) { unsigned char **bitmaps = new unsigned char *[charsAvailable]; BdfBoundingBox *boxes = 0; if (!hasFixedBBox) boxes = new BdfBoundingBox[charsAvailable]; unsigned char *advances = 0; if (!hasFixedAdvance) advances = new unsigned char[charsAvailable]; for (int i = 0; i < charsAvailable; ++i) { const int encoding = i + firstCharacter; if (font.bitmaps[encoding]) { bitmaps[i] = font.bitmaps[encoding]; if (!hasFixedBBox) boxes[i] = font.boxes[encoding]; if (!hasFixedAdvance) advances[i] = font.advances[encoding]; } else { bitmaps[i] = 0; } } delete[] font.bitmaps; font.bitmaps = bitmaps; delete[] font.advances; font.advances = advances; delete[] font.boxes; font.boxes = boxes; font.numCharacters = charsAvailable; } char dateBuffer[256]; time_t curTime = time(0); snprintf(dateBuffer, sizeof(dateBuffer), "%s", ctime(&curTime)); // Finally output the cpp source file to stdout printf("// Generated by convbdf on %s" "#include \"graphics/fonts/bdf.h\"\n" "\n" "// Font information:\n" "// Name: %s\n" "// Size: %dx%d\n" "// Box: %d %d %d %d\n" "// Ascent: %d\n" "// First character: %d\n" "// Default character: %d\n" "// Characters: %d\n" "// Copyright: %s\n" "\n", dateBuffer, fontName.c_str(), font.maxAdvance, font.height, font.defaultBox.width, font.defaultBox.height, font.defaultBox.xOffset, font.defaultBox.yOffset, font.ascent, font.firstCharacter, font.defaultCharacter, font.numCharacters, copyright.c_str()); printf("namespace Graphics {\n" "\n"); for (int i = 0; i < font.numCharacters; ++i) { if (!font.bitmaps[i]) continue; BdfBoundingBox box = hasFixedBBox ? font.defaultBox : font.boxes[i]; printf("// Character %d (0x%02X)\n" "// Box: %d %d %d %d\n" "// Advance: %d\n" "//\n", i + font.firstCharacter, i + font.firstCharacter, box.width, box.height, box.xOffset, box.yOffset, hasFixedAdvance ? font.maxAdvance : font.advances[i]); printf("// +"); for (int x = 0; x < box.width; ++x) printf("-"); printf("+\n"); const unsigned char *bitmap = font.bitmaps[i]; for (int y = 0; y < box.height; ++y) { printf("// |"); unsigned char data = 0; for (int x = 0; x < box.width; ++x) { if (!(x % 8)) data = *bitmap++; printf("%c", (data & 0x80) ? '*' : ' '); data <<= 1; } printf("|\n"); } printf("// +"); for (int x = 0; x < box.width; ++x) printf("-"); printf("+\n"); const int bytesPerRow = (box.width + 7) / 8; bitmap = font.bitmaps[i]; printf("static const byte glyph%d[] = {\n", i); for (int y = 0; y < box.height; ++y) { printf("\t"); for (int x = 0; x < bytesPerRow; ++x) { if (x) printf(", "); printf("0x%02X", *bitmap++); } if (y != box.height - 1) printf(","); printf("\n"); } printf("};\n" "\n"); } printf("// Bitmap pointer table\n" "const byte *const bitmapTable[] = {\n"); for (int i = 0; i < font.numCharacters; ++i) { if (font.bitmaps[i]) printf("\tglyph%d", i); else printf("\t0"); if (i != font.numCharacters - 1) printf(","); printf("\n"); } printf("};\n" "\n"); if (!hasFixedAdvance) { printf("// Advance table\n" "static const byte advances[] = {\n"); for (int i = 0; i < font.numCharacters; ++i) { if (font.bitmaps[i]) printf("\t%d", font.advances[i]); else printf("\t0"); if (i != font.numCharacters - 1) printf(","); printf("\n"); } printf("};\n" "\n"); } if (!hasFixedBBox) { printf("// Bounding box table\n" "static const BdfBoundingBox boxes[] = {\n"); for (int i = 0; i < font.numCharacters; ++i) { if (font.bitmaps[i]) { const BdfBoundingBox &box = font.boxes[i]; printf("\t{ %d, %d, %d, %d }", box.width, box.height, box.xOffset, box.yOffset); } else { printf("\t{ 0, 0, 0, 0 }"); } if (i != font.numCharacters - 1) printf(","); printf("\n"); } printf("};\n" "\n"); } printf("// Font structure\n" "static const BdfFontData desc = {\n" "\t%d, // Max advance\n" "\t%d, // Height\n" "\t{ %d, %d, %d, %d }, // Bounding box\n" "\t%d, // Ascent\n" "\n" "\t%d, // First character\n" "\t%d, // Default character\n" "\t%d, // Characters\n" "\n" "\tbitmapTable, // Bitmaps\n", font.maxAdvance, font.height, font.defaultBox.width, font.defaultBox.height, font.defaultBox.xOffset, font.defaultBox.yOffset, font.ascent, font.firstCharacter, font.defaultCharacter, font.numCharacters); if (hasFixedAdvance) printf("\t0, // Advances\n"); else printf("\tadvances, // Advances\n"); if (hasFixedBBox) printf("\t0 // Boxes\n"); else printf("\tboxes // Boxes\n"); printf("};\n" "\n" "DEFINE_FONT(%s)\n" "\n" "} // End of namespace Graphics\n", argv[2]); }
int main(int argc, char** argv) { Solver S; S.verbosity = 1; int i, j; const char* value; for (i = j = 0; i < argc; i++){ if ((value = hasPrefix(argv[i], "-polarity-mode="))){ if (strcmp(value, "true") == 0) S.polarity_mode = Solver::polarity_true; else if (strcmp(value, "false") == 0) S.polarity_mode = Solver::polarity_false; else if (strcmp(value, "rnd") == 0) S.polarity_mode = Solver::polarity_rnd; else{ reportf("ERROR! unknown polarity-mode %s\n", value); exit(0); } }else if ((value = hasPrefix(argv[i], "-rnd-freq="))){ double rnd; if (sscanf(value, "%lf", &rnd) <= 0 || rnd < 0 || rnd > 1){ reportf("ERROR! illegal rnd-freq constant %s\n", value); exit(0); } S.random_var_freq = rnd; }else if ((value = hasPrefix(argv[i], "-decay="))){ double decay; if (sscanf(value, "%lf", &decay) <= 0 || decay <= 0 || decay > 1){ reportf("ERROR! illegal decay constant %s\n", value); exit(0); } S.var_decay = 1 / decay; }else if ((value = hasPrefix(argv[i], "-verbosity="))){ int verbosity = (int)strtol(value, NULL, 10); if (verbosity == 0 && errno == EINVAL){ reportf("ERROR! illegal verbosity level %s\n", value); exit(0); } S.verbosity = verbosity; }else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-help") == 0 || strcmp(argv[i], "--help") == 0){ printUsage(argv); exit(0); }else if (strncmp(argv[i], "-", 1) == 0){ reportf("ERROR! unknown flag %s\n", argv[i]); exit(0); }else argv[j++] = argv[i]; } argc = j; reportf("This is MiniSat 2.0 beta\n"); #if defined(__linux__) fpu_control_t oldcw, newcw; _FPU_GETCW(oldcw); newcw = (oldcw & ~_FPU_EXTENDED) | _FPU_DOUBLE; _FPU_SETCW(newcw); reportf("WARNING: for repeatability, setting FPU to use double precision\n"); #endif double cpu_time = cpuTime(); solver = &S; signal(SIGINT,SIGINT_handler); signal(SIGHUP,SIGINT_handler); if (argc == 1) reportf("Reading from standard input... Use '-h' or '--help' for help.\n"); gzFile in = (argc == 1) ? gzdopen(0, "rb") : gzopen(argv[1], "rb"); if (in == NULL) reportf("ERROR! Could not open file: %s\n", argc == 1 ? "<stdin>" : argv[1]), exit(1); reportf("============================[ Problem Statistics ]=============================\n"); reportf("| |\n"); parse_DIMACS(in, S); gzclose(in); FILE* res = (argc >= 3) ? fopen(argv[2], "wb") : NULL; double parse_time = cpuTime() - cpu_time; reportf("| Parsing time: %-12.2f s |\n", parse_time); if (!S.simplify()){ reportf("Solved by unit propagation\n"); if (res != NULL) fprintf(res, "UNSAT\n"), fclose(res); printf("UNSATISFIABLE\n"); exit(20); } bool ret = S.solve(); printStats(S); reportf("\n"); printf(ret ? "SATISFIABLE\n" : "UNSATISFIABLE\n"); if (res != NULL){ if (ret){ fprintf(res, "SAT\n"); //S.liftModel(); for (int i = 0; i < S.nVars(); i++) if (S.model[i] != l_Undef) fprintf(res, "%s%s%d", (i==0)?"":" ", (S.model[i]==l_True)?"":"-", i+1); //else fprintf(res, "\nuninstanciated variable %d\n", i+1); fprintf(res, " 0\n"); }else fprintf(res, "UNSAT\n"); fclose(res); } #ifdef NDEBUG exit(ret ? 10 : 20); // (faster than "return", which will invoke the destructor for 'Solver') #endif }
// central dispatcher of all url requests arriving at the webserver // returns true, if request has been dispatched within dispatch. Otherwise the caller // should assume that static content is to be displayed. bool CommandDispatcher::dispatch(string uri, string query, string body, string &response, bool &okOrNOk) { response = ""; string urlPath = getPath(uri); vector<string> urlParamName; vector<string> urlParamValue; compileURLParameter(query,urlParamName,urlParamValue); // check if direct cortex command defined via URL parameter // example: /cortex/LED?blink if (hasPrefix(uri, "/cortex")) { LOG(DEBUG) << uri << " " << query; string cmd = uri.substr(string("/cortex/").length()); for (int i = 0;i<CommDefType::NumberOfCommands;i++) { string cortexCmdStr = string(commDef[i].name); if (hasPrefix(cmd, cortexCmdStr)) { string command = string(commDef[i].name); // are there any parameters ? if (query.length() > 0) { std::istringstream iss(query); std::string token; while (std::getline(iss, token, '&')) { // extract name and value of parameter int equalsIdx = token.find("="); if (equalsIdx > 0) { string name = token.substr(0,equalsIdx); string value = token.substr(equalsIdx+1); command += " " + name + "=" + value; } else { command += " " + token; } } }; LOG(DEBUG) << "calling cortex with \"" << command << "\""; string cmdReply; TrajectoryExecution::getInstance().directAccess(command, cmdReply, okOrNOk); if (cmdReply.length() > 0) response += cmdReply + ""; if (okOrNOk) response += "ok"; else response += "failed"; return true; } } } // check, if cortex is called via one command string // example /direct?param=LED+blink if (hasPrefix(uri, "/direct")) { if (hasPrefix(query, "param=")) { LOG(DEBUG) << uri << " " << query; string cmd = urlDecode(query.substr(string("param=").length())); LOG(DEBUG) << "calling cortex with \"" << cmd << "\""; string cmdReply; TrajectoryExecution::getInstance().directAccess(cmd, cmdReply, okOrNOk); std::ostringstream s; if (okOrNOk) { s << "OK"; } else { s << "NOK(" << getLastError() << ") " << getErrorMessage(getLastError()); } response += s.str(); return true; } } // check, if TransactionExecutor is called with orchestrated calls if (hasPrefix(uri, "/executor/")) { string executorPath = uri.substr(string("/executor/").length()); if (hasPrefix(executorPath, "startupbot")) { LOG(DEBUG) << uri << " " << query; okOrNOk = TrajectoryExecution::getInstance().startupBot(); std::ostringstream s; if (okOrNOk) { s << "OK"; } else { s << "NOK(" << getLastError() << ") " << getErrorMessage(getLastError()); } response = s.str(); } else if (hasPrefix(executorPath, "teardownbot")) { LOG(DEBUG) << uri << " " << query; okOrNOk = TrajectoryExecution::getInstance().teardownBot(); std::ostringstream s; if (okOrNOk) { s << "OK"; } else { s << "NOK(" << getLastError() << ") " << getErrorMessage(getLastError()); } response = s.str(); return true; } else if (hasPrefix(executorPath, "nullpositionbot")) { LOG(DEBUG) << uri << " " << query; okOrNOk = TrajectoryExecution::getInstance().moveToNullPosition(); std::ostringstream s; if (okOrNOk) { s << "OK"; } else { s << "NOK(" << getLastError() << ") " << getErrorMessage(getLastError()); } response = s.str(); return true; } else if (hasPrefix(executorPath, "isupandrunning")) { response = ""; bool result = TrajectoryExecution::getInstance().isBotUpAndReady(); okOrNOk = true; response = result?"true":"false"; return true; } else if (hasPrefix(executorPath, "emergencystop")) { LOG(DEBUG) << uri << " " << query; response = ""; bool result = TrajectoryExecution::getInstance().emergencyStopBot(); okOrNOk = true; response = result?"true":"false"; return true; } else if (hasPrefix(executorPath, "setangles")) { LOG(DEBUG) << uri << " " << query; string param = urlDecode(query.substr(string("param=").length())); okOrNOk = TrajectoryExecution::getInstance().setAnglesAsString(param); std::ostringstream s; if (okOrNOk) { s << "OK"; } else { s << "NOK(" << getLastError() << ") " << getErrorMessage(getLastError()); } response = s.str(); return true; } else if (hasPrefix(executorPath, "getangles")) { LOG(DEBUG) << uri << " " << query; int indent = 0; response = TrajectoryExecution::getInstance().currentTrajectoryNodeToString(indent); okOrNOk = !isError(); return true; } else if (hasPrefix(executorPath, "settrajectory")) { LOG(DEBUG) << uri << " " << query; string param = urlDecode(body); LOG(DEBUG) << "body:" << param; TrajectoryExecution::getInstance().runTrajectory(param); okOrNOk = !isError(); std::ostringstream s; if (okOrNOk) { s << "OK"; } else { s << "NOK(" << getLastError() << ") " << getErrorMessage(getLastError()); } response += s.str(); return true; } else if (hasPrefix(executorPath, "stoptrajectory")) { LOG(DEBUG) << uri << " " << query; TrajectoryExecution::getInstance().stopTrajectory(); okOrNOk = !isError(); std::ostringstream s; if (okOrNOk) { s << "OK"; } else { s << "NOK(" << getLastError() << ") " << getErrorMessage(getLastError()); } response = s.str(); return true; } } if (hasPrefix(uri, "/web")) { string keyValue; if (getURLParameter(urlParamName, urlParamValue, "key", keyValue)) { if (keyValue.compare(string("cortexcmd")) == 0) { if (getURLParameter(urlParamName, urlParamValue, "from", keyValue)) { int from = string_to_int(keyValue); if (from >=0 ) response = getCmdLineJson(from+1); else response = getCmdLineJson(0); } else response = getCmdLineJson(0); okOrNOk = true; return true; } else { if (keyValue.compare(string("cortexlog")) == 0) { if (getURLParameter(urlParamName, urlParamValue, "from", keyValue)) { int from = string_to_int(keyValue); if (from >=0) response = getLogLineJson(from+1); else response = getLogLineJson(0); } else response = getLogLineJson(0); okOrNOk = true; return true; } else { if (keyValue.compare(string("alert")) == 0) { if (getURLParameter(urlParamName, urlParamValue, "from", keyValue)) { int from = string_to_int(keyValue); if (from >=0) { response = getAlertLineJson(from); okOrNOk = true; return true; } } else { response = int_to_string(alertCounter); okOrNOk = true; return true; } } else { if (keyValue.compare(string("heartbeat")) == 0) { response = getHeartbeatJson(); okOrNOk = true; return true; } } } } } else { if (getURLParameter(urlParamName, urlParamValue, "action", keyValue)) { if (keyValue.compare("savecmd") == 0) { LOG(DEBUG) << uri << " " << query; string value; if (getURLParameter(urlParamName, urlParamValue, "value", value)) { string cmdReply; TrajectoryExecution::getInstance().directAccess(value, cmdReply, okOrNOk); response = cmdReply; return true; } } } } } okOrNOk = false; return false; }
// Returns if there is any word in the trie // that starts with the given prefix. bool startsWith(string prefix) { if(prefix.length() == 0) return true; return hasPrefix(root, prefix, 0); }
char OSISWordJS::processText(std::string &text, const SWKey *key, const SWModule *module) { if (option) { char token[2112]; // cheese. Fix. int tokpos = 0; bool intoken = false; int wordNum = 1; char wordstr[5]; std::string modName = (module)?module->getName():""; // add TR to w src in KJV then remove this next line std::string wordSrcPrefix = (modName == "KJV")?std::string("TR"):modName; VerseKey const * vkey = 0; if (key) { vkey = dynamic_cast<VerseKey const *>(key); } const std::string orig = text; const char * from = orig.c_str(); for (text = ""; *from; ++from) { if (*from == '<') { intoken = true; tokpos = 0; token[0] = 0; token[1] = 0; token[2] = 0; continue; } if (*from == '>') { // process tokens intoken = false; if ((*token == 'w') && (token[1] == ' ')) { // Word XMLTag wtag(token); sprintf(wordstr, "%03d", wordNum); std::string lemmaClass; std::string lemma; std::string morph; std::string page; std::string src; char gh = 0; page = module->getEntryAttributes()["Word"][wordstr]["Page"].c_str(); if (page.length()) page = (std::string)"p:" + page; int count = atoi(module->getEntryAttributes()["Word"][wordstr]["PartCount"].c_str()); for (int i = 0; i < count; i++) { // for now, lemma class can just be equal to last lemma class in multi part word std::string tmp = "LemmaClass"; if (count > 1) tmp += formatted(".%d", i+1); lemmaClass = module->getEntryAttributes()["Word"][wordstr][tmp]; tmp = "Lemma"; if (count > 1) tmp += formatted(".%d", i+1); tmp = (module->getEntryAttributes()["Word"][wordstr][tmp].c_str()); // if we're strongs, if (lemmaClass == "strong") { gh = tmp[0]; tmp.erase(0u, 1u); } if (lemma.size()) lemma += "|"; lemma += tmp; tmp = "Morph"; if (count > 1) tmp += formatted(".%d", i+1); tmp = (module->getEntryAttributes()["Word"][wordstr][tmp].c_str()); if (morph.size()) morph += "|"; morph += tmp; tmp = "Src"; if (count > 1) tmp += formatted(".%d", i+1); tmp = (module->getEntryAttributes()["Word"][wordstr][tmp].c_str()); if (!tmp.length()) tmp += formatted("%d", wordNum); tmp.insert(0, wordSrcPrefix); if (src.size()) src += "|"; src += tmp; } std::string lexName = ""; // we can pass the real lex name in, but we have some // aliases in the javascript to optimize bandwidth if ((gh == 'G') && (defaultGreekLex)) { lexName = (!strcmp(defaultGreekLex->getName(), "StrongsGreek"))?"G":defaultGreekLex->getName(); } else if ((gh == 'H') && (defaultHebLex)) { lexName = (!strcmp(defaultHebLex->getName(), "StrongsHebrew"))?"H":defaultHebLex->getName(); } std::string xlit = wtag.getAttribute("xlit"); if ((lemmaClass != "strong") && (hasPrefix(xlit, "betacode:"))) { lexName = "betacode"; // const char *m = strchr(xlit.c_str(), ':'); // strong = ++m; } std::string wordID; if (vkey) { // optimize for bandwidth and use only the verse as the unique entry id wordID += formatted("%d", vkey->getVerse()); } else { wordID = key->getText(); } wordID += formatted("_%s", src.c_str()); // clean up our word ID for XHTML for (unsigned int i = 0; i < wordID.size(); i++) { if ((!isdigit(wordID[i])) && (!isalpha(wordID[i]))) { wordID[i] = '_'; } } // 'p' = 'fillpop' to save bandwidth text += formatted("<span class=\"clk\" onclick=\"p('%s','%s','%s','%s','%s','%s');\" >", lexName.c_str(), lemma.c_str(), wordID.c_str(), morph.c_str(), page.c_str(), modName.c_str()); wordNum++; if (wtag.isEmpty()) { text += "</w></span>"; } } if ((*token == '/') && (token[1] == 'w') && option) { // Word text += "</w></span>"; continue; } // if not a strongs token, keep token in text text.push_back('<'); text.append(token); text.push_back('>'); continue; } if (intoken) { if (tokpos < 2045) { token[tokpos++] = *from; token[tokpos+2] = 0; } } else { text.push_back(*from); } } } return 0; }
OSStatus AKSampler_Plugin::loadPreset() { // Nicer way to load presets using .sfz metadata files. See bottom of AKSampler_Params.h // for instructions to download and set up these presets. const char *pPath = CFStringGetCStringPtr(presetFolderPath, kCFStringEncodingMacRoman); const char *pName = CFStringGetCStringPtr(presetName, kCFStringEncodingMacRoman); printf("loadPreset: %s...", pName); stopAllVoices(); // make sure no voices are active deinit(); // unload any samples already present char buf[1000]; sprintf(buf, "%s/%s.sfz", pPath, pName); FILE* pfile = fopen(buf, "r"); if (!pfile) return fnfErr; int lokey, hikey, pitch, lovel, hivel; bool isLooping; float fLoopStart, fLoopEnd; float volBoost, tuningOffset; char sampleFileName[100]; char *p, *pp; while (fgets(buf, sizeof(buf), pfile)) { p = buf; while (*p != 0 && isspace(*p)) p++; pp = strrchr(p, '\n'); if (pp) *pp = 0; if (hasPrefix(p, "<group>")) { p += 7; lokey = 0; hikey = 127; pitch = 60; pp = strstr(p, " key"); if (pp) { pp = strchr(pp, '='); if (pp) pp++; if (pp) pitch = hikey = lokey = atoi(pp); } pp = strstr(p, "lokey"); if (pp) { pp = strchr(pp, '='); if (pp) pp++; if (pp) lokey = atoi(pp); } pp= strstr(p, "hikey"); if (pp) { pp = strchr(pp, '='); if (pp) pp++; if (pp) hikey = atoi(pp); } pp= strstr(p, "pitch_keycenter"); if (pp) { pp = strchr(pp, '='); if (pp) pp++; if (pp) pitch = atoi(pp); } } else if (hasPrefix(p, "<region>")) { p += 8; lovel = 0; hivel = 127; sampleFileName[0] = 0; isLooping = false; fLoopStart = 0.0f; fLoopEnd = 0.0f; volBoost = 0.0f; tuningOffset = 0.0f; pp = strstr(p, "lovel"); if (pp) { pp = strchr(pp, '='); if (pp) pp++; if (pp) lovel = atoi(pp); } pp = strstr(p, "hivel"); if (pp) { pp = strchr(pp, '='); if (pp) pp++; if (pp) hivel = atoi(pp); } pp = strstr(p, "volume"); if (pp) { pp = strchr(pp, '='); if (pp) pp++; if (pp) volBoost = atof(pp); } pp = strstr(p, "tune"); if (pp) { pp = strchr(pp, '='); if (pp) pp++; if (pp) tuningOffset = atof(pp); } pp = strstr(p, "loop_mode"); if (pp) { isLooping = true; } pp = strstr(p, "loop_start"); if (pp) { pp = strchr(pp, '='); if (pp) pp++; if (pp) fLoopStart = atof(pp); } pp = strstr(p, "loop_end"); if (pp) { pp = strchr(pp, '='); if (pp) pp++; if (pp) fLoopEnd = atof(pp); } pp = strstr(p, "sample"); if (pp) { pp = strchr(pp, '='); if (pp) pp++; while (*pp != 0 && isspace(*pp)) pp++; char* pq = sampleFileName; char* pdot = strrchr(pp, '.'); while (pp < pdot) *pq++ = *pp++; strcpy(pq, ".wv"); } sprintf(buf, "%s/%s", pPath, sampleFileName); AKSampleFileDescriptor sfd; sfd.path = buf; sfd.sampleDescriptor.isLooping = isLooping; sfd.sampleDescriptor.startPoint = 0.0; sfd.sampleDescriptor.loopStartPoint = fLoopStart; sfd.sampleDescriptor.loopEndPoint = fLoopEnd; sfd.sampleDescriptor.endPoint = 0.0f; sfd.sampleDescriptor.noteNumber = pitch; sfd.sampleDescriptor.noteFrequency = NOTE_HZ(sfd.sampleDescriptor.noteNumber - tuningOffset/100.0f); sfd.sampleDescriptor.minimumNoteNumber = lokey; sfd.sampleDescriptor.maximumNoteNumber = hikey; sfd.sampleDescriptor.minimumVelocity = lovel; sfd.sampleDescriptor.maximumVelocity = hivel; loadCompressedSampleFile(sfd, volBoost); } } fclose(pfile); buildKeyMap(); restartVoices(); // now it's safe to start new notes printf("done\n"); return noErr; }
bool String::hasPrefix(String* str){ return hasPrefix(str->c_str()); }