String String::filenameBasePath(const char* szText) { String sPath = szText; String sPart; if (sPath.endsWith("/") #if defined(WIN32) || sPath.endsWith("\\") #endif ) { // Already is a base path } else { if (sPath.reverseToken("/" #if defined(WIN32) "\\" #endif , sPart)) { sPath.append(szText + sPath.bytes(), ::strlen(szText) - (sPath.bytes() + sPart.bytes())); } } return sPath; }
bool NumberLocalizer::detectSignAndGetDigitRange(const String& input, bool& isNegative, unsigned& startIndex, unsigned& endIndex) { startIndex = 0; endIndex = input.length(); if (m_negativePrefix.isEmpty() && m_negativeSuffix.isEmpty()) { if (input.startsWith(m_positivePrefix) && input.endsWith(m_positiveSuffix)) { isNegative = false; startIndex = m_positivePrefix.length(); endIndex -= m_positiveSuffix.length(); } else isNegative = true; } else { if (input.startsWith(m_negativePrefix) && input.endsWith(m_negativeSuffix)) { isNegative = true; startIndex = m_negativePrefix.length(); endIndex -= m_negativeSuffix.length(); } else { isNegative = false; if (input.startsWith(m_positivePrefix) && input.endsWith(m_positiveSuffix)) { startIndex = m_positivePrefix.length(); endIndex -= m_positiveSuffix.length(); } else return false; } } return true; }
static int getNumpadKeyCode (const String& desc) { if (desc.containsIgnoreCase (numberPadPrefix())) { auto lastChar = desc.trimEnd().getLastCharacter(); switch (lastChar) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return (int) (KeyPress::numberPad0 + (int) lastChar - '0'); case '+': return KeyPress::numberPadAdd; case '-': return KeyPress::numberPadSubtract; case '*': return KeyPress::numberPadMultiply; case '/': return KeyPress::numberPadDivide; case '.': return KeyPress::numberPadDecimalPoint; case '=': return KeyPress::numberPadEquals; default: break; } if (desc.endsWith ("separator")) return KeyPress::numberPadSeparator; if (desc.endsWith ("delete")) return KeyPress::numberPadDelete; } return 0; }
// Callback for messages, arrived from MQTT server void onMessageReceived(String topic, String message) { if (topic.endsWith("Firmware")) { if (message.equals("UPDATE")) { OtaUpdate(); } } if (topic.endsWith("Lunch")) { if (topic.equals(mqtt_client + "/Lunch")) { // My own message } else { messageSentByMe = false; } if (message.equals("ON")) { indicationState = INDICATION_LUNCH; } else { indicationState = INDICATION_CONNECTED; } } Serial.print(topic); Serial.print(":\r\n\t"); // Pretify alignment for printing Serial.println(message); WifiAccessPoint.enable(false); }
void HTMLTextFormControlElement::setInnerTextValue(const String& value) { TextControlInnerTextElement* innerText = innerTextElement(); if (!innerText) return; ASSERT(isTextFormControl()); String previousValue = innerTextValueFrom(*innerText); bool textIsChanged = value != previousValue; if (textIsChanged || !innerText->hasChildNodes()) { #if HAVE(ACCESSIBILITY) && !PLATFORM(COCOA) if (textIsChanged && renderer()) { if (AXObjectCache* cache = document().existingAXObjectCache()) cache->postNotification(this, AXObjectCache::AXValueChanged, TargetObservableParent); } #endif innerText->setInnerText(value, ASSERT_NO_EXCEPTION); if (value.endsWith('\n') || value.endsWith('\r')) innerText->appendChild(HTMLBRElement::create(document()), ASSERT_NO_EXCEPTION); #if HAVE(ACCESSIBILITY) && PLATFORM(COCOA) if (textIsChanged && renderer()) { if (AXObjectCache* cache = document().existingAXObjectCache()) cache->postTextReplacementNotification(this, AXTextEditTypeDelete, previousValue, AXTextEditTypeInsert, value, VisiblePosition(Position(this, Position::PositionIsBeforeAnchor))); } #endif } setFormControlValueMatchesRenderer(true); }
static bool isYouTubeUrl(const KURL& url, const String& mimeType) { String host = url.host(); bool youtube = host.endsWith("youtube.com") || host.endsWith("youtube-nocookie.com"); return youtube && isValidYouTubeVideo(url.path()) && equalIgnoringCase(mimeType, "application/x-shockwave-flash"); }
inline SVGLengthType stringToLengthType(const String& string) { if (string.endsWith("%")) return LengthTypePercentage; else if (string.endsWith("em")) return LengthTypeEMS; else if (string.endsWith("ex")) return LengthTypeEXS; else if (string.endsWith("px")) return LengthTypePX; else if (string.endsWith("cm")) return LengthTypeCM; else if (string.endsWith("mm")) return LengthTypeMM; else if (string.endsWith("in")) return LengthTypeIN; else if (string.endsWith("pt")) return LengthTypePT; else if (string.endsWith("pc")) return LengthTypePC; else if (!string.isEmpty()) return LengthTypeNumber; return LengthTypeUnknown; }
bool LayoutEditor::growInside(String propertyName, CSSPrimitiveValue* value) { FloatQuad content1, padding1, border1, margin1; InspectorHighlight::buildNodeQuads(m_element.get(), &content1, &padding1, &border1, &margin1); CSSStyleDeclaration* elementStyle = m_element->style(); if (!elementStyle) return false; String initialValue = elementStyle->getPropertyValue(propertyName); String initialPriority = elementStyle->getPropertyPriority(propertyName); String newValue; if (value) newValue = String::format("%f", value->getFloatValue() + 1) + CSSPrimitiveValue::unitTypeToString(value->typeWithCalcResolved()); else newValue = "5px"; TrackExceptionState exceptionState; elementStyle->setProperty(propertyName, newValue, "important", exceptionState); m_element->ownerDocument()->updateLayout(); FloatQuad content2, padding2, border2, margin2; InspectorHighlight::buildNodeQuads(m_element.get(), &content2, &padding2, &border2, &margin2); elementStyle->setProperty(propertyName, initialValue, initialPriority, exceptionState); m_element->ownerDocument()->updateLayout(); float eps = 0.0001; FloatRect boundingBox1, boundingBox2; if (propertyName.startsWith("padding")) { boundingBox1 = padding1.boundingBox(); boundingBox2 = padding2.boundingBox(); } else { boundingBox1 = margin1.boundingBox(); boundingBox2 = margin2.boundingBox(); } if (propertyName.endsWith("left")) return std::abs(boundingBox1.x() - boundingBox2.x() ) < eps; if (propertyName.endsWith("right")) return std::abs(boundingBox1.maxX() - boundingBox2.maxX() ) < eps; if (propertyName.endsWith("top")) return std::abs(boundingBox1.y() - boundingBox2.y()) < eps; if (propertyName.endsWith("bottom")) return std::abs(boundingBox1.maxY() - boundingBox2.maxY()) < eps; return false; }
bool loadFromSdCard(String path){ String dataType = "text/plain"; if(path.endsWith("/")) path += "index.htm"; if(path.endsWith(".src")) path = path.substring(0, path.lastIndexOf(".")); else if(path.endsWith(".htm")) dataType = "text/html"; else if(path.endsWith(".css")) dataType = "text/css"; else if(path.endsWith(".js")) dataType = "application/javascript"; else if(path.endsWith(".png")) dataType = "image/png"; else if(path.endsWith(".gif")) dataType = "image/gif"; else if(path.endsWith(".jpg")) dataType = "image/jpeg"; else if(path.endsWith(".ico")) dataType = "image/x-icon"; else if(path.endsWith(".xml")) dataType = "text/xml"; else if(path.endsWith(".pdf")) dataType = "application/pdf"; else if(path.endsWith(".zip")) dataType = "application/zip"; File dataFile = SD.open(path.c_str()); if(dataFile.isDirectory()){ path += "/index.htm"; dataType = "text/html"; dataFile = SD.open(path.c_str()); } if (!dataFile) return false; if (server.hasArg("download")) dataType = "application/octet-stream"; if (server.streamFile(dataFile, dataType) != dataFile.size()) { DBG_OUTPUT_PORT.println("Sent less data than expected!"); } dataFile.close(); return true; }
String pathByAppendingComponent(const String& path, const String& component) { if (path.endsWith("/")) return path + component; else return path + "/" + component; }
/* static */ void WebKitCSSKeyframeRule::parseKeyString(const String& s, Vector<float>& keys) { keys.clear(); Vector<String> strings; s.split(',', strings); for (size_t i = 0; i < strings.size(); ++i) { float key = -1; String cur = strings[i].stripWhiteSpace(); // For now the syntax MUST be 'xxx%' or 'from' or 'to', where xxx is a legal floating point number if (cur == "from") key = 0; else if (cur == "to") key = 1; else if (cur.endsWith("%")) { float k = cur.substring(0, cur.length() - 1).toFloat(); if (k >= 0 && k <= 100) key = k/100; } if (key < 0) { keys.clear(); return; } else keys.append(key); } }
MediaPlayer::SupportsType MediaPlayer::supportsType(const MediaEngineSupportParameters& parameters, const MediaPlayerSupportsTypeClient* client) { // 4.8.10.3 MIME types - The canPlayType(type) method must return the empty string if type is a type that the // user agent knows it cannot render or is the type "application/octet-stream" if (parameters.type == applicationOctetStream()) return IsNotSupported; MediaPlayerFactory* engine = bestMediaEngineForSupportParameters(parameters); if (!engine) return IsNotSupported; #if PLATFORM(COCOA) // YouTube will ask if the HTMLMediaElement canPlayType video/webm, then // video/x-flv, then finally video/mp4, and will then load a URL of the first type // in that list which returns "probably". When Perian is installed, // MediaPlayerPrivateQTKit claims to support both video/webm and video/x-flv, but // due to a bug in Perian, loading media in these formats will sometimes fail on // slow connections. <https://bugs.webkit.org/show_bug.cgi?id=86409> if (client && client->mediaPlayerNeedsSiteSpecificHacks()) { String host = client->mediaPlayerDocumentHost(); if ((host.endsWith(".youtube.com", false) || equalIgnoringCase("youtube.com", host)) && (parameters.type.startsWith("video/webm", false) || parameters.type.startsWith("video/x-flv", false))) return IsNotSupported; } #else UNUSED_PARAM(client); #endif return engine->supportsTypeAndCodecs(parameters); }
/* ====================================================================== Function: handleFileRead Purpose : return content of a file stored on SPIFFS file system Input : file path Output : true if file found and sent Comments: - ====================================================================== */ bool handleFileRead(String path) { if ( path.endsWith("/") ) path += "index.htm"; String contentType = getContentType(path); String pathWithGz = path + ".gz"; DebugF("handleFileRead "); Debug(path); if(SPIFFS.exists(pathWithGz) || SPIFFS.exists(path)) { if( SPIFFS.exists(pathWithGz) ){ path += ".gz"; DebugF(".gz"); } DebuglnF(" found on FS"); File file = SPIFFS.open(path, "r"); size_t sent = server.streamFile(file, contentType); file.close(); return true; } Debugln(""); server.send(404, "text/plain", "File Not Found"); return false; }
SMILTime SVGSMILElement::parseOffsetValue(const String& data) { bool ok; double result = 0; String parse = data.stripWhiteSpace(); if (parse.endsWith('h')) result = parse.left(parse.length() - 1).toDouble(&ok) * 60 * 60; else if (parse.endsWith("min")) result = parse.left(parse.length() - 3).toDouble(&ok) * 60; else if (parse.endsWith("ms")) result = parse.left(parse.length() - 2).toDouble(&ok) / 1000; else if (parse.endsWith('s')) result = parse.left(parse.length() - 1).toDouble(&ok); else result = parse.toDouble(&ok); if (!ok || !SMILTime(result).isFinite()) return SMILTime::unresolved(); return result; }
void HTMLTextFormControlElement::setInnerTextValue(const String& value) { if (!isTextFormControl()) return; bool textIsChanged = value != innerTextValue(); if (textIsChanged || !innerTextElement()->hasChildNodes()) { if (textIsChanged && renderer()) { if (AXObjectCache* cache = document().existingAXObjectCache()) cache->postNotification(this, AXObjectCache::AXValueChanged, TargetObservableParent); } innerTextElement()->setInnerText(value, ASSERT_NO_EXCEPTION); if (value.endsWith('\n') || value.endsWith('\r')) innerTextElement()->appendChild(HTMLBRElement::create(document()), ASSERT_NO_EXCEPTION); } setFormControlValueMatchesRenderer(true); }
void handleDataURL(ResourceHandle* handle) { ASSERT(handle->firstRequest().url().protocolIs("data")); String url = handle->firstRequest().url().string(); int index = url.find(','); if (index == -1) { handle->client()->cannotShowURL(handle); return; } String mediaType = url.substring(5, index - 5); String data = url.substring(index + 1); bool base64 = mediaType.endsWith(";base64", false); if (base64) mediaType = mediaType.left(mediaType.length() - 7); if (mediaType.isEmpty()) mediaType = "text/plain"; String mimeType = extractMIMETypeFromMediaType(mediaType); String charset = extractCharsetFromMediaType(mediaType); if (charset.isEmpty()) charset = "US-ASCII"; ResourceResponse response; response.setMimeType(mimeType); response.setTextEncodingName(charset); response.setURL(handle->firstRequest().url()); if (base64) { data = decodeURLEscapeSequences(data); handle->client()->didReceiveResponse(handle, response); Vector<char> out; if (base64Decode(data, out, IgnoreWhitespace) && out.size() > 0) { response.setExpectedContentLength(out.size()); handle->client()->didReceiveData(handle, out.data(), out.size(), 0); } } else { TextEncoding encoding(charset); data = decodeURLEscapeSequences(data, encoding); handle->client()->didReceiveResponse(handle, response); CString encodedData = encoding.encode(data.characters(), data.length(), URLEncodedEntitiesForUnencodables); response.setExpectedContentLength(encodedData.length()); if (encodedData.length()) handle->client()->didReceiveData(handle, encodedData.data(), encodedData.length(), 0); } handle->client()->didFinishLoading(handle, 0); }
bool Path::mksubdir(const String &path) const { if (isDir()) { String combined = *this; if (!combined.endsWith('/')) combined.append('/'); combined.append(path); return Path::mkdir(combined); } return false; }
static inline String pathExtension(const KURL& url) { String extension; String filename = url.lastPathComponent(); if (!filename.endsWith("/")) { int extensionPos = filename.reverseFind('.'); if (extensionPos != -1) extension = filename.substring(extensionPos + 1); } return extension; }
void PluginDatabase::getPluginPathsInDirectories(HashSet<String>& paths) const { // FIXME: This should be a case insensitive set. HashSet<String> uniqueFilenames; HANDLE hFind = INVALID_HANDLE_VALUE; WIN32_FIND_DATAW findFileData; String oldWMPPluginPath; String newWMPPluginPath; Vector<String>::const_iterator end = m_pluginDirectories.end(); for (Vector<String>::const_iterator it = m_pluginDirectories.begin(); it != end; ++it) { String pattern = *it + "\\*"; hFind = FindFirstFileW(pattern.charactersWithNullTermination(), &findFileData); if (hFind == INVALID_HANDLE_VALUE) continue; do { if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue; String filename = String(findFileData.cFileName, wcslen(findFileData.cFileName)); if ((!filename.startsWith("np", false) || !filename.endsWith("dll", false)) && (!equalIgnoringCase(filename, "Plugin.dll") || !it->endsWith("Shockwave 10", false))) continue; String fullPath = *it + "\\" + filename; if (!uniqueFilenames.add(fullPath).second) continue; paths.add(fullPath); if (equalIgnoringCase(filename, "npdsplay.dll")) oldWMPPluginPath = fullPath; else if (equalIgnoringCase(filename, "np-mswmp.dll")) newWMPPluginPath = fullPath; } while (FindNextFileW(hFind, &findFileData) != 0); FindClose(hFind); } addPluginPathsFromRegistry(HKEY_LOCAL_MACHINE, paths); addPluginPathsFromRegistry(HKEY_CURRENT_USER, paths); // If both the old and new WMP plugin are present in the plugins set, // we remove the old one so we don't end up choosing the old one. if (!oldWMPPluginPath.isEmpty() && !newWMPPluginPath.isEmpty()) paths.remove(oldWMPPluginPath); }
static bool defaultPollMaximumProcessMemory(size_t &criticalLimit, size_t &nonCriticalLimit) { // Syntax: Case insensitive, process name, wildcard (*), unit multipliers (M=Mb, K=Kb, <empty>=bytes). // Example: WPE_POLL_MAX_MEMORY='WPEWebProcess:500M,*Process:150M' String processName(getProcessName().convertToLowercaseWithoutLocale()); String s(getenv("WPE_POLL_MAX_MEMORY")); if (!s.isEmpty()) { Vector<String> entries; s.split(',', false, entries); for (const String& entry : entries) { Vector<String> keyvalue; entry.split(':', false, keyvalue); if (keyvalue.size() != 2) continue; String key = "*"+keyvalue[0].stripWhiteSpace().convertToLowercaseWithoutLocale(); String value = keyvalue[1].stripWhiteSpace().convertToLowercaseWithoutLocale(); size_t units = 1; if (value.endsWith('k')) units = 1024; else if (value.endsWith('m')) units = 1024 * 1024; if (units != 1) value = value.substring(0, value.length()-1); bool ok = false; size_t size = size_t(value.toUInt64(&ok)); if (!ok) continue; if (!fnmatch(key.utf8().data(), processName.utf8().data(), 0)) { criticalLimit = size * units; nonCriticalLimit = criticalLimit * 0.75; return true; } } } return false; }
static String valueWithoutImportant(const String& value) { if (!value.endsWith("important", false)) return value; String newValue = value; int bangIndex = newValue.length() - 9 - 1; if (newValue[bangIndex] == ' ') bangIndex--; newValue = newValue.left(bangIndex); return newValue; }
void HTMLTextFormControlElement::setInnerTextValue(const String& value) { if (!isTextFormControl()) return; bool textIsChanged = value != innerTextValue(); if (textIsChanged || !innerTextElement()->hasChildNodes()) { if (textIsChanged && document() && renderer() && AXObjectCache::accessibilityEnabled()) document()->axObjectCache()->postNotification(this, AXObjectCache::AXValueChanged, false); ExceptionCode ec = 0; innerTextElement()->setInnerText(value, ec); ASSERT(!ec); if (value.endsWith('\n') || value.endsWith('\r')) { innerTextElement()->appendChild(HTMLBRElement::create(document()), ec); ASSERT(!ec); } } setFormControlValueMatchesRenderer(true); }
void RenderTextControl::setInnerTextValue(const String& innerTextValue) { String value; if (innerTextValue.isNull()) value = ""; else { value = innerTextValue; value = document()->displayStringModifiedByEncoding(value); } if (value != text() || !m_innerText->hasChildNodes()) { if (value != text()) { if (Frame* frame = document()->frame()) { frame->editor()->clearUndoRedoOperations(); if (AXObjectCache::accessibilityEnabled()) document()->axObjectCache()->postNotification(this, AXObjectCache::AXValueChanged, false); } } ExceptionCode ec = 0; m_innerText->setInnerText(value, ec); ASSERT(!ec); if (value.endsWith("\n") || value.endsWith("\r")) { m_innerText->appendChild(new HTMLBRElement(brTag, document()), ec); ASSERT(!ec); } // We set m_lastChangeWasUserEdit to false since this change was not explicitly made by the user (say, via typing on the keyboard), see <rdar://problem/5359921>. m_lastChangeWasUserEdit = false; } static_cast<Element*>(node())->setFormControlValueMatchesRenderer(true); }
String MIMETypeRegistry::getMIMETypeForPath(const String& path) { QMimeType type = QMimeDatabase().mimeTypeForFile(path, QMimeDatabase::MatchExtension); if (type.isValid() && !type.isDefault()) return type.name(); const ExtensionMap *e = extensionMap; while (e->extension) { if (path.endsWith(e->dotExtension)) return e->mimeType; ++e; } return defaultMIMEType(); }
bool Directory::create(const String &dirPath, bool recursive) { if(dirPath.isEmpty()) return false; if(recursive) { String path = File::normalizePath(dirPath); unsigned int foundPos = path.find(WITCH_DIRECTORY_SEPARATOR); if(foundPos == String::npos) return false; #if WITCHENGINE_PLATFORM == WITCHENGINE_PLATFORM_WIN32 || WITCHENGINE_PLATFORM == WITCHENGINE_PLATFORM_WIN64 if(path.match("\\\\*")) { foundPos = path.find('\\', 2); if(foundPos == String::npos) return false; foundPos = path.find('\\', foundPos + 1); if(foundPos == String::npos) return false; } #endif do { String p = path.substr(0, foundPos); if(p.endsWith(WITCH_DIRECTORY_SEPARATOR)) p = p.substr(0, -2); if(!DirectoryImpl::exists(p) && !DirectoryImpl::create(p)) return false; if(foundPos == String::npos) break; foundPos = path.find(WITCH_DIRECTORY_SEPARATOR, foundPos + 1); } while(true); return true; } else return DirectoryImpl::create(File::normalizePath(dirPath)); }
// static KURL MHTMLParser::convertContentIDToURI(const String& contentID) { // This function is based primarily on an example from rfc2557 in section // 9.5, but also based on more normative parts of specs like: // - rfc2557 - MHTML - section 8.3 - "Use of the Content-ID header and CID URLs" // - rfc1738 - URL - section 4 (reserved scheme names; includes "cid") // - rfc2387 - multipart/related - section 3.4 - "Syntax" (cid := msg-id) // - rfc0822 - msg-id = "<" addr-spec ">"; addr-spec = local-part "@" domain if (contentID.length() <= 2) return KURL(); if (!contentID.startsWith('<') || !contentID.endsWith('>')) return KURL(); StringBuilder uriBuilder; uriBuilder.append("cid:"); uriBuilder.append(contentID, 1, contentID.length() - 2); return KURL(KURL(), uriBuilder.toString()); }
PtrLList<String> * LocalNodeInfo::getAllSubscriptions (void) { _m.lock (326); if (_consolidatedSubscriptions.isEmpty()) { _m.unlock (326); return NULL; } PtrLList<String> *pRet = _consolidatedSubscriptions.getAllSubscribedGroups(); const char *pszEnd = ".[od]"; PtrLList<String> temp = (*pRet); for (String *pszCurr = temp.getFirst(); pszCurr != NULL; pszCurr = temp.getNext()) { if (pszCurr->endsWith (pszEnd) == 1) { String *pDel = pRet->remove (pszCurr); if (pDel != NULL) { delete pDel; } } } _m.unlock (326); return pRet; }
bool DOMImplementation::isXMLMIMEType(const String& mimeType) { if (mimeType == "text/xml" || mimeType == "application/xml" || mimeType == "text/xsl") return true; if (!mimeType.endsWith("+xml")) return false; size_t slashPosition = mimeType.find('/'); // Take into account the '+xml' ending of mimeType. if (slashPosition == notFound || !slashPosition || slashPosition == mimeType.length() - 5) return false; // Again, mimeType ends with '+xml', no need to check the validity of that substring. size_t mimeLength = mimeType.length(); for (size_t i = 0; i < mimeLength - 4; ++i) { if (!isValidXMLMIMETypeChar(mimeType[i]) && i != slashPosition) return false; } return true; }
PluginPackage* PluginDatabase::findPlugin(const KURL& url, String& mimeType) { PluginPackage* plugin = pluginForMIMEType(mimeType); String filename = url.string(); if (!plugin) { String filename = url.lastPathComponent(); if (!filename.endsWith("/")) { int extensionPos = filename.reverseFind('.'); if (extensionPos != -1) { String extension = filename.substring(extensionPos + 1); mimeType = MIMETypeForExtension(extension); plugin = pluginForMIMEType(mimeType); } } } // FIXME: if no plugin could be found, query Windows for the mime type // corresponding to the extension. return plugin; }
static Vector<pair<int, String> > getRegularExpressionMatchesByLines(const RegularExpression& regex, const String& text) { Vector<pair<int, String> > result; if (text.isEmpty()) return result; OwnPtr<Vector<size_t> > endings(lineEndings(text)); size_t size = endings->size(); unsigned start = 0; for (size_t lineNumber = 0; lineNumber < size; ++lineNumber) { size_t lineEnd = endings->at(lineNumber); String line = text.substring(start, lineEnd - start); if (line.endsWith('\r')) line = line.left(line.length() - 1); int matchLength; if (regex.match(line, 0, &matchLength) != -1) result.append(pair<int, String>(lineNumber, line)); start = lineEnd + 1; } return result; }