Example #1
0
bool IsValidName(const String& name)
{
    // TODO: Maybe check against keyword list also

    if(name.length() == 0)
        return false;

    if(name.length() > 255)
        return false;

    for(int i = 0; i < (int)name.length(); ++i)
    {
        char c = name[i];

        if(c >= 'A' && c <= 'Z')
            continue;
        else if(c >= 'a' && c <= 'z')
            continue;
        else if(c == '_')
            continue;
        else if(c >= '0' && c <= '9' && i != 0)
            continue;
        else
            return false;
    }

    return true;
}
Example #2
0
static bool makeAllDirectories(IFileMgr* fileManager, const String& path)
{
    if (path == canonicalPath(AEEFS_HOME_DIR))
        return true;

    int lastDivPos = path.reverseFind('/');
    int endPos = path.length();
    if (lastDivPos == path.length() - 1) {
        endPos -= 1;
        lastDivPos = path.reverseFind('/', lastDivPos);
    }

    if (lastDivPos > 0) {
        if (!makeAllDirectories(fileManager, path.substring(0, lastDivPos)))
            return false;
    }

    String folder(path.substring(0, endPos));

    // IFILEMGR_MkDir return SUCCESS when the file is successfully created or if file already exists.
    // So we need to check fileinfo.attrib.
    IFILEMGR_MkDir(fileManager, folder.utf8().data());

    FileInfo fileInfo;
    if (IFILEMGR_GetInfo(fileManager, folder.utf8().data(), &fileInfo) != SUCCESS)
        return false;

    return fileInfo.attrib & _FA_DIR;
}
void PagePopupClient::addJavaScriptString(const String& str, SharedBuffer* data)
{
    addLiteral("\"", data);
    StringBuilder builder;
    builder.reserveCapacity(str.length());
    for (unsigned i = 0; i < str.length(); ++i) {
        if (str[i] == '\r') {
            builder.append("\\r");
        } else if (str[i] == '\n') {
            builder.append("\\n");
        } else if (str[i] == '\\' || str[i] == '"') {
            builder.append('\\');
            builder.append(str[i]);
        } else if (str[i] == '<') {
            // Need to avoid to add "</script>" because the resultant string is
            // typically embedded in <script>.
            builder.append("\\x3C");
        } else if (str[i] < 0x20 || str[i] == lineSeparator || str[i] == paragraphSeparator) {
            builder.append(String::format("\\u%04X", str[i]));
        } else {
            builder.append(str[i]);
        }
    }
    addString(builder.toString(), data);
    addLiteral("\"", data);
}
Vector<String> listDirectory(const String& path, const String& filter)
{
    Vector<String> entries;

    Vector<UChar, 256> pattern;
    pattern.append(path.characters(), path.length());
    if (pattern.last() != L'/' && pattern.last() != L'\\')
        pattern.append(L'\\');

    String root(pattern.data(), pattern.size());
    pattern.append(filter.characters(), filter.length());
    pattern.append(0);

    WIN32_FIND_DATA findData;
    HANDLE hFind = FindFirstFile(pattern.data(), &findData);
    if (INVALID_HANDLE_VALUE != hFind) {
        do {
            // FIXEME: should we also add the folders? This function
            // is so far only called by PluginDatabase.cpp to list
            // all plugins in a folder, where it's not supposed to list sub-folders.
            if (!(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
                entries.append(root + findData.cFileName);
        } while (FindNextFile(hFind, &findData));
        FindClose(hFind);
    }

    return entries;
}
Example #5
0
PassRefPtr<SecurityOrigin> SecurityOrigin::createFromDatabaseIdentifier(const String& databaseIdentifier)
{ 
    // Make sure there's a first separator
    int separator1 = databaseIdentifier.find(SeparatorCharacter);
    if (separator1 == -1)
        return create(KURL());
        
    // Make sure there's a second separator
    int separator2 = databaseIdentifier.find(SeparatorCharacter, separator1 + 1);
    if (separator2 == -1)
        return create(KURL());
        
    // Make sure there's not a third separator
    if (databaseIdentifier.reverseFind(SeparatorCharacter) != separator2)
        return create(KURL());
        
    // Make sure the port section is a valid port number or doesn't exist
    bool portOkay;
    int port = databaseIdentifier.right(databaseIdentifier.length() - separator2 - 1).toInt(&portOkay);
    if (!portOkay && separator2 + 1 == static_cast<int>(databaseIdentifier.length()))
        return create(KURL());
    
    if (port < 0 || port > 65535)
        return create(KURL());
        
    // Split out the 3 sections of data
    String protocol = databaseIdentifier.substring(0, separator1);
    String host = databaseIdentifier.substring(separator1 + 1, separator2 - separator1 - 1);
    return create(KURL(KURL(), protocol + "://" + host + ":" + String::number(port)));
}
Example #6
0
void FileInputType::setFileList(const Vector<String>& paths)
{
    m_fileList->clear();
    size_t size = paths.size();

#if ENABLE(DIRECTORY_UPLOAD)
    // If a directory is being selected, the UI allows a directory to be chosen
    // and the paths provided here share a root directory somewhere up the tree;
    // we want to store only the relative paths from that point.
    if (size && element()->fastHasAttribute(webkitdirectoryAttr)) {
        // Find the common root path.
        String rootPath = directoryName(paths[0]);
        for (size_t i = 1; i < size; i++) {
            while (!paths[i].startsWith(rootPath))
                rootPath = directoryName(rootPath);
        }
        rootPath = directoryName(rootPath);
        ASSERT(rootPath.length());
        int rootLength = rootPath.length();
        if (rootPath[rootLength - 1] != '\\' && rootPath[rootLength - 1] != '/')
            rootLength += 1;
        for (size_t i = 0; i < size; i++) {
            // Normalize backslashes to slashes before exposing the relative path to script.
            String relativePath = paths[i].substring(rootLength).replace('\\', '/');
            m_fileList->append(File::createWithRelativePath(paths[i], relativePath));
        }
        return;
    }
#endif

    for (size_t i = 0; i < size; i++)
        m_fileList->append(File::create(paths[i]));
}
Example #7
0
WebVTTParser::ParseState WebVTTParser::collectTimingsAndSettings(const String& line)
{
    // 4.8.10.13.3 Collect WebVTT cue timings and settings.
    // 1-3 - Let input be the string being parsed and position be a pointer into input
    unsigned position = 0;
    skipWhiteSpace(line, &position);

    // 4-5 - Collect a WebVTT timestamp. If that fails, then abort and return failure. Otherwise, let cue's text track cue start time be the collected time.
    m_currentStartTime = collectTimeStamp(line, &position);
    if (m_currentStartTime == malformedTime)
        return BadCue;
    if (position >= line.length())
        return BadCue;

    skipWhiteSpace(line, &position);

    // 6-9 - If the next three characters are not "-->", abort and return failure.
    if (line.find("-->", position) == kNotFound)
        return BadCue;
    position += 3;
    if (position >= line.length())
        return BadCue;

    skipWhiteSpace(line, &position);

    // 10-11 - Collect a WebVTT timestamp. If that fails, then abort and return failure. Otherwise, let cue's text track cue end time be the collected time.
    m_currentEndTime = collectTimeStamp(line, &position);
    if (m_currentEndTime == malformedTime)
        return BadCue;
    skipWhiteSpace(line, &position);

    // 12 - Parse the WebVTT settings for the cue (conducted in TextTrackCue).
    m_currentSettings = line.substring(position, line.length()-1);
    return CueText;
}
Example #8
0
//----------------------------------------------------------------------------
// MQTT client callback, topic=<client-id>/... msg=...
//----------------------------------------------------------------------------
void ICACHE_FLASH_ATTR mqttOnPublish(String strTopic, String strMsg)
{
  tUint32 cbTopic = strTopic.length(), cbMsg = strMsg.length();

  do {
    // make sure topic starts with <client-id>
    Debug.logTxt(CLSLVL_MQTT | 0x0000, "mqttOnPublish,topic=%s,msg=%s", strTopic.c_str(), strMsg.c_str());
    if (strTopic.startsWith(AppSettings.mqttClientId + "/") == 0) {
      Debug.logTxt(CLSLVL_MQTT | 0x0010, "mqttOnPublish,not for us,dropping");
      g_mqttPktRxDropped++;
      return;
      } // if

    g_mqttPktRx++;

    // copy topic/msg to modifiable buffer on stack
    tChar szTopic[cbTopic + 1], szMsg[cbMsg + 1];
    tChar *pTopic = szTopic;
    gstrcpy(szTopic, strTopic.c_str());
    gstrcpy(szMsg, strMsg.c_str());

    // pass topic=<pfx>/<obj>... on to GPIOD
    pTopic += (AppSettings.mqttClientId.length() + 1);
    gpiodOnMqttPublish(pTopic, szMsg);
    } while (FALSE);

  } // mqttOnPublish
bool setWifiConnectionMode(){
  int x;
  Serial1.println("AT+CIPMUX=0");
  Serial1.flush();
  String response = Serial1.readStringUntil(Serial1.available());
  if(response.length() > 2){
    x = findString("OK", response);
                           } 
  else{
    SerialUSB.println("Wi-Fi set Connection Mode Timeout!");
    return false;
      }
  if(x != -1){
    SerialUSB.println("Wi-Fi Connection Mode Set");
    return true;   
             }
  if(response.length() > 15){
    x = findString("link is builded", response);
  }else{
    SerialUSB.println("Wi-Fi set Connection Mode Timeout!");
    return false;
  }
  
  if(x!=-1){
    SerialUSB.println("Wi-Fi Connection Mode Already Set");
    return true;   
           }
  else{
    SerialUSB.println("Couldn't set Wi-Fi Connection Mode!");
    return false;
      }         
                            }
Example #10
0
void DS::Stream::writeSafeString(const String& value, DS::StringType format)
{
    if (format == e_StringUTF16) {
        StringBuffer<chr16_t> buffer = value.toUtf16();
        uint16_t length = value.length() & 0x0FFF;
        chr16_t* data = new chr16_t[length];
        memcpy(data, buffer.data(), length * sizeof(chr16_t));
        for (uint16_t i=0; i<length; ++i)
            data[i] = ~data[i];
        write<uint16_t>(length | 0xF000);
        writeBytes(data, length * sizeof(chr16_t));
        write<chr16_t>(0);
        delete[] data;
    } else {
        StringBuffer<chr8_t> buffer = (format == e_StringUTF8) ? value.toUtf8()
                                                               : value.toRaw();
        uint16_t length = value.length() & 0x0FFF;
        chr8_t* data = new chr8_t[length];
        memcpy(data, buffer.data(), length * sizeof(chr8_t));
        for (uint16_t i=0; i<length; ++i)
            data[i] = ~data[i];
        write<uint16_t>(length | 0xF000);
        writeBytes(data, length * sizeof(chr8_t));
        delete[] data;
    }
}
Example #11
0
void WipeCommand::rm(File dir, String tempPath) {
  while(true) {
    File entry =  dir.openNextFile();
    String localPath;

    if (entry) {
      if (entry.isDirectory()) {
        localPath = tempPath + entry.name() + "/" + '\0';
        char folderBuf[localPath.length()];
        localPath.toCharArray(folderBuf, localPath.length());
        rm(entry, folderBuf);
        SD.rmdir(folderBuf);
      }
      else {
        localPath = tempPath + entry.name() + '\0';
        char charBuf[localPath.length()];
        localPath.toCharArray(charBuf, localPath.length() );
        SD.remove(charBuf);
      }
    } 
    else {
      break; // break out of recursion when finished
    }
  }
}
Example #12
0
void SocketHandler::sendMessage(const char* message)
{
	// Get message size.
	String messageLength = Convert::intToHex(strlen(message));

	// Do we have a valid size string?
	if (messageLength.length() != 8)
	{
		maPanic(0, "ReloadClient::sendTCPMessage: messageLength.length != 8");
	}

	// Create message data, starting with a magic header.
	String data = mMagicHeader + messageLength + message;

	// Queue the data.
	mSendQueue.add(data);

	// Send it directly if this is the only item to be sent.
	// If there are elements waiting in the queue, they will
	// be sent in connWriteFinished.
	if (mSendQueue.size() == 1)
	{
		// Send the data.
		mSocket.write(data.c_str(), data.length());
	}
}
String ContentType::parameter(const String& parameterName) const
{
    String parameterValue;
    String strippedType = m_type.stripWhiteSpace();

    // a MIME type can have one or more "param=value" after a semi-colon, and separated from each other by semi-colons
    size_t semi = strippedType.find(';');
    if (semi != notFound) {
        size_t start = strippedType.find(parameterName, semi + 1, false);
        if (start != notFound) {
            start = strippedType.find('=', start + parameterName.length());
            if (start != notFound) {
                size_t quote = strippedType.find('\"', start + 1);
                size_t end = strippedType.find('\"', start + 2);
                if (quote != notFound && end != notFound)
                    start = quote;
                else {
                    end = strippedType.find(';', start + 1);
                    if (end == notFound)
                        end = strippedType.length();
                }
                parameterValue = strippedType.substring(start + 1, end - (start + 1)).stripWhiteSpace();
            }
        }
    }

    return parameterValue;
}
Example #14
0
static RegularExpression* createRegExpForLabels(const Vector<String>& labels)
{
    // REVIEW- version of this call in FrameMac.mm caches based on the NSArray ptrs being
    // the same across calls.  We can't do that.

    DEFINE_STATIC_LOCAL(RegularExpression, wordRegExp, ("\\w", TextCaseSensitive));
    String pattern("(");
    unsigned int numLabels = labels.size();
    unsigned int i;
    for (i = 0; i < numLabels; i++) {
        String label = labels[i];

        bool startsWithWordChar = false;
        bool endsWithWordChar = false;
        if (label.length()) {
            startsWithWordChar = wordRegExp.match(label.substring(0, 1)) >= 0;
            endsWithWordChar = wordRegExp.match(label.substring(label.length() - 1, 1)) >= 0;
        }

        if (i)
            pattern.append("|");
        // Search for word boundaries only if label starts/ends with "word characters".
        // If we always searched for word boundaries, this wouldn't work for languages
        // such as Japanese.
        if (startsWithWordChar)
            pattern.append("\\b");
        pattern.append(label);
        if (endsWithWordChar)
            pattern.append("\\b");
    }
    pattern.append(")");
    return new RegularExpression(pattern, TextCaseInsensitive);
}
void HTMLViewSourceDocument::processTagToken(const String& source, HTMLToken& token, SourceAnnotation annotation)
{
    maybeAddSpanForAnnotation(annotation);
    m_current = addSpanWithClassName("html-tag");

    AtomicString tagName(token.name());

    unsigned index = 0;
    HTMLToken::AttributeList::const_iterator iter = token.attributes().begin();
    while (index < source.length()) {
        if (iter == token.attributes().end()) {
            // We want to show the remaining characters in the token.
            index = addRange(source, index, source.length(), emptyAtom);
            ASSERT(index == source.length());
            break;
        }

        AtomicString name(iter->name);
        AtomicString value(StringImpl::create8BitIfPossible(iter->value));

        index = addRange(source, index, iter->nameRange.start - token.startIndex(), emptyAtom);
        index = addRange(source, index, iter->nameRange.end - token.startIndex(), "html-attribute-name");

        if (tagName == baseTag && name == hrefAttr)
            addBase(value);

        index = addRange(source, index, iter->valueRange.start - token.startIndex(), emptyAtom);

        bool isLink = name == srcAttr || name == hrefAttr;
        index = addRange(source, index, iter->valueRange.end - token.startIndex(), "html-attribute-value", isLink, tagName == aTag, value);

        ++iter;
    }
    m_current = m_td;
}
void TableInfo::put(RecordType &rec, UINT n, const String &v) const {
  if(v.length() > m_columns[n].getMaxStringLen()) {
    throwSqlError(SQL_STRING_TOO_LONG,_T("%s:String too long to fit in keyfield[%d]. len=%d. maxlen=%d")
                                     ,__TFUNCTION__,n,(UINT)v.length(),m_columns[n].getMaxStringLen());
  }
  USES_CONVERSION;
  switch(getColumn(n).getType()) {
  case DBTYPE_CSTRING    :
  case DBTYPE_CSTRINGN   :
    { char tmp[MAXRECSIZE+1];
      memset(tmp,0,sizeof(tmp));
      strcpy(tmp,T2A((TCHAR*)v.cstr()));
      putBytes(rec,n,tmp);
    }
    break;
  case DBTYPE_WSTRING    :
  case DBTYPE_WSTRINGN   :
    { wchar_t tmp[MAXRECSIZE+1];
      memset(tmp,0,sizeof(tmp));
      wcscpy(tmp,T2W((TCHAR*)v.cstr()));
      putBytes(rec,n,tmp);
    }
    break;
  default: THROWFIELDNOTSTRING(n);
  }
}
Example #17
0
    //---------------------------------
    String Utils::checkNCName ( const String &ncName )
    {
        String result;
        result.reserve ( ncName.length() );

        // check if first character is an alpha character
        char firstCharacter = ncName[0];

        if ( isAsciiAlphaChar ( firstCharacter )  )
            result.append ( 1, firstCharacter );
        else
            result.append ( 1, '_' );

        //replace all spaces and colons by underlines
        for ( size_t i = 1; i<ncName.length(); ++i )
        {
            char character = ncName[i];

            if ( isIDChar ( character ) )
                result.append ( 1, character );
            else
                result.append ( 1, '_' );
        }

        return result;
    }
Example #18
0
	bool yl_messenger::request_post(const yl_sensor &sensor, const yl_data_point &dp, bool keep_alive)
	{
		String data = dp.to_string();
		if (data.length() == 0)
		{
			return false;
		}
		String connection = keep_alive ? "\r\n" : "Connection:close\r\n\r\n";
		String temp("POST /");
		temp += version_;
		temp += "/device/";
		if (!client_->send(temp)
			|| !client_->send(sensor.get_device()->get_id())
			|| !client_->send("/sensor/") 
			|| !client_->send(sensor.get_id())
			|| !client_->send("/datapoints HTTP/1.1\r\nHost:")
			|| !client_->send(host_)
			|| !client_->send("\r\nAccept:*/*\r\nU-ApiKey:")
			|| !client_->send(api_key_)
			|| !client_->send("\r\nContent-Length:")
			|| !client_->send_ln(data.length())
			|| !client_->send("Content-Type:application/x-www-form-urlencoded\r\n")
			|| !client_->send(connection)
			|| !client_->send(data))
		{
#ifdef YL_SERIAL_DEBUG
			Serial.println("send error : 108");
#endif
			return false;
		}
		return true;
	}
Example #19
0
void InspectorStyleTextEditor::replaceProperty(unsigned index, const String& newText)
{
    ASSERT_WITH_SECURITY_IMPLICATION(index < m_allProperties->size());

    const InspectorStyleProperty& property = m_allProperties->at(index);
    long propertyStart = property.sourceData.range.start;
    long propertyEnd = property.sourceData.range.end;
    long oldLength = propertyEnd - propertyStart;
    long newLength = newText.length();
    long propertyLengthDelta = newLength - oldLength;

    if (!property.disabled) {
        SourceRange overwrittenRange;
        unsigned insertedLength;
        internalReplaceProperty(property, newText, &overwrittenRange, &insertedLength);
        propertyLengthDelta = static_cast<long>(insertedLength) - static_cast<long>(overwrittenRange.length());

        // Recompute subsequent disabled property ranges if acting on a non-disabled property.
        shiftDisabledProperties(disabledIndexByOrdinal(index, true), propertyLengthDelta);
    } else {
        long textLength = newText.length();
        unsigned disabledIndex = disabledIndexByOrdinal(index, false);
        if (!textLength) {
            // Delete disabled property.
            m_disabledProperties->remove(disabledIndex);
        } else {
            // Patch disabled property text.
            m_disabledProperties->at(disabledIndex).rawText = newText;
        }
    }
}
bool DOMImplementation::hasFeature(const String& feature, const String& version)
{
    String lower = feature.lower();
    if (lower == "core" || lower == "html" || lower == "xml" || lower == "xhtml")
        return version.isEmpty() || version == "1.0" || version == "2.0";
    if (lower == "css"
            || lower == "css2"
            || lower == "events"
            || lower == "htmlevents"
            || lower == "mouseevents"
            || lower == "mutationevents"
            || lower == "range"
            || lower == "stylesheets"
            || lower == "traversal"
            || lower == "uievents"
            || lower == "views")
        return version.isEmpty() || version == "2.0";
    if (lower == "xpath" || lower == "textevents")
        return version.isEmpty() || version == "3.0";

#if ENABLE(SVG)
    if ((version.isEmpty() || version == "1.1") && feature.startsWith("http://www.w3.org/tr/svg11/feature#", false)) {
        if (isSVG11Feature(feature.right(feature.length() - 35)))
            return true;
    }

    if ((version.isEmpty() || version == "1.0") && feature.startsWith("org.w3c.", false)) {
        if (isSVG10Feature(feature.right(feature.length() - 8)))
            return true;
    }
#endif
    
    return false;
}
void parse_message(String message) {
    if(message[0] == '(') {
        int digitVal = 10*(message[1]-'0') + (message[2]-'0');
        Serial.print("Setting display to: ");
        Serial.print(message[1]);
        Serial.println(message[2]);
        setDisplay(digitVal / 10, digitVal % 10);
    }

    Serial.print("message is: ");
    Serial.println(message);
    if(message[message.length() - 1] == ')') {
        double motorVal = 10*(message[message.length()-3]-'0') + (message[message.length()-2]-'0');
        unsigned long motorPer = motorVal * 1000/SPEED_SLOPE;
        unsigned long target = STEPS * motorPer / 100;
        Serial.print("Setting motor target to: ");
        Serial.println(target);
        setMotorTarget(target);
    }

    if (message[0] == '<') {
        int rgbValue = 100*(message[1] -'0') + 10*(message[2]-'0') + (message[3]-'0');
        setLED(rgbValue, 255, 255);
    }
}
Example #22
0
		void addFile(const String& name, bool imitEvents = true)
		{
			//fprintf(stderr, "ADDED: %s\n", name.c_str());
			
			// create entry
			struct stat attrib;
			stat(name.c_str(), &attrib);
			
			int fd = open(name.c_str(), O_RDONLY);

			if(fd == -1)
				throw FileNotFoundException(name);
			
			++mChangeListCount;
			
			char* namecopy = new char[name.length() + 1];
			strncpy(namecopy, name.c_str(), name.length());
			namecopy[name.length()] = 0;
			EntryStruct* entry = new EntryStruct(namecopy, attrib.st_mtime);
			
			// set the event data at the end of the list
			EV_SET(&mChangeList[mChangeListCount], fd, EVFILT_VNODE,
				   EV_ADD | EV_ENABLE | EV_ONESHOT,
				   NOTE_DELETE | NOTE_EXTEND | NOTE_WRITE | NOTE_ATTRIB,
				   0, (void*)entry);
			
			// qsort
			qsort(mChangeList + 1, mChangeListCount, sizeof(KEvent), comparator);
			
			// handle action
			if(imitEvents)
				handleAction(name, Action::Add);
		}
Example #23
0
Variant HHVM_FUNCTION(bzcompress, const String& source, int blocksize /* = 4 */,
                                  int workfactor /* = 0 */) {
  char *dest = NULL;
  int error;
  unsigned int source_len, dest_len;

  source_len = source.length();
  dest_len = source.length() + (0.01*source.length()) + 600;

  if (!(dest = (char *)malloc(dest_len + 1))) {
    return BZ_MEM_ERROR;
  }

  error = BZ2_bzBuffToBuffCompress(dest, &dest_len, (char *) source.c_str(),
                                   source_len, blocksize, 0, workfactor);
  if (error != BZ_OK) {
    free(dest);
    return error;
  } else {
    // this is to shrink the allocation, since we probably over allocated
    dest = (char *)realloc(dest, dest_len + 1);
    dest[dest_len] = '\0';
    String ret = String(dest, dest_len, AttachString);
    return ret;
  }
}
Example #24
0
void EditorHelp::_class_desc_select(const String& p_select) {



//	print_line("LINK: "+p_select);
	if (p_select.begins_with("#")) {
		//_goto_desc(p_select.substr(1,p_select.length()));
		emit_signal("go_to_help","class_name:"+p_select.substr(1,p_select.length()));
		return;
	} else if (p_select.begins_with("@")) {

		String m = p_select.substr(1,p_select.length());

		if (m.find(".")!=-1) {
			//must go somewhere else

			emit_signal("go_to_help","class_method:"+m.get_slice(".",0)+":"+m.get_slice(".",0));
		} else {

			if (!method_line.has(m))
				return;
			class_desc->scroll_to_line(method_line[m]);
		}

	}


}
Example #25
0
static void doDrawTextAtPoint(GraphicsContext& context, const String& text, const IntPoint& point, const Font& font, const Color& color, int underlinedIndex)
{
    FontCachePurgePreventer fontCachePurgePreventer;

    TextRun run(text.characters(), text.length());

    context.setFillColor(color, ColorSpaceDeviceRGB);
    if (isOneLeftToRightRun(run))
        font.drawText(&context, run, point);
    else
        context.drawBidiText(font, run, point);

    if (underlinedIndex >= 0) {
        ASSERT(underlinedIndex < static_cast<int>(text.length()));

        int beforeWidth;
        if (underlinedIndex > 0) {
            TextRun beforeRun(text.characters(), underlinedIndex);
            beforeWidth = font.width(beforeRun);
        } else
            beforeWidth = 0;

        TextRun underlinedRun(text.characters() + underlinedIndex, 1);
        int underlinedWidth = font.width(underlinedRun);

        IntPoint underlinePoint(point);
        underlinePoint.move(beforeWidth, 1);

        context.setStrokeColor(color, ColorSpaceDeviceRGB);
        context.drawLineForText(underlinePoint, underlinedWidth, false);
    }
}
Example #26
0
bool File::skipUntil(const String &text) {
	/**
	 * skipUntil(): Set file cursor after the next occurrence of 'text'.
	 *    Return false if 'text' was not found.
	 */
	char *wtf = NULL;
	while (good()) {
		if (myRdBufPos < myRdBufEnd) {
			wtf = ssi::strnstr(myRdBuf + myRdBufPos, text.begin(), myRdBufEnd - myRdBufPos);
		}
		if (wtf) {
			myRdBufPos = wtf - myRdBuf + text.length();
			return true;
		}
		
		/* 
		 * Not found yet => refill buffer.
		 * We leave the last (len - 1) chars in the buffer in case the
		 * text we're looking for is split across 2 buffer reads.
		 */
		INT64 leave =  text.length() - 1;
		if (leave > myRdBufEnd - myRdBufPos) {
			leave = myRdBufEnd - myRdBufPos;
		}
		memmove(myRdBuf, myRdBuf + myRdBufEnd - leave, leave);
		myRdBufEnd = ::read(myFd, myRdBuf + leave, myBufSize - leave) + leave;
		myRdBufPos = 0;
		myEof = (myRdBufEnd == leave);
	}
	
	return false;
}
SMILTime SVGSMILElement::parseClockValue(const String& data)
{
    if (data.isNull())
        return SMILTime::unresolved();

    String parse = data.stripWhiteSpace();

    DEFINE_STATIC_LOCAL(const AtomicString, indefiniteValue, ("indefinite"));
    if (parse == indefiniteValue)
        return SMILTime::indefinite();

    double result = 0;
    bool ok;
    size_t doublePointOne = parse.find(':');
    size_t doublePointTwo = parse.find(':', doublePointOne + 1);
    if (doublePointOne == 2 && doublePointTwo == 5 && parse.length() >= 8) {
        result += parse.substring(0, 2).toUIntStrict(&ok) * 60 * 60;
        if (!ok)
            return SMILTime::unresolved();
        result += parse.substring(3, 2).toUIntStrict(&ok) * 60;
        if (!ok)
            return SMILTime::unresolved();
        result += parse.substring(6).toDouble(&ok);
    } else if (doublePointOne == 2 && doublePointTwo == kNotFound && parse.length() >= 5) {
        result += parse.substring(0, 2).toUIntStrict(&ok) * 60;
        if (!ok)
            return SMILTime::unresolved();
        result += parse.substring(3).toDouble(&ok);
    } else
        return parseOffsetValue(parse);

    if (!ok || !SMILTime(result).isFinite())
        return SMILTime::unresolved();
    return result;
}
Example #28
0
//-----------------------------------------------------------------------
void DynLib::load()
{
    // Log library load
    LogManager::getSingleton().logMessage("Loading library " + mName);

    String name = mName;
#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX || OGRE_PLATFORM == OGRE_PLATFORM_NACL
    // dlopen() does not add .so to the filename, like windows does for .dll
    if (name.find(".so") == String::npos)
        name += ".so";
#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE
    // dlopen() does not add .dylib to the filename, like windows does for .dll
    if (name.substr(name.length() - 6, 6) != ".dylib")
        name += ".dylib";
#elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32
    // Although LoadLibraryEx will add .dll itself when you only specify the library name,
    // if you include a relative path then it does not. So, add it to be sure.
    if (name.substr(name.length() - 4, 4) != ".dll")
        name += ".dll";
#endif
    mInst = (DYNLIB_HANDLE)DYNLIB_LOAD( name.c_str() );

    if( !mInst )
        OGRE_EXCEPT(
            Exception::ERR_INTERNAL_ERROR,
            "Could not load dynamic library " + mName +
            ".  System Error: " + dynlibError(),
            "DynLib::load" );
}
 void render() {
   translate(width/2, height/2);
   steps += 5;          
   if (steps > production.length()) {
     steps = production.length();
   }
   for (int i = 0; i < steps; i++) {
     char step = production.charAt(i);
     if (step == 'F') {
       rect(0, 0, -drawLength, -drawLength);
       noFill();
       translate(0, -drawLength);
     } 
     else if (step == '+') {
       rotate(theta);
     } 
     else if (step == '-') {
       rotate(-theta);
     } 
     else if (step == '[') {
       pushMatrix();
     } 
     else if (step == ']') {
       popMatrix();            
     }
   }
 }
Example #30
0
// Shared implementation used by test and exec.
MatchResult RegExpObject::match(ExecState* exec, JSString* string)
{
    RegExp* regExp = this->regExp();
    RegExpConstructor* regExpConstructor = exec->lexicalGlobalObject()->regExpConstructor();
    String input = string->value(exec);
    VM& vm = exec->vm();
    if (!regExp->global())
        return regExpConstructor->performMatch(vm, regExp, string, input, 0);

    JSValue jsLastIndex = getLastIndex();
    unsigned lastIndex;
    if (LIKELY(jsLastIndex.isUInt32())) {
        lastIndex = jsLastIndex.asUInt32();
        if (lastIndex > input.length()) {
            setLastIndex(exec, 0);
            return MatchResult::failed();
        }
    } else {
        double doubleLastIndex = jsLastIndex.toInteger(exec);
        if (doubleLastIndex < 0 || doubleLastIndex > input.length()) {
            setLastIndex(exec, 0);
            return MatchResult::failed();
        }
        lastIndex = static_cast<unsigned>(doubleLastIndex);
    }

    MatchResult result = regExpConstructor->performMatch(vm, regExp, string, input, lastIndex);
    setLastIndex(exec, result.end);
    return result;
}