int
sqlite3_T_text16(sqlite3_context *aCtx,
                 const nsString &aValue)
{
  ::sqlite3_result_text16(aCtx,
                          aValue.get(),
                          aValue.Length() * 2, // Number of bytes.
                          SQLITE_TRANSIENT);
  return SQLITE_OK;
}
Example #2
0
bool
JetpackActorCommon::RecvMessage(JSContext* cx,
                                const nsString& messageName,
                                const nsTArray<Variant>& data,
                                nsTArray<Variant>* results)
{
  if (results)
    results->Clear();

  RecList* list;
  if (!mReceivers.Get(messageName, &list))
    return true;
  nsAutoTArray<jsval, 4> snapshot;
  list->copyTo(snapshot);
  if (!snapshot.Length())
    return true;
  
  nsAutoTArray<jsval, 4> args;
  PRUint32 argc = data.Length() + 1;
  jsval* argv = args.AppendElements(argc);
  if (!argv)
    return false;
  for (PRUint32 i = 0; i < argc; ++i)
    argv[i] = JSVAL_VOID;
  js::AutoArrayRooter argvRooter(cx, argc, argv);

  JSString* msgNameStr =
    JS_NewUCStringCopyN(cx,
                        messageName.get(),
                        messageName.Length());
  if (!msgNameStr)
    return false;
  argv[0] = STRING_TO_JSVAL(msgNameStr);

  for (PRUint32 i = 0; i < data.Length(); ++i)
    if (!jsval_from_Variant(cx, data.ElementAt(i), argv + i + 1))
      return false;

  JSObject* implGlobal = JS_GetGlobalObject(cx);
  js::AutoValueRooter rval(cx);

  for (PRUint32 i = 0; i < snapshot.Length(); ++i) {
    Variant* vp = results ? results->AppendElement() : NULL;
    rval.set(JSVAL_VOID);
    if (!JS_CallFunctionValue(cx, implGlobal, snapshot[i], argc, argv,
                              rval.jsval_addr())) {
      (void) JS_ReportPendingException(cx);
      if (vp)
        *vp = void_t();
    } else if (vp && !jsval_to_Variant(cx, rval.jsval_value(), vp))
      *vp = void_t();
  }

  return true;
}
Example #3
0
void nsEudoraCompose::ExtractType(nsString& str)
{
  nsString tStr;
  int32_t idx = str.FindChar(';');
  if (idx != -1)
    str.SetLength(idx);

  str.Trim(kWhitespace);

  if ((str.CharAt(0) == '"') && (str.Length() > 2)) {
    str.SetLength(str.Length() - 1);
    str.Cut(0, 1);
    str.Trim(kWhitespace);
  }

  // if multipart then ignore it since no outlook message body is ever
  // valid multipart!
  if (StringBeginsWith(str, NS_LITERAL_STRING("multipart/"), nsCaseInsensitiveStringComparator()))
    str.Truncate();
}
Example #4
0
nsresult
DOMStorageCache::SetItem(const DOMStorage* aStorage, const nsAString& aKey,
                         const nsString& aValue, nsString& aOld)
{
  Telemetry::AutoTimer<Telemetry::LOCALDOMSTORAGE_SETVALUE_MS> autoTimer;

  if (Persist(aStorage)) {
    WaitForPreload(Telemetry::LOCALDOMSTORAGE_SETVALUE_BLOCKING_MS);
    if (NS_FAILED(mLoadResult)) {
      return mLoadResult;
    }
  }

  Data& data = DataSet(aStorage);
  if (!data.mKeys.Get(aKey, &aOld)) {
    SetDOMStringToNull(aOld);
  }

  // Check the quota first
  const int64_t delta = static_cast<int64_t>(aValue.Length()) -
                        static_cast<int64_t>(aOld.Length());
  if (!ProcessUsageDelta(aStorage, delta)) {
    return NS_ERROR_DOM_QUOTA_REACHED;
  }

  if (aValue == aOld && DOMStringIsNull(aValue) == DOMStringIsNull(aOld)) {
    return NS_SUCCESS_DOM_NO_OPERATION;
  }

  data.mKeys.Put(aKey, aValue);

  if (Persist(aStorage)) {
    if (DOMStringIsNull(aOld)) {
      return sDatabase->AsyncAddItem(this, aKey, aValue);
    }

    return sDatabase->AsyncUpdateItem(this, aKey, aValue);
  }

  return NS_OK;
}
Example #5
0
void
nsTextBoxFrame::GetTextSize(nsPresContext* aPresContext, nsIRenderingContext& aRenderingContext,
                                const nsString& aString, nsSize& aSize, nscoord& aAscent)
{
    nsCOMPtr<nsIFontMetrics> fontMet;
    nsLayoutUtils::GetFontMetricsForFrame(this, getter_AddRefs(fontMet));
    fontMet->GetHeight(aSize.height);
    aRenderingContext.SetFont(fontMet);
    aSize.width =
      nsLayoutUtils::GetStringWidth(this, &aRenderingContext, aString.get(), aString.Length());
    fontMet->GetMaxAscent(aAscent);
}
// See if the string has any lines longer than longLineLen:
// if so, we presume formatting is wonky (e.g. the node has been edited)
// and we'd better rewrap the whole text node.
PRBool
nsXHTMLContentSerializer::HasLongLines(const nsString& text, PRInt32& aLastNewlineOffset)
{
  PRUint32 start=0;
  PRUint32 theLen = text.Length();
  PRBool rv = PR_FALSE;
  aLastNewlineOffset = kNotFound;
  for (start = 0; start < theLen; ) {
    PRInt32 eol = text.FindChar('\n', start);
    if (eol < 0) {
      eol = text.Length();
    }
    else {
      aLastNewlineOffset = eol;
    }
    if (PRInt32(eol - start) > kLongLineLen)
      rv = PR_TRUE;
    start = eol + 1;
  }
  return rv;
}
// See if the string has any lines longer than longLineLen:
// if so, we presume formatting is wonky (e.g. the node has been edited)
// and we'd better rewrap the whole text node.
bool
nsXHTMLContentSerializer::HasLongLines(const nsString& text, int32_t& aLastNewlineOffset)
{
  uint32_t start=0;
  uint32_t theLen = text.Length();
  bool rv = false;
  aLastNewlineOffset = kNotFound;
  for (start = 0; start < theLen; ) {
    int32_t eol = text.FindChar('\n', start);
    if (eol < 0) {
      eol = text.Length();
    }
    else {
      aLastNewlineOffset = eol;
    }
    if (int32_t(eol - start) > kLongLineLen)
      rv = true;
    start = eol + 1;
  }
  return rv;
}
bool
XPCShellEnvironment::EvaluateString(const nsString& aString,
                                    nsString* aResult)
{
  XPCShellEnvironment* env = Environment(mCx);
  XPCShellEnvironment::AutoContextPusher pusher(env);

  JSAutoRequest ar(mCx);

  JS_ClearPendingException(mCx);

  JSObject* global = GetGlobalObject();

  JSAutoEnterCompartment ac;
  if (!ac.enter(mCx, global)) {
      NS_ERROR("Failed to enter compartment!");
      return false;
  }

  JSScript* script =
      JS_CompileUCScriptForPrincipals(mCx, global, GetPrincipal(),
                                      aString.get(), aString.Length(),
                                      "typein", 0);
  if (!script) {
     return false;
  }

  if (!ShouldCompileOnly()) {
      if (aResult) {
          aResult->Truncate();
      }

      jsval result;
      JSBool ok = JS_ExecuteScript(mCx, global, script, &result);
      if (ok && result != JSVAL_VOID) {
          JSErrorReporter old = JS_SetErrorReporter(mCx, NULL);
          JSString* str = JS_ValueToString(mCx, result);
          nsDependentJSString depStr;
          if (str)
              depStr.init(mCx, str);
          JS_SetErrorReporter(mCx, old);

          if (!depStr.IsEmpty() && aResult) {
              aResult->Assign(depStr);
          }
      }
  }

  JS_DestroyScript(mCx, script);

  return true;
}
void nsEudoraCompose::ExtractCharset( nsString& str)
{
  nsString tStr;
  PRInt32 idx = str.Find( "charset=", PR_TRUE);
  if (idx != -1) {
    idx += 8;
    str.Right( tStr, str.Length() - idx);
    idx = tStr.FindChar( ';');
    if (idx != -1)
      tStr.Left( str, idx);
    else
      str = tStr;
    str.Trim( kWhitespace);
    if ((str.CharAt( 0) == '"') && (str.Length() > 2)) {
      str.Mid( tStr, 1, str.Length() - 2);
      str = tStr;
      str.Trim( kWhitespace);
    }
  }
  else
    str.Truncate();
}
Example #10
0
void CMapiFolderList::ChangeName( nsString& name)
{
  if (name.IsEmpty()) {
    name.AssignLiteral("1");
    return;
  }
  PRUnichar lastC = name.Last();
  if ((lastC >= '0') && (lastC <= '9')) {
    lastC++;
    if (lastC > '9') {
      lastC = '1';
      name.SetCharAt( lastC, name.Length() - 1);
      name.AppendLiteral("0");
    }
    else {
      name.SetCharAt( lastC, name.Length() - 1);
    }
  }
  else {
    name.AppendLiteral(" 2");
  }
}
Example #11
0
mozEnglishWordUtils::myspCapitalization
mozEnglishWordUtils::captype(const nsString &word)
{
  char16_t* lword=ToNewUnicode(word);
  ToUpperCase(lword,lword,word.Length());
  if(word.Equals(lword)){
    free(lword);
    return AllCap;
  }

  ToLowerCase(lword,lword,word.Length());
  if(word.Equals(lword)){
    free(lword);
    return NoCap;
  }
  int32_t length=word.Length();
  if(Substring(word,1,length-1).Equals(lword+1)){
    free(lword);
    return InitCap;
  }
  free(lword);
  return HuhCap;
}
void nsEudoraCompose::ExtractType( nsString& str)
{
  nsString tStr;
  PRInt32 idx = str.FindChar( ';');
  if (idx != -1) {
    str.Left( tStr, idx);
    str = tStr;
  }
  str.Trim( kWhitespace);

  if ((str.CharAt( 0) == '"') && (str.Length() > 2)) {
    str.Mid( tStr, 1, str.Length() - 2);
    str = tStr;
    str.Trim( kWhitespace);
  }

  // if multipart then ignore it since no outlook message body is ever
  // valid multipart!
  if (str.Length() > 10) {
    str.Left( tStr, 10);
    if (tStr.LowerCaseEqualsLiteral("multipart/"))
      str.Truncate();
  }
}
mozEnglishWordUtils::myspCapitalization 
mozEnglishWordUtils::captype(const nsString &word)
{
  if(!mCaseConv) return HuhCap; //punt
  PRUnichar* lword=ToNewUnicode(word);  
  mCaseConv->ToUpper(lword,lword,word.Length());
  if(word.Equals(lword)){
    nsMemory::Free(lword);
    return AllCap;
  }

  mCaseConv->ToLower(lword,lword,word.Length());
  if(word.Equals(lword)){
    nsMemory::Free(lword);
    return NoCap;
  }
  PRInt32 length=word.Length();
  if(Substring(word,1,length-1).Equals(lword+1)){
    nsMemory::Free(lword);
    return InitCap;
  }
  nsMemory::Free(lword);
  return HuhCap;
}
Example #14
0
bool
JetpackChild::RecvEvalScript(const nsString& code)
{
  JSAutoRequest request(mCx);

  JSObject *global = JS_GetGlobalObject(mCx);
  JSAutoEnterCompartment ac;
  if (!ac.enter(mCx, global))
    return false;

  jsval ignored;
  (void) JS_EvaluateUCScript(mCx, global, code.get(),
                             code.Length(), "", 1, &ignored);
  return true;
}
nsresult Conv_FE_06_WithReverse(const nsString& aSrc, nsString& aDst)
{
  PRUnichar *aSrcUnichars = (PRUnichar *)aSrc.get();
  PRBool foundArabic = PR_FALSE;
  PRUint32 i, endArabic, beginArabic, size;
  beginArabic = 0;
  size = aSrc.Length();
  aDst.Truncate();
  for (endArabic=0;endArabic<size;endArabic++) {
    if (aSrcUnichars[endArabic] == 0x0000) 
      break; // no need to convert char after the NULL

    while( (IS_FE_CHAR(aSrcUnichars[endArabic]))||
           (IS_ARABIC_CHAR(aSrcUnichars[endArabic]))||
           (IS_ARABIC_DIGIT(aSrcUnichars[endArabic]))||
           (aSrcUnichars[endArabic]==0x0020)) 
    {
      if(! foundArabic ) {
        beginArabic=endArabic;
        foundArabic= PR_TRUE;
      }
      endArabic++;
    }
    if(foundArabic) {
      endArabic--;
      for (i=endArabic; i>=beginArabic; i--) {
        if(IS_FE_CHAR(aSrcUnichars[i])) {
          //ahmed for the bug of lamalf
          aDst += PresentationToOriginal(aSrcUnichars[i], 0);
          if (PresentationToOriginal(aSrcUnichars[i], 1)) {
            // Two characters, we have to resize the buffer :(
             aDst += PresentationToOriginal(aSrcUnichars[i], 1);
          } // if expands to 2 char
        } else {
          // do we need to check the following if ?
          if((IS_ARABIC_CHAR(aSrcUnichars[i]))||
             (IS_ARABIC_DIGIT(aSrcUnichars[i]))||
             (aSrcUnichars[i]==0x0020))
            aDst += aSrcUnichars[i];
        }     
      }
    } else {
      aDst += aSrcUnichars[endArabic]; 
    }
    foundArabic=PR_FALSE;
  }// for : loop the buffer
  return NS_OK;
}
Example #16
0
//----------------------------------------------------------------------------------------
nsFileURL::nsFileURL(const nsString& inString, PRBool inCreateDirs)
//----------------------------------------------------------------------------------------
{
    NS_LossyConvertUCS2toASCII cstring(inString);
    if (!inString.Length())
        return;
    NS_ASSERTION(strstr(cstring.get(), kFileURLPrefix) == cstring.get(),
                 "Not a URL!");
    // Make canonical and absolute. Since it's a parameter to this constructor,
    // inString is escaped. We want to make an nsFilePath, which requires
    // an unescaped string.
    nsSimpleCharString unescapedPath(cstring.get() + kFileURLPrefixLength);
    unescapedPath.Unescape();
    nsFilePath path(unescapedPath, inCreateDirs);
    *this = path;
} // nsFileURL::nsFileURL
/**
 * Gather up the characters in an identifier. The identfier was
 * started by "aChar" which will be appended to aIdent. The result
 * will be aIdent with all of the identifier characters appended
 * until the first non-identifier character is seen. The termination
 * character is unread for the future re-reading.
 *
 * Returns failure when the character sequence does not form an ident at
 * all, in which case the caller is responsible for pushing back or
 * otherwise handling aChar.  (This occurs only when aChar is '\'.)
 */
