void Dtime::Time_Label (string label, Units_Type time_format) { String time; if (time_format == NO_UNITS) time_format = Time_Format (); dtime = 0; time = label; time.Trim (" \t"); if (time.empty ()) { exe->Warning ("Time Label Conversion "); return; } if (time.find_first_of (".:") == time.npos) { size_t len = time.length (); //---- scan for clock time ---- if (len >= 3 && len <= 4) { bool flag = false; if (time [0] == '0') { flag = true; } else if (len == 4) { if (time [0] <= '2' && time [2] <= '5') { flag = true; } } else if (time [1] <= '5') { flag = true; } if (flag) { if (len == 4) { time.insert (2, ":"); } else { time.insert (1, ":"); } } } } Time_String (time, time_format); return; }
/** This function aligns the string table to a 4-byte boundary @internalComponent @released @return Error status @param aStr - string to be aligned */ void ElfProducer::AlignString(String& aStr) { if( aStr.size() %4 ){ PLUCHAR aPad = (PLUCHAR)(4 - (aStr.size() %4)); while(aPad--) { aStr.insert(aStr.end(), 0); } } }
void HTMLTextFormControlElement::setRangeText(const String& replacement, unsigned start, unsigned end, const String& selectionMode, ExceptionState& exceptionState) { if (start > end) { exceptionState.throwDOMException(IndexSizeError, "The provided start value (" + String::number(start) + ") is larger than the provided end value (" + String::number(end) + ")."); return; } if (hasAuthorShadowRoot()) return; String text = innerTextValue(); unsigned textLength = text.length(); unsigned replacementLength = replacement.length(); unsigned newSelectionStart = selectionStart(); unsigned newSelectionEnd = selectionEnd(); start = std::min(start, textLength); end = std::min(end, textLength); if (start < end) text.replace(start, end - start, replacement); else text.insert(replacement, start); setInnerTextValue(text); // FIXME: What should happen to the value (as in value()) if there's no renderer? if (!renderer()) return; subtreeHasChanged(); if (equalIgnoringCase(selectionMode, "select")) { newSelectionStart = start; newSelectionEnd = start + replacementLength; } else if (equalIgnoringCase(selectionMode, "start")) newSelectionStart = newSelectionEnd = start; else if (equalIgnoringCase(selectionMode, "end")) newSelectionStart = newSelectionEnd = start + replacementLength; else { // Default is "preserve". long delta = replacementLength - (end - start); if (newSelectionStart > end) newSelectionStart += delta; else if (newSelectionStart > start) newSelectionStart = start; if (newSelectionEnd > end) newSelectionEnd += delta; else if (newSelectionEnd > start) newSelectionEnd = start + replacementLength; } setSelectionRange(newSelectionStart, newSelectionEnd, SelectionHasNoDirection); }
void report() { if (!m_scriptState->contextIsValid()) return; // If execution termination has been triggered, quietly bail out. if (v8::V8::IsExecutionTerminating(m_scriptState->isolate())) return; ExecutionContext* executionContext = m_scriptState->executionContext(); if (!executionContext) return; ScriptState::Scope scope(m_scriptState); v8::Local<v8::Value> value = m_promise.newLocal(m_scriptState->isolate()); v8::Local<v8::Value> reason = m_exception.newLocal(m_scriptState->isolate()); // Either collected or https://crbug.com/450330 if (value.IsEmpty() || !value->IsPromise()) return; ASSERT(!hasHandler()); EventTarget* target = executionContext->errorEventTarget(); if (RuntimeEnabledFeatures::promiseRejectionEventEnabled() && target && !executionContext->shouldSanitizeScriptError(m_resourceName, m_corsStatus)) { PromiseRejectionEventInit init; init.setPromise(ScriptPromise(m_scriptState, value)); init.setReason(ScriptValue(m_scriptState, reason)); init.setCancelable(true); RefPtrWillBeRawPtr<PromiseRejectionEvent> event = PromiseRejectionEvent::create(m_scriptState, EventTypeNames::unhandledrejection, init); // Log to console if event was not preventDefault()'ed. m_shouldLogToConsole = target->dispatchEvent(event); } if (m_shouldLogToConsole) { const String errorMessage = "Uncaught (in promise)"; Vector<ScriptValue> args; args.append(ScriptValue(m_scriptState, v8String(m_scriptState->isolate(), errorMessage))); args.append(ScriptValue(m_scriptState, reason)); RefPtrWillBeRawPtr<ScriptArguments> arguments = ScriptArguments::create(m_scriptState, args); String embedderErrorMessage = m_errorMessage; if (embedderErrorMessage.isEmpty()) embedderErrorMessage = errorMessage; else if (embedderErrorMessage.startsWith("Uncaught ")) embedderErrorMessage.insert(" (in promise)", 8); RefPtrWillBeRawPtr<ConsoleMessage> consoleMessage = ConsoleMessage::create(JSMessageSource, ErrorMessageLevel, embedderErrorMessage, m_resourceName, m_lineNumber, m_columnNumber); consoleMessage->setScriptArguments(arguments); consoleMessage->setCallStack(m_callStack); consoleMessage->setScriptId(m_scriptId); m_consoleMessageId = consoleMessage->assignMessageId(); executionContext->addConsoleMessage(consoleMessage.release()); } m_callStack.clear(); }
//-------------------------------------------------------------------------- // On add - verify data settings //-------------------------------------------------------------------------- bool CustomMaterial::onAdd() { if (Parent::onAdd() == false) return false; mShaderData = dynamic_cast<ShaderData*>(Sim::findObject( mShaderDataName ) ); if(mShaderDataName.isNotEmpty() && mShaderData == NULL) { logError("Failed to find ShaderData %s", mShaderDataName.c_str()); return false; } const char* samplerDecl = "sampler"; S32 i = 0; for (SimFieldDictionaryIterator itr(getFieldDictionary()); *itr; ++itr) { SimFieldDictionary::Entry* entry = *itr; if (dStrStartsWith(entry->slotName, samplerDecl)) { if (i >= MAX_TEX_PER_PASS) { logError("Too many sampler declarations, you may only have %i", MAX_TEX_PER_PASS); return false; } if (dStrlen(entry->slotName) == dStrlen(samplerDecl)) { logError("sampler declarations must have a sampler name, e.g. sampler[\"diffuseMap\"]"); return false; } // Assert sampler names are defined on ShaderData S32 pos = -1; String samplerName = entry->slotName + dStrlen(samplerDecl); samplerName.insert(0, '$'); mShaderData->hasSamplerDef(samplerName, pos); if(pos == -1) { const char *error = (avar("CustomMaterial(%s) bind sampler[%s] and is not present on ShaderData(%s)", getName(), samplerName.c_str(), mShaderDataName.c_str() )); Con::errorf(error); GFXAssertFatal(0, error); continue; } mSamplerNames[pos] = samplerName; mTexFilename[pos] = entry->value; ++i; } } return true; }
void HTMLTextFormControlElement::setRangeText(const String& replacement, unsigned start, unsigned end, const String& selectionMode, ExceptionCode& ec) { if (start > end) { ec = INDEX_SIZE_ERR; return; } String text = innerTextValue(); unsigned textLength = text.length(); unsigned replacementLength = replacement.length(); unsigned newSelectionStart = selectionStart(); unsigned newSelectionEnd = selectionEnd(); start = std::min(start, textLength); end = std::min(end, textLength); if (start < end) text.replace(start, end - start, replacement); else text.insert(replacement, start); setInnerTextValue(text); // FIXME: What should happen to the value (as in value()) if there's no renderer? if (!renderer()) return; subtreeHasChanged(); if (equalIgnoringCase(selectionMode, "select")) { newSelectionStart = start; newSelectionEnd = start + replacementLength; } else if (equalIgnoringCase(selectionMode, "start")) newSelectionStart = newSelectionEnd = start; else if (equalIgnoringCase(selectionMode, "end")) newSelectionStart = newSelectionEnd = start + replacementLength; else { // Default is "preserve". long delta = replacementLength - (end - start); if (newSelectionStart > end) newSelectionStart += delta; else if (newSelectionStart > start) newSelectionStart = start; if (newSelectionEnd > end) newSelectionEnd += delta; else if (newSelectionEnd > start) newSelectionEnd = start + replacementLength; } setSelectionRange(newSelectionStart, newSelectionEnd, SelectionHasNoDirection); }
void CharacterData::insertData(unsigned offset, const String& data, ExceptionCode& ec) { checkCharDataOperation(offset, ec); if (ec) return; String newStr = m_data; newStr.insert(data, offset); setDataAndUpdate(newStr.impl(), offset, 0, data.length()); document()->textInserted(this, offset, data.length()); }
String CVarRecord::generateSyncedStringRepresentation() const { // Replace the old value with the new. std::stringstream ss; if (cvar.getType() == sani::cvarlang::ValueType::StringVal) { String value; cvar.read(value); ss << value; } else if (cvar.getType() == sani::cvarlang::ValueType::IntVal) { int32 value = 0; cvar.read(value); ss << value; } else if (cvar.getType() == sani::cvarlang::ValueType::FloatVal) { float32 value = 0.0f; cvar.read(value); ss << value; } else if (cvar.getType() == sani::cvarlang::ValueType::DoubleVal) { float64 value = 0.0; cvar.read(value); ss << value; } // Create the new representation. const String newValue = ss.str(); String newRepresentation = token.getLine(); if (newValue.size() < originalValue.size()) { // Remove chars. const size_t diff = originalValue.size() - newValue.size(); newRepresentation.erase(indexOfValue, diff); } else if (newValue.size() > originalValue.size()) { // Add chars. const size_t diff = newValue.size() - originalValue.size(); String insertion; insertion.resize(diff, ' '); newRepresentation.insert(indexOfValue, insertion); } newRepresentation.replace(indexOfValue, newValue.size(), newValue); return newRepresentation; }
void DuplicateAmpersand(String& str) { String::size_type pos= str.find(_T('&'), 0); while (pos != String::npos) { str.insert(pos, _T("&")); pos += 2; if (pos >= str.length()) break; pos = str.find(_T('&'), pos); } }
String URI::nativePathToUri(const String& nativePath, Utils::SystemType type) { String uri = nativePath; if (type == Utils::WINDOWS) { // Convert "c:\" to "/c:/" if (uri.length() >= 2 && StringUtils::isAsciiAlphaChar(uri[0]) && uri[1] == ':') uri.insert(0, "/"); // Convert backslashes to forward slashes Utils::stringFindAndReplace(uri, "\\", "/"); } // Encode the uri string to a valid uri uri = URI::uriEncode ( uri ); return uri; }
void CompNovoIdentificationBase::permute_(String prefix, String s, set<String> & permutations) { if (s.size() <= 1) { permutations.insert(prefix + s); } else { for (String::Iterator p = s.begin(); p < s.end(); p++) { char c = *p; p = s.erase(p); permute_(prefix + c, s, permutations); s.insert(p, c); } } }
void InspectorStyleTextEditor::internalReplaceProperty(const InspectorStyleProperty& property, const String& newText, SourceRange* removedRange, unsigned* insertedLength) { const SourceRange& range = property.sourceData.range; long replaceRangeStart = range.start; long replaceRangeEnd = range.end; const UChar* characters = m_styleText.characters(); long newTextLength = newText.length(); String finalNewText = newText; // Removing a property - remove preceding prefix. String fullPrefix = m_format.first + m_format.second; long fullPrefixLength = fullPrefix.length(); if (!newTextLength && fullPrefixLength) { if (replaceRangeStart >= fullPrefixLength && m_styleText.substring(replaceRangeStart - fullPrefixLength, fullPrefixLength) == fullPrefix) replaceRangeStart -= fullPrefixLength; } else if (newTextLength) { if (isHTMLLineBreak(newText.characters()[newTextLength - 1])) { // Coalesce newlines of the original and new property values (to avoid a lot of blank lines while incrementally applying property values). bool foundNewline = false; bool isLastNewline = false; int i; int textLength = m_styleText.length(); for (i = replaceRangeEnd; i < textLength && isSpaceOrNewline(characters[i]); ++i) { isLastNewline = isHTMLLineBreak(characters[i]); if (isLastNewline) foundNewline = true; else if (foundNewline && !isLastNewline) { replaceRangeEnd = i; break; } } if (foundNewline && isLastNewline) replaceRangeEnd = i; } if (fullPrefixLength > replaceRangeStart || m_styleText.substring(replaceRangeStart - fullPrefixLength, fullPrefixLength) != fullPrefix) finalNewText.insert(fullPrefix, 0); } int replacedLength = replaceRangeEnd - replaceRangeStart; m_styleText.replace(replaceRangeStart, replacedLength, finalNewText); *removedRange = SourceRange(replaceRangeStart, replaceRangeEnd); *insertedLength = finalNewText.length(); }
HttpPath IHttpDirectory::getPath() const { OS_LOCK(m_cs); String path; shared_ptr<const IHttpDirectory> directory = get_this_ptr(); while(directory != nullptr) { String name = directory->getName(); OS_ASSERT((name.empty() == false) || (directory->getParent() == nullptr)); if(name.empty() == false) path.insert(0, (OS_HTTP_PATH_SEPARATOR + name).c_str()); directory = directory->getParent(); } return path; }
static HGLOBAL createGlobalImageFileDescriptor(const String& url, const String& title, CachedImage* image) { ASSERT_ARG(image, image); ASSERT(image->image()->data()); HRESULT hr = S_OK; HGLOBAL memObj = 0; String fsPath; memObj = GlobalAlloc(GPTR, sizeof(FILEGROUPDESCRIPTOR)); if (!memObj) return 0; FILEGROUPDESCRIPTOR* fgd = (FILEGROUPDESCRIPTOR*)GlobalLock(memObj); memset(fgd, 0, sizeof(FILEGROUPDESCRIPTOR)); fgd->cItems = 1; fgd->fgd[0].dwFlags = FD_FILESIZE; fgd->fgd[0].nFileSizeLow = image->image()->data()->size(); const String& preferredTitle = title.isEmpty() ? image->response().suggestedFilename() : title; String extension = image->image()->filenameExtension(); if (extension.isEmpty()) { // Do not continue processing in the rare and unusual case where a decoded image is not able // to provide a filename extension. Something tricky (like a bait-n-switch) is going on return 0; } extension.insert(".", 0); fsPath = filesystemPathFromUrlOrTitle(url, preferredTitle, extension.charactersWithNullTermination(), false); if (fsPath.length() <= 0) { GlobalUnlock(memObj); GlobalFree(memObj); return 0; } int maxSize = min(fsPath.length(), WTF_ARRAY_LENGTH(fgd->fgd[0].cFileName)); CopyMemory(fgd->fgd[0].cFileName, (LPCWSTR)fsPath.characters(), maxSize * sizeof(UChar)); GlobalUnlock(memObj); return memObj; }
void CharacterData::replaceData(unsigned offset, unsigned count, const String& data, ExceptionCode& ec) { checkCharDataOperation(offset, ec); if (ec) return; unsigned realCount; if (offset + count > length()) realCount = length() - offset; else realCount = count; String newStr = m_data; newStr.remove(offset, realCount); newStr.insert(data, offset); setDataAndUpdate(newStr.impl(), offset, count, data.length()); // update the markers for spell checking and grammar checking document()->textRemoved(this, offset, realCount); document()->textInserted(this, offset, data.length()); }
String ScriptParser::run(W3GReplay* w3g) { if (!errors.isEmpty()) return errors; ScriptGlobal* global = ScriptGlobal::create(w3g); Array<StackItem> stack; String result = ""; CodeBlock* cur = code; while (cur) { bool sub = false; if (cur->type == BLOCK_FOR) { Array<String> match; if (cur->text.match("for (\\w+) in ([a-zA-Z0-9_.]+)", &match)) { if (cur->child) { ScriptValue* val = global->getGlobalValue(match[2]); if (val && val->getEnumCount() > 0) { StackItem& fs = stack.push(); fs.type = cur->type; fs.list = val; fs.pos = 0; fs.var = match[1]; global->setGlobalValue(match[1], val->getEnum(0)); sub = true; } } } else return mkerror(cur, "Invalid for loop (expected {for <name> in <list>})"); } else if (cur->type == BLOCK_IF || cur->type == BLOCK_ELSEIF) { String result; if (!eval(cur->text.substring(cur->type == BLOCK_IF ? 2 : 6), result, global)) return mkerror(cur, "Invalid condition"); if (!result.isEmpty() && result.icompare("false")) { StackItem& fs = stack.push(); fs.type = cur->type; sub = true; } } else if (cur->type == BLOCK_ALIGN) { StackItem& fs = stack.push(); fs.type = cur->type; fs.pos = result.length(); sub = true; } else if (cur->type == BLOCK_VAR) { ScriptValue* val = global->getGlobalValue(cur->text); if (val) result += val->getValue(); } else if (cur->type == BLOCK_ELSE) { StackItem& fs = stack.push(); fs.type = cur->type; sub = true; } else if (cur->type == BLOCK_TEXT) result += cur->text; if (cur->child && sub) cur = cur->child; else if (cur->next && !sub) cur = cur->next; else { if (!sub) cur = cur->parent; if (cur == NULL) break; int top = stack.length() - 1; if (top < 0 || stack[top].type != cur->type) return mkerror(cur, "Error handling structure"); if (cur->type == BLOCK_FOR) { stack[top].pos++; if (stack[top].pos < stack[top].list->getEnumCount() && cur->child) { cur = cur->child; global->setGlobalValue(stack[top].var, stack[top].list->getEnum(stack[top].pos)); } else { cur = cur->next; global->unsetGlobalValue(stack[top].var); stack.pop(); } } else if (cur->type == BLOCK_IF || cur->type == BLOCK_ELSEIF || cur->type == BLOCK_ELSE) { stack.pop(); while (cur && (cur->type == BLOCK_IF || cur->type == BLOCK_ELSEIF || cur->type == BLOCK_ELSE)) cur = cur->next; } else if (cur->type == BLOCK_ALIGN) { Array<String> match; if (cur->text.match("align (left|right) (\\d+)", &match)) { int len = result.length() - stack[top].pos; int align = match[2].toInt(); if (align > len) { if (match[1] == "left") result += String(' ') * (align - len); else result.insert(stack[top].pos, String(' ') * (align - len)); } } else return mkerror(cur, "Invalid align (expected {align <left|right> <width>})"); stack.pop(); cur = cur->next; } else return mkerror(cur, "Unexpected block type"); } } if (stack.length() != 0) return "Generic script execution error"; delete global; return result; }
void InbandTextTrackPrivateAVF::processCueAttributes(CFAttributedStringRef attributedString, StringBuilder& content, StringBuilder& settings) { // Some of the attributes we translate into per-cue WebVTT settings are are repeated on each part of an attributed string so only // process the first instance of each. enum AttributeFlags { Line = 1 << 0, Position = 1 << 1, Size = 1 << 2, Vertical = 1 << 3, Align = 1 << 4 }; unsigned processed = 0; String attributedStringValue = CFAttributedStringGetString(attributedString); CFIndex length = attributedStringValue.length(); if (!length) return; CFRange effectiveRange = CFRangeMake(0, 0); while ((effectiveRange.location + effectiveRange.length) < length) { CFDictionaryRef attributes = CFAttributedStringGetAttributes(attributedString, effectiveRange.location + effectiveRange.length, &effectiveRange); if (!attributes) continue; StringBuilder tagStart; String tagEnd; CFIndex attributeCount = CFDictionaryGetCount(attributes); Vector<const void*> keys(attributeCount); Vector<const void*> values(attributeCount); CFDictionaryGetKeysAndValues(attributes, keys.data(), values.data()); for (CFIndex i = 0; i < attributeCount; ++i) { CFStringRef key = static_cast<CFStringRef>(keys[i]); CFTypeRef value = values[i]; if (CFGetTypeID(key) != CFStringGetTypeID() || !CFStringGetLength(key)) continue; if (CFStringCompare(key, kCMTextMarkupAttribute_Alignment, 0) == kCFCompareEqualTo) { CFStringRef valueString = static_cast<CFStringRef>(value); if (CFGetTypeID(valueString) != CFStringGetTypeID() || !CFStringGetLength(valueString)) continue; if (processed & Align) continue; processed |= Align; if (CFStringCompare(valueString, kCMTextMarkupAlignmentType_Start, 0) == kCFCompareEqualTo) settings.append("align:start "); else if (CFStringCompare(valueString, kCMTextMarkupAlignmentType_Middle, 0) == kCFCompareEqualTo) settings.append("align:middle "); else if (CFStringCompare(valueString, kCMTextMarkupAlignmentType_End, 0) == kCFCompareEqualTo) settings.append("align:end "); else ASSERT_NOT_REACHED(); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_BoldStyle, 0) == kCFCompareEqualTo) { if (static_cast<CFBooleanRef>(value) != kCFBooleanTrue) continue; tagStart.append("<b>"); tagEnd.insert("</b>", 0); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_ItalicStyle, 0) == kCFCompareEqualTo) { if (static_cast<CFBooleanRef>(value) != kCFBooleanTrue) continue; tagStart.append("<i>"); tagEnd.insert("</i>", 0); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_UnderlineStyle, 0) == kCFCompareEqualTo) { if (static_cast<CFBooleanRef>(value) != kCFBooleanTrue) continue; tagStart.append("<u>"); tagEnd.insert("</u>", 0); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_OrthogonalLinePositionPercentageRelativeToWritingDirection, 0) == kCFCompareEqualTo) { // Ignore the line position if the attributes also specify "size" so we keep WebVTT's default line logic if (CFDictionaryGetValue(attributes, kCMTextMarkupAttribute_WritingDirectionSizePercentage)) continue; if (CFGetTypeID(value) != CFNumberGetTypeID()) continue; if (processed & Line) continue; processed |= Line; CFNumberRef valueNumber = static_cast<CFNumberRef>(value); double position; CFNumberGetValue(valueNumber, kCFNumberFloat64Type, &position); settings.append(String::format("line:%ld%% ", lrint(position))); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_TextPositionPercentageRelativeToWritingDirection, 0) == kCFCompareEqualTo) { if (CFGetTypeID(value) != CFNumberGetTypeID()) continue; if (processed & Position) continue; processed |= Position; CFNumberRef valueNumber = static_cast<CFNumberRef>(value); double position; CFNumberGetValue(valueNumber, kCFNumberFloat64Type, &position); settings.append(String::format("position:%ld%% ", lrint(position))); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_WritingDirectionSizePercentage, 0) == kCFCompareEqualTo) { if (CFGetTypeID(value) != CFNumberGetTypeID()) continue; if (processed & Size) continue; processed |= Size; CFNumberRef valueNumber = static_cast<CFNumberRef>(value); double position; CFNumberGetValue(valueNumber, kCFNumberFloat64Type, &position); settings.append(String::format("size:%ld%% ", lrint(position))); continue; } } content.append(tagStart); content.append(attributedStringValue.substring(effectiveRange.location, effectiveRange.length)); content.append(tagEnd); } }
void InspectorStyleTextEditor::insertProperty(unsigned index, const String& propertyText, unsigned styleBodyLength) { long propertyStart = 0; bool insertLast = true; if (index < m_allProperties->size()) { const InspectorStyleProperty& property = m_allProperties->at(index); if (property.hasSource) { propertyStart = property.sourceData.range.start; // If inserting before a disabled property, it should be shifted, too. insertLast = false; } } bool insertFirstInSource = true; for (unsigned i = 0, size = m_allProperties->size(); i < index && i < size; ++i) { const InspectorStyleProperty& property = m_allProperties->at(i); if (property.hasSource && !property.disabled) { insertFirstInSource = false; break; } } bool insertLastInSource = true; for (unsigned i = index, size = m_allProperties->size(); i < size; ++i) { const InspectorStyleProperty& property = m_allProperties->at(i); if (property.hasSource && !property.disabled) { insertLastInSource = false; break; } } String textToSet = propertyText; int formattingPrependOffset = 0; if (insertLast && !insertFirstInSource) { propertyStart = styleBodyLength; if (propertyStart && textToSet.length()) { const UChar* characters = m_styleText.characters(); long curPos = propertyStart - 1; // The last position of style declaration, since propertyStart points past one. while (curPos && isHTMLSpace(characters[curPos])) --curPos; if (curPos && characters[curPos] != ';') { // Prepend a ";" to the property text if appending to a style declaration where // the last property has no trailing ";". textToSet.insert(";", 0); formattingPrependOffset = 1; } } } const String& formatLineFeed = m_format.first; const String& formatPropertyPrefix = m_format.second; if (insertLastInSource) { long formatPropertyPrefixLength = formatPropertyPrefix.length(); if (!formattingPrependOffset && (propertyStart < formatPropertyPrefixLength || m_styleText.substring(propertyStart - formatPropertyPrefixLength, formatPropertyPrefixLength) != formatPropertyPrefix)) { textToSet.insert(formatPropertyPrefix, formattingPrependOffset); if (!propertyStart || !isHTMLLineBreak(m_styleText[propertyStart - 1])) textToSet.insert(formatLineFeed, formattingPrependOffset); } if (!isHTMLLineBreak(m_styleText[propertyStart])) textToSet.append(formatLineFeed); } else { String fullPrefix = formatLineFeed + formatPropertyPrefix; long fullPrefixLength = fullPrefix.length(); textToSet.append(fullPrefix); if (insertFirstInSource && (propertyStart < fullPrefixLength || m_styleText.substring(propertyStart - fullPrefixLength, fullPrefixLength) != fullPrefix)) textToSet.insert(fullPrefix, formattingPrependOffset); } m_styleText.insert(textToSet, propertyStart); // Recompute disabled property ranges after an inserted property. long propertyLengthDelta = textToSet.length(); shiftDisabledProperties(disabledIndexByOrdinal(index, true), propertyLengthDelta); }
void InbandTextTrackPrivateAVF::processCueAttributes(CFAttributedStringRef attributedString, GenericCueData* cueData) { // Some of the attributes we translate into per-cue WebVTT settings are are repeated on each part of an attributed string so only // process the first instance of each. enum AttributeFlags { Line = 1 << 0, Position = 1 << 1, Size = 1 << 2, Vertical = 1 << 3, Align = 1 << 4, FontName = 1 << 5 }; unsigned processed = 0; StringBuilder content; String attributedStringValue = CFAttributedStringGetString(attributedString); CFIndex length = attributedStringValue.length(); if (!length) return; CFRange effectiveRange = CFRangeMake(0, 0); while ((effectiveRange.location + effectiveRange.length) < length) { CFDictionaryRef attributes = CFAttributedStringGetAttributes(attributedString, effectiveRange.location + effectiveRange.length, &effectiveRange); if (!attributes) continue; StringBuilder tagStart; CFStringRef valueString; String tagEnd; CFIndex attributeCount = CFDictionaryGetCount(attributes); Vector<const void*> keys(attributeCount); Vector<const void*> values(attributeCount); CFDictionaryGetKeysAndValues(attributes, keys.data(), values.data()); for (CFIndex i = 0; i < attributeCount; ++i) { CFStringRef key = static_cast<CFStringRef>(keys[i]); CFTypeRef value = values[i]; if (CFGetTypeID(key) != CFStringGetTypeID() || !CFStringGetLength(key)) continue; if (CFStringCompare(key, kCMTextMarkupAttribute_Alignment, 0) == kCFCompareEqualTo) { valueString = static_cast<CFStringRef>(value); if (CFGetTypeID(valueString) != CFStringGetTypeID() || !CFStringGetLength(valueString)) continue; if (processed & Align) continue; processed |= Align; if (CFStringCompare(valueString, kCMTextMarkupAlignmentType_Start, 0) == kCFCompareEqualTo) cueData->setAlign(GenericCueData::Start); else if (CFStringCompare(valueString, kCMTextMarkupAlignmentType_Middle, 0) == kCFCompareEqualTo) cueData->setAlign(GenericCueData::Middle); else if (CFStringCompare(valueString, kCMTextMarkupAlignmentType_End, 0) == kCFCompareEqualTo) cueData->setAlign(GenericCueData::End); else ASSERT_NOT_REACHED(); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_BoldStyle, 0) == kCFCompareEqualTo) { if (static_cast<CFBooleanRef>(value) != kCFBooleanTrue) continue; tagStart.append("<b>"); tagEnd.insert("</b>", 0); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_ItalicStyle, 0) == kCFCompareEqualTo) { if (static_cast<CFBooleanRef>(value) != kCFBooleanTrue) continue; tagStart.append("<i>"); tagEnd.insert("</i>", 0); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_UnderlineStyle, 0) == kCFCompareEqualTo) { if (static_cast<CFBooleanRef>(value) != kCFBooleanTrue) continue; tagStart.append("<u>"); tagEnd.insert("</u>", 0); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_OrthogonalLinePositionPercentageRelativeToWritingDirection, 0) == kCFCompareEqualTo) { if (CFGetTypeID(value) != CFNumberGetTypeID()) continue; if (processed & Line) continue; processed |= Line; CFNumberRef valueNumber = static_cast<CFNumberRef>(value); double line; CFNumberGetValue(valueNumber, kCFNumberFloat64Type, &line); cueData->setLine(line); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_TextPositionPercentageRelativeToWritingDirection, 0) == kCFCompareEqualTo) { if (CFGetTypeID(value) != CFNumberGetTypeID()) continue; if (processed & Position) continue; processed |= Position; CFNumberRef valueNumber = static_cast<CFNumberRef>(value); double position; CFNumberGetValue(valueNumber, kCFNumberFloat64Type, &position); cueData->setPosition(position); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_WritingDirectionSizePercentage, 0) == kCFCompareEqualTo) { if (CFGetTypeID(value) != CFNumberGetTypeID()) continue; if (processed & Size) continue; processed |= Size; CFNumberRef valueNumber = static_cast<CFNumberRef>(value); double size; CFNumberGetValue(valueNumber, kCFNumberFloat64Type, &size); cueData->setSize(size); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_VerticalLayout, 0) == kCFCompareEqualTo) { valueString = static_cast<CFStringRef>(value); if (CFGetTypeID(valueString) != CFStringGetTypeID() || !CFStringGetLength(valueString)) continue; if (CFStringCompare(valueString, kCMTextVerticalLayout_LeftToRight, 0) == kCFCompareEqualTo) tagStart.append(leftToRightMark); else if (CFStringCompare(valueString, kCMTextVerticalLayout_RightToLeft, 0) == kCFCompareEqualTo) tagStart.append(rightToLeftMark); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_BaseFontSizePercentageRelativeToVideoHeight, 0) == kCFCompareEqualTo) { if (CFGetTypeID(value) != CFNumberGetTypeID()) continue; CFNumberRef valueNumber = static_cast<CFNumberRef>(value); double baseFontSize; CFNumberGetValue(valueNumber, kCFNumberFloat64Type, &baseFontSize); cueData->setBaseFontSize(baseFontSize); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_RelativeFontSize, 0) == kCFCompareEqualTo) { if (CFGetTypeID(value) != CFNumberGetTypeID()) continue; CFNumberRef valueNumber = static_cast<CFNumberRef>(value); double relativeFontSize; CFNumberGetValue(valueNumber, kCFNumberFloat64Type, &relativeFontSize); cueData->setRelativeFontSize(relativeFontSize); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_FontFamilyName, 0) == kCFCompareEqualTo) { valueString = static_cast<CFStringRef>(value); if (CFGetTypeID(valueString) != CFStringGetTypeID() || !CFStringGetLength(valueString)) continue; if (processed & FontName) continue; processed |= FontName; cueData->setFontName(valueString); continue; } if (CFStringCompare(key, kCMTextMarkupAttribute_ForegroundColorARGB, 0) == kCFCompareEqualTo) { CFArrayRef arrayValue = static_cast<CFArrayRef>(value); if (CFGetTypeID(arrayValue) != CFArrayGetTypeID()) continue; RGBA32 color; if (!makeRGBA32FromARGBCFArray(arrayValue, color)) continue; cueData->setForegroundColor(color); } if (CFStringCompare(key, kCMTextMarkupAttribute_BackgroundColorARGB, 0) == kCFCompareEqualTo) { CFArrayRef arrayValue = static_cast<CFArrayRef>(value); if (CFGetTypeID(arrayValue) != CFArrayGetTypeID()) continue; RGBA32 color; if (!makeRGBA32FromARGBCFArray(arrayValue, color)) continue; cueData->setBackgroundColor(color); } if (CFStringCompare(key, kCMTextMarkupAttribute_CharacterBackgroundColorARGB, 0) == kCFCompareEqualTo) { CFArrayRef arrayValue = static_cast<CFArrayRef>(value); if (CFGetTypeID(arrayValue) != CFArrayGetTypeID()) continue; RGBA32 color; if (!makeRGBA32FromARGBCFArray(arrayValue, color)) continue; cueData->setHighlightColor(color); } } content.append(tagStart); content.append(attributedStringValue.substring(effectiveRange.location, effectiveRange.length)); content.append(tagEnd); } if (content.length()) cueData->setContent(content.toString()); }
void StructParser::amendHeaderFile(const File& file) { MetricsTimer timer(fmt("Code generation for {}", file.fileName())); String raw = file.readAllText(); ParsingContext context; Sequence<StructInfo> infos = parseStructData(context,raw); Arx::String fileName = file.fileName(); Arx::File generatedHeaderFile = file.parent().relativeFile(fileName + "_generated.h"); Arx::File generatedCppFile = file.parent().relativeFile(fileName + "_generated.cpp"); String genHead; genHead.append("// START_GENERATED_CODE\n"); genHead.append("#ifndef AXM_PARSER_H\n" "\t#ifndef AXM_FWD_DECL\n" "\t\tclass AxmNode;\n" "\t\t#define AXM_FWD_DECL\n" "\t#endif\n" "#endif\n" "#ifndef INTROSPECTION_H\n" "\t#ifndef INTROSPECTION_FWD_DECL\n" "\t\tclass StructInfo;\n" "\t\t#define INTROSPECTION_FWD_DECL\n" "\t#endif\n" "#endif\n"); String genCpp; genCpp.append("// START_GENERATED_CODE\n" "#include <conf/AxmParser.h>\n" "#include <core/Introspection.h>\n"); genCpp.append(Format::format("#include \"{}\"\n", fileName)); for (const StructInfo& info : infos) { Noto::info("\tProcessing struct info: {}", info.name); genHead.append(generateReadFunctionDecl(info).raw()); genHead.append(";\n"); genHead.append(Format::format("{};\n",generateIntrospectionFunctionDecl(info).raw())); genCpp.append(generateReadFunction(info).raw()); genCpp.append("\n"); genCpp.append(Format::format("{};\n",generateIntrospectionFunction(info).raw())); } String existingGenHead = generatedHeaderFile.exists() ? generatedHeaderFile.readAllText() : ""; String existingGenCpp = generatedCppFile.exists() ? generatedCppFile.readAllText() : ""; if (genHead.size() != existingGenHead.size() || genHead != existingGenHead) { Noto::info("\tRewriting generated header for {}", file.fileName()); generatedHeaderFile.write(genHead); } if (genCpp.size() != existingGenCpp.size() || genCpp != existingGenCpp) { Noto::info("\tRewriting generated cpp for {}", file.fileName()); generatedCppFile.write(genCpp); } Arx::String includeGeneratedIdent = "// Include Generated"; int existingIncludeEnd = raw.reverseFind(includeGeneratedIdent); if (existingIncludeEnd == -1) { Noto::info("\tRewriting file to include generated header {}", generatedHeaderFile.path); int lindex = raw.reverseFind("#endif"); raw.insert(Format::format("#include \"{}\" {}\n", generatedHeaderFile.fileName(), includeGeneratedIdent), lindex); file.write(raw); Arx::File mainCpp = file.withExtension(".cpp"); Arx::String cppRaw; if (mainCpp.exists()) { cppRaw = mainCpp.readAllText(); } if (!cppRaw.contains(includeGeneratedIdent)) { Noto::info("Rewriting cpp file to include generated cpp {}", generatedCppFile.path); cppRaw.append(Format::format("#include \"{}\" {}\n", generatedCppFile.fileName(), includeGeneratedIdent)); mainCpp.write(cppRaw); } } timer.printElapsed(); }