Example #1
0
void ContextGL_X11::set_use_vsync(bool p_use) {
	static bool setup = false;
	static PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT = NULL;
	static PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalMESA = NULL;
	static PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI = NULL;

	if (!setup) {
		setup = true;
		String extensions = glXQueryExtensionsString(x11_display, DefaultScreen(x11_display));
		if (extensions.find("GLX_EXT_swap_control") != -1)
			glXSwapIntervalEXT  = (PFNGLXSWAPINTERVALEXTPROC) glXGetProcAddressARB((const GLubyte*)"glXSwapIntervalEXT");
		if (extensions.find("GLX_MESA_swap_control") != -1)
			glXSwapIntervalMESA = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddressARB((const GLubyte*)"glXSwapIntervalMESA");
		if (extensions.find("GLX_SGI_swap_control") != -1)
			glXSwapIntervalSGI  = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddressARB((const GLubyte*)"glXSwapIntervalSGI");
	}
	int val = p_use ? 1:0;
	if (glXSwapIntervalMESA) {
		glXSwapIntervalMESA(val);
	}
	else if (glXSwapIntervalSGI) {
		glXSwapIntervalSGI(val);
	}
	else if (glXSwapIntervalEXT) {
		GLXDrawable drawable = glXGetCurrentDrawable();
		glXSwapIntervalEXT(x11_display, drawable, val);
	}
	else return;
	use_vsync = p_use;
}
Example #2
0
void WebSocket::close(int code, const String& reason, ExceptionCode& ec)
{
    if (code == WebSocketChannel::CloseEventCodeNotSpecified)
        LOG(Network, "WebSocket %p close() without code and reason", this);
    else {
        LOG(Network, "WebSocket %p close() code=%d reason='%s'", this, code, reason.utf8().data());
        if (!(code == WebSocketChannel::CloseEventCodeNormalClosure || (WebSocketChannel::CloseEventCodeMinimumUserDefined <= code && code <= WebSocketChannel::CloseEventCodeMaximumUserDefined))) {
            ec = INVALID_ACCESS_ERR;
            return;
        }
        CString utf8 = reason.utf8(StrictConversionReplacingUnpairedSurrogatesWithFFFD);
        if (utf8.length() > maxReasonSizeInBytes) {
            scriptExecutionContext()->addConsoleMessage(MessageSource::JS, MessageLevel::Error, ASCIILiteral("WebSocket close message is too long."));
            ec = SYNTAX_ERR;
            return;
        }
    }

    if (m_state == CLOSING || m_state == CLOSED)
        return;
    if (m_state == CONNECTING) {
        m_state = CLOSING;
        m_channel->fail("WebSocket is closed before the connection is established.");
        return;
    }
    m_state = CLOSING;
    if (m_channel)
        m_channel->close(code, reason);
}
Example #3
0
void NoteMapHandler::paintListBoxItem (int row, Graphics& g, int w, int h, bool selected)
{
    if (map)
    {
        g.setFont (Font(11.0f));
        String inName = MidiMessage::getMidiNoteName (row, true,true,octaveMiddleC);
        String inCh = String(inputChannel->getSelectedChannel ());
        String outName = MidiMessage::getMidiNoteName (map->getOutputNoteFor (row), true,true,octaveMiddleC);
        String outCh = String(map->getOutputChannelFor (row));
        if (inName.contains (T("#")))
        {
            g.setColour (Colours::darkgrey);
            g.fillRect  (0,0,w/2,h);
            g.setColour (Colours::white);
        }
        else g.setColour (Colours::black);
        g.drawFittedText (inName,20,0,w/2-20,h,Justification::centred,1);
        g.drawFittedText (inCh,0,0,20,h,Justification::centred,1);

        if (outName.contains (T("#")))
        {
            g.setColour (Colours::darkgrey);
            g.fillRect  (w/2,0,w/2,h);
            g.setColour (Colours::white);
        }
        else g.setColour (Colours::black);
        g.drawFittedText (outName,w/2,0,w/2-20,h,Justification::centred,1);
        g.drawFittedText (outCh,w-20,0,20,h,Justification::centred,1);

        if (selected) g.fillAll (Colours::orange.withAlpha (0.3f));
    }
}
Example #4
0
bool XMLReader::set_relaxng_schema(String source, int type) {
  SYNC_VM_REGS_SCOPED();
  if (source.empty()) {
    raise_warning("Schema data source is required");
    return false;
  }

  if (m_ptr) {
    int ret = -1;
    xmlRelaxNGPtr schema = nullptr;
    if (!source.empty()) {
      schema =  _xmlreader_get_relaxNG(source, type, nullptr, nullptr);
      if (schema) {
        ret = xmlTextReaderRelaxNGSetSchema(m_ptr, schema);
      }
    } else {
      ret = xmlTextReaderRelaxNGSetSchema(m_ptr, nullptr);
    }

    if (ret == 0) {
      if (m_schema) {
        xmlRelaxNGFree((xmlRelaxNGPtr) m_schema);
      }
      m_schema = schema;
      return true;
    }
  }

  raise_warning("Unable to set schema. This must be set prior to reading or schema contains errors.");
  return false;
}
Example #5
0
bool WebServer::authenticate(const char * username, const char * password)
{
  if(_autorization.length()>0)
  {
    String authReq = _autorization;
    if(authReq.startsWith("Basic")){
      authReq = authReq.substring(6);
      authReq.trim();
      char toencodeLen = strlen(username)+strlen(password)+1;
      char *toencode = new char[toencodeLen + 1];
      if(toencode == NULL){
        return false;
      }
      char *encoded = new char[base64_encode_expected_len(toencodeLen)+1];
      if(encoded == NULL){
        delete[] toencode;
        return false;
      }
      sprintf(toencode, "%s:%s", username, password);
      if(base64_encode_chars(toencode, toencodeLen, encoded) > 0 && authReq.equals(encoded)){
        delete[] toencode;
        delete[] encoded;
        return true;
      }
      delete[] toencode;
      delete[] encoded;
    }
  }
  return false;
}
Example #6
0
bool
XFace::CreateFromXFace(const char *xfacedata)
{
#ifndef HAVE_COMPFACE_H
   return false;
#else
   if(data) delete [] data;
   if(xface) delete [] xface;
   initialised = false;

   xface = new char [2500];
   strncpy(xface, xfacedata, 2500);
   data = new char [5000];
   strncpy(data, xface, 5000);
   if(uncompface(data) < 0)
   {
      delete [] data;
      delete [] xface;
      data = xface = NULL;
      return false;
   }
   String out = strutil_enforceCRLF(wxString::FromAscii(xface));
   delete [] xface;
   xface = strutil_strdup(out.ToAscii());
   initialised = true;
   return true;
#endif
}
int32 TranslationManager::findMatchingLanguage(const String &lang) {
	uint langLength = lang.size();
	uint numLangs = _langs.size();

	// Try to match languages of the same length or longer ones
	// that can be cut at the length of the given one.
	for (uint i = 0; i < numLangs; ++i) {
		uint iLength = _langs[i].size();
		if (iLength >= langLength) {
			// Found a candidate; compare the full string by default.
			String cmpLang = _langs[i];

			if ((iLength > langLength) && (_langs[i][langLength] == '_')) {
				// It has a separation mark at the length of the
				// requested language, so we can cut it.
				cmpLang = String(_langs[i].c_str(), langLength);
			}
			if (lang.equalsIgnoreCase(cmpLang))
				return i;
		}
	}

	// Couldn't find a matching language.
	return -1;
}
Example #8
0
gchar* webkit_web_frame_get_response_mime_type(WebKitWebFrame* frame)
{
    Frame* coreFrame = core(frame);
    WebCore::DocumentLoader* docLoader = coreFrame->loader()->documentLoader();
    String mimeType = docLoader->responseMIMEType();
    return g_strdup(mimeType.utf8().data());
}
Example #9
0
AutoPtr<ITimeZone> TimeZone::GetDefault()
{
    if (sDefaultTimeZone == NULL) {
        AutoPtr<ITimeZoneGetter> tzGetter = TimeZoneGetter::GetInstance();
        String zoneName;
        if (tzGetter != NULL) {
            tzGetter->GetId(&zoneName);
        }
        if (!zoneName.IsNull()) {
            zoneName = zoneName.Trim();
        }
        if (!zoneName.IsNull() || zoneName.IsEmpty()) {
            // try {
                // On the host, we can find the configured timezone here.
            ECode ec = IoUtils::ReadFileAsString(String("/etc/timezone"), &zoneName);
            // } catch (IOException ex) {
                // "vogar --mode device" can end up here.
                // TODO: give libcore access to Android system properties and read "persist.sys.timezone".
            if (FAILED(ec)) {
                zoneName = String("GMT");
            }
            // }
        }
        TimeZone::GetTimeZone(zoneName, (ITimeZone**)&sDefaultTimeZone);
    }

    AutoPtr<ITimeZone> tz;
    sDefaultTimeZone->Clone((ITimeZone**)&tz);
    return tz;
}
OriginAccessEntry::OriginAccessEntry(const String& protocol, const String& host, SubdomainSetting subdomainSetting)
    : m_protocol(protocol.lower())
    , m_host(host.lower())
    , m_subdomainSettings(subdomainSetting)
    , m_hostIsPublicSuffix(false)
{
    ASSERT(subdomainSetting >= AllowSubdomains || subdomainSetting <= DisallowSubdomains);

    m_hostIsIPAddress = HostIsIPAddress(host);

    // Look for top-level domains, either with or without an additional dot.
    if (!m_hostIsIPAddress) {
        WebPublicSuffixList* suffixList = Platform::current()->publicSuffixList();
        if (!suffixList)
            return;

        size_t publicSuffixLength = suffixList->getPublicSuffixLength(m_host);
        if (m_host.length() <= publicSuffixLength + 1) {
            m_hostIsPublicSuffix = true;
        } else if (subdomainSetting == AllowRegisterableDomains && publicSuffixLength) {
            // The "2" in the next line is 1 for the '.', plus a 1-char minimum label length.
            const size_t dot = m_host.reverseFind('.', m_host.length() - publicSuffixLength - 2);
            if (dot == kNotFound)
                m_registerableDomain = host;
            else
                m_registerableDomain = host.substring(dot + 1);
        }
    }
}
Example #11
0
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);
}
Example #12
0
//---------------------------------------------------------------------------
void CIter::Insert(String text)
{
  if(myown)
    component->Insert(text.c_str(), &itr);
  else
    component->Insert(text.c_str());
}
static duk_ret_t Terrain_EnsureTypeNameWithoutPrefix_Static_String(duk_context* ctx)
{
    String tn = duk_require_string(ctx, 0);
    String ret = Terrain::EnsureTypeNameWithoutPrefix(tn);
    duk_push_string(ctx, ret.CString());
    return 1;
}
Example #14
0
bool ProcessInstance::CanExecuteOn( const ImageVariant& image, String& whyNot ) const
{
   if ( !image.IsSharedImage() || !image.IsCompletelySelected() )
   {
      ImageVariant tmp;
      tmp.CreateSharedImageAs( image ).AssignImage( image );
      return CanExecuteOn( tmp, whyNot );
   }

   image.PushSelections();
   image.ResetSelections();

   ImageInfo info1( *image );

   image.PopSelections();

   whyNot.Clear();
   whyNot.Reserve( WHYNOT_MAXLENGTH );

   bool ok = (*API->Process->ValidateImageExecution)( handle, image.SharedImageHandle(), whyNot.c_str(), WHYNOT_MAXLENGTH ) != api_false;

   image.PushSelections();
   image.ResetSelections();

   ImageInfo info2( *image );

   image.PopSelections();

   if ( info1 != info2 )
      APIHackingAttempt( "ValidateImageExecution" );

   return ok;
}
Example #15
0
/* static */
String
XFace::ConvertImgToXFaceData(wxImage &img)
{
   int l, n, i;
   int value;
   String dataString;
   String tmp;

   for(l = 0; l < 48; l++)
   {
      for(n = 0; n <= 32; n+= 16)
      {
         value = 0;
         for(i = 0; i < 16; i++)
         {
            if(img.GetRed(n+i,l) != 0)
               value += 1;
            if(i != 15)
               value <<= 1;
         }
         value = value ^ 0xffff;
         tmp.Printf(_T("0x%04lX"), (unsigned long)value);
         dataString += tmp;
         dataString += _T(',');
      }
      dataString += _T('\n');
   }
   return dataString;
}
// Timer methods
void MainComponent::timerCallback()
{
	AudioPlayHead::CurrentPositionInfo pos (pluginAudioProcessor->lastPosInfo);
	
	if (lastDisplayedPosition != pos) {
		lastDisplayedPosition = pos;
		String displayText;
		displayText.preallocateStorage (64);
		
		displayText 
		<< "BPM: " << String (pos.bpm, 2) << " "
		//		<< "Time Sig: " << pos.timeSigNumerator << "/" << pos.timeSigDenominator << "\n"
		//<< "Recording: " << String (pos.isRecording) << " " // Doesn't work in Live 8
		//<< "Playing: " << String (pos.isPlaying) << " " 
		//<< "Time In Seconds: " << String (pos.timeInSeconds) << "\n"
		<< "PPQ Position: " << String (pos.ppqPosition);
		//<< "PPQ Position of Last Bar Start: " << String (pos.ppqPositionOfLastBarStart) << "\n"
		//<< "Edit Origin Time: " << String (pos.editOriginTime) << "\n" // Doesn't work in Live 8
		//<< "Framerate: " << String (pos.frameRate) << "\n" // Shows '99' in Live 8
		//<< "Timecode String: " << timeToTimecodeString (pos.timeInSeconds) << "\n"
		//<< "Bars, Beats, & Ticks: " << ppqToBarsBeatsString (pos.ppqPosition, pos.timeSigNumerator,
		//											 pos.timeSigDenominator);
		
		positionLabel->setText (displayText, false);
	}
}
Example #17
0
bool
XFace::CreateFromFile(const String& filename)
{
   wxImage img = GetXFaceImg(filename);
   String datastring = ConvertImgToXFaceData(img);
   return CreateFromData(datastring.ToAscii());
}
TEST(MediaConditionParserTest, Basic)
{
    // The first string represents the input string.
    // The second string represents the output string, if present.
    // Otherwise, the output string is identical to the first string.
    TestCase testCases[] = {
        {"screen", "not all"},
        {"screen and (color)", "not all"},
        {"all and (min-width:500px)", "not all"},
        {"(min-width:500px)", "(min-width: 500px)"},
        {"(min-width: -100px)", "not all"},
        {"(min-width: 100px) and print", "not all"},
        {"(min-width: 100px) and (max-width: 900px)", "(max-width: 900px) and (min-width: 100px)"},
        {"(min-width: [100px) and (max-width: 900px)", "not all"},
        {"not (min-width: 900px)", "not all and (min-width: 900px)"},
        {"not (blabla)", "not all"},
        {0, 0} // Do not remove the terminator line.
    };

    // FIXME: We should test comma-seperated media conditions
    for (unsigned i = 0; testCases[i].input; ++i) {
        CSSTokenizer::Scope scope(testCases[i].input);
        MediaQuerySet* mediaConditionQuerySet = MediaQueryParser::parseMediaCondition(scope.tokenRange());
        ASSERT_EQ(mediaConditionQuerySet->queryVector().size(), (unsigned)1);
        String queryText = mediaConditionQuerySet->queryVector()[0]->cssText();
        ASSERT_STREQ(testCases[i].output, queryText.ascii().data());
    }
}
Example #19
0
bool
XFace::CreateFromData(const char *idata)
{
#ifndef  HAVE_COMPFACE_H
   return false;
#else
   if(data)  delete [] data;
   data = strutil_strdup(idata);
   if(xface) delete [] xface;

   xface = new char[2500];
   strncpy(xface, data, 2500);
   if(compface(xface) < 0)
   {
      delete [] xface;
      delete [] data;
      xface = data = NULL;
      return false;
   }
   //convert it:
   String out = strutil_enforceCRLF(wxString::FromAscii(xface));
   delete [] xface;
   xface = strutil_strdup(out.ToAscii());
   initialised = true;
   return true;
#endif
}
 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 #21