bool
nsCSSScanner::GatherIdent(int32_t aChar, nsString& aIdent)
{
  if (aChar == '\\') {
    if (!ParseAndAppendEscape(aIdent, false)) {
      return false;
    }
  } else {
    MOZ_ASSERT(aChar > 0);
    aIdent.Append(aChar);
  }
  for (;;) {
    // If nothing in pushback, first try to get as much as possible in one go
    if (!mPushbackCount && mOffset < mCount) {
      // See how much we can consume and append in one go
      uint32_t n = mOffset;
      // Count number of Ident characters that can be processed
      while (n < mCount && IsIdent(mReadPointer[n])) {
        ++n;
      }
      // Add to the token what we have so far
      if (n > mOffset) {
#ifdef CSS_REPORT_PARSE_ERRORS
        mColNumber += n - mOffset;
#endif
        aIdent.Append(&mReadPointer[mOffset], n - mOffset);
        mOffset = n;
      }
    }

    aChar = Read();
    if (aChar < 0) break;
    if (aChar == '\\') {
      if (!ParseAndAppendEscape(aIdent, false)) {
        Pushback(aChar);
        break;
      }
    } else if (IsIdent(aChar)) {
      aIdent.Append(PRUnichar(aChar));
    } else {
      Pushback(aChar);
      break;
    }
  }
  MOZ_ASSERT(aIdent.Length() > 0);
  return true;
}
Example #18
0
nsresult
nsWebSocket::ConvertTextToUTF8(const nsString& aMessage, nsCString& buf)
{
  NS_ABORT_IF_FALSE(NS_IsMainThread(), "Not running on main thread");
  nsresult rv;

  nsCOMPtr<nsICharsetConverterManager> ccm =
    do_GetService(NS_CHARSETCONVERTERMANAGER_CONTRACTID, &rv);
  SUCCESS_OR_FAIL_WEBSOCKET(rv, rv);

  nsCOMPtr<nsIUnicodeEncoder> converter;
  rv = ccm->GetUnicodeEncoder("UTF-8", getter_AddRefs(converter));
  SUCCESS_OR_FAIL_WEBSOCKET(rv, rv);

  rv = converter->SetOutputErrorBehavior(nsIUnicodeEncoder::kOnError_Replace,
                                         nsnull, UTF_8_REPLACEMENT_CHAR);
  SUCCESS_OR_FAIL_WEBSOCKET(rv, rv);

  PRInt32 inLen = aMessage.Length();
  PRInt32 maxLen;
  rv = converter->GetMaxLength(aMessage.BeginReading(), inLen, &maxLen);
  SUCCESS_OR_FAIL_WEBSOCKET(rv, rv);

  buf.SetLength(maxLen);
  TRUE_OR_FAIL_WEBSOCKET(buf.Length() == static_cast<PRUint32>(maxLen),
                         NS_ERROR_OUT_OF_MEMORY);

  char* start = buf.BeginWriting();

  PRInt32 outLen = maxLen;
  rv = converter->Convert(aMessage.BeginReading(), &inLen, start, &outLen);
  if (NS_SUCCEEDED(rv)) {
    PRInt32 outLen2 = maxLen - outLen;
    rv = converter->Finish(start + outLen, &outLen2);
    outLen += outLen2;
  }
  if (NS_FAILED(rv) || rv == NS_ERROR_UENC_NOMAPPING) {
    // Yes, NS_ERROR_UENC_NOMAPPING is a success code
    return NS_ERROR_DOM_SYNTAX_ERR;
  }

  buf.SetLength(outLen);
  TRUE_OR_FAIL_WEBSOCKET(buf.Length() == static_cast<PRUint32>(outLen),
                         NS_ERROR_UNEXPECTED);

  return NS_OK;
}
Example #19
0
bool
DOMStorageCache::LoadItem(const nsAString& aKey, const nsString& aValue)
{
  MonitorAutoLock monitor(mMonitor);
  if (mLoaded) {
    return false;
  }

  Data& data = mData[kDefaultSet];
  if (data.mKeys.Get(aKey, nullptr)) {
    return true; // don't stop, just don't override
  }

  data.mKeys.Put(aKey, aValue);
  data.mOriginQuotaUsage += aKey.Length() + aValue.Length();
  return true;
}
nsresult
SessionStorageCache::RemoveItem(DataSetType aDataSetType, const nsAString& aKey,
                                nsString& aOldValue)
{
  DataSet* dataSet = Set(aDataSetType);

  if (!dataSet->mKeys.Get(aKey, &aOldValue)) {
    return NS_SUCCESS_DOM_NO_OPERATION;
  }

  // Recalculate the cached data size
  dataSet->ProcessUsageDelta(-(static_cast<int64_t>(aOldValue.Length()) +
                               static_cast<int64_t>(aKey.Length())));

  dataSet->mKeys.Remove(aKey);
  return NS_OK;
}
bool
XPCShellEnvironment::EvaluateString(const nsString& aString,
                                    nsString* aResult)
{
  XPCShellEnvironment* env = Environment(mCx);
  nsCxPusher pusher;
  pusher.Push(env->GetContext());

  JSAutoRequest ar(mCx);

  JS_ClearPendingException(mCx);

  JS::Rooted<JSObject*> global(mCx, GetGlobalObject());
  JSAutoCompartment ac(mCx, global);

  JSScript* script =
      JS_CompileUCScriptForPrincipals(mCx, global, GetPrincipal(),
                                      aString.get(), aString.Length(),
                                      "typein", 0);
  if (!script) {
     return false;
  }

  if (!ShouldCompileOnly()) {
      if (aResult) {
          aResult->Truncate();
      }

      JS::Rooted<JS::Value> result(mCx);
      JSBool ok = JS_ExecuteScript(mCx, global, script, result.address());
      if (ok && result != JSVAL_VOID) {
          JSErrorReporter old = JS_SetErrorReporter(mCx, NULL);
          JSString* str = JS_ValueToString(mCx, result);
          nsDependentJSString depStr;
          if (str)
              depStr.init(mCx, str);
          JS_SetErrorReporter(mCx, old);

          if (!depStr.IsEmpty() && aResult) {
              aResult->Assign(depStr);
          }
      }
  }

  return true;
}
Example #22
0
// EscapeStr takes the passed in string and
// escapes it IN PLACE.
void
mozTXTToHTMLConv::EscapeStr(nsString& aInString, bool inAttribute)
{
  // the replace substring routines
  // don't seem to work if you have a character
  // in the in string that is also in the replacement
  // string! =(
  //aInString.ReplaceSubstring("&", "&amp;");
  //aInString.ReplaceSubstring("<", "&lt;");
  //aInString.ReplaceSubstring(">", "&gt;");
  for (uint32_t i = 0; i < aInString.Length();)
  {
    switch (aInString[i])
    {
    case '<':
      aInString.Cut(i, 1);
      aInString.Insert(NS_LITERAL_STRING("&lt;"), i);
      i += 4; // skip past the integers we just added
      break;
    case '>':
      aInString.Cut(i, 1);
      aInString.Insert(NS_LITERAL_STRING("&gt;"), i);
      i += 4; // skip past the integers we just added
      break;
    case '&':
      aInString.Cut(i, 1);
      aInString.Insert(NS_LITERAL_STRING("&amp;"), i);
      i += 5; // skip past the integers we just added
      break;
    case '"':
      if (inAttribute)
      {
        aInString.Cut(i, 1);
        aInString.Insert(NS_LITERAL_STRING("&quot;"), i);
        i += 6;
        break;
      }
      // else fall through
      MOZ_FALLTHROUGH;
    default:
      i++;
    }
  }
}
NS_GFX_(bool) NS_HexToRGB(const nsString& aColorSpec,
                                       nscolor* aResult)
{
  const PRUnichar* buffer = aColorSpec.get();

  int nameLen = aColorSpec.Length();
  if ((nameLen == 3) || (nameLen == 6)) {
    // Make sure the digits are legal
    for (int i = 0; i < nameLen; i++) {
      PRUnichar ch = buffer[i];
      if (((ch >= '0') && (ch <= '9')) ||
          ((ch >= 'a') && (ch <= 'f')) ||
          ((ch >= 'A') && (ch <= 'F'))) {
        // Legal character
        continue;
      }
      // Whoops. Illegal character.
      return false;
    }

    // Convert the ascii to binary
    int dpc = ((3 == nameLen) ? 1 : 2);
    // Translate components from hex to binary
    int r = ComponentValue(buffer, nameLen, 0, dpc);
    int g = ComponentValue(buffer, nameLen, 1, dpc);
    int b = ComponentValue(buffer, nameLen, 2, dpc);
    if (dpc == 1) {
      // Scale single digit component to an 8 bit value. Replicate the
      // single digit to compute the new value.
      r = (r << 4) | r;
      g = (g << 4) | g;
      b = (b << 4) | b;
    }
    NS_ASSERTION((r >= 0) && (r <= 255), "bad r");
    NS_ASSERTION((g >= 0) && (g <= 255), "bad g");
    NS_ASSERTION((b >= 0) && (b <= 255), "bad b");
    *aResult = NS_RGB(r, g, b);
    return true;
  }

  // Improperly formatted color value
  return false;
}
/**
 * NTLM_Hash computes the NTLM hash of the given password.
 *
 * @param password
 *        null-terminated unicode password.
 * @param hash
 *        16-byte result buffer
 */
