SWBuf parseRangeKey(const char* keyValue, const char* locale) { const char* oldLocale = LocaleMgr::getSystemLocaleMgr()->getDefaultLocaleName(); LocaleMgr::getSystemLocaleMgr()->setDefaultLocaleName(locale); SWBuf ret; VerseKey DefaultVSKey; DefaultVSKey = "jas3:1"; ListKey verses = DefaultVSKey.ParseVerseList(keyValue, DefaultVSKey, true); for (int i = 0; i < verses.Count(); i++) { VerseKey *element = dynamic_cast<VerseKey *>(verses.GetElement(i)); if (element) { if (ret.length()) { ret.append(" "); } ret.appendFormatted( "%s - %s;", (const char*)element->LowerBound(), (const char*)element->UpperBound() ); } else { if (ret.length()) { ret.append(" "); } ret.appendFormatted("%s;", (const char *)*verses.GetElement(i)); } } // cout << ret.c_str() << endl; LocaleMgr::getSystemLocaleMgr()->setDefaultLocaleName(oldLocale); return ret; };
char PapyriPlain::processText (SWBuf &text, const SWKey *key, const SWModule *module) { SWBuf orig = text; const char *from = orig.c_str(); for (text = ""; *from; ++from) { // remove hyphen and whitespace if that is all that separates words // also be sure we're not a double hyphen '--' if ((*from == '-') && (text.length() > 0) && (text[text.length()-1] != '-')) { char remove = 0; const char *c; for (c = from+1; *c; c++) { if ((*c == 10) || (*c == 13)) { remove = 1; } if (!strchr(" \t\n", *c)) { if (remove) remove++; break; } } if (remove > 1) { from = c-1; continue; } } // remove all newlines if ((*from == 10) || (*from == 13)) { if ((text.length()>1) && (text[text.length()-2] != ' ') && (*(from+1) != ' ')) text.append(' '); continue; } // strip odd characters switch (*from) { case '(': case ')': case '[': case ']': case '{': case '}': case '<': case '>': continue; } // if we've made it this far text.append(*from); } return 0; }
ModInfoList *SWMgr_impl::getModInfoList() throw(CORBA::SystemException) { ModInfoList *milist = new ModInfoList; sword::SWModule *module = 0; int size = 0; for (sword::ModMap::iterator it = delegate->Modules.begin(); it != delegate->Modules.end(); it++) { if ((!(it->second->getConfigEntry("CipherKey"))) || (*(it->second->getConfigEntry("CipherKey")))) size++; } milist->length(size); int i = 0; for (sword::ModMap::iterator it = delegate->Modules.begin(); it != delegate->Modules.end(); it++) { module = it->second; if ((!(module->getConfigEntry("CipherKey"))) || (*(module->getConfigEntry("CipherKey")))) { SWBuf type = module->Type(); SWBuf cat = module->getConfigEntry("Category"); if (cat.length() > 0) type = cat; (*milist)[i].name = CORBA::string_dup(module->Name()); (*milist)[i].description = CORBA::string_dup(module->Description()); (*milist)[i].category = CORBA::string_dup(type.c_str()); (*milist)[i++].language = CORBA::string_dup(module->Lang()); } } return milist; }
char *SWModule_impl::getCategory() throw(CORBA::SystemException) { SWBuf type = delegate->Type(); SWBuf cat = delegate->getConfigEntry("Category"); if (cat.length() > 0) type = cat; return CORBA::string_dup((char *)type.c_str()); }
char CipherFilter::processText(SWBuf &text, const SWKey *key, const SWModule *module) { if (text.length() > 2) { //check if it's large enough to substract 2 in the next step. unsigned long len = text.length(); if (!key) { // hack, using key to determine encipher, or decipher cipher->cipherBuf(&len, text.getRawData()); //set buffer to enciphered text memcpy(text.getRawData(), cipher->Buf(), len); // text = cipher->Buf(); //get the deciphered buffer } else if ((unsigned long)key == 1) { cipher->Buf(text.getRawData(), len); memcpy(text.getRawData(), cipher->cipherBuf(&len), len); // text = cipher->cipherBuf(&len); } } return 0; }
void SWMgr::AddStripFilters(SWModule *module, ConfigEntMap §ion) { SWBuf sourceformat; ConfigEntMap::iterator entry; sourceformat = ((entry = section.find("SourceType")) != section.end()) ? (*entry).second : (SWBuf)""; // Temporary: To support old module types if (!sourceformat.length()) { sourceformat = ((entry = section.find("ModDrv")) != section.end()) ? (*entry).second : (SWBuf)""; if (!stricmp(sourceformat.c_str(), "RawGBF")) sourceformat = "GBF"; else sourceformat = ""; } if (!stricmp(sourceformat.c_str(), "GBF")) { module->addStripFilter(gbfplain); } else if (!stricmp(sourceformat.c_str(), "ThML")) { module->addStripFilter(thmlplain); } else if (!stricmp(sourceformat.c_str(), "OSIS")) { module->addStripFilter(osisplain); } else if (!stricmp(sourceformat.c_str(), "TEI")) { module->addStripFilter(teiplain); } if (filterMgr) filterMgr->AddStripFilters(module, section); }
SWBuf SWMgr::getHomeDir() { // figure out 'home' directory for app data SWBuf homeDir = getenv("HOME"); if (!homeDir.length()) { // silly windows homeDir = getenv("APPDATA"); } if (homeDir.length()) { if ((homeDir[homeDir.length()-1] != '\\') && (homeDir[homeDir.length()-1] != '/')) { homeDir += "/"; } } return homeDir; }
const char *SWModule_getEntryAttributes(SWHANDLE hmodule, const char *level1, const char *level2, const char *level3) { SWModule *module = (SWModule *)hmodule; static SWBuf retval; module->renderText(); retval = module->getEntryAttributes()[level1][level2][level3].c_str(); return (retval.length()) ? (const char*)retval.c_str() : NULL; }
void EncodingFilterMgr::AddRawFilters(SWModule *module, ConfigEntMap §ion) { ConfigEntMap::iterator entry; SWBuf encoding = ((entry = section.find("Encoding")) != section.end()) ? (*entry).second : (SWBuf)""; if (!encoding.length() || !stricmp(encoding.c_str(), "Latin-1")) { module->AddRawFilter(latin1utf8); } }
const char *SWModule_getPreverseHeader(SWHANDLE hmodule, const char *key, int pvHeading) { SWModule *module = (SWModule *)hmodule; static SWBuf preverseHeading; char buf[12]; sprintf(buf, "%i", pvHeading); module->setKey(key); module->renderText(); preverseHeading = module->getEntryAttributes()["Heading"]["Preverse"][buf].c_str(); return (preverseHeading.length()) ? (const char*)preverseHeading.c_str() : NULL; }
char OSISRedLetterWords::processText(SWBuf &text, const SWKey *key, const SWModule *module) { if (option) //leave in the red lettered words return 0; SWBuf token; bool intoken = false; SWBuf orig = text; const char *from = orig.c_str(); //taken out of the loop const char* start = 0; const char* end = 0; for (text = ""; *from; from++) { if (*from == '<') { intoken = true; token = ""; continue; } else if (*from == '>') { // process tokens intoken = false; if ((token[0] == 'q') && (token[1] == ' ')) { //q tag start = strstr(token.c_str(), " who=\"Jesus\""); if (start && (strlen(start) >= 12)) { //we found a quote of Jesus Christ end = start+12; //marks the end of the who attribute value text.append('<'); text.append(token, start - (token.c_str())); //the text before the who attr text.append(end, token.c_str() + token.length() - end); //text after the who attr text.append('>'); continue; } } //token not processed, append it. We don't want to alter the text text.append('<'); text.append(token); text.append('>'); continue; } if (intoken) { //copy token token.append(*from); } else { //copy text which is not inside a token text.append(*from); } } return 0; }
const SWBuf URL::decode(const char *encoded) { /*static*/ SWBuf text; text = encoded; SWBuf decoded; const int length = text.length(); int i = 0; while (i < length) { char a = text[i]; if ( a == '+' ) { //handle special cases decoded.append(' '); } else if ( (a == '%') && (i+2 < length)) { //decode the %ab hex encoded char const char b = toupper( text[i+1] ); const char c = toupper( text[i+2] ); if (isxdigit(b) && isxdigit(c)) { //valid %ab part unsigned int dec = 16 * ((b >= 'A' && b <= 'F') ? (b - 'A' + 10) : (b - '0')); //dec value of the most left digit (b) dec += (c >= 'A' && c <= 'F') ? (c - 'A' + 10) : (c - '0'); //dec value of the right digit (c) decoded.append((char)dec); //append the decoded char i += 2; //we jump over the %ab part; we have to leave out three, but the while loop adds one, too } } else { //just append the char decoded.append(a); } i++; } if (decoded.length()) { text = decoded; } return text; }
JNIEXPORT jobjectArray JNICALL Java_org_crosswire_android_sword_SWMgr_getModInfoList (JNIEnv *env, jobject) { init(); int size = 0; for (sword::ModMap::iterator it = mgr->Modules.begin(); it != mgr->Modules.end(); ++it) { if ((!(it->second->getConfigEntry("CipherKey"))) || (*(it->second->getConfigEntry("CipherKey")))) size++; } SWLog::getSystemLog()->logDebug("getModInfoList returning %d length array\n", size); jclass clazzModInfo = env->FindClass("org/crosswire/android/sword/SWMgr$ModInfo"); jfieldID nameID = env->GetFieldID(clazzModInfo, "name", "Ljava/lang/String;"); jfieldID descID = env->GetFieldID(clazzModInfo, "description", "Ljava/lang/String;"); jfieldID catID = env->GetFieldID(clazzModInfo, "category", "Ljava/lang/String;"); jfieldID langID = env->GetFieldID(clazzModInfo, "language", "Ljava/lang/String;"); jfieldID versionID = env->GetFieldID(clazzModInfo, "version", "Ljava/lang/String;"); jfieldID deltaID = env->GetFieldID(clazzModInfo, "delta", "Ljava/lang/String;"); jobjectArray ret = (jobjectArray) env->NewObjectArray(size, clazzModInfo, NULL); int i = 0; for (sword::ModMap::iterator it = mgr->Modules.begin(); it != mgr->Modules.end(); ++it) { SWModule *module = it->second; if ((!(module->getConfigEntry("CipherKey"))) || (*(module->getConfigEntry("CipherKey")))) { SWBuf type = module->Type(); SWBuf cat = module->getConfigEntry("Category"); SWBuf version = module->getConfigEntry("Version"); if (cat.length() > 0) type = cat; jobject modInfo = env->AllocObject(clazzModInfo); jstring val; val = env->NewStringUTF(assureValidUTF8(module->getName())); env->SetObjectField(modInfo, nameID , val); env->DeleteLocalRef(val); val = env->NewStringUTF(assureValidUTF8(module->getDescription())); env->SetObjectField(modInfo, descID , val); env->DeleteLocalRef(val); val = env->NewStringUTF(assureValidUTF8(type.c_str())); env->SetObjectField(modInfo, catID , val); env->DeleteLocalRef(val); val = env->NewStringUTF(assureValidUTF8(module->getLanguage())); env->SetObjectField(modInfo, langID , val); env->DeleteLocalRef(val); val = env->NewStringUTF(assureValidUTF8(version.c_str())); env->SetObjectField(modInfo, versionID, val); env->DeleteLocalRef(val); val = env->NewStringUTF(assureValidUTF8("")); env->SetObjectField(modInfo, deltaID , val); env->DeleteLocalRef(val); env->SetObjectArrayElement(ret, i++, modInfo); env->DeleteLocalRef(modInfo); } } return ret; }
const SWBuf URL::encode(const char *urlText) { /*static*/ SWBuf url; url = urlText; SWBuf buf; const int length = url.length(); for (int i = 0; i < length; i++) { //fill "buf" const char& c = url[i]; buf.append( ((m[c].length()) ? m[c] : SWBuf(c)) ); } url = buf; return url; }
char UTF8NFC::processText(SWBuf &text, const SWKey *key, const SWModule *module) { if ((unsigned long)key < 2) // hack, we're en(1)/de(0)ciphering return -1; err = U_ZERO_ERROR; UnicodeString source(text.getRawData(), text.length(), conv, err); UnicodeString target; err = U_ZERO_ERROR; Normalizer::normalize(source, UNORM_NFC, 0, target, err); err = U_ZERO_ERROR; text.setSize(text.size()*2); // potentially, it can grow to 2x the original size int32_t len = target.extract(text.getRawData(), text.size(), conv, err); text.setSize(len); return 0; }
/* * Class: org_crosswire_android_sword_InstallMgr * Method: getRemoteModuleByName * Signature: (Ljava/lang/String;Ljava/lang/String;)Lorg/crosswire/android/sword/SWModule; */ JNIEXPORT jobject JNICALL Java_org_crosswire_android_sword_InstallMgr_getRemoteModuleByName (JNIEnv *env, jobject me, jstring sourceNameJS, jstring modNameJS) { jobject retVal = 0; initInstall(); const char *sourceName = env->GetStringUTFChars(sourceNameJS, NULL); SWLog::getSystemLog()->logDebug("getRemoteModuleByName: sourceName: %s\n", sourceName); InstallSourceMap::iterator source = installMgr->sources.find(sourceName); env->ReleaseStringUTFChars(sourceNameJS, sourceName); if (source == installMgr->sources.end()) { SWLog::getSystemLog()->logDebug("Couldn't find remote source [%s]\n", sourceName); return 0; } SWMgr *mgr = source->second->getMgr(); const char *modName = env->GetStringUTFChars(modNameJS, NULL); sword::SWModule *module = mgr->getModule(modName); env->ReleaseStringUTFChars(modNameJS, modName); if (module) { SWBuf type = module->Type(); SWBuf cat = module->getConfigEntry("Category"); if (cat.length() > 0) type = cat; jfieldID fieldID; jclass clazzSWModule = env->FindClass("org/crosswire/android/sword/SWModule"); retVal = env->AllocObject(clazzSWModule); fieldID = env->GetFieldID(clazzSWModule, "name", "Ljava/lang/String;"); env->SetObjectField(retVal, fieldID, env->NewStringUTF(assureValidUTF8(module->getName()))); fieldID = env->GetFieldID(clazzSWModule, "description", "Ljava/lang/String;"); env->SetObjectField(retVal, fieldID, env->NewStringUTF(assureValidUTF8(module->getDescription()))); fieldID = env->GetFieldID(clazzSWModule, "category", "Ljava/lang/String;"); env->SetObjectField(retVal, fieldID, env->NewStringUTF(assureValidUTF8(type.c_str()))); fieldID = env->GetFieldID(clazzSWModule, "remoteSourceName", "Ljava/lang/String;"); env->SetObjectField(retVal, fieldID, sourceNameJS); } return retVal; }
char UTF8arShaping::processText(SWBuf &text, const SWKey *key, const SWModule *module) { UChar *ustr, *ustr2; if ((unsigned long)key < 2) // hack, we're en(1)/de(0)ciphering return -1; int32_t len = text.length(); ustr = new UChar[len]; ustr2 = new UChar[len]; // Convert UTF-8 string to UTF-16 (UChars) len = ucnv_toUChars(conv, ustr, len, text.c_str(), -1, &err); len = u_shapeArabic(ustr, len, ustr2, len, U_SHAPE_LETTERS_SHAPE | U_SHAPE_DIGITS_EN2AN, &err); text.setSize(text.size()*2); len = ucnv_fromUChars(conv, text.getRawData(), text.size(), ustr2, len, &err); text.setSize(len); delete [] ustr2; delete [] ustr; return 0; }
SWMgr::SWMgr(const char *iConfigPath, bool autoload, SWFilterMgr *filterMgr, bool multiMod, bool augmentHome) { init(); mgrModeMultiMod = multiMod; SWBuf path; this->filterMgr = filterMgr; if (filterMgr) filterMgr->setParentMgr(this); this->augmentHome = augmentHome; path = iConfigPath; int len = path.length(); if ((len < 1) || ((iConfigPath[len-1] != '\\') && (iConfigPath[len-1] != '/'))) path += "/"; if (FileMgr::existsFile(path.c_str(), "mods.conf")) { stdstr(&prefixPath, path.c_str()); path += "mods.conf"; stdstr(&configPath, path.c_str()); } else { if (FileMgr::existsDir(path.c_str(), "mods.d")) { stdstr(&prefixPath, path.c_str()); path += "mods.d"; stdstr(&configPath, path.c_str()); configType = 1; } } config = 0; sysConfig = 0; if (autoload && configPath) Load(); }
char UTF8NFKD::processText(SWBuf &text, const SWKey *key, const SWModule *module) { if ((unsigned long)key < 2) // hack, we're en(1)/de(0)ciphering return -1; int32_t len = 5 + text.length() * 5; source = new UChar[len + 1]; //each char could become a surrogate pair // Convert UTF-8 string to UTF-16 (UChars) int32_t ulen = ucnv_toUChars(conv, source, len, text.c_str(), -1, &err); target = new UChar[len + 1]; //compatability decomposition ulen = unorm_normalize(source, ulen, UNORM_NFKD, 0, target, len, &err); text.setSize(len); len = ucnv_fromUChars(conv, text.getRawData(), len, target, ulen, &err); text.setSize(len); delete [] source; delete [] target; return 0; }
void SWMgr::AddRenderFilters(SWModule *module, ConfigEntMap §ion) { SWBuf sourceformat; ConfigEntMap::iterator entry; sourceformat = ((entry = section.find("SourceType")) != section.end()) ? (*entry).second : (SWBuf)""; // Temporary: To support old module types // TODO: Remove at 1.6.0 release? if (!sourceformat.length()) { sourceformat = ((entry = section.find("ModDrv")) != section.end()) ? (*entry).second : (SWBuf)""; if (!stricmp(sourceformat.c_str(), "RawGBF")) sourceformat = "GBF"; else sourceformat = ""; } // process module - eg. follows // if (!stricmp(sourceformat.c_str(), "GBF")) { // module->AddRenderFilter(gbftortf); // } if (filterMgr) filterMgr->AddRenderFilters(module, section); }
/* * Class: org_crosswire_android_sword_SWMgr * Method: getModuleByName * Signature: (Ljava/lang/String;)Lorg/crosswire/android/sword/SWModule; */ JNIEXPORT jobject JNICALL Java_org_crosswire_android_sword_SWMgr_getModuleByName (JNIEnv *env, jobject me, jstring modNameJS) { init(); jobject retVal = 0; const char *modName = env->GetStringUTFChars(modNameJS, NULL); sword::SWModule *module = mgr->getModule(modName); env->ReleaseStringUTFChars(modNameJS, modName); if (module) { SWBuf type = module->Type(); SWBuf cat = module->getConfigEntry("Category"); if (cat.length() > 0) type = cat; jfieldID fieldID; jclass clazzSWModule = env->FindClass("org/crosswire/android/sword/SWModule"); retVal = env->AllocObject(clazzSWModule); fieldID = env->GetFieldID(clazzSWModule, "name", "Ljava/lang/String;"); env->SetObjectField(retVal, fieldID, env->NewStringUTF(assureValidUTF8(module->getName()))); fieldID = env->GetFieldID(clazzSWModule, "description", "Ljava/lang/String;"); env->SetObjectField(retVal, fieldID, env->NewStringUTF(assureValidUTF8(module->getDescription()))); fieldID = env->GetFieldID(clazzSWModule, "category", "Ljava/lang/String;"); env->SetObjectField(retVal, fieldID, env->NewStringUTF(assureValidUTF8(type.c_str()))); } return retVal; }
int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "usage: %s <tree/key/data/path>\n", *argv); exit(-1); } TreeKeyIdx *treeKey = new TreeKeyIdx(argv[1]); if (treeKey->Error()) { RawGenBook::createModule(argv[1]); } delete treeKey; RawGenBook *book = new RawGenBook(argv[1]); TreeKeyIdx root = *((TreeKeyIdx *)((SWKey *)(*book))); treeKey = (TreeKeyIdx *)(SWKey *)(*book); SWBuf input; char line[1024]; do { std::cout << "[" << treeKey->getText() << "] > "; fgets(line, 1000, stdin); input = line; input.trim(); if (input.length() > 0) { switch (input[0]) { case 'n': printLocalName(treeKey); break; case 's': setLocalName(treeKey); break; case 'g': gotoPath(treeKey); break; case 'G': assurePath(treeKey); break; case 'p': root.root(); printTree(root, treeKey); break; case 'a': appendSibbling(treeKey); break; case 'c': appendChild(treeKey); break; case 'd': deleteNode(treeKey); break; case 'j': treeKey->nextSibling(); break; case 'k': treeKey->previousSibling(); break; case 'h': treeKey->parent(); break; case 'l': treeKey->firstChild(); break; case 'r': treeKey->root(); break; case 't': setEntryText(book); break; case 'v': viewEntryText(book); break; case 'q': break; case '?': default: std::cout << "\n p - print tree\n"; std::cout << " n - get local name\n"; std::cout << " s - set local name\n"; std::cout << " j - next sibbling\n"; std::cout << " k - previous sibbling\n"; std::cout << " h - parent\n"; std::cout << " l - first child\n"; std::cout << " r - root\n"; std::cout << " g - goto path\n"; std::cout << " G goto path; create if it doesn't exist\n"; std::cout << " a - append sibbling\n"; std::cout << " c - append child\n"; std::cout << " d - delete node\n"; std::cout << " v - view entry text\n"; std::cout << " t - set entry text\n"; std::cout << " q - quit\n\n"; break; } } } while (input.compare("q")); delete treeKey; return 0; }
int main(int argc, char **argv) { // handle options if (argc < 2) usage(*argv); const char *progName = argv[0]; const char *inFileName = argv[1]; SWBuf v11n = "KJV"; SWBuf outPath = "./"; SWBuf locale = "en"; bool fourByteSize = false; bool append = false; int iType = 4; SWBuf cipherKey = ""; SWCompress *compressor = 0; SWBuf compType = ""; for (int i = 2; i < argc; i++) { if (!strcmp(argv[i], "-a")) { append = true; } else if (!strcmp(argv[i], "-z")) { if (fourByteSize) usage(*argv, "Cannot specify both -z and -4"); compType = "ZIP"; if (i+1 < argc && argv[i+1][0] != '-') { switch (argv[++i][0]) { case 'l': compType = "LZSS"; break; case 'z': compType = "ZIP"; break; case 'b': compType = "BZIP2"; break; case 'x': compType = "XZ"; break; } } } else if (!strcmp(argv[i], "-Z")) { if (compType.size()) usage(*argv, "Cannot specify both -z and -Z"); if (fourByteSize) usage(*argv, "Cannot specify both -Z and -4"); compType = "LZSS"; } else if (!strcmp(argv[i], "-4")) { fourByteSize = true; } else if (!strcmp(argv[i], "-b")) { if (i+1 < argc) { iType = atoi(argv[++i]); if ((iType >= 2) && (iType <= 4)) continue; } usage(*argv, "-b requires one of <2|3|4>"); } else if (!strcmp(argv[i], "-o")) { if (i+1 < argc) outPath = argv[++i]; else usage(progName, "-o requires <output_path>"); } else if (!strcmp(argv[i], "-v")) { if (i+1 < argc) v11n = argv[++i]; else usage(progName, "-v requires <v11n>"); } else if (!strcmp(argv[i], "-l")) { if (i+1 < argc) locale = argv[++i]; else usage(progName, "-l requires <locale>"); } else if (!strcmp(argv[i], "-c")) { if (i+1 < argc) cipherKey = argv[++i]; else usage(*argv, "-c requires <cipher_key>"); } else usage(progName, (((SWBuf)"Unknown argument: ")+ argv[i]).c_str()); } // ----------------------------------------------------- const VersificationMgr::System *v = VersificationMgr::getSystemVersificationMgr()->getVersificationSystem(v11n); if (!v) std::cout << "Warning: Versification " << v11n << " not found. Using KJV versification...\n"; if (compType == "LZSS") { compressor = new LZSSCompress(); } else if (compType == "ZIP") { #ifndef EXCLUDEZLIB compressor = new ZipCompress(); #else usage(*argv, "ERROR: SWORD library not compiled with ZIP compression support.\n\tBe sure libz is available when compiling SWORD library"); #endif } else if (compType == "BZIP2") { #ifndef EXCLUDEBZIP2 compressor = new Bzip2Compress(); #else usage(*argv, "ERROR: SWORD library not compiled with bzip2 compression support.\n\tBe sure libbz2 is available when compiling SWORD library"); #endif } else if (compType == "XZ") { #ifndef EXCLUDEXZ compressor = new XzCompress(); #else usage(*argv, "ERROR: SWORD library not compiled with xz compression support.\n\tBe sure liblzma is available when compiling SWORD library"); #endif } // setup module if (!append) { if (compressor) { if (zText::createModule(outPath, iType, v11n)) { fprintf(stderr, "ERROR: %s: couldn't create module at path: %s \n", *argv, outPath.c_str()); exit(-1); } } else { if (!fourByteSize) RawText::createModule(outPath, v11n); else RawText4::createModule(outPath, v11n); } } SWModule *module = 0; if (compressor) { // Create a compressed text module allowing very large entries // Taking defaults except for first, fourth, fifth and last argument module = new zText( outPath, // ipath 0, // iname 0, // idesc iType, // iblockType compressor, // icomp 0, // idisp ENC_UNKNOWN, // enc DIRECTION_LTR, // dir FMT_UNKNOWN, // markup 0, // lang v11n // versification ); } else { module = (!fourByteSize) ? (SWModule *)new RawText(outPath, 0, 0, 0, ENC_UNKNOWN, DIRECTION_LTR, FMT_UNKNOWN, 0, v11n) : (SWModule *)new RawText4(outPath, 0, 0, 0, ENC_UNKNOWN, DIRECTION_LTR, FMT_UNKNOWN, 0, v11n); } SWFilter *cipherFilter = 0; if (cipherKey.length()) { fprintf(stderr, "Adding cipher filter with phrase: %s\n", cipherKey.c_str() ); cipherFilter = new CipherFilter(cipherKey.c_str()); module->addRawFilter(cipherFilter); } // ----------------------------------------------------- // setup locale manager LocaleMgr::getSystemLocaleMgr()->setDefaultLocaleName(locale); // setup module key to allow full range of possible values, and then some VerseKey *vkey = (VerseKey *)module->createKey(); vkey->setIntros(true); vkey->setAutoNormalize(false); vkey->setPersist(true); module->setKey(*vkey); // ----------------------------------------------------- // process input file FileDesc *fd = FileMgr::getSystemFileMgr()->open(inFileName, FileMgr::RDONLY); SWBuf lineBuffer; SWBuf keyBuffer; SWBuf entBuffer; bool more = true; do { more = FileMgr::getLine(fd, lineBuffer)!=0; if (lineBuffer.startsWith("$$$")) { if ((keyBuffer.size()) && (entBuffer.size())) { writeEntry(module, keyBuffer, entBuffer); } keyBuffer = lineBuffer; keyBuffer << 3; keyBuffer.trim(); entBuffer.size(0); } else { if (keyBuffer.size()) { entBuffer += lineBuffer; entBuffer += "\n"; } } } while (more); if ((keyBuffer.size()) && (entBuffer.size())) { writeEntry(module, keyBuffer, entBuffer); } delete module; if (cipherFilter) delete cipherFilter; delete vkey; FileMgr::getSystemFileMgr()->close(fd); return 0; }
int main(int argc, char **argv) { SWBuf program = argv[0]; fprintf(stderr, "You are running %s: $Rev: 2138 $\n", argv[0]); // Let's test our command line arguments if (argc < 3) { usage(*argv); } // variables for arguments, holding defaults SWBuf path = argv[1]; SWBuf teiDoc = argv[2]; SWBuf compType = ""; SWBuf modDrv = ""; SWBuf recommendedPath = "./modules/lexdict/"; SWBuf cipherKey = ""; SWCompress *compressor = 0; for (int i = 3; i < argc; i++) { if (!strcmp(argv[i], "-z")) { if (compType.size()) usage(*argv, "Cannot specify both -z and -Z"); if (modDrv.size()) usage(*argv, "Cannot specify both -z and -s"); compType = "ZIP"; modDrv = "zLD"; recommendedPath += "zld/"; } else if (!strcmp(argv[i], "-Z")) { if (compType.size()) usage(*argv, "Cannot specify both -z and -Z"); if (modDrv.size()) usage(*argv, "Cannot specify both -Z and -s"); compType = "LZSS"; recommendedPath += "zld/"; } else if (!strcmp(argv[i], "-s")) { if (compType.size()) usage(*argv, "Cannot specify both -s and -z or -Z"); if (i+1 < argc) { int size = atoi(argv[++i]); if (size == 2) { modDrv = "RawLD"; recommendedPath += "rawld/"; continue; } if (size == 4) { modDrv = "RawLD4"; recommendedPath += "rawld4/"; continue; } } usage(*argv, "-s requires one of <2|4>"); } else if (!strcmp(argv[i], "-N")) { normalize = false; } else if (!strcmp(argv[i], "-c")) { if (i+1 < argc) cipherKey = argv[++i]; else usage(*argv, "-c requires <cipher_key>"); } else usage(*argv, (((SWBuf)"Unknown argument: ")+ argv[i]).c_str()); } if (!modDrv.size()) { modDrv = "RawLD4"; recommendedPath += "rawld4/"; } #ifndef _ICU_ if (normalize) { normalize = false; cout << program << " is not compiled with support for ICU. Setting -N flag." << endl; } #endif if (compType == "ZIP") { compressor = new ZipCompress(); } else if (compType = "LZSS") { compressor = new LZSSCompress(); } #ifdef DEBUG // cout << "path: " << path << " teiDoc: " << teiDoc << " compressType: " << compType << " ldType: " << modDrv << " cipherKey: " << cipherKey.c_str() << " normalize: " << normalize << "\n"; cout << "path: " << path << " teiDoc: " << teiDoc << " compressType: " << compType << " ldType: " << modDrv << " normalize: " << normalize << "\n"; cout << ""; // exit(-3); #endif SWBuf modName = path; int pathlen = path.length(); char lastChar = path[pathlen - 1]; if (lastChar != '/' && lastChar != '\\') { modName += "/"; } modName += "dict"; SWBuf keyBuf; SWBuf entBuf; SWBuf lineBuf; vector<string> linkBuf; if (modDrv == "zLD") { if (zLD::createModule(modName)) { fprintf(stderr, "error: %s: couldn't create module at path: %s \n", program.c_str(), modName.c_str()); exit(-3); } module = new zLD(modName, 0, 0, 30, compressor); } else if (modDrv == "RawLD") { if (RawLD::createModule(modName)) { fprintf(stderr, "error: %s: couldn't create module at path: %s \n", program.c_str(), modName.c_str()); exit(-3); } module = new RawLD(modName); } else { if (RawLD4::createModule(modName)) { fprintf(stderr, "error: %s: couldn't create module at path: %s \n", program.c_str(), modName.c_str()); exit(-3); } module = new RawLD4(modName); } SWFilter *cipherFilter = 0; if (cipherKey.size()) { fprintf(stderr, "Adding cipher filter with phrase: %s\n", cipherKey.c_str() ); cipherFilter = new CipherFilter(cipherKey.c_str()); module->AddRawFilter(cipherFilter); } if (!module->isWritable()) { fprintf(stderr, "The module is not writable. Writing text to it will not work.\nExiting.\n" ); exit(-1); } // Let's see if we can open our input file ifstream infile(teiDoc); if (infile.fail()) { fprintf(stderr, "error: %s: couldn't open input file: %s \n", program.c_str(), teiDoc.c_str()); exit(-2); } currentKey = module->CreateKey(); currentKey->Persist(1); module->setKey(*currentKey); (*module) = TOP; SWBuf token; SWBuf text; bool intoken = false; char curChar = '\0'; while (infile.good()) { curChar = infile.get(); // skip the character if it is bad. infile.good() will catch the problem if (curChar == -1) { continue; } if (!intoken && curChar == '<') { intoken = true; token = "<"; continue; } if (intoken && curChar == '>') { intoken = false; token.append('>'); XMLTag *t = new XMLTag(token.c_str()); if (!handleToken(text, t)) { text.append(*t); } delete t; continue; } if (intoken) token.append(curChar); else switch (curChar) { case '>' : text.append(">"); break; case '<' : text.append("<"); break; default : text.append(curChar); break; } } // Force the last entry from the text buffer. //text = ""; //writeEntry(*currentKey, text); delete module; delete currentKey; if (cipherFilter) delete cipherFilter; infile.close(); #ifdef _ICU_ if (converted) fprintf(stderr, "tei2mod converted %d verses to UTF-8\n", converted); if (normalized) fprintf(stderr, "tei2mod normalized %d verses to NFC\n", normalized); #endif /* * Suggested module name detection. * Only used for suggesting a conf. * * Various forms of path. * . and .. - no module name given, use "dict". * Or one of the following where z is the module name * and x may be . or .. * z * x/y/z * x/y/z/ * x/y/z/z */ SWBuf suggestedModuleName = path; if (lastChar == '/' || lastChar == '\\') { suggestedModuleName.setSize(--pathlen); } lastChar = suggestedModuleName[pathlen - 1]; if (lastChar == '.') { suggestedModuleName = "???"; } else { /* At this point the suggestion is either * what follows the last / or \ * or the entire string */ const char *m = strrchr(suggestedModuleName.c_str(), '/'); if (!m) { m = strrchr(suggestedModuleName.c_str(), '\\'); } if (m) { suggestedModuleName = m+1; } } recommendedPath += suggestedModuleName; recommendedPath += "/dict"; fprintf(stderr, "\nSuggested conf (replace ??? with appropriate values)\n\n"); fprintf(stderr, "[%s]\n", suggestedModuleName.c_str()); fprintf(stderr, "DataPath=%s\n", recommendedPath.c_str()); fprintf(stderr, "Description=???\n"); fprintf(stderr, "SourceType=TEI\n"); fprintf(stderr, "Encoding=%s\n", (normalize ? "UTF-8" : "???")); fprintf(stderr, "ModDrv=%s\n", modDrv.c_str()); if (compressor) { fprintf(stderr, "CompressType=%s\n", compType.c_str()); } if (cipherKey.size()) { fprintf(stderr, "CipherKey=%s\n", cipherKey.c_str()); } }
char OSISFootnotes::processText(SWBuf &text, const SWKey *key, const SWModule *module) { SWBuf token; bool intoken = false; bool hide = false; SWBuf tagText; XMLTag startTag; SWBuf refs = ""; int footnoteNum = 1; char buf[254]; SWKey *p = (module) ? module->createKey() : (key) ? key->clone() : new VerseKey(); VerseKey *parser = SWDYNAMIC_CAST(VerseKey, p); if (!parser) { delete p; parser = new VerseKey(); } *parser = key->getText(); SWBuf orig = text; const char *from = orig.c_str(); XMLTag tag; bool strongsMarkup = false; for (text = ""; *from; ++from) { // remove all newlines temporarily to fix kjv2003 module if ((*from == 10) || (*from == 13)) { if ((text.length()>1) && (text[text.length()-2] != ' ') && (*(from+1) != ' ')) text.append(' '); continue; } if (*from == '<') { intoken = true; token = ""; continue; } if (*from == '>') { // process tokens intoken = false; if (!strncmp(token, "note", 4) || !strncmp(token.c_str(), "/note", 5)) { tag = token; if (!tag.isEndTag()) { if (tag.getAttribute("type") && (!strcmp("x-strongsMarkup", tag.getAttribute("type")) || !strcmp("strongsMarkup", tag.getAttribute("type"))) // deprecated ) { tag.setEmpty(false); // handle bug in KJV2003 module where some note open tags were <note ... /> strongsMarkup = true; } if (!tag.isEmpty()) { // if ((!tag.isEmpty()) || (SWBuf("strongsMarkup") == tag.getAttribute("type"))) { refs = ""; startTag = tag; hide = true; tagText = ""; continue; } } if (hide && tag.isEndTag()) { if (module->isProcessEntryAttributes() && !strongsMarkup) { //don`t parse strongsMarkup to EntryAttributes as Footnote sprintf(buf, "%i", footnoteNum++); StringList attributes = startTag.getAttributeNames(); for (StringList::const_iterator it = attributes.begin(); it != attributes.end(); it++) { module->getEntryAttributes()["Footnote"][buf][it->c_str()] = startTag.getAttribute(it->c_str()); } module->getEntryAttributes()["Footnote"][buf]["body"] = tagText; startTag.setAttribute("swordFootnote", buf); if ((startTag.getAttribute("type")) && (!strcmp(startTag.getAttribute("type"), "crossReference"))) { if (!refs.length()) refs = parser->parseVerseList(tagText.c_str(), *parser, true).getRangeText(); module->getEntryAttributes()["Footnote"][buf]["refList"] = refs.c_str(); } } hide = false; if (option || (startTag.getAttribute("type") && !strcmp(startTag.getAttribute("type"), "crossReference"))) { // we want the tag in the text; crossReferences are handled by another filter text.append(startTag); // text.append(tagText); // we don't put the body back in because it is retrievable from EntryAttributes["Footnotes"][]["body"]. } else continue; } strongsMarkup = false; } // if not a heading token, keep token in text //if ((!strcmp(tag.getName(), "reference")) && (!tag.isEndTag())) { // SWBuf osisRef = tag.getAttribute("osisRef"); if (!strncmp(token, "reference", 9)) { if (refs.length()) { refs.append("; "); } const char* attr = strstr(token.c_str() + 9, "osisRef=\""); const char* end = attr ? strchr(attr+9, '"') : 0; if (attr && end) { refs.append(attr+9, end-(attr+9)); } } if (!hide) { text.append('<'); text.append(token); text.append('>'); } else { tagText.append('<'); tagText.append(token); tagText.append('>'); } continue; } if (intoken) { //copy token token.append(*from); } else if (!hide) { //copy text which is not inside a token text.append(*from); } else tagText.append(*from); } delete parser; return 0; }
int FTPTransport::copyDirectory(const char *urlPrefix, const char *dir, const char *dest, const char *suffix) { unsigned int i; int retVal = 0; SWBuf url = SWBuf(urlPrefix) + SWBuf(dir); removeTrailingSlash(url); url += '/'; SWLog::getSystemLog()->logWarning("FTPCopy: getting dir %s\n", url.c_str()); vector<struct DirEntry> dirList = getDirList(url.c_str()); if (!dirList.size()) { SWLog::getSystemLog()->logWarning("FTPCopy: failed to read dir %s\n", url.c_str()); return -1; } long totalBytes = 0; for (i = 0; i < dirList.size(); i++) totalBytes += dirList[i].size; long completedBytes = 0; for (i = 0; i < dirList.size(); i++) { struct DirEntry &dirEntry = dirList[i]; SWBuf buffer = (SWBuf)dest; removeTrailingSlash(buffer); buffer += "/"; buffer += dirEntry.name; if (!strcmp(&buffer.c_str()[buffer.length()-strlen(suffix)], suffix)) { SWBuf buffer2 = "Downloading ("; buffer2.appendFormatted("%d", i+1); buffer2 += " of "; buffer2.appendFormatted("%d", dirList.size()); buffer2 += "): "; buffer2 += dirEntry.name; if (statusReporter) statusReporter->preStatus(totalBytes, completedBytes, buffer2.c_str()); FileMgr::createParent(buffer.c_str()); // make sure parent directory exists SWTRY { SWBuf url = (SWBuf)urlPrefix + (SWBuf)dir; removeTrailingSlash(url); url += "/"; url += dirEntry.name; //dont forget the final slash if (!dirEntry.isDirectory) { if (getURL(buffer.c_str(), url.c_str())) { SWLog::getSystemLog()->logWarning("FTPCopy: failed to get file %s\n", url.c_str()); return -2; } completedBytes += dirEntry.size; } else { SWBuf subdir = (SWBuf)dir; removeTrailingSlash(subdir); subdir += (SWBuf)"/" + dirEntry.name; if (copyDirectory(urlPrefix, subdir, buffer.c_str(), suffix)) { SWLog::getSystemLog()->logWarning("FTPCopy: failed to get file %s\n", subdir.c_str()); return -2; } } } SWCATCH (...) {} if (term) { retVal = -3; break; } } }
signed char SWMgr::Load() { signed char ret = 0; if (!config) { // If we weren't passed a config object at construction, find a config file if (!configPath) { // If we weren't passed a config path at construction... SWLog::getSystemLog()->logDebug("LOOKING UP MODULE CONFIGURATION..."); SWConfig *externalSysConf = sysConfig; // if we have a sysConf before findConfig, then we were provided one from an external source. findConfig(&configType, &prefixPath, &configPath, &augPaths, &sysConfig); if (!externalSysConf) mysysconfig = sysConfig; // remind us to delete our own sysConfig in d-tor SWLog::getSystemLog()->logDebug("LOOKING UP MODULE CONFIGURATION COMPLETE."); } if (configPath) { if (configType) loadConfigDir(configPath); else config = myconfig = new SWConfig(configPath); } } if (config) { SectionMap::iterator Sectloop, Sectend; ConfigEntMap::iterator Entryloop, Entryend; DeleteMods(); for (Sectloop = config->Sections.lower_bound("Globals"), Sectend = config->Sections.upper_bound("Globals"); Sectloop != Sectend; Sectloop++) { // scan thru all 'Globals' sections for (Entryloop = (*Sectloop).second.lower_bound("AutoInstall"), Entryend = (*Sectloop).second.upper_bound("AutoInstall"); Entryloop != Entryend; Entryloop++) // scan thru all AutoInstall entries InstallScan((*Entryloop).second.c_str()); // Scan AutoInstall entry directory for new modules and install } if (configType) { // force reload on config object because we may have installed new modules delete myconfig; config = myconfig = 0; loadConfigDir(configPath); } else config->Load(); CreateMods(mgrModeMultiMod); for (std::list<SWBuf>::iterator pathIt = augPaths.begin(); pathIt != augPaths.end(); pathIt++) { augmentModules(pathIt->c_str(), mgrModeMultiMod); } if (augmentHome) { // augment config with ~/.sword/mods.d if it exists --------------------- SWBuf homeDir = getHomeDir(); if (homeDir.length() && configType != 2) { // 2 = user only SWBuf path = homeDir; path += ".sword/"; augmentModules(path.c_str(), mgrModeMultiMod); path = homeDir; path += "sword/"; augmentModules(path.c_str(), mgrModeMultiMod); } } // ------------------------------------------------------------------------- if (!Modules.size()) // config exists, but no modules ret = 1; } else { SWLog::getSystemLog()->logError("SWMgr: Can't find 'mods.conf' or 'mods.d'. Try setting:\n\tSWORD_PATH=<directory containing mods.conf>\n\tOr see the README file for a full description of setup options (%s)", (configPath) ? configPath : "<configPath is null>"); ret = -1; } return ret; }
void SWMgr::findConfig(char *configType, char **prefixPath, char **configPath, std::list<SWBuf> *augPaths, SWConfig **providedSysConf) { SWBuf path; SWBuf sysConfPath; ConfigEntMap::iterator entry; ConfigEntMap::iterator lastEntry; SWConfig *sysConf = 0; SWBuf sysConfDataPath = ""; *configType = 0; SWBuf homeDir = getHomeDir(); // check for a sysConf passed in to us SWLog::getSystemLog()->logDebug("Checking for provided SWConfig(\"sword.conf\")..."); if (providedSysConf && *providedSysConf) { sysConf = *providedSysConf; SWLog::getSystemLog()->logDebug("found."); } // if we haven't been given our datapath in a sysconf, we need to track it down if (!sysConf) { // check working directory SWLog::getSystemLog()->logDebug("Checking working directory for sword.conf..."); if (FileMgr::existsFile(".", "sword.conf")) { SWLog::getSystemLog()->logDebug("Overriding any systemwide or ~/.sword/ sword.conf with one found in current directory."); sysConfPath = "./sword.conf"; sysConf = new SWConfig(sysConfPath); if ((entry = sysConf->Sections["Install"].find("DataPath")) != sysConf->Sections["Install"].end()) { sysConfDataPath = (*entry).second; } if (providedSysConf) { *providedSysConf = sysConf; } else { delete sysConf; sysConf = 0; } } if (!sysConfDataPath.size()) { SWLog::getSystemLog()->logDebug("Checking working directory for mods.conf..."); if (FileMgr::existsFile(".", "mods.conf")) { SWLog::getSystemLog()->logDebug("found."); stdstr(prefixPath, "./"); stdstr(configPath, "./mods.conf"); return; } SWLog::getSystemLog()->logDebug("Checking working directory for mods.d..."); if (FileMgr::existsDir(".", "mods.d")) { SWLog::getSystemLog()->logDebug("found."); stdstr(prefixPath, "./"); stdstr(configPath, "./mods.d"); *configType = 1; return; } // check working directory ../library/ SWLog::getSystemLog()->logDebug("Checking working directory ../library/ for mods.d..."); if (FileMgr::existsDir("../library", "mods.d")) { SWLog::getSystemLog()->logDebug("found."); stdstr(prefixPath, "../library/"); stdstr(configPath, "../library/mods.d"); *configType = 1; return; } // check environment variable SWORD_PATH SWLog::getSystemLog()->logDebug("Checking $SWORD_PATH..."); SWBuf envsworddir = getenv("SWORD_PATH"); if (envsworddir.length()) { SWLog::getSystemLog()->logDebug("found (%s).", envsworddir.c_str()); path = envsworddir; if ((envsworddir[envsworddir.length()-1] != '\\') && (envsworddir[envsworddir.length()-1] != '/')) path += "/"; SWLog::getSystemLog()->logDebug("Checking $SWORD_PATH for mods.conf..."); if (FileMgr::existsFile(path.c_str(), "mods.conf")) { SWLog::getSystemLog()->logDebug("found."); stdstr(prefixPath, path.c_str()); path += "mods.conf"; stdstr(configPath, path.c_str()); return; } SWLog::getSystemLog()->logDebug("Checking $SWORD_PATH for mods.d..."); if (FileMgr::existsDir(path.c_str(), "mods.d")) { SWLog::getSystemLog()->logDebug("found."); stdstr(prefixPath, path.c_str()); path += "mods.d"; stdstr(configPath, path.c_str()); *configType = 1; return; } } // check for systemwide globalConfPath SWLog::getSystemLog()->logDebug("Parsing %s...", globalConfPath); char *globPaths = 0; char *gfp; stdstr(&globPaths, globalConfPath); for (gfp = strtok(globPaths, ":"); gfp; gfp = strtok(0, ":")) { SWLog::getSystemLog()->logDebug("Checking for %s...", gfp); if (FileMgr::existsFile(gfp)) { SWLog::getSystemLog()->logDebug("found."); break; } } if (gfp) sysConfPath = gfp; delete [] globPaths; if (homeDir.length()) { SWBuf tryPath = homeDir; tryPath += ".sword/sword.conf"; if (FileMgr::existsFile(tryPath)) { SWLog::getSystemLog()->logDebug("Overriding any systemwide sword.conf with one found in users home directory (%s)", tryPath.c_str()); sysConfPath = tryPath; } else { SWBuf tryPath = homeDir; tryPath += "sword/sword.conf"; if (FileMgr::existsFile(tryPath)) { SWLog::getSystemLog()->logDebug("Overriding any systemwide sword.conf with one found in users home directory (%s)", tryPath.c_str()); sysConfPath = tryPath; } } } } } if (!sysConf && sysConfPath.size()) { sysConf = new SWConfig(sysConfPath); } if (sysConf) { if ((entry = sysConf->Sections["Install"].find("DataPath")) != sysConf->Sections["Install"].end()) { sysConfDataPath = (*entry).second; } if (sysConfDataPath.size()) { if ((!sysConfDataPath.endsWith("\\")) && (!sysConfDataPath.endsWith("/"))) sysConfDataPath += "/"; path = sysConfDataPath; SWLog::getSystemLog()->logDebug("DataPath in %s is set to %s.", sysConfPath.c_str(), path.c_str()); SWLog::getSystemLog()->logDebug("Checking for mods.conf in DataPath..."); if (FileMgr::existsFile(path.c_str(), "mods.conf")) { SWLog::getSystemLog()->logDebug("found."); stdstr(prefixPath, path.c_str()); path += "mods.conf"; stdstr(configPath, path.c_str()); *configType = 1; } SWLog::getSystemLog()->logDebug("Checking for mods.d in DataPath..."); if (FileMgr::existsDir(path.c_str(), "mods.d")) { SWLog::getSystemLog()->logDebug("found."); stdstr(prefixPath, path.c_str()); path += "mods.d"; stdstr(configPath, path.c_str()); *configType = 1; } } } // do some extra processing of sysConf if we have one if (sysConf) { if (augPaths) { augPaths->clear(); entry = sysConf->Sections["Install"].lower_bound("AugmentPath"); lastEntry = sysConf->Sections["Install"].upper_bound("AugmentPath"); for (;entry != lastEntry; entry++) { path = entry->second; if ((entry->second.c_str()[strlen(entry->second.c_str())-1] != '\\') && (entry->second.c_str()[strlen(entry->second.c_str())-1] != '/')) path += "/"; augPaths->push_back(path); } } if (providedSysConf) { *providedSysConf = sysConf; } else delete sysConf; } if (*configType) return; // WE STILL HAVEN'T FOUND A CONFIGURATION. LET'S LOOK IN SOME OS SPECIFIC // LOCATIONS // // for various flavors of windoze... // check %ALLUSERSPROFILE%/Application Data/sword/ SWLog::getSystemLog()->logDebug("Checking $ALLUSERSPROFILE/Application Data/sword/..."); SWBuf envallusersdir = getenv("ALLUSERSPROFILE"); if (envallusersdir.length()) { SWLog::getSystemLog()->logDebug("found (%s).", envallusersdir.c_str()); path = envallusersdir; if ((!path.endsWith("\\")) && (!path.endsWith("/"))) path += "/"; path += "Application Data/sword/"; SWLog::getSystemLog()->logDebug("Checking %s for mods.d...", path.c_str()); if (FileMgr::existsDir(path.c_str(), "mods.d")) { SWLog::getSystemLog()->logDebug("found."); stdstr(prefixPath, path.c_str()); path += "mods.d"; stdstr(configPath, path.c_str()); *configType = 1; return; } } // for Mac OSX... // check $HOME/Library/Application Support/Sword/ SWLog::getSystemLog()->logDebug("Checking $HOME/Library/Application Support/Sword/..."); SWBuf pathCheck = getHomeDir(); if (pathCheck.length()) { SWLog::getSystemLog()->logDebug("found (%s).", pathCheck.c_str()); path = pathCheck; if ((!path.endsWith("\\")) && (!path.endsWith("/"))) path += "/"; SWLog::getSystemLog()->logDebug("Checking %s for mods.d...", path.c_str()); if (FileMgr::existsDir(path.c_str(), "mods.d")) { SWLog::getSystemLog()->logDebug("found."); stdstr(prefixPath, path.c_str()); path += "mods.d"; stdstr(configPath, path.c_str()); *configType = 1; return; } } // FINALLY CHECK PERSONAL HOME DIRECTORY LOCATIONS // check ~/.sword/ SWLog::getSystemLog()->logDebug("Checking home directory for ~/.sword..."); if (homeDir.length()) { path = homeDir; path += ".sword/"; SWLog::getSystemLog()->logDebug(" Checking for %smods.conf...", path.c_str()); if (FileMgr::existsFile(path.c_str(), "mods.conf")) { SWLog::getSystemLog()->logDebug("found."); stdstr(prefixPath, path.c_str()); path += "mods.conf"; stdstr(configPath, path.c_str()); return; } SWLog::getSystemLog()->logDebug(" Checking for %smods.d...", path.c_str()); if (FileMgr::existsDir(path.c_str(), "mods.d")) { SWLog::getSystemLog()->logDebug("found."); stdstr(prefixPath, path.c_str()); path += "mods.d"; stdstr(configPath, path.c_str()); *configType = 2; return; } path = homeDir; path += "sword/"; SWLog::getSystemLog()->logDebug(" Checking for %smods.d...", path.c_str()); if (FileMgr::existsDir(path.c_str(), "mods.d")) { SWLog::getSystemLog()->logDebug("found."); stdstr(prefixPath, path.c_str()); path += "mods.d"; stdstr(configPath, path.c_str()); *configType = 2; return; } } }
char GBFOSIS::processText(SWBuf &text, const SWKey *key, const SWModule *module) { char token[2048]; //cheesy, we seem to like cheese :) int tokpos = 0; bool intoken = false; bool keepToken = false; // static QuoteStack quoteStack; SWBuf orig = text; SWBuf tmp; SWBuf value; bool suspendTextPassThru = false; bool handled = false; bool newWord = false; bool newText = false; bool lastspace = false; const char *wordStart = text.c_str(); const char *wordEnd = NULL; const char *textStart = NULL; const char *textEnd = NULL; SWBuf textNode = ""; SWBuf buf; text = ""; for (const char* from = orig.c_str(); *from; ++from) { if (*from == '<') { //start of new token detected intoken = true; tokpos = 0; token[0] = 0; token[1] = 0; token[2] = 0; textEnd = from-1; //end of last text node found wordEnd = text.c_str() + text.length();//not good, instead of wordEnd = to! continue; } if (*from == '>') { // process tokens intoken = false; keepToken = false; suspendTextPassThru = false; newWord = true; handled = false; while (wordStart < (text.c_str() + text.length())) { //hack if (strchr(";,. :?!()'\"", *wordStart) && wordStart[0] && wordStart[1]) wordStart++; else break; } while (wordEnd > wordStart) { if (strchr(" ,;:.?!()'\"", *wordEnd)) wordEnd--; else break; } // Scripture Reference if (!strncmp(token, "scripRef", 8)) { suspendTextPassThru = true; newText = true; handled = true; } else if (!strncmp(token, "/scripRef", 9)) { tmp = ""; tmp.append(textStart, (int)(textEnd - textStart)+1); text += VerseKey::convertToOSIS(tmp.c_str(), key); lastspace = false; suspendTextPassThru = false; handled = true; } // Footnote if (!strcmp(token, "RF") || !strncmp(token, "RF ", 3)) { //the GBFFootnotes filter adds the attribute "swordFootnote", we want to catch that, too // pushString(buf, "<reference work=\"Bible.KJV\" reference=\""); text += "<note type=\"x-StudyNote\">"; newText = true; lastspace = false; handled = true; } else if (!strcmp(token, "Rf")) { text += "</note>"; lastspace = false; handled = true; } // hebrew titles if (!strcmp(token, "TH")) { text += "<title type=\"psalm\">"; newText = true; lastspace = false; handled = true; } else if (!strcmp(token, "Th")) { text += "</title>"; lastspace = false; handled = true; } // Italics assume transchange if (!strcmp(token, "FI")) { text += "<transChange type=\"added\">"; newText = true; lastspace = false; handled = true; } else if (!strcmp(token, "Fi")) { text += "</transChange>"; lastspace = false; handled = true; } // less than if (!strcmp(token, "CT")) { text += "<"; newText = true; lastspace = false; handled = true; } // greater than if (!strcmp(token, "CG")) { text += ">"; newText = true; lastspace = false; handled = true; } // Paragraph break. For now use empty paragraph element if (!strcmp(token, "CM")) { text += "<milestone type=\"x-p\" />"; newText = true; lastspace = false; handled = true; } // Figure else if (!strncmp(token, "img ", 4)) { const char *src = strstr(token, "src"); if (!src) // assert we have a src attribute continue; // return false; text += "<figure src=\""; const char *c; for (c = src;((*c) && (*c != '"')); c++); // uncomment for SWORD absolute path logic // if (*(c+1) == '/') { // pushString(buf, "file:"); // pushString(buf, module->getConfigEntry("AbsoluteDataPath")); // if (*((*buf)-1) == '/') // c++; // skip '/' // } // end of uncomment for asolute path logic for (c++;((*c) && (*c != '"')); c++) { text += *c; } text += "\" />"; lastspace = false; handled = true; } // Strongs numbers else if (*token == 'W' && (token[1] == 'G' || token[1] == 'H')) { // Strongs bool divineName = false; value = token+1; // normal strongs number //strstrip(val); if (!strncmp(wordStart, "<w ", 3)) { const char *attStart = strstr(wordStart, "lemma"); if (attStart) { attStart += 7; buf = ""; buf.appendFormatted("strong:%s ", value.c_str()); } else { // no lemma attribute attStart = wordStart + 3; buf = ""; buf.appendFormatted(buf, "lemma=\"strong:%s\" ", value.c_str()); } text.insert(attStart - text.c_str(), buf); } else { //wordStart doesn't point to an existing <w> attribute! if (!strcmp(value.c_str(), "H03068")) { //divineName buf = ""; buf.appendFormatted("<divineName><w lemma=\"strong:%s\">", value.c_str()); divineName = true; } else { buf = ""; buf.appendFormatted("<w lemma=\"strong:%s\">", value.c_str()); } text.insert(wordStart - text.c_str(), buf); if (divineName) { wordStart += 12; text += "</w></divineName>"; } else text += "</w>"; lastspace = false; } handled = true; } // Morphology else if (*token == 'W' && token[1] == 'T') { if (token[2] == 'G' || token[2] == 'H') { // Strongs value = token+2; } else value = token+1; if (!strncmp(wordStart, "<w ", 3)) { const char *attStart = strstr(wordStart, "morph"); if (attStart) { //existing morph attribute, append this one to it attStart += 7; buf = ""; buf.appendFormatted("%s:%s ", "robinson", value.c_str()); } else { // no lemma attribute attStart = wordStart + 3; buf = ""; buf.appendFormatted("morph=\"%s:%s\" ", "robinson", value.c_str()); } text.insert(attStart - text.c_str(), buf); //hack, we have to } else { //no existing <w> attribute fond buf = ""; buf.appendFormatted("<w morph=\"%s:%s\">", "robinson", value.c_str()); text.insert(wordStart - text.c_str(), buf); text += "</w>"; lastspace = false; } handled = true; } if (!keepToken) { if (!handled) { SWLog::getSystemLog()->logError("Unprocessed Token: <%s> in key %s", token, key ? (const char*)*key : "<unknown>"); // exit(-1); } if (from[1] && strchr(" ,;.:?!()'\"", from[1])) { if (lastspace) { text--; } } if (newText) { textStart = from+1; newText = false; } continue; } // if not a strongs token, keep token in text text.appendFormatted("<%s>", token); if (newText) { textStart = text.c_str() + text.length(); newWord = false; } continue; } if (intoken) { if ((tokpos < 2045) && ((*from != 10)&&(*from != 13))) { token[tokpos++] = *from; token[tokpos+2] = 0; } } else { switch (*from) { case '\'': case '\"': case '`': // quoteStack.handleQuote(fromStart, from, &to); text += *from; //from++; //this line removes chars after an apostrophe! Needs fixing. break; default: if (newWord && (*from != ' ')) { wordStart = text.c_str() + text.length(); newWord = false; //fix this if required? //memset(to, 0, 10); } if (!suspendTextPassThru) { text += (*from); lastspace = (*from == ' '); } } } } VerseKey *vkey = SWDYNAMIC_CAST(VerseKey, key); if (vkey) { SWBuf ref = ""; if (vkey->getVerse()) { ref.appendFormatted("\t\t<verse osisID=\"%s\">", vkey->getOSISRef()); } if (ref.length() > 0) { text = ref + text; if (vkey->getVerse()) { VerseKey *tmp = (VerseKey *)vkey->clone(); *tmp = *vkey; tmp->setAutoNormalize(false); tmp->setIntros(true); text += "</verse>"; *tmp = MAXVERSE; if (*vkey == *tmp) { tmp->setVerse(0); // sprintf(ref, "\t</div>"); // pushString(&to, ref); *tmp = MAXCHAPTER; *tmp = MAXVERSE; if (*vkey == *tmp) { tmp->setChapter(0); tmp->setVerse(0); // sprintf(ref, "\t</div>"); // pushString(&to, ref); /* if (!quoteStack.empty()) { SWLog::getSystemLog()->logError("popping unclosed quote at end of book"); quoteStack.clear(); } */ } } delete tmp; } // else if (vkey->Chapter()) { // sprintf(ref, "\t<div type=\"chapter\" osisID=\"%s\">", vkey->getOSISRef()); // } // else sprintf(ref, "\t<div type=\"book\" osisID=\"%s\">", vkey->getOSISRef()); } } return 0; }
char ThMLFootnotes::processText(SWBuf &text, const SWKey *key, const SWModule *module) { SWBuf token; bool intoken = false; bool hide = false; SWBuf tagText; XMLTag startTag; SWBuf refs = ""; int footnoteNum = 1; char buf[254]; SWKey *p = (module) ? module->createKey() : (key) ? key->clone() : new VerseKey(); VerseKey *parser = SWDYNAMIC_CAST(VerseKey, p); if (!parser) { delete p; parser = new VerseKey(); } *parser = key->getText(); SWBuf orig = text; const char *from = orig.c_str(); for (text = ""; *from; from++) { if (*from == '<') { intoken = true; token = ""; continue; } if (*from == '>') { // process tokens intoken = false; XMLTag tag(token); if (!strcmp(tag.getName(), "note")) { if (!tag.isEndTag()) { if (!tag.isEmpty()) { refs = ""; startTag = tag; hide = true; tagText = ""; continue; } } if (hide && tag.isEndTag()) { if (module->isProcessEntryAttributes()) { SWBuf fc = module->getEntryAttributes()["Footnote"]["count"]["value"]; footnoteNum = (fc.length()) ? atoi(fc.c_str()) : 0; sprintf(buf, "%i", ++footnoteNum); module->getEntryAttributes()["Footnote"]["count"]["value"] = buf; StringList attributes = startTag.getAttributeNames(); for (StringList::iterator it = attributes.begin(); it != attributes.end(); it++) { module->getEntryAttributes()["Footnote"][buf][it->c_str()] = startTag.getAttribute(it->c_str()); } module->getEntryAttributes()["Footnote"][buf]["body"] = tagText; startTag.setAttribute("swordFootnote", buf); if ((startTag.getAttribute("type")) && (!strcmp(startTag.getAttribute("type"), "crossReference"))) { if (!refs.length()) refs = parser->parseVerseList(tagText.c_str(), *parser, true).getRangeText(); module->getEntryAttributes()["Footnote"][buf]["refList"] = refs.c_str(); } } hide = false; if ((option) || ((startTag.getAttribute("type") && (!strcmp(startTag.getAttribute("type"), "crossReference"))))) { // we want the tag in the text; crossReferences are handled by another filter text += startTag; text.append(tagText); } else continue; } } // if not a note token, keep token in text if ((!strcmp(tag.getName(), "scripRef")) && (!tag.isEndTag())) { SWBuf osisRef = tag.getAttribute("passage"); if (refs.length()) refs += "; "; refs += osisRef; } if (!hide) { text += '<'; text.append(token); text += '>'; } else { tagText += '<'; tagText.append(token); tagText += '>'; } continue; } if (intoken) { //copy token token += *from; } else if (!hide) { //copy text which is not inside a token text += *from; } else tagText += *from; } delete parser; return 0; }