0
Variant HHVM_METHOD(XMLReader, getAttributeNs,
                    const String& name,
                    const String& namespaceURI) {
  auto* data = Native::data<XMLReader>(this_);
  SYNC_VM_REGS_SCOPED();
  if (name.empty() || namespaceURI.empty()) {
    raise_warning("Attribute Name and Namespace URI cannot be empty");
    return false;
  }

  char *retchar = nullptr;
  if (data->m_ptr) {
    retchar = (char *)xmlTextReaderGetAttributeNs(data->m_ptr,
                                                  (xmlChar *)name.data(),
                                                  (xmlChar *)namespaceURI.data());
  }

  if (retchar) {
    String ret((const char*)retchar, CopyString);
    xmlFree(retchar);
    return ret;
  } else {
    return init_null();
  }
}
 String iterate(String prod_, String rule_) {
   drawLength = drawLength * 0.6;
   generations++;
   String newProduction = prod_;          
   newProduction = newProduction.replaceAll("F", rule_);
   return newProduction;
 }
	var getResult(const Scope& s) const override
	{
		var result = object->getResult(s);

		if (VariantBuffer *b = result.getBuffer())
		{
			const int i = index->getResult(s);
			return (*b)[i];
		}
		else if (AssignableObject * instance = dynamic_cast<AssignableObject*>(result.getObject()))
		{
			cacheIndex(instance, s);

			return instance->getAssignedValue(cachedIndex);
		}
		else if (const Array<var>* array = result.getArray())
			return (*array)[static_cast<int> (index->getResult(s))];

        else if (const DynamicObject* obj = result.getDynamicObject())
        {
            const String name = index->getResult(s).toString();
            
            if(name.isNotEmpty())
            {
                return obj->getProperty(Identifier(name));
            }
            
            
        }
        
		return var::undefined();
	}
