Example #1
0
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;
}
Example #2
0
Vector<String> PluginInfoStore::pluginPathsInDirectory(const String& directory)
{
    Vector<String> paths;

    PathWalker walker(directory, "*");
    if (!walker.isValid())
        return paths;

    do {
        if (walker.data().dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            continue;

        String filename = walker.data().cFileName;
        if ((!filename.startsWith("np", false) || !filename.endsWith("dll", false)) && (!equalIgnoringCase(filename, "Plugin.dll") || !directory.endsWith("Shockwave 10", false)))
            continue;

        paths.append(directory + "\\" + filename);
    } while (walker.step());

    return paths;
}
Example #3
0
bool CSPSource::hostMatches(const String& host) const {
  Document* document = m_policy->document();
  bool match;

  bool equalHosts = m_host == host;
  if (m_hostWildcard == HasWildcard) {
    match = host.endsWith(String("." + m_host), TextCaseUnicodeInsensitive);

    // Chrome used to, incorrectly, match *.x.y to x.y. This was fixed, but
    // the following count measures when a match fails that would have
    // passed the old, incorrect style, in case a lot of sites were
    // relying on that behavior.
    if (document && equalHosts)
      UseCounter::count(*document,
                        UseCounter::CSPSourceWildcardWouldMatchExactHost);
  } else {
    match = equalHosts;
  }

  return match;
}
bool isAnimationFile(const char filename[]) {
	String fname = String(filename);
	fname.toUpperCase();
	
    if (filename[0] == '_')
        return false;

    if (filename[0] == '~')
        return false;

    if (filename[0] == '.')
        return false;

    //String filenameString = String(filename).toUpperCase();
    //String filenameString = fname;
    //if (filenameString.endsWith(".GIF") != 1)
    if (fname.endsWith(".GIF") != 1)
        return false;

    return true;
}
SharedLibraryRef
DLLSharedLibraryLoader::loadSharedLibrary(const String& filename) const
{
	if( filename.endsWith("libblocxx.dll") )
	{
		return SharedLibraryRef(0);
	}

	HINSTANCE libhandle = ::LoadLibrary(filename.c_str());
	if (libhandle)
	{
		return SharedLibraryRef(new DLLSharedLibrary(libhandle,
			filename));
	}

	Logger logger(COMPONENT_NAME);
	BLOCXX_LOG_ERROR(logger, Format("DLLSharedLibraryLoader::loadSharedLibrary "
		"LoadLibrary returned NULL.  Error is: %1",
		System::lastErrorMsg()).c_str());

	return SharedLibraryRef(0);
}
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;
}
Example #7
0
int startGifAnimation(String name) {
    name.trim();
    if (name.length() == 0) {
        return -1;
    }

    name.toLowerCase();
    if (!name.endsWith(".gif")) {
        name += ".gif";
    }
    String pathname = String(GIF_DIRECTORY) + name;

    if (!isValidFile(pathname)) {
        return -2;
    }

    Animation *anim = new GifAnimation{context, pathname, CLOUD_ANIMATION_TIME};
    abortCurrentAnimations();
    addAnimation(anim);

    return 0;
}
static Vector<std::pair<int, String>> getRegularExpressionMatchesByLines(const RegularExpression& regex, const String& text)
{
    Vector<std::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(std::pair<int, String>(lineNumber, line));

        start = lineEnd + 1;
    }
    return result;
}
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> > getScriptRegexpMatchesByLines(const ScriptRegexp* regex, const String& text)
{
    Vector<pair<int, String> > result;
    if (text.isEmpty())
        return result;

    OwnPtr<Vector<unsigned> > endings(lineEndings(text));
    unsigned size = endings->size();
    unsigned start = 0;
    for (unsigned lineNumber = 0; lineNumber < size; ++lineNumber) {
        unsigned 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;
}
Example #11
0
void WTFLog(WTFLogChannel* channel, const char* format, ...)
{
    if (channel->state == WTFLogChannelOff)
        return;

    if (channel->state == WTFLogChannelOn) {
        va_list args;
        va_start(args, format);
        vprintf_stderr_with_trailing_newline(format, args);
        va_end(args);
        return;
    }

    ASSERT(channel->state == WTFLogChannelOnWithAccumulation);

    va_list args;
    va_start(args, format);

#if COMPILER(CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wformat-nonliteral"
#endif
    String loggingString = String::format(format, args);
#if COMPILER(CLANG)
#pragma clang diagnostic pop
#endif

    va_end(args);

    if (!loggingString.endsWith('\n'))
        loggingString.append('\n');

    loggingAccumulator().accumulate(loggingString);

    logToStderr(loggingString.utf8().data());
}
Example #12
0
void File::recDir(const String &path, Array<String> &files) {
	DIR *dp = opendir(path.c_str());
	if (dp) {
		struct dirent *ep;
		while ((ep = readdir(dp)) != NULL) {
			String name = ep->d_name;
			if (name != "." && name != "..") {
				String full_name;
				if (! path.endsWith('/') && ! name.startsWith('/')) {
					full_name = path + '/' + name;
				} else {
					full_name = path + name;
				}

				if (isFile(full_name)) {
					files.add(full_name);
				} else if (isDir(full_name)) {
					/* Recursion - migth lead to stack overflow in very deep tree structures */
					recDir(full_name, files);
				}
			}
		}
	}
}
Example #13
0
PluginPackage* PluginDatabase::findPlugin(const KURL& url, String& mimeType)
{
    if (!mimeType.isEmpty())
        return pluginForMIMEType(mimeType);
    
    String filename = url.lastPathComponent();
    if (filename.endsWith('/'))
        return 0;
    
    int extensionPos = filename.reverseFind('.');
    if (extensionPos == -1)
        return 0;
    
    String mimeTypeForExtension = MIMETypeForExtension(filename.substring(extensionPos + 1));
    PluginPackage* plugin = pluginForMIMEType(mimeTypeForExtension);
    if (!plugin) {
        // FIXME: if no plugin could be found, query Windows for the mime type
        // corresponding to the extension.
        return 0;
    }
    
    mimeType = mimeTypeForExtension;
    return plugin;
}
Example #14
0
void HttpResponse::sendFile(File f) {
	if(f) {
		this->_socket->print("HTTP/1.1 200 OK\r\n");
		String fname = f.name();
		if(fname.endsWith(".html") || fname.endsWith(".htm")) {
			this->_socket->print("Content-Type: text/html\r\n");
		}
		else if(fname.endsWith(".css")) {
			this->_socket->print("Content-Type: text/css\r\n");
		}
		else if(fname.endsWith(".jpg") || fname.endsWith(".jpeg")) {
			this->_socket->print("Content-Type: image/jpeg\r\n");
		}
		else if(fname.endsWith(".js")) {
			this->_socket->print("Content-Type: application/javascript\r\n");
		}
		else {
			this->_socket->print("Content-Type: application/octet-stream\r\n");
		}
		this->_socket->print("Access-Control-Allow-Origin: *\r\n\r\n");
		char outbuff[512];
		int available = 0;
		size_t read = 0;
		while((available = f.available()) > 0) {
			if(available > sizeof(outbuff)) {
				read = f.readBytes((char*)outbuff, sizeof(outbuff));
			}
			else {
				read = f.readBytes((char*)outbuff, available);
			}
			this->_socket->write((uint8_t*)outbuff, read);
			delay(1);
		}
		f.close();
	}
}
Example #15
0
PassRefPtr<DocumentFragment> createFragmentFromText(Range* context, const String& text)
{
    if (!context)
        return 0;

    Node* styleNode = context->firstNode();
    if (!styleNode) {
        styleNode = context->startPosition().deprecatedNode();
        if (!styleNode)
            return 0;
    }

    Document* document = styleNode->document();
    RefPtr<DocumentFragment> fragment = document->createDocumentFragment();
    
    if (text.isEmpty())
        return fragment.release();

    String string = text;
    string.replace("\r\n", "\n");
    string.replace('\r', '\n');

    RenderObject* renderer = styleNode->renderer();
    if (renderer && renderer->style()->preserveNewline()) {
        fragment->appendChild(document->createTextNode(string), ASSERT_NO_EXCEPTION);
        if (string.endsWith('\n')) {
            RefPtr<Element> element = createBreakElement(document);
            element->setAttribute(classAttr, AppleInterchangeNewline);            
            fragment->appendChild(element.release(), ASSERT_NO_EXCEPTION);
        }
        return fragment.release();
    }

    // A string with no newlines gets added inline, rather than being put into a paragraph.
    if (string.find('\n') == notFound) {
        fillContainerFromString(fragment.get(), string);
        return fragment.release();
    }

    // Break string into paragraphs. Extra line breaks turn into empty paragraphs.
    Node* blockNode = enclosingBlock(context->firstNode());
    Element* block = toElement(blockNode);
    bool useClonesOfEnclosingBlock = blockNode
        && blockNode->isElementNode()
        && !block->hasTagName(bodyTag)
        && !block->hasTagName(htmlTag)
        && block != editableRootForPosition(context->startPosition());
    bool useLineBreak = enclosingTextFormControl(context->startPosition());

    Vector<String> list;
    string.split('\n', true, list); // true gets us empty strings in the list
    size_t numLines = list.size();
    for (size_t i = 0; i < numLines; ++i) {
        const String& s = list[i];

        RefPtr<Element> element;
        if (s.isEmpty() && i + 1 == numLines) {
            // For last line, use the "magic BR" rather than a P.
            element = createBreakElement(document);
            element->setAttribute(classAttr, AppleInterchangeNewline);
        } else if (useLineBreak) {
            element = createBreakElement(document);
            fillContainerFromString(fragment.get(), s);
        } else {
            if (useClonesOfEnclosingBlock)
                element = block->cloneElementWithoutChildren();
            else
                element = createDefaultParagraphElement(document);
            fillContainerFromString(element.get(), s);
        }
        fragment->appendChild(element.release(), ASSERT_NO_EXCEPTION);
    }
    return fragment.release();
}
Example #16
0
void FalhttpdClient::serve()
{
    m_log->log( LOGLEVEL_DEBUG, "Serving client "+ m_sRemote );

    // get the header
    String sHeader;
    StreamBuffer si( new SocketInputStream( m_nSocket ) );
    uint32 chr;
    while ( ! sHeader.endsWith("\r\n") && si.get(chr) )
    {
        // do nothing
        sHeader.append( chr );
    }

    if ( ! sHeader.endsWith("\r\n") )
    {
        m_log->log( LOGLEVEL_WARN, "Client "+ m_sRemote + " has sent an invalid header." );
        return;
    }
    // remove trailing \r\n
    sHeader.remove( sHeader.length()-2, 2 );

    // parse the header; must be in format GET/POST/HEAD 'uri' HTTP/1.x
    uint32 p1, p2;
    p1 = sHeader.find( " " );
    p2 = sHeader.rfind( " " );
    if ( p1 == p2 )
    {
        sHeader.trim();
        m_log->log( LOGLEVEL_WARN, "Client "+ m_sRemote + " has sent an invalid header: " + sHeader );
        return;
    }

    String sRequest = sHeader.subString( 0, p1 );
    String sUri = sHeader.subString( p1+1, p2 );
    String sProto = sHeader.subString( p2+1 );

    // a bit of formal control
    int type = sRequest == "GET" ? 1 :
               ( sRequest == "POST"  ? 2 : ( sRequest == "HEAD" ? 3 : 0 ) );

    if ( type == 0 )
    {
        m_log->log( LOGLEVEL_WARN, "Client "+ m_sRemote + " has sent an invalid type: " + sHeader );
        replyError( 400, "Invalid requests type" );
        return;
    }

    URI uri( sUri );
    if( ! uri.isValid() )
    {
        m_log->log( LOGLEVEL_WARN, "Client "+ m_sRemote + " has sent an invalid URI: " + sHeader );
        replyError( 400, "Invalid invalid uri" );
        return;
    }

    if( sProto != "HTTP/1.0" && sProto != "HTTP/1.1" )
    {
        m_log->log( LOGLEVEL_WARN, "Client "+ m_sRemote + " has sent an invalid Protocol: " + sHeader );
        replyError( 505 );
        return;
    }

    // ok, we got a valid header -- proceed in serving the request.
    serveRequest( sRequest, sUri, sProto, &si );
}
Example #17
0
bool copyAllResources( Options& options, const Path& from, const Path& tgtPath )
{
   // do we have an extension filter?
   bool bHasExt = from.getExtension() !=  "";

   VFSProvider* file = Engine::getVFS("file");
   if( file == 0 )
   {
      error( "Can't find FILE resource" );
      return false;
   }

   DirEntry *entry = file->openDir( from.getFullLocation() );
   if( entry == 0 )
   {
      warning( "Can't open directory " + from.getFullLocation() );
      return false;
   }

   String fname;
   while( entry->read( fname ) )
   {
      if( fname == ".." || fname == "." )
      {
         continue;
      }

      FileStat fs;
      if ( ! Sys::fal_stats( from.getFullLocation() + "/" + fname, fs ) )
      {
         continue;
      }

      if ( fs.m_type == FileStat::t_normal || fs.m_type == FileStat::t_link )
      {
         // do we filter the extension?
         if( bHasExt )
         {
            if ( ! fname.endsWith( "." + from.getExtension(), true ) )
            {
               continue;
            }
         }

         // TODO: Jail resources under modpath
         if ( ! copyFile( from.getFullLocation() + "/" + fname, tgtPath.getFullLocation() + "/" + fname ) )
         {
            warning( "Cannot copy resource " +
                  from.getFullLocation() + "/" + fname
                  + " into "
                  + tgtPath.getFullLocation() + "/" + fname );
            entry->close();
            delete entry;
            return false;
         }

         /*
         // descend
         Path nfrom( from );
         nfrom.setFullLocation( from.getFullLocation() + "/" + fname );
         if( ! copyAllResources( options, nfrom, modPath, tgtPath ) )
         {
            return false;
         }
         */
      }
   }

   entry->close();
   delete entry;

   return true;
}
bool SVGSMILElement::parseCondition(const String& value, BeginOrEnd beginOrEnd)
{
    String parseString = value.stripWhiteSpace();

    double sign = 1.;
    bool ok;
    size_t pos = parseString.find('+');
    if (pos == kNotFound) {
        pos = parseString.find('-');
        if (pos != kNotFound)
            sign = -1.;
    }
    String conditionString;
    SMILTime offset = 0;
    if (pos == kNotFound)
        conditionString = parseString;
    else {
        conditionString = parseString.left(pos).stripWhiteSpace();
        String offsetString = parseString.substring(pos + 1).stripWhiteSpace();
        offset = parseOffsetValue(offsetString);
        if (offset.isUnresolved())
            return false;
        offset = offset * sign;
    }
    if (conditionString.isEmpty())
        return false;
    pos = conditionString.find('.');

    String baseID;
    String nameString;
    if (pos == kNotFound)
        nameString = conditionString;
    else {
        baseID = conditionString.left(pos);
        nameString = conditionString.substring(pos + 1);
    }
    if (nameString.isEmpty())
        return false;

    Condition::Type type;
    int repeat = -1;
    if (nameString.startsWith("repeat(") && nameString.endsWith(')')) {
        repeat = nameString.substring(7, nameString.length() - 8).toUIntStrict(&ok);
        if (!ok)
            return false;
        nameString = "repeatn";
        type = Condition::EventBase;
    } else if (nameString == "begin" || nameString == "end") {
        if (baseID.isEmpty())
            return false;
        type = Condition::Syncbase;
    } else if (nameString.startsWith("accesskey(")) {
        // FIXME: accesskey() support.
        type = Condition::AccessKey;
    } else
        type = Condition::EventBase;

    m_conditions.append(Condition::create(type, beginOrEnd, baseID, nameString, offset, repeat));

    if (type == Condition::EventBase && beginOrEnd == End)
        m_hasEndEventConditions = true;

    return true;
}
Example #19
0
int saveApost(Config &config)
{

 bool writeAllFeature=true; // Output a vector for all input vectors (selected and not selected vectors) - DEFAULT=on
 if (config.existsParam("writeAllFeatures")) writeAllFeature=config.getParam("writeAllFeatures").toBool();    // Define if all the feature     (selected or not) should be written

	String modelname = config.getParam("inputModelFilename");
	  String inputFeatureFileName =config.getParam("inputFeatureFilename");          // input feature - could be a simple feature file or a list of filenames
        XLine inputFeatureFileNameList;                                                // The (feature) input filename list
        if (inputFeatureFileName.endsWith(".lst")){                                   // If the file parameter is the name of a XList file
	   XList inputFileNameXList(inputFeatureFileName,config);                   // Read the filename list file
           inputFeatureFileNameList=inputFileNameXList.getAllElements();            // And put the filename in a list if the file is a list of feature filenames
			      }
      else {                                                                         // It was a simple feature file and not a filename list
	          inputFeatureFileNameList.addElement(inputFeatureFileName);                   // add the filename in the list
		    }

	try{

        // read UBM 
        MixtureServer _ms(config);
	StatServer _ss(config);
        _ms.loadMixtureGD(config.getParam("inputWorldFilename"));
        MixtureGD & UBM=_ms.getMixtureGD((unsigned long) 0);
        MixtureGDStat &acc=_ss.createAndStoreMixtureStat(UBM);

	unsigned long _vsize=UBM.getVectSize();
	unsigned long _mixsize=UBM.getDistribCount();
        // Loop over the list of feature files
	String *file;
	String labelSelectedFrames;
        unsigned long codeSelectedFrame;
	while ((file=inputFeatureFileNameList.getElement())!= NULL){         
	String & featureFilename=(*file);

	FeatureServer fs(config,featureFilename);
	FeatureServer fs_out(config,featureFilename);
        SegServer segmentsServer;
        LabelServer labelServer;
        initializeClusters(featureFilename,segmentsServer,labelServer,config);
        verifyClusterFile(segmentsServer,fs,config);
	labelSelectedFrames=config.getParam("labelSelectedFrames");
        codeSelectedFrame=labelServer.getLabelIndexByString(labelSelectedFrames);
        SegCluster& selectedSegments=segmentsServer.getCluster(codeSelectedFrame); 

	// Compute Occupations and Statistics
        acc.resetOcc();
        Seg *seg;
        selectedSegments.rewind();
        String currentSource="";
        while((seg=selectedSegments.getSeg())!=NULL){
                unsigned long begin=seg->begin()+fs.getFirstFeatureIndexOfASource(seg->sourceName());    // Idx of the first frame of the current file in the feature server
                if (currentSource!=seg->sourceName()) {
                currentSource=seg->sourceName();
                if (verbose)cout << "Processing speaker["<<currentSource<<"]"<< endl;
                }

                fs.seekFeature(begin);
                Feature f;

	for (unsigned long idxFrame=0;idxFrame<seg->length();idxFrame++){
                                fs.readFeature(f);
                                acc.computeAndAccumulateOcc(f);
                                RealVector <double> aPost=acc.getOccVect();

				Feature tmpF;
				for(unsigned long k=0;k<_mixsize;k++) {
				tmpF[k]=aPost[k];
				}

                                fs_out.addFeature(f);
}

}

// Writing apost probabilities to file 

	cout << "Writing to: " << featureFilename << endl;
		        FeatureFileWriter w(featureFilename, config);   // build a featurefile writer to output the features (real features)
			SegServer fakeSegServer;
		        if (writeAllFeature) {                  // Output all the features- feature count id the same SegServer fakeSegServer;                                          // Create a new fake segment server
		            fakeSegServer.createCluster(0);       // Create a new cluster
		            SegCluster& fakeSeg=fakeSegServer.getCluster(0);    // Get the cluster               
		            fakeSeg.add(fakeSegServer.createSeg(0,fs_out.getFeatureCount(),codeSelectedFrame, labelSelectedFrames,featureFilename));            // Add a segment with all the features
		            outputFeatureFile(config,fs_out,fakeSeg,w);   // output all the features - giving the same file length
		        }
		        else
		            outputFeatureFile(config,fs_out,selectedSegments, w);    // Output only the selected features - giving a shorter output 


}


	}	
	catch (Exception& e){cout << e.toString().c_str() << endl;}
return 0;
}
Example #20
0
void CookieManager::getRawCookies(Vector<ParsedCookie*> &stackOfCookies, const KURL& requestURL, CookieFilter filter) const
{
    if (!m_syncedWithDatabase && !m_privateMode) {
        LOG_ERROR("CookieManager is calling getRawCookies before database values are loaded.");
        return;
    }

    CookieLog("CookieManager - getRawCookies - processing url with domain - %s & protocol: %s & path: %s\n", requestURL.host().utf8().data(), requestURL.protocol().utf8().data(), requestURL.path().utf8().data());

    const bool invalidScheme = shouldIgnoreScheme(requestURL.protocol());
    const bool specialCaseForWebWorks = invalidScheme && m_shouldDumpAllCookies;
    const bool isConnectionSecure = requestURL.protocolIs("https") || requestURL.protocolIs("wss") || specialCaseForWebWorks;

    Vector<ParsedCookie*> cookieCandidates;
    Vector<CookieMap*> protocolsToSearch;

    // Special Case: If a server sets a "secure" cookie over a non-secure channel and tries to access the cookie
    // over a secure channel, it will not succeed because the secure protocol isn't mapped to the insecure protocol yet.
    // Set the map to the non-secure version, so it'll search the mapping for a secure cookie.
    CookieMap* targetMap = m_managerMap.get(requestURL.protocol());
    if (!targetMap && isConnectionSecure) {
        CookieLog("CookieManager - special case: secure protocol are not linked yet.");
        if (requestURL.protocolIs("https"))
            targetMap = m_managerMap.get("http");
        else if (requestURL.protocolIs("wss"))
            targetMap = m_managerMap.get("ws");
    }

    // Decide which scheme tree we should look at.
    // Return on invalid schemes. cookies are currently disabled on file and local.
    // We only want to enable them for WebWorks that enabled a special flag.
    if (specialCaseForWebWorks)
        copyValuesToVector(m_managerMap, protocolsToSearch);
    else if (invalidScheme)
        return;
    else {
        protocolsToSearch.append(targetMap);
        // FIXME: this is a hack for webworks apps; RFC 6265 says "Cookies do not provide isolation by scheme"
        // so we should not be checking protocols at all. See PR 135595
        if (m_shouldDumpAllCookies) {
            protocolsToSearch.append(m_managerMap.get("file"));
            protocolsToSearch.append(m_managerMap.get("local"));
       }
    }

    Vector<String> delimitedHost;

    // IP addresses are stored in a particular format (due to ipv6). Reduce the ip address so we can match
    // it with the one in memory.
    string canonicalIP = BlackBerry::Platform::getCanonicalIPFormat(requestURL.host().utf8().data());
    if (!canonicalIP.empty())
        delimitedHost.append(String(canonicalIP.c_str()));
    else
        requestURL.host().lower().split(".", true, delimitedHost);

    // Go through all the protocol trees that we need to search for
    // and get all cookies that are valid for this domain
    for (size_t k = 0; k < protocolsToSearch.size(); k++) {
        CookieMap* currentMap = protocolsToSearch[k];

        // if no cookies exist for this protocol, break right away
        if (!currentMap)
            continue;

        CookieLog("CookieManager - looking at protocol map %s \n", currentMap->getName().utf8().data());

        // Special case for local and files - because WebApps expect to get ALL cookies from the backing-store on local protocol
        if (specialCaseForWebWorks) {
            CookieLog("CookieManager - special case find in protocol map - %s\n", currentMap->getName().utf8().data());
            currentMap->getAllChildCookies(&cookieCandidates);
        } else {
            // Get cookies from the null domain map
            currentMap->getAllCookies(&cookieCandidates);

            // Get cookies from the valid domain maps
            int i = delimitedHost.size() - 1;
            while (i >= 0) {
                CookieLog("CookieManager - finding %s in currentmap\n", delimitedHost[i].utf8().data());
                currentMap = currentMap->getSubdomainMap(delimitedHost[i]);
                // if this subdomain/domain does not exist in our mapping then we simply exit
                if (!currentMap) {
                    CookieLog("CookieManager - cannot find next map exiting the while loop.\n");
                    break;
                }
                CookieLog("CookieManager - found the map, grabbing cookies from this map\n");
                currentMap->getAllCookies(&cookieCandidates);
                i--;
            }
        }
    }

    CookieLog("CookieManager - there are %d cookies in candidate\n", cookieCandidates.size());

    for (size_t i = 0; i < cookieCandidates.size(); ++i) {
        ParsedCookie* cookie = cookieCandidates[i];

        // According to the path-matches rules in RFC6265, section 5.1.4,
        // we should add a '/' at the end of cookie-path for comparison if the cookie-path is not end with '/'.
        String path = cookie->path();
        CookieLog("CookieManager - comparing cookie path %s (len %d) to request path %s (len %d)", path.utf8().data(), path.length(), requestURL.path().utf8().data(), path.length());
        if (!equalIgnoringCase(path, requestURL.path()) && !path.endsWith("/", false))
            path = path + "/";

        // Only secure connections have access to secure cookies. Unless specialCaseForWebWorks is true.
        // Get the cookies filtering out HttpOnly cookies if requested.
        if (requestURL.path().startsWith(path, false) && (isConnectionSecure || !cookie->isSecure()) && (filter == WithHttpOnlyCookies || !cookie->isHttpOnly())) {
            CookieLog("CookieManager - cookie chosen - %s\n", cookie->toString().utf8().data());
            cookie->setLastAccessed(currentTime());
            stackOfCookies.append(cookie);
        }
    }

    std::stable_sort(stackOfCookies.begin(), stackOfCookies.end(), cookieSorter);
}
Example #21
0
  if (!origin || count != 2) return ;

  char nickbuf[128] ; irc_target_get_nick(origin , nickbuf , sizeof(nickbuf)) ;

  String      user_id           = String(origin ) ;
  String      nick              = String(nickbuf) ;
  String      channel           = CharPointer_UTF8(params[0]) ;
  String      filtered_message  = ProcessTextMeta (params[1]) ;
  StringArray processed_message = ProcessTimestamp(filtered_message) ;
  String      timestamp         = processed_message[0].trim() ;
  String      message           = processed_message[1].trim() ;
  bool        is_root_user      = IRC::BITLBEE_ROOT_USERS.contains(user_id) ;
  bool        is_root_channel   = channel == String(IRC::BITLBEE_ROOT_CHANNEL     ) ;
  bool        is_xmpp_channel   = channel == String(IRC::BITLBEE_XMPP_CHANNEL     ) ;
  bool        is_login_blocked  = message.endsWith (IRC::BITLBEE_LOGIN_BLOCKED_MSG) ;
  bool        has_kicked_self   = message.endsWith (IRC::BITLBEE_KICKED_SELF_MSG  ) ;
  bool        is_logged_in      = message.endsWith (IRC::BITLBEE_CONNECTED_MSG    ) ||
                                  has_kicked_self                                    ;

DEBUG_TRACE_CHAT_MSG

  // handle login confirmation from the bee
  if (is_root_user && is_root_channel)
    if      (is_login_blocked) AddClientChat(IRC::BITLBEE_SESSION_BLOCKED_MSG) ;
    else if (is_logged_in    ) irc_cmd_join(session , IRC::BITLBEE_XMPP_CHANNEL , NULL) ;
  if (is_root_user || is_root_channel) return ;

  // handle peer messages
  AddUserChat(timestamp , nick , message) ;
}
// parseDataUrl() is taken from the CURL http backend.
static gboolean parseDataUrl(gpointer callback_data)
{
    ResourceHandle* handle = static_cast<ResourceHandle*>(callback_data);
    ResourceHandleClient* client = handle->client();
    ResourceHandleInternal* d = handle->getInternal();
    if (d->m_cancelled)
        return false;

    d->m_idleHandler = 0;

    ASSERT(client);
    if (!client)
        return false;

    String url = handle->request().url().string();
    ASSERT(url.startsWith("data:", false));

    int index = url.find(',');
    if (index == -1) {
        client->cannotShowURL(handle);
        return false;
    }

    String mediaType = url.substring(5, index - 5);
    String data = url.substring(index + 1);

    bool isBase64 = mediaType.endsWith(";base64", false);
    if (isBase64)
        mediaType = mediaType.left(mediaType.length() - 7);

    if (mediaType.isEmpty())
        mediaType = "text/plain;charset=US-ASCII";

    String mimeType = extractMIMETypeFromMediaType(mediaType);
    String charset = extractCharsetFromMediaType(mediaType);

    ResourceResponse response;
    response.setMimeType(mimeType);

    if (isBase64) {
        data = decodeURLEscapeSequences(data);
        response.setTextEncodingName(charset);
        client->didReceiveResponse(handle, response);

        if (d->m_cancelled)
            return false;

        // Use the GLib Base64, since WebCore's decoder isn't
        // general-purpose and fails on Acid3 test 97 (whitespace).
        size_t outLength = 0;
        char* outData = 0;
        outData = reinterpret_cast<char*>(g_base64_decode(data.utf8().data(), &outLength));
        if (outData && outLength > 0)
            client->didReceiveData(handle, outData, outLength, 0);
        g_free(outData);
    } else {
        // We have to convert to UTF-16 early due to limitations in KURL
        data = decodeURLEscapeSequences(data, TextEncoding(charset));
        response.setTextEncodingName("UTF-16");
        client->didReceiveResponse(handle, response);

        if (d->m_cancelled)
            return false;

        if (data.length() > 0)
            client->didReceiveData(handle, reinterpret_cast<const char*>(data.characters()), data.length() * sizeof(UChar), 0);

        if (d->m_cancelled)
            return false;
    }

    client->didFinishLoading(handle);

    return false;
}
Example #23
0
// FIXME: This function does not deal properly with text encodings.
static void parseDataUrl(ResourceHandle* handle)
{
    String data = handle->request().url().string();

    ASSERT(data.startsWith("data:", false));

    String header;
    bool base64 = false;

    int index = data.find(',');
    if (index != -1) {
        header = data.substring(5, index - 5).lower();
        data = data.substring(index + 1);

        if (header.endsWith(";base64")) {
            base64 = true;
            header = header.left(header.length() - 7);
        }
    } else
        data = String();

    data = decodeURLEscapeSequences(data);

    size_t outLength = 0;
    char* outData = 0;
    if (base64 && !data.isEmpty()) {
        // Use the GLib Base64 if available, since WebCore's decoder isn't
        // general-purpose and fails on Acid3 test 97 (whitespace).
#ifdef USE_GLIB_BASE64
        outData = reinterpret_cast<char*>(g_base64_decode(data.utf8().data(), &outLength));
#else
        Vector<char> out;
        if (base64Decode(data.latin1().data(), data.length(), out))
            data = String(out.data(), out.size());
        else
            data = String();
#endif
    }

    if (header.isEmpty())
        header = "text/plain;charset=US-ASCII";

    ResourceHandleClient* client = handle->getInternal()->client();

    ResourceResponse response;

    response.setMimeType(extractMIMETypeFromMediaType(header));
    response.setTextEncodingName(extractCharsetFromMediaType(header));
    if (outData)
        response.setExpectedContentLength(outLength);
    else
        response.setExpectedContentLength(data.length());
    response.setHTTPStatusCode(200);

    client->didReceiveResponse(handle, response);

    if (outData)
        client->didReceiveData(handle, outData, outLength, 0);
    else
        client->didReceiveData(handle, data.latin1().data(), data.length(), 0);

#ifdef USE_GLIB_BASE64
    g_free(outData);
#endif

    client->didFinishLoading(handle);
}
Example #24
0
bool FW::parseTexture(const char*& ptr, TextureSpec& value, const String& dirName)
{
    // Initialize result.

    String name;
    value.texture   = Texture();
    value.base      = 0.0f;
    value.gain      = 1.0f;

    if (hasError())
        return false;

    // Parse options.

    while (*ptr)
    {
        parseSpace(ptr);
        if ((parseLiteral(ptr, "-blendu ") || parseLiteral(ptr, "-blendv ") || parseLiteral(ptr, "-cc ") || parseLiteral(ptr, "-clamp ")) && parseSpace(ptr))
        {
            if (!parseLiteral(ptr, "on") && !parseLiteral(ptr, "off"))
                return false;
        }
        else if (parseLiteral(ptr, "-mm ") && parseSpace(ptr))
        {
            if (!parseFloat(ptr, value.base) || !parseSpace(ptr) || !parseFloat(ptr, value.gain))
                return false;
        }
        else if ((parseLiteral(ptr, "-o ") || parseLiteral(ptr, "-s ") || parseLiteral(ptr, "-t ")) && parseSpace(ptr))
        {
            F32 tmp[2];
            if (!parseFloats(ptr, tmp, 2))
                return false;
            parseSpace(ptr);
            parseFloat(ptr, tmp[0]);
        }
        else if ((parseLiteral(ptr, "-texres ") || parseLiteral(ptr, "-bm ")) && parseSpace(ptr))
        {
            F32 tmp;
            if (!parseFloat(ptr, tmp))
                return false;
        }
        else if (parseLiteral(ptr, "-type ") && parseSpace(ptr))
        {
            if (!parseLiteral(ptr, "sphere") &&
                !parseLiteral(ptr, "cube_top") && !parseLiteral(ptr, "cube_bottom") &&
                !parseLiteral(ptr, "cube_front") && !parseLiteral(ptr, "cube_back") &&
                !parseLiteral(ptr, "cube_left") && !parseLiteral(ptr, "cube_right"))
            {
                return false;
            }
        }
        else
        {
            if (*ptr == '-' || name.getLength())
                return false;
            while (*ptr && (*ptr != '-' || !name.endsWith(' ')))
                name.append(*ptr++);
        }
    }

    // Process file name.

    while (name.startsWith('/'))
        name = name.substring(1);
    while (name.endsWith(' '))
        name = name.substring(0, name.getLength() - 1);

    // Zero-length file name => ignore.

    if (!name.getLength())
        return true;

    // Import texture.

    value.texture = Texture::import(dirName + '/' + name);

#if (!WAVEFRONT_DEBUG)
    clearError();
#endif
    return true;
}
Example #25
0
void addPlugins( const Options& options_main, const String& parentModule, const String& path )
{
   message( "Loading plugin \"" + path +"\" for module " + parentModule );

   Path modPath( parentModule );
   modPath = modPath.getFullLocation() + "/" + path;

   // prepare the target plugin path
   Path outputPath( modPath );
   outputPath.setFilename("");
   Path mainPath;
   mainPath.setFullLocation( options_main.m_sMainScriptPath );
   relativize( mainPath, outputPath );
   outputPath.setFullLocation(
         options_main.m_sTargetDir +"/"+ outputPath.getLocation() );


   // topmost location of the plugin must be
   if( path.endsWith("*") )
   {
      VFSProvider* file = Engine::getVFS("file");
      fassert( file != 0 );
      DirEntry *entry = file->openDir( modPath.getFullLocation() );
      if( entry == 0 )
      {
         warning( "Can't open plugin directory \"" + modPath.getFullLocation() + "\" for module "
               + parentModule );
      }

      String fname;
      while( entry->read( fname ) )
      {

         // binary?
         if ( fname.endsWith(".fam") )
         {
            // do we have also a source?
            modPath.setFilename( fname );
            modPath.setExtension( "fal" );
            FileStat famStats;

            if( Sys::fal_stats( modPath.get(), famStats ) )
            {
               // we have already a fal that has been transferred or will be transferred later,
               // so wait for that.
               continue;
               // otherwise, go on transferring the source.
            }

            // same for ftd
            modPath.setExtension( "ftd" );
            if( Sys::fal_stats( modPath.get(), famStats ) )
            {
               continue;
            }

         }
         else if( fname.endsWith( DllLoader::dllExt() ) )
         {
            //Transfer DLLS as they are.
         }
         // source?
         else if( fname.endsWith( ".fal" ) || fname.endsWith(".ftd") )
         {
               // go on, transfer the source.
         }
         else
         {
            // we don't know how to manage other plugins
            continue;
         }

         // copy our options, so that transferModule doesn't pollute them
         Options options( options_main );

         options.m_sTargetDir = outputPath.get();
         // ok, transfer the thing
         modPath.setFilename( fname );
         transferModules( options, modPath.get() );
      }

      entry->close();
      delete entry;
   }
   else
   {
      // copy our options, so that transferModule doesn't pollute them
      Options options( options_main );
      options.m_sTargetDir = outputPath.get();
      transferModules( options, modPath.get() );
   }
}
Example #26
0
const String SAMCompiler::compile(ValueTree mdlRoot_)
{
    String dspContent;

    //==========================================================================
    // DSP file header
    //==========================================================================
    dspContent << "// This DSP file has been generated by the Synth-A-Modeler compiler.\n";
    dspContent << "import(\"physicalmodeling.lib\");\n\n";

    //==========================================================================

    ValueTree faustTree = mdlRoot_.getChildWithName(Objects::variables);
    ValueTree massTree = mdlRoot_.getChildWithName(Objects::masses);
    ValueTree linkTree = mdlRoot_.getChildWithName(Objects::links);
    ValueTree wgTree = mdlRoot_.getChildWithName(Objects::waveguides);
    ValueTree jTree = mdlRoot_.getChildWithName(Objects::junctions);
    ValueTree tTree = mdlRoot_.getChildWithName(Objects::terminations);
    ValueTree aoTree = mdlRoot_.getChildWithName(Objects::audioobjects);

    int numMasslike = 0;
    int numPorts = 0;
    int numWaveguides = 0;
    int numJunctions = 0;
    String wgTermString;
    String junctString;
    StringArray wgOutputs;
    StringArray wgInputs;
    StringArray massWithJunct;
    StringArray linkWithJunct;
    StringArray massWithJunctLine;
    StringArray portWithJunctLine;
    StringArray massWithJunctOutputs;
    StringArray junctInputs;
    StringArray junctOutputs;

    //==========================================================================

    //==========================================================================
    // Write all waveguides and terminations
    //==========================================================================
    OwnedArray<WgWithSuffixes> wgWithSuffixes;
    for (int i = 0; i < wgTree.getNumChildren(); ++i)
    {
        ++numWaveguides;
        ValueTree wg = wgTree.getChild(i);
        WgWithSuffixes* wws = new WgWithSuffixes();
        wws->wgId = wg[Ids::identifier].toString();
        ValueTree left = jTree.getChildWithProperty(Ids::identifier,
                                                    wg[Ids::startVertex]);
        ValueTree right;
        if (left.isValid())
        {
            right = tTree.getChildWithProperty(Ids::identifier,
                                               wg[Ids::endVertex]);
        }
        else
        {
            left = tTree.getChildWithProperty(Ids::identifier, wg[Ids::startVertex]);
            right = jTree.getChildWithProperty(Ids::identifier, wg[Ids::endVertex]);
        }
        ValueTree term;
        ValueTree junct;
        StringArray wgSuffixes;
        if (left.getType() == Ids::termination)
        {
            wgSuffixes.add(wgR);
            wgSuffixes.add(wgL);
            wgSuffixes.add(wgRp);
            wgSuffixes.add(wgLp);
            term = left;
            junct = right;
            wws->termRight = false;
        }
        else if (left.getType() == Ids::junction)
        {
            wgSuffixes.add(wgL);
            wgSuffixes.add(wgR);
            wgSuffixes.add(wgLp);
            wgSuffixes.add(wgRp);
            term = right;
            junct = left;
            wws->termRight = true;
        }
        wws->wgSuffixes = wgSuffixes;

        wgInputs.add(wg[Ids::identifier].toString() + wgLp);
        wgInputs.add(wg[Ids::identifier].toString() + wgRp);
        wgOutputs.add(wg[Ids::identifier].toString() + wgL);
        wgOutputs.add(wg[Ids::identifier].toString() + wgR);

        ValueTree paWg = wg.getChildWithName(Ids::parameters);
        StringArray paWgStrings;
        for (int j = 0; j < paWg.getNumChildren(); ++j)
        {
            paWgStrings.add(paWg.getChild(j)[Ids::value].toString());
        }
        wws->wgParams = paWgStrings;
        wgWithSuffixes.add(wws);

        ValueTree paTerm = term.getChildWithName(Ids::parameters);
        StringArray paTermStrings;
        for (int j = 0; j < paTerm.getNumChildren(); ++j)
        {
            paTermStrings.add(paTerm.getChild(j)[Ids::value].toString());
        }

        //======================================================================
        wgTermString << "\t";
        wgTermString << wg[Ids::identifier].toString();
        wgTermString << wgSuffixes[0] << " = " << term[Ids::identifier].toString();

        wgTermString << " : ";
        wgTermString << paWgStrings[1];
        wgTermString << ";\n\t";

        wgTermString << term[Ids::identifier].toString();
        wgTermString << " = ";
        wgTermString << wg[Ids::identifier].toString() << wgSuffixes[3];
        wgTermString << " : ";

        wgTermString << paTermStrings[0] << ";\n\n";
        //======================================================================
    }

    //==========================================================================
    // Write all junctions
    //==========================================================================
    for (int i = 0; i < jTree.getNumChildren(); ++i)
    {
        ++numJunctions;
        ValueTree junct = jTree.getChild(i);

        junctOutputs.add(junct[Ids::identifier].toString());
        junctInputs.add(junct[Ids::identifier].toString()+"p");

        ValueTree wgs = getWgForJunct(wgTree, junct);
        StringArray junctWgOuts;
        StringArray junctWgParams;

        junctString << "\t";
        for (int k = 0; k < wgs.getNumChildren(); ++k)
        {
            ValueTree wg = wgs.getChild(k);
            int wgSuffixesIdx = containsWgRef(wgWithSuffixes, wg[Ids::identifier].toString());
            if (wgSuffixesIdx == -1)
                continue;

            const StringArray& wgSuffixes = wgWithSuffixes[wgSuffixesIdx]->wgSuffixes;
            junctString << wg[Ids::identifier].toString() << wgSuffixes[1];
            junctString << " = ";
            junctString << junct[Ids::identifier].toString() << jTO;
            junctString << wg[Ids::identifier].toString();
            junctString << " : ";
            junctString << wgWithSuffixes[wgSuffixesIdx]->wgParams[1];
            junctString << ";\n\t";

            junctString << junct[Ids::identifier].toString() << jTO;
            junctString << wg[Ids::identifier].toString() << " = ";
            junctString << junct[Ids::identifier].toString() << jOutputs;
            junctString << ":(_,!)-";
            junctString << wg[Ids::identifier].toString() << wgSuffixes[2];
            junctString << ";\n\t";

            String jwo;
            jwo << wg[Ids::identifier].toString() << wgSuffixes[2];
            jwo << "*" << wgWithSuffixes[wgSuffixesIdx]->wgParams[0];
            junctWgOuts.add(jwo);

            junctWgParams.add(wgWithSuffixes[wgSuffixesIdx]->wgParams[0]);
        }


        String junctLinkString;
        String junctMassString;
        // Check if junction has one link and mass connected
        ValueTree junctLink = getJunctionLink(linkTree, junct);
        if (junctLink.isValid())
        {
            String jm;
            if (junctLink[Ids::startVertex] == junct[Ids::identifier])
                jm << junctLink[Ids::endVertex].toString();
            else
                jm << junctLink[Ids::startVertex].toString();
            junctMassString << jm << "p";

            massWithJunct.add(jm);
            massWithJunctOutputs.add(jm + "p");
            linkWithJunct.add(junctLink[Ids::identifier].toString());

            ValueTree junctLinkParams = junctLink.getChildWithName(Ids::parameters);
            StringArray junctLinkParamsStrings;
            for (int k = 0; k < junctLinkParams.getNumChildren(); ++k)
            {
                ValueTree param = junctLinkParams.getChild(k);
                junctLinkParamsStrings.add(param[Ids::value].toString());
            }
            junctLinkString << "junction" << junctLink.getType().toString();
            junctLinkString << "Underneath(0.0,";
            junctLinkString << junctLinkParamsStrings.joinIntoString(",");
            junctLinkString << ")";

            // Get mass-like object connected with junction > link
            ValueTree mwj = massTree.getChildWithProperty(Ids::identifier, jm);
            String mwjl = "\t";
            mwjl << jm;
            mwjl << " = (0.0";

            StringArray otherLinks;
            for (int k = 0; k < linkTree.getNumChildren(); ++k)
            {
                ValueTree li = linkTree.getChild(k);
                if(li[Ids::identifier].toString() == junctLink[Ids::identifier].toString())
                    continue;
                if(li[Ids::startVertex].toString() == jm)
                {
                    otherLinks.add("-"+li[Ids::identifier].toString());
                }
                else if (li[Ids::endVertex].toString() == jm)
                {
                    otherLinks.add("+"+li[Ids::identifier].toString());
                }
            }


            mwjl << otherLinks.joinIntoString(String::empty);
            mwjl << "+(";
            mwjl << junct[Ids::identifier].toString() << jOutputs << ":(!,_)))";
//            mwjl << " : ";
//            ValueTree mwjp = mwj.getChildWithName(Ids::parameters);
//            StringArray mwjpStrings;
//            for (int p = 0; p < mwjp.getNumChildren(); ++p)
//            {
//                ValueTree param = mwjp.getChild(p);
//                mwjpStrings.add(param[Ids::value].toString());
//            }
//            mwjl << mwj.getType().toString();
//            mwjl << "(" << mwjpStrings.joinIntoString(",") << ")";
            mwjl << ";";
            massWithJunctLine.add(mwjl);

        }
        else
        {
            junctMassString << "0.0";
            junctLinkString << "junctionlink(0.0, 0.0, 0.0, 0.0)";
        }
        junctString << junct[Ids::identifier].toString() << jOutputs;
        junctString << " = (";
        junctString << junctMassString << ", 0.0+";

        junctString << junctWgOuts.joinIntoString("+");
        junctString << ", 0.0+";
        junctString << junctWgParams.joinIntoString("+");

        junctString << ") : ";
        junctString << junctLinkString << ";\n\t";

        junctString << junct[Ids::identifier].toString();
        junctString << " = ";
        junctString << junct[Ids::identifier].toString() << jOutputs;
        junctString << ":(_,!);\n\n";

    }

    //==========================================================================
    // Write all faustcode
    //==========================================================================
    for (int i = 0; i < faustTree.getNumChildren(); ++i)
    {
        ValueTree fa = faustTree.getChild(i);
        dspContent << fa[Ids::identifier].toString();
        dspContent << "=";
        dspContent << fa[Ids::faustCode].toString();
        dspContent << ";\n";
    }

    dspContent << "\n";

    //==========================================================================
    // Get all mass names
    //==========================================================================
    OwnedArray<MassLinkRef> massLinkRefs;
    for (int i = 0; i < massTree.getNumChildren(); ++i)
    {
        ValueTree ma = massTree.getChild(i);
        if (massWithJunct.contains(ma[Ids::identifier].toString()))
            continue;
        MassLinkRef* mlf = new MassLinkRef();
        mlf->massId = ma[Ids::identifier].toString();
        StringArray mlfa;
        mlf->linkRefs = mlfa;
        if (ma.getType() == Ids::port)
            mlf->isPort = true;
        else
            mlf->isPort = false;
        massLinkRefs.add(mlf);
    }

    //==========================================================================
    // Write all link-like objects
    //==========================================================================
    StringArray linkobjects;
    for (int i = 0; i < linkTree.getNumChildren(); ++i)
    {
        ValueTree li = linkTree.getChild(i);
        String linkId = li[Ids::identifier].toString();
        if (linkWithJunct.contains(linkId))
            continue;
        String startVertex = li[Ids::startVertex].toString();
        String endVertex = li[Ids::endVertex].toString();
        int sIdx = containsMassLinkRef(massLinkRefs, startVertex);
        if (sIdx >= 0)
            massLinkRefs[sIdx]->linkRefs.add("-" + linkId);

        int eIdx = containsMassLinkRef(massLinkRefs, endVertex);
        if (eIdx >= 0)
            massLinkRefs[eIdx]->linkRefs.add("+" + linkId);

        String tagName = li.getType().toString();
        ValueTree params = li.getChildWithName(Ids::parameters);
        StringArray paramsStr;
        for (int k = 0; k < params.getNumChildren(); ++k)
        {
            ValueTree param = params.getChild(k);
            paramsStr.add(param[Ids::value].toString());
        }

        //======================================================================
        String linkLine;
        linkLine << "\t";
        linkLine << linkId;
        linkLine << " = (";

        linkLine << startVertex << "p - ";
        linkLine << endVertex << "p) : ";
        linkLine << tagName << "(";
        linkLine << paramsStr.joinIntoString(",") << ");";
        linkobjects.add(linkLine);
        //======================================================================
    }

    StringArray massobjects;

    //==========================================================================
    // write all mass-like object except those connected to junctions
    //==========================================================================
    for (int i = 0; i < massTree.getNumChildren(); ++i)
    {
        ValueTree ma = massTree.getChild(i);
        if (massWithJunct.contains(ma[Ids::identifier].toString()))
        {
            if(ma.getType().toString().compare("port") == 0)
                ++numPorts;
            continue;
        }

        ++numMasslike;
        String tagName = ma.getType().toString();
        String massName = ma[Ids::identifier].toString();
        String massLine;
        massLine << "\t";
        massLine << massName << " = (0.0";
        if (tagName.compare("port") == 0)
            ++numPorts;

        int mIdx = containsMassLinkRef(massLinkRefs, massName);
        if (mIdx >= 0)
        {
            if (massLinkRefs[mIdx]->linkRefs.size() > 0)
            {
                massLine << massLinkRefs[mIdx]->linkRefs.joinIntoString(String::empty);
            }
        }

        massLine << ")";
        if (tagName.compare("port") != 0)
        {
            massLine << " : ";
            massLine << tagName << "(";
            ValueTree params = ma.getChildWithName(Ids::parameters);
            StringArray paramsStr;
            for (int k = 0; k < params.getNumChildren(); ++k)
            {
                ValueTree param = params.getChild(k);
                paramsStr.add(param[Ids::value].toString());
            }
            massLine << paramsStr.joinIntoString(",") << ")";
        }
        massLine << ";";
        massobjects.add(massLine);

    }
    //==========================================================================
    // add remaining mass-like object which are connected to junctions
    //==========================================================================
    massobjects.addArray(massWithJunctLine);

    //==========================================================================
    // Write all audio objects
    //==========================================================================
    StringArray audioobjects;
    StringArray audioNames;
    for (int i = 0; i < aoTree.getNumChildren(); ++i)
    {
        ValueTree ao = aoTree.getChild(i);

        String audioLine;
        String audioName = ao[Ids::identifier].toString();
        audioNames.add(audioName);
        audioLine << "\t";
        audioLine << audioName << " = ";
        ValueTree sources = ao.getChildWithName(Ids::sources);
        String paramLine;
        StringArray paramsStr;
        if (sources.getNumChildren() > 0)
        {
            for (int k = 0; k < sources.getNumChildren(); ++k)
            {
                ValueTree src = sources.getChild(k);
                paramsStr.add(src[Ids::value].toString());
            }
            paramLine << paramsStr.joinIntoString("+");
        }

        String optional = ao[Ids::optional].toString();
        if (optional != String::empty)
        {
            if(! paramLine.startsWith("("))
                paramLine = "(" + paramLine;
            if(! paramLine.endsWith(")"))
                paramLine << ")";
            paramLine << optional;
        }
        audioLine << paramLine;
        audioLine << ";";
        audioobjects.add(audioLine);
    }

    //==========================================================================
    // Generate all inputs and outputs
    //==========================================================================
    StringArray inputs;
    StringArray inputsPorts;
    for (int i = 0; i < massLinkRefs.size(); ++i)
    {
        if (massLinkRefs[i]->isPort)
            inputsPorts.add(massLinkRefs[i]->massId);
        else
            inputs.add(massLinkRefs[i]->massId);
    }

    StringArray outputs = inputs;
    outputs.addArray(massWithJunct);
    StringArray outputsPorts = inputsPorts;

    StringArray inputsP;
    StringArray inputsPPorts;
    for (int i = 0; i < inputs.size(); ++i)
    {
        String inputP = inputs[i];
        inputP << "p";
        inputsP.add(inputP);
    }
    for (int i = 0; i < massWithJunctOutputs.size(); ++i)
    {
        ++numMasslike;
        String inputP = massWithJunctOutputs[i];
        inputsP.add(inputP);
    }
    for (int i = 0; i < inputsPorts.size(); ++i)
    {
        String inputPPort = inputsPorts[i];
        inputPPort << "p";
        inputsPPorts.add(inputPPort);
    }

    //==========================================================================
    // bibBlock with all imputs and outputs
    //==========================================================================
    dspContent << "bigBlock(" << inputsP.joinIntoString(",");
    if (wgInputs.size() > 0)
        dspContent << "," << wgInputs.joinIntoString(",");
    if (junctInputs.size() > 0)
        dspContent << "," << junctInputs.joinIntoString(",");
    if (inputsPPorts.size() > 0)
        dspContent << "," << inputsPPorts.joinIntoString(",");
    dspContent << ") = (";
    dspContent << outputs.joinIntoString(",");
    if (wgOutputs.size() > 0)
        dspContent << "," << wgOutputs.joinIntoString(",");
    if (junctOutputs.size() > 0)
        dspContent << "," << junctOutputs.joinIntoString(",");
    if (outputsPorts.size() > 0)
        dspContent << "," << outputsPorts.joinIntoString(",");
    if (audioNames.size() > 0)
        dspContent << "," << audioNames.joinIntoString(",");
    dspContent << ") with {\n";

    //==========================================================================
    // code for model objects
    //==========================================================================
    dspContent << "\n\t//waveguide termination objects\n";
    dspContent << wgTermString;
    dspContent << "\t//junctions\n";
    dspContent << junctString;
    dspContent << "\t//mass-like objects\n";
    dspContent << massobjects.joinIntoString("\n") << "\n";
    dspContent << "\n\t//link-like objects\n";
    dspContent << linkobjects.joinIntoString("\n") << "\n";
    dspContent << "\n\t//audio objects\n";
    dspContent << audioobjects.joinIntoString("\n") << "\n};\n\n";

    //==========================================================================
    // Calculate and write feedback line
    //==========================================================================
    StringArray feedbackArray;
    StringArray outputArray;
    //TODO: needs to be fixed for latest Synth-A-Modeler changes/fiyes
    int numFeedback = numMasslike - numPorts + (2 * numWaveguides) + numJunctions;
    for (int i = 0; i < numFeedback; ++i)
    {
        feedbackArray.add("_");
        outputArray.add("!");
    }
    for (int i = 0; i < numPorts + audioNames.size(); ++i)
    {
        feedbackArray.add("!");
        outputArray.add("_");
    }
    dspContent << "process = (bigBlock)~(";
    dspContent << feedbackArray.joinIntoString(",");
    dspContent << "):(";
    dspContent << outputArray.joinIntoString(",") << ");";

    //==========================================================================
    massLinkRefs.clear();
    wgWithSuffixes.clear();

    return dspContent;
}
bool SVGSMILElement::parseCondition(const String& value, BeginOrEnd beginOrEnd)
{
    String parseString = value.stripWhiteSpace();
    
    double sign = 1.;
    bool ok;
    int pos = parseString.find('+');
    if (pos == -1) {
        pos = parseString.find('-');
        if (pos != -1)
            sign = -1.;
    }
    String conditionString;
    SMILTime offset = 0;
    if (pos == -1)
        conditionString = parseString;
    else {
        conditionString = parseString.left(pos).stripWhiteSpace();
        String offsetString = parseString.substring(pos + 1).stripWhiteSpace();
        offset = parseOffsetValue(offsetString);
        if (offset.isUnresolved())
            return false;
        offset = offset * sign;
    }
    if (conditionString.isEmpty())
        return false;
    pos = conditionString.find('.');
    
    String baseID;
    String nameString;
    if (pos == -1)
        nameString = conditionString;
    else {
        baseID = conditionString.left(pos);
        nameString = conditionString.substring(pos + 1);
    }
    if (nameString.isEmpty())
        return false;

    Condition::Type type;
    int repeats = -1;
    if (nameString.startsWith("repeat(") && nameString.endsWith(")")) {
        // FIXME: For repeat events we just need to add the data carrying TimeEvent class and 
        // fire the events at appropiate times.
        repeats = nameString.substring(7, nameString.length() - 8).toUIntStrict(&ok);
        if (!ok)
            return false;
        nameString = "repeat";
        type = Condition::EventBase;
    } else if (nameString == "begin" || nameString == "end") {
        if (baseID.isEmpty())
            return false;
        type = Condition::Syncbase;
    } else if (nameString.startsWith("accesskey(")) {
        // FIXME: accesskey() support.
        type = Condition::AccessKey;
    } else
        type = Condition::EventBase;
    
    m_conditions.append(Condition(type, beginOrEnd, baseID, nameString, offset, repeats));

    if (type == Condition::EventBase && beginOrEnd == End)
        m_hasEndEventConditions = true;

    return true;
}
Example #28
0
void WiFiLib::wifiLoop() {
    if(WiFiLib_DEV.available()) {
		char IPDSteps = 0, c;
		int ipd;
		String route = "";
		long int time = millis() + 500;
		while (time > millis()) {
			while (WiFiLib_DEV.available()) {
				c = WiFiLib_DEV.read(); // read the next character.
				switch (IPDSteps) {
					case 0:
						if (c == '+') {
							IPDSteps++;
						} else {
							IPDSteps = 0;
						}
						break;

					case 1:
						if (c == 'I') {
							IPDSteps++;
						} else {
							IPDSteps = 0;
						}
						break;

					case 2:
						if (c == 'P') {
							IPDSteps++;
						} else {
							IPDSteps = 0;
						}
						break;

					case 3:
						if (c == 'D') {
							IPDSteps++;
						} else {
							IPDSteps = 0;
						}
						break;

					case 4:
						if (c == ',') {
							IPDSteps++;
							ipd = 0;
						} else {
							IPDSteps = 0;
						}
						break;

					case 5: // Reading IPD channel
						if (c == ',') {
							IPDSteps++;
						} else {
							ipd = ipd * 10 + c - 48;
						}
						break;

					case 6: // Length, ignored
						if (c == ':') {
							IPDSteps++;
						}
						break;

					case 7: // GET, post, etc
						if (c == ' ') {
							IPDSteps++;
						}
						break;

					case 8: // Route
						if (c == ' ') {
							IPDSteps++;
						} else {
							route += c;
						}
						break;
			
					case 9: // Ignore, request completed
						break;
			
					default:
						IPDSteps = 0;
				}
			}
		}
		if (IPDSteps == 9) { // Request fond, check routes
			IPDStruct * last = IPDs;
			bool found = false;
			char *tmpstr = NULL;
			while (last != NULL) {
				tmpstr = NULL;
				if (last->mode == 4) {// 4 Default route
						found = true;
				} else if (strlen(last->route) <= route.length()) {
					switch (last->mode) {
						case 3:// 3 found in any position
							found = route.indexOf(*last->route) >= 0;
							break;

						case 2:// 2 ends with
							found = route.endsWith(last->route);
							break;

						case 1:// 1 starts with
							found = route.startsWith(last->route);
							break;

						case 0:// 0 same string
						default:
							found = route.equals(last->route);
							break;
					}
					if (tmpstr != NULL) {
						free(tmpstr);
					}
				}
				if (found) {
					last->fp(route, ipd);
					sendPart(F("AT+CIPCLOSE="));
					send(String(ipd, DEC), 100);
					return;
				}
				last = (IPDStruct *) last->next;
			}
		sendDataByIPD(ipd, F("404 - Not found"));
		send(String(ipd, DEC), 100);
		last->fp(route, ipd);
		sendPart(F("AT+CIPCLOSE="));
		send(String(ipd, DEC), 100);
		}			
	}
}
Example #29
0
DocumentFragment* createFragmentFromText(const EphemeralRange& context,
                                         const String& text) {
  if (context.isNull())
    return nullptr;

  Document& document = context.document();
  DocumentFragment* fragment = document.createDocumentFragment();

  if (text.isEmpty())
    return fragment;

  String string = text;
  string.replace("\r\n", "\n");
  string.replace('\r', '\n');

  if (!isRichlyEditablePosition(context.startPosition()) ||
      shouldPreserveNewline(context)) {
    fragment->appendChild(document.createTextNode(string));
    if (string.endsWith('\n')) {
      HTMLBRElement* element = HTMLBRElement::create(document);
      element->setAttribute(classAttr, AppleInterchangeNewline);
      fragment->appendChild(element);
    }
    return fragment;
  }

  // A string with no newlines gets added inline, rather than being put into a
  // paragraph.
  if (string.find('\n') == kNotFound) {
    fillContainerFromString(fragment, string);
    return fragment;
  }

  // Break string into paragraphs. Extra line breaks turn into empty paragraphs.
  Element* block =
      enclosingBlock(context.startPosition().nodeAsRangeFirstNode());
  bool useClonesOfEnclosingBlock =
      block && !isHTMLBodyElement(*block) && !isHTMLHtmlElement(*block) &&
      block != rootEditableElementOf(context.startPosition());

  Vector<String> list;
  string.split('\n', true, list);  // true gets us empty strings in the list
  size_t numLines = list.size();
  for (size_t i = 0; i < numLines; ++i) {
    const String& s = list[i];

    Element* element = nullptr;
    if (s.isEmpty() && i + 1 == numLines) {
      // For last line, use the "magic BR" rather than a P.
      element = HTMLBRElement::create(document);
      element->setAttribute(classAttr, AppleInterchangeNewline);
    } else {
      if (useClonesOfEnclosingBlock)
        element = block->cloneElementWithoutChildren();
      else
        element = createDefaultParagraphElement(document);
      fillContainerFromString(element, s);
    }
    fragment->appendChild(element);
  }
  return fragment;
}
Example #30
-1
void MainResourceLoader::substituteMIMETypeFromPluginDatabase(const ResourceResponse& r)
{
    if (!m_frame->loader()->subframeLoader()->allowPlugins(NotAboutToInstantiatePlugin))
        return;

    String filename = r.url().lastPathComponent();
    if (filename.endsWith("/"))
        return;

    size_t extensionPos = filename.reverseFind('.');
    if (extensionPos == notFound)
        return;

    String extension = filename.substring(extensionPos + 1);
    String mimeType = PluginDatabase::installedPlugins()->MIMETypeForExtension(extension);
    if (!mimeType.isEmpty()) {
        ResourceResponse* response = const_cast<ResourceResponse*>(&r);
        response->setMimeType(mimeType);
    }
}