static void
NTLM_Hash(const nsString &password, unsigned char *hash)
{
  uint32_t len = password.Length();
  uint8_t *passbuf;
  
#ifdef IS_BIG_ENDIAN
  passbuf = (uint8_t *) malloc(len * 2);
  WriteUnicodeLE(passbuf, password.get(), len);
#else
  passbuf = (uint8_t *) password.get();
#endif

  md4sum(passbuf, len * 2, hash);

#ifdef IS_BIG_ENDIAN
  ZapBuf(passbuf, len * 2);
  free(passbuf);
#endif
}
Example #25
0
void nsOutlookMail::SplitString( nsString& val1, nsString& val2)
{
    nsString  temp;

    // Find the last line if there is more than one!
    PRInt32 idx = val1.RFind( "\x0D\x0A");
    PRInt32  cnt = 2;
    if (idx == -1) {
        cnt = 1;
        idx = val1.RFindChar( 13);
    }
    if (idx == -1)
        idx= val1.RFindChar( 10);
    if (idx != -1) {
        val1.Right( val2, val1.Length() - idx - cnt);
        val1.Left( temp, idx);
        val1 = temp;
        SanitizeValue( val1);
    }
}
Example #26
0
// XXX i18n helper routines
void
nsIsIndexFrame::URLEncode(const nsString& aString, nsIUnicodeEncoder* encoder, nsString& oString) 
{
  char* inBuf = nsnull;
  if(encoder)
    inBuf  = UnicodeToNewBytes(aString.get(), aString.Length(), encoder);

  if(nsnull == inBuf)
    inBuf  = ToNewCString(aString);

  // convert to CRLF breaks
  char* convertedBuf = nsLinebreakConverter::ConvertLineBreaks(inBuf,
                           nsLinebreakConverter::eLinebreakAny, nsLinebreakConverter::eLinebreakNet);
  delete [] inBuf;
  
  char* outBuf = nsEscape(convertedBuf, url_XPAlphas);
  oString.AssignASCII(outBuf);
  nsMemory::Free(outBuf);
  nsMemory::Free(convertedBuf);
}
Example #27
0
// static
already_AddRefed<nsStringBuffer>
nsCSSValue::BufferFromString(const nsString& aValue)
{
  nsStringBuffer* buffer = nsStringBuffer::FromString(aValue);
  if (buffer) {
    buffer->AddRef();
    return buffer;
  }
  
  PRUnichar length = aValue.Length();

  // NOTE: Alloc prouduces a new, already-addref'd (refcnt = 1) buffer.
  buffer = nsStringBuffer::Alloc((length + 1) * sizeof(PRUnichar));
  if (NS_LIKELY(buffer != 0)) {
    PRUnichar* data = static_cast<PRUnichar*>(buffer->Data());
    nsCharTraits<PRUnichar>::copy(data, aValue.get(), length);
    // Null-terminate.
    data[length] = 0;
  }

  return buffer;
}
JSBool
TestShellCommandParent::RunCallback(const nsString& aResponse)
{
  NS_ENSURE_TRUE(*mCallback.ToJSValPtr() != JSVAL_NULL && mCx, JS_FALSE);

  JSAutoRequest ar(mCx);
  NS_ENSURE_TRUE(mCallback.ToJSObject(), JS_FALSE);
  JSAutoCompartment ac(mCx, mCallback.ToJSObject());
  JS::Rooted<JSObject*> global(mCx, JS::CurrentGlobalOrNull(mCx));

  JSString* str = JS_NewUCStringCopyN(mCx, aResponse.get(), aResponse.Length());
  NS_ENSURE_TRUE(str, JS_FALSE);

  JS::Rooted<JS::Value> strVal(mCx, JS::StringValue(str));

  JS::Rooted<JS::Value> rval(mCx);
  JSBool ok = JS_CallFunctionValue(mCx, global, mCallback, 1, strVal.address(),
                                   rval.address());
  NS_ENSURE_TRUE(ok, JS_FALSE);

  return JS_TRUE;
}
bool
XPCShellEnvironment::EvaluateString(const nsString& aString,
                                    nsString* aResult)
{
  AutoSafeJSContext cx;
  JS::Rooted<JSObject*> global(cx, GetGlobalObject());
  JSAutoCompartment ac(cx, global);

  JS::CompileOptions options(cx);
  options.setFileAndLine("typein", 0)
         .setPrincipals(GetPrincipal());
  JSScript* script = JS_CompileUCScript(cx, global, aString.get(),
                                        aString.Length(), options);
  if (!script) {
     return false;
  }

  if (aResult) {
      aResult->Truncate();
  }

  JS::Rooted<JS::Value> result(cx);
  bool ok = JS_ExecuteScript(cx, global, script, result.address());
  if (ok && result != JSVAL_VOID) {
      JSErrorReporter old = JS_SetErrorReporter(cx, nullptr);
      JSString* str = JS::ToString(cx, result);
      nsDependentJSString depStr;
      if (str)
          depStr.init(cx, str);
      JS_SetErrorReporter(cx, old);

      if (!depStr.IsEmpty() && aResult) {
          aResult->Assign(depStr);
      }
  }

  return true;
}
Example #30
0
bool
XPCShellEnvironment::EvaluateString(const nsString& aString,
                                    nsString* aResult)
{
  AutoEntryScript aes(GetGlobalObject(),
                      "ipc XPCShellEnvironment::EvaluateString");
  JSContext* cx = aes.cx();

  JS::CompileOptions options(cx);
  options.setFileAndLine("typein", 0);
  JS::Rooted<JSScript*> script(cx);
  if (!JS_CompileUCScript(cx, aString.get(), aString.Length(), options,
                          &script))
  {
     return false;
  }

  if (aResult) {
      aResult->Truncate();
  }

  JS::Rooted<JS::Value> result(cx);
  bool ok = JS_ExecuteScript(cx, script, &result);
  if (ok && !result.isUndefined()) {
      JS::WarningReporter old = JS::SetWarningReporter(cx, nullptr);
      JSString* str = JS::ToString(cx, result);
      nsAutoJSString autoStr;
      if (str)
          autoStr.init(cx, str);
      JS::SetWarningReporter(cx, old);

      if (!autoStr.IsEmpty() && aResult) {
          aResult->Assign(autoStr);
      }
  }

  return true;
}