Example #24
0
void Value_money_imp::put_String( const String& inStr )
{
	if( inStr.isSingleByte() )
		put_String( inStr.getBufferA() );
	else
		put_String( inStr.c_str() );
}
Example #25
0
void CmdHeaptrace::onClient(DebuggerClient &client) {
  if (DebuggerCommand::displayedHelp(client)) return;

  String format;
  String file;
  if (client.argCount() == 3) {
    format = client.argValue(2);
    file = client.argValue(3);
  } else if (client.argCount() != 1) {
    help(client);
    return;
  }

  CmdHeaptracePtr cmd = client.xend<CmdHeaptrace>(this);

  if (file.empty()) {
    cmd->printHeap(client);
  } else {
    std::string formatStr = format->data();
    const auto it = s_formatMap.find(formatStr);

    if (it == s_formatMap.end()) {
      client.print("Unsupported format type");
      return;
    }
    cmd->printGraphToFile(client, file, it->second);
  }

}
Example #26
0
void HTMLMapElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
    // FIXME: This logic seems wrong for XML documents.
    // Either the id or name will be used depending on the order the attributes are parsed.

    if (isIdAttributeName(name) || name == nameAttr) {
        if (isIdAttributeName(name)) {
            // Call base class so that hasID bit gets set.
            HTMLElement::parseAttribute(name, value);
            if (document().isHTMLDocument())
                return;
        }
        if (inDocument())
            treeScope().removeImageMap(this);
        String mapName = value;
        if (mapName[0] == '#')
            mapName = mapName.substring(1);
        m_name = AtomicString(document().isHTMLDocument() ? mapName.lower() : mapName);
        if (inDocument())
            treeScope().addImageMap(this);

        return;
    }

    HTMLElement::parseAttribute(name, value);
}
static bool TreatAsAttachment(const String& content_disposition) {
    // Some broken sites just send
    // Content-Disposition: ; filename="file"
    // screen those out here.
    if (content_disposition.startsWith(";"))
        return false;

    if (content_disposition.startsWith("inline", false))
        return false;

    // Some broken sites just send
    // Content-Disposition: filename="file"
    // without a disposition token... screen those out.
    if (content_disposition.startsWith("filename", false))
        return false;

    // Also in use is Content-Disposition: name="file"
    if (content_disposition.startsWith("name", false))
        return false;

    // We have a content-disposition of "attachment" or unknown.
    // RFC 2183, section 2.8 says that an unknown disposition
    // value should be treated as "attachment"
    return true;
}
Example #28
0
bool GwfTranslator::getScAddr(const String &idtf, sc_addr &addr)
{
    tStringAddrMap::iterator it = mLocalIdtfAddrs.find(idtf);
    if (it != mLocalIdtfAddrs.end())
    {
        addr = it->second;
        return true;
    }

    it = mSysIdtfAddrs.find(idtf);
    if (it != mSysIdtfAddrs.end())
    {
        addr = it->second;
        return true;
    }

    it = msGlobalIdtfAddrs.find(idtf);
    if (it != msGlobalIdtfAddrs.end())
    {
        addr = it->second;
        return true;
    }

    if (sc_helper_find_element_by_system_identifier(idtf.c_str(), idtf.size(), &addr) == SC_RESULT_OK)
        return true;

    return false;
}
Example #29
0
int PkiUtility::SignCsr(const String& csrfile, const String& certfile)
{
	char errbuf[120];

	InitializeOpenSSL();

	BIO *csrbio = BIO_new_file(csrfile.CStr(), "r");
	X509_REQ *req = PEM_read_bio_X509_REQ(csrbio, NULL, NULL, NULL);

	if (!req) {
		Log(LogCritical, "SSL")
		    << "Could not read X509 certificate request from '" << csrfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
		return 1;
	}

	BIO_free(csrbio);

	boost::shared_ptr<X509> cert = CreateCertIcingaCA(X509_REQ_get_pubkey(req), X509_REQ_get_subject_name(req));

	X509_REQ_free(req);

	std::ofstream fpcert;
	fpcert.open(certfile.CStr());

	if (!fpcert) {
		Log(LogCritical, "cli")
		    << "Failed to open certificate file '" << certfile << "' for output";
		return 1;
	}

	fpcert << CertificateToString(cert);
	fpcert.close();

	return 0;
}
void EmailInputType::warnIfValueIsInvalid(const String& value) const
{
    String invalidAddress = findInvalidAddress(value);
    if (invalidAddress.isNull())
        return;
    addWarningToConsole("The specified value %s is not a valid email address.", invalidAddress);
}